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);
78 // person_table = '{$jt->tableName()}'
81 // OR person_table IS NULL"
82 //); // default to our standard.. - unless otherwise requested..
86 if (!empty($q['query']['from'])) {
87 $dt = date('Y-m-d' , strtotime($q['query']['from']));
88 $this->whereAdd(" {$tn}.event_when >= '$dt' ");
90 if (!empty($q['query']['to'])) {
91 $dt = date('Y-m-d' , strtotime($q['query']['to']));
92 $this->whereAdd(" {$tn}.event_when <= '$dt' ");
95 if(!empty($q['_with_dupe_count'])){
97 $this->selectAdd("(select count(*)+1 from Events ev_cnt where ev_cnt.dupe_id = {$tn}.id) as dupe_count");
100 if (!empty($q['query']['grouped']) && $q['query']['grouped'] == 'gr') {
102 DB_DataObject::Debuglevel(1);
103 $this->groupBy('on_id');
105 (SELECT count(id) FROM core_event_audit WHERE event_id = Events.id) as changed
110 // _join = tablename,tablename...
114 // &_join_cols=cohead_number
115 // &_columns=on_id_cohead_number,event_when << this is ignored at present.
116 // max(event_when) is not supported... by any query yet..
118 if (isset($q['on_table']) && !strlen($q['on_table'])) {
119 // empty ontable queries.. these are valid..
120 $this->whereAdd("$tn.on_table = ''");
123 if (isset($q['query']['person_sum'])) {
124 //DB_DataObject::debugLevel(1);
125 $this->_extra_cols = array('qty' );
126 $this->selectAdd("count($tn.id) as qty");
127 $this->selectAdd("count( distinct $tn.on_id) as uqty");
128 $this->whereAdd('LENGTH(join_person_id_id.name) > 0 ');
129 $this->groupBy('person_id,join_person_id_id.name,join_person_id_id.email');
131 if (isset($q['query']['table_sum'])) {
132 //DB_DataObject::debugLevel(1);
133 $this->_extra_cols = array('qty' , 'uqty');
134 $this->selectAdd("count($tn.id) as qty");
135 $this->selectAdd("count( distinct $tn.on_table, $tn.on_id) as uqty");
137 $this->groupBy('on_table');
139 if (isset($q['query']['day_sum'])) {
140 //DB_DataObject::debugLevel(1);
141 $this->_extra_cols = array('qty' , 'uqty');
142 $this->selectAdd("DATE_FORMAT(event_when, '%Y-%m-%d') as on_day");
143 $this->selectAdd("count($tn.id) as qty");
144 $this->selectAdd("count( distinct $tn.on_id) as uqty");
146 $this->groupBy('on_day');
149 if (isset($q['_join'])) {
150 //DB_DataObject::DebugLevel(1);
151 $joins = explode(',',$q['_join']);
153 $this->selectAdd(); // ???
156 foreach($joins as $t) {
157 $t = preg_replace('/[^a-z_]+/', '', $t); // protection.
158 $x = DB_DataObject::Factory($t);
159 if (!is_a($x,'DB_DataObject')) {
162 $jtn = $x->tableName();
163 $jk = array_shift($x->keys());
166 LEFT JOIN {$jtn} as join_on_id_{$jtn} ON {$tn}.on_id = join_on_id_{$jtn}.{$jk}
167 AND on_table = '{$jtn}'
169 $keys = array_keys($x->tableColumns());
170 if (isset($q['_join_cols'])) {
171 $jcs = explode(',',$q['_join_cols'] );
172 //DB_DataObject::DebugLevel(1);
174 foreach($jcs as $jc) {
175 if (! in_array($jc, $keys)) {
181 $this->selectAdd( " join_on_id_{$jtn}.{$jc} as on_id_{$jc} ");
183 $this->selectAdd( " distinct(join_on_id_{$jtn}.{$jc} ) as on_id_{$jc} ");
186 $this->groupBy("on_id_{$jc} ");
187 $this->whereAdd("join_on_id_{$jtn}.{$jc} IS NOT NULL");
189 $this->selectAdd( "MAX(events.event_when) as event_when");
190 $this->orderBy('event_when DESC');
191 // $this->selectAs(array($q['_join_cols']) , 'on_id_%s', "join_on_id_{$jtn}");
193 $this->selectAs($x, 'on_id_%s', "join_on_id_{$jtn}");
200 if (isset($q['_related_on_id']) && isset($q['_related_on_table'])) {
201 // example: sales order - has invoices,
202 ///DB_DataObject::DebugLevel(1);
203 $ev =$this->factory('Events');
205 'on_id' => $q['_related_on_id'],
206 'on_table' => $q['_related_on_table'],
208 $obj = $ev->object();
211 $roo->jerr("ontable is invalid");
214 if (!method_exists($obj,'relatedWhere')) {
215 $roo->jerr( $q['_related_on_table'] . " Does not have method relatedWhere or relatedEventsWhere:" .
216 implode(',', get_class_methods($obj)));
218 if ($obj && method_exists($obj,'relatedWhere')) {
219 $ar = $obj->relatedWhere();
220 $tn = $this->tableName();
223 $w[] = "( {$tn}.on_table = '" .
224 $this->escape($q['_related_on_table']) .
225 "' AND {$tn}.on_id = ". ((int) $q['_related_on_id']) .
229 foreach($ar as $k=>$v) {
233 $w[] = "( {$tn}.on_table = '$k' AND {$tn}.on_id IN (". implode(',', $v). "))";
236 $this->whereAdd(implode(' OR ' , $w));
243 // since roo does not support autojoin yet..
244 if (!isset($q['_distinct'])) {
245 //$this->autoJoinExtra();
248 if(!empty($q['query']['action'])) {
249 $act = $this->escape($q['query']['action']);
250 $this->whereAdd("Events.action LIKE '%{$act}%'");
253 if(!empty($q['query']['on_table'])) {
254 $tnb = $this->escape($q['query']['on_table']);
255 $this->whereAdd("Events.on_table LIKE '%{$tnb}%'");
260 function autojoin($cfg = array()){
261 /*$mt = DB_DataObject::factory('member_types');
262 $m->joinAdd($mt, 'LEFT');
264 $t->joinAdd($m, 'LEFT');
265 $t->selectAs($m,'member_%s');
267 $e = DB_DataObject::factory('Events');
269 $cp = DB_DataObject::factory('core_person');
270 $e->joinAdd($cp, 'LEFT');
271 $t->joinAdd($e, 'LEFT');
273 $t->selectAdd("member_types.charge_code as member_type_charge_code ");
274 $t->selectAdd("Events.action as evType, Events.event_when as eventWhen");
275 $t->selectAdd("core_person.name as personName");*/
277 $ret = parent::autoJoin($cfg);
282 function applyPermissionFilters($q, $au ,$roo)
284 if (!$au->hasPerm("Admin.Admin_Tab", 'S')) {
285 //DB_DataObject::DebugLevel(1);
286 // they can only view their changes..
287 $this->whereAdd("($tn.person_id = {$au->id} OR $tn.person_id = 0)");
288 // $this->person_id = $au->id;
293 * check who is trying to access this. false == access denied..
294 * @return {boolean} true if access is allowed.
296 function checkPerm($lvl, $au)
301 // listing is controleed by applyfilters..
302 return $au->hasPerm("Admin.Admin_Tab", 'S');
306 * return the object that this relates to.
308 * @return {DB_DataObject} related object
312 $o = DB_DataObject::factory($this->on_table);
313 $o->get($this->on_id);
321 * Initialize an event - ready to insert..
323 * @param {String} action - group/name of event
324 * @param {DataObject|false} obj - dataobject action occured on.
325 * @param {String} any remarks
328 function init($act, $obj, $remarks)
330 $ff = HTML_FlexyFramework::get();
332 $au = $pg->getAuthUser();
334 if ($ff->cli) { // && empty($au) && isset($obj->person_id)) {
336 // $au = DB_DataObject::Factory('Person'); // not always a person..
337 // $au->get($obj->person_id);
340 $this->person_name = $au && !empty($au->name) ? $au->name : '';
343 //$this->who = $au && !empty($au->name) ? $au->name : '';
344 if (empty($au) || (isset($au->id) && empty($au->id))) {
345 // not authenticated - and a standard id based object
346 $this->person_id = 0;
348 $col = $au->tableName() == "Person" ? 'person_id' : $au->tableName() . '_id';
350 $cols = $this->tableColumns();
351 $col = isset($cols[$col]) ? $col : 'person_id'; // for BC.... - revert to using person_id
352 $this->{$col} = $au->pid();
353 //$this->person_id = $au ? (!empty($au->id) ? $au->id : $au->pid()) : -1;
355 $this->person_table = $au ? $au->tableName() : '';
356 $this->ipaddr = isset($_SERVER["REMOTE_ADDR"]) ? $_SERVER["REMOTE_ADDR"] : 'cli';
357 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
358 $this->ipaddr = $_SERVER['HTTP_X_FORWARDED_FOR'];
361 $this->action = $act;
362 $this->on_table = $obj ? $obj->tableName() : '';
363 $pk = $obj ? $obj->keys() : false;
364 $this->on_id = $obj && $pk ? $obj->{$pk[0]}: 0;
366 // should this really go in remarks? -
367 if ($obj && method_exists($obj,'toEventString')) {
368 if($obj->toEventString() !== false){
369 $rem[] = $obj->toEventString();
373 $this->remarks = implode(' : ', $rem);
377 * Generate an audit for this field.
379 * @param {DB_DataObject} new data
380 * @param {DB_DataObject} old data
382 * @return {int} number of entries logged.
385 function audit($new, $old = false)
388 return 0; // they are the same...
392 foreach(array_keys($new->tableColumns()) as $k) {
393 // should we JSON serialize this?
394 $n = empty($new->$k) ? '' : $new->$k;
395 $o = empty($old->$k) || empty($old->$k) ? '' : $old->$k;
399 $this->auditField($k, $o, $n, $old);
405 * Record an audited change, in theory so we can audit data that is not just
408 * @param {string} $name table field anme
409 * @param {mixed} $ov old value
410 * @param {mixed} $onv new value
411 * @param {mixed} $old old object (false if we are creating..)
413 function auditField($name, $ov, $nv, $old=false )
416 if (is_object($nv)) {
421 $x = DB_DataObject::factory('core_event_audit');
423 'event_id' => $this->id,
425 'old_audit_id' => $old ? $x->findLast($this, $name) : 0,
433 function beforeInsert($request,$roo)
435 if(empty($this->event_when)){
436 $this->event_when = $this->sqlValue("NOW()");
439 if(empty($this->person_id)){
440 $this->person_id = $roo->authUser->id;
441 $this->person_name = $roo->authUser->name;
442 $this->person_table = $roo->authUser->tableName();
445 if(empty($this->ipaddr)){
446 $this->ipaddr = isset($_SERVER["REMOTE_ADDR"]) ? $_SERVER["REMOTE_ADDR"] : 'cli';
447 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
448 $this->ipaddr = $_SERVER['HTTP_X_FORWARDED_FOR'];
453 function beforeUpdate($old, $request,$roo)
455 if(!empty($request['_restore'])){
456 $this->restore($roo);
460 function onInsert($request,$roo)
462 $this->writeEventLog();
465 static $deleted = array();
468 // log deleting of a record so that it can be written later..
469 function logDeletedRecord($obj = false)
471 if (is_array($obj)) {
473 foreach($obj as $o) {
474 $aret = $this->logDeletedRecord($o);
475 $ret = $ret ? $ret : $aret;
480 if(empty($obj) || !is_a($obj, 'DB_DataObject')){
485 $del = $obj->toArray();
486 $del['_table'] = $obj->tableName();
488 self::$deleted[] = $del;
491 static $extra_data = false;
493 static function writeEventLogExtra($data) {
494 self::$extra_data = $data;
499 $ff = HTML_FlexyFramework::get();
500 if (function_exists('posix_getpwuid')) {
501 $uinfo = posix_getpwuid( posix_getuid () );
503 $user = $uinfo['name'];
505 $user = getenv('USERNAME'); // windows.
510 if (!empty($ff->Pman['storedir'])) {
511 return $ff->Pman['storedir'] .'/Events/'.$user;
514 if (!empty($ff->Pman['event_log_dir'])) {
515 return $ff->Pman['event_log_dir'] . '/'.$user;
523 function writeEventLog($extra_data = false)
525 $logdir = $this->logDir();
533 $file = $logdir. date('/Y/m/d/'). $this->id . ".json";
534 if (!file_exists(dirname($file))) {
536 @mkdir(dirname($file),0700,true); // this might fail if it does not have correct permissions..
537 if (!file_exists(dirname($file))) {
539 die("could not create $file - permissons are not correct"); // fatal, otherwise we loop!?
544 // Remove all the password from logs...
545 $p = empty($_POST) ? array() : $_POST;
546 foreach(array('passwd', 'password','passwd1', 'passwd2','password1', 'password2') as $rm) {
547 if (isset($p[$rm])) {
557 foreach ($_FILES as $k=>$f){
558 // does not handle any other file[] arrary very well..
559 if (empty($f['tmp_name']) || !file_exists($f['tmp_name'])) {
566 $files[$k]['tmp_name'] = $this->id . '-'. $i;
567 $nf = $logdir . date('/Y/m/d/'). $files[$k]['tmp_name'];
568 if (!copy($f['tmp_name'], $nf)) {
569 print_r("failed to copy {$f['tmp_name']}...\n");
573 'REQUEST_URI' => empty($_SERVER['REQUEST_URI']) ? 'cli' : $_SERVER['REQUEST_URI'],
574 'HTTP_USER_AGENT' => empty($_SERVER['HTTP_USER_AGENT']) ? '' : $_SERVER['HTTP_USER_AGENT'],
575 'GET' => empty($_GET) ? array() : $_GET,
580 if (!empty(self::$deleted)) {
581 $out['DELETED_DATAOBJECTS'] = self::$deleted;
583 if ($extra_data !== false) {
584 $out['EXTRA'] = $extra_data;
586 if ( self::$extra_data !== false) {
587 $out['EXTRA_DATA'] = self::$extra_data;
590 file_put_contents($file, json_encode($out));
595 function toRooArray( $q)
597 $ret = $this->toArray();
599 // fill toEventString.
600 if (!empty($q['_with_obj_summary']) && !empty($this->on_id)) {
601 $obj = $this->object();
603 if ($obj && $obj->pid() && method_exists($obj,'toEventString')) {
604 $es = $obj->toEventString();
606 if (empty($this->remarks) || strpos($this->remarks, $es) < 0) {
607 $ret['remarks'] = $es . ' ' . $this->remarks;
609 } else if (empty($this->remarks)){
610 $ret['remarks'] = "DELETED";
619 function toRooSingleArray($au, $q)
621 $ret = $this->toArray();
625 if(empty($q['_retrieve_source'])){
629 $file = $this->retrieveEventLog();
632 return "No records?!";
635 $source = json_decode(file_get_contents($file));
640 function retrieveEventLog()
643 $logdir = $this->logDir();
649 $date = date('/Y/m/d/', strtotime($this->event_when));
651 $file = $logdir. $date. $this->id . ".json";
652 if (!file_exists(dirname($file))) {
659 function restore($roo)
661 $file = $this->retrieveEventLog();
663 if(empty($file) || !file_exists($file)){
664 $roo->jerr('Could not retrieve the event log file');
667 $log = json_decode(file_get_contents($file), true);
669 if(empty($log['POST']) || empty($log['POST']['_delete']) || empty($log['DELETED_DATAOBJECTS'])){
670 $roo->jerr('Invalid url');
675 foreach ($log['DELETED_DATAOBJECTS'] as $d){
678 empty($d['_table']) ||
680 !empty($restored[$d['_table']]) &&
681 in_array($d['id'], $restored[$d['_table']])
687 if(!isset($restored[$d['_table']])){
688 $restored[$d['_table']] = array();
691 $restored[$d['_table']][] = $d['id'];
693 $table = DB_DataObject::factory($d['_table']);
695 if (!is_a($table,'DB_DataObject')) {
704 * need to use the old id
706 $table->id = $d['id'];
708 $table->sequenceKey(false,false);
712 if($table->tableName() == 'crm_mailing_list_member'){
713 $ml = DB_DataObject::factory('crm_mailing_list');
714 if(!$ml->get($table->mailing_list_id)){
718 $mlm = DB_DataObject::factory('crm_mailing_list_member');
720 'mailing_list_id' => $table->mailing_list_id,
725 $ml->no_members = $mlm->count();
730 $roo->jok('RESTORE');
732 function selectAddPersonEmail()
734 $this->selectAdd('join_person_id_id.email as email');