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