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