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