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;
54 * if set to an array (when extending this, then you can restrict which tables are available
56 var $validTables = false;
58 var $key; // used by update currenly to store primary key.
61 var $max_limit = 10000;
63 var $debugEnabled = true; // disable this for public versions of this code.
65 var $do = false; // the dataobject being worked on..
68 var $countWhat; // set in loadMap
74 parent::getAuth(); // load company!
75 $au = $this->getAuthUser();
78 $this->jerror("LOGIN-NOAUTH", "Not authenticated", array('authFailure' => true));
80 if (!$au->pid() ) { // not set up yet..
81 $this->jerror("LOGIN-NOAUTH", "Not authenticated", array('authFailure' => true));
85 $this->authUser = $au;
89 * GET method Roo/TABLENAME
91 * Generally for SELECT or Single SELECT
94 * _id=value single fetch based on primary id.
95 * can be '0' if you want to fetch a set of defaults
96 * Use in conjuntion with toRooSingleArray()
98 * lookup[key]=value single fetch based on a single key value lookup.
99 * multiple key/value can be used. eg. ontable+onid..
100 * _columns what to return.
102 * _no_count skip the default count query.
103 * use the number of records in the query result as the total
107 * - all tables are always autojoined.
111 * _columns=a,b,c,d comma seperated list of columns.
112 * _exclude_columns=a,b,c,d comma seperated list of columns.
113 * _distinct=name a distinct column lookup. you also have to use _columns with this.
116 * colname = ... => colname = ....
117 * !colname=.... => colname != ....
118 * !colname[0]=... !colname[1]=... => colname NOT IN (.....) ** only supports main table at present..
119 * colname[0]=... colname[1]=... => colname IN (.....) ** only supports main table at present..
122 * sort=name what to sort.
123 * sort=a,b,d can support multiple columns
124 * dir=ASC what direction
125 * _multisort ={...} JSON encoded { sort : { row : direction }, order : [ row, row, row ] }
128 * start=0 limit start
129 * limit=25 limit number
133 * csvCols[0] csvCols[1].... = .... column titles for CSV output
134 * csvTitles[0], csvTitles[1] .... = columns to use for CSV output
137 * _toggleActive !:!:!:! - this hsould not really be here..
138 * query[add_blank] - add a line in with an empty option... - not really needed???
139 * _delete = delete a list of ids element. (depricated.. this will be removed...)
142 * _post =1 = simulate a post with debuggin on.
143 * _debug_post << This is prefered, as _post may overlap with accouting posts..
145 * _debug = turn on DB_dataobject deubbing, must be admin at present..
148 * CALLS methods on dataobjects if they exist
151 * checkPerm('S' , $authuser)
152 * - can we list the stuff
153 * - return false to disallow...
154 * applySort($au, $sortcol, $direction, $array_of_columns, $multisort)
155 * -- does not support multisort at present..
156 * applyFilters($_REQUEST, $authUser, $roo)
157 * -- apply any query filters on data. and hide stuff not to be seen.
158 * -- can exit by calling $roo->jerr()
159 * postListExtra($_REQUEST, $roo, $array_data) : array(extra_name => data)
160 * - add extra column to the jdata return key/value info.
161 * postListFilter($data, $authUser, $request) return $data
162 * - modify the returned array of data (either add stuff to the data, or remove lines etc)
165 * toRooSingleArray($authUser, $request) : array
166 * - called on single fetch only, add or maniuplate returned array data.
167 * - is also called when _id=0 is used (for fetching a default set.)
168 * toRooArray($request) : array
169 * - called if singleArray is unavailable on single fetch.
170 * - always tried for mutiple results.
171 * toArray() - the default method if none of the others are found.
172 * toSimpleExcelColumn($col) - see toCSV - this enables special columns to be created for exported data.
175 * - standard DataObject feature - causes all results to show all
179 * _extra_cols -- if set, then filtering by column etc. will use them.
183 function get($tab, $opts = Array())
185 // $this->jerr("Not authenticated", array('authFailure' => true));
186 //echo '<PRE>';print_R($_GET);
187 //DB_DataObject::debuglevel(1);
189 $this->init(); // from pman.
190 //DB_DataObject::debuglevel(1);
191 HTML_FlexyFramework::get()->generateDataobjectsCache($this->isDev && !empty($_REQUEST['isDev']));
195 if ( $this->checkDebugPost()) {
200 //DB_DAtaObject::debuglevel(1);
201 return $this->post($tab);
205 $this->initErrorHandling();
207 $tt = explode('/', $tab);
208 $tab = array_shift($tt);
209 $x = $this->dataObject($tab);
211 $_columns = !empty($_REQUEST['_columns']) && is_string($_REQUEST['_columns']) ? explode(',', $_REQUEST['_columns']) : false;
214 if (isset( $_REQUEST['lookup'] ) && is_array($_REQUEST['lookup'] )) { // single fetch based on key/value pairs
215 $this->selectSingle($x, $_REQUEST['lookup'],$_REQUEST);
220 // single fetch (use '0' to fetch an empty object..)
221 if (isset($_REQUEST['_id']) && is_numeric($_REQUEST['_id'])) {
223 $this->selectSingle($x, $_REQUEST['_id'],$_REQUEST);
230 if (isset($_REQUEST['_delete'])) {
231 $this->jerr("DELETE by GET has been removed - update the code to use POST");
238 if (isset($_REQUEST['_toggleActive'])) {
239 // do we really delete stuff!?!?!?
240 if (!$this->hasPerm("Core.Staff", 'E')) {
241 $this->jerr("PERMISSION DENIED (ta)");
243 $clean = create_function('$v', 'return (int)$v;');
244 $bits = array_map($clean, explode(',', $_REQUEST['_toggleActive']));
245 if (in_array($this->authUser->id, $bits) && $this->authUser->active) {
246 $this->jerr("you can not disable yourself");
248 $x->query('UPDATE core_person SET active = !active WHERE id IN (' .implode(',', $bits).')');
249 $this->addEvent("USERTOGGLE", false, implode(',', $bits));
250 $this->jok("Updated");
253 //DB_DataObject::debugLevel(1);
255 // sets map and countWhat
256 $this->loadMap($x, array(
257 'columns' => $_columns,
258 'distinct' => empty($_REQUEST['_distinct']) ? false: $_REQUEST['_distinct'],
259 'exclude' => empty($_REQUEST['_exclude_columns']) ? false: explode(',', $_REQUEST['_exclude_columns'])
263 $this->setFilters($x,$_REQUEST);
265 if (!$this->checkPerm($x,'S', $_REQUEST)) {
266 $this->jerror("NOTICE-NOPERM", "PERMISSION DENIED (g)");
270 // build join if req.
271 //DB_DataObject::debugLevel(1);
272 // count with multiple joins and no conditions can be quite slow - so if there are no conditions - just remove the joins from the count.
274 $old_where = $x->whereAdd();
275 if (empty($old_where )) {
278 $x->whereAdd($old_where);
283 if (!isset($_REQUEST['_no_count'])) {
284 $total = $xx->count($this->countWhat);
286 if (isset($xx->_real_total)) { // this is used when we subquery the search.
287 $total = $xx->_real_total;
291 // var_dump($total);exit;
292 $this->applySort($x);
296 if (!empty($_REQUEST['_distinct']) && $total !== false && $total < 400) {
303 empty($_REQUEST['start']) ? 0 : (int)$_REQUEST['start'],
304 min(empty($_REQUEST['limit']) ? 25 : (int)$_REQUEST['limit'], $this->max_limit)
307 $queryObj = clone($x);
308 //DB_DataObject::debuglevel(1);
310 $this->sessionState(0);
312 $this->sessionState(1);
314 if (false === $res) {
315 $this->jerr($x->_lastError->toString());
323 // ---------------- THESE ARE DEPRICATED.. they should be moved to the model...
326 if (!empty($_REQUEST['query']['add_blank'])) {
327 $ret[] = array( 'id' => 0, 'name' => '----');
328 $total === false ? false : $total+1;
331 $rooar = method_exists($x, 'toRooArray');
332 $_columnsf = $_columns ? array_flip($_columns) : false;
333 while ($x->fetch()) {
335 $add = $rooar ? $x->toRooArray($_REQUEST) : $x->toArray();
336 if ($add === false) {
339 $ret[] = !$_columns ? $add : array_intersect_key($add, $_columnsf);
343 $ret = array_slice($ret,
344 empty($_REQUEST['start']) ? 0 : (int)$_REQUEST['start'],
345 min(empty($_REQUEST['limit']) ? 25 : (int)$_REQUEST['limit'], 10000)
352 if (method_exists($queryObj ,'postListExtra')) {
353 $extra = $queryObj->postListExtra($_REQUEST, $this, $ret);
357 // filter results, and add any data that is needed...
358 if (method_exists($x,'postListFilter')) {
359 $ret = $x->postListFilter($ret, $this->authUser, $_REQUEST, $this);
364 if (!empty($_REQUEST['csvCols']) && !empty($_REQUEST['csvTitles']) ) {
367 $this->toCsv($ret, $_REQUEST['csvCols'], $_REQUEST['csvTitles'],
368 empty($_REQUEST['csvFilename']) ? '' : $_REQUEST['csvFilename'] );
375 if (!empty($_REQUEST['_requestMeta']) && count($ret)) {
376 $meta = $this->meta($x, $ret);
378 $extra = $extra ? $extra: array();
379 $extra['metaData'] = $meta;
382 // this make take some time...
383 $this->sessionState(0);
384 // echo "<PRE>"; print_r($ret);
385 $this->jdata($ret, max(count($ret), $total === false ? 0 : $total), $extra );
389 function checkDebug($req = false)
391 $req = $req === false ? $_REQUEST : $req;
393 if (empty($req['_debug'])) {
397 if (!empty($_SERVER['HTTP_HOST']) && $_SERVER['HTTP_HOST'] == 'localhost') {
398 DB_DAtaObject::debuglevel((int)$req['_debug']);
406 method_exists($this->authUser,'canDebug')
408 $this->authUser->canDebug()
413 method_exists($this->authUser,'groups')
415 is_a($this->authUser, 'Pman_Core_DataObjects_Core_person')
417 in_array('Administrators', $this->authUser->groups('name'))
422 DB_DAtaObject::debuglevel((int)$req['_debug']);
427 function checkDebugPost()
429 if (empty($_GET['_post']) && empty($_GET['_debug_post'])) {
432 // localhost can do anything...
433 if (!empty($_SERVER['HTTP_HOST']) && $_SERVER['HTTP_HOST'] == 'localhost') {
436 return $this->authUser &&
437 method_exists($this->authUser,'groups') &&
438 in_array('Administrators', $this->authUser->groups('name'));
442 function checkPerm($obj, $lvl, $req= null)
444 if (!method_exists($obj, 'checkPerm')) {
447 if ($obj->checkPerm($lvl, $this->authUser, $req)) {
453 function toCsv($data, $cols, $titles, $filename, $addDate = true)
456 $this->sessionState(0); // turn off sessions - no locking..
458 require_once 'Pman/Core/SimpleExcel.php';
460 $fn = (empty($filename) ? 'list-export-' : urlencode($filename)) . (($addDate) ? date('Y-m-d') : '') ;
464 'workbook' => substr($fn, 0, 31),
471 if (is_object($data)) {
472 $rooar = method_exists($data, 'toRooArray');
473 while($data->fetch()) {
474 $x = $rooar ? $data->toRooArray($q) : $data->toArray();
476 if ($cols == '*') { /// did we get cols sent to us?
477 $cols = array_keys($x);
480 if(!is_array($cols)) {
481 $cols = explode(',', $cols);
484 if ($titles !== false) {
486 $titles= array_keys($x);
488 if(!is_array($titles)) {
489 $titles = explode(',', $titles);
491 foreach($cols as $i=>$col) {
493 'header'=> isset($titles[$i]) ? $titles[$i] : $col,
496 // 'renderer' => array($this, 'getThumb'),
497 // 'color' => 'yellow', // set color for the cell which is a header element
498 // 'fillBlank' => 'gray', // set
501 if (method_exists($data, 'toSimpleExcelColumn')) {
502 $add = $data->toSimpleExcelColumn($add);
505 $se_config['cols'][] = $add;
510 $se = new Pman_Core_SimpleExcel(array(), $se_config);
516 $se->addLine($se_config['workbook'], $x);
522 $this->jerr('no data found', false, 'text/plain');
524 $se->send($fn .'.xls');
529 foreach($data as $x) {
530 //echo "<PRE>"; print_r(array($_REQUEST['csvCols'], $x->toArray())); exit;
534 $cols= array_keys($x);
537 if(!is_array($cols)) {
538 $cols = explode(',', $cols);
541 if ($titles !== false) {
543 $titles= array_keys($x);
546 if(!is_array($titles)) {
547 $titles = explode(',', $titles);
550 foreach($cols as $i=>$col) {
552 'header'=> isset($titles[$i]) ? $titles[$i] : $col,
555 // 'renderer' => array($this, 'getThumb'),
556 // 'color' => 'yellow', // set color for the cell which is a header element
557 // 'fillBlank' => 'gray', // set
560 if (!empty($this->do) && method_exists($this->do, 'toSimpleExcelColumn')) {
561 $add = $this->do->toSimpleExcelColumn($add);
564 $se_config['cols'][] = $add;
569 $se = new Pman_Core_SimpleExcel(array(),$se_config);
572 //fputcsv($fh, $titles);
576 $se->addLine($se_config['workbook'], $x);
580 $this->jerr('no data found');
583 $se->send($fn .'.xls');
590 * POST method Roo/TABLENAME
591 * -- creates, updates, or deletes data.
594 * if the primary key is empty, this happens
595 * will automatically set these to current date and authUser->id
596 * created, created_by, created_dt
597 * updated, update_by, updated_dt
598 * modified, modified_by, modified_dt
600 * will return a GET request SINGLE SELECT (and accepts same)
603 * _delete=1,2,3 delete a set of data.
605 * if the primary key value is set, then update occurs.
606 * will automatically set these to current date and authUser->id
607 * updated, update_by, updated_dt
608 * modified, modified_by, modified_dt
612 * _delete=1,2,3 causes a delete to occur.
613 * _ids=1,2,3,4 causes update to occur on all primary ids.
616 * = same as single SELECT GET request..
621 * _debug=1 forces debug
622 * _get=1 - causes a get request to occur when doing a POST..
626 * these methods on dataobjects if they exist
628 * checkPerm('E' / 'D' , $authuser)
629 * - can we list the stuff
630 * - return false to disallow...
632 * toRooSingleArray($authUser, $request) : array
633 * - called on single fetch only, add or maniuplate returned array data.
634 * toRooArray($request) : array
635 * - Called if toSingleArray does not exist.
636 * - if you need to return different data than toArray..
639 * (for logging - this is generically prefixed to all database operations.)
643 * called when $_FILES is not empty
646 * setFromRoo($ar, $roo)
647 * - alternative to setFrom() which is called if this method does not exist
648 * - values from post (deal with dates etc.) - return true|error string.
649 * - call $roo->jerr() on failure...
651 * CALLS BEFORE change occurs:
653 * beforeDelete($dependants_array, $roo)
654 * Argument is an array of un-find/fetched dependant items.
655 * - jerr() will stop insert.. (Prefered)
656 * - return false for fail and set DO->err;
658 * beforeUpdate($old, $request,$roo)
659 * - before update - jerr() will stop insert..
660 * beforeInsert($request,$roo)
661 * - before insert - jerr() will stop insert..
664 * CALLS AFTER change occured
666 * onUpdate($old, $request,$roo)
667 * - after update // return value ignored
669 * onInsert($request,$roo)
672 * onDelete($request, $roo) - after delete
676 function post($tab) // update / insert (?? delete??)
678 // -- why was this put in? - Roo is not related to Core.All ?
679 //if (!$this->hasPerm("Core.All", 'E')) {
680 // $this->jerr("PERMISSION DENIED (e)");
682 $this->initErrorHandling();
684 // DB_DataObject::debugLevel(1);
687 if (!empty($_REQUEST['_get'])) {
688 return $this->get($tab);
691 $this->init(); // for pman.
693 $x = $this->dataObject($tab);
695 $this->transObj = clone($x);
697 $this->transObj->query('BEGIN');
698 // find the key and use that to get the thing..
701 $this->jerr('no key');
704 $this->key = $keys[0];
706 // delete should be here...
707 if (isset($_REQUEST['_delete'])) {
708 // do we really delete stuff!?!?!?
709 return $this->delete($x,$_REQUEST);
717 // not sure if this is a good idea here...
719 if (!empty($_REQUEST['_ids'])) {
720 $ids = explode(',',$_REQUEST['_ids']);
721 $x->whereAddIn($this->key, $ids, 'int');
722 $ar = $x->fetchAll();
725 $this->update($x, $_REQUEST);
728 $this->jok("UPDATED");
733 if (!empty($_REQUEST[$this->key])) {
735 if (!$x->get($this->key, $_REQUEST[$this->key])) {
736 $this->jerr("Invalid request (id does not point to a record.)");
738 $this->jok($this->update($x, $_REQUEST));
742 $this->jerr("No data recieved for inserting");
745 $this->jok($this->insert($x, $_REQUEST));
757 * apply REQUEST[sort] and [dir]
758 * sort may be an array of columsn..
760 * @arg DB_DataObject $x
763 function applySort($x, $sort = '', $dir ='')
766 // Db_DataObject::debugLevel(1);
767 $sort = empty($_REQUEST['sort']) || !is_string($_REQUEST['sort']) ? $sort : $_REQUEST['sort'];
768 $dir = empty($_REQUEST['dir']) || !is_string($_REQUEST['dir']) ? $dir : $_REQUEST['dir'];
769 $dir = $dir == 'ASC' ? 'ASC' : 'DESC';
771 $ms = empty($_REQUEST['_multisort']) || !is_string($_REQUEST['_multisort']) ? false : $_REQUEST['_multisort'];
772 //var_Dump($ms);exit;
774 if (method_exists($x, 'applySort')) {
775 $sorted = $x->applySort(
779 array_keys($this->cols),
780 $ms ? json_decode($ms) : false
785 return $this->multiSort($x);
788 if ($sorted === false) {
789 $cols = $x->tableColumns();
790 $excols = array_keys($this->cols);
792 if (isset($x->_extra_cols)) {
793 $excols = array_merge($excols, $x->_extra_cols);
795 $sort_ar = explode(',', $sort);
798 foreach($sort_ar as $sort) {
800 if (strlen($sort) && isset($cols[$sort]) ) {
801 $sort_str[] = $x->tableName() .'.'.$sort . ' ' . $dir ;
803 } else if (in_array($sort, $excols)) {
804 $sort_str[] = $sort . ' ' . $dir ;
809 $x->orderBy(implode(', ', $sort_str ));
820 function multiSort($x)
822 //DB_DataObject::debugLevel(1);
823 $ms = json_decode($_REQUEST['_multisort']);
824 if (!isset($ms->order) || !is_array($ms->order)) {
829 $cols = $x->tableColumns();
831 //print_r($this->cols);exit;
832 // this-><cols contains colname => aliased name...
833 foreach($ms->order as $col) {
834 if (!isset($ms->sort->{$col})) {
835 continue; // no direction..
837 $ms->sort->{$col} = $ms->sort->{$col} == 'ASC' ? 'ASC' : 'DESC';
839 if (strlen($col) && isset($cols[$col]) ) {
840 $sort_str[] = $x->tableName() .'.'.$col . ' ' . $ms->sort->{$col};
843 //print_r($this->cols);
845 if (in_array($col, array_keys($this->cols))) {
846 $sort_str[] = $col. ' ' . $ms->sort->{$col};
849 if (isset($x->_extra_cols) && in_array($col, $x->_extra_cols)) {
850 $sort_str[] = $col. ' ' . $ms->sort->{$col};
855 $x->orderBy(implode(', ', $sort_str ));
862 * - used when _id is set, or after insert or update
864 * @param DataObject $x the dataobject to use
865 * @param int $id the pid of the object
866 * @param array $req the request, or false if it comes from insert/update.
869 function selectSingle($x, $id, $req=false)
873 $_columns = !empty($req['_columns']) ? explode(',', $req['_columns']) : false;
875 //var_dump(array(!is_array($id) , empty($id)));
876 if (!is_array($id) && empty($id)) {
879 if (method_exists($x, 'toRooSingleArray')) {
880 $this->jok($x->toRooSingleArray($this->authUser, $req));
882 if (method_exists($x, 'toRooArray')) {
883 $this->jok($x->toRooArray($req));
886 $this->jok($x->toArray());
890 $this->loadMap($x, array(
891 'columns' => $_columns,
894 if ($req !== false) {
895 $this->setFilters($x, $req);
896 } else if (method_exists($x, 'applyFilters')) {
897 // always call apply filters even after update/insert...
898 // however arguments are not passed.
899 $x->applyFilters(array('_is_update_request' => true), $this->authUser, $this);
902 // DB_DataObject::DebugLevel(1);
905 $x->setFrom($req['lookup'] );
907 if (!$x->find(true)) {
908 if (!empty($id['_id'])) {
910 $this->jok($x->toArray());
915 } else if (!$x->get($id)) {
916 $this->jerr("selectSingle: no such record ($id)");
919 // ignore perms if comming from update/insert - as it's already done...
920 if ($req !== false && !$this->checkPerm($x,'S')) {
921 $this->jerr("PERMISSION DENIED - si");
923 // different symantics on all these calls??
924 if (method_exists($x, 'toRooSingleArray')) {
925 $this->jok($x->toRooSingleArray($this->authUser, $req));
927 if (method_exists($x, 'toRooArray')) {
928 $this->jok($x->toRooArray($req));
930 $this->jok($x->toArray());
935 function insert($x, $req, $with_perm_check = true)
937 if (method_exists($x, 'setFromRoo')) {
938 $res = $x->setFromRoo($req, $this);
939 if (is_string($res)) {
940 $this->jerror("NOTICE-INSERT", $res);
946 if ( $with_perm_check && !$this->checkPerm($x,'A', $req)) {
947 $this->jerr("PERMISSION DENIED {$x->tableName()}:checkPerm(A)");
949 $cols = $x->tableColumns();
951 if (isset($cols['created'])) {
952 $x->created = date('Y-m-d H:i:s');
954 if (isset($cols['created_dt'])) {
955 $x->created_dt = date('Y-m-d H:i:s');
957 if (isset($cols['created_by'])) {
958 $x->created_by = $this->authUser->id;
961 if (isset($cols['modified'])) {
962 $x->modified = date('Y-m-d H:i:s');
964 if (isset($cols['modified_dt'])) {
965 $x->modified_dt = date('Y-m-d H:i:s');
967 if (isset($cols['modified_by'])) {
968 $x->modified_by = $this->authUser->id;
971 if (isset($cols['updated'])) {
972 $x->updated = date('Y-m-d H:i:s');
974 if (isset($cols['updated_dt'])) {
975 $x->updated_dt = date('Y-m-d H:i:s');
977 if (isset($cols['updated_by'])) {
978 $x->updated_by = $this->authUser->id;
981 if (method_exists($x, 'beforeInsert')) {
982 $x->beforeInsert($_REQUEST, $this);
987 if ($res === false) {
988 $this->jerr($x->_lastError->toString());
990 $ev = $this->addEvent("ADD", $x);
991 if (method_exists($x, 'onInsert')) {
993 $x->onInsert($_REQUEST, $this, $ev);
1000 // note setFrom might handle this before hand...!??!
1001 if (!empty($_FILES) && method_exists($x, 'onUpload')) {
1002 $x->onUpload($this, $_REQUEST);
1005 return $this->selectSingle(
1006 DB_DataObject::factory($x->tableName()),
1012 function updateLock($x, $req )
1014 Pman::$permitError = true; // allow it to fail without dieing
1016 $lock = DB_DataObjecT::factory('Core_locking');
1017 Pman::$permitError = false;
1018 if (is_a($lock,'DB_DataObject') && $this->authUser) {
1020 $lock->on_id = $x->{$this->key};
1021 $lock->on_table= strtolower($x->tableName());
1022 if (!empty($_REQUEST['_lock_id'])) {
1023 $lock->whereAdd('id != ' . ((int)$_REQUEST['_lock_id']));
1025 $lock->whereAdd('person_id !=' . $this->authUser->id);
1028 $llc = clone($lock);
1029 $exp = date('Y-m-d', strtotime('NOW - 1 WEEK'));
1030 $llc->whereAdd("created < '$exp'");
1031 if ($llc->count()) {
1033 while($llc->fetch()) {
1034 $llcd = clone($llc);
1040 if ($lock->find(true)) {
1041 // it's locked by someone else..
1042 $p = $lock->person();
1045 $this->jerr( "Record was locked by " . $p->name . " at " .$lock->created.
1046 " - Please confirm you wish to save"
1047 , array('needs_confirm' => true));
1051 // check the users lock.. - no point.. ??? - if there are no other locks and it's not the users, then they can
1052 // edit it anyways...
1054 // can we find the user's lock.
1055 $lock = DB_DataObjecT::factory('Core_locking');
1056 $lock->on_id = $x->{$this->key};
1057 $lock->on_table= strtolower($x->tableName());
1058 $lock->person_id = $this->authUser->id;
1059 $lock->orderBy('created DESC');
1063 $lock->find(true) &&
1064 isset($x->modified_dt) &&
1065 strtotime($x->modified_dt) > strtotime($lock->created) &&
1066 empty($req['_submit_confirmed']) &&
1067 $x->modified_by != $this->authUser->id
1070 $p = DB_DataObject::factory('core_person');
1071 $p->get($x->modified_by);
1072 $this->jerr($p->name . " saved the record since you started editing,\nDo you really want to update it?", array('needs_confirm' => true));
1084 function update($x, $req, $with_perm_check = true)
1086 if ( $with_perm_check && !$this->checkPerm($x,'E', $req) ) {
1087 $this->jerr("PERMISSION DENIED - No Edit permissions on this element");
1090 // check any locks..
1091 // only done if we recieve a lock_id.
1092 // we are very trusing here.. that someone has not messed around with locks..
1093 // the object might want to check in their checkPerm - if locking is essential..
1094 $lock = $this->updateLock($x,$req);
1104 // this lot is generic.. needs moving
1105 if (method_exists($x, 'setFromRoo')) {
1106 $res = $x->setFromRoo($req, $this);
1107 if (is_string($res)) {
1116 //echo '<PRE>';print_r($old);print_r($x);exit;
1119 $cols = $x->tableColumns();
1121 if (isset($cols['modified'])) {
1122 $x->modified = date('Y-m-d H:i:s');
1124 if (isset($cols['modified_dt'])) {
1125 $x->modified_dt = date('Y-m-d H:i:s');
1127 if (isset($cols['modified_by']) && $this->authUser) {
1128 $x->modified_by = $this->authUser->id;
1131 if (isset($cols['updated'])) {
1132 $x->updated = date('Y-m-d H:i:s');
1134 if (isset($cols['updated_dt'])) {
1135 $x->updated_dt = date('Y-m-d H:i:s');
1137 if (isset($cols['updated_by']) && $this->authUser) {
1138 $x->updated_by = $this->authUser->id;
1141 if (method_exists($x, 'beforeUpdate')) {
1142 $x->beforeUpdate($old, $req, $this);
1145 if ($with_perm_check && !empty($_FILES) && method_exists($x, 'onUpload')) {
1146 $x->onUpload($this, $_REQUEST);
1149 //DB_DataObject::DebugLevel(1);
1150 $res = $x->update($old);
1151 if ($res === false) {
1152 $this->jerr($x->_lastError->toString());
1154 $ev = $this->addEvent("EDIT", $x);
1156 if (method_exists($x, 'onUpdate')) {
1157 $x->onUpdate($old, $req, $this, $ev);
1160 $ev->audit($x, $old);
1164 return $this->selectSingle(
1165 DB_DataObject::factory($x->tableName()),
1171 * Delete a number of records.
1172 * calls $delete_obj->beforeDelete($array_of_dependant_dataobjects, $this)
1176 function delete($x, $req)
1178 // do we really delete stuff!?!?!?
1179 if (empty($req['_delete'])) {
1180 $this->jerr("Delete Requested with no value");
1184 // build a list of tables to queriy for dependant data..
1189 $all_links = $x->databaseLinks();
1191 foreach($all_links as $tbl => $links) {
1192 foreach($links as $col => $totbl_col) {
1193 $to = explode(':', $totbl_col);
1194 if ($to[0] != $x->tableName()) {
1198 $affects[$tbl .'.' . $col] = true;
1203 // echo '<PRE>';print_r($affects);exit;
1204 // DB_Dataobject::debugLevel(1);
1209 $bits = array_map(function($v) { return (int)$v; } , explode(',', $req['_delete']));
1211 // let's assume it has a key!!!
1213 $x->whereAdd($this->key .' IN ('. implode(',', $bits) .')');
1215 $this->jerror("NOTICE-DELETE","Nothing found to delete");
1218 while ($x->fetch()) {
1224 if (!$this->checkPerm($x,'D') ) {
1225 $this->jerr("PERMISSION DENIED (d)");
1228 $match_ar = array();
1229 foreach($affects as $k=> $true) {
1230 $ka = explode('.', $k);
1232 $chk = DB_DataObject::factory($ka[0]);
1233 if (!is_a($chk,'DB_DataObject') && !is_a($chk,'PDO_DataObject')) {
1234 $this->jerr('Unable to load referenced table, check the links config: ' .$ka[0]);
1236 // print_r(array($chk->tablename() , $ka[1] , $xx->tablename() , $this->key ));
1237 $chk->{$ka[1]} = $xx->{$this->key};
1239 if (count($chk->keys())) {
1240 $matches = $chk->count();
1242 //DB_DataObject::DebugLevel(1);
1243 $matches = $chk->count($ka[1]);
1247 $chk->_match_key = $ka[1];
1248 $match_ar[] = clone($chk);
1254 $has_beforeDelete = method_exists($xx, 'beforeDelete');
1255 // before delte = allows us to trash dependancies if needed..
1258 if ( $has_beforeDelete ) {
1259 if ($xx->beforeDelete($match_ar, $this, $_REQUEST) === false) {
1260 $errs[] = "Delete failed ({$xx->id})\n".
1261 (isset($xx->err) ? $xx->err : '');
1264 // refetch affects..
1266 $match_ar = array();
1267 foreach($affects as $k=> $true) {
1268 $ka = explode('.', $k);
1269 $chk = DB_DataObject::factory($ka[0]);
1270 if (!is_a($chk,'DB_DataObject') && !is_a($chk,'PDO_DataObject')) {
1271 $this->jerr('Unable to load referenced table, check the links config: ' .$ka[0]);
1273 $chk->{$ka[1]} = $xx->{$this->key};
1274 $matches = $chk->count();
1275 $match_total += $matches;
1277 $chk->_match_key = $ka[1];
1278 $match_ar[] = clone($chk);
1285 if (!empty($match_ar)) {
1286 $chk = $match_ar[0];
1288 $o = $chk->fetchAll();
1289 $key = isset($chk->_match_key) ?$chk->_match_key : '?unknown column?';
1290 $desc = $chk->tableName(). '.' . $key .'='.$xx->{$this->key} ;
1291 if (method_exists($chk, 'toEventString')) {
1292 $desc .= ' : ' . $o[0]->toEventString();
1294 $this->jerror("NOTICE-DELETE-DEP", "Delete Dependant records ($match_total found), " .
1295 "first is ( $desc )");
1301 DB_DataObject::Factory('Events')->logDeletedRecord($x);
1303 $this->addEvent("DELETE", $x);
1307 if (method_exists($xx,'onDelete')) {
1308 $xx->onDelete($req, $this);
1314 $this->jerr(implode("\n<BR>", $errs));
1316 $this->jok("Deleted");
1322 * cols stores the list of columns that are available from the query.
1325 * This is a dupe of what is in autojoin -- we should move to using autojoin really.
1337 var $cols = array();
1341 function loadMap($do, $cfg =array()) //$onlycolumns=false, $distinct = false)
1343 //DB_DataObject::debugLevel(5);
1344 $onlycolumns = !empty($cfg['columns']) ? $cfg['columns'] : false;
1345 $distinct = !empty($cfg['distinct']) ? $cfg['distinct'] : false;
1346 $excludecolumns = !empty($cfg['exclude']) ? $cfg['exclude'] : array();
1348 $excludecolumns[] = 'passwd'; // we never expose passwords
1349 $excludecolumns[] = 'oath_key';
1351 $ret = $do->autoJoin(array(
1352 'include' => $onlycolumns,
1353 'exclude' => $excludecolumns,
1354 'distinct' => $distinct
1357 $this->countWhat = $ret['count'];
1358 $this->cols = $ret['cols'];
1359 $this->colsJname = $ret['join_names'];
1368 * generate the meta data neede by queries.
1371 function meta($x, $data)
1373 // this is not going to work on queries where the data does not match the database def..
1374 // for unknown columns we send them as stirngs..
1376 $cols = array_keys($data[0]);
1380 if (class_exists('PDO_DataObject')) {
1381 $options = PDO_DataObject::config();
1382 if (!file_exists($options["schema_location"] . '.reader')) {
1386 $rdata = unserialize(file_get_contents($options["schema_location"] . '.reader'));
1389 //echo '<PRE>';print_r($this->cols); exit;
1390 $options = &PEAR::getStaticProperty('DB_DataObject','options');
1391 $reader = $options["ini_{$x->databaseNickname()}"] .'.reader';
1392 if (!file_exists( $reader )) {
1396 $rdata = unserialize(file_get_contents($reader));
1399 //echo '<PRE>';print_r($this->cols);exit;
1400 //echo '<PRE>';print_r($rdata);exit;
1401 // echo '<PRE>';print_r($rdata);exit;
1404 $key = empty($keys) ? 'id' : $keys[0];
1408 foreach($cols as $c ) {
1409 if (!isset($this->cols[$c]) || !isset($rdata[$this->cols[$c]]) || !is_array($rdata[$this->cols[$c]])) {
1413 $add = $rdata[$this->cols[$c]];
1418 'totalProperty' => 'total',
1419 'successProperty' => 'success',
1421 'id' => $key, // was 'id'...
1428 function setFilters($x, $q)
1430 // if a column is type int, and we get ',' -> the it should be come an inc clause..
1431 // DB_DataObject::debugLevel(1);
1432 if (method_exists($x, 'applyFilters')) {
1433 // DB_DataObject::debugLevel(1);
1434 if (false === $x->applyFilters($q, $this->authUser, $this)) {
1438 $q_filtered = array();
1442 foreach($q as $key=>$val) {
1444 if (in_array($key,$keys) && !is_array($val)) {
1449 // handles name[]=fred&name[]=brian => name in ('fred', 'brian').
1450 // value is an array..
1451 if (is_array($val) ) {
1455 if ($key[0] == '!') {
1457 $key = substr($key,1);
1460 if (!in_array( $key, array_keys($this->cols))) {
1464 // support a[0] a[1] ..... => whereAddIn(
1467 foreach($val as $k=>$v) {
1468 if (!is_numeric($k)) {
1472 // FIXME: note this is not typesafe for anything other than mysql..
1474 if (!is_numeric($v) || !is_long($v)) {
1483 $x->whereAddIn($pref . (
1484 isset($this->colsJname[$key]) ?
1485 $this->colsJname[$key] :
1486 ($x->tableName(). '.'.$key)),
1487 $ar, $quote ? 'string' : 'int');
1494 // handles !name=fred => name not equal fred.
1495 if ($key[0] == '!' && in_array(substr($key, 1), array_keys($this->cols))) {
1497 $key = substr($key, 1) ;
1500 isset($this->colsJname[$key]) ?
1501 $this->colsJname[$key] :
1502 $x->tableName(). '.'.$key ) . ' != ' .
1503 (is_numeric($val) ? $val : "'". $x->escape($val) . "'")
1513 // Events and remarks -- fixme - move to events/remarsk...
1514 case 'on_id': // where TF is this used...
1515 if (!empty($q['query']['original'])) {
1516 // DB_DataObject::debugLevel(1);
1517 $o = (int) $q['query']['original'];
1519 $x->whereAdd("(on_id = $oid OR
1520 on_id IN ( SELECT distinct(id) FROM Documents WHERE original = $o )
1529 if (strlen($val) && $key[0] != '_') {
1530 $q_filtered[$key] = $val;
1533 // subjoined columns = check the values.
1534 // note this is not typesafe for anything other than mysql..
1536 if (isset($this->colsJname[$key])) {
1538 // the aobve rule for !strlen non-joined cols should apply to joined ones.
1539 if (!strlen($val)) {
1545 if (!is_numeric($val) || !is_long($val)) {
1548 $x->whereAdd( "{$this->colsJname[$key]} = " . ($quote ? "'". $x->escape($val) ."'" : $val));
1556 if (!empty($q_filtered)) {
1557 //var_dump($q_filtered);
1561 $x->setFrom($q_filtered);
1567 // nice generic -- let's get rid of it.. where is it used!!!!
1569 // Person / Group / Comapnies.... most of my queries noww...
1571 if (!empty($q['query']['name'])) {
1574 if (in_array( 'name', array_keys($x->table()))) {
1575 $x->whereAdd($x->tableName().".name LIKE '". $x->escape($q['query']['name']) . "%'");
1580 // - projectdirectory staff list - persn queuy
1585 * create the dataobject from (usually the url)
1586 * This uses $this->validTables
1587 * $this->validPrefix (later..)
1588 * to determine if class can be created..
1592 function dataObject($tab)
1594 if (is_array($this->validTables) && !in_array($tab,$this->validTables)) {
1595 $this->jerr("Invalid url - not listed in validTables");
1597 $tab = str_replace('/', '',$tab); // basic protection??
1599 $pm = HTML_FlexyFramework::get()->Pman;
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');