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');
49 if(!array_key_exists("{$jt->tableName()}_id", $this->tableColumns())){ // coz we have triiger on mysql...
53 $this->_join = "LEFT JOIN {$jt->tableName()} AS join_person_id_id ON (join_person_id_id.{$keys[0]}={$tn}.person_id)";
54 //$this->_join = "LEFT JOIN {$jt->tableName()} AS join_person_id_id ON (join_person_id_id.{$keys[0]}=Events.person_id)";
58 $this->selectAs($jt, 'person_id_%s', 'join_person_id_id');
60 if (method_exists($jt,'nameColumn')) {
61 $this->selectAdd("join_person_id_id.{$jt->nameColumn()} as person_id_name");
64 if (method_exists($jt,'emailColumn')) {
65 $this->selectAdd("join_person_id_id.{$jt->emailColumn()} as person_id_email");
72 $person = $au->tableName(); //'Person'; -- projects may not use person as the auth table...
73 $cfg = HTML_FlexyFramework::get()->Pman;
74 if (!empty($cfg['authTable'])) {
75 $person =$cfg['authTable'];
78 $jt = DB_DataObject::factory($person);
80 person_table = '{$jt->tableName()}'
83 OR person_table IS NULL"
84 ); // default to our standard.. - unless otherwise requested..
88 if (!empty($q['query']['from'])) {
89 $dt = date('Y-m-d' , strtotime($q['query']['from']));
90 $this->whereAdd(" {$tn}.event_when >= '$dt' ");
92 if (!empty($q['query']['to'])) {
93 $dt = date('Y-m-d' , strtotime($q['query']['to']));
94 $this->whereAdd(" {$tn}.event_when <= '$dt' ");
97 if (!empty($q['query']['grouped']) && $q['query']['grouped'] == 'gr') {
99 DB_DataObject::Debuglevel(1);
100 $this->groupBy('on_id');
102 (SELECT count(id) FROM core_event_audit WHERE event_id = Events.id) as changed
107 if (!$au->hasPerm("Admin.Admin_Tab", 'S')) {
108 //DB_DataObject::DebugLevel(1);
109 // they can only view their changes..
110 $this->whereAdd("($tn.person_id = {$au->id} OR $tn.person_id = 0)");
111 // $this->person_id = $au->id;
114 // _join = tablename,tablename...
118 // &_join_cols=cohead_number
119 // &_columns=on_id_cohead_number,event_when << this is ignored at present.
120 // max(event_when) is not supported... by any query yet..
122 if (isset($q['on_table']) && !strlen($q['on_table'])) {
123 // empty ontable queries.. these are valid..
124 $this->whereAdd("{$tn}.on_table = ''");
127 if (isset($q['query']['person_sum'])) {
128 //DB_DataObject::debugLevel(1);
129 $this->_extra_cols = array('qty' );
130 $this->selectAdd("count($tn.id) as qty");
131 $this->selectAdd("count( distinct $tn.on_id) as uqty");
132 $this->whereAdd('LENGTH(join_person_id_id.name) > 0 ');
133 $this->groupBy('person_id,join_person_id_id.name,join_person_id_id.email');
135 if (isset($q['query']['table_sum'])) {
136 //DB_DataObject::debugLevel(1);
137 $this->_extra_cols = array('qty' , 'uqty');
138 $this->selectAdd("count($tn.id) as qty");
139 $this->selectAdd("count( distinct $tn.on_table, $tn.on_id) as uqty");
141 $this->groupBy('on_table');
143 if (isset($q['query']['day_sum'])) {
144 //DB_DataObject::debugLevel(1);
145 $this->_extra_cols = array('qty' , 'uqty');
146 $this->selectAdd("DATE_FORMAT(event_when, '%Y-%m-%d') as on_day");
147 $this->selectAdd("count($tn.id) as qty");
148 $this->selectAdd("count( distinct $tn.on_id) as uqty");
150 $this->groupBy('on_day');
153 if (isset($q['_join'])) {
154 //DB_DataObject::DebugLevel(1);
155 $joins = explode(',',$q['_join']);
157 $this->selectAdd(); // ???
160 foreach($joins as $t) {
161 $t = preg_replace('/[^a-z_]+/', '', $t); // protection.
162 $x = DB_DataObject::Factory($t);
163 if (!is_a($x,'DB_DataObject')) {
166 $jtn = $x->tableName();
167 $jk = array_shift($x->keys());
170 LEFT JOIN {$jtn} as join_on_id_{$jtn} ON {$tn}.on_id = join_on_id_{$jtn}.{$jk}
171 AND on_table = '{$jtn}'
173 $keys = array_keys($x->tableColumns());
174 if (isset($q['_join_cols'])) {
175 $jcs = explode(',',$q['_join_cols'] );
176 //DB_DataObject::DebugLevel(1);
178 foreach($jcs as $jc) {
179 if (! in_array($jc, $keys)) {
185 $this->selectAdd( " join_on_id_{$jtn}.{$jc} as on_id_{$jc} ");
187 $this->selectAdd( " distinct(join_on_id_{$jtn}.{$jc} ) as on_id_{$jc} ");
190 $this->groupBy("on_id_{$jc} ");
191 $this->whereAdd("join_on_id_{$jtn}.{$jc} IS NOT NULL");
193 $this->selectAdd( "MAX(events.event_when) as event_when");
194 $this->orderBy('event_when DESC');
195 // $this->selectAs(array($q['_join_cols']) , 'on_id_%s', "join_on_id_{$jtn}");
197 $this->selectAs($x, 'on_id_%s', "join_on_id_{$jtn}");
204 if (isset($q['_related_on_id']) && isset($q['_related_on_table'])) {
205 // example: sales order - has invoices,
206 ///DB_DataObject::DebugLevel(1);
207 $ev =$this->factory('Events');
209 'on_id' => $q['_related_on_id'],
210 'on_table' => $q['_related_on_table'],
212 $obj = $ev->object();
215 $roo->jerr("ontable is invalid");
217 if (!method_exists($obj,'relatedWhere')) {
218 $roo->jerr( $q['_related_on_table'] . " Does not have method relatedWhere :" .
219 implode(',', get_class_methods($obj)));
221 if ($obj && method_exists($obj,'relatedWhere')) {
222 $ar = $obj->relatedWhere();
223 $tn = $this->tableName();
226 $w[] = "( {$tn}.on_table = '" .
227 $this->escape($q['_related_on_table']) .
228 "' AND {$tn}.on_id = ". ((int) $q['_related_on_id']) .
232 foreach($ar as $k=>$v) {
236 $w[] = "( {$tn}.on_table = '$k' AND {$tn}.on_id IN (". implode(',', $v). "))";
239 $this->whereAdd(implode(' OR ' , $w));
247 // since roo does not support autojoin yet..
248 if (!isset($q['_distinct'])) {
249 //$this->autoJoinExtra();
252 if(!empty($q['query']['action'])) {
253 $act = $this->escape($q['query']['action']);
254 $this->whereAdd("{$tn}.action LIKE '%{$act}%'");
257 if(!empty($q['query']['on_table'])) {
258 $tnb = $this->escape($q['query']['on_table']);
259 $this->whereAdd("{$tn}.on_table LIKE '%{$tnb}%'");
267 * check who is trying to access this. false == access denied..
268 * @return {boolean} true if access is allowed.
270 function checkPerm($lvl, $au)
275 // listing is controleed by applyfilters..
276 return $au->hasPerm("Admin.Admin_Tab", 'S');
280 * return the object that this relates to.
282 * @return {DB_DataObject} related object
286 $o = DB_DataObject::factory($this->on_table);
287 $o->get($this->on_id);
295 * Initialize an event - ready to insert..
297 * @param {String} action - group/name of event
298 * @param {DataObject|false} obj - dataobject action occured on.
299 * @param {String} any remarks
302 function init($act, $obj, $remarks)
304 $ff = HTML_FlexyFramework::get();
306 $au = $pg->getAuthUser();
308 if ($ff->cli) { // && empty($au) && isset($obj->person_id)) {
310 // $au = DB_DataObject::Factory('Person'); // not always a person..
311 // $au->get($obj->person_id);
314 $this->person_name = $au && !empty($au->name) ? $au->name : '';
315 if (empty($au) || (isset($au->id) && empty($au->id))) {
316 // not authenticated - and a standard id based object
317 $this->person_id = 0;
319 $col = $au->tableName() == "Person" ? 'person_id' : $au->tableName() . '_id';
321 $cols = $this->tableColumns();
322 $col = isset($cols[$col]) ? $col : 'person_id'; // for BC.... - revert to using person_id
323 $this->{$col} = $au->pid();
324 //$this->person_id = $au ? (!empty($au->id) ? $au->id : $au->pid()) : -1;
326 $this->person_table = $au ? $au->tableName() : '';
327 $this->ipaddr = isset($_SERVER["REMOTE_ADDR"]) ? $_SERVER["REMOTE_ADDR"] : 'cli';
328 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
329 $this->ipaddr = $_SERVER['HTTP_X_FORWARDED_FOR'];
332 $this->action = $act;
333 $this->on_table = $obj ? $obj->tableName() : '';
334 $pk = $obj ? $obj->keys() : false;
335 $this->on_id = $obj && $pk ? $obj->{$pk[0]}: 0;
337 // should this really go in remarks? -
338 if ($obj && method_exists($obj,'toEventString')) {
339 if($obj->toEventString() !== false){
340 $rem[] = $obj->toEventString();
344 $this->remarks = implode(' : ', $rem);
348 * Generate an audit for this field.
350 * @param {DB_DataObject} new data
351 * @param {DB_DataObject} old data
353 * @return {int} number of entries logged.
356 function audit($new, $old = false)
359 return 0; // they are the same...
363 foreach(array_keys($new->tableColumns()) as $k) {
364 // should we JSON serialize this?
365 $n = empty($new->$k) ? '' : $new->$k;
366 $o = empty($old->$k) || empty($old->$k) ? '' : $old->$k;
370 $this->auditField($k, $o, $n, $old);
376 * Record an audited change, in theory so we can audit data that is not just
379 * @param {string} $name table field anme
380 * @param {mixed} $ov old value
381 * @param {mixed} $onv new value
382 * @param {mixed} $old old object (false if we are creating..)
384 function auditField($name, $ov, $nv, $old=false )
387 if (is_object($nv)) {
392 $x = DB_DataObject::factory('core_event_audit');
394 'event_id' => $this->id,
396 'old_audit_id' => $old ? $x->findLast($this, $name) : 0,
404 function beforeInsert($request,$roo)
406 if(empty($this->event_when)){
407 $this->event_when = $this->sqlValue("NOW()");
410 if(empty($this->person_id)){
411 $this->person_id = $roo->authUser->id;
412 $this->person_name = $roo->authUser->name;
413 $this->person_table = $roo->authUser->tableName();
416 if(empty($this->ipaddr)){
417 $this->ipaddr = isset($_SERVER["REMOTE_ADDR"]) ? $_SERVER["REMOTE_ADDR"] : 'cli';
418 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
419 $this->ipaddr = $_SERVER['HTTP_X_FORWARDED_FOR'];
424 function beforeUpdate($old, $request,$roo)
426 if(!empty($request['_restore'])){
427 $this->restore($roo);
431 function onInsert($request,$roo)
433 $this->writeEventLog();
436 static $deleted = array();
439 // log deleting of a record so that it can be written later..
440 function logDeletedRecord($obj = false)
442 if (is_array($obj)) {
444 foreach($obj as $o) {
445 $aret = $this->logDeletedRecord($o);
446 $ret = $ret ? $ret : $aret;
451 if(empty($obj) || !is_a($obj, 'DB_DataObject')){
456 $del = $obj->toArray();
457 $del['_table'] = $obj->tableName();
459 self::$deleted[] = $del;
462 static $extra_data = false;
464 static function writeEventLogExtra($data) {
465 self::$extra_data = $data;
470 $ff = HTML_FlexyFramework::get();
471 if (function_exists('posix_getpwuid')) {
472 $uinfo = posix_getpwuid( posix_getuid () );
474 $user = $uinfo['name'];
476 $user = getenv('USERNAME'); // windows.
480 if (!empty($ff->Pman['event_log_dir'])) {
481 return $ff->Pman['event_log_dir'] . '/'.$user;
483 if (!empty($ff->Pman['storedir'])) {
484 return $ff->Pman['storedir'] .'/Events/'.$user;
492 function writeEventLog($extra_data = false)
494 $logdir = $this->logDir();
501 $file = $logdir. date('/Y/m/d/'). $this->id . ".json";
502 if (!file_exists(dirname($file))) {
504 @mkdir(dirname($file),0700,true); // this might fail if it does not have correct permissions..
505 if (!file_exists(dirname($file))) {
506 die("could not create $file - permissons are not correct"); // fatal, otherwise we loop!?
511 // Remove all the password from logs...
512 $p = empty($_POST) ? array() : $_POST;
513 foreach(array('passwd', 'password','passwd1', 'passwd2','password1', 'password2') as $rm) {
514 if (isset($p[$rm])) {
524 foreach ($_FILES as $k=>$f){
525 // does not handle any other file[] arrary very well..
526 if (empty($f['tmp_name']) || !file_exists($f['tmp_name'])) {
533 $files[$k]['tmp_name'] = $this->id . '-'. $i;
534 $nf = $logdir . date('/Y/m/d/'). $files[$k]['tmp_name'];
535 if (!copy($f['tmp_name'], $nf)) {
536 print_r("failed to copy {$f['tmp_name']}...\n");
540 'REQUEST_URI' => empty($_SERVER['REQUEST_URI']) ? 'cli' : $_SERVER['REQUEST_URI'],
541 'HTTP_USER_AGENT' => empty($_SERVER['HTTP_USER_AGENT']) ? '' : $_SERVER['HTTP_USER_AGENT'],
542 'GET' => empty($_GET) ? array() : $_GET,
547 if (!empty(self::$deleted)) {
548 $out['DELETED_DATAOBJECTS'] = self::$deleted;
550 if ($extra_data !== false) {
551 $out['EXTRA'] = $extra_data;
553 if ( self::$extra_data !== false) {
554 $out['EXTRA_DATA'] = self::$extra_data;
557 file_put_contents($file, json_encode($out));
562 function toRooArray( $q)
564 $ret = $this->toArray();
566 // fill toEventString.
567 if (!empty($q['_with_obj_summary']) && !empty($this->on_id)) {
568 $obj = $this->object();
570 if ($obj && $obj->pid() && method_exists($obj,'toEventString')) {
571 $es = $obj->toEventString();
573 if (empty($this->remarks) || strpos($this->remarks, $es) < 0) {
574 $ret['remarks'] = $es . ' ' . $this->remarks;
576 } else if (empty($this->remarks)){
577 $ret['remarks'] = "DELETED";
586 function toRooSingleArray($au, $q)
588 $ret = $this->toArray();
592 if(empty($q['_retrieve_source'])){
596 $file = $this->retrieveEventLog();
599 return "No records?!";
602 $source = json_decode(file_get_contents($file));
607 function retrieveEventLog()
610 $logdir = $this->logDir();
616 $date = date('/Y/m/d/', strtotime($this->event_when));
618 $file = $logdir. $date. $this->id . ".json";
619 if (!file_exists(dirname($file))) {
626 function restore($roo)
628 $file = $this->retrieveEventLog();
630 if(empty($file) || !file_exists($file)){
631 $roo->jerr('Could not retrieve the event log file');
634 $log = json_decode(file_get_contents($file), true);
636 if(empty($log['POST']) || empty($log['POST']['_delete']) || empty($log['DELETED_DATAOBJECTS'])){
637 $roo->jerr('Invalid url');
642 foreach ($log['DELETED_DATAOBJECTS'] as $d){
645 empty($d['_table']) ||
647 !empty($restored[$d['_table']]) &&
648 in_array($d['id'], $restored[$d['_table']])
654 if(!isset($restored[$d['_table']])){
655 $restored[$d['_table']] = array();
658 $restored[$d['_table']][] = $d['id'];
660 $table = DB_DataObject::factory($d['_table']);
662 if (!is_a($table,'DB_DataObject')) {
671 * need to use the old id
673 $table->id = $d['id'];
675 $table->sequenceKey(false,false);
679 if($table->tableName() == 'crm_mailing_list_member'){
680 $ml = DB_DataObject::factory('crm_mailing_list');
681 if(!$ml->get($table->mailing_list_id)){
685 $mlm = DB_DataObject::factory('crm_mailing_list_member');
687 'mailing_list_id' => $table->mailing_list_id,
692 $ml->no_members = $mlm->count();
697 $roo->jok('RESTORE');
699 function selectAddPersonEmail()
701 $this->selectAdd('join_person_id_id.email as email');