d699ce4243a32978199418f790c6809e439fbfcf
[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     
173     function modules()
174     {
175         // appModules/appDisable contain a comma limited list of
176         // both modules and components that can be enabled/disabled..
177         
178         // the modules call just lists the modules
179         $enabled =  array('Core' => true);
180          $am = !empty($this->appModules) ? explode(',',  $this->appModules) : array();
181         foreach($am as $k) {
182             if (strpos( $k ,'.') ) {
183                 continue;
184             }
185             $enabled[$k] = true;
186         }
187         
188         
189         $disabled =  !empty($this->appDisable) ?  explode(',', $this->appDisable) : array();
190         foreach($disabled as $k) {
191             if ( strpos( $k ,'.') ) {
192                 continue;
193             }
194             if (isset($enabled[$k])) {
195                 unset($enabled[$k]);
196             }   
197         }
198                 var_Dump($enabled);
199
200         return array_keys($enabled); 
201     }
202     
203     function hasModule($name) 
204     {
205         $this->init();
206         if (!strpos( $name,'.') ) {
207             // use enable / disable..
208             return in_array($name, $this->modules()); 
209         }
210         
211         $x = DB_DataObject::factory('Group_Rights');
212         $ar = $x->defaultPermData();
213         if (empty($ar[$name]) || empty($ar[$name][0])) {
214             return false;
215         }
216         return true;
217     }
218     
219     
220     
221     
222     /**
223      * ---------------- Global Tools ---------------   
224      */
225     
226     
227     
228     /**
229      * send a template to the user
230      * rcpts are read from the resulting template.
231      * 
232      * @arg $templateFile  - the file in mail/XXXXXX.txt
233      * @arg $args  - variables available to the form as {t.*} over and above 'this'
234      * 
235      * 
236      */
237     
238     function sendTemplate($templateFile, $args)
239     {
240         
241         
242         
243         $content  = clone($this);
244         
245         foreach((array)$args as $k=>$v) {
246             $content->$k = $v;
247         }
248         $content->msgid = md5(time() . rand());
249         
250         $content->HTTP_HOST = $_SERVER["HTTP_HOST"];
251         /* use the regex compiler, as it doesnt parse <tags */
252         require_once 'HTML/Template/Flexy.php';
253         $template = new HTML_Template_Flexy( array(
254                  'compiler'    => 'Regex',
255                  'filters' => array('SimpleTags','Mail'),
256             //     'debug'=>1,
257             ));
258         
259         // this should be done by having multiple template sources...!!!
260          
261         $template->compile('mail/'. $templateFile.'.txt');
262         
263         /* use variables from this object to ouput data. */
264         $mailtext = $template->bufferedOutputObject($content);
265         //echo "<PRE>";print_R($mailtext);
266         
267         /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
268         require_once 'Mail/mimeDecode.php';
269         require_once 'Mail.php';
270         
271         $decoder = new Mail_mimeDecode($mailtext);
272         $parts = $decoder->getSendArray();
273         if (PEAR::isError($parts)) {
274             return $parts;
275             //echo "PROBLEM: {$parts->message}";
276             //exit;
277         } 
278         list($recipents,$headers,$body) = $parts;
279         ///$recipents = array($this->email);
280         $mailOptions = PEAR::getStaticProperty('Mail','options');
281         $mail = Mail::factory("SMTP",$mailOptions);
282         $headers['Date'] = date('r');
283         if (PEAR::isError($mail)) {
284             return $mail;
285         } 
286         $oe = error_reporting(E_ALL ^ E_NOTICE);
287         $ret = $mail->send($recipents,$headers,$body);
288         error_reporting($oe);
289        
290         return $ret;
291     
292     }
293     
294     function checkFileUploadError()  // check for file upload errors.
295     {    
296         if (
297             empty($_FILES['File']) 
298             || empty($_FILES['File']['name']) 
299             || empty($_FILES['File']['tmp_name']) 
300             || empty($_FILES['File']['type']) 
301             || !empty($_FILES['File']['error']) 
302             || empty($_FILES['File']['size']) 
303         ) {
304             $this->jerr("File upload error: <PRE>" . print_r($_FILES,true) . print_r($_POST,true) . "</PRE>");
305         }
306     }
307     
308     
309     /**
310      * generate a tempory file with an extension (dont forget to delete it)
311      */
312     
313     function tempName($ext)
314     {
315         $x = tempnam(ini_get('session.save_path'), HTML_FlexyFramework::get()->appNameShort.'TMP');
316         unlink($x);
317         return $x .'.'. $ext;
318     }
319     /**
320      * ------------- Authentication testing ------ ??? MOVEME?
321      * 
322      * 
323      */
324     function linkAuth($trid, $trkey) 
325     {
326         $tr = DB_DataObject::factory('Documents_Tracking');
327         if (!$tr->get($trid)) {
328             return "Invalid URL";
329         }
330         if (strtolower($tr->authkey) != strtolower($trkey)) {
331             $this->AddEvent("ERROR-L", false, "Invalid Key");
332             return "Invalid KEY";
333         }
334         // check date..
335         $this->onloadTrack = (int) $tr->doc_id;
336         if (strtotime($tr->date_sent) < strtotime("NOW - 14 DAYS")) {
337             $this->AddEvent("ERROR-L", false, "Key Expired");
338             return "Key Expired";
339         }
340         // user logged in and not
341         $au = $this->getAuthUser();
342         if ($au && $au->id && $au->id != $tr->person_id) {
343             $au->logout();
344             
345             return "Logged Out existing Session\n - reload to log in with correct key";
346         }
347         if ($au) { // logged in anyway..
348             $this->AddEvent("LOGIN", false, "With Key (ALREADY)");
349             header('Location: ' . $this->baseURL.'?onloadTrack='.$this->onloadTrack);
350             exit;
351             return false;
352         }
353         
354         // authenticate the user...
355         // slightly risky...
356         $u = DB_DataObject::factory('Person');
357          
358         $u->get($tr->person_id);
359         $u->login();
360         $this->AddEvent("LOGIN", false, "With Key");
361         
362         // we need to redirect out - otherwise refererer url will include key!
363         header('Location: ' . $this->baseURL.'?onloadTrack='.$this->onloadTrack);
364         exit;
365         
366         return false;
367         
368         
369         
370         
371     }
372     
373     
374     /**
375      * ------------- Authentication password reset ------ ??? MOVEME?
376      * 
377      * 
378      */
379     
380     
381     function resetPassword($id,$t, $key)
382     {
383         
384         $au = $this->getAuthUser();
385         if ($au) {
386             return "Already Logged in - no need to use Password Reset";
387         }
388         
389         $u = DB_DataObject::factory('Person');
390         //$u->company_id = $this->company->id;
391         $u->active = 1;
392         if (!$u->get($id) || !strlen($u->passwd)) {
393             return "invalid id";
394         }
395         
396         // validate key.. 
397         if ($key != $u->genPassKey($t)) {
398             return "invalid key";
399         }
400         $uu = clone($u);
401         $u->no_reset_sent = 0;
402         $u->update($uu);
403         
404         if ($t < strtotime("NOW - 1 DAY")) {
405             return "expired";
406         }
407         $this->showNewPass = implode("/", array($id,$t,$key));
408         return false;
409     }
410     
411      
412     /**
413      * ---------------- Standard JSON outputers. - used everywhere
414      */
415     
416     function jerr($str, $errors=array()) // standard error reporting..
417     {
418         require_once 'Services/JSON.php';
419         $json = new Services_JSON();
420         
421         // log all errors!!!
422         $this->addEvent("ERROR", false, $str);
423         
424         if (!empty($_REQUEST['returnHTML']) || 
425             (isset($_SERVER['CONTENT_TYPE']) && preg_match('#multipart/form-data#i', $_SERVER['CONTENT_TYPE']))
426         ) {
427             header('Content-type: text/html');
428             echo "<HTML><HEAD></HEAD><BODY>";
429             echo  $json->encodeUnsafe(array(
430                     'success'=> false, 
431                     'errorMsg' => $str,
432                     'message' => $str, // compate with exeption / loadexception.
433
434                     'errors' => $errors ? $errors : true, // used by forms to flag errors.
435                     'authFailure' => !empty($errors['authFailure']),
436                 ));
437             echo "</BODY></HTML>";
438             exit;
439         }
440         
441         echo $json->encode(array(
442             'success'=> false, 
443             'data'=> array(), 
444             'errorMsg' => $str,
445             'message' => $str, // compate with exeption / loadexception.
446             'errors' => $errors ? $errors : true, // used by forms to flag errors.
447             'authFailure' => !empty($errors['authFailure']),
448         ));
449         exit;
450         
451     }
452     function jok($str)
453     {
454         
455         require_once 'Services/JSON.php';
456         $json = new Services_JSON();
457         
458         if (!empty($_REQUEST['returnHTML']) || 
459             (isset($_SERVER['CONTENT_TYPE']) && preg_match('#multipart/form-data#i', $_SERVER['CONTENT_TYPE']))
460         
461         ) {
462             header('Content-type: text/html');
463             echo "<HTML><HEAD></HEAD><BODY>";
464             echo  $json->encodeUnsafe(array('success'=> true, 'data' => $str));
465             echo "</BODY></HTML>";
466             exit;
467         }
468          
469         
470         echo  $json->encode(array('success'=> true, 'data' => $str));
471         exit;
472         
473     }
474     /**
475      * output data for grids or tree
476      * @ar {Array} ar Array of data
477      * @total {Number|false} total number of records (or false to return count(ar)
478      * @extra {Array} extra key value list of data to pass as extra data.
479      * 
480      */
481     function jdata($ar,$total=false, $extra=array())
482     {
483         // should do mobile checking???
484         if ($total == false) {
485             $total = count($ar);
486         }
487         $extra=  $extra ? $extra : array();
488         require_once 'Services/JSON.php';
489         $json = new Services_JSON();
490         echo $json->encode(array('success' =>  true, 'total'=> $total, 'data' => $ar) + $extra);    
491         exit;
492         
493         
494     }
495     
496     
497    
498    
499       
500     /**
501      * ---------------- Page output?!?!?
502      */
503     
504     
505     function hasBg($fn) // used on front page to check if logos exist..
506     {
507         return file_exists($this->rootDir.'/Pman/'.$this->appNameShort.'/templates/images/'.  $fn);
508     }
509     
510     function outputJavascriptIncludes() // includes on devel version..
511     {
512         
513         $mods = explode(',', $this->appModules);
514         if (in_array('Core',$mods)) { // core has to be the first  modules loaded as it contains Pman.js
515             array_unshift($mods,   'Core');
516         }
517         
518         $mods = array_unique($mods);
519          
520         $disabled =  explode(',', $this->appDisable ? $this->appDisable: '');
521         
522         foreach($mods as $mod) {
523             // add the css file..
524             if (in_array($mod, $disabled)) {
525                 continue;
526             }
527             
528             
529             $files = $this->moduleJavascriptList($mod.'/widgets');
530             foreach($files as $f) {
531                 echo '<script type="text/javascript" src="'. $f. '"></script>'."\n";
532             }
533             
534             $files = $this->moduleJavascriptList($mod);
535             foreach($files as $f) {
536                 echo '<script type="text/javascript" src="'. $f. '"></script>'."\n";
537             }
538             
539         }
540          
541     }
542     
543     function outputCSSIncludes() // includes on CSS links.
544     {
545         
546         $mods = explode(',', $this->appModules);
547         array_unshift($mods,   'Core');
548         $mods = array_unique($mods);
549         
550         foreach($mods as $mod) {
551             // add the css file..
552             $css = $this->rootDir.'/Pman/'.$mod.'/'.strtolower($mod).'.css';
553             if (file_exists( $css)){
554                 $css = $this->rootURL .'/Pman/'.$mod.'/'.strtolower($mod).'.css';
555                 echo '<link rel="stylesheet" type="text/css" href="'.$css.'" />'."\n";
556             }
557              
558             
559         }
560          
561     }
562     
563
564     
565     
566     function moduleJavascriptList($mod)
567     {
568         
569         $ff = HTML_FlexyFramework::get();
570         
571         $dir =   $this->rootDir.'/Pman/'. $mod;
572             
573         $path =    $this->rootURL."/Pman/$mod/";
574         $base = dirname($_SERVER['SCRIPT_FILENAME']);
575         $cfile = realpath($base .'/_compiled_/' . $mod);
576         $lfile = realpath($base .'/_translations_/' . $mod .  '.js');
577         //    var_dump($cfile);
578         if (!file_exists($dir)) {
579         
580             return array();
581         }
582         $dh = opendir($dir);
583         $maxtime = 0;
584         $ctime = 0;
585         $files = array();
586         if (file_exists($cfile)) {
587            // $ctime = max(filemtime($cfile), filectime($cfile));
588             // otherwise use compile dfile..
589             $maxm = 0;
590             $ar = glob($cfile . '/' . $mod . '*.js');
591             // default to first..
592             $cfile = basename($ar[count($ar) -1]);
593             foreach($ar as $fn) {
594                 if (filemtime($fn) > $maxm) {
595                     $cfile = basename($fn);
596                     $maxm = filemtime($fn);
597                 }
598                 
599             }
600             
601              
602             $files = array( $this->rootURL. "/_compiled_/".$mod . "/" . $cfile);
603             if (file_exists($lfile)) {
604                 array_push($files, $this->rootURL."/_translations_/$mod.js");
605             }
606             return $files;
607         }
608         // works out if stuff has been updated..
609         // technically the non-dev version should output compiled only?!!?
610         
611         while (false !== ($f = readdir($dh))) {
612            // var_dump($f);
613             if (!preg_match('/\.js$/', $f)) {
614                 continue;
615             }
616             // got the 'module file..'
617         
618             $maxtime = max(filemtime($dir . '/'. $f), $maxtime);
619             $files[] = $path . $f;
620         }
621         if (empty($files)) {
622             return $files;
623         }
624        // var_dump(array($maxtime , $ctime)); 
625         //if ($maxtime > $ctime) {
626             $lsort = create_function('$a,$b','return strlen($a) > strlen($b) ? 1 : -1;');
627             usort($files, $lsort);
628            // if (file_exists($lfile)) {
629            //     array_unshift($files, $this->rootURL."/_translations_/$mod.js");
630             //}
631             //var_dump($files);
632             return $files;
633        // }
634         
635     }
636     
637     
638     
639     /**
640      * ---------------- Logging ---------------   
641      */
642     
643     /**
644      * addEventOnce:
645      * Log an action (only if it has not been logged already.
646      * 
647      * @param {String} action  - group/name of event
648      * @param {DataObject|false} obj - dataobject action occured on.
649      * @param {String} any remarks 
650      */
651     
652     function addEventOnce($act, $obj = false, $remarks = '') 
653     {
654         $au = $this->getAuthUser();
655         $e = DB_DataObject::factory('Events');
656         $e->init($act,$obj,$remarks); 
657         if ($e->find(true)) {
658             return;
659         }
660         $this->addEvent($act, $obj, $remarks);
661     }
662     /**
663      * addEvent:
664      * Log an action.
665      * 
666      * @param {String} action  - group/name of event
667      * @param {DataObject|false} obj - dataobject action occured on.
668      * @param {String} any remarks 
669      */
670     
671     function addEvent($act, $obj = false, $remarks = '') 
672     {
673         $au = $this->getAuthUser();
674         $e = DB_DataObject::factory('Events');
675         $e->init($act,$obj,$remarks); 
676          
677         $e->event_when = date('Y-m-d H:i:s');
678         
679         $eid = $e->insert();
680         $ff  = HTML_FlexyFramework::get();
681         if (empty($ff->Pman['event_log_dir'])) {
682             return;
683         }
684         $file = $ff->Pman['event_log_dir']. date('/Y/m/d/'). $eid . ".php";
685         if (!file_exists(dirname($file))) {
686             mkdir(dirname($file),0700,true);
687         }
688         file_put_contents($file, var_export(array(
689             'REQUEST_URI' => empty($_SERVER['REQUEST_URI']) ? 'cli' : $_SERVER['REQUEST_URI'],
690             'GET' => empty($_GET) ? array() : $_GET,
691             'POST' => empty($_POST) ? array() : $_POST,
692         ), true));
693         
694         
695         
696     }
697
698     
699      
700     
701 }