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