DataObjects/Events.php
[Pman.Core] / DataObjects / Events.php
1 <?php
2 /**
3  * Table Definition for Events
4  *
5  * objects can implement relatedWhere(), which should return
6  *    'tablename' => array of ids
7  *
8  * 
9  */
10 class_exists('DB_DataObject') ? '' : require_once 'DB/DataObject.php';
11
12 class Pman_Core_DataObjects_Events extends DB_DataObject 
13 {
14     ###START_AUTOCODE
15     /* the code below is auto generated do not remove the above tag */
16
17     public $__table = 'Events';                          // table name
18     public $id;                              // int(11)  not_null primary_key auto_increment
19     public $person_name;                     // string(128)  
20     public $event_when;                      // datetime(19)  binary
21     public $action;                          // string(32)  
22     public $ipaddr;                          // string(16)  
23     public $on_id;                           // int(11)  
24     public $on_table;                        // string(64)  
25     public $person_id;                       // int(11)  
26     public $remarks;                         // blob(65535)  blob
27     public $person_table;                    // string(64)
28
29     /* the code above is auto generated do not remove the tag below */
30     ###END_AUTOCODE
31     
32     
33     
34     
35     //  ------------ROO HOOKS------------------------------------
36     function applyFilters($q, $au ,$roo)
37     {
38         $tn = $this->tableName();
39         // if not empty on_table
40         exit;
41         if(!empty($q['person_table'])){
42             $jt = DB_DataObject::factory($q['person_table']);
43             
44             if(!array_key_exists("{$jt->tableName()}_id", $this->tableColumns())){ // coz we have triiger on mysql...
45                 
46                 $keys = $jt->keys();
47             
48                 $this->_join = "LEFT JOIN {$jt->tableName()} AS join_person_id_id ON (join_person_id_id.{$keys[0]}=Events.person_id)";
49                 $this->selectAdd();
50                 $this->selectAs();
51
52                 $this->selectAs($jt, 'person_id_%s', 'join_person_id_id');
53
54                 if (method_exists($jt,'nameColumn')) {
55                     $this->selectAdd("join_person_id_id.{$jt->nameColumn()} as person_id_name");
56                 }
57
58                 if (method_exists($jt,'emailColumn')) {
59                     $this->selectAdd("join_person_id_id.{$jt->emailColumn()} as person_id_email");
60                 }
61                 
62             }
63         
64         } else {
65             
66             $person = $au->tableName(); //'Person';  -- projects may not use person as the auth table...
67             $cfg = HTML_FlexyFramework::get()->Pman;
68             if (!empty($cfg['authTable'])) {
69                 $person =$cfg['authTable'];
70             }
71             
72             $jt = DB_DataObject::factory($person);
73             $this->whereAdd("
74                     person_table  = '{$jt->tableName()}'
75                     OR
76                     person_table = ''
77                     OR person_table IS NULL"
78             ); // default to  our standard.. - unless otherwise requested..
79         }
80         
81         
82         if (!empty($q['query']['from'])) {
83             $dt = date('Y-m-d' , strtotime($q['query']['from']));
84             $this->whereAdd(" {$tn}.event_when >=  '$dt' ");
85         }
86         if (!empty($q['query']['to'])) {
87             $dt = date('Y-m-d' , strtotime($q['query']['to']));
88             $this->whereAdd(" {$tn}.event_when <=  '$dt' ");
89         }
90         /*
91         if (!empty($q['query']['grouped']) && $q['query']['grouped'] == 'gr') {
92             // grouped..
93             DB_DataObject::Debuglevel(1);
94             $this->groupBy('on_id');
95             $this->selectAdd('
96                 (SELECT count(id) FROM core_event_audit WHERE event_id = Events.id) as changed
97                 ');
98         }
99         */
100         
101         if (!$au->hasPerm("Admin.Admin_Tab", 'S')) {
102             //DB_DataObject::DebugLevel(1);
103             // they can only view their changes..
104             $this->whereAdd("($tn.person_id = {$au->id} OR $tn.person_id = 0)");
105 //            $this->person_id = $au->id;
106             
107         }
108         // _join = tablename,tablename...
109         
110         /// on_table=cohead
111         //   &_join=cohead
112         //   &_join_cols=cohead_number
113         //    &_columns=on_id_cohead_number,event_when << this is ignored at present.
114         // max(event_when) is not supported... by any query yet..
115         
116         if (isset($q['on_table']) && !strlen($q['on_table'])) {
117             // empty ontable queries.. these are valid..
118             $this->whereAdd("$tn.on_table = ''");
119         }
120       
121         if (isset($q['query']['person_sum'])) {
122             //DB_DataObject::debugLevel(1);
123             $this->_extra_cols = array('qty' );
124             $this->selectAdd("count($tn.id) as qty");
125             $this->selectAdd("count( distinct $tn.on_id) as uqty");
126             $this->whereAdd('LENGTH(join_person_id_id.name) > 0 ');
127             $this->groupBy('person_id,join_person_id_id.name,join_person_id_id.email');
128         }
129          if (isset($q['query']['table_sum'])) {
130             //DB_DataObject::debugLevel(1);
131             $this->_extra_cols = array('qty' , 'uqty');
132             $this->selectAdd("count($tn.id) as qty");
133             $this->selectAdd("count( distinct $tn.on_table, $tn.on_id) as uqty");
134             
135             $this->groupBy('on_table');
136         }
137          if (isset($q['query']['day_sum'])) {
138             //DB_DataObject::debugLevel(1);
139             $this->_extra_cols = array('qty' , 'uqty');
140             $this->selectAdd("DATE_FORMAT(event_when, '%Y-%m-%d') as on_day");
141             $this->selectAdd("count($tn.id) as qty");
142             $this->selectAdd("count( distinct $tn.on_id) as uqty");
143             
144             $this->groupBy('on_day');
145         }
146         
147         if (isset($q['_join'])) {
148             //DB_DataObject::DebugLevel(1);
149             $joins = explode(',',$q['_join']);
150             
151             $this->selectAdd(); // ???
152             $distinct = false;
153             
154             foreach($joins as $t) {
155                 $t = preg_replace('/[^a-z_]+/', '', $t); // protection.
156                 $x = DB_DataObject::Factory($t);
157                 if (!is_a($x,'DB_DataObject')) {
158                     continue;
159                 }
160                 $jtn = $x->tableName();
161                 $jk = array_shift($x->keys());
162                 $this->_join .= "
163                 
164                     LEFT JOIN {$jtn} as join_on_id_{$jtn} ON {$tn}.on_id = join_on_id_{$jtn}.{$jk}
165                         AND on_table = '{$jtn}'
166                 ";
167                 $keys = array_keys($x->tableColumns());
168                 if (isset($q['_join_cols'])) {
169                     $jcs = explode(',',$q['_join_cols'] );
170                     //DB_DataObject::DebugLevel(1);
171                     
172                     foreach($jcs as $jc) { 
173                         if (! in_array($jc, $keys)) {
174                             continue;
175                         }
176                         if ($distinct) { 
177                         
178                        
179                             $this->selectAdd( " join_on_id_{$jtn}.{$jc}   as on_id_{$jc} ");
180                         } else {
181                             $this->selectAdd( " distinct(join_on_id_{$jtn}.{$jc}  ) as on_id_{$jc} ");
182                             $distinct = true;
183                         }
184                         $this->groupBy("on_id_{$jc} ");
185                         $this->whereAdd("join_on_id_{$jtn}.{$jc} IS NOT NULL");
186                     }
187                     $this->selectAdd( "MAX(events.event_when) as event_when");
188                     $this->orderBy('event_when DESC');
189                    // $this->selectAs(array($q['_join_cols']) , 'on_id_%s', "join_on_id_{$jtn}");
190                 } else { 
191                     $this->selectAs($x, 'on_id_%s', "join_on_id_{$jtn}");
192                 }
193             }
194                  
195             
196         }
197         
198         if (isset($q['_related_on_id']) && isset($q['_related_on_table'])) {
199             // example: sales order - has invoices,
200             ///DB_DataObject::DebugLevel(1);
201             $ev  =$this->factory('Events');
202             $ev->setFrom(array(
203                 'on_id' => $q['_related_on_id'],
204                 'on_table' => $q['_related_on_table'],
205                                ));
206             $obj = $ev->object();
207             
208             if (!$obj) {
209                 $roo->jerr("ontable is invalid");
210             }
211             if (!method_exists($obj,'relatedWhere')) {
212                 $roo->jerr( $q['_related_on_table'] . " Does not have method relatedWhere :" .
213                            implode(',', get_class_methods($obj)));
214             }
215             if ($obj && method_exists($obj,'relatedWhere')) {
216                 $ar = $obj->relatedWhere();
217                 $tn = $this->tableName();
218                 
219                 $w = array();
220                 $w[] = "( {$tn}.on_table = '" .
221                         $this->escape($q['_related_on_table']) .
222                         "' AND {$tn}.on_id = ". ((int)  $q['_related_on_id']) .
223                     ")";
224                 
225                 
226                 foreach($ar as $k=>$v) {
227                     if (empty($v)) {
228                         continue;
229                     }                
230                      $w[] = "( {$tn}.on_table = '$k' AND {$tn}.on_id IN (". implode(',', $v). "))";
231                     
232                 }
233                 $this->whereAdd(implode(' OR ' , $w));
234             }
235             
236             
237             
238             
239             
240         }
241         // since roo does not support autojoin yet..
242         if (!isset($q['_distinct'])) {
243             //$this->autoJoinExtra();
244         }
245         
246         if(!empty($q['query']['action'])) {
247             $act = $this->escape($q['query']['action']);
248             $this->whereAdd("Events.action LIKE '%{$act}%'");
249         }
250         
251         if(!empty($q['query']['on_table'])) {
252             $tnb = $this->escape($q['query']['on_table']);
253             $this->whereAdd("Events.on_table LIKE '%{$tnb}%'");
254         } 
255         
256     }
257       
258     
259     
260     /**
261      * check who is trying to access this. false == access denied..
262      * @return {boolean} true if access is allowed.
263      */
264     function checkPerm($lvl, $au) 
265     {
266         if ($lvl == 'S') {
267             return true;
268         }
269         // listing is controleed by applyfilters..
270         return $au->hasPerm("Admin.Admin_Tab", 'S');
271     }
272     /**
273      * object :
274      * return the object that this relates to.
275      * 
276      * @return {DB_DataObject} related object
277      */
278     function object()
279     {
280         $o = DB_DataObject::factory($this->on_table);
281         $o->get($this->on_id);
282         return $o;
283         
284     }
285     
286     
287     /**
288      * init:
289      * Initialize an event - ready to insert..
290      * 
291      * @param {String} action  - group/name of event
292      * @param {DataObject|false} obj - dataobject action occured on.
293      * @param {String} any remarks 
294      */
295     
296     function init($act, $obj, $remarks)
297     {
298         $ff = HTML_FlexyFramework::get();
299         $pg = $ff->page;
300         $au = $pg->getAuthUser();
301         
302         if ($ff->cli) { // && empty($au) && isset($obj->person_id)) {
303             $au = false;
304            // $au = DB_DataObject::Factory('Person'); // not always a person..
305            // $au->get($obj->person_id);
306         } 
307           
308         $this->person_name = $au && !empty($au->name) ? $au->name : '';
309         if (empty($au) || (isset($au->id) && empty($au->id))) {
310             // not authenticated - and a standard id based object
311             $this->person_id = 0;
312         } else {
313             $col = $au->tableName() == "Person" ? 'person_id' : $au->tableName() . '_id';
314             // does $col exist?
315             $cols = $this->tableColumns();
316             $col = isset($cols[$col]) ? $col : 'person_id'; // for BC.... - revert to using person_id
317             $this->{$col} = $au->pid();
318             //$this->person_id = $au ? (!empty($au->id) ? $au->id : $au->pid()) : -1;
319         }
320         $this->person_table = $au ? $au->tableName() : '';
321         $this->ipaddr = isset($_SERVER["REMOTE_ADDR"]) ? $_SERVER["REMOTE_ADDR"] : 'cli';
322         if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
323             $this->ipaddr = $_SERVER['HTTP_X_FORWARDED_FOR'];
324         }
325         
326         $this->action = $act;
327         $this->on_table = $obj ? $obj->tableName() : '';
328         $pk = $obj ? $obj->keys()  : false;
329         $this->on_id  = $obj && $pk ? $obj->{$pk[0]}: 0;
330         $rem  = array();
331         // should this really go in remarks? - 
332         if ($obj && method_exists($obj,'toEventString')) {
333             if($obj->toEventString() !== false){
334                 $rem[] = $obj->toEventString();
335             }
336         }
337         $rem[] = $remarks;
338         $this->remarks = implode(' : ', $rem);
339     }
340     
341     /**
342      * Generate an audit for this field.
343      *
344      * @param {DB_DataObject} new data
345      * @param {DB_DataObject} old data
346      * 
347      * @return {int} number of entries logged.
348      */
349     
350     function audit($new, $old = false)
351     {
352         if ($old == $new) {
353             return 0; // they are the same...
354         }
355          
356         $ret = 0;
357         foreach(array_keys($new->tableColumns()) as $k) {
358             // should we JSON serialize this?
359             $n = empty($new->$k) ? '' : $new->$k;
360             $o = empty($old->$k) || empty($old->$k) ? '' : $old->$k;
361             if ($n == $o) {
362                 continue;
363             }
364             $this->auditField($k, $o, $n, $old);
365             $ret++;
366         }
367         return $ret;
368     }
369     /**
370      * Record an audited change, in theory so we can audit data that is not just
371      * database Fields...
372      *
373      * @param {string} $name    table field anme
374      * @param {mixed} $ov  old value
375      * @param {mixed} $onv  new value
376      * @param {mixed} $old  old object (false if we are creating..)
377      */
378     function auditField($name, $ov, $nv, $old=false )
379     {
380         // hack..
381         if (is_object($nv)) {
382             return;
383         
384         }
385         
386         $x = DB_DataObject::factory('core_event_audit');
387         $x->setFrom(array(
388             'event_id' => $this->id,
389             'name' => $name,
390             'old_audit_id' => $old ? $x->findLast($this, $name) : 0,
391             'newvalue' => $nv
392
393         ));
394         $x->insert();
395     
396     }
397     
398     function beforeInsert($request,$roo)
399     {
400         if(empty($this->event_when)){
401             $this->event_when = $this->sqlValue("NOW()");
402         }
403         
404         if(empty($this->person_id)){
405             $this->person_id = $roo->authUser->id;
406             $this->person_name = $roo->authUser->name;
407             $this->person_table = $roo->authUser->tableName();
408         }
409         
410         if(empty($this->ipaddr)){
411             $this->ipaddr = isset($_SERVER["REMOTE_ADDR"]) ? $_SERVER["REMOTE_ADDR"] : 'cli';
412             if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
413                 $this->ipaddr = $_SERVER['HTTP_X_FORWARDED_FOR'];
414             }
415         }
416     }
417     
418     function beforeUpdate($old, $request,$roo)
419     {
420         if(!empty($request['_restore'])){
421             $this->restore($roo);
422         }
423     }
424     
425     function onInsert($request,$roo)
426     {
427         $this->writeEventLog();
428     }
429     
430     static $deleted = array();
431     
432     
433     // log deleting of a record so that it can be written later..
434     function logDeletedRecord($obj = false)
435     {
436         if (is_array($obj)) {
437             $ret = false;
438             foreach($obj as $o) {
439                 $aret = $this->logDeletedRecord($o);
440                 $ret = $ret ? $ret : $aret;
441             }
442             return true;
443         }
444         
445         if(empty($obj) || !is_a($obj, 'DB_DataObject')){
446             return false;
447         }
448         
449         
450         $del = $obj->toArray();
451         $del['_table'] = $obj->tableName();
452         
453         self::$deleted[] = $del;
454         return true;
455     }
456     static $extra_data = false;
457     
458     static function writeEventLogExtra($data) {
459         self::$extra_data = $data;
460     }
461     
462     function logDir()
463     {
464         $ff  = HTML_FlexyFramework::get();
465         if (function_exists('posix_getpwuid')) {
466             $uinfo = posix_getpwuid( posix_getuid () ); 
467          
468             $user = $uinfo['name'];
469         } else {
470             $user = getenv('USERNAME'); // windows.
471         }
472         
473         // DEPRICATED...
474         if (!empty($ff->Pman['event_log_dir'])) {
475             return $ff->Pman['event_log_dir'] . '/'.$user;
476         }
477         if (!empty($ff->Pman['storedir'])) {
478             return $ff->Pman['storedir'] .'/Events/'.$user;
479         
480         }
481         return false;
482     }
483     
484     
485     
486     function writeEventLog($extra_data  = false)
487     {
488         $logdir = $this->logDir();
489         if (!$logdir) {
490             return false;
491         }
492         
493          
494         //print_r($this);
495         $file = $logdir.  date('/Y/m/d/'). $this->id . ".json";
496         if (!file_exists(dirname($file))) {
497             
498             @mkdir(dirname($file),0700,true); // this might fail if it does not have correct permissions..
499             if (!file_exists(dirname($file))) {
500                 die("could not create $file - permissons are not correct"); // fatal, otherwise we loop!?
501             }
502             
503         }
504         
505         // Remove all the password from logs...
506         $p =  empty($_POST) ? array() : $_POST;
507         foreach(array('passwd', 'password','passwd1',  'passwd2','password1', 'password2') as $rm) {
508             if (isset($p[$rm])) {
509                 $p[$rm] = '******';
510             }
511         }
512         
513         
514         $i=0;
515         $files = array();
516          
517         $i = 0;
518         foreach ($_FILES as $k=>$f){
519             // does not handle any other file[] arrary very well..
520             if (empty($f['tmp_name']) || !file_exists($f['tmp_name'])) {
521                 continue;
522             }
523             $i++;
524             $files[$k] = $f;
525             
526              
527             $files[$k]['tmp_name'] =  $this->id . '-'. $i;
528             $nf = $logdir .   date('/Y/m/d/').   $files[$k]['tmp_name']; 
529             if (!copy($f['tmp_name'], $nf)) {
530                 print_r("failed to copy {$f['tmp_name']}...\n");
531             }
532         }
533         $out = array(
534             'REQUEST_URI' => empty($_SERVER['REQUEST_URI']) ? 'cli' : $_SERVER['REQUEST_URI'],
535             'HTTP_USER_AGENT' => empty($_SERVER['HTTP_USER_AGENT']) ? '' : $_SERVER['HTTP_USER_AGENT'],
536             'GET' => empty($_GET) ? array() : $_GET,
537             'POST' =>$p,
538             'FILES' => $files,
539             
540         );
541         if (!empty(self::$deleted)) {
542             $out['DELETED_DATAOBJECTS'] = self::$deleted;
543         }
544         if ($extra_data !== false) {
545             $out['EXTRA'] = $extra_data;
546         }
547         if ( self::$extra_data !== false) {
548             $out['EXTRA_DATA'] =  self::$extra_data;
549         }
550         
551         file_put_contents($file, json_encode($out));
552         
553         
554     }
555     
556     function toRooArray( $q)
557     {
558         $ret = $this->toArray();
559         
560         // fill toEventString.
561         if (!empty($q['_with_obj_summary']) && !empty($this->on_id)) {
562             $obj = $this->object();
563               
564             if ($obj && $obj->pid() && method_exists($obj,'toEventString')) {
565                 $es = $obj->toEventString();
566                 
567                 if (empty($this->remarks) || strpos($this->remarks, $es) < 0) {
568                     $ret['remarks'] = $es . ' ' . $this->remarks;
569                 }
570             } else if (empty($this->remarks)){
571                 $ret['remarks'] = "DELETED";
572                 
573             }
574         }
575         //print_r($ret);
576         return $ret;
577         
578     }
579     
580     function toRooSingleArray($au, $q)
581     {
582         $ret = $this->toArray();
583         
584          
585         
586         if(empty($q['_retrieve_source'])){
587             return $ret;
588         }
589         
590         $file = $this->retrieveEventLog();
591         
592         if(!$file){
593             return "No records?!";
594         }
595         
596         $source = json_decode(file_get_contents($file));
597         
598         return $source;
599     }
600     
601     function retrieveEventLog()
602     {
603         
604         $logdir = $this->logDir();
605         if (!$logdir) {
606             return false;
607          
608         }
609         
610         $date = date('/Y/m/d/', strtotime($this->event_when));
611         
612         $file = $logdir. $date. $this->id . ".json";
613         if (!file_exists(dirname($file))) {
614             return false;
615         }
616         
617         return $file;
618     }
619     
620     function restore($roo)
621     {
622         $file = $this->retrieveEventLog();
623         
624         if(empty($file) || !file_exists($file)){
625             $roo->jerr('Could not retrieve the event log file');
626         }
627         
628         $log = json_decode(file_get_contents($file), true);
629         
630         if(empty($log['POST']) || empty($log['POST']['_delete']) || empty($log['DELETED_DATAOBJECTS'])){
631             $roo->jerr('Invalid url');
632         }
633         
634         $restored = array();
635         
636         foreach ($log['DELETED_DATAOBJECTS'] as $d){
637             if(
638                     empty($d['id']) || 
639                     empty($d['_table']) || 
640                     (
641                             !empty($restored[$d['_table']]) && 
642                             in_array($d['id'], $restored[$d['_table']])
643                     )
644             ){
645                 continue;
646             }
647             
648             if(!isset($restored[$d['_table']])){
649                 $restored[$d['_table']] = array();
650             }
651             
652             $restored[$d['_table']][] = $d['id'];
653             
654             $table = DB_DataObject::factory($d['_table']);
655             
656             if (!is_a($table,'DB_DataObject')) {
657                 continue;
658             }
659             
660             unset($d['_table']);
661             
662             $table->setFrom($d);
663             
664             /*
665              * need to use the old id
666              */
667             $table->id = $d['id'];
668             
669             $table->sequenceKey(false,false);
670             
671             $table->insert();
672             
673             if($table->tableName() == 'crm_mailing_list_member'){
674                 $ml = DB_DataObject::factory('crm_mailing_list');
675                 if(!$ml->get($table->mailing_list_id)){
676                     continue;
677                 }
678
679                 $mlm = DB_DataObject::factory('crm_mailing_list_member');
680                 $mlm->setFrom(array(
681                     'mailing_list_id' => $table->mailing_list_id,
682                     'is_active' => 1
683                 ));
684
685                 $o = clone($ml);
686                 $ml->no_members = $mlm->count();
687                 $ml->update($o);
688             }
689         }
690         
691         $roo->jok('RESTORE');
692     }
693     function selectAddPersonEmail()
694     {
695         $this->selectAdd('join_person_id_id.email as email');
696         
697     }
698 }