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