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