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