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