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