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