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