php8 compat
[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         $o = HTML_FlexyFramework::get()->Pman_Core;
727         if (isset($o['packseed'])) {
728             return $this->outputJavascriptIncludesBC();
729         }
730         
731         
732         $mods = $this->modulesList();
733         
734         $is_bootstrap = in_array('BAdmin', $mods);
735         
736         foreach($mods as $mod) {
737             // add the css file..
738             
739             if ($is_bootstrap) {
740                 if (!file_exists($this->rootDir."/Pman/$mod/is_bootstrap")) {
741                     echo '<!-- missing '. $this->rootDir."/Pman/$mod/is_bootstrap  - skipping -->";
742                     continue;
743                 }
744                 
745             }
746         
747             $this->outputJavascriptDir("Pman/$mod/widgets", "*.js");
748             $this->outputJavascriptDir("Pman/$mod", "*.js");
749             
750         }
751         
752         if (empty($this->disable_jstemplate)) {
753         // and finally the JsTemplate...
754             echo '<script type="text/javascript" src="'. $this->baseURL. '/Core/JsTemplate"></script>'."\n";
755         }
756         
757         $this->callModules('outputJavascriptIncludes', $this);
758          
759     }
760     var $css_includes = array();
761      /**
762      * outputCSSIncludes:
763      *
764      * output <link rel=stylesheet......> for all the modules in the applcaiton
765      *
766      *
767      * This could css minify as well.
768      */
769     function outputCSSIncludes() // includes on CSS links.
770     {
771        
772         
773         $mods = $this->modulesList();
774         $is_bootstrap = in_array('BAdmin', $mods);
775
776         $this->callModules('applyCSSIncludes', $this);
777         foreach($this->css_includes as $module => $ar) {
778             
779             if ($ar) {
780                 $this->assetArrayToHtml( $ar , 'css');
781             }
782         }
783         
784         // old style... - probably remove this...
785         $this->callModules('outputCSSIncludes', $this);
786         
787         foreach($mods as $mod) {
788             // add the css file..
789             if ($is_bootstrap  && !file_exists($this->rootDir."/Pman/$mod/is_bootstrap")) {
790                 echo '<!-- missing '. $this->rootDir."/Pman/$mod/is_bootstrap  - skipping -->";
791                 continue;
792             }
793             $this->outputCSSDir("Pman/$mod","*.css");
794             $this->outputSCSS($mod);
795             
796         }
797         
798         
799     }
800     
801     
802     
803     
804     
805     
806     
807     
808     
809     
810     
811     
812     
813     
814     
815     
816     
817     // --- OLD CODE - in for BC on MO project.... - needs removing...
818     
819     // used on old versions.....
820     function outputJavascriptIncludesBC()  
821     {
822         
823         $mods = $this->modulesList();
824         
825         foreach($mods as $mod) {
826             // add the css file..
827         
828              
829             $files = $this->moduleJavascriptList($mod.'/widgets');
830             foreach($files as $f) {
831                 echo '<script type="text/javascript" src="'. $f. '"></script>'."\n";
832             }
833             
834             $files = $this->moduleJavascriptList($mod);
835             foreach($files as $f) {
836                 echo '<script type="text/javascript" src="'. $f. '"></script>'."\n";
837             }
838             
839         }
840         if (empty($this->disable_jstemplate)) {
841         // and finally the JsTemplate...
842             echo '<script type="text/javascript" src="'. $this->baseURL. '/Core/JsTemplate"></script>'."\n";
843         }
844          
845     }
846     /**
847      * Gather infor for javascript files..
848      *
849      * @param {String} $mod the module to get info about.
850      * @return {StdClass}  details about module.
851      */
852     function moduleJavascriptFilesInfo($mod)
853     {
854         
855         static $cache = array();
856         
857         if (isset($cache[$mod])) {
858             return $cache[$mod];
859         }
860         
861         
862         $ff = HTML_FlexyFramework::get();
863         
864         $base = dirname($_SERVER['SCRIPT_FILENAME']);
865         $dir =   $this->rootDir.'/Pman/'. $mod;
866         $path = $this->rootURL ."/Pman/$mod/";
867         
868         $ar = glob($dir . '/*.js');
869         
870         $files = array();
871         $arfiles = array();
872         $maxtime = 0;
873         $mtime = 0;
874         foreach($ar as $fn) {
875             $f = basename($fn);
876             // got the 'module file..'
877             $mtime = filemtime($dir . '/'. $f);
878             $maxtime = max($mtime, $maxtime);
879             $arfiles[$fn] = $mtime;
880             $files[] = $path . $f . '?ts='.$mtime;
881         }
882         
883         ksort($arfiles); // just sort by name so it's consistant for serialize..
884         
885         // The original idea of this was to serve the files direct from a publicly available 'cache' directory.
886         // but that doesnt really make sense - as we can just serve it from the session directory where we stick
887         // cached data anyway.
888         
889         /*
890         $compile  = empty($ff->Pman['public_cache_dir']) ? 0 : 1;
891         $basedir = $compile ? $ff->Pman['public_cache_dir'] : false;
892         $baseurl = $compile ? $ff->Pman['public_cache_url'] : false;
893         */
894        
895         $compile = 1;
896         $basedir = session_save_path().   '/translate-cache/';
897         if (!file_exists($basedir)) {
898             mkdir($basedir,0755);
899         }
900         $baseurl = $this->baseURL .  '/Admin/Translations';
901         
902         if (PHP_VERSION_ID < 70000 ) {
903             $lsort = create_function('$a,$b','return strlen($a) > strlen($b) ? 1 : -1;');
904             usort($files, $lsort);
905         } else {
906             usort($files, function($a,$b) { return strlen($a) > strlen($b) ? 1 : -1; });
907         }
908         
909         $smod = str_replace('/','.',$mod);
910         
911         $output = date('Y-m-d-H-i-s-', $maxtime). $smod .'-'.md5(serialize($arfiles)) .'.js';
912         
913         
914         // why are translations done like this - we just build them on the fly frmo the database..
915         $tmtime = file_exists($this->rootDir.'/_translations_/'. $smod.'.js')
916             ? filemtime($this->rootDir.'/_translations_/'. $smod.'.js') : 0;
917         
918         $cache[$mod]  = (object) array(
919             'smod' =>               $smod, // module name without '/'
920             'files' =>              $files, // list of all files.
921             'filesmtime' =>         $arfiles,  // map of mtime=>file
922             'maxtime' =>            $maxtime, // max mtime
923             'compile' =>            $this->isDev ? false : $compile,
924             'translation_file' =>   $base .'/_translations_/' . $smod .  '.js',
925             'translation_mtime' =>  $tmtime,
926             'output' =>             $output,
927             'translation_data' =>   preg_replace('/\.js$/', '.__translation__.js', $output),
928             'translation_base' =>   $dir .'/', //prefix of filename (without moudle name))
929             'basedir' =>            $basedir,   
930             'baseurl' =>            $baseurl,
931             'module_dir' =>         $dir,  
932         );
933         return $cache[$mod];
934     }
935      
936     
937     /**
938      *  moduleJavascriptList: list the javascript files in a module
939      *
940      *  The original version of this.. still needs more thought...
941      *
942      *  Compiled is in Pman/_compiled_/{$mod}/{LATEST...}.js
943      *  Translations are in Pman/_translations_/{$mod}.js
944      *  
945      *  if that stuff does not exist just list files in  Pman/{$mod}/*.js
946      *
947      *  Compiled could be done on the fly..
948      * 
949      *
950      *
951      *  @param {String} $mod  the module to look at - eg. Pman/{$mod}/*.js
952      *  @return {Array} list of include paths (either compiled or raw)
953      *
954      */
955
956     
957     
958     function moduleJavascriptList($mod)
959     {
960         
961         
962         $dir =   $this->rootDir.'/Pman/'. $mod;
963         
964         
965         if (!file_exists($dir)) {
966             echo '<!-- missing directory '. htmlspecialchars($dir) .' -->';
967             return array();
968         }
969         
970         $info = $this->moduleJavascriptFilesInfo($mod);
971        
972         
973           
974         if (empty($info->files)) {
975             return array();
976         }
977         // finally sort the files, so they are in the right order..
978         
979         // only compile this stuff if public_cache is set..
980         
981          
982         // suggestions...
983         //  public_cache_dir =   /var/www/myproject_cache
984         //  public_cache_url =   /myproject_cache    (with Alias apache /myproject_cache/ /var/www/myproject_cache/)
985         
986         // bit of debugging
987         if (!$info->compile) {
988             echo "<!-- Javascript compile turned off (isDev on, or public_cache_dir not set) -->\n";
989             return $info->files;
990         }
991         
992         // where are we going to write all of this..
993         // This has to be done via a 
994         if (!file_exists($info->basedir.'/'.$info->output) || !filesize($info->basedir.'/'.$info->output)) {
995             require_once 'Pman/Core/JsCompile.php';
996             $x = new Pman_Core_JsCompile();
997             
998             $x->pack($info->filesmtime,$info->basedir.'/'.$info->output, $info->translation_base);
999         } else {
1000             echo "<!-- file exists not exist: {$info->basedir}/{$info->output} -->\n";
1001         }
1002         
1003         if (file_exists($info->basedir.'/'.$info->output) &&
1004                 filesize($info->basedir.'/'.$info->output)) {
1005             
1006             $ret =array(
1007                 $info->baseurl.'/'. $info->output,
1008               
1009             );
1010             // output all the ava
1011             // fixme  - this needs the max datetime for the translation file..
1012             $ret[] = $this->baseURL."/Admin/InterfaceTranslations/".$mod.".js"; //?ts=".$info->translation_mtime;
1013             
1014             //if ($info->translation_mtime) {
1015             //    $ret[] = $this->rootURL."/_translations_/". $info->smod.".js?ts=".$info->translation_mtime;
1016             //}
1017             return $ret;
1018         }
1019         
1020         
1021         
1022         // give up and output original files...
1023         
1024          
1025         return $info->files;
1026
1027         
1028     }
1029     
1030     /**
1031      * Error handling...
1032      *  PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array($this, 'onPearError'));
1033      */
1034     function initErrorHandling()
1035     {
1036         if (!class_exists('HTML_FlexyFramework2')) {
1037             // what about older code that still users PEAR?
1038             PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array($this, 'onPearError'));
1039         }
1040         set_exception_handler(array($this,'onException'));
1041         
1042     }
1043     
1044     
1045     static $permitError = false; // static why?
1046     
1047     var $showErrorToUser = true;
1048     
1049     function onPearError($err)
1050     {
1051         return $this->onException($err);
1052         
1053     }
1054     
1055     
1056     function onException($ex)
1057     {
1058          static $reported = false;
1059         if ($reported) {
1060             return;
1061         }
1062         
1063         if (Pman::$permitError) {
1064             return;
1065         }
1066         
1067         
1068         $reported = true;
1069         
1070         $out = is_a($ex,'Exception') || is_a($ex, 'Error') ? $ex->getMessage() : $ex->toString();
1071         
1072         
1073         //print_R($bt); exit;
1074         $ret = array();
1075         $n = 0;
1076         $bt = is_a($ex,'Exception')|| is_a($ex, 'Error')  ? $ex->getTrace() : $ex->backtrace;
1077         if (is_a($ex,'Exception')|| is_a($ex, 'Error') ) {
1078             $ret[] = $ex->getFile() . '('. $ex->getLine() . ')';
1079         }
1080         foreach( $bt as $b) {
1081             $ret[] = @$b['file'] . '(' . @$b['line'] . ')@' .   @$b['class'] . '::' . @$b['function'];
1082             if ($n > 20) {
1083                 break;
1084             }
1085             $n++;
1086         }
1087         //convert the huge backtrace into something that is readable..
1088         $out .= "\n" . implode("\n",  $ret);
1089         
1090         $this->addEvent("EXCEPTION", false, $out);
1091         
1092         if ($this->showErrorToUser) {
1093             print_R($out);exit;
1094         }
1095         // not sure why this is here... - perhaps doing a jerr() was actually caught by the UI, and hidden from the user..?
1096         $this->jerror(false,"An error Occured, please contact the website owner");
1097         
1098         //$this->jerr($out);
1099         
1100         
1101     }
1102     
1103     
1104     /**
1105      * ---------------- Logging ---------------   
1106      */
1107     
1108     /**
1109      * addEventOnce:
1110      * Log an action (only if it has not been logged already.
1111      * 
1112      * @param {String} action  - group/name of event
1113      * @param {DataObject|false} obj - dataobject action occured on.
1114      * @param {String} any remarks
1115      * @return {false|DB_DataObject} Event object.,
1116      */
1117     
1118     function addEventOnce($act, $obj = false, $remarks = '') 
1119     {
1120         if (!empty(HTML_FlexyFramework::get()->Pman['disable_events'])) {
1121             return;
1122         }
1123         $e = DB_DataObject::factory('Events');
1124         $e->init($act,$obj,$remarks); 
1125         if ($e->find(true)) {
1126             return false;
1127         }
1128         return $this->addEvent($act, $obj, $remarks);
1129     }
1130     /**
1131      * addEvent:
1132      * Log an action.
1133      * 
1134      * @param {String} action  - group/name of event
1135      * @param {DataObject|false} obj - dataobject action occured on.
1136      * @param {String} any remarks
1137      * @return {DB_DataObject} Event object.,
1138      */
1139     
1140     function addEvent($act, $obj = false, $remarks = '') 
1141     {
1142         
1143         if (!empty(HTML_FlexyFramework::get()->Pman['disable_events'])) {
1144             return;
1145         }
1146         $au = $this->getAuthUser();
1147        
1148         $e = DB_DataObject::factory('Events');
1149         $e->init($act,$obj,$remarks); 
1150          
1151         $e->event_when = $e->sqlValue('NOW()');
1152         
1153         $eid = $e->insert();
1154         
1155         // fixme - this should be in onInsert..
1156         $wa = DB_DataObject::factory('core_watch');
1157         if (method_exists($wa,'notifyEvent')) {
1158             $wa->notifyEvent($e); // trigger any actions..
1159         }
1160         
1161         
1162         $e->onInsert(isset($_REQUEST) ? $_REQUEST : array() , $this);
1163         
1164        
1165         return $e;
1166         
1167     }
1168     
1169     function addEventNotifyOnly($act, $obj = false, $remarks = '')
1170     {
1171          $au = $this->getAuthUser();
1172        
1173         $e = DB_DataObject::factory('Events');
1174         $e->init($act,$obj,$remarks); 
1175          
1176         $e->event_when = $e->sqlValue('NOW()');
1177         $wa = DB_DataObject::factory('core_watch');
1178         if (method_exists($wa,'notifyEvent')) {
1179             $wa->notifyEvent($e); // trigger any actions..
1180         }
1181     }
1182     
1183     
1184     // ------------------ DEPERCIATED ----------------------------
1185      
1186     // DEPRECITAED - use moduleslist
1187     function modules()  { return $this->modulesList();  }
1188     
1189    
1190     // DEPRICATED  USE Pman_Core_Mailer
1191     
1192     function emailTemplate($templateFile, $args)
1193     {
1194     
1195         require_once 'Pman/Core/Mailer.php';
1196         $r = new Pman_Core_Mailer(array(
1197             'template'=>$templateFile,
1198             'contents' => $args,
1199             'page' => $this
1200         ));
1201         return $r->toData();
1202          
1203     }
1204     // DEPRICATED - USE Pman_Core_Mailer 
1205     // WHAT Part about DEPRICATED Does no one understand??
1206     function sendTemplate($templateFile, $args)
1207     {
1208         require_once 'Pman/Core/Mailer.php';
1209         $r = new Pman_Core_Mailer(array(
1210             'template'=>$templateFile,
1211             'contents' => array(),
1212             'page' => $this
1213         ));
1214         return $r->send();
1215         
1216     
1217     }
1218 }