3 * Table Definition for Events
5 * objects can implement relatedWhere(), which should return
6 * 'tablename' => array of ids
10 class_exists('DB_DataObject') ? '' : 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)
28 public $dupe_id; // int(11)
30 /* the code above is auto generated do not remove the tag below */
36 // ------------ROO HOOKS------------------------------------
37 function applyFilters($q, $au ,$roo)
39 $tn = $this->tableName();
40 // if not empty on_table
42 if(!empty($q['person_table'])){
43 $jt = DB_DataObject::factory($q['person_table']);
47 if(!array_key_exists("{$jt->tableName()}_id", $this->tableColumns())){ // coz we have triiger on mysql...
51 $this->_join = "LEFT JOIN {$jt->tableName()} AS join_person_id_id ON (join_person_id_id.{$keys[0]}=Events.person_id)";
56 $this->selectAs($jt, 'person_id_%s', 'join_person_id_id');
58 if (method_exists($jt,'nameColumn')) {
59 $this->selectAdd("join_person_id_id.{$jt->nameColumn()} as person_id_name");
62 if (method_exists($jt,'emailColumn')) {
63 $this->selectAdd("join_person_id_id.{$jt->emailColumn()} as person_id_email");
70 $person = $au->tableName(); //'Person'; -- projects may not use person as the auth table...
71 $cfg = HTML_FlexyFramework::get()->Pman;
72 if (!empty($cfg['authTable'])) {
73 $person =$cfg['authTable'];
76 $jt = DB_DataObject::factory($person);
80 // person_table = '{$jt->tableName()}'
83 // OR person_table IS NULL"
84 //); // default to our standard.. - unless otherwise requested..
88 if (!empty($q['query']['from'])) {
89 $dt = date('Y-m-d' , strtotime($q['query']['from']));
90 $this->whereAdd(" {$tn}.event_when >= '$dt' ");
92 if (!empty($q['query']['to'])) {
93 $dt = date('Y-m-d' , strtotime($q['query']['to']));
94 $this->whereAdd(" {$tn}.event_when <= '$dt' ");
97 if(!empty($q['_with_dupe_count'])){
99 $this->selectAdd("(select count(*)+1 from Events ev_cnt where ev_cnt.dupe_id = {$tn}.id) as dupe_count");
102 if (!empty($q['query']['grouped']) && $q['query']['grouped'] == 'gr') {
104 DB_DataObject::Debuglevel(1);
105 $this->groupBy('on_id');
107 (SELECT count(id) FROM core_event_audit WHERE event_id = Events.id) as changed
112 if (!$au->hasPerm("Admin.Admin_Tab", 'S')) {
113 //DB_DataObject::DebugLevel(1);
114 // they can only view their changes..
115 $this->whereAdd("($tn.person_id = {$au->id} OR $tn.person_id = 0)");
116 // $this->person_id = $au->id;
119 // _join = tablename,tablename...
123 // &_join_cols=cohead_number
124 // &_columns=on_id_cohead_number,event_when << this is ignored at present.
125 // max(event_when) is not supported... by any query yet..
127 if (isset($q['on_table']) && !strlen($q['on_table'])) {
128 // empty ontable queries.. these are valid..
129 $this->whereAdd("$tn.on_table = ''");
132 if (isset($q['query']['person_sum'])) {
133 //DB_DataObject::debugLevel(1);
134 $this->_extra_cols = array('qty' );
135 $this->selectAdd("count($tn.id) as qty");
136 $this->selectAdd("count( distinct $tn.on_id) as uqty");
137 $this->whereAdd('LENGTH(join_person_id_id.name) > 0 ');
138 $this->groupBy('person_id,join_person_id_id.name,join_person_id_id.email');
140 if (isset($q['query']['table_sum'])) {
141 //DB_DataObject::debugLevel(1);
142 $this->_extra_cols = array('qty' , 'uqty');
143 $this->selectAdd("count($tn.id) as qty");
144 $this->selectAdd("count( distinct $tn.on_table, $tn.on_id) as uqty");
146 $this->groupBy('on_table');
148 if (isset($q['query']['day_sum'])) {
149 //DB_DataObject::debugLevel(1);
150 $this->_extra_cols = array('qty' , 'uqty');
151 $this->selectAdd("DATE_FORMAT(event_when, '%Y-%m-%d') as on_day");
152 $this->selectAdd("count($tn.id) as qty");
153 $this->selectAdd("count( distinct $tn.on_id) as uqty");
155 $this->groupBy('on_day');
158 if (isset($q['_join'])) {
159 //DB_DataObject::DebugLevel(1);
160 $joins = explode(',',$q['_join']);
162 $this->selectAdd(); // ???
165 foreach($joins as $t) {
166 $t = preg_replace('/[^a-z_]+/', '', $t); // protection.
167 $x = DB_DataObject::Factory($t);
168 if (!is_a($x,'DB_DataObject')) {
171 $jtn = $x->tableName();
172 $jk = array_shift($x->keys());
175 LEFT JOIN {$jtn} as join_on_id_{$jtn} ON {$tn}.on_id = join_on_id_{$jtn}.{$jk}
176 AND on_table = '{$jtn}'
178 $keys = array_keys($x->tableColumns());
179 if (isset($q['_join_cols'])) {
180 $jcs = explode(',',$q['_join_cols'] );
181 //DB_DataObject::DebugLevel(1);
183 foreach($jcs as $jc) {
184 if (! in_array($jc, $keys)) {
190 $this->selectAdd( " join_on_id_{$jtn}.{$jc} as on_id_{$jc} ");
192 $this->selectAdd( " distinct(join_on_id_{$jtn}.{$jc} ) as on_id_{$jc} ");
195 $this->groupBy("on_id_{$jc} ");
196 $this->whereAdd("join_on_id_{$jtn}.{$jc} IS NOT NULL");
198 $this->selectAdd( "MAX(events.event_when) as event_when");
199 $this->orderBy('event_when DESC');
200 // $this->selectAs(array($q['_join_cols']) , 'on_id_%s', "join_on_id_{$jtn}");
202 $this->selectAs($x, 'on_id_%s', "join_on_id_{$jtn}");
209 if (isset($q['_related_on_id']) && isset($q['_related_on_table'])) {
210 // example: sales order - has invoices,
211 ///DB_DataObject::DebugLevel(1);
212 $ev =$this->factory('Events');
214 'on_id' => $q['_related_on_id'],
215 'on_table' => $q['_related_on_table'],
217 $obj = $ev->object();
220 $roo->jerr("ontable is invalid");
223 if (!method_exists($obj,'relatedWhere') && !method_exists($obj,'relatedEventsWhere')) {
224 $roo->jerr( $q['_related_on_table'] . " Does not have method relatedWhere or relatedEventsWhere:" .
225 implode(',', get_class_methods($obj)));
227 if ($obj && method_exists($obj,'relatedWhere')) {
228 $ar = $obj->relatedWhere();
229 $tn = $this->tableName();
232 $w[] = "( {$tn}.on_table = '" .
233 $this->escape($q['_related_on_table']) .
234 "' AND {$tn}.on_id = ". ((int) $q['_related_on_id']) .
238 foreach($ar as $k=>$v) {
242 $w[] = "( {$tn}.on_table = '$k' AND {$tn}.on_id IN (". implode(',', $v). "))";
245 $this->whereAdd(implode(' OR ' , $w));
248 if ($obj && method_exists($obj,'relatedEventsWhere')) {
249 $a = $obj->relatedEventsWhere($q,$roo);
259 // since roo does not support autojoin yet..
260 if (!isset($q['_distinct'])) {
261 //$this->autoJoinExtra();
264 if(!empty($q['query']['action'])) {
265 $act = $this->escape($q['query']['action']);
266 $this->whereAdd("Events.action LIKE '%{$act}%'");
269 if(!empty($q['query']['on_table'])) {
270 $tnb = $this->escape($q['query']['on_table']);
271 $this->whereAdd("Events.on_table LIKE '%{$tnb}%'");
279 * check who is trying to access this. false == access denied..
280 * @return {boolean} true if access is allowed.
282 function checkPerm($lvl, $au)
287 // listing is controleed by applyfilters..
288 return $au->hasPerm("Admin.Admin_Tab", 'S');
292 * return the object that this relates to.
294 * @return {DB_DataObject} related object
298 $o = DB_DataObject::factory($this->on_table);
299 $o->get($this->on_id);
307 * Initialize an event - ready to insert..
309 * @param {String} action - group/name of event
310 * @param {DataObject|false} obj - dataobject action occured on.
311 * @param {String} any remarks
314 function init($act, $obj, $remarks)
316 $ff = HTML_FlexyFramework::get();
318 $au = $pg->getAuthUser();
320 if ($ff->cli) { // && empty($au) && isset($obj->person_id)) {
322 // $au = DB_DataObject::Factory('Person'); // not always a person..
323 // $au->get($obj->person_id);
326 $this->person_name = $au && !empty($au->name) ? $au->name : '';
329 //$this->who = $au && !empty($au->name) ? $au->name : '';
330 if (empty($au) || (isset($au->id) && empty($au->id))) {
331 // not authenticated - and a standard id based object
332 $this->person_id = 0;
334 $col = $au->tableName() == "Person" ? 'person_id' : $au->tableName() . '_id';
336 $cols = $this->tableColumns();
337 $col = isset($cols[$col]) ? $col : 'person_id'; // for BC.... - revert to using person_id
338 $this->{$col} = $au->pid();
339 //$this->person_id = $au ? (!empty($au->id) ? $au->id : $au->pid()) : -1;
341 $this->person_table = $au ? $au->tableName() : '';
342 $this->ipaddr = isset($_SERVER["REMOTE_ADDR"]) ? $_SERVER["REMOTE_ADDR"] : 'cli';
343 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
344 $this->ipaddr = $_SERVER['HTTP_X_FORWARDED_FOR'];
347 $this->action = $act;
348 $this->on_table = $obj ? $obj->tableName() : '';
349 $pk = $obj ? $obj->keys() : false;
350 $this->on_id = $obj && $pk ? $obj->{$pk[0]}: 0;
352 // should this really go in remarks? -
353 if ($obj && method_exists($obj,'toEventString')) {
354 if($obj->toEventString() !== false){
355 $rem[] = $obj->toEventString();
359 $this->remarks = implode(' : ', $rem);
363 * Generate an audit for this field.
365 * @param {DB_DataObject} new data
366 * @param {DB_DataObject} old data
368 * @return {int} number of entries logged.
371 function audit($new, $old = false)
374 return 0; // they are the same...
378 foreach(array_keys($new->tableColumns()) as $k) {
379 // should we JSON serialize this?
380 $n = empty($new->$k) ? '' : $new->$k;
381 $o = empty($old->$k) || empty($old->$k) ? '' : $old->$k;
385 $this->auditField($k, $o, $n, $old);
391 * Record an audited change, in theory so we can audit data that is not just
394 * @param {string} $name table field anme
395 * @param {mixed} $ov old value
396 * @param {mixed} $onv new value
397 * @param {mixed} $old old object (false if we are creating..)
399 function auditField($name, $ov, $nv, $old=false )
402 if (is_object($nv)) {
407 $x = DB_DataObject::factory('core_event_audit');
409 'event_id' => $this->id,
411 'old_audit_id' => $old ? $x->findLast($this, $name) : 0,
419 function beforeInsert($request,$roo)
421 if(empty($this->event_when)){
422 $this->event_when = $this->sqlValue("NOW()");
425 if(empty($this->person_id)){
426 $this->person_id = $roo->authUser->id;
427 $this->person_name = $roo->authUser->name;
428 $this->person_table = $roo->authUser->tableName();
431 if(empty($this->ipaddr)){
432 $this->ipaddr = isset($_SERVER["REMOTE_ADDR"]) ? $_SERVER["REMOTE_ADDR"] : 'cli';
433 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
434 $this->ipaddr = $_SERVER['HTTP_X_FORWARDED_FOR'];
439 function beforeUpdate($old, $request,$roo)
441 if(!empty($request['_restore'])){
442 $this->restore($roo);
446 function onInsert($request,$roo)
448 $this->writeEventLog();
451 static $deleted = array();
454 // log deleting of a record so that it can be written later..
455 function logDeletedRecord($obj = false)
457 if (is_array($obj)) {
459 foreach($obj as $o) {
460 $aret = $this->logDeletedRecord($o);
461 $ret = $ret ? $ret : $aret;
466 if(empty($obj) || !is_a($obj, 'DB_DataObject')){
471 $del = $obj->toArray();
472 $del['_table'] = $obj->tableName();
474 self::$deleted[] = $del;
477 static $extra_data = false;
479 static function writeEventLogExtra($data) {
480 self::$extra_data = $data;
485 $ff = HTML_FlexyFramework::get();
486 if (function_exists('posix_getpwuid')) {
487 $uinfo = posix_getpwuid( posix_getuid () );
489 $user = $uinfo['name'];
491 $user = getenv('USERNAME'); // windows.
495 if (!empty($ff->Pman['event_log_dir'])) {
496 return $ff->Pman['event_log_dir'] . '/'.$user;
498 if (!empty($ff->Pman['storedir'])) {
499 return $ff->Pman['storedir'] .'/Events/'.$user;
507 function writeEventLog($extra_data = false)
509 $logdir = $this->logDir();
516 $file = $logdir. date('/Y/m/d/'). $this->id . ".json";
517 if (!file_exists(dirname($file))) {
519 @mkdir(dirname($file),0700,true); // this might fail if it does not have correct permissions..
520 if (!file_exists(dirname($file))) {
521 die("could not create $file - permissons are not correct"); // fatal, otherwise we loop!?
526 // Remove all the password from logs...
527 $p = empty($_POST) ? array() : $_POST;
528 foreach(array('passwd', 'password','passwd1', 'passwd2','password1', 'password2') as $rm) {
529 if (isset($p[$rm])) {
539 foreach ($_FILES as $k=>$f){
540 // does not handle any other file[] arrary very well..
541 if (empty($f['tmp_name']) || !file_exists($f['tmp_name'])) {
548 $files[$k]['tmp_name'] = $this->id . '-'. $i;
549 $nf = $logdir . date('/Y/m/d/'). $files[$k]['tmp_name'];
550 if (!copy($f['tmp_name'], $nf)) {
551 print_r("failed to copy {$f['tmp_name']}...\n");
555 'REQUEST_URI' => empty($_SERVER['REQUEST_URI']) ? 'cli' : $_SERVER['REQUEST_URI'],
556 'HTTP_USER_AGENT' => empty($_SERVER['HTTP_USER_AGENT']) ? '' : $_SERVER['HTTP_USER_AGENT'],
557 'GET' => empty($_GET) ? array() : $_GET,
562 if (!empty(self::$deleted)) {
563 $out['DELETED_DATAOBJECTS'] = self::$deleted;
565 if ($extra_data !== false) {
566 $out['EXTRA'] = $extra_data;
568 if ( self::$extra_data !== false) {
569 $out['EXTRA_DATA'] = self::$extra_data;
572 file_put_contents($file, json_encode($out));
577 function toRooArray( $q)
579 $ret = $this->toArray();
581 // fill toEventString.
582 if (!empty($q['_with_obj_summary']) && !empty($this->on_id)) {
583 $obj = $this->object();
585 if ($obj && $obj->pid() && method_exists($obj,'toEventString')) {
586 $es = $obj->toEventString();
588 if (empty($this->remarks) || strpos($this->remarks, $es) < 0) {
589 $ret['remarks'] = $es . ' ' . $this->remarks;
591 } else if (empty($this->remarks)){
592 $ret['remarks'] = "DELETED";
601 function toRooSingleArray($au, $q)
603 $ret = $this->toArray();
607 if(empty($q['_retrieve_source'])){
611 $file = $this->retrieveEventLog();
614 return "No records?!";
617 $source = json_decode(file_get_contents($file));
622 function retrieveEventLog()
625 $logdir = $this->logDir();
631 $date = date('/Y/m/d/', strtotime($this->event_when));
633 $file = $logdir. $date. $this->id . ".json";
634 if (!file_exists(dirname($file))) {
641 function restore($roo)
643 $file = $this->retrieveEventLog();
645 if(empty($file) || !file_exists($file)){
646 $roo->jerr('Could not retrieve the event log file');
649 $log = json_decode(file_get_contents($file), true);
651 if(empty($log['POST']) || empty($log['POST']['_delete']) || empty($log['DELETED_DATAOBJECTS'])){
652 $roo->jerr('Invalid url');
657 foreach ($log['DELETED_DATAOBJECTS'] as $d){
660 empty($d['_table']) ||
662 !empty($restored[$d['_table']]) &&
663 in_array($d['id'], $restored[$d['_table']])
669 if(!isset($restored[$d['_table']])){
670 $restored[$d['_table']] = array();
673 $restored[$d['_table']][] = $d['id'];
675 $table = DB_DataObject::factory($d['_table']);
677 if (!is_a($table,'DB_DataObject')) {
686 * need to use the old id
688 $table->id = $d['id'];
690 $table->sequenceKey(false,false);
694 if($table->tableName() == 'crm_mailing_list_member'){
695 $ml = DB_DataObject::factory('crm_mailing_list');
696 if(!$ml->get($table->mailing_list_id)){
700 $mlm = DB_DataObject::factory('crm_mailing_list_member');
702 'mailing_list_id' => $table->mailing_list_id,
707 $ml->no_members = $mlm->count();
712 $roo->jok('RESTORE');
714 function selectAddPersonEmail()
716 $this->selectAdd('join_person_id_id.email as email');