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
40 echo $this->tableName();
42 if(!empty($q['person_table'])){
43 $jt = DB_DataObject::factory($q['person_table']);
45 $et = DB_DataObject::factory($tn);
47 if(!array_key_exists("{$jt->tableName()}_id", $this->tableColumns())){ // coz we have triiger on mysql...
51 $this->_join = "LEFT JOIN {$jt->tableName()} AS join_person_id_id ON (join_person_id_id.{$keys[0]}=Events.person_id)";
52 $this->selectAdd("(select count(*) from Events where Events.dup_id = evet.id) as cnt ");
53 $this->selectAs($et,'%s','evet');
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['query']['grouped']) && $q['query']['grouped'] == 'gr') {
96 DB_DataObject::Debuglevel(1);
97 $this->groupBy('on_id');
99 (SELECT count(id) FROM core_event_audit WHERE event_id = Events.id) as changed
104 if (!$au->hasPerm("Admin.Admin_Tab", 'S')) {
105 //DB_DataObject::DebugLevel(1);
106 // they can only view their changes..
107 $this->whereAdd("($tn.person_id = {$au->id} OR $tn.person_id = 0)");
108 // $this->person_id = $au->id;
111 // _join = tablename,tablename...
115 // &_join_cols=cohead_number
116 // &_columns=on_id_cohead_number,event_when << this is ignored at present.
117 // max(event_when) is not supported... by any query yet..
119 if (isset($q['on_table']) && !strlen($q['on_table'])) {
120 // empty ontable queries.. these are valid..
121 $this->whereAdd("$tn.on_table = ''");
124 if (isset($q['query']['person_sum'])) {
125 //DB_DataObject::debugLevel(1);
126 $this->_extra_cols = array('qty' );
127 $this->selectAdd("count($tn.id) as qty");
128 $this->selectAdd("count( distinct $tn.on_id) as uqty");
129 $this->whereAdd('LENGTH(join_person_id_id.name) > 0 ');
130 $this->groupBy('person_id,join_person_id_id.name,join_person_id_id.email');
132 if (isset($q['query']['table_sum'])) {
133 //DB_DataObject::debugLevel(1);
134 $this->_extra_cols = array('qty' , 'uqty');
135 $this->selectAdd("count($tn.id) as qty");
136 $this->selectAdd("count( distinct $tn.on_table, $tn.on_id) as uqty");
138 $this->groupBy('on_table');
140 if (isset($q['query']['day_sum'])) {
141 //DB_DataObject::debugLevel(1);
142 $this->_extra_cols = array('qty' , 'uqty');
143 $this->selectAdd("DATE_FORMAT(event_when, '%Y-%m-%d') as on_day");
144 $this->selectAdd("count($tn.id) as qty");
145 $this->selectAdd("count( distinct $tn.on_id) as uqty");
147 $this->groupBy('on_day');
150 if (isset($q['_join'])) {
151 //DB_DataObject::DebugLevel(1);
152 $joins = explode(',',$q['_join']);
154 $this->selectAdd(); // ???
157 foreach($joins as $t) {
158 $t = preg_replace('/[^a-z_]+/', '', $t); // protection.
159 $x = DB_DataObject::Factory($t);
160 if (!is_a($x,'DB_DataObject')) {
163 $jtn = $x->tableName();
164 $jk = array_shift($x->keys());
167 LEFT JOIN {$jtn} as join_on_id_{$jtn} ON {$tn}.on_id = join_on_id_{$jtn}.{$jk}
168 AND on_table = '{$jtn}'
170 $keys = array_keys($x->tableColumns());
171 if (isset($q['_join_cols'])) {
172 $jcs = explode(',',$q['_join_cols'] );
173 //DB_DataObject::DebugLevel(1);
175 foreach($jcs as $jc) {
176 if (! in_array($jc, $keys)) {
182 $this->selectAdd( " join_on_id_{$jtn}.{$jc} as on_id_{$jc} ");
184 $this->selectAdd( " distinct(join_on_id_{$jtn}.{$jc} ) as on_id_{$jc} ");
187 $this->groupBy("on_id_{$jc} ");
188 $this->whereAdd("join_on_id_{$jtn}.{$jc} IS NOT NULL");
190 $this->selectAdd( "MAX(events.event_when) as event_when");
191 $this->orderBy('event_when DESC');
192 // $this->selectAs(array($q['_join_cols']) , 'on_id_%s', "join_on_id_{$jtn}");
194 $this->selectAs($x, 'on_id_%s', "join_on_id_{$jtn}");
201 if (isset($q['_related_on_id']) && isset($q['_related_on_table'])) {
202 // example: sales order - has invoices,
203 ///DB_DataObject::DebugLevel(1);
204 $ev =$this->factory('Events');
206 'on_id' => $q['_related_on_id'],
207 'on_table' => $q['_related_on_table'],
209 $obj = $ev->object();
212 $roo->jerr("ontable is invalid");
214 if (!method_exists($obj,'relatedWhere')) {
215 $roo->jerr( $q['_related_on_table'] . " Does not have method relatedWhere :" .
216 implode(',', get_class_methods($obj)));
218 if ($obj && method_exists($obj,'relatedWhere')) {
219 $ar = $obj->relatedWhere();
220 $tn = $this->tableName();
223 $w[] = "( {$tn}.on_table = '" .
224 $this->escape($q['_related_on_table']) .
225 "' AND {$tn}.on_id = ". ((int) $q['_related_on_id']) .
229 foreach($ar as $k=>$v) {
233 $w[] = "( {$tn}.on_table = '$k' AND {$tn}.on_id IN (". implode(',', $v). "))";
236 $this->whereAdd(implode(' OR ' , $w));
244 // since roo does not support autojoin yet..
245 if (!isset($q['_distinct'])) {
246 //$this->autoJoinExtra();
249 if(!empty($q['query']['action'])) {
250 $act = $this->escape($q['query']['action']);
251 $this->whereAdd("Events.action LIKE '%{$act}%'");
254 if(!empty($q['query']['on_table'])) {
255 $tnb = $this->escape($q['query']['on_table']);
256 $this->whereAdd("Events.on_table LIKE '%{$tnb}%'");
264 * check who is trying to access this. false == access denied..
265 * @return {boolean} true if access is allowed.
267 function checkPerm($lvl, $au)
272 // listing is controleed by applyfilters..
273 return $au->hasPerm("Admin.Admin_Tab", 'S');
277 * return the object that this relates to.
279 * @return {DB_DataObject} related object
283 $o = DB_DataObject::factory($this->on_table);
284 $o->get($this->on_id);
292 * Initialize an event - ready to insert..
294 * @param {String} action - group/name of event
295 * @param {DataObject|false} obj - dataobject action occured on.
296 * @param {String} any remarks
299 function init($act, $obj, $remarks)
301 $ff = HTML_FlexyFramework::get();
303 $au = $pg->getAuthUser();
305 if ($ff->cli) { // && empty($au) && isset($obj->person_id)) {
307 // $au = DB_DataObject::Factory('Person'); // not always a person..
308 // $au->get($obj->person_id);
311 $this->person_name = $au && !empty($au->name) ? $au->name : '';
312 if (empty($au) || (isset($au->id) && empty($au->id))) {
313 // not authenticated - and a standard id based object
314 $this->person_id = 0;
316 $col = $au->tableName() == "Person" ? 'person_id' : $au->tableName() . '_id';
318 $cols = $this->tableColumns();
319 $col = isset($cols[$col]) ? $col : 'person_id'; // for BC.... - revert to using person_id
320 $this->{$col} = $au->pid();
321 //$this->person_id = $au ? (!empty($au->id) ? $au->id : $au->pid()) : -1;
323 $this->person_table = $au ? $au->tableName() : '';
324 $this->ipaddr = isset($_SERVER["REMOTE_ADDR"]) ? $_SERVER["REMOTE_ADDR"] : 'cli';
325 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
326 $this->ipaddr = $_SERVER['HTTP_X_FORWARDED_FOR'];
329 $this->action = $act;
330 $this->on_table = $obj ? $obj->tableName() : '';
331 $pk = $obj ? $obj->keys() : false;
332 $this->on_id = $obj && $pk ? $obj->{$pk[0]}: 0;
334 // should this really go in remarks? -
335 if ($obj && method_exists($obj,'toEventString')) {
336 if($obj->toEventString() !== false){
337 $rem[] = $obj->toEventString();
341 $this->remarks = implode(' : ', $rem);
345 * Generate an audit for this field.
347 * @param {DB_DataObject} new data
348 * @param {DB_DataObject} old data
350 * @return {int} number of entries logged.
353 function audit($new, $old = false)
356 return 0; // they are the same...
360 foreach(array_keys($new->tableColumns()) as $k) {
361 // should we JSON serialize this?
362 $n = empty($new->$k) ? '' : $new->$k;
363 $o = empty($old->$k) || empty($old->$k) ? '' : $old->$k;
367 $this->auditField($k, $o, $n, $old);
373 * Record an audited change, in theory so we can audit data that is not just
376 * @param {string} $name table field anme
377 * @param {mixed} $ov old value
378 * @param {mixed} $onv new value
379 * @param {mixed} $old old object (false if we are creating..)
381 function auditField($name, $ov, $nv, $old=false )
384 if (is_object($nv)) {
389 $x = DB_DataObject::factory('core_event_audit');
391 'event_id' => $this->id,
393 'old_audit_id' => $old ? $x->findLast($this, $name) : 0,
401 function beforeInsert($request,$roo)
403 if(empty($this->event_when)){
404 $this->event_when = $this->sqlValue("NOW()");
407 if(empty($this->person_id)){
408 $this->person_id = $roo->authUser->id;
409 $this->person_name = $roo->authUser->name;
410 $this->person_table = $roo->authUser->tableName();
413 if(empty($this->ipaddr)){
414 $this->ipaddr = isset($_SERVER["REMOTE_ADDR"]) ? $_SERVER["REMOTE_ADDR"] : 'cli';
415 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
416 $this->ipaddr = $_SERVER['HTTP_X_FORWARDED_FOR'];
421 function beforeUpdate($old, $request,$roo)
423 if(!empty($request['_restore'])){
424 $this->restore($roo);
428 function onInsert($request,$roo)
430 $this->writeEventLog();
433 static $deleted = array();
436 // log deleting of a record so that it can be written later..
437 function logDeletedRecord($obj = false)
439 if (is_array($obj)) {
441 foreach($obj as $o) {
442 $aret = $this->logDeletedRecord($o);
443 $ret = $ret ? $ret : $aret;
448 if(empty($obj) || !is_a($obj, 'DB_DataObject')){
453 $del = $obj->toArray();
454 $del['_table'] = $obj->tableName();
456 self::$deleted[] = $del;
459 static $extra_data = false;
461 static function writeEventLogExtra($data) {
462 self::$extra_data = $data;
467 $ff = HTML_FlexyFramework::get();
468 if (function_exists('posix_getpwuid')) {
469 $uinfo = posix_getpwuid( posix_getuid () );
471 $user = $uinfo['name'];
473 $user = getenv('USERNAME'); // windows.
477 if (!empty($ff->Pman['event_log_dir'])) {
478 return $ff->Pman['event_log_dir'] . '/'.$user;
480 if (!empty($ff->Pman['storedir'])) {
481 return $ff->Pman['storedir'] .'/Events/'.$user;
489 function writeEventLog($extra_data = false)
491 $logdir = $this->logDir();
498 $file = $logdir. date('/Y/m/d/'). $this->id . ".json";
499 if (!file_exists(dirname($file))) {
501 @mkdir(dirname($file),0700,true); // this might fail if it does not have correct permissions..
502 if (!file_exists(dirname($file))) {
503 die("could not create $file - permissons are not correct"); // fatal, otherwise we loop!?
508 // Remove all the password from logs...
509 $p = empty($_POST) ? array() : $_POST;
510 foreach(array('passwd', 'password','passwd1', 'passwd2','password1', 'password2') as $rm) {
511 if (isset($p[$rm])) {
521 foreach ($_FILES as $k=>$f){
522 // does not handle any other file[] arrary very well..
523 if (empty($f['tmp_name']) || !file_exists($f['tmp_name'])) {
530 $files[$k]['tmp_name'] = $this->id . '-'. $i;
531 $nf = $logdir . date('/Y/m/d/'). $files[$k]['tmp_name'];
532 if (!copy($f['tmp_name'], $nf)) {
533 print_r("failed to copy {$f['tmp_name']}...\n");
537 'REQUEST_URI' => empty($_SERVER['REQUEST_URI']) ? 'cli' : $_SERVER['REQUEST_URI'],
538 'HTTP_USER_AGENT' => empty($_SERVER['HTTP_USER_AGENT']) ? '' : $_SERVER['HTTP_USER_AGENT'],
539 'GET' => empty($_GET) ? array() : $_GET,
544 if (!empty(self::$deleted)) {
545 $out['DELETED_DATAOBJECTS'] = self::$deleted;
547 if ($extra_data !== false) {
548 $out['EXTRA'] = $extra_data;
550 if ( self::$extra_data !== false) {
551 $out['EXTRA_DATA'] = self::$extra_data;
554 file_put_contents($file, json_encode($out));
559 function toRooArray( $q)
561 $ret = $this->toArray();
563 // fill toEventString.
564 if (!empty($q['_with_obj_summary']) && !empty($this->on_id)) {
565 $obj = $this->object();
567 if ($obj && $obj->pid() && method_exists($obj,'toEventString')) {
568 $es = $obj->toEventString();
570 if (empty($this->remarks) || strpos($this->remarks, $es) < 0) {
571 $ret['remarks'] = $es . ' ' . $this->remarks;
573 } else if (empty($this->remarks)){
574 $ret['remarks'] = "DELETED";
583 function toRooSingleArray($au, $q)
585 $ret = $this->toArray();
589 if(empty($q['_retrieve_source'])){
593 $file = $this->retrieveEventLog();
596 return "No records?!";
599 $source = json_decode(file_get_contents($file));
604 function retrieveEventLog()
607 $logdir = $this->logDir();
613 $date = date('/Y/m/d/', strtotime($this->event_when));
615 $file = $logdir. $date. $this->id . ".json";
616 if (!file_exists(dirname($file))) {
623 function restore($roo)
625 $file = $this->retrieveEventLog();
627 if(empty($file) || !file_exists($file)){
628 $roo->jerr('Could not retrieve the event log file');
631 $log = json_decode(file_get_contents($file), true);
633 if(empty($log['POST']) || empty($log['POST']['_delete']) || empty($log['DELETED_DATAOBJECTS'])){
634 $roo->jerr('Invalid url');
639 foreach ($log['DELETED_DATAOBJECTS'] as $d){
642 empty($d['_table']) ||
644 !empty($restored[$d['_table']]) &&
645 in_array($d['id'], $restored[$d['_table']])
651 if(!isset($restored[$d['_table']])){
652 $restored[$d['_table']] = array();
655 $restored[$d['_table']][] = $d['id'];
657 $table = DB_DataObject::factory($d['_table']);
659 if (!is_a($table,'DB_DataObject')) {
668 * need to use the old id
670 $table->id = $d['id'];
672 $table->sequenceKey(false,false);
676 if($table->tableName() == 'crm_mailing_list_member'){
677 $ml = DB_DataObject::factory('crm_mailing_list');
678 if(!$ml->get($table->mailing_list_id)){
682 $mlm = DB_DataObject::factory('crm_mailing_list_member');
684 'mailing_list_id' => $table->mailing_list_id,
689 $ml->no_members = $mlm->count();
694 $roo->jok('RESTORE');
696 function selectAddPersonEmail()
698 $this->selectAdd('join_person_id_id.email as email');