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         $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 && !empty($_REQUEST['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         if (!empty($this->authUser)) {
242             return $this->authUser;
243         }
244         $ff = HTML_FlexyFramework::get();
245         $tbl = empty($ff->Pman['authTable']) ? 'core_person' : $ff->Pman['authTable'];
246         
247         $u = DB_DataObject::factory( $tbl );
248         
249         if (is_a($u,'PEAR_Error') || !$u->isAuth()) {
250             return false;
251         }
252         $this->authUser =$u->getAuthUser();
253         return $this->authUser ;
254     }
255     /**
256      * hasPerm:
257      * wrapper arround authuser->hasPerm
258      * @see Pman_Core_DataObject_Core_person::hasPerm
259      *
260      * @param {String} $name  The permission name (eg. Projects.List)
261      * @param {String} $lvl   eg. (C)reate (E)dit (D)elete ... etc.
262      * 
263      */
264     function hasPerm($name, $lvl)  // do we have a permission
265     {
266         static $pcache = array();
267         $au = $this->getAuthUser();
268         return $au && $au->hasPerm($name,$lvl);
269         
270     }
271    
272     /**
273      * modulesList:  List the modules in the application
274      *
275      * @return {Array} list of modules
276      */
277     function modulesList()
278     {
279         $boot = HTML_FlexyFramework::get();
280         // echo'<PRE>';print_R($boot);exit;
281          
282          
283         $mods = explode(',', $boot->enable);
284         if (in_array('Core',$mods)) { // core has to be the first  modules loaded as it contains Pman.js
285             array_unshift($mods,   'Core');
286         }
287         
288         if (in_array($boot->appNameShort,$mods)) { // Project has to be the last  modules loaded as it contains Pman.js
289             unset($mods[array_search($boot->appNameShort, $mods)]);
290             $mods[] = $boot->appNameShort;
291         }
292         
293         $mods = array_unique($mods);
294          
295         $disabled =  explode(',', $boot->disable ? $boot->disable : '');
296         $ret = array();
297         foreach($mods as $mod) {
298             // add the css file..
299             if (in_array($mod, $disabled)) {
300                 continue;
301             }
302             $ret[] = $mod;
303         }
304         return $ret;
305     }
306     
307      
308     
309     
310     function hasModule($name) 
311     {
312         $this->init();
313         if (!strpos( $name,'.') ) {
314             // use enable / disable..
315             return in_array($name, $this->modules()); 
316         }
317         
318         $x = DB_DataObject::factory('core_group_right');
319         $ar = $x->defaultPermData();
320         if (empty($ar[$name]) || empty($ar[$name][0])) {
321             return false;
322         }
323         return true;
324     }
325     
326      
327     
328     
329
330     
331     
332     
333         
334     /**
335      * ---------------- Global Tools ---------------   
336      */
337     function checkFileUploadError()  // check for file upload errors.
338     {    
339         if (
340             empty($_FILES['File']) 
341             || empty($_FILES['File']['name']) 
342             || empty($_FILES['File']['tmp_name']) 
343             || empty($_FILES['File']['type']) 
344             || !empty($_FILES['File']['error']) 
345             || empty($_FILES['File']['size']) 
346         ) {
347             $this->jerr("File upload error: <PRE>" . print_r($_FILES,true) . print_r($_POST,true) . "</PRE>");
348         }
349     }
350     
351     
352     /**
353      * generate a tempory file with an extension (dont forget to delete it)
354      */
355     
356     function tempName($ext)
357     {
358         $x = tempnam(ini_get('session.save_path'), HTML_FlexyFramework::get()->appNameShort.'TMP');
359         unlink($x);
360         return $x .'.'. $ext;
361     }
362    
363     
364     /**
365      * ------------- Authentication password reset ------ ??? MOVEME?
366      * 
367      * 
368      */
369     
370     
371     function resetPassword($id,$t, $key)
372     {
373         
374         $au = $this->getAuthUser();
375         if ($au) {
376             return "Already Logged in - no need to use Password Reset";
377         }
378         
379         $u = DB_DataObject::factory('core_person');
380         //$u->company_id = $this->company->id;
381         $u->active = 1;
382         if (!$u->get($id) || !strlen($u->passwd)) {
383             return "invalid id";
384         }
385         
386         // validate key.. 
387         if ($key != $u->genPassKey($t)) {
388             return "invalid key";
389         }
390         $uu = clone($u);
391         $u->no_reset_sent = 0;
392         $u->update($uu);
393         
394         if ($t < strtotime("NOW - 1 DAY")) {
395             return "expired";
396         }
397         $this->showNewPass = implode("/", array($id,$t,$key));
398         return false;
399     }
400     
401     /**
402      * jerrAuth: standard auth failure - with data that let's the UI know..
403      */
404     function jerrAuth()
405     {
406         $au = $this->authUser();
407         if ($au) {
408             // is it an authfailure?
409             $this->jerr("Permission denied to view this resource", array('authFailure' => true));
410         }
411         $this->jerr("Not authenticated", array('authFailure' => true));
412     }
413      
414      
415      
416     /**
417      * ---------------- Standard JSON outputers. - used everywhere
418      */
419       /**
420      * ---------------- Standard JSON outputers. - used everywhere
421      * JSON error - simple error with logging.
422      * @see Pman::jerror
423      */
424     
425     function jerr($str, $errors=array(), $content_type = false) // standard error reporting..
426     {
427         return $this->jerror('ERROR', $str,$errors,$content_type);
428     }
429     /**
430      * Recomended JSON error indicator
431      *
432      * 
433      * @param string $type  - normally 'ERROR' - you can use this to track error types.
434      * @param string $message - error message displayed to user.
435      * @param array $errors - optioanl data to pass to front end.
436      * @param string $content_type - use text/plain to return plan text - ?? not sure why...
437      *
438      */
439     
440     function jerror($type, $str, $errors=array(), $content_type = false) // standard error reporting..
441     {
442         if ($type !== false) {
443             $this->addEvent($type, false, $str);
444         }
445          
446         $cli = HTML_FlexyFramework::get()->cli;
447         if ($cli) {
448             echo "ERROR: " .$str . "\n";
449             exit(1); // cli --- exit code to stop shell execution if necessary.
450         }
451         
452         
453         if ($content_type == 'text/plain') {
454             header('Content-Disposition: attachment; filename="error.txt"');
455             header('Content-type: '. $content_type);
456             echo "ERROR: " .$str . "\n";
457             exit;
458         } 
459         
460         
461         
462         require_once 'Services/JSON.php';
463         $json = new Services_JSON();
464         
465         // log all errors!!!
466         
467         $retHTML = isset($_SERVER['CONTENT_TYPE']) && 
468                 preg_match('#multipart/form-data#i', $_SERVER['CONTENT_TYPE']);
469         
470         if ($retHTML){
471             if (isset($_REQUEST['returnHTML']) && $_REQUEST['returnHTML'] == 'NO') {
472                 $retHTML = false;
473             }
474         } else {
475             $retHTML = isset($_REQUEST['returnHTML']) && $_REQUEST['returnHTML'] !='NO';
476         }
477         
478         
479         if ($retHTML) {
480             header('Content-type: text/html');
481             echo "<HTML><HEAD></HEAD><BODY>";
482             echo  $json->encodeUnsafe(array(
483                     'success'=> false, 
484                     'errorMsg' => $str,
485                     'message' => $str, // compate with exeption / loadexception.
486
487                     'errors' => $errors ? $errors : true, // used by forms to flag errors.
488                     'authFailure' => !empty($errors['authFailure']),
489                 ));
490             echo "</BODY></HTML>";
491             exit;
492         }
493         
494         if (isset($_REQUEST['_debug'])) {
495             echo '<PRE>'.htmlspecialchars(print_r(array(
496                 'success'=> false, 
497                 'data'=> array(), 
498                 'errorMsg' => $str,
499                 'message' => $str, // compate with exeption / loadexception.
500                 'errors' => $errors ? $errors : true, // used by forms to flag errors.
501                 'authFailure' => !empty($errors['authFailure']),
502             ),true));
503             exit;
504                 
505         }
506         
507         echo $json->encode(array(
508             'success'=> false, 
509             'data'=> array(), 
510             'errorMsg' => $str,
511             'message' => $str, // compate with exeption / loadexception.
512             'errors' => $errors ? $errors : true, // used by forms to flag errors.
513             'authFailure' => !empty($errors['authFailure']),
514         ));
515         
516         
517         exit;
518         
519     }
520     function jok($str)
521     {
522         $cli = HTML_FlexyFramework::get()->cli;
523         if ($cli) {
524             echo "OK: " .$str . "\n";
525             exit;
526         }
527         require_once 'Services/JSON.php';
528         $json = new Services_JSON();
529         
530         $retHTML = isset($_SERVER['CONTENT_TYPE']) && 
531                 preg_match('#multipart/form-data#i', $_SERVER['CONTENT_TYPE']);
532         
533         if ($retHTML){
534             if (isset($_REQUEST['returnHTML']) && $_REQUEST['returnHTML'] == 'NO') {
535                 $retHTML = false;
536             }
537         } else {
538             $retHTML = isset($_REQUEST['returnHTML']) && $_REQUEST['returnHTML'] !='NO';
539         }
540         
541         if ($retHTML) {
542             header('Content-type: text/html');
543             echo "<HTML><HEAD></HEAD><BODY>";
544             // encode html characters so they can be read..
545             echo  str_replace(array('<','>'), array('\u003c','\u003e'),
546                         $json->encodeUnsafe(array('success'=> true, 'data' => $str)));
547             echo "</BODY></HTML>";
548             exit;
549         }
550         
551         
552         echo  $json->encode(array('success'=> true, 'data' => $str));
553         
554         exit;
555         
556     }
557     /**
558      * output data for grids or tree
559      * @ar {Array} ar Array of data
560      * @total {Number|false} total number of records (or false to return count(ar)
561      * @extra {Array} extra key value list of data to pass as extra data.
562      * 
563      */
564     function jdata($ar,$total=false, $extra=array(), $cachekey = false)
565     {
566         // should do mobile checking???
567         if ($total == false) {
568             $total = count($ar);
569         }
570         print_r($ar);
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 }