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
27 public $person_table; // string(64)
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 not empty on_table
40 if(!empty($q['person_table'])){
41 $jt = DB_DataObject::factory($q['person_table']);
43 $this->_join = "LEFT JOIN {$jt->tableName()} AS join_person_id_id ON (join_person_id_id.id=Events.person_id)";
47 $this->selectAs($jt, 'person_id_%s', 'join_person_id_id');
49 if (method_exists($jt,'nameColumn')) {
50 $this->selectAdd("join_person_id_id.{$jt->nameColumn()} as person_id_name");
56 $cfg = HTML_FlexyFramework::get()->Pman;
57 if (!empty($cfg['authTable'])) {
58 $person =$cfg['authTable'];
61 $jt = DB_DataObject::factory($person);
63 person_table = '{$jt->tableName()}'
66 OR person_table IS NULL"
67 ); // default to our standard.. - unless otherwise requested..
71 if (!empty($q['query']['from'])) {
72 $dt = date('Y-m-d' , strtotime($q['query']['from']));
73 $this->whereAdd(" {$tn}.event_when >= '$dt' ");
75 if (!empty($q['query']['to'])) {
76 $dt = date('Y-m-d' , strtotime($q['query']['to']));
77 $this->whereAdd(" {$tn}.event_when <= '$dt' ");
80 if (!empty($q['query']['grouped']) && $q['query']['grouped'] == 'gr') {
82 DB_DataObject::Debuglevel(1);
83 $this->groupBy('on_id');
85 (SELECT count(id) FROM core_event_audit WHERE event_id = Events.id) as changed
90 if (!$au->hasPerm("Admin.Admin_Tab", 'S')) {
91 //DB_DataObject::DebugLevel(1);
92 // they can only view their changes..
93 $this->person_id = $au->id;
96 // _join = tablename,tablename...
100 // &_join_cols=cohead_number
101 // &_columns=on_id_cohead_number,event_when << this is ignored at present.
102 // max(event_when) is not supported... by any query yet..
104 if (isset($q['on_table']) && !strlen($q['on_table'])) {
105 // empty ontable queries.. these are valid..
106 $this->whereAdd("$tn.on_table = ''");
111 if (isset($q['query']['person_sum'])) {
112 //DB_DataObject::debugLevel(1);
113 $this->_extra_cols = array('qty' );
114 $this->selectAdd("count($tn.id) as qty");
115 $this->selectAdd("count( distinct $tn.on_id) as uqty");
116 $this->whereAdd('LENGTH(join_person_id_id.name) > 0 ');
117 $this->groupBy('person_id,join_person_id_id.name,join_person_id_id.email');
119 if (isset($q['query']['table_sum'])) {
120 //DB_DataObject::debugLevel(1);
121 $this->_extra_cols = array('qty' , 'uqty');
122 $this->selectAdd("count($tn.id) as qty");
123 $this->selectAdd("count( distinct $tn.on_table, $tn.on_id) as uqty");
125 $this->groupBy('on_table');
127 if (isset($q['query']['day_sum'])) {
128 //DB_DataObject::debugLevel(1);
129 $this->_extra_cols = array('qty' , 'uqty');
130 $this->selectAdd("DATE_FORMAT(event_when, '%Y-%m-%d') as on_day");
131 $this->selectAdd("count($tn.id) as qty");
132 $this->selectAdd("count( distinct $tn.on_id) as uqty");
134 $this->groupBy('on_day');
137 if (isset($q['_join'])) {
138 //DB_DataObject::DebugLevel(1);
139 $joins = explode(',',$q['_join']);
141 $this->selectAdd(); // ???
144 foreach($joins as $t) {
145 $t = preg_replace('/[^a-z_]+/', '', $t); // protection.
146 $x = DB_DataObject::Factory($t);
147 if (!is_a($x,'DB_DataObject')) {
150 $jtn = $x->tableName();
151 $jk = array_shift($x->keys());
154 LEFT JOIN {$jtn} as join_on_id_{$jtn} ON {$tn}.on_id = join_on_id_{$jtn}.{$jk}
155 AND on_table = '{$jtn}'
157 $keys = array_keys($x->table());
158 if (isset($q['_join_cols'])) {
159 $jcs = explode(',',$q['_join_cols'] );
160 //DB_DataObject::DebugLevel(1);
162 foreach($jcs as $jc) {
163 if (! in_array($jc, $keys)) {
169 $this->selectAdd( " join_on_id_{$jtn}.{$jc} as on_id_{$jc} ");
171 $this->selectAdd( " distinct(join_on_id_{$jtn}.{$jc} ) as on_id_{$jc} ");
174 $this->groupBy("on_id_{$jc} ");
175 $this->whereAdd("join_on_id_{$jtn}.{$jc} IS NOT NULL");
177 $this->selectAdd( "MAX(events.event_when) as event_when");
178 $this->orderBy('event_when DESC');
179 // $this->selectAs(array($q['_join_cols']) , 'on_id_%s', "join_on_id_{$jtn}");
181 $this->selectAs($x, 'on_id_%s', "join_on_id_{$jtn}");
188 if (isset($q['_related_on_id']) && isset($q['_related_on_table'])) {
189 // example: sales order - has invoices,
190 ///DB_DataObject::DebugLevel(1);
191 $ev =$this->factory('Events');
193 'on_id' => $q['_related_on_id'],
194 'on_table' => $q['_related_on_table'],
196 $obj = $ev->object();
199 $roo->jerr("ontable is invalid");
201 if (!method_exists($obj,'relatedWhere')) {
202 $roo->jerr( $q['_related_on_table'] . " Does not have method relatedWhere :" .
203 implode(',', get_class_methods($obj)));
205 if ($obj && method_exists($obj,'relatedWhere')) {
206 $ar = $obj->relatedWhere();
207 $tn = $this->tableName();
210 $w[] = "( {$tn}.on_table = '" .
211 $this->escape($q['_related_on_table']) .
212 "' AND {$tn}.on_id = ". ((int) $q['_related_on_id']) .
216 foreach($ar as $k=>$v) {
220 $w[] = "( {$tn}.on_table = '$k' AND {$tn}.on_id IN (". implode(',', $v). "))";
223 $this->whereAdd(implode(' OR ' , $w));
231 // since roo does not support autojoin yet..
232 if (!isset($q['_distinct'])) {
233 //$this->autoJoinExtra();
236 if(!empty($q['query']['action'])) {
237 $act = $this->escape($q['query']['action']);
238 $this->whereAdd("Events.action LIKE '%{$act}%'");
241 if(!empty($q['query']['on_table'])) {
242 $tnb = $this->escape($q['query']['on_table']);
243 $this->whereAdd("Events.on_table LIKE '%{$tnb}%'");
251 * check who is trying to access this. false == access denied..
252 * @return {boolean} true if access is allowed.
254 function checkPerm($lvl, $au)
259 // listing is controleed by applyfilters..
260 return $au->hasPerm("Admin.Admin_Tab", 'S');
264 * return the object that this relates to.
266 * @return {DB_DataObject} related object
270 $o = DB_DataObject::factory($this->on_table);
271 $o->get($this->on_id);
279 * Initialize an event - ready to insert..
281 * @param {String} action - group/name of event
282 * @param {DataObject|false} obj - dataobject action occured on.
283 * @param {String} any remarks
286 function init($act, $obj, $remarks)
288 $ff = HTML_FlexyFramework::get();
290 $au = $pg->getAuthUser();
292 if ($ff->cli) { // && empty($au) && isset($obj->person_id)) {
294 // $au = DB_DataObject::Factory('Person'); // not always a person..
295 // $au->get($obj->person_id);
298 $this->person_name = $au && !empty($au->name) ? $au->name : '';
299 if (isset($au->id) && empty($au->id)) {
300 // not authenticated - and a standard id based object
301 $this->person_id = 0;
303 $this->person_id = $au ? (!empty($au->id) ? $au->id : $au->pid()) : -1;
305 $this->person_table = $au ? $au->tableName() : '';
306 $this->ipaddr = isset($_SERVER["REMOTE_ADDR"]) ? $_SERVER["REMOTE_ADDR"] : 'cli';
307 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
308 $this->ipaddr = $_SERVER['HTTP_X_FORWARDED_FOR'];
311 $this->action = $act;
312 $this->on_table = $obj ? $obj->tableName() : '';
313 $pk = $obj ? $obj->keys() : false;
314 $this->on_id = $obj && $pk ? $obj->{$pk[0]}: 0;
316 // should this really go in remarks? -
317 if ($obj && method_exists($obj,'toEventString')) {
318 $rem[] = $obj->toEventString() ;
321 $this->remarks = implode(' : ', $rem);
325 * Generate an audit for this field.
327 * @param {DB_DataObject} new data
328 * @param {DB_DataObject} old data
330 * @return {int} number of entries logged.
333 function audit($new, $old = false)
336 return 0; // they are the same...
340 foreach(array_keys($new->table()) as $k) {
341 // should we JSON serialize this?
342 $n = empty($new->$k) ? '' : $new->$k;
343 $o = empty($old->$k) || empty($old->$k) ? '' : $old->$k;
347 $this->auditField($k, $o, $n, $old);
353 * Record an audited change, in theory so we can audit data that is not just
356 * @param {string} $name table field anme
357 * @param {mixed} $ov old value
358 * @param {mixed} $onv new value
359 * @param {mixed} $old old object (false if we are creating..)
361 function auditField($name, $ov, $nv, $old=false )
364 if (is_object($nv)) {
369 $x = DB_DataObject::factory('core_event_audit');
371 'event_id' => $this->id,
373 'old_audit_id' => $old ? $x->findLast($this, $name) : 0,
381 function beforeInsert($request,$roo)
383 if(empty($this->event_when)){
384 $this->event_when = $this->sqlValue("NOW()");
387 if(empty($this->person_id)){
388 $this->person_id = $roo->authUser->id;
389 $this->person_name = $roo->authUser->name;
390 $this->person_table = $roo->authUser->tableName();
393 if(empty($this->ipaddr)){
394 $this->ipaddr = isset($_SERVER["REMOTE_ADDR"]) ? $_SERVER["REMOTE_ADDR"] : 'cli';
395 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
396 $this->ipaddr = $_SERVER['HTTP_X_FORWARDED_FOR'];
401 function onInsert($request,$roo)
403 $this->writeEventLog();
406 function writeEventLog($extra_data = '')
408 $ff = HTML_FlexyFramework::get();
409 if (empty($ff->Pman['event_log_dir'])) {
413 // add user (eg. www-data or local user if not..)
414 if (function_exists('posix_getpwuid')) {
415 $uinfo = posix_getpwuid( posix_getuid () );
417 $user = $uinfo['name'];
419 $user = getenv('USERNAME'); // windows.
422 $file = $ff->Pman['event_log_dir']. '/'. $user. date('/Y/m/d/'). $this->id . ".json";
423 if (!file_exists(dirname($file))) {
424 mkdir(dirname($file),0700,true);
427 // Remove all the password from logs...
428 $p = empty($_POST) ? array() : $_POST;
429 foreach(array('passwd', 'password','passwd1', 'passwd2','password1', 'password2') as $rm) {
430 if (isset($p[$rm])) {
440 foreach ($_FILES as $k=>$f){
441 // does not handle any other file[] arrary very well..
442 if (empty($f['tmp_name']) || !file_exists($f['tmp_name'])) {
449 $files[$k]['tmp_name'] = $this->id . '-'. $i;
450 $nf = $ff->Pman['event_log_dir']. '/'. $user. date('/Y/m/d/'). $files[$k]['tmp_name'];
451 if (!copy($f['tmp_name'], $nf)) {
452 print_r("failed to copy {$f['tmp_name']}...\n");
456 'REQUEST_URI' => empty($_SERVER['REQUEST_URI']) ? 'cli' : $_SERVER['REQUEST_URI'],
457 'HTTP_USER_AGENT' => empty($_SERVER['HTTP_USER_AGENT']) ? '' : $_SERVER['HTTP_USER_AGENT'],
458 'GET' => empty($_GET) ? array() : $_GET,
462 if (!empty($extra_data)) {
463 $out['EXTRA'] = $extra_data;
466 file_put_contents($file, json_encode($out));
471 function toRooSingleArray($au, $q)
473 $ret = $this->toArray();
475 if(empty($q['_retrieve_source'])){
479 $file = $this->retrieveEventLog();
482 return "No records?!";
485 $source = json_decode(file_get_contents($file));
490 function retrieveEventLog()
492 $ff = HTML_FlexyFramework::get();
493 if (empty($ff->Pman['event_log_dir'])) {
497 if (function_exists('posix_getpwuid')) {
498 $uinfo = posix_getpwuid( posix_getuid () );
500 $user = $uinfo['name'];
502 $user = getenv('USERNAME'); // windows.
505 $date = date('/Y/m/d/', strtotime($this->event_when));
507 $file = $ff->Pman['event_log_dir']. '/'. $user. $date. $this->id . ".json";
508 if (!file_exists(dirname($file))) {