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() 
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(!empty($_REQUEST['isDev']) && $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        
807         
808         
809         $lsort = create_function('$a,$b','return strlen($a) > strlen($b) ? 1 : -1;');
810         usort($files, $lsort);
811         
812         $smod = str_replace('/','.',$mod);
813         
814         $output = date('Y-m-d-H-i-s-', $maxtime). $smod .'-'.md5(serialize($arfiles)) .'.js';
815         
816         
817         // why are translations done like this - we just build them on the fly frmo the database..
818         $tmtime = file_exists($this->rootDir.'/_translations_/'. $smod.'.js')
819             ? filemtime($this->rootDir.'/_translations_/'. $smod.'.js') : 0;
820         
821         $cache[$mod]  = (object) array(
822             'smod' =>               $smod, // module name without '/'
823             'files' =>              $files, // list of all files.
824             'filesmtime' =>         $arfiles,  // map of mtime=>file
825             'maxtime' =>            $maxtime, // max mtime
826             'compile' =>            $this->isDev ? false : $compile,
827             'translation_file' =>   $base .'/_translations_/' . $smod .  '.js',
828             'translation_mtime' =>  $tmtime,
829             'output' =>             $output,
830             'translation_data' =>   preg_replace('/\.js$/', '.__translation__.js', $output),
831             'translation_base' =>   $dir .'/', //prefix of filename (without moudle name))
832             'basedir' =>            $basedir,   
833             'baseurl' =>            $baseurl,
834             'module_dir' =>         $dir,  
835         );
836         return $cache[$mod];
837     }
838      
839     
840     /**
841      *  moduleJavascriptList: list the javascript files in a module
842      *
843      *  The original version of this.. still needs more thought...
844      *
845      *  Compiled is in Pman/_compiled_/{$mod}/{LATEST...}.js
846      *  Translations are in Pman/_translations_/{$mod}.js
847      *  
848      *  if that stuff does not exist just list files in  Pman/{$mod}/*.js
849      *
850      *  Compiled could be done on the fly..
851      * 
852      *
853      *
854      *  @param {String} $mod  the module to look at - eg. Pman/{$mod}/*.js
855      *  @return {Array} list of include paths (either compiled or raw)
856      *
857      */
858
859     
860     
861     function moduleJavascriptList($mod)
862     {
863         
864         
865         $dir =   $this->rootDir.'/Pman/'. $mod;
866         
867         
868         if (!file_exists($dir)) {
869             echo '<!-- missing directory '. htmlspecialchars($dir) .' -->';
870             return array();
871         }
872         
873         $info = $this->moduleJavascriptFilesInfo($mod);
874        
875         
876           
877         if (empty($info->files)) {
878             return array();
879         }
880         // finally sort the files, so they are in the right order..
881         
882         // only compile this stuff if public_cache is set..
883         
884          
885         // suggestions...
886         //  public_cache_dir =   /var/www/myproject_cache
887         //  public_cache_url =   /myproject_cache    (with Alias apache /myproject_cache/ /var/www/myproject_cache/)
888         
889         // bit of debugging
890         if (!$info->compile) {
891             echo "<!-- Javascript compile turned off (isDev on, or public_cache_dir not set) -->\n";
892             return $info->files;
893         }
894         
895         // where are we going to write all of this..
896         // This has to be done via a 
897         if (!file_exists($info->basedir.'/'.$info->output) || !filesize($info->basedir.'/'.$info->output)) {
898             require_once 'Pman/Core/JsCompile.php';
899             $x = new Pman_Core_JsCompile();
900             
901             $x->pack($info->filesmtime,$info->basedir.'/'.$info->output, $info->translation_base);
902         } else {
903             echo "<!-- file exists not exist: {$info->basedir}/{$info->output} -->\n";
904         }
905         
906         if (file_exists($info->basedir.'/'.$info->output) &&
907                 filesize($info->basedir.'/'.$info->output)) {
908             
909             $ret =array(
910                 $info->baseurl.'/'. $info->output,
911               
912             );
913             // output all the ava
914             // fixme  - this needs the max datetime for the translation file..
915             $ret[] = $this->baseURL."/Admin/InterfaceTranslations/".$mod.".js"; //?ts=".$info->translation_mtime;
916             
917             //if ($info->translation_mtime) {
918             //    $ret[] = $this->rootURL."/_translations_/". $info->smod.".js?ts=".$info->translation_mtime;
919             //}
920             return $ret;
921         }
922         
923         
924         
925         // give up and output original files...
926         
927          
928         return $info->files;
929
930         
931     }
932     
933     /**
934      * Error handling...
935      *  PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array($this, 'onPearError'));
936      */
937     function initErrorHandling()
938     {
939         if (!class_exists('HTML_FlexyFramework2')) {
940             // what about older code that still users PEAR?
941             PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array($this, 'onPearError'));
942         }
943         set_exception_handler(array($this,'onException'));
944         
945     }
946     
947     
948     static $permitError = false; // static why?
949     
950     var $showErrorToUser = true;
951     
952     function onPearError($err)
953     {
954         return $this->onException($err);
955         
956     }
957     
958     
959     function onException($ex)
960     {
961         
962         static $reported = false;
963         if ($reported) {
964             return;
965         }
966         
967         if (Pman::$permitError) {
968             return;
969         }
970         
971         
972         $reported = true;
973         $out = is_a($ex,'Exception') ? $ex->getMessage() : $ex->toString();
974         
975         
976         //print_R($bt); exit;
977         $ret = array();
978         $n = 0;
979         $bt = is_a($ex,'Exception') ? $ex->getTrace() : $ex->backtrace;
980         foreach( $bt as $b) {
981             $ret[] = @$b['file'] . '(' . @$b['line'] . ')@' .   @$b['class'] . '::' . @$b['function'];
982             if ($n > 20) {
983                 break;
984             }
985             $n++;
986         }
987         //convert the huge backtrace into something that is readable..
988         $out .= "\n" . implode("\n",  $ret);
989         
990         $this->addEvent("EXCEPTION", false, $out);
991         
992         if ($this->showErrorToUser) {
993             print_R($out);exit;
994         }
995         // not sure why this is here... - perhaps doing a jerr() was actually caught by the UI, and hidden from the user..?
996         $this->jerror(false,"An error Occured, please contact the website owner");
997         
998         //$this->jerr($out);
999         
1000         
1001     }
1002     
1003     
1004     /**
1005      * ---------------- Logging ---------------   
1006      */
1007     
1008     /**
1009      * addEventOnce:
1010      * Log an action (only if it has not been logged already.
1011      * 
1012      * @param {String} action  - group/name of event
1013      * @param {DataObject|false} obj - dataobject action occured on.
1014      * @param {String} any remarks
1015      * @return {false|DB_DataObject} Event object.,
1016      */
1017     
1018     function addEventOnce($act, $obj = false, $remarks = '') 
1019     {
1020         if (!empty(HTML_FlexyFramework::get()->Pman['disable_events'])) {
1021             return;
1022         }
1023         $e = DB_DataObject::factory('Events');
1024         $e->init($act,$obj,$remarks); 
1025         if ($e->find(true)) {
1026             return false;
1027         }
1028         return $this->addEvent($act, $obj, $remarks);
1029     }
1030     /**
1031      * addEvent:
1032      * Log an action.
1033      * 
1034      * @param {String} action  - group/name of event
1035      * @param {DataObject|false} obj - dataobject action occured on.
1036      * @param {String} any remarks
1037      * @return {DB_DataObject} Event object.,
1038      */
1039     
1040     function addEvent($act, $obj = false, $remarks = '') 
1041     {
1042         
1043         if (!empty(HTML_FlexyFramework::get()->Pman['disable_events'])) {
1044             return;
1045         }
1046         $au = $this->getAuthUser();
1047        
1048         $e = DB_DataObject::factory('Events');
1049         $e->init($act,$obj,$remarks); 
1050          
1051         $e->event_when = $e->sqlValue('NOW()');
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 = $e->sqlValue('NOW()');
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 }