#5024: allow to attach external files to records
[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         $controller = Tinebase_Core::getApplicationInstance($foreignRecordClassName);
190         
191         if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ 
192             . ' Fetching ' . $foreignRecordClassName . ' by id: ' . print_r($foreignIds, TRUE));
193         
194         if (array_key_exists('ignoreAcl', $options) && $options['ignoreAcl']) {
195             // @todo make sure that second param of getMultiple() is $ignoreAcl
196             $foreignRecords = $controller->getMultiple($foreignIds, TRUE);
197         } else {
198             $foreignRecords = $controller->getMultiple($foreignIds);
199         }
200         
201         if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ 
202             . ' Foreign records found: ' . print_r($foreignRecords->toArray(), TRUE));
203         
204         if (count($foreignRecords) === 0) {
205             return;
206         }
207         
208         foreach ($records as $record) {
209             foreach ($fields as $field) {
210                 if (is_scalar($record->{$field})) {
211                     $idx = $foreignRecords->getIndexById($record->{$field});
212                     if (isset($idx) && $idx !== FALSE) {
213                         $record->{$field} = $foreignRecords[$idx];
214                     } else {
215                         switch ($foreignRecordClassName) {
216                             case 'Tinebase_Model_User':
217                             case 'Tinebase_Model_FullUser':
218                                 $record->{$field} = Tinebase_User::getInstance()->getNonExistentUser();
219                                 break;
220                             default:
221                                 // skip
222                         }
223                     }
224                 }
225             }
226         }
227     }
228     
229     /**
230      * resolve multiple record fields (Tinebase_ModelConfiguration._recordsFields)
231      * 
232      * @param Tinebase_Record_RecordSet $_records
233      */
234     protected function _resolveMultipleRecordFields(Tinebase_Record_RecordSet $_records)
235     {
236         // show if there is something to resolve
237         $ownRecordClass = $_records->getRecordClassName();
238         
239         if (! $_records->count()) {
240             return;
241         }
242         
243         if (! (($config = $ownRecordClass::getConfiguration()) && ($resolveFields = $config->recordsFields))) {
244             return;
245         }
246         
247         $ownIds = $_records->{$config->idProperty};
248         
249         // iterate fields to resolve
250         foreach ($resolveFields as $fieldKey => $c) {
251             $config = $c['config'];
252             // fetch the fields by the refIfField
253             $controller = array_key_exists('controllerClassName', $config) ? $config['controllerClassName']::getInstance() : Tinebase_Core::getApplicationInstance($foreignRecordClassName);
254             $filterName = $config['filterClassName'];
255             
256             $filterArray = array();
257             
258             // addFilters can be added and must be added if the same model resides in more than one records fields
259             if (array_key_exists('addFilters', $config) && is_array($config['addFilters'])) {
260                 $useaddFilters = true;
261                 $filterArray = $config['addFilters'];
262             }
263             
264             $filter = new $filterName($filterArray);
265             $filter->addFilter(new Tinebase_Model_Filter_Id(array('field' => $config['refIdField'], 'operator' => 'in', 'value' => $ownIds)));
266             
267             $paging = NULL;
268             if (array_key_exists('paging', $config) && is_array($config['paging'])) {
269                 $paging = new Tinebase_Model_Pagination($config['paging']);
270             }
271             
272             $foreignRecords = $controller->search($filter, $paging);
273             $foreignRecords->setTimezone(Tinebase_Core::get(Tinebase_Core::USERTIMEZONE));
274             $foreignRecords->convertDates = true;
275             Tinebase_Frontend_Json_Abstract::resolveContainerTagsUsers($foreignRecords);
276             $fr = $foreignRecords->getFirstRecord();
277             if ($fr && $fr->has('notes')) {
278                 Tinebase_Notes::getInstance()->getMultipleNotesOfRecords($foreignRecords);
279             }
280             if ($foreignRecords->count() > 0) {
281                 foreach ($_records as $record) {
282                     $filtered = $foreignRecords->filter($config['refIdField'], $record->getId());
283                     $record->{$fieldKey} = $filtered->toArray();
284                 }
285             } else {
286                 $_records->{$fieldKey} = NULL;
287             }
288         }
289         
290     }
291     
292     /**
293      * converts Tinebase_Record_RecordSet to external format
294      * 
295      * @param  Tinebase_Record_RecordSet  $_records
296      * @param Tinebase_Model_Filter_FilterGroup $_filter
297      * @param Tinebase_Model_Pagination $_pagination
298      * 
299      * @return mixed
300      */
301     public function fromTine20RecordSet(Tinebase_Record_RecordSet $_records, $_filter = NULL, $_pagination = NULL)
302     {
303         if (count($_records) == 0) {
304             return array();
305         }
306         
307         Tinebase_Frontend_Json_Abstract::resolveContainerTagsUsers($_records);
308         
309         self::resolveMultipleIdFields($_records);
310         $this->_resolveSingleRecordFields($_records);
311         $this->_resolveMultipleRecordFields($_records);
312         
313         $_records->setTimezone(Tinebase_Core::get(Tinebase_Core::USERTIMEZONE));
314         $_records->convertDates = true;
315
316         $result = $_records->toArray();
317
318         return $result;
319     }
320 }