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  *   - any data object where this method exists, the result will get prefixed to the log remarks
22  */
23
24 class Pman extends HTML_FlexyFramework_Page 
25 {
26     var $appName= "";
27     var $appLogo= "";
28     var $appShortName= "";
29     var $appVersion = "1.8";
30     var $version = 'dev';
31     var $onloadTrack = 0;
32     var $linkFail = "";
33     var $showNewPass = 0;
34     var $logoPrefix = '';
35     var $appModules = '';
36     var $appDisabled = array(); // array of disabled modules..
37                     // (based on config option disable)
38     
39     var $authUser; // always contains the authenticated user..
40     
41     var $disable_jstemplate = false; /// disable inclusion of jstemplate code..
42     var $company = false;
43     
44     /**
45      * ------------- Standard getAuth/get/post methods of framework.
46      * 
47      * 
48      */
49     
50     function getAuth() // everyone allowed in!!!!!
51     {
52         $this->loadOwnerCompany();
53         
54         return true;
55         
56     }
57     
58     function init() 
59     {
60         if (isset($this->_hasInit)) {
61             return;
62         }
63         $this->_hasInit = true;
64          // move away from doing this ... you can access bootLoader.XXXXXX in the master template..
65         $boot = HTML_FlexyFramework::get();
66         // echo'<PRE>';print_R($boot);exit;
67         $this->appName= $boot->appName;
68         $this->appNameShort= $boot->appNameShort;
69         
70         
71         $this->appModules= $boot->enable;
72         
73 //        echo $this->arrayToJsInclude($files);        
74         $this->isDev = empty($boot->Pman['isDev']) ? false : $boot->Pman['isDev'];
75         
76         $this->appDisable = $boot->disable;
77         $this->appDisabled = explode(',', $boot->disable);
78         $this->version = $boot->version; 
79         $this->uiConfig = empty($boot->Pman['uiConfig']) ? false : $boot->Pman['uiConfig']; 
80         
81         if (!empty($ff->Pman['local_autoauth']) && 
82             ($_SERVER['SERVER_ADDR'] == '127.0.0.1') &&
83             ($_SERVER['REMOTE_ADDR'] == '127.0.0.1') 
84         ) {
85             $this->isDev = true;
86         }
87         
88         // if a file Pman_{module}_Pman exists.. and it has an init function... - call that..
89         
90         //var_dump($this->appModules);
91         
92         
93         
94     }
95     /*
96      * module init is only loaded on main page call, and includes checks for configuration settings.
97      */
98     function initModules()
99     {
100         foreach(explode(',',$this->appModules) as $m) {
101             $cls = 'Pman_'. $m . '_Pman';
102             //echo $cls;
103             //echo $this->rootDir . '/'.str_replace('_','/', $cls). '.php';
104             
105             if (!file_exists($this->rootDir . '/'.str_replace('_','/', $cls). '.php')) {
106                 continue;
107             }
108             require_once str_replace('_','/', $cls). '.php';
109             $c = new $cls();
110             if (method_exists($c,'init')) {
111                 $c->init($this);
112             }
113         }
114     }
115     
116     
117     
118     function get($base) 
119     {
120         $this->init();
121         if (empty($base)) {
122             $this->initModules();
123         }
124         
125             //$this->allowSignup= empty($opts['allowSignup']) ? 0 : 1;
126         $bits = explode('/', $base);
127         //print_R($bits);
128         if ($bits[0] == 'Link') {
129             $this->linkFail = $this->linkAuth(@$bits[1],@$bits[2]);
130             header('Content-type: text/html; charset=utf-8');
131             return;
132         }
133         
134         // should really be moved to Login...
135         
136         if ($bits[0] == 'PasswordReset') {
137             $this->linkFail = $this->resetPassword(@$bits[1],@$bits[2],@$bits[3]);
138             header('Content-type: text/html; charset=utf-8');
139             return;
140         } 
141          
142         $au = $this->getAuthUser();
143         if ($au) {
144             $ff= HTML_FlexyFramework::get();
145            
146             if (!empty($ff->Pman['auth_comptype']) && $au->id > 0 &&
147                 ( !$au->company_id || ($ff->Pman['auth_comptype'] != $au->company()->comptype))) {
148          
149                 $au->logout();
150                 
151                 $this->jerr("Login not permited to outside companies - please reload");
152             }
153             $this->addEvent("RELOAD");
154         }
155         
156         
157         if (strlen($base)) {
158             $this->addEvent("BADURL", false, $base);
159             $this->jerr("invalid url");
160         }
161         // deliver template
162         if (isset($_GET['onloadTrack'])) {
163             $this->onloadTrack = (int)$_GET['onloadTrack'];
164         }
165         // getting this to work with xhtml is a nightmare
166         // = nbsp / <img> issues screw everyting up.
167          //var_dump($this->isDev);
168         // force regeneration on load for development enviroments..
169         
170         HTML_FlexyFramework::get()->generateDataobjectsCache($this->isDev);
171         
172         //header('Content-type: application/xhtml+xml; charset=utf-8');
173         
174         
175         
176         if ($this->company && $this->company->logo_id) {
177             $im = DB_DataObject::Factory('Images');
178             $im->get($this->company->logo_id);
179             $this->appLogo = $this->baseURL . '/Images/Thumb/300x100/'. $this->company->logo_id .'/' . $im->filename;
180         }
181         
182         header('Content-type: text/html; charset=utf-8');
183          
184     }
185     function post($base) {
186         return $this->get($base);
187     }
188     
189     
190     // --------------- AUTHENTICATION or  system information
191     /**
192      * loadOwnerCompany:
193      * finds the compay with comptype=='OWNER'
194      *
195      * @return {Pman_Core_DataObjects_Companies} the owner company
196      */
197     function loadOwnerCompany()
198     {
199         // only applies if authtable is person..
200         $ff = HTML_FlexyFramework::get();
201         if (!empty($ff->Pman['authTable']) && $ff->Pman['authTable'] != 'Person') {
202             return false;
203         }
204         
205         $this->company = DB_DataObject::Factory('Companies');
206         if (!is_a($this->company, 'DB_DataObject')) { // non-core pman projects
207             return false; 
208         }
209         $this->company->get('comptype', 'OWNER');
210         return $this->company;
211     }
212     
213     
214     
215     /**
216      * getAuthUser: - get the authenticated user..
217      *
218      * @return {DB_DataObject} of type Pman[authTable] if authenticated.
219      */
220     
221     function getAuthUser()
222     {
223         if (!empty($this->authUser)) {
224             return $this->authUser;
225         }
226         $ff = HTML_FlexyFramework::get();
227         $tbl = empty($ff->Pman['authTable']) ? 'Person' : $ff->Pman['authTable'];
228         
229         $u = DB_DataObject::factory( $tbl );
230         if (!$u->isAuth()) {
231             return false;
232         }
233         $this->authUser =$u->getAuthUser();
234         return $this->authUser ;
235     }
236     /**
237      * hasPerm:
238      * wrapper arround authuser->hasPerm
239      * @see Pman_Core_DataObjects_User::hasPerm
240      *
241      * @param {String} $name  The permission name (eg. Projects.List)
242      * @param {String} $lvl   eg. (C)reate (E)dit (D)elete ... etc.
243      * 
244      */
245     function hasPerm($name, $lvl)  // do we have a permission
246     {
247         static $pcache = array();
248         $au = $this->getAuthUser();
249         return $au && $au->hasPerm($name,$lvl);
250         
251     }
252    
253     /**
254      * modulesList:  List the modules in the application
255      *
256      * @return {Array} list of modules
257      */
258     function modulesList()
259     {
260         $boot = HTML_FlexyFramework::get();
261         // echo'<PRE>';print_R($boot);exit;
262          
263          
264         $mods = explode(',', $boot->enable);
265         if (in_array('Core',$mods)) { // core has to be the first  modules loaded as it contains Pman.js
266             array_unshift($mods,   'Core');
267         }
268         
269         if (in_array($boot->appNameShort,$mods)) { // Project has to be the last  modules loaded as it contains Pman.js
270             unset($mods[array_search($boot->appNameShort, $mods)]);
271             $mods[] = $boot->appNameShort;
272         }
273         
274         $mods = array_unique($mods);
275          
276         $disabled =  explode(',', $boot->disable ? $boot->disable : '');
277         $ret = array();
278         foreach($mods as $mod) {
279             // add the css file..
280             if (in_array($mod, $disabled)) {
281                 continue;
282             }
283             $ret[] = $mod;
284         }
285         return $ret;
286     }
287     
288      
289     
290     
291     function hasModule($name) 
292     {
293         $this->init();
294         if (!strpos( $name,'.') ) {
295             // use enable / disable..
296             return in_array($name, $this->modules()); 
297         }
298         
299         $x = DB_DataObject::factory('Group_Rights');
300         $ar = $x->defaultPermData();
301         if (empty($ar[$name]) || empty($ar[$name][0])) {
302             return false;
303         }
304         return true;
305     }
306     
307      
308     
309     
310
311     
312     
313     
314         
315     /**
316      * ---------------- Global Tools ---------------   
317      */
318     function checkFileUploadError()  // check for file upload errors.
319     {    
320         if (
321             empty($_FILES['File']) 
322             || empty($_FILES['File']['name']) 
323             || empty($_FILES['File']['tmp_name']) 
324             || empty($_FILES['File']['type']) 
325             || !empty($_FILES['File']['error']) 
326             || empty($_FILES['File']['size']) 
327         ) {
328             $this->jerr("File upload error: <PRE>" . print_r($_FILES,true) . print_r($_POST,true) . "</PRE>");
329         }
330     }
331     
332     
333     /**
334      * generate a tempory file with an extension (dont forget to delete it)
335      */
336     
337     function tempName($ext)
338     {
339         $x = tempnam(ini_get('session.save_path'), HTML_FlexyFramework::get()->appNameShort.'TMP');
340         unlink($x);
341         return $x .'.'. $ext;
342     }
343     /**
344      * ------------- Authentication testing ------ ??? MOVEME?
345      * 
346      * 
347      */
348     function linkAuth($trid, $trkey) 
349     {
350         $tr = DB_DataObject::factory('Documents_Tracking');
351         if (!$tr->get($trid)) {
352             return "Invalid URL";
353         }
354         if (strtolower($tr->authkey) != strtolower($trkey)) {
355             $this->AddEvent("ERROR-L", false, "Invalid Key");
356             return "Invalid KEY";
357         }
358         // check date..
359         $this->onloadTrack = (int) $tr->doc_id;
360         if (strtotime($tr->date_sent) < strtotime("NOW - 14 DAYS")) {
361             $this->AddEvent("ERROR-L", false, "Key Expired");
362             return "Key Expired";
363         }
364         // user logged in and not
365         $au = $this->getAuthUser();
366         if ($au && $au->id && $au->id != $tr->person_id) {
367             $au->logout();
368             
369             return "Logged Out existing Session\n - reload to log in with correct key";
370         }
371         if ($au) { // logged in anyway..
372             $this->AddEvent("LOGIN", false, "With Key (ALREADY)");
373             header('Location: ' . $this->baseURL.'?onloadTrack='.$this->onloadTrack);
374             exit;
375             return false;
376         }
377         
378         // authenticate the user...
379         // slightly risky...
380         $u = DB_DataObject::factory('Person');
381          
382         $u->get($tr->person_id);
383         $u->login();
384         $this->AddEvent("LOGIN", false, "With Key");
385         
386         // we need to redirect out - otherwise refererer url will include key!
387         header('Location: ' . $this->baseURL.'?onloadTrack='.$this->onloadTrack);
388         exit;
389         
390         return false;
391         
392         
393         
394         
395     }
396     
397     
398     /**
399      * ------------- Authentication password reset ------ ??? MOVEME?
400      * 
401      * 
402      */
403     
404     
405     function resetPassword($id,$t, $key)
406     {
407         
408         $au = $this->getAuthUser();
409         if ($au) {
410             return "Already Logged in - no need to use Password Reset";
411         }
412         
413         $u = DB_DataObject::factory('Person');
414         //$u->company_id = $this->company->id;
415         $u->active = 1;
416         if (!$u->get($id) || !strlen($u->passwd)) {
417             return "invalid id";
418         }
419         
420         // validate key.. 
421         if ($key != $u->genPassKey($t)) {
422             return "invalid key";
423         }
424         $uu = clone($u);
425         $u->no_reset_sent = 0;
426         $u->update($uu);
427         
428         if ($t < strtotime("NOW - 1 DAY")) {
429             return "expired";
430         }
431         $this->showNewPass = implode("/", array($id,$t,$key));
432         return false;
433     }
434     
435     /**
436      * jerrAuth: standard auth failure - with data that let's the UI know..
437      */
438     function jerrAuth()
439     {
440         $au = $this->authUser();
441         if ($au) {
442             // is it an authfailure?
443             $this->jerr("Permission denied to view this resource", array('authFailure' => true));
444         }
445         $this->jerr("Not authenticated", array('authFailure' => true));
446     }
447      
448      
449      
450     /**
451      * ---------------- Standard JSON outputers. - used everywhere
452      */
453       /**
454      * ---------------- Standard JSON outputers. - used everywhere
455      * JSON error - simple error with logging.
456      * @see Pman::jerror
457      */
458     
459     function jerr($str, $errors=array(), $content_type = false) // standard error reporting..
460     {
461         return $this->jerror('ERROR', $str,$errors,$content_type);
462     }
463     /**
464      * Recomended JSON error indicator
465      *
466      * 
467      * @param string $type  - normally 'ERROR' - you can use this to track error types.
468      * @param string $message - error message displayed to user.
469      * @param array $errors - optioanl data to pass to front end.
470      * @param string $content_type - use text/plain to return plan text - ?? not sure why...
471      *
472      */
473     
474     function jerror($type, $str, $errors=array(), $content_type = false) // standard error reporting..
475     {
476         if ($type !== false) {
477             $this->addEvent($type, false, $str);
478         }
479          
480         $cli = HTML_FlexyFramework::get()->cli;
481         if ($cli) {
482             echo "ERROR: " .$str . "\n";
483             exit;
484         }
485         
486         
487         if ($content_type == 'text/plain') {
488             header('Content-Disposition: attachment; filename="error.txt"');
489             header('Content-type: '. $content_type);
490             echo "ERROR: " .$str . "\n";
491             exit;
492         } 
493         
494         
495         
496         require_once 'Services/JSON.php';
497         $json = new Services_JSON();
498         
499         // log all errors!!!
500         
501         
502         if (!empty($_REQUEST['returnHTML']) || 
503             (isset($_SERVER['CONTENT_TYPE']) && preg_match('#multipart/form-data#i', $_SERVER['CONTENT_TYPE']))
504         ) {
505             header('Content-type: text/html');
506             echo "<HTML><HEAD></HEAD><BODY>";
507             echo  $json->encodeUnsafe(array(
508                     'success'=> false, 
509                     'errorMsg' => $str,
510                     'message' => $str, // compate with exeption / loadexception.
511
512                     'errors' => $errors ? $errors : true, // used by forms to flag errors.
513                     'authFailure' => !empty($errors['authFailure']),
514                 ));
515             echo "</BODY></HTML>";
516             exit;
517         }
518         
519         if (isset($_REQUEST['_debug'])) {
520             echo '<PRE>'.htmlspecialchars(print_r(array(
521                 'success'=> false, 
522                 'data'=> array(), 
523                 'errorMsg' => $str,
524                 'message' => $str, // compate with exeption / loadexception.
525                 'errors' => $errors ? $errors : true, // used by forms to flag errors.
526                 'authFailure' => !empty($errors['authFailure']),
527             ),true));
528             exit;
529                 
530         }
531         
532         echo $json->encode(array(
533             'success'=> false, 
534             'data'=> array(), 
535             'errorMsg' => $str,
536             'message' => $str, // compate with exeption / loadexception.
537             'errors' => $errors ? $errors : true, // used by forms to flag errors.
538             'authFailure' => !empty($errors['authFailure']),
539         ));
540         
541         
542         exit;
543         
544     }
545     function jok($str)
546     {
547         $cli = HTML_FlexyFramework::get()->cli;
548         if ($cli) {
549             echo "OK: " .$str . "\n";
550             exit;
551         }
552         require_once 'Services/JSON.php';
553         $json = new Services_JSON();
554         
555         if (!empty($_REQUEST['returnHTML']) || 
556             (isset($_SERVER['CONTENT_TYPE']) && preg_match('#multipart/form-data#i', $_SERVER['CONTENT_TYPE']))
557         
558         ) {
559             header('Content-type: text/html');
560             echo "<HTML><HEAD></HEAD><BODY>";
561             // encode html characters so they can be read..
562             echo  str_replace(array('<','>'), array('\u003c','\u003e'),
563                         $json->encodeUnsafe(array('success'=> true, 'data' => $str)));
564             echo "</BODY></HTML>";
565             exit;
566         }
567         
568         
569         echo  $json->encode(array('success'=> true, 'data' => $str));
570         
571         exit;
572         
573     }
574     /**
575      * output data for grids or tree
576      * @ar {Array} ar Array of data
577      * @total {Number|false} total number of records (or false to return count(ar)
578      * @extra {Array} extra key value list of data to pass as extra data.
579      * 
580      */
581     function jdata($ar,$total=false, $extra=array(), $cachekey = false)
582     {
583         // should do mobile checking???
584         if ($total == false) {
585             $total = count($ar);
586         }
587         $extra=  $extra ? $extra : array();
588         require_once 'Services/JSON.php';
589         $json = new Services_JSON();
590         if (isset($_SERVER['CONTENT_TYPE']) && preg_match('#multipart/form-data#i', $_SERVER['CONTENT_TYPE'])) {
591             
592             header('Content-type: text/html');
593             echo "<HTML><HEAD></HEAD><BODY>";
594             // encode html characters so they can be read..
595             echo  str_replace(array('<','>'), array('\u003c','\u003e'),
596                         $json->encodeUnsafe(array('success' =>  true, 'total'=> $total, 'data' => $ar) + $extra));
597             echo "</BODY></HTML>";
598             exit;
599         }
600         
601         
602         // see if trimming will help...
603         if (!empty($_REQUEST['_pman_short'])) {
604             $nar = array();
605             
606             foreach($ar as $as) {
607                 $add = array();
608                 foreach($as as $k=>$v) {
609                     if (is_string($v) && !strlen(trim($v))) {
610                         continue;
611                     }
612                     $add[$k] = $v;
613                 }
614                 $nar[] = $add;
615             }
616             $ar = $nar;
617               
618         }
619         
620       
621         $ret =  $json->encode(array('success' =>  true, 'total'=> $total, 'data' => $ar) + $extra);  
622         
623         if (!empty($cachekey)) {
624             
625             $fn = ini_get('session.save_path') . '/json-cache'.date('/Y/m/d').'.'. $cachekey . '.cache.json';
626             if (!file_exists(dirname($fn))) {
627                 mkdir(dirname($fn), 0777,true);
628             }
629             file_put_contents($fn, $ret);
630         }
631         echo $ret;
632         exit;
633     }
634     
635     
636     
637     /** a daily cache **/
638     function jdataCache($cachekey)
639     {
640         $fn = ini_get('session.save_path') . '/json-cache'.date('/Y/m/d').'.'. $cachekey . '.cache.json';
641         if (file_exists($fn)) {
642             header('Content-type: application/json');
643             echo file_get_contents($fn);
644             exit;
645         }
646         return false;
647         
648     }
649     
650    
651     
652     /**
653      * ---------------- OUTPUT
654      */
655     function hasBg($fn) // used on front page to check if logos exist..
656     {
657         return file_exists($this->rootDir.'/Pman/'.$this->appNameShort.'/templates/images/'.  $fn);
658     }
659      /**
660      * outputJavascriptIncludes:
661      *
662      * output <script....> for all the modules in the applcaiton
663      *
664      */
665     function outputJavascriptIncludes()  
666     {
667         
668         $mods = $this->modulesList();
669         
670         foreach($mods as $mod) {
671             // add the css file..
672         
673             $this->outputJavascriptDir("Pman/$mod/widget", "*.js");
674             $this->outputJavascriptDir("Pman/$mod", "*.js");
675             
676         }
677         
678         if (empty($this->disable_jstemplate)) {
679         // and finally the JsTemplate...
680             echo '<script type="text/javascript" src="'. $this->baseURL. '/Core/JsTemplate"></script>'."\n";
681         }
682          
683     }
684     // used on old versions.....
685     function outputJavascriptIncludesBC()  
686     {
687         
688         $mods = $this->modulesList();
689         
690         foreach($mods as $mod) {
691             // add the css file..
692         
693              
694             $files = $this->moduleJavascriptList($mod.'/widgets');
695             foreach($files as $f) {
696                 echo '<script type="text/javascript" src="'. $f. '"></script>'."\n";
697             }
698             
699             $files = $this->moduleJavascriptList($mod);
700             foreach($files as $f) {
701                 echo '<script type="text/javascript" src="'. $f. '"></script>'."\n";
702             }
703             
704         }
705         if (empty($this->disable_jstemplate)) {
706         // and finally the JsTemplate...
707             echo '<script type="text/javascript" src="'. $this->baseURL. '/Core/JsTemplate"></script>'."\n";
708         }
709          
710     }
711      /**
712      * outputCSSIncludes:
713      *
714      * output <link rel=stylesheet......> for all the modules in the applcaiton
715      *
716      *
717      * This could css minify as well.
718      */
719     function outputCSSIncludes() // includes on CSS links.
720     {
721         
722         $mods = $this->modulesList();
723         
724         
725         foreach($mods as $mod) {
726             // add the css file..
727             $dir = $this->rootDir.'/Pman/'.$mod;
728             $ar = glob($dir . '/*.css');
729             foreach($ar as $fn) { 
730                 $css = $this->rootURL .'/Pman/'.$mod.'/'.basename($fn) . '?ts=' . filemtime($fn);
731                 echo '<link rel="stylesheet" type="text/css" href="'.$css.'" />'."\n";
732             }
733              
734             
735         }
736          
737     }
738     
739     
740     // --- OLD CODE - in for BC on MO project.... - needs removing...
741     
742     
743     /**
744      * Gather infor for javascript files..
745      *
746      * @param {String} $mod the module to get info about.
747      * @return {StdClass}  details about module.
748      */
749     function moduleJavascriptFilesInfo($mod)
750     {
751         
752         static $cache = array();
753         
754         if (isset($cache[$mod])) {
755             return $cache[$mod];
756         }
757         
758         
759         $ff = HTML_FlexyFramework::get();
760         
761         $base = dirname($_SERVER['SCRIPT_FILENAME']);
762         $dir =   $this->rootDir.'/Pman/'. $mod;
763         $path = $this->rootURL ."/Pman/$mod/";
764         
765         $ar = glob($dir . '/*.js');
766         
767         $files = array();
768         $arfiles = array();
769         $maxtime = 0;
770         $mtime = 0;
771         foreach($ar as $fn) {
772             $f = basename($fn);
773             // got the 'module file..'
774             $mtime = filemtime($dir . '/'. $f);
775             $maxtime = max($mtime, $maxtime);
776             $arfiles[$fn] = $mtime;
777             $files[] = $path . $f . '?ts='.$mtime;
778         }
779         
780         ksort($arfiles); // just sort by name so it's consistant for serialize..
781         
782         $compile  = empty($ff->Pman['public_cache_dir']) ? 0 : 1;
783         $basedir = $compile ? $ff->Pman['public_cache_dir'] : false;
784         $baseurl = $compile ? $ff->Pman['public_cache_url'] : false;
785         
786         $lsort = create_function('$a,$b','return strlen($a) > strlen($b) ? 1 : -1;');
787         usort($files, $lsort);
788         
789         $smod = str_replace('/','.',$mod);
790         
791         $output = date('Y-m-d-H-i-s-', $maxtime). $smod .'-'.md5(serialize($arfiles)) .'.js';
792         
793         
794         // why are translations done like this - we just build them on the fly frmo the database..
795         $tmtime = file_exists($this->rootDir.'/_translations_/'. $smod.'.js')
796             ? filemtime($this->rootDir.'/_translations_/'. $smod.'.js') : 0;
797         
798         $cache[$mod]  = (object) array(
799             'smod' =>               $smod, // module name without '/'
800             'files' =>              $files, // list of all files.
801             'filesmtime' =>         $arfiles,  // map of mtime=>file
802             'maxtime' =>            $maxtime, // max mtime
803             'compile' =>            $this->isDev ? false : $compile,
804             'translation_file' =>   $base .'/_translations_/' . $smod .  '.js',
805             'translation_mtime' =>  $tmtime,
806             'output' =>             $output,
807             'translation_data' =>   preg_replace('/\.js$/', '.__translation__.js', $output),
808             'translation_base' =>   $dir .'/', //prefix of filename (without moudle name))
809             'basedir' =>            $basedir,   
810             'baseurl' =>            $baseurl,
811             'module_dir' =>         $dir,  
812         );
813         return $cache[$mod];
814     }
815      
816     
817     /**
818      *  moduleJavascriptList: list the javascript files in a module
819      *
820      *  The original version of this.. still needs more thought...
821      *
822      *  Compiled is in Pman/_compiled_/{$mod}/{LATEST...}.js
823      *  Translations are in Pman/_translations_/{$mod}.js
824      *  
825      *  if that stuff does not exist just list files in  Pman/{$mod}/*.js
826      *
827      *  Compiled could be done on the fly..
828      * 
829      *
830      *
831      *  @param {String} $mod  the module to look at - eg. Pman/{$mod}/*.js
832      *  @return {Array} list of include paths (either compiled or raw)
833      *
834      */
835
836     
837     
838     function moduleJavascriptList($mod)
839     {
840         
841         
842         $dir =   $this->rootDir.'/Pman/'. $mod;
843         
844         
845         if (!file_exists($dir)) {
846             echo '<!-- missing directory '. htmlspecialchars($dir) .' -->';
847             return array();
848         }
849         
850         $info = $this->moduleJavascriptFilesInfo($mod);
851        
852         
853           
854         if (empty($info->files)) {
855             return array();
856         }
857         // finally sort the files, so they are in the right order..
858         
859         // only compile this stuff if public_cache is set..
860         
861          
862         // suggestions...
863         //  public_cache_dir =   /var/www/myproject_cache
864         //  public_cache_url =   /myproject_cache    (with Alias apache /myproject_cache/ /var/www/myproject_cache/)
865         
866         // bit of debugging
867         if (!$info->compile) {
868             echo "<!-- Javascript compile turned off (isDev on, or public_cache_dir not set) -->\n";
869             return $info->files;
870         }
871         
872         // where are we going to write all of this..
873         // This has to be done via a 
874         if (!file_exists($info->basedir.'/'.$info->output) || !filesize($info->basedir.'/'.$info->output)) {
875             require_once 'Pman/Core/JsCompile.php';
876             $x = new Pman_Core_JsCompile();
877             
878             $x->pack($info->filesmtime,$info->basedir.'/'.$info->output, $info->translation_base);
879         } else {
880             echo "<!-- file exists not exist: {$info->basedir}/{$info->output} -->\n";
881         }
882         
883         if (file_exists($info->basedir.'/'.$info->output) &&
884                 filesize($info->basedir.'/'.$info->output)) {
885             
886             $ret =array(
887                 $info->baseurl.'/'. $info->output,
888               
889             );
890             // output all the ava
891             // fixme  - this needs the max datetime for the translation file..
892             $ret[] = $this->baseURL."/Admin/InterfaceTranslations/".$mod.".js"; //?ts=".$info->translation_mtime;
893             
894             //if ($info->translation_mtime) {
895             //    $ret[] = $this->rootURL."/_translations_/". $info->smod.".js?ts=".$info->translation_mtime;
896             //}
897             return $ret;
898         }
899         
900         
901         
902         // give up and output original files...
903         
904          
905         return $info->files;
906
907         
908     }
909     
910     /**
911      * Error handling...
912      *  PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array($this, 'onPearError'));
913      */
914     
915     static $permitError = false;
916     
917     function onPearError($err)
918     {
919         static $reported = false;
920         if ($reported) {
921             return;
922         }
923         
924         if (Pman::$permitError) {
925              
926             return;
927             
928         }
929         
930         
931         $reported = true;
932         $out = $err->toString();
933         
934         
935         //print_R($bt); exit;
936         $ret = array();
937         $n = 0;
938         foreach($err->backtrace as $b) {
939             $ret[] = @$b['file'] . '(' . @$b['line'] . ')@' .   @$b['class'] . '::' . @$b['function'];
940             if ($n > 20) {
941                 break;
942             }
943             $n++;
944         }
945         //convert the huge backtrace into something that is readable..
946         $out .= "\n" . implode("\n",  $ret);
947      
948         print_R($out);exit;
949         
950         $this->jerr($out);
951         
952         
953         
954     }
955     
956     
957     /**
958      * ---------------- Logging ---------------   
959      */
960     
961     /**
962      * addEventOnce:
963      * Log an action (only if it has not been logged already.
964      * 
965      * @param {String} action  - group/name of event
966      * @param {DataObject|false} obj - dataobject action occured on.
967      * @param {String} any remarks
968      * @return {false|DB_DataObject} Event object.,
969      */
970     
971     function addEventOnce($act, $obj = false, $remarks = '') 
972     {
973         if (!empty(HTML_FlexyFramework::get()->Pman['disable_events'])) {
974             return;
975         }
976         $e = DB_DataObject::factory('Events');
977         $e->init($act,$obj,$remarks); 
978         if ($e->find(true)) {
979             return false;
980         }
981         return $this->addEvent($act, $obj, $remarks);
982     }
983     /**
984      * addEvent:
985      * Log an action.
986      * 
987      * @param {String} action  - group/name of event
988      * @param {DataObject|false} obj - dataobject action occured on.
989      * @param {String} any remarks
990      * @return {DB_DataObject} Event object.,
991      */
992     
993     function addEvent($act, $obj = false, $remarks = '') 
994     {
995         
996         if (!empty(HTML_FlexyFramework::get()->Pman['disable_events'])) {
997             return;
998         }
999         $au = $this->getAuthUser();
1000        
1001         $e = DB_DataObject::factory('Events');
1002         $e->init($act,$obj,$remarks); 
1003          
1004         $e->event_when = date('Y-m-d H:i:s');
1005         
1006         $eid = $e->insert();
1007         
1008         // fixme - this should be in onInsert..
1009         $wa = DB_DataObject::factory('core_watch');
1010         if (method_exists($wa,'notifyEvent')) {
1011             $wa->notifyEvent($e); // trigger any actions..
1012         }
1013         
1014         
1015         $e->onInsert(isset($_REQUEST) ? $_REQUEST : array() , $this);
1016         
1017        
1018         return $e;
1019         
1020     }
1021     // ------------------ DEPERCIATED ----------------------------
1022      
1023     // DEPRECITAED - use moduleslist
1024     function modules()  { return $this->modulesList();  }
1025     
1026     // DEPRECIATED.. - use getAuthUser...
1027     function staticGetAuthUser()  { $x = new Pman(); return $x->getAuthUser();  }
1028      
1029     
1030     // DEPRICATED  USE Pman_Core_Mailer
1031     
1032     function emailTemplate($templateFile, $args)
1033     {
1034     
1035         require_once 'Pman/Core/Mailer.php';
1036         $r = new Pman_Core_Mailer(array(
1037             'template'=>$templateFile,
1038             'contents' => $args,
1039             'page' => $this
1040         ));
1041         return $r->toData();
1042          
1043     }
1044     // DEPRICATED - USE Pman_Core_Mailer 
1045     // WHAT Part about DEPRICATED Does no one understand??
1046     function sendTemplate($templateFile, $args)
1047     {
1048         require_once 'Pman/Core/Mailer.php';
1049         $r = new Pman_Core_Mailer(array(
1050             'template'=>$templateFile,
1051             'contents' => array(),
1052             'page' => $this
1053         ));
1054         return $r->send();
1055         
1056     
1057     }
1058 }