4 require_once 'Pman.php';
10 * Uses these methods of the dataobjects:
12 * - checkPerm('L'/'E'/'A', $authuser) - can we list the stuff
14 * - applySort($au, $sortcol, $direction, $array_of_columns, $multisort) -- does not support multisort at present..
15 * - applyFilters($_REQUEST, $authUser, $roo) -- apply any query filters on data. and hide stuff not to be seen. (RETURN false to prevent default filters.)
16 * - postListExtra($_REQUEST) : array(extra_name => data) - add extra column data on the results (like new messages etc.)
17 * - postListFilter($data, $authUser, $request) return $data - add extra data to an object
19 * - toRooSingleArray($authUser, $request) // single fetch, add data..
20 * - toRooArray($request) /// toArray if you need to return different data.. for a list fetch.
23 * CRUD - before/after handlers..
24 * - setFromRoo($ar, $roo) - values from post (deal with dates etc.) - return true|error string.
25 * ... call $roo->jerr() on failure...
28 * - beforeDelete($dependants_array, $roo) Argument is an array of un-find/fetched dependant items.
29 * - jerr() will stop insert.. (Prefered)
30 * - return false for fail and set DO->err;
31 * - beforeUpdate($old, $request,$roo) - after update - jerr() will stop insert..
32 * - beforeInsert($request,$roo) - before insert - jerr() will stop insert..
35 * - onUpdate($old, $request,$roo, $event) - after update // return value ignored
36 * - onInsert($request,$roo, $event) - after insert
37 * - onDelete($req, $roo) - after delete
42 * - toEventString (for logging - this is generically prefixed to all database operations.)
45 class Pman_Roo extends Pman
48 * if set to an array (when extending this, then you can restrict which tables are available
50 var $validTables = false;
52 var $key; // used by update currenly to store primary key.
55 var $max_limit = 10000;
57 var $debugEnabled = true; // disable this for public versions of this code.
61 parent::getAuth(); // load company!
62 $au = $this->getAuthUser();
65 $this->jerr("Not authenticated", array('authFailure' => true));
67 if (!$au->pid() ) { // not set up yet..
68 $this->jerr("Not authenticated", array('authFailure' => true));
72 $this->authUser = $au;
76 * GET method Roo/TABLENAME
78 * Generally for SELECT or Single SELECT
81 * _id=value single fetch based on primary id.
82 * can be '0' if you want to fetch a set of defaults
83 * Use in conjuntion with toRooSingleArray()
85 * lookup[key]=value single fetch based on a single key value lookup.
86 * multiple key/value can be used. eg. ontable+onid..
87 * _columns what to return.
91 * - all tables are always autojoined.
95 * _columns=a,b,c,d comma seperated list of columns.
96 * _exclude_columns=a,b,c,d comma seperated list of columns.
97 * _distinct=name a distinct column lookup. you also have to use _columns with this.
100 * colname = ... => colname = ....
101 * !colname=.... => colname != ....
102 * !colname[0]=... !colname[1]=... => colname NOT IN (.....) ** only supports main table at present..
103 * colname[0]=... colname[1]=... => colname IN (.....) ** only supports main table at present..
106 * sort=name what to sort.
107 * sort=a,b,d can support multiple columns
108 * dir=ASC what direction
109 * _multisort ={...} JSON encoded { sort : { row : direction }, order : [ row, row, row ] }
112 * start=0 limit start
113 * limit=25 limit number
117 * csvCols[0] csvCols[1].... = .... column titles for CSV output
118 * csvTitles[0], csvTitles[1] .... = columns to use for CSV output
121 * _toggleActive !:!:!:! - this hsould not really be here..
122 * query[add_blank] - add a line in with an empty option... - not really needed???
123 * _delete = delete a list of ids element. (depricated.. this will be removed...)
126 * _post =1 = simulate a post with debuggin on.
127 * _debug_post << This is prefered, as _post may overlap with accouting posts..
129 * _debug = turn on DB_dataobject deubbing, must be admin at present..
132 * CALLS methods on dataobjects if they exist
135 * checkPerm('S' , $authuser)
136 * - can we list the stuff
137 * - return false to disallow...
138 * applySort($au, $sortcol, $direction, $array_of_columns, $multisort)
139 * -- does not support multisort at present..
140 * applyFilters($_REQUEST, $authUser, $roo)
141 * -- apply any query filters on data. and hide stuff not to be seen.
142 * -- can exit by calling $roo->jerr()
143 * postListExtra($_REQUEST) : array(extra_name => data)
144 * - add extra column data on the results (like new messages etc.)
145 * postListFilter($data, $authUser, $request) return $data
146 * - add extra data to an object
149 * toRooSingleArray($authUser, $request) : array
150 * - called on single fetch only, add or maniuplate returned array data.
151 * - is also called when _id=0 is used (for fetching a default set.)
152 * toRooArray($request) : array
153 * - called if singleArray is unavailable on single fetch.
154 * - always tried for mutiple results.
155 * toArray() - the default method if none of the others are found.
158 * - standard DataObject feature - causes all results to show all
162 * _extra_cols -- if set, then filtering by column etc. will use them.
166 function get($tab, $opts = Array())
168 // $this->jerr("Not authenticated", array('authFailure' => true));
169 //echo '<PRE>';print_R($_GET);
170 //DB_DataObject::debuglevel(1);
172 $this->init(); // from pman.
173 //DB_DataObject::debuglevel(1);
174 HTML_FlexyFramework::get()->generateDataobjectsCache($this->isDev && !empty($_REQUEST['isDev']));
182 if ( $this->checkDebugPost()) {
187 //DB_DAtaObject::debuglevel(1);
188 return $this->post($tab);
192 $this->initErrorHandling();
194 $tt = explode('/', $tab);
195 $tab = array_shift($tt);
196 $x = $this->dataObject($tab);
198 $_columns = !empty($_REQUEST['_columns']) ? explode(',', $_REQUEST['_columns']) : false;
200 if (isset( $_REQUEST['lookup'] ) && is_array($_REQUEST['lookup'] )) { // single fetch based on key/value pairs
201 $this->selectSingle($x, $_REQUEST['lookup'],$_REQUEST);
206 // single fetch (use '0' to fetch an empty object..)
207 if (isset($_REQUEST['_id']) && is_numeric($_REQUEST['_id'])) {
209 $this->selectSingle($x, $_REQUEST['_id'],$_REQUEST);
216 if (isset($_REQUEST['_delete'])) {
217 $this->jerr("DELETE by GET has been removed - update the code to use POST");
224 if (isset($_REQUEST['_toggleActive'])) {
225 // do we really delete stuff!?!?!?
226 if (!$this->hasPerm("Core.Staff", 'E')) {
227 $this->jerr("PERMISSION DENIED (ta)");
229 $clean = create_function('$v', 'return (int)$v;');
230 $bits = array_map($clean, explode(',', $_REQUEST['_toggleActive']));
231 if (in_array($this->authUser->id, $bits) && $this->authUser->active) {
232 $this->jerr("you can not disable yourself");
234 $x->query('UPDATE core_person SET active = !active WHERE id IN (' .implode(',', $bits).')');
235 $this->addEvent("USERTOGGLE", false, implode(',', $bits));
236 $this->jok("Updated");
239 //DB_DataObject::debugLevel(1);
241 // sets map and countWhat
242 $this->loadMap($x, array(
243 'columns' => $_columns,
244 'distinct' => empty($_REQUEST['_distinct']) ? false: $_REQUEST['_distinct'],
245 'exclude' => empty($_REQUEST['_exclude_columns']) ? false: explode(',', $_REQUEST['_exclude_columns'])
249 $this->setFilters($x,$_REQUEST);
251 if (!$this->checkPerm($x,'S', $_REQUEST)) {
252 $this->jerr("PERMISSION DENIED (g)");
256 // build join if req.
257 //DB_DataObject::debugLevel(1);
258 // var_dump($this->countWhat);
259 $total = $x->count($this->countWhat);
262 //var_dump($total);exit;
263 $this->applySort($x);
267 if (!empty($_REQUEST['_distinct']) && $total < 400) {
274 empty($_REQUEST['start']) ? 0 : (int)$_REQUEST['start'],
275 min(empty($_REQUEST['limit']) ? 25 : (int)$_REQUEST['limit'], $this->max_limit)
278 $queryObj = clone($x);
279 //DB_DataObject::debuglevel(1);
281 $this->sessionState(0);
283 $this->sessionState(1);
285 if (false === $res) {
286 $this->jerr($x->_lastError->toString());
294 // ---------------- THESE ARE DEPRICATED.. they should be moved to the model...
297 if (!empty($_REQUEST['query']['add_blank'])) {
298 $ret[] = array( 'id' => 0, 'name' => '----');
302 $rooar = method_exists($x, 'toRooArray');
303 $_columnsf = $_columns ? array_flip($_columns) : false;
304 while ($x->fetch()) {
306 $add = $rooar ? $x->toRooArray($_REQUEST) : $x->toArray();
307 if ($add === false) {
310 $ret[] = !$_columns ? $add : array_intersect_key($add, $_columnsf);
314 $ret = array_slice($ret,
315 empty($_REQUEST['start']) ? 0 : (int)$_REQUEST['start'],
316 min(empty($_REQUEST['limit']) ? 25 : (int)$_REQUEST['limit'], 10000)
323 if (method_exists($queryObj ,'postListExtra')) {
324 $extra = $queryObj->postListExtra($_REQUEST, $this);
328 // filter results, and add any data that is needed...
329 if (method_exists($x,'postListFilter')) {
330 $ret = $x->postListFilter($ret, $this->authUser, $_REQUEST);
335 if (!empty($_REQUEST['csvCols']) && !empty($_REQUEST['csvTitles']) ) {
338 $this->toCsv($ret, $_REQUEST['csvCols'], $_REQUEST['csvTitles'],
339 empty($_REQUEST['csvFilename']) ? '' : $_REQUEST['csvFilename']
347 //if ($x->tableName() == 'Documents_Tracking') {
348 // $ret = $this->replaceSubject(&$ret, 'doc_id_subject');
353 if (!empty($_REQUEST['_requestMeta']) && count($ret)) {
354 $meta = $this->meta($x, $ret);
356 $extra['metaData'] = $meta;
359 // this make take some time...
360 $this->sessionState(0);
361 // echo "<PRE>"; print_r($ret);
362 $this->jdata($ret, max(count($ret), $total), $extra );
366 function checkDebug($req = false)
368 $req = $req === false ? $_REQUEST : $req;
370 if (empty($req['_debug'])) {
374 if (!empty($_SERVER['HTTP_HOST']) && $_SERVER['HTTP_HOST'] == 'localhost') {
375 DB_DAtaObject::debuglevel((int)$req['_debug']);
383 method_exists($this->authUser,'canDebug')
385 $this->authUser->canDebug()
390 method_exists($this->authUser,'groups')
392 is_a($this->authUser, 'Pman_Core_DataObjects_Core_person')
394 in_array('Administrators', $this->authUser->groups('name'))
399 DB_DAtaObject::debuglevel((int)$req['_debug']);
404 function checkDebugPost()
406 if (empty($_GET['_post']) && empty($_GET['_debug_post'])) {
409 // localhost can do anything...
410 if (!empty($_SERVER['HTTP_HOST']) && $_SERVER['HTTP_HOST'] == 'localhost') {
413 return $this->authUser &&
414 method_exists($this->authUser,'groups') &&
415 in_array('Administrators', $this->authUser->groups('name'));
419 function checkPerm($obj, $lvl, $req= null)
421 if (!method_exists($obj, 'checkPerm')) {
424 if ($obj->checkPerm($lvl, $this->authUser, $req)) {
430 function toCsv($data, $cols, $titles, $filename, $addDate = true)
433 $this->sessionState(0); // turn off sessions - no locking..
435 require_once 'Pman/Core/SimpleExcel.php';
437 $fn = (empty($filename) ? 'list-export-' : urlencode($filename)) . (($addDate) ? date('Y-m-d') : '') ;
441 'workbook' => substr($fn, 0, 31),
448 if (is_object($data)) {
449 $rooar = method_exists($data, 'toRooArray');
450 while($data->fetch()) {
451 $x = $rooar ? $data->toRooArray($q) : $data->toArray();
454 if ($cols == '*') { /// did we get cols sent to us?
455 $cols = array_keys($x);
458 if(!is_array($cols)) {
459 $cols = explode(',', $cols);
462 if ($titles !== false) {
464 $titles= array_keys($x);
466 if(!is_array($titles)) {
467 $titles = explode(',', $titles);
469 foreach($cols as $i=>$col) {
470 $se_config['cols'][] = array(
471 'header'=> isset($titles[$i]) ? $titles[$i] : $col,
474 // 'renderer' => array($this, 'getThumb'),
475 // 'color' => 'yellow', // set color for the cell which is a header element
476 // 'fillBlank' => 'gray', // set
478 $se = new Pman_Core_SimpleExcel(array(), $se_config);
487 $se->addLine($se_config['workbook'], $x);
493 $this->jerr('no data found', false, 'text/plain');
495 $se->send($fn .'.xls');
501 foreach($data as $x) {
502 //echo "<PRE>"; print_r(array($_REQUEST['csvCols'], $x->toArray())); exit;
506 $cols= array_keys($x);
509 if(!is_array($cols)) {
510 $cols = explode(',', $cols);
513 if ($titles !== false) {
515 $titles= array_keys($x);
518 if(!is_array($titles)) {
519 $titles = explode(',', $titles);
522 foreach($cols as $i=>$col) {
523 $se_config['cols'][] = array(
524 'header'=> isset($titles[$i]) ? $titles[$i] : $col,
527 // 'renderer' => array($this, 'getThumb'),
528 // 'color' => 'yellow', // set color for the cell which is a header element
529 // 'fillBlank' => 'gray', // set
531 $se = new Pman_Core_SimpleExcel(array(),$se_config);
537 //fputcsv($fh, $titles);
541 $se->addLine($se_config['workbook'], $x);
545 $this->jerr('no data found');
548 $se->send($fn .'.xls');
555 * POST method Roo/TABLENAME
556 * -- creates, updates, or deletes data.
559 * if the primary key is empty, this happens
560 * will automatically set these to current date and authUser->id
561 * created, created_by, created_dt
562 * updated, update_by, updated_dt
563 * modified, modified_by, modified_dt
565 * will return a GET request SINGLE SELECT (and accepts same)
568 * _delete=1,2,3 delete a set of data.
570 * if the primary key value is set, then update occurs.
571 * will automatically set these to current date and authUser->id
572 * updated, update_by, updated_dt
573 * modified, modified_by, modified_dt
577 * _delete=1,2,3 causes a delete to occur.
578 * _ids=1,2,3,4 causes update to occur on all primary ids.
581 * = same as single SELECT GET request..
586 * _debug=1 forces debug
587 * _get=1 - causes a get request to occur when doing a POST..
591 * these methods on dataobjects if they exist
593 * checkPerm('E' / 'D' , $authuser)
594 * - can we list the stuff
595 * - return false to disallow...
597 * toRooSingleArray($authUser, $request) : array
598 * - called on single fetch only, add or maniuplate returned array data.
599 * toRooArray($request) : array
600 * - Called if toSingleArray does not exist.
601 * - if you need to return different data than toArray..
604 * (for logging - this is generically prefixed to all database operations.)
608 * called when $_FILES is not empty
611 * setFromRoo($ar, $roo)
612 * - alternative to setFrom() which is called if this method does not exist
613 * - values from post (deal with dates etc.) - return true|error string.
614 * - call $roo->jerr() on failure...
616 * CALLS BEFORE change occurs:
618 * beforeDelete($dependants_array, $roo)
619 * Argument is an array of un-find/fetched dependant items.
620 * - jerr() will stop insert.. (Prefered)
621 * - return false for fail and set DO->err;
623 * beforeUpdate($old, $request,$roo)
624 * - after update - jerr() will stop insert..
625 * beforeInsert($request,$roo)
626 * - before insert - jerr() will stop insert..
629 * CALLS AFTER change occured
631 * onUpdate($old, $request,$roo)
632 * - after update // return value ignored
634 * onInsert($request,$roo)
637 * onDelete($request, $roo) - after delete
641 function post($tab) // update / insert (?? delete??)
643 // -- why was this put in? - Roo is not related to Core.All ?
644 //if (!$this->hasPerm("Core.All", 'E')) {
645 // $this->jerr("PERMISSION DENIED (e)");
647 $this->initErrorHandling();
649 // DB_DataObject::debugLevel(1);
652 if (!empty($_REQUEST['_get'])) {
653 return $this->get($tab);
656 $this->init(); // for pman.
658 $x = $this->dataObject($tab);
660 $this->transObj = clone($x);
662 $this->transObj->query('BEGIN');
663 // find the key and use that to get the thing..
666 $this->jerr('no key');
669 $this->key = $keys[0];
671 // delete should be here...
672 if (isset($_REQUEST['_delete'])) {
673 // do we really delete stuff!?!?!?
674 return $this->delete($x,$_REQUEST);
682 // not sure if this is a good idea here...
684 if (!empty($_REQUEST['_ids'])) {
685 $ids = explode(',',$_REQUEST['_ids']);
686 $x->whereAddIn($this->key, $ids, 'int');
687 $ar = $x->fetchAll();
690 $this->update($x, $_REQUEST);
693 $this->jok("UPDATED");
698 if (!empty($_REQUEST[$this->key])) {
700 if (!$x->get($this->key, $_REQUEST[$this->key])) {
701 $this->jerr("Invalid request (id does not point to a record.)");
703 $this->jok($this->update($x, $_REQUEST));
707 $this->jerr("No data recieved for inserting");
710 $this->jok($this->insert($x, $_REQUEST));
722 * apply REQUEST[sort] and [dir]
723 * sort may be an array of columsn..
725 * @arg DB_DataObject $x
728 function applySort($x, $sort = '', $dir ='')
731 // Db_DataObject::debugLevel(1);
732 $sort = empty($_REQUEST['sort']) ? $sort : $_REQUEST['sort'];
733 $dir = empty($_REQUEST['dir']) ? $dir : $_REQUEST['dir'];
734 $dir = $dir == 'ASC' ? 'ASC' : 'DESC';
736 $ms = empty($_REQUEST['_multisort']) ? false : $_REQUEST['_multisort'];
737 //var_Dump($ms);exit;
739 if (method_exists($x, 'applySort')) {
740 $sorted = $x->applySort(
744 array_keys($this->cols),
745 $ms ? json_decode($ms) : false
749 return $this->multiSort($x);
752 if ($sorted === false) {
754 $cols = $x->tableColumns();
755 $excols = array_keys($this->cols);
757 if (isset($x->_extra_cols)) {
758 $excols = array_merge($excols, $x->_extra_cols);
760 $sort_ar = explode(',', $sort);
763 foreach($sort_ar as $sort) {
765 if (strlen($sort) && isset($cols[$sort]) ) {
766 $sort_str[] = $x->tableName() .'.'.$sort . ' ' . $dir ;
768 } else if (in_array($sort, $excols)) {
769 $sort_str[] = $sort . ' ' . $dir ;
774 $x->orderBy(implode(', ', $sort_str ));
785 function multiSort($x)
787 //DB_DataObject::debugLevel(1);
788 $ms = json_decode($_REQUEST['_multisort']);
789 if (!isset($ms->order) || !is_array($ms->order)) {
794 $cols = $x->tableColumns();
796 //print_r($this->cols);exit;
797 // this-><cols contains colname => aliased name...
798 foreach($ms->order as $col) {
799 if (!isset($ms->sort->{$col})) {
800 continue; // no direction..
802 $ms->sort->{$col} = $ms->sort->{$col} == 'ASC' ? 'ASC' : 'DESC';
804 if (strlen($col) && isset($cols[$col]) ) {
805 $sort_str[] = $x->tableName() .'.'.$col . ' ' . $ms->sort->{$col};
808 //print_r($this->cols);
810 if (in_array($col, array_keys($this->cols))) {
811 $sort_str[] = $col. ' ' . $ms->sort->{$col};
814 if (isset($x->_extra_cols) && in_array($col, $x->_extra_cols)) {
815 $sort_str[] = $col. ' ' . $ms->sort->{$col};
820 $x->orderBy(implode(', ', $sort_str ));
827 * - used when _id is set, or after insert or update
829 * @param DataObject $x the dataobject to use
830 * @param int $id the pid of the object
831 * @param array $req the request, or false if it comes from insert/update.
834 function selectSingle($x, $id, $req=false)
838 $_columns = !empty($req['_columns']) ? explode(',', $req['_columns']) : false;
840 //var_dump(array(!is_array($id) , empty($id)));
841 if (!is_array($id) && empty($id)) {
844 if (method_exists($x, 'toRooSingleArray')) {
845 $this->jok($x->toRooSingleArray($this->authUser, $req));
847 if (method_exists($x, 'toRooArray')) {
848 $this->jok($x->toRooArray($req));
851 $this->jok($x->toArray());
855 $this->loadMap($x, array(
856 'columns' => $_columns,
859 if ($req !== false) {
860 $this->setFilters($x, $req);
861 } else if (method_exists($x, 'applyFilters')) {
862 // always call apply filters even after update/insert...
863 // however arguments are not passed.
864 $x->applyFilters(array('_is_update_request' => true), $this->authUser, $this);
867 // DB_DataObject::DebugLevel(1);
870 $x->setFrom($req['lookup'] );
872 if (!$x->find(true)) {
873 if (!empty($id['_id'])) {
875 $this->jok($x->toArray());
880 } else if (!$x->get($id)) {
881 $this->jerr("selectSingle: no such record ($id)");
884 // ignore perms if comming from update/insert - as it's already done...
885 if ($req !== false && !$this->checkPerm($x,'S')) {
886 $this->jerr("PERMISSION DENIED - si");
888 // different symantics on all these calls??
889 if (method_exists($x, 'toRooSingleArray')) {
890 $this->jok($x->toRooSingleArray($this->authUser, $req));
892 if (method_exists($x, 'toRooArray')) {
893 $this->jok($x->toRooArray($req));
896 $this->jok($x->toArray());
901 function insert($x, $req, $with_perm_check = true)
903 if (method_exists($x, 'setFromRoo')) {
904 $res = $x->setFromRoo($req, $this);
905 if (is_string($res)) {
912 if ( $with_perm_check && !$this->checkPerm($x,'A', $req)) {
913 $this->jerr("PERMISSION DENIED (i)");
915 $cols = $x->tableColumns();
917 if (isset($cols['created'])) {
918 $x->created = date('Y-m-d H:i:s');
920 if (isset($cols['created_dt'])) {
921 $x->created_dt = date('Y-m-d H:i:s');
923 if (isset($cols['created_by'])) {
924 $x->created_by = $this->authUser->id;
927 if (isset($cols['modified'])) {
928 $x->modified = date('Y-m-d H:i:s');
930 if (isset($cols['modified_dt'])) {
931 $x->modified_dt = date('Y-m-d H:i:s');
933 if (isset($cols['modified_by'])) {
934 $x->modified_by = $this->authUser->id;
937 if (isset($cols['updated'])) {
938 $x->updated = date('Y-m-d H:i:s');
940 if (isset($cols['updated_dt'])) {
941 $x->updated_dt = date('Y-m-d H:i:s');
943 if (isset($cols['updated_by'])) {
944 $x->updated_by = $this->authUser->id;
947 if (method_exists($x, 'beforeInsert')) {
948 $x->beforeInsert($_REQUEST, $this);
953 if ($res === false) {
954 $this->jerr($x->_lastError->toString());
956 $ev = $this->addEvent("ADD", $x);
957 if (method_exists($x, 'onInsert')) {
958 $x->onInsert($_REQUEST, $this, $ev);
965 // note setFrom might handle this before hand...!??!
966 if (!empty($_FILES) && method_exists($x, 'onUpload')) {
967 $x->onUpload($this, $_REQUEST);
970 return $this->selectSingle(
971 DB_DataObject::factory($x->tableName()),
977 function updateLock($x, $req )
979 Pman::$permitError = true; // allow it to fail without dieing
981 $lock = DB_DataObjecT::factory('Core_locking');
982 Pman::$permitError = false;
983 if (is_a($lock,'DB_DataObject') && $this->authUser) {
985 $lock->on_id = $x->{$this->key};
986 $lock->on_table= strtolower($x->tableName());
987 if (!empty($_REQUEST['_lock_id'])) {
988 $lock->whereAdd('id != ' . ((int)$_REQUEST['_lock_id']));
990 $lock->whereAdd('person_id !=' . $this->authUser->id);
994 $exp = date('Y-m-d', strtotime('NOW - 1 WEEK'));
995 $llc->whereAdd("created < '$exp'");
998 while($llc->fetch()) {
1005 if ($lock->find(true)) {
1006 // it's locked by someone else..
1007 $p = $lock->person();
1010 $this->jerr( "Record was locked by " . $p->name . " at " .$lock->created.
1011 " - Please confirm you wish to save"
1012 , array('needs_confirm' => true));
1016 // check the users lock.. - no point.. ??? - if there are no other locks and it's not the users, then they can
1017 // edit it anyways...
1019 // can we find the user's lock.
1020 $lock = DB_DataObjecT::factory('Core_locking');
1021 $lock->on_id = $x->{$this->key};
1022 $lock->on_table= strtolower($x->tableName());
1023 $lock->person_id = $this->authUser->id;
1024 $lock->orderBy('created DESC');
1028 $lock->find(true) &&
1029 isset($x->modified_dt) &&
1030 strtotime($x->modified_dt) > strtotime($lock->created) &&
1031 empty($req['_submit_confirmed']) &&
1032 $x->modified_by != $this->authUser->id
1035 $p = DB_DataObject::factory('core_person');
1036 $p->get($x->modified_by);
1037 $this->jerr($p->name . " saved the record since you started editing,\nDo you really want to update it?", array('needs_confirm' => true));
1049 function update($x, $req, $with_perm_check = true)
1051 if ( $with_perm_check && !$this->checkPerm($x,'E', $req) ) {
1052 $this->jerr("PERMISSION DENIED - No Edit permissions on this element");
1055 // check any locks..
1056 // only done if we recieve a lock_id.
1057 // we are very trusing here.. that someone has not messed around with locks..
1058 // the object might want to check in their checkPerm - if locking is essential..
1059 $lock = $this->updateLock($x,$req);
1069 // this lot is generic.. needs moving
1070 if (method_exists($x, 'setFromRoo')) {
1071 $res = $x->setFromRoo($req, $this);
1072 if (is_string($res)) {
1081 //echo '<PRE>';print_r($old);print_r($x);exit;
1084 $cols = $x->tableColumns();
1086 if (isset($cols['modified'])) {
1087 $x->modified = date('Y-m-d H:i:s');
1089 if (isset($cols['modified_dt'])) {
1090 $x->modified_dt = date('Y-m-d H:i:s');
1092 if (isset($cols['modified_by']) && $this->authUser) {
1093 $x->modified_by = $this->authUser->id;
1096 if (isset($cols['updated'])) {
1097 $x->updated = date('Y-m-d H:i:s');
1099 if (isset($cols['updated_dt'])) {
1100 $x->updated_dt = date('Y-m-d H:i:s');
1102 if (isset($cols['updated_by']) && $this->authUser) {
1103 $x->updated_by = $this->authUser->id;
1106 if (method_exists($x, 'beforeUpdate')) {
1107 $x->beforeUpdate($old, $req, $this);
1110 if ($with_perm_check && !empty($_FILES) && method_exists($x, 'onUpload')) {
1111 $x->onUpload($this, $_REQUEST);
1114 //DB_DataObject::DebugLevel(1);
1115 $res = $x->update($old);
1116 if ($res === false) {
1117 $this->jerr($x->_lastError->toString());
1119 $ev = $this->addEvent("EDIT", $x);
1121 if (method_exists($x, 'onUpdate')) {
1122 $x->onUpdate($old, $req, $this, $ev);
1125 $ev->audit($x, $old);
1129 return $this->selectSingle(
1130 DB_DataObject::factory($x->tableName()),
1136 * Delete a number of records.
1137 * calls $delete_obj->beforeDelete($array_of_dependant_dataobjects, $this)
1141 function delete($x, $req)
1143 // do we really delete stuff!?!?!?
1144 if (empty($req['_delete'])) {
1145 $this->jerr("Delete Requested with no value");
1149 // build a list of tables to queriy for dependant data..
1154 $all_links = $x->databaseLinks();
1156 foreach($all_links as $tbl => $links) {
1157 foreach($links as $col => $totbl_col) {
1158 $to = explode(':', $totbl_col);
1159 if ($to[0] != $x->tableName()) {
1163 $affects[$tbl .'.' . $col] = true;
1168 // echo '<PRE>';print_r($affects);exit;
1169 // DB_Dataobject::debugLevel(1);
1174 $bits = array_map(function($v) { return (int)$v; } , explode(',', $req['_delete']));
1176 // let's assume it has a key!!!
1178 $x->whereAdd($this->key .' IN ('. implode(',', $bits) .')');
1180 $this->jerr("Nothing found to delete");
1183 while ($x->fetch()) {
1189 if (!$this->checkPerm($x,'D') ) {
1190 $this->jerr("PERMISSION DENIED (d)");
1193 $match_ar = array();
1194 foreach($affects as $k=> $true) {
1195 $ka = explode('.', $k);
1197 $chk = DB_DataObject::factory($ka[0]);
1198 if (!is_a($chk,'DB_DataObject') && !is_a($chk,'PDO_DataObject')) {
1199 $this->jerr('Unable to load referenced table, check the links config: ' .$ka[0]);
1201 // print_r(array($chk->tablename() , $ka[1] , $xx->tablename() , $this->key ));
1202 $chk->{$ka[1]} = $xx->{$this->key};
1204 if (count($chk->keys())) {
1205 $matches = $chk->count();
1207 //DB_DataObject::DebugLevel(1);
1208 $matches = $chk->count($ka[1]);
1212 $chk->_match_key = $ka[1];
1213 $match_ar[] = clone($chk);
1219 $has_beforeDelete = method_exists($xx, 'beforeDelete');
1220 // before delte = allows us to trash dependancies if needed..
1223 if ( $has_beforeDelete ) {
1224 if ($xx->beforeDelete($match_ar, $this) === false) {
1225 $errs[] = "Delete failed ({$xx->id})\n".
1226 (isset($xx->err) ? $xx->err : '');
1229 // refetch affects..
1231 $match_ar = array();
1232 foreach($affects as $k=> $true) {
1233 $ka = explode('.', $k);
1234 $chk = DB_DataObject::factory($ka[0]);
1235 if (!is_a($chk,'DB_DataObject') && !is_a($chk,'PDO_DataObject')) {
1236 $this->jerr('Unable to load referenced table, check the links config: ' .$ka[0]);
1238 $chk->{$ka[1]} = $xx->{$this->key};
1239 $matches = $chk->count();
1240 $match_total += $matches;
1242 $chk->_match_key = $ka[1];
1243 $match_ar[] = clone($chk);
1250 if (!empty($match_ar)) {
1251 $chk = $match_ar[0];
1253 $o = $chk->fetchAll();
1254 $key = isset($chk->_match_key) ?$chk->_match_key : '?unknown column?';
1255 $desc = $chk->tableName(). '.' . $key .'='.$xx->{$this->key} ;
1256 if (method_exists($chk, 'toEventString')) {
1257 $desc .= ' : ' . $o[0]->toEventString();
1259 $this->jerr("Delete Dependant records ($match_total found), " .
1260 "first is ( $desc )");
1266 DB_DataObject::Factory('Events')->logDeletedRecord($x);
1268 $this->addEvent("DELETE", $x);
1272 if (method_exists($xx,'onDelete')) {
1273 $xx->onDelete($req, $this);
1279 $this->jerr(implode("\n<BR>", $errs));
1281 $this->jok("Deleted");
1287 * cols stores the list of columns that are available from the query.
1290 * This is a dupe of what is in autojoin -- we should move to using autojoin really.
1302 var $cols = array();
1306 function loadMap($do, $cfg =array()) //$onlycolumns=false, $distinct = false)
1309 //DB_DataObject::debugLevel(5);
1310 $onlycolumns = !empty($cfg['columns']) ? $cfg['columns'] : false;
1311 $distinct = !empty($cfg['distinct']) ? $cfg['distinct'] : false;
1312 $excludecolumns = !empty($cfg['exclude']) ? $cfg['exclude'] : array();
1314 $excludecolumns[] = 'passwd'; // we never expose passwords
1315 $excludecolumns[] = 'oath_key';
1317 $ret = $do->autoJoin(array(
1318 'include' => $onlycolumns,
1319 'exclude' => $excludecolumns,
1320 'distinct' => $distinct
1323 $this->countWhat = $ret['count'];
1324 $this->cols = $ret['cols'];
1325 $this->colsJname = $ret['join_names'];
1334 * generate the meta data neede by queries.
1337 function meta($x, $data)
1339 // this is not going to work on queries where the data does not match the database def..
1340 // for unknown columns we send them as stirngs..
1342 $cols = array_keys($data[0]);
1346 if (class_exists('PDO_DataObject')) {
1347 $options = PDO_DataObject::config();
1348 if (!file_exists($options["schema_location"] . '.reader')) {
1352 $rdata = unserialize(file_get_contents($options["schema_location"] . '.reader'));
1355 //echo '<PRE>';print_r($this->cols); exit;
1356 $options = &PEAR::getStaticProperty('DB_DataObject','options');
1357 $reader = $options["ini_{$x->databaseNickname()}"] .'.reader';
1358 if (!file_exists( $reader )) {
1362 $rdata = unserialize(file_get_contents($reader));
1365 //echo '<PRE>';print_r($this->cols);exit;
1366 //echo '<PRE>';print_r($rdata);exit;
1367 // echo '<PRE>';print_r($rdata);exit;
1370 $key = empty($keys) ? 'id' : $keys[0];
1374 foreach($cols as $c ) {
1375 if (!isset($this->cols[$c]) || !isset($rdata[$this->cols[$c]]) || !is_array($rdata[$this->cols[$c]])) {
1379 $add = $rdata[$this->cols[$c]];
1384 'totalProperty' => 'total',
1385 'successProperty' => 'success',
1387 'id' => $key, // was 'id'...
1394 function setFilters($x, $q)
1396 // if a column is type int, and we get ',' -> the it should be come an inc clause..
1397 // DB_DataObject::debugLevel(1);
1398 if (method_exists($x, 'applyFilters')) {
1399 // DB_DataObject::debugLevel(1);
1400 if (false === $x->applyFilters($q, $this->authUser, $this)) {
1404 $q_filtered = array();
1408 foreach($q as $key=>$val) {
1410 if (in_array($key,$keys) && !is_array($val)) {
1415 // handles name[]=fred&name[]=brian => name in ('fred', 'brian').
1416 // value is an array..
1417 if (is_array($val) ) {
1421 if ($key[0] == '!') {
1423 $key = substr($key,1);
1426 if (!in_array( $key, array_keys($this->cols))) {
1430 // support a[0] a[1] ..... => whereAddIn(
1433 foreach($val as $k=>$v) {
1434 if (!is_numeric($k)) {
1438 // FIXME: note this is not typesafe for anything other than mysql..
1440 if (!is_numeric($v) || !is_long($v)) {
1449 $x->whereAddIn($pref . (
1450 isset($this->colsJname[$key]) ?
1451 $this->colsJname[$key] :
1452 ($x->tableName(). '.'.$key)),
1453 $ar, $quote ? 'string' : 'int');
1460 // handles !name=fred => name not equal fred.
1461 if ($key[0] == '!' && in_array(substr($key, 1), array_keys($this->cols))) {
1463 $key = substr($key, 1) ;
1466 isset($this->colsJname[$key]) ?
1467 $this->colsJname[$key] :
1468 $x->tableName(). '.'.$key ) . ' != ' .
1469 (is_numeric($val) ? $val : "'". $x->escape($val) . "'")
1479 // Events and remarks -- fixme - move to events/remarsk...
1480 case 'on_id': // where TF is this used...
1481 if (!empty($q['query']['original'])) {
1482 // DB_DataObject::debugLevel(1);
1483 $o = (int) $q['query']['original'];
1485 $x->whereAdd("(on_id = $oid OR
1486 on_id IN ( SELECT distinct(id) FROM Documents WHERE original = $o )
1495 if (strlen($val) && $key[0] != '_') {
1496 $q_filtered[$key] = $val;
1499 // subjoined columns = check the values.
1500 // note this is not typesafe for anything other than mysql..
1502 if (isset($this->colsJname[$key])) {
1504 // the aobve rule for !strlen non-joined cols should apply to joined ones.
1505 if (!strlen($val)) {
1511 if (!is_numeric($val) || !is_long($val)) {
1514 $x->whereAdd( "{$this->colsJname[$key]} = " . ($quote ? "'". $x->escape($val) ."'" : $val));
1522 if (!empty($q_filtered)) {
1523 //var_dump($q_filtered);
1527 $x->setFrom($q_filtered);
1533 // nice generic -- let's get rid of it.. where is it used!!!!
1535 // Person / Group / Comapnies.... most of my queries noww...
1537 if (!empty($q['query']['name'])) {
1540 if (in_array( 'name', array_keys($x->table()))) {
1541 $x->whereAdd($x->tableName().".name LIKE '". $x->escape($q['query']['name']) . "%'");
1546 // - projectdirectory staff list - persn queuy
1551 * create the dataobject from (usually the url)
1552 * This uses $this->validTables
1553 * $this->validPrefix (later..)
1554 * to determine if class can be created..
1558 function dataObject($tab)
1560 if (is_array($this->validTables) && !in_array($tab,$this->validTables)) {
1561 $this->jerr("Invalid url - not listed in validTables");
1563 $tab = str_replace('/', '',$tab); // basic protection??
1565 $pm = HTML_FlexyFramework::get()->Pman;
1567 if (isset($pm['roo_alias'])) {
1568 $map = array_flip($pm['roo_alias']);
1569 if (isset($map[$tab])) {
1575 $x = DB_DataObject::factory($tab);
1577 if (!is_a($x, 'DB_DataObject') && !is_a($x, 'PDO_DataObject')) {
1578 $this->jerr('invalid url - no dataobject');