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