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