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