DataObjects/Core_notify.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 (empty($au) || (isset($au->id) && empty($au->id))) {
306             // not authenticated - and a standard id based object
307             $this->person_id = 0;
308         } else {
309             $col = $au->tableName() == "Person" ? 'person_id' : $au->tableName() . '_id';
310             // does $col exist?
311             $cols = $this->table();
312             $col = isset($cols[$col]) ? $col : 'person_id'; // for BC.... - revert to using person_id
313             $this->{$col} = $au->pid();
314             //$this->person_id = $au ? (!empty($au->id) ? $au->id : $au->pid()) : -1;
315         }
316         $this->person_table = $au ? $au->tableName() : '';
317         $this->ipaddr = isset($_SERVER["REMOTE_ADDR"]) ? $_SERVER["REMOTE_ADDR"] : 'cli';
318         if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
319             $this->ipaddr = $_SERVER['HTTP_X_FORWARDED_FOR'];
320         }
321         
322         $this->action = $act;
323         $this->on_table = $obj ? $obj->tableName() : '';
324         $pk = $obj ? $obj->keys()  : false;
325         $this->on_id  = $obj && $pk ? $obj->{$pk[0]}: 0;
326         $rem  = array();
327         // should this really go in remarks? - 
328         if ($obj && method_exists($obj,'toEventString')) {
329             $rem[] = $obj->toEventString() ;
330         }
331         $rem[] = $remarks;
332         $this->remarks = implode(' : ', $rem);
333     }
334     
335     /**
336      * Generate an audit for this field.
337      *
338      * @param {DB_DataObject} new data
339      * @param {DB_DataObject} old data
340      * 
341      * @return {int} number of entries logged.
342      */
343     
344     function audit($new, $old = false)
345     {
346         if ($old == $new) {
347             return 0; // they are the same...
348         }
349          
350         $ret = 0;
351         foreach(array_keys($new->table()) as $k) {
352             // should we JSON serialize this?
353             $n = empty($new->$k) ? '' : $new->$k;
354             $o = empty($old->$k) || empty($old->$k) ? '' : $old->$k;
355             if ($n == $o) {
356                 continue;
357             }
358             $this->auditField($k, $o, $n, $old);
359             $ret++;
360         }
361         return $ret;
362     }
363     /**
364      * Record an audited change, in theory so we can audit data that is not just
365      * database Fields...
366      *
367      * @param {string} $name    table field anme
368      * @param {mixed} $ov  old value
369      * @param {mixed} $onv  new value
370      * @param {mixed} $old  old object (false if we are creating..)
371      */
372     function auditField($name, $ov, $nv, $old=false )
373     {
374         // hack..
375         if (is_object($nv)) {
376             return;
377         
378         }
379         
380         $x = DB_DataObject::factory('core_event_audit');
381         $x->setFrom(array(
382             'event_id' => $this->id,
383             'name' => $name,
384             'old_audit_id' => $old ? $x->findLast($this, $name) : 0,
385             'newvalue' => $nv
386
387         ));
388         $x->insert();
389     
390     }
391     
392     function beforeInsert($request,$roo)
393     {
394         if(empty($this->event_when)){
395             $this->event_when = $this->sqlValue("NOW()");
396         }
397         
398         if(empty($this->person_id)){
399             $this->person_id = $roo->authUser->id;
400             $this->person_name = $roo->authUser->name;
401             $this->person_table = $roo->authUser->tableName();
402         }
403         
404         if(empty($this->ipaddr)){
405             $this->ipaddr = isset($_SERVER["REMOTE_ADDR"]) ? $_SERVER["REMOTE_ADDR"] : 'cli';
406             if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
407                 $this->ipaddr = $_SERVER['HTTP_X_FORWARDED_FOR'];
408             }
409         }
410     }
411     
412     function onInsert($request,$roo)
413     {
414         $this->writeEventLog();
415     }
416     
417     static $deleted = array();
418     
419     
420     // log deleting of a record so that it can be written later..
421     function logDeletedRecord($obj = false, $reset = false)
422     {
423         
424         if(!empty($reset)){
425             self::$deleted = array();
426         }
427         
428         
429         if (is_array($obj)) {
430             $ret = false;
431             foreach($obj as $o) {
432                 $aret = $this->logDeletedRecord($o);
433                 $ret = $ret ? $ret : $aret;
434             }
435             return true;
436         }
437         
438         if(empty($obj) || !is_a($obj, 'DB_DataObject')){
439             return false;
440         }
441         
442         
443         $del = $obj->toArray();
444         $del['_table'] = $obj->tableName();
445
446         if(method_exists($obj, 'toDeletedArray')){
447             $del = $obj->toDeletedArray();
448         }
449         
450         self::$deleted[] = $del;
451         return true;
452     }
453     
454     function writeEventLog($extra_data  = '')
455     {
456         $ff  = HTML_FlexyFramework::get();
457         if (empty($ff->Pman['event_log_dir'])) {
458             return false;
459         }
460         
461         // add user (eg. www-data or local user if not..)
462         if (function_exists('posix_getpwuid')) {
463             $uinfo = posix_getpwuid( posix_getuid () ); 
464          
465             $user = $uinfo['name'];
466         } else {
467             $user = getenv('USERNAME'); // windows.
468         }
469         //print_r($this);
470         $file = $ff->Pman['event_log_dir']. '/'. $user. date('/Y/m/d/'). $this->id . ".json";
471         if (!file_exists(dirname($file))) {
472             mkdir(dirname($file),0700,true);
473         }
474         
475         // Remove all the password from logs...
476         $p =  empty($_POST) ? array() : $_POST;
477         foreach(array('passwd', 'password','passwd1',  'passwd2','password1', 'password2') as $rm) {
478             if (isset($p[$rm])) {
479                 $p[$rm] = '******';
480             }
481         }
482         
483         
484         $i=0;
485         $files = array();
486          
487         $i = 0;
488         foreach ($_FILES as $k=>$f){
489             // does not handle any other file[] arrary very well..
490             if (empty($f['tmp_name']) || !file_exists($f['tmp_name'])) {
491                 continue;
492             }
493             $i++;
494             $files[$k] = $f;
495             
496              
497             $files[$k]['tmp_name'] =  $this->id . '-'. $i;
498             $nf = $ff->Pman['event_log_dir']. '/'. $user. date('/Y/m/d/').   $files[$k]['tmp_name']; 
499             if (!copy($f['tmp_name'], $nf)) {
500                 print_r("failed to copy {$f['tmp_name']}...\n");
501             }
502         }
503         $out = array(
504             'REQUEST_URI' => empty($_SERVER['REQUEST_URI']) ? 'cli' : $_SERVER['REQUEST_URI'],
505             'HTTP_USER_AGENT' => empty($_SERVER['HTTP_USER_AGENT']) ? '' : $_SERVER['HTTP_USER_AGENT'],
506             'GET' => empty($_GET) ? array() : $_GET,
507             'POST' =>$p,
508             'FILES' => $files,
509             
510         );
511         if (!empty(self::$deleted)) {
512             $out['DELETED_DATAOBJECTS'] = self::$deleted;
513         }
514         if (!empty($extra_data)) {
515             $out['EXTRA'] = $extra_data;
516         }
517         
518         file_put_contents($file, json_encode($out));
519         
520         
521     }
522     
523     function toRooSingleArray($au, $q)
524     {
525         $ret = $this->toArray();
526         
527         if(empty($q['_retrieve_source'])){
528             return $ret;
529         }
530         
531         $file = $this->retrieveEventLog();
532         
533         if(!$file){
534             return "No records?!";
535         }
536         
537         $source = json_decode(file_get_contents($file));
538         
539         return $source;
540     }
541     
542     function retrieveEventLog()
543     {
544         $ff  = HTML_FlexyFramework::get();
545         if (empty($ff->Pman['event_log_dir'])) {
546             return false;
547         }
548         
549         if (function_exists('posix_getpwuid')) {
550             $uinfo = posix_getpwuid( posix_getuid () ); 
551          
552             $user = $uinfo['name'];
553         } else {
554             $user = getenv('USERNAME'); // windows.
555         }
556         
557         $date = date('/Y/m/d/', strtotime($this->event_when));
558         
559         $file = $ff->Pman['event_log_dir']. '/'. $user. $date. $this->id . ".json";
560         if (!file_exists(dirname($file))) {
561             return false;
562         }
563         
564         return $file;
565     }
566 }