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