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