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