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 if(!array_key_exists("{$jt->tableName()}_id", $this->table())){ // coz we have triiger on mysql...
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");
65 $person = $au->tableName(); //'Person'; -- projects may not use person as the auth table...
66 $cfg = HTML_FlexyFramework::get()->Pman;
67 if (!empty($cfg['authTable'])) {
68 $person =$cfg['authTable'];
71 $jt = DB_DataObject::factory($person);
73 person_table = '{$jt->tableName()}'
76 OR person_table IS NULL"
77 ); // default to our standard.. - unless otherwise requested..
81 if (!empty($q['query']['from'])) {
82 $dt = date('Y-m-d' , strtotime($q['query']['from']));
83 $this->whereAdd(" {$tn}.event_when >= '$dt' ");
85 if (!empty($q['query']['to'])) {
86 $dt = date('Y-m-d' , strtotime($q['query']['to']));
87 $this->whereAdd(" {$tn}.event_when <= '$dt' ");
90 if (!empty($q['query']['grouped']) && $q['query']['grouped'] == 'gr') {
92 DB_DataObject::Debuglevel(1);
93 $this->groupBy('on_id');
95 (SELECT count(id) FROM core_event_audit WHERE event_id = Events.id) as changed
100 if (!$au->hasPerm("Admin.Admin_Tab", 'S')) {
101 //DB_DataObject::DebugLevel(1);
102 // they can only view their changes..
103 $this->person_id = $au->id;
106 // _join = tablename,tablename...
110 // &_join_cols=cohead_number
111 // &_columns=on_id_cohead_number,event_when << this is ignored at present.
112 // max(event_when) is not supported... by any query yet..
114 if (isset($q['on_table']) && !strlen($q['on_table'])) {
115 // empty ontable queries.. these are valid..
116 $this->whereAdd("$tn.on_table = ''");
121 if (isset($q['query']['person_sum'])) {
122 //DB_DataObject::debugLevel(1);
123 $this->_extra_cols = array('qty' );
124 $this->selectAdd("count($tn.id) as qty");
125 $this->selectAdd("count( distinct $tn.on_id) as uqty");
126 $this->whereAdd('LENGTH(join_person_id_id.name) > 0 ');
127 $this->groupBy('person_id,join_person_id_id.name,join_person_id_id.email');
129 if (isset($q['query']['table_sum'])) {
130 //DB_DataObject::debugLevel(1);
131 $this->_extra_cols = array('qty' , 'uqty');
132 $this->selectAdd("count($tn.id) as qty");
133 $this->selectAdd("count( distinct $tn.on_table, $tn.on_id) as uqty");
135 $this->groupBy('on_table');
137 if (isset($q['query']['day_sum'])) {
138 //DB_DataObject::debugLevel(1);
139 $this->_extra_cols = array('qty' , 'uqty');
140 $this->selectAdd("DATE_FORMAT(event_when, '%Y-%m-%d') as on_day");
141 $this->selectAdd("count($tn.id) as qty");
142 $this->selectAdd("count( distinct $tn.on_id) as uqty");
144 $this->groupBy('on_day');
147 if (isset($q['_join'])) {
148 //DB_DataObject::DebugLevel(1);
149 $joins = explode(',',$q['_join']);
151 $this->selectAdd(); // ???
154 foreach($joins as $t) {
155 $t = preg_replace('/[^a-z_]+/', '', $t); // protection.
156 $x = DB_DataObject::Factory($t);
157 if (!is_a($x,'DB_DataObject')) {
160 $jtn = $x->tableName();
161 $jk = array_shift($x->keys());
164 LEFT JOIN {$jtn} as join_on_id_{$jtn} ON {$tn}.on_id = join_on_id_{$jtn}.{$jk}
165 AND on_table = '{$jtn}'
167 $keys = array_keys($x->table());
168 if (isset($q['_join_cols'])) {
169 $jcs = explode(',',$q['_join_cols'] );
170 //DB_DataObject::DebugLevel(1);
172 foreach($jcs as $jc) {
173 if (! in_array($jc, $keys)) {
179 $this->selectAdd( " join_on_id_{$jtn}.{$jc} as on_id_{$jc} ");
181 $this->selectAdd( " distinct(join_on_id_{$jtn}.{$jc} ) as on_id_{$jc} ");
184 $this->groupBy("on_id_{$jc} ");
185 $this->whereAdd("join_on_id_{$jtn}.{$jc} IS NOT NULL");
187 $this->selectAdd( "MAX(events.event_when) as event_when");
188 $this->orderBy('event_when DESC');
189 // $this->selectAs(array($q['_join_cols']) , 'on_id_%s', "join_on_id_{$jtn}");
191 $this->selectAs($x, 'on_id_%s', "join_on_id_{$jtn}");
198 if (isset($q['_related_on_id']) && isset($q['_related_on_table'])) {
199 // example: sales order - has invoices,
200 ///DB_DataObject::DebugLevel(1);
201 $ev =$this->factory('Events');
203 'on_id' => $q['_related_on_id'],
204 'on_table' => $q['_related_on_table'],
206 $obj = $ev->object();
209 $roo->jerr("ontable is invalid");
211 if (!method_exists($obj,'relatedWhere')) {
212 $roo->jerr( $q['_related_on_table'] . " Does not have method relatedWhere :" .
213 implode(',', get_class_methods($obj)));
215 if ($obj && method_exists($obj,'relatedWhere')) {
216 $ar = $obj->relatedWhere();
217 $tn = $this->tableName();
220 $w[] = "( {$tn}.on_table = '" .
221 $this->escape($q['_related_on_table']) .
222 "' AND {$tn}.on_id = ". ((int) $q['_related_on_id']) .
226 foreach($ar as $k=>$v) {
230 $w[] = "( {$tn}.on_table = '$k' AND {$tn}.on_id IN (". implode(',', $v). "))";
233 $this->whereAdd(implode(' OR ' , $w));
241 // since roo does not support autojoin yet..
242 if (!isset($q['_distinct'])) {
243 //$this->autoJoinExtra();
246 if(!empty($q['query']['action'])) {
247 $act = $this->escape($q['query']['action']);
248 $this->whereAdd("Events.action LIKE '%{$act}%'");
251 if(!empty($q['query']['on_table'])) {
252 $tnb = $this->escape($q['query']['on_table']);
253 $this->whereAdd("Events.on_table LIKE '%{$tnb}%'");
261 * check who is trying to access this. false == access denied..
262 * @return {boolean} true if access is allowed.
264 function checkPerm($lvl, $au)
269 // listing is controleed by applyfilters..
270 return $au->hasPerm("Admin.Admin_Tab", 'S');
274 * return the object that this relates to.
276 * @return {DB_DataObject} related object
280 $o = DB_DataObject::factory($this->on_table);
281 $o->get($this->on_id);
289 * Initialize an event - ready to insert..
291 * @param {String} action - group/name of event
292 * @param {DataObject|false} obj - dataobject action occured on.
293 * @param {String} any remarks
296 function init($act, $obj, $remarks)
298 $ff = HTML_FlexyFramework::get();
300 $au = $pg->getAuthUser();
302 if ($ff->cli) { // && empty($au) && isset($obj->person_id)) {
304 // $au = DB_DataObject::Factory('Person'); // not always a person..
305 // $au->get($obj->person_id);
308 $this->person_name = $au && !empty($au->name) ? $au->name : '';
309 if (empty($au) || (isset($au->id) && empty($au->id))) {
310 // not authenticated - and a standard id based object
311 $this->person_id = 0;
313 $col = $au->tableName() == "Person" ? 'person_id' : $au->tableName() . '_id';
315 $cols = $this->table();
316 $col = isset($cols[$col]) ? $col : 'person_id'; // for BC.... - revert to using person_id
317 $this->{$col} = $au->pid();
318 //$this->person_id = $au ? (!empty($au->id) ? $au->id : $au->pid()) : -1;
320 $this->person_table = $au ? $au->tableName() : '';
321 $this->ipaddr = isset($_SERVER["REMOTE_ADDR"]) ? $_SERVER["REMOTE_ADDR"] : 'cli';
322 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
323 $this->ipaddr = $_SERVER['HTTP_X_FORWARDED_FOR'];
326 $this->action = $act;
327 $this->on_table = $obj ? $obj->tableName() : '';
328 $pk = $obj ? $obj->keys() : false;
329 $this->on_id = $obj && $pk ? $obj->{$pk[0]}: 0;
331 // should this really go in remarks? -
332 if ($obj && method_exists($obj,'toEventString')) {
333 if($obj->toEventString() !== false){
334 $rem[] = $obj->toEventString();
338 $this->remarks = implode(' : ', $rem);
342 * Generate an audit for this field.
344 * @param {DB_DataObject} new data
345 * @param {DB_DataObject} old data
347 * @return {int} number of entries logged.
350 function audit($new, $old = false)
353 return 0; // they are the same...
357 foreach(array_keys($new->table()) as $k) {
358 // should we JSON serialize this?
359 $n = empty($new->$k) ? '' : $new->$k;
360 $o = empty($old->$k) || empty($old->$k) ? '' : $old->$k;
364 $this->auditField($k, $o, $n, $old);
370 * Record an audited change, in theory so we can audit data that is not just
373 * @param {string} $name table field anme
374 * @param {mixed} $ov old value
375 * @param {mixed} $onv new value
376 * @param {mixed} $old old object (false if we are creating..)
378 function auditField($name, $ov, $nv, $old=false )
381 if (is_object($nv)) {
386 $x = DB_DataObject::factory('core_event_audit');
388 'event_id' => $this->id,
390 'old_audit_id' => $old ? $x->findLast($this, $name) : 0,
398 function beforeInsert($request,$roo)
400 if(empty($this->event_when)){
401 $this->event_when = $this->sqlValue("NOW()");
404 if(empty($this->person_id)){
405 $this->person_id = $roo->authUser->id;
406 $this->person_name = $roo->authUser->name;
407 $this->person_table = $roo->authUser->tableName();
410 if(empty($this->ipaddr)){
411 $this->ipaddr = isset($_SERVER["REMOTE_ADDR"]) ? $_SERVER["REMOTE_ADDR"] : 'cli';
412 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
413 $this->ipaddr = $_SERVER['HTTP_X_FORWARDED_FOR'];
418 function beforeUpdate($old, $request,$roo)
420 if(!empty($request['_restore'])){
421 $this->restore($roo);
425 function onInsert($request,$roo)
427 $this->writeEventLog();
430 static $deleted = array();
433 // log deleting of a record so that it can be written later..
434 function logDeletedRecord($obj = false)
436 if (is_array($obj)) {
438 foreach($obj as $o) {
439 $aret = $this->logDeletedRecord($o);
440 $ret = $ret ? $ret : $aret;
445 if(empty($obj) || !is_a($obj, 'DB_DataObject')){
450 $del = $obj->toArray();
451 $del['_table'] = $obj->tableName();
453 self::$deleted[] = $del;
456 static $extra_data = false;
458 static function writeEventLogExtra($data) {
459 self::$extra_data = $data;
464 $ff = HTML_FlexyFramework::get();
465 if (function_exists('posix_getpwuid')) {
466 $uinfo = posix_getpwuid( posix_getuid () );
468 $user = $uinfo['name'];
470 $user = getenv('USERNAME'); // windows.
474 if (!empty($ff->Pman['event_log_dir'])) {
475 return $ff->Pman['event_log_dir'] . '/'.$user;
477 if (!empty($ff->Pman['storedir'])) {
478 return $ff->Pman['storedir'] .'/Events/'.$user;
486 function writeEventLog($extra_data = false)
488 $logdir = $this->logDir();
495 $file = $logdir. date('/Y/m/d/'). $this->id . ".json";
496 if (!file_exists(dirname($file))) {
497 mkdir(dirname($file),0700,true); // this might fail if it does not have correct permissions..
501 // Remove all the password from logs...
502 $p = empty($_POST) ? array() : $_POST;
503 foreach(array('passwd', 'password','passwd1', 'passwd2','password1', 'password2') as $rm) {
504 if (isset($p[$rm])) {
514 foreach ($_FILES as $k=>$f){
515 // does not handle any other file[] arrary very well..
516 if (empty($f['tmp_name']) || !file_exists($f['tmp_name'])) {
523 $files[$k]['tmp_name'] = $this->id . '-'. $i;
524 $nf = $logdir . date('/Y/m/d/'). $files[$k]['tmp_name'];
525 if (!copy($f['tmp_name'], $nf)) {
526 print_r("failed to copy {$f['tmp_name']}...\n");
530 'REQUEST_URI' => empty($_SERVER['REQUEST_URI']) ? 'cli' : $_SERVER['REQUEST_URI'],
531 'HTTP_USER_AGENT' => empty($_SERVER['HTTP_USER_AGENT']) ? '' : $_SERVER['HTTP_USER_AGENT'],
532 'GET' => empty($_GET) ? array() : $_GET,
537 if (!empty(self::$deleted)) {
538 $out['DELETED_DATAOBJECTS'] = self::$deleted;
540 if ($extra_data !== false) {
541 $out['EXTRA'] = $extra_data;
543 if ( self::$extra_data !== false) {
544 $out['EXTRA_DATA'] = self::$extra_data;
547 file_put_contents($file, json_encode($out));
552 function toRooArray( $q)
554 $ret = $this->toArray();
556 // fill toEventString.
557 if (!empty($q['_with_obj_summary']) && !empty($this->on_id)) {
558 $obj = $this->object();
560 if ($obj && $obj->pid() && method_exists($obj,'toEventString')) {
561 $es = $obj->toEventString();
563 if (empty($this->remarks) || strpos($this->remarks, $es) < 0) {
564 $ret['remarks'] = $es . ' ' . $this->remarks;
566 } else if (empty($this->remarks)){
567 $ret['remarks'] = "DELETED";
576 function toRooSingleArray($au, $q)
578 $ret = $this->toArray();
582 if(empty($q['_retrieve_source'])){
586 $file = $this->retrieveEventLog();
589 return "No records?!";
592 $source = json_decode(file_get_contents($file));
597 function retrieveEventLog()
600 $logdir = $this->logDir();
606 $date = date('/Y/m/d/', strtotime($this->event_when));
608 $file = $logdir. $date. $this->id . ".json";
609 if (!file_exists(dirname($file))) {
616 function restore($roo)
618 $file = $this->retrieveEventLog();
620 if(empty($file) || !file_exists($file)){
621 $roo->jerr('Could not retrieve the event log file');
624 $log = json_decode(file_get_contents($file), true);
626 if(empty($log['POST']) || empty($log['POST']['_delete']) || empty($log['DELETED_DATAOBJECTS'])){
627 $roo->jerr('Invalid url');
632 foreach ($log['DELETED_DATAOBJECTS'] as $d){
635 empty($d['_table']) ||
637 !empty($restored[$d['_table']]) &&
638 in_array($d['id'], $restored[$d['_table']])
644 if(!isset($restored[$d['_table']])){
645 $restored[$d['_table']] = array();
648 $restored[$d['_table']][] = $d['id'];
650 $table = DB_DataObject::factory($d['_table']);
652 if (!is_a($table,'DB_DataObject')) {
661 * need to use the old id
663 $table->id = $d['id'];
665 $table->sequenceKey(false,false);
669 if($table->tableName() == 'crm_mailing_list_member'){
670 $ml = DB_DataObject::factory('crm_mailing_list');
671 if(!$ml->get($table->mailing_list_id)){
675 $mlm = DB_DataObject::factory('crm_mailing_list_member');
677 'mailing_list_id' => $table->mailing_list_id,
682 $ml->no_members = $mlm->count();
687 $roo->jok('RESTORE');
689 function selectAddPersonEmail()
691 $this->selectAdd('join_person_id_id.email as email');