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