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.
156 * toSimpleExcelColumn($col) - see toCSV - this enables special columns to be created for exported data.
159 * - standard DataObject feature - causes all results to show all
163 * _extra_cols -- if set, then filtering by column etc. will use them.
167 function get($tab, $opts = Array())
169 // $this->jerr("Not authenticated", array('authFailure' => true));
170 //echo '<PRE>';print_R($_GET);
171 //DB_DataObject::debuglevel(1);
173 $this->init(); // from pman.
174 //DB_DataObject::debuglevel(1);
175 HTML_FlexyFramework::get()->generateDataobjectsCache($this->isDev && !empty($_REQUEST['isDev']));
183 if ( $this->checkDebugPost()) {
188 //DB_DAtaObject::debuglevel(1);
189 return $this->post($tab);
193 $this->initErrorHandling();
195 $tt = explode('/', $tab);
196 $tab = array_shift($tt);
197 $x = $this->dataObject($tab);
199 $_columns = !empty($_REQUEST['_columns']) ? explode(',', $_REQUEST['_columns']) : false;
201 if (isset( $_REQUEST['lookup'] ) && is_array($_REQUEST['lookup'] )) { // single fetch based on key/value pairs
202 $this->selectSingle($x, $_REQUEST['lookup'],$_REQUEST);
207 // single fetch (use '0' to fetch an empty object..)
208 if (isset($_REQUEST['_id']) && is_numeric($_REQUEST['_id'])) {
210 $this->selectSingle($x, $_REQUEST['_id'],$_REQUEST);
217 if (isset($_REQUEST['_delete'])) {
218 $this->jerr("DELETE by GET has been removed - update the code to use POST");
225 if (isset($_REQUEST['_toggleActive'])) {
226 // do we really delete stuff!?!?!?
227 if (!$this->hasPerm("Core.Staff", 'E')) {
228 $this->jerr("PERMISSION DENIED (ta)");
230 $clean = create_function('$v', 'return (int)$v;');
231 $bits = array_map($clean, explode(',', $_REQUEST['_toggleActive']));
232 if (in_array($this->authUser->id, $bits) && $this->authUser->active) {
233 $this->jerr("you can not disable yourself");
235 $x->query('UPDATE core_person SET active = !active WHERE id IN (' .implode(',', $bits).')');
236 $this->addEvent("USERTOGGLE", false, implode(',', $bits));
237 $this->jok("Updated");
240 //DB_DataObject::debugLevel(1);
242 // sets map and countWhat
243 $this->loadMap($x, array(
244 'columns' => $_columns,
245 'distinct' => empty($_REQUEST['_distinct']) ? false: $_REQUEST['_distinct'],
246 'exclude' => empty($_REQUEST['_exclude_columns']) ? false: explode(',', $_REQUEST['_exclude_columns'])
250 $this->setFilters($x,$_REQUEST);
252 if (!$this->checkPerm($x,'S', $_REQUEST)) {
253 $this->jerr("PERMISSION DENIED (g)");
257 // build join if req.
258 //DB_DataObject::debugLevel(1);
259 // var_dump($this->countWhat);
260 $total = $x->count($this->countWhat);
263 //var_dump($total);exit;
264 $this->applySort($x);
268 if (!empty($_REQUEST['_distinct']) && $total < 400) {
275 empty($_REQUEST['start']) ? 0 : (int)$_REQUEST['start'],
276 min(empty($_REQUEST['limit']) ? 25 : (int)$_REQUEST['limit'], $this->max_limit)
279 $queryObj = clone($x);
280 //DB_DataObject::debuglevel(1);
282 $this->sessionState(0);
284 $this->sessionState(1);
286 if (false === $res) {
287 $this->jerr($x->_lastError->toString());
295 // ---------------- THESE ARE DEPRICATED.. they should be moved to the model...
298 if (!empty($_REQUEST['query']['add_blank'])) {
299 $ret[] = array( 'id' => 0, 'name' => '----');
303 $rooar = method_exists($x, 'toRooArray');
304 $_columnsf = $_columns ? array_flip($_columns) : false;
305 while ($x->fetch()) {
307 $add = $rooar ? $x->toRooArray($_REQUEST) : $x->toArray();
308 if ($add === false) {
311 $ret[] = !$_columns ? $add : array_intersect_key($add, $_columnsf);
315 $ret = array_slice($ret,
316 empty($_REQUEST['start']) ? 0 : (int)$_REQUEST['start'],
317 min(empty($_REQUEST['limit']) ? 25 : (int)$_REQUEST['limit'], 10000)
324 if (method_exists($queryObj ,'postListExtra')) {
325 $extra = $queryObj->postListExtra($_REQUEST, $this);
329 // filter results, and add any data that is needed...
330 if (method_exists($x,'postListFilter')) {
331 $ret = $x->postListFilter($ret, $this->authUser, $_REQUEST);
336 if (!empty($_REQUEST['csvCols']) && !empty($_REQUEST['csvTitles']) ) {
339 $this->toCsv($ret, $_REQUEST['csvCols'], $_REQUEST['csvTitles'],
340 empty($_REQUEST['csvFilename']) ? '' : $_REQUEST['csvFilename'],
348 //if ($x->tableName() == 'Documents_Tracking') {
349 // $ret = $this->replaceSubject(&$ret, 'doc_id_subject');
354 if (!empty($_REQUEST['_requestMeta']) && count($ret)) {
355 $meta = $this->meta($x, $ret);
357 $extra['metaData'] = $meta;
360 // this make take some time...
361 $this->sessionState(0);
362 // echo "<PRE>"; print_r($ret);
363 $this->jdata($ret, max(count($ret), $total), $extra );
367 function checkDebug($req = false)
369 $req = $req === false ? $_REQUEST : $req;
371 if (empty($req['_debug'])) {
375 if (!empty($_SERVER['HTTP_HOST']) && $_SERVER['HTTP_HOST'] == 'localhost') {
376 DB_DAtaObject::debuglevel((int)$req['_debug']);
384 method_exists($this->authUser,'canDebug')
386 $this->authUser->canDebug()
391 method_exists($this->authUser,'groups')
393 is_a($this->authUser, 'Pman_Core_DataObjects_Core_person')
395 in_array('Administrators', $this->authUser->groups('name'))
400 DB_DAtaObject::debuglevel((int)$req['_debug']);
405 function checkDebugPost()
407 if (empty($_GET['_post']) && empty($_GET['_debug_post'])) {
410 // localhost can do anything...
411 if (!empty($_SERVER['HTTP_HOST']) && $_SERVER['HTTP_HOST'] == 'localhost') {
414 return $this->authUser &&
415 method_exists($this->authUser,'groups') &&
416 in_array('Administrators', $this->authUser->groups('name'));
420 function checkPerm($obj, $lvl, $req= null)
422 if (!method_exists($obj, 'checkPerm')) {
425 if ($obj->checkPerm($lvl, $this->authUser, $req)) {
431 function toCsv($data, $cols, $titles, $filename, $addDate = true)
434 $this->sessionState(0); // turn off sessions - no locking..
436 require_once 'Pman/Core/SimpleExcel.php';
438 $fn = (empty($filename) ? 'list-export-' : urlencode($filename)) . (($addDate) ? date('Y-m-d') : '') ;
442 'workbook' => substr($fn, 0, 31),
449 if (is_object($data)) {
450 $rooar = method_exists($data, 'toRooArray');
451 while($data->fetch()) {
452 $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($col);
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');
509 foreach($data as $x) {
510 //echo "<PRE>"; print_r(array($_REQUEST['csvCols'], $x->toArray())); exit;
514 $cols= array_keys($x);
517 if(!is_array($cols)) {
518 $cols = explode(',', $cols);
521 if ($titles !== false) {
523 $titles= array_keys($x);
526 if(!is_array($titles)) {
527 $titles = explode(',', $titles);
530 foreach($cols as $i=>$col) {
531 $se_config['cols'][] = array(
532 'header'=> isset($titles[$i]) ? $titles[$i] : $col,
535 // 'renderer' => array($this, 'getThumb'),
536 // 'color' => 'yellow', // set color for the cell which is a header element
537 // 'fillBlank' => 'gray', // set
539 $se = new Pman_Core_SimpleExcel(array(),$se_config);
545 //fputcsv($fh, $titles);
549 $se->addLine($se_config['workbook'], $x);
553 $this->jerr('no data found');
556 $se->send($fn .'.xls');
563 * POST method Roo/TABLENAME
564 * -- creates, updates, or deletes data.
567 * if the primary key is empty, this happens
568 * will automatically set these to current date and authUser->id
569 * created, created_by, created_dt
570 * updated, update_by, updated_dt
571 * modified, modified_by, modified_dt
573 * will return a GET request SINGLE SELECT (and accepts same)
576 * _delete=1,2,3 delete a set of data.
578 * if the primary key value is set, then update occurs.
579 * will automatically set these to current date and authUser->id
580 * updated, update_by, updated_dt
581 * modified, modified_by, modified_dt
585 * _delete=1,2,3 causes a delete to occur.
586 * _ids=1,2,3,4 causes update to occur on all primary ids.
589 * = same as single SELECT GET request..
594 * _debug=1 forces debug
595 * _get=1 - causes a get request to occur when doing a POST..
599 * these methods on dataobjects if they exist
601 * checkPerm('E' / 'D' , $authuser)
602 * - can we list the stuff
603 * - return false to disallow...
605 * toRooSingleArray($authUser, $request) : array
606 * - called on single fetch only, add or maniuplate returned array data.
607 * toRooArray($request) : array
608 * - Called if toSingleArray does not exist.
609 * - if you need to return different data than toArray..
612 * (for logging - this is generically prefixed to all database operations.)
616 * called when $_FILES is not empty
619 * setFromRoo($ar, $roo)
620 * - alternative to setFrom() which is called if this method does not exist
621 * - values from post (deal with dates etc.) - return true|error string.
622 * - call $roo->jerr() on failure...
624 * CALLS BEFORE change occurs:
626 * beforeDelete($dependants_array, $roo)
627 * Argument is an array of un-find/fetched dependant items.
628 * - jerr() will stop insert.. (Prefered)
629 * - return false for fail and set DO->err;
631 * beforeUpdate($old, $request,$roo)
632 * - after update - jerr() will stop insert..
633 * beforeInsert($request,$roo)
634 * - before insert - jerr() will stop insert..
637 * CALLS AFTER change occured
639 * onUpdate($old, $request,$roo)
640 * - after update // return value ignored
642 * onInsert($request,$roo)
645 * onDelete($request, $roo) - after delete
649 function post($tab) // update / insert (?? delete??)
651 // -- why was this put in? - Roo is not related to Core.All ?
652 //if (!$this->hasPerm("Core.All", 'E')) {
653 // $this->jerr("PERMISSION DENIED (e)");
655 $this->initErrorHandling();
657 // DB_DataObject::debugLevel(1);
660 if (!empty($_REQUEST['_get'])) {
661 return $this->get($tab);
664 $this->init(); // for pman.
666 $x = $this->dataObject($tab);
668 $this->transObj = clone($x);
670 $this->transObj->query('BEGIN');
671 // find the key and use that to get the thing..
674 $this->jerr('no key');
677 $this->key = $keys[0];
679 // delete should be here...
680 if (isset($_REQUEST['_delete'])) {
681 // do we really delete stuff!?!?!?
682 return $this->delete($x,$_REQUEST);
690 // not sure if this is a good idea here...
692 if (!empty($_REQUEST['_ids'])) {
693 $ids = explode(',',$_REQUEST['_ids']);
694 $x->whereAddIn($this->key, $ids, 'int');
695 $ar = $x->fetchAll();
698 $this->update($x, $_REQUEST);
701 $this->jok("UPDATED");
706 if (!empty($_REQUEST[$this->key])) {
708 if (!$x->get($this->key, $_REQUEST[$this->key])) {
709 $this->jerr("Invalid request (id does not point to a record.)");
711 $this->jok($this->update($x, $_REQUEST));
715 $this->jerr("No data recieved for inserting");
718 $this->jok($this->insert($x, $_REQUEST));
730 * apply REQUEST[sort] and [dir]
731 * sort may be an array of columsn..
733 * @arg DB_DataObject $x
736 function applySort($x, $sort = '', $dir ='')
739 // Db_DataObject::debugLevel(1);
740 $sort = empty($_REQUEST['sort']) ? $sort : $_REQUEST['sort'];
741 $dir = empty($_REQUEST['dir']) ? $dir : $_REQUEST['dir'];
742 $dir = $dir == 'ASC' ? 'ASC' : 'DESC';
744 $ms = empty($_REQUEST['_multisort']) ? false : $_REQUEST['_multisort'];
745 //var_Dump($ms);exit;
747 if (method_exists($x, 'applySort')) {
748 $sorted = $x->applySort(
752 array_keys($this->cols),
753 $ms ? json_decode($ms) : false
757 return $this->multiSort($x);
760 if ($sorted === false) {
762 $cols = $x->tableColumns();
763 $excols = array_keys($this->cols);
765 if (isset($x->_extra_cols)) {
766 $excols = array_merge($excols, $x->_extra_cols);
768 $sort_ar = explode(',', $sort);
771 foreach($sort_ar as $sort) {
773 if (strlen($sort) && isset($cols[$sort]) ) {
774 $sort_str[] = $x->tableName() .'.'.$sort . ' ' . $dir ;
776 } else if (in_array($sort, $excols)) {
777 $sort_str[] = $sort . ' ' . $dir ;
782 $x->orderBy(implode(', ', $sort_str ));
793 function multiSort($x)
795 //DB_DataObject::debugLevel(1);
796 $ms = json_decode($_REQUEST['_multisort']);
797 if (!isset($ms->order) || !is_array($ms->order)) {
802 $cols = $x->tableColumns();
804 //print_r($this->cols);exit;
805 // this-><cols contains colname => aliased name...
806 foreach($ms->order as $col) {
807 if (!isset($ms->sort->{$col})) {
808 continue; // no direction..
810 $ms->sort->{$col} = $ms->sort->{$col} == 'ASC' ? 'ASC' : 'DESC';
812 if (strlen($col) && isset($cols[$col]) ) {
813 $sort_str[] = $x->tableName() .'.'.$col . ' ' . $ms->sort->{$col};
816 //print_r($this->cols);
818 if (in_array($col, array_keys($this->cols))) {
819 $sort_str[] = $col. ' ' . $ms->sort->{$col};
822 if (isset($x->_extra_cols) && in_array($col, $x->_extra_cols)) {
823 $sort_str[] = $col. ' ' . $ms->sort->{$col};
828 $x->orderBy(implode(', ', $sort_str ));
835 * - used when _id is set, or after insert or update
837 * @param DataObject $x the dataobject to use
838 * @param int $id the pid of the object
839 * @param array $req the request, or false if it comes from insert/update.
842 function selectSingle($x, $id, $req=false)
846 $_columns = !empty($req['_columns']) ? explode(',', $req['_columns']) : false;
848 //var_dump(array(!is_array($id) , empty($id)));
849 if (!is_array($id) && empty($id)) {
852 if (method_exists($x, 'toRooSingleArray')) {
853 $this->jok($x->toRooSingleArray($this->authUser, $req));
855 if (method_exists($x, 'toRooArray')) {
856 $this->jok($x->toRooArray($req));
859 $this->jok($x->toArray());
863 $this->loadMap($x, array(
864 'columns' => $_columns,
867 if ($req !== false) {
868 $this->setFilters($x, $req);
869 } else if (method_exists($x, 'applyFilters')) {
870 // always call apply filters even after update/insert...
871 // however arguments are not passed.
872 $x->applyFilters(array('_is_update_request' => true), $this->authUser, $this);
875 // DB_DataObject::DebugLevel(1);
878 $x->setFrom($req['lookup'] );
880 if (!$x->find(true)) {
881 if (!empty($id['_id'])) {
883 $this->jok($x->toArray());
888 } else if (!$x->get($id)) {
889 $this->jerr("selectSingle: no such record ($id)");
892 // ignore perms if comming from update/insert - as it's already done...
893 if ($req !== false && !$this->checkPerm($x,'S')) {
894 $this->jerr("PERMISSION DENIED - si");
896 // different symantics on all these calls??
897 if (method_exists($x, 'toRooSingleArray')) {
898 $this->jok($x->toRooSingleArray($this->authUser, $req));
900 if (method_exists($x, 'toRooArray')) {
901 $this->jok($x->toRooArray($req));
904 $this->jok($x->toArray());
909 function insert($x, $req, $with_perm_check = true)
911 if (method_exists($x, 'setFromRoo')) {
912 $res = $x->setFromRoo($req, $this);
913 if (is_string($res)) {
920 if ( $with_perm_check && !$this->checkPerm($x,'A', $req)) {
921 $this->jerr("PERMISSION DENIED (i)");
923 $cols = $x->tableColumns();
925 if (isset($cols['created'])) {
926 $x->created = date('Y-m-d H:i:s');
928 if (isset($cols['created_dt'])) {
929 $x->created_dt = date('Y-m-d H:i:s');
931 if (isset($cols['created_by'])) {
932 $x->created_by = $this->authUser->id;
935 if (isset($cols['modified'])) {
936 $x->modified = date('Y-m-d H:i:s');
938 if (isset($cols['modified_dt'])) {
939 $x->modified_dt = date('Y-m-d H:i:s');
941 if (isset($cols['modified_by'])) {
942 $x->modified_by = $this->authUser->id;
945 if (isset($cols['updated'])) {
946 $x->updated = date('Y-m-d H:i:s');
948 if (isset($cols['updated_dt'])) {
949 $x->updated_dt = date('Y-m-d H:i:s');
951 if (isset($cols['updated_by'])) {
952 $x->updated_by = $this->authUser->id;
955 if (method_exists($x, 'beforeInsert')) {
956 $x->beforeInsert($_REQUEST, $this);
961 if ($res === false) {
962 $this->jerr($x->_lastError->toString());
964 $ev = $this->addEvent("ADD", $x);
965 if (method_exists($x, 'onInsert')) {
966 $x->onInsert($_REQUEST, $this, $ev);
973 // note setFrom might handle this before hand...!??!
974 if (!empty($_FILES) && method_exists($x, 'onUpload')) {
975 $x->onUpload($this, $_REQUEST);
978 return $this->selectSingle(
979 DB_DataObject::factory($x->tableName()),
985 function updateLock($x, $req )
987 Pman::$permitError = true; // allow it to fail without dieing
989 $lock = DB_DataObjecT::factory('Core_locking');
990 Pman::$permitError = false;
991 if (is_a($lock,'DB_DataObject') && $this->authUser) {
993 $lock->on_id = $x->{$this->key};
994 $lock->on_table= strtolower($x->tableName());
995 if (!empty($_REQUEST['_lock_id'])) {
996 $lock->whereAdd('id != ' . ((int)$_REQUEST['_lock_id']));
998 $lock->whereAdd('person_id !=' . $this->authUser->id);
1001 $llc = clone($lock);
1002 $exp = date('Y-m-d', strtotime('NOW - 1 WEEK'));
1003 $llc->whereAdd("created < '$exp'");
1004 if ($llc->count()) {
1006 while($llc->fetch()) {
1007 $llcd = clone($llc);
1013 if ($lock->find(true)) {
1014 // it's locked by someone else..
1015 $p = $lock->person();
1018 $this->jerr( "Record was locked by " . $p->name . " at " .$lock->created.
1019 " - Please confirm you wish to save"
1020 , array('needs_confirm' => true));
1024 // check the users lock.. - no point.. ??? - if there are no other locks and it's not the users, then they can
1025 // edit it anyways...
1027 // can we find the user's lock.
1028 $lock = DB_DataObjecT::factory('Core_locking');
1029 $lock->on_id = $x->{$this->key};
1030 $lock->on_table= strtolower($x->tableName());
1031 $lock->person_id = $this->authUser->id;
1032 $lock->orderBy('created DESC');
1036 $lock->find(true) &&
1037 isset($x->modified_dt) &&
1038 strtotime($x->modified_dt) > strtotime($lock->created) &&
1039 empty($req['_submit_confirmed']) &&
1040 $x->modified_by != $this->authUser->id
1043 $p = DB_DataObject::factory('core_person');
1044 $p->get($x->modified_by);
1045 $this->jerr($p->name . " saved the record since you started editing,\nDo you really want to update it?", array('needs_confirm' => true));
1057 function update($x, $req, $with_perm_check = true)
1059 if ( $with_perm_check && !$this->checkPerm($x,'E', $req) ) {
1060 $this->jerr("PERMISSION DENIED - No Edit permissions on this element");
1063 // check any locks..
1064 // only done if we recieve a lock_id.
1065 // we are very trusing here.. that someone has not messed around with locks..
1066 // the object might want to check in their checkPerm - if locking is essential..
1067 $lock = $this->updateLock($x,$req);
1077 // this lot is generic.. needs moving
1078 if (method_exists($x, 'setFromRoo')) {
1079 $res = $x->setFromRoo($req, $this);
1080 if (is_string($res)) {
1089 //echo '<PRE>';print_r($old);print_r($x);exit;
1092 $cols = $x->tableColumns();
1094 if (isset($cols['modified'])) {
1095 $x->modified = date('Y-m-d H:i:s');
1097 if (isset($cols['modified_dt'])) {
1098 $x->modified_dt = date('Y-m-d H:i:s');
1100 if (isset($cols['modified_by']) && $this->authUser) {
1101 $x->modified_by = $this->authUser->id;
1104 if (isset($cols['updated'])) {
1105 $x->updated = date('Y-m-d H:i:s');
1107 if (isset($cols['updated_dt'])) {
1108 $x->updated_dt = date('Y-m-d H:i:s');
1110 if (isset($cols['updated_by']) && $this->authUser) {
1111 $x->updated_by = $this->authUser->id;
1114 if (method_exists($x, 'beforeUpdate')) {
1115 $x->beforeUpdate($old, $req, $this);
1118 if ($with_perm_check && !empty($_FILES) && method_exists($x, 'onUpload')) {
1119 $x->onUpload($this, $_REQUEST);
1122 //DB_DataObject::DebugLevel(1);
1123 $res = $x->update($old);
1124 if ($res === false) {
1125 $this->jerr($x->_lastError->toString());
1127 $ev = $this->addEvent("EDIT", $x);
1129 if (method_exists($x, 'onUpdate')) {
1130 $x->onUpdate($old, $req, $this, $ev);
1133 $ev->audit($x, $old);
1137 return $this->selectSingle(
1138 DB_DataObject::factory($x->tableName()),
1144 * Delete a number of records.
1145 * calls $delete_obj->beforeDelete($array_of_dependant_dataobjects, $this)
1149 function delete($x, $req)
1151 // do we really delete stuff!?!?!?
1152 if (empty($req['_delete'])) {
1153 $this->jerr("Delete Requested with no value");
1157 // build a list of tables to queriy for dependant data..
1162 $all_links = $x->databaseLinks();
1164 foreach($all_links as $tbl => $links) {
1165 foreach($links as $col => $totbl_col) {
1166 $to = explode(':', $totbl_col);
1167 if ($to[0] != $x->tableName()) {
1171 $affects[$tbl .'.' . $col] = true;
1176 // echo '<PRE>';print_r($affects);exit;
1177 // DB_Dataobject::debugLevel(1);
1182 $bits = array_map(function($v) { return (int)$v; } , explode(',', $req['_delete']));
1184 // let's assume it has a key!!!
1186 $x->whereAdd($this->key .' IN ('. implode(',', $bits) .')');
1188 $this->jerr("Nothing found to delete");
1191 while ($x->fetch()) {
1197 if (!$this->checkPerm($x,'D') ) {
1198 $this->jerr("PERMISSION DENIED (d)");
1201 $match_ar = array();
1202 foreach($affects as $k=> $true) {
1203 $ka = explode('.', $k);
1205 $chk = DB_DataObject::factory($ka[0]);
1206 if (!is_a($chk,'DB_DataObject') && !is_a($chk,'PDO_DataObject')) {
1207 $this->jerr('Unable to load referenced table, check the links config: ' .$ka[0]);
1209 // print_r(array($chk->tablename() , $ka[1] , $xx->tablename() , $this->key ));
1210 $chk->{$ka[1]} = $xx->{$this->key};
1212 if (count($chk->keys())) {
1213 $matches = $chk->count();
1215 //DB_DataObject::DebugLevel(1);
1216 $matches = $chk->count($ka[1]);
1220 $chk->_match_key = $ka[1];
1221 $match_ar[] = clone($chk);
1227 $has_beforeDelete = method_exists($xx, 'beforeDelete');
1228 // before delte = allows us to trash dependancies if needed..
1231 if ( $has_beforeDelete ) {
1232 if ($xx->beforeDelete($match_ar, $this) === false) {
1233 $errs[] = "Delete failed ({$xx->id})\n".
1234 (isset($xx->err) ? $xx->err : '');
1237 // refetch affects..
1239 $match_ar = array();
1240 foreach($affects as $k=> $true) {
1241 $ka = explode('.', $k);
1242 $chk = DB_DataObject::factory($ka[0]);
1243 if (!is_a($chk,'DB_DataObject') && !is_a($chk,'PDO_DataObject')) {
1244 $this->jerr('Unable to load referenced table, check the links config: ' .$ka[0]);
1246 $chk->{$ka[1]} = $xx->{$this->key};
1247 $matches = $chk->count();
1248 $match_total += $matches;
1250 $chk->_match_key = $ka[1];
1251 $match_ar[] = clone($chk);
1258 if (!empty($match_ar)) {
1259 $chk = $match_ar[0];
1261 $o = $chk->fetchAll();
1262 $key = isset($chk->_match_key) ?$chk->_match_key : '?unknown column?';
1263 $desc = $chk->tableName(). '.' . $key .'='.$xx->{$this->key} ;
1264 if (method_exists($chk, 'toEventString')) {
1265 $desc .= ' : ' . $o[0]->toEventString();
1267 $this->jerr("Delete Dependant records ($match_total found), " .
1268 "first is ( $desc )");
1274 DB_DataObject::Factory('Events')->logDeletedRecord($x);
1276 $this->addEvent("DELETE", $x);
1280 if (method_exists($xx,'onDelete')) {
1281 $xx->onDelete($req, $this);
1287 $this->jerr(implode("\n<BR>", $errs));
1289 $this->jok("Deleted");
1295 * cols stores the list of columns that are available from the query.
1298 * This is a dupe of what is in autojoin -- we should move to using autojoin really.
1310 var $cols = array();
1314 function loadMap($do, $cfg =array()) //$onlycolumns=false, $distinct = false)
1317 //DB_DataObject::debugLevel(5);
1318 $onlycolumns = !empty($cfg['columns']) ? $cfg['columns'] : false;
1319 $distinct = !empty($cfg['distinct']) ? $cfg['distinct'] : false;
1320 $excludecolumns = !empty($cfg['exclude']) ? $cfg['exclude'] : array();
1322 $excludecolumns[] = 'passwd'; // we never expose passwords
1323 $excludecolumns[] = 'oath_key';
1325 $ret = $do->autoJoin(array(
1326 'include' => $onlycolumns,
1327 'exclude' => $excludecolumns,
1328 'distinct' => $distinct
1331 $this->countWhat = $ret['count'];
1332 $this->cols = $ret['cols'];
1333 $this->colsJname = $ret['join_names'];
1342 * generate the meta data neede by queries.
1345 function meta($x, $data)
1347 // this is not going to work on queries where the data does not match the database def..
1348 // for unknown columns we send them as stirngs..
1350 $cols = array_keys($data[0]);
1354 if (class_exists('PDO_DataObject')) {
1355 $options = PDO_DataObject::config();
1356 if (!file_exists($options["schema_location"] . '.reader')) {
1360 $rdata = unserialize(file_get_contents($options["schema_location"] . '.reader'));
1363 //echo '<PRE>';print_r($this->cols); exit;
1364 $options = &PEAR::getStaticProperty('DB_DataObject','options');
1365 $reader = $options["ini_{$x->databaseNickname()}"] .'.reader';
1366 if (!file_exists( $reader )) {
1370 $rdata = unserialize(file_get_contents($reader));
1373 //echo '<PRE>';print_r($this->cols);exit;
1374 //echo '<PRE>';print_r($rdata);exit;
1375 // echo '<PRE>';print_r($rdata);exit;
1378 $key = empty($keys) ? 'id' : $keys[0];
1382 foreach($cols as $c ) {
1383 if (!isset($this->cols[$c]) || !isset($rdata[$this->cols[$c]]) || !is_array($rdata[$this->cols[$c]])) {
1387 $add = $rdata[$this->cols[$c]];
1392 'totalProperty' => 'total',
1393 'successProperty' => 'success',
1395 'id' => $key, // was 'id'...
1402 function setFilters($x, $q)
1404 // if a column is type int, and we get ',' -> the it should be come an inc clause..
1405 // DB_DataObject::debugLevel(1);
1406 if (method_exists($x, 'applyFilters')) {
1407 // DB_DataObject::debugLevel(1);
1408 if (false === $x->applyFilters($q, $this->authUser, $this)) {
1412 $q_filtered = array();
1416 foreach($q as $key=>$val) {
1418 if (in_array($key,$keys) && !is_array($val)) {
1423 // handles name[]=fred&name[]=brian => name in ('fred', 'brian').
1424 // value is an array..
1425 if (is_array($val) ) {
1429 if ($key[0] == '!') {
1431 $key = substr($key,1);
1434 if (!in_array( $key, array_keys($this->cols))) {
1438 // support a[0] a[1] ..... => whereAddIn(
1441 foreach($val as $k=>$v) {
1442 if (!is_numeric($k)) {
1446 // FIXME: note this is not typesafe for anything other than mysql..
1448 if (!is_numeric($v) || !is_long($v)) {
1457 $x->whereAddIn($pref . (
1458 isset($this->colsJname[$key]) ?
1459 $this->colsJname[$key] :
1460 ($x->tableName(). '.'.$key)),
1461 $ar, $quote ? 'string' : 'int');
1468 // handles !name=fred => name not equal fred.
1469 if ($key[0] == '!' && in_array(substr($key, 1), array_keys($this->cols))) {
1471 $key = substr($key, 1) ;
1474 isset($this->colsJname[$key]) ?
1475 $this->colsJname[$key] :
1476 $x->tableName(). '.'.$key ) . ' != ' .
1477 (is_numeric($val) ? $val : "'". $x->escape($val) . "'")
1487 // Events and remarks -- fixme - move to events/remarsk...
1488 case 'on_id': // where TF is this used...
1489 if (!empty($q['query']['original'])) {
1490 // DB_DataObject::debugLevel(1);
1491 $o = (int) $q['query']['original'];
1493 $x->whereAdd("(on_id = $oid OR
1494 on_id IN ( SELECT distinct(id) FROM Documents WHERE original = $o )
1503 if (strlen($val) && $key[0] != '_') {
1504 $q_filtered[$key] = $val;
1507 // subjoined columns = check the values.
1508 // note this is not typesafe for anything other than mysql..
1510 if (isset($this->colsJname[$key])) {
1512 // the aobve rule for !strlen non-joined cols should apply to joined ones.
1513 if (!strlen($val)) {
1519 if (!is_numeric($val) || !is_long($val)) {
1522 $x->whereAdd( "{$this->colsJname[$key]} = " . ($quote ? "'". $x->escape($val) ."'" : $val));
1530 if (!empty($q_filtered)) {
1531 //var_dump($q_filtered);
1535 $x->setFrom($q_filtered);
1541 // nice generic -- let's get rid of it.. where is it used!!!!
1543 // Person / Group / Comapnies.... most of my queries noww...
1545 if (!empty($q['query']['name'])) {
1548 if (in_array( 'name', array_keys($x->table()))) {
1549 $x->whereAdd($x->tableName().".name LIKE '". $x->escape($q['query']['name']) . "%'");
1554 // - projectdirectory staff list - persn queuy
1559 * create the dataobject from (usually the url)
1560 * This uses $this->validTables
1561 * $this->validPrefix (later..)
1562 * to determine if class can be created..
1566 function dataObject($tab)
1568 if (is_array($this->validTables) && !in_array($tab,$this->validTables)) {
1569 $this->jerr("Invalid url - not listed in validTables");
1571 $tab = str_replace('/', '',$tab); // basic protection??
1573 $pm = HTML_FlexyFramework::get()->Pman;
1575 if (isset($pm['roo_alias'])) {
1576 $map = array_flip($pm['roo_alias']);
1577 if (isset($map[$tab])) {
1583 $x = DB_DataObject::factory($tab);
1585 if (!is_a($x, 'DB_DataObject') && !is_a($x, 'PDO_DataObject')) {
1586 $this->jerr('invalid url - no dataobject');