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