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