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