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