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