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         // log all errors!!!
401         $this->addEvent("ERROR", false, $str);
402         
403         if (!empty($_REQUEST['returnHTML']) || 
404             (isset($_SERVER['CONTENT_TYPE']) && preg_match('#multipart/form-data#i', $_SERVER['CONTENT_TYPE']))
405         ) {
406             header('Content-type: text/html');
407             echo "<HTML><HEAD></HEAD><BODY>";
408             echo  $json->encodeUnsafe(array(
409                     'success'=> false, 
410                     'errorMsg' => $str,
411                     'message' => $str, // compate with exeption / loadexception.
412
413                     'errors' => $errors ? $errors : true, // used by forms to flag errors.
414                     'authFailure' => !empty($errors['authFailure']),
415                 ));
416             echo "</BODY></HTML>";
417             exit;
418         }
419         
420         echo $json->encode(array(
421             'success'=> false, 
422             'data'=> array(), 
423             'errorMsg' => $str,
424             'message' => $str, // compate with exeption / loadexception.
425             'errors' => $errors ? $errors : true, // used by forms to flag errors.
426             'authFailure' => !empty($errors['authFailure']),
427         ));
428         exit;
429         
430     }
431     function jok($str)
432     {
433         
434         require_once 'Services/JSON.php';
435         $json = new Services_JSON();
436         
437         if (!empty($_REQUEST['returnHTML']) || 
438             (isset($_SERVER['CONTENT_TYPE']) && preg_match('#multipart/form-data#i', $_SERVER['CONTENT_TYPE']))
439         
440         ) {
441             header('Content-type: text/html');
442             echo "<HTML><HEAD></HEAD><BODY>";
443             echo  $json->encodeUnsafe(array('success'=> true, 'data' => $str));
444             echo "</BODY></HTML>";
445             exit;
446         }
447          
448         
449         echo  $json->encode(array('success'=> true, 'data' => $str));
450         exit;
451         
452     }
453     /**
454      * output data for grids or tree
455      * @ar {Array} ar Array of data
456      * @total {Number|false} total number of records (or false to return count(ar)
457      * @extra {Array} extra key value list of data to pass as extra data.
458      * 
459      */
460     function jdata($ar,$total=false, $extra=array())
461     {
462         // should do mobile checking???
463         if ($total == false) {
464             $total = count($ar);
465         }
466         $extra=  $extra ? $extra : array();
467         require_once 'Services/JSON.php';
468         $json = new Services_JSON();
469         echo $json->encode(array('success' =>  true, 'total'=> $total, 'data' => $ar) + $extra);    
470         exit;
471         
472         
473     }
474     
475     
476    
477    
478       
479     /**
480      * ---------------- Page output?!?!?
481      */
482     
483     
484     function hasBg($fn) // used on front page to check if logos exist..
485     {
486         return file_exists($this->rootDir.'/Pman/'.$this->appNameShort.'/templates/images/'.  $fn);
487     }
488     
489     function outputJavascriptIncludes() // includes on devel version..
490     {
491         
492         $mods = explode(',', $this->appModules);
493         if (!in_array('Core',$this->appModules)) {
494             array_unshift($mods,   'Core');
495         }
496         
497         $mods = array_unique($mods);
498         print_r($mods);exit;
499         
500         $disabled =  explode(',', $this->appDisable ? $this->appDisable: '');
501         
502         foreach($mods as $mod) {
503             // add the css file..
504             if (in_array($mod, $disabled)) {
505                 continue;
506             }
507             
508             
509             $files = $this->moduleJavascriptList($mod.'/widgets');
510             foreach($files as $f) {
511                 echo '<script type="text/javascript" src="'. $f. '"></script>'."\n";
512             }
513             
514             $files = $this->moduleJavascriptList($mod);
515             foreach($files as $f) {
516                 echo '<script type="text/javascript" src="'. $f. '"></script>'."\n";
517             }
518             
519         }
520          
521     }
522     
523     function outputCSSIncludes() // includes on CSS links.
524     {
525         
526         $mods = explode(',', $this->appModules);
527         array_unshift($mods,   'Core');
528         $mods = array_unique($mods);
529         
530         foreach($mods as $mod) {
531             // add the css file..
532             $css = $this->rootDir.'/Pman/'.$mod.'/'.strtolower($mod).'.css';
533             if (file_exists( $css)){
534                 $css = $this->rootURL .'/Pman/'.$mod.'/'.strtolower($mod).'.css';
535                 echo '<link rel="stylesheet" type="text/css" href="'.$css.'" />'."\n";
536             }
537              
538             
539         }
540          
541     }
542     
543
544     
545     
546     function moduleJavascriptList($mod)
547     {
548         
549         $ff = HTML_FlexyFramework::get();
550         
551         $dir =   $this->rootDir.'/Pman/'. $mod;
552             
553         $path =    $this->rootURL."/Pman/$mod/";
554         $base = dirname($_SERVER['SCRIPT_FILENAME']);
555         $cfile = realpath($base .'/_compiled_/' . $mod);
556         $lfile = realpath($base .'/_translations_/' . $mod .  '.js');
557         //    var_dump($cfile);
558         if (!file_exists($dir)) {
559         
560             return array();
561         }
562         $dh = opendir($dir);
563         $maxtime = 0;
564         $ctime = 0;
565         $files = array();
566         if (file_exists($cfile)) {
567            // $ctime = max(filemtime($cfile), filectime($cfile));
568             // otherwise use compile dfile..
569             $maxm = 0;
570             $ar = glob($cfile . '/' . $mod . '*.js');
571             // default to first..
572             $cfile = basename($ar[count($ar) -1]);
573             foreach($ar as $fn) {
574                 if (filemtime($fn) > $maxm) {
575                     $cfile = basename($fn);
576                     $maxm = filemtime($fn);
577                 }
578                 
579             }
580             
581              
582             $files = array( $this->rootURL. "/_compiled_/".$mod . "/" . $cfile);
583             if (file_exists($lfile)) {
584                 array_push($files, $this->rootURL."/_translations_/$mod.js");
585             }
586             return $files;
587         }
588         // works out if stuff has been updated..
589         // technically the non-dev version should output compiled only?!!?
590         
591         while (false !== ($f = readdir($dh))) {
592            // var_dump($f);
593             if (!preg_match('/\.js$/', $f)) {
594                 continue;
595             }
596             // got the 'module file..'
597         
598             $maxtime = max(filemtime($dir . '/'. $f), $maxtime);
599             $files[] = $path . $f;
600         }
601         if (empty($files)) {
602             return $files;
603         }
604        // var_dump(array($maxtime , $ctime)); 
605         //if ($maxtime > $ctime) {
606             $lsort = create_function('$a,$b','return strlen($a) > strlen($b) ? 1 : -1;');
607             usort($files, $lsort);
608            // if (file_exists($lfile)) {
609            //     array_unshift($files, $this->rootURL."/_translations_/$mod.js");
610             //}
611             //var_dump($files);
612             return $files;
613        // }
614         
615     }
616     
617     
618     
619     /**
620      * ---------------- Logging ---------------   
621      */
622     
623     /**
624      * addEventOnce:
625      * Log an action (only if it has not been logged already.
626      * 
627      * @param {String} action  - group/name of event
628      * @param {DataObject|false} obj - dataobject action occured on.
629      * @param {String} any remarks 
630      */
631     
632     function addEventOnce($act, $obj = false, $remarks = '') 
633     {
634         $au = $this->getAuthUser();
635         $e = DB_DataObject::factory('Events');
636         $e->init($act,$obj,$remarks); 
637         if ($e->find(true)) {
638             return;
639         }
640         $this->addEvent($act, $obj, $remarks);
641     }
642     /**
643      * addEvent:
644      * Log an action.
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 addEvent($act, $obj = false, $remarks = '') 
652     {
653         $au = $this->getAuthUser();
654         $e = DB_DataObject::factory('Events');
655         $e->init($act,$obj,$remarks); 
656          
657         $e->event_when = date('Y-m-d H:i:s');
658         
659         $eid = $e->insert();
660         $ff  = HTML_FlexyFramework::get();
661         if (empty($ff->Pman['event_log_dir'])) {
662             return;
663         }
664         $file = $ff->Pman['event_log_dir']. date('/Y/m/d/'). $eid . ".php";
665         if (!file_exists(dirname($file))) {
666             mkdir(dirname($file),0700,true);
667         }
668         file_put_contents($file, var_export(array(
669             'REQUEST_URI' => empty($_SERVER['REQUEST_URI']) ? 'cli' : $_SERVER['REQUEST_URI'],
670             'GET' => empty($_GET) ? array() : $_GET,
671             'POST' => empty($_POST) ? array() : $_POST,
672         ), true));
673         
674         
675         
676     }
677
678     
679      
680     
681 }