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