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]}={$tn}.person_id)";
53 //$this->_join = "LEFT JOIN {$jt->tableName()} AS join_person_id_id ON (join_person_id_id.{$keys[0]}=Events.person_id)";
57 $this->selectAs($jt, 'person_id_%s', 'join_person_id_id');
59 if (method_exists($jt,'nameColumn')) {
60 $this->selectAdd("join_person_id_id.{$jt->nameColumn()} as person_id_name");
63 if (method_exists($jt,'emailColumn')) {
64 $this->selectAdd("join_person_id_id.{$jt->emailColumn()} as person_id_email");
71 $person = $au->tableName(); //'Person'; -- projects may not use person as the auth table...
72 $cfg = HTML_FlexyFramework::get()->Pman;
73 if (!empty($cfg['authTable'])) {
74 $person =$cfg['authTable'];
77 $jt = DB_DataObject::factory($person);
79 person_table = '{$jt->tableName()}'
82 OR person_table IS NULL"
83 ); // default to our standard.. - unless otherwise requested..
87 if (!empty($q['query']['from'])) {
88 $dt = date('Y-m-d' , strtotime($q['query']['from']));
89 $this->whereAdd(" {$tn}.event_when >= '$dt' ");
91 if (!empty($q['query']['to'])) {
92 $dt = date('Y-m-d' , strtotime($q['query']['to']));
93 $this->whereAdd(" {$tn}.event_when <= '$dt' ");
96 if (!empty($q['query']['grouped']) && $q['query']['grouped'] == 'gr') {
98 DB_DataObject::Debuglevel(1);
99 $this->groupBy('on_id');
101 (SELECT count(id) FROM core_event_audit WHERE event_id = Events.id) as changed
106 if (!$au->hasPerm("Admin.Admin_Tab", 'S')) {
107 //DB_DataObject::DebugLevel(1);
108 // they can only view their changes..
109 $this->whereAdd("($tn.person_id = {$au->id} OR $tn.person_id = 0)");
110 // $this->person_id = $au->id;
113 // _join = tablename,tablename...
117 // &_join_cols=cohead_number
118 // &_columns=on_id_cohead_number,event_when << this is ignored at present.
119 // max(event_when) is not supported... by any query yet..
121 if (isset($q['on_table']) && !strlen($q['on_table'])) {
122 // empty ontable queries.. these are valid..
123 $this->whereAdd("{$tn}.on_table = ''");
126 if (isset($q['query']['person_sum'])) {
127 //DB_DataObject::debugLevel(1);
128 $this->_extra_cols = array('qty' );
129 $this->selectAdd("count($tn.id) as qty");
130 $this->selectAdd("count( distinct $tn.on_id) as uqty");
131 $this->whereAdd('LENGTH(join_person_id_id.name) > 0 ');
132 $this->groupBy('person_id,join_person_id_id.name,join_person_id_id.email');
134 if (isset($q['query']['table_sum'])) {
135 //DB_DataObject::debugLevel(1);
136 $this->_extra_cols = array('qty' , 'uqty');
137 $this->selectAdd("count($tn.id) as qty");
138 $this->selectAdd("count( distinct $tn.on_table, $tn.on_id) as uqty");
140 $this->groupBy('on_table');
142 if (isset($q['query']['day_sum'])) {
143 //DB_DataObject::debugLevel(1);
144 $this->_extra_cols = array('qty' , 'uqty');
145 $this->selectAdd("DATE_FORMAT(event_when, '%Y-%m-%d') as on_day");
146 $this->selectAdd("count($tn.id) as qty");
147 $this->selectAdd("count( distinct $tn.on_id) as uqty");
149 $this->groupBy('on_day');
152 if (isset($q['_join'])) {
153 //DB_DataObject::DebugLevel(1);
154 $joins = explode(',',$q['_join']);
156 $this->selectAdd(); // ???
159 foreach($joins as $t) {
160 $t = preg_replace('/[^a-z_]+/', '', $t); // protection.
161 $x = DB_DataObject::Factory($t);
162 if (!is_a($x,'DB_DataObject')) {
165 $jtn = $x->tableName();
166 $jk = array_shift($x->keys());
169 LEFT JOIN {$jtn} as join_on_id_{$jtn} ON {$tn}.on_id = join_on_id_{$jtn}.{$jk}
170 AND on_table = '{$jtn}'
172 $keys = array_keys($x->tableColumns());
173 if (isset($q['_join_cols'])) {
174 $jcs = explode(',',$q['_join_cols'] );
175 //DB_DataObject::DebugLevel(1);
177 foreach($jcs as $jc) {
178 if (! in_array($jc, $keys)) {
184 $this->selectAdd( " join_on_id_{$jtn}.{$jc} as on_id_{$jc} ");
186 $this->selectAdd( " distinct(join_on_id_{$jtn}.{$jc} ) as on_id_{$jc} ");
189 $this->groupBy("on_id_{$jc} ");
190 $this->whereAdd("join_on_id_{$jtn}.{$jc} IS NOT NULL");
192 $this->selectAdd( "MAX(events.event_when) as event_when");
193 $this->orderBy('event_when DESC');
194 // $this->selectAs(array($q['_join_cols']) , 'on_id_%s', "join_on_id_{$jtn}");
196 $this->selectAs($x, 'on_id_%s', "join_on_id_{$jtn}");
203 if (isset($q['_related_on_id']) && isset($q['_related_on_table'])) {
204 // example: sales order - has invoices,
205 ///DB_DataObject::DebugLevel(1);
206 $ev =$this->factory('Events');
208 'on_id' => $q['_related_on_id'],
209 'on_table' => $q['_related_on_table'],
211 $obj = $ev->object();
214 $roo->jerr("ontable is invalid");
216 if (!method_exists($obj,'relatedWhere')) {
217 $roo->jerr( $q['_related_on_table'] . " Does not have method relatedWhere :" .
218 implode(',', get_class_methods($obj)));
220 if ($obj && method_exists($obj,'relatedWhere')) {
221 $ar = $obj->relatedWhere();
222 $tn = $this->tableName();
225 $w[] = "( {$tn}.on_table = '" .
226 $this->escape($q['_related_on_table']) .
227 "' AND {$tn}.on_id = ". ((int) $q['_related_on_id']) .
231 foreach($ar as $k=>$v) {
235 $w[] = "( {$tn}.on_table = '$k' AND {$tn}.on_id IN (". implode(',', $v). "))";
238 $this->whereAdd(implode(' OR ' , $w));
246 // since roo does not support autojoin yet..
247 if (!isset($q['_distinct'])) {
248 //$this->autoJoinExtra();
251 if(!empty($q['query']['action'])) {
252 $act = $this->escape($q['query']['action']);
253 $this->whereAdd("{$tn}.action LIKE '%{$act}%'");
256 if(!empty($q['query']['on_table'])) {
257 $tnb = $this->escape($q['query']['on_table']);
258 $this->whereAdd("{$tn}.on_table LIKE '%{$tnb}%'");
266 * check who is trying to access this. false == access denied..
267 * @return {boolean} true if access is allowed.
269 function checkPerm($lvl, $au)
274 // listing is controleed by applyfilters..
275 return $au->hasPerm("Admin.Admin_Tab", 'S');
279 * return the object that this relates to.
281 * @return {DB_DataObject} related object
285 $o = DB_DataObject::factory($this->on_table);
286 $o->get($this->on_id);
294 * Initialize an event - ready to insert..
296 * @param {String} action - group/name of event
297 * @param {DataObject|false} obj - dataobject action occured on.
298 * @param {String} any remarks
301 function init($act, $obj, $remarks)
303 $ff = HTML_FlexyFramework::get();
305 $au = $pg->getAuthUser();
307 if ($ff->cli) { // && empty($au) && isset($obj->person_id)) {
309 // $au = DB_DataObject::Factory('Person'); // not always a person..
310 // $au->get($obj->person_id);
313 $this->person_name = $au && !empty($au->name) ? $au->name : '';
314 if (empty($au) || (isset($au->id) && empty($au->id))) {
315 // not authenticated - and a standard id based object
316 $this->person_id = 0;
318 $col = $au->tableName() == "Person" ? 'person_id' : $au->tableName() . '_id';
320 $cols = $this->tableColumns();
321 $col = isset($cols[$col]) ? $col : 'person_id'; // for BC.... - revert to using person_id
322 $this->{$col} = $au->pid();
323 //$this->person_id = $au ? (!empty($au->id) ? $au->id : $au->pid()) : -1;
325 $this->person_table = $au ? $au->tableName() : '';
326 $this->ipaddr = isset($_SERVER["REMOTE_ADDR"]) ? $_SERVER["REMOTE_ADDR"] : 'cli';
327 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
328 $this->ipaddr = $_SERVER['HTTP_X_FORWARDED_FOR'];
331 $this->action = $act;
332 $this->on_table = $obj ? $obj->tableName() : '';
333 $pk = $obj ? $obj->keys() : false;
334 $this->on_id = $obj && $pk ? $obj->{$pk[0]}: 0;
336 // should this really go in remarks? -
337 if ($obj && method_exists($obj,'toEventString')) {
338 if($obj->toEventString() !== false){
339 $rem[] = $obj->toEventString();
343 $this->remarks = implode(' : ', $rem);
347 * Generate an audit for this field.
349 * @param {DB_DataObject} new data
350 * @param {DB_DataObject} old data
352 * @return {int} number of entries logged.
355 function audit($new, $old = false)
358 return 0; // they are the same...
362 foreach(array_keys($new->tableColumns()) as $k) {
363 // should we JSON serialize this?
364 $n = empty($new->$k) ? '' : $new->$k;
365 $o = empty($old->$k) || empty($old->$k) ? '' : $old->$k;
369 $this->auditField($k, $o, $n, $old);
375 * Record an audited change, in theory so we can audit data that is not just
378 * @param {string} $name table field anme
379 * @param {mixed} $ov old value
380 * @param {mixed} $onv new value
381 * @param {mixed} $old old object (false if we are creating..)
383 function auditField($name, $ov, $nv, $old=false )
386 if (is_object($nv)) {
391 $x = DB_DataObject::factory('core_event_audit');
393 'event_id' => $this->id,
395 'old_audit_id' => $old ? $x->findLast($this, $name) : 0,
403 function beforeInsert($request,$roo)
405 if(empty($this->event_when)){
406 $this->event_when = $this->sqlValue("NOW()");
409 if(empty($this->person_id)){
410 $this->person_id = $roo->authUser->id;
411 $this->person_name = $roo->authUser->name;
412 $this->person_table = $roo->authUser->tableName();
415 if(empty($this->ipaddr)){
416 $this->ipaddr = isset($_SERVER["REMOTE_ADDR"]) ? $_SERVER["REMOTE_ADDR"] : 'cli';
417 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
418 $this->ipaddr = $_SERVER['HTTP_X_FORWARDED_FOR'];
423 function beforeUpdate($old, $request,$roo)
425 if(!empty($request['_restore'])){
426 $this->restore($roo);
430 function onInsert($request,$roo)
432 $this->writeEventLog();
435 static $deleted = array();
438 // log deleting of a record so that it can be written later..
439 function logDeletedRecord($obj = false)
441 if (is_array($obj)) {
443 foreach($obj as $o) {
444 $aret = $this->logDeletedRecord($o);
445 $ret = $ret ? $ret : $aret;
450 if(empty($obj) || !is_a($obj, 'DB_DataObject')){
455 $del = $obj->toArray();
456 $del['_table'] = $obj->tableName();
458 self::$deleted[] = $del;
461 static $extra_data = false;
463 static function writeEventLogExtra($data) {
464 self::$extra_data = $data;
469 $ff = HTML_FlexyFramework::get();
470 if (function_exists('posix_getpwuid')) {
471 $uinfo = posix_getpwuid( posix_getuid () );
473 $user = $uinfo['name'];
475 $user = getenv('USERNAME'); // windows.
479 if (!empty($ff->Pman['event_log_dir'])) {
480 return $ff->Pman['event_log_dir'] . '/'.$user;
482 if (!empty($ff->Pman['storedir'])) {
483 return $ff->Pman['storedir'] .'/Events/'.$user;
491 function writeEventLog($extra_data = false)
493 $logdir = $this->logDir();
500 $file = $logdir. date('/Y/m/d/'). $this->id . ".json";
501 if (!file_exists(dirname($file))) {
503 @mkdir(dirname($file),0700,true); // this might fail if it does not have correct permissions..
504 if (!file_exists(dirname($file))) {
505 die("could not create $file - permissons are not correct"); // fatal, otherwise we loop!?
510 // Remove all the password from logs...
511 $p = empty($_POST) ? array() : $_POST;
512 foreach(array('passwd', 'password','passwd1', 'passwd2','password1', 'password2') as $rm) {
513 if (isset($p[$rm])) {
523 foreach ($_FILES as $k=>$f){
524 // does not handle any other file[] arrary very well..
525 if (empty($f['tmp_name']) || !file_exists($f['tmp_name'])) {
532 $files[$k]['tmp_name'] = $this->id . '-'. $i;
533 $nf = $logdir . date('/Y/m/d/'). $files[$k]['tmp_name'];
534 if (!copy($f['tmp_name'], $nf)) {
535 print_r("failed to copy {$f['tmp_name']}...\n");
539 'REQUEST_URI' => empty($_SERVER['REQUEST_URI']) ? 'cli' : $_SERVER['REQUEST_URI'],
540 'HTTP_USER_AGENT' => empty($_SERVER['HTTP_USER_AGENT']) ? '' : $_SERVER['HTTP_USER_AGENT'],
541 'GET' => empty($_GET) ? array() : $_GET,
546 if (!empty(self::$deleted)) {
547 $out['DELETED_DATAOBJECTS'] = self::$deleted;
549 if ($extra_data !== false) {
550 $out['EXTRA'] = $extra_data;
552 if ( self::$extra_data !== false) {
553 $out['EXTRA_DATA'] = self::$extra_data;
556 file_put_contents($file, json_encode($out));
561 function toRooArray( $q)
563 $ret = $this->toArray();
565 // fill toEventString.
566 if (!empty($q['_with_obj_summary']) && !empty($this->on_id)) {
567 $obj = $this->object();
569 if ($obj && $obj->pid() && method_exists($obj,'toEventString')) {
570 $es = $obj->toEventString();
572 if (empty($this->remarks) || strpos($this->remarks, $es) < 0) {
573 $ret['remarks'] = $es . ' ' . $this->remarks;
575 } else if (empty($this->remarks)){
576 $ret['remarks'] = "DELETED";
585 function toRooSingleArray($au, $q)
587 $ret = $this->toArray();
591 if(empty($q['_retrieve_source'])){
595 $file = $this->retrieveEventLog();
598 return "No records?!";
601 $source = json_decode(file_get_contents($file));
606 function retrieveEventLog()
609 $logdir = $this->logDir();
615 $date = date('/Y/m/d/', strtotime($this->event_when));
617 $file = $logdir. $date. $this->id . ".json";
618 if (!file_exists(dirname($file))) {
625 function restore($roo)
627 $file = $this->retrieveEventLog();
629 if(empty($file) || !file_exists($file)){
630 $roo->jerr('Could not retrieve the event log file');
633 $log = json_decode(file_get_contents($file), true);
635 if(empty($log['POST']) || empty($log['POST']['_delete']) || empty($log['DELETED_DATAOBJECTS'])){
636 $roo->jerr('Invalid url');
641 foreach ($log['DELETED_DATAOBJECTS'] as $d){
644 empty($d['_table']) ||
646 !empty($restored[$d['_table']]) &&
647 in_array($d['id'], $restored[$d['_table']])
653 if(!isset($restored[$d['_table']])){
654 $restored[$d['_table']] = array();
657 $restored[$d['_table']][] = $d['id'];
659 $table = DB_DataObject::factory($d['_table']);
661 if (!is_a($table,'DB_DataObject')) {
670 * need to use the old id
672 $table->id = $d['id'];
674 $table->sequenceKey(false,false);
678 if($table->tableName() == 'crm_mailing_list_member'){
679 $ml = DB_DataObject::factory('crm_mailing_list');
680 if(!$ml->get($table->mailing_list_id)){
684 $mlm = DB_DataObject::factory('crm_mailing_list_member');
686 'mailing_list_id' => $table->mailing_list_id,
691 $ml->no_members = $mlm->count();
696 $roo->jok('RESTORE');
698 function selectAddPersonEmail()
700 $this->selectAdd('join_person_id_id.email as email');