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