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