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