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']) ? 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);
278 // var_dump($total);exit;
279 $this->applySort($x);
283 if (!empty($_REQUEST['_distinct']) && $total !== false && $total < 400) {
290 empty($_REQUEST['start']) ? 0 : (int)$_REQUEST['start'],
291 min(empty($_REQUEST['limit']) ? 25 : (int)$_REQUEST['limit'], $this->max_limit)
294 $queryObj = clone($x);
295 //DB_DataObject::debuglevel(1);
297 $this->sessionState(0);
299 $this->sessionState(1);
301 if (false === $res) {
302 $this->jerr($x->_lastError->toString());
310 // ---------------- THESE ARE DEPRICATED.. they should be moved to the model...
313 if (!empty($_REQUEST['query']['add_blank'])) {
314 $ret[] = array( 'id' => 0, 'name' => '----');
315 $total === false ? false : $total+1;
318 $rooar = method_exists($x, 'toRooArray');
319 $_columnsf = $_columns ? array_flip($_columns) : false;
320 while ($x->fetch()) {
322 $add = $rooar ? $x->toRooArray($_REQUEST) : $x->toArray();
323 if ($add === false) {
326 $ret[] = !$_columns ? $add : array_intersect_key($add, $_columnsf);
330 $ret = array_slice($ret,
331 empty($_REQUEST['start']) ? 0 : (int)$_REQUEST['start'],
332 min(empty($_REQUEST['limit']) ? 25 : (int)$_REQUEST['limit'], 10000)
339 if (method_exists($queryObj ,'postListExtra')) {
340 $extra = $queryObj->postListExtra($_REQUEST, $this, $ret);
344 // filter results, and add any data that is needed...
345 if (method_exists($x,'postListFilter')) {
346 $ret = $x->postListFilter($ret, $this->authUser, $_REQUEST);
351 if (!empty($_REQUEST['csvCols']) && !empty($_REQUEST['csvTitles']) ) {
354 $this->toCsv($ret, $_REQUEST['csvCols'], $_REQUEST['csvTitles'],
355 empty($_REQUEST['csvFilename']) ? '' : $_REQUEST['csvFilename'] );
362 if (!empty($_REQUEST['_requestMeta']) && count($ret)) {
363 $meta = $this->meta($x, $ret);
365 $extra = $extra ? $extra: array();
366 $extra['metaData'] = $meta;
369 // this make take some time...
370 $this->sessionState(0);
371 // echo "<PRE>"; print_r($ret);
372 $this->jdata($ret, max(count($ret), $total === false ? 0 : $total), $extra );
376 function checkDebug($req = false)
378 $req = $req === false ? $_REQUEST : $req;
380 if (empty($req['_debug'])) {
384 if (!empty($_SERVER['HTTP_HOST']) && $_SERVER['HTTP_HOST'] == 'localhost') {
385 DB_DAtaObject::debuglevel((int)$req['_debug']);
393 method_exists($this->authUser,'canDebug')
395 $this->authUser->canDebug()
400 method_exists($this->authUser,'groups')
402 is_a($this->authUser, 'Pman_Core_DataObjects_Core_person')
404 in_array('Administrators', $this->authUser->groups('name'))
409 DB_DAtaObject::debuglevel((int)$req['_debug']);
414 function checkDebugPost()
416 if (empty($_GET['_post']) && empty($_GET['_debug_post'])) {
419 // localhost can do anything...
420 if (!empty($_SERVER['HTTP_HOST']) && $_SERVER['HTTP_HOST'] == 'localhost') {
423 return $this->authUser &&
424 method_exists($this->authUser,'groups') &&
425 in_array('Administrators', $this->authUser->groups('name'));
429 function checkPerm($obj, $lvl, $req= null)
431 if (!method_exists($obj, 'checkPerm')) {
434 if ($obj->checkPerm($lvl, $this->authUser, $req)) {
440 function toCsv($data, $cols, $titles, $filename, $addDate = true)
443 $this->sessionState(0); // turn off sessions - no locking..
445 require_once 'Pman/Core/SimpleExcel.php';
447 $fn = (empty($filename) ? 'list-export-' : urlencode($filename)) . (($addDate) ? date('Y-m-d') : '') ;
451 'workbook' => substr($fn, 0, 31),
458 if (is_object($data)) {
459 $rooar = method_exists($data, 'toRooArray');
460 while($data->fetch()) {
461 $x = $rooar ? $data->toRooArray($q) : $data->toArray();
463 if ($cols == '*') { /// did we get cols sent to us?
464 $cols = array_keys($x);
467 if(!is_array($cols)) {
468 $cols = explode(',', $cols);
471 if ($titles !== false) {
473 $titles= array_keys($x);
475 if(!is_array($titles)) {
476 $titles = explode(',', $titles);
478 foreach($cols as $i=>$col) {
480 'header'=> isset($titles[$i]) ? $titles[$i] : $col,
483 // 'renderer' => array($this, 'getThumb'),
484 // 'color' => 'yellow', // set color for the cell which is a header element
485 // 'fillBlank' => 'gray', // set
488 if (method_exists($data, 'toSimpleExcelColumn')) {
489 $add = $data->toSimpleExcelColumn($add);
492 $se_config['cols'][] = $add;
497 $se = new Pman_Core_SimpleExcel(array(), $se_config);
503 $se->addLine($se_config['workbook'], $x);
509 $this->jerr('no data found', false, 'text/plain');
511 $se->send($fn .'.xls');
516 foreach($data as $x) {
517 //echo "<PRE>"; print_r(array($_REQUEST['csvCols'], $x->toArray())); exit;
521 $cols= array_keys($x);
524 if(!is_array($cols)) {
525 $cols = explode(',', $cols);
528 if ($titles !== false) {
530 $titles= array_keys($x);
533 if(!is_array($titles)) {
534 $titles = explode(',', $titles);
537 foreach($cols as $i=>$col) {
539 'header'=> isset($titles[$i]) ? $titles[$i] : $col,
542 // 'renderer' => array($this, 'getThumb'),
543 // 'color' => 'yellow', // set color for the cell which is a header element
544 // 'fillBlank' => 'gray', // set
547 if (!empty($this->do) && method_exists($this->do, 'toSimpleExcelColumn')) {
548 $add = $this->do->toSimpleExcelColumn($add);
551 $se_config['cols'][] = $add;
556 $se = new Pman_Core_SimpleExcel(array(),$se_config);
559 //fputcsv($fh, $titles);
563 $se->addLine($se_config['workbook'], $x);
567 $this->jerr('no data found');
570 $se->send($fn .'.xls');
577 * POST method Roo/TABLENAME
578 * -- creates, updates, or deletes data.
581 * if the primary key is empty, this happens
582 * will automatically set these to current date and authUser->id
583 * created, created_by, created_dt
584 * updated, update_by, updated_dt
585 * modified, modified_by, modified_dt
587 * will return a GET request SINGLE SELECT (and accepts same)
590 * _delete=1,2,3 delete a set of data.
592 * if the primary key value is set, then update occurs.
593 * will automatically set these to current date and authUser->id
594 * updated, update_by, updated_dt
595 * modified, modified_by, modified_dt
599 * _delete=1,2,3 causes a delete to occur.
600 * _ids=1,2,3,4 causes update to occur on all primary ids.
603 * = same as single SELECT GET request..
608 * _debug=1 forces debug
609 * _get=1 - causes a get request to occur when doing a POST..
613 * these methods on dataobjects if they exist
615 * checkPerm('E' / 'D' , $authuser)
616 * - can we list the stuff
617 * - return false to disallow...
619 * toRooSingleArray($authUser, $request) : array
620 * - called on single fetch only, add or maniuplate returned array data.
621 * toRooArray($request) : array
622 * - Called if toSingleArray does not exist.
623 * - if you need to return different data than toArray..
626 * (for logging - this is generically prefixed to all database operations.)
630 * called when $_FILES is not empty
633 * setFromRoo($ar, $roo)
634 * - alternative to setFrom() which is called if this method does not exist
635 * - values from post (deal with dates etc.) - return true|error string.
636 * - call $roo->jerr() on failure...
638 * CALLS BEFORE change occurs:
640 * beforeDelete($dependants_array, $roo)
641 * Argument is an array of un-find/fetched dependant items.
642 * - jerr() will stop insert.. (Prefered)
643 * - return false for fail and set DO->err;
645 * beforeUpdate($old, $request,$roo)
646 * - before update - jerr() will stop insert..
647 * beforeInsert($request,$roo)
648 * - before insert - jerr() will stop insert..
651 * CALLS AFTER change occured
653 * onUpdate($old, $request,$roo)
654 * - after update // return value ignored
656 * onInsert($request,$roo)
659 * onDelete($request, $roo) - after delete
663 function post($tab) // update / insert (?? delete??)
665 // -- why was this put in? - Roo is not related to Core.All ?
666 //if (!$this->hasPerm("Core.All", 'E')) {
667 // $this->jerr("PERMISSION DENIED (e)");
669 $this->initErrorHandling();
671 // DB_DataObject::debugLevel(1);
674 if (!empty($_REQUEST['_get'])) {
675 return $this->get($tab);
678 $this->init(); // for pman.
680 $x = $this->dataObject($tab);
682 $this->transObj = clone($x);
684 $this->transObj->query('BEGIN');
685 // find the key and use that to get the thing..
688 $this->jerr('no key');
691 $this->key = $keys[0];
693 // delete should be here...
694 if (isset($_REQUEST['_delete'])) {
695 // do we really delete stuff!?!?!?
696 return $this->delete($x,$_REQUEST);
704 // not sure if this is a good idea here...
706 if (!empty($_REQUEST['_ids'])) {
707 $ids = explode(',',$_REQUEST['_ids']);
708 $x->whereAddIn($this->key, $ids, 'int');
709 $ar = $x->fetchAll();
712 $this->update($x, $_REQUEST);
715 $this->jok("UPDATED");
720 if (!empty($_REQUEST[$this->key])) {
722 if (!$x->get($this->key, $_REQUEST[$this->key])) {
723 $this->jerr("Invalid request (id does not point to a record.)");
725 $this->jok($this->update($x, $_REQUEST));
729 $this->jerr("No data recieved for inserting");
732 $this->jok($this->insert($x, $_REQUEST));
744 * apply REQUEST[sort] and [dir]
745 * sort may be an array of columsn..
747 * @arg DB_DataObject $x
750 function applySort($x, $sort = '', $dir ='')
753 // Db_DataObject::debugLevel(1);
754 $sort = empty($_REQUEST['sort']) ? $sort : $_REQUEST['sort'];
755 $dir = empty($_REQUEST['dir']) ? $dir : $_REQUEST['dir'];
756 $dir = $dir == 'ASC' ? 'ASC' : 'DESC';
758 $ms = empty($_REQUEST['_multisort']) ? false : $_REQUEST['_multisort'];
759 //var_Dump($ms);exit;
761 if (method_exists($x, 'applySort')) {
762 $sorted = $x->applySort(
766 array_keys($this->cols),
767 $ms ? json_decode($ms) : false
772 return $this->multiSort($x);
775 if ($sorted === false) {
776 $cols = $x->tableColumns();
777 $excols = array_keys($this->cols);
779 if (isset($x->_extra_cols)) {
780 $excols = array_merge($excols, $x->_extra_cols);
782 $sort_ar = explode(',', $sort);
785 foreach($sort_ar as $sort) {
787 if (strlen($sort) && isset($cols[$sort]) ) {
788 $sort_str[] = $x->tableName() .'.'.$sort . ' ' . $dir ;
790 } else if (in_array($sort, $excols)) {
791 $sort_str[] = $sort . ' ' . $dir ;
796 $x->orderBy(implode(', ', $sort_str ));
807 function multiSort($x)
809 //DB_DataObject::debugLevel(1);
810 $ms = json_decode($_REQUEST['_multisort']);
811 if (!isset($ms->order) || !is_array($ms->order)) {
816 $cols = $x->tableColumns();
818 //print_r($this->cols);exit;
819 // this-><cols contains colname => aliased name...
820 foreach($ms->order as $col) {
821 if (!isset($ms->sort->{$col})) {
822 continue; // no direction..
824 $ms->sort->{$col} = $ms->sort->{$col} == 'ASC' ? 'ASC' : 'DESC';
826 if (strlen($col) && isset($cols[$col]) ) {
827 $sort_str[] = $x->tableName() .'.'.$col . ' ' . $ms->sort->{$col};
830 //print_r($this->cols);
832 if (in_array($col, array_keys($this->cols))) {
833 $sort_str[] = $col. ' ' . $ms->sort->{$col};
836 if (isset($x->_extra_cols) && in_array($col, $x->_extra_cols)) {
837 $sort_str[] = $col. ' ' . $ms->sort->{$col};
842 $x->orderBy(implode(', ', $sort_str ));
849 * - used when _id is set, or after insert or update
851 * @param DataObject $x the dataobject to use
852 * @param int $id the pid of the object
853 * @param array $req the request, or false if it comes from insert/update.
856 function selectSingle($x, $id, $req=false)
860 $_columns = !empty($req['_columns']) ? explode(',', $req['_columns']) : false;
862 //var_dump(array(!is_array($id) , empty($id)));
863 if (!is_array($id) && empty($id)) {
866 if (method_exists($x, 'toRooSingleArray')) {
867 $this->jok($x->toRooSingleArray($this->authUser, $req));
869 if (method_exists($x, 'toRooArray')) {
870 $this->jok($x->toRooArray($req));
873 $this->jok($x->toArray());
877 $this->loadMap($x, array(
878 'columns' => $_columns,
881 if ($req !== false) {
882 $this->setFilters($x, $req);
883 } else if (method_exists($x, 'applyFilters')) {
884 // always call apply filters even after update/insert...
885 // however arguments are not passed.
886 $x->applyFilters(array('_is_update_request' => true), $this->authUser, $this);
889 // DB_DataObject::DebugLevel(1);
892 $x->setFrom($req['lookup'] );
894 if (!$x->find(true)) {
895 if (!empty($id['_id'])) {
897 $this->jok($x->toArray());
902 } else if (!$x->get($id)) {
903 $this->jerr("selectSingle: no such record ($id)");
906 // ignore perms if comming from update/insert - as it's already done...
907 if ($req !== false && !$this->checkPerm($x,'S')) {
908 $this->jerr("PERMISSION DENIED - si");
910 // different symantics on all these calls??
911 if (method_exists($x, 'toRooSingleArray')) {
912 $this->jok($x->toRooSingleArray($this->authUser, $req));
914 if (method_exists($x, 'toRooArray')) {
915 $this->jok($x->toRooArray($req));
917 $this->jok($x->toArray());
922 function insert($x, $req, $with_perm_check = true)
924 if (method_exists($x, 'setFromRoo')) {
925 $res = $x->setFromRoo($req, $this);
926 if (is_string($res)) {
933 if ( $with_perm_check && !$this->checkPerm($x,'A', $req)) {
934 $this->jerr("PERMISSION DENIED (i)");
936 $cols = $x->tableColumns();
938 if (isset($cols['created'])) {
939 $x->created = date('Y-m-d H:i:s');
941 if (isset($cols['created_dt'])) {
942 $x->created_dt = date('Y-m-d H:i:s');
944 if (isset($cols['created_by'])) {
945 $x->created_by = $this->authUser->id;
948 if (isset($cols['modified'])) {
949 $x->modified = date('Y-m-d H:i:s');
951 if (isset($cols['modified_dt'])) {
952 $x->modified_dt = date('Y-m-d H:i:s');
954 if (isset($cols['modified_by'])) {
955 $x->modified_by = $this->authUser->id;
958 if (isset($cols['updated'])) {
959 $x->updated = date('Y-m-d H:i:s');
961 if (isset($cols['updated_dt'])) {
962 $x->updated_dt = date('Y-m-d H:i:s');
964 if (isset($cols['updated_by'])) {
965 $x->updated_by = $this->authUser->id;
968 if (method_exists($x, 'beforeInsert')) {
969 $x->beforeInsert($_REQUEST, $this);
974 if ($res === false) {
975 $this->jerr($x->_lastError->toString());
977 $ev = $this->addEvent("ADD", $x);
978 if (method_exists($x, 'onInsert')) {
980 $x->onInsert($_REQUEST, $this, $ev);
987 // note setFrom might handle this before hand...!??!
988 if (!empty($_FILES) && method_exists($x, 'onUpload')) {
989 $x->onUpload($this, $_REQUEST);
992 return $this->selectSingle(
993 DB_DataObject::factory($x->tableName()),
999 function updateLock($x, $req )
1001 Pman::$permitError = true; // allow it to fail without dieing
1003 $lock = DB_DataObjecT::factory('Core_locking');
1004 Pman::$permitError = false;
1005 if (is_a($lock,'DB_DataObject') && $this->authUser) {
1007 $lock->on_id = $x->{$this->key};
1008 $lock->on_table= strtolower($x->tableName());
1009 if (!empty($_REQUEST['_lock_id'])) {
1010 $lock->whereAdd('id != ' . ((int)$_REQUEST['_lock_id']));
1012 $lock->whereAdd('person_id !=' . $this->authUser->id);
1015 $llc = clone($lock);
1016 $exp = date('Y-m-d', strtotime('NOW - 1 WEEK'));
1017 $llc->whereAdd("created < '$exp'");
1018 if ($llc->count()) {
1020 while($llc->fetch()) {
1021 $llcd = clone($llc);
1027 if ($lock->find(true)) {
1028 // it's locked by someone else..
1029 $p = $lock->person();
1032 $this->jerr( "Record was locked by " . $p->name . " at " .$lock->created.
1033 " - Please confirm you wish to save"
1034 , array('needs_confirm' => true));
1038 // check the users lock.. - no point.. ??? - if there are no other locks and it's not the users, then they can
1039 // edit it anyways...
1041 // can we find the user's lock.
1042 $lock = DB_DataObjecT::factory('Core_locking');
1043 $lock->on_id = $x->{$this->key};
1044 $lock->on_table= strtolower($x->tableName());
1045 $lock->person_id = $this->authUser->id;
1046 $lock->orderBy('created DESC');
1050 $lock->find(true) &&
1051 isset($x->modified_dt) &&
1052 strtotime($x->modified_dt) > strtotime($lock->created) &&
1053 empty($req['_submit_confirmed']) &&
1054 $x->modified_by != $this->authUser->id
1057 $p = DB_DataObject::factory('core_person');
1058 $p->get($x->modified_by);
1059 $this->jerr($p->name . " saved the record since you started editing,\nDo you really want to update it?", array('needs_confirm' => true));
1071 function update($x, $req, $with_perm_check = true)
1073 if ( $with_perm_check && !$this->checkPerm($x,'E', $req) ) {
1074 $this->jerr("PERMISSION DENIED - No Edit permissions on this element");
1077 // check any locks..
1078 // only done if we recieve a lock_id.
1079 // we are very trusing here.. that someone has not messed around with locks..
1080 // the object might want to check in their checkPerm - if locking is essential..
1081 $lock = $this->updateLock($x,$req);
1091 // this lot is generic.. needs moving
1092 if (method_exists($x, 'setFromRoo')) {
1093 $res = $x->setFromRoo($req, $this);
1094 if (is_string($res)) {
1103 //echo '<PRE>';print_r($old);print_r($x);exit;
1106 $cols = $x->tableColumns();
1108 if (isset($cols['modified'])) {
1109 $x->modified = date('Y-m-d H:i:s');
1111 if (isset($cols['modified_dt'])) {
1112 $x->modified_dt = date('Y-m-d H:i:s');
1114 if (isset($cols['modified_by']) && $this->authUser) {
1115 $x->modified_by = $this->authUser->id;
1118 if (isset($cols['updated'])) {
1119 $x->updated = date('Y-m-d H:i:s');
1121 if (isset($cols['updated_dt'])) {
1122 $x->updated_dt = date('Y-m-d H:i:s');
1124 if (isset($cols['updated_by']) && $this->authUser) {
1125 $x->updated_by = $this->authUser->id;
1128 if (method_exists($x, 'beforeUpdate')) {
1129 $x->beforeUpdate($old, $req, $this);
1132 if ($with_perm_check && !empty($_FILES) && method_exists($x, 'onUpload')) {
1133 $x->onUpload($this, $_REQUEST);
1136 //DB_DataObject::DebugLevel(1);
1137 $res = $x->update($old);
1138 if ($res === false) {
1139 $this->jerr($x->_lastError->toString());
1141 $ev = $this->addEvent("EDIT", $x);
1143 if (method_exists($x, 'onUpdate')) {
1144 $x->onUpdate($old, $req, $this, $ev);
1147 $ev->audit($x, $old);
1151 return $this->selectSingle(
1152 DB_DataObject::factory($x->tableName()),
1158 * Delete a number of records.
1159 * calls $delete_obj->beforeDelete($array_of_dependant_dataobjects, $this)
1163 function delete($x, $req)
1165 // do we really delete stuff!?!?!?
1166 if (empty($req['_delete'])) {
1167 $this->jerr("Delete Requested with no value");
1171 // build a list of tables to queriy for dependant data..
1176 $all_links = $x->databaseLinks();
1178 foreach($all_links as $tbl => $links) {
1179 foreach($links as $col => $totbl_col) {
1180 $to = explode(':', $totbl_col);
1181 if ($to[0] != $x->tableName()) {
1185 $affects[$tbl .'.' . $col] = true;
1190 // echo '<PRE>';print_r($affects);exit;
1191 // DB_Dataobject::debugLevel(1);
1196 $bits = array_map(function($v) { return (int)$v; } , explode(',', $req['_delete']));
1198 // let's assume it has a key!!!
1200 $x->whereAdd($this->key .' IN ('. implode(',', $bits) .')');
1202 $this->jerr("Nothing found to delete");
1205 while ($x->fetch()) {
1211 if (!$this->checkPerm($x,'D') ) {
1212 $this->jerr("PERMISSION DENIED (d)");
1215 $match_ar = array();
1216 foreach($affects as $k=> $true) {
1217 $ka = explode('.', $k);
1219 $chk = DB_DataObject::factory($ka[0]);
1220 if (!is_a($chk,'DB_DataObject') && !is_a($chk,'PDO_DataObject')) {
1221 $this->jerr('Unable to load referenced table, check the links config: ' .$ka[0]);
1223 // print_r(array($chk->tablename() , $ka[1] , $xx->tablename() , $this->key ));
1224 $chk->{$ka[1]} = $xx->{$this->key};
1226 if (count($chk->keys())) {
1227 $matches = $chk->count();
1229 //DB_DataObject::DebugLevel(1);
1230 $matches = $chk->count($ka[1]);
1234 $chk->_match_key = $ka[1];
1235 $match_ar[] = clone($chk);
1241 $has_beforeDelete = method_exists($xx, 'beforeDelete');
1242 // before delte = allows us to trash dependancies if needed..
1245 if ( $has_beforeDelete ) {
1246 if ($xx->beforeDelete($match_ar, $this, $_REQUEST) === false) {
1247 $errs[] = "Delete failed ({$xx->id})\n".
1248 (isset($xx->err) ? $xx->err : '');
1251 // refetch affects..
1253 $match_ar = array();
1254 foreach($affects as $k=> $true) {
1255 $ka = explode('.', $k);
1256 $chk = DB_DataObject::factory($ka[0]);
1257 if (!is_a($chk,'DB_DataObject') && !is_a($chk,'PDO_DataObject')) {
1258 $this->jerr('Unable to load referenced table, check the links config: ' .$ka[0]);
1260 $chk->{$ka[1]} = $xx->{$this->key};
1261 $matches = $chk->count();
1262 $match_total += $matches;
1264 $chk->_match_key = $ka[1];
1265 $match_ar[] = clone($chk);
1272 if (!empty($match_ar)) {
1273 $chk = $match_ar[0];
1275 $o = $chk->fetchAll();
1276 $key = isset($chk->_match_key) ?$chk->_match_key : '?unknown column?';
1277 $desc = $chk->tableName(). '.' . $key .'='.$xx->{$this->key} ;
1278 if (method_exists($chk, 'toEventString')) {
1279 $desc .= ' : ' . $o[0]->toEventString();
1281 $this->jerr("Delete Dependant records ($match_total found), " .
1282 "first is ( $desc )");
1288 DB_DataObject::Factory('Events')->logDeletedRecord($x);
1290 $this->addEvent("DELETE", $x);
1294 if (method_exists($xx,'onDelete')) {
1295 $xx->onDelete($req, $this);
1301 $this->jerr(implode("\n<BR>", $errs));
1303 $this->jok("Deleted");
1309 * cols stores the list of columns that are available from the query.
1312 * This is a dupe of what is in autojoin -- we should move to using autojoin really.
1324 var $cols = array();
1328 function loadMap($do, $cfg =array()) //$onlycolumns=false, $distinct = false)
1331 //DB_DataObject::debugLevel(5);
1332 $onlycolumns = !empty($cfg['columns']) ? $cfg['columns'] : false;
1333 $distinct = !empty($cfg['distinct']) ? $cfg['distinct'] : false;
1334 $excludecolumns = !empty($cfg['exclude']) ? $cfg['exclude'] : array();
1336 $excludecolumns[] = 'passwd'; // we never expose passwords
1337 $excludecolumns[] = 'oath_key';
1339 $ret = $do->autoJoin(array(
1340 'include' => $onlycolumns,
1341 'exclude' => $excludecolumns,
1342 'distinct' => $distinct
1345 $this->countWhat = $ret['count'];
1346 $this->cols = $ret['cols'];
1347 $this->colsJname = $ret['join_names'];
1356 * generate the meta data neede by queries.
1359 function meta($x, $data)
1361 // this is not going to work on queries where the data does not match the database def..
1362 // for unknown columns we send them as stirngs..
1364 $cols = array_keys($data[0]);
1368 if (class_exists('PDO_DataObject')) {
1369 $options = PDO_DataObject::config();
1370 if (!file_exists($options["schema_location"] . '.reader')) {
1374 $rdata = unserialize(file_get_contents($options["schema_location"] . '.reader'));
1377 //echo '<PRE>';print_r($this->cols); exit;
1378 $options = &PEAR::getStaticProperty('DB_DataObject','options');
1379 $reader = $options["ini_{$x->databaseNickname()}"] .'.reader';
1380 if (!file_exists( $reader )) {
1384 $rdata = unserialize(file_get_contents($reader));
1387 //echo '<PRE>';print_r($this->cols);exit;
1388 //echo '<PRE>';print_r($rdata);exit;
1389 // echo '<PRE>';print_r($rdata);exit;
1392 $key = empty($keys) ? 'id' : $keys[0];
1396 foreach($cols as $c ) {
1397 if (!isset($this->cols[$c]) || !isset($rdata[$this->cols[$c]]) || !is_array($rdata[$this->cols[$c]])) {
1401 $add = $rdata[$this->cols[$c]];
1406 'totalProperty' => 'total',
1407 'successProperty' => 'success',
1409 'id' => $key, // was 'id'...
1416 function setFilters($x, $q)
1418 // if a column is type int, and we get ',' -> the it should be come an inc clause..
1419 // DB_DataObject::debugLevel(1);
1420 if (method_exists($x, 'applyFilters')) {
1421 // DB_DataObject::debugLevel(1);
1422 if (false === $x->applyFilters($q, $this->authUser, $this)) {
1426 $q_filtered = array();
1430 foreach($q as $key=>$val) {
1432 if (in_array($key,$keys) && !is_array($val)) {
1437 // handles name[]=fred&name[]=brian => name in ('fred', 'brian').
1438 // value is an array..
1439 if (is_array($val) ) {
1443 if ($key[0] == '!') {
1445 $key = substr($key,1);
1448 if (!in_array( $key, array_keys($this->cols))) {
1452 // support a[0] a[1] ..... => whereAddIn(
1455 foreach($val as $k=>$v) {
1456 if (!is_numeric($k)) {
1460 // FIXME: note this is not typesafe for anything other than mysql..
1462 if (!is_numeric($v) || !is_long($v)) {
1471 $x->whereAddIn($pref . (
1472 isset($this->colsJname[$key]) ?
1473 $this->colsJname[$key] :
1474 ($x->tableName(). '.'.$key)),
1475 $ar, $quote ? 'string' : 'int');
1482 // handles !name=fred => name not equal fred.
1483 if ($key[0] == '!' && in_array(substr($key, 1), array_keys($this->cols))) {
1485 $key = substr($key, 1) ;
1488 isset($this->colsJname[$key]) ?
1489 $this->colsJname[$key] :
1490 $x->tableName(). '.'.$key ) . ' != ' .
1491 (is_numeric($val) ? $val : "'". $x->escape($val) . "'")
1501 // Events and remarks -- fixme - move to events/remarsk...
1502 case 'on_id': // where TF is this used...
1503 if (!empty($q['query']['original'])) {
1504 // DB_DataObject::debugLevel(1);
1505 $o = (int) $q['query']['original'];
1507 $x->whereAdd("(on_id = $oid OR
1508 on_id IN ( SELECT distinct(id) FROM Documents WHERE original = $o )
1517 if (strlen($val) && $key[0] != '_') {
1518 $q_filtered[$key] = $val;
1521 // subjoined columns = check the values.
1522 // note this is not typesafe for anything other than mysql..
1524 if (isset($this->colsJname[$key])) {
1526 // the aobve rule for !strlen non-joined cols should apply to joined ones.
1527 if (!strlen($val)) {
1533 if (!is_numeric($val) || !is_long($val)) {
1536 $x->whereAdd( "{$this->colsJname[$key]} = " . ($quote ? "'". $x->escape($val) ."'" : $val));
1544 if (!empty($q_filtered)) {
1545 //var_dump($q_filtered);
1549 $x->setFrom($q_filtered);
1555 // nice generic -- let's get rid of it.. where is it used!!!!
1557 // Person / Group / Comapnies.... most of my queries noww...
1559 if (!empty($q['query']['name'])) {
1562 if (in_array( 'name', array_keys($x->table()))) {
1563 $x->whereAdd($x->tableName().".name LIKE '". $x->escape($q['query']['name']) . "%'");
1568 // - projectdirectory staff list - persn queuy
1573 * create the dataobject from (usually the url)
1574 * This uses $this->validTables
1575 * $this->validPrefix (later..)
1576 * to determine if class can be created..
1580 function dataObject($tab)
1582 if (is_array($this->validTables) && !in_array($tab,$this->validTables)) {
1583 $this->jerr("Invalid url - not listed in validTables");
1585 $tab = str_replace('/', '',$tab); // basic protection??
1587 $pm = HTML_FlexyFramework::get()->Pman;
1589 if (isset($pm['roo_alias'])) {
1590 $map = array_flip($pm['roo_alias']);
1591 if (isset($map[$tab])) {
1597 $x = DB_DataObject::factory($tab);
1599 if (!is_a($x, 'DB_DataObject') && !is_a($x, 'PDO_DataObject')) {
1600 $this->jerr('invalid url - no dataobject');