Merge branch 'master' of http://private.akbkhome.com/Pman.Base
[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             echo  $json->encodeUnsafe(array('success'=> true, 'data' => $str));
468             echo "</BODY></HTML>";
469             exit;
470         }
471          
472         
473         echo  $json->encode(array('success'=> true, 'data' => $str));
474         exit;
475         
476     }
477     /**
478      * output data for grids or tree
479      * @ar {Array} ar Array of data
480      * @total {Number|false} total number of records (or false to return count(ar)
481      * @extra {Array} extra key value list of data to pass as extra data.
482      * 
483      */
484     function jdata($ar,$total=false, $extra=array())
485     {
486         // should do mobile checking???
487         if ($total == false) {
488             $total = count($ar);
489         }
490         $extra=  $extra ? $extra : array();
491         require_once 'Services/JSON.php';
492         $json = new Services_JSON();
493         echo $json->encode(array('success' =>  true, 'total'=> $total, 'data' => $ar) + $extra);    
494         exit;
495         
496         
497     }
498     
499     
500    
501    
502       
503     /**
504      * ---------------- Page output?!?!?
505      */
506     
507     
508     function hasBg($fn) // used on front page to check if logos exist..
509     {
510         return file_exists($this->rootDir.'/Pman/'.$this->appNameShort.'/templates/images/'.  $fn);
511     }
512     
513     function outputJavascriptIncludes() // includes on devel version..
514     {
515         
516         $mods = explode(',', $this->appModules);
517         if (in_array('Core',$mods)) { // core has to be the first  modules loaded as it contains Pman.js
518             array_unshift($mods,   'Core');
519         }
520         
521         $mods = array_unique($mods);
522          
523         $disabled =  explode(',', $this->appDisable ? $this->appDisable: '');
524         
525         foreach($mods as $mod) {
526             // add the css file..
527             if (in_array($mod, $disabled)) {
528                 continue;
529             }
530             
531             
532             $files = $this->moduleJavascriptList($mod.'/widgets');
533             foreach($files as $f) {
534                 echo '<script type="text/javascript" src="'. $f. '"></script>'."\n";
535             }
536             
537             $files = $this->moduleJavascriptList($mod);
538             foreach($files as $f) {
539                 echo '<script type="text/javascript" src="'. $f. '"></script>'."\n";
540             }
541             
542         }
543          
544     }
545     
546     function outputCSSIncludes() // includes on CSS links.
547     {
548         
549         $mods = explode(',', $this->appModules);
550         array_unshift($mods,   'Core');
551         $mods = array_unique($mods);
552         
553         foreach($mods as $mod) {
554             // add the css file..
555             $css = $this->rootDir.'/Pman/'.$mod.'/'.strtolower($mod).'.css';
556             if (file_exists( $css)){
557                 $css = $this->rootURL .'/Pman/'.$mod.'/'.strtolower($mod).'.css';
558                 echo '<link rel="stylesheet" type="text/css" href="'.$css.'" />'."\n";
559             }
560              
561             
562         }
563          
564     }
565     
566
567     
568     
569     function moduleJavascriptList($mod)
570     {
571         
572         $ff = HTML_FlexyFramework::get();
573         
574         $dir =   $this->rootDir.'/Pman/'. $mod;
575             
576         $path =    $this->rootURL."/Pman/$mod/";
577         $base = dirname($_SERVER['SCRIPT_FILENAME']);
578         $cfile = realpath($base .'/_compiled_/' . $mod);
579         $lfile = realpath($base .'/_translations_/' . $mod .  '.js');
580         //    var_dump($cfile);
581         if (!file_exists($dir)) {
582         
583             return array();
584         }
585         $dh = opendir($dir);
586         $maxtime = 0;
587         $ctime = 0;
588         $files = array();
589         if (file_exists($cfile)) {
590            // $ctime = max(filemtime($cfile), filectime($cfile));
591             // otherwise use compile dfile..
592             $maxm = 0;
593             $ar = glob($cfile . '/' . $mod . '*.js');
594             // default to first..
595             $cfile = basename($ar[count($ar) -1]);
596             foreach($ar as $fn) {
597                 if (filemtime($fn) > $maxm) {
598                     $cfile = basename($fn);
599                     $maxm = filemtime($fn);
600                 }
601                 
602             }
603             
604              
605             $files = array( $this->rootURL. "/_compiled_/".$mod . "/" . $cfile);
606             if (file_exists($lfile)) {
607                 array_push($files, $this->rootURL."/_translations_/$mod.js");
608             }
609             return $files;
610         }
611         // works out if stuff has been updated..
612         // technically the non-dev version should output compiled only?!!?
613         
614         while (false !== ($f = readdir($dh))) {
615            // var_dump($f);
616             if (!preg_match('/\.js$/', $f)) {
617                 continue;
618             }
619             // got the 'module file..'
620         
621             $maxtime = max(filemtime($dir . '/'. $f), $maxtime);
622             $files[] = $path . $f;
623         }
624         if (empty($files)) {
625             return $files;
626         }
627        // var_dump(array($maxtime , $ctime)); 
628         //if ($maxtime > $ctime) {
629             $lsort = create_function('$a,$b','return strlen($a) > strlen($b) ? 1 : -1;');
630             usort($files, $lsort);
631            // if (file_exists($lfile)) {
632            //     array_unshift($files, $this->rootURL."/_translations_/$mod.js");
633             //}
634             //var_dump($files);
635             return $files;
636        // }
637         
638     }
639     
640     
641     
642     /**
643      * ---------------- Logging ---------------   
644      */
645     
646     /**
647      * addEventOnce:
648      * Log an action (only if it has not been logged already.
649      * 
650      * @param {String} action  - group/name of event
651      * @param {DataObject|false} obj - dataobject action occured on.
652      * @param {String} any remarks 
653      */
654     
655     function addEventOnce($act, $obj = false, $remarks = '') 
656     {
657         $au = $this->getAuthUser();
658         $e = DB_DataObject::factory('Events');
659         $e->init($act,$obj,$remarks); 
660         if ($e->find(true)) {
661             return;
662         }
663         $this->addEvent($act, $obj, $remarks);
664     }
665     /**
666      * addEvent:
667      * Log an action.
668      * 
669      * @param {String} action  - group/name of event
670      * @param {DataObject|false} obj - dataobject action occured on.
671      * @param {String} any remarks 
672      */
673     
674     function addEvent($act, $obj = false, $remarks = '') 
675     {
676         $au = $this->getAuthUser();
677         $e = DB_DataObject::factory('Events');
678         $e->init($act,$obj,$remarks); 
679          
680         $e->event_when = date('Y-m-d H:i:s');
681         
682         $eid = $e->insert();
683         $ff  = HTML_FlexyFramework::get();
684         if (empty($ff->Pman['event_log_dir'])) {
685             return;
686         }
687         $file = $ff->Pman['event_log_dir']. date('/Y/m/d/'). $eid . ".php";
688         if (!file_exists(dirname($file))) {
689             mkdir(dirname($file),0700,true);
690         }
691         file_put_contents($file, var_export(array(
692             'REQUEST_URI' => empty($_SERVER['REQUEST_URI']) ? 'cli' : $_SERVER['REQUEST_URI'],
693             'GET' => empty($_GET) ? array() : $_GET,
694             'POST' => empty($_POST) ? array() : $_POST,
695         ), true));
696         
697         
698         
699     }
700
701     
702      
703     
704 }