forked from tine20/tine20
/
Abstract.php
1453 lines (1273 loc) · 51.7 KB
/
Abstract.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Tinebase Abstract export class
*
* @package Tinebase
* @subpackage Export
* @license http://www.gnu.org/licenses/agpl.html AGPL Version 3
* @author Paul Mehrer <p.mehrer@metaways.de>
* @copyright Copyright (c) 2017-2018 Metaways Infosystems GmbH (http://www.metaways.de)
*
*/
/**
* Tinebase Abstract export class
*
* @package Tinebase
* @subpackage Export
*
*
* @todo remove: Commonly used export translation strings:
* _('Exporttime')
*/
abstract class Tinebase_Export_Abstract implements Tinebase_Record_IteratableInterface
{
const ROW_TYPE_RECORD = 'record';
const ROW_TYPE_GENERIC_HEADER = 'genericHeader';
const ROW_TYPE_GROUP_HEADER = 'groupHeader';
/**
* default export definition name
*
* @var string
*/
protected $_defaultExportname = 'default';
/**
* the record controller
*
* @var Tinebase_Controller_Record_Abstract
*/
protected $_controller = null;
/**
* translation object
*
* @var Zend_Translate
*/
protected $_translate;
/**
* translation object
*
* @var Zend_Translate
*/
protected $_tinebaseTranslate;
/**
* locale object
*
* @var Zend_Locale
*/
protected $_locale;
/**
* export config
*
* @var Zend_Config_Xml
*/
protected $_config = array();
/**
* @var string application name of this export class
*/
protected $_applicationName = null;
/**
* the record model
*
* @var string
*/
protected $_modelName = null;
/**
* filter to generate export for
*
* @var Tinebase_Model_Filter_FilterGroup
*/
protected $_filter = null;
/**
* sort records by this field (array keys: sort / dir / ...)
*
* @var array
* @see Tinebase_Model_Pagination
*/
protected $_sortInfo = array();
/**
* preference key if users can have different export configs
*
* @var string
*/
protected $_prefKey = null;
/**
* format strings
*
* @var string
*/
protected $_format = null;
/**
* custom field names for this model
*
* @var array
*/
protected $_customFieldNames = null;
/**
* user fields to resolve
*
* @var array
*/
protected $_userFields = array('created_by', 'last_modified_by', 'account_id');
/**
* first iteration (helper to write generic headings, etc.)
*
* @var boolean
*/
protected $_firstIteration = true;
/**
* helper to determine if we are done with record processing
*
* @var bool
*/
protected $_iterationDone = false;
/**
* just dump all properties of the records to _writeValue (through _getValue($field, $record) of course)
*
* @var boolean
*/
protected $_dumpRecords = true;
/**
* write a generic header based on the properties of a record created from _modelName
*
* @var boolean
*/
protected $_writeGenericHeader = true;
/**
* class cache for field config from _config->columns->column
*
* @var array
*/
protected $_fieldConfig = array();
/**
* fields with special treatment in addBody
*
* @var array
*/
protected $_specialFields = array();
/**
* if set to true _hasTwig() will return true in any case
*
* @var boolean
*/
protected $_hasTemplate = false;
/** @var Tinebase_Twig */
protected $_twig = null;
/**
* @var Twig_TemplateWrapper|null
*/
protected $_twigTemplate = null;
protected $_twigMapping = array();
protected $_twigExtensions = [];
/**
* @var string
*/
protected $_templateFileName = null;
protected $_resolvedFields = array();
/**
* @var Tinebase_DateTime|null
*/
protected $_exportTimeStamp = null;
/**
* @var null|string
*/
protected $_logoPath = null;
/**
* @var Tinebase_Record_RecordSet|null
*/
protected $_records = null;
protected $_lastGroupValue = null;
protected $_groupByProperty = null;
protected $_groupByProcessor = null;
protected $_currentRowType = null;
/**
* @var Tinebase_Record_Abstract
*/
protected $_currentRecord = null;
protected $_getRelations = false;
protected $_additionalRecords = array();
protected $_keyFields = array();
protected $_virtualFields = array();
protected $_foreignIdFields = array();
protected $_expandCustomFields = array();
protected $_fields = null;
protected $_rawData = false;
/**
* @var Tinebase_ModelConfiguration|null
*/
protected $_modelConfig = null;
protected $_FEDataRecordResolving = false;
/**
* @var array
*/
protected $_customFieldsNameLocalLabelMapping = [];
/**
* the constructor
*
* @param Tinebase_Model_Filter_FilterGroup $_filter
* @param Tinebase_Controller_Record_Interface $_controller (optional)
* @param array $_additionalOptions (optional) additional options
* @throws Tinebase_Exception_AccessDenied
* @throws Tinebase_Exception_InvalidArgument
* @throws Tinebase_Exception_NotFound
*/
public function __construct(
Tinebase_Model_Filter_FilterGroup $_filter,
Tinebase_Controller_Record_Interface $_controller = null,
$_additionalOptions = array()
) {
$this->_filter = $_filter;
if (!$this->_modelName) {
$this->_modelName = $this->_filter->getModelName();
}
if (!$this->_applicationName) {
$this->_applicationName = $this->_filter->getApplicationName();
}
$this->_controller = ($_controller !== null) ? $_controller :
Tinebase_Core::getApplicationInstance($this->_applicationName, $this->_modelName);
$this->_translate = Tinebase_Translation::getTranslation($this->_applicationName);
$this->_tinebaseTranslate = Tinebase_Translation::getTranslation('Tinebase');
$this->_locale = Tinebase_Core::get(Tinebase_Core::LOCALE);
$this->_config = $this->_getExportConfig($_additionalOptions);
if ($this->_config->template) {
$this->_templateFileName = $this->_config->template;
}
if ($this->_config->templateFileId) {
try {
$path = Tinebase_Model_Tree_Node_Path::createFromStatPath(Tinebase_FileSystem::getInstance()->getPathOfNode($this->_config->templateFileId,
true));
$this->_templateFileName = $path->streamwrapperpath;
} catch (Exception $e) {
}
}
if (isset($_additionalOptions['template'])) {
try {
$path = Tinebase_Model_Tree_Node_Path::createFromStatPath(Tinebase_FileSystem::getInstance()->getPathOfNode($_additionalOptions['template'],
true));
$this->_templateFileName = $path->streamwrapperpath;
} catch (Exception $e) {
}
}
if (!$this->_modelName && !empty($this->_config->model)) {
$this->_modelName = $this->_config->model;
}
$this->_exportTimeStamp = Tinebase_DateTime::now();
if (!empty($this->_config->group)) {
$this->_groupByProperty = $this->_config->group;
$this->_sortInfo['sort'] = $this->_groupByProperty;
if (!empty($this->_config->groupSortDir)) {
$this->_sortInfo['dir'] = $this->_config->groupSortDir;
}
}
if (isset($_additionalOptions['sortInfo'])) {
if (isset($this->_sortInfo['sort'])) {
$this->_sortInfo['sort'] = array_unique(array_merge((array)$this->_sortInfo['sort'],
(array)((isset($_additionalOptions['sortInfo']['field']) ?
$_additionalOptions['sortInfo']['field'] : $_additionalOptions['sortInfo']['sort']))));
} else {
if (isset($_additionalOptions['sortInfo']['field'])) {
$this->_sortInfo['sort'] = $_additionalOptions['sortInfo']['field'];
$this->_sortInfo['dir'] = isset($_additionalOptions['sortInfo']['direction']) ?
$_additionalOptions['sortInfo']['direction'] : 'ASC';
} else {
$this->_sortInfo = $_additionalOptions['sortInfo'];
}
}
}
if (!isset($this->_sortInfo['sort']) && !empty($this->_modelName)) {
/** @var Tinebase_Record_Abstract $mc */
$mc = $this->_modelName;
if (null !== ($mc = $mc::getConfiguration())) {
/** @var Tinebase_ModelConfiguration $mc */
$titleProp = $mc->titleProperty;
if (is_array($titleProp)) {
$titleProp = $titleProp[1];
} else {
$titleProp = [$titleProp];
}
$sort = [];
foreach ($titleProp as $prop) {
if ($mc->hasField($prop) && !array_key_exists($prop, $mc->getVirtualFields())) {
$sort[] = $prop;
}
}
if (count($sort) > 0) {
$this->_sortInfo['sort'] = $sort;
}
}
}
if (isset($_additionalOptions['recordData'])) {
if (isset($_additionalOptions['recordData']['container_id']) && is_array($_additionalOptions['recordData']['container_id'])) {
$_additionalOptions['recordData']['container_id'] = $_additionalOptions['recordData']['container_id']['id'];
}
$this->_FEDataRecordResolving = true;
/** @var Tinebase_Record_Abstract $record */
$record = new $this->_modelName([], true);
$record->setFromJsonInUsersTimezone($_additionalOptions['recordData']);
$this->_records = new Tinebase_Record_RecordSet($this->_modelName, [$record]);
}
if (isset($_additionalOptions['additionalRecords'])) {
foreach ($_additionalOptions['additionalRecords'] as $key => $value) {
if (!isset($value['model']) || !isset($value['recordData'])) {
throw new Tinebase_Exception_UnexpectedValue('additionalRecords needs to specify model and recordData');
}
$record = new $value['model']($value['recordData']);
$this->_additionalRecords[$key] = $record;
}
}
if ($this->_config->keyFields) {
foreach (Tinebase_Helper_ZendConfig::getChildrenConfigs($this->_config->keyFields, 'keyField')
as $keyField) {
$this->_keyFields[$keyField->propertyName] = [
'name' => $keyField->name,
'application' => $keyField->application ? $keyField->application : $this->_applicationName
];
}
}
if ($this->_config->foreignIds) {
foreach (Tinebase_Helper_ZendConfig::getChildrenConfigs($this->_config->foreignIds, 'foreignId')
as $foreignId) {
$this->_foreignIdFields[$foreignId->name] = $foreignId->controller;
}
}
if ($this->_config->virtualFields) {
foreach (Tinebase_Helper_ZendConfig::getChildrenConfigs($this->_config->virtualFields, 'virtualField')
as $virtualField) {
$this->_virtualFields[$virtualField->name] = array(
'relatedModel' => $virtualField->relatedModel,
'relatedDegree' => $virtualField->relatedDegree,
'type' => $virtualField->type
);
}
}
$customFieldConfigs = Tinebase_CustomField::getInstance()->getCustomFieldsForApplication(
$this->_applicationName, $this->_modelName);
/** @var Tinebase_Model_CustomField_Config $cfConfig */
foreach ($customFieldConfigs as $cfConfig) {
$label = empty($cfConfig->definition->label) ? $cfConfig->name : $cfConfig->definition->label;
$name = $this->_translate->_($label);
if (empty($name) || $name === $label) {
$name = $this->_tinebaseTranslate->_($label);
if (empty($name)) {
$name = $label;
}
}
$this->_customFieldsNameLocalLabelMapping[$cfConfig->name] = $name;
}
if ($this->_config->rawData) {
$this->_rawData = true;
}
if (!$this->_rawData && !$this->_config->noCustomFieldExpand) {
$disallowedKeys = Tinebase_Helper_ZendConfig::getChildrenStrings($this->_config->customfieldBlackList,
'name');
/** @var Tinebase_Model_CustomField_Config $cfConfig */
foreach ($customFieldConfigs as $cfConfig) {
if (isset($disallowedKeys[$cfConfig->name])) {
continue;
}
$this->_expandCustomFields[$cfConfig->name] = empty($cfConfig->definition->label) ? $cfConfig->name :
$cfConfig->definition->label;
}
}
}
/**
* get export config
*
* @param array $_additionalOptions additional options
* @return Zend_Config_Xml
* @throws Tinebase_Exception_NotFound
*/
protected function _getExportConfig($_additionalOptions = array())
{
if (isset($_additionalOptions['definitionFilename'])) {
// get definition from file
$definition = Tinebase_ImportExportDefinition::getInstance()->getFromFile(
$_additionalOptions['definitionFilename'],
Tinebase_Application::getInstance()->getApplicationByName($this->_applicationName)->getId()
);
} elseif (isset($_additionalOptions['definitionId'])) {
$definition = Tinebase_ImportExportDefinition::getInstance()->get($_additionalOptions['definitionId']);
} else {
// get preference from db and set export definition name
$exportName = $this->_defaultExportname;
if ($this->_prefKey !== null) {
$exportName = Tinebase_Core::getPreference($this->_applicationName)->
getValue($this->_prefKey, $exportName);
}
// get export definition by name / model
$filter = new Tinebase_Model_ImportExportDefinitionFilter(array(
array('field' => 'model', 'operator' => 'equals', 'value' => $this->_modelName),
array('field' => 'name', 'operator' => 'equals', 'value' => $exportName),
));
$definitions = Tinebase_ImportExportDefinition::getInstance()->search($filter);
if (count($definitions) == 0) {
throw new Tinebase_Exception_NotFound('Export definition for model ' .
$this->_modelName . ' not found.');
}
$definition = $definitions->getFirstRecord();
}
$config = Tinebase_ImportExportDefinition::getInstance()->
getOptionsAsZendConfigXml($definition, $_additionalOptions);
if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) {
Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' export config: ' .
print_r($config->toArray(), true));
}
return $config;
}
protected function _getTemplateFilename()
{
return $this->_templateFileName;
}
/**
* get export format string (csv, ...)
*
* @return string
* @throws Tinebase_Exception_NotFound
*/
public function getFormat()
{
if ($this->_format === null) {
throw new Tinebase_Exception_NotFound('Format string not found.');
}
return $this->_format;
}
public static function getDefaultFormat()
{
return null;
}
/**
* get download content type
*
* @return string
*/
abstract public function getDownloadContentType();
/**
* return download filename
*
* @param string $_appName
* @param string $_format
* @return string
*/
public function getDownloadFilename($_appName, $_format)
{
$model = '';
if (null !== $this->_modelName) {
/** @var Tinebase_Record_Abstract $model */
$model = $this->_modelName;
if (null !== ($modelConf = $model::getConfiguration())) {
$model = ' ' . $this->_translate->_($modelConf->recordName, $this->_locale);
} else {
$model = explode(' ', $model, 3);
if (count($model) === 3) {
$model = ' ' . $this->_translate->_($model[2], $this->_locale);
} else {
$model = '';
}
}
}
$name = '';
if (!empty($this->_config->label)) {
if ($model !== '') {
$name .= ' ';
}
$name .= $this->_translate->_($this->_config->label, $this->_locale);
}
$tineTranslate = Tinebase_Translation::getTranslation('Tinebase');
return mb_strtolower($tineTranslate->_('Export', $this->_locale) . ' ' .
$this->_translate->_($_appName, $this->_locale) . $model . $name . '.' . $_format);
}
/**
* workflow
* generate();
* * _exportRecords();
* * * if _hasTwig()
* * * * _loadTwig();
* * * * * _getTwigSource();
* * processIteration();
* * * _resolveRecords();
* * * if _firstIteration && _writeGenericHeader
* * * * _writeGenericHead();
* * * foreach $records
* * * * _startRow();
* * * * _processRecord();
* * * * _endRow();
* * _onAfterExportRecords();
*/
/**
* generate export
*/
abstract public function generate();
/**
* export records
*/
protected function _exportRecords()
{
if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__
. ' Starting export of ' . $this->_modelName . ' with filter: ' . print_r($this->_filter->toArray(), true)
. ' and sort info: ' . print_r($this->_sortInfo, true));
if (true === $this->_hasTwig()) {
$this->_loadTwig();
}
$this->_onBeforeExportRecords();
$this->_firstIteration = true;
if (null === $this->_records) {
$iterator = new Tinebase_Record_Iterator(array(
'iteratable' => $this,
'controller' => $this->_controller,
'filter' => $this->_filter,
'options' => array(
'searchAction' => 'export',
'sortInfo' => $this->_sortInfo,
'getRelations' => $this->_getRelations,
),
));
if (false === ($result = $iterator->iterate())) {
$result = array(
'totalcount' => $this->_records->count(),
'results' => array(),
);
}
} else {
$totalCount = 0;
$totalCountFn = function(&$val) use (&$totalCountFn, &$totalCount) {
if (is_array($val)) {
foreach ($val as &$a) {
$totalCountFn($a);
}
} else {
/** @var Tinebase_Record_RecordSet $val */
$totalCount += $val->count();
}
};
$totalCountFn($this->_records);
$result = array(
'totalcount' => $totalCount,
'results' => array(),
);
$result['results'][] = $this->processIteration($this->_records);
}
$this->_onAfterExportRecords($result);
if (Tinebase_Core::isLogLevel(Zend_Log::INFO)) Tinebase_Core::getLogger()->info(__METHOD__ . '::' . __LINE__
. ' Exported ' . $result['totalcount'] . ' records.');
}
protected function _onBeforeExportRecords()
{
}
/**
* @return bool
*/
protected function _hasTwig()
{
if (true === $this->_hasTemplate) {
return true;
}
if ($this->_config->columns) {
foreach (Tinebase_Helper_ZendConfig::getChildrenConfigs($this->_config->columns, 'column') as $column) {
if ($column->twig) {
return true;
}
}
}
return false;
}
protected function _loadTwig()
{
if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' loading twig template...');
$options = [
// in order to cache the templates, we need to cache $this->_twigMapping too!
Tinebase_Twig::TWIG_CACHE => false,
Tinebase_Twig::TWIG_AUTOESCAPE => 'json',
Tinebase_Twig::TWIG_LOADER => new Twig_Loader_Chain(array(
new Tinebase_Twig_CallBackLoader($this->_templateFileName, $this->_getLastModifiedTimeStamp(),
array($this, '_getTwigSource'))))
];
$this->_twig = new Tinebase_Twig($this->_locale, $this->_translate, $options);
foreach ($this->_twigExtensions as $extension) {
$this->_twig->addExtension($extension);
}
$this->_extendTwigSetup();
$this->_twigTemplate = $this->_twig->load($this->_templateFileName);
}
protected function _extendTwigSetup()
{
// the concrete class may do stuff to the twig environment here before we load the template
// example:
// $this->_twig->getEnvironment()->addFunction(new Twig_SimpleFunction(...));
}
/**
* @return string
*/
public function _getTwigSource()
{
$source = '[';
if (true !== $this->_hasTemplate && $this->_config->columns) {
foreach (Tinebase_Helper_ZendConfig::getChildrenConfigs($this->_config->columns, 'column') as $column) {
if ($column->twig) {
$source .= ($source!=='' ? ',"' : '""') . (string)$column->twig . '"';
}
}
}
return $source . ']';
}
/**
* @return int
*/
protected function _getLastModifiedTimeStamp()
{
return filemtime($this->_templateFileName);
}
protected function _getCurrentState()
{
return array(
'_firstIteration' => $this->_firstIteration,
'_writeGenericHeader' => $this->_writeGenericHeader,
'_groupByProperty' => $this->_groupByProperty,
'_groupByProcessor' => $this->_groupByProcessor,
'_lastGroupValue' => $this->_lastGroupValue,
'_currentRecord' => $this->_currentRecord,
'_currentRowType' => $this->_currentRowType,
'_twigTemplate' => $this->_twigTemplate,
'_twigMapping' => $this->_twigMapping,
'_keyFields' => $this->_keyFields,
'_virtualField' => $this->_virtualFields,
);
}
protected function _setCurrentState(array $array)
{
foreach ($array as $key => $value) {
$this->{$key} = $value;
}
}
/**
* add body rows
*
* @param Tinebase_Record_RecordSet|array $_records
*/
public function processIteration($_records)
{
if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' iterating over export data...');
if (is_array($_records)) {
foreach ($_records as $key => $value) {
$this->_startDataSource($key);
$this->processIteration($value);
$this->_endDataSource($key);
}
return;
}
$this->_resolveRecords($_records);
if (true === $this->_firstIteration && true === $this->_writeGenericHeader) {
$this->_writeGenericHead();
}
$first = $this->_firstIteration;
foreach ($_records as $record) {
if (null !== $this->_groupByProperty) {
$propertyValue = $record->{$this->_groupByProperty};
if (null !== $this->_groupByProcessor) {
/** @var closure $fn */
$fn = $this->_groupByProcessor;
$fn($propertyValue);
}
if (true === $first || $this->_lastGroupValue !== $propertyValue) {
$this->_lastGroupValue = $propertyValue;
if (false === $first) {
$this->_endGroup();
}
$this->_currentRecord = $record;
$this->_startGroup();
}
// TODO fix this?
//$this->_writeGroupHeading($record);
}
$this->_currentRecord = $record;
$this->_currentRowType = self::ROW_TYPE_RECORD;
$this->_startRow();
$this->_processRecord($record);
$this->_endRow();
if (true === $first) {
$first = false;
}
}
if ($_records->count() > 0 && null !== $this->_groupByProperty) {
$this->_endGroup();
}
$this->_firstIteration = false;
}
/**
* @param $_name
*/
protected function _startDataSource($_name)
{
}
/**
* @param $_name
*/
protected function _endDataSource($_name)
{
}
protected function _startGroup()
{
}
protected function _endGroup()
{
}
protected function _writeGroupHeading(Tinebase_Record_Interface $_record)
{
if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' writting group heading...');
$this->_currentRowType = self::ROW_TYPE_GROUP_HEADER;
$this->_startRow();
$this->_writeValue($_record->{$this->_groupByProperty});
$this->_endRow();
}
/**
* resolve records and prepare for export (set user timezone, ...)
*
* @param Tinebase_Record_RecordSet $_records
*/
protected function _resolveRecords(Tinebase_Record_RecordSet $_records)
{
if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' resolving export records...');
if ($_records->count() === 0) {
return;
}
$record = $_records->getFirstRecord();
// FIXME think what to do
// TODO fix ALL this!
// this is code present in the abstract controller, getRelatedData... why is it here?
// get field types/identifiers from config, this is sort of dead code?
$identifiers = [];
$types = [];
if ($this->_config->columns) {
$types = array();
foreach (Tinebase_Helper_ZendConfig::getChildrenConfigs($this->_config->columns, 'column') as $column) {
$types[] = $column->type;
$identifiers[] = $column->identifier;
}
$types = array_unique($types);
} /* else {
$types = $this->_resolvedFields;
}*/
// resolve users, also for FE Data!
$userFields = [];
foreach ($this->_userFields as $field) {
if (empty($types) || in_array($field, $types) || in_array($field, $identifiers)) {
$userFields[] = $field;
}
}
if (count($userFields) > 0) {
Tinebase_User::getInstance()->resolveMultipleUsers($_records, $userFields, true);
if ($this->_FEDataRecordResolving) {
foreach ($userFields as $field) {
foreach ($_records->{$field} as $idx => $value) {
if (is_array($value)) {
$_records->getByIndex($idx)->{$field} = new Tinebase_Model_FullUser($value);
}
}
}
}
}
// add notes, this is dead code?
if (in_array('notes', $types) && !$this->_FEDataRecordResolving) {
Tinebase_Notes::getInstance()->getMultipleNotesOfRecords($_records, 'notes', 'Sql', false);
}
// add container, this is dead code?
if (in_array('container_id', $types) && !$this->_FEDataRecordResolving) {
Tinebase_Container::getInstance()->getGrantsOfRecords($_records, Tinebase_Core::getUser());
}
while ($record->has('customfields')) {
$customFieldConfigs = Tinebase_CustomField::getInstance()->getCustomFieldsForApplication(
$this->_applicationName, $this->_modelName);
if (empty($customFieldConfigs)) {
$_records->customfields = array();
break;
}
if (!$this->_FEDataRecordResolving) {
$_records->customfields = array();
Tinebase_CustomField::getInstance()->resolveMultipleCustomfields($_records, true);
}
$availableCFNames = [];
/** @var Tinebase_Model_CustomField_Config $cfc */
foreach ($customFieldConfigs as $cfc) {
$cfc->value = null;
$availableCFNames[$cfc->name] = $cfc;
}
$validators = null;
$cfNameLabelMap = $this->_customFieldsNameLocalLabelMapping;
$instance = $this;
$stringifyCallBack = function($val) use ($instance) {
return $instance->_convertToString($val);
};
if (!empty($this->_expandCustomFields)) {
$validators = $_records->getFirstRecord()->getValidators();
foreach ($this->_expandCustomFields as $field => $label) {
if (!isset($validators[$field])) {
$validators[$field] = [];
}
}
}
/** @var Tinebase_Record_Abstract $record */
foreach ($_records as $record) {
$cfs = $record->customfields;
if (empty($cfs)) {
$cfs = [];
}
if ($this->_FEDataRecordResolving) {
foreach ($cfs as $name => &$val) {
if (!isset($availableCFNames[$name])) {
unset($cfs[$name]);
continue;
}
/** @var Tinebase_Model_CustomField_Config $cfc */
$cfc = clone $availableCFNames[$name];
$cfc->value = $cfs[$name];
$val = $cfc;
}
}
foreach (array_diff_key($availableCFNames, $cfs) as $name => $cfc) {
$cfs[$name] = clone $cfc;
}
array_walk($cfs, function(Tinebase_Model_CustomField_Config $val, $key)
use($cfNameLabelMap, $stringifyCallBack) {
$val->label = $cfNameLabelMap[$key];
$val->value = new Tinebase_CustomField_Value($val->value, $val->definition, $stringifyCallBack,
$val->application_id);
});
uksort($cfs, function($a, $b) use($cfNameLabelMap) {
return strcmp($cfNameLabelMap[$a], $cfNameLabelMap[$b]);
});
$record->customfields = $cfs;
if (null !== $validators) {
$record->setValidators($validators);
foreach ($this->_expandCustomFields as $field => $label) {
if (isset($cfs[$field])) {
$record->{$field} = $cfs[$field];
}
}
}
}
break;
}
/** @var Tinebase_Record_Abstract $modelName */
$modelName = $_records->getRecordClassName();
if ($record->has('relations')) {
if (!$this->_FEDataRecordResolving) {
$relations = Tinebase_Relations::getInstance()->getMultipleRelations($modelName, 'Sql',
$_records->getArrayOfIds());
/** @var Tinebase_Record_RecordSet $rels */
foreach ($relations as $rels) {
$rels->removeRecords($rels->filter('related_record'));
}
} else {
$relations = [];
foreach ($_records as $idx => $record) {
$rels = $record->relations;
if (empty($rels)) {
continue;
}
if (is_array($rels)) {