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