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