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']);
46 if(!array_key_exists("{$jt->tableName()}_id", $this->tableColumns())){ // coz we have triiger on mysql...
50 $this->_join = "LEFT JOIN {$jt->tableName()} AS join_person_id_id ON (join_person_id_id.{$keys[0]}=Events.person_id)";
55 $this->selectAs($jt, 'person_id_%s', 'join_person_id_id');
57 if (method_exists($jt,'nameColumn')) {
58 $this->selectAdd("join_person_id_id.{$jt->nameColumn()} as person_id_name");
61 if (method_exists($jt,'emailColumn')) {
62 $this->selectAdd("join_person_id_id.{$jt->emailColumn()} as person_id_email");
69 $person = $au->tableName(); //'Person'; -- projects may not use person as the auth table...
70 $cfg = HTML_FlexyFramework::get()->Pman;
71 if (!empty($cfg['authTable'])) {
72 $person =$cfg['authTable'];
75 $jt = DB_DataObject::factory($person);
77 person_table = '{$jt->tableName()}'
80 OR person_table IS NULL"
81 ); // default to our standard.. - unless otherwise requested..
85 if (!empty($q['query']['from'])) {
86 $dt = date('Y-m-d' , strtotime($q['query']['from']));
87 $this->whereAdd(" {$tn}.event_when >= '$dt' ");
89 if (!empty($q['query']['to'])) {
90 $dt = date('Y-m-d' , strtotime($q['query']['to']));
91 $this->whereAdd(" {$tn}.event_when <= '$dt' ");
94 if(!empty($q['dup_check'])){
95 $et = DB_DataObject::factory($tn);
96 $this->_join = "LEFT JOIN {$et->tableName()} AS evet ON (evet.id=Events.id)";
97 $this->selectAdd("(select count(*) from Events where Events.dup_id = evet.id) as cnt ");
98 $this->selectAs($et,'evet_%s','evet');
104 if (!empty($q['query']['grouped']) && $q['query']['grouped'] == 'gr') {
106 DB_DataObject::Debuglevel(1);
107 $this->groupBy('on_id');
109 (SELECT count(id) FROM core_event_audit WHERE event_id = Events.id) as changed
114 if (!$au->hasPerm("Admin.Admin_Tab", 'S')) {
115 //DB_DataObject::DebugLevel(1);
116 // they can only view their changes..
117 $this->whereAdd("($tn.person_id = {$au->id} OR $tn.person_id = 0)");
118 // $this->person_id = $au->id;
121 // _join = tablename,tablename...
125 // &_join_cols=cohead_number
126 // &_columns=on_id_cohead_number,event_when << this is ignored at present.
127 // max(event_when) is not supported... by any query yet..
129 if (isset($q['on_table']) && !strlen($q['on_table'])) {
130 // empty ontable queries.. these are valid..
131 $this->whereAdd("$tn.on_table = ''");
134 if (isset($q['query']['person_sum'])) {
135 //DB_DataObject::debugLevel(1);
136 $this->_extra_cols = array('qty' );
137 $this->selectAdd("count($tn.id) as qty");
138 $this->selectAdd("count( distinct $tn.on_id) as uqty");
139 $this->whereAdd('LENGTH(join_person_id_id.name) > 0 ');
140 $this->groupBy('person_id,join_person_id_id.name,join_person_id_id.email');
142 if (isset($q['query']['table_sum'])) {
143 //DB_DataObject::debugLevel(1);
144 $this->_extra_cols = array('qty' , 'uqty');
145 $this->selectAdd("count($tn.id) as qty");
146 $this->selectAdd("count( distinct $tn.on_table, $tn.on_id) as uqty");
148 $this->groupBy('on_table');
150 if (isset($q['query']['day_sum'])) {
151 //DB_DataObject::debugLevel(1);
152 $this->_extra_cols = array('qty' , 'uqty');
153 $this->selectAdd("DATE_FORMAT(event_when, '%Y-%m-%d') as on_day");
154 $this->selectAdd("count($tn.id) as qty");
155 $this->selectAdd("count( distinct $tn.on_id) as uqty");
157 $this->groupBy('on_day');
160 if (isset($q['_join'])) {
161 //DB_DataObject::DebugLevel(1);
162 $joins = explode(',',$q['_join']);
164 $this->selectAdd(); // ???
167 foreach($joins as $t) {
168 $t = preg_replace('/[^a-z_]+/', '', $t); // protection.
169 $x = DB_DataObject::Factory($t);
170 if (!is_a($x,'DB_DataObject')) {
173 $jtn = $x->tableName();
174 $jk = array_shift($x->keys());
177 LEFT JOIN {$jtn} as join_on_id_{$jtn} ON {$tn}.on_id = join_on_id_{$jtn}.{$jk}
178 AND on_table = '{$jtn}'
180 $keys = array_keys($x->tableColumns());
181 if (isset($q['_join_cols'])) {
182 $jcs = explode(',',$q['_join_cols'] );
183 //DB_DataObject::DebugLevel(1);
185 foreach($jcs as $jc) {
186 if (! in_array($jc, $keys)) {
192 $this->selectAdd( " join_on_id_{$jtn}.{$jc} as on_id_{$jc} ");
194 $this->selectAdd( " distinct(join_on_id_{$jtn}.{$jc} ) as on_id_{$jc} ");
197 $this->groupBy("on_id_{$jc} ");
198 $this->whereAdd("join_on_id_{$jtn}.{$jc} IS NOT NULL");
200 $this->selectAdd( "MAX(events.event_when) as event_when");
201 $this->orderBy('event_when DESC');
202 // $this->selectAs(array($q['_join_cols']) , 'on_id_%s', "join_on_id_{$jtn}");
204 $this->selectAs($x, 'on_id_%s', "join_on_id_{$jtn}");
211 if (isset($q['_related_on_id']) && isset($q['_related_on_table'])) {
212 // example: sales order - has invoices,
213 ///DB_DataObject::DebugLevel(1);
214 $ev =$this->factory('Events');
216 'on_id' => $q['_related_on_id'],
217 'on_table' => $q['_related_on_table'],
219 $obj = $ev->object();
222 $roo->jerr("ontable is invalid");
224 if (!method_exists($obj,'relatedWhere')) {
225 $roo->jerr( $q['_related_on_table'] . " Does not have method relatedWhere :" .
226 implode(',', get_class_methods($obj)));
228 if ($obj && method_exists($obj,'relatedWhere')) {
229 $ar = $obj->relatedWhere();
230 $tn = $this->tableName();
233 $w[] = "( {$tn}.on_table = '" .
234 $this->escape($q['_related_on_table']) .
235 "' AND {$tn}.on_id = ". ((int) $q['_related_on_id']) .
239 foreach($ar as $k=>$v) {
243 $w[] = "( {$tn}.on_table = '$k' AND {$tn}.on_id IN (". implode(',', $v). "))";
246 $this->whereAdd(implode(' OR ' , $w));
254 // since roo does not support autojoin yet..
255 if (!isset($q['_distinct'])) {
256 //$this->autoJoinExtra();
259 if(!empty($q['query']['action'])) {
260 $act = $this->escape($q['query']['action']);
261 $this->whereAdd("Events.action LIKE '%{$act}%'");
264 if(!empty($q['query']['on_table'])) {
265 $tnb = $this->escape($q['query']['on_table']);
266 $this->whereAdd("Events.on_table LIKE '%{$tnb}%'");
274 * check who is trying to access this. false == access denied..
275 * @return {boolean} true if access is allowed.
277 function checkPerm($lvl, $au)
282 // listing is controleed by applyfilters..
283 return $au->hasPerm("Admin.Admin_Tab", 'S');
287 * return the object that this relates to.
289 * @return {DB_DataObject} related object
293 $o = DB_DataObject::factory($this->on_table);
294 $o->get($this->on_id);
302 * Initialize an event - ready to insert..
304 * @param {String} action - group/name of event
305 * @param {DataObject|false} obj - dataobject action occured on.
306 * @param {String} any remarks
309 function init($act, $obj, $remarks)
311 $ff = HTML_FlexyFramework::get();
313 $au = $pg->getAuthUser();
315 if ($ff->cli) { // && empty($au) && isset($obj->person_id)) {
317 // $au = DB_DataObject::Factory('Person'); // not always a person..
318 // $au->get($obj->person_id);
321 $this->person_name = $au && !empty($au->name) ? $au->name : '';
322 if (empty($au) || (isset($au->id) && empty($au->id))) {
323 // not authenticated - and a standard id based object
324 $this->person_id = 0;
326 $col = $au->tableName() == "Person" ? 'person_id' : $au->tableName() . '_id';
328 $cols = $this->tableColumns();
329 $col = isset($cols[$col]) ? $col : 'person_id'; // for BC.... - revert to using person_id
330 $this->{$col} = $au->pid();
331 //$this->person_id = $au ? (!empty($au->id) ? $au->id : $au->pid()) : -1;
333 $this->person_table = $au ? $au->tableName() : '';
334 $this->ipaddr = isset($_SERVER["REMOTE_ADDR"]) ? $_SERVER["REMOTE_ADDR"] : 'cli';
335 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
336 $this->ipaddr = $_SERVER['HTTP_X_FORWARDED_FOR'];
339 $this->action = $act;
340 $this->on_table = $obj ? $obj->tableName() : '';
341 $pk = $obj ? $obj->keys() : false;
342 $this->on_id = $obj && $pk ? $obj->{$pk[0]}: 0;
344 // should this really go in remarks? -
345 if ($obj && method_exists($obj,'toEventString')) {
346 if($obj->toEventString() !== false){
347 $rem[] = $obj->toEventString();
351 $this->remarks = implode(' : ', $rem);
355 * Generate an audit for this field.
357 * @param {DB_DataObject} new data
358 * @param {DB_DataObject} old data
360 * @return {int} number of entries logged.
363 function audit($new, $old = false)
366 return 0; // they are the same...
370 foreach(array_keys($new->tableColumns()) as $k) {
371 // should we JSON serialize this?
372 $n = empty($new->$k) ? '' : $new->$k;
373 $o = empty($old->$k) || empty($old->$k) ? '' : $old->$k;
377 $this->auditField($k, $o, $n, $old);
383 * Record an audited change, in theory so we can audit data that is not just
386 * @param {string} $name table field anme
387 * @param {mixed} $ov old value
388 * @param {mixed} $onv new value
389 * @param {mixed} $old old object (false if we are creating..)
391 function auditField($name, $ov, $nv, $old=false )
394 if (is_object($nv)) {
399 $x = DB_DataObject::factory('core_event_audit');
401 'event_id' => $this->id,
403 'old_audit_id' => $old ? $x->findLast($this, $name) : 0,
411 function beforeInsert($request,$roo)
413 if(empty($this->event_when)){
414 $this->event_when = $this->sqlValue("NOW()");
417 if(empty($this->person_id)){
418 $this->person_id = $roo->authUser->id;
419 $this->person_name = $roo->authUser->name;
420 $this->person_table = $roo->authUser->tableName();
423 if(empty($this->ipaddr)){
424 $this->ipaddr = isset($_SERVER["REMOTE_ADDR"]) ? $_SERVER["REMOTE_ADDR"] : 'cli';
425 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
426 $this->ipaddr = $_SERVER['HTTP_X_FORWARDED_FOR'];
431 function beforeUpdate($old, $request,$roo)
433 if(!empty($request['_restore'])){
434 $this->restore($roo);
438 function onInsert($request,$roo)
440 $this->writeEventLog();
443 static $deleted = array();
446 // log deleting of a record so that it can be written later..
447 function logDeletedRecord($obj = false)
449 if (is_array($obj)) {
451 foreach($obj as $o) {
452 $aret = $this->logDeletedRecord($o);
453 $ret = $ret ? $ret : $aret;
458 if(empty($obj) || !is_a($obj, 'DB_DataObject')){
463 $del = $obj->toArray();
464 $del['_table'] = $obj->tableName();
466 self::$deleted[] = $del;
469 static $extra_data = false;
471 static function writeEventLogExtra($data) {
472 self::$extra_data = $data;
477 $ff = HTML_FlexyFramework::get();
478 if (function_exists('posix_getpwuid')) {
479 $uinfo = posix_getpwuid( posix_getuid () );
481 $user = $uinfo['name'];
483 $user = getenv('USERNAME'); // windows.
487 if (!empty($ff->Pman['event_log_dir'])) {
488 return $ff->Pman['event_log_dir'] . '/'.$user;
490 if (!empty($ff->Pman['storedir'])) {
491 return $ff->Pman['storedir'] .'/Events/'.$user;
499 function writeEventLog($extra_data = false)
501 $logdir = $this->logDir();
508 $file = $logdir. date('/Y/m/d/'). $this->id . ".json";
509 if (!file_exists(dirname($file))) {
511 @mkdir(dirname($file),0700,true); // this might fail if it does not have correct permissions..
512 if (!file_exists(dirname($file))) {
513 die("could not create $file - permissons are not correct"); // fatal, otherwise we loop!?
518 // Remove all the password from logs...
519 $p = empty($_POST) ? array() : $_POST;
520 foreach(array('passwd', 'password','passwd1', 'passwd2','password1', 'password2') as $rm) {
521 if (isset($p[$rm])) {
531 foreach ($_FILES as $k=>$f){
532 // does not handle any other file[] arrary very well..
533 if (empty($f['tmp_name']) || !file_exists($f['tmp_name'])) {
540 $files[$k]['tmp_name'] = $this->id . '-'. $i;
541 $nf = $logdir . date('/Y/m/d/'). $files[$k]['tmp_name'];
542 if (!copy($f['tmp_name'], $nf)) {
543 print_r("failed to copy {$f['tmp_name']}...\n");
547 'REQUEST_URI' => empty($_SERVER['REQUEST_URI']) ? 'cli' : $_SERVER['REQUEST_URI'],
548 'HTTP_USER_AGENT' => empty($_SERVER['HTTP_USER_AGENT']) ? '' : $_SERVER['HTTP_USER_AGENT'],
549 'GET' => empty($_GET) ? array() : $_GET,
554 if (!empty(self::$deleted)) {
555 $out['DELETED_DATAOBJECTS'] = self::$deleted;
557 if ($extra_data !== false) {
558 $out['EXTRA'] = $extra_data;
560 if ( self::$extra_data !== false) {
561 $out['EXTRA_DATA'] = self::$extra_data;
564 file_put_contents($file, json_encode($out));
569 function toRooArray( $q)
571 $ret = $this->toArray();
573 // fill toEventString.
574 if (!empty($q['_with_obj_summary']) && !empty($this->on_id)) {
575 $obj = $this->object();
577 if ($obj && $obj->pid() && method_exists($obj,'toEventString')) {
578 $es = $obj->toEventString();
580 if (empty($this->remarks) || strpos($this->remarks, $es) < 0) {
581 $ret['remarks'] = $es . ' ' . $this->remarks;
583 } else if (empty($this->remarks)){
584 $ret['remarks'] = "DELETED";
593 function toRooSingleArray($au, $q)
595 $ret = $this->toArray();
599 if(empty($q['_retrieve_source'])){
603 $file = $this->retrieveEventLog();
606 return "No records?!";
609 $source = json_decode(file_get_contents($file));
614 function retrieveEventLog()
617 $logdir = $this->logDir();
623 $date = date('/Y/m/d/', strtotime($this->event_when));
625 $file = $logdir. $date. $this->id . ".json";
626 if (!file_exists(dirname($file))) {
633 function restore($roo)
635 $file = $this->retrieveEventLog();
637 if(empty($file) || !file_exists($file)){
638 $roo->jerr('Could not retrieve the event log file');
641 $log = json_decode(file_get_contents($file), true);
643 if(empty($log['POST']) || empty($log['POST']['_delete']) || empty($log['DELETED_DATAOBJECTS'])){
644 $roo->jerr('Invalid url');
649 foreach ($log['DELETED_DATAOBJECTS'] as $d){
652 empty($d['_table']) ||
654 !empty($restored[$d['_table']]) &&
655 in_array($d['id'], $restored[$d['_table']])
661 if(!isset($restored[$d['_table']])){
662 $restored[$d['_table']] = array();
665 $restored[$d['_table']][] = $d['id'];
667 $table = DB_DataObject::factory($d['_table']);
669 if (!is_a($table,'DB_DataObject')) {
678 * need to use the old id
680 $table->id = $d['id'];
682 $table->sequenceKey(false,false);
686 if($table->tableName() == 'crm_mailing_list_member'){
687 $ml = DB_DataObject::factory('crm_mailing_list');
688 if(!$ml->get($table->mailing_list_id)){
692 $mlm = DB_DataObject::factory('crm_mailing_list_member');
694 'mailing_list_id' => $table->mailing_list_id,
699 $ml->no_members = $mlm->count();
704 $roo->jok('RESTORE');
706 function selectAddPersonEmail()
708 $this->selectAdd('join_person_id_id.email as email');