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