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