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