DataObjects/pman.links.ini
[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      
39         $tn = $this->tableName();
40         if (!empty($q['query']['from'])) {
41             $dt = date('Y-m-d' , strtotime($q['query']['from']));
42             $this->whereAdd(" {$tn}.event_when >=  '$dt' ");
43         }
44         if (!empty($q['query']['to'])) {
45             $dt = date('Y-m-d' , strtotime($q['query']['to']));
46             $this->whereAdd(" {$tn}.event_when <=  '$dt' ");
47         }
48         /*
49         if (!empty($q['query']['grouped']) && $q['query']['grouped'] == 'gr') {
50             // grouped..
51             DB_DataObject::Debuglevel(1);
52             $this->groupBy('on_id');
53             $this->selectAdd('
54                 (SELECT count(id) FROM core_event_audit WHERE event_id = Events.id) as changed
55                 ');
56         }
57         */
58         
59         if (!$au->hasPerm("Admin.Admin_Tab", 'S')) {
60             //DB_DataObject::DebugLevel(1);
61             // they can only view their changes..
62             $this->person_id = $au->id;
63             
64         }
65         // _join = tablename,tablename...
66         
67         /// on_table=cohead
68         //   &_join=cohead
69         //   &_join_cols=cohead_number
70         //    &_columns=on_id_cohead_number,event_when << this is ignored at present.
71         // max(event_when) is not supported... by any query yet..
72         
73         if (isset($q['on_table']) && !strlen($q['on_table'])) {
74             // empty ontable queries.. these are valid..
75             $this->whereAdd("$tn.on_table = ''");
76         }
77         
78         // if not empty on_table
79         if(!empty($q['person_table'])){
80             $jt = DB_DataObject::factory($q['person_table']);
81         
82             //$jt = DB_DataObjec factory person_ontable
83             
84             $this->_join = "LEFT JOIN {$jt->tableName()} AS join_person_id_id ON (join_person_id_id.id=Events.person_id)";
85             //$item = DB_DataObject::factory('')
86 //            $this->_join .= '
87 //                LEFT JOIN
88 //                    crm_action as join_crm_action_updated
89 //                ON
90 //                    join_crm_action_updated.id = join_person_id_id.crm_updated_action_id
91 //            ';
92             //$item = DB_DataObject::Factory('crm_action');
93             $this->selectAs($jt, 'person_id_%s', 'join_person_id_id');
94
95             //$this->person_table = $q['person_table'];
96             // $this->_join
97         
98         }
99         
100         if (isset($q['query']['person_sum'])) {
101             //DB_DataObject::debugLevel(1);
102             $this->_extra_cols = array('qty' );
103             $this->selectAdd("count($tn.id) as qty");
104             $this->selectAdd("count( distinct $tn.on_id) as uqty");
105             $this->whereAdd('LENGTH(join_person_id_id.name) > 0 ');
106             $this->groupBy('person_id,join_person_id_id.name,join_person_id_id.email');
107         }
108          if (isset($q['query']['table_sum'])) {
109             //DB_DataObject::debugLevel(1);
110             $this->_extra_cols = array('qty' , 'uqty');
111             $this->selectAdd("count($tn.id) as qty");
112             $this->selectAdd("count( distinct $tn.on_table, $tn.on_id) as uqty");
113             
114             $this->groupBy('on_table');
115         }
116          if (isset($q['query']['day_sum'])) {
117             //DB_DataObject::debugLevel(1);
118             $this->_extra_cols = array('qty' , 'uqty');
119             $this->selectAdd("DATE_FORMAT(event_when, '%Y-%m-%d') as on_day");
120             $this->selectAdd("count($tn.id) as qty");
121             $this->selectAdd("count( distinct $tn.on_id) as uqty");
122             
123             $this->groupBy('on_day');
124         }
125         
126         if (isset($q['_join'])) {
127             //DB_DataObject::DebugLevel(1);
128             $joins = explode(',',$q['_join']);
129             
130             $this->selectAdd(); // ???
131             $distinct = false;
132             
133             foreach($joins as $t) {
134                 $t = preg_replace('/[^a-z_]+/', '', $t); // protection.
135                 $x = DB_DataObject::Factory($t);
136                 if (!is_a($x,'DB_DataObject')) {
137                     continue;
138                 }
139                 $jtn = $x->tableName();
140                 $jk = array_shift($x->keys());
141                 $this->_join .= "
142                 
143                     LEFT JOIN {$jtn} as join_on_id_{$jtn} ON {$tn}.on_id = join_on_id_{$jtn}.{$jk}
144                         AND on_table = '{$jtn}'
145                 ";
146                 $keys = array_keys($x->table());
147                 if (isset($q['_join_cols'])) {
148                     $jcs = explode(',',$q['_join_cols'] );
149                     //DB_DataObject::DebugLevel(1);
150                     
151                     foreach($jcs as $jc) { 
152                         if (! in_array($jc, $keys)) {
153                             continue;
154                         }
155                         if ($distinct) { 
156                         
157                        
158                             $this->selectAdd( " join_on_id_{$jtn}.{$jc}   as on_id_{$jc} ");
159                         } else {
160                             $this->selectAdd( " distinct(join_on_id_{$jtn}.{$jc}  ) as on_id_{$jc} ");
161                             $distinct = true;
162                         }
163                         $this->groupBy("on_id_{$jc} ");
164                         $this->whereAdd("join_on_id_{$jtn}.{$jc} IS NOT NULL");
165                     }
166                     $this->selectAdd( "MAX(events.event_when) as event_when");
167                     $this->orderBy('event_when DESC');
168                    // $this->selectAs(array($q['_join_cols']) , 'on_id_%s', "join_on_id_{$jtn}");
169                 } else { 
170                     $this->selectAs($x, 'on_id_%s', "join_on_id_{$jtn}");
171                 }
172             }
173                 
174                 
175             
176             
177         }
178         
179         if (isset($q['_related_on_id']) && isset($q['_related_on_table'])) {
180             // example: sales order - has invoices,
181             ///DB_DataObject::DebugLevel(1);
182             $ev  =$this->factory('Events');
183             $ev->setFrom(array(
184                 'on_id' => $q['_related_on_id'],
185                 'on_table' => $q['_related_on_table'],
186                                ));
187             $obj = $ev->object();
188             
189             if (!$obj) {
190                 $roo->jerr("ontable is invalid");
191             }
192             if (!method_exists($obj,'relatedWhere')) {
193                 $roo->jerr( $q['_related_on_table'] . " Does not have method relatedWhere :" .
194                            implode(',', get_class_methods($obj)));
195             }
196             if ($obj && method_exists($obj,'relatedWhere')) {
197                 $ar = $obj->relatedWhere();
198                 $tn = $this->tableName();
199                 
200                 $w = array();
201                 $w[] = "( {$tn}.on_table = '" .
202                         $this->escape($q['_related_on_table']) .
203                         "' AND {$tn}.on_id = ". ((int)  $q['_related_on_id']) .
204                     ")";
205                 
206                 
207                 foreach($ar as $k=>$v) {
208                     if (empty($v)) {
209                         continue;
210                     }                
211                      $w[] = "( {$tn}.on_table = '$k' AND {$tn}.on_id IN (". implode(',', $v). "))";
212                     
213                 }
214                 $this->whereAdd(implode(' OR ' , $w));
215             }
216             
217             
218             
219             
220             
221         }
222         // since roo does not support autojoin yet..
223         if (!isset($q['_distinct'])) {
224             //$this->autoJoinExtra();
225         }
226         
227         
228         
229             
230     }
231      
232 //    function autoJoinExtra()
233 //    {
234 //        //$ret = parent::autoJoin();
235 //        // DB_DataObject::debugLevel(1);
236 //        
237 //        // now try and magically join person_table to the right table..
238 //        return;
239 //        // this does not work on postgres.. 
240 //        $tn = $this->tableName();
241 //        $pt = DB_DataObject::Factory($this->tableName());
242 //        $pt->selectAdD();
243 //        $pt->selectAdD('distinct(person_table) as person_table');
244 //        $pt->whereAdd('person_table IS NOT NULL AND LENGTH(person_table) > 0');
245 //        $tbls = $pt->fetchAll('person_table');
246 //        $pers = DB_DataObject::Factory('Person');
247 //        $ptbl = $pers->tableName();
248 //        if (!in_array($ptbl,$tbls)) {
249 //            $tbls[] = $ptbl;
250 //            
251 //        }
252 //        foreach($tbls as $tbl) {
253 //            
254 //            // find all the columns from the joined table..
255 //            $st = DB_DataObject::Factory($tbl);
256 //            $tcols = array_keys($st->table());
257 //            
258 //            $cond = "{$tn}.person_table = '{$tbl}'";
259 //            if ($tbl == $ptbl) {
260 //                $cond = "( $cond OR {$tn}.person_table  = '')";
261 //            }
262 //            
263 //            foreach($tcols as $col) {
264 //                if ($col == 'passwd') {
265 //                    continue;
266 //                }
267 //                $cols[$col]  = isset($cols[$col] ) ? $cols[$col]  : array();
268 //                $cols[$col][] = "WHEN $cond  THEN join_person_table_{$tbl}.{$col}";
269 //            }
270 //            // id's are hard coded...
271 //            
272 //            $this->_join .= "
273 //                LEFT JOIN {$tbl} AS  join_person_table_{$tbl}
274 //                    ON {$tn}.person_id = join_person_table_{$tbl}.id
275 //                        AND $cond
276 //            ";
277 //        }
278 //        foreach($cols as $col=>$whens) {
279 //            
280 //            $this->selectAdd("
281 //                    CASE
282 //                        ". implode("\n", $whens) ." 
283 //                        ELSE ''
284 //                    END
285 //                    as person_table_{$col}"
286 //            );
287 //        }
288 //        //return $ret;
289 //         
290 //    }
291     
292     
293     /**
294      * check who is trying to access this. false == access denied..
295      * @return {boolean} true if access is allowed.
296      */
297     function checkPerm($lvl, $au) 
298     {
299         if ($lvl == 'S') {
300             return true;
301         }
302         // listing is controleed by applyfilters..
303         return $au->hasPerm("Admin.Admin_Tab", 'S');
304     }
305     /**
306      * object :
307      * return the object that this relates to.
308      * 
309      * @return {DB_DataObject} related object
310      */
311     function object()
312     {
313         $o = DB_DataObject::factory($this->on_table);
314         $o->get($this->on_id);
315         return $o;
316         
317     }
318     
319     
320     /**
321      * init:
322      * Initialize an event - ready to insert..
323      * 
324      * @param {String} action  - group/name of event
325      * @param {DataObject|false} obj - dataobject action occured on.
326      * @param {String} any remarks 
327      */
328     
329     function init($act, $obj, $remarks)
330     {
331         $ff = HTML_FlexyFramework::get();
332         $pg = $ff->page;
333         $au = $pg->getAuthUser();
334         
335         if ($ff->cli) { // && empty($au) && isset($obj->person_id)) {
336             $au = false;
337            // $au = DB_DataObject::Factory('Person'); // not always a person..
338            // $au->get($obj->person_id);
339         } 
340           
341         $this->person_name = $au && !empty($au->name) ? $au->name : '';
342         $this->person_id = $au ? $au->id : -1;
343         $this->person_table = $au ? $au->tableName() : '';
344         $this->ipaddr = isset($_SERVER["REMOTE_ADDR"]) ? $_SERVER["REMOTE_ADDR"] : 'cli';
345         $this->action = $act;
346         $this->on_table = $obj ? $obj->tableName() : '';
347         $pk = $obj ? $obj->keys()  : false;
348         $this->on_id  = $obj && $pk ? $obj->{$pk[0]}: 0;
349         $rem  = array();
350         // should this really go in remarks? - 
351         if ($obj && method_exists($obj,'toEventString')) {
352             $rem[] = $obj->toEventString() ;
353         }
354         $rem[] = $remarks;
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->table()) 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     
416     
417     function onInsert($request,$roo)
418     {
419         $this->writeEventLog();
420     }
421     
422     function writeEventLog()
423     {
424         $ff  = HTML_FlexyFramework::get();
425         if (empty($ff->Pman['event_log_dir'])) {
426             return false;
427         }
428         
429         // add user (eg. www-data or local user if not..)
430         if (function_exists('posix_getpwuid')) {
431             $uinfo = posix_getpwuid( posix_getuid () ); 
432          
433             $user = $uinfo['name'];
434         } else {
435             $user = getenv('USERNAME'); // windows.
436         }
437         //print_r($this);
438         $file = $ff->Pman['event_log_dir']. '/'. $user. date('/Y/m/d/'). $this->id . ".json";
439         if (!file_exists(dirname($file))) {
440             mkdir(dirname($file),0700,true);
441         }
442         
443         // Remove all the password from logs...
444         $p =  empty($_POST) ? array() : $_POST;
445         foreach(array('passwd', 'password', 'passwd2', 'password2') as $rm) {
446             if (isset($p[$rm])) {
447                 $p['passwd'] = '******';
448             }
449         }
450         $i=0;
451         $files = array();
452         foreach ($_FILES as $k=>$f){
453             if (empty($f['tmp_name']) || !file_exists($f['tmp_name'])) {
454                 continue;
455             }
456             $i++;
457             $files[$k] = $f;
458             $files[$k]['tmp_name'] = $this->id . '.file_'. $i.'.jpg';
459             $nf = $ff->Pman['event_log_dir']. '/'. $this->id . ".file_$i.jpg";
460             if (!copy($f['tmp_name'], $nf)) {
461                 print_r("failed to copy {$f['tmp_name']}...\n");
462             }
463         }
464         
465         file_put_contents($file, json_encode(array(
466             'REQUEST_URI' => empty($_SERVER['REQUEST_URI']) ? 'cli' : $_SERVER['REQUEST_URI'],
467             'GET' => empty($_GET) ? array() : $_GET,
468             'POST' =>$p,
469             'FILES' => $files,
470         )));
471         
472     }
473     
474     
475 }