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