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