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.
93 * - all tables are always autojoined.
97 * _columns=a,b,c,d comma seperated list of columns.
98 * _exclude_columns=a,b,c,d comma seperated list of columns.
99 * _distinct=name a distinct column lookup. you also have to use _columns with this.
102 * colname = ... => colname = ....
103 * !colname=.... => colname != ....
104 * !colname[0]=... !colname[1]=... => colname NOT IN (.....) ** only supports main table at present..
105 * colname[0]=... colname[1]=... => colname IN (.....) ** only supports main table at present..
108 * sort=name what to sort.
109 * sort=a,b,d can support multiple columns
110 * dir=ASC what direction
111 * _multisort ={...} JSON encoded { sort : { row : direction }, order : [ row, row, row ] }
114 * start=0 limit start
115 * limit=25 limit number
119 * csvCols[0] csvCols[1].... = .... column titles for CSV output
120 * csvTitles[0], csvTitles[1] .... = columns to use for CSV output
123 * _toggleActive !:!:!:! - this hsould not really be here..
124 * query[add_blank] - add a line in with an empty option... - not really needed???
125 * _delete = delete a list of ids element. (depricated.. this will be removed...)
128 * _post =1 = simulate a post with debuggin on.
129 * _debug_post << This is prefered, as _post may overlap with accouting posts..
131 * _debug = turn on DB_dataobject deubbing, must be admin at present..
134 * CALLS methods on dataobjects if they exist
137 * checkPerm('S' , $authuser)
138 * - can we list the stuff
139 * - return false to disallow...
140 * applySort($au, $sortcol, $direction, $array_of_columns, $multisort)
141 * -- does not support multisort at present..
142 * applyFilters($_REQUEST, $authUser, $roo)
143 * -- apply any query filters on data. and hide stuff not to be seen.
144 * -- can exit by calling $roo->jerr()
145 * postListExtra($_REQUEST, $roo, $array_data) : array(extra_name => data)
146 * - add extra column to the jdata return key/value info.
147 * postListFilter($data, $authUser, $request) return $data
148 * - modify the returned array of data (either add stuff to the data, or remove lines etc)
151 * toRooSingleArray($authUser, $request) : array
152 * - called on single fetch only, add or maniuplate returned array data.
153 * - is also called when _id=0 is used (for fetching a default set.)
154 * toRooArray($request) : array
155 * - called if singleArray is unavailable on single fetch.
156 * - always tried for mutiple results.
157 * toArray() - the default method if none of the others are found.
158 * toSimpleExcelColumn($col) - see toCSV - this enables special columns to be created for exported data.
161 * - standard DataObject feature - causes all results to show all
165 * _extra_cols -- if set, then filtering by column etc. will use them.
169 function get($tab, $opts = Array())
171 // $this->jerr("Not authenticated", array('authFailure' => true));
172 //echo '<PRE>';print_R($_GET);
173 //DB_DataObject::debuglevel(1);
175 $this->init(); // from pman.
176 //DB_DataObject::debuglevel(1);
177 HTML_FlexyFramework::get()->generateDataobjectsCache($this->isDev && !empty($_REQUEST['isDev']));
185 if ( $this->checkDebugPost()) {
190 //DB_DAtaObject::debuglevel(1);
191 return $this->post($tab);
195 $this->initErrorHandling();
197 $tt = explode('/', $tab);
198 $tab = array_shift($tt);
199 $x = $this->dataObject($tab);
201 $_columns = !empty($_REQUEST['_columns']) ? explode(',', $_REQUEST['_columns']) : false;
203 if (isset( $_REQUEST['lookup'] ) && is_array($_REQUEST['lookup'] )) { // single fetch based on key/value pairs
204 $this->selectSingle($x, $_REQUEST['lookup'],$_REQUEST);
209 // single fetch (use '0' to fetch an empty object..)
210 if (isset($_REQUEST['_id']) && is_numeric($_REQUEST['_id'])) {
212 $this->selectSingle($x, $_REQUEST['_id'],$_REQUEST);
219 if (isset($_REQUEST['_delete'])) {
220 $this->jerr("DELETE by GET has been removed - update the code to use POST");
227 if (isset($_REQUEST['_toggleActive'])) {
228 // do we really delete stuff!?!?!?
229 if (!$this->hasPerm("Core.Staff", 'E')) {
230 $this->jerr("PERMISSION DENIED (ta)");
232 $clean = create_function('$v', 'return (int)$v;');
233 $bits = array_map($clean, explode(',', $_REQUEST['_toggleActive']));
234 if (in_array($this->authUser->id, $bits) && $this->authUser->active) {
235 $this->jerr("you can not disable yourself");
237 $x->query('UPDATE core_person SET active = !active WHERE id IN (' .implode(',', $bits).')');
238 $this->addEvent("USERTOGGLE", false, implode(',', $bits));
239 $this->jok("Updated");
242 //DB_DataObject::debugLevel(1);
244 // sets map and countWhat
245 $this->loadMap($x, array(
246 'columns' => $_columns,
247 'distinct' => empty($_REQUEST['_distinct']) ? false: $_REQUEST['_distinct'],
248 'exclude' => empty($_REQUEST['_exclude_columns']) ? false: explode(',', $_REQUEST['_exclude_columns'])
252 $this->setFilters($x,$_REQUEST);
254 if (!$this->checkPerm($x,'S', $_REQUEST)) {
255 $this->jerr("PERMISSION DENIED (g)");
259 // build join if req.
260 //DB_DataObject::debugLevel(1);
261 // count with multiple joins and no conditions can be quite slow - so if there are no conditions - just remove the joins from the count.
263 $old_where = $x->whereAdd();
264 if (empty($old_where )) {
267 $x->whereAdd($old_where);
272 if (!isset($_REQUEST['_no_count'])) {
273 $total = $xx->count($this->countWhat);
277 // var_dump($total);exit;
278 $this->applySort($x);
282 if (!empty($_REQUEST['_distinct']) && !isset($_REQUEST['_no_count']) && $total < 400) {
289 empty($_REQUEST['start']) ? 0 : (int)$_REQUEST['start'],
290 min(empty($_REQUEST['limit']) ? 25 : (int)$_REQUEST['limit'], $this->max_limit)
293 $queryObj = clone($x);
294 //DB_DataObject::debuglevel(1);
296 $this->sessionState(0);
298 $this->sessionState(1);
300 if (false === $res) {
301 $this->jerr($x->_lastError->toString());
309 // ---------------- THESE ARE DEPRICATED.. they should be moved to the model...
312 if (!empty($_REQUEST['query']['add_blank'])) {
313 $ret[] = array( 'id' => 0, 'name' => '----');
317 $rooar = method_exists($x, 'toRooArray');
318 $_columnsf = $_columns ? array_flip($_columns) : false;
319 while ($x->fetch()) {
321 $add = $rooar ? $x->toRooArray($_REQUEST) : $x->toArray();
322 if ($add === false) {
325 $ret[] = !$_columns ? $add : array_intersect_key($add, $_columnsf);
329 $ret = array_slice($ret,
330 empty($_REQUEST['start']) ? 0 : (int)$_REQUEST['start'],
331 min(empty($_REQUEST['limit']) ? 25 : (int)$_REQUEST['limit'], 10000)
338 if (method_exists($queryObj ,'postListExtra')) {
339 $extra = $queryObj->postListExtra($_REQUEST, $this, $ret);
343 // filter results, and add any data that is needed...
344 if (method_exists($x,'postListFilter')) {
345 $ret = $x->postListFilter($ret, $this->authUser, $_REQUEST);
350 if (!empty($_REQUEST['csvCols']) && !empty($_REQUEST['csvTitles']) ) {
353 $this->toCsv($ret, $_REQUEST['csvCols'], $_REQUEST['csvTitles'],
354 empty($_REQUEST['csvFilename']) ? '' : $_REQUEST['csvFilename'] );
361 if (!empty($_REQUEST['_requestMeta']) && count($ret)) {
362 $meta = $this->meta($x, $ret);
364 $extra = $extra ? $extra: array();
365 $extra['metaData'] = $meta;
368 // this make take some time...
369 $this->sessionState(0);
370 // echo "<PRE>"; print_r($ret);
371 $this->jdata($ret, max(count($ret), $total), $extra );
375 function checkDebug($req = false)
377 $req = $req === false ? $_REQUEST : $req;
379 if (empty($req['_debug'])) {
383 if (!empty($_SERVER['HTTP_HOST']) && $_SERVER['HTTP_HOST'] == 'localhost') {
384 DB_DAtaObject::debuglevel((int)$req['_debug']);
392 method_exists($this->authUser,'canDebug')
394 $this->authUser->canDebug()
399 method_exists($this->authUser,'groups')
401 is_a($this->authUser, 'Pman_Core_DataObjects_Core_person')
403 in_array('Administrators', $this->authUser->groups('name'))
408 DB_DAtaObject::debuglevel((int)$req['_debug']);
413 function checkDebugPost()
415 if (empty($_GET['_post']) && empty($_GET['_debug_post'])) {
418 // localhost can do anything...
419 if (!empty($_SERVER['HTTP_HOST']) && $_SERVER['HTTP_HOST'] == 'localhost') {
422 return $this->authUser &&
423 method_exists($this->authUser,'groups') &&
424 in_array('Administrators', $this->authUser->groups('name'));
428 function checkPerm($obj, $lvl, $req= null)
430 if (!method_exists($obj, 'checkPerm')) {
433 if ($obj->checkPerm($lvl, $this->authUser, $req)) {
439 function toCsv($data, $cols, $titles, $filename, $addDate = true)
442 $this->sessionState(0); // turn off sessions - no locking..
444 require_once 'Pman/Core/SimpleExcel.php';
446 $fn = (empty($filename) ? 'list-export-' : urlencode($filename)) . (($addDate) ? date('Y-m-d') : '') ;
450 'workbook' => substr($fn, 0, 31),
457 if (is_object($data)) {
458 $rooar = method_exists($data, 'toRooArray');
459 while($data->fetch()) {
460 $x = $rooar ? $data->toRooArray($q) : $data->toArray();
462 if ($cols == '*') { /// did we get cols sent to us?
463 $cols = array_keys($x);
466 if(!is_array($cols)) {
467 $cols = explode(',', $cols);
470 if ($titles !== false) {
472 $titles= array_keys($x);
474 if(!is_array($titles)) {
475 $titles = explode(',', $titles);
477 foreach($cols as $i=>$col) {
479 'header'=> isset($titles[$i]) ? $titles[$i] : $col,
482 // 'renderer' => array($this, 'getThumb'),
483 // 'color' => 'yellow', // set color for the cell which is a header element
484 // 'fillBlank' => 'gray', // set
487 if (method_exists($data, 'toSimpleExcelColumn')) {
488 $add = $data->toSimpleExcelColumn($add);
491 $se_config['cols'][] = $add;
496 $se = new Pman_Core_SimpleExcel(array(), $se_config);
502 $se->addLine($se_config['workbook'], $x);
508 $this->jerr('no data found', false, 'text/plain');
510 $se->send($fn .'.xls');
515 foreach($data as $x) {
516 //echo "<PRE>"; print_r(array($_REQUEST['csvCols'], $x->toArray())); exit;
520 $cols= array_keys($x);
523 if(!is_array($cols)) {
524 $cols = explode(',', $cols);
527 if ($titles !== false) {
529 $titles= array_keys($x);
532 if(!is_array($titles)) {
533 $titles = explode(',', $titles);
536 foreach($cols as $i=>$col) {
538 'header'=> isset($titles[$i]) ? $titles[$i] : $col,
541 // 'renderer' => array($this, 'getThumb'),
542 // 'color' => 'yellow', // set color for the cell which is a header element
543 // 'fillBlank' => 'gray', // set
546 if (method_exists($this->do, 'toSimpleExcelColumn')) {
547 $add = $this->do->toSimpleExcelColumn($add);
550 $se_config['cols'][] = $add;
555 $se = new Pman_Core_SimpleExcel(array(),$se_config);
558 //fputcsv($fh, $titles);
562 $se->addLine($se_config['workbook'], $x);
566 $this->jerr('no data found');
569 $se->send($fn .'.xls');
576 * POST method Roo/TABLENAME
577 * -- creates, updates, or deletes data.
580 * if the primary key is empty, this happens
581 * will automatically set these to current date and authUser->id
582 * created, created_by, created_dt
583 * updated, update_by, updated_dt
584 * modified, modified_by, modified_dt
586 * will return a GET request SINGLE SELECT (and accepts same)
589 * _delete=1,2,3 delete a set of data.
591 * if the primary key value is set, then update occurs.
592 * will automatically set these to current date and authUser->id
593 * updated, update_by, updated_dt
594 * modified, modified_by, modified_dt
598 * _delete=1,2,3 causes a delete to occur.
599 * _ids=1,2,3,4 causes update to occur on all primary ids.
602 * = same as single SELECT GET request..
607 * _debug=1 forces debug
608 * _get=1 - causes a get request to occur when doing a POST..
612 * these methods on dataobjects if they exist
614 * checkPerm('E' / 'D' , $authuser)
615 * - can we list the stuff
616 * - return false to disallow...
618 * toRooSingleArray($authUser, $request) : array
619 * - called on single fetch only, add or maniuplate returned array data.
620 * toRooArray($request) : array
621 * - Called if toSingleArray does not exist.
622 * - if you need to return different data than toArray..
625 * (for logging - this is generically prefixed to all database operations.)
629 * called when $_FILES is not empty
632 * setFromRoo($ar, $roo)
633 * - alternative to setFrom() which is called if this method does not exist
634 * - values from post (deal with dates etc.) - return true|error string.
635 * - call $roo->jerr() on failure...
637 * CALLS BEFORE change occurs:
639 * beforeDelete($dependants_array, $roo)
640 * Argument is an array of un-find/fetched dependant items.
641 * - jerr() will stop insert.. (Prefered)
642 * - return false for fail and set DO->err;
644 * beforeUpdate($old, $request,$roo)
645 * - before update - jerr() will stop insert..
646 * beforeInsert($request,$roo)
647 * - before insert - jerr() will stop insert..
650 * CALLS AFTER change occured
652 * onUpdate($old, $request,$roo)
653 * - after update // return value ignored
655 * onInsert($request,$roo)
658 * onDelete($request, $roo) - after delete
662 function post($tab) // update / insert (?? delete??)
664 // -- why was this put in? - Roo is not related to Core.All ?
665 //if (!$this->hasPerm("Core.All", 'E')) {
666 // $this->jerr("PERMISSION DENIED (e)");
668 $this->initErrorHandling();
670 // DB_DataObject::debugLevel(1);
673 if (!empty($_REQUEST['_get'])) {
674 return $this->get($tab);
677 $this->init(); // for pman.
679 $x = $this->dataObject($tab);
681 $this->transObj = clone($x);
683 $this->transObj->query('BEGIN');
684 // find the key and use that to get the thing..
687 $this->jerr('no key');
690 $this->key = $keys[0];
692 // delete should be here...
693 if (isset($_REQUEST['_delete'])) {
694 // do we really delete stuff!?!?!?
695 return $this->delete($x,$_REQUEST);
703 // not sure if this is a good idea here...
705 if (!empty($_REQUEST['_ids'])) {
706 $ids = explode(',',$_REQUEST['_ids']);
707 $x->whereAddIn($this->key, $ids, 'int');
708 $ar = $x->fetchAll();
711 $this->update($x, $_REQUEST);
714 $this->jok("UPDATED");
719 if (!empty($_REQUEST[$this->key])) {
721 if (!$x->get($this->key, $_REQUEST[$this->key])) {
722 $this->jerr("Invalid request (id does not point to a record.)");
724 $this->jok($this->update($x, $_REQUEST));
728 $this->jerr("No data recieved for inserting");
731 $this->jok($this->insert($x, $_REQUEST));
743 * apply REQUEST[sort] and [dir]
744 * sort may be an array of columsn..
746 * @arg DB_DataObject $x
749 function applySort($x, $sort = '', $dir ='')
752 // Db_DataObject::debugLevel(1);
753 $sort = empty($_REQUEST['sort']) ? $sort : $_REQUEST['sort'];
754 $dir = empty($_REQUEST['dir']) ? $dir : $_REQUEST['dir'];
755 $dir = $dir == 'ASC' ? 'ASC' : 'DESC';
757 $ms = empty($_REQUEST['_multisort']) ? false : $_REQUEST['_multisort'];
758 //var_Dump($ms);exit;
760 if (method_exists($x, 'applySort')) {
761 $sorted = $x->applySort(
765 array_keys($this->cols),
766 $ms ? json_decode($ms) : false
771 return $this->multiSort($x);
774 if ($sorted === false) {
775 $cols = $x->tableColumns();
776 $excols = array_keys($this->cols);
778 if (isset($x->_extra_cols)) {
779 $excols = array_merge($excols, $x->_extra_cols);
781 $sort_ar = explode(',', $sort);
784 foreach($sort_ar as $sort) {
786 if (strlen($sort) && isset($cols[$sort]) ) {
787 $sort_str[] = $x->tableName() .'.'.$sort . ' ' . $dir ;
789 } else if (in_array($sort, $excols)) {
790 $sort_str[] = $sort . ' ' . $dir ;
795 $x->orderBy(implode(', ', $sort_str ));
806 function multiSort($x)
808 //DB_DataObject::debugLevel(1);
809 $ms = json_decode($_REQUEST['_multisort']);
810 if (!isset($ms->order) || !is_array($ms->order)) {
815 $cols = $x->tableColumns();
817 //print_r($this->cols);exit;
818 // this-><cols contains colname => aliased name...
819 foreach($ms->order as $col) {
820 if (!isset($ms->sort->{$col})) {
821 continue; // no direction..
823 $ms->sort->{$col} = $ms->sort->{$col} == 'ASC' ? 'ASC' : 'DESC';
825 if (strlen($col) && isset($cols[$col]) ) {
826 $sort_str[] = $x->tableName() .'.'.$col . ' ' . $ms->sort->{$col};
829 //print_r($this->cols);
831 if (in_array($col, array_keys($this->cols))) {
832 $sort_str[] = $col. ' ' . $ms->sort->{$col};
835 if (isset($x->_extra_cols) && in_array($col, $x->_extra_cols)) {
836 $sort_str[] = $col. ' ' . $ms->sort->{$col};
841 $x->orderBy(implode(', ', $sort_str ));
848 * - used when _id is set, or after insert or update
850 * @param DataObject $x the dataobject to use
851 * @param int $id the pid of the object
852 * @param array $req the request, or false if it comes from insert/update.
855 function selectSingle($x, $id, $req=false)
859 $_columns = !empty($req['_columns']) ? explode(',', $req['_columns']) : false;
861 //var_dump(array(!is_array($id) , empty($id)));
862 if (!is_array($id) && empty($id)) {
865 if (method_exists($x, 'toRooSingleArray')) {
866 $this->jok($x->toRooSingleArray($this->authUser, $req));
868 if (method_exists($x, 'toRooArray')) {
869 $this->jok($x->toRooArray($req));
872 $this->jok($x->toArray());
876 $this->loadMap($x, array(
877 'columns' => $_columns,
880 if ($req !== false) {
881 $this->setFilters($x, $req);
882 } else if (method_exists($x, 'applyFilters')) {
883 // always call apply filters even after update/insert...
884 // however arguments are not passed.
885 $x->applyFilters(array('_is_update_request' => true), $this->authUser, $this);
888 // DB_DataObject::DebugLevel(1);
891 $x->setFrom($req['lookup'] );
893 if (!$x->find(true)) {
894 if (!empty($id['_id'])) {
896 $this->jok($x->toArray());
901 } else if (!$x->get($id)) {
902 $this->jerr("selectSingle: no such record ($id)");
905 // ignore perms if comming from update/insert - as it's already done...
906 if ($req !== false && !$this->checkPerm($x,'S')) {
907 $this->jerr("PERMISSION DENIED - si");
909 // different symantics on all these calls??
910 if (method_exists($x, 'toRooSingleArray')) {
911 $this->jok($x->toRooSingleArray($this->authUser, $req));
913 if (method_exists($x, 'toRooArray')) {
914 $this->jok($x->toRooArray($req));
916 $this->jok($x->toArray());
921 function insert($x, $req, $with_perm_check = true)
923 if (method_exists($x, 'setFromRoo')) {
924 $res = $x->setFromRoo($req, $this);
925 if (is_string($res)) {
932 if ( $with_perm_check && !$this->checkPerm($x,'A', $req)) {
933 $this->jerr("PERMISSION DENIED (i)");
935 $cols = $x->tableColumns();
937 if (isset($cols['created'])) {
938 $x->created = date('Y-m-d H:i:s');
940 if (isset($cols['created_dt'])) {
941 $x->created_dt = date('Y-m-d H:i:s');
943 if (isset($cols['created_by'])) {
944 $x->created_by = $this->authUser->id;
947 if (isset($cols['modified'])) {
948 $x->modified = date('Y-m-d H:i:s');
950 if (isset($cols['modified_dt'])) {
951 $x->modified_dt = date('Y-m-d H:i:s');
953 if (isset($cols['modified_by'])) {
954 $x->modified_by = $this->authUser->id;
957 if (isset($cols['updated'])) {
958 $x->updated = date('Y-m-d H:i:s');
960 if (isset($cols['updated_dt'])) {
961 $x->updated_dt = date('Y-m-d H:i:s');
963 if (isset($cols['updated_by'])) {
964 $x->updated_by = $this->authUser->id;
967 if (method_exists($x, 'beforeInsert')) {
968 $x->beforeInsert($_REQUEST, $this);
973 if ($res === false) {
974 $this->jerr($x->_lastError->toString());
976 $ev = $this->addEvent("ADD", $x);
977 if (method_exists($x, 'onInsert')) {
979 $x->onInsert($_REQUEST, $this, $ev);
986 // note setFrom might handle this before hand...!??!
987 if (!empty($_FILES) && method_exists($x, 'onUpload')) {
988 $x->onUpload($this, $_REQUEST);
991 return $this->selectSingle(
992 DB_DataObject::factory($x->tableName()),
998 function updateLock($x, $req )
1000 Pman::$permitError = true; // allow it to fail without dieing
1002 $lock = DB_DataObjecT::factory('Core_locking');
1003 Pman::$permitError = false;
1004 if (is_a($lock,'DB_DataObject') && $this->authUser) {
1006 $lock->on_id = $x->{$this->key};
1007 $lock->on_table= strtolower($x->tableName());
1008 if (!empty($_REQUEST['_lock_id'])) {
1009 $lock->whereAdd('id != ' . ((int)$_REQUEST['_lock_id']));
1011 $lock->whereAdd('person_id !=' . $this->authUser->id);
1014 $llc = clone($lock);
1015 $exp = date('Y-m-d', strtotime('NOW - 1 WEEK'));
1016 $llc->whereAdd("created < '$exp'");
1017 if ($llc->count()) {
1019 while($llc->fetch()) {
1020 $llcd = clone($llc);
1026 if ($lock->find(true)) {
1027 // it's locked by someone else..
1028 $p = $lock->person();
1031 $this->jerr( "Record was locked by " . $p->name . " at " .$lock->created.
1032 " - Please confirm you wish to save"
1033 , array('needs_confirm' => true));
1037 // check the users lock.. - no point.. ??? - if there are no other locks and it's not the users, then they can
1038 // edit it anyways...
1040 // can we find the user's lock.
1041 $lock = DB_DataObjecT::factory('Core_locking');
1042 $lock->on_id = $x->{$this->key};
1043 $lock->on_table= strtolower($x->tableName());
1044 $lock->person_id = $this->authUser->id;
1045 $lock->orderBy('created DESC');
1049 $lock->find(true) &&
1050 isset($x->modified_dt) &&
1051 strtotime($x->modified_dt) > strtotime($lock->created) &&
1052 empty($req['_submit_confirmed']) &&
1053 $x->modified_by != $this->authUser->id
1056 $p = DB_DataObject::factory('core_person');
1057 $p->get($x->modified_by);
1058 $this->jerr($p->name . " saved the record since you started editing,\nDo you really want to update it?", array('needs_confirm' => true));
1070 function update($x, $req, $with_perm_check = true)
1072 if ( $with_perm_check && !$this->checkPerm($x,'E', $req) ) {
1073 $this->jerr("PERMISSION DENIED - No Edit permissions on this element");
1076 // check any locks..
1077 // only done if we recieve a lock_id.
1078 // we are very trusing here.. that someone has not messed around with locks..
1079 // the object might want to check in their checkPerm - if locking is essential..
1080 $lock = $this->updateLock($x,$req);
1090 // this lot is generic.. needs moving
1091 if (method_exists($x, 'setFromRoo')) {
1092 $res = $x->setFromRoo($req, $this);
1093 if (is_string($res)) {
1102 //echo '<PRE>';print_r($old);print_r($x);exit;
1105 $cols = $x->tableColumns();
1107 if (isset($cols['modified'])) {
1108 $x->modified = date('Y-m-d H:i:s');
1110 if (isset($cols['modified_dt'])) {
1111 $x->modified_dt = date('Y-m-d H:i:s');
1113 if (isset($cols['modified_by']) && $this->authUser) {
1114 $x->modified_by = $this->authUser->id;
1117 if (isset($cols['updated'])) {
1118 $x->updated = date('Y-m-d H:i:s');
1120 if (isset($cols['updated_dt'])) {
1121 $x->updated_dt = date('Y-m-d H:i:s');
1123 if (isset($cols['updated_by']) && $this->authUser) {
1124 $x->updated_by = $this->authUser->id;
1127 if (method_exists($x, 'beforeUpdate')) {
1128 $x->beforeUpdate($old, $req, $this);
1131 if ($with_perm_check && !empty($_FILES) && method_exists($x, 'onUpload')) {
1132 $x->onUpload($this, $_REQUEST);
1135 //DB_DataObject::DebugLevel(1);
1136 $res = $x->update($old);
1137 if ($res === false) {
1138 $this->jerr($x->_lastError->toString());
1140 $ev = $this->addEvent("EDIT", $x);
1142 if (method_exists($x, 'onUpdate')) {
1143 $x->onUpdate($old, $req, $this, $ev);
1146 $ev->audit($x, $old);
1150 return $this->selectSingle(
1151 DB_DataObject::factory($x->tableName()),
1157 * Delete a number of records.
1158 * calls $delete_obj->beforeDelete($array_of_dependant_dataobjects, $this)
1162 function delete($x, $req)
1164 // do we really delete stuff!?!?!?
1165 if (empty($req['_delete'])) {
1166 $this->jerr("Delete Requested with no value");
1170 // build a list of tables to queriy for dependant data..
1175 $all_links = $x->databaseLinks();
1177 foreach($all_links as $tbl => $links) {
1178 foreach($links as $col => $totbl_col) {
1179 $to = explode(':', $totbl_col);
1180 if ($to[0] != $x->tableName()) {
1184 $affects[$tbl .'.' . $col] = true;
1189 // echo '<PRE>';print_r($affects);exit;
1190 // DB_Dataobject::debugLevel(1);
1195 $bits = array_map(function($v) { return (int)$v; } , explode(',', $req['_delete']));
1197 // let's assume it has a key!!!
1199 $x->whereAdd($this->key .' IN ('. implode(',', $bits) .')');
1201 $this->jerr("Nothing found to delete");
1204 while ($x->fetch()) {
1210 if (!$this->checkPerm($x,'D') ) {
1211 $this->jerr("PERMISSION DENIED (d)");
1214 $match_ar = array();
1215 foreach($affects as $k=> $true) {
1216 $ka = explode('.', $k);
1218 $chk = DB_DataObject::factory($ka[0]);
1219 if (!is_a($chk,'DB_DataObject') && !is_a($chk,'PDO_DataObject')) {
1220 $this->jerr('Unable to load referenced table, check the links config: ' .$ka[0]);
1222 // print_r(array($chk->tablename() , $ka[1] , $xx->tablename() , $this->key ));
1223 $chk->{$ka[1]} = $xx->{$this->key};
1225 if (count($chk->keys())) {
1226 $matches = $chk->count();
1228 //DB_DataObject::DebugLevel(1);
1229 $matches = $chk->count($ka[1]);
1233 $chk->_match_key = $ka[1];
1234 $match_ar[] = clone($chk);
1240 $has_beforeDelete = method_exists($xx, 'beforeDelete');
1241 // before delte = allows us to trash dependancies if needed..
1244 if ( $has_beforeDelete ) {
1245 if ($xx->beforeDelete($match_ar, $this, $_REQUEST) === false) {
1246 $errs[] = "Delete failed ({$xx->id})\n".
1247 (isset($xx->err) ? $xx->err : '');
1250 // refetch affects..
1252 $match_ar = array();
1253 foreach($affects as $k=> $true) {
1254 $ka = explode('.', $k);
1255 $chk = DB_DataObject::factory($ka[0]);
1256 if (!is_a($chk,'DB_DataObject') && !is_a($chk,'PDO_DataObject')) {
1257 $this->jerr('Unable to load referenced table, check the links config: ' .$ka[0]);
1259 $chk->{$ka[1]} = $xx->{$this->key};
1260 $matches = $chk->count();
1261 $match_total += $matches;
1263 $chk->_match_key = $ka[1];
1264 $match_ar[] = clone($chk);
1271 if (!empty($match_ar)) {
1272 $chk = $match_ar[0];
1274 $o = $chk->fetchAll();
1275 $key = isset($chk->_match_key) ?$chk->_match_key : '?unknown column?';
1276 $desc = $chk->tableName(). '.' . $key .'='.$xx->{$this->key} ;
1277 if (method_exists($chk, 'toEventString')) {
1278 $desc .= ' : ' . $o[0]->toEventString();
1280 $this->jerr("Delete Dependant records ($match_total found), " .
1281 "first is ( $desc )");
1287 DB_DataObject::Factory('Events')->logDeletedRecord($x);
1289 $this->addEvent("DELETE", $x);
1293 if (method_exists($xx,'onDelete')) {
1294 $xx->onDelete($req, $this);
1300 $this->jerr(implode("\n<BR>", $errs));
1302 $this->jok("Deleted");
1308 * cols stores the list of columns that are available from the query.
1311 * This is a dupe of what is in autojoin -- we should move to using autojoin really.
1323 var $cols = array();
1327 function loadMap($do, $cfg =array()) //$onlycolumns=false, $distinct = false)
1330 //DB_DataObject::debugLevel(5);
1331 $onlycolumns = !empty($cfg['columns']) ? $cfg['columns'] : false;
1332 $distinct = !empty($cfg['distinct']) ? $cfg['distinct'] : false;
1333 $excludecolumns = !empty($cfg['exclude']) ? $cfg['exclude'] : array();
1335 $excludecolumns[] = 'passwd'; // we never expose passwords
1336 $excludecolumns[] = 'oath_key';
1338 $ret = $do->autoJoin(array(
1339 'include' => $onlycolumns,
1340 'exclude' => $excludecolumns,
1341 'distinct' => $distinct
1344 $this->countWhat = $ret['count'];
1345 $this->cols = $ret['cols'];
1346 $this->colsJname = $ret['join_names'];
1355 * generate the meta data neede by queries.
1358 function meta($x, $data)
1360 // this is not going to work on queries where the data does not match the database def..
1361 // for unknown columns we send them as stirngs..
1363 $cols = array_keys($data[0]);
1367 if (class_exists('PDO_DataObject')) {
1368 $options = PDO_DataObject::config();
1369 if (!file_exists($options["schema_location"] . '.reader')) {
1373 $rdata = unserialize(file_get_contents($options["schema_location"] . '.reader'));
1376 //echo '<PRE>';print_r($this->cols); exit;
1377 $options = &PEAR::getStaticProperty('DB_DataObject','options');
1378 $reader = $options["ini_{$x->databaseNickname()}"] .'.reader';
1379 if (!file_exists( $reader )) {
1383 $rdata = unserialize(file_get_contents($reader));
1386 //echo '<PRE>';print_r($this->cols);exit;
1387 //echo '<PRE>';print_r($rdata);exit;
1388 // echo '<PRE>';print_r($rdata);exit;
1391 $key = empty($keys) ? 'id' : $keys[0];
1395 foreach($cols as $c ) {
1396 if (!isset($this->cols[$c]) || !isset($rdata[$this->cols[$c]]) || !is_array($rdata[$this->cols[$c]])) {
1400 $add = $rdata[$this->cols[$c]];
1405 'totalProperty' => 'total',
1406 'successProperty' => 'success',
1408 'id' => $key, // was 'id'...
1415 function setFilters($x, $q)
1417 // if a column is type int, and we get ',' -> the it should be come an inc clause..
1418 // DB_DataObject::debugLevel(1);
1419 if (method_exists($x, 'applyFilters')) {
1420 // DB_DataObject::debugLevel(1);
1421 if (false === $x->applyFilters($q, $this->authUser, $this)) {
1425 $q_filtered = array();
1429 foreach($q as $key=>$val) {
1431 if (in_array($key,$keys) && !is_array($val)) {
1436 // handles name[]=fred&name[]=brian => name in ('fred', 'brian').
1437 // value is an array..
1438 if (is_array($val) ) {
1442 if ($key[0] == '!') {
1444 $key = substr($key,1);
1447 if (!in_array( $key, array_keys($this->cols))) {
1451 // support a[0] a[1] ..... => whereAddIn(
1454 foreach($val as $k=>$v) {
1455 if (!is_numeric($k)) {
1459 // FIXME: note this is not typesafe for anything other than mysql..
1461 if (!is_numeric($v) || !is_long($v)) {
1470 $x->whereAddIn($pref . (
1471 isset($this->colsJname[$key]) ?
1472 $this->colsJname[$key] :
1473 ($x->tableName(). '.'.$key)),
1474 $ar, $quote ? 'string' : 'int');
1481 // handles !name=fred => name not equal fred.
1482 if ($key[0] == '!' && in_array(substr($key, 1), array_keys($this->cols))) {
1484 $key = substr($key, 1) ;
1487 isset($this->colsJname[$key]) ?
1488 $this->colsJname[$key] :
1489 $x->tableName(). '.'.$key ) . ' != ' .
1490 (is_numeric($val) ? $val : "'". $x->escape($val) . "'")
1500 // Events and remarks -- fixme - move to events/remarsk...
1501 case 'on_id': // where TF is this used...
1502 if (!empty($q['query']['original'])) {
1503 // DB_DataObject::debugLevel(1);
1504 $o = (int) $q['query']['original'];
1506 $x->whereAdd("(on_id = $oid OR
1507 on_id IN ( SELECT distinct(id) FROM Documents WHERE original = $o )
1516 if (strlen($val) && $key[0] != '_') {
1517 $q_filtered[$key] = $val;
1520 // subjoined columns = check the values.
1521 // note this is not typesafe for anything other than mysql..
1523 if (isset($this->colsJname[$key])) {
1525 // the aobve rule for !strlen non-joined cols should apply to joined ones.
1526 if (!strlen($val)) {
1532 if (!is_numeric($val) || !is_long($val)) {
1535 $x->whereAdd( "{$this->colsJname[$key]} = " . ($quote ? "'". $x->escape($val) ."'" : $val));
1543 if (!empty($q_filtered)) {
1544 //var_dump($q_filtered);
1548 $x->setFrom($q_filtered);
1554 // nice generic -- let's get rid of it.. where is it used!!!!
1556 // Person / Group / Comapnies.... most of my queries noww...
1558 if (!empty($q['query']['name'])) {
1561 if (in_array( 'name', array_keys($x->table()))) {
1562 $x->whereAdd($x->tableName().".name LIKE '". $x->escape($q['query']['name']) . "%'");
1567 // - projectdirectory staff list - persn queuy
1572 * create the dataobject from (usually the url)
1573 * This uses $this->validTables
1574 * $this->validPrefix (later..)
1575 * to determine if class can be created..
1579 function dataObject($tab)
1581 if (is_array($this->validTables) && !in_array($tab,$this->validTables)) {
1582 $this->jerr("Invalid url - not listed in validTables");
1584 $tab = str_replace('/', '',$tab); // basic protection??
1586 $pm = HTML_FlexyFramework::get()->Pman;
1588 if (isset($pm['roo_alias'])) {
1589 $map = array_flip($pm['roo_alias']);
1590 if (isset($map[$tab])) {
1596 $x = DB_DataObject::factory($tab);
1598 if (!is_a($x, 'DB_DataObject') && !is_a($x, 'PDO_DataObject')) {
1599 $this->jerr('invalid url - no dataobject');