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..
60 var $countWhat; // set in loadMap
66 parent::getAuth(); // load company!
67 $au = $this->getAuthUser();
70 $this->jerror("LOGIN-NOAUTH", "Not authenticated", array('authFailure' => true));
72 if (!$au->pid() ) { // not set up yet..
73 $this->jerror("LOGIN-NOAUTH", "Not authenticated", array('authFailure' => true));
77 $this->authUser = $au;
81 * GET method Roo/TABLENAME
83 * Generally for SELECT or Single SELECT
86 * _id=value single fetch based on primary id.
87 * can be '0' if you want to fetch a set of defaults
88 * Use in conjuntion with toRooSingleArray()
90 * lookup[key]=value single fetch based on a single key value lookup.
91 * multiple key/value can be used. eg. ontable+onid..
92 * _columns what to return.
94 * _no_count skip the default count query.
95 * use the number of records in the query result as the total
99 * - all tables are always autojoined.
103 * _columns=a,b,c,d comma seperated list of columns.
104 * _exclude_columns=a,b,c,d comma seperated list of columns.
105 * _distinct=name a distinct column lookup. you also have to use _columns with this.
108 * colname = ... => colname = ....
109 * !colname=.... => colname != ....
110 * !colname[0]=... !colname[1]=... => colname NOT IN (.....) ** only supports main table at present..
111 * colname[0]=... colname[1]=... => colname IN (.....) ** only supports main table at present..
114 * sort=name what to sort.
115 * sort=a,b,d can support multiple columns
116 * dir=ASC what direction
117 * _multisort ={...} JSON encoded { sort : { row : direction }, order : [ row, row, row ] }
120 * start=0 limit start
121 * limit=25 limit number
125 * csvCols[0] csvCols[1].... = .... column titles for CSV output
126 * csvTitles[0], csvTitles[1] .... = columns to use for CSV output
129 * _toggleActive !:!:!:! - this hsould not really be here..
130 * query[add_blank] - add a line in with an empty option... - not really needed???
131 * _delete = delete a list of ids element. (depricated.. this will be removed...)
134 * _post =1 = simulate a post with debuggin on.
135 * _debug_post << This is prefered, as _post may overlap with accouting posts..
137 * _debug = turn on DB_dataobject deubbing, must be admin at present..
140 * CALLS methods on dataobjects if they exist
143 * checkPerm('S' , $authuser)
144 * - can we list the stuff
145 * - return false to disallow...
146 * applySort($au, $sortcol, $direction, $array_of_columns, $multisort)
147 * -- does not support multisort at present..
148 * applyFilters($_REQUEST, $authUser, $roo)
149 * -- apply any query filters on data. and hide stuff not to be seen.
150 * -- can exit by calling $roo->jerr()
151 * postListExtra($_REQUEST, $roo, $array_data) : array(extra_name => data)
152 * - add extra column to the jdata return key/value info.
153 * postListFilter($data, $authUser, $request) return $data
154 * - modify the returned array of data (either add stuff to the data, or remove lines etc)
157 * toRooSingleArray($authUser, $request) : array
158 * - called on single fetch only, add or maniuplate returned array data.
159 * - is also called when _id=0 is used (for fetching a default set.)
160 * toRooArray($request) : array
161 * - called if singleArray is unavailable on single fetch.
162 * - always tried for mutiple results.
163 * toArray() - the default method if none of the others are found.
164 * toSimpleExcelColumn($col) - see toCSV - this enables special columns to be created for exported data.
167 * - standard DataObject feature - causes all results to show all
171 * _extra_cols -- if set, then filtering by column etc. will use them.
175 function get($tab, $opts = Array())
177 // $this->jerr("Not authenticated", array('authFailure' => true));
178 //echo '<PRE>';print_R($_GET);
179 //DB_DataObject::debuglevel(1);
181 $this->init(); // from pman.
182 //DB_DataObject::debuglevel(1);
183 HTML_FlexyFramework::get()->generateDataobjectsCache($this->isDev && !empty($_REQUEST['isDev']));
187 if ( $this->checkDebugPost()) {
192 //DB_DAtaObject::debuglevel(1);
193 return $this->post($tab);
197 $this->initErrorHandling();
199 $tt = explode('/', $tab);
200 $tab = array_shift($tt);
201 $x = $this->dataObject($tab);
203 $_columns = !empty($_REQUEST['_columns']) && is_string($_REQUEST['_columns']) ? explode(',', $_REQUEST['_columns']) : false;
206 if (isset( $_REQUEST['lookup'] ) && is_array($_REQUEST['lookup'] )) { // single fetch based on key/value pairs
207 $this->selectSingle($x, $_REQUEST['lookup'],$_REQUEST);
212 // single fetch (use '0' to fetch an empty object..)
213 if (isset($_REQUEST['_id']) && is_numeric($_REQUEST['_id'])) {
215 $this->selectSingle($x, $_REQUEST['_id'],$_REQUEST);
222 if (isset($_REQUEST['_delete'])) {
223 $this->jerr("DELETE by GET has been removed - update the code to use POST");
230 if (isset($_REQUEST['_toggleActive'])) {
231 // do we really delete stuff!?!?!?
232 if (!$this->hasPerm("Core.Staff", 'E')) {
233 $this->jerr("PERMISSION DENIED (ta)");
235 $clean = create_function('$v', 'return (int)$v;');
236 $bits = array_map($clean, explode(',', $_REQUEST['_toggleActive']));
237 if (in_array($this->authUser->id, $bits) && $this->authUser->active) {
238 $this->jerr("you can not disable yourself");
240 $x->query('UPDATE core_person SET active = !active WHERE id IN (' .implode(',', $bits).')');
241 $this->addEvent("USERTOGGLE", false, implode(',', $bits));
242 $this->jok("Updated");
245 //DB_DataObject::debugLevel(1);
247 // sets map and countWhat
248 $this->loadMap($x, array(
249 'columns' => $_columns,
250 'distinct' => empty($_REQUEST['_distinct']) ? false: $_REQUEST['_distinct'],
251 'exclude' => empty($_REQUEST['_exclude_columns']) ? false: explode(',', $_REQUEST['_exclude_columns'])
255 $this->setFilters($x,$_REQUEST);
257 if (!$this->checkPerm($x,'S', $_REQUEST)) {
258 $this->jerror("NOTICE-NOPERM", "PERMISSION DENIED (g)");
262 // build join if req.
263 //DB_DataObject::debugLevel(1);
264 // count with multiple joins and no conditions can be quite slow - so if there are no conditions - just remove the joins from the count.
266 $old_where = $x->whereAdd();
267 if (empty($old_where )) {
270 $x->whereAdd($old_where);
275 if (!isset($_REQUEST['_no_count'])) {
276 $total = $xx->count($this->countWhat);
278 if (isset($xx->_real_total)) { // this is used when we subquery the search.
279 $total = $xx->_real_total;
283 // var_dump($total);exit;
284 $this->applySort($x);
288 if (!empty($_REQUEST['_distinct']) && $total !== false && $total < 400) {
295 empty($_REQUEST['start']) ? 0 : (int)$_REQUEST['start'],
296 min(empty($_REQUEST['limit']) ? 25 : (int)$_REQUEST['limit'], $this->max_limit)
299 $queryObj = clone($x);
300 //DB_DataObject::debuglevel(1);
302 $this->sessionState(0);
304 $this->sessionState(1);
306 if (false === $res) {
307 $this->jerr($x->_lastError->toString());
315 // ---------------- THESE ARE DEPRICATED.. they should be moved to the model...
318 if (!empty($_REQUEST['query']['add_blank'])) {
319 $ret[] = array( 'id' => 0, 'name' => '----');
320 $total === false ? false : $total+1;
323 $rooar = method_exists($x, 'toRooArray');
324 $_columnsf = $_columns ? array_flip($_columns) : false;
325 while ($x->fetch()) {
327 $add = $rooar ? $x->toRooArray($_REQUEST) : $x->toArray();
328 if ($add === false) {
331 $ret[] = !$_columns ? $add : array_intersect_key($add, $_columnsf);
335 $ret = array_slice($ret,
336 empty($_REQUEST['start']) ? 0 : (int)$_REQUEST['start'],
337 min(empty($_REQUEST['limit']) ? 25 : (int)$_REQUEST['limit'], 10000)
344 if (method_exists($queryObj ,'postListExtra')) {
345 $extra = $queryObj->postListExtra($_REQUEST, $this, $ret);
349 // filter results, and add any data that is needed...
350 if (method_exists($x,'postListFilter')) {
351 $ret = $x->postListFilter($ret, $this->authUser, $_REQUEST, $this);
356 if (!empty($_REQUEST['csvCols']) && !empty($_REQUEST['csvTitles']) ) {
359 $this->toCsv($ret, $_REQUEST['csvCols'], $_REQUEST['csvTitles'],
360 empty($_REQUEST['csvFilename']) ? '' : $_REQUEST['csvFilename'] );
367 if (!empty($_REQUEST['_requestMeta']) && count($ret)) {
368 $meta = $this->meta($x, $ret);
370 $extra = $extra ? $extra: array();
371 $extra['metaData'] = $meta;
374 // this make take some time...
375 $this->sessionState(0);
376 // echo "<PRE>"; print_r($ret);
377 $this->jdata($ret, max(count($ret), $total === false ? 0 : $total), $extra );
381 function checkDebug($req = false)
383 $req = $req === false ? $_REQUEST : $req;
385 if (empty($req['_debug'])) {
389 if (!empty($_SERVER['HTTP_HOST']) && $_SERVER['HTTP_HOST'] == 'localhost') {
390 DB_DAtaObject::debuglevel((int)$req['_debug']);
398 method_exists($this->authUser,'canDebug')
400 $this->authUser->canDebug()
405 method_exists($this->authUser,'groups')
407 is_a($this->authUser, 'Pman_Core_DataObjects_Core_person')
409 in_array('Administrators', $this->authUser->groups('name'))
414 DB_DAtaObject::debuglevel((int)$req['_debug']);
419 function checkDebugPost()
421 if (empty($_GET['_post']) && empty($_GET['_debug_post'])) {
424 // localhost can do anything...
425 if (!empty($_SERVER['HTTP_HOST']) && $_SERVER['HTTP_HOST'] == 'localhost') {
428 return $this->authUser &&
429 method_exists($this->authUser,'groups') &&
430 in_array('Administrators', $this->authUser->groups('name'));
434 function checkPerm($obj, $lvl, $req= null)
436 if (!method_exists($obj, 'checkPerm')) {
439 if ($obj->checkPerm($lvl, $this->authUser, $req)) {
445 function toCsv($data, $cols, $titles, $filename, $addDate = true)
448 $this->sessionState(0); // turn off sessions - no locking..
450 require_once 'Pman/Core/SimpleExcel.php';
452 $fn = (empty($filename) ? 'list-export-' : urlencode($filename)) . (($addDate) ? date('Y-m-d') : '') ;
456 'workbook' => substr($fn, 0, 31),
463 if (is_object($data)) {
464 $rooar = method_exists($data, 'toRooArray');
465 while($data->fetch()) {
466 $x = $rooar ? $data->toRooArray($q) : $data->toArray();
468 if ($cols == '*') { /// did we get cols sent to us?
469 $cols = array_keys($x);
472 if(!is_array($cols)) {
473 $cols = explode(',', $cols);
476 if ($titles !== false) {
478 $titles= array_keys($x);
480 if(!is_array($titles)) {
481 $titles = explode(',', $titles);
483 foreach($cols as $i=>$col) {
485 'header'=> isset($titles[$i]) ? $titles[$i] : $col,
488 // 'renderer' => array($this, 'getThumb'),
489 // 'color' => 'yellow', // set color for the cell which is a header element
490 // 'fillBlank' => 'gray', // set
493 if (method_exists($data, 'toSimpleExcelColumn')) {
494 $add = $data->toSimpleExcelColumn($add);
497 $se_config['cols'][] = $add;
502 $se = new Pman_Core_SimpleExcel(array(), $se_config);
508 $se->addLine($se_config['workbook'], $x);
514 $this->jerr('no data found', false, 'text/plain');
516 $se->send($fn .'.xls');
521 foreach($data as $x) {
522 //echo "<PRE>"; print_r(array($_REQUEST['csvCols'], $x->toArray())); exit;
526 $cols= array_keys($x);
529 if(!is_array($cols)) {
530 $cols = explode(',', $cols);
533 if ($titles !== false) {
535 $titles= array_keys($x);
538 if(!is_array($titles)) {
539 $titles = explode(',', $titles);
542 foreach($cols as $i=>$col) {
544 'header'=> isset($titles[$i]) ? $titles[$i] : $col,
547 // 'renderer' => array($this, 'getThumb'),
548 // 'color' => 'yellow', // set color for the cell which is a header element
549 // 'fillBlank' => 'gray', // set
552 if (!empty($this->do) && method_exists($this->do, 'toSimpleExcelColumn')) {
553 $add = $this->do->toSimpleExcelColumn($add);
556 $se_config['cols'][] = $add;
561 $se = new Pman_Core_SimpleExcel(array(),$se_config);
564 //fputcsv($fh, $titles);
568 $se->addLine($se_config['workbook'], $x);
572 $this->jerr('no data found');
575 $se->send($fn .'.xls');
582 * POST method Roo/TABLENAME
583 * -- creates, updates, or deletes data.
586 * if the primary key is empty, this happens
587 * will automatically set these to current date and authUser->id
588 * created, created_by, created_dt
589 * updated, update_by, updated_dt
590 * modified, modified_by, modified_dt
592 * will return a GET request SINGLE SELECT (and accepts same)
595 * _delete=1,2,3 delete a set of data.
597 * if the primary key value is set, then update occurs.
598 * will automatically set these to current date and authUser->id
599 * updated, update_by, updated_dt
600 * modified, modified_by, modified_dt
604 * _delete=1,2,3 causes a delete to occur.
605 * _ids=1,2,3,4 causes update to occur on all primary ids.
608 * = same as single SELECT GET request..
613 * _debug=1 forces debug
614 * _get=1 - causes a get request to occur when doing a POST..
618 * these methods on dataobjects if they exist
620 * checkPerm('E' / 'D' , $authuser)
621 * - can we list the stuff
622 * - return false to disallow...
624 * toRooSingleArray($authUser, $request) : array
625 * - called on single fetch only, add or maniuplate returned array data.
626 * toRooArray($request) : array
627 * - Called if toSingleArray does not exist.
628 * - if you need to return different data than toArray..
631 * (for logging - this is generically prefixed to all database operations.)
635 * called when $_FILES is not empty
638 * setFromRoo($ar, $roo)
639 * - alternative to setFrom() which is called if this method does not exist
640 * - values from post (deal with dates etc.) - return true|error string.
641 * - call $roo->jerr() on failure...
643 * CALLS BEFORE change occurs:
645 * beforeDelete($dependants_array, $roo)
646 * Argument is an array of un-find/fetched dependant items.
647 * - jerr() will stop insert.. (Prefered)
648 * - return false for fail and set DO->err;
650 * beforeUpdate($old, $request,$roo)
651 * - before update - jerr() will stop insert..
652 * beforeInsert($request,$roo)
653 * - before insert - jerr() will stop insert..
656 * CALLS AFTER change occured
658 * onUpdate($old, $request,$roo)
659 * - after update // return value ignored
661 * onInsert($request,$roo)
664 * onDelete($request, $roo) - after delete
668 function post($tab) // update / insert (?? delete??)
670 // -- why was this put in? - Roo is not related to Core.All ?
671 //if (!$this->hasPerm("Core.All", 'E')) {
672 // $this->jerr("PERMISSION DENIED (e)");
674 $this->initErrorHandling();
676 // DB_DataObject::debugLevel(1);
679 if (!empty($_REQUEST['_get'])) {
680 return $this->get($tab);
683 $this->init(); // for pman.
685 $x = $this->dataObject($tab);
687 $this->transObj = clone($x);
689 $this->transObj->query('BEGIN');
690 // find the key and use that to get the thing..
693 $this->jerr('no key');
696 $this->key = $keys[0];
698 // delete should be here...
699 if (isset($_REQUEST['_delete'])) {
700 // do we really delete stuff!?!?!?
701 return $this->delete($x,$_REQUEST);
709 // not sure if this is a good idea here...
711 if (!empty($_REQUEST['_ids'])) {
712 $ids = explode(',',$_REQUEST['_ids']);
713 $x->whereAddIn($this->key, $ids, 'int');
714 $ar = $x->fetchAll();
717 $this->update($x, $_REQUEST);
720 $this->jok("UPDATED");
725 if (!empty($_REQUEST[$this->key])) {
727 if (!$x->get($this->key, $_REQUEST[$this->key])) {
728 $this->jerr("Invalid request (id does not point to a record.)");
730 $this->jok($this->update($x, $_REQUEST));
734 $this->jerr("No data recieved for inserting");
737 $this->jok($this->insert($x, $_REQUEST));
749 * apply REQUEST[sort] and [dir]
750 * sort may be an array of columsn..
752 * @arg DB_DataObject $x
755 function applySort($x, $sort = '', $dir ='')
758 // Db_DataObject::debugLevel(1);
759 $sort = empty($_REQUEST['sort']) || !is_string($_REQUEST['sort']) ? $sort : $_REQUEST['sort'];
760 $dir = empty($_REQUEST['dir']) || !is_string($_REQUEST['dir']) ? $dir : $_REQUEST['dir'];
761 $dir = $dir == 'ASC' ? 'ASC' : 'DESC';
763 $ms = empty($_REQUEST['_multisort']) || !is_string($_REQUEST['_multisort']) ? false : $_REQUEST['_multisort'];
764 //var_Dump($ms);exit;
766 if (method_exists($x, 'applySort')) {
767 $sorted = $x->applySort(
771 array_keys($this->cols),
772 $ms ? json_decode($ms) : false
777 return $this->multiSort($x);
780 if ($sorted === false) {
781 $cols = $x->tableColumns();
782 $excols = array_keys($this->cols);
784 if (isset($x->_extra_cols)) {
785 $excols = array_merge($excols, $x->_extra_cols);
787 $sort_ar = explode(',', $sort);
790 foreach($sort_ar as $sort) {
792 if (strlen($sort) && isset($cols[$sort]) ) {
793 $sort_str[] = $x->tableName() .'.'.$sort . ' ' . $dir ;
795 } else if (in_array($sort, $excols)) {
796 $sort_str[] = $sort . ' ' . $dir ;
801 $x->orderBy(implode(', ', $sort_str ));
812 function multiSort($x)
814 //DB_DataObject::debugLevel(1);
815 $ms = json_decode($_REQUEST['_multisort']);
816 if (!isset($ms->order) || !is_array($ms->order)) {
821 $cols = $x->tableColumns();
823 //print_r($this->cols);exit;
824 // this-><cols contains colname => aliased name...
825 foreach($ms->order as $col) {
826 if (!isset($ms->sort->{$col})) {
827 continue; // no direction..
829 $ms->sort->{$col} = $ms->sort->{$col} == 'ASC' ? 'ASC' : 'DESC';
831 if (strlen($col) && isset($cols[$col]) ) {
832 $sort_str[] = $x->tableName() .'.'.$col . ' ' . $ms->sort->{$col};
835 //print_r($this->cols);
837 if (in_array($col, array_keys($this->cols))) {
838 $sort_str[] = $col. ' ' . $ms->sort->{$col};
841 if (isset($x->_extra_cols) && in_array($col, $x->_extra_cols)) {
842 $sort_str[] = $col. ' ' . $ms->sort->{$col};
847 $x->orderBy(implode(', ', $sort_str ));
854 * - used when _id is set, or after insert or update
856 * @param DataObject $x the dataobject to use
857 * @param int $id the pid of the object
858 * @param array $req the request, or false if it comes from insert/update.
861 function selectSingle($x, $id, $req=false)
865 $_columns = !empty($req['_columns']) ? explode(',', $req['_columns']) : false;
867 //var_dump(array(!is_array($id) , empty($id)));
868 if (!is_array($id) && empty($id)) {
871 if (method_exists($x, 'toRooSingleArray')) {
872 $this->jok($x->toRooSingleArray($this->authUser, $req));
874 if (method_exists($x, 'toRooArray')) {
875 $this->jok($x->toRooArray($req));
878 $this->jok($x->toArray());
882 $this->loadMap($x, array(
883 'columns' => $_columns,
886 if ($req !== false) {
887 $this->setFilters($x, $req);
888 } else if (method_exists($x, 'applyFilters')) {
889 // always call apply filters even after update/insert...
890 // however arguments are not passed.
891 $x->applyFilters(array('_is_update_request' => true), $this->authUser, $this);
894 // DB_DataObject::DebugLevel(1);
897 $x->setFrom($req['lookup'] );
899 if (!$x->find(true)) {
900 if (!empty($id['_id'])) {
902 $this->jok($x->toArray());
907 } else if (!$x->get($id)) {
908 $this->jerr("selectSingle: no such record ($id)");
911 // ignore perms if comming from update/insert - as it's already done...
912 if ($req !== false && !$this->checkPerm($x,'S')) {
913 $this->jerr("PERMISSION DENIED - si");
915 // different symantics on all these calls??
916 if (method_exists($x, 'toRooSingleArray')) {
917 $this->jok($x->toRooSingleArray($this->authUser, $req));
919 if (method_exists($x, 'toRooArray')) {
920 $this->jok($x->toRooArray($req));
922 $this->jok($x->toArray());
927 function insert($x, $req, $with_perm_check = true)
929 if (method_exists($x, 'setFromRoo')) {
930 $res = $x->setFromRoo($req, $this);
931 if (is_string($res)) {
932 $this->jerror("NOTICE-INSERT", $res);
938 if ( $with_perm_check && !$this->checkPerm($x,'A', $req)) {
939 $this->jerr("PERMISSION DENIED {$x->tableName()}:checkPerm(A)");
941 $cols = $x->tableColumns();
943 if (isset($cols['created'])) {
944 $x->created = date('Y-m-d H:i:s');
946 if (isset($cols['created_dt'])) {
947 $x->created_dt = date('Y-m-d H:i:s');
949 if (isset($cols['created_by'])) {
950 $x->created_by = $this->authUser->id;
953 if (isset($cols['modified'])) {
954 $x->modified = date('Y-m-d H:i:s');
956 if (isset($cols['modified_dt'])) {
957 $x->modified_dt = date('Y-m-d H:i:s');
959 if (isset($cols['modified_by'])) {
960 $x->modified_by = $this->authUser->id;
963 if (isset($cols['updated'])) {
964 $x->updated = date('Y-m-d H:i:s');
966 if (isset($cols['updated_dt'])) {
967 $x->updated_dt = date('Y-m-d H:i:s');
969 if (isset($cols['updated_by'])) {
970 $x->updated_by = $this->authUser->id;
973 if (method_exists($x, 'beforeInsert')) {
974 $x->beforeInsert($_REQUEST, $this);
979 if ($res === false) {
980 $this->jerr($x->_lastError->toString());
982 $ev = $this->addEvent("ADD", $x);
983 if (method_exists($x, 'onInsert')) {
985 $x->onInsert($_REQUEST, $this, $ev);
992 // note setFrom might handle this before hand...!??!
993 if (!empty($_FILES) && method_exists($x, 'onUpload')) {
994 $x->onUpload($this, $_REQUEST);
997 return $this->selectSingle(
998 DB_DataObject::factory($x->tableName()),
1004 function updateLock($x, $req )
1006 Pman::$permitError = true; // allow it to fail without dieing
1008 $lock = DB_DataObjecT::factory('Core_locking');
1009 Pman::$permitError = false;
1010 if (is_a($lock,'DB_DataObject') && $this->authUser) {
1012 $lock->on_id = $x->{$this->key};
1013 $lock->on_table= strtolower($x->tableName());
1014 if (!empty($_REQUEST['_lock_id'])) {
1015 $lock->whereAdd('id != ' . ((int)$_REQUEST['_lock_id']));
1017 $lock->whereAdd('person_id !=' . $this->authUser->id);
1020 $llc = clone($lock);
1021 $exp = date('Y-m-d', strtotime('NOW - 1 WEEK'));
1022 $llc->whereAdd("created < '$exp'");
1023 if ($llc->count()) {
1025 while($llc->fetch()) {
1026 $llcd = clone($llc);
1032 if ($lock->find(true)) {
1033 // it's locked by someone else..
1034 $p = $lock->person();
1037 $this->jerr( "Record was locked by " . $p->name . " at " .$lock->created.
1038 " - Please confirm you wish to save"
1039 , array('needs_confirm' => true));
1043 // check the users lock.. - no point.. ??? - if there are no other locks and it's not the users, then they can
1044 // edit it anyways...
1046 // can we find the user's lock.
1047 $lock = DB_DataObjecT::factory('Core_locking');
1048 $lock->on_id = $x->{$this->key};
1049 $lock->on_table= strtolower($x->tableName());
1050 $lock->person_id = $this->authUser->id;
1051 $lock->orderBy('created DESC');
1055 $lock->find(true) &&
1056 isset($x->modified_dt) &&
1057 strtotime($x->modified_dt) > strtotime($lock->created) &&
1058 empty($req['_submit_confirmed']) &&
1059 $x->modified_by != $this->authUser->id
1062 $p = DB_DataObject::factory('core_person');
1063 $p->get($x->modified_by);
1064 $this->jerr($p->name . " saved the record since you started editing,\nDo you really want to update it?", array('needs_confirm' => true));
1076 function update($x, $req, $with_perm_check = true)
1078 if ( $with_perm_check && !$this->checkPerm($x,'E', $req) ) {
1079 $this->jerr("PERMISSION DENIED - No Edit permissions on this element");
1082 // check any locks..
1083 // only done if we recieve a lock_id.
1084 // we are very trusing here.. that someone has not messed around with locks..
1085 // the object might want to check in their checkPerm - if locking is essential..
1086 $lock = $this->updateLock($x,$req);
1096 // this lot is generic.. needs moving
1097 if (method_exists($x, 'setFromRoo')) {
1098 $res = $x->setFromRoo($req, $this);
1099 if (is_string($res)) {
1108 //echo '<PRE>';print_r($old);print_r($x);exit;
1111 $cols = $x->tableColumns();
1113 if (isset($cols['modified'])) {
1114 $x->modified = date('Y-m-d H:i:s');
1116 if (isset($cols['modified_dt'])) {
1117 $x->modified_dt = date('Y-m-d H:i:s');
1119 if (isset($cols['modified_by']) && $this->authUser) {
1120 $x->modified_by = $this->authUser->id;
1123 if (isset($cols['updated'])) {
1124 $x->updated = date('Y-m-d H:i:s');
1126 if (isset($cols['updated_dt'])) {
1127 $x->updated_dt = date('Y-m-d H:i:s');
1129 if (isset($cols['updated_by']) && $this->authUser) {
1130 $x->updated_by = $this->authUser->id;
1133 if (method_exists($x, 'beforeUpdate')) {
1134 $x->beforeUpdate($old, $req, $this);
1137 if ($with_perm_check && !empty($_FILES) && method_exists($x, 'onUpload')) {
1138 $x->onUpload($this, $_REQUEST);
1141 //DB_DataObject::DebugLevel(1);
1142 $res = $x->update($old);
1143 if ($res === false) {
1144 $this->jerr($x->_lastError->toString());
1146 $ev = $this->addEvent("EDIT", $x);
1148 if (method_exists($x, 'onUpdate')) {
1149 $x->onUpdate($old, $req, $this, $ev);
1152 $ev->audit($x, $old);
1156 return $this->selectSingle(
1157 DB_DataObject::factory($x->tableName()),
1163 * Delete a number of records.
1164 * calls $delete_obj->beforeDelete($array_of_dependant_dataobjects, $this)
1168 function delete($x, $req)
1170 // do we really delete stuff!?!?!?
1171 if (empty($req['_delete'])) {
1172 $this->jerr("Delete Requested with no value");
1176 // build a list of tables to queriy for dependant data..
1181 $all_links = $x->databaseLinks();
1183 foreach($all_links as $tbl => $links) {
1184 foreach($links as $col => $totbl_col) {
1185 $to = explode(':', $totbl_col);
1186 if ($to[0] != $x->tableName()) {
1190 $affects[$tbl .'.' . $col] = true;
1195 // echo '<PRE>';print_r($affects);exit;
1196 // DB_Dataobject::debugLevel(1);
1201 $bits = array_map(function($v) { return (int)$v; } , explode(',', $req['_delete']));
1203 // let's assume it has a key!!!
1205 $x->whereAdd($this->key .' IN ('. implode(',', $bits) .')');
1207 $this->jerror("NOTICE-DELETE","Nothing found to delete");
1210 while ($x->fetch()) {
1216 if (!$this->checkPerm($x,'D') ) {
1217 $this->jerr("PERMISSION DENIED (d)");
1220 $match_ar = array();
1221 foreach($affects as $k=> $true) {
1222 $ka = explode('.', $k);
1224 $chk = DB_DataObject::factory($ka[0]);
1225 if (!is_a($chk,'DB_DataObject') && !is_a($chk,'PDO_DataObject')) {
1226 $this->jerr('Unable to load referenced table, check the links config: ' .$ka[0]);
1228 // print_r(array($chk->tablename() , $ka[1] , $xx->tablename() , $this->key ));
1229 $chk->{$ka[1]} = $xx->{$this->key};
1231 if (count($chk->keys())) {
1232 $matches = $chk->count();
1234 //DB_DataObject::DebugLevel(1);
1235 $matches = $chk->count($ka[1]);
1239 $chk->_match_key = $ka[1];
1240 $match_ar[] = clone($chk);
1246 $has_beforeDelete = method_exists($xx, 'beforeDelete');
1247 // before delte = allows us to trash dependancies if needed..
1250 if ( $has_beforeDelete ) {
1251 if ($xx->beforeDelete($match_ar, $this, $_REQUEST) === false) {
1252 $errs[] = "Delete failed ({$xx->id})\n".
1253 (isset($xx->err) ? $xx->err : '');
1256 // refetch affects..
1258 $match_ar = array();
1259 foreach($affects as $k=> $true) {
1260 $ka = explode('.', $k);
1261 $chk = DB_DataObject::factory($ka[0]);
1262 if (!is_a($chk,'DB_DataObject') && !is_a($chk,'PDO_DataObject')) {
1263 $this->jerr('Unable to load referenced table, check the links config: ' .$ka[0]);
1265 $chk->{$ka[1]} = $xx->{$this->key};
1266 $matches = $chk->count();
1267 $match_total += $matches;
1269 $chk->_match_key = $ka[1];
1270 $match_ar[] = clone($chk);
1277 if (!empty($match_ar)) {
1278 $chk = $match_ar[0];
1280 $o = $chk->fetchAll();
1281 $key = isset($chk->_match_key) ?$chk->_match_key : '?unknown column?';
1282 $desc = $chk->tableName(). '.' . $key .'='.$xx->{$this->key} ;
1283 if (method_exists($chk, 'toEventString')) {
1284 $desc .= ' : ' . $o[0]->toEventString();
1286 $this->jerror("NOTICE-DELETE-DEP", "Delete Dependant records ($match_total found), " .
1287 "first is ( $desc )");
1293 DB_DataObject::Factory('Events')->logDeletedRecord($x);
1295 $this->addEvent("DELETE", $x);
1299 if (method_exists($xx,'onDelete')) {
1300 $xx->onDelete($req, $this);
1306 $this->jerr(implode("\n<BR>", $errs));
1308 $this->jok("Deleted");
1314 * cols stores the list of columns that are available from the query.
1317 * This is a dupe of what is in autojoin -- we should move to using autojoin really.
1329 var $cols = array();
1333 function loadMap($do, $cfg =array()) //$onlycolumns=false, $distinct = false)
1335 //DB_DataObject::debugLevel(5);
1336 $onlycolumns = !empty($cfg['columns']) ? $cfg['columns'] : false;
1337 $distinct = !empty($cfg['distinct']) ? $cfg['distinct'] : false;
1338 $excludecolumns = !empty($cfg['exclude']) ? $cfg['exclude'] : array();
1340 $excludecolumns[] = 'passwd'; // we never expose passwords
1341 $excludecolumns[] = 'oath_key';
1343 $ret = $do->autoJoin(array(
1344 'include' => $onlycolumns,
1345 'exclude' => $excludecolumns,
1346 'distinct' => $distinct
1349 $this->countWhat = $ret['count'];
1350 $this->cols = $ret['cols'];
1351 $this->colsJname = $ret['join_names'];
1360 * generate the meta data neede by queries.
1363 function meta($x, $data)
1365 // this is not going to work on queries where the data does not match the database def..
1366 // for unknown columns we send them as stirngs..
1368 $cols = array_keys($data[0]);
1372 if (class_exists('PDO_DataObject')) {
1373 $options = PDO_DataObject::config();
1374 if (!file_exists($options["schema_location"] . '.reader')) {
1378 $rdata = unserialize(file_get_contents($options["schema_location"] . '.reader'));
1381 //echo '<PRE>';print_r($this->cols); exit;
1382 $options = &PEAR::getStaticProperty('DB_DataObject','options');
1383 $reader = $options["ini_{$x->databaseNickname()}"] .'.reader';
1384 if (!file_exists( $reader )) {
1388 $rdata = unserialize(file_get_contents($reader));
1391 //echo '<PRE>';print_r($this->cols);exit;
1392 //echo '<PRE>';print_r($rdata);exit;
1393 // echo '<PRE>';print_r($rdata);exit;
1396 $key = empty($keys) ? 'id' : $keys[0];
1400 foreach($cols as $c ) {
1401 if (!isset($this->cols[$c]) || !isset($rdata[$this->cols[$c]]) || !is_array($rdata[$this->cols[$c]])) {
1405 $add = $rdata[$this->cols[$c]];
1410 'totalProperty' => 'total',
1411 'successProperty' => 'success',
1413 'id' => $key, // was 'id'...
1420 function setFilters($x, $q)
1422 // if a column is type int, and we get ',' -> the it should be come an inc clause..
1423 // DB_DataObject::debugLevel(1);
1424 if (method_exists($x, 'applyFilters')) {
1425 // DB_DataObject::debugLevel(1);
1426 if (false === $x->applyFilters($q, $this->authUser, $this)) {
1430 $q_filtered = array();
1434 foreach($q as $key=>$val) {
1436 if (in_array($key,$keys) && !is_array($val)) {
1441 // handles name[]=fred&name[]=brian => name in ('fred', 'brian').
1442 // value is an array..
1443 if (is_array($val) ) {
1447 if ($key[0] == '!') {
1449 $key = substr($key,1);
1452 if (!in_array( $key, array_keys($this->cols))) {
1456 // support a[0] a[1] ..... => whereAddIn(
1459 foreach($val as $k=>$v) {
1460 if (!is_numeric($k)) {
1464 // FIXME: note this is not typesafe for anything other than mysql..
1466 if (!is_numeric($v) || !is_long($v)) {
1475 $x->whereAddIn($pref . (
1476 isset($this->colsJname[$key]) ?
1477 $this->colsJname[$key] :
1478 ($x->tableName(). '.'.$key)),
1479 $ar, $quote ? 'string' : 'int');
1486 // handles !name=fred => name not equal fred.
1487 if ($key[0] == '!' && in_array(substr($key, 1), array_keys($this->cols))) {
1489 $key = substr($key, 1) ;
1492 isset($this->colsJname[$key]) ?
1493 $this->colsJname[$key] :
1494 $x->tableName(). '.'.$key ) . ' != ' .
1495 (is_numeric($val) ? $val : "'". $x->escape($val) . "'")
1505 // Events and remarks -- fixme - move to events/remarsk...
1506 case 'on_id': // where TF is this used...
1507 if (!empty($q['query']['original'])) {
1508 // DB_DataObject::debugLevel(1);
1509 $o = (int) $q['query']['original'];
1511 $x->whereAdd("(on_id = $oid OR
1512 on_id IN ( SELECT distinct(id) FROM Documents WHERE original = $o )
1521 if (strlen($val) && $key[0] != '_') {
1522 $q_filtered[$key] = $val;
1525 // subjoined columns = check the values.
1526 // note this is not typesafe for anything other than mysql..
1528 if (isset($this->colsJname[$key])) {
1530 // the aobve rule for !strlen non-joined cols should apply to joined ones.
1531 if (!strlen($val)) {
1537 if (!is_numeric($val) || !is_long($val)) {
1540 $x->whereAdd( "{$this->colsJname[$key]} = " . ($quote ? "'". $x->escape($val) ."'" : $val));
1548 if (!empty($q_filtered)) {
1549 //var_dump($q_filtered);
1553 $x->setFrom($q_filtered);
1559 // nice generic -- let's get rid of it.. where is it used!!!!
1561 // Person / Group / Comapnies.... most of my queries noww...
1563 if (!empty($q['query']['name'])) {
1566 if (in_array( 'name', array_keys($x->table()))) {
1567 $x->whereAdd($x->tableName().".name LIKE '". $x->escape($q['query']['name']) . "%'");
1572 // - projectdirectory staff list - persn queuy
1577 * create the dataobject from (usually the url)
1578 * This uses $this->validTables
1579 * $this->validPrefix (later..)
1580 * to determine if class can be created..
1584 function dataObject($tab)
1586 if (is_array($this->validTables) && !in_array($tab,$this->validTables)) {
1587 $this->jerr("Invalid url - not listed in validTables");
1589 $tab = str_replace('/', '',$tab); // basic protection??
1591 $pm = HTML_FlexyFramework::get()->Pman;
1593 if (isset($pm['roo_alias'])) {
1594 $map = array_flip($pm['roo_alias']);
1595 if (isset($map[$tab])) {
1601 $x = DB_DataObject::factory($tab);
1603 if (!is_a($x, 'DB_DataObject') && !is_a($x, 'PDO_DataObject')) {
1604 $this->jerr('invalid url - no dataobject');