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