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