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