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