forked from civicrm/civicrm-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DAO.php
3620 lines (3287 loc) · 111 KB
/
DAO.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
/*
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC. All rights reserved. |
| |
| This work is published under the GNU AGPLv3 license with some |
| permitted exceptions and without any warranty. For full license |
| and copyright information, see https://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* Base Database Access Object class.
*
* All DAO classes should inherit from this class.
*
* @package CRM
* @copyright CiviCRM LLC https://civicrm.org/licensing
*/
use Civi\Core\DAO\Event\PostUpdate;
use Civi\Core\DAO\Event\PreUpdate;
if (!defined('DB_DSN_MODE')) {
define('DB_DSN_MODE', 'auto');
}
require_once 'PEAR.php';
require_once 'DB/DataObject.php';
require_once 'CRM/Core/I18n.php';
/**
* Class CRM_Core_DAO
*/
class CRM_Core_DAO extends DB_DataObject {
/**
* Primary key field(s).
*
* @var string[]
*/
public static $_primaryKey = ['id'];
/**
* @return string
*/
protected function getFirstPrimaryKey(): string {
// Historically it was always 'id'. It is now the case that some entities (import entities)
// have a single key that is NOT 'id'. However, for entities that have multiple
// keys (which we support in codegen if not many other places) we return 'id'
// simply because that is what we historically did & we don't want to 'just change'
// it & break those extensions without doing the work to create an alternative.
return count($this->keys()) > 1 ? 'id' : $this->keys()[0];
}
/**
* How many times has this instance been cloned.
*
* @var int
*/
protected $resultCopies = 0;
/**
* @var null
* @deprecated
*/
public static $_nullObject = NULL;
/**
* Icon associated with this entity.
*
* @var string
*/
public static $_icon = NULL;
/**
* Field to show when displaying a record.
*
* @var string
*/
public static $_labelField = NULL;
/**
* @var array
* @deprecated
*/
public static $_nullArray = [];
public static $_dbColumnValueCache = NULL;
const NOT_NULL = 1, IS_NULL = 2,
DB_DAO_NOTNULL = 128,
VALUE_SEPARATOR = "",
BULK_INSERT_COUNT = 200,
BULK_INSERT_HIGH_COUNT = 200,
QUERY_FORMAT_WILDCARD = 1,
QUERY_FORMAT_NO_QUOTES = 2,
/**
* No serialization.
*/
SERIALIZE_NONE = 0,
/**
* Serialized string separated by and bookended with VALUE_SEPARATOR
*/
SERIALIZE_SEPARATOR_BOOKEND = 1,
/**
* @deprecated format separated by VALUE_SEPARATOR
*/
SERIALIZE_SEPARATOR_TRIMMED = 2,
/**
* Recommended serialization format
*/
SERIALIZE_JSON = 3,
/**
* @deprecated format using php serialize()
*/
SERIALIZE_PHP = 4,
/**
* Comma separated string, no quotes, no spaces
*/
SERIALIZE_COMMA = 5;
/**
* Define entities that shouldn't be created or deleted when creating/ deleting
* test objects - this prevents world regions, countries etc from being added / deleted
* @var array
*/
public static $_testEntitiesToSkip = [];
/**
* https://issues.civicrm.org/jira/browse/CRM-17748
* internal variable for DAO to hold per-query settings
* @var array
*/
protected $_options = [];
/**
* Class constructor.
*
* @return static
*/
public function __construct() {
$this->initialize();
$this->__table = $this::getLocaleTableName();
}
/**
* Returns localized title of this entity.
*
* @return string
*/
public static function getEntityTitle() {
$className = static::class;
CRM_Core_Error::deprecatedWarning("$className needs to be regenerated. Missing getEntityTitle method.");
return CRM_Core_DAO_AllCoreTables::getEntityNameForClass($className);
}
/**
* Returns user-friendly description of this entity.
*
* @return string|null
*/
public static function getEntityDescription() {
return NULL;
}
public function __clone() {
if (!empty($this->_DB_resultid)) {
$this->resultCopies++;
}
}
/**
* Class destructor.
*/
public function __destruct() {
if ($this->resultCopies === 0) {
$this->free();
}
$this->resultCopies--;
}
/**
* Returns the name of this table
*
* Name is not localized, which is generally fine because localization happens when executing the query:
* @see \CRM_Core_I18n_Schema::rewriteQuery()
*
* To get the localized name of this table,
* @see self::getLocaleTableName()
*
* @return string
*/
public static function getTableName() {
return static::$_tableName ?? NULL;
}
/**
* Returns if this table needs to be logged
*
* @return bool
*/
public function getLog() {
return static::$_log ?? FALSE;
}
/**
* Returns the list of fields that can be imported
*
* @param bool $prefix
* @return array
*/
public static function import($prefix = FALSE) {
return CRM_Core_DAO_AllCoreTables::getImports(static::class, substr(static::getTableName(), 8), $prefix);
}
/**
* Returns the list of fields that can be exported
*
* @param bool $prefix
* @return array
*/
public static function export($prefix = FALSE) {
return CRM_Core_DAO_AllCoreTables::getExports(static::class, substr(static::getTableName(), 8), $prefix);
}
/**
* Initialize the DAO object.
*
* @param string $dsn
* The database connection string.
*/
public static function init($dsn) {
Civi::$statics[__CLASS__]['init'] = 1;
$options = &PEAR::getStaticProperty('DB_DataObject', 'options');
$dsn = CRM_Utils_SQL::autoSwitchDSN($dsn);
$options['database'] = $dsn;
$options['quote_identifiers'] = TRUE;
if (CRM_Utils_SQL::isSSLDSN($dsn)) {
// There are two different options arrays.
$other_options = &PEAR::getStaticProperty('DB', 'options');
$other_options['ssl'] = TRUE;
}
if (defined('CIVICRM_DAO_DEBUG')) {
self::DebugLevel(CIVICRM_DAO_DEBUG);
}
CRM_Core_DAO::executeQuery('SET NAMES utf8mb4');
CRM_Core_DAO::executeQuery('SET @uniqueID = %1', [1 => [CRM_Utils_Request::id(), 'String']]);
}
/**
* @return DB_common
*/
public static function getConnection() {
global $_DB_DATAOBJECT;
$dao = new CRM_Core_DAO();
return $_DB_DATAOBJECT['CONNECTIONS'][$dao->_database_dsn_md5];
}
/**
* Disables usage of the ONLY_FULL_GROUP_BY Mode if necessary
*/
public static function disableFullGroupByMode() {
$currentModes = CRM_Utils_SQL::getSqlModes();
if (in_array('ONLY_FULL_GROUP_BY', $currentModes) && CRM_Utils_SQL::isGroupByModeInDefault()) {
$key = array_search('ONLY_FULL_GROUP_BY', $currentModes);
unset($currentModes[$key]);
CRM_Core_DAO::executeQuery("SET SESSION sql_mode = %1", [1 => [implode(',', $currentModes), 'String']]);
}
}
/**
* Re-enables ONLY_FULL_GROUP_BY sql_mode as necessary..
*/
public static function reenableFullGroupByMode() {
$currentModes = CRM_Utils_SQL::getSqlModes();
if (!in_array('ONLY_FULL_GROUP_BY', $currentModes) && CRM_Utils_SQL::isGroupByModeInDefault()) {
$currentModes[] = 'ONLY_FULL_GROUP_BY';
CRM_Core_DAO::executeQuery("SET SESSION sql_mode = %1", [1 => [implode(',', $currentModes), 'String']]);
}
}
/**
* @param string $fieldName
* @param $fieldDef
* @param array $params
*/
protected function assignTestFK($fieldName, $fieldDef, $params) {
$required = $fieldDef['required'] ?? NULL;
$FKClassName = $fieldDef['FKClassName'] ?? NULL;
$dbName = $fieldDef['name'];
$daoName = str_replace('_BAO_', '_DAO_', get_class($this));
// skip the FK if it is not required
// if it's contact id we should create even if not required
// we'll have a go @ fetching first though
// we WILL create campaigns though for so tests with a campaign pseudoconstant will complete
if ($FKClassName === 'CRM_Campaign_DAO_Campaign' && $daoName != $FKClassName) {
$required = TRUE;
}
if (!$required && $dbName != 'contact_id') {
$fkDAO = new $FKClassName();
if ($fkDAO->find(TRUE)) {
$this->$dbName = $fkDAO->id;
}
}
elseif (in_array($FKClassName, CRM_Core_DAO::$_testEntitiesToSkip)) {
$depObject = new $FKClassName();
$depObject->find(TRUE);
$this->$dbName = $depObject->id;
}
elseif ($daoName == 'CRM_Member_DAO_MembershipType' && $fieldName == 'member_of_contact_id') {
// FIXME: the fields() metadata is not specific enough
$depObject = CRM_Core_DAO::createTestObject($FKClassName, ['contact_type' => 'Organization']);
$this->$dbName = $depObject->id;
}
else {
//if it is required we need to generate the dependency object first
$depObject = CRM_Core_DAO::createTestObject($FKClassName, CRM_Utils_Array::value($dbName, $params, 1));
$this->$dbName = $depObject->id;
}
}
/**
* Generate and assign an arbitrary value to a field of a test object.
*
* @param string $fieldName
* @param array $fieldDef
* @param int $counter
* The globally-unique ID of the test object.
*
* @throws \CRM_Core_Exception
*/
protected function assignTestValue($fieldName, &$fieldDef, $counter) {
$dbName = $fieldDef['name'];
$daoName = get_class($this);
$handled = FALSE;
if (in_array($dbName, ['contact_sub_type', 'email_greeting_id', 'postal_greeting_id', 'addressee_id'], TRUE)) {
//coming up with a rule to set these is too complex - skip
return;
}
// Pick an option value if needed
if (!$handled && $fieldDef['type'] !== CRM_Utils_Type::T_BOOLEAN) {
$options = $daoName::buildOptions($dbName, 'create');
if ($options) {
$this->$dbName = key($options);
$handled = TRUE;
}
}
if (!$handled) {
switch ($fieldDef['type']) {
case CRM_Utils_Type::T_INT:
case CRM_Utils_Type::T_FLOAT:
case CRM_Utils_Type::T_MONEY:
if (isset($fieldDef['precision'])) {
// $object->$dbName = CRM_Utils_Number::createRandomDecimal($value['precision']);
$this->$dbName = CRM_Utils_Number::createTruncatedDecimal($counter, $fieldDef['precision']);
}
else {
$this->$dbName = $counter;
}
break;
case CRM_Utils_Type::T_BOOLEAN:
if (isset($fieldDef['default'])) {
$this->$dbName = $fieldDef['default'];
}
elseif ($fieldDef['name'] == 'is_deleted' || $fieldDef['name'] == 'is_test') {
$this->$dbName = 0;
}
else {
$this->$dbName = 1;
}
break;
case CRM_Utils_Type::T_DATE:
case CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME:
$this->$dbName = '19700101';
if ($dbName == 'end_date') {
// put this in the future
$this->$dbName = '20200101';
}
break;
case CRM_Utils_Type::T_TIMESTAMP:
$this->$dbName = '19700201000000';
break;
case CRM_Utils_Type::T_TIME:
throw new CRM_Core_Exception('T_TIME shouldn\'t be used.');
case CRM_Utils_Type::T_CCNUM:
$this->$dbName = '4111 1111 1111 1111';
break;
case CRM_Utils_Type::T_URL:
$this->$dbName = 'http://www.civicrm.org';
break;
case CRM_Utils_Type::T_STRING:
case CRM_Utils_Type::T_BLOB:
case CRM_Utils_Type::T_MEDIUMBLOB:
case CRM_Utils_Type::T_TEXT:
case CRM_Utils_Type::T_LONGTEXT:
case CRM_Utils_Type::T_EMAIL:
default:
// WAS: if (isset($value['enumValues'])) {
// TODO: see if this works with all pseudoconstants
if (isset($fieldDef['pseudoconstant'], $fieldDef['pseudoconstant']['callback'])) {
if (isset($fieldDef['default'])) {
$this->$dbName = $fieldDef['default'];
}
else {
$options = CRM_Core_PseudoConstant::get($daoName, $fieldName);
if (is_array($options)) {
$this->$dbName = $options[0] ?? NULL;
}
else {
$defaultValues = explode(',', $options);
$this->$dbName = $defaultValues[0];
}
}
}
else {
$this->$dbName = $dbName . '_' . $counter;
$maxlength = $fieldDef['maxlength'] ?? NULL;
if ($maxlength > 0 && strlen($this->$dbName) > $maxlength) {
$this->$dbName = substr($this->$dbName, 0, $fieldDef['maxlength']);
}
}
}
}
}
/**
* Reset the DAO object.
*
* DAO is kinda crappy in that there is an unwritten rule of one query per DAO.
*
* We attempt to get around this crappy restriction by resetting some of DAO's internal fields. Use this with caution
*/
public function reset() {
foreach (array_keys($this->table()) as $field) {
unset($this->$field);
}
/**
* reset the various DB_DAO structures manually
*/
$this->_query = [];
$this->whereAdd();
$this->selectAdd();
$this->joinAdd();
}
/**
* Get localized name of this table, if applicable.
*
* If this is a multi-language installation and the table has localized columns,
* will return table name with language string appended, which points to a sql view.
* Otherwise, this returns the same output as
* @see self::getTableName()
*
* @param string|null $tableName
* Unnecessary deprecated param
*
* @return string
*/
public static function getLocaleTableName($tableName = NULL) {
$tableName ??= static::getTableName();
global $dbLocale;
if ($dbLocale) {
$tables = CRM_Core_I18n_Schema::schemaStructureTables();
if (in_array($tableName, $tables)) {
return $tableName . $dbLocale;
}
}
return $tableName;
}
/**
* Execute a query by the current DAO, localizing it along the way (if needed).
*
* @param string $query
* The SQL query for execution.
* @param bool $i18nRewrite
* Whether to rewrite the query.
*
* @return object
* the current DAO object after the query execution
*/
public function query($query, $i18nRewrite = TRUE) {
// rewrite queries that should use $dbLocale-based views for multi-language installs
global $dbLocale, $_DB_DATAOBJECT;
if (empty($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5])) {
// Will force connection to be populated per CRM-20541.
new CRM_Core_DAO();
}
$conn = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
$orig_options = $conn->options;
$this->_setDBOptions($this->_options);
if ($i18nRewrite and $dbLocale) {
$query = CRM_Core_I18n_Schema::rewriteQuery($query);
}
$ret = parent::query($query);
$this->_setDBOptions($orig_options);
return $ret;
}
/**
* Initialization for all DAO objects. Since we access DB_DO programatically
* we need to set the links manually.
*/
public function initialize() {
$this->_connect();
if (empty(Civi::$statics[__CLASS__]['init'])) {
// CRM_Core_DAO::init() must be called before CRM_Core_DAO->initialize().
// This occurs very early in bootstrap - error handlers may not be wired up.
echo "Inconsistent system initialization sequence. Premature access of (" . get_class($this) . ")";
CRM_Utils_System::civiExit();
}
}
/**
* Returns primary keys (usually ['id'])
*
* @return string[]
*/
public function keys() {
return static::$_primaryKey;
}
/**
* Tells DB_DataObject which keys use autoincrement.
* 'id' is autoincrementing by default.
*
* FIXME: this should return all autoincrement keys not just the first.
*
* @return array
*/
public function sequenceKey() {
return [$this->getFirstPrimaryKey(), TRUE];
}
/**
* Returns list of FK relationships.
*
* @return CRM_Core_Reference_Basic[]
*/
public static function getReferenceColumns() {
if (!isset(Civi::$statics[static::class]['links'])) {
$links = static::createReferenceColumns(static::class);
// Add references based on field metadata
foreach (static::fields() as $field) {
if (!empty($field['FKClassName'])) {
$links[] = new CRM_Core_Reference_Basic(
static::getTableName(),
$field['name'],
CRM_Core_DAO_AllCoreTables::getTableForClass($field['FKClassName']),
$field['FKColumnName'] ?? 'id'
);
}
if (!empty($field['DFKEntityColumn'])) {
$links[] = new CRM_Core_Reference_Dynamic(
static::getTableName(),
$field['name'],
NULL,
$field['FKColumnName'] ?? 'id',
$field['DFKEntityColumn']
);
}
}
CRM_Core_DAO_AllCoreTables::invoke(static::class, 'links_callback', $links);
Civi::$statics[static::class]['links'] = $links;
}
return Civi::$statics[static::class]['links'];
}
/**
* Returns all the column names of this table.
*
*
* @return array
*/
public static function &fields() {
$result = NULL;
return $result;
}
/**
* Returns all usable fields, indexed by name.
*
* This function differs from fields() in that it indexes by name rather than unique_name.
*
* It excludes fields not added yet by pending upgrades.
* This avoids problems with trying to SELECT a field that exists in code but has not yet been added to the db.
*
* @param bool $checkPermissions
* Filter by field permissions.
* @return array
*/
public static function getSupportedFields($checkPermissions = FALSE) {
$fields = array_column((array) static::fields(), NULL, 'name');
// Exclude fields yet not added by pending upgrades
$dbVer = \CRM_Core_BAO_Domain::version();
$daoExt = static::getExtensionName();
if ($fields && $daoExt === 'civicrm' && version_compare($dbVer, \CRM_Utils_System::version()) < 0) {
$fields = array_filter($fields, function($field) use ($dbVer) {
$add = $field['add'] ?? '1.0.0';
if (substr_count($add, '.') < 2) {
$add .= '.alpha1';
}
return version_compare($dbVer, $add, '>=');
});
}
// Exclude fields the user does not have permission for
if ($checkPermissions) {
$fields = array_filter($fields, function($field) {
return empty($field['permission']) || CRM_Core_Permission::check($field['permission']);
});
}
return $fields;
}
/**
* Get name of extension in which this DAO is defined.
* @return string|null
*/
public static function getExtensionName(): ?string {
return defined(static::class . '::EXT') ? constant(static::class . '::EXT') : NULL;
}
/**
* Format field values according to fields() metadata.
*
* When fetching results from a query, every field is returned as a string.
* This function automatically converts them to the correct data type.
*
* @param array $fieldValues
* @return void
*/
public static function formatFieldValues(array &$fieldValues) {
$fields = array_column((array) static::fields(), NULL, 'name');
foreach ($fieldValues as $fieldName => $fieldValue) {
$fieldSpec = $fields[$fieldName] ?? NULL;
$fieldValues[$fieldName] = self::formatFieldValue($fieldValue, $fieldSpec);
}
}
/**
* Format a value according to field metadata.
*
* @param string|null $value
* @param array|null $fieldSpec
* @return mixed
*/
protected static function formatFieldValue($value, ?array $fieldSpec) {
// DAO queries return `null` db values as empty string
if ($value === '' && empty($fieldSpec['required'])) {
return NULL;
}
if (!isset($value) || !isset($fieldSpec)) {
return $value;
}
$dataType = $fieldSpec['type'] ?? NULL;
if ($dataType === CRM_Utils_Type::T_INT) {
return (int) $value;
}
if ($dataType === CRM_Utils_Type::T_BOOLEAN) {
return (bool) $value;
}
if (!empty($fieldSpec['serialize'])) {
return self::unSerializeField($value, $fieldSpec['serialize']);
}
return $value;
}
/**
* Get/set an associative array of table columns
*
* @return array
* (associative)
*/
public function table() {
$fields = $this->fields();
$table = [];
if ($fields) {
foreach ($fields as $name => $value) {
$table[$value['name']] = $value['type'];
if (!empty($value['required'])) {
$table[$value['name']] += self::DB_DAO_NOTNULL;
}
}
}
return $table;
}
/**
* Save DAO object.
*
* @param bool $hook
*
* @return CRM_Core_DAO
*/
public function save($hook = TRUE) {
$eventID = uniqid();
$primaryField = $this->getFirstPrimaryKey();
if (!empty($this->$primaryField)) {
if ($hook) {
$preEvent = new PreUpdate($this);
$preEvent->eventID = $eventID;
\Civi::dispatcher()->dispatch('civi.dao.preUpdate', $preEvent);
}
$result = $this->update();
if ($hook) {
$event = new PostUpdate($this, $result);
$event->eventID = $eventID;
\Civi::dispatcher()->dispatch('civi.dao.postUpdate', $event);
}
$this->clearDbColumnValueCache();
}
else {
if ($hook) {
$preEvent = new PreUpdate($this);
$preEvent->eventID = $eventID;
\Civi::dispatcher()->dispatch("civi.dao.preInsert", $preEvent);
}
$result = $this->insert();
if ($hook) {
$event = new PostUpdate($this, $result);
$event->eventID = $eventID;
\Civi::dispatcher()->dispatch("civi.dao.postInsert", $event);
}
}
$this->free();
if ($hook) {
CRM_Utils_Hook::postSave($this);
}
return $this;
}
/**
* Deletes items from table which match current objects variables.
*
* Returns the true on success
*
* for example
*
* Designed to be extended
*
* $object = new mytable();
* $object->ID=123;
* echo $object->delete(); // builds a conditon
*
* $object = new mytable();
* $object->whereAdd('age > 12');
* $object->limit(1);
* $object->orderBy('age DESC');
* $object->delete(true); // dont use object vars, use the conditions, limit and order.
*
* @param bool $useWhere (optional) If DB_DATAOBJECT_WHEREADD_ONLY is passed in then
* we will build the condition only using the whereAdd's. Default is to
* build the condition only using the object parameters.
*
* @return int|false
* Int (No. of rows affected) on success, false on failure, 0 on no data affected
*/
public function delete($useWhere = FALSE) {
$preEvent = new \Civi\Core\DAO\Event\PreDelete($this);
\Civi::dispatcher()->dispatch("civi.dao.preDelete", $preEvent);
$result = parent::delete($useWhere);
$event = new \Civi\Core\DAO\Event\PostDelete($this, $result);
\Civi::dispatcher()->dispatch("civi.dao.postDelete", $event);
$this->free();
$this->clearDbColumnValueCache();
return $result;
}
/**
* @param bool $created
*/
public function log($created = FALSE) {
static $cid = NULL;
if (!$this->getLog()) {
return;
}
if (!$cid) {
$session = CRM_Core_Session::singleton();
$cid = $session->get('userID');
}
// return is we dont have handle to FK
if (!$cid) {
return;
}
$dao = new CRM_Core_DAO_Log();
$dao->entity_table = $this->getTableName();
$dao->entity_id = $this->id;
$dao->modified_id = $cid;
$dao->modified_date = date("YmdHis");
$dao->insert();
}
/**
* Given an associative array of name/value pairs, extract all the values
* that belong to this object and initialize the object with said values
*
* @param array $params
* Array of name/value pairs to save.
*
* @return bool
* Did we copy all null values into the object
*/
public function copyValues($params) {
$allNull = TRUE;
$primaryKey = $this->getFirstPrimaryKey();
foreach ($this->fields() as $uniqueName => $field) {
$dbName = $field['name'];
if (is_array($params) && array_key_exists($dbName, $params)) {
$value = $params[$dbName];
$exists = TRUE;
}
elseif (is_array($params) && array_key_exists($uniqueName, $params)) {
$value = $params[$uniqueName];
$exists = TRUE;
}
else {
$exists = FALSE;
}
// if there is no value then make the variable NULL
if ($exists) {
if ($value === '') {
if ($dbName === $primaryKey && $field['type'] === CRM_Utils_Type::T_INT) {
// See also \Civi\Api4\Utils\FormattingUtil::formatWriteParams().
// The string 'null' is used in pear::db to "unset" values, whereas
// it skips over fields where the param is real null. However
// "unsetting" a primary key doesn't make sense - you can't convert
// an existing record to a "new" one. And then having string 'null'
// in the dao object can confuse later code, in particular save()
// which then calls the update hook instead of the create hook.
$this->$dbName = NULL;
}
else {
$this->$dbName = 'null';
}
}
elseif (is_array($value) && !empty($field['serialize'])) {
if (!empty($field['pseudoconstant'])) {
// Pseudoconstant implies 1-1 option matching; duplicates would not make sense
$value = array_unique($value);
}
$this->$dbName = CRM_Core_DAO::serializeField($value, $field['serialize']);
$allNull = FALSE;
}
// When a single value was entered for a serialized field, it's probably due to sloppy coding.
// Folks, always use an array to pass in values for fields containing array data.
// Meanwhile, I'll convert it for you. You're welcome.
elseif (is_numeric($value) && !empty($field['serialize'])) {
$this->$dbName = CRM_Core_DAO::serializeField((array) $value, $field['serialize']);
$allNull = FALSE;
}
else {
$maxLength = $field['maxlength'] ?? NULL;
if (!is_array($value) && $maxLength && mb_strlen($value ?? '') > $maxLength && empty($field['pseudoconstant'])) {
// No ts() since this is a sysadmin-y string not seen by general users.
Civi::log()->warning('A string for field {dbName} has been truncated. The original string was {value}.', ['dbName' => $dbName, 'value' => $value]);
// The string is too long - what to do what to do? Well losing data is generally bad so let's truncate
$value = CRM_Utils_String::ellipsify($value, $maxLength);
}
$this->$dbName = $value;
$allNull = FALSE;
}
}
}
return $allNull;
}
/**
* Store all the values from this object in an associative array
* this is a destructive store, calling function is responsible
* for keeping sanity of id's.
*
* @param object $object
* The object that we are extracting data from.
* @param array $values
* (reference ) associative array of name/value pairs.
*/
public static function storeValues(&$object, &$values) {
$fields = $object->fields();
foreach ($fields as $name => $value) {
$dbName = $value['name'];
if (isset($object->$dbName) && $object->$dbName !== 'null') {
$values[$dbName] = $object->$dbName;
if ($name != $dbName) {
$values[$name] = $object->$dbName;
}
}
}
}
/**
* Create an attribute for this specific field. We only do this for strings and text
*
* @param array $field
* The field under task.
*
* @return array|null
* the attributes for the object
*/
public static function makeAttribute($field) {
if ($field) {
if (($field['type'] ?? NULL) == CRM_Utils_Type::T_STRING) {
$maxLength = $field['maxlength'] ?? NULL;
$size = $field['size'] ?? NULL;
if ($maxLength || $size) {
$attributes = [];
if ($maxLength) {
$attributes['maxlength'] = $maxLength;
}
if ($size) {
$attributes['size'] = $size;
}
return $attributes;
}
}
elseif (($field['type'] ?? NULL) == CRM_Utils_Type::T_TEXT) {
$rows = $field['rows'] ?? NULL;
if (!isset($rows)) {
$rows = 2;
}
$cols = $field['cols'] ?? NULL;
if (!isset($cols)) {
$cols = 80;
}
$attributes = [];
$attributes['rows'] = $rows;
$attributes['cols'] = $cols;
return $attributes;
}
elseif (($field['type'] ?? NULL) == CRM_Utils_Type::T_INT || ($field['type'] ?? NULL) == CRM_Utils_Type::T_FLOAT || ($field['type'] ?? NULL) == CRM_Utils_Type::T_MONEY) {
$attributes['size'] = 6;
$attributes['maxlength'] = 14;
return $attributes;
}
}
return NULL;
}
/**
* Get the size and maxLength attributes for this text field.
* (or for all text fields) in the DAO object.
*
* @param string $class
* Name of DAO class.
* @param string $fieldName
* Field that i'm interested in or null if.
* you want the attributes for all DAO text fields
*
* @return array
* assoc array of name => attribute pairs
*/
public static function getAttribute($class, $fieldName = NULL) {
$object = new $class();
$fields = $object->fields();
if ($fieldName != NULL) {
$field = $fields[$fieldName] ?? NULL;
return self::makeAttribute($field);
}
else {