a86cd68b174847037e2951f2867dde3fd200f51d
[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     
79     function init() 
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         $this->init();
144         if (empty($base)) {
145             $this->initModules();
146         }
147         
148             //$this->allowSignup= empty($opts['allowSignup']) ? 0 : 1;
149         $bits = explode('/', $base);
150       
151         
152         // should really be moved to Login...
153         
154         if ($bits[0] == 'PasswordReset') {
155             $this->linkFail = $this->resetPassword(@$bits[1],@$bits[2],@$bits[3]);
156             header('Content-type: text/html; charset=utf-8');
157             return;
158         } 
159          
160         $au = $this->getAuthUser();
161         if ($au) {
162             $ff= HTML_FlexyFramework::get();
163            
164             if (!empty($ff->Pman['auth_comptype']) && $au->id > 0 &&
165                 ( !$au->company_id || ($ff->Pman['auth_comptype'] != $au->company()->comptype))) {
166          
167                 $au->logout();
168                 
169                 $this->jerr("Login not permited to outside companies - please reload");
170             }
171             $this->addEvent("RELOAD");
172         }
173         
174         
175         if (strlen($base)) {
176             $this->jerror("BADURL","invalid url: $base");
177         }
178         // deliver template
179         if (isset($_GET['onloadTrack'])) {
180             $this->onloadTrack = (int)$_GET['onloadTrack'];
181         }
182         // getting this to work with xhtml is a nightmare
183         // = nbsp / <img> issues screw everyting up.
184          //var_dump($this->isDev);
185         // force regeneration on load for development enviroments..
186         
187         HTML_FlexyFramework::get()->generateDataobjectsCache($this->isDev);
188         
189         //header('Content-type: application/xhtml+xml; charset=utf-8');
190         
191         
192         
193         if ($this->company && $this->company->logo_id) {
194             $im = DB_DataObject::Factory('Images');
195             $im->get($this->company->logo_id);
196             $this->appLogo = $this->baseURL . '/Images/Thumb/x100/'. $this->company->logo_id .'/' . $im->filename;
197         }
198         
199         header('Content-type: text/html; charset=utf-8');
200          
201     }
202     function post($base) {
203         return $this->get($base);
204     }
205     
206     
207     // --------------- AUTHENTICATION or  system information
208     /**
209      * loadOwnerCompany:
210      * finds the compay with comptype=='OWNER'
211      * ?? what about comptype_id-name ?????
212      *
213      * @return {Pman_Core_DataObjects_Companies} the owner company
214      */
215     function loadOwnerCompany()
216     {
217         // only applies if authtable is person..
218         $ff = HTML_FlexyFramework::get();
219         if (!empty($ff->Pman['authTable']) && !in_array($ff->Pman['authTable'] , [ 'core_person', 'Person' ])) {
220             return false;
221         }
222         
223         $this->company = DB_DataObject::Factory('core_company');
224         if (!is_a($this->company, 'DB_DataObject')) { // non-core pman projects
225             return false; 
226         }
227         $this->company->get('comptype', 'OWNER');
228         return $this->company;
229     }
230     
231     
232     
233     /**
234      * getAuthUser: - get the authenticated user..
235      *
236      * @return {DB_DataObject} of type Pman[authTable] if authenticated.
237      */
238     
239     function getAuthUser()
240     {
241         print_R('run????');exit;
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         $lsort = create_function('$a,$b','return strlen($a) > strlen($b) ? 1 : -1;');
809         usort($files, $lsort);
810         
811         $smod = str_replace('/','.',$mod);
812         
813         $output = date('Y-m-d-H-i-s-', $maxtime). $smod .'-'.md5(serialize($arfiles)) .'.js';
814         
815         
816         // why are translations done like this - we just build them on the fly frmo the database..
817         $tmtime = file_exists($this->rootDir.'/_translations_/'. $smod.'.js')
818             ? filemtime($this->rootDir.'/_translations_/'. $smod.'.js') : 0;
819         
820         $cache[$mod]  = (object) array(
821             'smod' =>               $smod, // module name without '/'
822             'files' =>              $files, // list of all files.
823             'filesmtime' =>         $arfiles,  // map of mtime=>file
824             'maxtime' =>            $maxtime, // max mtime
825             'compile' =>            $this->isDev ? false : $compile,
826             'translation_file' =>   $base .'/_translations_/' . $smod .  '.js',
827             'translation_mtime' =>  $tmtime,
828             'output' =>             $output,
829             'translation_data' =>   preg_replace('/\.js$/', '.__translation__.js', $output),
830             'translation_base' =>   $dir .'/', //prefix of filename (without moudle name))
831             'basedir' =>            $basedir,   
832             'baseurl' =>            $baseurl,
833             'module_dir' =>         $dir,  
834         );
835         return $cache[$mod];
836     }
837      
838     
839     /**
840      *  moduleJavascriptList: list the javascript files in a module
841      *
842      *  The original version of this.. still needs more thought...
843      *
844      *  Compiled is in Pman/_compiled_/{$mod}/{LATEST...}.js
845      *  Translations are in Pman/_translations_/{$mod}.js
846      *  
847      *  if that stuff does not exist just list files in  Pman/{$mod}/*.js
848      *
849      *  Compiled could be done on the fly..
850      * 
851      *
852      *
853      *  @param {String} $mod  the module to look at - eg. Pman/{$mod}/*.js
854      *  @return {Array} list of include paths (either compiled or raw)
855      *
856      */
857
858     
859     
860     function moduleJavascriptList($mod)
861     {
862         
863         
864         $dir =   $this->rootDir.'/Pman/'. $mod;
865         
866         
867         if (!file_exists($dir)) {
868             echo '<!-- missing directory '. htmlspecialchars($dir) .' -->';
869             return array();
870         }
871         
872         $info = $this->moduleJavascriptFilesInfo($mod);
873        
874         
875           
876         if (empty($info->files)) {
877             return array();
878         }
879         // finally sort the files, so they are in the right order..
880         
881         // only compile this stuff if public_cache is set..
882         
883          
884         // suggestions...
885         //  public_cache_dir =   /var/www/myproject_cache
886         //  public_cache_url =   /myproject_cache    (with Alias apache /myproject_cache/ /var/www/myproject_cache/)
887         
888         // bit of debugging
889         if (!$info->compile) {
890             echo "<!-- Javascript compile turned off (isDev on, or public_cache_dir not set) -->\n";
891             return $info->files;
892         }
893         
894         // where are we going to write all of this..
895         // This has to be done via a 
896         if (!file_exists($info->basedir.'/'.$info->output) || !filesize($info->basedir.'/'.$info->output)) {
897             require_once 'Pman/Core/JsCompile.php';
898             $x = new Pman_Core_JsCompile();
899             
900             $x->pack($info->filesmtime,$info->basedir.'/'.$info->output, $info->translation_base);
901         } else {
902             echo "<!-- file exists not exist: {$info->basedir}/{$info->output} -->\n";
903         }
904         
905         if (file_exists($info->basedir.'/'.$info->output) &&
906                 filesize($info->basedir.'/'.$info->output)) {
907             
908             $ret =array(
909                 $info->baseurl.'/'. $info->output,
910               
911             );
912             // output all the ava
913             // fixme  - this needs the max datetime for the translation file..
914             $ret[] = $this->baseURL."/Admin/InterfaceTranslations/".$mod.".js"; //?ts=".$info->translation_mtime;
915             
916             //if ($info->translation_mtime) {
917             //    $ret[] = $this->rootURL."/_translations_/". $info->smod.".js?ts=".$info->translation_mtime;
918             //}
919             return $ret;
920         }
921         
922         
923         
924         // give up and output original files...
925         
926          
927         return $info->files;
928
929         
930     }
931     
932     /**
933      * Error handling...
934      *  PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array($this, 'onPearError'));
935      */
936     function initErrorHandling()
937     {
938         if (!class_exists('HTML_FlexyFramework2')) {
939             // what about older code that still users PEAR?
940             PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array($this, 'onPearError'));
941         }
942         set_exception_handler(array($this,'onException'));
943         
944     }
945     
946     
947     static $permitError = false; // static why?
948     
949     var $showErrorToUser = true;
950     
951     function onPearError($err)
952     {
953         return $this->onException($err);
954         
955     }
956     
957     
958     function onException($ex)
959     {
960         
961         static $reported = false;
962         if ($reported) {
963             return;
964         }
965         
966         if (Pman::$permitError) {
967             return;
968         }
969         
970         
971         $reported = true;
972         $out = is_a($ex,'Exception') ? $ex->getMessage() : $ex->toString();
973         
974         
975         //print_R($bt); exit;
976         $ret = array();
977         $n = 0;
978         $bt = is_a($ex,'Exception') ? $ex->getTrace() : $ex->backtrace;
979         foreach( $bt as $b) {
980             $ret[] = @$b['file'] . '(' . @$b['line'] . ')@' .   @$b['class'] . '::' . @$b['function'];
981             if ($n > 20) {
982                 break;
983             }
984             $n++;
985         }
986         //convert the huge backtrace into something that is readable..
987         $out .= "\n" . implode("\n",  $ret);
988         
989         $this->addEvent("EXCEPTION", false, $out);
990         
991         if ($this->showErrorToUser) {
992             print_R($out);exit;
993         }
994         // not sure why this is here... - perhaps doing a jerr() was actually caught by the UI, and hidden from the user..?
995         $this->jerror(false,"An error Occured, please contact the website owner");
996         
997         //$this->jerr($out);
998         
999         
1000     }
1001     
1002     
1003     /**
1004      * ---------------- Logging ---------------   
1005      */
1006     
1007     /**
1008      * addEventOnce:
1009      * Log an action (only if it has not been logged already.
1010      * 
1011      * @param {String} action  - group/name of event
1012      * @param {DataObject|false} obj - dataobject action occured on.
1013      * @param {String} any remarks
1014      * @return {false|DB_DataObject} Event object.,
1015      */
1016     
1017     function addEventOnce($act, $obj = false, $remarks = '') 
1018     {
1019         if (!empty(HTML_FlexyFramework::get()->Pman['disable_events'])) {
1020             return;
1021         }
1022         $e = DB_DataObject::factory('Events');
1023         $e->init($act,$obj,$remarks); 
1024         if ($e->find(true)) {
1025             return false;
1026         }
1027         return $this->addEvent($act, $obj, $remarks);
1028     }
1029     /**
1030      * addEvent:
1031      * Log an action.
1032      * 
1033      * @param {String} action  - group/name of event
1034      * @param {DataObject|false} obj - dataobject action occured on.
1035      * @param {String} any remarks
1036      * @return {DB_DataObject} Event object.,
1037      */
1038     
1039     function addEvent($act, $obj = false, $remarks = '') 
1040     {
1041         
1042         if (!empty(HTML_FlexyFramework::get()->Pman['disable_events'])) {
1043             return;
1044         }
1045         
1046         $au = $this->getAuthUser();
1047         print_R($au);exit;
1048         $e = DB_DataObject::factory('Events');
1049         $e->init($act,$obj,$remarks); 
1050          
1051         $e->event_when = date('Y-m-d H:i:s');
1052         
1053         $eid = $e->insert();
1054         
1055         // fixme - this should be in onInsert..
1056         $wa = DB_DataObject::factory('core_watch');
1057         if (method_exists($wa,'notifyEvent')) {
1058             $wa->notifyEvent($e); // trigger any actions..
1059         }
1060         
1061         
1062         $e->onInsert(isset($_REQUEST) ? $_REQUEST : array() , $this);
1063         
1064        
1065         return $e;
1066         
1067     }
1068     
1069     function addEventNotifyOnly($act, $obj = false, $remarks = '')
1070     {
1071          $au = $this->getAuthUser();
1072        
1073         $e = DB_DataObject::factory('Events');
1074         $e->init($act,$obj,$remarks); 
1075          
1076         $e->event_when = date('Y-m-d H:i:s');
1077         $wa = DB_DataObject::factory('core_watch');
1078         if (method_exists($wa,'notifyEvent')) {
1079             $wa->notifyEvent($e); // trigger any actions..
1080         }
1081     }
1082     
1083     
1084     // ------------------ DEPERCIATED ----------------------------
1085      
1086     // DEPRECITAED - use moduleslist
1087     function modules()  { return $this->modulesList();  }
1088     
1089     // DEPRECIATED.. - use getAuthUser...
1090     function staticGetAuthUser()  { $x = new Pman(); return $x->getAuthUser();  }
1091      
1092     
1093     // DEPRICATED  USE Pman_Core_Mailer
1094     
1095     function emailTemplate($templateFile, $args)
1096     {
1097     
1098         require_once 'Pman/Core/Mailer.php';
1099         $r = new Pman_Core_Mailer(array(
1100             'template'=>$templateFile,
1101             'contents' => $args,
1102             'page' => $this
1103         ));
1104         return $r->toData();
1105          
1106     }
1107     // DEPRICATED - USE Pman_Core_Mailer 
1108     // WHAT Part about DEPRICATED Does no one understand??
1109     function sendTemplate($templateFile, $args)
1110     {
1111         require_once 'Pman/Core/Mailer.php';
1112         $r = new Pman_Core_Mailer(array(
1113             'template'=>$templateFile,
1114             'contents' => array(),
1115             'page' => $this
1116         ));
1117         return $r->send();
1118         
1119     
1120     }
1121 }