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