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
41 if(!empty($q['person_table'])){
42 $jt = DB_DataObject::factory($q['person_table']);
44 $et = DB_DataObject::factory($tn);
45 $this->selectAdd("(select count(*) from Events where Events.dup_id = evet.id) as cnt ");
46 $this->selectAs($et,'%s','evet');
48 if(!array_key_exists("{$jt->tableName()}_id", $this->tableColumns())){ // coz we have triiger on mysql...
52 $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['query']['grouped']) && $q['query']['grouped'] == 'gr') {
97 DB_DataObject::Debuglevel(1);
98 $this->groupBy('on_id');
100 (SELECT count(id) FROM core_event_audit WHERE event_id = Events.id) as changed
105 if (!$au->hasPerm("Admin.Admin_Tab", 'S')) {
106 //DB_DataObject::DebugLevel(1);
107 // they can only view their changes..
108 $this->whereAdd("($tn.person_id = {$au->id} OR $tn.person_id = 0)");
109 // $this->person_id = $au->id;
112 // _join = tablename,tablename...
116 // &_join_cols=cohead_number
117 // &_columns=on_id_cohead_number,event_when << this is ignored at present.
118 // max(event_when) is not supported... by any query yet..
120 if (isset($q['on_table']) && !strlen($q['on_table'])) {
121 // empty ontable queries.. these are valid..
122 $this->whereAdd("$tn.on_table = ''");
125 if (isset($q['query']['person_sum'])) {
126 //DB_DataObject::debugLevel(1);
127 $this->_extra_cols = array('qty' );
128 $this->selectAdd("count($tn.id) as qty");
129 $this->selectAdd("count( distinct $tn.on_id) as uqty");
130 $this->whereAdd('LENGTH(join_person_id_id.name) > 0 ');
131 $this->groupBy('person_id,join_person_id_id.name,join_person_id_id.email');
133 if (isset($q['query']['table_sum'])) {
134 //DB_DataObject::debugLevel(1);
135 $this->_extra_cols = array('qty' , 'uqty');
136 $this->selectAdd("count($tn.id) as qty");
137 $this->selectAdd("count( distinct $tn.on_table, $tn.on_id) as uqty");
139 $this->groupBy('on_table');
141 if (isset($q['query']['day_sum'])) {
142 //DB_DataObject::debugLevel(1);
143 $this->_extra_cols = array('qty' , 'uqty');
144 $this->selectAdd("DATE_FORMAT(event_when, '%Y-%m-%d') as on_day");
145 $this->selectAdd("count($tn.id) as qty");
146 $this->selectAdd("count( distinct $tn.on_id) as uqty");
148 $this->groupBy('on_day');
151 if (isset($q['_join'])) {
152 //DB_DataObject::DebugLevel(1);
153 $joins = explode(',',$q['_join']);
155 $this->selectAdd(); // ???
158 foreach($joins as $t) {
159 $t = preg_replace('/[^a-z_]+/', '', $t); // protection.
160 $x = DB_DataObject::Factory($t);
161 if (!is_a($x,'DB_DataObject')) {
164 $jtn = $x->tableName();
165 $jk = array_shift($x->keys());
168 LEFT JOIN {$jtn} as join_on_id_{$jtn} ON {$tn}.on_id = join_on_id_{$jtn}.{$jk}
169 AND on_table = '{$jtn}'
171 $keys = array_keys($x->tableColumns());
172 if (isset($q['_join_cols'])) {
173 $jcs = explode(',',$q['_join_cols'] );
174 //DB_DataObject::DebugLevel(1);
176 foreach($jcs as $jc) {
177 if (! in_array($jc, $keys)) {
183 $this->selectAdd( " join_on_id_{$jtn}.{$jc} as on_id_{$jc} ");
185 $this->selectAdd( " distinct(join_on_id_{$jtn}.{$jc} ) as on_id_{$jc} ");
188 $this->groupBy("on_id_{$jc} ");
189 $this->whereAdd("join_on_id_{$jtn}.{$jc} IS NOT NULL");
191 $this->selectAdd( "MAX(events.event_when) as event_when");
192 $this->orderBy('event_when DESC');
193 // $this->selectAs(array($q['_join_cols']) , 'on_id_%s', "join_on_id_{$jtn}");
195 $this->selectAs($x, 'on_id_%s', "join_on_id_{$jtn}");
202 if (isset($q['_related_on_id']) && isset($q['_related_on_table'])) {
203 // example: sales order - has invoices,
204 ///DB_DataObject::DebugLevel(1);
205 $ev =$this->factory('Events');
207 'on_id' => $q['_related_on_id'],
208 'on_table' => $q['_related_on_table'],
210 $obj = $ev->object();
213 $roo->jerr("ontable is invalid");
215 if (!method_exists($obj,'relatedWhere')) {
216 $roo->jerr( $q['_related_on_table'] . " Does not have method relatedWhere :" .
217 implode(',', get_class_methods($obj)));
219 if ($obj && method_exists($obj,'relatedWhere')) {
220 $ar = $obj->relatedWhere();
221 $tn = $this->tableName();
224 $w[] = "( {$tn}.on_table = '" .
225 $this->escape($q['_related_on_table']) .
226 "' AND {$tn}.on_id = ". ((int) $q['_related_on_id']) .
230 foreach($ar as $k=>$v) {
234 $w[] = "( {$tn}.on_table = '$k' AND {$tn}.on_id IN (". implode(',', $v). "))";
237 $this->whereAdd(implode(' OR ' , $w));
245 // since roo does not support autojoin yet..
246 if (!isset($q['_distinct'])) {
247 //$this->autoJoinExtra();
250 if(!empty($q['query']['action'])) {
251 $act = $this->escape($q['query']['action']);
252 $this->whereAdd("Events.action LIKE '%{$act}%'");
255 if(!empty($q['query']['on_table'])) {
256 $tnb = $this->escape($q['query']['on_table']);
257 $this->whereAdd("Events.on_table LIKE '%{$tnb}%'");
265 * check who is trying to access this. false == access denied..
266 * @return {boolean} true if access is allowed.
268 function checkPerm($lvl, $au)
273 // listing is controleed by applyfilters..
274 return $au->hasPerm("Admin.Admin_Tab", 'S');
278 * return the object that this relates to.
280 * @return {DB_DataObject} related object
284 $o = DB_DataObject::factory($this->on_table);
285 $o->get($this->on_id);
293 * Initialize an event - ready to insert..
295 * @param {String} action - group/name of event
296 * @param {DataObject|false} obj - dataobject action occured on.
297 * @param {String} any remarks
300 function init($act, $obj, $remarks)
302 $ff = HTML_FlexyFramework::get();
304 $au = $pg->getAuthUser();
306 if ($ff->cli) { // && empty($au) && isset($obj->person_id)) {
308 // $au = DB_DataObject::Factory('Person'); // not always a person..
309 // $au->get($obj->person_id);
312 $this->person_name = $au && !empty($au->name) ? $au->name : '';
313 if (empty($au) || (isset($au->id) && empty($au->id))) {
314 // not authenticated - and a standard id based object
315 $this->person_id = 0;
317 $col = $au->tableName() == "Person" ? 'person_id' : $au->tableName() . '_id';
319 $cols = $this->tableColumns();
320 $col = isset($cols[$col]) ? $col : 'person_id'; // for BC.... - revert to using person_id
321 $this->{$col} = $au->pid();
322 //$this->person_id = $au ? (!empty($au->id) ? $au->id : $au->pid()) : -1;
324 $this->person_table = $au ? $au->tableName() : '';
325 $this->ipaddr = isset($_SERVER["REMOTE_ADDR"]) ? $_SERVER["REMOTE_ADDR"] : 'cli';
326 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
327 $this->ipaddr = $_SERVER['HTTP_X_FORWARDED_FOR'];
330 $this->action = $act;
331 $this->on_table = $obj ? $obj->tableName() : '';
332 $pk = $obj ? $obj->keys() : false;
333 $this->on_id = $obj && $pk ? $obj->{$pk[0]}: 0;
335 // should this really go in remarks? -
336 if ($obj && method_exists($obj,'toEventString')) {
337 if($obj->toEventString() !== false){
338 $rem[] = $obj->toEventString();
342 $this->remarks = implode(' : ', $rem);
346 * Generate an audit for this field.
348 * @param {DB_DataObject} new data
349 * @param {DB_DataObject} old data
351 * @return {int} number of entries logged.
354 function audit($new, $old = false)
357 return 0; // they are the same...
361 foreach(array_keys($new->tableColumns()) as $k) {
362 // should we JSON serialize this?
363 $n = empty($new->$k) ? '' : $new->$k;
364 $o = empty($old->$k) || empty($old->$k) ? '' : $old->$k;
368 $this->auditField($k, $o, $n, $old);
374 * Record an audited change, in theory so we can audit data that is not just
377 * @param {string} $name table field anme
378 * @param {mixed} $ov old value
379 * @param {mixed} $onv new value
380 * @param {mixed} $old old object (false if we are creating..)
382 function auditField($name, $ov, $nv, $old=false )
385 if (is_object($nv)) {
390 $x = DB_DataObject::factory('core_event_audit');
392 'event_id' => $this->id,
394 'old_audit_id' => $old ? $x->findLast($this, $name) : 0,
402 function beforeInsert($request,$roo)
404 if(empty($this->event_when)){
405 $this->event_when = $this->sqlValue("NOW()");
408 if(empty($this->person_id)){
409 $this->person_id = $roo->authUser->id;
410 $this->person_name = $roo->authUser->name;
411 $this->person_table = $roo->authUser->tableName();
414 if(empty($this->ipaddr)){
415 $this->ipaddr = isset($_SERVER["REMOTE_ADDR"]) ? $_SERVER["REMOTE_ADDR"] : 'cli';
416 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
417 $this->ipaddr = $_SERVER['HTTP_X_FORWARDED_FOR'];
422 function beforeUpdate($old, $request,$roo)
424 if(!empty($request['_restore'])){
425 $this->restore($roo);
429 function onInsert($request,$roo)
431 $this->writeEventLog();
434 static $deleted = array();
437 // log deleting of a record so that it can be written later..
438 function logDeletedRecord($obj = false)
440 if (is_array($obj)) {
442 foreach($obj as $o) {
443 $aret = $this->logDeletedRecord($o);
444 $ret = $ret ? $ret : $aret;
449 if(empty($obj) || !is_a($obj, 'DB_DataObject')){
454 $del = $obj->toArray();
455 $del['_table'] = $obj->tableName();
457 self::$deleted[] = $del;
460 static $extra_data = false;
462 static function writeEventLogExtra($data) {
463 self::$extra_data = $data;
468 $ff = HTML_FlexyFramework::get();
469 if (function_exists('posix_getpwuid')) {
470 $uinfo = posix_getpwuid( posix_getuid () );
472 $user = $uinfo['name'];
474 $user = getenv('USERNAME'); // windows.
478 if (!empty($ff->Pman['event_log_dir'])) {
479 return $ff->Pman['event_log_dir'] . '/'.$user;
481 if (!empty($ff->Pman['storedir'])) {
482 return $ff->Pman['storedir'] .'/Events/'.$user;
490 function writeEventLog($extra_data = false)
492 $logdir = $this->logDir();
499 $file = $logdir. date('/Y/m/d/'). $this->id . ".json";
500 if (!file_exists(dirname($file))) {
502 @mkdir(dirname($file),0700,true); // this might fail if it does not have correct permissions..
503 if (!file_exists(dirname($file))) {
504 die("could not create $file - permissons are not correct"); // fatal, otherwise we loop!?
509 // Remove all the password from logs...
510 $p = empty($_POST) ? array() : $_POST;
511 foreach(array('passwd', 'password','passwd1', 'passwd2','password1', 'password2') as $rm) {
512 if (isset($p[$rm])) {
522 foreach ($_FILES as $k=>$f){
523 // does not handle any other file[] arrary very well..
524 if (empty($f['tmp_name']) || !file_exists($f['tmp_name'])) {
531 $files[$k]['tmp_name'] = $this->id . '-'. $i;
532 $nf = $logdir . date('/Y/m/d/'). $files[$k]['tmp_name'];
533 if (!copy($f['tmp_name'], $nf)) {
534 print_r("failed to copy {$f['tmp_name']}...\n");
538 'REQUEST_URI' => empty($_SERVER['REQUEST_URI']) ? 'cli' : $_SERVER['REQUEST_URI'],
539 'HTTP_USER_AGENT' => empty($_SERVER['HTTP_USER_AGENT']) ? '' : $_SERVER['HTTP_USER_AGENT'],
540 'GET' => empty($_GET) ? array() : $_GET,
545 if (!empty(self::$deleted)) {
546 $out['DELETED_DATAOBJECTS'] = self::$deleted;
548 if ($extra_data !== false) {
549 $out['EXTRA'] = $extra_data;
551 if ( self::$extra_data !== false) {
552 $out['EXTRA_DATA'] = self::$extra_data;
555 file_put_contents($file, json_encode($out));
560 function toRooArray( $q)
562 $ret = $this->toArray();
564 // fill toEventString.
565 if (!empty($q['_with_obj_summary']) && !empty($this->on_id)) {
566 $obj = $this->object();
568 if ($obj && $obj->pid() && method_exists($obj,'toEventString')) {
569 $es = $obj->toEventString();
571 if (empty($this->remarks) || strpos($this->remarks, $es) < 0) {
572 $ret['remarks'] = $es . ' ' . $this->remarks;
574 } else if (empty($this->remarks)){
575 $ret['remarks'] = "DELETED";
584 function toRooSingleArray($au, $q)
586 $ret = $this->toArray();
590 if(empty($q['_retrieve_source'])){
594 $file = $this->retrieveEventLog();
597 return "No records?!";
600 $source = json_decode(file_get_contents($file));
605 function retrieveEventLog()
608 $logdir = $this->logDir();
614 $date = date('/Y/m/d/', strtotime($this->event_when));
616 $file = $logdir. $date. $this->id . ".json";
617 if (!file_exists(dirname($file))) {
624 function restore($roo)
626 $file = $this->retrieveEventLog();
628 if(empty($file) || !file_exists($file)){
629 $roo->jerr('Could not retrieve the event log file');
632 $log = json_decode(file_get_contents($file), true);
634 if(empty($log['POST']) || empty($log['POST']['_delete']) || empty($log['DELETED_DATAOBJECTS'])){
635 $roo->jerr('Invalid url');
640 foreach ($log['DELETED_DATAOBJECTS'] as $d){
643 empty($d['_table']) ||
645 !empty($restored[$d['_table']]) &&
646 in_array($d['id'], $restored[$d['_table']])
652 if(!isset($restored[$d['_table']])){
653 $restored[$d['_table']] = array();
656 $restored[$d['_table']][] = $d['id'];
658 $table = DB_DataObject::factory($d['_table']);
660 if (!is_a($table,'DB_DataObject')) {
669 * need to use the old id
671 $table->id = $d['id'];
673 $table->sequenceKey(false,false);
677 if($table->tableName() == 'crm_mailing_list_member'){
678 $ml = DB_DataObject::factory('crm_mailing_list');
679 if(!$ml->get($table->mailing_list_id)){
683 $mlm = DB_DataObject::factory('crm_mailing_list_member');
685 'mailing_list_id' => $table->mailing_list_id,
690 $ml->no_members = $mlm->count();
695 $roo->jok('RESTORE');
697 function selectAddPersonEmail()
699 $this->selectAdd('join_person_id_id.email as email');