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