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