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