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, $roo, $array_data) : 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, $request) 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
40 * - toEventString (for logging - this is generically prefixed to all database operations.)
43 class Pman_Roo extends Pman
46 * if set to an array (when extending this, then you can restrict which tables are available
48 var $validTables = false;
50 var $key; // used by update currenly to store primary key.
53 var $max_limit = 10000;
55 var $debugEnabled = true; // disable this for public versions of this code.
57 var $do = false; // the dataobject being worked on..
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.
89 * _no_count skip the default count query.
90 * use the number of records in the query result as the total
94 * - all tables are always autojoined.
98 * _columns=a,b,c,d comma seperated list of columns.
99 * _exclude_columns=a,b,c,d comma seperated list of columns.
100 * _distinct=name a distinct column lookup. you also have to use _columns with this.
103 * colname = ... => colname = ....
104 * !colname=.... => colname != ....
105 * !colname[0]=... !colname[1]=... => colname NOT IN (.....) ** only supports main table at present..
106 * colname[0]=... colname[1]=... => colname IN (.....) ** only supports main table at present..
109 * sort=name what to sort.
110 * sort=a,b,d can support multiple columns
111 * dir=ASC what direction
112 * _multisort ={...} JSON encoded { sort : { row : direction }, order : [ row, row, row ] }
115 * start=0 limit start
116 * limit=25 limit number
120 * csvCols[0] csvCols[1].... = .... column titles for CSV output
121 * csvTitles[0], csvTitles[1] .... = columns to use for CSV output
124 * _toggleActive !:!:!:! - this hsould not really be here..
125 * query[add_blank] - add a line in with an empty option... - not really needed???
126 * _delete = delete a list of ids element. (depricated.. this will be removed...)
129 * _post =1 = simulate a post with debuggin on.
130 * _debug_post << This is prefered, as _post may overlap with accouting posts..
132 * _debug = turn on DB_dataobject deubbing, must be admin at present..
135 * CALLS methods on dataobjects if they exist
138 * checkPerm('S' , $authuser)
139 * - can we list the stuff
140 * - return false to disallow...
141 * applySort($au, $sortcol, $direction, $array_of_columns, $multisort)
142 * -- does not support multisort at present..
143 * applyFilters($_REQUEST, $authUser, $roo)
144 * -- apply any query filters on data. and hide stuff not to be seen.
145 * -- can exit by calling $roo->jerr()
146 * postListExtra($_REQUEST, $roo, $array_data) : array(extra_name => data)
147 * - add extra column to the jdata return key/value info.
148 * postListFilter($data, $authUser, $request) return $data
149 * - modify the returned array of data (either add stuff to the data, or remove lines etc)
152 * toRooSingleArray($authUser, $request) : array
153 * - called on single fetch only, add or maniuplate returned array data.
154 * - is also called when _id=0 is used (for fetching a default set.)
155 * toRooArray($request) : array
156 * - called if singleArray is unavailable on single fetch.
157 * - always tried for mutiple results.
158 * toArray() - the default method if none of the others are found.
159 * toSimpleExcelColumn($col) - see toCSV - this enables special columns to be created for exported data.
162 * - standard DataObject feature - causes all results to show all
166 * _extra_cols -- if set, then filtering by column etc. will use them.
170 function get($tab, $opts = Array())
172 // $this->jerr("Not authenticated", array('authFailure' => true));
173 //echo '<PRE>';print_R($_GET);
174 //DB_DataObject::debuglevel(1);
176 $this->init(); // from pman.
177 //DB_DataObject::debuglevel(1);
178 HTML_FlexyFramework::get()->generateDataobjectsCache($this->isDev && !empty($_REQUEST['isDev']));
186 if ( $this->checkDebugPost()) {
191 //DB_DAtaObject::debuglevel(1);
192 return $this->post($tab);
196 $this->initErrorHandling();
198 $tt = explode('/', $tab);
199 $tab = array_shift($tt);
200 $x = $this->dataObject($tab);
202 $_columns = !empty($_REQUEST['_columns']) && is_string(['_columns']) ? explode(',', $_REQUEST['_columns']) : false;
204 if (isset( $_REQUEST['lookup'] ) && is_array($_REQUEST['lookup'] )) { // single fetch based on key/value pairs
205 $this->selectSingle($x, $_REQUEST['lookup'],$_REQUEST);
210 // single fetch (use '0' to fetch an empty object..)
211 if (isset($_REQUEST['_id']) && is_numeric($_REQUEST['_id'])) {
213 $this->selectSingle($x, $_REQUEST['_id'],$_REQUEST);
220 if (isset($_REQUEST['_delete'])) {
221 $this->jerr("DELETE by GET has been removed - update the code to use POST");
228 if (isset($_REQUEST['_toggleActive'])) {
229 // do we really delete stuff!?!?!?
230 if (!$this->hasPerm("Core.Staff", 'E')) {
231 $this->jerr("PERMISSION DENIED (ta)");
233 $clean = create_function('$v', 'return (int)$v;');
234 $bits = array_map($clean, explode(',', $_REQUEST['_toggleActive']));
235 if (in_array($this->authUser->id, $bits) && $this->authUser->active) {
236 $this->jerr("you can not disable yourself");
238 $x->query('UPDATE core_person SET active = !active WHERE id IN (' .implode(',', $bits).')');
239 $this->addEvent("USERTOGGLE", false, implode(',', $bits));
240 $this->jok("Updated");
243 //DB_DataObject::debugLevel(1);
245 // sets map and countWhat
246 $this->loadMap($x, array(
247 'columns' => $_columns,
248 'distinct' => empty($_REQUEST['_distinct']) ? false: $_REQUEST['_distinct'],
249 'exclude' => empty($_REQUEST['_exclude_columns']) ? false: explode(',', $_REQUEST['_exclude_columns'])
253 $this->setFilters($x,$_REQUEST);
255 if (!$this->checkPerm($x,'S', $_REQUEST)) {
256 $this->jerr("PERMISSION DENIED (g)");
260 // build join if req.
261 //DB_DataObject::debugLevel(1);
262 // count with multiple joins and no conditions can be quite slow - so if there are no conditions - just remove the joins from the count.
264 $old_where = $x->whereAdd();
265 if (empty($old_where )) {
268 $x->whereAdd($old_where);
273 if (!isset($_REQUEST['_no_count'])) {
274 $total = $xx->count($this->countWhat);
276 if (isset($xx->_real_total)) { // this is used when we subquery the search.
277 $total = $xx->_real_total;
281 // var_dump($total);exit;
282 $this->applySort($x);
286 if (!empty($_REQUEST['_distinct']) && $total !== false && $total < 400) {
293 empty($_REQUEST['start']) ? 0 : (int)$_REQUEST['start'],
294 min(empty($_REQUEST['limit']) ? 25 : (int)$_REQUEST['limit'], $this->max_limit)
297 $queryObj = clone($x);
298 //DB_DataObject::debuglevel(1);
300 $this->sessionState(0);
302 $this->sessionState(1);
304 if (false === $res) {
305 $this->jerr($x->_lastError->toString());
313 // ---------------- THESE ARE DEPRICATED.. they should be moved to the model...
316 if (!empty($_REQUEST['query']['add_blank'])) {
317 $ret[] = array( 'id' => 0, 'name' => '----');
318 $total === false ? false : $total+1;
321 $rooar = method_exists($x, 'toRooArray');
322 $_columnsf = $_columns ? array_flip($_columns) : false;
323 while ($x->fetch()) {
325 $add = $rooar ? $x->toRooArray($_REQUEST) : $x->toArray();
326 if ($add === false) {
329 $ret[] = !$_columns ? $add : array_intersect_key($add, $_columnsf);
333 $ret = array_slice($ret,
334 empty($_REQUEST['start']) ? 0 : (int)$_REQUEST['start'],
335 min(empty($_REQUEST['limit']) ? 25 : (int)$_REQUEST['limit'], 10000)
342 if (method_exists($queryObj ,'postListExtra')) {
343 $extra = $queryObj->postListExtra($_REQUEST, $this, $ret);
347 // filter results, and add any data that is needed...
348 if (method_exists($x,'postListFilter')) {
349 $ret = $x->postListFilter($ret, $this->authUser, $_REQUEST, $this);
354 if (!empty($_REQUEST['csvCols']) && !empty($_REQUEST['csvTitles']) ) {
357 $this->toCsv($ret, $_REQUEST['csvCols'], $_REQUEST['csvTitles'],
358 empty($_REQUEST['csvFilename']) ? '' : $_REQUEST['csvFilename'] );
365 if (!empty($_REQUEST['_requestMeta']) && count($ret)) {
366 $meta = $this->meta($x, $ret);
368 $extra = $extra ? $extra: array();
369 $extra['metaData'] = $meta;
372 // this make take some time...
373 $this->sessionState(0);
374 // echo "<PRE>"; print_r($ret);
375 $this->jdata($ret, max(count($ret), $total === false ? 0 : $total), $extra );
379 function checkDebug($req = false)
381 $req = $req === false ? $_REQUEST : $req;
383 if (empty($req['_debug'])) {
387 if (!empty($_SERVER['HTTP_HOST']) && $_SERVER['HTTP_HOST'] == 'localhost') {
388 DB_DAtaObject::debuglevel((int)$req['_debug']);
396 method_exists($this->authUser,'canDebug')
398 $this->authUser->canDebug()
403 method_exists($this->authUser,'groups')
405 is_a($this->authUser, 'Pman_Core_DataObjects_Core_person')
407 in_array('Administrators', $this->authUser->groups('name'))
412 DB_DAtaObject::debuglevel((int)$req['_debug']);
417 function checkDebugPost()
419 if (empty($_GET['_post']) && empty($_GET['_debug_post'])) {
422 // localhost can do anything...
423 if (!empty($_SERVER['HTTP_HOST']) && $_SERVER['HTTP_HOST'] == 'localhost') {
426 return $this->authUser &&
427 method_exists($this->authUser,'groups') &&
428 in_array('Administrators', $this->authUser->groups('name'));
432 function checkPerm($obj, $lvl, $req= null)
434 if (!method_exists($obj, 'checkPerm')) {
437 if ($obj->checkPerm($lvl, $this->authUser, $req)) {
443 function toCsv($data, $cols, $titles, $filename, $addDate = true)
446 $this->sessionState(0); // turn off sessions - no locking..
448 require_once 'Pman/Core/SimpleExcel.php';
450 $fn = (empty($filename) ? 'list-export-' : urlencode($filename)) . (($addDate) ? date('Y-m-d') : '') ;
454 'workbook' => substr($fn, 0, 31),
461 if (is_object($data)) {
462 $rooar = method_exists($data, 'toRooArray');
463 while($data->fetch()) {
464 $x = $rooar ? $data->toRooArray($q) : $data->toArray();
466 if ($cols == '*') { /// did we get cols sent to us?
467 $cols = array_keys($x);
470 if(!is_array($cols)) {
471 $cols = explode(',', $cols);
474 if ($titles !== false) {
476 $titles= array_keys($x);
478 if(!is_array($titles)) {
479 $titles = explode(',', $titles);
481 foreach($cols as $i=>$col) {
483 'header'=> isset($titles[$i]) ? $titles[$i] : $col,
486 // 'renderer' => array($this, 'getThumb'),
487 // 'color' => 'yellow', // set color for the cell which is a header element
488 // 'fillBlank' => 'gray', // set
491 if (method_exists($data, 'toSimpleExcelColumn')) {
492 $add = $data->toSimpleExcelColumn($add);
495 $se_config['cols'][] = $add;
500 $se = new Pman_Core_SimpleExcel(array(), $se_config);
506 $se->addLine($se_config['workbook'], $x);
512 $this->jerr('no data found', false, 'text/plain');
514 $se->send($fn .'.xls');
519 foreach($data as $x) {
520 //echo "<PRE>"; print_r(array($_REQUEST['csvCols'], $x->toArray())); exit;
524 $cols= array_keys($x);
527 if(!is_array($cols)) {
528 $cols = explode(',', $cols);
531 if ($titles !== false) {
533 $titles= array_keys($x);
536 if(!is_array($titles)) {
537 $titles = explode(',', $titles);
540 foreach($cols as $i=>$col) {
542 'header'=> isset($titles[$i]) ? $titles[$i] : $col,
545 // 'renderer' => array($this, 'getThumb'),
546 // 'color' => 'yellow', // set color for the cell which is a header element
547 // 'fillBlank' => 'gray', // set
550 if (!empty($this->do) && method_exists($this->do, 'toSimpleExcelColumn')) {
551 $add = $this->do->toSimpleExcelColumn($add);
554 $se_config['cols'][] = $add;
559 $se = new Pman_Core_SimpleExcel(array(),$se_config);
562 //fputcsv($fh, $titles);
566 $se->addLine($se_config['workbook'], $x);
570 $this->jerr('no data found');
573 $se->send($fn .'.xls');
580 * POST method Roo/TABLENAME
581 * -- creates, updates, or deletes data.
584 * if the primary key is empty, this happens
585 * will automatically set these to current date and authUser->id
586 * created, created_by, created_dt
587 * updated, update_by, updated_dt
588 * modified, modified_by, modified_dt
590 * will return a GET request SINGLE SELECT (and accepts same)
593 * _delete=1,2,3 delete a set of data.
595 * if the primary key value is set, then update occurs.
596 * will automatically set these to current date and authUser->id
597 * updated, update_by, updated_dt
598 * modified, modified_by, modified_dt
602 * _delete=1,2,3 causes a delete to occur.
603 * _ids=1,2,3,4 causes update to occur on all primary ids.
606 * = same as single SELECT GET request..
611 * _debug=1 forces debug
612 * _get=1 - causes a get request to occur when doing a POST..
616 * these methods on dataobjects if they exist
618 * checkPerm('E' / 'D' , $authuser)
619 * - can we list the stuff
620 * - return false to disallow...
622 * toRooSingleArray($authUser, $request) : array
623 * - called on single fetch only, add or maniuplate returned array data.
624 * toRooArray($request) : array
625 * - Called if toSingleArray does not exist.
626 * - if you need to return different data than toArray..
629 * (for logging - this is generically prefixed to all database operations.)
633 * called when $_FILES is not empty
636 * setFromRoo($ar, $roo)
637 * - alternative to setFrom() which is called if this method does not exist
638 * - values from post (deal with dates etc.) - return true|error string.
639 * - call $roo->jerr() on failure...
641 * CALLS BEFORE change occurs:
643 * beforeDelete($dependants_array, $roo)
644 * Argument is an array of un-find/fetched dependant items.
645 * - jerr() will stop insert.. (Prefered)
646 * - return false for fail and set DO->err;
648 * beforeUpdate($old, $request,$roo)
649 * - before update - jerr() will stop insert..
650 * beforeInsert($request,$roo)
651 * - before insert - jerr() will stop insert..
654 * CALLS AFTER change occured
656 * onUpdate($old, $request,$roo)
657 * - after update // return value ignored
659 * onInsert($request,$roo)
662 * onDelete($request, $roo) - after delete
666 function post($tab) // update / insert (?? delete??)
668 // -- why was this put in? - Roo is not related to Core.All ?
669 //if (!$this->hasPerm("Core.All", 'E')) {
670 // $this->jerr("PERMISSION DENIED (e)");
672 $this->initErrorHandling();
674 // DB_DataObject::debugLevel(1);
677 if (!empty($_REQUEST['_get'])) {
678 return $this->get($tab);
681 $this->init(); // for pman.
683 $x = $this->dataObject($tab);
685 $this->transObj = clone($x);
687 $this->transObj->query('BEGIN');
688 // find the key and use that to get the thing..
691 $this->jerr('no key');
694 $this->key = $keys[0];
696 // delete should be here...
697 if (isset($_REQUEST['_delete'])) {
698 // do we really delete stuff!?!?!?
699 return $this->delete($x,$_REQUEST);
707 // not sure if this is a good idea here...
709 if (!empty($_REQUEST['_ids'])) {
710 $ids = explode(',',$_REQUEST['_ids']);
711 $x->whereAddIn($this->key, $ids, 'int');
712 $ar = $x->fetchAll();
715 $this->update($x, $_REQUEST);
718 $this->jok("UPDATED");
723 if (!empty($_REQUEST[$this->key])) {
725 if (!$x->get($this->key, $_REQUEST[$this->key])) {
726 $this->jerr("Invalid request (id does not point to a record.)");
728 $this->jok($this->update($x, $_REQUEST));
732 $this->jerr("No data recieved for inserting");
735 $this->jok($this->insert($x, $_REQUEST));
747 * apply REQUEST[sort] and [dir]
748 * sort may be an array of columsn..
750 * @arg DB_DataObject $x
753 function applySort($x, $sort = '', $dir ='')
756 // Db_DataObject::debugLevel(1);
757 $sort = empty($_REQUEST['sort']) || !is_string($_REQUEST['sort']) ? $sort : $_REQUEST['sort'];
758 $dir = empty($_REQUEST['dir']) || !is_string($_REQUEST['dir']) ? $dir : $_REQUEST['dir'];
759 $dir = $dir == 'ASC' ? 'ASC' : 'DESC';
761 $ms = empty($_REQUEST['_multisort']) || !is_string($_REQUEST['_multisort']) ? false : $_REQUEST['_multisort'];
762 //var_Dump($ms);exit;
764 if (method_exists($x, 'applySort')) {
765 $sorted = $x->applySort(
769 array_keys($this->cols),
770 $ms ? json_decode($ms) : false
775 return $this->multiSort($x);
778 if ($sorted === false) {
779 $cols = $x->tableColumns();
780 $excols = array_keys($this->cols);
782 if (isset($x->_extra_cols)) {
783 $excols = array_merge($excols, $x->_extra_cols);
785 $sort_ar = explode(',', $sort);
788 foreach($sort_ar as $sort) {
790 if (strlen($sort) && isset($cols[$sort]) ) {
791 $sort_str[] = $x->tableName() .'.'.$sort . ' ' . $dir ;
793 } else if (in_array($sort, $excols)) {
794 $sort_str[] = $sort . ' ' . $dir ;
799 $x->orderBy(implode(', ', $sort_str ));
810 function multiSort($x)
812 //DB_DataObject::debugLevel(1);
813 $ms = json_decode($_REQUEST['_multisort']);
814 if (!isset($ms->order) || !is_array($ms->order)) {
819 $cols = $x->tableColumns();
821 //print_r($this->cols);exit;
822 // this-><cols contains colname => aliased name...
823 foreach($ms->order as $col) {
824 if (!isset($ms->sort->{$col})) {
825 continue; // no direction..
827 $ms->sort->{$col} = $ms->sort->{$col} == 'ASC' ? 'ASC' : 'DESC';
829 if (strlen($col) && isset($cols[$col]) ) {
830 $sort_str[] = $x->tableName() .'.'.$col . ' ' . $ms->sort->{$col};
833 //print_r($this->cols);
835 if (in_array($col, array_keys($this->cols))) {
836 $sort_str[] = $col. ' ' . $ms->sort->{$col};
839 if (isset($x->_extra_cols) && in_array($col, $x->_extra_cols)) {
840 $sort_str[] = $col. ' ' . $ms->sort->{$col};
845 $x->orderBy(implode(', ', $sort_str ));
852 * - used when _id is set, or after insert or update
854 * @param DataObject $x the dataobject to use
855 * @param int $id the pid of the object
856 * @param array $req the request, or false if it comes from insert/update.
859 function selectSingle($x, $id, $req=false)
863 $_columns = !empty($req['_columns']) ? explode(',', $req['_columns']) : false;
865 //var_dump(array(!is_array($id) , empty($id)));
866 if (!is_array($id) && empty($id)) {
869 if (method_exists($x, 'toRooSingleArray')) {
870 $this->jok($x->toRooSingleArray($this->authUser, $req));
872 if (method_exists($x, 'toRooArray')) {
873 $this->jok($x->toRooArray($req));
876 $this->jok($x->toArray());
880 $this->loadMap($x, array(
881 'columns' => $_columns,
884 if ($req !== false) {
885 $this->setFilters($x, $req);
886 } else if (method_exists($x, 'applyFilters')) {
887 // always call apply filters even after update/insert...
888 // however arguments are not passed.
889 $x->applyFilters(array('_is_update_request' => true), $this->authUser, $this);
892 // DB_DataObject::DebugLevel(1);
895 $x->setFrom($req['lookup'] );
897 if (!$x->find(true)) {
898 if (!empty($id['_id'])) {
900 $this->jok($x->toArray());
905 } else if (!$x->get($id)) {
906 $this->jerr("selectSingle: no such record ($id)");
909 // ignore perms if comming from update/insert - as it's already done...
910 if ($req !== false && !$this->checkPerm($x,'S')) {
911 $this->jerr("PERMISSION DENIED - si");
913 // different symantics on all these calls??
914 if (method_exists($x, 'toRooSingleArray')) {
915 $this->jok($x->toRooSingleArray($this->authUser, $req));
917 if (method_exists($x, 'toRooArray')) {
918 $this->jok($x->toRooArray($req));
920 $this->jok($x->toArray());
925 function insert($x, $req, $with_perm_check = true)
927 if (method_exists($x, 'setFromRoo')) {
928 $res = $x->setFromRoo($req, $this);
929 if (is_string($res)) {
936 if ( $with_perm_check && !$this->checkPerm($x,'A', $req)) {
937 $this->jerr("PERMISSION DENIED {$x->tableName()}:checkPerm(A)");
939 $cols = $x->tableColumns();
941 if (isset($cols['created'])) {
942 $x->created = date('Y-m-d H:i:s');
944 if (isset($cols['created_dt'])) {
945 $x->created_dt = date('Y-m-d H:i:s');
947 if (isset($cols['created_by'])) {
948 $x->created_by = $this->authUser->id;
951 if (isset($cols['modified'])) {
952 $x->modified = date('Y-m-d H:i:s');
954 if (isset($cols['modified_dt'])) {
955 $x->modified_dt = date('Y-m-d H:i:s');
957 if (isset($cols['modified_by'])) {
958 $x->modified_by = $this->authUser->id;
961 if (isset($cols['updated'])) {
962 $x->updated = date('Y-m-d H:i:s');
964 if (isset($cols['updated_dt'])) {
965 $x->updated_dt = date('Y-m-d H:i:s');
967 if (isset($cols['updated_by'])) {
968 $x->updated_by = $this->authUser->id;
971 if (method_exists($x, 'beforeInsert')) {
972 $x->beforeInsert($_REQUEST, $this);
977 if ($res === false) {
978 $this->jerr($x->_lastError->toString());
980 $ev = $this->addEvent("ADD", $x);
981 if (method_exists($x, 'onInsert')) {
983 $x->onInsert($_REQUEST, $this, $ev);
990 // note setFrom might handle this before hand...!??!
991 if (!empty($_FILES) && method_exists($x, 'onUpload')) {
992 $x->onUpload($this, $_REQUEST);
995 return $this->selectSingle(
996 DB_DataObject::factory($x->tableName()),
1002 function updateLock($x, $req )
1004 Pman::$permitError = true; // allow it to fail without dieing
1006 $lock = DB_DataObjecT::factory('Core_locking');
1007 Pman::$permitError = false;
1008 if (is_a($lock,'DB_DataObject') && $this->authUser) {
1010 $lock->on_id = $x->{$this->key};
1011 $lock->on_table= strtolower($x->tableName());
1012 if (!empty($_REQUEST['_lock_id'])) {
1013 $lock->whereAdd('id != ' . ((int)$_REQUEST['_lock_id']));
1015 $lock->whereAdd('person_id !=' . $this->authUser->id);
1018 $llc = clone($lock);
1019 $exp = date('Y-m-d', strtotime('NOW - 1 WEEK'));
1020 $llc->whereAdd("created < '$exp'");
1021 if ($llc->count()) {
1023 while($llc->fetch()) {
1024 $llcd = clone($llc);
1030 if ($lock->find(true)) {
1031 // it's locked by someone else..
1032 $p = $lock->person();
1035 $this->jerr( "Record was locked by " . $p->name . " at " .$lock->created.
1036 " - Please confirm you wish to save"
1037 , array('needs_confirm' => true));
1041 // check the users lock.. - no point.. ??? - if there are no other locks and it's not the users, then they can
1042 // edit it anyways...
1044 // can we find the user's lock.
1045 $lock = DB_DataObjecT::factory('Core_locking');
1046 $lock->on_id = $x->{$this->key};
1047 $lock->on_table= strtolower($x->tableName());
1048 $lock->person_id = $this->authUser->id;
1049 $lock->orderBy('created DESC');
1053 $lock->find(true) &&
1054 isset($x->modified_dt) &&
1055 strtotime($x->modified_dt) > strtotime($lock->created) &&
1056 empty($req['_submit_confirmed']) &&
1057 $x->modified_by != $this->authUser->id
1060 $p = DB_DataObject::factory('core_person');
1061 $p->get($x->modified_by);
1062 $this->jerr($p->name . " saved the record since you started editing,\nDo you really want to update it?", array('needs_confirm' => true));
1074 function update($x, $req, $with_perm_check = true)
1076 if ( $with_perm_check && !$this->checkPerm($x,'E', $req) ) {
1077 $this->jerr("PERMISSION DENIED - No Edit permissions on this element");
1080 // check any locks..
1081 // only done if we recieve a lock_id.
1082 // we are very trusing here.. that someone has not messed around with locks..
1083 // the object might want to check in their checkPerm - if locking is essential..
1084 $lock = $this->updateLock($x,$req);
1094 // this lot is generic.. needs moving
1095 if (method_exists($x, 'setFromRoo')) {
1096 $res = $x->setFromRoo($req, $this);
1097 if (is_string($res)) {
1106 //echo '<PRE>';print_r($old);print_r($x);exit;
1109 $cols = $x->tableColumns();
1111 if (isset($cols['modified'])) {
1112 $x->modified = date('Y-m-d H:i:s');
1114 if (isset($cols['modified_dt'])) {
1115 $x->modified_dt = date('Y-m-d H:i:s');
1117 if (isset($cols['modified_by']) && $this->authUser) {
1118 $x->modified_by = $this->authUser->id;
1121 if (isset($cols['updated'])) {
1122 $x->updated = date('Y-m-d H:i:s');
1124 if (isset($cols['updated_dt'])) {
1125 $x->updated_dt = date('Y-m-d H:i:s');
1127 if (isset($cols['updated_by']) && $this->authUser) {
1128 $x->updated_by = $this->authUser->id;
1131 if (method_exists($x, 'beforeUpdate')) {
1132 $x->beforeUpdate($old, $req, $this);
1135 if ($with_perm_check && !empty($_FILES) && method_exists($x, 'onUpload')) {
1136 $x->onUpload($this, $_REQUEST);
1139 //DB_DataObject::DebugLevel(1);
1140 $res = $x->update($old);
1141 if ($res === false) {
1142 $this->jerr($x->_lastError->toString());
1144 $ev = $this->addEvent("EDIT", $x);
1146 if (method_exists($x, 'onUpdate')) {
1147 $x->onUpdate($old, $req, $this, $ev);
1150 $ev->audit($x, $old);
1154 return $this->selectSingle(
1155 DB_DataObject::factory($x->tableName()),
1161 * Delete a number of records.
1162 * calls $delete_obj->beforeDelete($array_of_dependant_dataobjects, $this)
1166 function delete($x, $req)
1168 // do we really delete stuff!?!?!?
1169 if (empty($req['_delete'])) {
1170 $this->jerr("Delete Requested with no value");
1174 // build a list of tables to queriy for dependant data..
1179 $all_links = $x->databaseLinks();
1181 foreach($all_links as $tbl => $links) {
1182 foreach($links as $col => $totbl_col) {
1183 $to = explode(':', $totbl_col);
1184 if ($to[0] != $x->tableName()) {
1188 $affects[$tbl .'.' . $col] = true;
1193 // echo '<PRE>';print_r($affects);exit;
1194 // DB_Dataobject::debugLevel(1);
1199 $bits = array_map(function($v) { return (int)$v; } , explode(',', $req['_delete']));
1201 // let's assume it has a key!!!
1203 $x->whereAdd($this->key .' IN ('. implode(',', $bits) .')');
1205 $this->jerr("Nothing found to delete");
1208 while ($x->fetch()) {
1214 if (!$this->checkPerm($x,'D') ) {
1215 $this->jerr("PERMISSION DENIED (d)");
1218 $match_ar = array();
1219 foreach($affects as $k=> $true) {
1220 $ka = explode('.', $k);
1222 $chk = DB_DataObject::factory($ka[0]);
1223 if (!is_a($chk,'DB_DataObject') && !is_a($chk,'PDO_DataObject')) {
1224 $this->jerr('Unable to load referenced table, check the links config: ' .$ka[0]);
1226 // print_r(array($chk->tablename() , $ka[1] , $xx->tablename() , $this->key ));
1227 $chk->{$ka[1]} = $xx->{$this->key};
1229 if (count($chk->keys())) {
1230 $matches = $chk->count();
1232 //DB_DataObject::DebugLevel(1);
1233 $matches = $chk->count($ka[1]);
1237 $chk->_match_key = $ka[1];
1238 $match_ar[] = clone($chk);
1244 $has_beforeDelete = method_exists($xx, 'beforeDelete');
1245 // before delte = allows us to trash dependancies if needed..
1248 if ( $has_beforeDelete ) {
1249 if ($xx->beforeDelete($match_ar, $this, $_REQUEST) === false) {
1250 $errs[] = "Delete failed ({$xx->id})\n".
1251 (isset($xx->err) ? $xx->err : '');
1254 // refetch affects..
1256 $match_ar = array();
1257 foreach($affects as $k=> $true) {
1258 $ka = explode('.', $k);
1259 $chk = DB_DataObject::factory($ka[0]);
1260 if (!is_a($chk,'DB_DataObject') && !is_a($chk,'PDO_DataObject')) {
1261 $this->jerr('Unable to load referenced table, check the links config: ' .$ka[0]);
1263 $chk->{$ka[1]} = $xx->{$this->key};
1264 $matches = $chk->count();
1265 $match_total += $matches;
1267 $chk->_match_key = $ka[1];
1268 $match_ar[] = clone($chk);
1275 if (!empty($match_ar)) {
1276 $chk = $match_ar[0];
1278 $o = $chk->fetchAll();
1279 $key = isset($chk->_match_key) ?$chk->_match_key : '?unknown column?';
1280 $desc = $chk->tableName(). '.' . $key .'='.$xx->{$this->key} ;
1281 if (method_exists($chk, 'toEventString')) {
1282 $desc .= ' : ' . $o[0]->toEventString();
1284 $this->jerr("Delete Dependant records ($match_total found), " .
1285 "first is ( $desc )");
1291 DB_DataObject::Factory('Events')->logDeletedRecord($x);
1293 $this->addEvent("DELETE", $x);
1297 if (method_exists($xx,'onDelete')) {
1298 $xx->onDelete($req, $this);
1304 $this->jerr(implode("\n<BR>", $errs));
1306 $this->jok("Deleted");
1312 * cols stores the list of columns that are available from the query.
1315 * This is a dupe of what is in autojoin -- we should move to using autojoin really.
1327 var $cols = array();
1331 function loadMap($do, $cfg =array()) //$onlycolumns=false, $distinct = false)
1334 //DB_DataObject::debugLevel(5);
1335 $onlycolumns = !empty($cfg['columns']) ? $cfg['columns'] : false;
1336 $distinct = !empty($cfg['distinct']) ? $cfg['distinct'] : false;
1337 $excludecolumns = !empty($cfg['exclude']) ? $cfg['exclude'] : array();
1339 $excludecolumns[] = 'passwd'; // we never expose passwords
1340 $excludecolumns[] = 'oath_key';
1342 $ret = $do->autoJoin(array(
1343 'include' => $onlycolumns,
1344 'exclude' => $excludecolumns,
1345 'distinct' => $distinct
1348 $this->countWhat = $ret['count'];
1349 $this->cols = $ret['cols'];
1350 $this->colsJname = $ret['join_names'];
1359 * generate the meta data neede by queries.
1362 function meta($x, $data)
1364 // this is not going to work on queries where the data does not match the database def..
1365 // for unknown columns we send them as stirngs..
1367 $cols = array_keys($data[0]);
1371 if (class_exists('PDO_DataObject')) {
1372 $options = PDO_DataObject::config();
1373 if (!file_exists($options["schema_location"] . '.reader')) {
1377 $rdata = unserialize(file_get_contents($options["schema_location"] . '.reader'));
1380 //echo '<PRE>';print_r($this->cols); exit;
1381 $options = &PEAR::getStaticProperty('DB_DataObject','options');
1382 $reader = $options["ini_{$x->databaseNickname()}"] .'.reader';
1383 if (!file_exists( $reader )) {
1387 $rdata = unserialize(file_get_contents($reader));
1390 //echo '<PRE>';print_r($this->cols);exit;
1391 //echo '<PRE>';print_r($rdata);exit;
1392 // echo '<PRE>';print_r($rdata);exit;
1395 $key = empty($keys) ? 'id' : $keys[0];
1399 foreach($cols as $c ) {
1400 if (!isset($this->cols[$c]) || !isset($rdata[$this->cols[$c]]) || !is_array($rdata[$this->cols[$c]])) {
1404 $add = $rdata[$this->cols[$c]];
1409 'totalProperty' => 'total',
1410 'successProperty' => 'success',
1412 'id' => $key, // was 'id'...
1419 function setFilters($x, $q)
1421 // if a column is type int, and we get ',' -> the it should be come an inc clause..
1422 // DB_DataObject::debugLevel(1);
1423 if (method_exists($x, 'applyFilters')) {
1424 // DB_DataObject::debugLevel(1);
1425 if (false === $x->applyFilters($q, $this->authUser, $this)) {
1429 $q_filtered = array();
1433 foreach($q as $key=>$val) {
1435 if (in_array($key,$keys) && !is_array($val)) {
1440 // handles name[]=fred&name[]=brian => name in ('fred', 'brian').
1441 // value is an array..
1442 if (is_array($val) ) {
1446 if ($key[0] == '!') {
1448 $key = substr($key,1);
1451 if (!in_array( $key, array_keys($this->cols))) {
1455 // support a[0] a[1] ..... => whereAddIn(
1458 foreach($val as $k=>$v) {
1459 if (!is_numeric($k)) {
1463 // FIXME: note this is not typesafe for anything other than mysql..
1465 if (!is_numeric($v) || !is_long($v)) {
1474 $x->whereAddIn($pref . (
1475 isset($this->colsJname[$key]) ?
1476 $this->colsJname[$key] :
1477 ($x->tableName(). '.'.$key)),
1478 $ar, $quote ? 'string' : 'int');
1485 // handles !name=fred => name not equal fred.
1486 if ($key[0] == '!' && in_array(substr($key, 1), array_keys($this->cols))) {
1488 $key = substr($key, 1) ;
1491 isset($this->colsJname[$key]) ?
1492 $this->colsJname[$key] :
1493 $x->tableName(). '.'.$key ) . ' != ' .
1494 (is_numeric($val) ? $val : "'". $x->escape($val) . "'")
1504 // Events and remarks -- fixme - move to events/remarsk...
1505 case 'on_id': // where TF is this used...
1506 if (!empty($q['query']['original'])) {
1507 // DB_DataObject::debugLevel(1);
1508 $o = (int) $q['query']['original'];
1510 $x->whereAdd("(on_id = $oid OR
1511 on_id IN ( SELECT distinct(id) FROM Documents WHERE original = $o )
1520 if (strlen($val) && $key[0] != '_') {
1521 $q_filtered[$key] = $val;
1524 // subjoined columns = check the values.
1525 // note this is not typesafe for anything other than mysql..
1527 if (isset($this->colsJname[$key])) {
1529 // the aobve rule for !strlen non-joined cols should apply to joined ones.
1530 if (!strlen($val)) {
1536 if (!is_numeric($val) || !is_long($val)) {
1539 $x->whereAdd( "{$this->colsJname[$key]} = " . ($quote ? "'". $x->escape($val) ."'" : $val));
1547 if (!empty($q_filtered)) {
1548 //var_dump($q_filtered);
1552 $x->setFrom($q_filtered);
1558 // nice generic -- let's get rid of it.. where is it used!!!!
1560 // Person / Group / Comapnies.... most of my queries noww...
1562 if (!empty($q['query']['name'])) {
1565 if (in_array( 'name', array_keys($x->table()))) {
1566 $x->whereAdd($x->tableName().".name LIKE '". $x->escape($q['query']['name']) . "%'");
1571 // - projectdirectory staff list - persn queuy
1576 * create the dataobject from (usually the url)
1577 * This uses $this->validTables
1578 * $this->validPrefix (later..)
1579 * to determine if class can be created..
1583 function dataObject($tab)
1585 if (is_array($this->validTables) && !in_array($tab,$this->validTables)) {
1586 $this->jerr("Invalid url - not listed in validTables");
1588 $tab = str_replace('/', '',$tab); // basic protection??
1590 $pm = HTML_FlexyFramework::get()->Pman;
1592 if (isset($pm['roo_alias'])) {
1593 $map = array_flip($pm['roo_alias']);
1594 if (isset($map[$tab])) {
1600 $x = DB_DataObject::factory($tab);
1602 if (!is_a($x, 'DB_DataObject') && !is_a($x, 'PDO_DataObject')) {
1603 $this->jerr('invalid url - no dataobject');