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 print_R($this->table());exit;
47 $this->_join = "LEFT JOIN {$jt->tableName()} AS join_person_id_id ON (join_person_id_id.{$keys[0]}=Events.person_id)";
51 $this->selectAs($jt, 'person_id_%s', 'join_person_id_id');
53 if (method_exists($jt,'nameColumn')) {
54 $this->selectAdd("join_person_id_id.{$jt->nameColumn()} as person_id_name");
57 if (method_exists($jt,'emailColumn')) {
58 $this->selectAdd("join_person_id_id.{$jt->emailColumn()} as person_id_email");
64 $cfg = HTML_FlexyFramework::get()->Pman;
65 if (!empty($cfg['authTable'])) {
66 $person =$cfg['authTable'];
69 $jt = DB_DataObject::factory($person);
71 person_table = '{$jt->tableName()}'
74 OR person_table IS NULL"
75 ); // default to our standard.. - unless otherwise requested..
79 if (!empty($q['query']['from'])) {
80 $dt = date('Y-m-d' , strtotime($q['query']['from']));
81 $this->whereAdd(" {$tn}.event_when >= '$dt' ");
83 if (!empty($q['query']['to'])) {
84 $dt = date('Y-m-d' , strtotime($q['query']['to']));
85 $this->whereAdd(" {$tn}.event_when <= '$dt' ");
88 if (!empty($q['query']['grouped']) && $q['query']['grouped'] == 'gr') {
90 DB_DataObject::Debuglevel(1);
91 $this->groupBy('on_id');
93 (SELECT count(id) FROM core_event_audit WHERE event_id = Events.id) as changed
98 if (!$au->hasPerm("Admin.Admin_Tab", 'S')) {
99 //DB_DataObject::DebugLevel(1);
100 // they can only view their changes..
101 $this->person_id = $au->id;
104 // _join = tablename,tablename...
108 // &_join_cols=cohead_number
109 // &_columns=on_id_cohead_number,event_when << this is ignored at present.
110 // max(event_when) is not supported... by any query yet..
112 if (isset($q['on_table']) && !strlen($q['on_table'])) {
113 // empty ontable queries.. these are valid..
114 $this->whereAdd("$tn.on_table = ''");
119 if (isset($q['query']['person_sum'])) {
120 //DB_DataObject::debugLevel(1);
121 $this->_extra_cols = array('qty' );
122 $this->selectAdd("count($tn.id) as qty");
123 $this->selectAdd("count( distinct $tn.on_id) as uqty");
124 $this->whereAdd('LENGTH(join_person_id_id.name) > 0 ');
125 $this->groupBy('person_id,join_person_id_id.name,join_person_id_id.email');
127 if (isset($q['query']['table_sum'])) {
128 //DB_DataObject::debugLevel(1);
129 $this->_extra_cols = array('qty' , 'uqty');
130 $this->selectAdd("count($tn.id) as qty");
131 $this->selectAdd("count( distinct $tn.on_table, $tn.on_id) as uqty");
133 $this->groupBy('on_table');
135 if (isset($q['query']['day_sum'])) {
136 //DB_DataObject::debugLevel(1);
137 $this->_extra_cols = array('qty' , 'uqty');
138 $this->selectAdd("DATE_FORMAT(event_when, '%Y-%m-%d') as on_day");
139 $this->selectAdd("count($tn.id) as qty");
140 $this->selectAdd("count( distinct $tn.on_id) as uqty");
142 $this->groupBy('on_day');
145 if (isset($q['_join'])) {
146 //DB_DataObject::DebugLevel(1);
147 $joins = explode(',',$q['_join']);
149 $this->selectAdd(); // ???
152 foreach($joins as $t) {
153 $t = preg_replace('/[^a-z_]+/', '', $t); // protection.
154 $x = DB_DataObject::Factory($t);
155 if (!is_a($x,'DB_DataObject')) {
158 $jtn = $x->tableName();
159 $jk = array_shift($x->keys());
162 LEFT JOIN {$jtn} as join_on_id_{$jtn} ON {$tn}.on_id = join_on_id_{$jtn}.{$jk}
163 AND on_table = '{$jtn}'
165 $keys = array_keys($x->table());
166 if (isset($q['_join_cols'])) {
167 $jcs = explode(',',$q['_join_cols'] );
168 //DB_DataObject::DebugLevel(1);
170 foreach($jcs as $jc) {
171 if (! in_array($jc, $keys)) {
177 $this->selectAdd( " join_on_id_{$jtn}.{$jc} as on_id_{$jc} ");
179 $this->selectAdd( " distinct(join_on_id_{$jtn}.{$jc} ) as on_id_{$jc} ");
182 $this->groupBy("on_id_{$jc} ");
183 $this->whereAdd("join_on_id_{$jtn}.{$jc} IS NOT NULL");
185 $this->selectAdd( "MAX(events.event_when) as event_when");
186 $this->orderBy('event_when DESC');
187 // $this->selectAs(array($q['_join_cols']) , 'on_id_%s', "join_on_id_{$jtn}");
189 $this->selectAs($x, 'on_id_%s', "join_on_id_{$jtn}");
196 if (isset($q['_related_on_id']) && isset($q['_related_on_table'])) {
197 // example: sales order - has invoices,
198 ///DB_DataObject::DebugLevel(1);
199 $ev =$this->factory('Events');
201 'on_id' => $q['_related_on_id'],
202 'on_table' => $q['_related_on_table'],
204 $obj = $ev->object();
207 $roo->jerr("ontable is invalid");
209 if (!method_exists($obj,'relatedWhere')) {
210 $roo->jerr( $q['_related_on_table'] . " Does not have method relatedWhere :" .
211 implode(',', get_class_methods($obj)));
213 if ($obj && method_exists($obj,'relatedWhere')) {
214 $ar = $obj->relatedWhere();
215 $tn = $this->tableName();
218 $w[] = "( {$tn}.on_table = '" .
219 $this->escape($q['_related_on_table']) .
220 "' AND {$tn}.on_id = ". ((int) $q['_related_on_id']) .
224 foreach($ar as $k=>$v) {
228 $w[] = "( {$tn}.on_table = '$k' AND {$tn}.on_id IN (". implode(',', $v). "))";
231 $this->whereAdd(implode(' OR ' , $w));
239 // since roo does not support autojoin yet..
240 if (!isset($q['_distinct'])) {
241 //$this->autoJoinExtra();
244 if(!empty($q['query']['action'])) {
245 $act = $this->escape($q['query']['action']);
246 $this->whereAdd("Events.action LIKE '%{$act}%'");
249 if(!empty($q['query']['on_table'])) {
250 $tnb = $this->escape($q['query']['on_table']);
251 $this->whereAdd("Events.on_table LIKE '%{$tnb}%'");
259 * check who is trying to access this. false == access denied..
260 * @return {boolean} true if access is allowed.
262 function checkPerm($lvl, $au)
267 // listing is controleed by applyfilters..
268 return $au->hasPerm("Admin.Admin_Tab", 'S');
272 * return the object that this relates to.
274 * @return {DB_DataObject} related object
278 $o = DB_DataObject::factory($this->on_table);
279 $o->get($this->on_id);
287 * Initialize an event - ready to insert..
289 * @param {String} action - group/name of event
290 * @param {DataObject|false} obj - dataobject action occured on.
291 * @param {String} any remarks
294 function init($act, $obj, $remarks)
296 $ff = HTML_FlexyFramework::get();
298 $au = $pg->getAuthUser();
300 if ($ff->cli) { // && empty($au) && isset($obj->person_id)) {
302 // $au = DB_DataObject::Factory('Person'); // not always a person..
303 // $au->get($obj->person_id);
306 $this->person_name = $au && !empty($au->name) ? $au->name : '';
307 if (empty($au) || (isset($au->id) && empty($au->id))) {
308 // not authenticated - and a standard id based object
309 $this->person_id = 0;
311 $col = $au->tableName() == "Person" ? 'person_id' : $au->tableName() . '_id';
313 $cols = $this->table();
314 $col = isset($cols[$col]) ? $col : 'person_id'; // for BC.... - revert to using person_id
315 $this->{$col} = $au->pid();
316 //$this->person_id = $au ? (!empty($au->id) ? $au->id : $au->pid()) : -1;
318 $this->person_table = $au ? $au->tableName() : '';
319 $this->ipaddr = isset($_SERVER["REMOTE_ADDR"]) ? $_SERVER["REMOTE_ADDR"] : 'cli';
320 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
321 $this->ipaddr = $_SERVER['HTTP_X_FORWARDED_FOR'];
324 $this->action = $act;
325 $this->on_table = $obj ? $obj->tableName() : '';
326 $pk = $obj ? $obj->keys() : false;
327 $this->on_id = $obj && $pk ? $obj->{$pk[0]}: 0;
329 // should this really go in remarks? -
330 if ($obj && method_exists($obj,'toEventString')) {
331 $rem[] = $obj->toEventString() ;
334 $this->remarks = implode(' : ', $rem);
338 * Generate an audit for this field.
340 * @param {DB_DataObject} new data
341 * @param {DB_DataObject} old data
343 * @return {int} number of entries logged.
346 function audit($new, $old = false)
349 return 0; // they are the same...
353 foreach(array_keys($new->table()) as $k) {
354 // should we JSON serialize this?
355 $n = empty($new->$k) ? '' : $new->$k;
356 $o = empty($old->$k) || empty($old->$k) ? '' : $old->$k;
360 $this->auditField($k, $o, $n, $old);
366 * Record an audited change, in theory so we can audit data that is not just
369 * @param {string} $name table field anme
370 * @param {mixed} $ov old value
371 * @param {mixed} $onv new value
372 * @param {mixed} $old old object (false if we are creating..)
374 function auditField($name, $ov, $nv, $old=false )
377 if (is_object($nv)) {
382 $x = DB_DataObject::factory('core_event_audit');
384 'event_id' => $this->id,
386 'old_audit_id' => $old ? $x->findLast($this, $name) : 0,
394 function beforeInsert($request,$roo)
396 if(empty($this->event_when)){
397 $this->event_when = $this->sqlValue("NOW()");
400 if(empty($this->person_id)){
401 $this->person_id = $roo->authUser->id;
402 $this->person_name = $roo->authUser->name;
403 $this->person_table = $roo->authUser->tableName();
406 if(empty($this->ipaddr)){
407 $this->ipaddr = isset($_SERVER["REMOTE_ADDR"]) ? $_SERVER["REMOTE_ADDR"] : 'cli';
408 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
409 $this->ipaddr = $_SERVER['HTTP_X_FORWARDED_FOR'];
414 function onInsert($request,$roo)
416 $this->writeEventLog();
419 static $deleted = array();
422 // log deleting of a record so that it can be written later..
423 function logDeletedRecord($obj = false, $reset = false)
427 self::$deleted = array();
431 if (is_array($obj)) {
433 foreach($obj as $o) {
434 $aret = $this->logDeletedRecord($o);
435 $ret = $ret ? $ret : $aret;
440 if(empty($obj) || !is_a($obj, 'DB_DataObject')){
445 $del = $obj->toArray();
446 $del['_table'] = $obj->tableName();
448 if(method_exists($obj, 'toDeletedArray')){
449 $del = $obj->toDeletedArray();
452 self::$deleted[] = $del;
456 function writeEventLog($extra_data = '')
458 $ff = HTML_FlexyFramework::get();
459 if (empty($ff->Pman['event_log_dir'])) {
463 // add user (eg. www-data or local user if not..)
464 if (function_exists('posix_getpwuid')) {
465 $uinfo = posix_getpwuid( posix_getuid () );
467 $user = $uinfo['name'];
469 $user = getenv('USERNAME'); // windows.
472 $file = $ff->Pman['event_log_dir']. '/'. $user. date('/Y/m/d/'). $this->id . ".json";
473 if (!file_exists(dirname($file))) {
474 mkdir(dirname($file),0700,true);
477 // Remove all the password from logs...
478 $p = empty($_POST) ? array() : $_POST;
479 foreach(array('passwd', 'password','passwd1', 'passwd2','password1', 'password2') as $rm) {
480 if (isset($p[$rm])) {
490 foreach ($_FILES as $k=>$f){
491 // does not handle any other file[] arrary very well..
492 if (empty($f['tmp_name']) || !file_exists($f['tmp_name'])) {
499 $files[$k]['tmp_name'] = $this->id . '-'. $i;
500 $nf = $ff->Pman['event_log_dir']. '/'. $user. date('/Y/m/d/'). $files[$k]['tmp_name'];
501 if (!copy($f['tmp_name'], $nf)) {
502 print_r("failed to copy {$f['tmp_name']}...\n");
506 'REQUEST_URI' => empty($_SERVER['REQUEST_URI']) ? 'cli' : $_SERVER['REQUEST_URI'],
507 'HTTP_USER_AGENT' => empty($_SERVER['HTTP_USER_AGENT']) ? '' : $_SERVER['HTTP_USER_AGENT'],
508 'GET' => empty($_GET) ? array() : $_GET,
513 if (!empty(self::$deleted)) {
514 $out['DELETED_DATAOBJECTS'] = self::$deleted;
516 if (!empty($extra_data)) {
517 $out['EXTRA'] = $extra_data;
520 file_put_contents($file, json_encode($out));
525 function toRooSingleArray($au, $q)
527 $ret = $this->toArray();
529 if(empty($q['_retrieve_source'])){
533 $file = $this->retrieveEventLog();
536 return "No records?!";
539 $source = json_decode(file_get_contents($file));
544 function retrieveEventLog()
546 $ff = HTML_FlexyFramework::get();
547 if (empty($ff->Pman['event_log_dir'])) {
551 if (function_exists('posix_getpwuid')) {
552 $uinfo = posix_getpwuid( posix_getuid () );
554 $user = $uinfo['name'];
556 $user = getenv('USERNAME'); // windows.
559 $date = date('/Y/m/d/', strtotime($this->event_when));
561 $file = $ff->Pman['event_log_dir']. '/'. $user. $date. $this->id . ".json";
562 if (!file_exists(dirname($file))) {