Merge branch 'pu/2013.03/modelconfig-hr'
[tine20] / tine20 / Tinebase / Convert / Json.php
1 <?php
2 /**
3  * convert functions for records from/to json (array) format
4  * 
5  * @package     Tinebase
6  * @subpackage  Convert
7  * @license     http://www.gnu.org/licenses/agpl.html AGPL Version 3
8  * @author      Philipp Schüle <p.schuele@metaways.de>
9  * @copyright   Copyright (c) 2011-2013 Metaways Infosystems GmbH (http://www.metaways.de)
10  */
11
12 /**
13  * convert functions for records from/to json (array) format
14  *
15  * @package     Tinebase
16  * @subpackage  Convert
17  */
18 class Tinebase_Convert_Json implements Tinebase_Convert_Interface
19 {
20     /**
21      * converts external format to Tinebase_Record_Abstract
22      * 
23      * @param  mixed                     $_blob   the input data to parse
24      * @param  Tinebase_Record_Abstract  $_record  update existing record
25      * @return Tinebase_Record_Abstract
26      */
27     public function toTine20Model($_blob, Tinebase_Record_Abstract $_record = NULL)
28     {
29         throw new Tinebase_Exception_NotImplemented('From json to record is not implemented yet');
30     }
31     
32     /**
33      * converts Tinebase_Record_Abstract to external format
34      * 
35      * @param  Tinebase_Record_Abstract $_record
36      * @return mixed
37      */
38     public function fromTine20Model(Tinebase_Record_Abstract $_record)
39     {
40         if (! $_record) {
41             return array();
42         }
43         
44         // for resolving we'll use recordset
45         $records = new Tinebase_Record_RecordSet(get_class($_record), array($_record));
46         
47         Tinebase_Frontend_Json_Abstract::resolveContainerTagsUsers($records);
48         
49         // use modern record resolving, if the model was configured using Tinebase_ModelConfiguration
50         // at first, resolve all single record fields
51         $this->_resolveSingleRecordFields($records);
52         // next step, resolve all multiple records fields
53         $this->_resolveMultipleRecordFields($records);
54         
55         // resolve the traditional way, if model hasn't been configured with Tinebase_ModelConfiguration
56         self::resolveMultipleIdFields($records);
57         
58         $_record = $records->getFirstRecord();
59         $_record->setTimezone(Tinebase_Core::get(Tinebase_Core::USERTIMEZONE));
60         $_record->bypassFilters = true;
61         
62         return $_record->toArray();
63     }
64
65     /**
66      * resolves single record fields (Tinebase_ModelConfiguration._recordsFields)
67      * 
68      * @param Tinebase_Record_RecordSet $_records the records
69      */
70     protected function _resolveSingleRecordFields(Tinebase_Record_RecordSet $_records)
71     {
72         $ownRecordClass = $_records->getRecordClassName();
73         
74         if (! $cfg = $ownRecordClass::getConfiguration()) {
75             return;
76         }
77         $resolveFields = $cfg->recordFields;
78         if ($resolveFields && is_array($resolveFields)) {
79             // don't search twice if the same recordClass gets resolved on multiple fields
80             foreach ($resolveFields as $fieldKey => $fieldConfig) {
81                 $resolveRecords[$fieldConfig['config']['recordClassName']][] = $fieldKey;
82             }
83             
84             foreach ($resolveRecords as $foreignRecordClassName => $fields) {
85                 $foreignIds = array();
86                 $fields = (array) $fields;
87                 
88                 foreach($fields as $field) {
89                     $foreignIds = array_unique(array_merge($foreignIds, $_records->{$field}));
90                 }
91                 
92                 if (! Tinebase_Core::getUser()->hasRight(substr($foreignRecordClassName, 0, strpos($foreignRecordClassName, "_")), Tinebase_Acl_Rights_Abstract::RUN)) {
93                     continue;
94                 }
95                 
96                 $cfg = $resolveFields[$fields[0]];
97                 
98                 if ($cfg['type'] == 'user') {
99                     $foreignRecords = Tinebase_User::getInstance()->getUsers();
100                 } elseif ($cfg['type'] == 'container') {
101                     $foreignRecords = new Tinebase_Record_RecordSet('Tinebase_Model_Container');
102                     $foreignRecords->addRecord(Tinebase_Container::getInstance()->get($_id));
103                 // TODO: resolve recursive records of records better in controller
104                 // TODO: resolve containers
105                 } else {
106                     $controller = array_key_exists('controllerClassName', $cfg['config']) ? $cfg['config']['controllerClassName']::getInstance() : Tinebase_Core::getApplicationInstance($foreignRecordClassName);
107                     $foreignRecords = $controller->getMultiple($foreignIds);
108                 }
109                 
110                 $foreignRecords->setTimezone(Tinebase_Core::get(Tinebase_Core::USERTIMEZONE));
111                 $foreignRecords->convertDates = true;
112                 Tinebase_Frontend_Json_Abstract::resolveContainerTagsUsers($foreignRecords);
113                 $fr = $foreignRecords->getFirstRecord();
114                 if ($fr && $fr->has('notes')) {
115                     Tinebase_Notes::getInstance()->getMultipleNotesOfRecords($foreignRecords);
116                 }
117                 
118                 if ($foreignRecords->count()) {
119                     foreach ($_records as $record) {
120                         foreach ($fields as $field) {
121                             $idx = $foreignRecords->getIndexById($record->{$field});
122                             if (isset($idx) && $idx !== FALSE) {
123                                 $record->{$field} = $foreignRecords[$idx];
124                             }
125                         }
126                     }
127                 }
128             }
129         }
130     }
131     
132     /**
133      * resolves multiple records (fallback)
134      * 
135      * @deprecated use Tinebase_ModelConfiguration to configure your models, so this won't be used anymore 
136      * @param Tinebase_Record_RecordSet $_records the records
137      * @param array $resolveFields
138      */
139     public static function resolveMultipleIdFields($records, $resolveFields = NULL)
140     {
141         if (! $records instanceof Tinebase_Record_RecordSet) {
142             return;
143         }
144         
145         $ownRecordClass = $records->getRecordClassName();
146         if ($resolveFields === NULL) {
147             $resolveFields = $ownRecordClass::getResolveForeignIdFields();
148         }
149         
150         if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ 
151             . ' Resolving ' . $ownRecordClass . ' fields: ' . print_r($resolveFields, TRUE));
152         
153         foreach ((array) $resolveFields as $foreignRecordClassName => $fields) {
154             if ($foreignRecordClassName === 'recursive') {
155                 foreach ($fields as $field => $model) {
156                     foreach ($records->$field as $subRecords) {
157                         self::resolveMultipleIdFields($subRecords);
158                     }
159                 }
160             } else {
161                 self::_resolveForeignIdFields($records, $foreignRecordClassName, (array) $fields);
162             }
163         }
164     }
165     
166     /**
167      * resolve foreign fields for records
168      * 
169      * @param Tinebase_Record_RecordSet $records
170      * @param string $foreignRecordClassName
171      * @param array $fields
172      */
173     protected static function _resolveForeignIdFields($records, $foreignRecordClassName, $fields)
174     {
175         $options = array_key_exists('options', $fields) ? $fields['options'] : array();
176         $fields = array_key_exists('fields', $fields) ? $fields['fields'] : $fields;
177         
178         $foreignIds = array();
179         foreach ($fields as $field) {
180             $foreignIds = array_unique(array_merge($foreignIds, $records->{$field}));
181         }
182         
183         if (! Tinebase_Core::getUser()->hasRight(substr($foreignRecordClassName, 0, strpos($foreignRecordClassName, "_")), Tinebase_Acl_Rights_Abstract::RUN)) {
184             if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ 
185                 . ' Not resolving ' . $foreignRecordClassName . ' records because user has no right to run app.');
186             return;
187         }
188         
189         try {
190             $controller = Tinebase_Core::getApplicationInstance($foreignRecordClassName);
191         } catch (Tinebase_Exception_AccessDenied $tead) {
192             return;
193         }
194         
195         if (method_exists($controller, 'modlogActive')) {
196             $modlogActive = $controller->modlogActive(FALSE);
197         }
198         
199         if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ 
200             . ' Fetching ' . $foreignRecordClassName . ' by id: ' . print_r($foreignIds, TRUE));
201         
202         if (array_key_exists('ignoreAcl', $options) && $options['ignoreAcl']) {
203             // @todo make sure that second param of getMultiple() is $ignoreAcl
204             $foreignRecords = $controller->getMultiple($foreignIds, TRUE);
205         } else {
206             $foreignRecords = $controller->getMultiple($foreignIds);
207         }
208         
209         if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ 
210             . ' Foreign records found: ' . print_r($foreignRecords->toArray(), TRUE));
211         
212         if (count($foreignRecords) === 0) {
213             return;
214         }
215         
216         foreach ($records as $record) {
217             foreach ($fields as $field) {
218                 if (is_scalar($record->{$field})) {
219                     $idx = $foreignRecords->getIndexById($record->{$field});
220                     if (isset($idx) && $idx !== FALSE) {
221                         $record->{$field} = $foreignRecords[$idx];
222                     } else {
223                         switch ($foreignRecordClassName) {
224                             case 'Tinebase_Model_User':
225                             case 'Tinebase_Model_FullUser':
226                                 $record->{$field} = Tinebase_User::getInstance()->getNonExistentUser();
227                                 break;
228                             default:
229                                 // skip
230                         }
231                     }
232                 }
233             }
234         }
235     }
236     
237     /**
238      * resolve multiple record fields (Tinebase_ModelConfiguration._recordsFields)
239      * 
240      * @param Tinebase_Record_RecordSet $_records
241      */
242     protected function _resolveMultipleRecordFields(Tinebase_Record_RecordSet $_records)
243     {
244         // show if there is something to resolve
245         $ownRecordClass = $_records->getRecordClassName();
246         
247         if (! $_records->count()) {
248             return;
249         }
250         
251         if (! (($config = $ownRecordClass::getConfiguration()) && ($resolveFields = $config->recordsFields))) {
252             return;
253         }
254         
255         $ownIds = $_records->{$config->idProperty};
256         
257         // iterate fields to resolve
258         foreach ($resolveFields as $fieldKey => $c) {
259             $config = $c['config'];
260             // fetch the fields by the refIfField
261             $controller = array_key_exists('controllerClassName', $config) ? $config['controllerClassName']::getInstance() : Tinebase_Core::getApplicationInstance($foreignRecordClassName);
262             $filterName = $config['filterClassName'];
263             
264             $filterArray = array();
265             
266             // addFilters can be added and must be added if the same model resides in more than one records fields
267             if (array_key_exists('addFilters', $config) && is_array($config['addFilters'])) {
268                 $useaddFilters = true;
269                 $filterArray = $config['addFilters'];
270             }
271             
272             $filter = new $filterName($filterArray);
273             $filter->addFilter(new Tinebase_Model_Filter_Id(array('field' => $config['refIdField'], 'operator' => 'in', 'value' => $ownIds)));
274             
275             $paging = NULL;
276             if (array_key_exists('paging', $config) && is_array($config['paging'])) {
277                 $paging = new Tinebase_Model_Pagination($config['paging']);
278             }
279             
280             $foreignRecords = $controller->search($filter, $paging);
281             $foreignRecords->setTimezone(Tinebase_Core::get(Tinebase_Core::USERTIMEZONE));
282             $foreignRecords->convertDates = true;
283             Tinebase_Frontend_Json_Abstract::resolveContainerTagsUsers($foreignRecords);
284             $fr = $foreignRecords->getFirstRecord();
285             if ($fr && $fr->has('notes')) {
286                 Tinebase_Notes::getInstance()->getMultipleNotesOfRecords($foreignRecords);
287             }
288             if ($foreignRecords->count() > 0) {
289                 foreach ($_records as $record) {
290                     $filtered = $foreignRecords->filter($config['refIdField'], $record->getId());
291                     $record->{$fieldKey} = $filtered->toArray();
292                 }
293             } else {
294                 $_records->{$fieldKey} = NULL;
295             }
296         }
297         
298     }
299     
300     /**
301      * converts Tinebase_Record_RecordSet to external format
302      * 
303      * @param  Tinebase_Record_RecordSet  $_records
304      * @param Tinebase_Model_Filter_FilterGroup $_filter
305      * @param Tinebase_Model_Pagination $_pagination
306      * 
307      * @return mixed
308      */
309     public function fromTine20RecordSet(Tinebase_Record_RecordSet $_records, $_filter = NULL, $_pagination = NULL)
310     {
311         if (count($_records) == 0) {
312             return array();
313         }
314         
315         Tinebase_Frontend_Json_Abstract::resolveContainerTagsUsers($_records);
316         
317         self::resolveMultipleIdFields($_records);
318         $this->_resolveSingleRecordFields($_records);
319         $this->_resolveMultipleRecordFields($_records);
320         
321         $_records->setTimezone(Tinebase_Core::get(Tinebase_Core::USERTIMEZONE));
322         $_records->convertDates = true;
323
324         $result = $_records->toArray();
325
326         return $result;
327     }
328 }