Pman.php
[Pman.Base] / Pman.php
1 <?php 
2 /**
3  * Pman Base class
4  * 
5  * Provides:
6  *  - base application setup (variables etc to javascript)
7  * 
8  *  - authentication and permission info about user / application
9  *  - json output methods.
10  *  - file upload error checking - checkFileUploadError
11  *  - logging to event table
12  *  - sendTemplate code (normally use the Person version for sending to specific people..)
13  * 
14  *  - doc managment code?? - remarks and tracking??? - MOVEME
15  *  - authentication link checking?? MOVEME?
16  *  - authentication reset password ?? MOVEME?
17  *  ?? arrayClean.. what's it doing here?!? ;)
18  * 
19  * 
20  */
21
22 class Pman extends HTML_FlexyFramework_Page 
23 {
24     var $appName= "";
25     var $appShortName= "";
26     var $appVersion = "1.8";
27     var $version = 'dev';
28     var $onloadTrack = 0;
29     var $linkFail = "";
30     var $showNewPass = 0;
31     var $logoPrefix = '';
32     var $appModules = '';
33     
34     
35    
36     
37     /**
38      * ------------- Standard getAuth/get/post methods of framework.
39      * 
40      * 
41      */
42     
43     function getAuth() // everyone allowed in!!!!!
44     {
45         $this->loadOwnerCompany();
46         
47         return true;
48         
49     }
50     
51     function init() 
52     {
53         if (isset($this->_hasInit)) {
54             return;
55             
56         }
57         $this->_hasInit = true;
58         /*
59         if (method_exists('HTML_FlexyFramework', 'get')) {
60         */    
61             $boot = HTML_FlexyFramework::get();
62            // echo'<PRE>';print_R($boot);exit;
63             $this->appName= $boot->appName;
64             $this->appNameShort= $boot->appNameShort;
65             $this->appModules= $boot->enable;
66             $this->isDev = true; //empty($opts['isDev']) ? '' : $opts['isDev'];
67             $this->appDisable = $boot->disable;
68             $this->version = $boot->version;
69         /*    
70         } else {
71             // BC!!!
72            
73             $opts = PEAR::getStaticProperty('Pman', 'options');  
74             
75             $this->isDev = true; //empty($opts['isDev']) ? '' : $opts['isDev'];
76             
77             $this->appName= empty($opts['appName']) ? '' : $opts['appName'];
78             $this->appNameShort= empty($opts['appNameShort']) ? '' : $opts['appNameShort'];
79             $this->appModules= $opts['enable'];
80             $this->appDisable = $opts['disable'];
81             $this->version = isset($opts['version']) ? $this->version : $opts['version'];
82         }
83         */
84     }
85     
86     function get($base) 
87     {
88         $this->init();
89             //$this->allowSignup= empty($opts['allowSignup']) ? 0 : 1;
90         $bits = explode('/', $base);
91         //print_R($bits);
92         if ($bits[0] == 'Link') {
93             $this->linkFail = $this->linkAuth(@$bits[1],@$bits[2]);
94             header('Content-type: text/html; charset=utf-8');
95             return;
96         } 
97         if ($bits[0] == 'PasswordReset') {
98             $this->linkFail = $this->resetPassword(@$bits[1],@$bits[2],@$bits[3]);
99             header('Content-type: text/html; charset=utf-8');
100             return;
101         } 
102         
103         
104         if ($this->getAuthUser()) {
105             $this->addEvent("RELOAD");
106         }
107         
108         
109         if (strlen($base)) {
110             $this->addEvent("BADURL", false, $base);
111             $this->jerr("invalid url");
112         }
113         // deliver template
114         if (isset($_GET['onloadTrack'])) {
115             $this->onloadTrack = (int)$_GET['onloadTrack'];
116         }
117         // getting this to work with xhtml is a nightmare
118         // = nbsp / <img> issues screw everyting up.
119         
120         //header('Content-type: application/xhtml+xml; charset=utf-8');
121         header('Content-type: text/html; charset=utf-8');
122          
123     }
124     function post($base) {
125         return $this->get($base);
126     }
127     
128     /**
129      * ------------- Authentication and permission info about logged in user!!!
130      * 
131      * 
132      */
133     
134     function loadOwnerCompany()
135     {
136         $this->company = DB_DataObject::Factory('Companies');
137         if ($this->company) { // non-core pman projects
138             return; 
139         }
140         $this->company->get('comptype', 'OWNER');
141         
142     }
143     function staticGetAuthUser()
144     {
145         $ff = HTML_FlexyFramework::get();
146         $tbl = empty($ff->Pman['authTable']) ? 'Person' : $ff->Pman['authTable'];
147         
148         $u = DB_DataObject::factory($tbl);
149         if (!$u->isAuth()) {
150             return false;
151         }
152         return $u->getAuthUser();
153     }
154     function getAuthUser()
155     {
156         if (!empty($this->authUser)) {
157             return $this->authUser;
158         }
159         $ff = HTML_FlexyFramework::get();
160         $tbl = empty($ff->Pman['authTable']) ? 'Person' : $ff->Pman['authTable'];
161         
162         $u = DB_DataObject::factory( $tbl );
163         if (!$u->isAuth()) {
164             return false;
165         }
166         $this->authUser =$u->getAuthUser();
167         return $this->authUser ;
168     }
169     function hasPerm($name, $lvl)  // do we have a permission
170     {
171         static $pcache = array();
172         $au = $this->getAuthUser();
173         return $au->hasPerm($name,$lvl);
174         
175     }
176     function hasModule($name) 
177     {
178         $this->init();
179         if (!strpos( $name,'.') ) {
180             // use enable / disable..
181             
182             
183             $enabled =  array('Core') ;
184             $enabled = !empty($this->appModules) ? 
185                 array_merge($enabled, explode(',',  $this->appModules)) : 
186                 $enabled;
187             $disabled =  explode(',', $this->appDisable ? $this->appDisable: '');
188             
189             //print_R($opts);
190             
191             return in_array($name, $enabled) && !in_array($name, $disabled);
192         }
193         
194         $x = DB_DataObject::factory('Group_Rights');
195         $ar = $x->defaultPermData();
196         if (empty($ar[$name]) || empty($ar[$name][0])) {
197             return false;
198         }
199         return true;
200     }
201     
202     
203     
204     
205     /**
206      * ---------------- Global Tools ---------------   
207      */
208     
209     
210     
211     /**
212      * send a template to the user
213      * rcpts are read from the resulting template.
214      * 
215      * @arg $templateFile  - the file in mail/XXXXXX.txt
216      * @arg $args  - variables available to the form as {t.*} over and above 'this'
217      * 
218      * 
219      */
220     
221     function sendTemplate($templateFile, $args)
222     {
223         
224         
225         
226         $content  = clone($this);
227         
228         foreach((array)$args as $k=>$v) {
229             $content->$k = $v;
230         }
231         $content->msgid = md5(time() . rand());
232         
233         $content->HTTP_HOST = $_SERVER["HTTP_HOST"];
234         /* use the regex compiler, as it doesnt parse <tags */
235         require_once 'HTML/Template/Flexy.php';
236         $template = new HTML_Template_Flexy( array(
237                  'compiler'    => 'Regex',
238                  'filters' => array('SimpleTags','Mail'),
239             //     'debug'=>1,
240             ));
241         
242         // this should be done by having multiple template sources...!!!
243          
244         $template->compile('mail/'. $templateFile.'.txt');
245         
246         /* use variables from this object to ouput data. */
247         $mailtext = $template->bufferedOutputObject($content);
248         //echo "<PRE>";print_R($mailtext);
249         
250         /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
251         require_once 'Mail/mimeDecode.php';
252         require_once 'Mail.php';
253         
254         $decoder = new Mail_mimeDecode($mailtext);
255         $parts = $decoder->getSendArray();
256         if (PEAR::isError($parts)) {
257             return $parts;
258             //echo "PROBLEM: {$parts->message}";
259             //exit;
260         } 
261         list($recipents,$headers,$body) = $parts;
262         ///$recipents = array($this->email);
263         $mailOptions = PEAR::getStaticProperty('Mail','options');
264         $mail = Mail::factory("SMTP",$mailOptions);
265         $headers['Date'] = date('r');
266         if (PEAR::isError($mail)) {
267             return $mail;
268         } 
269         $oe = error_reporting(E_ALL ^ E_NOTICE);
270         $ret = $mail->send($recipents,$headers,$body);
271         error_reporting($oe);
272        
273         return $ret;
274     
275     }
276     
277     function checkFileUploadError()  // check for file upload errors.
278     {    
279         if (
280             empty($_FILES['File']) 
281             || empty($_FILES['File']['name']) 
282             || empty($_FILES['File']['tmp_name']) 
283             || empty($_FILES['File']['type']) 
284             || !empty($_FILES['File']['error']) 
285             || empty($_FILES['File']['size']) 
286         ) {
287             $this->jerr("File upload error: <PRE>" . print_r($_FILES,true) . print_r($_POST,true) . "</PRE>");
288         }
289     }
290     
291     
292     /**
293      * generate a tempory file with an extension (dont forget to delete it)
294      */
295     
296     function tempName($ext)
297     {
298         $x = tempnam(ini_get('session.save_path'), HTML_FlexyFramework::get()->appNameShort.'TMP');
299         unlink($x);
300         return $x .'.'. $ext;
301     }
302     /**
303      * ------------- Authentication testing ------ ??? MOVEME?
304      * 
305      * 
306      */
307     function linkAuth($trid, $trkey) 
308     {
309         $tr = DB_DataObject::factory('Documents_Tracking');
310         if (!$tr->get($trid)) {
311             return "Invalid URL";
312         }
313         if (strtolower($tr->authkey) != strtolower($trkey)) {
314             $this->AddEvent("ERROR-L", false, "Invalid Key");
315             return "Invalid KEY";
316         }
317         // check date..
318         $this->onloadTrack = (int) $tr->doc_id;
319         if (strtotime($tr->date_sent) < strtotime("NOW - 14 DAYS")) {
320             $this->AddEvent("ERROR-L", false, "Key Expired");
321             return "Key Expired";
322         }
323         // user logged in and not
324         $au = $this->getAuthUser();
325         if ($au && $au->id && $au->id != $tr->person_id) {
326             $au->logout();
327             
328             return "Logged Out existing Session\n - reload to log in with correct key";
329         }
330         if ($au) { // logged in anyway..
331             $this->AddEvent("LOGIN", false, "With Key (ALREADY)");
332             header('Location: ' . $this->baseURL.'?onloadTrack='.$this->onloadTrack);
333             exit;
334             return false;
335         }
336         
337         // authenticate the user...
338         // slightly risky...
339         $u = DB_DataObject::factory('Person');
340          
341         $u->get($tr->person_id);
342         $u->login();
343         $this->AddEvent("LOGIN", false, "With Key");
344         
345         // we need to redirect out - otherwise refererer url will include key!
346         header('Location: ' . $this->baseURL.'?onloadTrack='.$this->onloadTrack);
347         exit;
348         
349         return false;
350         
351         
352         
353         
354     }
355     
356     
357     /**
358      * ------------- Authentication password reset ------ ??? MOVEME?
359      * 
360      * 
361      */
362     
363     
364     function resetPassword($id,$t, $key)
365     {
366         
367         $au = $this->getAuthUser();
368         if ($au) {
369             return "Already Logged in - no need to use Password Reset";
370         }
371         
372         $u = DB_DataObject::factory('Person');
373         //$u->company_id = $this->company->id;
374         $u->active = 1;
375         if (!$u->get($id) || !strlen($u->passwd)) {
376             return "invalid id";
377         }
378         
379         // validate key.. 
380         if ($key != $u->genPassKey($t)) {
381             return "invalid key";
382         }
383         $uu = clone($u);
384         $u->no_reset_sent = 0;
385         $u->update($uu);
386         
387         if ($t < strtotime("NOW - 1 DAY")) {
388             return "expired";
389         }
390         $this->showNewPass = implode("/", array($id,$t,$key));
391         return false;
392     }
393     
394      
395     /**
396      * ---------------- Standard JSON outputers. - used everywhere
397      */
398     
399     function jerr($str, $errors=array()) // standard error reporting..
400     {
401         require_once 'Services/JSON.php';
402         $json = new Services_JSON();
403         
404         if (!empty($_REQUEST['returnHTML']) || 
405             (isset($_SERVER['CONTENT_TYPE']) && preg_match('#multipart/form-data#i', $_SERVER['CONTENT_TYPE']))
406         ) {
407             header('Content-type: text/html');
408             echo "<HTML><HEAD></HEAD><BODY>";
409             echo  $json->encodeUnsafe(array(
410                     'success'=> false, 
411                     'errorMsg' => $str,
412                      'message' => $str, // compate with exeption / loadexception.
413
414                     'errors' => $errors ? $errors : true, // used by forms to flag errors.
415                     'authFailure' => !empty($errors['authFailure']),
416                 ));
417             echo "</BODY></HTML>";
418             exit;
419         }
420        
421         echo $json->encode(array(
422             'success'=> false, 
423             'data'=> array(), 
424             'errorMsg' => $str,
425             'message' => $str, // compate with exeption / loadexception.
426             'errors' => $errors ? $errors : true, // used by forms to flag errors.
427             'authFailure' => !empty($errors['authFailure']),
428         ));
429         exit;
430         
431     }
432     function jok($str)
433     {
434         
435         require_once 'Services/JSON.php';
436         $json = new Services_JSON();
437         
438         if (!empty($_REQUEST['returnHTML']) || 
439             (isset($_SERVER['CONTENT_TYPE']) && preg_match('#multipart/form-data#i', $_SERVER['CONTENT_TYPE']))
440         
441         ) {
442             header('Content-type: text/html');
443             echo "<HTML><HEAD></HEAD><BODY>";
444             echo  $json->encodeUnsafe(array('success'=> true, 'data' => $str));
445             echo "</BODY></HTML>";
446             exit;
447         }
448          
449         
450         echo  $json->encode(array('success'=> true, 'data' => $str));
451         exit;
452         
453     }
454     /**
455      * output data for grids or tree
456      * @ar {Array} ar Array of data
457      * @total {Number|false} total number of records (or false to return count(ar)
458      * @extra {Array} extra key value list of data to pass as extra data.
459      * 
460      */
461     function jdata($ar,$total=false, $extra=array())
462     {
463         // should do mobile checking???
464         if ($total == false) {
465             $total = count($ar);
466         }
467         $extra=  $extra ? $extra : array();
468         require_once 'Services/JSON.php';
469         $json = new Services_JSON();
470         echo $json->encode(array('success' =>  true, 'total'=> $total, 'data' => $ar) + $extra);    
471         exit;
472         
473         
474     }
475     
476     
477    
478    
479       
480     /**
481      * ---------------- Page output?!?!?
482      */
483     
484     
485     function hasBg($fn) // used on front page to check if logos exist..
486     {
487         return file_exists($this->rootDir.'/Pman/'.$this->appNameShort.'/templates/images/'.  $fn);
488     }
489     
490     function outputJavascriptIncludes() // includes on devel version..
491     {
492         
493         $mods = explode(',', $this->appModules);
494         array_unshift($mods,   'Core');
495         $mods = array_unique($mods);
496         
497         foreach($mods as $mod) {
498             // add the css file..
499             
500             $files = $this->moduleJavascriptList($mod.'/widgets');
501             foreach($files as $f) {
502                 echo '<script type="text/javascript" src="'. $f. '"></script>'."\n";
503             }
504             
505             $files = $this->moduleJavascriptList($mod);
506             foreach($files as $f) {
507                 echo '<script type="text/javascript" src="'. $f. '"></script>'."\n";
508             }
509             
510         }
511          
512     }
513     
514     function outputCSSIncludes() // includes on CSS links.
515     {
516         
517         $mods = explode(',', $this->appModules);
518         array_unshift($mods,   'Core');
519         $mods = array_unique($mods);
520         
521         foreach($mods as $mod) {
522             // add the css file..
523             $css = $this->rootDir.'/Pman/'.$mod.'/'.strtolower($mod).'.css';
524             if (file_exists( $css)){
525                 $css = $this->rootURL .'/Pman/'.$mod.'/'.strtolower($mod).'.css';
526                 echo '<link rel="stylesheet" type="text/css" href="'.$css.'" />'."\n";
527             }
528              
529             
530         }
531          
532     }
533     
534
535     
536     
537     function moduleJavascriptList($mod)
538     {
539         
540         $ff = HTML_FlexyFramework::get();
541         
542         $dir =   $this->rootDir.'/Pman/'. $mod;
543             
544         $path =    $this->rootURL."/Pman/$mod/";
545         $base = dirname($_SERVER['SCRIPT_FILENAME']);
546         $cfile = realpath($base .'/_compiled_/' . $mod);
547         $lfile = realpath($base .'/_translations_/' . $mod .  '.js');
548         //    var_dump($cfile);
549         if (!file_exists($dir)) {
550         
551             return array();
552         }
553         $dh = opendir($dir);
554         $maxtime = 0;
555         $ctime = 0;
556         $files = array();
557         if (file_exists($cfile)) {
558            // $ctime = max(filemtime($cfile), filectime($cfile));
559             // otherwise use compile dfile..
560             $cfile = array_pop(glob($cfile . '/' . $mod + '*.js'));
561             echo $cfile;exit;
562             
563             $files = array( $this->rootURL."/_compiled_/". basename($cfile));
564             if (file_exists($lfile)) {
565                 array_push($files, $this->rootURL."/_translations_/$mod.js");
566             }
567             return $files;
568         }
569         // works out if stuff has been updated..
570         // technically the non-dev version should output compiled only?!!?
571         
572         while (false !== ($f = readdir($dh))) {
573            // var_dump($f);
574             if (!preg_match('/\.js$/', $f)) {
575                 continue;
576             }
577             // got the 'module file..'
578         
579             $maxtime = max(filemtime($dir . '/'. $f), $maxtime);
580             $files[] = $path . $f;
581         }
582         if (empty($files)) {
583             return $files;
584         }
585        // var_dump(array($maxtime , $ctime)); 
586         //if ($maxtime > $ctime) {
587             $lsort = create_function('$a,$b','return strlen($a) > strlen($b) ? 1 : -1;');
588             usort($files, $lsort);
589            // if (file_exists($lfile)) {
590            //     array_unshift($files, $this->rootURL."/_translations_/$mod.js");
591             //}
592             //var_dump($files);
593             return $files;
594        // }
595         
596     }
597     
598     
599     
600     /**
601      * ---------------- Logging ---------------   
602      */
603     
604     
605     
606     
607     
608     function addEvent($act, $obj = false, $remarks = '') {
609         $au = $this->getAuthUser();
610         $e = DB_DataObject::factory('Events');
611         
612         if (is_a($e, 'PEAR_Error')) {
613             return; // no event table!
614         }
615         $e->person_name = $au ? $au->name : '';
616         $e->person_id = $au ? $au->id : '';
617         $e->event_when = date('Y-m-d H:i:s');
618         $e->ipaddr = $_SERVER["REMOTE_ADDR"];
619         $e->action = $act;
620         $e->on_table = $obj ? $obj->tableName() : '';
621         $e->on_id  = $obj ? $obj->id : 0;
622         $e->remarks = $remarks;
623         $e->insert();
624         
625     }
626
627     
628      
629     
630 }