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)
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 $et = DB_DataObject::factory($tn);
45 if(!array_key_exists("{$jt->tableName()}_id", $this->tableColumns())){ // coz we have triiger on mysql...
49 $this->_join = "LEFT JOIN {$jt->tableName()} AS join_person_id_id ON (join_person_id_id.{$keys[0]}=Events.person_id)";
53 $this->selectAs($jt, 'person_id_%s', 'join_person_id_id');
55 if (method_exists($jt,'nameColumn')) {
56 $this->selectAdd("join_person_id_id.{$jt->nameColumn()} as person_id_name");
59 if (method_exists($jt,'emailColumn')) {
60 $this->selectAdd("join_person_id_id.{$jt->emailColumn()} as person_id_email");
67 $person = $au->tableName(); //'Person'; -- projects may not use person as the auth table...
68 $cfg = HTML_FlexyFramework::get()->Pman;
69 if (!empty($cfg['authTable'])) {
70 $person =$cfg['authTable'];
73 $jt = DB_DataObject::factory($person);
75 person_table = '{$jt->tableName()}'
78 OR person_table IS NULL"
79 ); // default to our standard.. - unless otherwise requested..
83 if (!empty($q['query']['from'])) {
84 $dt = date('Y-m-d' , strtotime($q['query']['from']));
85 $this->whereAdd(" {$tn}.event_when >= '$dt' ");
87 if (!empty($q['query']['to'])) {
88 $dt = date('Y-m-d' , strtotime($q['query']['to']));
89 $this->whereAdd(" {$tn}.event_when <= '$dt' ");
92 if (!empty($q['query']['grouped']) && $q['query']['grouped'] == 'gr') {
94 DB_DataObject::Debuglevel(1);
95 $this->groupBy('on_id');
97 (SELECT count(id) FROM core_event_audit WHERE event_id = Events.id) as changed
102 if (!$au->hasPerm("Admin.Admin_Tab", 'S')) {
103 //DB_DataObject::DebugLevel(1);
104 // they can only view their changes..
105 $this->whereAdd("($tn.person_id = {$au->id} OR $tn.person_id = 0)");
106 // $this->person_id = $au->id;
109 // _join = tablename,tablename...
113 // &_join_cols=cohead_number
114 // &_columns=on_id_cohead_number,event_when << this is ignored at present.
115 // max(event_when) is not supported... by any query yet..
117 if (isset($q['on_table']) && !strlen($q['on_table'])) {
118 // empty ontable queries.. these are valid..
119 $this->whereAdd("$tn.on_table = ''");
122 if (isset($q['query']['person_sum'])) {
123 //DB_DataObject::debugLevel(1);
124 $this->_extra_cols = array('qty' );
125 $this->selectAdd("count($tn.id) as qty");
126 $this->selectAdd("count( distinct $tn.on_id) as uqty");
127 $this->whereAdd('LENGTH(join_person_id_id.name) > 0 ');
128 $this->groupBy('person_id,join_person_id_id.name,join_person_id_id.email');
130 if (isset($q['query']['table_sum'])) {
131 //DB_DataObject::debugLevel(1);
132 $this->_extra_cols = array('qty' , 'uqty');
133 $this->selectAdd("count($tn.id) as qty");
134 $this->selectAdd("count( distinct $tn.on_table, $tn.on_id) as uqty");
136 $this->groupBy('on_table');
138 if (isset($q['query']['day_sum'])) {
139 //DB_DataObject::debugLevel(1);
140 $this->_extra_cols = array('qty' , 'uqty');
141 $this->selectAdd("DATE_FORMAT(event_when, '%Y-%m-%d') as on_day");
142 $this->selectAdd("count($tn.id) as qty");
143 $this->selectAdd("count( distinct $tn.on_id) as uqty");
145 $this->groupBy('on_day');
148 if (isset($q['_join'])) {
149 //DB_DataObject::DebugLevel(1);
150 $joins = explode(',',$q['_join']);
152 $this->selectAdd(); // ???
155 foreach($joins as $t) {
156 $t = preg_replace('/[^a-z_]+/', '', $t); // protection.
157 $x = DB_DataObject::Factory($t);
158 if (!is_a($x,'DB_DataObject')) {
161 $jtn = $x->tableName();
162 $jk = array_shift($x->keys());
165 LEFT JOIN {$jtn} as join_on_id_{$jtn} ON {$tn}.on_id = join_on_id_{$jtn}.{$jk}
166 AND on_table = '{$jtn}'
168 $keys = array_keys($x->tableColumns());
169 if (isset($q['_join_cols'])) {
170 $jcs = explode(',',$q['_join_cols'] );
171 //DB_DataObject::DebugLevel(1);
173 foreach($jcs as $jc) {
174 if (! in_array($jc, $keys)) {
180 $this->selectAdd( " join_on_id_{$jtn}.{$jc} as on_id_{$jc} ");
182 $this->selectAdd( " distinct(join_on_id_{$jtn}.{$jc} ) as on_id_{$jc} ");
185 $this->groupBy("on_id_{$jc} ");
186 $this->whereAdd("join_on_id_{$jtn}.{$jc} IS NOT NULL");
188 $this->selectAdd( "MAX(events.event_when) as event_when");
189 $this->orderBy('event_when DESC');
190 // $this->selectAs(array($q['_join_cols']) , 'on_id_%s', "join_on_id_{$jtn}");
192 $this->selectAs($x, 'on_id_%s', "join_on_id_{$jtn}");
199 if (isset($q['_related_on_id']) && isset($q['_related_on_table'])) {
200 // example: sales order - has invoices,
201 ///DB_DataObject::DebugLevel(1);
202 $ev =$this->factory('Events');
204 'on_id' => $q['_related_on_id'],
205 'on_table' => $q['_related_on_table'],
207 $obj = $ev->object();
210 $roo->jerr("ontable is invalid");
212 if (!method_exists($obj,'relatedWhere')) {
213 $roo->jerr( $q['_related_on_table'] . " Does not have method relatedWhere :" .
214 implode(',', get_class_methods($obj)));
216 if ($obj && method_exists($obj,'relatedWhere')) {
217 $ar = $obj->relatedWhere();
218 $tn = $this->tableName();
221 $w[] = "( {$tn}.on_table = '" .
222 $this->escape($q['_related_on_table']) .
223 "' AND {$tn}.on_id = ". ((int) $q['_related_on_id']) .
227 foreach($ar as $k=>$v) {
231 $w[] = "( {$tn}.on_table = '$k' AND {$tn}.on_id IN (". implode(',', $v). "))";
234 $this->whereAdd(implode(' OR ' , $w));
242 // since roo does not support autojoin yet..
243 if (!isset($q['_distinct'])) {
244 //$this->autoJoinExtra();
247 if(!empty($q['query']['action'])) {
248 $act = $this->escape($q['query']['action']);
249 $this->whereAdd("Events.action LIKE '%{$act}%'");
252 if(!empty($q['query']['on_table'])) {
253 $tnb = $this->escape($q['query']['on_table']);
254 $this->whereAdd("Events.on_table LIKE '%{$tnb}%'");
262 * check who is trying to access this. false == access denied..
263 * @return {boolean} true if access is allowed.
265 function checkPerm($lvl, $au)
270 // listing is controleed by applyfilters..
271 return $au->hasPerm("Admin.Admin_Tab", 'S');
275 * return the object that this relates to.
277 * @return {DB_DataObject} related object
281 $o = DB_DataObject::factory($this->on_table);
282 $o->get($this->on_id);
290 * Initialize an event - ready to insert..
292 * @param {String} action - group/name of event
293 * @param {DataObject|false} obj - dataobject action occured on.
294 * @param {String} any remarks
297 function init($act, $obj, $remarks)
299 $ff = HTML_FlexyFramework::get();
301 $au = $pg->getAuthUser();
303 if ($ff->cli) { // && empty($au) && isset($obj->person_id)) {
305 // $au = DB_DataObject::Factory('Person'); // not always a person..
306 // $au->get($obj->person_id);
309 $this->person_name = $au && !empty($au->name) ? $au->name : '';
310 if (empty($au) || (isset($au->id) && empty($au->id))) {
311 // not authenticated - and a standard id based object
312 $this->person_id = 0;
314 $col = $au->tableName() == "Person" ? 'person_id' : $au->tableName() . '_id';
316 $cols = $this->tableColumns();
317 $col = isset($cols[$col]) ? $col : 'person_id'; // for BC.... - revert to using person_id
318 $this->{$col} = $au->pid();
319 //$this->person_id = $au ? (!empty($au->id) ? $au->id : $au->pid()) : -1;
321 $this->person_table = $au ? $au->tableName() : '';
322 $this->ipaddr = isset($_SERVER["REMOTE_ADDR"]) ? $_SERVER["REMOTE_ADDR"] : 'cli';
323 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
324 $this->ipaddr = $_SERVER['HTTP_X_FORWARDED_FOR'];
327 $this->action = $act;
328 $this->on_table = $obj ? $obj->tableName() : '';
329 $pk = $obj ? $obj->keys() : false;
330 $this->on_id = $obj && $pk ? $obj->{$pk[0]}: 0;
332 // should this really go in remarks? -
333 if ($obj && method_exists($obj,'toEventString')) {
334 if($obj->toEventString() !== false){
335 $rem[] = $obj->toEventString();
339 $this->remarks = implode(' : ', $rem);
343 * Generate an audit for this field.
345 * @param {DB_DataObject} new data
346 * @param {DB_DataObject} old data
348 * @return {int} number of entries logged.
351 function audit($new, $old = false)
354 return 0; // they are the same...
358 foreach(array_keys($new->tableColumns()) as $k) {
359 // should we JSON serialize this?
360 $n = empty($new->$k) ? '' : $new->$k;
361 $o = empty($old->$k) || empty($old->$k) ? '' : $old->$k;
365 $this->auditField($k, $o, $n, $old);
371 * Record an audited change, in theory so we can audit data that is not just
374 * @param {string} $name table field anme
375 * @param {mixed} $ov old value
376 * @param {mixed} $onv new value
377 * @param {mixed} $old old object (false if we are creating..)
379 function auditField($name, $ov, $nv, $old=false )
382 if (is_object($nv)) {
387 $x = DB_DataObject::factory('core_event_audit');
389 'event_id' => $this->id,
391 'old_audit_id' => $old ? $x->findLast($this, $name) : 0,
399 function beforeInsert($request,$roo)
401 if(empty($this->event_when)){
402 $this->event_when = $this->sqlValue("NOW()");
405 if(empty($this->person_id)){
406 $this->person_id = $roo->authUser->id;
407 $this->person_name = $roo->authUser->name;
408 $this->person_table = $roo->authUser->tableName();
411 if(empty($this->ipaddr)){
412 $this->ipaddr = isset($_SERVER["REMOTE_ADDR"]) ? $_SERVER["REMOTE_ADDR"] : 'cli';
413 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
414 $this->ipaddr = $_SERVER['HTTP_X_FORWARDED_FOR'];
419 function beforeUpdate($old, $request,$roo)
421 if(!empty($request['_restore'])){
422 $this->restore($roo);
426 function onInsert($request,$roo)
428 $this->writeEventLog();
431 static $deleted = array();
434 // log deleting of a record so that it can be written later..
435 function logDeletedRecord($obj = false)
437 if (is_array($obj)) {
439 foreach($obj as $o) {
440 $aret = $this->logDeletedRecord($o);
441 $ret = $ret ? $ret : $aret;
446 if(empty($obj) || !is_a($obj, 'DB_DataObject')){
451 $del = $obj->toArray();
452 $del['_table'] = $obj->tableName();
454 self::$deleted[] = $del;
457 static $extra_data = false;
459 static function writeEventLogExtra($data) {
460 self::$extra_data = $data;
465 $ff = HTML_FlexyFramework::get();
466 if (function_exists('posix_getpwuid')) {
467 $uinfo = posix_getpwuid( posix_getuid () );
469 $user = $uinfo['name'];
471 $user = getenv('USERNAME'); // windows.
475 if (!empty($ff->Pman['event_log_dir'])) {
476 return $ff->Pman['event_log_dir'] . '/'.$user;
478 if (!empty($ff->Pman['storedir'])) {
479 return $ff->Pman['storedir'] .'/Events/'.$user;
487 function writeEventLog($extra_data = false)
489 $logdir = $this->logDir();
496 $file = $logdir. date('/Y/m/d/'). $this->id . ".json";
497 if (!file_exists(dirname($file))) {
499 @mkdir(dirname($file),0700,true); // this might fail if it does not have correct permissions..
500 if (!file_exists(dirname($file))) {
501 die("could not create $file - permissons are not correct"); // fatal, otherwise we loop!?
506 // Remove all the password from logs...
507 $p = empty($_POST) ? array() : $_POST;
508 foreach(array('passwd', 'password','passwd1', 'passwd2','password1', 'password2') as $rm) {
509 if (isset($p[$rm])) {
519 foreach ($_FILES as $k=>$f){
520 // does not handle any other file[] arrary very well..
521 if (empty($f['tmp_name']) || !file_exists($f['tmp_name'])) {
528 $files[$k]['tmp_name'] = $this->id . '-'. $i;
529 $nf = $logdir . date('/Y/m/d/'). $files[$k]['tmp_name'];
530 if (!copy($f['tmp_name'], $nf)) {
531 print_r("failed to copy {$f['tmp_name']}...\n");
535 'REQUEST_URI' => empty($_SERVER['REQUEST_URI']) ? 'cli' : $_SERVER['REQUEST_URI'],
536 'HTTP_USER_AGENT' => empty($_SERVER['HTTP_USER_AGENT']) ? '' : $_SERVER['HTTP_USER_AGENT'],
537 'GET' => empty($_GET) ? array() : $_GET,
542 if (!empty(self::$deleted)) {
543 $out['DELETED_DATAOBJECTS'] = self::$deleted;
545 if ($extra_data !== false) {
546 $out['EXTRA'] = $extra_data;
548 if ( self::$extra_data !== false) {
549 $out['EXTRA_DATA'] = self::$extra_data;
552 file_put_contents($file, json_encode($out));
557 function toRooArray( $q)
559 $ret = $this->toArray();
561 // fill toEventString.
562 if (!empty($q['_with_obj_summary']) && !empty($this->on_id)) {
563 $obj = $this->object();
565 if ($obj && $obj->pid() && method_exists($obj,'toEventString')) {
566 $es = $obj->toEventString();
568 if (empty($this->remarks) || strpos($this->remarks, $es) < 0) {
569 $ret['remarks'] = $es . ' ' . $this->remarks;
571 } else if (empty($this->remarks)){
572 $ret['remarks'] = "DELETED";
581 function toRooSingleArray($au, $q)
583 $ret = $this->toArray();
587 if(empty($q['_retrieve_source'])){
591 $file = $this->retrieveEventLog();
594 return "No records?!";
597 $source = json_decode(file_get_contents($file));
602 function retrieveEventLog()
605 $logdir = $this->logDir();
611 $date = date('/Y/m/d/', strtotime($this->event_when));
613 $file = $logdir. $date. $this->id . ".json";
614 if (!file_exists(dirname($file))) {
621 function restore($roo)
623 $file = $this->retrieveEventLog();
625 if(empty($file) || !file_exists($file)){
626 $roo->jerr('Could not retrieve the event log file');
629 $log = json_decode(file_get_contents($file), true);
631 if(empty($log['POST']) || empty($log['POST']['_delete']) || empty($log['DELETED_DATAOBJECTS'])){
632 $roo->jerr('Invalid url');
637 foreach ($log['DELETED_DATAOBJECTS'] as $d){
640 empty($d['_table']) ||
642 !empty($restored[$d['_table']]) &&
643 in_array($d['id'], $restored[$d['_table']])
649 if(!isset($restored[$d['_table']])){
650 $restored[$d['_table']] = array();
653 $restored[$d['_table']][] = $d['id'];
655 $table = DB_DataObject::factory($d['_table']);
657 if (!is_a($table,'DB_DataObject')) {
666 * need to use the old id
668 $table->id = $d['id'];
670 $table->sequenceKey(false,false);
674 if($table->tableName() == 'crm_mailing_list_member'){
675 $ml = DB_DataObject::factory('crm_mailing_list');
676 if(!$ml->get($table->mailing_list_id)){
680 $mlm = DB_DataObject::factory('crm_mailing_list_member');
682 'mailing_list_id' => $table->mailing_list_id,
687 $ml->no_members = $mlm->count();
692 $roo->jok('RESTORE');
694 function selectAddPersonEmail()
696 $this->selectAdd('join_person_id_id.email as email');