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