Pman/Images.php
[Pman.Base] / Pman.php
1 <?php 
2 /**
3  * Pman Base class
4  * 
5  * Provides:
6  *  - base application setup (variables etc to javascript)
7  * 
8  *  - authentication and permission info about user / application
9  *  - json output methods.
10  *  - file upload error checking - checkFileUploadError
11  *  - logging to event table
12  *  - sendTemplate code (normally use the Person version for sending to specific people..)
13  * 
14  *  - doc managment code?? - remarks and tracking??? - MOVEME
15  *  - authentication link checking?? MOVEME?
16  *  - authentication reset password ?? MOVEME?
17  *  ?? arrayClean.. what's it doing here?!? ;)
18  * 
19  * Usefull implemetors
20  * DB_DataObject*:*toEventString (for logging - this is generically prefixed to all database operations.)
21  *   - any data object where this method exists, the result will get prefixed to the log remarks
22  */
23
24 class Pman extends HTML_FlexyFramework_Page 
25 {
26     var $appName= "";
27     var $appLogo= "";
28     var $appShortName= "";
29     var $appVersion = "1.8";
30     var $version = 'dev';
31     var $onloadTrack = 0;
32     var $linkFail = "";
33     var $showNewPass = 0;
34     var $logoPrefix = '';
35     var $appModules = '';
36     var $appDisabled = array(); // array of disabled modules..
37                     // (based on config option disable)
38     
39     var $authUser; // always contains the authenticated user..
40     
41    
42     
43     /**
44      * ------------- Standard getAuth/get/post methods of framework.
45      * 
46      * 
47      */
48     
49     function getAuth() // everyone allowed in!!!!!
50     {
51         $this->loadOwnerCompany();
52         
53         return true;
54         
55     }
56     
57     function init() 
58     {
59         if (isset($this->_hasInit)) {
60             return;
61         }
62         $this->_hasInit = true;
63           
64         $boot = HTML_FlexyFramework::get();
65         // echo'<PRE>';print_R($boot);exit;
66         $this->appName= $boot->appName;
67         $this->appNameShort= $boot->appNameShort;
68         
69         
70         $this->appModules= $boot->enable;
71         $this->isDev = empty($boot->Pman['isDev']) ? false : $boot->Pman['isDev'];
72         $this->appDisable = $boot->disable;
73         $this->appDisabled = explode(',', $boot->disable);
74         $this->version = $boot->version;
75         
76         if (!empty($ff->Pman['local_autoauth']) && 
77             ($_SERVER['SERVER_ADDR'] == '127.0.0.1') &&
78             ($_SERVER['REMOTE_ADDR'] == '127.0.0.1') 
79         ) {
80             $this->isDev = true;
81         }
82         
83         
84         
85         
86     }
87     
88     function get($base) 
89     {
90         $this->init();
91             //$this->allowSignup= empty($opts['allowSignup']) ? 0 : 1;
92         $bits = explode('/', $base);
93         //print_R($bits);
94         if ($bits[0] == 'Link') {
95             $this->linkFail = $this->linkAuth(@$bits[1],@$bits[2]);
96             header('Content-type: text/html; charset=utf-8');
97             return;
98         } 
99         if ($bits[0] == 'PasswordReset') {
100             $this->linkFail = $this->resetPassword(@$bits[1],@$bits[2],@$bits[3]);
101             header('Content-type: text/html; charset=utf-8');
102             return;
103         } 
104         
105         
106         if ($this->getAuthUser()) {
107             $this->addEvent("RELOAD");
108         }
109         
110         
111         if (strlen($base)) {
112             $this->addEvent("BADURL", false, $base);
113             $this->jerr("invalid url");
114         }
115         // deliver template
116         if (isset($_GET['onloadTrack'])) {
117             $this->onloadTrack = (int)$_GET['onloadTrack'];
118         }
119         // getting this to work with xhtml is a nightmare
120         // = nbsp / <img> issues screw everyting up.
121          //var_dump($this->isDev);
122         // force regeneration on load for development enviroments..
123         
124         HTML_FlexyFramework::get()->generateDataobjectsCache($this->isDev);
125         
126         //header('Content-type: application/xhtml+xml; charset=utf-8');
127         
128         
129         
130         if ($this->company->logo_id) {
131             $im = DB_DataObject::Factory('Images');
132             $im->get($this->company->logo_id);
133             $this->appLogo = $this->baseURL . '/Images/Thumb/400x100/'. $this->company->logo_id .'/' . $im->filename;
134         }
135         
136         header('Content-type: text/html; charset=utf-8');
137          
138     }
139     function post($base) {
140         return $this->get($base);
141     }
142     
143     
144     // --------------- AUTHENTICATION or  system information
145     /**
146      * loadOwnerCompany:
147      * finds the compay with comptype=='OWNER'
148      *
149      * @return {Pman_Core_DataObjects_Companies} the owner company
150      */
151     function loadOwnerCompany()
152     {
153          
154         $this->company = DB_DataObject::Factory('Companies');
155         if (!is_a($this->company, 'DB_DataObject')) { // non-core pman projects
156             return false; 
157         }
158         $this->company->get('comptype', 'OWNER');
159         return $this->company;
160     }
161     
162     
163     
164     /**
165      * getAuthUser: - get the authenticated user..
166      *
167      * @return {DB_DataObject} of type Pman[authTable] if authenticated.
168      */
169     
170     function getAuthUser()
171     {
172         if (!empty($this->authUser)) {
173             return $this->authUser;
174         }
175         $ff = HTML_FlexyFramework::get();
176         $tbl = empty($ff->Pman['authTable']) ? 'Person' : $ff->Pman['authTable'];
177         
178         $u = DB_DataObject::factory( $tbl );
179         if (!$u->isAuth()) {
180             return false;
181         }
182         $this->authUser =$u->getAuthUser();
183         return $this->authUser ;
184     }
185     /**
186      * hasPerm:
187      * wrapper arround authuser->hasPerm
188      * @see Pman_Core_DataObjects_User::hasPerm
189      *
190      * @param {String} $name  The permission name (eg. Projects.List)
191      * @param {String} $lvl   eg. (C)reate (E)dit (D)elete ... etc.
192      * 
193      */
194     function hasPerm($name, $lvl)  // do we have a permission
195     {
196         static $pcache = array();
197         $au = $this->getAuthUser();
198         return $au && $au->hasPerm($name,$lvl);
199         
200     }
201    
202     /**
203      * modulesList:  List the modules in the application
204      *
205      * @return {Array} list of modules
206      */
207     function modulesList()
208     {
209         $this->init();
210         
211         $mods = explode(',', $this->appModules);
212         if (in_array('Core',$mods)) { // core has to be the first  modules loaded as it contains Pman.js
213             array_unshift($mods,   'Core');
214         }
215         
216         $mods = array_unique($mods);
217          
218         $disabled =  explode(',', $this->appDisable ? $this->appDisable: '');
219         $ret = array();
220         foreach($mods as $mod) {
221             // add the css file..
222             if (in_array($mod, $disabled)) {
223                 continue;
224             }
225             $ret[] = $mod;
226         }
227         return $ret;
228     }
229     
230      
231     
232     
233     function hasModule($name) 
234     {
235         $this->init();
236         if (!strpos( $name,'.') ) {
237             // use enable / disable..
238             return in_array($name, $this->modules()); 
239         }
240         
241         $x = DB_DataObject::factory('Group_Rights');
242         $ar = $x->defaultPermData();
243         if (empty($ar[$name]) || empty($ar[$name][0])) {
244             return false;
245         }
246         return true;
247     }
248     
249      
250     
251     
252     
253     /**
254      * ---------------- Global Tools ---------------   
255      */
256     
257     
258     
259     /**
260      * send a template to the user
261      * rcpts are read from the resulting template.
262      * 
263      * @arg $templateFile  - the file in mail/XXXXXX.txt
264      * @arg $args  - variables available to the form as {t.*} over and above 'this'
265      * 
266      * 
267      */
268     
269     function sendTemplate($templateFile, $args)
270     {
271         
272         
273         
274         $content  = clone($this);
275         
276         foreach((array)$args as $k=>$v) {
277             $content->$k = $v;
278         }
279         $content->msgid = md5(time() . rand());
280         
281         $content->HTTP_HOST = $_SERVER["HTTP_HOST"];
282         /* use the regex compiler, as it doesnt parse <tags */
283         require_once 'HTML/Template/Flexy.php';
284         $template = new HTML_Template_Flexy( array(
285                  'compiler'    => 'Regex',
286                  'filters' => array('SimpleTags','Mail'),
287             //     'debug'=>1,
288             ));
289         
290         // this should be done by having multiple template sources...!!!
291          
292         $template->compile('mail/'. $templateFile.'.txt');
293         
294         /* use variables from this object to ouput data. */
295         $mailtext = $template->bufferedOutputObject($content);
296         //echo "<PRE>";print_R($mailtext);
297         
298         /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
299         require_once 'Mail/mimeDecode.php';
300         require_once 'Mail.php';
301         
302         $decoder = new Mail_mimeDecode($mailtext);
303         $parts = $decoder->getSendArray();
304         if (PEAR::isError($parts)) {
305             return $parts;
306             //echo "PROBLEM: {$parts->message}";
307             //exit;
308         } 
309         list($recipents,$headers,$body) = $parts;
310         ///$recipents = array($this->email);
311         $mailOptions = PEAR::getStaticProperty('Mail','options');
312         $mail = Mail::factory("SMTP",$mailOptions);
313         $headers['Date'] = date('r');
314         if (PEAR::isError($mail)) {
315             return $mail;
316         } 
317         $oe = error_reporting(E_ALL ^ E_NOTICE);
318         $ret = $mail->send($recipents,$headers,$body);
319         error_reporting($oe);
320        
321         return $ret;
322     
323     }
324     
325     function checkFileUploadError()  // check for file upload errors.
326     {    
327         if (
328             empty($_FILES['File']) 
329             || empty($_FILES['File']['name']) 
330             || empty($_FILES['File']['tmp_name']) 
331             || empty($_FILES['File']['type']) 
332             || !empty($_FILES['File']['error']) 
333             || empty($_FILES['File']['size']) 
334         ) {
335             $this->jerr("File upload error: <PRE>" . print_r($_FILES,true) . print_r($_POST,true) . "</PRE>");
336         }
337     }
338     
339     
340     /**
341      * generate a tempory file with an extension (dont forget to delete it)
342      */
343     
344     function tempName($ext)
345     {
346         $x = tempnam(ini_get('session.save_path'), HTML_FlexyFramework::get()->appNameShort.'TMP');
347         unlink($x);
348         return $x .'.'. $ext;
349     }
350     /**
351      * ------------- Authentication testing ------ ??? MOVEME?
352      * 
353      * 
354      */
355     function linkAuth($trid, $trkey) 
356     {
357         $tr = DB_DataObject::factory('Documents_Tracking');
358         if (!$tr->get($trid)) {
359             return "Invalid URL";
360         }
361         if (strtolower($tr->authkey) != strtolower($trkey)) {
362             $this->AddEvent("ERROR-L", false, "Invalid Key");
363             return "Invalid KEY";
364         }
365         // check date..
366         $this->onloadTrack = (int) $tr->doc_id;
367         if (strtotime($tr->date_sent) < strtotime("NOW - 14 DAYS")) {
368             $this->AddEvent("ERROR-L", false, "Key Expired");
369             return "Key Expired";
370         }
371         // user logged in and not
372         $au = $this->getAuthUser();
373         if ($au && $au->id && $au->id != $tr->person_id) {
374             $au->logout();
375             
376             return "Logged Out existing Session\n - reload to log in with correct key";
377         }
378         if ($au) { // logged in anyway..
379             $this->AddEvent("LOGIN", false, "With Key (ALREADY)");
380             header('Location: ' . $this->baseURL.'?onloadTrack='.$this->onloadTrack);
381             exit;
382             return false;
383         }
384         
385         // authenticate the user...
386         // slightly risky...
387         $u = DB_DataObject::factory('Person');
388          
389         $u->get($tr->person_id);
390         $u->login();
391         $this->AddEvent("LOGIN", false, "With Key");
392         
393         // we need to redirect out - otherwise refererer url will include key!
394         header('Location: ' . $this->baseURL.'?onloadTrack='.$this->onloadTrack);
395         exit;
396         
397         return false;
398         
399         
400         
401         
402     }
403     
404     
405     /**
406      * ------------- Authentication password reset ------ ??? MOVEME?
407      * 
408      * 
409      */
410     
411     
412     function resetPassword($id,$t, $key)
413     {
414         
415         $au = $this->getAuthUser();
416         if ($au) {
417             return "Already Logged in - no need to use Password Reset";
418         }
419         
420         $u = DB_DataObject::factory('Person');
421         //$u->company_id = $this->company->id;
422         $u->active = 1;
423         if (!$u->get($id) || !strlen($u->passwd)) {
424             return "invalid id";
425         }
426         
427         // validate key.. 
428         if ($key != $u->genPassKey($t)) {
429             return "invalid key";
430         }
431         $uu = clone($u);
432         $u->no_reset_sent = 0;
433         $u->update($uu);
434         
435         if ($t < strtotime("NOW - 1 DAY")) {
436             return "expired";
437         }
438         $this->showNewPass = implode("/", array($id,$t,$key));
439         return false;
440     }
441     
442     /**
443      * jerrAuth: standard auth failure - with data that let's the UI know..
444      */
445     function jerrAuth()
446     {
447         $au = $this->authUser();
448         if ($au) {
449             // is it an authfailure?
450             $this->jerr("Permission denied to view this resource", array('authFailure' => true));
451         }
452         $this->jerr("Not authenticated", array('authFailure' => true));
453     }
454      
455      
456      
457     /**
458      * ---------------- Standard JSON outputers. - used everywhere
459      */
460     
461     function jerr($str, $errors=array()) // standard error reporting..
462     {
463         
464         $cli = HTML_FlexyFramework::get()->cli;
465         if ($cli) {
466             echo "ERROR:\n" .$str . "\n";
467             exit;
468         }
469         
470         require_once 'Services/JSON.php';
471         $json = new Services_JSON();
472         
473         // log all errors!!!
474         $this->addEvent("ERROR", false, $str);
475         
476         if (!empty($_REQUEST['returnHTML']) || 
477             (isset($_SERVER['CONTENT_TYPE']) && preg_match('#multipart/form-data#i', $_SERVER['CONTENT_TYPE']))
478         ) {
479             header('Content-type: text/html');
480             echo "<HTML><HEAD></HEAD><BODY>";
481             echo  $json->encodeUnsafe(array(
482                     'success'=> false, 
483                     'errorMsg' => $str,
484                     'message' => $str, // compate with exeption / loadexception.
485
486                     'errors' => $errors ? $errors : true, // used by forms to flag errors.
487                     'authFailure' => !empty($errors['authFailure']),
488                 ));
489             echo "</BODY></HTML>";
490             exit;
491         }
492         
493         echo $json->encode(array(
494             'success'=> false, 
495             'data'=> array(), 
496             'errorMsg' => $str,
497             'message' => $str, // compate with exeption / loadexception.
498             'errors' => $errors ? $errors : true, // used by forms to flag errors.
499             'authFailure' => !empty($errors['authFailure']),
500         ));
501         exit;
502         
503     }
504     function jok($str)
505     {
506         
507         require_once 'Services/JSON.php';
508         $json = new Services_JSON();
509         
510         if (!empty($_REQUEST['returnHTML']) || 
511             (isset($_SERVER['CONTENT_TYPE']) && preg_match('#multipart/form-data#i', $_SERVER['CONTENT_TYPE']))
512         
513         ) {
514             header('Content-type: text/html');
515             echo "<HTML><HEAD></HEAD><BODY>";
516             // encode html characters so they can be read..
517             echo  str_replace(array('<','>'), array('\u003c','\u003e'),
518                         $json->encodeUnsafe(array('success'=> true, 'data' => $str)));
519             echo "</BODY></HTML>";
520             exit;
521         }
522          
523         
524         echo  $json->encode(array('success'=> true, 'data' => $str));
525         exit;
526         
527     }
528     /**
529      * output data for grids or tree
530      * @ar {Array} ar Array of data
531      * @total {Number|false} total number of records (or false to return count(ar)
532      * @extra {Array} extra key value list of data to pass as extra data.
533      * 
534      */
535     function jdata($ar,$total=false, $extra=array())
536     {
537         // should do mobile checking???
538         if ($total == false) {
539             $total = count($ar);
540         }
541         $extra=  $extra ? $extra : array();
542         require_once 'Services/JSON.php';
543         $json = new Services_JSON();
544         if (isset($_SERVER['CONTENT_TYPE']) && preg_match('#multipart/form-data#i', $_SERVER['CONTENT_TYPE'])) {
545             
546             header('Content-type: text/html');
547             echo "<HTML><HEAD></HEAD><BODY>";
548             // encode html characters so they can be read..
549             echo  str_replace(array('<','>'), array('\u003c','\u003e'),
550                         $json->encodeUnsafe(array('success' =>  true, 'total'=> $total, 'data' => $ar) + $extra));
551             echo "</BODY></HTML>";
552             exit;
553         }
554         
555       
556         
557         
558         
559         
560        
561         echo $json->encode(array('success' =>  true, 'total'=> $total, 'data' => $ar) + $extra);    
562         exit;
563         
564         
565     }
566     
567     
568    
569     
570     /**
571      * ---------------- OUTPUT
572      */
573     function hasBg($fn) // used on front page to check if logos exist..
574     {
575         return file_exists($this->rootDir.'/Pman/'.$this->appNameShort.'/templates/images/'.  $fn);
576     }
577      /**
578      * outputJavascriptIncludes:
579      *
580      * output <script....> for all the modules in the applcaiton
581      *
582      */
583     function outputJavascriptIncludes() // includes on devel version..
584     {
585         
586         $mods = $this->modulesList();
587         
588         foreach($mods as $mod) {
589             // add the css file..
590         
591             
592             $files = $this->moduleJavascriptList($mod.'/widgets');
593              foreach($files as $f) {
594                 echo '<script type="text/javascript" src="'. $f. '"></script>'."\n";
595             }
596             
597             $files = $this->moduleJavascriptList($mod);
598             foreach($files as $f) {
599                 echo '<script type="text/javascript" src="'. $f. '"></script>'."\n";
600             }
601             
602         }
603          
604     }
605      /**
606      * outputCSSIncludes:
607      *
608      * output <link rel=stylesheet......> for all the modules in the applcaiton
609      *
610      */
611     function outputCSSIncludes() // includes on CSS links.
612     {
613         
614         $mods = $this->modulesList();
615         
616         
617         foreach($mods as $mod) {
618             // add the css file..
619             $css = $this->rootDir.'/Pman/'.$mod.'/'.strtolower($mod).'.css';
620             if (file_exists( $css)){
621                 $css = $this->rootURL .'/Pman/'.$mod.'/'.strtolower($mod).'.css';
622                 echo '<link rel="stylesheet" type="text/css" href="'.$css.'" />'."\n";
623             }
624              
625             
626         }
627          
628     }
629       
630     /**
631      * Gather infor for javascript files..
632      *
633      * @param {String} $mod the module to get info about.
634      * @return {StdClass}  details about module.
635      */
636     function moduleJavascriptFilesInfo($mod)
637     {
638         
639         static $cache = array();
640         
641         if (isset($cache[$mod])) {
642             return $cache[$mod];
643         }
644         
645         
646         $ff = HTML_FlexyFramework::get();
647         
648         $base = dirname($_SERVER['SCRIPT_FILENAME']);
649         $dir =   $this->rootDir.'/Pman/'. $mod;
650         $path = $this->rootURL ."/Pman/$mod/";
651         
652         $ar = glob($dir . '/*.js');
653         
654         $files = array();
655         $arfiles = array();
656         $maxtime = 0;
657         $mtime = 0;
658         foreach($ar as $fn) {
659             $f = basename($fn);
660             // got the 'module file..'
661             $mtime = filemtime($dir . '/'. $f);
662             $maxtime = max($mtime, $maxtime);
663             $arfiles[$fn] = $mtime;
664             $files[] = $path . $f . '?ts='.$mtime;
665         }
666         
667         ksort($arfiles); // just sort by name so it's consistant for serialize..
668         
669         $compile  = empty($ff->Pman['public_cache_dir']) ? 0 : 1;
670         $basedir = $ff->Pman['public_cache_dir'];
671         $baseurl = $ff->Pman['public_cache_url'];
672         
673         $lsort = create_function('$a,$b','return strlen($a) > strlen($b) ? 1 : -1;');
674         usort($files, $lsort);
675         
676         $smod = str_replace('/','.',$mod);
677         
678         $output = date('Y-m-d-H-i-s-', $maxtime). $smod .'-'.md5(serialize($arfiles)) .'.js';
679         
680         $tmtime = file_exists($this->rootDir.'/_translations_/'. $smod.'.js')
681             ? filemtime($this->rootDir.'/_translations_/'. $smod.'.js') : 0;
682         
683         $cache[$mod]  = (object) array(
684             'smod' =>               $smod, // module name without '/'
685             'files' =>              $files, // list of all files.
686             'filesmtime' =>         $arfiles,  // map of mtime=>file
687             'maxtime' =>            $maxtime, // max mtime
688             'compile' =>            $this->isDev ? false : $compile,
689             'translation_file' =>   $base .'/_translations_/' . $smod .  '.js',
690             'translation_mtime' =>  $tmtime,
691             'output' =>             $output,
692             'translation_data' =>   preg_replace('/\.js$/', '.__translation__.js', $output),
693             'translation_base' =>   $dir .'/', //prefix of filename (without moudle name))
694             'basedir' =>            $basedir,   
695             'baseurl' =>            $baseurl,
696             'module_dir' =>         $dir,  
697         );
698         return $cache[$mod];
699     }
700      
701     
702     /**
703      *  moduleJavascriptList: list the javascript files in a module
704      *
705      *  The original version of this.. still needs more thought...
706      *
707      *  Compiled is in Pman/_compiled_/{$mod}/{LATEST...}.js
708      *  Translations are in Pman/_translations_/{$mod}.js
709      *  
710      *  if that stuff does not exist just list files in  Pman/{$mod}/*.js
711      *
712      *  Compiled could be done on the fly..
713      * 
714      *
715      *
716      *  @param {String} $mod  the module to look at - eg. Pman/{$mod}/*.js
717      *  @return {Array} list of include paths (either compiled or raw)
718      *
719      */
720
721     
722     
723     function moduleJavascriptList($mod)
724     {
725         
726         
727         $dir =   $this->rootDir.'/Pman/'. $mod;
728         
729         
730         if (!file_exists($dir)) {
731             echo '<!-- missing directory '. htmlspecialchars($dir) .' -->';
732             return array();
733         }
734         
735         $info = $this->moduleJavascriptFilesInfo($mod);
736        
737         
738           
739         if (empty($info->files)) {
740             return array();
741         }
742         // finally sort the files, so they are in the right order..
743         
744         // only compile this stuff if public_cache is set..
745         
746          
747         // suggestions...
748         //  public_cache_dir =   /var/www/myproject_cache
749         //  public_cache_url =   /myproject_cache    (with Alias apache /myproject_cache/ /var/www/myproject_cache/)
750         
751         // bit of debugging
752         if (!$info->compile) {
753             echo "<!-- Javascript compile turned off (isDev on, or public_cache_dir not set) -->\n";
754             return $info->files;
755         }
756         // where are we going to write all of this..
757         // This has to be done via a 
758         if (!file_exists($info->basedir.'/'.$info->output)) {
759             require_once 'Pman/Core/JsCompile.php';
760             $x = new Pman_Core_JsCompile();
761             
762             $x->pack($info->filesmtime,$info->basedir.'/'.$info->output, $info->translation_base);
763         }
764         
765         if (file_exists($info->basedir.'/'.$info->output) &&
766                 filesize($info->basedir.'/'.$info->output)) {
767             
768             $ret =array(
769                 $info->baseurl.'/'. $info->output,
770               
771             );
772             if ($info->translation_mtime) {
773                 $ret[] = $this->rootURL."/_translations_/". $info->smod.".js?ts=".$info->translation_mtime;
774             }
775             return $ret;
776         }
777         
778         
779         
780         // give up and output original files...
781         
782          
783         return $info->files;
784
785         
786     }
787     
788     
789     
790     /**
791      * ---------------- Logging ---------------   
792      */
793     
794     /**
795      * addEventOnce:
796      * Log an action (only if it has not been logged already.
797      * 
798      * @param {String} action  - group/name of event
799      * @param {DataObject|false} obj - dataobject action occured on.
800      * @param {String} any remarks
801      * @return {false|DB_DataObject} Event object.,
802      */
803     
804     function addEventOnce($act, $obj = false, $remarks = '') 
805     {
806         
807         $e = DB_DataObject::factory('Events');
808         $e->init($act,$obj,$remarks); 
809         if ($e->find(true)) {
810             return false;
811         }
812         return $this->addEvent($act, $obj, $remarks);
813     }
814     /**
815      * addEvent:
816      * Log an action.
817      * 
818      * @param {String} action  - group/name of event
819      * @param {DataObject|false} obj - dataobject action occured on.
820      * @param {String} any remarks
821      * @return {DB_DataObject} Event object.,
822      */
823     
824     function addEvent($act, $obj = false, $remarks = '') 
825     {
826         $au = $this->getAuthUser();
827        
828         $e = DB_DataObject::factory('Events');
829         $e->init($act,$obj,$remarks); 
830          
831         $e->event_when = date('Y-m-d H:i:s');
832         
833         $eid = $e->insert();
834         
835         $wa = DB_DataObject::factory('core_watch');
836         $wa->notifyEvent($e); // trigger any actions..
837         
838         
839         $ff  = HTML_FlexyFramework::get();
840         if (empty($ff->Pman['event_log_dir'])) {
841             return $e;
842         }
843         $file = $ff->Pman['event_log_dir']. date('/Y/m/d/'). $eid . ".php";
844         if (!file_exists(dirname($file))) {
845             mkdir(dirname($file),0700,true);
846         }
847         file_put_contents($file, var_export(array(
848             'REQUEST_URI' => empty($_SERVER['REQUEST_URI']) ? 'cli' : $_SERVER['REQUEST_URI'],
849             'GET' => empty($_GET) ? array() : $_GET,
850             'POST' => empty($_POST) ? array() : $_POST,
851         ), true));
852          
853         return $e;
854         
855     }
856     // ------------------ DEPERCIATED ---
857      
858     function modules() // DEPRECITAED
859     {
860         return $this->modulesList(); 
861     }
862     function staticGetAuthUser() // DEPRECIATED..
863     {
864         
865         $x = new Pman();
866         return $x->getAuthUser();
867         
868     }
869      
870     
871 }