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 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         print_r($this->keys());exit;
40         // if not empty on_table
41         if(!empty($q['person_table'])){
42             $jt = DB_DataObject::factory($q['person_table']);
43         
44             $this->_join = "LEFT JOIN {$jt->tableName()} AS join_person_id_id ON (join_person_id_id.id=Events.person_id)";
45             $this->selectAdd();
46             $this->selectAs();
47             
48             $this->selectAs($jt, 'person_id_%s', 'join_person_id_id');
49         
50             if (method_exists($jt,'nameColumn')) {
51                 $this->selectAdd("join_person_id_id.{$jt->nameColumn()} as person_id_name");
52             }
53         
54         
55         } else {
56             $person = 'Person';
57             $cfg = HTML_FlexyFramework::get()->Pman;
58             if (!empty($cfg['authTable'])) {
59                 $person =$cfg['authTable'];
60             }
61             
62             $jt = DB_DataObject::factory($person);
63             $this->whereAdd("
64                     person_table  = '{$jt->tableName()}'
65                     OR
66                     person_table = ''
67                     OR person_table IS NULL"
68             ); // default to  our standard.. - unless otherwise requested..
69         }
70         
71         
72         if (!empty($q['query']['from'])) {
73             $dt = date('Y-m-d' , strtotime($q['query']['from']));
74             $this->whereAdd(" {$tn}.event_when >=  '$dt' ");
75         }
76         if (!empty($q['query']['to'])) {
77             $dt = date('Y-m-d' , strtotime($q['query']['to']));
78             $this->whereAdd(" {$tn}.event_when <=  '$dt' ");
79         }
80         /*
81         if (!empty($q['query']['grouped']) && $q['query']['grouped'] == 'gr') {
82             // grouped..
83             DB_DataObject::Debuglevel(1);
84             $this->groupBy('on_id');
85             $this->selectAdd('
86                 (SELECT count(id) FROM core_event_audit WHERE event_id = Events.id) as changed
87                 ');
88         }
89         */
90         
91         if (!$au->hasPerm("Admin.Admin_Tab", 'S')) {
92             //DB_DataObject::DebugLevel(1);
93             // they can only view their changes..
94             $this->person_id = $au->id;
95             
96         }
97         // _join = tablename,tablename...
98         
99         /// on_table=cohead
100         //   &_join=cohead
101         //   &_join_cols=cohead_number
102         //    &_columns=on_id_cohead_number,event_when << this is ignored at present.
103         // max(event_when) is not supported... by any query yet..
104         
105         if (isset($q['on_table']) && !strlen($q['on_table'])) {
106             // empty ontable queries.. these are valid..
107             $this->whereAdd("$tn.on_table = ''");
108         }
109         
110         
111         
112         if (isset($q['query']['person_sum'])) {
113             //DB_DataObject::debugLevel(1);
114             $this->_extra_cols = array('qty' );
115             $this->selectAdd("count($tn.id) as qty");
116             $this->selectAdd("count( distinct $tn.on_id) as uqty");
117             $this->whereAdd('LENGTH(join_person_id_id.name) > 0 ');
118             $this->groupBy('person_id,join_person_id_id.name,join_person_id_id.email');
119         }
120          if (isset($q['query']['table_sum'])) {
121             //DB_DataObject::debugLevel(1);
122             $this->_extra_cols = array('qty' , 'uqty');
123             $this->selectAdd("count($tn.id) as qty");
124             $this->selectAdd("count( distinct $tn.on_table, $tn.on_id) as uqty");
125             
126             $this->groupBy('on_table');
127         }
128          if (isset($q['query']['day_sum'])) {
129             //DB_DataObject::debugLevel(1);
130             $this->_extra_cols = array('qty' , 'uqty');
131             $this->selectAdd("DATE_FORMAT(event_when, '%Y-%m-%d') as on_day");
132             $this->selectAdd("count($tn.id) as qty");
133             $this->selectAdd("count( distinct $tn.on_id) as uqty");
134             
135             $this->groupBy('on_day');
136         }
137         
138         if (isset($q['_join'])) {
139             //DB_DataObject::DebugLevel(1);
140             $joins = explode(',',$q['_join']);
141             
142             $this->selectAdd(); // ???
143             $distinct = false;
144             
145             foreach($joins as $t) {
146                 $t = preg_replace('/[^a-z_]+/', '', $t); // protection.
147                 $x = DB_DataObject::Factory($t);
148                 if (!is_a($x,'DB_DataObject')) {
149                     continue;
150                 }
151                 $jtn = $x->tableName();
152                 $jk = array_shift($x->keys());
153                 $this->_join .= "
154                 
155                     LEFT JOIN {$jtn} as join_on_id_{$jtn} ON {$tn}.on_id = join_on_id_{$jtn}.{$jk}
156                         AND on_table = '{$jtn}'
157                 ";
158                 $keys = array_keys($x->table());
159                 if (isset($q['_join_cols'])) {
160                     $jcs = explode(',',$q['_join_cols'] );
161                     //DB_DataObject::DebugLevel(1);
162                     
163                     foreach($jcs as $jc) { 
164                         if (! in_array($jc, $keys)) {
165                             continue;
166                         }
167                         if ($distinct) { 
168                         
169                        
170                             $this->selectAdd( " join_on_id_{$jtn}.{$jc}   as on_id_{$jc} ");
171                         } else {
172                             $this->selectAdd( " distinct(join_on_id_{$jtn}.{$jc}  ) as on_id_{$jc} ");
173                             $distinct = true;
174                         }
175                         $this->groupBy("on_id_{$jc} ");
176                         $this->whereAdd("join_on_id_{$jtn}.{$jc} IS NOT NULL");
177                     }
178                     $this->selectAdd( "MAX(events.event_when) as event_when");
179                     $this->orderBy('event_when DESC');
180                    // $this->selectAs(array($q['_join_cols']) , 'on_id_%s', "join_on_id_{$jtn}");
181                 } else { 
182                     $this->selectAs($x, 'on_id_%s', "join_on_id_{$jtn}");
183                 }
184             }
185                  
186             
187         }
188         
189         if (isset($q['_related_on_id']) && isset($q['_related_on_table'])) {
190             // example: sales order - has invoices,
191             ///DB_DataObject::DebugLevel(1);
192             $ev  =$this->factory('Events');
193             $ev->setFrom(array(
194                 'on_id' => $q['_related_on_id'],
195                 'on_table' => $q['_related_on_table'],
196                                ));
197             $obj = $ev->object();
198             
199             if (!$obj) {
200                 $roo->jerr("ontable is invalid");
201             }
202             if (!method_exists($obj,'relatedWhere')) {
203                 $roo->jerr( $q['_related_on_table'] . " Does not have method relatedWhere :" .
204                            implode(',', get_class_methods($obj)));
205             }
206             if ($obj && method_exists($obj,'relatedWhere')) {
207                 $ar = $obj->relatedWhere();
208                 $tn = $this->tableName();
209                 
210                 $w = array();
211                 $w[] = "( {$tn}.on_table = '" .
212                         $this->escape($q['_related_on_table']) .
213                         "' AND {$tn}.on_id = ". ((int)  $q['_related_on_id']) .
214                     ")";
215                 
216                 
217                 foreach($ar as $k=>$v) {
218                     if (empty($v)) {
219                         continue;
220                     }                
221                      $w[] = "( {$tn}.on_table = '$k' AND {$tn}.on_id IN (". implode(',', $v). "))";
222                     
223                 }
224                 $this->whereAdd(implode(' OR ' , $w));
225             }
226             
227             
228             
229             
230             
231         }
232         // since roo does not support autojoin yet..
233         if (!isset($q['_distinct'])) {
234             //$this->autoJoinExtra();
235         }
236         
237         if(!empty($q['query']['action'])) {
238             $act = $this->escape($q['query']['action']);
239             $this->whereAdd("Events.action LIKE '%{$act}%'");
240         }
241         
242         if(!empty($q['query']['on_table'])) {
243             $tnb = $this->escape($q['query']['on_table']);
244             $this->whereAdd("Events.on_table LIKE '%{$tnb}%'");
245         } 
246         
247     }
248       
249     
250     
251     /**
252      * check who is trying to access this. false == access denied..
253      * @return {boolean} true if access is allowed.
254      */
255     function checkPerm($lvl, $au) 
256     {
257         if ($lvl == 'S') {
258             return true;
259         }
260         // listing is controleed by applyfilters..
261         return $au->hasPerm("Admin.Admin_Tab", 'S');
262     }
263     /**
264      * object :
265      * return the object that this relates to.
266      * 
267      * @return {DB_DataObject} related object
268      */
269     function object()
270     {
271         $o = DB_DataObject::factory($this->on_table);
272         $o->get($this->on_id);
273         return $o;
274         
275     }
276     
277     
278     /**
279      * init:
280      * Initialize an event - ready to insert..
281      * 
282      * @param {String} action  - group/name of event
283      * @param {DataObject|false} obj - dataobject action occured on.
284      * @param {String} any remarks 
285      */
286     
287     function init($act, $obj, $remarks)
288     {
289         $ff = HTML_FlexyFramework::get();
290         $pg = $ff->page;
291         $au = $pg->getAuthUser();
292         
293         if ($ff->cli) { // && empty($au) && isset($obj->person_id)) {
294             $au = false;
295            // $au = DB_DataObject::Factory('Person'); // not always a person..
296            // $au->get($obj->person_id);
297         } 
298           
299         $this->person_name = $au && !empty($au->name) ? $au->name : '';
300         if (isset($au->id) && empty($au->id)) {
301             // not authenticated - and a standard id based object
302             $this->person_id = 0;
303         } else {
304             $this->person_id = $au ? (!empty($au->id) ? $au->id : $au->pid()) : -1;
305         }
306         $this->person_table = $au ? $au->tableName() : '';
307         $this->ipaddr = isset($_SERVER["REMOTE_ADDR"]) ? $_SERVER["REMOTE_ADDR"] : 'cli';
308         if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
309             $this->ipaddr = $_SERVER['HTTP_X_FORWARDED_FOR'];
310         }
311         
312         $this->action = $act;
313         $this->on_table = $obj ? $obj->tableName() : '';
314         $pk = $obj ? $obj->keys()  : false;
315         $this->on_id  = $obj && $pk ? $obj->{$pk[0]}: 0;
316         $rem  = array();
317         // should this really go in remarks? - 
318         if ($obj && method_exists($obj,'toEventString')) {
319             $rem[] = $obj->toEventString() ;
320         }
321         $rem[] = $remarks;
322         $this->remarks = implode(' : ', $rem);
323     }
324     
325     /**
326      * Generate an audit for this field.
327      *
328      * @param {DB_DataObject} new data
329      * @param {DB_DataObject} old data
330      * 
331      * @return {int} number of entries logged.
332      */
333     
334     function audit($new, $old = false)
335     {
336         if ($old == $new) {
337             return 0; // they are the same...
338         }
339          
340         $ret = 0;
341         foreach(array_keys($new->table()) as $k) {
342             // should we JSON serialize this?
343             $n = empty($new->$k) ? '' : $new->$k;
344             $o = empty($old->$k) || empty($old->$k) ? '' : $old->$k;
345             if ($n == $o) {
346                 continue;
347             }
348             $this->auditField($k, $o, $n, $old);
349             $ret++;
350         }
351         return $ret;
352     }
353     /**
354      * Record an audited change, in theory so we can audit data that is not just
355      * database Fields...
356      *
357      * @param {string} $name    table field anme
358      * @param {mixed} $ov  old value
359      * @param {mixed} $onv  new value
360      * @param {mixed} $old  old object (false if we are creating..)
361      */
362     function auditField($name, $ov, $nv, $old=false )
363     {
364         // hack..
365         if (is_object($nv)) {
366             return;
367         
368         }
369         
370         $x = DB_DataObject::factory('core_event_audit');
371         $x->setFrom(array(
372             'event_id' => $this->id,
373             'name' => $name,
374             'old_audit_id' => $old ? $x->findLast($this, $name) : 0,
375             'newvalue' => $nv
376
377         ));
378         $x->insert();
379     
380     }
381     
382     function beforeInsert($request,$roo)
383     {
384         if(empty($this->event_when)){
385             $this->event_when = $this->sqlValue("NOW()");
386         }
387         
388         if(empty($this->person_id)){
389             $this->person_id = $roo->authUser->id;
390             $this->person_name = $roo->authUser->name;
391             $this->person_table = $roo->authUser->tableName();
392         }
393         
394         if(empty($this->ipaddr)){
395             $this->ipaddr = isset($_SERVER["REMOTE_ADDR"]) ? $_SERVER["REMOTE_ADDR"] : 'cli';
396             if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
397                 $this->ipaddr = $_SERVER['HTTP_X_FORWARDED_FOR'];
398             }
399         }
400     }
401     
402     function onInsert($request,$roo)
403     {
404         $this->writeEventLog();
405     }
406     
407     function writeEventLog($extra_data  = '')
408     {
409         $ff  = HTML_FlexyFramework::get();
410         if (empty($ff->Pman['event_log_dir'])) {
411             return false;
412         }
413         
414         // add user (eg. www-data or local user if not..)
415         if (function_exists('posix_getpwuid')) {
416             $uinfo = posix_getpwuid( posix_getuid () ); 
417          
418             $user = $uinfo['name'];
419         } else {
420             $user = getenv('USERNAME'); // windows.
421         }
422         //print_r($this);
423         $file = $ff->Pman['event_log_dir']. '/'. $user. date('/Y/m/d/'). $this->id . ".json";
424         if (!file_exists(dirname($file))) {
425             mkdir(dirname($file),0700,true);
426         }
427         
428         // Remove all the password from logs...
429         $p =  empty($_POST) ? array() : $_POST;
430         foreach(array('passwd', 'password','passwd1',  'passwd2','password1', 'password2') as $rm) {
431             if (isset($p[$rm])) {
432                 $p[$rm] = '******';
433             }
434         }
435         
436         
437         $i=0;
438         $files = array();
439          
440         $i = 0;
441         foreach ($_FILES as $k=>$f){
442             // does not handle any other file[] arrary very well..
443             if (empty($f['tmp_name']) || !file_exists($f['tmp_name'])) {
444                 continue;
445             }
446             $i++;
447             $files[$k] = $f;
448             
449              
450             $files[$k]['tmp_name'] =  $this->id . '-'. $i;
451             $nf = $ff->Pman['event_log_dir']. '/'. $user. date('/Y/m/d/').   $files[$k]['tmp_name']; 
452             if (!copy($f['tmp_name'], $nf)) {
453                 print_r("failed to copy {$f['tmp_name']}...\n");
454             }
455         }
456         $out = array(
457             'REQUEST_URI' => empty($_SERVER['REQUEST_URI']) ? 'cli' : $_SERVER['REQUEST_URI'],
458             'HTTP_USER_AGENT' => empty($_SERVER['HTTP_USER_AGENT']) ? '' : $_SERVER['HTTP_USER_AGENT'],
459             'GET' => empty($_GET) ? array() : $_GET,
460             'POST' =>$p,
461             'FILES' => $files,
462         );
463         if (!empty($extra_data)) {
464             $out['EXTRA'] = $extra_data;
465         }
466         
467         file_put_contents($file, json_encode($out));
468         
469         
470     }
471     
472     function toRooSingleArray($au, $q)
473     {
474         $ret = $this->toArray();
475         
476         if(empty($q['_retrieve_source'])){
477             return $ret;
478         }
479         
480         $file = $this->retrieveEventLog();
481         
482         if(!$file){
483             return "No records?!";
484         }
485         
486         $source = json_decode(file_get_contents($file));
487         
488         return $source;
489     }
490     
491     function retrieveEventLog()
492     {
493         $ff  = HTML_FlexyFramework::get();
494         if (empty($ff->Pman['event_log_dir'])) {
495             return false;
496         }
497         
498         if (function_exists('posix_getpwuid')) {
499             $uinfo = posix_getpwuid( posix_getuid () ); 
500          
501             $user = $uinfo['name'];
502         } else {
503             $user = getenv('USERNAME'); // windows.
504         }
505         
506         $date = date('/Y/m/d/', strtotime($this->event_when));
507         
508         $file = $ff->Pman['event_log_dir']. '/'. $user. $date. $this->id . ".json";
509         if (!file_exists(dirname($file))) {
510             return false;
511         }
512         
513         return $file;
514     }
515 }