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