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