-
Notifications
You must be signed in to change notification settings - Fork 151
Expand file tree
/
Copy pathQubitFlatfileImport.class.php
More file actions
2335 lines (1998 loc) · 79 KB
/
QubitFlatfileImport.class.php
File metadata and controls
2335 lines (1998 loc) · 79 KB
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
/*
* This file is part of the Access to Memory (AtoM) software.
*
* Access to Memory (AtoM) is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Access to Memory (AtoM) is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Access to Memory (AtoM). If not, see <http://www.gnu.org/licenses/>.
*/
/**
* Import flatfile data.
*
* @author Mike Cantelon <mike@artefactual.com>
*/
class QubitFlatfileImport
{
public $context; // optional sfContext
public $className; // optional class name of object to create/save
public $errorLog; // optional location of error log file
public $displayProgress = true; // display progress by default
public $rowsUntilProgressDisplay; // optional display progress every n rows
public $searchIndexingDisabled = true; // disable per-object search indexing by default
public $disableNestedSetUpdating = false; // update nested set on object creation
public $matchAndUpdate = false; // match existing records & update them
public $deleteAndReplace = false; // delete matching records & replace them
public $skipMatched = false; // skip creating new record if matching one is found
public $skipUnmatched = false; // skip creating new record if matching one is not found
public $roundtrip = false; // treat legacy ID as internal ID
public $keepDigitalObjects = false; // skip deletion of DOs when set. Works when --update set.
public $limitToId = 0; // id of repository or TLD to limit our update matching under
public $status = []; // place to store data related to overall import
public $rowStatusVars = []; // place to store data related to current row
public $columnNames = []; // column names from first row of imported CSV
public $ignoreColumns = []; // columns in CSV to ignore
public $renameColumns = []; // CSV header column substitutions
public $addColumns = []; // columns to add to internal row buffer
public $standardColumns = []; // columns in CSV are object properties
public $columnMap = []; // columns in CSV that map to object properties
public $propertyMap = []; // columns in CSV that map to Qubit properties
public $termRelations = []; // columns in CSV that map to terms in a given taxonomy
public $noteMap = []; // columns in CSV that should become notes
public $languageMap = []; // columns in CSV that map to serialized language Qubit properties
public $scriptMap = []; // columns in CSV that map to serialized script Qubit properties
public $handlers = []; // columns in CSV paired with custom handling logic
public $variableColumns = []; // columns in CSV to be later referenced by logic
public $arrayColumns = []; // columns in CSV to explode and later reference
public $updatePreparationLogic; // Optional pre-update logic (remove related data, etc.)
public $rowInitLogic; // Optional logic to create/load object if not using $className
public $preSaveLogic; // Optional pre-save logic
public $saveLogic; // Optional logic to save object if not using $className
public $postSaveLogic; // Optional post-save logic
public $completeLogic; // Optional cleanup, etc. logic for after import
// Replaceable logic to filter content before entering Qubit
public $contentFilterLogic;
public function __construct($options = [])
{
// Replaceable logic to filter content before entering Qubit
$this->contentLogic = function ($text) {
return $text;
};
$this->setPropertiesFromArray($this, $options, true);
// initialize bookkeeping of rows processed
$this->status['rows'] = 0;
$this->status['duplicates'] = 0;
$this->status['updated'] = 0;
}
/*
*
* General helper methods
* ----------------------
*/
/**
* Use an array of properties and their respective values to set an object's
* properties (restricting to a set of allowed properties and allowing the
* specification of properties that should be ignored and not set).
*
* @param object &$object object to act upon
* @param array $propertyArray array of properties and their respective values
* @param array $allowedProperties array of properties that can be set or true if any allowed
* @param array $ignore array of properties that should be ignored
*/
public function setPropertiesFromArray(&$object, $propertyArray, $allowedProperties, $ignore = [])
{
// set properties from options, halting upon invalid option
foreach ($propertyArray as $option => $value) {
if (!in_array($option, $ignore)) {
// if allowing all properties, inspect object to see if property is legitimate
// otherwise use array of allowed properties
$settingAllowed = (
(true === $allowedProperties && property_exists(get_class($object), $option))
|| (is_array($allowedProperties) && in_array($option, $allowedProperties))
);
if ($settingAllowed) {
$object->{$option} = $value;
} else {
throw new Exception('Option "'.$option.'" not allowed.');
}
}
}
}
public function setUpdateOptions($options)
{
if ($options['limit']) {
$this->limitToId = $this->getIdCorrespondingToSlug($options['limit']);
}
// Are there params set on --update flag?
if ($options['update']) {
// Parameters for --update are validated in csvImportBaseTask.class.php.
switch ($options['update']) {
case 'delete-and-replace':
// Delete any matching records, and re-import them (attach to existing entities if possible).
$this->deleteAndReplace = true;
break;
case 'match-and-update':
// Save match option. If update is ON, and match is set, only updating
// existing records - do not create new objects.
$this->matchAndUpdate = true;
// keepDigitalObjects only makes sense with match-and-update
$this->keepDigitalObjects = $options['keep-digital-objects'];
break;
default:
throw new sfException('Update parameter "'.$options['update'].'" not handled: Correct --update parameter.');
}
}
$this->skipMatched = $options['skip-matched'];
$this->skipUnmatched = $options['skip-unmatched'];
$this->roundtrip = $options['roundtrip'];
}
/*
* Utility function to filter data, with a function that can be optionally
* overridden, before it enters Qubit
*
* This function will be automatically applied to data handled by the
* standardColumns, columnMap, propertyMap, and noteMap handlers
*
* This function will not be applied to data handled by variableColumns
* or arrayColumns or other handlers allowing the user to do ad-hoc things
*
* @param string $text Text to process
*/
public function content($text)
{
if ($this->contentFilterLogic) {
return trim(call_user_func_array($this->contentFilterLogic, [$text]));
}
return trim($text);
}
/**
* Set status variable value.
*
* @param string $var name of variable
* @param value value of variable (could be any type)
* @param mixed $value
*/
public function setStatus($var, $value)
{
$this->status[$var] = $value;
}
/**
* Determine whether or not a column exists.
*
* @param string $column name of column
*
* @return bool
*/
public function columnExists($column)
{
$columnIndex = array_search($column, $this->columnNames);
return is_numeric($columnIndex);
}
/**
* Get/set values in internal representation of current row.
*
* @param mixed $column
* @param mixed $value
*/
public function columnValue($column, $value = false)
{
$columnIndex = array_search($column, $this->columnNames);
if (is_numeric($columnIndex)) {
if (false === $value) {
return trim($this->status['row'][$columnIndex]);
}
$this->status['row'][$columnIndex] = $value;
} else {
throw new sfException('Missing column "'.$column.'".');
}
}
/**
* Copy one column value to another column in internal representation of current row.
*
* @param mixed $sourceColumn
* @param mixed $destinationColumn
*/
public function copy($sourceColumn, $destinationColumn)
{
$this->columnValue($destinationColumn, $this->columnValue($sourceColumn));
}
/**
* Get status variable value.
*
* @param string $var name of variable
*
* @return value value of variable (could be any type)
*/
public function getStatus($var)
{
return $this->status[$var];
}
/**
* Test whether a property is set and, if so, execute it.
*
* @param string $property name of property
*/
public function executeClosurePropertyIfSet($property)
{
// attempting to directly call an object property that's a
// closure results in "Fatal error: Call to undefined method"
if ($this->{$property}) {
call_user_func_array($this->{$property}, [&$this]);
}
}
/**
* Get time elapsed during import.
*
* @return int microseconds since import began
*/
public function getTimeElapsed()
{
return $this->timer->elapsed();
}
/**
* Log error message if an error log has been defined.
*
* @param string $message error message
* @param bool $includeCurrentRowNumber prefix error message with row number
*
* @return string message prefixed with current row number
*/
public function logError($message, $includeCurrentRowNumber = true)
{
$message = ($includeCurrentRowNumber) ? sprintf("Row %d: %s\n", $this->getStatus('rows') + 1, $message) : $message;
// If a carriage-return progress line is active on STDERR, break it so
// subsequent STDOUT messages start on a new line.
if ($this->displayProgress) {
fwrite(STDERR, "\r");
fflush(STDERR);
}
if ($this->errorLog) {
file_put_contents($this->errorLog, $message, FILE_APPEND);
}
return $message;
}
/**
* Append content to existing content, prepending a line break to new content
* if necessary.
*
* @param string $oldContent existing content
* @param string $newContent new content to add to existing content
*
* @return string both strings appended
*/
public function appendWithLineBreakIfNeeded($oldContent, $newContent)
{
return ($oldContent) ? $oldContent."\n".$newContent : $newContent;
}
/**
* Combine column text, using optional pre-column prefixes.
*
* @param array $prefixesAndColumns array, optional keys specifying prefix
* @param string $destinationColumn optional destination column for result
*
* @return string combined column text
*/
public function amalgamateColumns($prefixesAndColumns, $destinationColumn = false)
{
$output = '';
foreach ($prefixesAndColumns as $prefix => $column) {
$columnValue = $this->columnValue($column);
if ($columnValue) {
// numeric keys are considered prefixes
$prepend = (!is_numeric($prefix)) ? $prefix : '';
$output = $this->appendWithLineBreakIfNeeded(
$output,
$prepend.$columnValue
);
}
}
// optional direct setting of column
if ($destinationColumn) {
$this->columnValue($destinationColumn, $output);
}
return $output;
}
/**
* Convert human readable (e.g. 'This string') strings to camelCase
* representation (e.g. 'thisString').
*
* @param string $str input string
*
* @return string camelCase string
*/
public static function camelize($str)
{
$str = str_replace(' ', '_', $str);
$str = sfInflector::camelize($str);
return lcfirst($str);
}
/**
* Pull data from a csv file and process each row.
*
* @param resource $fh file handler for file containing CSV data
* @param int $skipRows number of rows to skip (optional)
*/
public function csv($fh, $skipRows = 0)
{
$this->handleByteOrderMark($fh);
$this->status['skippedRows'] = $skipRows;
$this->columnNames = fgetcsv($fh, 60000);
if (false === $this->columnNames) {
throw new sfException('Could not read initial row. File could be empty.');
}
$this->handleUnnamedColumns();
$this->handleColumnRenaming();
// add virtual columns (for column amalgamation, etc.)
foreach ($this->addColumns as $column) {
$this->columnNames[] = $column;
}
// warn if column names contain whitespace
foreach ($this->columnNames as $column) {
if ($column != trim($column)) {
echo $this->logError(sprintf("WARNING: Column '%s' has whitespace before or after its name.", $column));
}
}
// disabling search indexing improves import speed
$this->searchIndexingDisabled ? QubitSearch::disable() : QubitSearch::enable();
if ($skipRows) {
echo 'Skipped '.$skipRows." rows...\n";
}
$timerStarted = false;
// import each row
while ($item = fgetcsv($fh, 60000)) {
if ($this->status['rows'] >= $skipRows) {
// Skip blank rows, but keep track of rows parsed
if (!$this->rowContainsData($item)) {
++$this->status['rows'];
continue;
}
if (!$timerStarted) {
$this->startTimer();
$timerStarted = true;
}
$this->row($item);
++$this->status['rows'];
if ($this->displayProgress) {
$this->renderProgressDescription();
}
} else {
++$this->status['rows'];
}
}
if ($timerStarted) {
$this->stopTimer();
}
if ($this->displayProgress) {
fwrite(STDERR, "\r");
fflush(STDERR);
$this->progressLineActive = false;
}
// Final summary to STDOUT for logs
$rowsProcessed = $this->getStatus('rows') - $this->getStatus('skippedRows');
$totalDuration = $this->getTimeElapsed();
// Ensure total duration is never zero (avoid div by zero in rate calc below)
$finalRate = $rowsProcessed / max($totalDuration, 1e-9);
$msg = sprintf(
"Processed %d rows total in %.2fs (%.1f/s)\n",
$rowsProcessed,
$totalDuration,
$finalRate
);
echo $this->logError($msg, false);
if ($this->status['duplicates']) {
$msg = sprintf('Duplicates found: %d', $this->status['duplicates']);
echo $this->logError($msg, false);
}
if ($this->status['updated']) {
$msg = sprintf('Updated: %d', $this->status['updated']);
echo $this->logError($msg, false);
}
// add ability to define cleanup, etc. logic
$this->executeClosurePropertyIfSet('completeLogic');
}
/**
* Check array of event data from import, check if this exact event already exists.
*
* @param mixed $event
*
* @return bool True if exists, false if not
*/
public function hasDuplicateEvent($event)
{
if (!isset($this->object->id)) {
return;
}
// Event caching interferes with duplicate detection
QubitEvent::clearCache();
// Get related events
$criteria = new Criteria();
$criteria->add(QubitEvent::OBJECT_ID, $this->object->id);
// Compare fields of the event in question with each associated event
$fields = [
'startDate', 'startTime', 'endDate', 'endTime', 'typeId', 'objectId', 'actorId', 'name',
'description', 'date', 'culture',
];
foreach (QubitEvent::get($criteria) as $existingEvent) {
$match = true;
foreach ($fields as $field) {
// Use special logic when comparing dates, see dateStringsEqual for details.
if (false !== strpos(strtolower($field), 'date')) {
$match = $match && $this->dateStringsEqual($existingEvent->{$field}, $event->{$field});
} else {
$match = $match && $existingEvent->{$field} === $event->{$field};
}
// Event fields differ, don't bother checking other fields since these aren't equal
if (!$match) {
break;
}
}
// All fields matched, found duplicate.
if ($match) {
return true;
}
}
return false;
}
/**
* Process a row of imported data.
*
* @param array $row array of column data
*/
public function row($row = [])
{
$this->object = null; // Ensure object set to null so our --update options don't get confused between rows
$this->status['row'] = $row; // Stash raw row data so it's accessible to closure logic
$skipRowProcessing = false;
$this->handleVirtualCols();
$this->handleCulture();
$this->rowProcessingBeforeObjectCreation($row); // Set row status variables that are based on column values
if (isset($this->className)) {
$skipRowProcessing = $this->fetchOrCreateObjectByClass();
if (!$skipRowProcessing && property_exists(get_class($this->object), 'disableNestedSetUpdating')) {
$this->object->disableNestedSetUpdating = $this->disableNestedSetUpdating;
}
} else {
// Execute ad-hoc row initialization logic (which can make objects, load them, etc.)
$this->executeClosurePropertyIfSet('rowInitLogic');
}
if (!$skipRowProcessing) {
$this->rowProcessingBeforeSave($row); // Set fields in object and execute custom column handlers
$this->executeClosurePropertyIfSet('preSaveLogic');
if (isset($this->className)) {
$this->object->save();
} else {
// execute row completion logic
$this->executeClosurePropertyIfSet('saveLogic');
}
$this->executeClosurePropertyIfSet('postSaveLogic'); // Import cols that have child data (properties and notes)
$this->rowProcessingAfterSave($row);
}
// reset row-specific status variables
$this->rowStatusVars = [];
}
public function isUpdating()
{
return $this->matchAndUpdate || $this->deleteAndReplace;
}
/**
* Output import progress, time elapsed, and memory usage.
*
* @return string description of import progress
*/
public function renderProgressDescription()
{
// Periodic single-line summaries to STDERR.
static $startTime = null;
static $lastLogTime = null;
static $processedCount = 0;
if (null === $startTime) {
$startTime = microtime(true);
$lastLogTime = $startTime;
}
++$processedCount;
$now = microtime(true);
if ($now - $lastLogTime >= 5) {
// Ensure elapsed is never zero (avoid div by zero in rate calc below)
$elapsed = max($now - $startTime, 1e-9);
$rate = $processedCount / $elapsed;
$memoryUsageMB = round(memory_get_usage() / (1024 * 1024), 2);
fwrite(STDERR, sprintf("\rProcessed %d rows (%.1f/s, %.2f MB)", $processedCount, $rate, $memoryUsageMB));
fflush(STDERR);
$lastLogTime = $now;
}
return '';
}
/*
*
* Column handlers
* ---------------
*/
/**
* Add an ad-hoc column handler.
*
* @param string $column name of column
* @param closure $handler column handling logic
*/
public function addColumnHandler($column, $handler)
{
$this->handlers[$column] = $handler;
}
/**
* Add an ad-hoc column handler to multiple columns.
*
* @param array $columns names of columns
* @param closure $handler column handling logic
*/
public function addColumnHandlers($columns, $handler)
{
foreach ($columns as $column) {
$this->addColumnHandler($column, $handler);
}
}
/**
* Handle mapping of column to object property.
*
* @param array $mapDefinition array defining which property to map to and
* optional transformation logic
* @param string $value column value
*/
public function mappedColumnHandler($mapDefinition, $value)
{
if (isset($this->object) && is_object($this->object)) {
if (is_array($mapDefinition)) {
// tranform value is logic provided to do so
if (is_callable($mapDefinition['transformationLogic'])) {
$this->object->{$mapDefinition['column']} = $this->content($mapDefinition['transformationLogic']($this, $value));
} else {
$this->object->{$mapDefinition['column']} = $this->content($value);
}
} else {
$this->object->{$mapDefinition} = $this->content($value);
}
}
}
/**
* Handle mapping of column, containing multiple values delimited by a
* character, to an array. Any values set to 'NULL' will be filtered out.
*
* @param string $column column name
* @param array $delimiter delimiting character
* @param string $value column value
*/
public function arrayColumnHandler($column, $delimiter, $value)
{
if ($value) {
$this->rowStatusVars[$column] = array_map('trim', explode($delimiter, $value));
}
}
/*
*
* Qubit data helpers
* ------------------
*/
/**
* Issue an SQL query.
*
* @param string $query SQL query
* @param string $params values to map to placeholders (optional)
*
* @return object database statement object
*/
public static function sqlQuery($query, $params = [])
{
$connection = Propel::getConnection();
$statement = $connection->prepare($query);
for ($index = 0; $index < count($params); ++$index) {
$statement->bindValue($index + 1, $params[$index]);
}
$statement->execute();
return $statement;
}
/**
* Create one or more Qubit notes of a certain type.
*
* @param int $typeId term ID of note type
* @param string $array Note text items
* @param closure $transformationLogic logic to manipulate note text
* @param mixed $textArray
*
* @return array Notes created
*/
public function createOrUpdateNotes($typeId, $textArray, $transformationLogic = false)
{
// If importing a translation row we currently don't handle notes
if (!defined(get_class($this->object).'::SOURCE_CULTURE')) {
return;
}
$noteIds = [];
// I18n row handler
if ($this->columnValue('culture') != $this->object->sourceCulture) {
$query = 'SELECT id FROM note WHERE object_id = ? AND type_id = ?;';
$statement = self::sqlQuery($query, [$this->object->id, $typeId]);
while ($noteId = $statement->fetchColumn()) {
$noteIds[] = $noteId;
}
}
// Get existing notes content as array - do this once per CSV row to reduce DB requests.
// Update array with note->content being added so values within CSV are also
// checked as they are added.
$existingNotes = $this->getExistingNotes($this->object->id, $typeId, $this->columnValue('culture'));
foreach ($textArray as $i => $text) {
$options = [];
if ($transformationLogic) {
$options['transformationLogic'] = $transformationLogic;
}
if (isset($noteIds[$i])) {
$options['noteId'] = $noteIds[$i];
}
// checkNoteExists will prevent note duplication.
if (!$this->checkNoteExists($existingNotes, $this->content($text))) {
$this->createOrUpdateNote($typeId, $text, $options);
}
}
}
/**
* Create a Qubit note.
*
* @param int $typeId term ID of note type
* @param string $text Note text
* @param closure $transformationLogic logic to manipulate note text
* @param mixed $options
*
* @return QubitNote created note
*/
public function createOrUpdateNote($typeId, $text, $options = [])
{
// Trim whitespace
$text = trim($text);
if (isset($options['noteId'])) {
// Clearing the cache seems to prevent a weird issue with trying to save
// a cached version of the note? In any case, it makes it work (!?)
QubitNote::clearCache();
$note = QubitNote::getById($options['noteId']);
} else {
$note = new QubitNote();
$note->objectId = $this->object->id;
$note->typeId = $typeId;
}
if (isset($options['transformationLogic'])) {
$transformer = $options['transformationLogic'];
$text = $transformer($this, $text);
}
$note->content = $this->content($text);
$note->culture = $this->columnValue('culture');
$note->indexOnSave = false;
$note->save();
return $note;
}
/**
* Create a Qubit event, or add an i18n row to existing event.
*
* @param int $typeId term ID of event type
* @param array $options option parameter
*/
public function createOrUpdateEvent($typeId, $options = [])
{
if (isset($options['eventId'])) {
// Adding new i18n values to an existing event
$event = QubitEvent::getById($options['eventId']);
unset($options['eventId']);
} else {
// Create new event
$event = new QubitEvent();
$event->objectId = $this->object->id;
$event->typeId = $typeId;
}
if (null === $event) {
// Couldn't find or create event
return;
}
$allowedProperties = ['date', 'description', 'startDate', 'endDate', 'typeId'];
$ignoreOptions = ['actorName', 'actorHistory', 'place', 'culture'];
$this->setPropertiesFromArray($event, $options, $allowedProperties, $ignoreOptions);
// Save actor history in untitled actor if there is actorHistory without actorName
if (isset($options['actorHistory']) && !isset($options['actorName'])) {
$options['actorName'] = '';
}
if (isset($options['actorName'])) {
if (isset($event->actorId)) {
// Update i18n values
$event->actor->authorizedFormOfName = $options['actorName'];
if (isset($options['actorHistory'])) {
$event->actor->history = $options['actorHistory'];
}
$event->actor->save();
} else {
// Link actor
$actorOptions = [];
if (isset($options['actorHistory'])) {
$actorOptions['history'] = $options['actorHistory'];
}
if ($this->object instanceof QubitInformationObject) {
$actor = $this->createOrFetchAndUpdateActorForIo($options['actorName'], $actorOptions);
} else {
$actor = $this->createOrFetchActor($options['actorName'], $actorOptions);
}
$event->actorId = $actor->id;
}
}
if ($this->matchAndUpdate && $this->hasDuplicateEvent($event)) {
return; // Skip creating / updating events if this exact one already exists.
}
$event->indexOnSave = false;
$event->save();
// Add relation with place
if (isset($options['place'])) {
$culture = 'en';
if (isset($options['culture'])) {
$culture = $options['culture'];
}
$placeTerm = $this->createOrFetchTerm(QubitTaxonomy::PLACE_ID, $options['place'], $culture);
self::createObjectTermRelation($event->id, $placeTerm->id);
}
}
/**
* Create a Qubit physical object or, if one already exists, fetch it.
*
* @param string $name name of physical object
* @param string $location location of physical object
* @param int $typeId type ID of physical object
*
* @return QubitPhysicalObject created or fetched physical object
*/
public function createOrFetchPhysicalObject($name, $location, $typeId)
{
$query = 'SELECT p.id FROM physical_object p
INNER JOIN physical_object_i18n pi ON p.id=pi.id
WHERE pi.name=? AND pi.location=? AND p.type_id=?';
$statement = QubitFlatfileImport::sqlQuery($query, [$name, $location, $typeId]);
$result = $statement->fetch(PDO::FETCH_OBJ);
if ($result) {
return QubitPhysicalObject::getById($result->id);
}
return $this->createPhysicalObject($name, $location, $typeId);
}
/**
* Create a Qubit repository or, if one already exists, fetch it.
*
* @param string $name name of repository
* @param mixed $fetchOnly prevent create
*
* @return QubitRepository created or fetched repository
*/
public static function createOrFetchRepository($name, $fetchOnly = false)
{
$query = "SELECT r.id FROM actor_i18n a \r
INNER JOIN repository r ON a.id=r.id \r
WHERE a.authorized_form_of_name=?";
$statement = QubitFlatfileImport::sqlQuery($query, [$name]);
$result = $statement->fetch(PDO::FETCH_OBJ);
if ($result && strlen($name) > 0) {
return QubitRepository::getById($result->id);
}
if (!$fetchOnly) {
return QubitFlatfileImport::createRepository($name);
}
}
/**
* Fetch or create a QubitActor record based on the actor name,
* the imported IO repository and the update options. Update the
* actor history in matches from the same repository when using
* the match and update option.
*
* @param string $name name of actor
* @param array $options optional data
*
* @return QubitActor created or fetched actor
*/
public function createOrFetchAndUpdateActorForIo($name, $options = [])
{
// Create new actor if there is no match by
// auth. form of name (do not match untitled actors)
if (empty($name) || null === $actor = QubitActor::getByAuthorizedFormOfName($name)) {
return $this->createActor($name, $options);
}
// Return first matching actor if the actor history is empty on the import
if (empty($options['history'])) {
return $actor;
}
// Check for a match with the same auth. form of name and history
if (null !== $actor = QubitActor::getByAuthorizedFormOfName($name, ['history' => $options['history']])) {
return $actor;
}
// Importing to an IO without repository or in a repo not maintaining an actor match
if (
!isset($this->object->repository)
|| null === $actor = QubitActor::getByAuthorizedFormOfName($name, ['repositoryId' => $this->object->repository->id])
) {
// Create a new one with the new history
return $this->createActor($name, $options);
}
// Change actor history when updating a match in the same repo
if ($this->matchAndUpdate) {
$actor->history = $options['history'];
$actor->save();
return $actor;
}
// Create new actor when importing as new or deleting and replacing
return $this->createActor($name, $options);
}
/**
* Create a Qubit actor or, if one already exists, fetch it.
*
* @param string $name name of actor
* @param string $options optional data
*
* @return QubitActor created or fetched actor
*/
public static function createOrFetchActor($name, $options = [])
{
// Get actor or create a new one (don't match untitled actors).
// If the actor exists the data is not overwritten
if ('' == $name || null === $actor = QubitActor::getByAuthorizedFormOfName($name)) {
$actor = QubitFlatfileImport::createActor($name, $options);
}
return $actor;
}
/**
* Create a Qubit rights holder or, if one already exists, fetch it.
*
* @param string $name name of rights holder
*
* @return QubitRightsHolder created or fetched rights holder
*/
public function createOrFetchRightsHolder($name)
{
$query = "SELECT object.id
FROM object JOIN actor_i18n i18n
ON object.id = i18n.id
WHERE i18n.authorized_form_of_name = ?