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