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