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