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