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.
59 var $do = false; // the dataobject being worked on..
63 parent::getAuth(); // load company!
64 $au = $this->getAuthUser();
67 $this->jerr("Not authenticated", array('authFailure' => true));
69 if (!$au->pid() ) { // not set up yet..
70 $this->jerr("Not authenticated", array('authFailure' => true));
74 $this->authUser = $au;
78 * GET method Roo/TABLENAME
80 * Generally for SELECT or Single SELECT
83 * _id=value single fetch based on primary id.
84 * can be '0' if you want to fetch a set of defaults
85 * Use in conjuntion with toRooSingleArray()
87 * lookup[key]=value single fetch based on a single key value lookup.
88 * multiple key/value can be used. eg. ontable+onid..
89 * _columns what to return.
93 * - all tables are always autojoined.
97 * _columns=a,b,c,d comma seperated list of columns.
98 * _exclude_columns=a,b,c,d comma seperated list of columns.
99 * _distinct=name a distinct column lookup. you also have to use _columns with this.
102 * colname = ... => colname = ....
103 * !colname=.... => colname != ....
104 * !colname[0]=... !colname[1]=... => colname NOT IN (.....) ** only supports main table at present..
105 * colname[0]=... colname[1]=... => colname IN (.....) ** only supports main table at present..
108 * sort=name what to sort.
109 * sort=a,b,d can support multiple columns
110 * dir=ASC what direction
111 * _multisort ={...} JSON encoded { sort : { row : direction }, order : [ row, row, row ] }
114 * start=0 limit start
115 * limit=25 limit number
119 * csvCols[0] csvCols[1].... = .... column titles for CSV output
120 * csvTitles[0], csvTitles[1] .... = columns to use for CSV output
123 * _toggleActive !:!:!:! - this hsould not really be here..
124 * query[add_blank] - add a line in with an empty option... - not really needed???
125 * _delete = delete a list of ids element. (depricated.. this will be removed...)
128 * _post =1 = simulate a post with debuggin on.
129 * _debug_post << This is prefered, as _post may overlap with accouting posts..
131 * _debug = turn on DB_dataobject deubbing, must be admin at present..
134 * CALLS methods on dataobjects if they exist
137 * checkPerm('S' , $authuser)
138 * - can we list the stuff
139 * - return false to disallow...
140 * applySort($au, $sortcol, $direction, $array_of_columns, $multisort)
141 * -- does not support multisort at present..
142 * applyFilters($_REQUEST, $authUser, $roo)
143 * -- apply any query filters on data. and hide stuff not to be seen.
144 * -- can exit by calling $roo->jerr()
145 * postListExtra($_REQUEST) : array(extra_name => data)
146 * - add extra column data on the results (like new messages etc.)
147 * postListFilter($data, $authUser, $request) return $data
148 * - add extra data to an object
151 * toRooSingleArray($authUser, $request) : array
152 * - called on single fetch only, add or maniuplate returned array data.
153 * - is also called when _id=0 is used (for fetching a default set.)
154 * toRooArray($request) : array
155 * - called if singleArray is unavailable on single fetch.
156 * - always tried for mutiple results.
157 * toArray() - the default method if none of the others are found.
158 * toSimpleExcelColumn($col) - see toCSV - this enables special columns to be created for exported data.
161 * - standard DataObject feature - causes all results to show all
165 * _extra_cols -- if set, then filtering by column etc. will use them.
169 function get($tab, $opts = Array())
171 // $this->jerr("Not authenticated", array('authFailure' => true));
172 //echo '<PRE>';print_R($_GET);
173 //DB_DataObject::debuglevel(1);
175 $this->init(); // from pman.
176 //DB_DataObject::debuglevel(1);
177 HTML_FlexyFramework::get()->generateDataobjectsCache($this->isDev && !empty($_REQUEST['isDev']));
185 if ( $this->checkDebugPost()) {
190 //DB_DAtaObject::debuglevel(1);
191 return $this->post($tab);
195 $this->initErrorHandling();
197 $tt = explode('/', $tab);
198 $tab = array_shift($tt);
199 $x = $this->dataObject($tab);
201 $_columns = !empty($_REQUEST['_columns']) ? explode(',', $_REQUEST['_columns']) : false;
203 if (isset( $_REQUEST['lookup'] ) && is_array($_REQUEST['lookup'] )) { // single fetch based on key/value pairs
204 $this->selectSingle($x, $_REQUEST['lookup'],$_REQUEST);
209 // single fetch (use '0' to fetch an empty object..)
210 if (isset($_REQUEST['_id']) && is_numeric($_REQUEST['_id'])) {
212 $this->selectSingle($x, $_REQUEST['_id'],$_REQUEST);
219 if (isset($_REQUEST['_delete'])) {
220 $this->jerr("DELETE by GET has been removed - update the code to use POST");
227 if (isset($_REQUEST['_toggleActive'])) {
228 // do we really delete stuff!?!?!?
229 if (!$this->hasPerm("Core.Staff", 'E')) {
230 $this->jerr("PERMISSION DENIED (ta)");
232 $clean = create_function('$v', 'return (int)$v;');
233 $bits = array_map($clean, explode(',', $_REQUEST['_toggleActive']));
234 if (in_array($this->authUser->id, $bits) && $this->authUser->active) {
235 $this->jerr("you can not disable yourself");
237 $x->query('UPDATE core_person SET active = !active WHERE id IN (' .implode(',', $bits).')');
238 $this->addEvent("USERTOGGLE", false, implode(',', $bits));
239 $this->jok("Updated");
242 //DB_DataObject::debugLevel(1);
244 // sets map and countWhat
245 $this->loadMap($x, array(
246 'columns' => $_columns,
247 'distinct' => empty($_REQUEST['_distinct']) ? false: $_REQUEST['_distinct'],
248 'exclude' => empty($_REQUEST['_exclude_columns']) ? false: explode(',', $_REQUEST['_exclude_columns'])
252 $this->setFilters($x,$_REQUEST);
254 if (!$this->checkPerm($x,'S', $_REQUEST)) {
255 $this->jerr("PERMISSION DENIED (g)");
259 // build join if req.
260 //DB_DataObject::debugLevel(1);
261 // var_dump($this->countWhat);
262 $total = $x->count($this->countWhat);
265 //var_dump($total);exit;
266 $this->applySort($x);
270 if (!empty($_REQUEST['_distinct']) && $total < 400) {
277 empty($_REQUEST['start']) ? 0 : (int)$_REQUEST['start'],
278 min(empty($_REQUEST['limit']) ? 25 : (int)$_REQUEST['limit'], $this->max_limit)
281 $queryObj = clone($x);
282 //DB_DataObject::debuglevel(1);
284 $this->sessionState(0);
286 $this->sessionState(1);
288 if (false === $res) {
289 $this->jerr($x->_lastError->toString());
297 // ---------------- THESE ARE DEPRICATED.. they should be moved to the model...
300 if (!empty($_REQUEST['query']['add_blank'])) {
301 $ret[] = array( 'id' => 0, 'name' => '----');
305 $rooar = method_exists($x, 'toRooArray');
306 $_columnsf = $_columns ? array_flip($_columns) : false;
307 while ($x->fetch()) {
309 $add = $rooar ? $x->toRooArray($_REQUEST) : $x->toArray();
310 if ($add === false) {
313 $ret[] = !$_columns ? $add : array_intersect_key($add, $_columnsf);
317 $ret = array_slice($ret,
318 empty($_REQUEST['start']) ? 0 : (int)$_REQUEST['start'],
319 min(empty($_REQUEST['limit']) ? 25 : (int)$_REQUEST['limit'], 10000)
326 if (method_exists($queryObj ,'postListExtra')) {
327 $extra = $queryObj->postListExtra($_REQUEST, $this);
331 // filter results, and add any data that is needed...
332 if (method_exists($x,'postListFilter')) {
333 $ret = $x->postListFilter($ret, $this->authUser, $_REQUEST);
338 if (!empty($_REQUEST['csvCols']) && !empty($_REQUEST['csvTitles']) ) {
341 $this->toCsv($ret, $_REQUEST['csvCols'], $_REQUEST['csvTitles'],
342 empty($_REQUEST['csvFilename']) ? '' : $_REQUEST['csvFilename'] );
349 //if ($x->tableName() == 'Documents_Tracking') {
350 // $ret = $this->replaceSubject(&$ret, 'doc_id_subject');
355 if (!empty($_REQUEST['_requestMeta']) && count($ret)) {
356 $meta = $this->meta($x, $ret);
358 $extra['metaData'] = $meta;
361 // this make take some time...
362 $this->sessionState(0);
363 // echo "<PRE>"; print_r($ret);
364 $this->jdata($ret, max(count($ret), $total), $extra );
368 function checkDebug($req = false)
370 $req = $req === false ? $_REQUEST : $req;
372 if (empty($req['_debug'])) {
376 if (!empty($_SERVER['HTTP_HOST']) && $_SERVER['HTTP_HOST'] == 'localhost') {
377 DB_DAtaObject::debuglevel((int)$req['_debug']);
385 method_exists($this->authUser,'canDebug')
387 $this->authUser->canDebug()
392 method_exists($this->authUser,'groups')
394 is_a($this->authUser, 'Pman_Core_DataObjects_Core_person')
396 in_array('Administrators', $this->authUser->groups('name'))
401 DB_DAtaObject::debuglevel((int)$req['_debug']);
406 function checkDebugPost()
408 if (empty($_GET['_post']) && empty($_GET['_debug_post'])) {
411 // localhost can do anything...
412 if (!empty($_SERVER['HTTP_HOST']) && $_SERVER['HTTP_HOST'] == 'localhost') {
415 return $this->authUser &&
416 method_exists($this->authUser,'groups') &&
417 in_array('Administrators', $this->authUser->groups('name'));
421 function checkPerm($obj, $lvl, $req= null)
423 if (!method_exists($obj, 'checkPerm')) {
426 if ($obj->checkPerm($lvl, $this->authUser, $req)) {
432 function toCsv($data, $cols, $titles, $filename, $addDate = true)
435 $this->sessionState(0); // turn off sessions - no locking..
437 require_once 'Pman/Core/SimpleExcel.php';
439 $fn = (empty($filename) ? 'list-export-' : urlencode($filename)) . (($addDate) ? date('Y-m-d') : '') ;
443 'workbook' => substr($fn, 0, 31),
450 if (is_object($data)) {
451 $rooar = method_exists($data, 'toRooArray');
452 while($data->fetch()) {
453 $x = $rooar ? $data->toRooArray($q) : $data->toArray();
455 if ($cols == '*') { /// did we get cols sent to us?
456 $cols = array_keys($x);
459 if(!is_array($cols)) {
460 $cols = explode(',', $cols);
463 if ($titles !== false) {
465 $titles= array_keys($x);
467 if(!is_array($titles)) {
468 $titles = explode(',', $titles);
470 foreach($cols as $i=>$col) {
472 'header'=> isset($titles[$i]) ? $titles[$i] : $col,
475 // 'renderer' => array($this, 'getThumb'),
476 // 'color' => 'yellow', // set color for the cell which is a header element
477 // 'fillBlank' => 'gray', // set
480 if (method_exists($data, 'toSimpleExcelColumn')) {
481 $add = $data->toSimpleExcelColumn($add);
484 $se_config['cols'][] = $add;
489 $se = new Pman_Core_SimpleExcel(array(), $se_config);
495 $se->addLine($se_config['workbook'], $x);
501 $this->jerr('no data found', false, 'text/plain');
503 $se->send($fn .'.xls');
508 foreach($data as $x) {
509 //echo "<PRE>"; print_r(array($_REQUEST['csvCols'], $x->toArray())); exit;
513 $cols= array_keys($x);
516 if(!is_array($cols)) {
517 $cols = explode(',', $cols);
520 if ($titles !== false) {
522 $titles= array_keys($x);
525 if(!is_array($titles)) {
526 $titles = explode(',', $titles);
529 foreach($cols as $i=>$col) {
531 'header'=> isset($titles[$i]) ? $titles[$i] : $col,
534 // 'renderer' => array($this, 'getThumb'),
535 // 'color' => 'yellow', // set color for the cell which is a header element
536 // 'fillBlank' => 'gray', // set
539 if (method_exists($this->do, 'toSimpleExcelColumn')) {
540 $add = $this->do->toSimpleExcelColumn($add);
543 $se_config['cols'][] = $add;
548 $se = new Pman_Core_SimpleExcel(array(),$se_config);
551 //fputcsv($fh, $titles);
555 $se->addLine($se_config['workbook'], $x);
559 $this->jerr('no data found');
562 $se->send($fn .'.xls');
569 * POST method Roo/TABLENAME
570 * -- creates, updates, or deletes data.
573 * if the primary key is empty, this happens
574 * will automatically set these to current date and authUser->id
575 * created, created_by, created_dt
576 * updated, update_by, updated_dt
577 * modified, modified_by, modified_dt
579 * will return a GET request SINGLE SELECT (and accepts same)
582 * _delete=1,2,3 delete a set of data.
584 * if the primary key value is set, then update occurs.
585 * will automatically set these to current date and authUser->id
586 * updated, update_by, updated_dt
587 * modified, modified_by, modified_dt
591 * _delete=1,2,3 causes a delete to occur.
592 * _ids=1,2,3,4 causes update to occur on all primary ids.
595 * = same as single SELECT GET request..
600 * _debug=1 forces debug
601 * _get=1 - causes a get request to occur when doing a POST..
605 * these methods on dataobjects if they exist
607 * checkPerm('E' / 'D' , $authuser)
608 * - can we list the stuff
609 * - return false to disallow...
611 * toRooSingleArray($authUser, $request) : array
612 * - called on single fetch only, add or maniuplate returned array data.
613 * toRooArray($request) : array
614 * - Called if toSingleArray does not exist.
615 * - if you need to return different data than toArray..
618 * (for logging - this is generically prefixed to all database operations.)
622 * called when $_FILES is not empty
625 * setFromRoo($ar, $roo)
626 * - alternative to setFrom() which is called if this method does not exist
627 * - values from post (deal with dates etc.) - return true|error string.
628 * - call $roo->jerr() on failure...
630 * CALLS BEFORE change occurs:
632 * beforeDelete($dependants_array, $roo)
633 * Argument is an array of un-find/fetched dependant items.
634 * - jerr() will stop insert.. (Prefered)
635 * - return false for fail and set DO->err;
637 * beforeUpdate($old, $request,$roo)
638 * - after update - jerr() will stop insert..
639 * beforeInsert($request,$roo)
640 * - before insert - jerr() will stop insert..
643 * CALLS AFTER change occured
645 * onUpdate($old, $request,$roo)
646 * - after update // return value ignored
648 * onInsert($request,$roo)
651 * onDelete($request, $roo) - after delete
655 function post($tab) // update / insert (?? delete??)
657 // -- why was this put in? - Roo is not related to Core.All ?
658 //if (!$this->hasPerm("Core.All", 'E')) {
659 // $this->jerr("PERMISSION DENIED (e)");
661 $this->initErrorHandling();
663 // DB_DataObject::debugLevel(1);
666 if (!empty($_REQUEST['_get'])) {
667 return $this->get($tab);
670 $this->init(); // for pman.
672 $x = $this->dataObject($tab);
674 $this->transObj = clone($x);
676 $this->transObj->query('BEGIN');
677 // find the key and use that to get the thing..
680 $this->jerr('no key');
683 $this->key = $keys[0];
685 // delete should be here...
686 if (isset($_REQUEST['_delete'])) {
687 // do we really delete stuff!?!?!?
688 return $this->delete($x,$_REQUEST);
696 // not sure if this is a good idea here...
698 if (!empty($_REQUEST['_ids'])) {
699 $ids = explode(',',$_REQUEST['_ids']);
700 $x->whereAddIn($this->key, $ids, 'int');
701 $ar = $x->fetchAll();
704 $this->update($x, $_REQUEST);
707 $this->jok("UPDATED");
712 if (!empty($_REQUEST[$this->key])) {
714 if (!$x->get($this->key, $_REQUEST[$this->key])) {
715 $this->jerr("Invalid request (id does not point to a record.)");
717 $this->jok($this->update($x, $_REQUEST));
721 $this->jerr("No data recieved for inserting");
724 $this->jok($this->insert($x, $_REQUEST));
736 * apply REQUEST[sort] and [dir]
737 * sort may be an array of columsn..
739 * @arg DB_DataObject $x
742 function applySort($x, $sort = '', $dir ='')
745 // Db_DataObject::debugLevel(1);
746 $sort = empty($_REQUEST['sort']) ? $sort : $_REQUEST['sort'];
747 $dir = empty($_REQUEST['dir']) ? $dir : $_REQUEST['dir'];
748 $dir = $dir == 'ASC' ? 'ASC' : 'DESC';
750 $ms = empty($_REQUEST['_multisort']) ? false : $_REQUEST['_multisort'];
751 //var_Dump($ms);exit;
753 if (method_exists($x, 'applySort')) {
754 $sorted = $x->applySort(
758 array_keys($this->cols),
759 $ms ? json_decode($ms) : false
763 return $this->multiSort($x);
766 if ($sorted === false) {
768 $cols = $x->tableColumns();
769 $excols = array_keys($this->cols);
771 if (isset($x->_extra_cols)) {
772 $excols = array_merge($excols, $x->_extra_cols);
774 $sort_ar = explode(',', $sort);
777 foreach($sort_ar as $sort) {
779 if (strlen($sort) && isset($cols[$sort]) ) {
780 $sort_str[] = $x->tableName() .'.'.$sort . ' ' . $dir ;
782 } else if (in_array($sort, $excols)) {
783 $sort_str[] = $sort . ' ' . $dir ;
788 $x->orderBy(implode(', ', $sort_str ));
799 function multiSort($x)
801 //DB_DataObject::debugLevel(1);
802 $ms = json_decode($_REQUEST['_multisort']);
803 if (!isset($ms->order) || !is_array($ms->order)) {
808 $cols = $x->tableColumns();
810 //print_r($this->cols);exit;
811 // this-><cols contains colname => aliased name...
812 foreach($ms->order as $col) {
813 if (!isset($ms->sort->{$col})) {
814 continue; // no direction..
816 $ms->sort->{$col} = $ms->sort->{$col} == 'ASC' ? 'ASC' : 'DESC';
818 if (strlen($col) && isset($cols[$col]) ) {
819 $sort_str[] = $x->tableName() .'.'.$col . ' ' . $ms->sort->{$col};
822 //print_r($this->cols);
824 if (in_array($col, array_keys($this->cols))) {
825 $sort_str[] = $col. ' ' . $ms->sort->{$col};
828 if (isset($x->_extra_cols) && in_array($col, $x->_extra_cols)) {
829 $sort_str[] = $col. ' ' . $ms->sort->{$col};
834 $x->orderBy(implode(', ', $sort_str ));
841 * - used when _id is set, or after insert or update
843 * @param DataObject $x the dataobject to use
844 * @param int $id the pid of the object
845 * @param array $req the request, or false if it comes from insert/update.
848 function selectSingle($x, $id, $req=false)
852 $_columns = !empty($req['_columns']) ? explode(',', $req['_columns']) : false;
854 //var_dump(array(!is_array($id) , empty($id)));
855 if (!is_array($id) && empty($id)) {
858 if (method_exists($x, 'toRooSingleArray')) {
859 $this->jok($x->toRooSingleArray($this->authUser, $req));
861 if (method_exists($x, 'toRooArray')) {
862 $this->jok($x->toRooArray($req));
865 $this->jok($x->toArray());
869 $this->loadMap($x, array(
870 'columns' => $_columns,
873 if ($req !== false) {
874 $this->setFilters($x, $req);
875 } else if (method_exists($x, 'applyFilters')) {
876 // always call apply filters even after update/insert...
877 // however arguments are not passed.
878 $x->applyFilters(array('_is_update_request' => true), $this->authUser, $this);
881 // DB_DataObject::DebugLevel(1);
884 $x->setFrom($req['lookup'] );
886 if (!$x->find(true)) {
887 if (!empty($id['_id'])) {
889 $this->jok($x->toArray());
894 } else if (!$x->get($id)) {
895 $this->jerr("selectSingle: no such record ($id)");
898 // ignore perms if comming from update/insert - as it's already done...
899 if ($req !== false && !$this->checkPerm($x,'S')) {
900 $this->jerr("PERMISSION DENIED - si");
902 // different symantics on all these calls??
903 if (method_exists($x, 'toRooSingleArray')) {
904 $this->jok($x->toRooSingleArray($this->authUser, $req));
906 if (method_exists($x, 'toRooArray')) {
907 $this->jok($x->toRooArray($req));
910 $this->jok($x->toArray());
915 function insert($x, $req, $with_perm_check = true)
917 if (method_exists($x, 'setFromRoo')) {
918 $res = $x->setFromRoo($req, $this);
919 if (is_string($res)) {
926 if ( $with_perm_check && !$this->checkPerm($x,'A', $req)) {
927 $this->jerr("PERMISSION DENIED (i)");
929 $cols = $x->tableColumns();
931 if (isset($cols['created'])) {
932 $x->created = date('Y-m-d H:i:s');
934 if (isset($cols['created_dt'])) {
935 $x->created_dt = date('Y-m-d H:i:s');
937 if (isset($cols['created_by'])) {
938 $x->created_by = $this->authUser->id;
941 if (isset($cols['modified'])) {
942 $x->modified = date('Y-m-d H:i:s');
944 if (isset($cols['modified_dt'])) {
945 $x->modified_dt = date('Y-m-d H:i:s');
947 if (isset($cols['modified_by'])) {
948 $x->modified_by = $this->authUser->id;
951 if (isset($cols['updated'])) {
952 $x->updated = date('Y-m-d H:i:s');
954 if (isset($cols['updated_dt'])) {
955 $x->updated_dt = date('Y-m-d H:i:s');
957 if (isset($cols['updated_by'])) {
958 $x->updated_by = $this->authUser->id;
961 if (method_exists($x, 'beforeInsert')) {
962 $x->beforeInsert($_REQUEST, $this);
967 if ($res === false) {
968 $this->jerr($x->_lastError->toString());
970 $ev = $this->addEvent("ADD", $x);
971 if (method_exists($x, 'onInsert')) {
972 $x->onInsert($_REQUEST, $this, $ev);
979 // note setFrom might handle this before hand...!??!
980 if (!empty($_FILES) && method_exists($x, 'onUpload')) {
981 $x->onUpload($this, $_REQUEST);
984 return $this->selectSingle(
985 DB_DataObject::factory($x->tableName()),
991 function updateLock($x, $req )
993 Pman::$permitError = true; // allow it to fail without dieing
995 $lock = DB_DataObjecT::factory('Core_locking');
996 Pman::$permitError = false;
997 if (is_a($lock,'DB_DataObject') && $this->authUser) {
999 $lock->on_id = $x->{$this->key};
1000 $lock->on_table= strtolower($x->tableName());
1001 if (!empty($_REQUEST['_lock_id'])) {
1002 $lock->whereAdd('id != ' . ((int)$_REQUEST['_lock_id']));
1004 $lock->whereAdd('person_id !=' . $this->authUser->id);
1007 $llc = clone($lock);
1008 $exp = date('Y-m-d', strtotime('NOW - 1 WEEK'));
1009 $llc->whereAdd("created < '$exp'");
1010 if ($llc->count()) {
1012 while($llc->fetch()) {
1013 $llcd = clone($llc);
1019 if ($lock->find(true)) {
1020 // it's locked by someone else..
1021 $p = $lock->person();
1024 $this->jerr( "Record was locked by " . $p->name . " at " .$lock->created.
1025 " - Please confirm you wish to save"
1026 , array('needs_confirm' => true));
1030 // check the users lock.. - no point.. ??? - if there are no other locks and it's not the users, then they can
1031 // edit it anyways...
1033 // can we find the user's lock.
1034 $lock = DB_DataObjecT::factory('Core_locking');
1035 $lock->on_id = $x->{$this->key};
1036 $lock->on_table= strtolower($x->tableName());
1037 $lock->person_id = $this->authUser->id;
1038 $lock->orderBy('created DESC');
1042 $lock->find(true) &&
1043 isset($x->modified_dt) &&
1044 strtotime($x->modified_dt) > strtotime($lock->created) &&
1045 empty($req['_submit_confirmed']) &&
1046 $x->modified_by != $this->authUser->id
1049 $p = DB_DataObject::factory('core_person');
1050 $p->get($x->modified_by);
1051 $this->jerr($p->name . " saved the record since you started editing,\nDo you really want to update it?", array('needs_confirm' => true));
1063 function update($x, $req, $with_perm_check = true)
1065 if ( $with_perm_check && !$this->checkPerm($x,'E', $req) ) {
1066 $this->jerr("PERMISSION DENIED - No Edit permissions on this element");
1069 // check any locks..
1070 // only done if we recieve a lock_id.
1071 // we are very trusing here.. that someone has not messed around with locks..
1072 // the object might want to check in their checkPerm - if locking is essential..
1073 $lock = $this->updateLock($x,$req);
1083 // this lot is generic.. needs moving
1084 if (method_exists($x, 'setFromRoo')) {
1085 $res = $x->setFromRoo($req, $this);
1086 if (is_string($res)) {
1095 //echo '<PRE>';print_r($old);print_r($x);exit;
1098 $cols = $x->tableColumns();
1100 if (isset($cols['modified'])) {
1101 $x->modified = date('Y-m-d H:i:s');
1103 if (isset($cols['modified_dt'])) {
1104 $x->modified_dt = date('Y-m-d H:i:s');
1106 if (isset($cols['modified_by']) && $this->authUser) {
1107 $x->modified_by = $this->authUser->id;
1110 if (isset($cols['updated'])) {
1111 $x->updated = date('Y-m-d H:i:s');
1113 if (isset($cols['updated_dt'])) {
1114 $x->updated_dt = date('Y-m-d H:i:s');
1116 if (isset($cols['updated_by']) && $this->authUser) {
1117 $x->updated_by = $this->authUser->id;
1120 if (method_exists($x, 'beforeUpdate')) {
1121 $x->beforeUpdate($old, $req, $this);
1124 if ($with_perm_check && !empty($_FILES) && method_exists($x, 'onUpload')) {
1125 $x->onUpload($this, $_REQUEST);
1128 //DB_DataObject::DebugLevel(1);
1129 $res = $x->update($old);
1130 if ($res === false) {
1131 $this->jerr($x->_lastError->toString());
1133 $ev = $this->addEvent("EDIT", $x);
1135 if (method_exists($x, 'onUpdate')) {
1136 $x->onUpdate($old, $req, $this, $ev);
1139 $ev->audit($x, $old);
1143 return $this->selectSingle(
1144 DB_DataObject::factory($x->tableName()),
1150 * Delete a number of records.
1151 * calls $delete_obj->beforeDelete($array_of_dependant_dataobjects, $this)
1155 function delete($x, $req)
1157 // do we really delete stuff!?!?!?
1158 if (empty($req['_delete'])) {
1159 $this->jerr("Delete Requested with no value");
1163 // build a list of tables to queriy for dependant data..
1168 $all_links = $x->databaseLinks();
1170 foreach($all_links as $tbl => $links) {
1171 foreach($links as $col => $totbl_col) {
1172 $to = explode(':', $totbl_col);
1173 if ($to[0] != $x->tableName()) {
1177 $affects[$tbl .'.' . $col] = true;
1182 // echo '<PRE>';print_r($affects);exit;
1183 // DB_Dataobject::debugLevel(1);
1188 $bits = array_map(function($v) { return (int)$v; } , explode(',', $req['_delete']));
1190 // let's assume it has a key!!!
1192 $x->whereAdd($this->key .' IN ('. implode(',', $bits) .')');
1194 $this->jerr("Nothing found to delete");
1197 while ($x->fetch()) {
1203 if (!$this->checkPerm($x,'D') ) {
1204 $this->jerr("PERMISSION DENIED (d)");
1207 $match_ar = array();
1208 foreach($affects as $k=> $true) {
1209 $ka = explode('.', $k);
1211 $chk = DB_DataObject::factory($ka[0]);
1212 if (!is_a($chk,'DB_DataObject') && !is_a($chk,'PDO_DataObject')) {
1213 $this->jerr('Unable to load referenced table, check the links config: ' .$ka[0]);
1215 // print_r(array($chk->tablename() , $ka[1] , $xx->tablename() , $this->key ));
1216 $chk->{$ka[1]} = $xx->{$this->key};
1218 if (count($chk->keys())) {
1219 $matches = $chk->count();
1221 //DB_DataObject::DebugLevel(1);
1222 $matches = $chk->count($ka[1]);
1226 $chk->_match_key = $ka[1];
1227 $match_ar[] = clone($chk);
1233 $has_beforeDelete = method_exists($xx, 'beforeDelete');
1234 // before delte = allows us to trash dependancies if needed..
1237 if ( $has_beforeDelete ) {
1238 if ($xx->beforeDelete($match_ar, $this) === false) {
1239 $errs[] = "Delete failed ({$xx->id})\n".
1240 (isset($xx->err) ? $xx->err : '');
1243 // refetch affects..
1245 $match_ar = array();
1246 foreach($affects as $k=> $true) {
1247 $ka = explode('.', $k);
1248 $chk = DB_DataObject::factory($ka[0]);
1249 if (!is_a($chk,'DB_DataObject') && !is_a($chk,'PDO_DataObject')) {
1250 $this->jerr('Unable to load referenced table, check the links config: ' .$ka[0]);
1252 $chk->{$ka[1]} = $xx->{$this->key};
1253 $matches = $chk->count();
1254 $match_total += $matches;
1256 $chk->_match_key = $ka[1];
1257 $match_ar[] = clone($chk);
1264 if (!empty($match_ar)) {
1265 $chk = $match_ar[0];
1267 $o = $chk->fetchAll();
1268 $key = isset($chk->_match_key) ?$chk->_match_key : '?unknown column?';
1269 $desc = $chk->tableName(). '.' . $key .'='.$xx->{$this->key} ;
1270 if (method_exists($chk, 'toEventString')) {
1271 $desc .= ' : ' . $o[0]->toEventString();
1273 $this->jerr("Delete Dependant records ($match_total found), " .
1274 "first is ( $desc )");
1280 DB_DataObject::Factory('Events')->logDeletedRecord($x);
1282 $this->addEvent("DELETE", $x);
1286 if (method_exists($xx,'onDelete')) {
1287 $xx->onDelete($req, $this);
1293 $this->jerr(implode("\n<BR>", $errs));
1295 $this->jok("Deleted");
1301 * cols stores the list of columns that are available from the query.
1304 * This is a dupe of what is in autojoin -- we should move to using autojoin really.
1316 var $cols = array();
1320 function loadMap($do, $cfg =array()) //$onlycolumns=false, $distinct = false)
1323 //DB_DataObject::debugLevel(5);
1324 $onlycolumns = !empty($cfg['columns']) ? $cfg['columns'] : false;
1325 $distinct = !empty($cfg['distinct']) ? $cfg['distinct'] : false;
1326 $excludecolumns = !empty($cfg['exclude']) ? $cfg['exclude'] : array();
1328 $excludecolumns[] = 'passwd'; // we never expose passwords
1329 $excludecolumns[] = 'oath_key';
1331 $ret = $do->autoJoin(array(
1332 'include' => $onlycolumns,
1333 'exclude' => $excludecolumns,
1334 'distinct' => $distinct
1337 $this->countWhat = $ret['count'];
1338 $this->cols = $ret['cols'];
1339 $this->colsJname = $ret['join_names'];
1348 * generate the meta data neede by queries.
1351 function meta($x, $data)
1353 // this is not going to work on queries where the data does not match the database def..
1354 // for unknown columns we send them as stirngs..
1356 $cols = array_keys($data[0]);
1360 if (class_exists('PDO_DataObject')) {
1361 $options = PDO_DataObject::config();
1362 if (!file_exists($options["schema_location"] . '.reader')) {
1366 $rdata = unserialize(file_get_contents($options["schema_location"] . '.reader'));
1369 //echo '<PRE>';print_r($this->cols); exit;
1370 $options = &PEAR::getStaticProperty('DB_DataObject','options');
1371 $reader = $options["ini_{$x->databaseNickname()}"] .'.reader';
1372 if (!file_exists( $reader )) {
1376 $rdata = unserialize(file_get_contents($reader));
1379 //echo '<PRE>';print_r($this->cols);exit;
1380 //echo '<PRE>';print_r($rdata);exit;
1381 // echo '<PRE>';print_r($rdata);exit;
1384 $key = empty($keys) ? 'id' : $keys[0];
1388 foreach($cols as $c ) {
1389 if (!isset($this->cols[$c]) || !isset($rdata[$this->cols[$c]]) || !is_array($rdata[$this->cols[$c]])) {
1393 $add = $rdata[$this->cols[$c]];
1398 'totalProperty' => 'total',
1399 'successProperty' => 'success',
1401 'id' => $key, // was 'id'...
1408 function setFilters($x, $q)
1410 // if a column is type int, and we get ',' -> the it should be come an inc clause..
1411 // DB_DataObject::debugLevel(1);
1412 if (method_exists($x, 'applyFilters')) {
1413 // DB_DataObject::debugLevel(1);
1414 if (false === $x->applyFilters($q, $this->authUser, $this)) {
1418 $q_filtered = array();
1422 foreach($q as $key=>$val) {
1424 if (in_array($key,$keys) && !is_array($val)) {
1429 // handles name[]=fred&name[]=brian => name in ('fred', 'brian').
1430 // value is an array..
1431 if (is_array($val) ) {
1435 if ($key[0] == '!') {
1437 $key = substr($key,1);
1440 if (!in_array( $key, array_keys($this->cols))) {
1444 // support a[0] a[1] ..... => whereAddIn(
1447 foreach($val as $k=>$v) {
1448 if (!is_numeric($k)) {
1452 // FIXME: note this is not typesafe for anything other than mysql..
1454 if (!is_numeric($v) || !is_long($v)) {
1463 $x->whereAddIn($pref . (
1464 isset($this->colsJname[$key]) ?
1465 $this->colsJname[$key] :
1466 ($x->tableName(). '.'.$key)),
1467 $ar, $quote ? 'string' : 'int');
1474 // handles !name=fred => name not equal fred.
1475 if ($key[0] == '!' && in_array(substr($key, 1), array_keys($this->cols))) {
1477 $key = substr($key, 1) ;
1480 isset($this->colsJname[$key]) ?
1481 $this->colsJname[$key] :
1482 $x->tableName(). '.'.$key ) . ' != ' .
1483 (is_numeric($val) ? $val : "'". $x->escape($val) . "'")
1493 // Events and remarks -- fixme - move to events/remarsk...
1494 case 'on_id': // where TF is this used...
1495 if (!empty($q['query']['original'])) {
1496 // DB_DataObject::debugLevel(1);
1497 $o = (int) $q['query']['original'];
1499 $x->whereAdd("(on_id = $oid OR
1500 on_id IN ( SELECT distinct(id) FROM Documents WHERE original = $o )
1509 if (strlen($val) && $key[0] != '_') {
1510 $q_filtered[$key] = $val;
1513 // subjoined columns = check the values.
1514 // note this is not typesafe for anything other than mysql..
1516 if (isset($this->colsJname[$key])) {
1518 // the aobve rule for !strlen non-joined cols should apply to joined ones.
1519 if (!strlen($val)) {
1525 if (!is_numeric($val) || !is_long($val)) {
1528 $x->whereAdd( "{$this->colsJname[$key]} = " . ($quote ? "'". $x->escape($val) ."'" : $val));
1536 if (!empty($q_filtered)) {
1537 //var_dump($q_filtered);
1541 $x->setFrom($q_filtered);
1547 // nice generic -- let's get rid of it.. where is it used!!!!
1549 // Person / Group / Comapnies.... most of my queries noww...
1551 if (!empty($q['query']['name'])) {
1554 if (in_array( 'name', array_keys($x->table()))) {
1555 $x->whereAdd($x->tableName().".name LIKE '". $x->escape($q['query']['name']) . "%'");
1560 // - projectdirectory staff list - persn queuy
1565 * create the dataobject from (usually the url)
1566 * This uses $this->validTables
1567 * $this->validPrefix (later..)
1568 * to determine if class can be created..
1572 function dataObject($tab)
1574 if (is_array($this->validTables) && !in_array($tab,$this->validTables)) {
1575 $this->jerr("Invalid url - not listed in validTables");
1577 $tab = str_replace('/', '',$tab); // basic protection??
1579 $pm = HTML_FlexyFramework::get()->Pman;
1581 if (isset($pm['roo_alias'])) {
1582 $map = array_flip($pm['roo_alias']);
1583 if (isset($map[$tab])) {
1589 $x = DB_DataObject::factory($tab);
1591 if (!is_a($x, 'DB_DataObject') && !is_a($x, 'PDO_DataObject')) {
1592 $this->jerr('invalid url - no dataobject');