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