-
-
Notifications
You must be signed in to change notification settings - Fork 824
/
Copy pathDAO.php
3072 lines (2783 loc) · 89.1 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
*/
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 {
/**
* 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;
/**
* @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,
/**
* 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 = [];
/**
* The factory class for this application.
* @var object
*/
public static $_factory = NULL;
public static $_checkedSqlFunctionsExist = FALSE;
/**
* https://issues.civicrm.org/jira/browse/CRM-17748
* internal variable for DAO to hold per-query settings
* @var array
*/
protected $_options = [];
/**
* Class constructor.
*
* @return \CRM_Core_DAO
*/
public function __construct() {
$this->initialize();
$this->__table = $this->getTableName();
}
/**
* Returns localized title of this entity.
* @return string
*/
public static function getEntityTitle() {
$className = static::class;
Civi::log()->warning("$className needs to be regeneraged. Missing getEntityTitle method.", ['civi.tag' => 'deprecated']);
return CRM_Core_DAO_AllCoreTables::getBriefName($className);
}
public function __clone() {
if (!empty($this->_DB_resultid)) {
$this->resultCopies++;
}
}
/**
* Class destructor.
*/
public function __destruct() {
if ($this->resultCopies === 0) {
$this->free();
}
$this->resultCopies--;
}
/**
* Empty definition for virtual function.
*/
public static function getTableName() {
return NULL;
}
/**
* 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');
$options['database'] = $dsn;
$options['quote_identifiers'] = TRUE;
if (defined('CIVICRM_DAO_DEBUG')) {
self::DebugLevel(CIVICRM_DAO_DEBUG);
}
$factory = new CRM_Contact_DAO_Factory();
CRM_Core_DAO::setFactory($factory);
$currentModes = CRM_Utils_SQL::getSqlModes();
if (CRM_Utils_Constant::value('CIVICRM_MYSQL_STRICT', CRM_Utils_System::isDevelopment())) {
if (CRM_Utils_SQL::supportsFullGroupBy() && !in_array('ONLY_FULL_GROUP_BY', $currentModes) && CRM_Utils_SQL::isGroupByModeInDefault()) {
$currentModes[] = 'ONLY_FULL_GROUP_BY';
}
if (!in_array('STRICT_TRANS_TABLES', $currentModes)) {
$currentModes = array_merge(['STRICT_TRANS_TABLES'], $currentModes);
}
CRM_Core_DAO::executeQuery("SET SESSION sql_mode = %1", [1 => [implode(',', $currentModes), 'String']]);
}
CRM_Core_DAO::executeQuery('SET NAMES utf8');
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 (!$handled && $dbName == 'contact_sub_type') {
//coming up with a rule to set this is too complex let's not set it
$handled = TRUE;
}
// 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];
}
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();
}
/**
* @param string $tableName
*
* @return string
*/
public static function getLocaleTableName($tableName) {
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;
}
/**
* Static function to set the factory instance for this class.
*
* @param object $factory
* The factory application object.
*/
public static function setFactory(&$factory) {
self::$_factory = &$factory;
}
/**
* Factory method to instantiate a new object from a table name.
*
* @param string $table
* @return \DataObject|\PEAR_Error
*/
public function factory($table = '') {
if (!isset(self::$_factory)) {
return parent::factory($table);
}
return self::$_factory->create($table);
}
/**
* 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();
}
}
/**
* Defines the default key as 'id'.
*
* @return array
*/
public function keys() {
static $keys;
if (!isset($keys)) {
$keys = ['id'];
}
return $keys;
}
/**
* Tells DB_DataObject which keys use autoincrement.
* 'id' is autoincrementing by default.
*
*
* @return array
*/
public function sequenceKey() {
static $sequenceKeys;
if (!isset($sequenceKeys)) {
$sequenceKeys = ['id', TRUE];
}
return $sequenceKeys;
}
/**
* Returns list of FK relationships.
*
*
* @return array
* Array of CRM_Core_Reference_Interface
*/
public static function getReferenceColumns() {
return [];
}
/**
* Returns all the column names of this table.
*
*
* @return array
*/
public static function &fields() {
$result = NULL;
return $result;
}
/**
* 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) {
if (!empty($this->id)) {
if ($hook) {
$preEvent = new \Civi\Core\DAO\Event\PreUpdate($this);
\Civi::dispatcher()->dispatch("civi.dao.preUpdate", $preEvent);
}
$result = $this->update();
if ($hook) {
$event = new \Civi\Core\DAO\Event\PostUpdate($this, $result);
\Civi::dispatcher()->dispatch("civi.dao.postUpdate", $event);
}
$this->clearDbColumnValueCache();
}
else {
if ($hook) {
$preEvent = new \Civi\Core\DAO\Event\PreUpdate($this);
\Civi::dispatcher()->dispatch("civi.dao.preInsert", $preEvent);
}
$result = $this->insert();
if ($hook) {
$event = new \Civi\Core\DAO\Event\PostUpdate($this, $result);
\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 mixed 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;
foreach ($this->fields() as $uniqueName => $field) {
$dbName = $field['name'];
if (array_key_exists($dbName, $params)) {
$value = $params[$dbName];
$exists = TRUE;
}
elseif (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 === '') {
$this->$dbName = 'null';
}
elseif (is_array($value) && !empty($field['serialize'])) {
$this->$dbName = CRM_Core_DAO::serializeField($value, $field['serialize']);
$allNull = FALSE;
}
else {
$maxLength = $field['maxlength'] ?? NULL;
if (!is_array($value) && $maxLength && mb_strlen($value) > $maxLength && empty($field['pseudoconstant'])) {
Civi::log()->warning(ts('A string for field $dbName has been truncated. The original string was %1', [CRM_Utils_Type::escape($value, 'String')]));
// The string is too long - what to do what to do? Well losing data is generally bad so lets' 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 (CRM_Utils_Array::value('type', $field) == 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 (CRM_Utils_Array::value('type', $field) == 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 (CRM_Utils_Array::value('type', $field) == CRM_Utils_Type::T_INT || CRM_Utils_Array::value('type', $field) == CRM_Utils_Type::T_FLOAT || CRM_Utils_Array::value('type', $field) == 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 {
$attributes = [];
foreach ($fields as $name => $field) {
$attribute = self::makeAttribute($field);
if ($attribute) {
$attributes[$name] = $attribute;
}
}
if (!empty($attributes)) {
return $attributes;
}
}
return NULL;
}
/**
* Create or update a record from supplied params.
*
* If 'id' is supplied, an existing record will be updated
* Otherwise a new record will be created.
*
* @param array $record
* @return CRM_Core_DAO
* @throws CRM_Core_Exception
*/
public static function writeRecord(array $record) {
$hook = empty($record['id']) ? 'create' : 'edit';
$className = CRM_Core_DAO_AllCoreTables::getCanonicalClassName(static::class);
if ($className === 'CRM_Core_DAO') {
throw new CRM_Core_Exception('Function writeRecord must be called on a subclass of CRM_Core_DAO');
}
$entityName = CRM_Core_DAO_AllCoreTables::getBriefName($className);
\CRM_Utils_Hook::pre($hook, $entityName, $record['id'] ?? NULL, $record);
$instance = new $className();
$instance->copyValues($record);
$instance->save();
\CRM_Utils_Hook::post($hook, $entityName, $instance->id, $instance);
return $instance;
}
/**
* Delete a record from supplied params.
*
* @param array $record
* 'id' is required.
* @return CRM_Core_DAO
* @throws CRM_Core_Exception
*/
public static function deleteRecord(array $record) {
$className = CRM_Core_DAO_AllCoreTables::getCanonicalClassName(static::class);
if ($className === 'CRM_Core_DAO') {
throw new CRM_Core_Exception('Function deleteRecord must be called on a subclass of CRM_Core_DAO');
}
$entityName = CRM_Core_DAO_AllCoreTables::getBriefName($className);
if (empty($record['id'])) {
throw new CRM_Core_Exception("Cannot delete {$entityName} with no id.");
}
CRM_Utils_Hook::pre('delete', $entityName, $record['id'], $record);
$instance = new $className();
$instance->id = $record['id'];
if (!$instance->delete()) {
throw new CRM_Core_Exception("Could not delete {$entityName} id {$record['id']}");
}
CRM_Utils_Hook::post('delete', $entityName, $record['id'], $instance);
return $instance;
}
/**
* Check if there is a record with the same name in the db.
*
* @param string $value
* The value of the field we are checking.
* @param string $daoName
* The dao object name.
* @param string $daoID
* The id of the object being updated. u can change your name.
* as long as there is no conflict
* @param string $fieldName
* The name of the field in the DAO.
*
* @param string $domainID
* The id of the domain. Object exists only for the given domain.
*
* @return bool
* true if object exists
*/
public static function objectExists($value, $daoName, $daoID, $fieldName = 'name', $domainID = NULL) {
$object = new $daoName();
$object->$fieldName = $value;
if ($domainID) {
$object->domain_id = $domainID;
}
if ($object->find(TRUE)) {
return $daoID && $object->id == $daoID;
}
else {
return TRUE;
}
}
/**
* Check if there is a given column in a specific table.
*
* @deprecated
* @see CRM_Core_BAO_SchemaHandler::checkIfFieldExists
*
* @param string $tableName
* @param string $columnName
* @param bool $i18nRewrite
* Whether to rewrite the query on multilingual setups.
*
* @return bool
* true if exists, else false
*/
public static function checkFieldExists($tableName, $columnName, $i18nRewrite = TRUE) {
return CRM_Core_BAO_SchemaHandler::checkIfFieldExists($tableName, $columnName, $i18nRewrite);
}
/**
* Scans all the tables using a slow query and table name.
*
* @return array
*/
public static function getTableNames() {
$dao = CRM_Core_DAO::executeQuery(
"SELECT TABLE_NAME
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = '" . CRM_Core_DAO::getDatabaseName() . "'
AND TABLE_NAME LIKE 'civicrm_%'
AND TABLE_NAME NOT LIKE 'civicrm_import_job_%'
AND TABLE_NAME NOT LIKE '%_temp%'
");
while ($dao->fetch()) {
$values[] = $dao->TABLE_NAME;
}
return $values;
}
/**
* @param int $maxTablesToCheck
*
* @return bool
*/
public static function isDBMyISAM($maxTablesToCheck = 10) {
return CRM_Core_DAO::singleValueQuery(
"SELECT count(*)
FROM information_schema.TABLES
WHERE ENGINE = 'MyISAM'
AND TABLE_SCHEMA = '" . CRM_Core_DAO::getDatabaseName() . "'
AND TABLE_NAME LIKE 'civicrm_%'
AND TABLE_NAME NOT LIKE 'civicrm_import_job_%'
AND TABLE_NAME NOT LIKE '%_temp%'
AND TABLE_NAME NOT LIKE 'civicrm_tmp_%'
");
}
/**
* Get the name of the CiviCRM database.
*
* @return string
*/
public static function getDatabaseName() {
$daoObj = new CRM_Core_DAO();
return $daoObj->database();
}
/**
* Checks if a constraint exists for a specified table.
*
* @param string $tableName
* @param string $constraint
*
* @return bool
* true if constraint exists, false otherwise
*
* @throws \CRM_Core_Exception
*/
public static function checkConstraintExists($tableName, $constraint) {
static $show = [];
if (!array_key_exists($tableName, $show)) {
$query = "SHOW CREATE TABLE $tableName";
$dao = CRM_Core_DAO::executeQuery($query, [], TRUE, NULL, FALSE, FALSE);
if (!$dao->fetch()) {