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