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