4 require_once 'Pman.php';
10 * Uses these methods of the dataobjects:
12 * - checkPerm('L'/'E'/'A', $authuser) - can we list the stuff
14 * - applySort($au, $sortcol, $direction, $array_of_columns, $multisort) -- does not support multisort at present..
15 * - applyFilters($_REQUEST, $authUser, $roo) -- apply any query filters on data. and hide stuff not to be seen. (RETURN false to prevent default filters.)
16 * - postListExtra($_REQUEST) : array(extra_name => data) - add extra column data on the results (like new messages etc.)
17 * - postListFilter($data, $authUser, $request) return $data - add extra data to an object
19 * - toRooSingleArray($authUser, $request) // single fetch, add data..
20 * - toRooArray($request) /// toArray if you need to return different data.. for a list fetch.
23 * CRUD - before/after handlers..
24 * - setFromRoo($ar, $roo) - values from post (deal with dates etc.) - return true|error string.
25 * ... call $roo->jerr() on failure...
28 * - beforeDelete($dependants_array, $roo) Argument is an array of un-find/fetched dependant items.
29 * - jerr() will stop insert.. (Prefered)
30 * - return false for fail and set DO->err;
31 * - beforeUpdate($old, $request,$roo) - after update - jerr() will stop insert..
32 * - beforeInsert($request,$roo) - before insert - jerr() will stop insert..
35 * - onUpdate($old, $request,$roo, $event) - after update // return value ignored
36 * - onInsert($request,$roo, $event) - after insert
37 * - onDelete($req, $roo) - after delete
42 * - toEventString (for logging - this is generically prefixed to all database operations.)
45 class Pman_Roo extends Pman
48 * if set to an array (when extending this, then you can restrict which tables are available
50 var $validTables = false;
52 var $key; // used by update currenly to store primary key.
55 var $max_limit = 10000;
57 var $debugEnabled = true; // disable this for public versions of this code.
61 parent::getAuth(); // load company!
62 $au = $this->getAuthUser();
65 $this->jerr("Not authenticated", array('authFailure' => true));
67 if (!$au->pid() ) { // not set up yet..
68 $this->jerr("Not authenticated", array('authFailure' => true));
72 $this->authUser = $au;
76 * GET method Roo/TABLENAME
78 * Generally for SELECT or Single SELECT
81 * _id=value single fetch based on primary id.
82 * can be '0' if you want to fetch a set of defaults
83 * Use in conjuntion with toRooSingleArray()
85 * lookup[key]=value single fetch based on a single key value lookup.
86 * multiple key/value can be used. eg. ontable+onid..
87 * _columns what to return.
91 * - all tables are always autojoined.
95 * _columns=a,b,c,d comma seperated list of columns.
96 * _exclude_columns=a,b,c,d comma seperated list of columns.
97 * _distinct=name a distinct column lookup. you also have to use _columns with this.
100 * colname = ... => colname = ....
101 * !colname=.... => colname != ....
102 * !colname[0]=... !colname[1]=... => colname NOT IN (.....) ** only supports main table at present..
103 * colname[0]=... colname[1]=... => colname IN (.....) ** only supports main table at present..
106 * sort=name what to sort.
107 * sort=a,b,d can support multiple columns
108 * dir=ASC what direction
109 * _multisort ={...} JSON encoded { sort : { row : direction }, order : [ row, row, row ] }
112 * start=0 limit start
113 * limit=25 limit number
117 * csvCols[0] csvCols[1].... = .... column titles for CSV output
118 * csvTitles[0], csvTitles[1] .... = columns to use for CSV output
121 * _toggleActive !:!:!:! - this hsould not really be here..
122 * query[add_blank] - add a line in with an empty option... - not really needed???
123 * _delete = delete a list of ids element. (depricated.. this will be removed...)
126 * _post =1 = simulate a post with debuggin on.
127 * _debug_post << This is prefered, as _post may overlap with accouting posts..
129 * _debug = turn on DB_dataobject deubbing, must be admin at present..
132 * CALLS methods on dataobjects if they exist
135 * checkPerm('S' , $authuser)
136 * - can we list the stuff
137 * - return false to disallow...
138 * applySort($au, $sortcol, $direction, $array_of_columns, $multisort)
139 * -- does not support multisort at present..
140 * applyFilters($_REQUEST, $authUser, $roo)
141 * -- apply any query filters on data. and hide stuff not to be seen.
142 * -- can exit by calling $roo->jerr()
143 * postListExtra($_REQUEST) : array(extra_name => data)
144 * - add extra column data on the results (like new messages etc.)
145 * postListFilter($data, $authUser, $request) return $data
146 * - add extra data to an object
149 * toRooSingleArray($authUser, $request) : array
150 * - called on single fetch only, add or maniuplate returned array data.
151 * - is also called when _id=0 is used (for fetching a default set.)
152 * toRooArray($request) : array
153 * - called if singleArray is unavailable on single fetch.
154 * - always tried for mutiple results.
155 * toArray() - the default method if none of the others are found.
158 * - standard DataObject feature - causes all results to show all
162 * _extra_cols -- if set, then filtering by column etc. will use them.
166 function get($tab, $opts = Array())
168 // $this->jerr("Not authenticated", array('authFailure' => true));
169 //echo '<PRE>';print_R($_GET);
170 //DB_DataObject::debuglevel(1);
172 $this->init(); // from pman.
173 //DB_DataObject::debuglevel(1);
174 HTML_FlexyFramework::get()->generateDataobjectsCache($this->isDev && !empty($_REQUEST['isDev']));
182 if ( $this->checkDebugPost()) {
187 //DB_DAtaObject::debuglevel(1);
188 return $this->post($tab);
192 $this->initErrorHandling();
194 $tt = explode('/', $tab);
195 $tab = array_shift($tt);
196 $x = $this->dataObject($tab);
198 $_columns = !empty($_REQUEST['_columns']) ? explode(',', $_REQUEST['_columns']) : false;
200 if (isset( $_REQUEST['lookup'] ) && is_array($_REQUEST['lookup'] )) { // single fetch based on key/value pairs
201 $this->selectSingle($x, $_REQUEST['lookup'],$_REQUEST);
206 // single fetch (use '0' to fetch an empty object..)
207 if (isset($_REQUEST['_id']) && is_numeric($_REQUEST['_id'])) {
209 $this->selectSingle($x, $_REQUEST['_id'],$_REQUEST);
216 if (isset($_REQUEST['_delete'])) {
217 $this->jerr("DELETE by GET has been removed - update the code to use POST");
224 if (isset($_REQUEST['_toggleActive'])) {
225 // do we really delete stuff!?!?!?
226 if (!$this->hasPerm("Core.Staff", 'E')) {
227 $this->jerr("PERMISSION DENIED (ta)");
229 $clean = create_function('$v', 'return (int)$v;');
230 $bits = array_map($clean, explode(',', $_REQUEST['_toggleActive']));
231 if (in_array($this->authUser->id, $bits) && $this->authUser->active) {
232 $this->jerr("you can not disable yourself");
234 $x->query('UPDATE core_person SET active = !active WHERE id IN (' .implode(',', $bits).')');
235 $this->addEvent("USERTOGGLE", false, implode(',', $bits));
236 $this->jok("Updated");
239 //DB_DataObject::debugLevel(1);
241 // sets map and countWhat
242 $this->loadMap($x, array(
243 'columns' => $_columns,
244 'distinct' => empty($_REQUEST['_distinct']) ? false: $_REQUEST['_distinct'],
245 'exclude' => empty($_REQUEST['_exclude_columns']) ? false: explode(',', $_REQUEST['_exclude_columns'])
249 $this->setFilters($x,$_REQUEST);
251 if (!$this->checkPerm($x,'S', $_REQUEST)) {
252 $this->jerr("PERMISSION DENIED (g)");
256 // build join if req.
257 //DB_DataObject::debugLevel(1);
258 // var_dump($this->countWhat);
259 $total = $x->count($this->countWhat);
262 //var_dump($total);exit;
263 $this->applySort($x);
267 if (!empty($_REQUEST['_distinct']) && $total < 400) {
274 empty($_REQUEST['start']) ? 0 : (int)$_REQUEST['start'],
275 min(empty($_REQUEST['limit']) ? 25 : (int)$_REQUEST['limit'], $this->max_limit)
278 $queryObj = clone($x);
279 //DB_DataObject::debuglevel(1);
281 $this->sessionState(0);
283 $this->sessionState(1);
285 if (false === $res) {
286 $this->jerr($x->_lastError->toString());
294 // ---------------- THESE ARE DEPRICATED.. they should be moved to the model...
297 if (!empty($_REQUEST['query']['add_blank'])) {
298 $ret[] = array( 'id' => 0, 'name' => '----');
302 $rooar = method_exists($x, 'toRooArray');
303 $_columnsf = $_columns ? array_flip($_columns) : false;
304 while ($x->fetch()) {
306 $add = $rooar ? $x->toRooArray($_REQUEST) : $x->toArray();
307 if ($add === false) {
310 $ret[] = !$_columns ? $add : array_intersect_key($add, $_columnsf);
314 $ret = array_slice($ret,
315 empty($_REQUEST['start']) ? 0 : (int)$_REQUEST['start'],
316 min(empty($_REQUEST['limit']) ? 25 : (int)$_REQUEST['limit'], 10000)
323 if (method_exists($queryObj ,'postListExtra')) {
324 $extra = $queryObj->postListExtra($_REQUEST, $this);
328 // filter results, and add any data that is needed...
329 if (method_exists($x,'postListFilter')) {
330 $ret = $x->postListFilter($ret, $this->authUser, $_REQUEST);
335 if (!empty($_REQUEST['csvCols']) && !empty($_REQUEST['csvTitles']) ) {
338 $this->toCsv($ret, $_REQUEST['csvCols'], $_REQUEST['csvTitles'],
339 empty($_REQUEST['csvFilename']) ? '' : $_REQUEST['csvFilename']
347 //if ($x->tableName() == 'Documents_Tracking') {
348 // $ret = $this->replaceSubject(&$ret, 'doc_id_subject');
353 if (!empty($_REQUEST['_requestMeta']) && count($ret)) {
354 $meta = $this->meta($x, $ret);
356 $extra['metaData'] = $meta;
359 // this make take some time...
360 $this->sessionState(0);
361 // echo "<PRE>"; print_r($ret);
362 $this->jdata($ret, max(count($ret), $total), $extra );
366 function checkDebug($req = false)
368 $req = $req === false ? $_REQUEST : $req;
370 if (empty($req['_debug'])) {
374 if (!empty($_SERVER['HTTP_HOST']) && $_SERVER['HTTP_HOST'] == 'localhost') {
375 DB_DAtaObject::debuglevel((int)$req['_debug']);
383 method_exists($this->authUser,'canDebug')
385 $this->authUser->canDebug()
390 method_exists($this->authUser,'groups')
392 is_a($this->authUser, 'Pman_Core_DataObjects_Core_person')
394 in_array('Administrators', $this->authUser->groups('name'))
399 DB_DAtaObject::debuglevel((int)$req['_debug']);
404 function checkDebugPost()
406 if (empty($_GET['_post']) && empty($_GET['_debug_post'])) {
409 // localhost can do anything...
410 if (!empty($_SERVER['HTTP_HOST']) && $_SERVER['HTTP_HOST'] == 'localhost') {
413 return $this->authUser &&
414 method_exists($this->authUser,'groups') &&
415 in_array('Administrators', $this->authUser->groups('name'));
419 function checkPerm($obj, $lvl, $req= null)
421 if (!method_exists($obj, 'checkPerm')) {
424 if ($obj->checkPerm($lvl, $this->authUser, $req)) {
430 function toCsv($data, $cols, $titles, $filename, $addDate = true)
433 $this->sessionState(0); // turn off sessions - no locking..
435 require_once 'Pman/Core/SimpleExcel.php';
437 $fn = (empty($filename) ? 'list-export-' : urlencode($filename)) . (($addDate) ? date('Y-m-d') : '') ;
441 'workbook' => substr($fn, 0, 31),
448 if (is_object($data)) {
449 $rooar = method_exists($data, 'toRooArray');
450 while($data->fetch()) {
451 $x = $rooar ? $data->toRooArray($q) : $data->toArray();
454 if ($cols == '*') { /// did we get cols sent to us?
455 $cols = array_keys($x);
458 if ($titles !== false) {
460 $titles= array_keys($x);
462 foreach($cols as $i=>$col) {
463 $se_config['cols'][] = array(
464 'header'=> isset($titles[$i]) ? $titles[$i] : $col,
467 // 'renderer' => array($this, 'getThumb'),
468 // 'color' => 'yellow', // set color for the cell which is a header element
469 // 'fillBlank' => 'gray', // set
471 $se = new Pman_Core_SimpleExcel(array(), $se_config);
480 $se->addLine($se_config['workbook'], $x);
486 $this->jerr('no data found', false, 'text/plain');
488 $se->send($fn .'.xls');
494 foreach($data as $x) {
495 //echo "<PRE>"; print_r(array($_REQUEST['csvCols'], $x->toArray())); exit;
498 $titles= array_keys($x);
501 $cols= array_keys($x);
503 if ($titles !== false) {
504 foreach($cols as $i=>$col) {
505 $se_config['cols'][] = array(
506 'header'=> isset($titles[$i]) ? $titles[$i] : $col,
509 // 'renderer' => array($this, 'getThumb'),
510 // 'color' => 'yellow', // set color for the cell which is a header element
511 // 'fillBlank' => 'gray', // set
513 $se = new Pman_Core_SimpleExcel(array(),$se_config);
519 //fputcsv($fh, $titles);
525 $se->addLine($se_config['workbook'], $x);
528 $this->jerr('no data found');
530 $se->send($fn .'.xls');
539 * POST method Roo/TABLENAME
540 * -- creates, updates, or deletes data.
543 * if the primary key is empty, this happens
544 * will automatically set these to current date and authUser->id
545 * created, created_by, created_dt
546 * updated, update_by, updated_dt
547 * modified, modified_by, modified_dt
549 * will return a GET request SINGLE SELECT (and accepts same)
552 * _delete=1,2,3 delete a set of data.
554 * if the primary key value is set, then update occurs.
555 * will automatically set these to current date and authUser->id
556 * updated, update_by, updated_dt
557 * modified, modified_by, modified_dt
561 * _delete=1,2,3 causes a delete to occur.
562 * _ids=1,2,3,4 causes update to occur on all primary ids.
565 * = same as single SELECT GET request..
570 * _debug=1 forces debug
571 * _get=1 - causes a get request to occur when doing a POST..
575 * these methods on dataobjects if they exist
577 * checkPerm('E' / 'D' , $authuser)
578 * - can we list the stuff
579 * - return false to disallow...
581 * toRooSingleArray($authUser, $request) : array
582 * - called on single fetch only, add or maniuplate returned array data.
583 * toRooArray($request) : array
584 * - Called if toSingleArray does not exist.
585 * - if you need to return different data than toArray..
588 * (for logging - this is generically prefixed to all database operations.)
592 * called when $_FILES is not empty
595 * setFromRoo($ar, $roo)
596 * - alternative to setFrom() which is called if this method does not exist
597 * - values from post (deal with dates etc.) - return true|error string.
598 * - call $roo->jerr() on failure...
600 * CALLS BEFORE change occurs:
602 * beforeDelete($dependants_array, $roo)
603 * Argument is an array of un-find/fetched dependant items.
604 * - jerr() will stop insert.. (Prefered)
605 * - return false for fail and set DO->err;
607 * beforeUpdate($old, $request,$roo)
608 * - after update - jerr() will stop insert..
609 * beforeInsert($request,$roo)
610 * - before insert - jerr() will stop insert..
613 * CALLS AFTER change occured
615 * onUpdate($old, $request,$roo)
616 * - after update // return value ignored
618 * onInsert($request,$roo)
621 * onDelete($request, $roo) - after delete
625 function post($tab) // update / insert (?? delete??)
627 // -- why was this put in? - Roo is not related to Core.All ?
628 //if (!$this->hasPerm("Core.All", 'E')) {
629 // $this->jerr("PERMISSION DENIED (e)");
631 $this->initErrorHandling();
633 // DB_DataObject::debugLevel(1);
636 if (!empty($_REQUEST['_get'])) {
637 return $this->get($tab);
640 $this->init(); // for pman.
642 $x = $this->dataObject($tab);
644 $this->transObj = clone($x);
646 $this->transObj->query('BEGIN');
647 // find the key and use that to get the thing..
650 $this->jerr('no key');
653 $this->key = $keys[0];
655 // delete should be here...
656 if (isset($_REQUEST['_delete'])) {
657 // do we really delete stuff!?!?!?
658 return $this->delete($x,$_REQUEST);
666 // not sure if this is a good idea here...
668 if (!empty($_REQUEST['_ids'])) {
669 $ids = explode(',',$_REQUEST['_ids']);
670 $x->whereAddIn($this->key, $ids, 'int');
671 $ar = $x->fetchAll();
674 $this->update($x, $_REQUEST);
677 $this->jok("UPDATED");
682 if (!empty($_REQUEST[$this->key])) {
684 if (!$x->get($this->key, $_REQUEST[$this->key])) {
685 $this->jerr("Invalid request (id does not point to a record.)");
687 $this->jok($this->update($x, $_REQUEST));
691 $this->jerr("No data recieved for inserting");
694 $this->jok($this->insert($x, $_REQUEST));
706 * apply REQUEST[sort] and [dir]
707 * sort may be an array of columsn..
709 * @arg DB_DataObject $x
712 function applySort($x, $sort = '', $dir ='')
715 // Db_DataObject::debugLevel(1);
716 $sort = empty($_REQUEST['sort']) ? $sort : $_REQUEST['sort'];
717 $dir = empty($_REQUEST['dir']) ? $dir : $_REQUEST['dir'];
718 $dir = $dir == 'ASC' ? 'ASC' : 'DESC';
720 $ms = empty($_REQUEST['_multisort']) ? false : $_REQUEST['_multisort'];
721 //var_Dump($ms);exit;
723 if (method_exists($x, 'applySort')) {
724 $sorted = $x->applySort(
728 array_keys($this->cols),
729 $ms ? json_decode($ms) : false
733 return $this->multiSort($x);
736 if ($sorted === false) {
738 $cols = $x->tableColumns();
739 $excols = array_keys($this->cols);
741 if (isset($x->_extra_cols)) {
742 $excols = array_merge($excols, $x->_extra_cols);
744 $sort_ar = explode(',', $sort);
747 foreach($sort_ar as $sort) {
749 if (strlen($sort) && isset($cols[$sort]) ) {
750 $sort_str[] = $x->tableName() .'.'.$sort . ' ' . $dir ;
752 } else if (in_array($sort, $excols)) {
753 $sort_str[] = $sort . ' ' . $dir ;
758 $x->orderBy(implode(', ', $sort_str ));
769 function multiSort($x)
771 //DB_DataObject::debugLevel(1);
772 $ms = json_decode($_REQUEST['_multisort']);
773 if (!isset($ms->order) || !is_array($ms->order)) {
778 $cols = $x->tableColumns();
780 //print_r($this->cols);exit;
781 // this-><cols contains colname => aliased name...
782 foreach($ms->order as $col) {
783 if (!isset($ms->sort->{$col})) {
784 continue; // no direction..
786 $ms->sort->{$col} = $ms->sort->{$col} == 'ASC' ? 'ASC' : 'DESC';
788 if (strlen($col) && isset($cols[$col]) ) {
789 $sort_str[] = $x->tableName() .'.'.$col . ' ' . $ms->sort->{$col};
792 //print_r($this->cols);
794 if (in_array($col, array_keys($this->cols))) {
795 $sort_str[] = $col. ' ' . $ms->sort->{$col};
798 if (isset($x->_extra_cols) && in_array($col, $x->_extra_cols)) {
799 $sort_str[] = $col. ' ' . $ms->sort->{$col};
804 $x->orderBy(implode(', ', $sort_str ));
811 * - used when _id is set, or after insert or update
813 * @param DataObject $x the dataobject to use
814 * @param int $id the pid of the object
815 * @param array $req the request, or false if it comes from insert/update.
818 function selectSingle($x, $id, $req=false)
822 $_columns = !empty($req['_columns']) ? explode(',', $req['_columns']) : false;
824 //var_dump(array(!is_array($id) , empty($id)));
825 if (!is_array($id) && empty($id)) {
828 if (method_exists($x, 'toRooSingleArray')) {
829 $this->jok($x->toRooSingleArray($this->authUser, $req));
831 if (method_exists($x, 'toRooArray')) {
832 $this->jok($x->toRooArray($req));
835 $this->jok($x->toArray());
839 $this->loadMap($x, array(
840 'columns' => $_columns,
843 if ($req !== false) {
844 $this->setFilters($x, $req);
845 } else if (method_exists($x, 'applyFilters')) {
846 // always call apply filters even after update/insert...
847 // however arguments are not passed.
848 $x->applyFilters(array('_is_update_request' => true), $this->authUser, $this);
851 // DB_DataObject::DebugLevel(1);
854 $x->setFrom($req['lookup'] );
856 if (!$x->find(true)) {
857 if (!empty($id['_id'])) {
859 $this->jok($x->toArray());
864 } else if (!$x->get($id)) {
865 $this->jerr("selectSingle: no such record ($id)");
868 // ignore perms if comming from update/insert - as it's already done...
869 if ($req !== false && !$this->checkPerm($x,'S')) {
870 $this->jerr("PERMISSION DENIED - si");
872 // different symantics on all these calls??
873 if (method_exists($x, 'toRooSingleArray')) {
874 $this->jok($x->toRooSingleArray($this->authUser, $req));
876 if (method_exists($x, 'toRooArray')) {
877 $this->jok($x->toRooArray($req));
880 $this->jok($x->toArray());
885 function insert($x, $req, $with_perm_check = true)
887 if (method_exists($x, 'setFromRoo')) {
888 $res = $x->setFromRoo($req, $this);
889 if (is_string($res)) {
896 if ( $with_perm_check && !$this->checkPerm($x,'A', $req)) {
897 $this->jerr("PERMISSION DENIED (i)");
899 $cols = $x->tableColumns();
901 if (isset($cols['created'])) {
902 $x->created = date('Y-m-d H:i:s');
904 if (isset($cols['created_dt'])) {
905 $x->created_dt = date('Y-m-d H:i:s');
907 if (isset($cols['created_by'])) {
908 $x->created_by = $this->authUser->id;
911 if (isset($cols['modified'])) {
912 $x->modified = date('Y-m-d H:i:s');
914 if (isset($cols['modified_dt'])) {
915 $x->modified_dt = date('Y-m-d H:i:s');
917 if (isset($cols['modified_by'])) {
918 $x->modified_by = $this->authUser->id;
921 if (isset($cols['updated'])) {
922 $x->updated = date('Y-m-d H:i:s');
924 if (isset($cols['updated_dt'])) {
925 $x->updated_dt = date('Y-m-d H:i:s');
927 if (isset($cols['updated_by'])) {
928 $x->updated_by = $this->authUser->id;
931 if (method_exists($x, 'beforeInsert')) {
932 $x->beforeInsert($_REQUEST, $this);
937 if ($res === false) {
938 $this->jerr($x->_lastError->toString());
940 $ev = $this->addEvent("ADD", $x);
941 if (method_exists($x, 'onInsert')) {
942 $x->onInsert($_REQUEST, $this, $ev);
949 // note setFrom might handle this before hand...!??!
950 if (!empty($_FILES) && method_exists($x, 'onUpload')) {
951 $x->onUpload($this, $_REQUEST);
954 return $this->selectSingle(
955 DB_DataObject::factory($x->tableName()),
961 function updateLock($x, $req )
963 Pman::$permitError = true; // allow it to fail without dieing
965 $lock = DB_DataObjecT::factory('Core_locking');
966 Pman::$permitError = false;
967 if (is_a($lock,'DB_DataObject') && $this->authUser) {
969 $lock->on_id = $x->{$this->key};
970 $lock->on_table= strtolower($x->tableName());
971 if (!empty($_REQUEST['_lock_id'])) {
972 $lock->whereAdd('id != ' . ((int)$_REQUEST['_lock_id']));
974 $lock->whereAdd('person_id !=' . $this->authUser->id);
978 $exp = date('Y-m-d', strtotime('NOW - 1 WEEK'));
979 $llc->whereAdd("created < '$exp'");
982 while($llc->fetch()) {
989 if ($lock->find(true)) {
990 // it's locked by someone else..
991 $p = $lock->person();
994 $this->jerr( "Record was locked by " . $p->name . " at " .$lock->created.
995 " - Please confirm you wish to save"
996 , array('needs_confirm' => true));
1000 // check the users lock.. - no point.. ??? - if there are no other locks and it's not the users, then they can
1001 // edit it anyways...
1003 // can we find the user's lock.
1004 $lock = DB_DataObjecT::factory('Core_locking');
1005 $lock->on_id = $x->{$this->key};
1006 $lock->on_table= strtolower($x->tableName());
1007 $lock->person_id = $this->authUser->id;
1008 $lock->orderBy('created DESC');
1012 $lock->find(true) &&
1013 isset($x->modified_dt) &&
1014 strtotime($x->modified_dt) > strtotime($lock->created) &&
1015 empty($req['_submit_confirmed']) &&
1016 $x->modified_by != $this->authUser->id
1019 $p = DB_DataObject::factory('core_person');
1020 $p->get($x->modified_by);
1021 $this->jerr($p->name . " saved the record since you started editing,\nDo you really want to update it?", array('needs_confirm' => true));
1033 function update($x, $req, $with_perm_check = true)
1035 if ( $with_perm_check && !$this->checkPerm($x,'E', $req) ) {
1036 $this->jerr("PERMISSION DENIED - No Edit permissions on this element");
1039 // check any locks..
1040 // only done if we recieve a lock_id.
1041 // we are very trusing here.. that someone has not messed around with locks..
1042 // the object might want to check in their checkPerm - if locking is essential..
1043 $lock = $this->updateLock($x,$req);
1053 // this lot is generic.. needs moving
1054 if (method_exists($x, 'setFromRoo')) {
1055 $res = $x->setFromRoo($req, $this);
1056 if (is_string($res)) {
1065 //echo '<PRE>';print_r($old);print_r($x);exit;
1068 $cols = $x->tableColumns();
1070 if (isset($cols['modified'])) {
1071 $x->modified = date('Y-m-d H:i:s');
1073 if (isset($cols['modified_dt'])) {
1074 $x->modified_dt = date('Y-m-d H:i:s');
1076 if (isset($cols['modified_by']) && $this->authUser) {
1077 $x->modified_by = $this->authUser->id;
1080 if (isset($cols['updated'])) {
1081 $x->updated = date('Y-m-d H:i:s');
1083 if (isset($cols['updated_dt'])) {
1084 $x->updated_dt = date('Y-m-d H:i:s');
1086 if (isset($cols['updated_by']) && $this->authUser) {
1087 $x->updated_by = $this->authUser->id;
1090 if (method_exists($x, 'beforeUpdate')) {
1091 $x->beforeUpdate($old, $req, $this);
1094 if ($with_perm_check && !empty($_FILES) && method_exists($x, 'onUpload')) {
1095 $x->onUpload($this, $_REQUEST);
1098 //DB_DataObject::DebugLevel(1);
1099 $res = $x->update($old);
1100 if ($res === false) {
1101 $this->jerr($x->_lastError->toString());
1103 $ev = $this->addEvent("EDIT", $x);
1105 if (method_exists($x, 'onUpdate')) {
1106 $x->onUpdate($old, $req, $this, $ev);
1109 $ev->audit($x, $old);
1113 return $this->selectSingle(
1114 DB_DataObject::factory($x->tableName()),
1120 * Delete a number of records.
1121 * calls $delete_obj->beforeDelete($array_of_dependant_dataobjects, $this)
1125 function delete($x, $req)
1127 // do we really delete stuff!?!?!?
1128 if (empty($req['_delete'])) {
1129 $this->jerr("Delete Requested with no value");
1133 // build a list of tables to queriy for dependant data..
1138 $all_links = $x->databaseLinks();
1140 foreach($all_links as $tbl => $links) {
1141 foreach($links as $col => $totbl_col) {
1142 $to = explode(':', $totbl_col);
1143 if ($to[0] != $x->tableName()) {
1147 $affects[$tbl .'.' . $col] = true;
1152 // echo '<PRE>';print_r($affects);exit;
1153 // DB_Dataobject::debugLevel(1);
1158 $bits = array_map(function($v) { return (int)$v; } , explode(',', $req['_delete']));
1160 // let's assume it has a key!!!
1162 $x->whereAdd($this->key .' IN ('. implode(',', $bits) .')');
1164 $this->jerr("Nothing found to delete");
1167 while ($x->fetch()) {
1173 if (!$this->checkPerm($x,'D') ) {
1174 $this->jerr("PERMISSION DENIED (d)");
1177 $match_ar = array();
1178 foreach($affects as $k=> $true) {
1179 $ka = explode('.', $k);
1181 $chk = DB_DataObject::factory($ka[0]);
1182 if (!is_a($chk,'DB_DataObject') && !is_a($chk,'PDO_DataObject')) {
1183 $this->jerr('Unable to load referenced table, check the links config: ' .$ka[0]);
1185 // print_r(array($chk->tablename() , $ka[1] , $xx->tablename() , $this->key ));
1186 $chk->{$ka[1]} = $xx->{$this->key};
1188 if (count($chk->keys())) {
1189 $matches = $chk->count();
1191 //DB_DataObject::DebugLevel(1);
1192 $matches = $chk->count($ka[1]);
1196 $chk->_match_key = $ka[1];
1197 $match_ar[] = clone($chk);
1203 $has_beforeDelete = method_exists($xx, 'beforeDelete');
1204 // before delte = allows us to trash dependancies if needed..
1207 if ( $has_beforeDelete ) {
1208 if ($xx->beforeDelete($match_ar, $this) === false) {
1209 $errs[] = "Delete failed ({$xx->id})\n".
1210 (isset($xx->err) ? $xx->err : '');
1213 // refetch affects..
1215 $match_ar = array();
1216 foreach($affects as $k=> $true) {
1217 $ka = explode('.', $k);
1218 $chk = DB_DataObject::factory($ka[0]);
1219 if (!is_a($chk,'DB_DataObject') && !is_a($chk,'PDO_DataObject')) {
1220 $this->jerr('Unable to load referenced table, check the links config: ' .$ka[0]);
1222 $chk->{$ka[1]} = $xx->{$this->key};
1223 $matches = $chk->count();
1224 $match_total += $matches;
1226 $chk->_match_key = $ka[1];
1227 $match_ar[] = clone($chk);
1234 if (!empty($match_ar)) {
1235 $chk = $match_ar[0];
1237 $o = $chk->fetchAll();
1238 $key = isset($chk->_match_key) ?$chk->_match_key : '?unknown column?';
1239 $desc = $chk->tableName(). '.' . $key .'='.$xx->{$this->key} ;
1240 if (method_exists($chk, 'toEventString')) {
1241 $desc .= ' : ' . $o[0]->toEventString();
1243 $this->jerr("Delete Dependant records ($match_total found), " .
1244 "first is ( $desc )");
1250 DB_DataObject::Factory('Events')->logDeletedRecord($x);
1252 $this->addEvent("DELETE", $x);
1256 if (method_exists($xx,'onDelete')) {
1257 $xx->onDelete($req, $this);
1263 $this->jerr(implode("\n<BR>", $errs));
1265 $this->jok("Deleted");
1271 * cols stores the list of columns that are available from the query.
1274 * This is a dupe of what is in autojoin -- we should move to using autojoin really.
1286 var $cols = array();
1290 function loadMap($do, $cfg =array()) //$onlycolumns=false, $distinct = false)
1293 //DB_DataObject::debugLevel(5);
1294 $onlycolumns = !empty($cfg['columns']) ? $cfg['columns'] : false;
1295 $distinct = !empty($cfg['distinct']) ? $cfg['distinct'] : false;
1296 $excludecolumns = !empty($cfg['exclude']) ? $cfg['exclude'] : array();
1298 $excludecolumns[] = 'passwd'; // we never expose passwords
1299 $excludecolumns[] = 'oath_key';
1301 $ret = $do->autoJoin(array(
1302 'include' => $onlycolumns,
1303 'exclude' => $excludecolumns,
1304 'distinct' => $distinct
1307 $this->countWhat = $ret['count'];
1308 $this->cols = $ret['cols'];
1309 $this->colsJname = $ret['join_names'];
1318 * generate the meta data neede by queries.
1321 function meta($x, $data)
1323 // this is not going to work on queries where the data does not match the database def..
1324 // for unknown columns we send them as stirngs..
1326 $cols = array_keys($data[0]);
1330 if (class_exists('PDO_DataObject')) {
1331 $options = PDO_DataObject::config();
1332 if (!file_exists($options["schema_location"] . '.reader')) {
1336 $rdata = unserialize(file_get_contents($options["schema_location"] . '.reader'));
1339 //echo '<PRE>';print_r($this->cols); exit;
1340 $options = &PEAR::getStaticProperty('DB_DataObject','options');
1341 $reader = $options["ini_{$x->databaseNickname()}"] .'.reader';
1342 if (!file_exists( $reader )) {
1346 $rdata = unserialize(file_get_contents($reader));
1349 //echo '<PRE>';print_r($this->cols);exit;
1350 //echo '<PRE>';print_r($rdata);exit;
1351 // echo '<PRE>';print_r($rdata);exit;
1354 $key = empty($keys) ? 'id' : $keys[0];
1358 foreach($cols as $c ) {
1359 if (!isset($this->cols[$c]) || !isset($rdata[$this->cols[$c]]) || !is_array($rdata[$this->cols[$c]])) {
1363 $add = $rdata[$this->cols[$c]];
1368 'totalProperty' => 'total',
1369 'successProperty' => 'success',
1371 'id' => $key, // was 'id'...
1378 function setFilters($x, $q)
1380 // if a column is type int, and we get ',' -> the it should be come an inc clause..
1381 // DB_DataObject::debugLevel(1);
1382 if (method_exists($x, 'applyFilters')) {
1383 // DB_DataObject::debugLevel(1);
1384 if (false === $x->applyFilters($q, $this->authUser, $this)) {
1388 $q_filtered = array();
1392 foreach($q as $key=>$val) {
1394 if (in_array($key,$keys) && !is_array($val)) {
1399 // handles name[]=fred&name[]=brian => name in ('fred', 'brian').
1400 // value is an array..
1401 if (is_array($val) ) {
1405 if ($key[0] == '!') {
1407 $key = substr($key,1);
1410 if (!in_array( $key, array_keys($this->cols))) {
1414 // support a[0] a[1] ..... => whereAddIn(
1417 foreach($val as $k=>$v) {
1418 if (!is_numeric($k)) {
1422 // FIXME: note this is not typesafe for anything other than mysql..
1424 if (!is_numeric($v) || !is_long($v)) {
1433 $x->whereAddIn($pref . (
1434 isset($this->colsJname[$key]) ?
1435 $this->colsJname[$key] :
1436 ($x->tableName(). '.'.$key)),
1437 $ar, $quote ? 'string' : 'int');
1444 // handles !name=fred => name not equal fred.
1445 if ($key[0] == '!' && in_array(substr($key, 1), array_keys($this->cols))) {
1447 $key = substr($key, 1) ;
1450 isset($this->colsJname[$key]) ?
1451 $this->colsJname[$key] :
1452 $x->tableName(). '.'.$key ) . ' != ' .
1453 (is_numeric($val) ? $val : "'". $x->escape($val) . "'")
1463 // Events and remarks -- fixme - move to events/remarsk...
1464 case 'on_id': // where TF is this used...
1465 if (!empty($q['query']['original'])) {
1466 // DB_DataObject::debugLevel(1);
1467 $o = (int) $q['query']['original'];
1469 $x->whereAdd("(on_id = $oid OR
1470 on_id IN ( SELECT distinct(id) FROM Documents WHERE original = $o )
1479 if (strlen($val) && $key[0] != '_') {
1480 $q_filtered[$key] = $val;
1483 // subjoined columns = check the values.
1484 // note this is not typesafe for anything other than mysql..
1486 if (isset($this->colsJname[$key])) {
1488 // the aobve rule for !strlen non-joined cols should apply to joined ones.
1489 if (!strlen($val)) {
1495 if (!is_numeric($val) || !is_long($val)) {
1498 $x->whereAdd( "{$this->colsJname[$key]} = " . ($quote ? "'". $x->escape($val) ."'" : $val));
1506 if (!empty($q_filtered)) {
1507 //var_dump($q_filtered);
1511 $x->setFrom($q_filtered);
1517 // nice generic -- let's get rid of it.. where is it used!!!!
1519 // Person / Group / Comapnies.... most of my queries noww...
1521 if (!empty($q['query']['name'])) {
1524 if (in_array( 'name', array_keys($x->table()))) {
1525 $x->whereAdd($x->tableName().".name LIKE '". $x->escape($q['query']['name']) . "%'");
1530 // - projectdirectory staff list - persn queuy
1535 * create the dataobject from (usually the url)
1536 * This uses $this->validTables
1537 * $this->validPrefix (later..)
1538 * to determine if class can be created..
1542 function dataObject($tab)
1544 if (is_array($this->validTables) && !in_array($tab,$this->validTables)) {
1545 $this->jerr("Invalid url - not listed in validTables");
1547 $tab = str_replace('/', '',$tab); // basic protection??
1549 $pm = HTML_FlexyFramework::get()->Pman;
1551 if (isset($pm['roo_alias'])) {
1552 $map = array_flip($pm['roo_alias']);
1553 if (isset($map[$tab])) {
1559 $x = DB_DataObject::factory($tab);
1561 if (!is_a($x, 'DB_DataObject') && !is_a($x, 'PDO_DataObject')) {
1562 $this->jerr('invalid url - no dataobject');