4 require_once 'Pman.php';
10 * Uses these methods of the dataobjects:
12 * - checkPerm('L'/'E'/'A', $authuser) - can we list the stuff
14 * - applySort($au, $sortcol, $direction, $array_of_columns, $multisort) -- does not support multisort at present..
15 * - applyFilters($_REQUEST, $authUser, $roo) -- apply any query filters on data. and hide stuff not to be seen. (RETURN false to prevent default filters.)
16 * - postListExtra($_REQUEST) : array(extra_name => data) - add extra column data on the results (like new messages etc.)
17 * - postListFilter($data, $authUser, $request) return $data - add extra data to an object
19 * - toRooSingleArray($authUser, $request) // single fetch, add data..
20 * - toRooArray($request) /// toArray if you need to return different data.. for a list fetch.
23 * CRUD - before/after handlers..
24 * - setFromRoo($ar, $roo) - values from post (deal with dates etc.) - return true|error string.
25 * ... call $roo->jerr() on failure...
28 * - beforeDelete($dependants_array, $roo) Argument is an array of un-find/fetched dependant items.
29 * - jerr() will stop insert.. (Prefered)
30 * - return false for fail and set DO->err;
31 * - beforeUpdate($old, $request,$roo) - after update - jerr() will stop insert..
32 * - beforeInsert($request,$roo) - before insert - jerr() will stop insert..
35 * - onUpdate($old, $request,$roo, $event) - after update // return value ignored
36 * - onInsert($request,$roo, $event) - after insert
37 * - onDelete($req, $roo) - after delete
42 * - toEventString (for logging - this is generically prefixed to all database operations.)
45 class Pman_Roo extends Pman
48 * if set to an array (when extending this, then you can restrict which tables are available
50 var $validTables = false;
52 var $key; // used by update currenly to store primary key.
55 var $max_limit = 10000;
57 var $debugEnabled = true; // disable this for public versions of this code.
61 parent::getAuth(); // load company!
62 $au = $this->getAuthUser();
65 $this->jerr("Not authenticated", array('authFailure' => true));
67 if (!$au->pid() ) { // not set up yet..
68 $this->jerr("Not authenticated", array('authFailure' => true));
72 $this->authUser = $au;
76 * GET method Roo/TABLENAME
78 * Generally for SELECT or Single SELECT
81 * _id=value single fetch based on primary id.
82 * can be '0' if you want to fetch a set of defaults
83 * Use in conjuntion with toRooSingleArray()
85 * lookup[key]=value single fetch based on a single key value lookup.
86 * multiple key/value can be used. eg. ontable+onid..
87 * _columns what to return.
91 * - all tables are always autojoined.
95 * _columns=a,b,c,d comma seperated list of columns.
96 * _exclude_columns=a,b,c,d comma seperated list of columns.
97 * _distinct=name a distinct column lookup. you also have to use _columns with this.
100 * colname = ... => colname = ....
101 * !colname=.... => colname != ....
102 * !colname[0]=... !colname[1]=... => colname NOT IN (.....) ** only supports main table at present..
103 * colname[0]=... colname[1]=... => colname IN (.....) ** only supports main table at present..
106 * sort=name what to sort.
107 * sort=a,b,d can support multiple columns
108 * dir=ASC what direction
109 * _multisort ={...} JSON encoded { sort : { row : direction }, order : [ row, row, row ] }
112 * start=0 limit start
113 * limit=25 limit number
117 * csvCols[0] csvCols[1].... = .... column titles for CSV output
118 * csvTitles[0], csvTitles[1] .... = columns to use for CSV output
121 * _toggleActive !:!:!:! - this hsould not really be here..
122 * query[add_blank] - add a line in with an empty option... - not really needed???
123 * _delete = delete a list of ids element. (depricated.. this will be removed...)
126 * _post =1 = simulate a post with debuggin on.
127 * _debug_post << This is prefered, as _post may overlap with accouting posts..
129 * _debug = turn on DB_dataobject deubbing, must be admin at present..
132 * CALLS methods on dataobjects if they exist
135 * checkPerm('S' , $authuser)
136 * - can we list the stuff
137 * - return false to disallow...
138 * applySort($au, $sortcol, $direction, $array_of_columns, $multisort)
139 * -- does not support multisort at present..
140 * applyFilters($_REQUEST, $authUser, $roo)
141 * -- apply any query filters on data. and hide stuff not to be seen.
142 * -- can exit by calling $roo->jerr()
143 * postListExtra($_REQUEST) : array(extra_name => data)
144 * - add extra column data on the results (like new messages etc.)
145 * postListFilter($data, $authUser, $request) return $data
146 * - add extra data to an object
149 * toRooSingleArray($authUser, $request) : array
150 * - called on single fetch only, add or maniuplate returned array data.
151 * - is also called when _id=0 is used (for fetching a default set.)
152 * toRooArray($request) : array
153 * - called if singleArray is unavailable on single fetch.
154 * - always tried for mutiple results.
155 * toArray() - the default method if none of the others are found.
158 * - standard DataObject feature - causes all results to show all
162 * _extra_cols -- if set, then filtering by column etc. will use them.
166 function get($tab, $opts = Array())
168 // $this->jerr("Not authenticated", array('authFailure' => true));
169 //echo '<PRE>';print_R($_GET);
170 //DB_DataObject::debuglevel(1);
172 $this->init(); // from pman.
173 //DB_DataObject::debuglevel(1);
174 HTML_FlexyFramework::get()->generateDataobjectsCache($this->isDev && !empty($_REQUEST['isDev']));
182 if ( $this->checkDebugPost()) {
187 //DB_DAtaObject::debuglevel(1);
188 return $this->post($tab);
192 $this->initErrorHandling();
194 $tt = explode('/', $tab);
195 $tab = array_shift($tt);
196 $x = $this->dataObject($tab);
198 $_columns = !empty($_REQUEST['_columns']) ? explode(',', $_REQUEST['_columns']) : false;
200 if (isset( $_REQUEST['lookup'] ) && is_array($_REQUEST['lookup'] )) { // single fetch based on key/value pairs
201 $this->selectSingle($x, $_REQUEST['lookup'],$_REQUEST);
206 // single fetch (use '0' to fetch an empty object..)
207 if (isset($_REQUEST['_id']) && is_numeric($_REQUEST['_id'])) {
209 $this->selectSingle($x, $_REQUEST['_id'],$_REQUEST);
216 if (isset($_REQUEST['_delete'])) {
217 $this->jerr("DELETE by GET has been removed - update the code to use POST");
224 if (isset($_REQUEST['_toggleActive'])) {
225 // do we really delete stuff!?!?!?
226 if (!$this->hasPerm("Core.Staff", 'E')) {
227 $this->jerr("PERMISSION DENIED (ta)");
229 $clean = create_function('$v', 'return (int)$v;');
230 $bits = array_map($clean, explode(',', $_REQUEST['_toggleActive']));
231 if (in_array($this->authUser->id, $bits) && $this->authUser->active) {
232 $this->jerr("you can not disable yourself");
234 $x->query('UPDATE core_person SET active = !active WHERE id IN (' .implode(',', $bits).')');
235 $this->addEvent("USERTOGGLE", false, implode(',', $bits));
236 $this->jok("Updated");
239 //DB_DataObject::debugLevel(1);
241 // sets map and countWhat
242 $this->loadMap($x, array(
243 'columns' => $_columns,
244 'distinct' => empty($_REQUEST['_distinct']) ? false: $_REQUEST['_distinct'],
245 'exclude' => empty($_REQUEST['_exclude_columns']) ? false: explode(',', $_REQUEST['_exclude_columns'])
249 $this->setFilters($x,$_REQUEST);
251 if (!$this->checkPerm($x,'S', $_REQUEST)) {
252 $this->jerr("PERMISSION DENIED (g)");
256 // build join if req.
257 //DB_DataObject::debugLevel(1);
258 // var_dump($this->countWhat);
259 $total = $x->count($this->countWhat);
262 //var_dump($total);exit;
263 $this->applySort($x);
267 if (!empty($_REQUEST['_distinct']) && $total < 400) {
274 empty($_REQUEST['start']) ? 0 : (int)$_REQUEST['start'],
275 min(empty($_REQUEST['limit']) ? 25 : (int)$_REQUEST['limit'], $this->max_limit)
278 $queryObj = clone($x);
279 //DB_DataObject::debuglevel(1);
281 $this->sessionState(0);
283 $this->sessionState(1);
285 if (false === $res) {
286 $this->jerr($x->_lastError->toString());
294 // ---------------- THESE ARE DEPRICATED.. they should be moved to the model...
297 if (!empty($_REQUEST['query']['add_blank'])) {
298 $ret[] = array( 'id' => 0, 'name' => '----');
302 $rooar = method_exists($x, 'toRooArray');
303 $_columnsf = $_columns ? array_flip($_columns) : false;
304 while ($x->fetch()) {
306 $add = $rooar ? $x->toRooArray($_REQUEST) : $x->toArray();
307 if ($add === false) {
310 $ret[] = !$_columns ? $add : array_intersect_key($add, $_columnsf);
314 $ret = array_slice($ret,
315 empty($_REQUEST['start']) ? 0 : (int)$_REQUEST['start'],
316 min(empty($_REQUEST['limit']) ? 25 : (int)$_REQUEST['limit'], 10000)
323 if (method_exists($queryObj ,'postListExtra')) {
324 $extra = $queryObj->postListExtra($_REQUEST, $this);
328 // filter results, and add any data that is needed...
329 if (method_exists($x,'postListFilter')) {
330 $ret = $x->postListFilter($ret, $this->authUser, $_REQUEST);
335 if (!empty($_REQUEST['csvCols']) && !empty($_REQUEST['csvTitles']) ) {
338 $this->toCsv($ret, $_REQUEST['csvCols'], $_REQUEST['csvTitles'],
339 empty($_REQUEST['csvFilename']) ? '' : $_REQUEST['csvFilename']
347 //if ($x->tableName() == 'Documents_Tracking') {
348 // $ret = $this->replaceSubject(&$ret, 'doc_id_subject');
353 if (!empty($_REQUEST['_requestMeta']) && count($ret)) {
354 $meta = $this->meta($x, $ret);
356 $extra['metaData'] = $meta;
359 // this make take some time...
360 $this->sessionState(0);
361 // echo "<PRE>"; print_r($ret);
362 $this->jdata($ret, max(count($ret), $total), $extra );
366 function checkDebug($req = false)
368 $req = $req === false ? $_REQUEST : $req;
370 if (empty($req['_debug'])) {
374 if (!empty($_SERVER['HTTP_HOST']) && $_SERVER['HTTP_HOST'] == 'localhost') {
375 DB_DAtaObject::debuglevel((int)$req['_debug']);
383 method_exists($this->authUser,'canDebug')
385 $this->authUser->canDebug()
390 method_exists($this->authUser,'groups')
392 is_a($this->authUser, 'Pman_Core_DataObjects_Core_person')
394 in_array('Administrators', $this->authUser->groups('name'))
399 DB_DAtaObject::debuglevel((int)$req['_debug']);
404 function checkDebugPost()
406 if (empty($_GET['_post']) && empty($_GET['_debug_post'])) {
409 // localhost can do anything...
410 if (!empty($_SERVER['HTTP_HOST']) && $_SERVER['HTTP_HOST'] == 'localhost') {
413 return $this->authUser &&
414 method_exists($this->authUser,'groups') &&
415 in_array('Administrators', $this->authUser->groups('name'));
419 function checkPerm($obj, $lvl, $req= null)
421 if (!method_exists($obj, 'checkPerm')) {
424 if ($obj->checkPerm($lvl, $this->authUser, $req)) {
430 function toCsv($data, $cols, $titles, $filename, $addDate = true)
433 $this->sessionState(0); // turn off sessions - no locking..
435 require_once 'Pman/Core/SimpleExcel.php';
437 $fn = (empty($filename) ? 'list-export-' : urlencode($filename)) . (($addDate) ? date('Y-m-d') : '') ;
441 'workbook' => substr($fn, 0, 31),
448 if (is_object($data)) {
449 $rooar = method_exists($data, 'toRooArray');
450 while($data->fetch()) {
451 $x = $rooar ? $data->toRooArray($q) : $data->toArray();
454 if ($cols == '*') { /// did we get cols sent to us?
455 $cols = array_keys($x);
458 if(!is_array($cols)) {
459 $cols = explode(',', $cols);
462 if ($titles !== false) {
464 $titles= array_keys($x);
466 if(!is_array($titles)) {
467 $titles = explode(',', $titles);
469 foreach($cols as $i=>$col) {
470 $se_config['cols'][] = array(
471 'header'=> isset($titles[$i]) ? $titles[$i] : $col,
474 // 'renderer' => array($this, 'getThumb'),
475 // 'color' => 'yellow', // set color for the cell which is a header element
476 // 'fillBlank' => 'gray', // set
478 $se = new Pman_Core_SimpleExcel(array(), $se_config);
487 $se->addLine($se_config['workbook'], $x);
493 $this->jerr('no data found', false, 'text/plain');
495 $se->send($fn .'.xls');
501 foreach($data as $x) {
502 //echo "<PRE>"; print_r(array($_REQUEST['csvCols'], $x->toArray())); exit;
505 $titles= array_keys($x);
508 $cols= array_keys($x);
511 if ($titles !== false) {
512 foreach($cols as $i=>$col) {
513 $se_config['cols'][] = array(
514 'header'=> isset($titles[$i]) ? $titles[$i] : $col,
517 // 'renderer' => array($this, 'getThumb'),
518 // 'color' => 'yellow', // set color for the cell which is a header element
519 // 'fillBlank' => 'gray', // set
521 $se = new Pman_Core_SimpleExcel(array(),$se_config);
527 //fputcsv($fh, $titles);
533 $se->addLine($se_config['workbook'], $x);
536 $this->jerr('no data found');
538 $se->send($fn .'.xls');
547 * POST method Roo/TABLENAME
548 * -- creates, updates, or deletes data.
551 * if the primary key is empty, this happens
552 * will automatically set these to current date and authUser->id
553 * created, created_by, created_dt
554 * updated, update_by, updated_dt
555 * modified, modified_by, modified_dt
557 * will return a GET request SINGLE SELECT (and accepts same)
560 * _delete=1,2,3 delete a set of data.
562 * if the primary key value is set, then update occurs.
563 * will automatically set these to current date and authUser->id
564 * updated, update_by, updated_dt
565 * modified, modified_by, modified_dt
569 * _delete=1,2,3 causes a delete to occur.
570 * _ids=1,2,3,4 causes update to occur on all primary ids.
573 * = same as single SELECT GET request..
578 * _debug=1 forces debug
579 * _get=1 - causes a get request to occur when doing a POST..
583 * these methods on dataobjects if they exist
585 * checkPerm('E' / 'D' , $authuser)
586 * - can we list the stuff
587 * - return false to disallow...
589 * toRooSingleArray($authUser, $request) : array
590 * - called on single fetch only, add or maniuplate returned array data.
591 * toRooArray($request) : array
592 * - Called if toSingleArray does not exist.
593 * - if you need to return different data than toArray..
596 * (for logging - this is generically prefixed to all database operations.)
600 * called when $_FILES is not empty
603 * setFromRoo($ar, $roo)
604 * - alternative to setFrom() which is called if this method does not exist
605 * - values from post (deal with dates etc.) - return true|error string.
606 * - call $roo->jerr() on failure...
608 * CALLS BEFORE change occurs:
610 * beforeDelete($dependants_array, $roo)
611 * Argument is an array of un-find/fetched dependant items.
612 * - jerr() will stop insert.. (Prefered)
613 * - return false for fail and set DO->err;
615 * beforeUpdate($old, $request,$roo)
616 * - after update - jerr() will stop insert..
617 * beforeInsert($request,$roo)
618 * - before insert - jerr() will stop insert..
621 * CALLS AFTER change occured
623 * onUpdate($old, $request,$roo)
624 * - after update // return value ignored
626 * onInsert($request,$roo)
629 * onDelete($request, $roo) - after delete
633 function post($tab) // update / insert (?? delete??)
635 // -- why was this put in? - Roo is not related to Core.All ?
636 //if (!$this->hasPerm("Core.All", 'E')) {
637 // $this->jerr("PERMISSION DENIED (e)");
639 $this->initErrorHandling();
641 // DB_DataObject::debugLevel(1);
644 if (!empty($_REQUEST['_get'])) {
645 return $this->get($tab);
648 $this->init(); // for pman.
650 $x = $this->dataObject($tab);
652 $this->transObj = clone($x);
654 $this->transObj->query('BEGIN');
655 // find the key and use that to get the thing..
658 $this->jerr('no key');
661 $this->key = $keys[0];
663 // delete should be here...
664 if (isset($_REQUEST['_delete'])) {
665 // do we really delete stuff!?!?!?
666 return $this->delete($x,$_REQUEST);
674 // not sure if this is a good idea here...
676 if (!empty($_REQUEST['_ids'])) {
677 $ids = explode(',',$_REQUEST['_ids']);
678 $x->whereAddIn($this->key, $ids, 'int');
679 $ar = $x->fetchAll();
682 $this->update($x, $_REQUEST);
685 $this->jok("UPDATED");
690 if (!empty($_REQUEST[$this->key])) {
692 if (!$x->get($this->key, $_REQUEST[$this->key])) {
693 $this->jerr("Invalid request (id does not point to a record.)");
695 $this->jok($this->update($x, $_REQUEST));
699 $this->jerr("No data recieved for inserting");
702 $this->jok($this->insert($x, $_REQUEST));
714 * apply REQUEST[sort] and [dir]
715 * sort may be an array of columsn..
717 * @arg DB_DataObject $x
720 function applySort($x, $sort = '', $dir ='')
723 // Db_DataObject::debugLevel(1);
724 $sort = empty($_REQUEST['sort']) ? $sort : $_REQUEST['sort'];
725 $dir = empty($_REQUEST['dir']) ? $dir : $_REQUEST['dir'];
726 $dir = $dir == 'ASC' ? 'ASC' : 'DESC';
728 $ms = empty($_REQUEST['_multisort']) ? false : $_REQUEST['_multisort'];
729 //var_Dump($ms);exit;
731 if (method_exists($x, 'applySort')) {
732 $sorted = $x->applySort(
736 array_keys($this->cols),
737 $ms ? json_decode($ms) : false
741 return $this->multiSort($x);
744 if ($sorted === false) {
746 $cols = $x->tableColumns();
747 $excols = array_keys($this->cols);
749 if (isset($x->_extra_cols)) {
750 $excols = array_merge($excols, $x->_extra_cols);
752 $sort_ar = explode(',', $sort);
755 foreach($sort_ar as $sort) {
757 if (strlen($sort) && isset($cols[$sort]) ) {
758 $sort_str[] = $x->tableName() .'.'.$sort . ' ' . $dir ;
760 } else if (in_array($sort, $excols)) {
761 $sort_str[] = $sort . ' ' . $dir ;
766 $x->orderBy(implode(', ', $sort_str ));
777 function multiSort($x)
779 //DB_DataObject::debugLevel(1);
780 $ms = json_decode($_REQUEST['_multisort']);
781 if (!isset($ms->order) || !is_array($ms->order)) {
786 $cols = $x->tableColumns();
788 //print_r($this->cols);exit;
789 // this-><cols contains colname => aliased name...
790 foreach($ms->order as $col) {
791 if (!isset($ms->sort->{$col})) {
792 continue; // no direction..
794 $ms->sort->{$col} = $ms->sort->{$col} == 'ASC' ? 'ASC' : 'DESC';
796 if (strlen($col) && isset($cols[$col]) ) {
797 $sort_str[] = $x->tableName() .'.'.$col . ' ' . $ms->sort->{$col};
800 //print_r($this->cols);
802 if (in_array($col, array_keys($this->cols))) {
803 $sort_str[] = $col. ' ' . $ms->sort->{$col};
806 if (isset($x->_extra_cols) && in_array($col, $x->_extra_cols)) {
807 $sort_str[] = $col. ' ' . $ms->sort->{$col};
812 $x->orderBy(implode(', ', $sort_str ));
819 * - used when _id is set, or after insert or update
821 * @param DataObject $x the dataobject to use
822 * @param int $id the pid of the object
823 * @param array $req the request, or false if it comes from insert/update.
826 function selectSingle($x, $id, $req=false)
830 $_columns = !empty($req['_columns']) ? explode(',', $req['_columns']) : false;
832 //var_dump(array(!is_array($id) , empty($id)));
833 if (!is_array($id) && empty($id)) {
836 if (method_exists($x, 'toRooSingleArray')) {
837 $this->jok($x->toRooSingleArray($this->authUser, $req));
839 if (method_exists($x, 'toRooArray')) {
840 $this->jok($x->toRooArray($req));
843 $this->jok($x->toArray());
847 $this->loadMap($x, array(
848 'columns' => $_columns,
851 if ($req !== false) {
852 $this->setFilters($x, $req);
853 } else if (method_exists($x, 'applyFilters')) {
854 // always call apply filters even after update/insert...
855 // however arguments are not passed.
856 $x->applyFilters(array('_is_update_request' => true), $this->authUser, $this);
859 // DB_DataObject::DebugLevel(1);
862 $x->setFrom($req['lookup'] );
864 if (!$x->find(true)) {
865 if (!empty($id['_id'])) {
867 $this->jok($x->toArray());
872 } else if (!$x->get($id)) {
873 $this->jerr("selectSingle: no such record ($id)");
876 // ignore perms if comming from update/insert - as it's already done...
877 if ($req !== false && !$this->checkPerm($x,'S')) {
878 $this->jerr("PERMISSION DENIED - si");
880 // different symantics on all these calls??
881 if (method_exists($x, 'toRooSingleArray')) {
882 $this->jok($x->toRooSingleArray($this->authUser, $req));
884 if (method_exists($x, 'toRooArray')) {
885 $this->jok($x->toRooArray($req));
888 $this->jok($x->toArray());
893 function insert($x, $req, $with_perm_check = true)
895 if (method_exists($x, 'setFromRoo')) {
896 $res = $x->setFromRoo($req, $this);
897 if (is_string($res)) {
904 if ( $with_perm_check && !$this->checkPerm($x,'A', $req)) {
905 $this->jerr("PERMISSION DENIED (i)");
907 $cols = $x->tableColumns();
909 if (isset($cols['created'])) {
910 $x->created = date('Y-m-d H:i:s');
912 if (isset($cols['created_dt'])) {
913 $x->created_dt = date('Y-m-d H:i:s');
915 if (isset($cols['created_by'])) {
916 $x->created_by = $this->authUser->id;
919 if (isset($cols['modified'])) {
920 $x->modified = date('Y-m-d H:i:s');
922 if (isset($cols['modified_dt'])) {
923 $x->modified_dt = date('Y-m-d H:i:s');
925 if (isset($cols['modified_by'])) {
926 $x->modified_by = $this->authUser->id;
929 if (isset($cols['updated'])) {
930 $x->updated = date('Y-m-d H:i:s');
932 if (isset($cols['updated_dt'])) {
933 $x->updated_dt = date('Y-m-d H:i:s');
935 if (isset($cols['updated_by'])) {
936 $x->updated_by = $this->authUser->id;
939 if (method_exists($x, 'beforeInsert')) {
940 $x->beforeInsert($_REQUEST, $this);
945 if ($res === false) {
946 $this->jerr($x->_lastError->toString());
948 $ev = $this->addEvent("ADD", $x);
949 if (method_exists($x, 'onInsert')) {
950 $x->onInsert($_REQUEST, $this, $ev);
957 // note setFrom might handle this before hand...!??!
958 if (!empty($_FILES) && method_exists($x, 'onUpload')) {
959 $x->onUpload($this, $_REQUEST);
962 return $this->selectSingle(
963 DB_DataObject::factory($x->tableName()),
969 function updateLock($x, $req )
971 Pman::$permitError = true; // allow it to fail without dieing
973 $lock = DB_DataObjecT::factory('Core_locking');
974 Pman::$permitError = false;
975 if (is_a($lock,'DB_DataObject') && $this->authUser) {
977 $lock->on_id = $x->{$this->key};
978 $lock->on_table= strtolower($x->tableName());
979 if (!empty($_REQUEST['_lock_id'])) {
980 $lock->whereAdd('id != ' . ((int)$_REQUEST['_lock_id']));
982 $lock->whereAdd('person_id !=' . $this->authUser->id);
986 $exp = date('Y-m-d', strtotime('NOW - 1 WEEK'));
987 $llc->whereAdd("created < '$exp'");
990 while($llc->fetch()) {
997 if ($lock->find(true)) {
998 // it's locked by someone else..
999 $p = $lock->person();
1002 $this->jerr( "Record was locked by " . $p->name . " at " .$lock->created.
1003 " - Please confirm you wish to save"
1004 , array('needs_confirm' => true));
1008 // check the users lock.. - no point.. ??? - if there are no other locks and it's not the users, then they can
1009 // edit it anyways...
1011 // can we find the user's lock.
1012 $lock = DB_DataObjecT::factory('Core_locking');
1013 $lock->on_id = $x->{$this->key};
1014 $lock->on_table= strtolower($x->tableName());
1015 $lock->person_id = $this->authUser->id;
1016 $lock->orderBy('created DESC');
1020 $lock->find(true) &&
1021 isset($x->modified_dt) &&
1022 strtotime($x->modified_dt) > strtotime($lock->created) &&
1023 empty($req['_submit_confirmed']) &&
1024 $x->modified_by != $this->authUser->id
1027 $p = DB_DataObject::factory('core_person');
1028 $p->get($x->modified_by);
1029 $this->jerr($p->name . " saved the record since you started editing,\nDo you really want to update it?", array('needs_confirm' => true));
1041 function update($x, $req, $with_perm_check = true)
1043 if ( $with_perm_check && !$this->checkPerm($x,'E', $req) ) {
1044 $this->jerr("PERMISSION DENIED - No Edit permissions on this element");
1047 // check any locks..
1048 // only done if we recieve a lock_id.
1049 // we are very trusing here.. that someone has not messed around with locks..
1050 // the object might want to check in their checkPerm - if locking is essential..
1051 $lock = $this->updateLock($x,$req);
1061 // this lot is generic.. needs moving
1062 if (method_exists($x, 'setFromRoo')) {
1063 $res = $x->setFromRoo($req, $this);
1064 if (is_string($res)) {
1073 //echo '<PRE>';print_r($old);print_r($x);exit;
1076 $cols = $x->tableColumns();
1078 if (isset($cols['modified'])) {
1079 $x->modified = date('Y-m-d H:i:s');
1081 if (isset($cols['modified_dt'])) {
1082 $x->modified_dt = date('Y-m-d H:i:s');
1084 if (isset($cols['modified_by']) && $this->authUser) {
1085 $x->modified_by = $this->authUser->id;
1088 if (isset($cols['updated'])) {
1089 $x->updated = date('Y-m-d H:i:s');
1091 if (isset($cols['updated_dt'])) {
1092 $x->updated_dt = date('Y-m-d H:i:s');
1094 if (isset($cols['updated_by']) && $this->authUser) {
1095 $x->updated_by = $this->authUser->id;
1098 if (method_exists($x, 'beforeUpdate')) {
1099 $x->beforeUpdate($old, $req, $this);
1102 if ($with_perm_check && !empty($_FILES) && method_exists($x, 'onUpload')) {
1103 $x->onUpload($this, $_REQUEST);
1106 //DB_DataObject::DebugLevel(1);
1107 $res = $x->update($old);
1108 if ($res === false) {
1109 $this->jerr($x->_lastError->toString());
1111 $ev = $this->addEvent("EDIT", $x);
1113 if (method_exists($x, 'onUpdate')) {
1114 $x->onUpdate($old, $req, $this, $ev);
1117 $ev->audit($x, $old);
1121 return $this->selectSingle(
1122 DB_DataObject::factory($x->tableName()),
1128 * Delete a number of records.
1129 * calls $delete_obj->beforeDelete($array_of_dependant_dataobjects, $this)
1133 function delete($x, $req)
1135 // do we really delete stuff!?!?!?
1136 if (empty($req['_delete'])) {
1137 $this->jerr("Delete Requested with no value");
1141 // build a list of tables to queriy for dependant data..
1146 $all_links = $x->databaseLinks();
1148 foreach($all_links as $tbl => $links) {
1149 foreach($links as $col => $totbl_col) {
1150 $to = explode(':', $totbl_col);
1151 if ($to[0] != $x->tableName()) {
1155 $affects[$tbl .'.' . $col] = true;
1160 // echo '<PRE>';print_r($affects);exit;
1161 // DB_Dataobject::debugLevel(1);
1166 $bits = array_map(function($v) { return (int)$v; } , explode(',', $req['_delete']));
1168 // let's assume it has a key!!!
1170 $x->whereAdd($this->key .' IN ('. implode(',', $bits) .')');
1172 $this->jerr("Nothing found to delete");
1175 while ($x->fetch()) {
1181 if (!$this->checkPerm($x,'D') ) {
1182 $this->jerr("PERMISSION DENIED (d)");
1185 $match_ar = array();
1186 foreach($affects as $k=> $true) {
1187 $ka = explode('.', $k);
1189 $chk = DB_DataObject::factory($ka[0]);
1190 if (!is_a($chk,'DB_DataObject') && !is_a($chk,'PDO_DataObject')) {
1191 $this->jerr('Unable to load referenced table, check the links config: ' .$ka[0]);
1193 // print_r(array($chk->tablename() , $ka[1] , $xx->tablename() , $this->key ));
1194 $chk->{$ka[1]} = $xx->{$this->key};
1196 if (count($chk->keys())) {
1197 $matches = $chk->count();
1199 //DB_DataObject::DebugLevel(1);
1200 $matches = $chk->count($ka[1]);
1204 $chk->_match_key = $ka[1];
1205 $match_ar[] = clone($chk);
1211 $has_beforeDelete = method_exists($xx, 'beforeDelete');
1212 // before delte = allows us to trash dependancies if needed..
1215 if ( $has_beforeDelete ) {
1216 if ($xx->beforeDelete($match_ar, $this) === false) {
1217 $errs[] = "Delete failed ({$xx->id})\n".
1218 (isset($xx->err) ? $xx->err : '');
1221 // refetch affects..
1223 $match_ar = array();
1224 foreach($affects as $k=> $true) {
1225 $ka = explode('.', $k);
1226 $chk = DB_DataObject::factory($ka[0]);
1227 if (!is_a($chk,'DB_DataObject') && !is_a($chk,'PDO_DataObject')) {
1228 $this->jerr('Unable to load referenced table, check the links config: ' .$ka[0]);
1230 $chk->{$ka[1]} = $xx->{$this->key};
1231 $matches = $chk->count();
1232 $match_total += $matches;
1234 $chk->_match_key = $ka[1];
1235 $match_ar[] = clone($chk);
1242 if (!empty($match_ar)) {
1243 $chk = $match_ar[0];
1245 $o = $chk->fetchAll();
1246 $key = isset($chk->_match_key) ?$chk->_match_key : '?unknown column?';
1247 $desc = $chk->tableName(). '.' . $key .'='.$xx->{$this->key} ;
1248 if (method_exists($chk, 'toEventString')) {
1249 $desc .= ' : ' . $o[0]->toEventString();
1251 $this->jerr("Delete Dependant records ($match_total found), " .
1252 "first is ( $desc )");
1258 DB_DataObject::Factory('Events')->logDeletedRecord($x);
1260 $this->addEvent("DELETE", $x);
1264 if (method_exists($xx,'onDelete')) {
1265 $xx->onDelete($req, $this);
1271 $this->jerr(implode("\n<BR>", $errs));
1273 $this->jok("Deleted");
1279 * cols stores the list of columns that are available from the query.
1282 * This is a dupe of what is in autojoin -- we should move to using autojoin really.
1294 var $cols = array();
1298 function loadMap($do, $cfg =array()) //$onlycolumns=false, $distinct = false)
1301 //DB_DataObject::debugLevel(5);
1302 $onlycolumns = !empty($cfg['columns']) ? $cfg['columns'] : false;
1303 $distinct = !empty($cfg['distinct']) ? $cfg['distinct'] : false;
1304 $excludecolumns = !empty($cfg['exclude']) ? $cfg['exclude'] : array();
1306 $excludecolumns[] = 'passwd'; // we never expose passwords
1307 $excludecolumns[] = 'oath_key';
1309 $ret = $do->autoJoin(array(
1310 'include' => $onlycolumns,
1311 'exclude' => $excludecolumns,
1312 'distinct' => $distinct
1315 $this->countWhat = $ret['count'];
1316 $this->cols = $ret['cols'];
1317 $this->colsJname = $ret['join_names'];
1326 * generate the meta data neede by queries.
1329 function meta($x, $data)
1331 // this is not going to work on queries where the data does not match the database def..
1332 // for unknown columns we send them as stirngs..
1334 $cols = array_keys($data[0]);
1338 if (class_exists('PDO_DataObject')) {
1339 $options = PDO_DataObject::config();
1340 if (!file_exists($options["schema_location"] . '.reader')) {
1344 $rdata = unserialize(file_get_contents($options["schema_location"] . '.reader'));
1347 //echo '<PRE>';print_r($this->cols); exit;
1348 $options = &PEAR::getStaticProperty('DB_DataObject','options');
1349 $reader = $options["ini_{$x->databaseNickname()}"] .'.reader';
1350 if (!file_exists( $reader )) {
1354 $rdata = unserialize(file_get_contents($reader));
1357 //echo '<PRE>';print_r($this->cols);exit;
1358 //echo '<PRE>';print_r($rdata);exit;
1359 // echo '<PRE>';print_r($rdata);exit;
1362 $key = empty($keys) ? 'id' : $keys[0];
1366 foreach($cols as $c ) {
1367 if (!isset($this->cols[$c]) || !isset($rdata[$this->cols[$c]]) || !is_array($rdata[$this->cols[$c]])) {
1371 $add = $rdata[$this->cols[$c]];
1376 'totalProperty' => 'total',
1377 'successProperty' => 'success',
1379 'id' => $key, // was 'id'...
1386 function setFilters($x, $q)
1388 // if a column is type int, and we get ',' -> the it should be come an inc clause..
1389 // DB_DataObject::debugLevel(1);
1390 if (method_exists($x, 'applyFilters')) {
1391 // DB_DataObject::debugLevel(1);
1392 if (false === $x->applyFilters($q, $this->authUser, $this)) {
1396 $q_filtered = array();
1400 foreach($q as $key=>$val) {
1402 if (in_array($key,$keys) && !is_array($val)) {
1407 // handles name[]=fred&name[]=brian => name in ('fred', 'brian').
1408 // value is an array..
1409 if (is_array($val) ) {
1413 if ($key[0] == '!') {
1415 $key = substr($key,1);
1418 if (!in_array( $key, array_keys($this->cols))) {
1422 // support a[0] a[1] ..... => whereAddIn(
1425 foreach($val as $k=>$v) {
1426 if (!is_numeric($k)) {
1430 // FIXME: note this is not typesafe for anything other than mysql..
1432 if (!is_numeric($v) || !is_long($v)) {
1441 $x->whereAddIn($pref . (
1442 isset($this->colsJname[$key]) ?
1443 $this->colsJname[$key] :
1444 ($x->tableName(). '.'.$key)),
1445 $ar, $quote ? 'string' : 'int');
1452 // handles !name=fred => name not equal fred.
1453 if ($key[0] == '!' && in_array(substr($key, 1), array_keys($this->cols))) {
1455 $key = substr($key, 1) ;
1458 isset($this->colsJname[$key]) ?
1459 $this->colsJname[$key] :
1460 $x->tableName(). '.'.$key ) . ' != ' .
1461 (is_numeric($val) ? $val : "'". $x->escape($val) . "'")
1471 // Events and remarks -- fixme - move to events/remarsk...
1472 case 'on_id': // where TF is this used...
1473 if (!empty($q['query']['original'])) {
1474 // DB_DataObject::debugLevel(1);
1475 $o = (int) $q['query']['original'];
1477 $x->whereAdd("(on_id = $oid OR
1478 on_id IN ( SELECT distinct(id) FROM Documents WHERE original = $o )
1487 if (strlen($val) && $key[0] != '_') {
1488 $q_filtered[$key] = $val;
1491 // subjoined columns = check the values.
1492 // note this is not typesafe for anything other than mysql..
1494 if (isset($this->colsJname[$key])) {
1496 // the aobve rule for !strlen non-joined cols should apply to joined ones.
1497 if (!strlen($val)) {
1503 if (!is_numeric($val) || !is_long($val)) {
1506 $x->whereAdd( "{$this->colsJname[$key]} = " . ($quote ? "'". $x->escape($val) ."'" : $val));
1514 if (!empty($q_filtered)) {
1515 //var_dump($q_filtered);
1519 $x->setFrom($q_filtered);
1525 // nice generic -- let's get rid of it.. where is it used!!!!
1527 // Person / Group / Comapnies.... most of my queries noww...
1529 if (!empty($q['query']['name'])) {
1532 if (in_array( 'name', array_keys($x->table()))) {
1533 $x->whereAdd($x->tableName().".name LIKE '". $x->escape($q['query']['name']) . "%'");
1538 // - projectdirectory staff list - persn queuy
1543 * create the dataobject from (usually the url)
1544 * This uses $this->validTables
1545 * $this->validPrefix (later..)
1546 * to determine if class can be created..
1550 function dataObject($tab)
1552 if (is_array($this->validTables) && !in_array($tab,$this->validTables)) {
1553 $this->jerr("Invalid url - not listed in validTables");
1555 $tab = str_replace('/', '',$tab); // basic protection??
1557 $pm = HTML_FlexyFramework::get()->Pman;
1559 if (isset($pm['roo_alias'])) {
1560 $map = array_flip($pm['roo_alias']);
1561 if (isset($map[$tab])) {
1567 $x = DB_DataObject::factory($tab);
1569 if (!is_a($x, 'DB_DataObject') && !is_a($x, 'PDO_DataObject')) {
1570 $this->jerr('invalid url - no dataobject');