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