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         
597         $retHTML = isset($_SERVER['CONTENT_TYPE']) && 
598                 preg_match('#multipart/form-data#i', $_SERVER['CONTENT_TYPE']);
599         
600         if ($retHTML){
601             if (isset($_REQUEST['returnHTML']) && $_REQUEST['returnHTML'] == 'NO') {
602                 $retHTML = false;
603             }
604         } else {
605             $retHTML = isset($_REQUEST['returnHTML']) && $_REQUEST['returnHTML'] !='NO';
606         }
607         
608         
609         
610         if ($retHTML) {
611             
612             header('Content-type: text/html');
613             echo "<HTML><HEAD></HEAD><BODY>";
614             // encode html characters so they can be read..
615             echo  str_replace(array('<','>'), array('\u003c','\u003e'),
616                         $json->encodeUnsafe(array('success' =>  true, 'total'=> $total, 'data' => $ar) + $extra));
617             echo "</BODY></HTML>";
618             exit;
619         }
620         
621         
622         // see if trimming will help...
623         if (!empty($_REQUEST['_pman_short'])) {
624             $nar = array();
625             
626             foreach($ar as $as) {
627                 $add = array();
628                 foreach($as as $k=>$v) {
629                     if (is_string($v) && !strlen(trim($v))) {
630                         continue;
631                     }
632                     $add[$k] = $v;
633                 }
634                 $nar[] = $add;
635             }
636             $ar = $nar;
637               
638         }
639         
640       
641         $ret =  $json->encode(array('success' =>  true, 'total'=> $total, 'data' => $ar) + $extra);  
642         
643         if (!empty($cachekey)) {
644             
645             $fn = ini_get('session.save_path') . '/json-cache'.date('/Y/m/d').'.'. $cachekey . '.cache.json';
646             if (!file_exists(dirname($fn))) {
647                 mkdir(dirname($fn), 0777,true);
648             }
649             file_put_contents($fn, $ret);
650         }
651         echo $ret;
652         exit;
653     }
654     
655     
656     
657     /** a daily cache **/
658     function jdataCache($cachekey)
659     {
660         $fn = ini_get('session.save_path') . '/json-cache'.date('/Y/m/d').'.'. $cachekey . '.cache.json';
661         if (file_exists($fn)) {
662             header('Content-type: application/json');
663             echo file_get_contents($fn);
664             exit;
665         }
666         return false;
667         
668     }
669     
670    
671     
672     /**
673      * ---------------- OUTPUT
674      */
675     function hasBg($fn) // used on front page to check if logos exist..
676     {
677         return file_exists($this->rootDir.'/Pman/'.$this->appNameShort.'/templates/images/'.  $fn);
678     }
679      /**
680      * outputJavascriptIncludes:
681      *
682      * output <script....> for all the modules in the applcaiton
683      *
684      */
685     function outputJavascriptIncludes()  
686     {
687         
688         $mods = $this->modulesList();
689         
690         foreach($mods as $mod) {
691             // add the css file..
692         
693             $this->outputJavascriptDir("Pman/$mod/widgets", "*.js");
694             $this->outputJavascriptDir("Pman/$mod", "*.js");
695             
696         }
697         
698         if (empty($this->disable_jstemplate)) {
699         // and finally the JsTemplate...
700             echo '<script type="text/javascript" src="'. $this->baseURL. '/Core/JsTemplate"></script>'."\n";
701         }
702          
703     }
704     
705      /**
706      * outputCSSIncludes:
707      *
708      * output <link rel=stylesheet......> for all the modules in the applcaiton
709      *
710      *
711      * This could css minify as well.
712      */
713     function outputCSSIncludes() // includes on CSS links.
714     {
715         
716         $mods = $this->modulesList();
717         
718         
719         foreach($mods as $mod) {
720             // add the css file..
721             $this->outputCSSDir("Pman/$mod","*.css");
722             
723             
724         }
725          
726     }
727     
728     
729     
730     
731     
732     
733     
734     
735     
736     
737     
738     
739     
740     
741     
742     
743     
744     // --- OLD CODE - in for BC on MO project.... - needs removing...
745     
746     // used on old versions.....
747     function outputJavascriptIncludesBC()  
748     {
749         
750         $mods = $this->modulesList();
751         
752         foreach($mods as $mod) {
753             // add the css file..
754         
755              
756             $files = $this->moduleJavascriptList($mod.'/widgets');
757             foreach($files as $f) {
758                 echo '<script type="text/javascript" src="'. $f. '"></script>'."\n";
759             }
760             
761             $files = $this->moduleJavascriptList($mod);
762             foreach($files as $f) {
763                 echo '<script type="text/javascript" src="'. $f. '"></script>'."\n";
764             }
765             
766         }
767         if (empty($this->disable_jstemplate)) {
768         // and finally the JsTemplate...
769             echo '<script type="text/javascript" src="'. $this->baseURL. '/Core/JsTemplate"></script>'."\n";
770         }
771          
772     }
773     /**
774      * Gather infor for javascript files..
775      *
776      * @param {String} $mod the module to get info about.
777      * @return {StdClass}  details about module.
778      */
779     function moduleJavascriptFilesInfo($mod)
780     {
781         
782         static $cache = array();
783         
784         if (isset($cache[$mod])) {
785             return $cache[$mod];
786         }
787         
788         
789         $ff = HTML_FlexyFramework::get();
790         
791         $base = dirname($_SERVER['SCRIPT_FILENAME']);
792         $dir =   $this->rootDir.'/Pman/'. $mod;
793         $path = $this->rootURL ."/Pman/$mod/";
794         
795         $ar = glob($dir . '/*.js');
796         
797         $files = array();
798         $arfiles = array();
799         $maxtime = 0;
800         $mtime = 0;
801         foreach($ar as $fn) {
802             $f = basename($fn);
803             // got the 'module file..'
804             $mtime = filemtime($dir . '/'. $f);
805             $maxtime = max($mtime, $maxtime);
806             $arfiles[$fn] = $mtime;
807             $files[] = $path . $f . '?ts='.$mtime;
808         }
809         
810         ksort($arfiles); // just sort by name so it's consistant for serialize..
811         
812         $compile  = empty($ff->Pman['public_cache_dir']) ? 0 : 1;
813         $basedir = $compile ? $ff->Pman['public_cache_dir'] : false;
814         $baseurl = $compile ? $ff->Pman['public_cache_url'] : false;
815         
816         $lsort = create_function('$a,$b','return strlen($a) > strlen($b) ? 1 : -1;');
817         usort($files, $lsort);
818         
819         $smod = str_replace('/','.',$mod);
820         
821         $output = date('Y-m-d-H-i-s-', $maxtime). $smod .'-'.md5(serialize($arfiles)) .'.js';
822         
823         
824         // why are translations done like this - we just build them on the fly frmo the database..
825         $tmtime = file_exists($this->rootDir.'/_translations_/'. $smod.'.js')
826             ? filemtime($this->rootDir.'/_translations_/'. $smod.'.js') : 0;
827         
828         $cache[$mod]  = (object) array(
829             'smod' =>               $smod, // module name without '/'
830             'files' =>              $files, // list of all files.
831             'filesmtime' =>         $arfiles,  // map of mtime=>file
832             'maxtime' =>            $maxtime, // max mtime
833             'compile' =>            $this->isDev ? false : $compile,
834             'translation_file' =>   $base .'/_translations_/' . $smod .  '.js',
835             'translation_mtime' =>  $tmtime,
836             'output' =>             $output,
837             'translation_data' =>   preg_replace('/\.js$/', '.__translation__.js', $output),
838             'translation_base' =>   $dir .'/', //prefix of filename (without moudle name))
839             'basedir' =>            $basedir,   
840             'baseurl' =>            $baseurl,
841             'module_dir' =>         $dir,  
842         );
843         return $cache[$mod];
844     }
845      
846     
847     /**
848      *  moduleJavascriptList: list the javascript files in a module
849      *
850      *  The original version of this.. still needs more thought...
851      *
852      *  Compiled is in Pman/_compiled_/{$mod}/{LATEST...}.js
853      *  Translations are in Pman/_translations_/{$mod}.js
854      *  
855      *  if that stuff does not exist just list files in  Pman/{$mod}/*.js
856      *
857      *  Compiled could be done on the fly..
858      * 
859      *
860      *
861      *  @param {String} $mod  the module to look at - eg. Pman/{$mod}/*.js
862      *  @return {Array} list of include paths (either compiled or raw)
863      *
864      */
865
866     
867     
868     function moduleJavascriptList($mod)
869     {
870         
871         
872         $dir =   $this->rootDir.'/Pman/'. $mod;
873         
874         
875         if (!file_exists($dir)) {
876             echo '<!-- missing directory '. htmlspecialchars($dir) .' -->';
877             return array();
878         }
879         
880         $info = $this->moduleJavascriptFilesInfo($mod);
881        
882         
883           
884         if (empty($info->files)) {
885             return array();
886         }
887         // finally sort the files, so they are in the right order..
888         
889         // only compile this stuff if public_cache is set..
890         
891          
892         // suggestions...
893         //  public_cache_dir =   /var/www/myproject_cache
894         //  public_cache_url =   /myproject_cache    (with Alias apache /myproject_cache/ /var/www/myproject_cache/)
895         
896         // bit of debugging
897         if (!$info->compile) {
898             echo "<!-- Javascript compile turned off (isDev on, or public_cache_dir not set) -->\n";
899             return $info->files;
900         }
901         
902         // where are we going to write all of this..
903         // This has to be done via a 
904         if (!file_exists($info->basedir.'/'.$info->output) || !filesize($info->basedir.'/'.$info->output)) {
905             require_once 'Pman/Core/JsCompile.php';
906             $x = new Pman_Core_JsCompile();
907             
908             $x->pack($info->filesmtime,$info->basedir.'/'.$info->output, $info->translation_base);
909         } else {
910             echo "<!-- file exists not exist: {$info->basedir}/{$info->output} -->\n";
911         }
912         
913         if (file_exists($info->basedir.'/'.$info->output) &&
914                 filesize($info->basedir.'/'.$info->output)) {
915             
916             $ret =array(
917                 $info->baseurl.'/'. $info->output,
918               
919             );
920             // output all the ava
921             // fixme  - this needs the max datetime for the translation file..
922             $ret[] = $this->baseURL."/Admin/InterfaceTranslations/".$mod.".js"; //?ts=".$info->translation_mtime;
923             
924             //if ($info->translation_mtime) {
925             //    $ret[] = $this->rootURL."/_translations_/". $info->smod.".js?ts=".$info->translation_mtime;
926             //}
927             return $ret;
928         }
929         
930         
931         
932         // give up and output original files...
933         
934          
935         return $info->files;
936
937         
938     }
939     
940     /**
941      * Error handling...
942      *  PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array($this, 'onPearError'));
943      */
944     
945     static $permitError = false;
946     
947     function onPearError($err)
948     {
949         static $reported = false;
950         if ($reported) {
951             return;
952         }
953         
954         if (Pman::$permitError) {
955              
956             return;
957             
958         }
959         
960         
961         $reported = true;
962         $out = $err->toString();
963         
964         
965         //print_R($bt); exit;
966         $ret = array();
967         $n = 0;
968         foreach($err->backtrace as $b) {
969             $ret[] = @$b['file'] . '(' . @$b['line'] . ')@' .   @$b['class'] . '::' . @$b['function'];
970             if ($n > 20) {
971                 break;
972             }
973             $n++;
974         }
975         //convert the huge backtrace into something that is readable..
976         $out .= "\n" . implode("\n",  $ret);
977      
978         print_R($out);exit;
979         
980         $this->jerr($out);
981         
982         
983         
984     }
985     
986     
987     /**
988      * ---------------- Logging ---------------   
989      */
990     
991     /**
992      * addEventOnce:
993      * Log an action (only if it has not been logged already.
994      * 
995      * @param {String} action  - group/name of event
996      * @param {DataObject|false} obj - dataobject action occured on.
997      * @param {String} any remarks
998      * @return {false|DB_DataObject} Event object.,
999      */
1000     
1001     function addEventOnce($act, $obj = false, $remarks = '') 
1002     {
1003         if (!empty(HTML_FlexyFramework::get()->Pman['disable_events'])) {
1004             return;
1005         }
1006         $e = DB_DataObject::factory('Events');
1007         $e->init($act,$obj,$remarks); 
1008         if ($e->find(true)) {
1009             return false;
1010         }
1011         return $this->addEvent($act, $obj, $remarks);
1012     }
1013     /**
1014      * addEvent:
1015      * Log an action.
1016      * 
1017      * @param {String} action  - group/name of event
1018      * @param {DataObject|false} obj - dataobject action occured on.
1019      * @param {String} any remarks
1020      * @return {DB_DataObject} Event object.,
1021      */
1022     
1023     function addEvent($act, $obj = false, $remarks = '') 
1024     {
1025         
1026         if (!empty(HTML_FlexyFramework::get()->Pman['disable_events'])) {
1027             return;
1028         }
1029         $au = $this->getAuthUser();
1030        
1031         $e = DB_DataObject::factory('Events');
1032         $e->init($act,$obj,$remarks); 
1033          
1034         $e->event_when = date('Y-m-d H:i:s');
1035         
1036         $eid = $e->insert();
1037         
1038         // fixme - this should be in onInsert..
1039         $wa = DB_DataObject::factory('core_watch');
1040         if (method_exists($wa,'notifyEvent')) {
1041             $wa->notifyEvent($e); // trigger any actions..
1042         }
1043         
1044         
1045         $e->onInsert(isset($_REQUEST) ? $_REQUEST : array() , $this);
1046         
1047        
1048         return $e;
1049         
1050     }
1051     // ------------------ DEPERCIATED ----------------------------
1052      
1053     // DEPRECITAED - use moduleslist
1054     function modules()  { return $this->modulesList();  }
1055     
1056     // DEPRECIATED.. - use getAuthUser...
1057     function staticGetAuthUser()  { $x = new Pman(); return $x->getAuthUser();  }
1058      
1059     
1060     // DEPRICATED  USE Pman_Core_Mailer
1061     
1062     function emailTemplate($templateFile, $args)
1063     {
1064     
1065         require_once 'Pman/Core/Mailer.php';
1066         $r = new Pman_Core_Mailer(array(
1067             'template'=>$templateFile,
1068             'contents' => $args,
1069             'page' => $this
1070         ));
1071         return $r->toData();
1072          
1073     }
1074     // DEPRICATED - USE Pman_Core_Mailer 
1075     // WHAT Part about DEPRICATED Does no one understand??
1076     function sendTemplate($templateFile, $args)
1077     {
1078         require_once 'Pman/Core/Mailer.php';
1079         $r = new Pman_Core_Mailer(array(
1080             'template'=>$templateFile,
1081             'contents' => array(),
1082             'page' => $this
1083         ));
1084         return $r->send();
1085         
1086     
1087     }
1088 }