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