3 * Table Definition for Events
5 * objects can implement relatedWhere(), which should return
6 * 'tablename' => array of ids
10 require_once 'DB/DataObject.php';
12 class Pman_Core_DataObjects_Events extends DB_DataObject
15 /* the code below is auto generated do not remove the above tag */
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
29 /* the code above is auto generated do not remove the tag below */
35 // ------------ROO HOOKS------------------------------------
36 function applyFilters($q, $au ,$roo)
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' ");
43 if (!empty($q['query']['to'])) {
44 $dt = date('Y-m-d' , strtotime($q['query']['to']));
45 $this->whereAdd(" {$tn}.event_when <= '$dt' ");
48 if (!empty($q['query']['grouped']) && $q['query']['grouped'] == 'gr') {
50 DB_DataObject::Debuglevel(1);
51 $this->groupBy('on_id');
53 (SELECT count(id) FROM core_event_audit WHERE event_id = Events.id) as changed
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;
64 // _join = tablename,tablename...
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..
72 if (isset($q['on_table']) && !strlen($q['on_table'])) {
73 // empty ontable queries.. these are valid..
74 $this->whereAdd("$tn.on_table = ''");
78 if (isset($q['query']['person_sum'])) {
79 //DB_DataObject::debugLevel(1);
80 $this->_extra_cols = array('qty' );
81 $this->selectAdd("count($tn.id) as qty");
82 $this->selectAdd("count( distinct $tn.on_id) as uqty");
83 $this->whereAdd('LENGTH(join_person_id_id.name) > 0 ');
84 $this->groupBy('person_id,join_person_id_id.name,join_person_id_id.email');
86 if (isset($q['query']['table_sum'])) {
87 //DB_DataObject::debugLevel(1);
88 $this->_extra_cols = array('qty' , 'uqty');
89 $this->selectAdd("count($tn.id) as qty");
90 $this->selectAdd("count( distinct $tn.on_table, $tn.on_id) as uqty");
92 $this->groupBy('on_table');
94 if (isset($q['query']['day_sum'])) {
95 //DB_DataObject::debugLevel(1);
96 $this->_extra_cols = array('qty' , 'uqty');
97 $this->selectAdd("DATE_FORMAT(event_when, '%Y-%m-%d') as on_day");
98 $this->selectAdd("count($tn.id) as qty");
99 $this->selectAdd("count( distinct $tn.on_id) as uqty");
101 $this->groupBy('on_day');
104 if (isset($q['_join'])) {
105 //DB_DataObject::DebugLevel(1);
106 $joins = explode(',',$q['_join']);
108 $this->selectAdd(); // ???
111 foreach($joins as $t) {
112 $t = preg_replace('/[^a-z_]+/', '', $t); // protection.
113 $x = DB_DataObject::Factory($t);
114 if (!is_a($x,'DB_DataObject')) {
117 $jtn = $x->tableName();
118 $jk = array_shift($x->keys());
121 LEFT JOIN {$jtn} as join_on_id_{$jtn} ON {$tn}.on_id = join_on_id_{$jtn}.{$jk}
122 AND on_table = '{$jtn}'
124 $keys = array_keys($x->table());
125 if (isset($q['_join_cols'])) {
126 $jcs = explode(',',$q['_join_cols'] );
127 //DB_DataObject::DebugLevel(1);
129 foreach($jcs as $jc) {
130 if (! in_array($jc, $keys)) {
136 $this->selectAdd( " join_on_id_{$jtn}.{$jc} as on_id_{$jc} ");
138 $this->selectAdd( " distinct(join_on_id_{$jtn}.{$jc} ) as on_id_{$jc} ");
141 $this->groupBy("on_id_{$jc} ");
142 $this->whereAdd("join_on_id_{$jtn}.{$jc} IS NOT NULL");
144 $this->selectAdd( "MAX(events.event_when) as event_when");
145 $this->orderBy('event_when DESC');
146 // $this->selectAs(array($q['_join_cols']) , 'on_id_%s', "join_on_id_{$jtn}");
148 $this->selectAs($x, 'on_id_%s', "join_on_id_{$jtn}");
157 if (isset($q['_related_on_id']) && isset($q['_related_on_table'])) {
158 // example: sales order - has invoices,
159 ///DB_DataObject::DebugLevel(1);
160 $ev =$this->factory('Events');
162 'on_id' => $q['_related_on_id'],
163 'on_table' => $q['_related_on_table'],
165 $obj = $ev->object();
168 $roo->jerr("ontable is invalid");
170 if (!method_exists($obj,'relatedWhere')) {
171 $roo->jerr( $q['_related_on_table'] . " Does not have method relatedWhere :" .
172 implode(',', get_class_methods($obj)));
174 if ($obj && method_exists($obj,'relatedWhere')) {
175 $ar = $obj->relatedWhere();
176 $tn = $this->tableName();
179 $w[] = "( {$tn}.on_table = '" .
180 $this->escape($q['_related_on_table']) .
181 "' AND {$tn}.on_id = ". ((int) $q['_related_on_id']) .
185 foreach($ar as $k=>$v) {
189 $w[] = "( {$tn}.on_table = '$k' AND {$tn}.on_id IN (". implode(',', $v). "))";
192 $this->whereAdd(implode(' OR ' , $w));
200 // since roo does not support autojoin yet..
201 if (!isset($q['_distinct'])) {
202 $this->autoJoinExtra();
210 function autoJoinExtra()
212 //$ret = parent::autoJoin();
213 // DB_DataObject::debugLevel(1);
215 // now try and magically join person_table to the right table..
217 // this does not work on postgres..
218 $tn = $this->tableName();
219 $pt = DB_DataObject::Factory($this->tableName());
221 $pt->selectAdD('distinct(person_table) as person_table');
222 $pt->whereAdd('person_table IS NOT NULL AND LENGTH(person_table) > 0');
223 $tbls = $pt->fetchAll('person_table');
224 $pers = DB_DataObject::Factory('Person');
225 $ptbl = $pers->tableName();
226 if (!in_array($ptbl,$tbls)) {
230 foreach($tbls as $tbl) {
232 // find all the columns from the joined table..
233 $st = DB_DataObject::Factory($tbl);
234 $tcols = array_keys($st->table());
236 $cond = "{$tn}.person_table = '{$tbl}'";
238 $cond = "( $cond OR {$tn}.person_table = '')";
241 foreach($tcols as $col) {
242 if ($col == 'passwd') {
245 $cols[$col] = isset($cols[$col] ) ? $cols[$col] : array();
246 $cols[$col][] = "WHEN $cond THEN join_person_table_{$tbl}.{$col}";
248 // id's are hard coded...
251 LEFT JOIN {$tbl} AS join_person_table_{$tbl}
252 ON {$tn}.person_id = join_person_table_{$tbl}.id
256 foreach($cols as $col=>$whens) {
260 ". implode("\n", $whens) ."
263 as person_table_{$col}"
272 * check who is trying to access this. false == access denied..
273 * @return {boolean} true if access is allowed.
275 function checkPerm($lvl, $au)
280 // listing is controleed by applyfilters..
281 return $au->hasPerm("Admin.Admin_Tab", 'S');
285 * return the object that this relates to.
287 * @return {DB_DataObject} related object
291 $o = DB_DataObject::factory($this->on_table);
292 $o->get($this->on_id);
300 * Initialize an event - ready to insert..
302 * @param {String} action - group/name of event
303 * @param {DataObject|false} obj - dataobject action occured on.
304 * @param {String} any remarks
307 function init($act, $obj, $remarks)
309 $ff = HTML_FlexyFramework::get();
311 $au = $pg->getAuthUser();
313 if ($ff->cli) { // && empty($au) && isset($obj->person_id)) {
315 // $au = DB_DataObject::Factory('Person'); // not always a person..
316 // $au->get($obj->person_id);
319 $this->person_name = $au && !empty($au->name) ? $au->name : '';
320 $this->person_id = $au ? $au->id : -1;
321 $this->person_table = $au ? $au->tableName() : '';
322 $this->ipaddr = isset($_SERVER["REMOTE_ADDR"]) ? $_SERVER["REMOTE_ADDR"] : 'cli';
323 $this->action = $act;
324 $this->on_table = $obj ? $obj->tableName() : '';
325 $pk = $obj ? $obj->keys() : false;
326 $this->on_id = $obj && $pk ? $obj->{$pk[0]}: 0;
328 // should this really go in remarks? -
329 if ($obj && method_exists($obj,'toEventString')) {
330 $rem[] = $obj->toEventString() ;
333 $this->remarks = implode(' : ', $rem);
337 * Generate an audit for this field.
339 * @param {DB_DataObject} new data
340 * @param {DB_DataObject} old data
342 * @return {int} number of entries logged.
345 function audit($new, $old = false)
348 return 0; // they are the same...
352 foreach(array_keys($new->table()) as $k) {
353 // should we JSON serialize this?
354 $n = empty($new->$k) ? '' : $new->$k;
355 $o = empty($old->$k) || empty($old->$k) ? '' : $old->$k;
359 $this->auditField($k, $o, $n, $old);
365 * Record an audited change, in theory so we can audit data that is not just
368 * @param {string} $name table field anme
369 * @param {mixed} $ov old value
370 * @param {mixed} $onv new value
371 * @param {mixed} $old old object (false if we are creating..)
373 function auditField($name, $ov, $nv, $old=false )
376 if (is_object($nv)) {
381 $x = DB_DataObject::factory('core_event_audit');
383 'event_id' => $this->id,
385 'old_audit_id' => $old ? $x->findLast($this, $name) : 0,
395 function onInsert($request,$roo)
397 $this->writeEventLog();
400 function writeEventLog()
402 $ff = HTML_FlexyFramework::get();
403 if (empty($ff->Pman['event_log_dir'])) {
407 // add user (eg. www-data or local user if not..)
408 if (function_exists('posix_getpwuid')) {
409 $uinfo = posix_getpwuid( posix_getuid () );
411 $user = $uinfo['name'];
413 $user = getenv('USERNAME'); // windows.
416 $file = $ff->Pman['event_log_dir']. '/'. $user. date('/Y/m/d/'). $this->id . ".json";
417 if (!file_exists(dirname($file))) {
418 mkdir(dirname($file),0700,true);
421 // Remove all the password from logs...
422 $p = empty($_POST) ? array() : $_POST;
423 foreach(array('passwd', 'password', 'passwd2', 'password2') as $rm) {
424 if (isset($p[$rm])) {
425 $p['passwd'] = '******';
430 foreach ($_FILES as $k=>$f){
431 if (empty($f['tmp_name']) || !file_exists($f['tmp_name'])) {
436 $files[$k]['tmp_name'] = $this->id . '.file_'. $i.'.jpg';
437 $nf = $ff->Pman['event_log_dir']. '/'. $this->id . ".file_$i.jpg";
438 if (!copy($f['tmp_name'], $nf)) {
439 print_r("failed to copy {$f['tmp_name']}...\n");
443 file_put_contents($file, json_encode(array(
444 'REQUEST_URI' => empty($_SERVER['REQUEST_URI']) ? 'cli' : $_SERVER['REQUEST_URI'],
445 'GET' => empty($_GET) ? array() : $_GET,