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