typo
[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 class_exists('DB_DataObject') ? '' : 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     public $dupe_id;                    // int(11)
29
30     /* the code above is auto generated do not remove the tag below */
31     ###END_AUTOCODE
32     
33     
34     
35     
36     //  ------------ROO HOOKS------------------------------------
37     function applyFilters($q, $au ,$roo)
38     {
39         $tn = $this->tableName();
40         // if not empty on_table
41         
42         if(!empty($q['person_table'])){
43             $jt = DB_DataObject::factory($q['person_table']);
44
45             
46             
47             if(!array_key_exists("{$jt->tableName()}_id", $this->tableColumns())){ // coz we have triiger on mysql...
48                 
49                 $keys = $jt->keys();
50             
51                 $this->_join = "LEFT JOIN {$jt->tableName()} AS join_person_id_id ON (join_person_id_id.{$keys[0]}=Events.person_id)";
52                 
53                 $this->selectAdd();
54                 $this->selectAs();
55
56                 $this->selectAs($jt, 'person_id_%s', 'join_person_id_id');
57                 if (method_exists($jt,'nameColumn')) {
58                     $this->selectAdd("join_person_id_id.{$jt->nameColumn()} as person_id_name");
59                 }
60
61                 if (method_exists($jt,'emailColumn')) {
62                     $this->selectAdd("join_person_id_id.{$jt->emailColumn()} as person_id_email");
63                 }
64                 
65             }
66         
67         } else {
68             
69             $person = $au->tableName(); //'Person';  -- projects may not use person as the auth table...
70             $cfg = HTML_FlexyFramework::get()->Pman;
71             if (!empty($cfg['authTable'])) {
72                 $person =$cfg['authTable'];
73             }
74             
75             $jt = DB_DataObject::factory($person);
76             //$this->whereAdd("
77             //        person_table  = '{$jt->tableName()}'
78             //        OR
79             //        person_table = ''
80             //        OR person_table IS NULL"
81             //); // default to  our standard.. - unless otherwise requested..
82         }
83         
84         
85         if (!empty($q['query']['from'])) {
86             $dt = date('Y-m-d' , strtotime($q['query']['from']));
87             $this->whereAdd(" {$tn}.event_when >=  '$dt' ");
88         }
89         if (!empty($q['query']['to'])) {
90             $dt = date('Y-m-d' , strtotime($q['query']['to']));
91             $this->whereAdd(" {$tn}.event_when <=  '$dt' ");
92         }
93         
94         if(!empty($q['_with_dupe_count'])){
95             $this->dupe_id = 0;                            
96             $this->selectAdd("(select count(*)+1 from Events ev_cnt where ev_cnt.dupe_id = {$tn}.id) as dupe_count");
97         }
98         /*
99         if (!empty($q['query']['grouped']) && $q['query']['grouped'] == 'gr') {
100             // grouped..
101             DB_DataObject::Debuglevel(1);
102             $this->groupBy('on_id');
103             $this->selectAdd('
104                 (SELECT count(id) FROM core_event_audit WHERE event_id = Events.id) as changed
105                 ');
106         }
107         */
108         
109         // _join = tablename,tablename...
110         
111         /// on_table=cohead
112         //   &_join=cohead
113         //   &_join_cols=cohead_number
114         //    &_columns=on_id_cohead_number,event_when << this is ignored at present.
115         // max(event_when) is not supported... by any query yet..
116         
117         if (isset($q['on_table']) && !strlen($q['on_table'])) {
118             // empty ontable queries.. these are valid..
119             $this->whereAdd("$tn.on_table = ''");
120         }
121       
122         if (isset($q['query']['person_sum'])) {
123             //DB_DataObject::debugLevel(1);
124             $this->_extra_cols = array('qty' );
125             $this->selectAdd("count($tn.id) as qty");
126             $this->selectAdd("count( distinct $tn.on_id) as uqty");
127             $this->whereAdd('LENGTH(join_person_id_id.name) > 0 ');
128             $this->groupBy('person_id,join_person_id_id.name,join_person_id_id.email');
129         }
130          if (isset($q['query']['table_sum'])) {
131             //DB_DataObject::debugLevel(1);
132             $this->_extra_cols = array('qty' , 'uqty');
133             $this->selectAdd("count($tn.id) as qty");
134             $this->selectAdd("count( distinct $tn.on_table, $tn.on_id) as uqty");
135             
136             $this->groupBy('on_table');
137         }
138          if (isset($q['query']['day_sum'])) {
139             //DB_DataObject::debugLevel(1);
140             $this->_extra_cols = array('qty' , 'uqty');
141             $this->selectAdd("DATE_FORMAT(event_when, '%Y-%m-%d') as on_day");
142             $this->selectAdd("count($tn.id) as qty");
143             $this->selectAdd("count( distinct $tn.on_id) as uqty");
144             
145             $this->groupBy('on_day');
146         }
147         
148         if (isset($q['_join'])) {
149             //DB_DataObject::DebugLevel(1);
150             $joins = explode(',',$q['_join']);
151             
152             //$this->selectAdd(); // ??? << this wipes out the default options
153             $distinct = false;
154             
155             foreach($joins as $t) {
156                 $t = preg_replace('/[^a-z_]+/', '', $t); // protection.
157                 $x = DB_DataObject::Factory($t);
158                 if (!is_a($x,'DB_DataObject')) {
159                     continue;
160                 }
161                 $jtn = $x->tableName();
162                 $jks = $x->keys();
163                 $jk = array_shift($jks);
164                 $this->_join .= "
165                 
166                     LEFT JOIN {$jtn} as join_on_id_{$jtn} ON {$tn}.on_id = join_on_id_{$jtn}.{$jk}
167                         AND on_table = '{$jtn}'
168                 ";
169                 $keys = array_keys($x->tableColumns());
170                 if (isset($q['_join_cols'])) {
171                     $jcs = explode(',',$q['_join_cols'] );
172                     //DB_DataObject::DebugLevel(1);
173                     
174                     foreach($jcs as $jc) { 
175                         if (! in_array($jc, $keys)) {
176                             continue;
177                         }
178                         if ($distinct) { 
179                         
180                        
181                             $this->selectAdd( " join_on_id_{$jtn}.{$jc}   as on_id_{$jc} ");
182                         } else {
183                             $this->selectAdd( " distinct(join_on_id_{$jtn}.{$jc}  ) as on_id_{$jc} ");
184                             $distinct = true;
185                         }
186                         $this->groupBy("on_id_{$jc} ");
187                         $this->whereAdd("join_on_id_{$jtn}.{$jc} IS NOT NULL");
188                     }
189                     $this->selectAdd( "MAX(events.event_when) as event_when");
190                     $this->orderBy('event_when DESC');
191                    // $this->selectAs(array($q['_join_cols']) , 'on_id_%s', "join_on_id_{$jtn}");
192                 } else { 
193                     $this->selectAs($x, 'on_id_%s', "join_on_id_{$jtn}");
194                 }
195             }
196                  
197             
198         }
199         
200         if (isset($q['_related_on_id']) && isset($q['_related_on_table'])) {
201             // example: sales order - has invoices,
202             ///DB_DataObject::DebugLevel(1);
203             $ev  =$this->factory('Events');
204             $ev->setFrom(array(
205                 'on_id' => $q['_related_on_id'],
206                 'on_table' => $q['_related_on_table'],
207                                ));
208             $obj = $ev->object();
209             
210             if (!$obj) {
211                 $roo->jerr("ontable is invalid");
212             }
213             
214             if (!method_exists($obj,'relatedWhere')) {
215                 $roo->jerr( $q['_related_on_table'] . " Does not have method relatedWhere  or relatedEventsWhere:" .
216                            implode(',', get_class_methods($obj)));
217             }
218             if ($obj && method_exists($obj,'relatedWhere')) {
219                 $ar = $obj->relatedWhere();
220                 $tn = $this->tableName();
221                 
222                 $w = array();
223                 $w[] = "( {$tn}.on_table = '" .
224                         $this->escape($q['_related_on_table']) .
225                         "' AND {$tn}.on_id = ". ((int)  $q['_related_on_id']) .
226                     ")";
227                 
228                 
229                 foreach($ar as $k=>$v) {
230                     if (empty($v)) {
231                         continue;
232                     }                
233                      $w[] = "( {$tn}.on_table = '$k' AND {$tn}.on_id IN (". implode(',', $v). "))";
234                     
235                 }
236                 $this->whereAdd(implode(' OR ' , $w));
237             }
238             
239          
240             
241         }
242         
243         // since roo does not support autojoin yet..
244         if (!isset($q['_distinct'])) {
245             //$this->autoJoinExtra();
246         }
247         
248         if(!empty($q['query']['action'])) {
249             $act = $this->escape($q['query']['action']);
250             $this->whereAdd("Events.action LIKE '%{$act}%'");
251         }
252         
253         if(!empty($q['query']['on_table'])) {
254             $tnb = $this->escape($q['query']['on_table']);
255             $this->whereAdd("Events.on_table LIKE '%{$tnb}%'");
256         } 
257         
258     }
259     
260     function applyPermissionFilters($q, $au ,$roo)
261     {
262         if (!$au->hasPerm("Admin.Admin_Tab", 'S')) {
263             //DB_DataObject::DebugLevel(1);
264             // they can only view their changes..
265             $this->whereAdd("($tn.person_id = {$au->id} OR $tn.person_id = 0)");
266 //            $this->person_id = $au->id;
267         }
268     }
269     
270     /**
271      * check who is trying to access this. false == access denied..
272      * @return {boolean} true if access is allowed.
273      */
274     function checkPerm($lvl, $au) 
275     {
276         if ($lvl == 'S') {
277             return true;
278         }
279         // listing is controleed by applyfilters..
280         return $au->hasPerm("Admin.Admin_Tab", 'S');
281     }
282     /**
283      * object :
284      * return the object that this relates to.
285      * 
286      * @return {DB_DataObject} related object
287      */
288     function object()
289     {
290         $o = DB_DataObject::factory($this->on_table);
291         $o->get($this->on_id);
292         return $o;
293         
294     }
295     
296     
297     /**
298      * init:
299      * Initialize an event - ready to insert..
300      * 
301      * @param {String} action  - group/name of event
302      * @param {DataObject|false} obj - dataobject action occured on.
303      * @param {String} any remarks 
304      */
305     
306     function init($act, $obj, $remarks)
307     {
308         $ff = HTML_FlexyFramework::get();
309         $pg = $ff->page;
310         $au = $pg->getAuthUser();
311
312         if ($ff->cli) { // && empty($au) && isset($obj->person_id)) {
313             $au = false;
314            // $au = DB_DataObject::Factory('Person'); // not always a person..
315            // $au->get($obj->person_id);
316         } 
317
318         $this->person_name = $au && !empty($au->name) ? $au->name : '';
319         //print_r($au);
320         //exit;
321         //$this->who = $au && !empty($au->name) ? $au->name : '';
322         if (empty($au) || (isset($au->id) && empty($au->id))) {
323             // not authenticated - and a standard id based object
324             $this->person_id = 0;
325         } else {
326             $col = $au->tableName() == "Person" ? 'person_id' : $au->tableName() . '_id';
327             // does $col exist?
328             $cols = $this->tableColumns();
329             $col = isset($cols[$col]) ? $col : 'person_id'; // for BC.... - revert to using person_id
330             $this->{$col} = $au->pid();
331             //$this->person_id = $au ? (!empty($au->id) ? $au->id : $au->pid()) : -1;            
332         }
333         $this->person_table = $au ? $au->tableName() : '';
334         $this->ipaddr = isset($_SERVER["REMOTE_ADDR"]) ? $_SERVER["REMOTE_ADDR"] : 'cli';
335         if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
336             $this->ipaddr = $_SERVER['HTTP_X_FORWARDED_FOR'];
337         }
338         
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             if($obj->toEventString() !== false){
347                 $rem[] = $obj->toEventString();
348             }
349         }
350         
351         if(!empty($remarks)){
352             $rem[] = $remarks;
353         }
354         
355         $this->remarks = implode(' : ', $rem);
356     }
357     
358     /**
359      * Generate an audit for this field.
360      *
361      * @param {DB_DataObject} new data
362      * @param {DB_DataObject} old data
363      * 
364      * @return {int} number of entries logged.
365      */
366     
367     function audit($new, $old = false)
368     {
369         if ($old == $new) {
370             return 0; // they are the same...
371         }
372          
373         $ret = 0;
374         foreach(array_keys($new->tableColumns()) as $k) {
375             // should we JSON serialize this?
376             $n = empty($new->$k) ? '' : $new->$k;
377             $o = empty($old->$k) || empty($old->$k) ? '' : $old->$k;
378             if ($n == $o) {
379                 continue;
380             }
381             $this->auditField($k, $o, $n, $old);
382             $ret++;
383         }
384         return $ret;
385     }
386     /**
387      * Record an audited change, in theory so we can audit data that is not just
388      * database Fields...
389      *
390      * @param {string} $name    table field anme
391      * @param {mixed} $ov  old value
392      * @param {mixed} $onv  new value
393      * @param {mixed} $old  old object (false if we are creating..)
394      */
395     function auditField($name, $ov, $nv, $old=false )
396     {
397         // hack..
398         if (is_object($nv)) {
399             return;
400         
401         }
402         
403         $x = DB_DataObject::factory('core_event_audit');
404         $x->setFrom(array(
405             'event_id' => $this->id,
406             'name' => $name,
407             'old_audit_id' => $old ? $x->findLast($this, $name) : 0,
408             'newvalue' => $nv
409
410         ));
411         $x->insert();
412     
413     }
414     
415     function beforeInsert($request,$roo)
416     {
417         if(empty($this->event_when)){
418             $this->event_when = $this->sqlValue("NOW()");
419         }
420         
421         if(empty($this->person_id)){
422             $this->person_id = $roo->authUser->id;
423             $this->person_name = $roo->authUser->name;
424             $this->person_table = $roo->authUser->tableName();
425         }
426         
427         if(empty($this->ipaddr)){
428             $this->ipaddr = isset($_SERVER["REMOTE_ADDR"]) ? $_SERVER["REMOTE_ADDR"] : 'cli';
429             if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
430                 $this->ipaddr = $_SERVER['HTTP_X_FORWARDED_FOR'];
431             }
432         }        
433     }
434     
435     function beforeUpdate($old, $request,$roo)
436     {
437         if(!empty($request['_restore'])){
438             $this->restore($roo);
439         }
440     }
441     
442     function onInsert($request,$roo)
443     {
444         $this->writeEventLog();
445     }
446     
447     static $deleted = array();
448     
449     
450     // log deleting of a record so that it can be written later..
451     function logDeletedRecord($obj = false)
452     {
453         if (is_array($obj)) {
454             $ret = false;
455             foreach($obj as $o) {
456                 $aret = $this->logDeletedRecord($o);
457                 $ret = $ret ? $ret : $aret;
458             }
459             return true;
460         }
461         
462         if(empty($obj) || !is_a($obj, 'DB_DataObject')){
463             return false;
464         }
465         
466         
467         $del = $obj->toArray();
468         $del['_table'] = $obj->tableName();
469         
470         self::$deleted[] = $del;
471         return true;
472     }
473     static $extra_data = false;
474     
475     static function writeEventLogExtra($data) {
476         self::$extra_data = $data;
477     }
478     static $files = array();
479     
480     /**
481      * Add a file to the output log
482      * this needs to be called before addEvent, and the data format should be the same as $_FILES
483      * eg.
484      * 
485      * DB_DataObject::factory('Events')->addFile(array(
486      *    'tmp_name' => real file location
487      *    'name' => real file name
488      *    'type' => mimetype
489      *    'size' => filesize
490      *    
491      * ))
492      * 
493      */
494     function addFile($data)
495     {
496         self::$files[] = $data;
497     }
498     
499     function logDir($user = false)
500     {
501         $ff  = HTML_FlexyFramework::get();
502         if ($user === false) {
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         
512    
513         if (!empty($ff->Pman['storedir'])) {
514             return $ff->Pman['storedir'] .'/Events/'.$user;
515         }
516         // DEPRICATED... 
517         if (!empty($ff->Pman['event_log_dir'])) {
518             return $ff->Pman['event_log_dir'] . '/'.$user;
519         }
520         
521         return false;
522     }
523     
524     
525     
526     function writeEventLog($extra_data  = false)
527     {
528         $logdir = $this->logDir();
529         
530         if (!$logdir) {
531             return false;
532         }
533         
534          
535         //print_r($this);
536         $file = $logdir.  date('/Y/m/d/'). $this->id . ".json";
537         if (!file_exists(dirname($file))) {
538             
539             @mkdir(dirname($file),0700,true); // this might fail if it does not have correct permissions..
540             clearstatcache();
541             if (!file_exists(dirname($file))) {
542                 //print_r($this);
543                 die("Events:: writeEventLog: could not create $file - permissons are not correct\n"); // fatal, otherwise we loop!?
544             }
545             
546         }
547         
548         // Remove all the password from logs...
549         $p =  empty($_POST) ? array() : $_POST;
550         foreach(array('passwd', 'password','passwd1',  'passwd2','password1', 'password2') as $rm) {
551             if (isset($p[$rm])) {
552                 $p[$rm] = '******';
553             }
554         }
555         
556         
557         $i=0;
558         $files = array();
559           
560          
561         
562         foreach (array_merge($_FILES, self::$files) as $k=>$f){
563             // does not handle any other file[] arrary very well..
564             if (empty($f['tmp_name']) || !file_exists($f['tmp_name'])) {
565                 continue;
566             }
567             $i++;
568             $files[$k] = $f;
569             
570              
571             $files[$k]['tmp_name'] =  $this->id . '-'. $i;
572             $nf = $logdir .   date('/Y/m/d/').   $files[$k]['tmp_name']; 
573             if (!copy($f['tmp_name'], $nf)) {
574                 print_r("failed to copy {$f['tmp_name']}...\n");
575             }
576         }
577         
578         
579         
580         $out = array(
581             'REQUEST_URI' => empty($_SERVER['REQUEST_URI']) ? 'cli' : $_SERVER['REQUEST_URI'],
582             'HTTP_USER_AGENT' => empty($_SERVER['HTTP_USER_AGENT']) ? '' : $_SERVER['HTTP_USER_AGENT'],
583             'GET' => empty($_GET) ? array() : $_GET,
584             'POST' =>$p,
585             'FILES' => $files,
586             
587         );
588         if (!empty(self::$deleted)) {
589             $out['DELETED_DATAOBJECTS'] = self::$deleted;
590         }
591         if ($extra_data !== false) {
592             $out['EXTRA'] = $extra_data;
593         }
594         if ( self::$extra_data !== false) {
595             $out['EXTRA_DATA'] =  self::$extra_data;
596         }
597         $total_data = 0;
598         foreach($out as $k=>$v) {
599             if (!empty($v) && $k != 'REQUEST_URI') {
600                 $total_data++;
601             }
602         }
603         if (!$total_data) {
604             return; // do not write an empty file with no usefull info.
605         }
606         
607         
608         file_put_contents($file, json_encode($out));
609         
610         
611     }
612     
613     function toRooArray( $q)
614     {
615         $ret = $this->toArray();
616         
617         // fill toEventString.
618         if (!empty($q['_with_obj_summary']) && !empty($this->on_id)) {
619             $obj = $this->object();
620               
621             if ($obj && $obj->pid() && method_exists($obj,'toEventString')) {
622                 $es = $obj->toEventString();
623                 
624                 if (empty($this->remarks) || strpos($this->remarks, $es) < 0) {
625                     $ret['remarks'] = $es . ' ' . $this->remarks;
626                 }
627             } else if (empty($this->remarks)){
628                 $ret['remarks'] = "DELETED";
629                 
630             }
631         }
632         //print_r($ret);
633         return $ret;
634         
635     }
636     
637     function toRooSingleArray($au, $q)
638     {
639         $ret = $this->toArray();
640         
641          
642         
643         if(empty($q['_retrieve_source'])){
644             return $ret;
645         }
646         
647         $file = $this->retrieveEventLog();
648         
649         if(!$file){
650             return "No records?!";
651         }
652         
653         $source = json_decode(file_get_contents($file));
654         
655         return $source;
656     }
657     
658     function retrieveEventLog()
659     {
660
661         $logdir = $this->logDir();
662         if (!$logdir) {
663             return false;
664          
665         }
666         
667         $date = date('/Y/m/d/', strtotime($this->event_when));
668         
669         $file = $logdir. $date. $this->id . ".json";
670         if (!file_exists($file)) {
671             
672             // try looking www-dir..
673             $file = $this->logDir('www-data'). $date. $this->id . ".json";
674             if (!file_exists($file)) {   
675                 return false;
676             }
677         }
678         
679         return $file;
680     }
681     
682     function restore($roo)
683     {
684         $file = $this->retrieveEventLog();
685         
686         if(empty($file) || !file_exists($file)){
687             $roo->jerr('Could not retrieve the event log file');
688         }
689         
690         $log = json_decode(file_get_contents($file), true);
691         
692         if(empty($log['POST']) || empty($log['POST']['_delete']) || empty($log['DELETED_DATAOBJECTS'])){
693             $roo->jerr('Invalid url');
694         }
695         
696         $restored = array();
697         
698         foreach ($log['DELETED_DATAOBJECTS'] as $d){
699             if(
700                     empty($d['id']) || 
701                     empty($d['_table']) || 
702                     (
703                             !empty($restored[$d['_table']]) && 
704                             in_array($d['id'], $restored[$d['_table']])
705                     )
706             ){
707                 continue;
708             }
709             
710             if(!isset($restored[$d['_table']])){
711                 $restored[$d['_table']] = array();
712             }
713             
714             $restored[$d['_table']][] = $d['id'];
715             
716             $table = DB_DataObject::factory($d['_table']);
717             
718             if (!is_a($table,'DB_DataObject')) {
719                 continue;
720             }
721             
722             unset($d['_table']);
723             
724             $table->setFrom($d);
725             
726             /*
727              * need to use the old id
728              */
729             $table->id = $d['id'];
730             
731             $table->sequenceKey(false,false);
732             
733             $table->insert();
734             
735             if($table->tableName() == 'crm_mailing_list_member'){
736                 $ml = DB_DataObject::factory('crm_mailing_list');
737                 if(!$ml->get($table->mailing_list_id)){
738                     continue;
739                 }
740
741                 $mlm = DB_DataObject::factory('crm_mailing_list_member');
742                 $mlm->setFrom(array(
743                     'mailing_list_id' => $table->mailing_list_id,
744                     'is_active' => 1
745                 ));
746
747                 $o = clone($ml);
748                 $ml->no_members = $mlm->count();
749                 $ml->update($o);
750             }
751         }
752         
753         $roo->jok('RESTORE');
754     }
755     function selectAddPersonEmail()
756     {
757         $this->selectAdd('join_person_id_id.email as email');
758         
759     }
760     
761     
762 }