MTrackWeb.php
[web.mtrack] / MTrackWeb.php
1 <?php
2 /**
3  * every class extends this...
4  */
5  
6  
7 class MTrackWeb extends HTML_FlexyFramework_Page
8 {
9     var $template = 'wiki.html';
10     var $priorities = array();
11     var $severities = array();
12     var $link = false; // the link handler..
13     
14     function hasPerm($what, $cando) {
15         // our whole perm logic sits in here....
16         
17         // here's how it works
18         // a) anonymous users - not authenticated.
19         // - can see projects that are in *PUBLIC project "MTrack.Repos", "S"
20         // - can see bugs that are in *PUBLIC project "MTrack.Issue", "S"
21         // - can see bugs that are in *PUBLIC project "MTrack.Wiki", "S"
22         if (!$this->authUser) {
23             if ($cando == 'S' &&
24                     in_array( $what , array( 'MTrack.Repos', 'MTrack.Issue', 'MTrack.Wiki'))) {
25                 
26                 return true; // not a diffinative answer...
27             }
28             return false;
29         }
30         
31         return $this->authUser->hasPerm($what, $cando); 
32     }
33     
34     function projectPerm($project_id, $what, $cando)
35     {
36         if (!$project_id) {
37             return false;
38         }
39         $p = DB_DataObject::factory('Projects');
40         $p->get($project_id);
41         if (!$this->authUser) {
42             if ($p->code != '*PUBLIC') {
43                 return false; // only public projects
44             }
45             if ($cando != 'S') {
46                 return false;
47             }
48             // all permissions to view public stuff.
49             return true;
50         }
51         if (!$this->authUser->hasPerm($what, $cando)) {
52             echo "NO PERMS $what $cando";
53             echo '<PRE>'; print_r($this->authUser->getPerms());
54             return false;
55         }
56         // membership rules?
57         //echo "COMPTYPE " . $this->authUser->company()->comptype ;
58         if ($this->authUser->company()->comptype == 'OWNER') {
59                 
60             if ($this->authUser->hasPerm('Core.Projects_All', $cando)) { // they can do what they like on all projects.
61                return true;
62             }
63            // return $p->hasPerm($what, $cando);
64         }
65         // otherwise they have to be a team member of that project.
66         
67         $pd = DB_DataObject::factory('ProjectDirectory');
68         $pd->project_id = $project_id;
69         $pd->user_id = $this->authUser->id;
70         if (!$pd->count()) {
71             return false;
72         }
73         return true;
74          
75     }
76     
77     
78     function currentProject($val = false)
79     {
80         // we do need the option for me to look at all projects...
81         static $currentProject = false;
82         if ($val !== false) {
83             // attempt to set it..
84             $_SESSION[__CLASS__]['active_project_id'] = $val ;
85             $currentProject = false;
86             // reset to ensure not cached..
87         }
88         if ($currentProject !== false) {
89             return $currentProject;
90         }
91         
92         
93         $p = DB_DataObject::factory('Projects');
94         $ar = array();
95         if ($this->authUser) {
96             $p->applyFilters(array(), $this->authUser);
97             $p->whereAdd('id in (SELECT distinct(project_id) FROM mtrack_repos)');
98             $ar = $p->fetchAll('id', 'name');
99         }
100         
101         if (empty($_SESSION[__CLASS__]['active_project_id']) ||
102             !isset($ar[$_SESSION[__CLASS__]['active_project_id']]))
103         {
104             $p = DB_DataObject::factory('Projects');
105              
106             $p->get('code', '*PUBLIC');
107             $_SESSION[__CLASS__]['active_project_id'] = $p->id;
108             return $p->id; // always allowed..
109         }
110         $currentProject = $_SESSION[__CLASS__]['active_project_id'];
111         return $_SESSION[__CLASS__]['active_project_id'];
112         
113         
114     }
115     
116     function loadProjectList()
117     {
118         
119         $p = DB_DataObject::factory('Projects');
120         if (!$this->authUser) {
121             $p->code = '*PUBLIC';
122            
123             $ar = $p->fetchAll('id', 'name');
124         } else {
125             
126             $p->applyFilters(array(), $this->authUser);
127             $p->whereAdd('id in (SELECT distinct(project_id) FROM mtrack_repos)');
128             $ar = $p->fetchAll('id', 'name');
129         }
130          
131         $this->elements['active_project_id'] = new HTML_Template_Flexy_Element();
132         $this->elements['active_project_id']->setOptions($ar);
133         
134          
135         $this->elements['active_project_id']->setValue( $_SESSION[__CLASS__]['active_project_id']);
136    
137         
138         
139     }
140     
141     
142     function getAuthUser()
143     {
144         $u = DB_DataObject::factory('Person');
145         if (!$u->isAuth()) {
146             return false;
147         }
148         return $u->getAuthUser();
149     }
150     /**
151      * base getAuth allows everyone in..
152      */
153     
154     function getAuth()
155     {
156         $this->registerClasses(); // to be destroyed??
157         
158         $ff = HTML_FlexyFramework::get();
159         if ($ff->cli) {
160             return true;
161         }
162         
163         // default timezone first..
164         $ff = HTML_FlexyFramework::get();
165         if (isset($ff->MTrack['timezone'])) {
166             date_default_timezone_set($ff->MTrack['timezone']);
167         }
168         
169         //MTrackConfig::boot(); // eak.. .remove me...
170       
171         $this->authUser = DB_DataObject::factory('Person')->getAuthUser();
172         $this->loadProjectList();
173         
174         if (!$this->authUser) {
175             return true; // we do allow people in this far..
176         }
177         
178          
179         // timezone setting... -- this may be a good addon to our core person class.
180         
181         if (!empty($this->authUser->timezone)) {
182             date_default_timezone_set($this->authUser->timezone);
183         }
184         
185         
186         
187          
188         /// fixme...
189         //$this->authUser = 
190         return true; // anyone at present..
191     }
192     function get($loc='')
193     {
194         // 
195         if (!empty($loc)) {
196             die ("invalid location". htmlspecialchars($loc));
197         }
198         if (!$this->authUser) {
199              return HTML_FlexyFramework::run('Wiki'); 
200         }
201         return HTML_FlexyFramework::run('Wiki/Today'); 
202  
203     }
204     function post()
205     {
206         header("Status: 404 Not Found");
207         die("not valid");
208     }
209     
210     
211     function initOptions()
212     {
213         
214          
215         $q = MTrackDB::q('select priorityname, value from priorities');
216
217         foreach ($q->fetchAll() as $row) {
218             $this->priorities[$row[0]] = $row[1];
219         }
220         $q = MTrackDB::q('select sevname, ordinal from severities');
221         
222         foreach ($q->fetchAll() as $row) {
223             $this->severities[$row[0]] = $row[1];
224         }
225
226     }
227     
228     function registerClasses()
229     {
230         require_once 'MTrack/Wiki.php';
231         require_once 'MTrack/Wiki/Item.php';
232         require_once 'MTrack/Milestone.php';
233   
234         
235         require_once 'MTrackWeb/LinkHandler.php';
236         require_once 'MTrack/Wiki/HTMLFormatter.php';
237         
238         $this->link = new MTrackWeb_LinkHandler();
239         MTrack_Wiki_HTMLFormatter::registerLinkHandler($this->link);
240  
241
242         $r = DB_DataObject::factory('mtrack_repos');
243         $r->loadFromPath('default/wiki');
244         MTrack_Wiki_Item::$repo = $r->impl();
245         
246         
247         
248         //MTrack_Wiki::register_macro('MilestoneSummary', array('MTrack_Milestone', 'macro_MilestoneSummary'));
249        // MTrack_Wiki::register_macro('BurnDown', array('MTrack_Milestone', 'macro_BurnDown'));
250         //MTrack_Wiki::register_macro('RunReport', array('MTrack_Report', 'macro_RunReport')); << fixme how are we to hanlde this..
251         //MTrack_Wiki::register_macro('TicketQuery', array('MTrack_Report', 'macro_TicketQuery'));
252         MTrack_Wiki::register_macro('IncludeWikiPage', array('MTrack_Wiki', 'macro_IncludeWiki'));
253         MTrack_Wiki::register_macro('IncludeHelpPage', array('MTrack_Wiki', 'macro_IncludeHelp'));
254         MTrack_Wiki::register_macro('Comment', array('MTrack_Wiki', 'macro_comment'));
255         MTrack_Wiki::register_processor('comment', array('MTrack_Wiki', 'processor_comment'));
256         MTrack_Wiki::register_processor('html', array('MTrack_Wiki', 'processor_html'));
257         MTrack_Wiki::register_processor('dataset', array('MTrack_Wiki', 'processor_dataset'));
258
259  
260         //MTrackSearchDB::register_indexer('ticket', array('MTrackIssue', 'index_issue'));
261         //MTrackSearchDB::register_indexer('wiki', array('MTrack_Wiki_Item', 'index_item'));
262
263
264
265         //MTrackWatch::registerEventTypes('ticket', array( 'ticket' => 'Tickets' ));
266         //MTrackWatch::registerEventTypes('milestone', array( 'ticket' => 'Tickets', 'changeset' => 'Code changes' ));
267         //MTrackWatch::registerEventTypes('repo', array( 'ticket' => 'Tickets', 'changeset' => 'Code changes' ));
268
269         // should this get registered here??
270         //MTrackCommitChecker::addCheck('Wiki');
271         
272         
273         
274    }
275     
276     function favicon()
277     {
278         return false;
279         /// FIXME - we should allow upload of a favion...
280         $ff = HTML_FlexyFramework::get();
281         
282         
283     }
284      
285     
286     /* renders the attachment list for a given object */
287     // was Attachments::render
288     // move it to MTrackWebAttachemnt...
289     
290   function attachmentsToHtml($object)
291   {
292     return 'TODO';
293     if (is_object($object)) {
294         $object = $object->toIdString(); // eg. ticket:1
295     }
296     $atts = MTrackDB::q('
297       select * from attachments
298       left join changes on (attachments.cid = changes.cid)
299       where attachments.object = ? order by changedate, filename',
300         $object)->fetchAll(PDO::FETCH_ASSOC);
301
302     if (count($atts) == 0) return '';
303
304     $max_dim = 150;
305
306     $html = "<div class='attachment-list'><b>Attachments</b><ul>";
307     foreach ($atts as $row) {
308       $url = "{$this->baseURL}/Attachment/$object/". $row['cid'] . '/' . $row['filename'];
309       
310       $html .= "<li><a class='attachment'" .
311         " href='$url'>".
312         "$row[filename]</a> ($row[size]) added by " .
313         $this->link->username($row['who'], array(
314           'no_image' => true
315         )) .
316         " " . $this->link->date($row['changedate']);
317         require_once 'MTrack/Attachment.php';
318       list($width, $height) = getimagesize(MTrackAttachment::local_path($row['hash']));
319       if ($width + $height) {
320         /* limit maximum size */
321         if ($width > $max_dim) {
322           $height *= $max_dim / $width;
323           $width = $max_dim;
324         }
325         if ($height > $max_dim) {
326           $width *= $max_dim / $height;
327           $height = $max_dim;
328         }
329         $html .= "<br><a href='$url'><img src='$url' width='$width' border='0' height='$height'></a>";
330       }
331
332       $html .= "</li>\n";
333     }
334     $html .= "</ul></div>";
335     return $html;
336   }
337     function jerr($str, $errors=array()) // standard error reporting..
338     {
339         require_once 'Services/JSON.php';
340         $json = new Services_JSON();
341         
342         // log all errors!!!
343         //$this->addEvent("ERROR", false, $str);
344         /*
345         if (!empty($_REQUEST['returnHTML']) || 
346             (isset($_SERVER['CONTENT_TYPE']) && preg_match('#multipart/form-data#i', $_SERVER['CONTENT_TYPE']))
347         ) {
348             header('Content-type: text/html');
349             echo "<HTML><HEAD></HEAD><BODY>";
350             echo  $json->encodeUnsafe(array(
351                     'success'=> false, 
352                     'message' => $str, // compate with exeption / loadexception.
353
354                     'errors' => $errors ? $errors : true, // used by forms to flag errors.
355                     'authFailure' => !empty($errors['authFailure']),
356                 ));
357             echo "</BODY></HTML>";
358             exit;
359         }
360         */
361         echo $json->encode(array(
362             'success'=> false, 
363             'data'=> array(), 
364             'message' => $str, // compate with exeption / loadexception.
365             'errors' => $errors ? $errors : true, // used by forms to flag errors.
366             'authFailure' => !empty($errors['authFailure']),
367         ));
368         exit;
369         
370     }
371     function jok($str)
372     {
373         
374         require_once 'Services/JSON.php';
375         $json = new Services_JSON();
376         /*
377         if (!empty($_REQUEST['returnHTML']) || 
378             (isset($_SERVER['CONTENT_TYPE']) && preg_match('#multipart/form-data#i', $_SERVER['CONTENT_TYPE']))
379         
380         ) {
381             header('Content-type: text/html');
382             echo "<HTML><HEAD></HEAD><BODY>";
383             echo  $json->encodeUnsafe(array('success'=> true, 'data' => $str));
384             echo "</BODY></HTML>";
385             exit;
386         }
387         */
388         
389         echo  $json->encode(array('success'=> true, 'data' => $str));
390         exit;
391         
392     }
393     /**
394      * output data for grids or tree
395      * @ar {Array} ar Array of data
396      * @total {Number|false} total number of records (or false to return count(ar)
397      * @extra {Array} extra key value list of data to pass as extra data.
398      * 
399      */
400     function jdata($ar,$total=false, $extra=array())
401     {
402         // should do mobile checking???
403         if ($total == false) {
404             $total = count($ar);
405         }
406         $extra=  $extra ? $extra : array();
407         require_once 'Services/JSON.php';
408         $json = new Services_JSON();
409         echo $json->encode(array('success' =>  true, 'total'=> $total, 'data' => $ar) + $extra);    
410         exit;
411         
412         
413     }
414     
415     /**
416      * ---------------- Logging ---------------   
417      */
418     
419     /**
420      * addEventOnce:
421      * Log an action (only if it has not been logged already.
422      * 
423      * @param {String} action  - group/name of event
424      * @param {DataObject|false} obj - dataobject action occured on.
425      * @param {String} any remarks 
426      */
427     
428     function addEventOnce($act, $obj = false, $remarks = '') 
429     {
430         $au = $this->getAuthUser();
431         $e = DB_DataObject::factory('Events');
432         $e->init($act,$obj,$remarks); 
433         if ($e->find(true)) {
434             return;
435         }
436         $this->addEvent($act, $obj, $remarks);
437     }
438     /**
439      * addEvent:
440      * Log an action.
441      * 
442      * @param {String} action  - group/name of event
443      * @param {DataObject|false} obj - dataobject action occured on.
444      * @param {String} any remarks 
445      */
446     
447     function addEvent($act, $obj = false, $remarks = '') 
448     {
449         $au = $this->getAuthUser();
450         $e = DB_DataObject::factory('Events');
451         $e->init($act,$obj,$remarks); 
452          
453         $e->event_when = date('Y-m-d H:i:s');
454         
455         $eid = $e->insert();
456         $ff  = HTML_FlexyFramework::get();
457         if (empty($ff->Pman['event_log_dir'])) {
458             return;
459         }
460         $file = $ff->Pman['event_log_dir']. date('/Y/m/d/'). $eid . ".php";
461         if (!file_exists(dirname($file))) {
462             mkdir(dirname($file),0700,true);
463         }
464         file_put_contents($file, var_export(array(
465             'REQUEST_URI' => empty($_SERVER['REQUEST_URI']) ? 'cli' : $_SERVER['REQUEST_URI'],
466             'GET' => empty($_GET) ? array() : $_GET,
467             'POST' => empty($_POST) ? array() : $_POST,
468         ), true));
469         
470         
471         
472     }
473
474     
475     
476
477 }