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