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         return $this->authUser ;
235     }
236     /**
237      * hasPerm:
238      * wrapper arround authuser->hasPerm
239      * @see Pman_Core_DataObjects_User::hasPerm
240      *
241      * @param {String} $name  The permission name (eg. Projects.List)
242      * @param {String} $lvl   eg. (C)reate (E)dit (D)elete ... etc.
243      * 
244      */
245     function hasPerm($name, $lvl)  // do we have a permission
246     {
247         static $pcache = array();
248         $au = $this->getAuthUser();
249         return $au && $au->hasPerm($name,$lvl);
250         
251     }
252    
253     /**
254      * modulesList:  List the modules in the application
255      *
256      * @return {Array} list of modules
257      */
258     function modulesList()
259     {
260         $boot = HTML_FlexyFramework::get();
261         // echo'<PRE>';print_R($boot);exit;
262          
263          
264         $mods = explode(',', $boot->enable);
265         if (in_array('Core',$mods)) { // core has to be the first  modules loaded as it contains Pman.js
266             array_unshift($mods,   'Core');
267         }
268         
269         if (in_array($boot->appNameShort,$mods)) { // Project has to be the last  modules loaded as it contains Pman.js
270             unset($mods[array_search($boot->appNameShort, $mods)]);
271             $mods[] = $boot->appNameShort;
272         }
273         
274         $mods = array_unique($mods);
275          
276         $disabled =  explode(',', $boot->disable ? $boot->disable : '');
277         $ret = array();
278         foreach($mods as $mod) {
279             // add the css file..
280             if (in_array($mod, $disabled)) {
281                 continue;
282             }
283             $ret[] = $mod;
284         }
285         return $ret;
286     }
287     
288      
289     
290     
291     function hasModule($name) 
292     {
293         $this->init();
294         print_R($this->modules());exit;
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     function jerr($str, $errors=array(), $content_type = false) // standard error reporting..
456     {
457         $this->addEvent("ERROR", false, $str);
458          
459         $cli = HTML_FlexyFramework::get()->cli;
460         if ($cli) {
461             echo "ERROR: " .$str . "\n";
462             exit;
463         }
464         
465         
466         if ($content_type == 'text/plain') {
467             header('Content-Disposition: attachment; filename="error.txt"');
468             header('Content-type: '. $content_type);
469             echo "ERROR: " .$str . "\n";
470             exit;
471         } 
472         
473         
474         
475         require_once 'Services/JSON.php';
476         $json = new Services_JSON();
477         
478         // log all errors!!!
479         
480         
481         if (!empty($_REQUEST['returnHTML']) || 
482             (isset($_SERVER['CONTENT_TYPE']) && preg_match('#multipart/form-data#i', $_SERVER['CONTENT_TYPE']))
483         ) {
484             header('Content-type: text/html');
485             echo "<HTML><HEAD></HEAD><BODY>";
486             echo  $json->encodeUnsafe(array(
487                     'success'=> false, 
488                     'errorMsg' => $str,
489                     'message' => $str, // compate with exeption / loadexception.
490
491                     'errors' => $errors ? $errors : true, // used by forms to flag errors.
492                     'authFailure' => !empty($errors['authFailure']),
493                 ));
494             echo "</BODY></HTML>";
495             exit;
496         }
497         
498         if (isset($_REQUEST['_debug'])) {
499             echo '<PRE>'.htmlspecialchars(print_r(array(
500                 'success'=> false, 
501                 'data'=> array(), 
502                 'errorMsg' => $str,
503                 'message' => $str, // compate with exeption / loadexception.
504                 'errors' => $errors ? $errors : true, // used by forms to flag errors.
505                 'authFailure' => !empty($errors['authFailure']),
506             ),true));
507             exit;
508                 
509         }
510         
511         echo $json->encode(array(
512             'success'=> false, 
513             'data'=> array(), 
514             'errorMsg' => $str,
515             'message' => $str, // compate with exeption / loadexception.
516             'errors' => $errors ? $errors : true, // used by forms to flag errors.
517             'authFailure' => !empty($errors['authFailure']),
518         ));
519         
520         
521         exit;
522         
523     }
524     function jok($str)
525     {
526         $cli = HTML_FlexyFramework::get()->cli;
527         if ($cli) {
528             echo "OK: " .$str . "\n";
529             exit;
530         }
531         require_once 'Services/JSON.php';
532         $json = new Services_JSON();
533         
534         if (!empty($_REQUEST['returnHTML']) || 
535             (isset($_SERVER['CONTENT_TYPE']) && preg_match('#multipart/form-data#i', $_SERVER['CONTENT_TYPE']))
536         
537         ) {
538             header('Content-type: text/html');
539             echo "<HTML><HEAD></HEAD><BODY>";
540             // encode html characters so they can be read..
541             echo  str_replace(array('<','>'), array('\u003c','\u003e'),
542                         $json->encodeUnsafe(array('success'=> true, 'data' => $str)));
543             echo "</BODY></HTML>";
544             exit;
545         }
546         
547         
548         echo  $json->encode(array('success'=> true, 'data' => $str));
549         
550         exit;
551         
552     }
553     /**
554      * output data for grids or tree
555      * @ar {Array} ar Array of data
556      * @total {Number|false} total number of records (or false to return count(ar)
557      * @extra {Array} extra key value list of data to pass as extra data.
558      * 
559      */
560     function jdata($ar,$total=false, $extra=array(), $cachekey = false)
561     {
562         // should do mobile checking???
563         if ($total == false) {
564             $total = count($ar);
565         }
566         $extra=  $extra ? $extra : array();
567         require_once 'Services/JSON.php';
568         $json = new Services_JSON();
569         if (isset($_SERVER['CONTENT_TYPE']) && preg_match('#multipart/form-data#i', $_SERVER['CONTENT_TYPE'])) {
570             
571             header('Content-type: text/html');
572             echo "<HTML><HEAD></HEAD><BODY>";
573             // encode html characters so they can be read..
574             echo  str_replace(array('<','>'), array('\u003c','\u003e'),
575                         $json->encodeUnsafe(array('success' =>  true, 'total'=> $total, 'data' => $ar) + $extra));
576             echo "</BODY></HTML>";
577             exit;
578         }
579         
580         
581         // see if trimming will help...
582         if (!empty($_REQUEST['_pman_short'])) {
583             $nar = array();
584             
585             foreach($ar as $as) {
586                 $add = array();
587                 foreach($as as $k=>$v) {
588                     if (is_string($v) && !strlen(trim($v))) {
589                         continue;
590                     }
591                     $add[$k] = $v;
592                 }
593                 $nar[] = $add;
594             }
595             $ar = $nar;
596               
597         }
598         
599       
600         $ret =  $json->encode(array('success' =>  true, 'total'=> $total, 'data' => $ar) + $extra);  
601         
602         if (!empty($cachekey)) {
603             
604             $fn = ini_get('session.save_path') . '/json-cache'.date('/Y/m/d').'.'. $cachekey . '.cache.json';
605             if (!file_exists(dirname($fn))) {
606                 mkdir(dirname($fn), 0777,true);
607             }
608             file_put_contents($fn, $ret);
609         }
610         echo $ret;
611         exit;
612     }
613     
614     
615     
616     /** a daily cache **/
617     function jdataCache($cachekey)
618     {
619         $fn = ini_get('session.save_path') . '/json-cache'.date('/Y/m/d').'.'. $cachekey . '.cache.json';
620         if (file_exists($fn)) {
621             header('Content-type: application/json');
622             echo file_get_contents($fn);
623             exit;
624         }
625         return false;
626         
627     }
628     
629    
630     
631     /**
632      * ---------------- OUTPUT
633      */
634     function hasBg($fn) // used on front page to check if logos exist..
635     {
636         return file_exists($this->rootDir.'/Pman/'.$this->appNameShort.'/templates/images/'.  $fn);
637     }
638      /**
639      * outputJavascriptIncludes:
640      *
641      * output <script....> for all the modules in the applcaiton
642      *
643      */
644     function outputJavascriptIncludes()  
645     {
646         
647         $mods = $this->modulesList();
648         
649         foreach($mods as $mod) {
650             // add the css file..
651         
652             
653             $files = $this->moduleJavascriptList($mod.'/widgets');
654              foreach($files as $f) {
655                 echo '<script type="text/javascript" src="'. $f. '"></script>'."\n";
656             }
657             
658             $files = $this->moduleJavascriptList($mod);
659             foreach($files as $f) {
660                 echo '<script type="text/javascript" src="'. $f. '"></script>'."\n";
661             }
662             
663         }
664         if (empty($this->disable_jstemplate)) {
665         // and finally the JsTemplate...
666             echo '<script type="text/javascript" src="'. $this->baseURL. '/Core/JsTemplate"></script>'."\n";
667         }
668          
669     }
670      /**
671      * outputCSSIncludes:
672      *
673      * output <link rel=stylesheet......> for all the modules in the applcaiton
674      *
675      *
676      * This could css minify as well.
677      */
678     function outputCSSIncludes() // includes on CSS links.
679     {
680         
681         $mods = $this->modulesList();
682         
683         
684         foreach($mods as $mod) {
685             // add the css file..
686             $dir = $this->rootDir.'/Pman/'.$mod;
687             $ar = glob($dir . '/*.css');
688             foreach($ar as $fn) { 
689                 $css = $this->rootURL .'/Pman/'.$mod.'/'.basename($fn) . '?ts=' . filemtime($fn);
690                 echo '<link rel="stylesheet" type="text/css" href="'.$css.'" />'."\n";
691             }
692              
693             
694         }
695          
696     }
697       
698     /**
699      * Gather infor for javascript files..
700      *
701      * @param {String} $mod the module to get info about.
702      * @return {StdClass}  details about module.
703      */
704     function moduleJavascriptFilesInfo($mod)
705     {
706         
707         static $cache = array();
708         
709         if (isset($cache[$mod])) {
710             return $cache[$mod];
711         }
712         
713         
714         $ff = HTML_FlexyFramework::get();
715         
716         $base = dirname($_SERVER['SCRIPT_FILENAME']);
717         $dir =   $this->rootDir.'/Pman/'. $mod;
718         $path = $this->rootURL ."/Pman/$mod/";
719         
720         $ar = glob($dir . '/*.js');
721         
722         $files = array();
723         $arfiles = array();
724         $maxtime = 0;
725         $mtime = 0;
726         foreach($ar as $fn) {
727             $f = basename($fn);
728             // got the 'module file..'
729             $mtime = filemtime($dir . '/'. $f);
730             $maxtime = max($mtime, $maxtime);
731             $arfiles[$fn] = $mtime;
732             $files[] = $path . $f . '?ts='.$mtime;
733         }
734         
735         ksort($arfiles); // just sort by name so it's consistant for serialize..
736         
737         $compile  = empty($ff->Pman['public_cache_dir']) ? 0 : 1;
738         $basedir = $compile ? $ff->Pman['public_cache_dir'] : false;
739         $baseurl = $compile ? $ff->Pman['public_cache_url'] : false;
740         
741         $lsort = create_function('$a,$b','return strlen($a) > strlen($b) ? 1 : -1;');
742         usort($files, $lsort);
743         
744         $smod = str_replace('/','.',$mod);
745         
746         $output = date('Y-m-d-H-i-s-', $maxtime). $smod .'-'.md5(serialize($arfiles)) .'.js';
747         
748         
749         // why are translations done like this - we just build them on the fly frmo the database..
750         $tmtime = file_exists($this->rootDir.'/_translations_/'. $smod.'.js')
751             ? filemtime($this->rootDir.'/_translations_/'. $smod.'.js') : 0;
752         
753         $cache[$mod]  = (object) array(
754             'smod' =>               $smod, // module name without '/'
755             'files' =>              $files, // list of all files.
756             'filesmtime' =>         $arfiles,  // map of mtime=>file
757             'maxtime' =>            $maxtime, // max mtime
758             'compile' =>            $this->isDev ? false : $compile,
759             'translation_file' =>   $base .'/_translations_/' . $smod .  '.js',
760             'translation_mtime' =>  $tmtime,
761             'output' =>             $output,
762             'translation_data' =>   preg_replace('/\.js$/', '.__translation__.js', $output),
763             'translation_base' =>   $dir .'/', //prefix of filename (without moudle name))
764             'basedir' =>            $basedir,   
765             'baseurl' =>            $baseurl,
766             'module_dir' =>         $dir,  
767         );
768         return $cache[$mod];
769     }
770      
771     
772     /**
773      *  moduleJavascriptList: list the javascript files in a module
774      *
775      *  The original version of this.. still needs more thought...
776      *
777      *  Compiled is in Pman/_compiled_/{$mod}/{LATEST...}.js
778      *  Translations are in Pman/_translations_/{$mod}.js
779      *  
780      *  if that stuff does not exist just list files in  Pman/{$mod}/*.js
781      *
782      *  Compiled could be done on the fly..
783      * 
784      *
785      *
786      *  @param {String} $mod  the module to look at - eg. Pman/{$mod}/*.js
787      *  @return {Array} list of include paths (either compiled or raw)
788      *
789      */
790
791     
792     
793     function moduleJavascriptList($mod)
794     {
795         
796         
797         $dir =   $this->rootDir.'/Pman/'. $mod;
798         
799         
800         if (!file_exists($dir)) {
801             echo '<!-- missing directory '. htmlspecialchars($dir) .' -->';
802             return array();
803         }
804         
805         $info = $this->moduleJavascriptFilesInfo($mod);
806        
807         
808           
809         if (empty($info->files)) {
810             return array();
811         }
812         // finally sort the files, so they are in the right order..
813         
814         // only compile this stuff if public_cache is set..
815         
816          
817         // suggestions...
818         //  public_cache_dir =   /var/www/myproject_cache
819         //  public_cache_url =   /myproject_cache    (with Alias apache /myproject_cache/ /var/www/myproject_cache/)
820         
821         // bit of debugging
822         if (!$info->compile) {
823             echo "<!-- Javascript compile turned off (isDev on, or public_cache_dir not set) -->\n";
824             return $info->files;
825         }
826         
827         // where are we going to write all of this..
828         // This has to be done via a 
829         if (!file_exists($info->basedir.'/'.$info->output) || !filesize($info->basedir.'/'.$info->output)) {
830             require_once 'Pman/Core/JsCompile.php';
831             $x = new Pman_Core_JsCompile();
832             
833             $x->pack($info->filesmtime,$info->basedir.'/'.$info->output, $info->translation_base);
834         } else {
835             echo "<!-- file exists not exist: {$info->basedir}/{$info->output} -->\n";
836         }
837         
838         if (file_exists($info->basedir.'/'.$info->output) &&
839                 filesize($info->basedir.'/'.$info->output)) {
840             
841             $ret =array(
842                 $info->baseurl.'/'. $info->output,
843               
844             );
845             // output all the ava
846             // fixme  - this needs the max datetime for the translation file..
847             $ret[] = $this->baseURL."/Admin/InterfaceTranslations/".$mod.".js"; //?ts=".$info->translation_mtime;
848             
849             //if ($info->translation_mtime) {
850             //    $ret[] = $this->rootURL."/_translations_/". $info->smod.".js?ts=".$info->translation_mtime;
851             //}
852             return $ret;
853         }
854         
855         
856         
857         // give up and output original files...
858         
859          
860         return $info->files;
861
862         
863     }
864     
865     /**
866      * Error handling...
867      *  PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array($this, 'onPearError'));
868      */
869     
870     static $permitError = false;
871     
872     function onPearError($err)
873     {
874         static $reported = false;
875         if ($reported) {
876             return;
877         }
878         
879         if (Pman::$permitError) {
880              
881             return;
882             
883         }
884         
885         
886         $reported = true;
887         $out = $err->toString();
888         
889         
890         //print_R($bt); exit;
891         $ret = array();
892         $n = 0;
893         foreach($err->backtrace as $b) {
894             $ret[] = @$b['file'] . '(' . @$b['line'] . ')@' .   @$b['class'] . '::' . @$b['function'];
895             if ($n > 20) {
896                 break;
897             }
898             $n++;
899         }
900         //convert the huge backtrace into something that is readable..
901         $out .= "\n" . implode("\n",  $ret);
902      
903         
904         $this->jerr($out);
905         
906         
907         
908     }
909     
910     
911     /**
912      * ---------------- Logging ---------------   
913      */
914     
915     /**
916      * addEventOnce:
917      * Log an action (only if it has not been logged already.
918      * 
919      * @param {String} action  - group/name of event
920      * @param {DataObject|false} obj - dataobject action occured on.
921      * @param {String} any remarks
922      * @return {false|DB_DataObject} Event object.,
923      */
924     
925     function addEventOnce($act, $obj = false, $remarks = '') 
926     {
927         if (!empty(HTML_FlexyFramework::get()->Pman['disable_events'])) {
928             return;
929         }
930         $e = DB_DataObject::factory('Events');
931         $e->init($act,$obj,$remarks); 
932         if ($e->find(true)) {
933             return false;
934         }
935         return $this->addEvent($act, $obj, $remarks);
936     }
937     /**
938      * addEvent:
939      * Log an action.
940      * 
941      * @param {String} action  - group/name of event
942      * @param {DataObject|false} obj - dataobject action occured on.
943      * @param {String} any remarks
944      * @return {DB_DataObject} Event object.,
945      */
946     
947     function addEvent($act, $obj = false, $remarks = '') 
948     {
949         
950         if (!empty(HTML_FlexyFramework::get()->Pman['disable_events'])) {
951             return;
952         }
953         $au = $this->getAuthUser();
954        
955         $e = DB_DataObject::factory('Events');
956         $e->init($act,$obj,$remarks); 
957          
958         $e->event_when = date('Y-m-d H:i:s');
959         
960         $eid = $e->insert();
961         
962         // fixme - this should be in onInsert..
963         $wa = DB_DataObject::factory('core_watch');
964         if (method_exists($wa,'notifyEvent')) {
965             $wa->notifyEvent($e); // trigger any actions..
966         }
967         
968         
969         $e->onInsert(isset($_REQUEST) ? $_REQUEST : array() , $this);
970         
971        
972         return $e;
973         
974     }
975     // ------------------ DEPERCIATED ----------------------------
976      
977     // DEPRECITAED - use moduleslist
978     function modules()  { return $this->modulesList();  }
979     
980     // DEPRECIATED.. - use getAuthUser...
981     function staticGetAuthUser()  { $x = new Pman(); return $x->getAuthUser();  }
982      
983     
984     // DEPRICATED  USE Pman_Core_Mailer
985     
986     function emailTemplate($templateFile, $args)
987     {
988     
989         require_once 'Pman/Core/Mailer.php';
990         $r = new Pman_Core_Mailer(array(
991             'template'=>$templateFile,
992             'contents' => $args,
993             'page' => $this
994         ));
995         return $r->toData();
996          
997     }
998     // DEPRICATED - USE Pman_Core_Mailer 
999     // WHAT Part about DEPRICATED Does no one understand??
1000     function sendTemplate($templateFile, $args)
1001     {
1002         require_once 'Pman/Core/Mailer.php';
1003         $r = new Pman_Core_Mailer(array(
1004             'template'=>$templateFile,
1005             'contents' => array(),
1006             'page' => $this
1007         ));
1008         return $r->send();
1009         
1010     
1011     }
1012 }