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.
59 var $do = false; // the dataobject being worked on..
63 parent::getAuth(); // load company!
64 $au = $this->getAuthUser();
67 $this->jerr("Not authenticated", array('authFailure' => true));
69 if (!$au->pid() ) { // not set up yet..
70 $this->jerr("Not authenticated", array('authFailure' => true));
74 $this->authUser = $au;
78 * GET method Roo/TABLENAME
80 * Generally for SELECT or Single SELECT
83 * _id=value single fetch based on primary id.
84 * can be '0' if you want to fetch a set of defaults
85 * Use in conjuntion with toRooSingleArray()
87 * lookup[key]=value single fetch based on a single key value lookup.
88 * multiple key/value can be used. eg. ontable+onid..
89 * _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) : array(extra_name => data)
146 * - add extra column data on the results (like new messages etc.)
147 * postListFilter($data, $authUser, $request) return $data
148 * - add extra data to an object
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'])
251 $this->setFilters($x,$_REQUEST);
253 if (!$this->checkPerm($x,'S', $_REQUEST)) {
254 $this->jerr("PERMISSION DENIED (g)");
258 // build join if req.
259 //DB_DataObject::debugLevel(1);
260 // count with multiple joins and no conditions can be quite slow - so if there are no conditions - just remove the joins from the count.
262 if (empty($xx->_query['condition']) && !empty($xx->_join)) {
266 $total = $xx->count($this->countWhat);
269 //var_dump($total);exit;
270 $this->applySort($x);
274 if (!empty($_REQUEST['_distinct']) && $total < 400) {
281 empty($_REQUEST['start']) ? 0 : (int)$_REQUEST['start'],
282 min(empty($_REQUEST['limit']) ? 25 : (int)$_REQUEST['limit'], $this->max_limit)
285 $queryObj = clone($x);
286 //DB_DataObject::debuglevel(1);
288 $this->sessionState(0);
290 $this->sessionState(1);
292 if (false === $res) {
293 $this->jerr($x->_lastError->toString());
301 // ---------------- THESE ARE DEPRICATED.. they should be moved to the model...
304 if (!empty($_REQUEST['query']['add_blank'])) {
305 $ret[] = array( 'id' => 0, 'name' => '----');
309 $rooar = method_exists($x, 'toRooArray');
310 $_columnsf = $_columns ? array_flip($_columns) : false;
311 while ($x->fetch()) {
313 $add = $rooar ? $x->toRooArray($_REQUEST) : $x->toArray();
314 if ($add === false) {
317 $ret[] = !$_columns ? $add : array_intersect_key($add, $_columnsf);
321 $ret = array_slice($ret,
322 empty($_REQUEST['start']) ? 0 : (int)$_REQUEST['start'],
323 min(empty($_REQUEST['limit']) ? 25 : (int)$_REQUEST['limit'], 10000)
330 if (method_exists($queryObj ,'postListExtra')) {
331 $extra = $queryObj->postListExtra($_REQUEST, $this);
335 // filter results, and add any data that is needed...
336 if (method_exists($x,'postListFilter')) {
337 $ret = $x->postListFilter($ret, $this->authUser, $_REQUEST);
342 if (!empty($_REQUEST['csvCols']) && !empty($_REQUEST['csvTitles']) ) {
345 $this->toCsv($ret, $_REQUEST['csvCols'], $_REQUEST['csvTitles'],
346 empty($_REQUEST['csvFilename']) ? '' : $_REQUEST['csvFilename'] );
353 //if ($x->tableName() == 'Documents_Tracking') {
354 // $ret = $this->replaceSubject(&$ret, 'doc_id_subject');
359 if (!empty($_REQUEST['_requestMeta']) && count($ret)) {
360 $meta = $this->meta($x, $ret);
362 $extra['metaData'] = $meta;
365 // this make take some time...
366 $this->sessionState(0);
367 // echo "<PRE>"; print_r($ret);
368 $this->jdata($ret, max(count($ret), $total), $extra );
372 function checkDebug($req = false)
374 $req = $req === false ? $_REQUEST : $req;
376 if (empty($req['_debug'])) {
380 if (!empty($_SERVER['HTTP_HOST']) && $_SERVER['HTTP_HOST'] == 'localhost') {
381 DB_DAtaObject::debuglevel((int)$req['_debug']);
389 method_exists($this->authUser,'canDebug')
391 $this->authUser->canDebug()
396 method_exists($this->authUser,'groups')
398 is_a($this->authUser, 'Pman_Core_DataObjects_Core_person')
400 in_array('Administrators', $this->authUser->groups('name'))
405 DB_DAtaObject::debuglevel((int)$req['_debug']);
410 function checkDebugPost()
412 if (empty($_GET['_post']) && empty($_GET['_debug_post'])) {
415 // localhost can do anything...
416 if (!empty($_SERVER['HTTP_HOST']) && $_SERVER['HTTP_HOST'] == 'localhost') {
419 return $this->authUser &&
420 method_exists($this->authUser,'groups') &&
421 in_array('Administrators', $this->authUser->groups('name'));
425 function checkPerm($obj, $lvl, $req= null)
427 if (!method_exists($obj, 'checkPerm')) {
430 if ($obj->checkPerm($lvl, $this->authUser, $req)) {
436 function toCsv($data, $cols, $titles, $filename, $addDate = true)
439 $this->sessionState(0); // turn off sessions - no locking..
441 require_once 'Pman/Core/SimpleExcel.php';
443 $fn = (empty($filename) ? 'list-export-' : urlencode($filename)) . (($addDate) ? date('Y-m-d') : '') ;
447 'workbook' => substr($fn, 0, 31),
454 if (is_object($data)) {
455 $rooar = method_exists($data, 'toRooArray');
456 while($data->fetch()) {
457 $x = $rooar ? $data->toRooArray($q) : $data->toArray();
459 if ($cols == '*') { /// did we get cols sent to us?
460 $cols = array_keys($x);
463 if(!is_array($cols)) {
464 $cols = explode(',', $cols);
467 if ($titles !== false) {
469 $titles= array_keys($x);
471 if(!is_array($titles)) {
472 $titles = explode(',', $titles);
474 foreach($cols as $i=>$col) {
476 'header'=> isset($titles[$i]) ? $titles[$i] : $col,
479 // 'renderer' => array($this, 'getThumb'),
480 // 'color' => 'yellow', // set color for the cell which is a header element
481 // 'fillBlank' => 'gray', // set
484 if (method_exists($data, 'toSimpleExcelColumn')) {
485 $add = $data->toSimpleExcelColumn($add);
488 $se_config['cols'][] = $add;
493 $se = new Pman_Core_SimpleExcel(array(), $se_config);
499 $se->addLine($se_config['workbook'], $x);
505 $this->jerr('no data found', false, 'text/plain');
507 $se->send($fn .'.xls');
512 foreach($data as $x) {
513 //echo "<PRE>"; print_r(array($_REQUEST['csvCols'], $x->toArray())); exit;
517 $cols= array_keys($x);
520 if(!is_array($cols)) {
521 $cols = explode(',', $cols);
524 if ($titles !== false) {
526 $titles= array_keys($x);
529 if(!is_array($titles)) {
530 $titles = explode(',', $titles);
533 foreach($cols as $i=>$col) {
535 'header'=> isset($titles[$i]) ? $titles[$i] : $col,
538 // 'renderer' => array($this, 'getThumb'),
539 // 'color' => 'yellow', // set color for the cell which is a header element
540 // 'fillBlank' => 'gray', // set
543 if (method_exists($this->do, 'toSimpleExcelColumn')) {
544 $add = $this->do->toSimpleExcelColumn($add);
547 $se_config['cols'][] = $add;
552 $se = new Pman_Core_SimpleExcel(array(),$se_config);
555 //fputcsv($fh, $titles);
559 $se->addLine($se_config['workbook'], $x);
563 $this->jerr('no data found');
566 $se->send($fn .'.xls');
573 * POST method Roo/TABLENAME
574 * -- creates, updates, or deletes data.
577 * if the primary key is empty, this happens
578 * will automatically set these to current date and authUser->id
579 * created, created_by, created_dt
580 * updated, update_by, updated_dt
581 * modified, modified_by, modified_dt
583 * will return a GET request SINGLE SELECT (and accepts same)
586 * _delete=1,2,3 delete a set of data.
588 * if the primary key value is set, then update occurs.
589 * will automatically set these to current date and authUser->id
590 * updated, update_by, updated_dt
591 * modified, modified_by, modified_dt
595 * _delete=1,2,3 causes a delete to occur.
596 * _ids=1,2,3,4 causes update to occur on all primary ids.
599 * = same as single SELECT GET request..
604 * _debug=1 forces debug
605 * _get=1 - causes a get request to occur when doing a POST..
609 * these methods on dataobjects if they exist
611 * checkPerm('E' / 'D' , $authuser)
612 * - can we list the stuff
613 * - return false to disallow...
615 * toRooSingleArray($authUser, $request) : array
616 * - called on single fetch only, add or maniuplate returned array data.
617 * toRooArray($request) : array
618 * - Called if toSingleArray does not exist.
619 * - if you need to return different data than toArray..
622 * (for logging - this is generically prefixed to all database operations.)
626 * called when $_FILES is not empty
629 * setFromRoo($ar, $roo)
630 * - alternative to setFrom() which is called if this method does not exist
631 * - values from post (deal with dates etc.) - return true|error string.
632 * - call $roo->jerr() on failure...
634 * CALLS BEFORE change occurs:
636 * beforeDelete($dependants_array, $roo)
637 * Argument is an array of un-find/fetched dependant items.
638 * - jerr() will stop insert.. (Prefered)
639 * - return false for fail and set DO->err;
641 * beforeUpdate($old, $request,$roo)
642 * - before update - jerr() will stop insert..
643 * beforeInsert($request,$roo)
644 * - before insert - jerr() will stop insert..
647 * CALLS AFTER change occured
649 * onUpdate($old, $request,$roo)
650 * - after update // return value ignored
652 * onInsert($request,$roo)
655 * onDelete($request, $roo) - after delete
659 function post($tab) // update / insert (?? delete??)
661 // -- why was this put in? - Roo is not related to Core.All ?
662 //if (!$this->hasPerm("Core.All", 'E')) {
663 // $this->jerr("PERMISSION DENIED (e)");
665 $this->initErrorHandling();
667 // DB_DataObject::debugLevel(1);
670 if (!empty($_REQUEST['_get'])) {
671 return $this->get($tab);
674 $this->init(); // for pman.
676 $x = $this->dataObject($tab);
678 $this->transObj = clone($x);
680 $this->transObj->query('BEGIN');
681 // find the key and use that to get the thing..
684 $this->jerr('no key');
687 $this->key = $keys[0];
689 // delete should be here...
690 if (isset($_REQUEST['_delete'])) {
691 // do we really delete stuff!?!?!?
692 return $this->delete($x,$_REQUEST);
700 // not sure if this is a good idea here...
702 if (!empty($_REQUEST['_ids'])) {
703 $ids = explode(',',$_REQUEST['_ids']);
704 $x->whereAddIn($this->key, $ids, 'int');
705 $ar = $x->fetchAll();
708 $this->update($x, $_REQUEST);
711 $this->jok("UPDATED");
716 if (!empty($_REQUEST[$this->key])) {
718 if (!$x->get($this->key, $_REQUEST[$this->key])) {
719 $this->jerr("Invalid request (id does not point to a record.)");
721 $this->jok($this->update($x, $_REQUEST));
725 $this->jerr("No data recieved for inserting");
728 $this->jok($this->insert($x, $_REQUEST));
740 * apply REQUEST[sort] and [dir]
741 * sort may be an array of columsn..
743 * @arg DB_DataObject $x
746 function applySort($x, $sort = '', $dir ='')
749 // Db_DataObject::debugLevel(1);
750 $sort = empty($_REQUEST['sort']) ? $sort : $_REQUEST['sort'];
751 $dir = empty($_REQUEST['dir']) ? $dir : $_REQUEST['dir'];
752 $dir = $dir == 'ASC' ? 'ASC' : 'DESC';
754 $ms = empty($_REQUEST['_multisort']) ? false : $_REQUEST['_multisort'];
755 //var_Dump($ms);exit;
757 if (method_exists($x, 'applySort')) {
758 $sorted = $x->applySort(
762 array_keys($this->cols),
763 $ms ? json_decode($ms) : false
767 return $this->multiSort($x);
770 if ($sorted === false) {
772 $cols = $x->tableColumns();
773 $excols = array_keys($this->cols);
775 if (isset($x->_extra_cols)) {
776 $excols = array_merge($excols, $x->_extra_cols);
778 $sort_ar = explode(',', $sort);
781 foreach($sort_ar as $sort) {
783 if (strlen($sort) && isset($cols[$sort]) ) {
784 $sort_str[] = $x->tableName() .'.'.$sort . ' ' . $dir ;
786 } else if (in_array($sort, $excols)) {
787 $sort_str[] = $sort . ' ' . $dir ;
792 $x->orderBy(implode(', ', $sort_str ));
803 function multiSort($x)
805 //DB_DataObject::debugLevel(1);
806 $ms = json_decode($_REQUEST['_multisort']);
807 if (!isset($ms->order) || !is_array($ms->order)) {
812 $cols = $x->tableColumns();
814 //print_r($this->cols);exit;
815 // this-><cols contains colname => aliased name...
816 foreach($ms->order as $col) {
817 if (!isset($ms->sort->{$col})) {
818 continue; // no direction..
820 $ms->sort->{$col} = $ms->sort->{$col} == 'ASC' ? 'ASC' : 'DESC';
822 if (strlen($col) && isset($cols[$col]) ) {
823 $sort_str[] = $x->tableName() .'.'.$col . ' ' . $ms->sort->{$col};
826 //print_r($this->cols);
828 if (in_array($col, array_keys($this->cols))) {
829 $sort_str[] = $col. ' ' . $ms->sort->{$col};
832 if (isset($x->_extra_cols) && in_array($col, $x->_extra_cols)) {
833 $sort_str[] = $col. ' ' . $ms->sort->{$col};
838 $x->orderBy(implode(', ', $sort_str ));
845 * - used when _id is set, or after insert or update
847 * @param DataObject $x the dataobject to use
848 * @param int $id the pid of the object
849 * @param array $req the request, or false if it comes from insert/update.
852 function selectSingle($x, $id, $req=false)
856 $_columns = !empty($req['_columns']) ? explode(',', $req['_columns']) : false;
858 //var_dump(array(!is_array($id) , empty($id)));
859 if (!is_array($id) && empty($id)) {
862 if (method_exists($x, 'toRooSingleArray')) {
863 $this->jok($x->toRooSingleArray($this->authUser, $req));
865 if (method_exists($x, 'toRooArray')) {
866 $this->jok($x->toRooArray($req));
869 $this->jok($x->toArray());
873 $this->loadMap($x, array(
874 'columns' => $_columns,
877 if ($req !== false) {
878 $this->setFilters($x, $req);
879 } else if (method_exists($x, 'applyFilters')) {
880 // always call apply filters even after update/insert...
881 // however arguments are not passed.
882 $x->applyFilters(array('_is_update_request' => true), $this->authUser, $this);
885 // DB_DataObject::DebugLevel(1);
888 $x->setFrom($req['lookup'] );
890 if (!$x->find(true)) {
891 if (!empty($id['_id'])) {
893 $this->jok($x->toArray());
898 } else if (!$x->get($id)) {
899 $this->jerr("selectSingle: no such record ($id)");
902 // ignore perms if comming from update/insert - as it's already done...
903 if ($req !== false && !$this->checkPerm($x,'S')) {
904 $this->jerr("PERMISSION DENIED - si");
906 // different symantics on all these calls??
907 if (method_exists($x, 'toRooSingleArray')) {
908 $this->jok($x->toRooSingleArray($this->authUser, $req));
910 if (method_exists($x, 'toRooArray')) {
911 $this->jok($x->toRooArray($req));
914 $this->jok($x->toArray());
919 function insert($x, $req, $with_perm_check = true)
921 if (method_exists($x, 'setFromRoo')) {
922 $res = $x->setFromRoo($req, $this);
923 if (is_string($res)) {
930 if ( $with_perm_check && !$this->checkPerm($x,'A', $req)) {
931 $this->jerr("PERMISSION DENIED (i)");
933 $cols = $x->tableColumns();
935 if (isset($cols['created'])) {
936 $x->created = date('Y-m-d H:i:s');
938 if (isset($cols['created_dt'])) {
939 $x->created_dt = date('Y-m-d H:i:s');
941 if (isset($cols['created_by'])) {
942 $x->created_by = $this->authUser->id;
945 if (isset($cols['modified'])) {
946 $x->modified = date('Y-m-d H:i:s');
948 if (isset($cols['modified_dt'])) {
949 $x->modified_dt = date('Y-m-d H:i:s');
951 if (isset($cols['modified_by'])) {
952 $x->modified_by = $this->authUser->id;
955 if (isset($cols['updated'])) {
956 $x->updated = date('Y-m-d H:i:s');
958 if (isset($cols['updated_dt'])) {
959 $x->updated_dt = date('Y-m-d H:i:s');
961 if (isset($cols['updated_by'])) {
962 $x->updated_by = $this->authUser->id;
965 if (method_exists($x, 'beforeInsert')) {
966 $x->beforeInsert($_REQUEST, $this);
971 if ($res === false) {
972 $this->jerr($x->_lastError->toString());
974 $ev = $this->addEvent("ADD", $x);
975 if (method_exists($x, 'onInsert')) {
977 $x->onInsert($_REQUEST, $this, $ev);
984 // note setFrom might handle this before hand...!??!
985 if (!empty($_FILES) && method_exists($x, 'onUpload')) {
986 $x->onUpload($this, $_REQUEST);
989 return $this->selectSingle(
990 DB_DataObject::factory($x->tableName()),
996 function updateLock($x, $req )
998 Pman::$permitError = true; // allow it to fail without dieing
1000 $lock = DB_DataObjecT::factory('Core_locking');
1001 Pman::$permitError = false;
1002 if (is_a($lock,'DB_DataObject') && $this->authUser) {
1004 $lock->on_id = $x->{$this->key};
1005 $lock->on_table= strtolower($x->tableName());
1006 if (!empty($_REQUEST['_lock_id'])) {
1007 $lock->whereAdd('id != ' . ((int)$_REQUEST['_lock_id']));
1009 $lock->whereAdd('person_id !=' . $this->authUser->id);
1012 $llc = clone($lock);
1013 $exp = date('Y-m-d', strtotime('NOW - 1 WEEK'));
1014 $llc->whereAdd("created < '$exp'");
1015 if ($llc->count()) {
1017 while($llc->fetch()) {
1018 $llcd = clone($llc);
1024 if ($lock->find(true)) {
1025 // it's locked by someone else..
1026 $p = $lock->person();
1029 $this->jerr( "Record was locked by " . $p->name . " at " .$lock->created.
1030 " - Please confirm you wish to save"
1031 , array('needs_confirm' => true));
1035 // check the users lock.. - no point.. ??? - if there are no other locks and it's not the users, then they can
1036 // edit it anyways...
1038 // can we find the user's lock.
1039 $lock = DB_DataObjecT::factory('Core_locking');
1040 $lock->on_id = $x->{$this->key};
1041 $lock->on_table= strtolower($x->tableName());
1042 $lock->person_id = $this->authUser->id;
1043 $lock->orderBy('created DESC');
1047 $lock->find(true) &&
1048 isset($x->modified_dt) &&
1049 strtotime($x->modified_dt) > strtotime($lock->created) &&
1050 empty($req['_submit_confirmed']) &&
1051 $x->modified_by != $this->authUser->id
1054 $p = DB_DataObject::factory('core_person');
1055 $p->get($x->modified_by);
1056 $this->jerr($p->name . " saved the record since you started editing,\nDo you really want to update it?", array('needs_confirm' => true));
1068 function update($x, $req, $with_perm_check = true)
1070 if ( $with_perm_check && !$this->checkPerm($x,'E', $req) ) {
1071 $this->jerr("PERMISSION DENIED - No Edit permissions on this element");
1074 // check any locks..
1075 // only done if we recieve a lock_id.
1076 // we are very trusing here.. that someone has not messed around with locks..
1077 // the object might want to check in their checkPerm - if locking is essential..
1078 $lock = $this->updateLock($x,$req);
1088 // this lot is generic.. needs moving
1089 if (method_exists($x, 'setFromRoo')) {
1090 $res = $x->setFromRoo($req, $this);
1091 if (is_string($res)) {
1100 //echo '<PRE>';print_r($old);print_r($x);exit;
1103 $cols = $x->tableColumns();
1105 if (isset($cols['modified'])) {
1106 $x->modified = date('Y-m-d H:i:s');
1108 if (isset($cols['modified_dt'])) {
1109 $x->modified_dt = date('Y-m-d H:i:s');
1111 if (isset($cols['modified_by']) && $this->authUser) {
1112 $x->modified_by = $this->authUser->id;
1115 if (isset($cols['updated'])) {
1116 $x->updated = date('Y-m-d H:i:s');
1118 if (isset($cols['updated_dt'])) {
1119 $x->updated_dt = date('Y-m-d H:i:s');
1121 if (isset($cols['updated_by']) && $this->authUser) {
1122 $x->updated_by = $this->authUser->id;
1125 if (method_exists($x, 'beforeUpdate')) {
1126 $x->beforeUpdate($old, $req, $this);
1129 if ($with_perm_check && !empty($_FILES) && method_exists($x, 'onUpload')) {
1130 $x->onUpload($this, $_REQUEST);
1133 //DB_DataObject::DebugLevel(1);
1134 $res = $x->update($old);
1135 if ($res === false) {
1136 $this->jerr($x->_lastError->toString());
1138 $ev = $this->addEvent("EDIT", $x);
1140 if (method_exists($x, 'onUpdate')) {
1141 $x->onUpdate($old, $req, $this, $ev);
1144 $ev->audit($x, $old);
1148 return $this->selectSingle(
1149 DB_DataObject::factory($x->tableName()),
1155 * Delete a number of records.
1156 * calls $delete_obj->beforeDelete($array_of_dependant_dataobjects, $this)
1160 function delete($x, $req)
1162 // do we really delete stuff!?!?!?
1163 if (empty($req['_delete'])) {
1164 $this->jerr("Delete Requested with no value");
1168 // build a list of tables to queriy for dependant data..
1173 $all_links = $x->databaseLinks();
1175 foreach($all_links as $tbl => $links) {
1176 foreach($links as $col => $totbl_col) {
1177 $to = explode(':', $totbl_col);
1178 if ($to[0] != $x->tableName()) {
1182 $affects[$tbl .'.' . $col] = true;
1187 // echo '<PRE>';print_r($affects);exit;
1188 // DB_Dataobject::debugLevel(1);
1193 $bits = array_map(function($v) { return (int)$v; } , explode(',', $req['_delete']));
1195 // let's assume it has a key!!!
1197 $x->whereAdd($this->key .' IN ('. implode(',', $bits) .')');
1199 $this->jerr("Nothing found to delete");
1202 while ($x->fetch()) {
1208 if (!$this->checkPerm($x,'D') ) {
1209 $this->jerr("PERMISSION DENIED (d)");
1212 $match_ar = array();
1213 foreach($affects as $k=> $true) {
1214 $ka = explode('.', $k);
1216 $chk = DB_DataObject::factory($ka[0]);
1217 if (!is_a($chk,'DB_DataObject') && !is_a($chk,'PDO_DataObject')) {
1218 $this->jerr('Unable to load referenced table, check the links config: ' .$ka[0]);
1220 // print_r(array($chk->tablename() , $ka[1] , $xx->tablename() , $this->key ));
1221 $chk->{$ka[1]} = $xx->{$this->key};
1223 if (count($chk->keys())) {
1224 $matches = $chk->count();
1226 //DB_DataObject::DebugLevel(1);
1227 $matches = $chk->count($ka[1]);
1231 $chk->_match_key = $ka[1];
1232 $match_ar[] = clone($chk);
1238 $has_beforeDelete = method_exists($xx, 'beforeDelete');
1239 // before delte = allows us to trash dependancies if needed..
1242 if ( $has_beforeDelete ) {
1243 if ($xx->beforeDelete($match_ar, $this) === false) {
1244 $errs[] = "Delete failed ({$xx->id})\n".
1245 (isset($xx->err) ? $xx->err : '');
1248 // refetch affects..
1250 $match_ar = array();
1251 foreach($affects as $k=> $true) {
1252 $ka = explode('.', $k);
1253 $chk = DB_DataObject::factory($ka[0]);
1254 if (!is_a($chk,'DB_DataObject') && !is_a($chk,'PDO_DataObject')) {
1255 $this->jerr('Unable to load referenced table, check the links config: ' .$ka[0]);
1257 $chk->{$ka[1]} = $xx->{$this->key};
1258 $matches = $chk->count();
1259 $match_total += $matches;
1261 $chk->_match_key = $ka[1];
1262 $match_ar[] = clone($chk);
1269 if (!empty($match_ar)) {
1270 $chk = $match_ar[0];
1272 $o = $chk->fetchAll();
1273 $key = isset($chk->_match_key) ?$chk->_match_key : '?unknown column?';
1274 $desc = $chk->tableName(). '.' . $key .'='.$xx->{$this->key} ;
1275 if (method_exists($chk, 'toEventString')) {
1276 $desc .= ' : ' . $o[0]->toEventString();
1278 $this->jerr("Delete Dependant records ($match_total found), " .
1279 "first is ( $desc )");
1285 DB_DataObject::Factory('Events')->logDeletedRecord($x);
1287 $this->addEvent("DELETE", $x);
1291 if (method_exists($xx,'onDelete')) {
1292 $xx->onDelete($req, $this);
1298 $this->jerr(implode("\n<BR>", $errs));
1300 $this->jok("Deleted");
1306 * cols stores the list of columns that are available from the query.
1309 * This is a dupe of what is in autojoin -- we should move to using autojoin really.
1321 var $cols = array();
1325 function loadMap($do, $cfg =array()) //$onlycolumns=false, $distinct = false)
1328 //DB_DataObject::debugLevel(5);
1329 $onlycolumns = !empty($cfg['columns']) ? $cfg['columns'] : false;
1330 $distinct = !empty($cfg['distinct']) ? $cfg['distinct'] : false;
1331 $excludecolumns = !empty($cfg['exclude']) ? $cfg['exclude'] : array();
1333 $excludecolumns[] = 'passwd'; // we never expose passwords
1334 $excludecolumns[] = 'oath_key';
1336 $ret = $do->autoJoin(array(
1337 'include' => $onlycolumns,
1338 'exclude' => $excludecolumns,
1339 'distinct' => $distinct
1342 $this->countWhat = $ret['count'];
1343 $this->cols = $ret['cols'];
1344 $this->colsJname = $ret['join_names'];
1353 * generate the meta data neede by queries.
1356 function meta($x, $data)
1358 // this is not going to work on queries where the data does not match the database def..
1359 // for unknown columns we send them as stirngs..
1361 $cols = array_keys($data[0]);
1365 if (class_exists('PDO_DataObject')) {
1366 $options = PDO_DataObject::config();
1367 if (!file_exists($options["schema_location"] . '.reader')) {
1371 $rdata = unserialize(file_get_contents($options["schema_location"] . '.reader'));
1374 //echo '<PRE>';print_r($this->cols); exit;
1375 $options = &PEAR::getStaticProperty('DB_DataObject','options');
1376 $reader = $options["ini_{$x->databaseNickname()}"] .'.reader';
1377 if (!file_exists( $reader )) {
1381 $rdata = unserialize(file_get_contents($reader));
1384 //echo '<PRE>';print_r($this->cols);exit;
1385 //echo '<PRE>';print_r($rdata);exit;
1386 // echo '<PRE>';print_r($rdata);exit;
1389 $key = empty($keys) ? 'id' : $keys[0];
1393 foreach($cols as $c ) {
1394 if (!isset($this->cols[$c]) || !isset($rdata[$this->cols[$c]]) || !is_array($rdata[$this->cols[$c]])) {
1398 $add = $rdata[$this->cols[$c]];
1403 'totalProperty' => 'total',
1404 'successProperty' => 'success',
1406 'id' => $key, // was 'id'...
1413 function setFilters($x, $q)
1415 // if a column is type int, and we get ',' -> the it should be come an inc clause..
1416 // DB_DataObject::debugLevel(1);
1417 if (method_exists($x, 'applyFilters')) {
1418 // DB_DataObject::debugLevel(1);
1419 if (false === $x->applyFilters($q, $this->authUser, $this)) {
1423 $q_filtered = array();
1427 foreach($q as $key=>$val) {
1429 if (in_array($key,$keys) && !is_array($val)) {
1434 // handles name[]=fred&name[]=brian => name in ('fred', 'brian').
1435 // value is an array..
1436 if (is_array($val) ) {
1440 if ($key[0] == '!') {
1442 $key = substr($key,1);
1445 if (!in_array( $key, array_keys($this->cols))) {
1449 // support a[0] a[1] ..... => whereAddIn(
1452 foreach($val as $k=>$v) {
1453 if (!is_numeric($k)) {
1457 // FIXME: note this is not typesafe for anything other than mysql..
1459 if (!is_numeric($v) || !is_long($v)) {
1468 $x->whereAddIn($pref . (
1469 isset($this->colsJname[$key]) ?
1470 $this->colsJname[$key] :
1471 ($x->tableName(). '.'.$key)),
1472 $ar, $quote ? 'string' : 'int');
1479 // handles !name=fred => name not equal fred.
1480 if ($key[0] == '!' && in_array(substr($key, 1), array_keys($this->cols))) {
1482 $key = substr($key, 1) ;
1485 isset($this->colsJname[$key]) ?
1486 $this->colsJname[$key] :
1487 $x->tableName(). '.'.$key ) . ' != ' .
1488 (is_numeric($val) ? $val : "'". $x->escape($val) . "'")
1498 // Events and remarks -- fixme - move to events/remarsk...
1499 case 'on_id': // where TF is this used...
1500 if (!empty($q['query']['original'])) {
1501 // DB_DataObject::debugLevel(1);
1502 $o = (int) $q['query']['original'];
1504 $x->whereAdd("(on_id = $oid OR
1505 on_id IN ( SELECT distinct(id) FROM Documents WHERE original = $o )
1514 if (strlen($val) && $key[0] != '_') {
1515 $q_filtered[$key] = $val;
1518 // subjoined columns = check the values.
1519 // note this is not typesafe for anything other than mysql..
1521 if (isset($this->colsJname[$key])) {
1523 // the aobve rule for !strlen non-joined cols should apply to joined ones.
1524 if (!strlen($val)) {
1530 if (!is_numeric($val) || !is_long($val)) {
1533 $x->whereAdd( "{$this->colsJname[$key]} = " . ($quote ? "'". $x->escape($val) ."'" : $val));
1541 if (!empty($q_filtered)) {
1542 //var_dump($q_filtered);
1546 $x->setFrom($q_filtered);
1552 // nice generic -- let's get rid of it.. where is it used!!!!
1554 // Person / Group / Comapnies.... most of my queries noww...
1556 if (!empty($q['query']['name'])) {
1559 if (in_array( 'name', array_keys($x->table()))) {
1560 $x->whereAdd($x->tableName().".name LIKE '". $x->escape($q['query']['name']) . "%'");
1565 // - projectdirectory staff list - persn queuy
1570 * create the dataobject from (usually the url)
1571 * This uses $this->validTables
1572 * $this->validPrefix (later..)
1573 * to determine if class can be created..
1577 function dataObject($tab)
1579 if (is_array($this->validTables) && !in_array($tab,$this->validTables)) {
1580 $this->jerr("Invalid url - not listed in validTables");
1582 $tab = str_replace('/', '',$tab); // basic protection??
1584 $pm = HTML_FlexyFramework::get()->Pman;
1586 if (isset($pm['roo_alias'])) {
1587 $map = array_flip($pm['roo_alias']);
1588 if (isset($map[$tab])) {
1594 $x = DB_DataObject::factory($tab);
1596 if (!is_a($x, 'DB_DataObject') && !is_a($x, 'PDO_DataObject')) {
1597 $this->jerr('invalid url - no dataobject');