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