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 /* EVENTUALLY - move this stuff here..
47 * use Pman_Core_RooTrait,
48 Pman_Core_RooGetTrait,
49 Pman_Core_RooPostTrait,
50 Pman_Core_RooJsonOutputTrait;
53 * if set to an array (when extending this, then you can restrict which tables are available
55 var $validTables = false;
57 var $key; // used by update currenly to store primary key.
60 var $max_limit = 10000;
62 var $debugEnabled = true; // disable this for public versions of this code.
64 var $do = false; // the dataobject being worked on..
67 var $countWhat; // set in loadMap
73 parent::getAuth(); // load company!
74 $au = $this->getAuthUser();
77 $this->jerror("LOGIN-NOAUTH", "Not authenticated", array('authFailure' => true));
79 if (!$au->pid() ) { // not set up yet..
80 $this->jerror("LOGIN-NOAUTH", "Not authenticated", array('authFailure' => true));
84 $this->authUser = $au;
88 * GET method Roo/TABLENAME
90 * Generally for SELECT or Single SELECT
93 * _id=value single fetch based on primary id.
94 * can be '0' if you want to fetch a set of defaults
95 * Use in conjuntion with toRooSingleArray()
97 * lookup[key]=value single fetch based on a single key value lookup.
98 * multiple key/value can be used. eg. ontable+onid..
99 * _columns what to return.
101 * _no_count skip the default count query.
102 * use the number of records in the query result as the total
106 * - all tables are always autojoined.
110 * _columns=a,b,c,d comma seperated list of columns.
111 * _exclude_columns=a,b,c,d comma seperated list of columns.
112 * _distinct=name a distinct column lookup. you also have to use _columns with this.
115 * colname = ... => colname = ....
116 * !colname=.... => colname != ....
117 * !colname[0]=... !colname[1]=... => colname NOT IN (.....) ** only supports main table at present..
118 * colname[0]=... colname[1]=... => colname IN (.....) ** only supports main table at present..
121 * sort=name what to sort.
122 * sort=a,b,d can support multiple columns
123 * dir=ASC what direction
124 * _multisort ={...} JSON encoded { sort : { row : direction }, order : [ row, row, row ] }
127 * start=0 limit start
128 * limit=25 limit number
132 * csvCols[0] csvCols[1].... = .... column titles for CSV output
133 * csvTitles[0], csvTitles[1] .... = columns to use for CSV output
136 * _toggleActive !:!:!:! - this hsould not really be here..
137 * query[add_blank] - add a line in with an empty option... - not really needed???
138 * _delete = delete a list of ids element. (depricated.. this will be removed...)
141 * _post =1 = simulate a post with debuggin on.
142 * _debug_post << This is prefered, as _post may overlap with accouting posts..
144 * _debug = turn on DB_dataobject deubbing, must be admin at present..
147 * CALLS methods on dataobjects if they exist
150 * checkPerm('S' , $authuser)
151 * - can we list the stuff
152 * - return false to disallow...
153 * applySort($au, $sortcol, $direction, $array_of_columns, $multisort)
154 * -- does not support multisort at present..
155 * applyFilters($_REQUEST, $authUser, $roo)
156 * -- apply any query filters on data. and hide stuff not to be seen.
157 * -- can exit by calling $roo->jerr()
158 * postListExtra($_REQUEST, $roo, $array_data) : array(extra_name => data)
159 * - add extra column to the jdata return key/value info.
160 * postListFilter($data, $authUser, $request) return $data
161 * - modify the returned array of data (either add stuff to the data, or remove lines etc)
164 * toRooSingleArray($authUser, $request) : array
165 * - called on single fetch only, add or maniuplate returned array data.
166 * - is also called when _id=0 is used (for fetching a default set.)
167 * toRooArray($request) : array
168 * - called if singleArray is unavailable on single fetch.
169 * - always tried for mutiple results.
170 * toArray() - the default method if none of the others are found.
171 * toSimpleExcelColumn($col) - see toCSV - this enables special columns to be created for exported data.
174 * - standard DataObject feature - causes all results to show all
178 * _extra_cols -- if set, then filtering by column etc. will use them.
182 function get($tab, $opts = Array())
184 // $this->jerr("Not authenticated", array('authFailure' => true));
185 //echo '<PRE>';print_R($_GET);
186 //DB_DataObject::debuglevel(1);
188 $this->init(); // from pman.
189 //DB_DataObject::debuglevel(1);
190 HTML_FlexyFramework::get()->generateDataobjectsCache($this->isDev && !empty($_REQUEST['isDev']));
194 if ( $this->checkDebugPost()) {
199 //DB_DAtaObject::debuglevel(1);
200 return $this->post($tab);
204 $this->initErrorHandling();
206 $tt = explode('/', $tab);
207 $tab = array_shift($tt);
208 $x = $this->dataObject($tab);
210 $_columns = !empty($_REQUEST['_columns']) && is_string($_REQUEST['_columns']) ? explode(',', $_REQUEST['_columns']) : false;
213 if (isset( $_REQUEST['lookup'] ) && is_array($_REQUEST['lookup'] )) { // single fetch based on key/value pairs
214 $this->selectSingle($x, $_REQUEST['lookup'],$_REQUEST);
219 // single fetch (use '0' to fetch an empty object..)
220 if (isset($_REQUEST['_id']) && is_numeric($_REQUEST['_id'])) {
222 $this->selectSingle($x, $_REQUEST['_id'],$_REQUEST);
229 if (isset($_REQUEST['_delete'])) {
230 $this->jerr("DELETE by GET has been removed - update the code to use POST");
237 if (isset($_REQUEST['_toggleActive'])) {
238 // do we really delete stuff!?!?!?
239 if (!$this->hasPerm("Core.Staff", 'E')) {
240 $this->jerr("PERMISSION DENIED (ta)");
242 $clean = create_function('$v', 'return (int)$v;');
243 $bits = array_map($clean, explode(',', $_REQUEST['_toggleActive']));
244 if (in_array($this->authUser->id, $bits) && $this->authUser->active) {
245 $this->jerr("you can not disable yourself");
247 $x->query('UPDATE core_person SET active = !active WHERE id IN (' .implode(',', $bits).')');
248 $this->addEvent("USERTOGGLE", false, implode(',', $bits));
249 $this->jok("Updated");
252 //DB_DataObject::debugLevel(1);
254 // sets map and countWhat
255 $this->loadMap($x, array(
256 'columns' => $_columns,
257 'distinct' => empty($_REQUEST['_distinct']) ? false: $_REQUEST['_distinct'],
258 'exclude' => empty($_REQUEST['_exclude_columns']) ? false: explode(',', $_REQUEST['_exclude_columns'])
262 $this->setFilters($x,$_REQUEST);
264 if (!$this->checkPerm($x,'S', $_REQUEST)) {
265 $this->jerror("NOTICE-NOPERM", "PERMISSION DENIED (g)");
269 // build join if req.
270 //DB_DataObject::debugLevel(1);
271 // count with multiple joins and no conditions can be quite slow - so if there are no conditions - just remove the joins from the count.
273 $old_where = $x->whereAdd();
274 if (empty($old_where )) {
277 $x->whereAdd($old_where);
282 if (!isset($_REQUEST['_no_count'])) {
283 $total = $xx->count($this->countWhat);
285 if (isset($xx->_real_total)) { // this is used when we subquery the search.
286 $total = $xx->_real_total;
290 // var_dump($total);exit;
291 $this->applySort($x);
295 if (!empty($_REQUEST['_distinct']) && $total !== false && $total < 400) {
302 empty($_REQUEST['start']) ? 0 : (int)$_REQUEST['start'],
303 min(empty($_REQUEST['limit']) ? 25 : (int)$_REQUEST['limit'], $this->max_limit)
306 $queryObj = clone($x);
307 //DB_DataObject::debuglevel(1);
309 $this->sessionState(0);
311 $this->sessionState(1);
313 if (false === $res) {
314 $this->jerr($x->_lastError->toString());
322 // ---------------- THESE ARE DEPRICATED.. they should be moved to the model...
325 if (!empty($_REQUEST['query']['add_blank'])) {
326 $ret[] = array( 'id' => 0, 'name' => '----');
327 $total === false ? false : $total+1;
330 $rooar = method_exists($x, 'toRooArray');
331 $_columnsf = $_columns ? array_flip($_columns) : false;
332 while ($x->fetch()) {
334 $add = $rooar ? $x->toRooArray($_REQUEST) : $x->toArray();
335 if ($add === false) {
338 $ret[] = !$_columns ? $add : array_intersect_key($add, $_columnsf);
342 $ret = array_slice($ret,
343 empty($_REQUEST['start']) ? 0 : (int)$_REQUEST['start'],
344 min(empty($_REQUEST['limit']) ? 25 : (int)$_REQUEST['limit'], 10000)
351 if (method_exists($queryObj ,'postListExtra')) {
352 $extra = $queryObj->postListExtra($_REQUEST, $this, $ret);
356 // filter results, and add any data that is needed...
357 if (method_exists($x,'postListFilter')) {
358 $ret = $x->postListFilter($ret, $this->authUser, $_REQUEST, $this);
363 if (!empty($_REQUEST['csvCols']) && !empty($_REQUEST['csvTitles']) ) {
366 $this->toCsv($ret, $_REQUEST['csvCols'], $_REQUEST['csvTitles'],
367 empty($_REQUEST['csvFilename']) ? '' : $_REQUEST['csvFilename'] );
374 if (!empty($_REQUEST['_requestMeta']) && count($ret)) {
375 $meta = $this->meta($x, $ret);
377 $extra = $extra ? $extra: array();
378 $extra['metaData'] = $meta;
381 // this make take some time...
382 $this->sessionState(0);
383 // echo "<PRE>"; print_r($ret);
384 $this->jdata($ret, max(count($ret), $total === false ? 0 : $total), $extra );
388 function checkDebug($req = false)
390 $req = $req === false ? $_REQUEST : $req;
392 if (empty($req['_debug'])) {
396 if (!empty($_SERVER['HTTP_HOST']) && $_SERVER['HTTP_HOST'] == 'localhost') {
397 DB_DAtaObject::debuglevel((int)$req['_debug']);
405 method_exists($this->authUser,'canDebug')
407 $this->authUser->canDebug()
412 method_exists($this->authUser,'groups')
414 is_a($this->authUser, 'Pman_Core_DataObjects_Core_person')
416 in_array('Administrators', $this->authUser->groups('name'))
421 DB_DAtaObject::debuglevel((int)$req['_debug']);
426 function checkDebugPost()
428 if (empty($_GET['_post']) && empty($_GET['_debug_post'])) {
431 // localhost can do anything...
432 if (!empty($_SERVER['HTTP_HOST']) && $_SERVER['HTTP_HOST'] == 'localhost') {
435 return $this->authUser &&
436 method_exists($this->authUser,'groups') &&
437 in_array('Administrators', $this->authUser->groups('name'));
441 function checkPerm($obj, $lvl, $req= null)
443 if (!method_exists($obj, 'checkPerm')) {
446 if ($obj->checkPerm($lvl, $this->authUser, $req)) {
452 function toCsv($data, $cols, $titles, $filename, $addDate = true)
455 $this->sessionState(0); // turn off sessions - no locking..
457 require_once 'Pman/Core/SimpleExcel.php';
459 $fn = (empty($filename) ? 'list-export-' : urlencode($filename)) . (($addDate) ? date('Y-m-d') : '') ;
463 'workbook' => substr($fn, 0, 31),
470 if (is_object($data)) {
471 $rooar = method_exists($data, 'toRooArray');
472 while($data->fetch()) {
473 $x = $rooar ? $data->toRooArray($q) : $data->toArray();
475 if ($cols == '*') { /// did we get cols sent to us?
476 $cols = array_keys($x);
479 if(!is_array($cols)) {
480 $cols = explode(',', $cols);
483 if ($titles !== false) {
485 $titles= array_keys($x);
487 if(!is_array($titles)) {
488 $titles = explode(',', $titles);
490 foreach($cols as $i=>$col) {
492 'header'=> isset($titles[$i]) ? $titles[$i] : $col,
495 // 'renderer' => array($this, 'getThumb'),
496 // 'color' => 'yellow', // set color for the cell which is a header element
497 // 'fillBlank' => 'gray', // set
500 if (method_exists($data, 'toSimpleExcelColumn')) {
501 $add = $data->toSimpleExcelColumn($add);
504 $se_config['cols'][] = $add;
509 $se = new Pman_Core_SimpleExcel(array(), $se_config);
515 $se->addLine($se_config['workbook'], $x);
521 $this->jerr('no data found', false, 'text/plain');
523 $se->send($fn .'.xls');
528 foreach($data as $x) {
529 //echo "<PRE>"; print_r(array($_REQUEST['csvCols'], $x->toArray())); exit;
533 $cols= array_keys($x);
536 if(!is_array($cols)) {
537 $cols = explode(',', $cols);
540 if ($titles !== false) {
542 $titles= array_keys($x);
545 if(!is_array($titles)) {
546 $titles = explode(',', $titles);
549 foreach($cols as $i=>$col) {
551 'header'=> isset($titles[$i]) ? $titles[$i] : $col,
554 // 'renderer' => array($this, 'getThumb'),
555 // 'color' => 'yellow', // set color for the cell which is a header element
556 // 'fillBlank' => 'gray', // set
559 if (!empty($this->do) && method_exists($this->do, 'toSimpleExcelColumn')) {
560 $add = $this->do->toSimpleExcelColumn($add);
563 $se_config['cols'][] = $add;
568 $se = new Pman_Core_SimpleExcel(array(),$se_config);
571 //fputcsv($fh, $titles);
575 $se->addLine($se_config['workbook'], $x);
579 $this->jerr('no data found');
582 $se->send($fn .'.xls');
589 * POST method Roo/TABLENAME
590 * -- creates, updates, or deletes data.
593 * if the primary key is empty, this happens
594 * will automatically set these to current date and authUser->id
595 * created, created_by, created_dt
596 * updated, update_by, updated_dt
597 * modified, modified_by, modified_dt
599 * will return a GET request SINGLE SELECT (and accepts same)
602 * _delete=1,2,3 delete a set of data.
604 * if the primary key value is set, then update occurs.
605 * will automatically set these to current date and authUser->id
606 * updated, update_by, updated_dt
607 * modified, modified_by, modified_dt
611 * _delete=1,2,3 causes a delete to occur.
612 * _ids=1,2,3,4 causes update to occur on all primary ids.
615 * = same as single SELECT GET request..
620 * _debug=1 forces debug
621 * _get=1 - causes a get request to occur when doing a POST..
625 * these methods on dataobjects if they exist
627 * checkPerm('E' / 'D' , $authuser)
628 * - can we list the stuff
629 * - return false to disallow...
631 * toRooSingleArray($authUser, $request) : array
632 * - called on single fetch only, add or maniuplate returned array data.
633 * toRooArray($request) : array
634 * - Called if toSingleArray does not exist.
635 * - if you need to return different data than toArray..
638 * (for logging - this is generically prefixed to all database operations.)
642 * called when $_FILES is not empty
645 * setFromRoo($ar, $roo)
646 * - alternative to setFrom() which is called if this method does not exist
647 * - values from post (deal with dates etc.) - return true|error string.
648 * - call $roo->jerr() on failure...
650 * CALLS BEFORE change occurs:
652 * beforeDelete($dependants_array, $roo)
653 * Argument is an array of un-find/fetched dependant items.
654 * - jerr() will stop insert.. (Prefered)
655 * - return false for fail and set DO->err;
657 * beforeUpdate($old, $request,$roo)
658 * - before update - jerr() will stop insert..
659 * beforeInsert($request,$roo)
660 * - before insert - jerr() will stop insert..
663 * CALLS AFTER change occured
665 * onUpdate($old, $request,$roo)
666 * - after update // return value ignored
668 * onInsert($request,$roo)
671 * onDelete($request, $roo) - after delete
675 function post($tab) // update / insert (?? delete??)
677 // -- why was this put in? - Roo is not related to Core.All ?
678 //if (!$this->hasPerm("Core.All", 'E')) {
679 // $this->jerr("PERMISSION DENIED (e)");
681 $this->initErrorHandling();
683 // DB_DataObject::debugLevel(1);
686 if (!empty($_REQUEST['_get'])) {
687 return $this->get($tab);
690 $this->init(); // for pman.
692 $x = $this->dataObject($tab);
694 $this->transObj = clone($x);
696 $this->transObj->query('BEGIN');
697 // find the key and use that to get the thing..
700 $this->jerr('no key');
703 $this->key = $keys[0];
705 // delete should be here...
706 if (isset($_REQUEST['_delete'])) {
707 // do we really delete stuff!?!?!?
708 return $this->delete($x,$_REQUEST);
716 // not sure if this is a good idea here...
718 if (!empty($_REQUEST['_ids'])) {
719 $ids = explode(',',$_REQUEST['_ids']);
720 $x->whereAddIn($this->key, $ids, 'int');
721 $ar = $x->fetchAll();
724 $this->update($x, $_REQUEST);
727 $this->jok("UPDATED");
732 if (!empty($_REQUEST[$this->key])) {
734 if (!$x->get($this->key, $_REQUEST[$this->key])) {
735 $this->jerr("Invalid request (id does not point to a record.)");
737 $this->jok($this->update($x, $_REQUEST));
741 $this->jerr("No data recieved for inserting");
744 $this->jok($this->insert($x, $_REQUEST));
756 * apply REQUEST[sort] and [dir]
757 * sort may be an array of columsn..
759 * @arg DB_DataObject $x
762 function applySort($x, $sort = '', $dir ='')
765 // Db_DataObject::debugLevel(1);
766 $sort = empty($_REQUEST['sort']) || !is_string($_REQUEST['sort']) ? $sort : $_REQUEST['sort'];
767 $dir = empty($_REQUEST['dir']) || !is_string($_REQUEST['dir']) ? $dir : $_REQUEST['dir'];
768 $dir = $dir == 'ASC' ? 'ASC' : 'DESC';
770 $ms = empty($_REQUEST['_multisort']) || !is_string($_REQUEST['_multisort']) ? false : $_REQUEST['_multisort'];
771 //var_Dump($ms);exit;
773 if (method_exists($x, 'applySort')) {
774 $sorted = $x->applySort(
778 array_keys($this->cols),
779 $ms ? json_decode($ms) : false
784 return $this->multiSort($x);
787 if ($sorted === false) {
788 $cols = $x->tableColumns();
789 $excols = array_keys($this->cols);
791 if (isset($x->_extra_cols)) {
792 $excols = array_merge($excols, $x->_extra_cols);
794 $sort_ar = explode(',', $sort);
797 foreach($sort_ar as $sort) {
799 if (strlen($sort) && isset($cols[$sort]) ) {
800 $sort_str[] = $x->tableName() .'.'.$sort . ' ' . $dir ;
802 } else if (in_array($sort, $excols)) {
803 $sort_str[] = $sort . ' ' . $dir ;
808 $x->orderBy(implode(', ', $sort_str ));
819 function multiSort($x)
821 //DB_DataObject::debugLevel(1);
822 $ms = json_decode($_REQUEST['_multisort']);
823 if (!isset($ms->order) || !is_array($ms->order)) {
828 $cols = $x->tableColumns();
830 //print_r($this->cols);exit;
831 // this-><cols contains colname => aliased name...
832 foreach($ms->order as $col) {
833 if (!isset($ms->sort->{$col})) {
834 continue; // no direction..
836 $ms->sort->{$col} = $ms->sort->{$col} == 'ASC' ? 'ASC' : 'DESC';
838 if (strlen($col) && isset($cols[$col]) ) {
839 $sort_str[] = $x->tableName() .'.'.$col . ' ' . $ms->sort->{$col};
842 //print_r($this->cols);
844 if (in_array($col, array_keys($this->cols))) {
845 $sort_str[] = $col. ' ' . $ms->sort->{$col};
848 if (isset($x->_extra_cols) && in_array($col, $x->_extra_cols)) {
849 $sort_str[] = $col. ' ' . $ms->sort->{$col};
854 $x->orderBy(implode(', ', $sort_str ));
861 * - used when _id is set, or after insert or update
863 * @param DataObject $x the dataobject to use
864 * @param int $id the pid of the object
865 * @param array $req the request, or false if it comes from insert/update.
868 function selectSingle($x, $id, $req=false)
872 $_columns = !empty($req['_columns']) ? explode(',', $req['_columns']) : false;
874 //var_dump(array(!is_array($id) , empty($id)));
875 if (!is_array($id) && empty($id)) {
878 if (method_exists($x, 'toRooSingleArray')) {
879 $this->jok($x->toRooSingleArray($this->authUser, $req));
881 if (method_exists($x, 'toRooArray')) {
882 $this->jok($x->toRooArray($req));
885 $this->jok($x->toArray());
889 $this->loadMap($x, array(
890 'columns' => $_columns,
893 if ($req !== false) {
894 $this->setFilters($x, $req);
895 } else if (method_exists($x, 'applyFilters')) {
896 // always call apply filters even after update/insert...
897 // however arguments are not passed.
898 $x->applyFilters(array('_is_update_request' => true), $this->authUser, $this);
901 // DB_DataObject::DebugLevel(1);
904 $x->setFrom($req['lookup'] );
906 if (!$x->find(true)) {
907 if (!empty($id['_id'])) {
909 $this->jok($x->toArray());
914 } else if (!$x->get($id)) {
915 $this->jerr("selectSingle: no such record ($id)");
918 // ignore perms if comming from update/insert - as it's already done...
919 if ($req !== false && !$this->checkPerm($x,'S')) {
920 $this->jerr("PERMISSION DENIED - si");
922 // different symantics on all these calls??
923 if (method_exists($x, 'toRooSingleArray')) {
924 $this->jok($x->toRooSingleArray($this->authUser, $req));
926 if (method_exists($x, 'toRooArray')) {
927 $this->jok($x->toRooArray($req));
929 $this->jok($x->toArray());
934 function insert($x, $req, $with_perm_check = true)
936 if (method_exists($x, 'setFromRoo')) {
937 $res = $x->setFromRoo($req, $this);
938 if (is_string($res)) {
939 $this->jerror("NOTICE-INSERT", $res);
945 if ( $with_perm_check && !$this->checkPerm($x,'A', $req)) {
946 $this->jerr("PERMISSION DENIED {$x->tableName()}:checkPerm(A)");
948 $cols = $x->tableColumns();
950 if (isset($cols['created'])) {
951 $x->created = date('Y-m-d H:i:s');
953 if (isset($cols['created_dt'])) {
954 $x->created_dt = date('Y-m-d H:i:s');
956 if (isset($cols['created_by'])) {
957 $x->created_by = $this->authUser->id;
960 if (isset($cols['modified'])) {
961 $x->modified = date('Y-m-d H:i:s');
963 if (isset($cols['modified_dt'])) {
964 $x->modified_dt = date('Y-m-d H:i:s');
966 if (isset($cols['modified_by'])) {
967 $x->modified_by = $this->authUser->id;
970 if (isset($cols['updated'])) {
971 $x->updated = date('Y-m-d H:i:s');
973 if (isset($cols['updated_dt'])) {
974 $x->updated_dt = date('Y-m-d H:i:s');
976 if (isset($cols['updated_by'])) {
977 $x->updated_by = $this->authUser->id;
980 if (method_exists($x, 'beforeInsert')) {
981 $x->beforeInsert($_REQUEST, $this);
986 if ($res === false) {
987 $this->jerr($x->_lastError->toString());
989 $ev = $this->addEvent("ADD", $x);
990 if (method_exists($x, 'onInsert')) {
992 $x->onInsert($_REQUEST, $this, $ev);
999 // note setFrom might handle this before hand...!??!
1000 if (!empty($_FILES) && method_exists($x, 'onUpload')) {
1001 $x->onUpload($this, $_REQUEST);
1004 return $this->selectSingle(
1005 DB_DataObject::factory($x->tableName()),
1011 function updateLock($x, $req )
1013 Pman::$permitError = true; // allow it to fail without dieing
1015 $lock = DB_DataObjecT::factory('Core_locking');
1016 Pman::$permitError = false;
1017 if (is_a($lock,'DB_DataObject') && $this->authUser) {
1019 $lock->on_id = $x->{$this->key};
1020 $lock->on_table= strtolower($x->tableName());
1021 if (!empty($_REQUEST['_lock_id'])) {
1022 $lock->whereAdd('id != ' . ((int)$_REQUEST['_lock_id']));
1024 $lock->whereAdd('person_id !=' . $this->authUser->id);
1027 $llc = clone($lock);
1028 $exp = date('Y-m-d', strtotime('NOW - 1 WEEK'));
1029 $llc->whereAdd("created < '$exp'");
1030 if ($llc->count()) {
1032 while($llc->fetch()) {
1033 $llcd = clone($llc);
1039 if ($lock->find(true)) {
1040 // it's locked by someone else..
1041 $p = $lock->person();
1044 $this->jerr( "Record was locked by " . $p->name . " at " .$lock->created.
1045 " - Please confirm you wish to save"
1046 , array('needs_confirm' => true));
1050 // check the users lock.. - no point.. ??? - if there are no other locks and it's not the users, then they can
1051 // edit it anyways...
1053 // can we find the user's lock.
1054 $lock = DB_DataObjecT::factory('Core_locking');
1055 $lock->on_id = $x->{$this->key};
1056 $lock->on_table= strtolower($x->tableName());
1057 $lock->person_id = $this->authUser->id;
1058 $lock->orderBy('created DESC');
1062 $lock->find(true) &&
1063 isset($x->modified_dt) &&
1064 strtotime($x->modified_dt) > strtotime($lock->created) &&
1065 empty($req['_submit_confirmed']) &&
1066 $x->modified_by != $this->authUser->id
1069 $p = DB_DataObject::factory('core_person');
1070 $p->get($x->modified_by);
1071 $this->jerr($p->name . " saved the record since you started editing,\nDo you really want to update it?", array('needs_confirm' => true));
1083 function update($x, $req, $with_perm_check = true)
1085 if ( $with_perm_check && !$this->checkPerm($x,'E', $req) ) {
1086 $this->jerr("PERMISSION DENIED - No Edit permissions on this element");
1089 // check any locks..
1090 // only done if we recieve a lock_id.
1091 // we are very trusing here.. that someone has not messed around with locks..
1092 // the object might want to check in their checkPerm - if locking is essential..
1093 $lock = $this->updateLock($x,$req);
1103 // this lot is generic.. needs moving
1104 if (method_exists($x, 'setFromRoo')) {
1105 $res = $x->setFromRoo($req, $this);
1106 if (is_string($res)) {
1115 //echo '<PRE>';print_r($old);print_r($x);exit;
1118 $cols = $x->tableColumns();
1120 if (isset($cols['modified'])) {
1121 $x->modified = date('Y-m-d H:i:s');
1123 if (isset($cols['modified_dt'])) {
1124 $x->modified_dt = date('Y-m-d H:i:s');
1126 if (isset($cols['modified_by']) && $this->authUser) {
1127 $x->modified_by = $this->authUser->id;
1130 if (isset($cols['updated'])) {
1131 $x->updated = date('Y-m-d H:i:s');
1133 if (isset($cols['updated_dt'])) {
1134 $x->updated_dt = date('Y-m-d H:i:s');
1136 if (isset($cols['updated_by']) && $this->authUser) {
1137 $x->updated_by = $this->authUser->id;
1140 if (method_exists($x, 'beforeUpdate')) {
1141 $x->beforeUpdate($old, $req, $this);
1144 if ($with_perm_check && !empty($_FILES) && method_exists($x, 'onUpload')) {
1145 $x->onUpload($this, $_REQUEST);
1148 //DB_DataObject::DebugLevel(1);
1149 $res = $x->update($old);
1150 if ($res === false) {
1151 $this->jerr($x->_lastError->toString());
1153 $ev = $this->addEvent("EDIT", $x);
1155 if (method_exists($x, 'onUpdate')) {
1156 $x->onUpdate($old, $req, $this, $ev);
1159 $ev->audit($x, $old);
1163 return $this->selectSingle(
1164 DB_DataObject::factory($x->tableName()),
1170 * Delete a number of records.
1171 * calls $delete_obj->beforeDelete($array_of_dependant_dataobjects, $this)
1175 function delete($x, $req)
1177 // do we really delete stuff!?!?!?
1178 if (empty($req['_delete'])) {
1179 $this->jerr("Delete Requested with no value");
1183 // build a list of tables to queriy for dependant data..
1188 $all_links = $x->databaseLinks();
1190 foreach($all_links as $tbl => $links) {
1191 foreach($links as $col => $totbl_col) {
1192 $to = explode(':', $totbl_col);
1193 if ($to[0] != $x->tableName()) {
1197 $affects[$tbl .'.' . $col] = true;
1202 // echo '<PRE>';print_r($affects);exit;
1203 // DB_Dataobject::debugLevel(1);
1208 $bits = array_map(function($v) { return (int)$v; } , explode(',', $req['_delete']));
1210 // let's assume it has a key!!!
1212 $x->whereAdd($this->key .' IN ('. implode(',', $bits) .')');
1214 $this->jerror("NOTICE-DELETE","Nothing found to delete");
1217 while ($x->fetch()) {
1223 if (!$this->checkPerm($x,'D') ) {
1224 $this->jerr("PERMISSION DENIED (d)");
1227 $match_ar = array();
1228 foreach($affects as $k=> $true) {
1229 $ka = explode('.', $k);
1231 $chk = DB_DataObject::factory($ka[0]);
1232 if (!is_a($chk,'DB_DataObject') && !is_a($chk,'PDO_DataObject')) {
1233 $this->jerr('Unable to load referenced table, check the links config: ' .$ka[0]);
1235 // print_r(array($chk->tablename() , $ka[1] , $xx->tablename() , $this->key ));
1236 $chk->{$ka[1]} = $xx->{$this->key};
1238 if (count($chk->keys())) {
1239 $matches = $chk->count();
1241 //DB_DataObject::DebugLevel(1);
1242 $matches = $chk->count($ka[1]);
1246 $chk->_match_key = $ka[1];
1247 $match_ar[] = clone($chk);
1253 $has_beforeDelete = method_exists($xx, 'beforeDelete');
1254 // before delte = allows us to trash dependancies if needed..
1257 if ( $has_beforeDelete ) {
1258 if ($xx->beforeDelete($match_ar, $this, $_REQUEST) === false) {
1259 $errs[] = "Delete failed ({$xx->id})\n".
1260 (isset($xx->err) ? $xx->err : '');
1263 // refetch affects..
1265 $match_ar = array();
1266 foreach($affects as $k=> $true) {
1267 $ka = explode('.', $k);
1268 $chk = DB_DataObject::factory($ka[0]);
1269 if (!is_a($chk,'DB_DataObject') && !is_a($chk,'PDO_DataObject')) {
1270 $this->jerr('Unable to load referenced table, check the links config: ' .$ka[0]);
1272 $chk->{$ka[1]} = $xx->{$this->key};
1273 $matches = $chk->count();
1274 $match_total += $matches;
1276 $chk->_match_key = $ka[1];
1277 $match_ar[] = clone($chk);
1284 if (!empty($match_ar)) {
1285 $chk = $match_ar[0];
1287 $o = $chk->fetchAll();
1288 $key = isset($chk->_match_key) ?$chk->_match_key : '?unknown column?';
1289 $desc = $chk->tableName(). '.' . $key .'='.$xx->{$this->key} ;
1290 if (method_exists($chk, 'toEventString')) {
1291 $desc .= ' : ' . $o[0]->toEventString();
1293 $this->jerror("NOTICE-DELETE-DEP", "Delete Dependant records ($match_total found), " .
1294 "first is ( $desc )");
1300 DB_DataObject::Factory('Events')->logDeletedRecord($x);
1302 $this->addEvent("DELETE", $x);
1306 if (method_exists($xx,'onDelete')) {
1307 $xx->onDelete($req, $this);
1313 $this->jerr(implode("\n<BR>", $errs));
1315 $this->jok("Deleted");
1321 * cols stores the list of columns that are available from the query.
1324 * This is a dupe of what is in autojoin -- we should move to using autojoin really.
1336 var $cols = array();
1340 function loadMap($do, $cfg =array()) //$onlycolumns=false, $distinct = false)
1342 //DB_DataObject::debugLevel(5);
1343 $onlycolumns = !empty($cfg['columns']) ? $cfg['columns'] : false;
1344 $distinct = !empty($cfg['distinct']) ? $cfg['distinct'] : false;
1345 $excludecolumns = !empty($cfg['exclude']) ? $cfg['exclude'] : array();
1347 $excludecolumns[] = 'passwd'; // we never expose passwords
1348 $excludecolumns[] = 'oath_key';
1350 $ret = $do->autoJoin(array(
1351 'include' => $onlycolumns,
1352 'exclude' => $excludecolumns,
1353 'distinct' => $distinct
1356 $this->countWhat = $ret['count'];
1357 $this->cols = $ret['cols'];
1358 $this->colsJname = $ret['join_names'];
1367 * generate the meta data neede by queries.
1370 function meta($x, $data)
1372 // this is not going to work on queries where the data does not match the database def..
1373 // for unknown columns we send them as stirngs..
1375 $cols = array_keys($data[0]);
1379 if (class_exists('PDO_DataObject')) {
1380 $options = PDO_DataObject::config();
1381 if (!file_exists($options["schema_location"] . '.reader')) {
1385 $rdata = unserialize(file_get_contents($options["schema_location"] . '.reader'));
1388 //echo '<PRE>';print_r($this->cols); exit;
1389 $options = &PEAR::getStaticProperty('DB_DataObject','options');
1390 $reader = $options["ini_{$x->databaseNickname()}"] .'.reader';
1391 if (!file_exists( $reader )) {
1395 $rdata = unserialize(file_get_contents($reader));
1398 //echo '<PRE>';print_r($this->cols);exit;
1399 //echo '<PRE>';print_r($rdata);exit;
1400 // echo '<PRE>';print_r($rdata);exit;
1403 $key = empty($keys) ? 'id' : $keys[0];
1407 foreach($cols as $c ) {
1408 if (!isset($this->cols[$c]) || !isset($rdata[$this->cols[$c]]) || !is_array($rdata[$this->cols[$c]])) {
1412 $add = $rdata[$this->cols[$c]];
1417 'totalProperty' => 'total',
1418 'successProperty' => 'success',
1420 'id' => $key, // was 'id'...
1427 function setFilters($x, $q)
1429 // if a column is type int, and we get ',' -> the it should be come an inc clause..
1430 // DB_DataObject::debugLevel(1);
1431 if (method_exists($x, 'applyFilters')) {
1432 // DB_DataObject::debugLevel(1);
1433 if (false === $x->applyFilters($q, $this->authUser, $this)) {
1437 $q_filtered = array();
1441 foreach($q as $key=>$val) {
1443 if (in_array($key,$keys) && !is_array($val)) {
1448 // handles name[]=fred&name[]=brian => name in ('fred', 'brian').
1449 // value is an array..
1450 if (is_array($val) ) {
1454 if ($key[0] == '!') {
1456 $key = substr($key,1);
1459 if (!in_array( $key, array_keys($this->cols))) {
1463 // support a[0] a[1] ..... => whereAddIn(
1466 foreach($val as $k=>$v) {
1467 if (!is_numeric($k)) {
1471 // FIXME: note this is not typesafe for anything other than mysql..
1473 if (!is_numeric($v) || !is_long($v)) {
1482 $x->whereAddIn($pref . (
1483 isset($this->colsJname[$key]) ?
1484 $this->colsJname[$key] :
1485 ($x->tableName(). '.'.$key)),
1486 $ar, $quote ? 'string' : 'int');
1493 // handles !name=fred => name not equal fred.
1494 if ($key[0] == '!' && in_array(substr($key, 1), array_keys($this->cols))) {
1496 $key = substr($key, 1) ;
1499 isset($this->colsJname[$key]) ?
1500 $this->colsJname[$key] :
1501 $x->tableName(). '.'.$key ) . ' != ' .
1502 (is_numeric($val) ? $val : "'". $x->escape($val) . "'")
1512 // Events and remarks -- fixme - move to events/remarsk...
1513 case 'on_id': // where TF is this used...
1514 if (!empty($q['query']['original'])) {
1515 // DB_DataObject::debugLevel(1);
1516 $o = (int) $q['query']['original'];
1518 $x->whereAdd("(on_id = $oid OR
1519 on_id IN ( SELECT distinct(id) FROM Documents WHERE original = $o )
1528 if (strlen($val) && $key[0] != '_') {
1529 $q_filtered[$key] = $val;
1532 // subjoined columns = check the values.
1533 // note this is not typesafe for anything other than mysql..
1535 if (isset($this->colsJname[$key])) {
1537 // the aobve rule for !strlen non-joined cols should apply to joined ones.
1538 if (!strlen($val)) {
1544 if (!is_numeric($val) || !is_long($val)) {
1547 $x->whereAdd( "{$this->colsJname[$key]} = " . ($quote ? "'". $x->escape($val) ."'" : $val));
1555 if (!empty($q_filtered)) {
1556 //var_dump($q_filtered);
1560 $x->setFrom($q_filtered);
1566 // nice generic -- let's get rid of it.. where is it used!!!!
1568 // Person / Group / Comapnies.... most of my queries noww...
1570 if (!empty($q['query']['name'])) {
1573 if (in_array( 'name', array_keys($x->table()))) {
1574 $x->whereAdd($x->tableName().".name LIKE '". $x->escape($q['query']['name']) . "%'");
1579 // - projectdirectory staff list - persn queuy
1584 * create the dataobject from (usually the url)
1585 * This uses $this->validTables
1586 * $this->validPrefix (later..)
1587 * to determine if class can be created..
1591 function dataObject($tab)
1593 if (is_array($this->validTables) && !in_array($tab,$this->validTables)) {
1594 $this->jerr("Invalid url - not listed in validTables");
1596 $tab = str_replace('/', '',$tab); // basic protection??
1598 $ff = HTML_FlexyFramework::get();
1599 $pm = isset($ff->Pman) ? $ff->Pman : array();
1601 if (isset($pm['roo_alias'])) {
1602 $map = array_flip($pm['roo_alias']);
1603 if (isset($map[$tab])) {
1609 $x = DB_DataObject::factory($tab);
1611 if (!is_a($x, 'DB_DataObject') && !is_a($x, 'PDO_DataObject')) {
1612 $this->jerr('invalid url - no dataobject');