DataObjects/Events.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
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)
37     {
38         $tn = $this->tableName();
39         if (!empty($q['query']['from'])) {
40             $dt = date('Y-m-d' , strtotime($q['query']['from']));
41             $this->whereAdd(" {$tn}.event_when >=  '$dt' ");
42         }
43         if (!empty($q['query']['to'])) {
44             $dt = date('Y-m-d' , strtotime($q['query']['to']));
45             $this->whereAdd(" {$tn}.event_when <=  '$dt' ");
46         }
47         /*
48         if (!empty($q['query']['grouped']) && $q['query']['grouped'] == 'gr') {
49             // grouped..
50             DB_DataObject::Debuglevel(1);
51             $this->groupBy('on_id');
52             $this->selectAdd('
53                 (SELECT count(id) FROM core_event_audit WHERE event_id = Events.id) as changed
54                 ');
55         }
56         */
57         
58         if (!$au->hasPerm("Admin.Admin_Tab", 'S')) {
59             //DB_DataObject::DebugLevel(1);
60             // they can only view their changes..
61             $this->person_id = $au->id;
62             
63         }
64         // _join = tablename,tablename...
65         
66         /// on_table=cohead
67         //   &_join=cohead
68         //   &_join_cols=cohead_number
69         //    &_columns=on_id_cohead_number,event_when << this is ignored at present.
70         // max(event_when) is not supported... by any query yet..
71         
72         if (isset($q['query']['person_sum'])) {
73             $this->selectAdd("sum($tn.id) as qty");
74             $this->groupBy('person_id');
75         }
76         
77         
78         
79         if (isset($q['_join'])) {
80             //DB_DataObject::DebugLevel(1);
81             $joins = explode(',',$q['_join']);
82             
83             $this->selectAdd(); // ???
84             $distinct = false;
85             
86             foreach($joins as $t) {
87                 $t = preg_replace('/[^a-z_]+/', '', $t); // protection.
88                 $x = DB_DataObject::Factory($t);
89                 if (!is_a($x,'DB_DataObject')) {
90                     continue;
91                 }
92                 $jtn = $x->tableName();
93                 $jk = array_shift($x->keys());
94                 $this->_join .= "
95                 
96                     LEFT JOIN {$jtn} as join_on_id_{$jtn} ON {$tn}.on_id = join_on_id_{$jtn}.{$jk}
97                         AND on_table = '{$jtn}'
98                 ";
99                 $keys = array_keys($x->table());
100                 if (isset($q['_join_cols'])) {
101                     $jcs = explode(',',$q['_join_cols'] );
102                     //DB_DataObject::DebugLevel(1);
103                     
104                     foreach($jcs as $jc) { 
105                         if (! in_array($jc, $keys)) {
106                             continue;
107                         }
108                         if ($distinct) { 
109                         
110                        
111                             $this->selectAdd( " join_on_id_{$jtn}.{$jc}   as on_id_{$jc} ");
112                         } else {
113                             $this->selectAdd( " distinct(join_on_id_{$jtn}.{$jc}  ) as on_id_{$jc} ");
114                             $distinct = true;
115                         }
116                         $this->groupBy("on_id_{$jc} ");
117                         $this->whereAdd("join_on_id_{$jtn}.{$jc} IS NOT NULL");
118                     }
119                     $this->selectAdd( "MAX(events.event_when) as event_when");
120                     $this->orderBy('event_when DESC');
121                    // $this->selectAs(array($q['_join_cols']) , 'on_id_%s', "join_on_id_{$jtn}");
122                 } else { 
123                     $this->selectAs($x, 'on_id_%s', "join_on_id_{$jtn}");
124                 }
125             }
126                 
127                 
128             
129             
130         }
131         
132         if (isset($q['_related_on_id']) && isset($q['_related_on_table'])) {
133             // example: sales order - has invoices,
134             $ev  =$this->factory('Events');
135             $ev->setFrom(array(
136                 'on_id' => $q['_related_on_id'],
137                 'on_table' => $q['_related_on_table'],
138                                ));
139             $obj = $ev->object();
140             
141             if ($obj && method_exists($obj,'relatedWhere')) {
142                 $ar = $obj->relatedWhere();
143                 $tn = $this->tableName();
144                 
145                 $w = array();
146                 $w[] = "( {$tn}.on_table = '" .
147                         $this->escape($q['_related_on_table']) .
148                         "' AND {$tn}.on_id = ". ((int)  $q['_related_on_id']) .
149                     ")";
150                 
151                 
152                 foreach($ar as $k=>$v) {
153                     if (empty($v)) {
154                         continue;
155                     }                
156                      $w[] = "( {$tn}.on_table = '$k' AND {$tn}.on_id IN (". implode(',', $v). "))";
157                     
158                 }
159                 $this->whereAdd(implode(' OR ' , $w));
160             }
161             
162             
163             
164             
165             
166         }
167         
168         
169         
170         
171         
172             
173     }
174     /**
175      * check who is trying to access this. false == access denied..
176      * @return {boolean} true if access is allowed.
177      */
178     function checkPerm($lvl, $au) 
179     {
180         if ($lvl == 'S') {
181             return true;
182         }
183         // listing is controleed by applyfilters..
184         return $au->hasPerm("Admin.Admin_Tab", 'S');
185     }
186     /**
187      * object :
188      * return the object that this relates to.
189      * 
190      * @return {DB_DataObject} related object
191      */
192     function object()
193     {
194         $o = DB_DataObject::factory($this->on_table);
195         $o->get($this->on_id);
196         return $o;
197         
198     }
199     
200     
201     /**
202      * init:
203      * Initialize an event - ready to insert..
204      * 
205      * @param {String} action  - group/name of event
206      * @param {DataObject|false} obj - dataobject action occured on.
207      * @param {String} any remarks 
208      */
209     
210     function init($act, $obj, $remarks)
211     {
212         $ff = HTML_FlexyFramework::get();
213         $pg = $ff->page;
214         $au = $pg->getAuthUser();
215         
216         if ($ff->cli && empty($au) && isset($obj->person_id)) {
217             $au = DB_DataObject::Factory('Person'); // not always a person..
218             $au->get($obj->person_id);
219         } 
220          
221          
222          
223         $this->person_name = $au && !empty($au->name) ? $au->name : '';
224         $this->person_id = $au ? $au->id : '';
225         $this->ipaddr = isset($_SERVER["REMOTE_ADDR"]) ? $_SERVER["REMOTE_ADDR"] : 'cli';
226         $this->action = $act;
227         $this->on_table = $obj ? $obj->tableName() : '';
228         $pk = $obj ? $obj->keys()  : false;
229         $this->on_id  = $obj && $pk ? $obj->{$pk[0]}: 0;
230         $rem  = array();
231         // should this really go in remarks? - 
232         if ($obj && method_exists($obj,'toEventString')) {
233             $rem[] = $obj->toEventString() ;
234         }
235         $rem[] = $remarks;
236         $this->remarks = implode(' : ', $rem);
237     }
238     
239     /**
240      * Generate an audit for this field.
241      *
242      * @param {DB_DataObject} new data
243      * @param {DB_DataObject} old data
244      * 
245      * @return {int} number of entries logged.
246      */
247     
248     function audit($new, $old = false)
249     {
250         if ($old == $new) {
251             return 0; // they are the same...
252         }
253          
254         $ret = 0;
255         foreach(array_keys($new->table()) as $k) {
256             // should we JSON serialize this?
257             $n = empty($new->$k) ? '' : $new->$k;
258             $o = empty($old->$k) || empty($old->$k) ? '' : $old->$k;
259             if ($n == $o) {
260                 continue;
261             }
262             $this->auditField($k, $o, $n, $old);
263             $ret++;
264         }
265         return $ret;
266     }
267     /**
268      * Record an audited change, in theory so we can audit data that is not just
269      * database Fields...
270      *
271      * @param {string} $name    table field anme
272      * @param {mixed} $ov  old value
273      * @param {mixed} $onv  new value
274      * @param {mixed} $old  old object (false if we are creating..)
275      */
276     function auditField($name, $ov, $nv, $old=false )
277     {
278         $x = DB_DataObject::factory('core_event_audit');
279         $x->setFrom(array(
280             'event_id' => $this->id,
281             'name' => $name,
282             'old_audit_id' => $old ? $x->findLast($this, $name) : 0,
283             'newvalue' => $nv
284
285         ));
286         $x->insert();
287     
288     }
289 }