Pman/Roo.php
[Pman.Base] / Pman / Roo.php
1 <?php
2
3
4 require_once 'Pman.php';
5 /**
6  * 
7  * 
8  * not really sure how save our factory method is....!!!
9  * 
10  * 
11  * Uses these methods of the dataobjects:
12  * - checkPerm('L'/'E'/'A', $authuser) - can we list the stuff
13  * 
14  * - applySort($au, $sortcol, $direction, $array_of_columns, $multisort) -- does not support multisort at present..
15  * - applyFilters($_REQUEST, $authUser) -- apply any query filters on data. and hide stuff not to be seen.
16  * - postListExtra($_REQUEST) : array(extra_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
18  * 
19  * - toRooSingleArray($authUser, $request) // single fetch, add data..
20  * - toRooArray($request) /// toArray if you need to return different data.. for a list fetch.
21  * 
22  * 
23  * - beforeDelete($ar) -- return false for fail and set DO->err;
24  *                        Argument is an array of un-find/fetched dependant items.
25  * - onUpdate($old, $request,$roo) - after update // return value ignored
26  * - onInsert($request,$roo) - after insert
27  * - onUpload($roo)
28  * - setFromRoo($ar) - values from post (deal with dates etc.) - return true|error string.
29  * 
30  * - toEventString (for logging - this is generically prefixed to all database operations.)
31  */
32
33 class Pman_Roo extends Pman
34 {
35     
36     
37     var $key; // used by update currenly to store primary key.
38     
39     function getAuth() {
40         parent::getAuth(); // load company!
41         $au = $this->getAuthUser();
42         if (!$au) {
43             $this->jerr("Not authenticated", array('authFailure' => true));
44         }
45         $this->authUser = $au;
46         return true;
47     }
48     /**
49      * GET method   Roo/TABLENAME.php 
50      * -- defaults to listing data. with args.
51      *
52      * 
53      * !colname=....                 => colname != ....
54      * !colname[0]=... !colname[1]=... => colname NOT IN (.....) ** only supports main table at present..
55      * colname[0]=... colname[1]=... => colname IN (.....) ** only supports main table at present..
56      * 
57      * other opts:
58      * _post      = simulate a post with debuggin on.
59      * lookup     =  array( k=>v) single fetch based on a key/value pair
60      * _id        =  single fetch based on id.
61      * _delete    = delete a list of ids element. (seperated by ,);
62      * _columns   = comma seperated list of columns.
63      * _distinct   = a distinct column lookup.
64      * _requestMeta = default behaviour of Roo stores.. on first query..
65      * 
66      * csvCols[0] csvCols[1]....    = .... column titles for CSV output
67      * 
68      * csvTitles[0], csvTitles[1] ....  = columns to use for CSV output
69      *
70      * sort        = sort column (',' comma delimited)
71      * dir         = sort direction ?? in future comma delimited...
72      * _multisort  = JSON encoded { sort : { row : direction }, order : [ row, row, row ] }
73      * start       = limit start
74      * limit       = limit number 
75      * 
76      * _toggleActive !:!:!:! - this hsould not really be here..
77      * query[add_blank] - add a line in with an empty option...  - not really needed???
78      * 
79      */
80     function get($tab)
81     {
82          //  $this->jerr("Not authenticated", array('authFailure' => true));
83        //echo '<PRE>';print_R($_GET);
84       //DB_DataObject::debuglevel(1);
85         
86         $this->init(); // from pnan.
87         //DB_DataObject::debuglevel(1);
88         HTML_FlexyFramework::get()->generateDataobjectsCache($this->isDev);
89         // debugging...
90         if (!empty($_GET['_post'])) {
91             $_POST  = $_GET;
92             //DB_DAtaObject::debuglevel(1);
93             return $this->post($tab);
94         }
95         $tab = str_replace('/', '',$tab); // basic protection??
96         
97         $x = DB_DataObject::factory($tab);
98         
99         if (!is_a($x, 'DB_DataObject')) {
100             $this->jerr('invalid url');
101         }
102         $_columns = !empty($_REQUEST['_columns']) ? explode(',', $_REQUEST['_columns']) : false;
103         
104         if (isset( $_REQUEST['lookup'] )) { // single fetch based on key/value pairs
105             if (method_exists($x, 'checkPerm') && !$x->checkPerm('S', $this->authUser))  {
106                 $this->jerr("PERMISSION DENIED");
107             }
108             $this->loadMap($x, $_columns);
109             $x->setFrom($_REQUEST['lookup'] );
110             $x->limit(1);
111             if (!$x->find(true)) {
112                 $this->jok(false);
113             }
114             $this->jok($x->toArray());
115         }
116         
117         
118         
119         if (isset($_REQUEST['_id'])) { // single fetch
120             
121             if (empty($_REQUEST['_id'])) {
122                 $this->jok($x->toArray());  // return an empty array!
123             }
124            
125             $this->loadMap($x, $_columns);
126             
127             if (!$x->get($_REQUEST['_id'])) {
128                 $this->jerr("no such record");
129             }
130             
131             if (method_exists($x, 'checkPerm') && !$x->checkPerm('S', $this->authUser))  {
132                 $this->jerr("PERMISSION DENIED");
133             }
134             
135             $this->jok(method_exists($x, 'toRooSingleArray') ? $x->toRooSingleArray($this->authUser, $_REQUEST) : $x->toArray());
136             
137         }
138         
139        
140         if (isset($_REQUEST['_delete'])) {
141             
142             $keys = $x->keys();
143             if (empty($keys) ) {
144                 $this->jerr('no key');
145             }
146             
147             $this->key = $keys[0];
148             
149             
150             // do we really delete stuff!?!?!?
151             return $this->delete($x,$_REQUEST);
152         } 
153         
154         
155         
156         
157         if (isset($_REQUEST['_toggleActive'])) {
158             // do we really delete stuff!?!?!?
159             if (!$this->hasPerm("Core.Staff", 'E'))  {
160                 $this->jerr("PERMISSION DENIED");
161             }
162             $clean = create_function('$v', 'return (int)$v;');
163             $bits = array_map($clean, explode(',', $_REQUEST['_toggleActive']));
164             if (in_array($this->authUser->id, $bits) && $this->authUser->active) {
165                 $this->jerr("you can not disable yourself");
166             }
167             $x->query('UPDATE Person SET active = !active WHERE id IN (' .implode(',', $bits).')');
168             $this->addEvent("USERTOGGLE", false, implode(',', $bits));
169             $this->jok("Updated");
170             
171         }
172        //DB_DataObject::debugLevel(1);
173         if (method_exists($x, 'checkPerm') && !$x->checkPerm('S', $this->authUser))  {
174             $this->jerr("PERMISSION DENIED");
175         }
176         
177         // sets map and countWhat
178         $this->loadMap($x, $_columns, empty($_REQUEST['_distinct']) ? false:  $_REQUEST['_distinct']);
179         
180         $this->setFilters($x,$_REQUEST);
181       
182          //print_r($x);
183         // build join if req.
184           //DB_DataObject::debugLevel(1);
185         $total = $x->count($this->countWhat);
186         // sorting..
187       //   
188         //var_dump($total);exit;
189         $this->applySort($x);
190         
191         
192  
193         $x->limit(
194             empty($_REQUEST['start']) ? 0 : (int)$_REQUEST['start'],
195             min(empty($_REQUEST['limit']) ? 25 : (int)$_REQUEST['limit'], 5000)
196         );
197         
198         $queryObj = clone($x);
199         //DB_DataObject::debuglevel(1);
200         $res = $x->find();
201         if ($res === false) {
202             //echo '<PRE>';print_R($x);exit;
203             $this->jerr($x->_lastError->toString());
204         }
205         
206         $ret = array();
207         
208         if (!empty($_REQUEST['query']['add_blank'])) {
209             $ret[] = array( 'id' => 0, 'name' => '----');
210             $total+=1;
211         }
212         // MOVE ME...
213         
214         //if (($tab == 'Groups') && ($_REQUEST['type'] != 0))  { // then it's a list of teams..
215         if ($tab == 'Groups') {
216             
217             $ret[] = array( 'id' => 0, 'name' => 'EVERYONE');
218             $ret[] = array( 'id' => -1, 'name' => 'NOT_IN_GROUP');
219             //$ret[] = array( 'id' => 999999, 'name' => 'ADMINISTRATORS');
220             $total+=2;
221         }
222         
223         // DOWNLOAD...
224         
225           
226         $rooar = method_exists($x, 'toRooArray');
227         
228         while ($x->fetch()) {
229             //print_R($x);exit;
230             $add = $rooar  ? $x->toRooArray($_REQUEST) : $x->toArray();
231             
232             $ret[] =  !$_columns ? $add : array_intersect_key($add, array_flip($_columns));
233         }
234         $extra = false;
235         if (method_exists($queryObj ,'postListExtra')) {
236             $extra = $queryObj->postListExtra($_REQUEST);
237         }
238         // filter results, and add any data that is needed...
239         if (method_exists($x,'postListFilter')) {
240             $ret = $x->postListFilter($ret, $this->authUser, $_REQUEST);
241         }
242         
243         if (!empty($_REQUEST['csvCols']) && !empty($_REQUEST['csvTitles']) ) {
244             header('Content-type: text/csv');
245             
246             header('Content-Disposition: attachment; filename="list-export-'.date('Y-m-d') . '.csv"');
247             //header('Content-type: text/plain');
248             $fh = fopen('php://output', 'w');
249             fputcsv($fh, $_REQUEST['csvTitles']);
250             
251             
252             foreach($ret as $x) {
253                 //echo "<PRE>"; print_r(array($_REQUEST['csvCols'], $x->toArray())); exit;
254                 $line = array();
255                 foreach($_REQUEST['csvCols'] as $k) {
256                     $line[] = isset($x[$k]) ? $x[$k] : '';
257                 }
258                 fputcsv($fh, $line);
259             }
260             fclose($fh);
261             exit;
262             
263         
264         }
265         //die("DONE?");
266       
267         //if ($x->tableName() == 'Documents_Tracking') {
268         //    $ret = $this->replaceSubject(&$ret, 'doc_id_subject');
269        // }
270         
271         
272         
273         if (!empty($_REQUEST['_requestMeta']) &&  count($ret)) {
274             $meta = $this->meta($x, $ret);
275             if ($meta) {
276                 $extra['metaData'] = $meta;
277             }
278         }
279         
280        // echo "<PRE>"; print_r($ret);
281         $this->jdata($ret,$total, $extra );
282
283     
284     }
285     /**
286      * applySort
287      * 
288      * apply REQUEST[sort] and [dir]
289      * sort may be an array of columsn..
290      * 
291      * @arg   DB_DataObject $x
292      * 
293      */
294     function applySort($x, $sort = '', $dir ='')
295     {
296         
297         // Db_DataObject::debugLevel(1);
298         $sort = empty($_REQUEST['sort']) ? $sort : $_REQUEST['sort'];
299         $dir = empty($_REQUEST['dir']) ? $dir : $_REQUEST['dir'];
300         $dir = $dir == 'ASC' ? 'ASC' : 'DESC';
301          
302         $ms = empty($_REQUEST['_multisort']) ? false : $_REQUEST['_multisort'];
303         $sorted = false;
304         if (method_exists($x, 'applySort')) {
305             $sorted = $x->applySort(
306                     $this->authUser,
307                     $sort,
308                     $dir,
309                     array_keys($this->cols),
310                     $ms ? json_decode($ms) : false
311             );
312         }
313         if ($ms) {
314             return $this->multiSort($x);
315         }
316         
317         if ($sorted === false) {
318             
319             $cols = $x->table();
320             $sort_ar = explode(',', $sort);
321             $sort_str = array();
322           
323             foreach($sort_ar as $sort) {
324                 
325                 if (strlen($sort) && isset($cols[$sort]) ) {
326                     $sort_str[] =  $x->tableName() .'.'.$sort . ' ' . $dir ;
327                     
328                 } else if (in_array($sort, array_keys($this->cols))) {
329                     $sort_str[] = $sort . ' ' . $dir ;
330                 }
331             }
332              
333             if ($sort_str) {
334                 $x->orderBy(implode(', ', $sort_str ));
335             }
336         }
337     }
338     
339     function multiSort($x)
340     {
341         //DB_DataObject::debugLevel(1);
342         $ms = json_decode($_REQUEST['_multisort']);
343         
344         $sort_str = array();
345         
346         $cols = $x->table();
347         foreach($ms->order  as $col) {
348             if (!isset($ms->sort->{$col})) {
349                 continue; // no direction..
350             }
351             $ms->sort->{$col} = $ms->sort->{$col}  == 'ASC' ? 'ASC' : 'DESC';
352             
353             if (strlen($col) && isset($cols[$col]) ) {
354                 $sort_str[] =  $x->tableName() .'.'.$col . ' ' .  $ms->sort->{$col};
355                 
356             } else if (in_array($col, array_keys($this->cols))) {
357                 $sort_str[] = $col. ' ' . $ms->sort->{$col};
358             }
359         }
360          
361         if ($sort_str) {
362             $x->orderBy(implode(', ', $sort_str ));
363         }
364          
365         
366         
367     }
368     
369     
370     
371      /**
372      * POST method   Roo/TABLENAME.php 
373      * -- updates the data..
374      * 
375      * other opts:
376      * _debug - forces debugging on.
377      * _get - forces a get request
378      * _ids - multiple update of records.
379      * {colid} - forces fetching
380      * 
381      */
382     function post($tab) // update / insert (?? dleete??)
383     {
384         //DB_DataObject::debugLevel(1);
385         if (!empty($_REQUEST['_debug'])) {
386             DB_DataObject::debugLevel(1);
387         }
388         
389         if (!empty($_REQUEST['_get'])) {
390             return $this->get($tab);
391         }
392       
393         $_columns = !empty($_REQUEST['_columns']) ? explode(',', $_REQUEST['_columns']) : false;
394         
395         $tab = str_replace('/', '',$tab); // basic protection??
396         $x = DB_DataObject::factory($tab);
397         if (!is_a($x, 'DB_DataObject')) {
398             $this->jerr('invalid url');
399         }
400         // find the key and use that to get the thing..
401         $keys = $x->keys();
402         if (empty($keys) ) {
403             $this->jerr('no key');
404         }
405         
406         $this->key = $keys[0];
407         
408           // delete should be here...
409         if (isset($_REQUEST['_delete'])) {
410             // do we really delete stuff!?!?!?
411             return $this->delete($x,$_REQUEST);
412         } 
413          
414         
415         $old = false;
416         
417         // not sure if this is a good idea here...
418         
419         if (!empty($_REQUEST['_ids'])) {
420             $ids = explode(',',$_REQUEST['_ids']);
421             $x->whereAddIn($this->key, $ids, 'int');
422             $ar = $x->fetchAll();
423             foreach($ar as $x) {
424                 $this->update($x, $_REQUEST);
425                 
426             }
427             // all done..
428             $this->jok("UPDATED");
429             
430             
431         }
432          
433         if (!empty($_REQUEST[$this->key])) {
434             // it's a create..
435             if (!$x->get($this->key, $_REQUEST[$this->key]))  {
436                 $this->jerr("Invalid request");
437             }
438             $this->jok($this->update($x, $_REQUEST));
439         } else {
440             
441             if (empty($_POST)) {
442                 $this->jerr("No data recieved for inserting");
443             }
444             
445             $this->jok($this->insert($x, $_REQUEST));
446             
447         }
448         
449         
450         
451     }
452     function insert($x, $req)
453     {
454         
455     
456         if (method_exists($x, 'checkPerm') && !$x->checkPerm('A', $this->authUser, $req))  {
457             $this->jerr("PERMISSION DENIED");
458         }
459         
460         $_columns = !empty($req['_columns']) ? explode(',', $req['_columns']) : false;
461    
462         if (method_exists($x, 'setFromRoo')) {
463             $res = $x->setFromRoo($req, $this);
464             if (is_string($res)) {
465                 $this->jerr($res);
466             }
467         } else {
468             $x->setFrom($req);
469         }
470         
471          
472         $cols = $x->table();
473      
474         if (isset($cols['created'])) {
475             $x->created = date('Y-m-d H:i:s');
476         }
477         if (isset($cols['created_dt'])) {
478             $x->created_dt = date('Y-m-d H:i:s');
479         }
480         if (isset($cols['created_by'])) {
481             $x->created_by = $this->authUser->id;
482         }
483         
484      
485          if (isset($cols['modified'])) {
486             $x->modified = date('Y-m-d H:i:s');
487         }
488         if (isset($cols['modified_dt'])) {
489             $x->modified_dt = date('Y-m-d H:i:s');
490         }
491         if (isset($cols['modified_by'])) {
492             $x->modified_by = $this->authUser->id;
493         }
494         
495         if (isset($cols['updated'])) {
496             $x->updated = date('Y-m-d H:i:s');
497         }
498         if (isset($cols['updated_dt'])) {
499             $x->updated_dt = date('Y-m-d H:i:s');
500         }
501         if (isset($cols['updated_by'])) {
502             $x->updated_by = $this->authUser->id;
503         }
504         
505      
506         
507         
508         
509         $x->insert();
510         if (method_exists($x, 'onInsert')) {
511             $x->onInsert($_REQUEST, $this);
512         }
513         $ev = $this->addEvent("ADD", $x);
514         if ($ev) { 
515             $ev->audit($x);
516         }
517         
518         // note setFrom might handle this before hand...!??!
519         if (!empty($_FILES) && method_exists($x, 'onUpload')) {
520             $x->onUpload($this);
521         }
522         
523         $r = DB_DataObject::factory($x->tableName());
524         // let's assume it has a key!!!
525         
526         $r->{$this->key} = $x->{$this->key};
527         $this->loadMap($r, $_columns);
528         $r->limit(1);
529         $r->find(true);
530         
531         $rooar = method_exists($r, 'toRooArray');
532         //print_r(var_dump($rooar)); exit;
533         return $rooar  ? $r->toRooArray($_REQUEST) : $r->toArray();
534     }
535     
536     
537     function update($x, $req)
538     {
539         if (method_exists($x, 'checkPerm') && !$x->checkPerm('E', $this->authUser, $_REQUEST))  {
540             $this->jerr("PERMISSION DENIED");
541         }
542        
543         // check any locks..
544         // only done if we recieve a lock_id.
545         // we are very trusing here.. that someone has not messed around with locks..
546         // the object might want to check in their checkPerm - if locking is essential..
547         $lock_warning =  false;
548         $lock = DB_DataObjecT::factory('Core_locking');
549         if (is_a($lock,'DB_DataObject'))  {
550                  
551             $lock->on_id = $x->{$this->key};
552             $lock->on_table= $x->tableName();
553             if (!empty($_REQUEST['_lock_id'])) {
554                 $lock->whereAdd('id != ' . ((int)$_REQUEST['_lock_id']));
555             } else {
556                $lock->whereAdd('person_id !=' . $this->authUser->id);
557             }
558             
559             $lock->limit(1);
560             if ($lock->find(true)) {
561                 // it's locked by someone else..
562                $p = $lock->person();
563                $lock_warning =  "Record was locked by " . $p->name . " at " .$lock->created.
564                            " - Your changes have been saved - you may like to warn them if " .
565                            " they are editing now";
566             }
567             // check the users lock.. - no point.. ??? - if there are no other locks and it's not the users, then they can 
568             // edit it anyways...
569             
570         }
571         
572          
573         
574         
575         
576        
577         $_columns = !empty($req['_columns']) ? explode(',', $req['_columns']) : false;
578
579        
580         $old = clone($x);
581         $this->old = $x;
582         // this lot is generic.. needs moving 
583         if (method_exists($x, 'setFromRoo')) {
584             $res = $x->setFromRoo($req, $this);
585             if (is_string($res)) {
586                 $this->jerr($res);
587             }
588         } else {
589             $x->setFrom($req);
590         }
591         $ev = $this->addEvent("EDIT", $x);
592         $ev->audit($x, $old);
593         //print_r($x);
594         //print_r($old);
595         
596         $cols = $x->table();
597         
598         if (isset($cols['modified'])) {
599             $x->modified = date('Y-m-d H:i:s');
600         }
601         if (isset($cols['modified_dt'])) {
602             $x->modified_dt = date('Y-m-d H:i:s');
603         }
604         if (isset($cols['modified_by'])) {
605             $x->modified_by = $this->authUser->id;
606         }
607         
608         if (isset($cols['updated'])) {
609             $x->updated = date('Y-m-d H:i:s');
610         }
611         if (isset($cols['updated_dt'])) {
612             $x->updated_dt = date('Y-m-d H:i:s');
613         }
614         if (isset($cols['updated_by'])) {
615             $x->updated_by = $this->authUser->id;
616         }
617         
618         //DB_DataObject::DebugLevel(1);
619         $res = $x->update($old);
620         if ($res === false) {
621             $this->jerr($x->_lastError->toString());
622         }
623         
624         if (method_exists($x, 'onUpdate')) {
625             $x->onUpdate($old, $req, $this);
626         }
627         
628         
629         if ($lock_warning) {
630             $this->jerr($lock_warning);
631         }
632         
633         
634         $r = DB_DataObject::factory($x->tableName());
635         // let's assume it has a key!!!
636         $r->{$this->key}= $x->{$this->key};
637         $this->loadMap($r, $_columns);
638         $r->limit(1);
639         $r->find(true);
640         $rooar = method_exists($r, 'toRooArray');
641         //print_r(var_dump($rooar)); exit;
642         return $rooar  ? $r->toRooArray($_REQUEST) : $r->toArray();
643     }
644     /**
645      * Delete a number of records.
646      * calls $delete_obj->beforeDelete($array_of_dependant_dataobjects)
647      *
648      */
649     
650     function delete($x, $req)
651     {
652         // do we really delete stuff!?!?!?
653         if (empty($req['_delete'])) {
654             $this->jerr("Delete Requested with no value");
655         }
656         // build a list of tables to queriy for dependant data..
657         $map = $x->links();
658         
659         $affects  = array();
660         
661         $all_links = $GLOBALS['_DB_DATAOBJECT']['LINKS'][$x->_database];
662         foreach($all_links as $tbl => $links) {
663             foreach($links as $col => $totbl_col) {
664                 $to = explode(':', $totbl_col);
665                 if ($to[0] != $x->tableName()) {
666                     continue;
667                 }
668                 
669                 $affects[$tbl .'.' . $col] = true;
670             }
671         }
672         // collect tables
673         
674        // echo '<PRE>';print_r($affects);exit;
675        //DB_Dataobject::debugLevel(1);
676        
677         
678         $clean = create_function('$v', 'return (int)$v;');
679         
680         $bits = array_map($clean, explode(',', $req['_delete']));
681         
682        // print_r($bits);exit;
683          
684         // let's assume it has a key!!!
685         
686         
687         $x->whereAdd($this->key .'  IN ('. implode(',', $bits) .')');
688         if (!$x->find()) {
689             $this->jerr("Nothing found to delete");
690         }
691         $errs = array();
692         while ($x->fetch()) {
693             $xx = clone($x);
694             
695            
696             // perms first.
697             
698             if (method_exists($x, 'checkPerm') && !$x->checkPerm('D', $this->authUser))  {
699                 $this->jerr("PERMISSION DENIED");
700             }
701             
702             $match_ar = array();
703             foreach($affects as $k=> $true) {
704                 $ka = explode('.', $k);
705                 $chk = DB_DataObject::factory($ka[0]);
706                 if (!is_a($chk,'DB_DataObject')) {
707                     $this->jerr('Unable to load referenced table, check the links config: ' .$ka[0]);
708                 }
709                 $chk->{$ka[1]} =  $xx->{$this->key};
710                 $matches = $chk->count();
711                 
712                 if ($matches) {
713                     $match_ar[] = clone($chk);
714                     continue;
715                 }          
716             }
717             
718             $has_beforeDelete = method_exists($xx, 'beforeDelete');
719             // before delte = allows us to trash dependancies if needed..
720             $match_total = 0;
721             
722             if ( method_exists($xx, 'beforeDelete') ) {
723                 if ($xx->beforeDelete($match_ar) === false) {
724                     $errs[] = "Delete failed ({$xx->id})\n".
725                         (isset($xx->err) ? $xx->err : '');
726                     continue;
727                 }
728                 // refetch affects..
729                 
730                 $match_ar = array();
731                 foreach($affects as $k=> $true) {
732                     $ka = explode('.', $k);
733                     $chk = DB_DataObject::factory($ka[0]);
734                     if (!is_a($chk,'DB_DataObject')) {
735                         $this->jerr('Unable to load referenced table, check the links config: ' .$ka[0]);
736                     }
737                     $chk->{$ka[1]} =  $xx->$pk;
738                     $matches = $chk->count();
739                     $match_total += $matches;
740                     if ($matches) {
741                         $match_ar[] = clone($chk);
742                         continue;
743                     }          
744                 }
745                 
746             }
747             
748             //
749             
750             
751             if (!empty($match_ar)) {
752                 $chk = $match_ar[0];
753                 $chk->limit(1);
754                 $o = $chk->fetchAll();
755                 $key = $this->key;
756                 $desc =  $chk->tableName(). '.' . $key .'='.$xx->$key ;
757                 if (method_exists($chk, 'toEventString')) {
758                     $desc .=  ' : ' . $o[0]->toEventString();
759                 }
760                     
761                 $this->jerr("Delete Dependant records ($match_total  found),  " .
762                              "first is ( $desc )");
763           
764             }
765             
766             // now che 
767             // finally log it.. 
768             
769             $this->addEvent("DELETE", $x);
770             
771             $xx->delete();
772         }
773         if ($errs) {
774             $this->jerr(implode("\n<BR>", $errs));
775         }
776         $this->jok("Deleted");
777         
778     }
779    
780     
781     
782     
783     var $cols = array();
784     function loadMap($do, $filter=false, $distinct = false) 
785     {
786         //DB_DataObject::debugLevel(1);
787         
788         $this->countWhat = false;
789         
790         $conf = array();
791         
792         $this->init();
793         
794         $mods = explode(',',$this->appModules);
795         
796         $ff = HTML_FlexyFramework::get();
797        
798          $map = $do->links();
799          
800         
801         
802         // current table..
803         $tabdef = $do->table();
804         if (isset($tabdef['passwd'])) {
805             // prevent exposure of passwords..
806             unset($tabdef['passwd']);     
807         }
808         $xx = clone($do);
809         $xx = array_keys($tabdef);
810         $do->selectAdd(); // we need thsi as normally it's only cleared by an empty selectAs call.
811         
812         $selectAs = array(array(  $xx , '%s', false));
813        
814         $has_distinct = false;
815         if ($filter || $distinct) {
816             $cols = array();
817             //echo '<PRE>' ;print_r($filter);exit;
818             foreach($xx as $c) {
819                 if ($distinct && $distinct == $c) {
820                     $has_distinct = 'DISTINCT( ' . $do->tableName() .'.'. $c .') as ' . $c;
821                     $this->countWhat =  'DISTINCT  ' . $do->tableName() .'.'. $c .'';
822                     continue;
823                 }
824                 if (!$filter || in_array($c, $filter)) {
825                     $cols[] = $c;
826                 }
827             }
828             
829             
830             $selectAs = empty($cols) ?  array() : array(array(  $cols , '%s', false)) ;
831             
832             
833             
834         } 
835         
836         $this->cols = array();
837         $this->colsJoinName =array();
838         foreach($xx as $k) {
839             $this->cols[$k] = $do->tableName(). '.' . $k;
840         }
841         
842         
843         
844         
845          
846         
847         foreach($map as $ocl=>$info) {
848             
849             list($tab,$col) = explode(':', $info);
850             // what about multiple joins on the same table!!!
851             $xx = DB_DataObject::factory($tab);
852             if (!is_a($xx, 'DB_DataObject')) {
853                 continue;
854             }
855             // this is borked ... for multiple jions..
856             $do->joinAdd($xx, 'LEFT', 'join_'.$ocl.'_'. $col, $ocl);
857             $tabdef = $xx->table();
858             $table = $xx->tableName();
859             if (isset($tabdef['passwd'])) {
860              
861                 unset($tabdef['passwd']);
862               
863             } 
864             $xx = array_keys($tabdef);
865             
866             
867             if ($filter || $distinct) {
868                 $cols = array();
869                 foreach($xx as $c) {
870                     $tn = sprintf($ocl.'_%s', $c);
871                   // echo '<PRE>'; var_dump($tn);
872                     if ($distinct && $tn == $distinct) {
873                         $has_distinct = 'DISTINCT( ' . 'join_'.$ocl.'_'.$col.'.'.$k .')  as ' . $tn ;
874                         $this->countWhat =  'DISTINCT  join_'.$ocl.'_'.$col.'.'.$k;
875                         continue;
876                     }
877                     
878                     
879                     if (!$filter || in_array($tn, $filter)) {
880                         $cols[] = $c;
881                     }
882                 }
883                 if (!empty($cols)) {
884                      $selectAs[] = array($cols, $ocl.'_%s', 'join_'.$ocl.'_'. $col);
885                 }
886                
887                 
888             } else {
889                 $selectAs[] = array($xx, $ocl.'_%s', 'join_'.$ocl.'_'. $col);
890                 
891             }
892              
893             
894             foreach($xx as $k) {
895                 $this->cols[sprintf($ocl.'_%s', $k)] = $tab.'.'.$k;
896                 $this->colsJname[sprintf($ocl.'_%s', $k)] = 'join_'.$ocl.'_'.$col.'.'.$k;
897             }
898             
899             
900         }
901         
902         if ($has_distinct) {
903             $do->selectAdd($has_distinct);
904         }
905          
906         // we do select as after everything else as we need to plop distinct at the beginning??
907         /// well I assume..
908        // echo '<PRE>';print_r($this->colsJname);exit;
909         foreach($selectAs as $ar) {
910             $do->selectAs($ar[0], $ar[1], $ar[2]);
911         }
912         
913         
914     }
915     /**
916      * generate the meta data neede by queries.
917      * 
918      */
919     function meta($x, $data)
920     {
921         // this is not going to work on queries where the data does not match the database def..
922         // for unknown columns we send them as stirngs..
923         $lost = 0;
924         $cols  = array_keys($data[0]);
925      
926         
927         
928         
929         //echo '<PRE>';print_r($this->cols); exit;
930         $options = &PEAR::getStaticProperty('DB_DataObject','options');
931         $reader = $options["ini_{$x->_database}"] .'.reader';
932         if (!file_exists( $reader )) {
933             return;
934         }
935         
936         $rdata = unserialize(file_get_contents($reader));
937         
938        // echo '<PRE>';print_r($rdata);exit;
939         
940         $meta = array();
941         foreach($cols as $c ) {
942             if (!isset($this->cols[$c]) || !isset($rdata[$this->cols[$c]]) || !is_array($rdata[$this->cols[$c]])) {
943                 $meta[] = $c;
944                 continue;    
945             }
946             $add = $rdata[$this->cols[$c]];
947             $add['name'] = $c;
948             $meta[] = $add;
949         }
950         return array(
951             'totalProperty' =>  'total',
952             'successProperty' => 'success',
953             'root' => 'data',
954             'id' => 'id',
955             'fields' => $meta
956         );
957          
958         
959     }
960     
961     function setFilters($x, $q)
962     {
963         // if a column is type int, and we get ',' -> the it should be come an inc clause..
964        // DB_DataObject::debugLevel(1);
965         if (method_exists($x, 'applyFilters')) {
966            // DB_DataObject::debugLevel(1);
967             $x->applyFilters($q, $this->authUser);
968         }
969         $q_filtered = array();
970         
971         foreach($q as $key=>$val) {
972             
973             // value is an array..
974             if (is_array($val) ) {
975                 
976                 $pref = '';
977                 
978                 if ($key[0] == '!') {
979                     $pref = '!';
980                     $key = substr($key,1);
981                 }
982                 
983                 if (!in_array( $key,  array_keys($this->cols))) {
984                     continue;
985                 }
986                 
987                 // support a[0] a[1] ..... => whereAddIn(
988                 $ar = array();
989                 $quote = false;
990                 foreach($val as $k=>$v) {
991                     if (!is_numeric($k)) {
992                         $ar = array();
993                         break;
994                     }
995                     // FIXME: note this is not typesafe for anything other than mysql..
996                     
997                     if (!is_numeric($v) || !is_long($v)) {
998                         $quote = true;
999                     }
1000                     $ar[] = $v;
1001                     
1002                 }
1003                 if (count($ar)) {
1004                     
1005                     
1006                     $x->whereAddIn($pref . (
1007                         isset($this->colsJname[$key]) ? 
1008                             $this->colsJname[$key] :
1009                             ($x->tableName(). '.'.$key)),
1010                         $ar, $quote ? 'string' : 'int');
1011                 }
1012                 
1013                 continue;
1014             }
1015             
1016             
1017             
1018             if ($key[0] == '!' && in_array(substr($key, 1), array_keys($this->cols))) {
1019                 
1020                 $key  = substr($key, 1) ;
1021                 
1022                 $x->whereAdd(   (
1023                         isset($this->colsJname[$key]) ? 
1024                             $this->colsJname[$key] :
1025                             $x->tableName(). '.'.$key ) . ' != ' .
1026                     (is_numeric($val) ? $val : "'".  $x->escape($val) . "'")
1027                 );
1028                 continue;
1029                 
1030             }
1031             
1032             
1033             
1034             switch($key) {
1035                     
1036                 // Events and remarks -- fixme - move to events/remarsk...
1037                 case 'on_id':  // where TF is this used...
1038                     if (!empty($q['query']['original'])) {
1039                       //  DB_DataObject::debugLevel(1);
1040                         $o = (int) $q['query']['original'];
1041                         $oid = (int) $val;
1042                         $x->whereAdd("(on_id = $oid  OR 
1043                                 on_id IN ( SELECT distinct(id) FROM Documents WHERE original = $o ) 
1044                             )");
1045                         continue;
1046                                 
1047                     }
1048                     $x->on_id = $val;
1049                 
1050                 
1051                 default:
1052                     if (strlen($val)) {
1053                         $q_filtered[$key] = $val;
1054                     }
1055                     
1056                     // subjoined columns = check the values.
1057                     // note this is not typesafe for anything other than mysql..
1058                     
1059                     if (isset($this->colsJname[$key])) {
1060                         $quote = false;
1061                         if (!is_numeric($val) || !is_long($val)) {
1062                             $quote = true;
1063                         }
1064                         $x->whereAdd( "{$this->colsJname[$key]} = " . ($quote ? "'". $x->escape($val) ."'" : $val));
1065                         
1066                     }
1067                     
1068                     
1069                     continue;
1070             }
1071         }
1072         
1073         $x->setFrom($q_filtered);
1074         
1075         
1076         
1077        
1078         // nice generic -- let's get rid of it.. where is it used!!!!
1079         // used by: 
1080         // Person / Group / most of my queries noww...
1081         if (!empty($q['query']['name'])) {
1082             $x->whereAdd($x->tableName().".name LIKE '". $x->escape($q['query']['name']) . "%'");
1083         }
1084         
1085         // - projectdirectory staff list - persn queuy
1086       
1087          
1088        
1089          
1090           
1091         
1092         
1093     }
1094     
1095 }