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