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