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