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