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 if (!$au->hasPerm("Admin.Admin_Tab", 'S')) {
111 //DB_DataObject::DebugLevel(1);
112 // they can only view their changes..
113 $this->whereAdd("($tn.person_id = {$au->id} OR $tn.person_id = 0)");
114 // $this->person_id = $au->id;
117 // _join = tablename,tablename...
121 // &_join_cols=cohead_number
122 // &_columns=on_id_cohead_number,event_when << this is ignored at present.
123 // max(event_when) is not supported... by any query yet..
125 if (isset($q['on_table']) && !strlen($q['on_table'])) {
126 // empty ontable queries.. these are valid..
127 $this->whereAdd("$tn.on_table = ''");
130 if (isset($q['query']['person_sum'])) {
131 //DB_DataObject::debugLevel(1);
132 $this->_extra_cols = array('qty' );
133 $this->selectAdd("count($tn.id) as qty");
134 $this->selectAdd("count( distinct $tn.on_id) as uqty");
135 $this->whereAdd('LENGTH(join_person_id_id.name) > 0 ');
136 $this->groupBy('person_id,join_person_id_id.name,join_person_id_id.email');
138 if (isset($q['query']['table_sum'])) {
139 //DB_DataObject::debugLevel(1);
140 $this->_extra_cols = array('qty' , 'uqty');
141 $this->selectAdd("count($tn.id) as qty");
142 $this->selectAdd("count( distinct $tn.on_table, $tn.on_id) as uqty");
144 $this->groupBy('on_table');
146 if (isset($q['query']['day_sum'])) {
147 //DB_DataObject::debugLevel(1);
148 $this->_extra_cols = array('qty' , 'uqty');
149 $this->selectAdd("DATE_FORMAT(event_when, '%Y-%m-%d') as on_day");
150 $this->selectAdd("count($tn.id) as qty");
151 $this->selectAdd("count( distinct $tn.on_id) as uqty");
153 $this->groupBy('on_day');
156 if (isset($q['_join'])) {
157 //DB_DataObject::DebugLevel(1);
158 $joins = explode(',',$q['_join']);
160 $this->selectAdd(); // ???
163 foreach($joins as $t) {
164 $t = preg_replace('/[^a-z_]+/', '', $t); // protection.
165 $x = DB_DataObject::Factory($t);
166 if (!is_a($x,'DB_DataObject')) {
169 $jtn = $x->tableName();
170 $jk = array_shift($x->keys());
173 LEFT JOIN {$jtn} as join_on_id_{$jtn} ON {$tn}.on_id = join_on_id_{$jtn}.{$jk}
174 AND on_table = '{$jtn}'
176 $keys = array_keys($x->tableColumns());
177 if (isset($q['_join_cols'])) {
178 $jcs = explode(',',$q['_join_cols'] );
179 //DB_DataObject::DebugLevel(1);
181 foreach($jcs as $jc) {
182 if (! in_array($jc, $keys)) {
188 $this->selectAdd( " join_on_id_{$jtn}.{$jc} as on_id_{$jc} ");
190 $this->selectAdd( " distinct(join_on_id_{$jtn}.{$jc} ) as on_id_{$jc} ");
193 $this->groupBy("on_id_{$jc} ");
194 $this->whereAdd("join_on_id_{$jtn}.{$jc} IS NOT NULL");
196 $this->selectAdd( "MAX(events.event_when) as event_when");
197 $this->orderBy('event_when DESC');
198 // $this->selectAs(array($q['_join_cols']) , 'on_id_%s', "join_on_id_{$jtn}");
200 $this->selectAs($x, 'on_id_%s', "join_on_id_{$jtn}");
207 if (isset($q['_related_on_id']) && isset($q['_related_on_table'])) {
208 // example: sales order - has invoices,
209 ///DB_DataObject::DebugLevel(1);
210 $ev =$this->factory('Events');
212 'on_id' => $q['_related_on_id'],
213 'on_table' => $q['_related_on_table'],
215 $obj = $ev->object();
218 $roo->jerr("ontable is invalid");
221 if (!method_exists($obj,'relatedWhere') && !method_exists($obj,'relatedEventsWhere')) {
222 $roo->jerr( $q['_related_on_table'] . " Does not have method relatedWhere or relatedEventsWhere:" .
223 implode(',', get_class_methods($obj)));
225 if ($obj && method_exists($obj,'relatedWhere')) {
226 $ar = $obj->relatedWhere();
227 $tn = $this->tableName();
230 $w[] = "( {$tn}.on_table = '" .
231 $this->escape($q['_related_on_table']) .
232 "' AND {$tn}.on_id = ". ((int) $q['_related_on_id']) .
236 foreach($ar as $k=>$v) {
240 $w[] = "( {$tn}.on_table = '$k' AND {$tn}.on_id IN (". implode(',', $v). "))";
243 $this->whereAdd(implode(' OR ' , $w));
246 if ($obj && method_exists($obj,'relatedEventsWhere')) {
247 $a = $obj->relatedEventsWhere($q,$roo);
257 if (!isset($q['_who'])) {
258 $this->autoJoinExtData();
259 $this->autoJoinCorePerson();
260 $this->selectAddWho();
263 // since roo does not support autojoin yet..
264 if (!isset($q['_distinct'])) {
265 //$this->autoJoinExtra();
268 if(!empty($q['query']['action'])) {
269 $act = $this->escape($q['query']['action']);
270 $this->whereAdd("Events.action LIKE '%{$act}%'");
273 if(!empty($q['query']['on_table'])) {
274 $tnb = $this->escape($q['query']['on_table']);
275 $this->whereAdd("Events.on_table LIKE '%{$tnb}%'");
283 * check who is trying to access this. false == access denied..
284 * @return {boolean} true if access is allowed.
286 function checkPerm($lvl, $au)
291 // listing is controleed by applyfilters..
292 return $au->hasPerm("Admin.Admin_Tab", 'S');
296 * return the object that this relates to.
298 * @return {DB_DataObject} related object
302 $o = DB_DataObject::factory($this->on_table);
303 $o->get($this->on_id);
311 * Initialize an event - ready to insert..
313 * @param {String} action - group/name of event
314 * @param {DataObject|false} obj - dataobject action occured on.
315 * @param {String} any remarks
318 function init($act, $obj, $remarks)
320 $ff = HTML_FlexyFramework::get();
322 $au = $pg->getAuthUser();
324 if ($ff->cli) { // && empty($au) && isset($obj->person_id)) {
326 // $au = DB_DataObject::Factory('Person'); // not always a person..
327 // $au->get($obj->person_id);
330 $this->person_name = $au && !empty($au->name) ? $au->name : '';
333 //$this->who = $au && !empty($au->name) ? $au->name : '';
334 if (empty($au) || (isset($au->id) && empty($au->id))) {
335 // not authenticated - and a standard id based object
336 $this->person_id = 0;
338 $col = $au->tableName() == "Person" ? 'person_id' : $au->tableName() . '_id';
340 $cols = $this->tableColumns();
341 $col = isset($cols[$col]) ? $col : 'person_id'; // for BC.... - revert to using person_id
342 $this->{$col} = $au->pid();
343 //$this->person_id = $au ? (!empty($au->id) ? $au->id : $au->pid()) : -1;
345 $this->person_table = $au ? $au->tableName() : '';
346 $this->ipaddr = isset($_SERVER["REMOTE_ADDR"]) ? $_SERVER["REMOTE_ADDR"] : 'cli';
347 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
348 $this->ipaddr = $_SERVER['HTTP_X_FORWARDED_FOR'];
351 $this->action = $act;
352 $this->on_table = $obj ? $obj->tableName() : '';
353 $pk = $obj ? $obj->keys() : false;
354 $this->on_id = $obj && $pk ? $obj->{$pk[0]}: 0;
356 // should this really go in remarks? -
357 if ($obj && method_exists($obj,'toEventString')) {
358 if($obj->toEventString() !== false){
359 $rem[] = $obj->toEventString();
363 $this->remarks = implode(' : ', $rem);
367 * Generate an audit for this field.
369 * @param {DB_DataObject} new data
370 * @param {DB_DataObject} old data
372 * @return {int} number of entries logged.
375 function audit($new, $old = false)
378 return 0; // they are the same...
382 foreach(array_keys($new->tableColumns()) as $k) {
383 // should we JSON serialize this?
384 $n = empty($new->$k) ? '' : $new->$k;
385 $o = empty($old->$k) || empty($old->$k) ? '' : $old->$k;
389 $this->auditField($k, $o, $n, $old);
395 * Record an audited change, in theory so we can audit data that is not just
398 * @param {string} $name table field anme
399 * @param {mixed} $ov old value
400 * @param {mixed} $onv new value
401 * @param {mixed} $old old object (false if we are creating..)
403 function auditField($name, $ov, $nv, $old=false )
406 if (is_object($nv)) {
411 $x = DB_DataObject::factory('core_event_audit');
413 'event_id' => $this->id,
415 'old_audit_id' => $old ? $x->findLast($this, $name) : 0,
423 function beforeInsert($request,$roo)
425 if(empty($this->event_when)){
426 $this->event_when = $this->sqlValue("NOW()");
429 if(empty($this->person_id)){
430 $this->person_id = $roo->authUser->id;
431 $this->person_name = $roo->authUser->name;
432 $this->person_table = $roo->authUser->tableName();
435 if(empty($this->ipaddr)){
436 $this->ipaddr = isset($_SERVER["REMOTE_ADDR"]) ? $_SERVER["REMOTE_ADDR"] : 'cli';
437 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
438 $this->ipaddr = $_SERVER['HTTP_X_FORWARDED_FOR'];
443 function beforeUpdate($old, $request,$roo)
445 if(!empty($request['_restore'])){
446 $this->restore($roo);
450 function onInsert($request,$roo)
452 $this->writeEventLog();
455 static $deleted = array();
458 // log deleting of a record so that it can be written later..
459 function logDeletedRecord($obj = false)
461 if (is_array($obj)) {
463 foreach($obj as $o) {
464 $aret = $this->logDeletedRecord($o);
465 $ret = $ret ? $ret : $aret;
470 if(empty($obj) || !is_a($obj, 'DB_DataObject')){
475 $del = $obj->toArray();
476 $del['_table'] = $obj->tableName();
478 self::$deleted[] = $del;
481 static $extra_data = false;
483 static function writeEventLogExtra($data) {
484 self::$extra_data = $data;
489 $ff = HTML_FlexyFramework::get();
490 if (function_exists('posix_getpwuid')) {
491 $uinfo = posix_getpwuid( posix_getuid () );
493 $user = $uinfo['name'];
495 $user = getenv('USERNAME'); // windows.
499 if (!empty($ff->Pman['event_log_dir'])) {
500 return $ff->Pman['event_log_dir'] . '/'.$user;
502 if (!empty($ff->Pman['storedir'])) {
503 return $ff->Pman['storedir'] .'/Events/'.$user;
511 function writeEventLog($extra_data = false)
513 $logdir = $this->logDir();
520 $file = $logdir. date('/Y/m/d/'). $this->id . ".json";
521 if (!file_exists(dirname($file))) {
523 @mkdir(dirname($file),0700,true); // this might fail if it does not have correct permissions..
524 if (!file_exists(dirname($file))) {
525 die("could not create $file - permissons are not correct"); // fatal, otherwise we loop!?
530 // Remove all the password from logs...
531 $p = empty($_POST) ? array() : $_POST;
532 foreach(array('passwd', 'password','passwd1', 'passwd2','password1', 'password2') as $rm) {
533 if (isset($p[$rm])) {
543 foreach ($_FILES as $k=>$f){
544 // does not handle any other file[] arrary very well..
545 if (empty($f['tmp_name']) || !file_exists($f['tmp_name'])) {
552 $files[$k]['tmp_name'] = $this->id . '-'. $i;
553 $nf = $logdir . date('/Y/m/d/'). $files[$k]['tmp_name'];
554 if (!copy($f['tmp_name'], $nf)) {
555 print_r("failed to copy {$f['tmp_name']}...\n");
559 'REQUEST_URI' => empty($_SERVER['REQUEST_URI']) ? 'cli' : $_SERVER['REQUEST_URI'],
560 'HTTP_USER_AGENT' => empty($_SERVER['HTTP_USER_AGENT']) ? '' : $_SERVER['HTTP_USER_AGENT'],
561 'GET' => empty($_GET) ? array() : $_GET,
566 if (!empty(self::$deleted)) {
567 $out['DELETED_DATAOBJECTS'] = self::$deleted;
569 if ($extra_data !== false) {
570 $out['EXTRA'] = $extra_data;
572 if ( self::$extra_data !== false) {
573 $out['EXTRA_DATA'] = self::$extra_data;
576 file_put_contents($file, json_encode($out));
581 function toRooArray( $q)
583 $ret = $this->toArray();
585 // fill toEventString.
586 if (!empty($q['_with_obj_summary']) && !empty($this->on_id)) {
587 $obj = $this->object();
589 if ($obj && $obj->pid() && method_exists($obj,'toEventString')) {
590 $es = $obj->toEventString();
592 if (empty($this->remarks) || strpos($this->remarks, $es) < 0) {
593 $ret['remarks'] = $es . ' ' . $this->remarks;
595 } else if (empty($this->remarks)){
596 $ret['remarks'] = "DELETED";
605 function toRooSingleArray($au, $q)
607 $ret = $this->toArray();
611 if(empty($q['_retrieve_source'])){
615 $file = $this->retrieveEventLog();
618 return "No records?!";
621 $source = json_decode(file_get_contents($file));
626 function retrieveEventLog()
629 $logdir = $this->logDir();
635 $date = date('/Y/m/d/', strtotime($this->event_when));
637 $file = $logdir. $date. $this->id . ".json";
638 if (!file_exists(dirname($file))) {
645 function restore($roo)
647 $file = $this->retrieveEventLog();
649 if(empty($file) || !file_exists($file)){
650 $roo->jerr('Could not retrieve the event log file');
653 $log = json_decode(file_get_contents($file), true);
655 if(empty($log['POST']) || empty($log['POST']['_delete']) || empty($log['DELETED_DATAOBJECTS'])){
656 $roo->jerr('Invalid url');
661 foreach ($log['DELETED_DATAOBJECTS'] as $d){
664 empty($d['_table']) ||
666 !empty($restored[$d['_table']]) &&
667 in_array($d['id'], $restored[$d['_table']])
673 if(!isset($restored[$d['_table']])){
674 $restored[$d['_table']] = array();
677 $restored[$d['_table']][] = $d['id'];
679 $table = DB_DataObject::factory($d['_table']);
681 if (!is_a($table,'DB_DataObject')) {
690 * need to use the old id
692 $table->id = $d['id'];
694 $table->sequenceKey(false,false);
698 if($table->tableName() == 'crm_mailing_list_member'){
699 $ml = DB_DataObject::factory('crm_mailing_list');
700 if(!$ml->get($table->mailing_list_id)){
704 $mlm = DB_DataObject::factory('crm_mailing_list_member');
706 'mailing_list_id' => $table->mailing_list_id,
711 $ml->no_members = $mlm->count();
716 $roo->jok('RESTORE');
718 function selectAddPersonEmail()
720 $this->selectAdd('join_person_id_id.email as email');
724 function autoJoinExtData()
726 $this->_join .= "LEFT JOIN
727 ext_data AS ext_data_id
729 Events.modx_users_id = ext_data_id.userdata_id";
732 function autoJoinCorePerson()
734 $this->_join .= "LEFT JOIN
735 core_person AS core_person_id
737 Events.person_id = core_person_id.id";
740 function selectAddWho()
743 core_person_id.name AS person_name,
745 WHEN ext_data_id.in_middlename='' THEN
746 CONCAT_WS(' ', ext_data_id.in_firstname,ext_data_id.in_lastname)
748 CONCAT_WS(' ', ext_data_id.in_firstname,ext_data_id.in_middlename,ext_data_id.in_lastname)
749 END AS ext_data_full_name