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 // count with multiple joins and no conditions can be quite slow - so if there are no conditions - just remove the joins from the count.
263 $old_where = $x->whereAdd();
264 if (empty($old_where )) {
267 $x->whereAdd($old_where);
272 $total = $xx->count($this->countWhat);
275 //var_dump($total);exit;
276 $this->applySort($x);
280 if (!empty($_REQUEST['_distinct']) && $total < 400) {
287 empty($_REQUEST['start']) ? 0 : (int)$_REQUEST['start'],
288 min(empty($_REQUEST['limit']) ? 25 : (int)$_REQUEST['limit'], $this->max_limit)
291 $queryObj = clone($x);
292 //DB_DataObject::debuglevel(1);
294 $this->sessionState(0);
296 $this->sessionState(1);
298 if (false === $res) {
299 $this->jerr($x->_lastError->toString());
307 // ---------------- THESE ARE DEPRICATED.. they should be moved to the model...
310 if (!empty($_REQUEST['query']['add_blank'])) {
311 $ret[] = array( 'id' => 0, 'name' => '----');
315 $rooar = method_exists($x, 'toRooArray');
316 $_columnsf = $_columns ? array_flip($_columns) : false;
317 while ($x->fetch()) {
319 $add = $rooar ? $x->toRooArray($_REQUEST) : $x->toArray();
320 if ($add === false) {
323 $ret[] = !$_columns ? $add : array_intersect_key($add, $_columnsf);
327 $ret = array_slice($ret,
328 empty($_REQUEST['start']) ? 0 : (int)$_REQUEST['start'],
329 min(empty($_REQUEST['limit']) ? 25 : (int)$_REQUEST['limit'], 10000)
336 if (method_exists($queryObj ,'postListExtra')) {
337 $extra = $queryObj->postListExtra($_REQUEST, $this);
341 // filter results, and add any data that is needed...
342 if (method_exists($x,'postListFilter')) {
343 $ret = $x->postListFilter($ret, $this->authUser, $_REQUEST);
348 if (!empty($_REQUEST['csvCols']) && !empty($_REQUEST['csvTitles']) ) {
351 $this->toCsv($ret, $_REQUEST['csvCols'], $_REQUEST['csvTitles'],
352 empty($_REQUEST['csvFilename']) ? '' : $_REQUEST['csvFilename'] );
359 //if ($x->tableName() == 'Documents_Tracking') {
360 // $ret = $this->replaceSubject(&$ret, 'doc_id_subject');
365 if (!empty($_REQUEST['_requestMeta']) && count($ret)) {
366 $meta = $this->meta($x, $ret);
368 $extra['metaData'] = $meta;
371 // this make take some time...
372 $this->sessionState(0);
373 // echo "<PRE>"; print_r($ret);
374 $this->jdata($ret, max(count($ret), $total), $extra );
378 function checkDebug($req = false)
380 $req = $req === false ? $_REQUEST : $req;
382 if (empty($req['_debug'])) {
386 if (!empty($_SERVER['HTTP_HOST']) && $_SERVER['HTTP_HOST'] == 'localhost') {
387 DB_DAtaObject::debuglevel((int)$req['_debug']);
395 method_exists($this->authUser,'canDebug')
397 $this->authUser->canDebug()
402 method_exists($this->authUser,'groups')
404 is_a($this->authUser, 'Pman_Core_DataObjects_Core_person')
406 in_array('Administrators', $this->authUser->groups('name'))
411 DB_DAtaObject::debuglevel((int)$req['_debug']);
416 function checkDebugPost()
418 if (empty($_GET['_post']) && empty($_GET['_debug_post'])) {
421 // localhost can do anything...
422 if (!empty($_SERVER['HTTP_HOST']) && $_SERVER['HTTP_HOST'] == 'localhost') {
425 return $this->authUser &&
426 method_exists($this->authUser,'groups') &&
427 in_array('Administrators', $this->authUser->groups('name'));
431 function checkPerm($obj, $lvl, $req= null)
433 if (!method_exists($obj, 'checkPerm')) {
436 if ($obj->checkPerm($lvl, $this->authUser, $req)) {
442 function toCsv($data, $cols, $titles, $filename, $addDate = true)
445 $this->sessionState(0); // turn off sessions - no locking..
447 require_once 'Pman/Core/SimpleExcel.php';
449 $fn = (empty($filename) ? 'list-export-' : urlencode($filename)) . (($addDate) ? date('Y-m-d') : '') ;
453 'workbook' => substr($fn, 0, 31),
460 if (is_object($data)) {
461 $rooar = method_exists($data, 'toRooArray');
462 while($data->fetch()) {
463 $x = $rooar ? $data->toRooArray($q) : $data->toArray();
465 if ($cols == '*') { /// did we get cols sent to us?
466 $cols = array_keys($x);
469 if(!is_array($cols)) {
470 $cols = explode(',', $cols);
473 if ($titles !== false) {
475 $titles= array_keys($x);
477 if(!is_array($titles)) {
478 $titles = explode(',', $titles);
480 foreach($cols as $i=>$col) {
482 'header'=> isset($titles[$i]) ? $titles[$i] : $col,
485 // 'renderer' => array($this, 'getThumb'),
486 // 'color' => 'yellow', // set color for the cell which is a header element
487 // 'fillBlank' => 'gray', // set
490 if (method_exists($data, 'toSimpleExcelColumn')) {
491 $add = $data->toSimpleExcelColumn($add);
494 $se_config['cols'][] = $add;
499 $se = new Pman_Core_SimpleExcel(array(), $se_config);
505 $se->addLine($se_config['workbook'], $x);
511 $this->jerr('no data found', false, 'text/plain');
513 $se->send($fn .'.xls');
518 foreach($data as $x) {
519 //echo "<PRE>"; print_r(array($_REQUEST['csvCols'], $x->toArray())); exit;
523 $cols= array_keys($x);
526 if(!is_array($cols)) {
527 $cols = explode(',', $cols);
530 if ($titles !== false) {
532 $titles= array_keys($x);
535 if(!is_array($titles)) {
536 $titles = explode(',', $titles);
539 foreach($cols as $i=>$col) {
541 'header'=> isset($titles[$i]) ? $titles[$i] : $col,
544 // 'renderer' => array($this, 'getThumb'),
545 // 'color' => 'yellow', // set color for the cell which is a header element
546 // 'fillBlank' => 'gray', // set
549 if (method_exists($this->do, 'toSimpleExcelColumn')) {
550 $add = $this->do->toSimpleExcelColumn($add);
553 $se_config['cols'][] = $add;
558 $se = new Pman_Core_SimpleExcel(array(),$se_config);
561 //fputcsv($fh, $titles);
565 $se->addLine($se_config['workbook'], $x);
569 $this->jerr('no data found');
572 $se->send($fn .'.xls');
579 * POST method Roo/TABLENAME
580 * -- creates, updates, or deletes data.
583 * if the primary key is empty, this happens
584 * will automatically set these to current date and authUser->id
585 * created, created_by, created_dt
586 * updated, update_by, updated_dt
587 * modified, modified_by, modified_dt
589 * will return a GET request SINGLE SELECT (and accepts same)
592 * _delete=1,2,3 delete a set of data.
594 * if the primary key value is set, then update occurs.
595 * will automatically set these to current date and authUser->id
596 * updated, update_by, updated_dt
597 * modified, modified_by, modified_dt
601 * _delete=1,2,3 causes a delete to occur.
602 * _ids=1,2,3,4 causes update to occur on all primary ids.
605 * = same as single SELECT GET request..
610 * _debug=1 forces debug
611 * _get=1 - causes a get request to occur when doing a POST..
615 * these methods on dataobjects if they exist
617 * checkPerm('E' / 'D' , $authuser)
618 * - can we list the stuff
619 * - return false to disallow...
621 * toRooSingleArray($authUser, $request) : array
622 * - called on single fetch only, add or maniuplate returned array data.
623 * toRooArray($request) : array
624 * - Called if toSingleArray does not exist.
625 * - if you need to return different data than toArray..
628 * (for logging - this is generically prefixed to all database operations.)
632 * called when $_FILES is not empty
635 * setFromRoo($ar, $roo)
636 * - alternative to setFrom() which is called if this method does not exist
637 * - values from post (deal with dates etc.) - return true|error string.
638 * - call $roo->jerr() on failure...
640 * CALLS BEFORE change occurs:
642 * beforeDelete($dependants_array, $roo)
643 * Argument is an array of un-find/fetched dependant items.
644 * - jerr() will stop insert.. (Prefered)
645 * - return false for fail and set DO->err;
647 * beforeUpdate($old, $request,$roo)
648 * - before update - jerr() will stop insert..
649 * beforeInsert($request,$roo)
650 * - before insert - jerr() will stop insert..
653 * CALLS AFTER change occured
655 * onUpdate($old, $request,$roo)
656 * - after update // return value ignored
658 * onInsert($request,$roo)
661 * onDelete($request, $roo) - after delete
665 function post($tab) // update / insert (?? delete??)
667 // -- why was this put in? - Roo is not related to Core.All ?
668 //if (!$this->hasPerm("Core.All", 'E')) {
669 // $this->jerr("PERMISSION DENIED (e)");
671 $this->initErrorHandling();
673 // DB_DataObject::debugLevel(1);
676 if (!empty($_REQUEST['_get'])) {
677 return $this->get($tab);
680 $this->init(); // for pman.
682 $x = $this->dataObject($tab);
684 $this->transObj = clone($x);
686 $this->transObj->query('BEGIN');
687 // find the key and use that to get the thing..
690 $this->jerr('no key');
693 $this->key = $keys[0];
695 // delete should be here...
696 if (isset($_REQUEST['_delete'])) {
697 // do we really delete stuff!?!?!?
698 return $this->delete($x,$_REQUEST);
706 // not sure if this is a good idea here...
708 if (!empty($_REQUEST['_ids'])) {
709 $ids = explode(',',$_REQUEST['_ids']);
710 $x->whereAddIn($this->key, $ids, 'int');
711 $ar = $x->fetchAll();
714 $this->update($x, $_REQUEST);
717 $this->jok("UPDATED");
722 if (!empty($_REQUEST[$this->key])) {
724 if (!$x->get($this->key, $_REQUEST[$this->key])) {
725 $this->jerr("Invalid request (id does not point to a record.)");
727 $this->jok($this->update($x, $_REQUEST));
731 $this->jerr("No data recieved for inserting");
734 $this->jok($this->insert($x, $_REQUEST));
746 * apply REQUEST[sort] and [dir]
747 * sort may be an array of columsn..
749 * @arg DB_DataObject $x
752 function applySort($x, $sort = '', $dir ='')
755 // Db_DataObject::debugLevel(1);
756 $sort = empty($_REQUEST['sort']) ? $sort : $_REQUEST['sort'];
757 $dir = empty($_REQUEST['dir']) ? $dir : $_REQUEST['dir'];
758 $dir = $dir == 'ASC' ? 'ASC' : 'DESC';
760 $ms = empty($_REQUEST['_multisort']) ? false : $_REQUEST['_multisort'];
761 //var_Dump($ms);exit;
763 if (method_exists($x, 'applySort')) {
764 $sorted = $x->applySort(
768 array_keys($this->cols),
769 $ms ? json_decode($ms) : false
773 return $this->multiSort($x);
776 if ($sorted === false) {
778 $cols = $x->tableColumns();
779 $excols = array_keys($this->cols);
781 if (isset($x->_extra_cols)) {
782 $excols = array_merge($excols, $x->_extra_cols);
784 $sort_ar = explode(',', $sort);
787 foreach($sort_ar as $sort) {
789 if (strlen($sort) && isset($cols[$sort]) ) {
790 $sort_str[] = $x->tableName() .'.'.$sort . ' ' . $dir ;
792 } else if (in_array($sort, $excols)) {
793 $sort_str[] = $sort . ' ' . $dir ;
798 $x->orderBy(implode(', ', $sort_str ));
809 function multiSort($x)
811 //DB_DataObject::debugLevel(1);
812 $ms = json_decode($_REQUEST['_multisort']);
813 if (!isset($ms->order) || !is_array($ms->order)) {
818 $cols = $x->tableColumns();
820 //print_r($this->cols);exit;
821 // this-><cols contains colname => aliased name...
822 foreach($ms->order as $col) {
823 if (!isset($ms->sort->{$col})) {
824 continue; // no direction..
826 $ms->sort->{$col} = $ms->sort->{$col} == 'ASC' ? 'ASC' : 'DESC';
828 if (strlen($col) && isset($cols[$col]) ) {
829 $sort_str[] = $x->tableName() .'.'.$col . ' ' . $ms->sort->{$col};
832 //print_r($this->cols);
834 if (in_array($col, array_keys($this->cols))) {
835 $sort_str[] = $col. ' ' . $ms->sort->{$col};
838 if (isset($x->_extra_cols) && in_array($col, $x->_extra_cols)) {
839 $sort_str[] = $col. ' ' . $ms->sort->{$col};
844 $x->orderBy(implode(', ', $sort_str ));
851 * - used when _id is set, or after insert or update
853 * @param DataObject $x the dataobject to use
854 * @param int $id the pid of the object
855 * @param array $req the request, or false if it comes from insert/update.
858 function selectSingle($x, $id, $req=false)
862 $_columns = !empty($req['_columns']) ? explode(',', $req['_columns']) : false;
864 //var_dump(array(!is_array($id) , empty($id)));
865 if (!is_array($id) && empty($id)) {
868 if (method_exists($x, 'toRooSingleArray')) {
869 $this->jok($x->toRooSingleArray($this->authUser, $req));
871 if (method_exists($x, 'toRooArray')) {
872 $this->jok($x->toRooArray($req));
875 $this->jok($x->toArray());
879 $this->loadMap($x, array(
880 'columns' => $_columns,
883 if ($req !== false) {
884 $this->setFilters($x, $req);
885 } else if (method_exists($x, 'applyFilters')) {
886 // always call apply filters even after update/insert...
887 // however arguments are not passed.
888 $x->applyFilters(array('_is_update_request' => true), $this->authUser, $this);
891 // DB_DataObject::DebugLevel(1);
894 $x->setFrom($req['lookup'] );
896 if (!$x->find(true)) {
897 if (!empty($id['_id'])) {
899 $this->jok($x->toArray());
904 } else if (!$x->get($id)) {
905 $this->jerr("selectSingle: no such record ($id)");
908 // ignore perms if comming from update/insert - as it's already done...
909 if ($req !== false && !$this->checkPerm($x,'S')) {
910 $this->jerr("PERMISSION DENIED - si");
912 // different symantics on all these calls??
913 if (method_exists($x, 'toRooSingleArray')) {
914 $this->jok($x->toRooSingleArray($this->authUser, $req));
916 if (method_exists($x, 'toRooArray')) {
917 $this->jok($x->toRooArray($req));
919 $this->jok($x->toArray());
924 function insert($x, $req, $with_perm_check = true)
927 if (method_exists($x, 'setFromRoo')) {
928 $res = $x->setFromRoo($req, $this);
929 if (is_string($res)) {
936 if ( $with_perm_check && !$this->checkPerm($x,'A', $req)) {
937 $this->jerr("PERMISSION DENIED (i)");
939 $cols = $x->tableColumns();
941 if (isset($cols['created'])) {
942 $x->created = date('Y-m-d H:i:s');
944 if (isset($cols['created_dt'])) {
945 $x->created_dt = date('Y-m-d H:i:s');
947 if (isset($cols['created_by'])) {
948 $x->created_by = $this->authUser->id;
951 if (isset($cols['modified'])) {
952 $x->modified = date('Y-m-d H:i:s');
954 if (isset($cols['modified_dt'])) {
955 $x->modified_dt = date('Y-m-d H:i:s');
957 if (isset($cols['modified_by'])) {
958 $x->modified_by = $this->authUser->id;
961 if (isset($cols['updated'])) {
962 $x->updated = date('Y-m-d H:i:s');
964 if (isset($cols['updated_dt'])) {
965 $x->updated_dt = date('Y-m-d H:i:s');
967 if (isset($cols['updated_by'])) {
968 $x->updated_by = $this->authUser->id;
971 if (method_exists($x, 'beforeInsert')) {
972 $x->beforeInsert($_REQUEST, $this);
977 if ($res === false) {
978 $this->jerr($x->_lastError->toString());
980 $ev = $this->addEvent("ADD", $x);
981 if (method_exists($x, 'onInsert')) {
983 $x->onInsert($_REQUEST, $this, $ev);
990 // note setFrom might handle this before hand...!??!
991 if (!empty($_FILES) && method_exists($x, 'onUpload')) {
992 $x->onUpload($this, $_REQUEST);
995 return $this->selectSingle(
996 DB_DataObject::factory($x->tableName()),
1002 function updateLock($x, $req )
1004 Pman::$permitError = true; // allow it to fail without dieing
1006 $lock = DB_DataObjecT::factory('Core_locking');
1007 Pman::$permitError = false;
1008 if (is_a($lock,'DB_DataObject') && $this->authUser) {
1010 $lock->on_id = $x->{$this->key};
1011 $lock->on_table= strtolower($x->tableName());
1012 if (!empty($_REQUEST['_lock_id'])) {
1013 $lock->whereAdd('id != ' . ((int)$_REQUEST['_lock_id']));
1015 $lock->whereAdd('person_id !=' . $this->authUser->id);
1018 $llc = clone($lock);
1019 $exp = date('Y-m-d', strtotime('NOW - 1 WEEK'));
1020 $llc->whereAdd("created < '$exp'");
1021 if ($llc->count()) {
1023 while($llc->fetch()) {
1024 $llcd = clone($llc);
1030 if ($lock->find(true)) {
1031 // it's locked by someone else..
1032 $p = $lock->person();
1035 $this->jerr( "Record was locked by " . $p->name . " at " .$lock->created.
1036 " - Please confirm you wish to save"
1037 , array('needs_confirm' => true));
1041 // check the users lock.. - no point.. ??? - if there are no other locks and it's not the users, then they can
1042 // edit it anyways...
1044 // can we find the user's lock.
1045 $lock = DB_DataObjecT::factory('Core_locking');
1046 $lock->on_id = $x->{$this->key};
1047 $lock->on_table= strtolower($x->tableName());
1048 $lock->person_id = $this->authUser->id;
1049 $lock->orderBy('created DESC');
1053 $lock->find(true) &&
1054 isset($x->modified_dt) &&
1055 strtotime($x->modified_dt) > strtotime($lock->created) &&
1056 empty($req['_submit_confirmed']) &&
1057 $x->modified_by != $this->authUser->id
1060 $p = DB_DataObject::factory('core_person');
1061 $p->get($x->modified_by);
1062 $this->jerr($p->name . " saved the record since you started editing,\nDo you really want to update it?", array('needs_confirm' => true));
1074 function update($x, $req, $with_perm_check = true)
1076 if ( $with_perm_check && !$this->checkPerm($x,'E', $req) ) {
1077 $this->jerr("PERMISSION DENIED - No Edit permissions on this element");
1080 // check any locks..
1081 // only done if we recieve a lock_id.
1082 // we are very trusing here.. that someone has not messed around with locks..
1083 // the object might want to check in their checkPerm - if locking is essential..
1084 $lock = $this->updateLock($x,$req);
1094 // this lot is generic.. needs moving
1095 if (method_exists($x, 'setFromRoo')) {
1096 $res = $x->setFromRoo($req, $this);
1097 if (is_string($res)) {
1106 //echo '<PRE>';print_r($old);print_r($x);exit;
1109 $cols = $x->tableColumns();
1111 if (isset($cols['modified'])) {
1112 $x->modified = date('Y-m-d H:i:s');
1114 if (isset($cols['modified_dt'])) {
1115 $x->modified_dt = date('Y-m-d H:i:s');
1117 if (isset($cols['modified_by']) && $this->authUser) {
1118 $x->modified_by = $this->authUser->id;
1121 if (isset($cols['updated'])) {
1122 $x->updated = date('Y-m-d H:i:s');
1124 if (isset($cols['updated_dt'])) {
1125 $x->updated_dt = date('Y-m-d H:i:s');
1127 if (isset($cols['updated_by']) && $this->authUser) {
1128 $x->updated_by = $this->authUser->id;
1131 if (method_exists($x, 'beforeUpdate')) {
1132 $x->beforeUpdate($old, $req, $this);
1135 if ($with_perm_check && !empty($_FILES) && method_exists($x, 'onUpload')) {
1136 $x->onUpload($this, $_REQUEST);
1139 //DB_DataObject::DebugLevel(1);
1140 $res = $x->update($old);
1141 if ($res === false) {
1142 $this->jerr($x->_lastError->toString());
1144 $ev = $this->addEvent("EDIT", $x);
1146 if (method_exists($x, 'onUpdate')) {
1147 $x->onUpdate($old, $req, $this, $ev);
1150 $ev->audit($x, $old);
1154 return $this->selectSingle(
1155 DB_DataObject::factory($x->tableName()),
1161 * Delete a number of records.
1162 * calls $delete_obj->beforeDelete($array_of_dependant_dataobjects, $this)
1166 function delete($x, $req)
1168 // do we really delete stuff!?!?!?
1169 if (empty($req['_delete'])) {
1170 $this->jerr("Delete Requested with no value");
1174 // build a list of tables to queriy for dependant data..
1179 $all_links = $x->databaseLinks();
1181 foreach($all_links as $tbl => $links) {
1182 foreach($links as $col => $totbl_col) {
1183 $to = explode(':', $totbl_col);
1184 if ($to[0] != $x->tableName()) {
1188 $affects[$tbl .'.' . $col] = true;
1193 // echo '<PRE>';print_r($affects);exit;
1194 // DB_Dataobject::debugLevel(1);
1199 $bits = array_map(function($v) { return (int)$v; } , explode(',', $req['_delete']));
1201 // let's assume it has a key!!!
1203 $x->whereAdd($this->key .' IN ('. implode(',', $bits) .')');
1205 $this->jerr("Nothing found to delete");
1208 while ($x->fetch()) {
1214 if (!$this->checkPerm($x,'D') ) {
1215 $this->jerr("PERMISSION DENIED (d)");
1218 $match_ar = array();
1219 foreach($affects as $k=> $true) {
1220 $ka = explode('.', $k);
1222 $chk = DB_DataObject::factory($ka[0]);
1223 if (!is_a($chk,'DB_DataObject') && !is_a($chk,'PDO_DataObject')) {
1224 $this->jerr('Unable to load referenced table, check the links config: ' .$ka[0]);
1226 // print_r(array($chk->tablename() , $ka[1] , $xx->tablename() , $this->key ));
1227 $chk->{$ka[1]} = $xx->{$this->key};
1229 if (count($chk->keys())) {
1230 $matches = $chk->count();
1232 //DB_DataObject::DebugLevel(1);
1233 $matches = $chk->count($ka[1]);
1237 $chk->_match_key = $ka[1];
1238 $match_ar[] = clone($chk);
1244 $has_beforeDelete = method_exists($xx, 'beforeDelete');
1245 // before delte = allows us to trash dependancies if needed..
1248 if ( $has_beforeDelete ) {
1249 if ($xx->beforeDelete($match_ar, $this) === false) {
1250 $errs[] = "Delete failed ({$xx->id})\n".
1251 (isset($xx->err) ? $xx->err : '');
1254 // refetch affects..
1256 $match_ar = array();
1257 foreach($affects as $k=> $true) {
1258 $ka = explode('.', $k);
1259 $chk = DB_DataObject::factory($ka[0]);
1260 if (!is_a($chk,'DB_DataObject') && !is_a($chk,'PDO_DataObject')) {
1261 $this->jerr('Unable to load referenced table, check the links config: ' .$ka[0]);
1263 $chk->{$ka[1]} = $xx->{$this->key};
1264 $matches = $chk->count();
1265 $match_total += $matches;
1267 $chk->_match_key = $ka[1];
1268 $match_ar[] = clone($chk);
1275 if (!empty($match_ar)) {
1276 $chk = $match_ar[0];
1278 $o = $chk->fetchAll();
1279 $key = isset($chk->_match_key) ?$chk->_match_key : '?unknown column?';
1280 $desc = $chk->tableName(). '.' . $key .'='.$xx->{$this->key} ;
1281 if (method_exists($chk, 'toEventString')) {
1282 $desc .= ' : ' . $o[0]->toEventString();
1284 $this->jerr("Delete Dependant records ($match_total found), " .
1285 "first is ( $desc )");
1291 DB_DataObject::Factory('Events')->logDeletedRecord($x);
1293 $this->addEvent("DELETE", $x);
1297 if (method_exists($xx,'onDelete')) {
1298 $xx->onDelete($req, $this);
1304 $this->jerr(implode("\n<BR>", $errs));
1306 $this->jok("Deleted");
1312 * cols stores the list of columns that are available from the query.
1315 * This is a dupe of what is in autojoin -- we should move to using autojoin really.
1327 var $cols = array();
1331 function loadMap($do, $cfg =array()) //$onlycolumns=false, $distinct = false)
1334 //DB_DataObject::debugLevel(5);
1335 $onlycolumns = !empty($cfg['columns']) ? $cfg['columns'] : false;
1336 $distinct = !empty($cfg['distinct']) ? $cfg['distinct'] : false;
1337 $excludecolumns = !empty($cfg['exclude']) ? $cfg['exclude'] : array();
1339 $excludecolumns[] = 'passwd'; // we never expose passwords
1340 $excludecolumns[] = 'oath_key';
1342 $ret = $do->autoJoin(array(
1343 'include' => $onlycolumns,
1344 'exclude' => $excludecolumns,
1345 'distinct' => $distinct
1348 $this->countWhat = $ret['count'];
1349 $this->cols = $ret['cols'];
1350 $this->colsJname = $ret['join_names'];
1359 * generate the meta data neede by queries.
1362 function meta($x, $data)
1364 // this is not going to work on queries where the data does not match the database def..
1365 // for unknown columns we send them as stirngs..
1367 $cols = array_keys($data[0]);
1371 if (class_exists('PDO_DataObject')) {
1372 $options = PDO_DataObject::config();
1373 if (!file_exists($options["schema_location"] . '.reader')) {
1377 $rdata = unserialize(file_get_contents($options["schema_location"] . '.reader'));
1380 //echo '<PRE>';print_r($this->cols); exit;
1381 $options = &PEAR::getStaticProperty('DB_DataObject','options');
1382 $reader = $options["ini_{$x->databaseNickname()}"] .'.reader';
1383 if (!file_exists( $reader )) {
1387 $rdata = unserialize(file_get_contents($reader));
1390 //echo '<PRE>';print_r($this->cols);exit;
1391 //echo '<PRE>';print_r($rdata);exit;
1392 // echo '<PRE>';print_r($rdata);exit;
1395 $key = empty($keys) ? 'id' : $keys[0];
1399 foreach($cols as $c ) {
1400 if (!isset($this->cols[$c]) || !isset($rdata[$this->cols[$c]]) || !is_array($rdata[$this->cols[$c]])) {
1404 $add = $rdata[$this->cols[$c]];
1409 'totalProperty' => 'total',
1410 'successProperty' => 'success',
1412 'id' => $key, // was 'id'...
1419 function setFilters($x, $q)
1421 // if a column is type int, and we get ',' -> the it should be come an inc clause..
1422 // DB_DataObject::debugLevel(1);
1423 if (method_exists($x, 'applyFilters')) {
1424 // DB_DataObject::debugLevel(1);
1425 if (false === $x->applyFilters($q, $this->authUser, $this)) {
1429 $q_filtered = array();
1433 foreach($q as $key=>$val) {
1435 if (in_array($key,$keys) && !is_array($val)) {
1440 // handles name[]=fred&name[]=brian => name in ('fred', 'brian').
1441 // value is an array..
1442 if (is_array($val) ) {
1446 if ($key[0] == '!') {
1448 $key = substr($key,1);
1451 if (!in_array( $key, array_keys($this->cols))) {
1455 // support a[0] a[1] ..... => whereAddIn(
1458 foreach($val as $k=>$v) {
1459 if (!is_numeric($k)) {
1463 // FIXME: note this is not typesafe for anything other than mysql..
1465 if (!is_numeric($v) || !is_long($v)) {
1474 $x->whereAddIn($pref . (
1475 isset($this->colsJname[$key]) ?
1476 $this->colsJname[$key] :
1477 ($x->tableName(). '.'.$key)),
1478 $ar, $quote ? 'string' : 'int');
1485 // handles !name=fred => name not equal fred.
1486 if ($key[0] == '!' && in_array(substr($key, 1), array_keys($this->cols))) {
1488 $key = substr($key, 1) ;
1491 isset($this->colsJname[$key]) ?
1492 $this->colsJname[$key] :
1493 $x->tableName(). '.'.$key ) . ' != ' .
1494 (is_numeric($val) ? $val : "'". $x->escape($val) . "'")
1504 // Events and remarks -- fixme - move to events/remarsk...
1505 case 'on_id': // where TF is this used...
1506 if (!empty($q['query']['original'])) {
1507 // DB_DataObject::debugLevel(1);
1508 $o = (int) $q['query']['original'];
1510 $x->whereAdd("(on_id = $oid OR
1511 on_id IN ( SELECT distinct(id) FROM Documents WHERE original = $o )
1520 if (strlen($val) && $key[0] != '_') {
1521 $q_filtered[$key] = $val;
1524 // subjoined columns = check the values.
1525 // note this is not typesafe for anything other than mysql..
1527 if (isset($this->colsJname[$key])) {
1529 // the aobve rule for !strlen non-joined cols should apply to joined ones.
1530 if (!strlen($val)) {
1536 if (!is_numeric($val) || !is_long($val)) {
1539 $x->whereAdd( "{$this->colsJname[$key]} = " . ($quote ? "'". $x->escape($val) ."'" : $val));
1547 if (!empty($q_filtered)) {
1548 //var_dump($q_filtered);
1552 $x->setFrom($q_filtered);
1558 // nice generic -- let's get rid of it.. where is it used!!!!
1560 // Person / Group / Comapnies.... most of my queries noww...
1562 if (!empty($q['query']['name'])) {
1565 if (in_array( 'name', array_keys($x->table()))) {
1566 $x->whereAdd($x->tableName().".name LIKE '". $x->escape($q['query']['name']) . "%'");
1571 // - projectdirectory staff list - persn queuy
1576 * create the dataobject from (usually the url)
1577 * This uses $this->validTables
1578 * $this->validPrefix (later..)
1579 * to determine if class can be created..
1583 function dataObject($tab)
1585 if (is_array($this->validTables) && !in_array($tab,$this->validTables)) {
1586 $this->jerr("Invalid url - not listed in validTables");
1588 $tab = str_replace('/', '',$tab); // basic protection??
1590 $pm = HTML_FlexyFramework::get()->Pman;
1592 if (isset($pm['roo_alias'])) {
1593 $map = array_flip($pm['roo_alias']);
1594 if (isset($map[$tab])) {
1600 $x = DB_DataObject::factory($tab);
1602 if (!is_a($x, 'DB_DataObject') && !is_a($x, 'PDO_DataObject')) {
1603 $this->jerr('invalid url - no dataobject');