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