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