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