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