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