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