Commit | Line | Data |
---|---|---|
6a488035 TO |
1 | <?php |
2 | /* | |
bc77d7c0 TO |
3 | +--------------------------------------------------------------------+ |
4 | | Copyright CiviCRM LLC. All rights reserved. | | |
5 | | | | |
6 | | This work is published under the GNU AGPLv3 license with some | | |
7 | | permitted exceptions and without any warranty. For full license | | |
8 | | and copyright information, see https://civicrm.org/licensing | | |
9 | +--------------------------------------------------------------------+ | |
ced9bfed | 10 | */ |
6a488035 TO |
11 | |
12 | /** | |
44ce4aa3 CW |
13 | * Base Database Access Object class. |
14 | * | |
15 | * All DAO classes should inherit from this class. | |
6a488035 TO |
16 | * |
17 | * @package CRM | |
ca5cec67 | 18 | * @copyright CiviCRM LLC https://civicrm.org/licensing |
6a488035 TO |
19 | */ |
20 | ||
b3029f89 SL |
21 | if (!defined('DB_DSN_MODE')) { |
22 | define('DB_DSN_MODE', 'auto'); | |
23 | } | |
24 | ||
6a488035 TO |
25 | require_once 'PEAR.php'; |
26 | require_once 'DB/DataObject.php'; | |
27 | ||
28 | require_once 'CRM/Core/I18n.php'; | |
28518c90 EM |
29 | |
30 | /** | |
31 | * Class CRM_Core_DAO | |
32 | */ | |
6a488035 TO |
33 | class CRM_Core_DAO extends DB_DataObject { |
34 | ||
ffcc1d11 | 35 | /** |
36 | * How many times has this instance been cloned. | |
37 | * | |
38 | * @var int | |
39 | */ | |
40 | protected $resultCopies = 0; | |
41 | ||
6a488035 | 42 | /** |
1273d77c CW |
43 | * @var null |
44 | * @deprecated | |
6a488035 | 45 | */ |
518fa0ee | 46 | public static $_nullObject = NULL; |
449c4e6b CW |
47 | |
48 | /** | |
49 | * Icon associated with this entity. | |
50 | * | |
51 | * @var string | |
52 | */ | |
53 | public static $_icon = NULL; | |
54 | ||
1273d77c CW |
55 | /** |
56 | * @var array | |
57 | * @deprecated | |
58 | */ | |
518fa0ee | 59 | public static $_nullArray = []; |
6a488035 | 60 | |
518fa0ee | 61 | public static $_dbColumnValueCache = NULL; |
7da04cde | 62 | const NOT_NULL = 1, IS_NULL = 2, |
353ffa53 TO |
63 | DB_DAO_NOTNULL = 128, |
64 | VALUE_SEPARATOR = "\ 1", | |
65 | BULK_INSERT_COUNT = 200, | |
66 | BULK_INSERT_HIGH_COUNT = 200, | |
353ffa53 | 67 | QUERY_FORMAT_WILDCARD = 1, |
2a5c9b4d | 68 | QUERY_FORMAT_NO_QUOTES = 2, |
168c8704 CW |
69 | |
70 | /** | |
71 | * Serialized string separated by and bookended with VALUE_SEPARATOR | |
72 | */ | |
2a5c9b4d | 73 | SERIALIZE_SEPARATOR_BOOKEND = 1, |
168c8704 CW |
74 | /** |
75 | * @deprecated format separated by VALUE_SEPARATOR | |
76 | */ | |
2a5c9b4d | 77 | SERIALIZE_SEPARATOR_TRIMMED = 2, |
168c8704 CW |
78 | /** |
79 | * Recommended serialization format | |
80 | */ | |
81 | SERIALIZE_JSON = 3, | |
82 | /** | |
83 | * @deprecated format using php serialize() | |
84 | */ | |
dd3ec98b CW |
85 | SERIALIZE_PHP = 4, |
86 | /** | |
87 | * Comma separated string, no quotes, no spaces | |
88 | */ | |
89 | SERIALIZE_COMMA = 5; | |
887a4028 | 90 | |
d424ffde | 91 | /** |
6a488035 | 92 | * Define entities that shouldn't be created or deleted when creating/ deleting |
d424ffde CW |
93 | * test objects - this prevents world regions, countries etc from being added / deleted |
94 | * @var array | |
6a488035 | 95 | */ |
518fa0ee | 96 | public static $_testEntitiesToSkip = []; |
6a488035 | 97 | /** |
fe482240 | 98 | * The factory class for this application. |
6a488035 TO |
99 | * @var object |
100 | */ | |
518fa0ee | 101 | public static $_factory = NULL; |
6a488035 | 102 | |
518fa0ee | 103 | public static $_checkedSqlFunctionsExist = FALSE; |
aca2de91 | 104 | |
33092c89 SB |
105 | /** |
106 | * https://issues.civicrm.org/jira/browse/CRM-17748 | |
107 | * internal variable for DAO to hold per-query settings | |
518fa0ee | 108 | * @var array |
33092c89 | 109 | */ |
be2fb01f | 110 | protected $_options = []; |
33092c89 | 111 | |
6a488035 | 112 | /** |
fe482240 | 113 | * Class constructor. |
6a488035 | 114 | * |
77b97be7 | 115 | * @return \CRM_Core_DAO |
6a488035 | 116 | */ |
00be9182 | 117 | public function __construct() { |
6a488035 TO |
118 | $this->initialize(); |
119 | $this->__table = $this->getTableName(); | |
120 | } | |
121 | ||
449c4e6b CW |
122 | /** |
123 | * Returns localized title of this entity. | |
124 | * @return string | |
125 | */ | |
126 | public static function getEntityTitle() { | |
127 | $className = static::class; | |
128 | Civi::log()->warning("$className needs to be regeneraged. Missing getEntityTitle method.", ['civi.tag' => 'deprecated']); | |
129 | return CRM_Core_DAO_AllCoreTables::getBriefName($className); | |
130 | } | |
131 | ||
ffcc1d11 | 132 | public function __clone() { |
133 | if (!empty($this->_DB_resultid)) { | |
134 | $this->resultCopies++; | |
135 | } | |
136 | } | |
137 | ||
138 | /** | |
139 | * Class destructor. | |
140 | */ | |
141 | public function __destruct() { | |
142 | if ($this->resultCopies === 0) { | |
143 | $this->free(); | |
144 | } | |
145 | $this->resultCopies--; | |
146 | } | |
147 | ||
6a488035 | 148 | /** |
fe482240 | 149 | * Empty definition for virtual function. |
6a488035 | 150 | */ |
00be9182 | 151 | public static function getTableName() { |
6a488035 TO |
152 | return NULL; |
153 | } | |
154 | ||
155 | /** | |
fe482240 | 156 | * Initialize the DAO object. |
6a488035 | 157 | * |
6a0b768e TO |
158 | * @param string $dsn |
159 | * The database connection string. | |
6a488035 | 160 | */ |
00be9182 | 161 | public static function init($dsn) { |
3a036b15 | 162 | Civi::$statics[__CLASS__]['init'] = 1; |
6a488035 | 163 | $options = &PEAR::getStaticProperty('DB_DataObject', 'options'); |
58d1e21e | 164 | $dsn = CRM_Utils_SQL::autoSwitchDSN($dsn); |
6a488035 | 165 | $options['database'] = $dsn; |
078428c7 | 166 | $options['quote_identifiers'] = TRUE; |
fa1e300b | 167 | if (CRM_Utils_SQL::isSSLDSN($dsn)) { |
6f738dbf | 168 | // There are two different options arrays. |
169 | $other_options = &PEAR::getStaticProperty('DB', 'options'); | |
170 | $other_options['ssl'] = TRUE; | |
171 | } | |
6a488035 TO |
172 | if (defined('CIVICRM_DAO_DEBUG')) { |
173 | self::DebugLevel(CIVICRM_DAO_DEBUG); | |
174 | } | |
f720cdf0 | 175 | $factory = new CRM_Contact_DAO_Factory(); |
176 | CRM_Core_DAO::setFactory($factory); | |
712e729f | 177 | $currentModes = CRM_Utils_SQL::getSqlModes(); |
635f0b86 | 178 | if (CRM_Utils_Constant::value('CIVICRM_MYSQL_STRICT', CRM_Utils_System::isDevelopment())) { |
a2ed62b3 | 179 | if (CRM_Utils_SQL::supportsFullGroupBy() && !in_array('ONLY_FULL_GROUP_BY', $currentModes) && CRM_Utils_SQL::isGroupByModeInDefault()) { |
403b1c11 SL |
180 | $currentModes[] = 'ONLY_FULL_GROUP_BY'; |
181 | } | |
907995af | 182 | if (!in_array('STRICT_TRANS_TABLES', $currentModes)) { |
be2fb01f | 183 | $currentModes = array_merge(['STRICT_TRANS_TABLES'], $currentModes); |
9b065dcf | 184 | } |
be2fb01f | 185 | CRM_Core_DAO::executeQuery("SET SESSION sql_mode = %1", [1 => [implode(',', $currentModes), 'String']]); |
635f0b86 | 186 | } |
d10ba6cb | 187 | CRM_Core_DAO::executeQuery('SET NAMES utf8mb4'); |
be2fb01f | 188 | CRM_Core_DAO::executeQuery('SET @uniqueID = %1', [1 => [CRM_Utils_Request::id(), 'String']]); |
6a488035 TO |
189 | } |
190 | ||
e95fbe72 TO |
191 | /** |
192 | * @return DB_common | |
193 | */ | |
194 | public static function getConnection() { | |
195 | global $_DB_DATAOBJECT; | |
196 | $dao = new CRM_Core_DAO(); | |
197 | return $_DB_DATAOBJECT['CONNECTIONS'][$dao->_database_dsn_md5]; | |
198 | } | |
199 | ||
84cb7d10 SL |
200 | /** |
201 | * Disables usage of the ONLY_FULL_GROUP_BY Mode if necessary | |
202 | */ | |
203 | public static function disableFullGroupByMode() { | |
204 | $currentModes = CRM_Utils_SQL::getSqlModes(); | |
63dc1f23 | 205 | if (in_array('ONLY_FULL_GROUP_BY', $currentModes) && CRM_Utils_SQL::isGroupByModeInDefault()) { |
84cb7d10 SL |
206 | $key = array_search('ONLY_FULL_GROUP_BY', $currentModes); |
207 | unset($currentModes[$key]); | |
be2fb01f | 208 | CRM_Core_DAO::executeQuery("SET SESSION sql_mode = %1", [1 => [implode(',', $currentModes), 'String']]); |
84cb7d10 SL |
209 | } |
210 | } | |
211 | ||
212 | /** | |
2f68ef20 | 213 | * Re-enables ONLY_FULL_GROUP_BY sql_mode as necessary.. |
84cb7d10 | 214 | */ |
2f68ef20 | 215 | public static function reenableFullGroupByMode() { |
84cb7d10 | 216 | $currentModes = CRM_Utils_SQL::getSqlModes(); |
63dc1f23 | 217 | if (!in_array('ONLY_FULL_GROUP_BY', $currentModes) && CRM_Utils_SQL::isGroupByModeInDefault()) { |
84cb7d10 | 218 | $currentModes[] = 'ONLY_FULL_GROUP_BY'; |
be2fb01f | 219 | CRM_Core_DAO::executeQuery("SET SESSION sql_mode = %1", [1 => [implode(',', $currentModes), 'String']]); |
84cb7d10 SL |
220 | } |
221 | } | |
222 | ||
e1b64aab | 223 | /** |
100fef9d | 224 | * @param string $fieldName |
e1b64aab | 225 | * @param $fieldDef |
c490a46a | 226 | * @param array $params |
e1b64aab | 227 | */ |
e79cd558 | 228 | protected function assignTestFK($fieldName, $fieldDef, $params) { |
9c1bc317 CW |
229 | $required = $fieldDef['required'] ?? NULL; |
230 | $FKClassName = $fieldDef['FKClassName'] ?? NULL; | |
e1b64aab | 231 | $dbName = $fieldDef['name']; |
2444854d | 232 | $daoName = str_replace('_BAO_', '_DAO_', get_class($this)); |
e1b64aab TO |
233 | |
234 | // skip the FK if it is not required | |
235 | // if it's contact id we should create even if not required | |
236 | // we'll have a go @ fetching first though | |
237 | // we WILL create campaigns though for so tests with a campaign pseudoconstant will complete | |
238 | if ($FKClassName === 'CRM_Campaign_DAO_Campaign' && $daoName != $FKClassName) { | |
239 | $required = TRUE; | |
240 | } | |
241 | if (!$required && $dbName != 'contact_id') { | |
795492f3 | 242 | $fkDAO = new $FKClassName(); |
e1b64aab | 243 | if ($fkDAO->find(TRUE)) { |
e79cd558 | 244 | $this->$dbName = $fkDAO->id; |
e1b64aab | 245 | } |
e1b64aab TO |
246 | } |
247 | ||
248 | elseif (in_array($FKClassName, CRM_Core_DAO::$_testEntitiesToSkip)) { | |
249 | $depObject = new $FKClassName(); | |
250 | $depObject->find(TRUE); | |
e79cd558 | 251 | $this->$dbName = $depObject->id; |
e1b64aab TO |
252 | } |
253 | elseif ($daoName == 'CRM_Member_DAO_MembershipType' && $fieldName == 'member_of_contact_id') { | |
254 | // FIXME: the fields() metadata is not specific enough | |
be2fb01f | 255 | $depObject = CRM_Core_DAO::createTestObject($FKClassName, ['contact_type' => 'Organization']); |
e79cd558 | 256 | $this->$dbName = $depObject->id; |
e1b64aab TO |
257 | } |
258 | else { | |
259 | //if it is required we need to generate the dependency object first | |
260 | $depObject = CRM_Core_DAO::createTestObject($FKClassName, CRM_Utils_Array::value($dbName, $params, 1)); | |
e79cd558 | 261 | $this->$dbName = $depObject->id; |
e1b64aab TO |
262 | } |
263 | } | |
264 | ||
265 | /** | |
e79cd558 TO |
266 | * Generate and assign an arbitrary value to a field of a test object. |
267 | * | |
268 | * @param string $fieldName | |
269 | * @param array $fieldDef | |
6a0b768e TO |
270 | * @param int $counter |
271 | * The globally-unique ID of the test object. | |
7c58994a | 272 | * |
273 | * @throws \CRM_Core_Exception | |
e1b64aab | 274 | */ |
e79cd558 TO |
275 | protected function assignTestValue($fieldName, &$fieldDef, $counter) { |
276 | $dbName = $fieldDef['name']; | |
277 | $daoName = get_class($this); | |
e1b64aab TO |
278 | $handled = FALSE; |
279 | ||
e79cd558 | 280 | if (!$handled && $dbName == 'contact_sub_type') { |
e1b64aab TO |
281 | //coming up with a rule to set this is too complex let's not set it |
282 | $handled = TRUE; | |
283 | } | |
284 | ||
285 | // Pick an option value if needed | |
286 | if (!$handled && $fieldDef['type'] !== CRM_Utils_Type::T_BOOLEAN) { | |
287 | $options = $daoName::buildOptions($dbName, 'create'); | |
288 | if ($options) { | |
e79cd558 | 289 | $this->$dbName = key($options); |
e1b64aab TO |
290 | $handled = TRUE; |
291 | } | |
292 | } | |
293 | ||
294 | if (!$handled) { | |
295 | switch ($fieldDef['type']) { | |
296 | case CRM_Utils_Type::T_INT: | |
297 | case CRM_Utils_Type::T_FLOAT: | |
298 | case CRM_Utils_Type::T_MONEY: | |
299 | if (isset($fieldDef['precision'])) { | |
300 | // $object->$dbName = CRM_Utils_Number::createRandomDecimal($value['precision']); | |
e79cd558 | 301 | $this->$dbName = CRM_Utils_Number::createTruncatedDecimal($counter, $fieldDef['precision']); |
e1b64aab TO |
302 | } |
303 | else { | |
e79cd558 | 304 | $this->$dbName = $counter; |
e1b64aab TO |
305 | } |
306 | break; | |
307 | ||
308 | case CRM_Utils_Type::T_BOOLEAN: | |
309 | if (isset($fieldDef['default'])) { | |
e79cd558 | 310 | $this->$dbName = $fieldDef['default']; |
e1b64aab TO |
311 | } |
312 | elseif ($fieldDef['name'] == 'is_deleted' || $fieldDef['name'] == 'is_test') { | |
e79cd558 | 313 | $this->$dbName = 0; |
e1b64aab TO |
314 | } |
315 | else { | |
e79cd558 | 316 | $this->$dbName = 1; |
e1b64aab TO |
317 | } |
318 | break; | |
319 | ||
320 | case CRM_Utils_Type::T_DATE: | |
e1b64aab | 321 | case CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME: |
e79cd558 | 322 | $this->$dbName = '19700101'; |
e1b64aab TO |
323 | if ($dbName == 'end_date') { |
324 | // put this in the future | |
e79cd558 | 325 | $this->$dbName = '20200101'; |
e1b64aab TO |
326 | } |
327 | break; | |
328 | ||
2149f4bd | 329 | case CRM_Utils_Type::T_TIMESTAMP: |
330 | $this->$dbName = '19700201000000'; | |
331 | break; | |
332 | ||
e1b64aab | 333 | case CRM_Utils_Type::T_TIME: |
7c58994a | 334 | throw new CRM_Core_Exception('T_TIME shouldn\'t be used.'); |
335 | ||
e1b64aab | 336 | case CRM_Utils_Type::T_CCNUM: |
e79cd558 | 337 | $this->$dbName = '4111 1111 1111 1111'; |
e1b64aab TO |
338 | break; |
339 | ||
340 | case CRM_Utils_Type::T_URL: | |
e79cd558 | 341 | $this->$dbName = 'http://www.civicrm.org'; |
e1b64aab TO |
342 | break; |
343 | ||
344 | case CRM_Utils_Type::T_STRING: | |
345 | case CRM_Utils_Type::T_BLOB: | |
346 | case CRM_Utils_Type::T_MEDIUMBLOB: | |
347 | case CRM_Utils_Type::T_TEXT: | |
348 | case CRM_Utils_Type::T_LONGTEXT: | |
349 | case CRM_Utils_Type::T_EMAIL: | |
350 | default: | |
351 | // WAS: if (isset($value['enumValues'])) { | |
352 | // TODO: see if this works with all pseudoconstants | |
353 | if (isset($fieldDef['pseudoconstant'], $fieldDef['pseudoconstant']['callback'])) { | |
354 | if (isset($fieldDef['default'])) { | |
e79cd558 | 355 | $this->$dbName = $fieldDef['default']; |
e1b64aab TO |
356 | } |
357 | else { | |
358 | $options = CRM_Core_PseudoConstant::get($daoName, $fieldName); | |
359 | if (is_array($options)) { | |
e79cd558 | 360 | $this->$dbName = $options[0]; |
e1b64aab TO |
361 | } |
362 | else { | |
363 | $defaultValues = explode(',', $options); | |
e79cd558 | 364 | $this->$dbName = $defaultValues[0]; |
e1b64aab TO |
365 | } |
366 | } | |
367 | } | |
368 | else { | |
e79cd558 | 369 | $this->$dbName = $dbName . '_' . $counter; |
9c1bc317 | 370 | $maxlength = $fieldDef['maxlength'] ?? NULL; |
e79cd558 TO |
371 | if ($maxlength > 0 && strlen($this->$dbName) > $maxlength) { |
372 | $this->$dbName = substr($this->$dbName, 0, $fieldDef['maxlength']); | |
e1b64aab TO |
373 | } |
374 | } | |
375 | } | |
376 | } | |
377 | } | |
378 | ||
6a488035 | 379 | /** |
8eedd10a | 380 | * Reset the DAO object. |
6a488035 | 381 | * |
8eedd10a | 382 | * DAO is kinda crappy in that there is an unwritten rule of one query per DAO. |
383 | * | |
384 | * We attempt to get around this crappy restriction by resetting some of DAO's internal fields. Use this with caution | |
6a488035 | 385 | */ |
00be9182 | 386 | public function reset() { |
6a488035 TO |
387 | |
388 | foreach (array_keys($this->table()) as $field) { | |
389 | unset($this->$field); | |
390 | } | |
391 | ||
392 | /** | |
393 | * reset the various DB_DAO structures manually | |
394 | */ | |
be2fb01f | 395 | $this->_query = []; |
6a488035 TO |
396 | $this->whereAdd(); |
397 | $this->selectAdd(); | |
398 | $this->joinAdd(); | |
399 | } | |
400 | ||
a0ee3941 | 401 | /** |
100fef9d | 402 | * @param string $tableName |
a0ee3941 EM |
403 | * |
404 | * @return string | |
405 | */ | |
00be9182 | 406 | public static function getLocaleTableName($tableName) { |
6a488035 TO |
407 | global $dbLocale; |
408 | if ($dbLocale) { | |
409 | $tables = CRM_Core_I18n_Schema::schemaStructureTables(); | |
410 | if (in_array($tableName, $tables)) { | |
411 | return $tableName . $dbLocale; | |
412 | } | |
413 | } | |
414 | return $tableName; | |
415 | } | |
416 | ||
417 | /** | |
418 | * Execute a query by the current DAO, localizing it along the way (if needed). | |
419 | * | |
6a0b768e TO |
420 | * @param string $query |
421 | * The SQL query for execution. | |
422 | * @param bool $i18nRewrite | |
423 | * Whether to rewrite the query. | |
6a488035 | 424 | * |
a6c01b45 CW |
425 | * @return object |
426 | * the current DAO object after the query execution | |
6a488035 | 427 | */ |
00be9182 | 428 | public function query($query, $i18nRewrite = TRUE) { |
6a488035 | 429 | // rewrite queries that should use $dbLocale-based views for multi-language installs |
33092c89 SB |
430 | global $dbLocale, $_DB_DATAOBJECT; |
431 | ||
96f346f8 | 432 | if (empty($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5])) { |
433 | // Will force connection to be populated per CRM-20541. | |
434 | new CRM_Core_DAO(); | |
435 | } | |
436 | ||
33092c89 SB |
437 | $conn = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]; |
438 | $orig_options = $conn->options; | |
439 | $this->_setDBOptions($this->_options); | |
440 | ||
6a488035 TO |
441 | if ($i18nRewrite and $dbLocale) { |
442 | $query = CRM_Core_I18n_Schema::rewriteQuery($query); | |
443 | } | |
444 | ||
33092c89 SB |
445 | $ret = parent::query($query); |
446 | ||
447 | $this->_setDBOptions($orig_options); | |
448 | return $ret; | |
6a488035 TO |
449 | } |
450 | ||
451 | /** | |
452 | * Static function to set the factory instance for this class. | |
453 | * | |
6a0b768e TO |
454 | * @param object $factory |
455 | * The factory application object. | |
6a488035 | 456 | */ |
00be9182 | 457 | public static function setFactory(&$factory) { |
6a488035 TO |
458 | self::$_factory = &$factory; |
459 | } | |
460 | ||
461 | /** | |
462 | * Factory method to instantiate a new object from a table name. | |
463 | * | |
da6b46f4 | 464 | * @param string $table |
44ce4aa3 | 465 | * @return \DataObject|\PEAR_Error |
6a488035 | 466 | */ |
00be9182 | 467 | public function factory($table = '') { |
6a488035 TO |
468 | if (!isset(self::$_factory)) { |
469 | return parent::factory($table); | |
470 | } | |
471 | ||
472 | return self::$_factory->create($table); | |
473 | } | |
474 | ||
475 | /** | |
476 | * Initialization for all DAO objects. Since we access DB_DO programatically | |
477 | * we need to set the links manually. | |
6a488035 | 478 | */ |
00be9182 | 479 | public function initialize() { |
6a488035 | 480 | $this->_connect(); |
3a036b15 TO |
481 | if (empty(Civi::$statics[__CLASS__]['init'])) { |
482 | // CRM_Core_DAO::init() must be called before CRM_Core_DAO->initialize(). | |
483 | // This occurs very early in bootstrap - error handlers may not be wired up. | |
484 | echo "Inconsistent system initialization sequence. Premature access of (" . get_class($this) . ")"; | |
485 | CRM_Utils_System::civiExit(); | |
486 | } | |
6a488035 TO |
487 | } |
488 | ||
489 | /** | |
490 | * Defines the default key as 'id'. | |
491 | * | |
6a488035 TO |
492 | * @return array |
493 | */ | |
00be9182 | 494 | public function keys() { |
6a488035 TO |
495 | static $keys; |
496 | if (!isset($keys)) { | |
be2fb01f | 497 | $keys = ['id']; |
6a488035 TO |
498 | } |
499 | return $keys; | |
500 | } | |
501 | ||
502 | /** | |
503 | * Tells DB_DataObject which keys use autoincrement. | |
504 | * 'id' is autoincrementing by default. | |
505 | * | |
6a488035 TO |
506 | * |
507 | * @return array | |
508 | */ | |
00be9182 | 509 | public function sequenceKey() { |
6a488035 TO |
510 | static $sequenceKeys; |
511 | if (!isset($sequenceKeys)) { | |
be2fb01f | 512 | $sequenceKeys = ['id', TRUE]; |
6a488035 TO |
513 | } |
514 | return $sequenceKeys; | |
515 | } | |
516 | ||
517 | /** | |
fe482240 | 518 | * Returns list of FK relationships. |
6a488035 | 519 | * |
6a488035 | 520 | * |
a6c01b45 | 521 | * @return array |
16b10e64 | 522 | * Array of CRM_Core_Reference_Interface |
6a488035 | 523 | */ |
00be9182 | 524 | public static function getReferenceColumns() { |
be2fb01f | 525 | return []; |
6a488035 TO |
526 | } |
527 | ||
528 | /** | |
fe482240 | 529 | * Returns all the column names of this table. |
6a488035 | 530 | * |
6a488035 TO |
531 | * |
532 | * @return array | |
533 | */ | |
795492f3 | 534 | public static function &fields() { |
6a488035 TO |
535 | $result = NULL; |
536 | return $result; | |
537 | } | |
538 | ||
2ca7273b CW |
539 | /** |
540 | * Returns all usable fields, indexed by name. | |
541 | * | |
542 | * This function differs from fields() in that it indexes by name rather than unique_name. | |
543 | * | |
544 | * It excludes fields not added yet by pending upgrades. | |
545 | * This avoids problems with trying to SELECT a field that exists in code but has not yet been added to the db. | |
546 | * | |
547 | * @param bool $checkPermissions | |
548 | * Filter by field permissions. | |
549 | * @return array | |
550 | */ | |
551 | public static function getSupportedFields($checkPermissions = FALSE) { | |
552 | $fields = array_column((array) static::fields(), NULL, 'name'); | |
553 | ||
554 | // Exclude fields yet not added by pending upgrades | |
555 | $dbVer = \CRM_Core_BAO_Domain::version(); | |
633a8dbc | 556 | $daoExt = defined(static::class . '::EXT') ? constant(static::class . '::EXT') : NULL; |
9162496e | 557 | if ($fields && $daoExt === 'civicrm' && version_compare($dbVer, \CRM_Utils_System::version()) < 0) { |
2ca7273b CW |
558 | $fields = array_filter($fields, function($field) use ($dbVer) { |
559 | $add = $field['add'] ?? '1.0.0'; | |
560 | if (substr_count($add, '.') < 2) { | |
561 | $add .= '.alpha1'; | |
562 | } | |
563 | return version_compare($dbVer, $add, '>='); | |
564 | }); | |
565 | } | |
566 | ||
567 | // Exclude fields the user does not have permission for | |
568 | if ($checkPermissions) { | |
569 | $fields = array_filter($fields, function($field) { | |
570 | return empty($field['permission']) || CRM_Core_Permission::check($field['permission']); | |
571 | }); | |
572 | } | |
573 | ||
574 | return $fields; | |
575 | } | |
576 | ||
b5c2afd0 | 577 | /** |
100fef9d | 578 | * Get/set an associative array of table columns |
b5c2afd0 | 579 | * |
a6c01b45 CW |
580 | * @return array |
581 | * (associative) | |
b5c2afd0 | 582 | */ |
00be9182 | 583 | public function table() { |
44ce4aa3 | 584 | $fields = $this->fields(); |
6a488035 | 585 | |
be2fb01f | 586 | $table = []; |
6a488035 TO |
587 | if ($fields) { |
588 | foreach ($fields as $name => $value) { | |
589 | $table[$value['name']] = $value['type']; | |
a7488080 | 590 | if (!empty($value['required'])) { |
6a488035 TO |
591 | $table[$value['name']] += self::DB_DAO_NOTNULL; |
592 | } | |
593 | } | |
594 | } | |
595 | ||
6a488035 TO |
596 | return $table; |
597 | } | |
598 | ||
a0ee3941 | 599 | /** |
ea3ddccf | 600 | * Save DAO object. |
601 | * | |
602 | * @param bool $hook | |
603 | * | |
14069c56 | 604 | * @return CRM_Core_DAO |
a0ee3941 | 605 | */ |
9f35e05d | 606 | public function save($hook = TRUE) { |
6a488035 | 607 | if (!empty($this->id)) { |
e232c68f CW |
608 | if ($hook) { |
609 | $preEvent = new \Civi\Core\DAO\Event\PreUpdate($this); | |
4162ab6f | 610 | \Civi::dispatcher()->dispatch("civi.dao.preUpdate", $preEvent); |
e232c68f CW |
611 | } |
612 | ||
613 | $result = $this->update(); | |
8498c2b7 | 614 | |
9f35e05d | 615 | if ($hook) { |
e232c68f | 616 | $event = new \Civi\Core\DAO\Event\PostUpdate($this, $result); |
4162ab6f | 617 | \Civi::dispatcher()->dispatch("civi.dao.postUpdate", $event); |
9f35e05d | 618 | } |
10cac951 | 619 | $this->clearDbColumnValueCache(); |
6a488035 TO |
620 | } |
621 | else { | |
e232c68f CW |
622 | if ($hook) { |
623 | $preEvent = new \Civi\Core\DAO\Event\PreUpdate($this); | |
4162ab6f | 624 | \Civi::dispatcher()->dispatch("civi.dao.preInsert", $preEvent); |
e232c68f CW |
625 | } |
626 | ||
627 | $result = $this->insert(); | |
8498c2b7 | 628 | |
9f35e05d | 629 | if ($hook) { |
e232c68f | 630 | $event = new \Civi\Core\DAO\Event\PostUpdate($this, $result); |
4162ab6f | 631 | \Civi::dispatcher()->dispatch("civi.dao.postInsert", $event); |
9f35e05d | 632 | } |
6a488035 TO |
633 | } |
634 | $this->free(); | |
635 | ||
9f35e05d TO |
636 | if ($hook) { |
637 | CRM_Utils_Hook::postSave($this); | |
638 | } | |
6a488035 TO |
639 | |
640 | return $this; | |
641 | } | |
642 | ||
1cd3ffa9 | 643 | /** |
fe482240 | 644 | * Deletes items from table which match current objects variables. |
1cd3ffa9 EM |
645 | * |
646 | * Returns the true on success | |
647 | * | |
648 | * for example | |
649 | * | |
650 | * Designed to be extended | |
651 | * | |
652 | * $object = new mytable(); | |
653 | * $object->ID=123; | |
654 | * echo $object->delete(); // builds a conditon | |
655 | * | |
656 | * $object = new mytable(); | |
657 | * $object->whereAdd('age > 12'); | |
658 | * $object->limit(1); | |
659 | * $object->orderBy('age DESC'); | |
660 | * $object->delete(true); // dont use object vars, use the conditions, limit and order. | |
661 | * | |
662 | * @param bool $useWhere (optional) If DB_DATAOBJECT_WHEREADD_ONLY is passed in then | |
663 | * we will build the condition only using the whereAdd's. Default is to | |
664 | * build the condition only using the object parameters. | |
665 | * | |
666 | * * @return mixed Int (No. of rows affected) on success, false on failure, 0 on no data affected | |
667 | */ | |
00be9182 | 668 | public function delete($useWhere = FALSE) { |
7b83ea83 | 669 | $preEvent = new \Civi\Core\DAO\Event\PreDelete($this); |
4162ab6f | 670 | \Civi::dispatcher()->dispatch("civi.dao.preDelete", $preEvent); |
7b83ea83 | 671 | |
97c4fe76 | 672 | $result = parent::delete($useWhere); |
8498c2b7 | 673 | |
48d849b1 | 674 | $event = new \Civi\Core\DAO\Event\PostDelete($this, $result); |
4162ab6f | 675 | \Civi::dispatcher()->dispatch("civi.dao.postDelete", $event); |
37eb13b2 | 676 | $this->free(); |
8498c2b7 | 677 | |
10cac951 CW |
678 | $this->clearDbColumnValueCache(); |
679 | ||
97c4fe76 | 680 | return $result; |
681 | } | |
682 | ||
a0ee3941 EM |
683 | /** |
684 | * @param bool $created | |
685 | */ | |
00be9182 | 686 | public function log($created = FALSE) { |
6a488035 TO |
687 | static $cid = NULL; |
688 | ||
689 | if (!$this->getLog()) { | |
690 | return; | |
691 | } | |
692 | ||
693 | if (!$cid) { | |
694 | $session = CRM_Core_Session::singleton(); | |
695 | $cid = $session->get('userID'); | |
696 | } | |
697 | ||
698 | // return is we dont have handle to FK | |
699 | if (!$cid) { | |
700 | return; | |
701 | } | |
702 | ||
353ffa53 TO |
703 | $dao = new CRM_Core_DAO_Log(); |
704 | $dao->entity_table = $this->getTableName(); | |
705 | $dao->entity_id = $this->id; | |
706 | $dao->modified_id = $cid; | |
6a488035 TO |
707 | $dao->modified_date = date("YmdHis"); |
708 | $dao->insert(); | |
709 | } | |
710 | ||
711 | /** | |
712 | * Given an associative array of name/value pairs, extract all the values | |
713 | * that belong to this object and initialize the object with said values | |
714 | * | |
6a0b768e | 715 | * @param array $params |
fc944198 | 716 | * Array of name/value pairs to save. |
6a488035 | 717 | * |
795492f3 TO |
718 | * @return bool |
719 | * Did we copy all null values into the object | |
6a488035 | 720 | */ |
fc944198 | 721 | public function copyValues($params) { |
6a488035 | 722 | $allNull = TRUE; |
fc944198 CW |
723 | foreach ($this->fields() as $uniqueName => $field) { |
724 | $dbName = $field['name']; | |
6a488035 | 725 | if (array_key_exists($dbName, $params)) { |
fc944198 | 726 | $value = $params[$dbName]; |
6a488035 TO |
727 | $exists = TRUE; |
728 | } | |
fc944198 CW |
729 | elseif (array_key_exists($uniqueName, $params)) { |
730 | $value = $params[$uniqueName]; | |
6a488035 TO |
731 | $exists = TRUE; |
732 | } | |
733 | else { | |
734 | $exists = FALSE; | |
735 | } | |
736 | ||
737 | // if there is no value then make the variable NULL | |
738 | if ($exists) { | |
fc944198 | 739 | if ($value === '') { |
6a488035 TO |
740 | $this->$dbName = 'null'; |
741 | } | |
fc944198 CW |
742 | elseif (is_array($value) && !empty($field['serialize'])) { |
743 | $this->$dbName = CRM_Core_DAO::serializeField($value, $field['serialize']); | |
30208fab | 744 | $allNull = FALSE; |
745 | } | |
6a488035 | 746 | else { |
9c1bc317 | 747 | $maxLength = $field['maxlength'] ?? NULL; |
fc944198 CW |
748 | if (!is_array($value) && $maxLength && mb_strlen($value) > $maxLength && empty($field['pseudoconstant'])) { |
749 | Civi::log()->warning(ts('A string for field $dbName has been truncated. The original string was %1', [CRM_Utils_Type::escape($value, 'String')])); | |
809e1a83 | 750 | // The string is too long - what to do what to do? Well losing data is generally bad so lets' truncate |
fc944198 | 751 | $value = CRM_Utils_String::ellipsify($value, $maxLength); |
809e1a83 | 752 | } |
fc944198 | 753 | $this->$dbName = $value; |
6a488035 TO |
754 | $allNull = FALSE; |
755 | } | |
756 | } | |
757 | } | |
758 | return $allNull; | |
759 | } | |
760 | ||
761 | /** | |
762 | * Store all the values from this object in an associative array | |
763 | * this is a destructive store, calling function is responsible | |
764 | * for keeping sanity of id's. | |
765 | * | |
6a0b768e TO |
766 | * @param object $object |
767 | * The object that we are extracting data from. | |
768 | * @param array $values | |
769 | * (reference ) associative array of name/value pairs. | |
6a488035 | 770 | */ |
00be9182 | 771 | public static function storeValues(&$object, &$values) { |
44ce4aa3 | 772 | $fields = $object->fields(); |
6a488035 TO |
773 | foreach ($fields as $name => $value) { |
774 | $dbName = $value['name']; | |
775 | if (isset($object->$dbName) && $object->$dbName !== 'null') { | |
776 | $values[$dbName] = $object->$dbName; | |
777 | if ($name != $dbName) { | |
778 | $values[$name] = $object->$dbName; | |
779 | } | |
780 | } | |
781 | } | |
782 | } | |
783 | ||
784 | /** | |
100fef9d | 785 | * Create an attribute for this specific field. We only do this for strings and text |
6a488035 | 786 | * |
6a0b768e TO |
787 | * @param array $field |
788 | * The field under task. | |
6a488035 | 789 | * |
72b3a70c CW |
790 | * @return array|null |
791 | * the attributes for the object | |
6a488035 | 792 | */ |
00be9182 | 793 | public static function makeAttribute($field) { |
6a488035 TO |
794 | if ($field) { |
795 | if (CRM_Utils_Array::value('type', $field) == CRM_Utils_Type::T_STRING) { | |
9c1bc317 CW |
796 | $maxLength = $field['maxlength'] ?? NULL; |
797 | $size = $field['size'] ?? NULL; | |
6a488035 | 798 | if ($maxLength || $size) { |
be2fb01f | 799 | $attributes = []; |
6a488035 TO |
800 | if ($maxLength) { |
801 | $attributes['maxlength'] = $maxLength; | |
802 | } | |
803 | if ($size) { | |
804 | $attributes['size'] = $size; | |
805 | } | |
806 | return $attributes; | |
807 | } | |
808 | } | |
809 | elseif (CRM_Utils_Array::value('type', $field) == CRM_Utils_Type::T_TEXT) { | |
9c1bc317 | 810 | $rows = $field['rows'] ?? NULL; |
6a488035 TO |
811 | if (!isset($rows)) { |
812 | $rows = 2; | |
813 | } | |
9c1bc317 | 814 | $cols = $field['cols'] ?? NULL; |
6a488035 TO |
815 | if (!isset($cols)) { |
816 | $cols = 80; | |
817 | } | |
818 | ||
be2fb01f | 819 | $attributes = []; |
6a488035 TO |
820 | $attributes['rows'] = $rows; |
821 | $attributes['cols'] = $cols; | |
822 | return $attributes; | |
823 | } | |
824 | 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) { | |
825 | $attributes['size'] = 6; | |
826 | $attributes['maxlength'] = 14; | |
827 | return $attributes; | |
828 | } | |
829 | } | |
830 | return NULL; | |
831 | } | |
832 | ||
833 | /** | |
d09edf64 | 834 | * Get the size and maxLength attributes for this text field. |
6a488035 TO |
835 | * (or for all text fields) in the DAO object. |
836 | * | |
6a0b768e TO |
837 | * @param string $class |
838 | * Name of DAO class. | |
839 | * @param string $fieldName | |
840 | * Field that i'm interested in or null if. | |
6a488035 TO |
841 | * you want the attributes for all DAO text fields |
842 | * | |
a6c01b45 CW |
843 | * @return array |
844 | * assoc array of name => attribute pairs | |
6a488035 | 845 | */ |
00be9182 | 846 | public static function getAttribute($class, $fieldName = NULL) { |
353ffa53 | 847 | $object = new $class(); |
44ce4aa3 | 848 | $fields = $object->fields(); |
6a488035 | 849 | if ($fieldName != NULL) { |
9c1bc317 | 850 | $field = $fields[$fieldName] ?? NULL; |
6a488035 TO |
851 | return self::makeAttribute($field); |
852 | } | |
853 | else { | |
be2fb01f | 854 | $attributes = []; |
6a488035 TO |
855 | foreach ($fields as $name => $field) { |
856 | $attribute = self::makeAttribute($field); | |
857 | if ($attribute) { | |
858 | $attributes[$name] = $attribute; | |
859 | } | |
860 | } | |
861 | ||
862 | if (!empty($attributes)) { | |
863 | return $attributes; | |
864 | } | |
865 | } | |
866 | return NULL; | |
867 | } | |
868 | ||
2ee9afab CW |
869 | /** |
870 | * Create or update a record from supplied params. | |
871 | * | |
872 | * If 'id' is supplied, an existing record will be updated | |
873 | * Otherwise a new record will be created. | |
874 | * | |
875 | * @param array $record | |
876 | * @return CRM_Core_DAO | |
877 | * @throws CRM_Core_Exception | |
878 | */ | |
879 | public static function writeRecord(array $record) { | |
880 | $hook = empty($record['id']) ? 'create' : 'edit'; | |
881 | $className = CRM_Core_DAO_AllCoreTables::getCanonicalClassName(static::class); | |
882 | if ($className === 'CRM_Core_DAO') { | |
883 | throw new CRM_Core_Exception('Function writeRecord must be called on a subclass of CRM_Core_DAO'); | |
884 | } | |
885 | $entityName = CRM_Core_DAO_AllCoreTables::getBriefName($className); | |
886 | ||
887 | \CRM_Utils_Hook::pre($hook, $entityName, $record['id'] ?? NULL, $record); | |
888 | $instance = new $className(); | |
889 | $instance->copyValues($record); | |
890 | $instance->save(); | |
891 | \CRM_Utils_Hook::post($hook, $entityName, $instance->id, $instance); | |
892 | ||
893 | return $instance; | |
894 | } | |
895 | ||
896 | /** | |
897 | * Delete a record from supplied params. | |
898 | * | |
899 | * @param array $record | |
900 | * 'id' is required. | |
901 | * @return CRM_Core_DAO | |
902 | * @throws CRM_Core_Exception | |
903 | */ | |
904 | public static function deleteRecord(array $record) { | |
905 | $className = CRM_Core_DAO_AllCoreTables::getCanonicalClassName(static::class); | |
906 | if ($className === 'CRM_Core_DAO') { | |
907 | throw new CRM_Core_Exception('Function deleteRecord must be called on a subclass of CRM_Core_DAO'); | |
908 | } | |
909 | $entityName = CRM_Core_DAO_AllCoreTables::getBriefName($className); | |
910 | if (empty($record['id'])) { | |
911 | throw new CRM_Core_Exception("Cannot delete {$entityName} with no id."); | |
912 | } | |
913 | ||
914 | CRM_Utils_Hook::pre('delete', $entityName, $record['id'], $record); | |
915 | $instance = new $className(); | |
916 | $instance->id = $record['id']; | |
917 | if (!$instance->delete()) { | |
918 | throw new CRM_Core_Exception("Could not delete {$entityName} id {$record['id']}"); | |
919 | } | |
920 | CRM_Utils_Hook::post('delete', $entityName, $record['id'], $instance); | |
921 | ||
922 | return $instance; | |
923 | } | |
924 | ||
6a488035 | 925 | /** |
fe482240 | 926 | * Check if there is a record with the same name in the db. |
6a488035 | 927 | * |
6a0b768e TO |
928 | * @param string $value |
929 | * The value of the field we are checking. | |
930 | * @param string $daoName | |
931 | * The dao object name. | |
932 | * @param string $daoID | |
933 | * The id of the object being updated. u can change your name. | |
6a488035 | 934 | * as long as there is no conflict |
6a0b768e TO |
935 | * @param string $fieldName |
936 | * The name of the field in the DAO. | |
6a488035 | 937 | * |
35b63106 DS |
938 | * @param string $domainID |
939 | * The id of the domain. Object exists only for the given domain. | |
940 | * | |
795492f3 | 941 | * @return bool |
a6c01b45 | 942 | * true if object exists |
6a488035 | 943 | */ |
35b63106 | 944 | public static function objectExists($value, $daoName, $daoID, $fieldName = 'name', $domainID = NULL) { |
353ffa53 | 945 | $object = new $daoName(); |
6a488035 | 946 | $object->$fieldName = $value; |
35b63106 DS |
947 | if ($domainID) { |
948 | $object->domain_id = $domainID; | |
949 | } | |
6a488035 TO |
950 | |
951 | if ($object->find(TRUE)) { | |
63d76404 | 952 | return $daoID && $object->id == $daoID; |
6a488035 TO |
953 | } |
954 | else { | |
955 | return TRUE; | |
956 | } | |
957 | } | |
958 | ||
959 | /** | |
fe482240 | 960 | * Check if there is a given column in a specific table. |
6a488035 | 961 | * |
eed7e803 CW |
962 | * @deprecated |
963 | * @see CRM_Core_BAO_SchemaHandler::checkIfFieldExists | |
964 | * | |
6a488035 TO |
965 | * @param string $tableName |
966 | * @param string $columnName | |
6a0b768e TO |
967 | * @param bool $i18nRewrite |
968 | * Whether to rewrite the query on multilingual setups. | |
6a488035 | 969 | * |
795492f3 | 970 | * @return bool |
a6c01b45 | 971 | * true if exists, else false |
6a488035 | 972 | */ |
00be9182 | 973 | public static function checkFieldExists($tableName, $columnName, $i18nRewrite = TRUE) { |
fdc2e63a | 974 | CRM_Core_Error::deprecatedFunctionWarning('CRM_Core_BAO_SchemaHandler::checkIfFieldExists'); |
eed7e803 | 975 | return CRM_Core_BAO_SchemaHandler::checkIfFieldExists($tableName, $columnName, $i18nRewrite); |
6a488035 TO |
976 | } |
977 | ||
978 | /** | |
3fa9688a | 979 | * Scans all the tables using a slow query and table name. |
2a6da8d7 | 980 | * |
6a488035 | 981 | * @return array |
6a488035 | 982 | */ |
3fa9688a | 983 | public static function getTableNames() { |
984 | $dao = CRM_Core_DAO::executeQuery( | |
985 | "SELECT TABLE_NAME | |
986 | FROM information_schema.TABLES | |
987 | WHERE TABLE_SCHEMA = '" . CRM_Core_DAO::getDatabaseName() . "' | |
988 | AND TABLE_NAME LIKE 'civicrm_%' | |
989 | AND TABLE_NAME NOT LIKE 'civicrm_import_job_%' | |
2475b550 | 990 | AND TABLE_NAME NOT LIKE '%_temp%' |
3fa9688a | 991 | "); |
6a488035 | 992 | |
6a488035 | 993 | while ($dao->fetch()) { |
3fa9688a | 994 | $values[] = $dao->TABLE_NAME; |
6a488035 | 995 | } |
6a488035 TO |
996 | return $values; |
997 | } | |
998 | ||
a0ee3941 EM |
999 | /** |
1000 | * @param int $maxTablesToCheck | |
1001 | * | |
1002 | * @return bool | |
1003 | */ | |
00be9182 | 1004 | public static function isDBMyISAM($maxTablesToCheck = 10) { |
3fa9688a | 1005 | return CRM_Core_DAO::singleValueQuery( |
1006 | "SELECT count(*) | |
1007 | FROM information_schema.TABLES | |
1008 | WHERE ENGINE = 'MyISAM' | |
1009 | AND TABLE_SCHEMA = '" . CRM_Core_DAO::getDatabaseName() . "' | |
1010 | AND TABLE_NAME LIKE 'civicrm_%' | |
1011 | AND TABLE_NAME NOT LIKE 'civicrm_import_job_%' | |
2475b550 | 1012 | AND TABLE_NAME NOT LIKE '%_temp%' |
0cb1aeab | 1013 | AND TABLE_NAME NOT LIKE 'civicrm_tmp_%' |
3fa9688a | 1014 | "); |
1015 | } | |
1016 | ||
1017 | /** | |
1018 | * Get the name of the CiviCRM database. | |
1019 | * | |
1020 | * @return string | |
1021 | */ | |
1022 | public static function getDatabaseName() { | |
1023 | $daoObj = new CRM_Core_DAO(); | |
1024 | return $daoObj->database(); | |
6a488035 TO |
1025 | } |
1026 | ||
1027 | /** | |
1028 | * Checks if a constraint exists for a specified table. | |
1029 | * | |
1030 | * @param string $tableName | |
1031 | * @param string $constraint | |
1032 | * | |
795492f3 | 1033 | * @return bool |
a6c01b45 | 1034 | * true if constraint exists, false otherwise |
7c58994a | 1035 | * |
1036 | * @throws \CRM_Core_Exception | |
6a488035 | 1037 | */ |
00be9182 | 1038 | public static function checkConstraintExists($tableName, $constraint) { |
be2fb01f | 1039 | static $show = []; |
6a488035 TO |
1040 | |
1041 | if (!array_key_exists($tableName, $show)) { | |
1042 | $query = "SHOW CREATE TABLE $tableName"; | |
220d454c | 1043 | $dao = CRM_Core_DAO::executeQuery($query, [], TRUE, NULL, FALSE, FALSE); |
6a488035 TO |
1044 | |
1045 | if (!$dao->fetch()) { | |
7c58994a | 1046 | throw new CRM_Core_Exception('query failed'); |
6a488035 TO |
1047 | } |
1048 | ||
6a488035 TO |
1049 | $show[$tableName] = $dao->Create_Table; |
1050 | } | |
1051 | ||
63d76404 | 1052 | return (bool) preg_match("/\b$constraint\b/i", $show[$tableName]); |
6a488035 TO |
1053 | } |
1054 | ||
1055 | /** | |
1056 | * Checks if CONSTRAINT keyword exists for a specified table. | |
1057 | * | |
2a6da8d7 EM |
1058 | * @param array $tables |
1059 | * | |
7c58994a | 1060 | * @throws CRM_Core_Exception |
6a488035 | 1061 | * |
795492f3 | 1062 | * @return bool |
a6c01b45 | 1063 | * true if CONSTRAINT keyword exists, false otherwise |
6a488035 | 1064 | */ |
be2fb01f CW |
1065 | public static function schemaRequiresRebuilding($tables = ["civicrm_contact"]) { |
1066 | $show = []; | |
9b873358 | 1067 | foreach ($tables as $tableName) { |
6a488035 TO |
1068 | if (!array_key_exists($tableName, $show)) { |
1069 | $query = "SHOW CREATE TABLE $tableName"; | |
220d454c | 1070 | $dao = CRM_Core_DAO::executeQuery($query, [], TRUE, NULL, FALSE, FALSE); |
6a488035 TO |
1071 | |
1072 | if (!$dao->fetch()) { | |
7c58994a | 1073 | throw new CRM_Core_Exception('Show create table failed.'); |
6a488035 TO |
1074 | } |
1075 | ||
6a488035 TO |
1076 | $show[$tableName] = $dao->Create_Table; |
1077 | } | |
1078 | ||
63d76404 | 1079 | $result = (bool) preg_match("/\bCONSTRAINT\b\s/i", $show[$tableName]); |
9b873358 | 1080 | if ($result == TRUE) { |
6a488035 TO |
1081 | continue; |
1082 | } | |
c490a46a | 1083 | else { |
6a488035 TO |
1084 | return FALSE; |
1085 | } | |
1086 | } | |
1087 | return TRUE; | |
1088 | } | |
1089 | ||
1090 | /** | |
1091 | * Checks if the FK constraint name is in the format 'FK_tableName_columnName' | |
1092 | * for a specified column of a table. | |
1093 | * | |
1094 | * @param string $tableName | |
1095 | * @param string $columnName | |
1096 | * | |
795492f3 | 1097 | * @return bool |
a6c01b45 | 1098 | * true if in format, false otherwise |
7c58994a | 1099 | * |
1100 | * @throws \CRM_Core_Exception | |
6a488035 | 1101 | */ |
00be9182 | 1102 | public static function checkFKConstraintInFormat($tableName, $columnName) { |
be2fb01f | 1103 | static $show = []; |
6a488035 TO |
1104 | |
1105 | if (!array_key_exists($tableName, $show)) { | |
1106 | $query = "SHOW CREATE TABLE $tableName"; | |
1107 | $dao = CRM_Core_DAO::executeQuery($query); | |
1108 | ||
1109 | if (!$dao->fetch()) { | |
7c58994a | 1110 | throw new CRM_Core_Exception('query failed'); |
6a488035 TO |
1111 | } |
1112 | ||
6a488035 TO |
1113 | $show[$tableName] = $dao->Create_Table; |
1114 | } | |
1115 | $constraint = "`FK_{$tableName}_{$columnName}`"; | |
1116 | $pattern = "/\bCONSTRAINT\b\s+%s\s+\bFOREIGN\s+KEY\b\s/i"; | |
63d76404 | 1117 | return (bool) preg_match(sprintf($pattern, $constraint), $show[$tableName]); |
6a488035 TO |
1118 | } |
1119 | ||
1120 | /** | |
fe482240 | 1121 | * Check whether a specific column in a specific table has always the same value. |
6a488035 TO |
1122 | * |
1123 | * @param string $tableName | |
1124 | * @param string $columnName | |
1125 | * @param string $columnValue | |
1126 | * | |
795492f3 | 1127 | * @return bool |
a6c01b45 | 1128 | * true if the value is always $columnValue, false otherwise |
6a488035 | 1129 | */ |
00be9182 | 1130 | public static function checkFieldHasAlwaysValue($tableName, $columnName, $columnValue) { |
353ffa53 TO |
1131 | $query = "SELECT * FROM $tableName WHERE $columnName != '$columnValue'"; |
1132 | $dao = CRM_Core_DAO::executeQuery($query); | |
6a488035 | 1133 | $result = $dao->fetch() ? FALSE : TRUE; |
6a488035 TO |
1134 | return $result; |
1135 | } | |
1136 | ||
1137 | /** | |
fe482240 | 1138 | * Check whether a specific column in a specific table is always NULL. |
6a488035 TO |
1139 | * |
1140 | * @param string $tableName | |
1141 | * @param string $columnName | |
1142 | * | |
795492f3 | 1143 | * @return bool |
a6c01b45 | 1144 | * true if if the value is always NULL, false otherwise |
6a488035 | 1145 | */ |
00be9182 | 1146 | public static function checkFieldIsAlwaysNull($tableName, $columnName) { |
353ffa53 TO |
1147 | $query = "SELECT * FROM $tableName WHERE $columnName IS NOT NULL"; |
1148 | $dao = CRM_Core_DAO::executeQuery($query); | |
6a488035 | 1149 | $result = $dao->fetch() ? FALSE : TRUE; |
6a488035 TO |
1150 | return $result; |
1151 | } | |
1152 | ||
06f83d5c CW |
1153 | /** |
1154 | * Checks if this DAO's table ought to exist. | |
1155 | * | |
1156 | * If there are pending DB updates, this function compares the CiviCRM version of the table to the current schema version. | |
1157 | * | |
1158 | * @return bool | |
1159 | * @throws CRM_Core_Exception | |
1160 | */ | |
1161 | public static function tableHasBeenAdded() { | |
1162 | if (CRM_Utils_System::version() === CRM_Core_BAO_Domain::version()) { | |
1163 | return TRUE; | |
1164 | } | |
633a8dbc CW |
1165 | $daoExt = defined(static::class . '::EXT') ? constant(static::class . '::EXT') : NULL; |
1166 | $daoVersion = defined(static::class . '::TABLE_ADDED') ? constant(static::class . '::TABLE_ADDED') : '1.0'; | |
06f83d5c CW |
1167 | return !($daoExt === 'civicrm' && version_compare(CRM_Core_BAO_Domain::version(), $daoVersion, '<')); |
1168 | } | |
1169 | ||
6a488035 | 1170 | /** |
fe482240 | 1171 | * Check if there is a given table in the database. |
6a488035 TO |
1172 | * |
1173 | * @param string $tableName | |
1174 | * | |
795492f3 | 1175 | * @return bool |
a6c01b45 | 1176 | * true if exists, else false |
6a488035 | 1177 | */ |
00be9182 | 1178 | public static function checkTableExists($tableName) { |
6a488035 TO |
1179 | $query = " |
1180 | SHOW TABLES | |
1181 | LIKE %1 | |
1182 | "; | |
be2fb01f | 1183 | $params = [1 => [$tableName, 'String']]; |
6a488035 TO |
1184 | |
1185 | $dao = CRM_Core_DAO::executeQuery($query, $params); | |
63d76404 | 1186 | return (bool) $dao->fetch(); |
6a488035 TO |
1187 | } |
1188 | ||
66f5e240 TO |
1189 | /** |
1190 | * Check if a given table has data. | |
1191 | * | |
1192 | * @param string $tableName | |
1193 | * @return bool | |
1194 | * TRUE if $tableName has at least one record. | |
1195 | */ | |
1196 | public static function checkTableHasData($tableName) { | |
1197 | $c = CRM_Core_DAO::singleValueQuery(sprintf('SELECT count(*) c FROM `%s`', $tableName)); | |
1198 | return $c > 0; | |
1199 | } | |
1200 | ||
a0ee3941 EM |
1201 | /** |
1202 | * @param $version | |
895e3d81 | 1203 | * @deprecated |
a0ee3941 EM |
1204 | * @return bool |
1205 | */ | |
00be9182 | 1206 | public function checkVersion($version) { |
895e3d81 CW |
1207 | CRM_Core_Error::deprecatedFunctionWarning('CRM_Core_BAO_Domain::version'); |
1208 | $dbVersion = CRM_Core_BAO_Domain::version(); | |
63d76404 | 1209 | return trim($version) == trim($dbVersion); |
6a488035 TO |
1210 | } |
1211 | ||
47ff2df7 AN |
1212 | /** |
1213 | * Find a DAO object for the given ID and return it. | |
1214 | * | |
6a0b768e TO |
1215 | * @param int $id |
1216 | * Id of the DAO object being searched for. | |
47ff2df7 | 1217 | * |
44ce4aa3 | 1218 | * @return CRM_Core_DAO |
a6c01b45 | 1219 | * Object of the type of the class that called this function. |
44ce4aa3 CW |
1220 | * |
1221 | * @throws Exception | |
47ff2df7 | 1222 | */ |
00be9182 | 1223 | public static function findById($id) { |
47ff2df7 AN |
1224 | $object = new static(); |
1225 | $object->id = $id; | |
1226 | if (!$object->find(TRUE)) { | |
1227 | throw new Exception("Unable to find a " . get_called_class() . " with id {$id}."); | |
1228 | } | |
1229 | return $object; | |
1230 | } | |
1231 | ||
63782ba4 TO |
1232 | /** |
1233 | * Returns all results as array-encoded records. | |
1234 | * | |
1235 | * @return array | |
1236 | */ | |
2fabb51b | 1237 | public function fetchAll($k = FALSE, $v = FALSE, $method = FALSE) { |
be2fb01f | 1238 | $result = []; |
63782ba4 TO |
1239 | while ($this->fetch()) { |
1240 | $result[] = $this->toArray(); | |
1241 | } | |
1242 | return $result; | |
1243 | } | |
b5bbb074 | 1244 | |
41d41c91 TO |
1245 | /** |
1246 | * Return the results as PHP generator. | |
1247 | * | |
1248 | * @param string $type | |
1249 | * Whether the generator yields 'dao' objects or 'array's. | |
1250 | */ | |
1251 | public function fetchGenerator($type = 'dao') { | |
1252 | while ($this->fetch()) { | |
1253 | switch ($type) { | |
1254 | case 'dao': | |
1255 | yield $this; | |
1256 | break; | |
1257 | ||
1258 | case 'array': | |
1259 | yield $this->toArray(); | |
1260 | break; | |
1261 | ||
1262 | default: | |
1263 | throw new \RuntimeException("Invalid record type ($type)"); | |
1264 | } | |
1265 | } | |
1266 | } | |
1267 | ||
77e74ae1 TO |
1268 | /** |
1269 | * Returns a singular value. | |
1270 | * | |
1271 | * @return mixed|NULL | |
1272 | */ | |
1273 | public function fetchValue() { | |
1274 | $result = $this->getDatabaseResult(); | |
1275 | $row = $result->fetchRow(); | |
1276 | $ret = NULL; | |
1277 | if ($row) { | |
1278 | $ret = $row[0]; | |
1279 | } | |
1280 | $this->free(); | |
1281 | return $ret; | |
1282 | } | |
1283 | ||
b5bbb074 TO |
1284 | /** |
1285 | * Get all the result records as mapping between columns. | |
1286 | * | |
1287 | * @param string $keyColumn | |
1288 | * Ex: "name" | |
1289 | * @param string $valueColumn | |
1290 | * Ex: "label" | |
1291 | * @return array | |
1292 | * Ex: ["foo" => "The Foo Bar", "baz" => "The Baz Qux"] | |
1293 | */ | |
1294 | public function fetchMap($keyColumn, $valueColumn) { | |
be2fb01f | 1295 | $result = []; |
b5bbb074 TO |
1296 | while ($this->fetch()) { |
1297 | $result[$this->{$keyColumn}] = $this->{$valueColumn}; | |
1298 | } | |
1299 | return $result; | |
1300 | } | |
63782ba4 | 1301 | |
6a488035 TO |
1302 | /** |
1303 | * Given a DAO name, a column name and a column value, find the record and GET the value of another column in that record | |
1304 | * | |
6a0b768e TO |
1305 | * @param string $daoName |
1306 | * Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact). | |
1307 | * @param int $searchValue | |
1308 | * Value of the column you want to search by. | |
1309 | * @param string $returnColumn | |
1310 | * Name of the column you want to GET the value of. | |
1311 | * @param string $searchColumn | |
1312 | * Name of the column you want to search by. | |
1313 | * @param bool $force | |
1314 | * Skip use of the cache. | |
6a488035 | 1315 | * |
f4b8bef7 | 1316 | * @return string|int|null |
72b3a70c | 1317 | * Value of $returnColumn in the retrieved record |
7c58994a | 1318 | * |
1319 | * @throws \CRM_Core_Exception | |
6a488035 | 1320 | */ |
00be9182 | 1321 | public static function getFieldValue($daoName, $searchValue, $returnColumn = 'name', $searchColumn = 'id', $force = FALSE) { |
6a488035 TO |
1322 | if ( |
1323 | empty($searchValue) || | |
1324 | trim(strtolower($searchValue)) == 'null' | |
1325 | ) { | |
cf79ac58 | 1326 | // adding this here since developers forget to check for an id |
6a488035 TO |
1327 | // or for the 'null' (which is a bad DAO kludge) |
1328 | // and hence we get the first value in the db | |
7c58994a | 1329 | throw new CRM_Core_Exception('getFieldValue failed'); |
6a488035 TO |
1330 | } |
1331 | ||
10cac951 CW |
1332 | self::$_dbColumnValueCache = self::$_dbColumnValueCache ?? []; |
1333 | ||
1334 | while (strpos($daoName, '_BAO_') !== FALSE) { | |
1335 | $daoName = get_parent_class($daoName); | |
6a488035 TO |
1336 | } |
1337 | ||
10cac951 CW |
1338 | if ($force || |
1339 | empty(self::$_dbColumnValueCache[$daoName][$searchColumn][$searchValue]) || | |
1340 | !array_key_exists($returnColumn, self::$_dbColumnValueCache[$daoName][$searchColumn][$searchValue]) | |
1341 | ) { | |
353ffa53 | 1342 | $object = new $daoName(); |
6a488035 TO |
1343 | $object->$searchColumn = $searchValue; |
1344 | $object->selectAdd(); | |
1345 | $object->selectAdd($returnColumn); | |
1346 | ||
1347 | $result = NULL; | |
1348 | if ($object->find(TRUE)) { | |
1349 | $result = $object->$returnColumn; | |
1350 | } | |
6a488035 | 1351 | |
10cac951 | 1352 | self::$_dbColumnValueCache[$daoName][$searchColumn][$searchValue][$returnColumn] = $result; |
6a488035 | 1353 | } |
10cac951 | 1354 | return self::$_dbColumnValueCache[$daoName][$searchColumn][$searchValue][$returnColumn]; |
6a488035 TO |
1355 | } |
1356 | ||
1357 | /** | |
1358 | * Given a DAO name, a column name and a column value, find the record and SET the value of another column in that record | |
1359 | * | |
6a0b768e TO |
1360 | * @param string $daoName |
1361 | * Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact). | |
1362 | * @param int $searchValue | |
1363 | * Value of the column you want to search by. | |
1364 | * @param string $setColumn | |
1365 | * Name of the column you want to SET the value of. | |
1366 | * @param string $setValue | |
1367 | * SET the setColumn to this value. | |
1368 | * @param string $searchColumn | |
1369 | * Name of the column you want to search by. | |
6a488035 | 1370 | * |
795492f3 | 1371 | * @return bool |
a6c01b45 | 1372 | * true if we found and updated the object, else false |
6a488035 | 1373 | */ |
00be9182 | 1374 | public static function setFieldValue($daoName, $searchValue, $setColumn, $setValue, $searchColumn = 'id') { |
353ffa53 | 1375 | $object = new $daoName(); |
6a488035 TO |
1376 | $object->selectAdd(); |
1377 | $object->selectAdd("$searchColumn, $setColumn"); | |
1378 | $object->$searchColumn = $searchValue; | |
1379 | $result = FALSE; | |
1380 | if ($object->find(TRUE)) { | |
1381 | $object->$setColumn = $setValue; | |
1382 | if ($object->save()) { | |
1383 | $result = TRUE; | |
1384 | } | |
1385 | } | |
1386 | $object->free(); | |
1387 | return $result; | |
1388 | } | |
1389 | ||
1390 | /** | |
fe482240 | 1391 | * Get sort string. |
6a488035 TO |
1392 | * |
1393 | * @param array|object $sort either array or CRM_Utils_Sort | |
6a0b768e TO |
1394 | * @param string $default |
1395 | * Default sort value. | |
6a488035 | 1396 | * |
a6c01b45 | 1397 | * @return string |
6a488035 | 1398 | */ |
00be9182 | 1399 | public static function getSortString($sort, $default = NULL) { |
6a488035 TO |
1400 | // check if sort is of type CRM_Utils_Sort |
1401 | if (is_a($sort, 'CRM_Utils_Sort')) { | |
1402 | return $sort->orderBy(); | |
1403 | } | |
1404 | ||
44ce4aa3 CW |
1405 | $sortString = ''; |
1406 | ||
6a488035 TO |
1407 | // is it an array specified as $field => $sortDirection ? |
1408 | if ($sort) { | |
1409 | foreach ($sort as $k => $v) { | |
1410 | $sortString .= "$k $v,"; | |
1411 | } | |
1412 | return rtrim($sortString, ','); | |
1413 | } | |
1414 | return $default; | |
1415 | } | |
1416 | ||
1417 | /** | |
fe482240 | 1418 | * Fetch object based on array of properties. |
6a488035 | 1419 | * |
6a0b768e TO |
1420 | * @param string $daoName |
1421 | * Name of the dao object. | |
1422 | * @param array $params | |
1423 | * (reference ) an assoc array of name/value pairs. | |
1424 | * @param array $defaults | |
1425 | * (reference ) an assoc array to hold the flattened values. | |
1426 | * @param array $returnProperities | |
1427 | * An assoc array of fields that need to be returned, eg array( 'first_name', 'last_name'). | |
6a488035 | 1428 | * |
a6c01b45 CW |
1429 | * @return object |
1430 | * an object of type referenced by daoName | |
6a488035 | 1431 | */ |
00be9182 | 1432 | public static function commonRetrieve($daoName, &$params, &$defaults, $returnProperities = NULL) { |
353ffa53 | 1433 | $object = new $daoName(); |
6a488035 TO |
1434 | $object->copyValues($params); |
1435 | ||
1436 | // return only specific fields if returnproperties are sent | |
1437 | if (!empty($returnProperities)) { | |
1438 | $object->selectAdd(); | |
1439 | $object->selectAdd(implode(',', $returnProperities)); | |
1440 | } | |
1441 | ||
1442 | if ($object->find(TRUE)) { | |
1443 | self::storeValues($object, $defaults); | |
1444 | return $object; | |
1445 | } | |
1446 | return NULL; | |
1447 | } | |
1448 | ||
1449 | /** | |
fe482240 | 1450 | * Delete the object records that are associated with this contact. |
6a488035 | 1451 | * |
6a0b768e TO |
1452 | * @param string $daoName |
1453 | * Name of the dao object. | |
1454 | * @param int $contactId | |
1455 | * Id of the contact to delete. | |
6a488035 | 1456 | */ |
00be9182 | 1457 | public static function deleteEntityContact($daoName, $contactId) { |
353ffa53 | 1458 | $object = new $daoName(); |
6a488035 TO |
1459 | |
1460 | $object->entity_table = 'civicrm_contact'; | |
1461 | $object->entity_id = $contactId; | |
1462 | $object->delete(); | |
1463 | } | |
1464 | ||
67cae873 | 1465 | /** |
bf48aa29 | 1466 | * Execute an unbuffered query. |
1467 | * | |
1468 | * This is a wrapper around new functionality exposed with CRM-17748. | |
67cae873 SB |
1469 | * |
1470 | * @param string $query query to be executed | |
3a8ce9d6 | 1471 | * |
bf48aa29 | 1472 | * @param array $params |
1473 | * @param bool $abort | |
1474 | * @param null $daoName | |
1475 | * @param bool $freeDAO | |
1476 | * @param bool $i18nRewrite | |
1477 | * @param bool $trapException | |
1478 | * | |
1479 | * @return CRM_Core_DAO | |
1480 | * Object that points to an unbuffered result set | |
67cae873 | 1481 | */ |
518fa0ee | 1482 | public static function executeUnbufferedQuery( |
67cae873 | 1483 | $query, |
be2fb01f | 1484 | $params = [], |
3a8ce9d6 SB |
1485 | $abort = TRUE, |
1486 | $daoName = NULL, | |
1487 | $freeDAO = FALSE, | |
1488 | $i18nRewrite = TRUE, | |
67cae873 SB |
1489 | $trapException = FALSE |
1490 | ) { | |
67cae873 | 1491 | |
4d1368d8 | 1492 | return self::executeQuery( |
1493 | $query, | |
1494 | $params, | |
1495 | $abort, | |
1496 | $daoName, | |
1497 | $freeDAO, | |
1498 | $i18nRewrite, | |
1499 | $trapException, | |
be2fb01f | 1500 | ['result_buffering' => 0] |
4d1368d8 | 1501 | ); |
67cae873 SB |
1502 | } |
1503 | ||
6a488035 | 1504 | /** |
fe482240 | 1505 | * Execute a query. |
6a488035 | 1506 | * |
6a0b768e TO |
1507 | * @param string $query |
1508 | * Query to be executed. | |
6a488035 | 1509 | * |
2a6da8d7 EM |
1510 | * @param array $params |
1511 | * @param bool $abort | |
1512 | * @param null $daoName | |
1513 | * @param bool $freeDAO | |
1514 | * @param bool $i18nRewrite | |
1515 | * @param bool $trapException | |
4d1368d8 | 1516 | * @param array $options |
2a6da8d7 | 1517 | * |
5f1ebaec | 1518 | * @return CRM_Core_DAO|object |
16b10e64 | 1519 | * object that holds the results of the query |
5f1ebaec EM |
1520 | * NB - if this is defined as just returning a DAO phpstorm keeps pointing |
1521 | * out all the properties that are not part of the DAO | |
6a488035 | 1522 | */ |
795492f3 | 1523 | public static function &executeQuery( |
6a488035 | 1524 | $query, |
be2fb01f | 1525 | $params = [], |
353ffa53 TO |
1526 | $abort = TRUE, |
1527 | $daoName = NULL, | |
1528 | $freeDAO = FALSE, | |
1529 | $i18nRewrite = TRUE, | |
4d1368d8 | 1530 | $trapException = FALSE, |
be2fb01f | 1531 | $options = [] |
6a488035 TO |
1532 | ) { |
1533 | $queryStr = self::composeQuery($query, $params, $abort); | |
6a488035 TO |
1534 | |
1535 | if (!$daoName) { | |
1536 | $dao = new CRM_Core_DAO(); | |
1537 | } | |
1538 | else { | |
353ffa53 | 1539 | $dao = new $daoName(); |
6a488035 TO |
1540 | } |
1541 | ||
1542 | if ($trapException) { | |
41ac4ae1 | 1543 | CRM_Core_Error::deprecatedFunctionWarning('calling functions should handle exceptions'); |
6a4257d4 | 1544 | $errorScope = CRM_Core_TemporaryErrorScope::ignoreException(); |
6a488035 TO |
1545 | } |
1546 | ||
4d1368d8 | 1547 | if ($dao->isValidOption($options)) { |
1548 | $dao->setOptions($options); | |
1549 | } | |
1550 | ||
6a488035 TO |
1551 | $result = $dao->query($queryStr, $i18nRewrite); |
1552 | ||
4d1368d8 | 1553 | // since it is unbuffered, ($dao->N==0) is true. This blocks the standard fetch() mechanism. |
1554 | if (CRM_Utils_Array::value('result_buffering', $options) === 0) { | |
1555 | $dao->N = TRUE; | |
1556 | } | |
1557 | ||
6a488035 | 1558 | if (is_a($result, 'DB_Error')) { |
41ac4ae1 | 1559 | CRM_Core_Error::deprecatedFunctionWarning('calling functions should handle exceptions'); |
6a488035 TO |
1560 | return $result; |
1561 | } | |
1562 | ||
6a488035 TO |
1563 | return $dao; |
1564 | } | |
1565 | ||
4d1368d8 | 1566 | /** |
1567 | * Wrapper to validate internal DAO options before passing to DB_mysql/DB_Common level | |
1568 | * | |
1569 | * @param array $options | |
1570 | * | |
1571 | * @return bool | |
1572 | * Provided options are valid | |
1573 | */ | |
1574 | public function isValidOption($options) { | |
1575 | $isValid = FALSE; | |
be2fb01f | 1576 | $validOptions = [ |
4d1368d8 | 1577 | 'result_buffering', |
1578 | 'persistent', | |
1579 | 'ssl', | |
1580 | 'portability', | |
be2fb01f | 1581 | ]; |
4d1368d8 | 1582 | |
1583 | if (empty($options)) { | |
1584 | return $isValid; | |
1585 | } | |
1586 | ||
1587 | foreach (array_keys($options) as $option) { | |
1588 | if (!in_array($option, $validOptions)) { | |
1589 | return FALSE; | |
1590 | } | |
1591 | $isValid = TRUE; | |
1592 | } | |
1593 | ||
1594 | return $isValid; | |
1595 | } | |
1596 | ||
6a488035 | 1597 | /** |
fe482240 | 1598 | * Execute a query and get the single result. |
6a488035 | 1599 | * |
6a0b768e TO |
1600 | * @param string $query |
1601 | * Query to be executed. | |
e869b07d CW |
1602 | * @param array $params |
1603 | * @param bool $abort | |
1604 | * @param bool $i18nRewrite | |
72b3a70c CW |
1605 | * @return string|null |
1606 | * the result of the query if any | |
6a488035 | 1607 | * |
6a488035 | 1608 | */ |
795492f3 | 1609 | public static function &singleValueQuery( |
f9f40af3 | 1610 | $query, |
be2fb01f | 1611 | $params = [], |
353ffa53 | 1612 | $abort = TRUE, |
6a488035 TO |
1613 | $i18nRewrite = TRUE |
1614 | ) { | |
1615 | $queryStr = self::composeQuery($query, $params, $abort); | |
1616 | ||
1617 | static $_dao = NULL; | |
1618 | ||
1619 | if (!$_dao) { | |
1620 | $_dao = new CRM_Core_DAO(); | |
1621 | } | |
1622 | ||
1623 | $_dao->query($queryStr, $i18nRewrite); | |
1624 | ||
1625 | $result = $_dao->getDatabaseResult(); | |
1626 | $ret = NULL; | |
1627 | if ($result) { | |
1628 | $row = $result->fetchRow(); | |
1629 | if ($row) { | |
1630 | $ret = $row[0]; | |
1631 | } | |
1632 | } | |
1633 | $_dao->free(); | |
1634 | return $ret; | |
1635 | } | |
1636 | ||
a0ee3941 | 1637 | /** |
edc8adfc | 1638 | * Compose the query by merging the parameters into it. |
1639 | * | |
1640 | * @param string $query | |
c490a46a | 1641 | * @param array $params |
a0ee3941 EM |
1642 | * @param bool $abort |
1643 | * | |
1644 | * @return string | |
22b4a080 | 1645 | * @throws CRM_Core_Exception |
a0ee3941 | 1646 | */ |
a954b445 | 1647 | public static function composeQuery($query, $params = [], $abort = TRUE) { |
be2fb01f | 1648 | $tr = []; |
6a488035 TO |
1649 | foreach ($params as $key => $item) { |
1650 | if (is_numeric($key)) { | |
1651 | if (CRM_Utils_Type::validate($item[0], $item[1]) !== NULL) { | |
1652 | $item[0] = self::escapeString($item[0]); | |
1653 | if ($item[1] == 'String' || | |
1654 | $item[1] == 'Memo' || | |
1655 | $item[1] == 'Link' | |
1656 | ) { | |
887a4028 A |
1657 | // Support class constants stipulating wildcard characters and/or |
1658 | // non-quoting of strings. Also support legacy code which may be | |
1659 | // passing in TRUE or 1 for $item[2], which used to indicate the | |
1660 | // use of wildcard characters. | |
1661 | if (!empty($item[2])) { | |
1662 | if ($item[2] & CRM_Core_DAO::QUERY_FORMAT_WILDCARD || $item[2] === TRUE) { | |
1663 | $item[0] = "'%{$item[0]}%'"; | |
1664 | } | |
1665 | elseif (!($item[2] & CRM_Core_DAO::QUERY_FORMAT_NO_QUOTES)) { | |
1666 | $item[0] = "'{$item[0]}'"; | |
1667 | } | |
6a488035 TO |
1668 | } |
1669 | else { | |
1670 | $item[0] = "'{$item[0]}'"; | |
1671 | } | |
1672 | } | |
1673 | ||
1674 | if (($item[1] == 'Date' || $item[1] == 'Timestamp') && | |
1675 | strlen($item[0]) == 0 | |
1676 | ) { | |
1677 | $item[0] = 'null'; | |
1678 | } | |
1679 | ||
1680 | $tr['%' . $key] = $item[0]; | |
1681 | } | |
1682 | elseif ($abort) { | |
d8bf477d | 1683 | throw new CRM_Core_Exception("{$item[0]} is not of type {$item[1]}"); |
6a488035 TO |
1684 | } |
1685 | } | |
1686 | } | |
1687 | ||
e2508c90 | 1688 | return strtr($query, $tr); |
6a488035 TO |
1689 | } |
1690 | ||
a0ee3941 EM |
1691 | /** |
1692 | * @param null $ids | |
1693 | */ | |
00be9182 | 1694 | public static function freeResult($ids = NULL) { |
6a488035 TO |
1695 | global $_DB_DATAOBJECT; |
1696 | ||
6a488035 TO |
1697 | if (!$ids) { |
1698 | if (!$_DB_DATAOBJECT || | |
1699 | !isset($_DB_DATAOBJECT['RESULTS']) | |
1700 | ) { | |
1701 | return; | |
1702 | } | |
1703 | $ids = array_keys($_DB_DATAOBJECT['RESULTS']); | |
1704 | } | |
1705 | ||
1706 | foreach ($ids as $id) { | |
1707 | if (isset($_DB_DATAOBJECT['RESULTS'][$id])) { | |
8f56d1f5 | 1708 | $_DB_DATAOBJECT['RESULTS'][$id]->free(); |
6a488035 TO |
1709 | unset($_DB_DATAOBJECT['RESULTS'][$id]); |
1710 | } | |
1711 | ||
1712 | if (isset($_DB_DATAOBJECT['RESULTFIELDS'][$id])) { | |
1713 | unset($_DB_DATAOBJECT['RESULTFIELDS'][$id]); | |
1714 | } | |
1715 | } | |
1716 | } | |
1717 | ||
1718 | /** | |
44ce4aa3 | 1719 | * Make a shallow copy of an object and all the fields in the object. |
6a488035 | 1720 | * |
6a0b768e TO |
1721 | * @param string $daoName |
1722 | * Name of the dao. | |
1723 | * @param array $criteria | |
1724 | * Array of all the fields & values. | |
44ce4aa3 | 1725 | * on which basis to copy |
6a0b768e TO |
1726 | * @param array $newData |
1727 | * Array of all the fields & values. | |
44ce4aa3 | 1728 | * to be copied besides the other fields |
6a0b768e TO |
1729 | * @param string $fieldsFix |
1730 | * Array of fields that you want to prefix/suffix/replace. | |
1731 | * @param string $blockCopyOfDependencies | |
1732 | * Fields that you want to block from. | |
44ce4aa3 | 1733 | * getting copied |
8c605c27 MD |
1734 | * @param bool $blockCopyofCustomValues |
1735 | * Case when you don't want to copy the custom values set in a | |
1736 | * template as it will override/ignore the submitted custom values | |
6a488035 | 1737 | * |
3fec1adc | 1738 | * @return CRM_Core_DAO|bool |
1739 | * the newly created copy of the object. False if none created. | |
6a488035 | 1740 | */ |
8c605c27 | 1741 | public static function copyGeneric($daoName, $criteria, $newData = NULL, $fieldsFix = NULL, $blockCopyOfDependencies = NULL, $blockCopyofCustomValues = FALSE) { |
353ffa53 | 1742 | $object = new $daoName(); |
3fec1adc | 1743 | $newObject = FALSE; |
6a488035 TO |
1744 | if (!$newData) { |
1745 | $object->id = $criteria['id']; | |
1746 | } | |
1747 | else { | |
1748 | foreach ($criteria as $key => $value) { | |
1749 | $object->$key = $value; | |
1750 | } | |
1751 | } | |
1752 | ||
1753 | $object->find(); | |
1754 | while ($object->fetch()) { | |
1755 | ||
1756 | // all the objects except with $blockCopyOfDependencies set | |
1757 | // be copied - addresses #CRM-1962 | |
1758 | ||
1759 | if ($blockCopyOfDependencies && $object->$blockCopyOfDependencies) { | |
1760 | break; | |
1761 | } | |
1762 | ||
353ffa53 | 1763 | $newObject = new $daoName(); |
6a488035 | 1764 | |
44ce4aa3 | 1765 | $fields = $object->fields(); |
6a488035 | 1766 | if (!is_array($fieldsFix)) { |
be2fb01f CW |
1767 | $fieldsToPrefix = []; |
1768 | $fieldsToSuffix = []; | |
1769 | $fieldsToReplace = []; | |
6a488035 | 1770 | } |
a7488080 | 1771 | if (!empty($fieldsFix['prefix'])) { |
6a488035 TO |
1772 | $fieldsToPrefix = $fieldsFix['prefix']; |
1773 | } | |
a7488080 | 1774 | if (!empty($fieldsFix['suffix'])) { |
6a488035 TO |
1775 | $fieldsToSuffix = $fieldsFix['suffix']; |
1776 | } | |
a7488080 | 1777 | if (!empty($fieldsFix['replace'])) { |
6a488035 TO |
1778 | $fieldsToReplace = $fieldsFix['replace']; |
1779 | } | |
1780 | ||
1781 | foreach ($fields as $name => $value) { | |
1782 | if ($name == 'id' || $value['name'] == 'id') { | |
1783 | // copy everything but the id! | |
1784 | continue; | |
1785 | } | |
1786 | ||
1787 | $dbName = $value['name']; | |
a1305c92 | 1788 | $type = CRM_Utils_Type::typeToString($value['type']); |
6a488035 TO |
1789 | $newObject->$dbName = $object->$dbName; |
1790 | if (isset($fieldsToPrefix[$dbName])) { | |
1791 | $newObject->$dbName = $fieldsToPrefix[$dbName] . $newObject->$dbName; | |
1792 | } | |
1793 | if (isset($fieldsToSuffix[$dbName])) { | |
1794 | $newObject->$dbName .= $fieldsToSuffix[$dbName]; | |
1795 | } | |
1796 | if (isset($fieldsToReplace[$dbName])) { | |
1797 | $newObject->$dbName = $fieldsToReplace[$dbName]; | |
1798 | } | |
1799 | ||
6c71f6c7 | 1800 | if ($type == 'Timestamp' || $type == 'Date') { |
6a488035 TO |
1801 | $newObject->$dbName = CRM_Utils_Date::isoToMysql($newObject->$dbName); |
1802 | } | |
1803 | ||
1804 | if ($newData) { | |
2e45b2f8 | 1805 | $newObject->copyValues($newData); |
6a488035 TO |
1806 | } |
1807 | } | |
1808 | $newObject->save(); | |
8c605c27 MD |
1809 | if (!$blockCopyofCustomValues) { |
1810 | $newObject->copyCustomFields($object->id, $newObject->id); | |
1811 | } | |
3d182a04 | 1812 | CRM_Utils_Hook::post('create', CRM_Core_DAO_AllCoreTables::getBriefName($daoName), $newObject->id, $newObject); |
6a488035 | 1813 | } |
ae70f47e | 1814 | |
6a488035 TO |
1815 | return $newObject; |
1816 | } | |
1817 | ||
50182f0e | 1818 | /** |
e60bcca6 | 1819 | * Method that copies custom fields values from an old entity to a new one. |
1820 | * | |
1821 | * Fixes bug CRM-19302, | |
50182f0e | 1822 | * where if a custom field of File type was present, left both events using the same file, |
1823 | * breaking download URL's for the old event. | |
1824 | * | |
1825 | * @todo the goal here is to clean this up so that it works for any entity. Copy Generic already DOES some custom field stuff | |
e60bcca6 | 1826 | * but it seems to be bypassed & perhaps less good than this (or this just duplicates it...) |
50182f0e | 1827 | * |
e60bcca6 | 1828 | * @param int $entityID |
1829 | * @param int $newEntityID | |
50182f0e | 1830 | */ |
e60bcca6 | 1831 | public function copyCustomFields($entityID, $newEntityID) { |
1832 | $entity = CRM_Core_DAO_AllCoreTables::getBriefName(get_class($this)); | |
1833 | $tableName = CRM_Core_DAO_AllCoreTables::getTableForClass(get_class($this)); | |
50182f0e | 1834 | // Obtain custom values for old event |
1835 | $customParams = $htmlType = []; | |
e60bcca6 | 1836 | $customValues = CRM_Core_BAO_CustomValueTable::getEntityValues($entityID, $entity); |
50182f0e | 1837 | |
1838 | // If custom values present, we copy them | |
1839 | if (!empty($customValues)) { | |
1840 | // Get Field ID's and identify File type attributes, to handle file copying. | |
1841 | $fieldIds = implode(', ', array_keys($customValues)); | |
1842 | $sql = "SELECT id FROM civicrm_custom_field WHERE html_type = 'File' AND id IN ( {$fieldIds} )"; | |
1843 | $result = CRM_Core_DAO::executeQuery($sql); | |
1844 | ||
1845 | // Build array of File type fields | |
1846 | while ($result->fetch()) { | |
1847 | $htmlType[] = $result->id; | |
1848 | } | |
1849 | ||
1850 | // Build params array of custom values | |
1851 | foreach ($customValues as $field => $value) { | |
1852 | if ($value !== NULL) { | |
1853 | // Handle File type attributes | |
1854 | if (in_array($field, $htmlType)) { | |
e60bcca6 | 1855 | $fileValues = CRM_Core_BAO_File::path($value, $entityID); |
50182f0e | 1856 | $customParams["custom_{$field}_-1"] = [ |
1857 | 'name' => CRM_Utils_File::duplicate($fileValues[0]), | |
1858 | 'type' => $fileValues[1], | |
1859 | ]; | |
1860 | } | |
1861 | // Handle other types | |
1862 | else { | |
1863 | $customParams["custom_{$field}_-1"] = $value; | |
1864 | } | |
1865 | } | |
1866 | } | |
1867 | ||
1868 | // Save Custom Fields for new Event | |
e60bcca6 | 1869 | CRM_Core_BAO_CustomValueTable::postProcess($customParams, $tableName, $newEntityID, $entity); |
50182f0e | 1870 | } |
1871 | ||
1872 | // copy activity attachments ( if any ) | |
e60bcca6 | 1873 | CRM_Core_BAO_File::copyEntityFile($tableName, $entityID, $tableName, $newEntityID); |
50182f0e | 1874 | } |
1875 | ||
7a9ab499 EM |
1876 | /** |
1877 | * Cascade update through related entities. | |
1878 | * | |
1879 | * @param string $daoName | |
1880 | * @param $fromId | |
1881 | * @param $toId | |
1882 | * @param array $newData | |
1883 | * | |
1273d77c | 1884 | * @return CRM_Core_DAO|null |
7a9ab499 | 1885 | */ |
be2fb01f | 1886 | public static function cascadeUpdate($daoName, $fromId, $toId, $newData = []) { |
353ffa53 | 1887 | $object = new $daoName(); |
62933949 | 1888 | $object->id = $fromId; |
1889 | ||
1890 | if ($object->find(TRUE)) { | |
353ffa53 | 1891 | $newObject = new $daoName(); |
62933949 | 1892 | $newObject->id = $toId; |
1893 | ||
1894 | if ($newObject->find(TRUE)) { | |
44ce4aa3 | 1895 | $fields = $object->fields(); |
62933949 | 1896 | foreach ($fields as $name => $value) { |
1897 | if ($name == 'id' || $value['name'] == 'id') { | |
1898 | // copy everything but the id! | |
1899 | continue; | |
1900 | } | |
1901 | ||
1902 | $colName = $value['name']; | |
1903 | $newObject->$colName = $object->$colName; | |
1904 | ||
1905 | if (substr($name, -5) == '_date' || | |
1906 | substr($name, -10) == '_date_time' | |
1907 | ) { | |
1908 | $newObject->$colName = CRM_Utils_Date::isoToMysql($newObject->$colName); | |
1909 | } | |
1910 | } | |
1911 | foreach ($newData as $k => $v) { | |
1912 | $newObject->$k = $v; | |
1913 | } | |
1914 | $newObject->save(); | |
1915 | return $newObject; | |
1916 | } | |
1917 | } | |
1273d77c | 1918 | return NULL; |
62933949 | 1919 | } |
1920 | ||
6a488035 TO |
1921 | /** |
1922 | * Given the component id, compute the contact id | |
1923 | * since its used for things like send email | |
b3342109 EM |
1924 | * |
1925 | * @param $componentIDs | |
100fef9d | 1926 | * @param string $tableName |
d94a02b4 | 1927 | * @param string $idField |
6e3090fb | 1928 | * |
b3342109 | 1929 | * @return array |
6a488035 | 1930 | */ |
d94a02b4 | 1931 | public static function getContactIDsFromComponent($componentIDs, $tableName, $idField = 'id') { |
be2fb01f | 1932 | $contactIDs = []; |
6a488035 TO |
1933 | |
1934 | if (empty($componentIDs)) { | |
1935 | return $contactIDs; | |
1936 | } | |
1937 | ||
1938 | $IDs = implode(',', $componentIDs); | |
1939 | $query = " | |
1940 | SELECT contact_id | |
1941 | FROM $tableName | |
d94a02b4 | 1942 | WHERE $idField IN ( $IDs ) |
6a488035 TO |
1943 | "; |
1944 | ||
1945 | $dao = CRM_Core_DAO::executeQuery($query); | |
1946 | while ($dao->fetch()) { | |
1947 | $contactIDs[] = $dao->contact_id; | |
1948 | } | |
1949 | return $contactIDs; | |
1950 | } | |
1951 | ||
1952 | /** | |
fe482240 | 1953 | * Fetch object based on array of properties. |
6a488035 | 1954 | * |
6a0b768e TO |
1955 | * @param string $daoName |
1956 | * Name of the dao object. | |
dd244018 | 1957 | * @param string $fieldIdName |
100fef9d | 1958 | * @param int $fieldId |
dd244018 | 1959 | * @param $details |
6a0b768e TO |
1960 | * @param array $returnProperities |
1961 | * An assoc array of fields that need to be returned, eg array( 'first_name', 'last_name'). | |
dd244018 | 1962 | * |
a6c01b45 CW |
1963 | * @return object |
1964 | * an object of type referenced by daoName | |
6a488035 | 1965 | */ |
00be9182 | 1966 | public static function commonRetrieveAll($daoName, $fieldIdName = 'id', $fieldId, &$details, $returnProperities = NULL) { |
795492f3 | 1967 | require_once str_replace('_', DIRECTORY_SEPARATOR, $daoName) . ".php"; |
353ffa53 | 1968 | $object = new $daoName(); |
6a488035 TO |
1969 | $object->$fieldIdName = $fieldId; |
1970 | ||
1971 | // return only specific fields if returnproperties are sent | |
1972 | if (!empty($returnProperities)) { | |
1973 | $object->selectAdd(); | |
1974 | $object->selectAdd('id'); | |
1975 | $object->selectAdd(implode(',', $returnProperities)); | |
1976 | } | |
1977 | ||
1978 | $object->find(); | |
1979 | while ($object->fetch()) { | |
be2fb01f | 1980 | $defaults = []; |
6a488035 TO |
1981 | self::storeValues($object, $defaults); |
1982 | $details[$object->id] = $defaults; | |
1983 | } | |
1984 | ||
1985 | return $details; | |
1986 | } | |
1987 | ||
44ce4aa3 CW |
1988 | /** |
1989 | * Drop all CiviCRM tables. | |
1990 | * | |
ff48e573 | 1991 | * @throws \CRM_Core_Exception |
44ce4aa3 | 1992 | */ |
00be9182 | 1993 | public static function dropAllTables() { |
6a488035 TO |
1994 | |
1995 | // first drop all the custom tables we've created | |
1996 | CRM_Core_BAO_CustomGroup::dropAllTables(); | |
1997 | ||
1998 | // drop all multilingual views | |
1999 | CRM_Core_I18n_Schema::dropAllViews(); | |
2000 | ||
2001 | CRM_Utils_File::sourceSQLFile(CIVICRM_DSN, | |
2002 | dirname(__FILE__) . DIRECTORY_SEPARATOR . | |
2003 | '..' . DIRECTORY_SEPARATOR . | |
2004 | '..' . DIRECTORY_SEPARATOR . | |
2005 | 'sql' . DIRECTORY_SEPARATOR . | |
2006 | 'civicrm_drop.mysql' | |
2007 | ); | |
2008 | } | |
2009 | ||
a0ee3941 EM |
2010 | /** |
2011 | * @param $string | |
2012 | * | |
2013 | * @return string | |
2014 | */ | |
00be9182 | 2015 | public static function escapeString($string) { |
6a488035 | 2016 | static $_dao = NULL; |
6a488035 | 2017 | if (!$_dao) { |
8f56d1f5 MM |
2018 | // If this is an atypical case (e.g. preparing .sql file before CiviCRM |
2019 | // has been installed), then we fallback DB-less str_replace escaping, as | |
2020 | // we can't use mysqli_real_escape_string, as there is no DB connection. | |
2021 | // Note: In typical usage, escapeString() will only check one conditional | |
2022 | // ("if !$_dao") rather than two conditionals ("if !defined(DSN)") | |
74032946 | 2023 | if (!defined('CIVICRM_DSN')) { |
8f56d1f5 MM |
2024 | // See http://php.net/manual/en/mysqli.real-escape-string.php for the |
2025 | // list of characters mysqli_real_escape_string escapes. | |
be2fb01f CW |
2026 | $search = ["\\", "\x00", "\n", "\r", "'", '"', "\x1a"]; |
2027 | $replace = ["\\\\", "\\0", "\\n", "\\r", "\'", '\"', "\\Z"]; | |
8f56d1f5 | 2028 | return str_replace($search, $replace, $string); |
74032946 | 2029 | } |
6a488035 TO |
2030 | $_dao = new CRM_Core_DAO(); |
2031 | } | |
6a488035 TO |
2032 | return $_dao->escape($string); |
2033 | } | |
2034 | ||
2035 | /** | |
2036 | * Escape a list of strings for use with "WHERE X IN (...)" queries. | |
2037 | * | |
5a4f6742 CW |
2038 | * @param array $strings |
2039 | * @param string $default | |
2040 | * the value to use if $strings has no elements. | |
a6c01b45 CW |
2041 | * @return string |
2042 | * eg "abc","def","ghi" | |
6a488035 | 2043 | */ |
00be9182 | 2044 | public static function escapeStrings($strings, $default = NULL) { |
6a488035 TO |
2045 | static $_dao = NULL; |
2046 | if (!$_dao) { | |
2047 | $_dao = new CRM_Core_DAO(); | |
2048 | } | |
2049 | ||
2050 | if (empty($strings)) { | |
2051 | return $default; | |
2052 | } | |
2053 | ||
be2fb01f | 2054 | $escapes = array_map([$_dao, 'escape'], $strings); |
6a488035 TO |
2055 | return '"' . implode('","', $escapes) . '"'; |
2056 | } | |
2057 | ||
a0ee3941 EM |
2058 | /** |
2059 | * @param $string | |
2060 | * | |
2061 | * @return string | |
2062 | */ | |
00be9182 | 2063 | public static function escapeWildCardString($string) { |
6a488035 TO |
2064 | // CRM-9155 |
2065 | // ensure we escape the single characters % and _ which are mysql wild | |
2066 | // card characters and could come in via sortByCharacter | |
2067 | // note that mysql does not escape these characters | |
2068 | if ($string && in_array($string, | |
be2fb01f | 2069 | ['%', '_', '%%', '_%'] |
353ffa53 TO |
2070 | ) |
2071 | ) { | |
6a488035 TO |
2072 | return '\\' . $string; |
2073 | } | |
2074 | ||
2075 | return self::escapeString($string); | |
2076 | } | |
2077 | ||
92b83508 EM |
2078 | /** |
2079 | * Creates a test object, including any required objects it needs via recursion | |
b3342109 EM |
2080 | * createOnly: only create in database, do not store or return the objects (useful for perf testing) |
2081 | * ONLY USE FOR TESTING | |
2082 | * | |
c490a46a | 2083 | * @param string $daoName |
b3342109 EM |
2084 | * @param array $params |
2085 | * @param int $numObjects | |
2086 | * @param bool $createOnly | |
2087 | * | |
795492f3 TO |
2088 | * @return object|array|NULL |
2089 | * NULL if $createOnly. A single object if $numObjects==1. Otherwise, an array of multiple objects. | |
92b83508 | 2090 | */ |
795492f3 | 2091 | public static function createTestObject( |
6a488035 | 2092 | $daoName, |
be2fb01f | 2093 | $params = [], |
6a488035 TO |
2094 | $numObjects = 1, |
2095 | $createOnly = FALSE | |
2096 | ) { | |
b6262a4c EM |
2097 | //this is a test function also backtrace is set for the test suite it sometimes unsets itself |
2098 | // so we re-set here in case | |
2099 | $config = CRM_Core_Config::singleton(); | |
2100 | $config->backtrace = TRUE; | |
2101 | ||
6a488035 | 2102 | static $counter = 0; |
be2fb01f | 2103 | CRM_Core_DAO::$_testEntitiesToSkip = [ |
6a488035 TO |
2104 | 'CRM_Core_DAO_Worldregion', |
2105 | 'CRM_Core_DAO_StateProvince', | |
2106 | 'CRM_Core_DAO_Country', | |
2107 | 'CRM_Core_DAO_Domain', | |
795492f3 | 2108 | 'CRM_Financial_DAO_FinancialType', |
353ffa53 | 2109 | //because valid ones exist & we use pick them due to pseudoconstant can't reliably create & delete these |
be2fb01f | 2110 | ]; |
6a488035 | 2111 | |
2069d1b7 TO |
2112 | // Prefer to instantiate BAO's instead of DAO's (when possible) |
2113 | // so that assignTestValue()/assignTestFK() can be overloaded. | |
2114 | $baoName = str_replace('_DAO_', '_BAO_', $daoName); | |
a494d7a3 | 2115 | if ($baoName === 'CRM_Financial_BAO_FinancialTrxn') { |
2116 | // OMG OMG OMG this is so incredibly bad. The BAO is insanely named. | |
2117 | // @todo create a new class called what the BAO SHOULD be | |
2118 | // that extends BAO-crazy-name.... migrate. | |
2119 | $baoName = 'CRM_Core_BAO_FinancialTrxn'; | |
2120 | } | |
2069d1b7 TO |
2121 | if (class_exists($baoName)) { |
2122 | $daoName = $baoName; | |
2123 | } | |
2124 | ||
6a488035 TO |
2125 | for ($i = 0; $i < $numObjects; ++$i) { |
2126 | ||
2127 | ++$counter; | |
e79cd558 | 2128 | /** @var CRM_Core_DAO $object */ |
ab9aa379 | 2129 | $object = new $daoName(); |
6a488035 | 2130 | |
44ce4aa3 | 2131 | $fields = $object->fields(); |
e1b64aab TO |
2132 | foreach ($fields as $fieldName => $fieldDef) { |
2133 | $dbName = $fieldDef['name']; | |
9c1bc317 | 2134 | $FKClassName = $fieldDef['FKClassName'] ?? NULL; |
f290b6ef | 2135 | |
015ba54e | 2136 | if (isset($params[$dbName]) && !is_array($params[$dbName])) { |
6a488035 TO |
2137 | $object->$dbName = $params[$dbName]; |
2138 | } | |
2139 | ||
2140 | elseif ($dbName != 'id') { | |
f290b6ef | 2141 | if ($FKClassName != NULL) { |
e79cd558 | 2142 | $object->assignTestFK($fieldName, $fieldDef, $params); |
6a488035 | 2143 | continue; |
0db6c3e1 TO |
2144 | } |
2145 | else { | |
f290b6ef | 2146 | $object->assignTestValue($fieldName, $fieldDef, $counter); |
6a488035 | 2147 | } |
6a488035 TO |
2148 | } |
2149 | } | |
b3342109 | 2150 | |
6a488035 TO |
2151 | $object->save(); |
2152 | ||
2153 | if (!$createOnly) { | |
6a488035 | 2154 | $objects[$i] = $object; |
6a488035 | 2155 | } |
f290b6ef TO |
2156 | else { |
2157 | unset($object); | |
2158 | } | |
6a488035 TO |
2159 | } |
2160 | ||
2161 | if ($createOnly) { | |
795492f3 | 2162 | return NULL; |
6a488035 | 2163 | } |
f290b6ef TO |
2164 | elseif ($numObjects == 1) { |
2165 | return $objects[0]; | |
2166 | } | |
2167 | else { | |
2168 | return $objects; | |
2169 | } | |
6a488035 TO |
2170 | } |
2171 | ||
92b83508 | 2172 | /** |
fe482240 | 2173 | * Deletes the this object plus any dependent objects that are associated with it. |
92b83508 | 2174 | * ONLY USE FOR TESTING |
b3342109 | 2175 | * |
c490a46a | 2176 | * @param string $daoName |
b3342109 | 2177 | * @param array $params |
92b83508 | 2178 | */ |
be2fb01f | 2179 | public static function deleteTestObjects($daoName, $params = []) { |
b6262a4c EM |
2180 | //this is a test function also backtrace is set for the test suite it sometimes unsets itself |
2181 | // so we re-set here in case | |
2182 | $config = CRM_Core_Config::singleton(); | |
2183 | $config->backtrace = TRUE; | |
6a488035 | 2184 | |
b6262a4c | 2185 | $object = new $daoName(); |
9c1bc317 | 2186 | $object->id = $params['id'] ?? NULL; |
6a488035 | 2187 | |
518fa0ee SL |
2188 | // array(array(0 => $daoName, 1 => $daoParams)) |
2189 | $deletions = []; | |
6a488035 TO |
2190 | if ($object->find(TRUE)) { |
2191 | ||
44ce4aa3 | 2192 | $fields = $object->fields(); |
6a488035 TO |
2193 | foreach ($fields as $name => $value) { |
2194 | ||
2195 | $dbName = $value['name']; | |
2196 | ||
9c1bc317 CW |
2197 | $FKClassName = $value['FKClassName'] ?? NULL; |
2198 | $required = $value['required'] ?? NULL; | |
6a488035 TO |
2199 | if ($FKClassName != NULL |
2200 | && $object->$dbName | |
2201 | && !in_array($FKClassName, CRM_Core_DAO::$_testEntitiesToSkip) | |
806e9b71 EM |
2202 | && ($required || $dbName == 'contact_id') |
2203 | //I'm a bit stuck on this one - we might need to change the singleValueAlter so that the entities don't share a contact | |
2204 | // to make this test process pass - line below makes pass for now | |
353ffa53 TO |
2205 | && $dbName != 'member_of_contact_id' |
2206 | ) { | |
518fa0ee SL |
2207 | // x |
2208 | $deletions[] = [$FKClassName, ['id' => $object->$dbName]]; | |
6a488035 TO |
2209 | } |
2210 | } | |
2211 | } | |
2212 | ||
2213 | $object->delete(); | |
2214 | ||
2215 | foreach ($deletions as $deletion) { | |
2216 | CRM_Core_DAO::deleteTestObjects($deletion[0], $deletion[1]); | |
353ffa53 | 2217 | } |
6a488035 TO |
2218 | } |
2219 | ||
64d24a64 | 2220 | /** |
fe482240 | 2221 | * Set defaults when creating new entity. |
64d24a64 EM |
2222 | * (don't call this set defaults as already in use with different signature in some places) |
2223 | * | |
c490a46a | 2224 | * @param array $params |
64d24a64 EM |
2225 | * @param $defaults |
2226 | */ | |
00be9182 | 2227 | public static function setCreateDefaults(&$params, $defaults) { |
16e268ad | 2228 | if (!empty($params['id'])) { |
64d24a64 EM |
2229 | return; |
2230 | } | |
2231 | foreach ($defaults as $key => $value) { | |
2232 | if (!array_key_exists($key, $params) || $params[$key] === NULL) { | |
2233 | $params[$key] = $value; | |
2234 | } | |
2235 | } | |
2236 | } | |
2237 | ||
a0ee3941 EM |
2238 | /** |
2239 | * @param string $prefix | |
2240 | * @param bool $addRandomString | |
2241 | * @param null $string | |
2242 | * | |
2243 | * @return string | |
00f8d61b TO |
2244 | * @deprecated |
2245 | * @see CRM_Utils_SQL_TempTable | |
a0ee3941 | 2246 | */ |
00be9182 | 2247 | public static function createTempTableName($prefix = 'civicrm', $addRandomString = TRUE, $string = NULL) { |
5b508244 | 2248 | CRM_Core_Error::deprecatedFunctionWarning('Use CRM_Utils_SQL_TempTable interface to create temporary tables'); |
6a488035 TO |
2249 | $tableName = $prefix . "_temp"; |
2250 | ||
2251 | if ($addRandomString) { | |
2252 | if ($string) { | |
2253 | $tableName .= "_" . $string; | |
2254 | } | |
2255 | else { | |
2256 | $tableName .= "_" . md5(uniqid('', TRUE)); | |
2257 | } | |
2258 | } | |
2259 | return $tableName; | |
2260 | } | |
2261 | ||
a0ee3941 EM |
2262 | /** |
2263 | * @param bool $view | |
2264 | * @param bool $trigger | |
2265 | * | |
2266 | * @return bool | |
2267 | */ | |
00be9182 | 2268 | public static function checkTriggerViewPermission($view = TRUE, $trigger = TRUE) { |
344b05bc | 2269 | if (\Civi::settings()->get('logging_no_trigger_permission')) { |
2270 | return TRUE; | |
2271 | } | |
6a488035 TO |
2272 | // test for create view and trigger permissions and if allowed, add the option to go multilingual |
2273 | // and logging | |
2274 | // I'm not sure why we use the getStaticProperty for an error, rather than checking for DB_Error | |
344b05bc | 2275 | CRM_Core_TemporaryErrorScope::ignoreException(); |
6a488035 TO |
2276 | $dao = new CRM_Core_DAO(); |
2277 | if ($view) { | |
cc7762c0 | 2278 | $result = $dao->query('CREATE OR REPLACE VIEW civicrm_domain_view AS SELECT * FROM civicrm_domain'); |
2279 | if (PEAR::getStaticProperty('DB_DataObject', 'lastError') || is_a($result, 'DB_Error')) { | |
6a488035 TO |
2280 | return FALSE; |
2281 | } | |
2282 | } | |
2283 | ||
2284 | if ($trigger) { | |
2285 | $result = $dao->query('CREATE TRIGGER civicrm_domain_trigger BEFORE INSERT ON civicrm_domain FOR EACH ROW BEGIN END'); | |
2286 | if (PEAR::getStaticProperty('DB_DataObject', 'lastError') || is_a($result, 'DB_Error')) { | |
6a488035 TO |
2287 | if ($view) { |
2288 | $dao->query('DROP VIEW IF EXISTS civicrm_domain_view'); | |
2289 | } | |
2290 | return FALSE; | |
2291 | } | |
2292 | ||
2293 | $dao->query('DROP TRIGGER IF EXISTS civicrm_domain_trigger'); | |
2294 | if (PEAR::getStaticProperty('DB_DataObject', 'lastError')) { | |
6a488035 TO |
2295 | if ($view) { |
2296 | $dao->query('DROP VIEW IF EXISTS civicrm_domain_view'); | |
2297 | } | |
2298 | return FALSE; | |
2299 | } | |
2300 | } | |
2301 | ||
2302 | if ($view) { | |
2303 | $dao->query('DROP VIEW IF EXISTS civicrm_domain_view'); | |
2304 | if (PEAR::getStaticProperty('DB_DataObject', 'lastError')) { | |
6a488035 TO |
2305 | return FALSE; |
2306 | } | |
2307 | } | |
6a488035 TO |
2308 | |
2309 | return TRUE; | |
2310 | } | |
2311 | ||
a0ee3941 EM |
2312 | /** |
2313 | * @param null $message | |
2314 | * @param bool $printDAO | |
2315 | */ | |
00be9182 | 2316 | public static function debugPrint($message = NULL, $printDAO = TRUE) { |
6a488035 TO |
2317 | CRM_Utils_System::xMemory("{$message}: "); |
2318 | ||
2319 | if ($printDAO) { | |
2320 | global $_DB_DATAOBJECT; | |
be2fb01f | 2321 | $q = []; |
6a488035 TO |
2322 | foreach (array_keys($_DB_DATAOBJECT['RESULTS']) as $id) { |
2323 | $q[] = $_DB_DATAOBJECT['RESULTS'][$id]->query; | |
2324 | } | |
2325 | CRM_Core_Error::debug('_DB_DATAOBJECT', $q); | |
2326 | } | |
2327 | } | |
2328 | ||
77b97be7 EM |
2329 | /** |
2330 | * Build a list of triggers via hook and add them to (err, reconcile them | |
2331 | * with) the database. | |
2332 | * | |
5a4f6742 CW |
2333 | * @param string $tableName |
2334 | * the specific table requiring a rebuild; or NULL to rebuild all tables. | |
77b97be7 | 2335 | * @param bool $force |
4ed867e0 | 2336 | * @deprecated |
77b97be7 EM |
2337 | * |
2338 | * @see CRM-9716 | |
2339 | */ | |
00be9182 | 2340 | public static function triggerRebuild($tableName = NULL, $force = FALSE) { |
4ed867e0 | 2341 | Civi::service('sql_triggers')->rebuild($tableName, $force); |
6a488035 TO |
2342 | } |
2343 | ||
aca2de91 CW |
2344 | /** |
2345 | * Because sql functions are sometimes lost, esp during db migration, we check here to avoid numerous support requests | |
2346 | * @see http://issues.civicrm.org/jira/browse/CRM-13822 | |
2347 | * TODO: Alternative solutions might be | |
2348 | * * Stop using functions and find another way to strip numeric characters from phones | |
2349 | * * Give better error messages (currently a missing fn fatals with "unknown error") | |
2350 | */ | |
00be9182 | 2351 | public static function checkSqlFunctionsExist() { |
aca2de91 CW |
2352 | if (!self::$_checkedSqlFunctionsExist) { |
2353 | self::$_checkedSqlFunctionsExist = TRUE; | |
2354 | $dao = CRM_Core_DAO::executeQuery("SHOW function status WHERE db = database() AND name = 'civicrm_strip_non_numeric'"); | |
2355 | if (!$dao->fetch()) { | |
2356 | self::triggerRebuild(); | |
2357 | } | |
2358 | } | |
2359 | } | |
2360 | ||
6a488035 | 2361 | /** |
fe482240 | 2362 | * Wrapper function to drop triggers. |
6a488035 | 2363 | * |
5a4f6742 CW |
2364 | * @param string $tableName |
2365 | * the specific table requiring a rebuild; or NULL to rebuild all tables. | |
4ed867e0 | 2366 | * @deprecated |
6a488035 | 2367 | */ |
00be9182 | 2368 | public static function dropTriggers($tableName = NULL) { |
4ed867e0 | 2369 | Civi::service('sql_triggers')->dropTriggers($tableName); |
6a488035 TO |
2370 | } |
2371 | ||
2372 | /** | |
5a4f6742 CW |
2373 | * @param array $info |
2374 | * per hook_civicrm_triggerInfo. | |
2375 | * @param string $onlyTableName | |
2376 | * the specific table requiring a rebuild; or NULL to rebuild all tables. | |
4ed867e0 | 2377 | * @deprecated |
6a488035 | 2378 | */ |
00be9182 | 2379 | public static function createTriggers(&$info, $onlyTableName = NULL) { |
4ed867e0 | 2380 | Civi::service('sql_triggers')->createTriggers($info, $onlyTableName); |
6a488035 TO |
2381 | } |
2382 | ||
ffcef054 TO |
2383 | /** |
2384 | * Given a list of fields, create a list of references. | |
2385 | * | |
6a0b768e TO |
2386 | * @param string $className |
2387 | * BAO/DAO class name. | |
ffcef054 TO |
2388 | * @return array<CRM_Core_Reference_Interface> |
2389 | */ | |
00be9182 | 2390 | public static function createReferenceColumns($className) { |
be2fb01f | 2391 | $result = []; |
ffcef054 TO |
2392 | $fields = $className::fields(); |
2393 | foreach ($fields as $field) { | |
2394 | if (isset($field['pseudoconstant'], $field['pseudoconstant']['optionGroupName'])) { | |
2395 | $result[] = new CRM_Core_Reference_OptionValue( | |
2396 | $className::getTableName(), | |
2397 | $field['name'], | |
2398 | 'civicrm_option_value', | |
2399 | CRM_Utils_Array::value('keyColumn', $field['pseudoconstant'], 'value'), | |
2400 | $field['pseudoconstant']['optionGroupName'] | |
2401 | ); | |
2402 | } | |
2403 | } | |
2404 | return $result; | |
2405 | } | |
2406 | ||
6a488035 | 2407 | /** |
71e5aa5c ARW |
2408 | * Find all records which refer to this entity. |
2409 | * | |
a6c01b45 | 2410 | * @return array |
16b10e64 | 2411 | * Array of objects referencing this |
71e5aa5c | 2412 | */ |
00be9182 | 2413 | public function findReferences() { |
71e5aa5c ARW |
2414 | $links = self::getReferencesToTable(static::getTableName()); |
2415 | ||
be2fb01f | 2416 | $occurrences = []; |
71e5aa5c | 2417 | foreach ($links as $refSpec) { |
11626cf1 | 2418 | /** @var $refSpec CRM_Core_Reference_Interface */ |
31bed28c | 2419 | $daoName = CRM_Core_DAO_AllCoreTables::getClassForTable($refSpec->getReferenceTable()); |
de49f39c | 2420 | $result = $refSpec->findReferences($this); |
ffcef054 TO |
2421 | if ($result) { |
2422 | while ($result->fetch()) { | |
2423 | $obj = new $daoName(); | |
2424 | $obj->id = $result->id; | |
2425 | $occurrences[] = $obj; | |
2426 | } | |
71e5aa5c ARW |
2427 | } |
2428 | } | |
2429 | ||
2430 | return $occurrences; | |
2431 | } | |
2432 | ||
a0ee3941 | 2433 | /** |
a6c01b45 CW |
2434 | * @return array |
2435 | * each item has keys: | |
16b10e64 CW |
2436 | * - name: string |
2437 | * - type: string | |
2438 | * - count: int | |
2439 | * - table: string|null SQL table name | |
2440 | * - key: string|null SQL column name | |
a0ee3941 | 2441 | */ |
00be9182 | 2442 | public function getReferenceCounts() { |
1256c139 TO |
2443 | $links = self::getReferencesToTable(static::getTableName()); |
2444 | ||
be2fb01f | 2445 | $counts = []; |
1256c139 TO |
2446 | foreach ($links as $refSpec) { |
2447 | /** @var $refSpec CRM_Core_Reference_Interface */ | |
2448 | $count = $refSpec->getReferenceCount($this); | |
2449 | if ($count['count'] != 0) { | |
2450 | $counts[] = $count; | |
2451 | } | |
2452 | } | |
2453 | ||
91dee34b TO |
2454 | foreach (CRM_Core_Component::getEnabledComponents() as $component) { |
2455 | /** @var $component CRM_Core_Component_Info */ | |
2456 | $counts = array_merge($counts, $component->getReferenceCounts($this)); | |
2457 | } | |
2458 | CRM_Utils_Hook::referenceCounts($this, $counts); | |
2459 | ||
1256c139 TO |
2460 | return $counts; |
2461 | } | |
2462 | ||
71e5aa5c ARW |
2463 | /** |
2464 | * List all tables which have hard foreign keys to this table. | |
6a488035 | 2465 | * |
71e5aa5c ARW |
2466 | * For now, this returns a description of every entity_id/entity_table |
2467 | * reference. | |
2468 | * TODO: filter dynamic entity references on the $tableName, based on | |
2469 | * schema metadata in dynamicForeignKey which enumerates a restricted | |
2470 | * set of possible entity_table's. | |
6a488035 | 2471 | * |
6a0b768e TO |
2472 | * @param string $tableName |
2473 | * Table referred to. | |
6a488035 | 2474 | * |
a6c01b45 CW |
2475 | * @return array |
2476 | * structure of table and column, listing every table with a | |
16b10e64 | 2477 | * foreign key reference to $tableName, and the column where the key appears. |
6a488035 | 2478 | */ |
00be9182 | 2479 | public static function getReferencesToTable($tableName) { |
be2fb01f | 2480 | $refsFound = []; |
31bed28c | 2481 | foreach (CRM_Core_DAO_AllCoreTables::getClasses() as $daoClassName) { |
71e5aa5c | 2482 | $links = $daoClassName::getReferenceColumns(); |
71e5aa5c ARW |
2483 | |
2484 | foreach ($links as $refSpec) { | |
11626cf1 TO |
2485 | /** @var $refSpec CRM_Core_Reference_Interface */ |
2486 | if ($refSpec->matchesTargetTable($tableName)) { | |
71e5aa5c ARW |
2487 | $refsFound[] = $refSpec; |
2488 | } | |
6a488035 TO |
2489 | } |
2490 | } | |
71e5aa5c | 2491 | return $refsFound; |
6a488035 | 2492 | } |
032c9d10 | 2493 | |
e3e87c73 | 2494 | /** |
2495 | * Get all references to contact table. | |
2496 | * | |
2497 | * This includes core tables, custom group tables, tables added by the merge | |
2498 | * hook and the entity_tag table. | |
2499 | * | |
2500 | * Refer to CRM-17454 for information on the danger of querying the information | |
2501 | * schema to derive this. | |
eca28463 | 2502 | * |
2503 | * @throws \CiviCRM_API3_Exception | |
e3e87c73 | 2504 | */ |
2505 | public static function getReferencesToContactTable() { | |
2506 | if (isset(\Civi::$statics[__CLASS__]) && isset(\Civi::$statics[__CLASS__]['contact_references'])) { | |
2507 | return \Civi::$statics[__CLASS__]['contact_references']; | |
2508 | } | |
2509 | $contactReferences = []; | |
2510 | $coreReferences = CRM_Core_DAO::getReferencesToTable('civicrm_contact'); | |
2511 | foreach ($coreReferences as $coreReference) { | |
2512 | if (!is_a($coreReference, 'CRM_Core_Reference_Dynamic')) { | |
2513 | $contactReferences[$coreReference->getReferenceTable()][] = $coreReference->getReferenceKey(); | |
2514 | } | |
2515 | } | |
2516 | self::appendCustomTablesExtendingContacts($contactReferences); | |
4c7e5001 | 2517 | self::appendCustomContactReferenceFields($contactReferences); |
e3e87c73 | 2518 | \Civi::$statics[__CLASS__]['contact_references'] = $contactReferences; |
2519 | return \Civi::$statics[__CLASS__]['contact_references']; | |
2520 | } | |
2521 | ||
eca28463 | 2522 | /** |
2523 | * Get all dynamic references to the given table. | |
2524 | * | |
2525 | * @param string $tableName | |
2526 | * | |
2527 | * @return array | |
2528 | */ | |
2529 | public static function getDynamicReferencesToTable($tableName) { | |
2530 | if (!isset(\Civi::$statics[__CLASS__]['contact_references_dynamic'][$tableName])) { | |
2531 | \Civi::$statics[__CLASS__]['contact_references_dynamic'][$tableName] = []; | |
2532 | $coreReferences = CRM_Core_DAO::getReferencesToTable($tableName); | |
2533 | foreach ($coreReferences as $coreReference) { | |
2534 | if ($coreReference instanceof \CRM_Core_Reference_Dynamic) { | |
9811efd4 | 2535 | \Civi::$statics[__CLASS__]['contact_references_dynamic'][$tableName][$coreReference->getReferenceTable()][] = [$coreReference->getReferenceKey(), $coreReference->getTypeColumn()]; |
eca28463 | 2536 | } |
2537 | } | |
2538 | } | |
2539 | return \Civi::$statics[__CLASS__]['contact_references_dynamic'][$tableName]; | |
2540 | } | |
2541 | ||
e3e87c73 | 2542 | /** |
2543 | * Add custom tables that extend contacts to the list of contact references. | |
2544 | * | |
2545 | * CRM_Core_BAO_CustomGroup::getAllCustomGroupsByBaseEntity seems like a safe-ish | |
2546 | * function to be sure all are retrieved & we don't miss subtypes or inactive or multiples | |
2547 | * - the down side is it is not cached. | |
2548 | * | |
2549 | * Further changes should be include tests in the CRM_Core_MergerTest class | |
2550 | * to ensure that disabled, subtype, multiple etc groups are still captured. | |
2551 | * | |
2552 | * @param array $cidRefs | |
2553 | */ | |
2554 | public static function appendCustomTablesExtendingContacts(&$cidRefs) { | |
2555 | $customValueTables = CRM_Core_BAO_CustomGroup::getAllCustomGroupsByBaseEntity('Contact'); | |
2556 | $customValueTables->find(); | |
2557 | while ($customValueTables->fetch()) { | |
4c7e5001 PF |
2558 | $cidRefs[$customValueTables->table_name][] = 'entity_id'; |
2559 | } | |
2560 | } | |
2561 | ||
2562 | /** | |
2563 | * Add custom ContactReference fields to the list of contact references | |
2564 | * | |
2565 | * This includes active and inactive fields/groups | |
2566 | * | |
2567 | * @param array $cidRefs | |
2568 | * | |
2569 | * @throws \CiviCRM_API3_Exception | |
2570 | */ | |
2571 | public static function appendCustomContactReferenceFields(&$cidRefs) { | |
2572 | $fields = civicrm_api3('CustomField', 'get', [ | |
2573 | 'return' => ['column_name', 'custom_group_id.table_name'], | |
2574 | 'data_type' => 'ContactReference', | |
fe3b8caf | 2575 | 'options' => ['limit' => 0], |
4c7e5001 PF |
2576 | ])['values']; |
2577 | foreach ($fields as $field) { | |
2578 | $cidRefs[$field['custom_group_id.table_name']][] = $field['column_name']; | |
e3e87c73 | 2579 | } |
2580 | } | |
2581 | ||
032c9d10 TO |
2582 | /** |
2583 | * Lookup the value of a MySQL global configuration variable. | |
2584 | * | |
6a0b768e TO |
2585 | * @param string $name |
2586 | * E.g. "thread_stack". | |
032c9d10 TO |
2587 | * @param mixed $default |
2588 | * @return mixed | |
2589 | */ | |
2590 | public static function getGlobalSetting($name, $default = NULL) { | |
2591 | // Alternatively, SELECT @@GLOBAL.thread_stack, but | |
2592 | // that has been reported to fail under MySQL 5.0 for OS X | |
2593 | $escapedName = self::escapeString($name); | |
2594 | $dao = CRM_Core_DAO::executeQuery("SHOW VARIABLES LIKE '$escapedName'"); | |
2595 | if ($dao->fetch()) { | |
2596 | return $dao->Value; | |
ab00f69d DL |
2597 | } |
2598 | else { | |
032c9d10 TO |
2599 | return $default; |
2600 | } | |
2601 | } | |
dc86f881 | 2602 | |
9d5c7f14 | 2603 | /** |
2604 | * Update the fields array to also hold keys for pseudoconstant fields that relate to contained fields. | |
2605 | * | |
2606 | * This is relevant where we want to offer both the ID field and the label field | |
2607 | * as an option, e.g. search builder. | |
2608 | * | |
b55d81b4 | 2609 | * It is currently limited for optionGroupName & id+ name+ FK combos for purposes keeping the scope of the |
9d5c7f14 | 2610 | * change small, but is appropriate for other sorts of pseudoconstants. |
2611 | * | |
2612 | * @param array $fields | |
2613 | */ | |
a0090e6b | 2614 | public static function appendPseudoConstantsToFields(&$fields) { |
6b051312 | 2615 | foreach ($fields as $fieldUniqueName => $field) { |
b55d81b4 | 2616 | if (!empty($field['pseudoconstant'])) { |
2617 | $pseudoConstant = $field['pseudoconstant']; | |
2618 | if (!empty($pseudoConstant['optionGroupName'])) { | |
2619 | $fields[$pseudoConstant['optionGroupName']] = [ | |
2620 | 'title' => CRM_Core_BAO_OptionGroup::getTitleByName($pseudoConstant['optionGroupName']), | |
2621 | 'name' => $pseudoConstant['optionGroupName'], | |
2622 | 'data_type' => CRM_Utils_Type::T_STRING, | |
6b051312 | 2623 | 'is_pseudofield_for' => $fieldUniqueName, |
b55d81b4 | 2624 | ]; |
2625 | } | |
2626 | // We restrict to id + name + FK as we are extending this a bit, but cautiously. | |
2627 | elseif ( | |
2628 | !empty($field['FKClassName']) | |
2629 | && CRM_Utils_Array::value('keyColumn', $pseudoConstant) === 'id' | |
2630 | && CRM_Utils_Array::value('labelColumn', $pseudoConstant) === 'name' | |
2631 | ) { | |
2632 | $pseudoFieldName = str_replace('_' . $pseudoConstant['keyColumn'], '', $field['name']); | |
2633 | // This if is just an extra caution when adding change. | |
2634 | if (!isset($fields[$pseudoFieldName])) { | |
2635 | $daoName = $field['FKClassName']; | |
2636 | $fkFields = $daoName::fields(); | |
2637 | foreach ($fkFields as $fkField) { | |
2638 | if ($fkField['name'] === $pseudoConstant['labelColumn']) { | |
2639 | $fields[$pseudoFieldName] = [ | |
2640 | 'name' => $pseudoFieldName, | |
2641 | 'is_pseudofield_for' => $field['name'], | |
2642 | 'title' => $fkField['title'], | |
2643 | 'data_type' => $fkField['type'], | |
2644 | 'where' => $field['where'], | |
2645 | ]; | |
2646 | } | |
2647 | } | |
2648 | } | |
2649 | } | |
9d5c7f14 | 2650 | } |
2651 | } | |
2652 | } | |
2653 | ||
dc86f881 CW |
2654 | /** |
2655 | * Get options for the called BAO object's field. | |
167bcb5f | 2656 | * |
dc86f881 | 2657 | * This function can be overridden by each BAO to add more logic related to context. |
2158332a | 2658 | * The overriding function will generally call the lower-level CRM_Core_PseudoConstant::get |
dc86f881 | 2659 | * |
2a3f958d | 2660 | * @param string $fieldName |
6a0b768e | 2661 | * @param string $context |
795492f3 | 2662 | * @see CRM_Core_DAO::buildOptionsContext |
6a0b768e | 2663 | * @param array $props |
39868387 CW |
2664 | * Raw field values; whatever is known about this bao object. |
2665 | * | |
2666 | * Note: $props can contain unsanitized input and should not be passed directly to CRM_Core_PseudoConstant::get | |
9a1b1948 | 2667 | * |
795492f3 | 2668 | * @return array|bool |
dc86f881 | 2669 | */ |
be2fb01f | 2670 | public static function buildOptions($fieldName, $context = NULL, $props = []) { |
2158332a | 2671 | // If a given bao does not override this function |
dc86f881 | 2672 | $baoName = get_called_class(); |
39868387 | 2673 | return CRM_Core_PseudoConstant::get($baoName, $fieldName, [], $context); |
dc86f881 | 2674 | } |
786ad6e1 | 2675 | |
2a3f958d CW |
2676 | /** |
2677 | * Populate option labels for this object's fields. | |
2678 | * | |
2679 | * @throws exception if called directly on the base class | |
2680 | */ | |
2681 | public function getOptionLabels() { | |
2682 | $fields = $this->fields(); | |
2683 | if ($fields === NULL) { | |
795492f3 | 2684 | throw new Exception('Cannot call getOptionLabels on CRM_Core_DAO'); |
2a3f958d CW |
2685 | } |
2686 | foreach ($fields as $field) { | |
9c1bc317 | 2687 | $name = $field['name'] ?? NULL; |
2a3f958d | 2688 | if ($name && isset($this->$name)) { |
a8c23526 | 2689 | $label = CRM_Core_PseudoConstant::getLabel(get_class($this), $name, $this->$name); |
2a3f958d CW |
2690 | if ($label !== FALSE) { |
2691 | // Append 'label' onto the field name | |
2692 | $labelName = $name . '_label'; | |
2693 | $this->$labelName = $label; | |
2694 | } | |
2695 | } | |
2696 | } | |
2697 | } | |
2698 | ||
786ad6e1 CW |
2699 | /** |
2700 | * Provides documentation and validation for the buildOptions $context param | |
2701 | * | |
6a0b768e | 2702 | * @param string $context |
77b97be7 | 2703 | * |
d1d108ee | 2704 | * @throws CRM_Core_Exception |
77b97be7 | 2705 | * @return array |
786ad6e1 CW |
2706 | */ |
2707 | public static function buildOptionsContext($context = NULL) { | |
be2fb01f | 2708 | $contexts = [ |
a2407bc0 CW |
2709 | 'get' => "get: all options are returned, even if they are disabled; labels are translated.", |
2710 | 'create' => "create: options are filtered appropriately for the object being created/updated; labels are translated.", | |
2711 | 'search' => "search: searchable options are returned; labels are translated.", | |
2712 | 'validate' => "validate: all options are returned, even if they are disabled; machine names are used in place of labels.", | |
2713 | 'abbreviate' => "abbreviate: enabled options are returned; labels are replaced with abbreviations.", | |
2714 | 'match' => "match: enabled options are returned using machine names as keys; labels are translated.", | |
be2fb01f | 2715 | ]; |
786ad6e1 CW |
2716 | // Validation: enforce uniformity of this param |
2717 | if ($context !== NULL && !isset($contexts[$context])) { | |
d1d108ee | 2718 | throw new CRM_Core_Exception("'$context' is not a valid context for buildOptions."); |
786ad6e1 CW |
2719 | } |
2720 | return $contexts; | |
2721 | } | |
2722 | ||
5fafc9b0 | 2723 | /** |
100fef9d | 2724 | * @param string $fieldName |
5fafc9b0 CW |
2725 | * @return bool|array |
2726 | */ | |
00be9182 | 2727 | public function getFieldSpec($fieldName) { |
5fafc9b0 CW |
2728 | $fields = $this->fields(); |
2729 | $fieldKeys = $this->fieldKeys(); | |
2730 | ||
2731 | // Support "unique names" as well as sql names | |
2732 | $fieldKey = $fieldName; | |
2733 | if (empty($fields[$fieldKey])) { | |
9c1bc317 | 2734 | $fieldKey = $fieldKeys[$fieldName] ?? NULL; |
5fafc9b0 CW |
2735 | } |
2736 | // If neither worked then this field doesn't exist. Return false. | |
2737 | if (empty($fields[$fieldKey])) { | |
2738 | return FALSE; | |
2739 | } | |
2740 | return $fields[$fieldKey]; | |
2741 | } | |
2742 | ||
faf8c53b | 2743 | /** |
bb05da0c | 2744 | * Get SQL where clause for SQL filter syntax input parameters. |
2745 | * | |
faf8c53b | 2746 | * SQL version of api function to assign filters to the DAO based on the syntax |
2747 | * $field => array('IN' => array(4,6,9)) | |
2748 | * OR | |
2749 | * $field => array('LIKE' => array('%me%)) | |
2750 | * etc | |
2751 | * | |
6a0b768e TO |
2752 | * @param string $fieldName |
2753 | * Name of fields. | |
5a4f6742 CW |
2754 | * @param array $filter |
2755 | * filter to be applied indexed by operator. | |
2756 | * @param string $type | |
2757 | * type of field (not actually used - nor in api @todo ). | |
2758 | * @param string $alias | |
2759 | * alternative field name ('as') @todo- not actually used. | |
6a0b768e TO |
2760 | * @param bool $returnSanitisedArray |
2761 | * Return a sanitised array instead of a clause. | |
16b10e64 | 2762 | * this is primarily so we can add filters @ the api level to the Query object based fields |
9a1b1948 EM |
2763 | * |
2764 | * @throws Exception | |
c490a46a | 2765 | * |
72b3a70c CW |
2766 | * @return NULL|string|array |
2767 | * a string is returned if $returnSanitisedArray is not set, otherwise and Array or NULL | |
06f48f96 | 2768 | * depending on whether it is supported as yet |
9a1b1948 | 2769 | */ |
e47bcddb | 2770 | public static function createSQLFilter($fieldName, $filter, $type = NULL, $alias = NULL, $returnSanitisedArray = FALSE) { |
faf8c53b | 2771 | foreach ($filter as $operator => $criteria) { |
6e23130a | 2772 | if (in_array($operator, self::acceptedSQLOperators(), TRUE)) { |
faf8c53b | 2773 | switch ($operator) { |
2774 | // unary operators | |
faf8c53b | 2775 | case 'IS NULL': |
2776 | case 'IS NOT NULL': | |
c490a46a | 2777 | if (!$returnSanitisedArray) { |
78c0bfc0 | 2778 | return (sprintf('%s %s', $fieldName, $operator)); |
2779 | } | |
c490a46a | 2780 | else { |
a75c13cc | 2781 | return (sprintf('%s %s ', $fieldName, $operator)); |
06f48f96 | 2782 | } |
faf8c53b | 2783 | break; |
2784 | ||
2785 | // ternary operators | |
2786 | case 'BETWEEN': | |
2787 | case 'NOT BETWEEN': | |
d03a02d9 | 2788 | if ((empty($criteria[0]) && !in_array($criteria[0], ['0', 0]))|| (empty($criteria[1]) && !in_array($criteria[1], ['0', 0]))) { |
395d8dc6 | 2789 | throw new Exception("invalid criteria for $operator"); |
faf8c53b | 2790 | } |
c490a46a | 2791 | if (!$returnSanitisedArray) { |
78c0bfc0 | 2792 | return (sprintf('%s ' . $operator . ' "%s" AND "%s"', $fieldName, CRM_Core_DAO::escapeString($criteria[0]), CRM_Core_DAO::escapeString($criteria[1]))); |
2793 | } | |
c490a46a | 2794 | else { |
518fa0ee SL |
2795 | // not yet implemented (tests required to implement) |
2796 | return NULL; | |
06f48f96 | 2797 | } |
faf8c53b | 2798 | break; |
2799 | ||
2800 | // n-ary operators | |
2801 | case 'IN': | |
2802 | case 'NOT IN': | |
2803 | if (empty($criteria)) { | |
395d8dc6 | 2804 | throw new Exception("invalid criteria for $operator"); |
faf8c53b | 2805 | } |
be2fb01f | 2806 | $escapedCriteria = array_map([ |
faf8c53b | 2807 | 'CRM_Core_DAO', |
795492f3 | 2808 | 'escapeString', |
be2fb01f | 2809 | ], $criteria); |
c490a46a | 2810 | if (!$returnSanitisedArray) { |
78c0bfc0 | 2811 | return (sprintf('%s %s ("%s")', $fieldName, $operator, implode('", "', $escapedCriteria))); |
2812 | } | |
2813 | return $escapedCriteria; | |
faf8c53b | 2814 | |
2815 | // binary operators | |
6a488035 | 2816 | |
faf8c53b | 2817 | default: |
c490a46a | 2818 | if (!$returnSanitisedArray) { |
353ffa53 | 2819 | return (sprintf('%s %s "%s"', $fieldName, $operator, CRM_Core_DAO::escapeString($criteria))); |
78c0bfc0 | 2820 | } |
c490a46a | 2821 | else { |
518fa0ee SL |
2822 | // not yet implemented (tests required to implement) |
2823 | return NULL; | |
06f48f96 | 2824 | } |
faf8c53b | 2825 | } |
2826 | } | |
2827 | } | |
2828 | } | |
6842bb53 | 2829 | |
e4176358 CW |
2830 | /** |
2831 | * @see http://issues.civicrm.org/jira/browse/CRM-9150 | |
2832 | * support for other syntaxes is discussed in ticket but being put off for now | |
2833 | * @return array | |
2834 | */ | |
2835 | public static function acceptedSQLOperators() { | |
be2fb01f | 2836 | return [ |
353ffa53 TO |
2837 | '=', |
2838 | '<=', | |
2839 | '>=', | |
2840 | '>', | |
2841 | '<', | |
2842 | 'LIKE', | |
2843 | "<>", | |
2844 | "!=", | |
2845 | "NOT LIKE", | |
2846 | 'IN', | |
2847 | 'NOT IN', | |
2848 | 'BETWEEN', | |
2849 | 'NOT BETWEEN', | |
2850 | 'IS NOT NULL', | |
795492f3 | 2851 | 'IS NULL', |
be2fb01f | 2852 | ]; |
e4176358 CW |
2853 | } |
2854 | ||
6842bb53 DL |
2855 | /** |
2856 | * SQL has a limit of 64 characters on various names: | |
2857 | * table name, trigger name, column name ... | |
2858 | * | |
2859 | * For custom groups and fields we generated names from user entered input | |
2860 | * which can be longer than this length, this function helps with creating | |
2861 | * strings that meet various criteria. | |
2862 | * | |
6a0b768e TO |
2863 | * @param string $string |
2864 | * The string to be shortened. | |
2865 | * @param int $length | |
2866 | * The max length of the string. | |
9a1b1948 EM |
2867 | * |
2868 | * @param bool $makeRandom | |
2869 | * | |
2870 | * @return string | |
6842bb53 DL |
2871 | */ |
2872 | public static function shortenSQLName($string, $length = 60, $makeRandom = FALSE) { | |
2873 | // early return for strings that meet the requirements | |
2874 | if (strlen($string) <= $length) { | |
2875 | return $string; | |
2876 | } | |
2877 | ||
2878 | // easy return for calls that dont need a randomized uniq string | |
c490a46a | 2879 | if (!$makeRandom) { |
6842bb53 DL |
2880 | return substr($string, 0, $length); |
2881 | } | |
2882 | ||
2883 | // the string is longer than the length and we need a uniq string | |
b44e3f84 | 2884 | // for the same tablename we need the same uniq string every time |
6842bb53 | 2885 | // hence we use md5 on the string, which is not random |
a8dd306e DL |
2886 | // we'll append 8 characters to the end of the tableName |
2887 | $md5string = substr(md5($string), 0, 8); | |
2888 | return substr($string, 0, $length - 8) . "_{$md5string}"; | |
6842bb53 DL |
2889 | } |
2890 | ||
a0ee3941 | 2891 | /** |
33092c89 SB |
2892 | * https://issues.civicrm.org/jira/browse/CRM-17748 |
2893 | * Sets the internal options to be used on a query | |
2894 | * | |
2895 | * @param array $options | |
2896 | * | |
2897 | */ | |
6232119d | 2898 | public function setOptions($options) { |
33092c89 SB |
2899 | if (is_array($options)) { |
2900 | $this->_options = $options; | |
2901 | } | |
2902 | } | |
2903 | ||
2904 | /** | |
2905 | * https://issues.civicrm.org/jira/browse/CRM-17748 | |
2906 | * wrapper to pass internal DAO options down to DB_mysql/DB_Common level | |
2907 | * | |
2908 | * @param array $options | |
2909 | * | |
2910 | */ | |
2911 | protected function _setDBOptions($options) { | |
2912 | global $_DB_DATAOBJECT; | |
2913 | ||
2914 | if (is_array($options) && count($options)) { | |
2915 | $conn = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]; | |
2916 | foreach ($options as $option_name => $option_value) { | |
2917 | $conn->setOption($option_name, $option_value); | |
2918 | } | |
2919 | } | |
2920 | } | |
2921 | ||
6232119d | 2922 | /** |
d343069c | 2923 | * @deprecated |
c490a46a | 2924 | * @param array $params |
a0ee3941 | 2925 | */ |
353ffa53 TO |
2926 | public function setApiFilter(&$params) { |
2927 | } | |
6e1bb60c | 2928 | |
d343069c | 2929 | /** |
20e41014 | 2930 | * Generates acl clauses suitable for adding to WHERE or ON when doing an api.get for this entity |
d343069c | 2931 | * |
b53bcc5d | 2932 | * Return format is in the form of fieldname => clauses starting with an operator. e.g.: |
0b882a86 | 2933 | * ``` |
b53bcc5d CW |
2934 | * array( |
2935 | * 'location_type_id' => array('IS NOT NULL', 'IN (1,2,3)') | |
2936 | * ) | |
0b882a86 | 2937 | * ``` |
b53bcc5d CW |
2938 | * |
2939 | * Note that all array keys must be actual field names in this entity. Use subqueries to filter on other tables e.g. custom values. | |
2940 | * | |
2941 | * @return array | |
d343069c | 2942 | */ |
20e41014 | 2943 | public function addSelectWhereClause() { |
be2fb01f | 2944 | $clauses = []; |
c6835264 CW |
2945 | $fields = $this->fields(); |
2946 | foreach ($fields as $fieldName => $field) { | |
2947 | // Clause for contact-related entities like Email, Relationship, etc. | |
0b80f0b4 | 2948 | if (strpos($fieldName, 'contact_id') === 0 && CRM_Utils_Array::value('FKClassName', $field) == 'CRM_Contact_DAO_Contact') { |
d1d3c04a | 2949 | $clauses[$fieldName] = CRM_Utils_SQL::mergeSubquery('Contact'); |
0b80f0b4 | 2950 | } |
c6835264 CW |
2951 | // Clause for an entity_table/entity_id combo |
2952 | if ($fieldName == 'entity_id' && isset($fields['entity_table'])) { | |
be2fb01f | 2953 | $relatedClauses = []; |
c6835264 CW |
2954 | $relatedEntities = $this->buildOptions('entity_table', 'get'); |
2955 | foreach ((array) $relatedEntities as $table => $ent) { | |
fb1c6b2c SL |
2956 | if (!empty($ent)) { |
2957 | $ent = CRM_Core_DAO_AllCoreTables::getBriefName(CRM_Core_DAO_AllCoreTables::getClassForTable($table)); | |
2958 | $subquery = CRM_Utils_SQL::mergeSubquery($ent); | |
2959 | if ($subquery) { | |
2960 | $relatedClauses[] = "(entity_table = '$table' AND entity_id " . implode(' AND entity_id ', $subquery) . ")"; | |
2961 | } | |
2962 | else { | |
2963 | $relatedClauses[] = "(entity_table = '$table')"; | |
2964 | } | |
c6835264 CW |
2965 | } |
2966 | } | |
2967 | if ($relatedClauses) { | |
2968 | $clauses['id'] = 'IN (SELECT id FROM `' . $this->tableName() . '` WHERE (' . implode(') OR (', $relatedClauses) . '))'; | |
2969 | } | |
2970 | } | |
d343069c | 2971 | } |
032346cc CW |
2972 | CRM_Utils_Hook::selectWhereClause($this, $clauses); |
2973 | return $clauses; | |
d343069c CW |
2974 | } |
2975 | ||
6c051493 | 2976 | /** |
0b80f0b4 CW |
2977 | * This returns the final permissioned query string for this entity |
2978 | * | |
2979 | * With acls from related entities + additional clauses from hook_civicrm_selectWhereClause | |
2980 | * | |
6c051493 CW |
2981 | * @param string $tableAlias |
2982 | * @return array | |
2983 | */ | |
20e41014 | 2984 | public static function getSelectWhereClause($tableAlias = NULL) { |
6c051493 CW |
2985 | $bao = new static(); |
2986 | if ($tableAlias === NULL) { | |
2987 | $tableAlias = $bao->tableName(); | |
2988 | } | |
be2fb01f | 2989 | $clauses = []; |
20e41014 | 2990 | foreach ((array) $bao->addSelectWhereClause() as $field => $vals) { |
6c051493 CW |
2991 | $clauses[$field] = NULL; |
2992 | if ($vals) { | |
8db05db8 | 2993 | $clauses[$field] = "(`$tableAlias`.`$field` IS NULL OR (`$tableAlias`.`$field` " . implode(" AND `$tableAlias`.`$field` ", (array) $vals) . '))'; |
6c051493 CW |
2994 | } |
2995 | } | |
2996 | return $clauses; | |
2997 | } | |
2998 | ||
a00fe575 | 2999 | /** |
ee17d64d MM |
3000 | * ensure database name is 'safe', i.e. only contains word characters (includes underscores) |
3001 | * and dashes, and contains at least one [a-z] case insenstive. | |
a00fe575 PN |
3002 | * |
3003 | * @param $database | |
a00fe575 PN |
3004 | * |
3005 | * @return bool | |
3006 | */ | |
ee17d64d | 3007 | public static function requireSafeDBName($database) { |
be2fb01f | 3008 | $matches = []; |
a00fe575 | 3009 | preg_match( |
ee17d64d | 3010 | "/^[\w\-]*[a-z]+[\w\-]*$/i", |
a00fe575 PN |
3011 | $database, |
3012 | $matches | |
3013 | ); | |
3014 | if (empty($matches)) { | |
a00fe575 PN |
3015 | return FALSE; |
3016 | } | |
a00fe575 PN |
3017 | return TRUE; |
3018 | } | |
3019 | ||
2a5c9b4d CW |
3020 | /** |
3021 | * Transform an array to a serialized string for database storage. | |
3022 | * | |
e97c66ff | 3023 | * @param array|null $value |
3024 | * @param int $serializationType | |
3025 | * @return string|null | |
3026 | * | |
dd3ec98b | 3027 | * @throws \Exception |
2a5c9b4d CW |
3028 | */ |
3029 | public static function serializeField($value, $serializationType) { | |
3030 | if ($value === NULL) { | |
3031 | return NULL; | |
3032 | } | |
3033 | switch ($serializationType) { | |
3034 | case self::SERIALIZE_SEPARATOR_BOOKEND: | |
be2fb01f | 3035 | return $value === [] ? '' : CRM_Utils_Array::implodePadded($value); |
2a5c9b4d CW |
3036 | |
3037 | case self::SERIALIZE_SEPARATOR_TRIMMED: | |
3038 | return is_array($value) ? implode(self::VALUE_SEPARATOR, $value) : $value; | |
3039 | ||
2a5c9b4d CW |
3040 | case self::SERIALIZE_JSON: |
3041 | return is_array($value) ? json_encode($value) : $value; | |
3042 | ||
3043 | case self::SERIALIZE_PHP: | |
3044 | return is_array($value) ? serialize($value) : $value; | |
dd3ec98b CW |
3045 | |
3046 | case self::SERIALIZE_COMMA: | |
3047 | return is_array($value) ? implode(',', $value) : $value; | |
3048 | ||
3049 | default: | |
3050 | throw new Exception('Unknown serialization method for field.'); | |
2a5c9b4d CW |
3051 | } |
3052 | } | |
3053 | ||
3054 | /** | |
3055 | * Transform a serialized string from the database into an array. | |
3056 | * | |
3057 | * @param string|null $value | |
3058 | * @param $serializationType | |
8cec96dc | 3059 | * |
2a5c9b4d | 3060 | * @return array|null |
8cec96dc | 3061 | * @throws CRM_Core_Exception |
2a5c9b4d CW |
3062 | */ |
3063 | public static function unSerializeField($value, $serializationType) { | |
3064 | if ($value === NULL) { | |
3065 | return NULL; | |
3066 | } | |
3067 | if ($value === '') { | |
be2fb01f | 3068 | return []; |
2a5c9b4d CW |
3069 | } |
3070 | switch ($serializationType) { | |
3071 | case self::SERIALIZE_SEPARATOR_BOOKEND: | |
3072 | return (array) CRM_Utils_Array::explodePadded($value); | |
3073 | ||
3074 | case self::SERIALIZE_SEPARATOR_TRIMMED: | |
3075 | return explode(self::VALUE_SEPARATOR, trim($value)); | |
3076 | ||
2a5c9b4d | 3077 | case self::SERIALIZE_JSON: |
be2fb01f | 3078 | return strlen($value) ? json_decode($value, TRUE) : []; |
2a5c9b4d CW |
3079 | |
3080 | case self::SERIALIZE_PHP: | |
f24846d5 | 3081 | return strlen($value) ? CRM_Utils_String::unserialize($value) : []; |
dd3ec98b CW |
3082 | |
3083 | case self::SERIALIZE_COMMA: | |
3084 | return explode(',', trim(str_replace(', ', '', $value))); | |
3085 | ||
3086 | default: | |
8cec96dc | 3087 | throw new CRM_Core_Exception('Unknown serialization method for field.'); |
2a5c9b4d CW |
3088 | } |
3089 | } | |
3090 | ||
1d6f94ab CW |
3091 | /** |
3092 | * @return array | |
3093 | */ | |
3094 | public static function getEntityRefFilters() { | |
3095 | return []; | |
3096 | } | |
3097 | ||
304dc580 | 3098 | /** |
3099 | * Get exportable fields with pseudoconstants rendered as an extra field. | |
3100 | * | |
3101 | * @param string $baoClass | |
3102 | * | |
3103 | * @return array | |
3104 | */ | |
3105 | public static function getExportableFieldsWithPseudoConstants($baoClass) { | |
3106 | if (method_exists($baoClass, 'exportableFields')) { | |
3107 | $fields = $baoClass::exportableFields(); | |
3108 | } | |
3109 | else { | |
3110 | $fields = $baoClass::export(); | |
3111 | } | |
3112 | CRM_Core_DAO::appendPseudoConstantsToFields($fields); | |
3113 | return $fields; | |
3114 | } | |
3115 | ||
10cac951 CW |
3116 | /** |
3117 | * Remove item from static cache during update/delete operations | |
3118 | */ | |
3119 | private function clearDbColumnValueCache() { | |
3120 | $daoName = get_class($this); | |
3121 | while (strpos($daoName, '_BAO_') !== FALSE) { | |
3122 | $daoName = get_parent_class($daoName); | |
3123 | } | |
3124 | if (isset($this->id)) { | |
3125 | unset(self::$_dbColumnValueCache[$daoName]['id'][$this->id]); | |
3126 | } | |
3127 | if (isset($this->name)) { | |
3128 | unset(self::$_dbColumnValueCache[$daoName]['name'][$this->name]); | |
3129 | } | |
3130 | } | |
3131 | ||
232624b1 | 3132 | } |