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']);
45 $this->_join = "LEFT JOIN {$jt->tableName()} AS join_person_id_id ON (join_person_id_id.{$keys[0]}=Events.person_id)";
49 $this->selectAs($jt, 'person_id_%s', 'join_person_id_id');
51 if (method_exists($jt,'nameColumn')) {
52 $this->selectAdd("join_person_id_id.{$jt->nameColumn()} as person_id_name");
55 if (method_exists($jt,'emailColumn')) {
56 $this->selectAdd("join_person_id_id.{$jt->emailColumn()} as person_id_email");
62 $cfg = HTML_FlexyFramework::get()->Pman;
63 if (!empty($cfg['authTable'])) {
64 $person =$cfg['authTable'];
67 $jt = DB_DataObject::factory($person);
69 person_table = '{$jt->tableName()}'
72 OR person_table IS NULL"
73 ); // default to our standard.. - unless otherwise requested..
77 if (!empty($q['query']['from'])) {
78 $dt = date('Y-m-d' , strtotime($q['query']['from']));
79 $this->whereAdd(" {$tn}.event_when >= '$dt' ");
81 if (!empty($q['query']['to'])) {
82 $dt = date('Y-m-d' , strtotime($q['query']['to']));
83 $this->whereAdd(" {$tn}.event_when <= '$dt' ");
86 if (!empty($q['query']['grouped']) && $q['query']['grouped'] == 'gr') {
88 DB_DataObject::Debuglevel(1);
89 $this->groupBy('on_id');
91 (SELECT count(id) FROM core_event_audit WHERE event_id = Events.id) as changed
96 if (!$au->hasPerm("Admin.Admin_Tab", 'S')) {
97 //DB_DataObject::DebugLevel(1);
98 // they can only view their changes..
99 $this->person_id = $au->id;
102 // _join = tablename,tablename...
106 // &_join_cols=cohead_number
107 // &_columns=on_id_cohead_number,event_when << this is ignored at present.
108 // max(event_when) is not supported... by any query yet..
110 if (isset($q['on_table']) && !strlen($q['on_table'])) {
111 // empty ontable queries.. these are valid..
112 $this->whereAdd("$tn.on_table = ''");
117 if (isset($q['query']['person_sum'])) {
118 //DB_DataObject::debugLevel(1);
119 $this->_extra_cols = array('qty' );
120 $this->selectAdd("count($tn.id) as qty");
121 $this->selectAdd("count( distinct $tn.on_id) as uqty");
122 $this->whereAdd('LENGTH(join_person_id_id.name) > 0 ');
123 $this->groupBy('person_id,join_person_id_id.name,join_person_id_id.email');
125 if (isset($q['query']['table_sum'])) {
126 //DB_DataObject::debugLevel(1);
127 $this->_extra_cols = array('qty' , 'uqty');
128 $this->selectAdd("count($tn.id) as qty");
129 $this->selectAdd("count( distinct $tn.on_table, $tn.on_id) as uqty");
131 $this->groupBy('on_table');
133 if (isset($q['query']['day_sum'])) {
134 //DB_DataObject::debugLevel(1);
135 $this->_extra_cols = array('qty' , 'uqty');
136 $this->selectAdd("DATE_FORMAT(event_when, '%Y-%m-%d') as on_day");
137 $this->selectAdd("count($tn.id) as qty");
138 $this->selectAdd("count( distinct $tn.on_id) as uqty");
140 $this->groupBy('on_day');
143 if (isset($q['_join'])) {
144 //DB_DataObject::DebugLevel(1);
145 $joins = explode(',',$q['_join']);
147 $this->selectAdd(); // ???
150 foreach($joins as $t) {
151 $t = preg_replace('/[^a-z_]+/', '', $t); // protection.
152 $x = DB_DataObject::Factory($t);
153 if (!is_a($x,'DB_DataObject')) {
156 $jtn = $x->tableName();
157 $jk = array_shift($x->keys());
160 LEFT JOIN {$jtn} as join_on_id_{$jtn} ON {$tn}.on_id = join_on_id_{$jtn}.{$jk}
161 AND on_table = '{$jtn}'
163 $keys = array_keys($x->table());
164 if (isset($q['_join_cols'])) {
165 $jcs = explode(',',$q['_join_cols'] );
166 //DB_DataObject::DebugLevel(1);
168 foreach($jcs as $jc) {
169 if (! in_array($jc, $keys)) {
175 $this->selectAdd( " join_on_id_{$jtn}.{$jc} as on_id_{$jc} ");
177 $this->selectAdd( " distinct(join_on_id_{$jtn}.{$jc} ) as on_id_{$jc} ");
180 $this->groupBy("on_id_{$jc} ");
181 $this->whereAdd("join_on_id_{$jtn}.{$jc} IS NOT NULL");
183 $this->selectAdd( "MAX(events.event_when) as event_when");
184 $this->orderBy('event_when DESC');
185 // $this->selectAs(array($q['_join_cols']) , 'on_id_%s', "join_on_id_{$jtn}");
187 $this->selectAs($x, 'on_id_%s', "join_on_id_{$jtn}");
194 if (isset($q['_related_on_id']) && isset($q['_related_on_table'])) {
195 // example: sales order - has invoices,
196 ///DB_DataObject::DebugLevel(1);
197 $ev =$this->factory('Events');
199 'on_id' => $q['_related_on_id'],
200 'on_table' => $q['_related_on_table'],
202 $obj = $ev->object();
205 $roo->jerr("ontable is invalid");
207 if (!method_exists($obj,'relatedWhere')) {
208 $roo->jerr( $q['_related_on_table'] . " Does not have method relatedWhere :" .
209 implode(',', get_class_methods($obj)));
211 if ($obj && method_exists($obj,'relatedWhere')) {
212 $ar = $obj->relatedWhere();
213 $tn = $this->tableName();
216 $w[] = "( {$tn}.on_table = '" .
217 $this->escape($q['_related_on_table']) .
218 "' AND {$tn}.on_id = ". ((int) $q['_related_on_id']) .
222 foreach($ar as $k=>$v) {
226 $w[] = "( {$tn}.on_table = '$k' AND {$tn}.on_id IN (". implode(',', $v). "))";
229 $this->whereAdd(implode(' OR ' , $w));
237 // since roo does not support autojoin yet..
238 if (!isset($q['_distinct'])) {
239 //$this->autoJoinExtra();
242 if(!empty($q['query']['action'])) {
243 $act = $this->escape($q['query']['action']);
244 $this->whereAdd("Events.action LIKE '%{$act}%'");
247 if(!empty($q['query']['on_table'])) {
248 $tnb = $this->escape($q['query']['on_table']);
249 $this->whereAdd("Events.on_table LIKE '%{$tnb}%'");
257 * check who is trying to access this. false == access denied..
258 * @return {boolean} true if access is allowed.
260 function checkPerm($lvl, $au)
265 // listing is controleed by applyfilters..
266 return $au->hasPerm("Admin.Admin_Tab", 'S');
270 * return the object that this relates to.
272 * @return {DB_DataObject} related object
276 $o = DB_DataObject::factory($this->on_table);
277 $o->get($this->on_id);
285 * Initialize an event - ready to insert..
287 * @param {String} action - group/name of event
288 * @param {DataObject|false} obj - dataobject action occured on.
289 * @param {String} any remarks
292 function init($act, $obj, $remarks)
294 $ff = HTML_FlexyFramework::get();
296 $au = $pg->getAuthUser();
298 if ($ff->cli) { // && empty($au) && isset($obj->person_id)) {
300 // $au = DB_DataObject::Factory('Person'); // not always a person..
301 // $au->get($obj->person_id);
304 $this->person_name = $au && !empty($au->name) ? $au->name : '';
305 if (isset($au->id) && empty($au->id)) {
306 // not authenticated - and a standard id based object
307 $this->person_id = 0;
309 $this->person_id = $au ? (!empty($au->id) ? $au->id : $au->pid()) : -1;
311 $this->person_table = $au ? $au->tableName() : '';
312 $this->ipaddr = isset($_SERVER["REMOTE_ADDR"]) ? $_SERVER["REMOTE_ADDR"] : 'cli';
313 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
314 $this->ipaddr = $_SERVER['HTTP_X_FORWARDED_FOR'];
317 $this->action = $act;
318 $this->on_table = $obj ? $obj->tableName() : '';
319 $pk = $obj ? $obj->keys() : false;
320 $this->on_id = $obj && $pk ? $obj->{$pk[0]}: 0;
322 // should this really go in remarks? -
323 if ($obj && method_exists($obj,'toEventString')) {
324 $rem[] = $obj->toEventString() ;
327 $this->remarks = implode(' : ', $rem);
331 * Generate an audit for this field.
333 * @param {DB_DataObject} new data
334 * @param {DB_DataObject} old data
336 * @return {int} number of entries logged.
339 function audit($new, $old = false)
342 return 0; // they are the same...
346 foreach(array_keys($new->table()) as $k) {
347 // should we JSON serialize this?
348 $n = empty($new->$k) ? '' : $new->$k;
349 $o = empty($old->$k) || empty($old->$k) ? '' : $old->$k;
353 $this->auditField($k, $o, $n, $old);
359 * Record an audited change, in theory so we can audit data that is not just
362 * @param {string} $name table field anme
363 * @param {mixed} $ov old value
364 * @param {mixed} $onv new value
365 * @param {mixed} $old old object (false if we are creating..)
367 function auditField($name, $ov, $nv, $old=false )
370 if (is_object($nv)) {
375 $x = DB_DataObject::factory('core_event_audit');
377 'event_id' => $this->id,
379 'old_audit_id' => $old ? $x->findLast($this, $name) : 0,
387 function beforeInsert($request,$roo)
389 if(empty($this->event_when)){
390 $this->event_when = $this->sqlValue("NOW()");
393 if(empty($this->person_id)){
394 $this->person_id = $roo->authUser->id;
395 $this->person_name = $roo->authUser->name;
396 $this->person_table = $roo->authUser->tableName();
399 if(empty($this->ipaddr)){
400 $this->ipaddr = isset($_SERVER["REMOTE_ADDR"]) ? $_SERVER["REMOTE_ADDR"] : 'cli';
401 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
402 $this->ipaddr = $_SERVER['HTTP_X_FORWARDED_FOR'];
407 function onInsert($request,$roo)
409 $this->writeEventLog();
412 function writeEventLog($extra_data = '')
414 $ff = HTML_FlexyFramework::get();
415 if (empty($ff->Pman['event_log_dir'])) {
419 // add user (eg. www-data or local user if not..)
420 if (function_exists('posix_getpwuid')) {
421 $uinfo = posix_getpwuid( posix_getuid () );
423 $user = $uinfo['name'];
425 $user = getenv('USERNAME'); // windows.
428 $file = $ff->Pman['event_log_dir']. '/'. $user. date('/Y/m/d/'). $this->id . ".json";
429 if (!file_exists(dirname($file))) {
430 mkdir(dirname($file),0700,true);
433 // Remove all the password from logs...
434 $p = empty($_POST) ? array() : $_POST;
435 foreach(array('passwd', 'password','passwd1', 'passwd2','password1', 'password2') as $rm) {
436 if (isset($p[$rm])) {
446 foreach ($_FILES as $k=>$f){
447 // does not handle any other file[] arrary very well..
448 if (empty($f['tmp_name']) || !file_exists($f['tmp_name'])) {
455 $files[$k]['tmp_name'] = $this->id . '-'. $i;
456 $nf = $ff->Pman['event_log_dir']. '/'. $user. date('/Y/m/d/'). $files[$k]['tmp_name'];
457 if (!copy($f['tmp_name'], $nf)) {
458 print_r("failed to copy {$f['tmp_name']}...\n");
462 'REQUEST_URI' => empty($_SERVER['REQUEST_URI']) ? 'cli' : $_SERVER['REQUEST_URI'],
463 'HTTP_USER_AGENT' => empty($_SERVER['HTTP_USER_AGENT']) ? '' : $_SERVER['HTTP_USER_AGENT'],
464 'GET' => empty($_GET) ? array() : $_GET,
468 if (!empty($extra_data)) {
469 $out['EXTRA'] = $extra_data;
472 file_put_contents($file, json_encode($out));
477 function toRooSingleArray($au, $q)
479 $ret = $this->toArray();
481 if(empty($q['_retrieve_source'])){
485 $file = $this->retrieveEventLog();
488 return "No records?!";
491 $source = json_decode(file_get_contents($file));
496 function retrieveEventLog()
498 $ff = HTML_FlexyFramework::get();
499 if (empty($ff->Pman['event_log_dir'])) {
503 if (function_exists('posix_getpwuid')) {
504 $uinfo = posix_getpwuid( posix_getuid () );
506 $user = $uinfo['name'];
508 $user = getenv('USERNAME'); // windows.
511 $date = date('/Y/m/d/', strtotime($this->event_when));
513 $file = $ff->Pman['event_log_dir']. '/'. $user. $date. $this->id . ".json";
514 if (!file_exists(dirname($file))) {