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