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