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             $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         if(!empty($q['_retrieve_autosave'])){
247             $this->retrieveAutoSave($q, $au, $roo);
248         }
249     }
250       
251     
252     
253     /**
254      * check who is trying to access this. false == access denied..
255      * @return {boolean} true if access is allowed.
256      */
257     function checkPerm($lvl, $au) 
258     {
259         if ($lvl == 'S') {
260             return true;
261         }
262         // listing is controleed by applyfilters..
263         return $au->hasPerm("Admin.Admin_Tab", 'S');
264     }
265     /**
266      * object :
267      * return the object that this relates to.
268      * 
269      * @return {DB_DataObject} related object
270      */
271     function object()
272     {
273         $o = DB_DataObject::factory($this->on_table);
274         $o->get($this->on_id);
275         return $o;
276         
277     }
278     
279     
280     /**
281      * init:
282      * Initialize an event - ready to insert..
283      * 
284      * @param {String} action  - group/name of event
285      * @param {DataObject|false} obj - dataobject action occured on.
286      * @param {String} any remarks 
287      */
288     
289     function init($act, $obj, $remarks)
290     {
291         $ff = HTML_FlexyFramework::get();
292         $pg = $ff->page;
293         $au = $pg->getAuthUser();
294         
295         if ($ff->cli) { // && empty($au) && isset($obj->person_id)) {
296             $au = false;
297            // $au = DB_DataObject::Factory('Person'); // not always a person..
298            // $au->get($obj->person_id);
299         } 
300           
301         $this->person_name = $au && !empty($au->name) ? $au->name : '';
302         if (isset($au->id) && empty($au->id)) {
303             // not authenticated - and a standard id based object
304             $this->person_id = 0;
305         } else {
306             $this->person_id = $au ? (!empty($au->id) ? $au->id : $au->pid()) : -1;
307         }
308         $this->person_table = $au ? $au->tableName() : '';
309         $this->ipaddr = isset($_SERVER["REMOTE_ADDR"]) ? $_SERVER["REMOTE_ADDR"] : 'cli';
310         if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
311             $this->ipaddr = $_SERVER['HTTP_X_FORWARDED_FOR'];
312         }
313         
314         $this->action = $act;
315         $this->on_table = $obj ? $obj->tableName() : '';
316         $pk = $obj ? $obj->keys()  : false;
317         $this->on_id  = $obj && $pk ? $obj->{$pk[0]}: 0;
318         $rem  = array();
319         // should this really go in remarks? - 
320         if ($obj && method_exists($obj,'toEventString')) {
321             $rem[] = $obj->toEventString() ;
322         }
323         $rem[] = $remarks;
324         $this->remarks = implode(' : ', $rem);
325     }
326     
327     /**
328      * Generate an audit for this field.
329      *
330      * @param {DB_DataObject} new data
331      * @param {DB_DataObject} old data
332      * 
333      * @return {int} number of entries logged.
334      */
335     
336     function audit($new, $old = false)
337     {
338         if ($old == $new) {
339             return 0; // they are the same...
340         }
341          
342         $ret = 0;
343         foreach(array_keys($new->table()) as $k) {
344             // should we JSON serialize this?
345             $n = empty($new->$k) ? '' : $new->$k;
346             $o = empty($old->$k) || empty($old->$k) ? '' : $old->$k;
347             if ($n == $o) {
348                 continue;
349             }
350             $this->auditField($k, $o, $n, $old);
351             $ret++;
352         }
353         return $ret;
354     }
355     /**
356      * Record an audited change, in theory so we can audit data that is not just
357      * database Fields...
358      *
359      * @param {string} $name    table field anme
360      * @param {mixed} $ov  old value
361      * @param {mixed} $onv  new value
362      * @param {mixed} $old  old object (false if we are creating..)
363      */
364     function auditField($name, $ov, $nv, $old=false )
365     {
366         // hack..
367         if (is_object($nv)) {
368             return;
369         
370         }
371         
372         $x = DB_DataObject::factory('core_event_audit');
373         $x->setFrom(array(
374             'event_id' => $this->id,
375             'name' => $name,
376             'old_audit_id' => $old ? $x->findLast($this, $name) : 0,
377             'newvalue' => $nv
378
379         ));
380         $x->insert();
381     
382     }
383     
384     
385     
386     function onInsert($request,$roo)
387     {
388         $this->writeEventLog();
389     }
390     
391     function writeEventLog()
392     {
393         $ff  = HTML_FlexyFramework::get();
394         if (empty($ff->Pman['event_log_dir'])) {
395             return false;
396         }
397         
398         // add user (eg. www-data or local user if not..)
399         if (function_exists('posix_getpwuid')) {
400             $uinfo = posix_getpwuid( posix_getuid () ); 
401          
402             $user = $uinfo['name'];
403         } else {
404             $user = getenv('USERNAME'); // windows.
405         }
406         //print_r($this);
407         $file = $ff->Pman['event_log_dir']. '/'. $user. date('/Y/m/d/'). $this->id . ".json";
408         if (!file_exists(dirname($file))) {
409             mkdir(dirname($file),0700,true);
410         }
411         
412         // Remove all the password from logs...
413         $p =  empty($_POST) ? array() : $_POST;
414         foreach(array('passwd', 'password','passwd1',  'passwd2','password1', 'password2') as $rm) {
415             if (isset($p[$rm])) {
416                 $p[$rm] = '******';
417             }
418         }
419         
420         
421         $i=0;
422         $files = array();
423          
424         $i = 0;
425         foreach ($_FILES as $k=>$f){
426             // does not handle any other file[] arrary very well..
427             if (empty($f['tmp_name']) || !file_exists($f['tmp_name'])) {
428                 continue;
429             }
430             $i++;
431             $files[$k] = $f;
432             
433              
434             $files[$k]['tmp_name'] =  $this->id . '-'. $i;
435             $nf = $ff->Pman['event_log_dir']. '/'. $user. date('/Y/m/d/').   $files[$k]['tmp_name']; 
436             if (!copy($f['tmp_name'], $nf)) {
437                 print_r("failed to copy {$f['tmp_name']}...\n");
438             }
439         }
440         
441         file_put_contents($file, json_encode(array(
442             'REQUEST_URI' => empty($_SERVER['REQUEST_URI']) ? 'cli' : $_SERVER['REQUEST_URI'],
443             'HTTP_USER_AGENT' => empty($_SERVER['HTTP_USER_AGENT']) ? '' : $_SERVER['HTTP_USER_AGENT'],
444             'GET' => empty($_GET) ? array() : $_GET,
445             'POST' =>$p,
446             'FILES' => $files,
447         )));
448         
449         
450     }
451     
452 //    function postListFilter($data, $au, $q)
453 //    {
454 //        if(empty($q['_retrieve_file'])){
455 //            return $data;
456 //        }
457 //        
458 //        foreach ($data as $k => $v){
459 //            $images = DB_DataObject::factory('Images');
460 //            if(!$images->get($v['on_id'])){
461 //                unset($data[$k]);
462 //                continue;
463 //            }
464 //            
465 //            $source = json_decode(file_get_contents($images->getStoreName()))->source;
466 //            
467 //            $data[$k]['source'] = $source;
468 //        }
469 //        
470 //        return $data;
471 //    }
472 }