Merge pull request #12368 from totten/master-cache-schema
[civicrm-core.git] / CRM / Core / DAO.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
fee14197 4 | CiviCRM version 5 |
6a488035 5 +--------------------------------------------------------------------+
8c9251b3 6 | Copyright CiviCRM LLC (c) 2004-2018 |
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
8c9251b3 34 * @copyright CiviCRM LLC (c) 2004-2018
6a488035
TO
35 */
36
b3029f89
SL
37if (!defined('DB_DSN_MODE')) {
38 define('DB_DSN_MODE', 'auto');
39}
40
6a488035
TO
41require_once 'PEAR.php';
42require_once 'DB/DataObject.php';
43
44require_once 'CRM/Core/I18n.php';
28518c90
EM
45
46/**
47 * Class CRM_Core_DAO
48 */
6a488035
TO
49class 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 }
6a488035
TO
699 $this->$dbName = $pValue;
700 $allNull = FALSE;
701 }
702 }
703 }
704 return $allNull;
705 }
706
707 /**
708 * Store all the values from this object in an associative array
709 * this is a destructive store, calling function is responsible
710 * for keeping sanity of id's.
711 *
6a0b768e
TO
712 * @param object $object
713 * The object that we are extracting data from.
714 * @param array $values
715 * (reference ) associative array of name/value pairs.
6a488035 716 */
00be9182 717 public static function storeValues(&$object, &$values) {
44ce4aa3 718 $fields = $object->fields();
6a488035
TO
719 foreach ($fields as $name => $value) {
720 $dbName = $value['name'];
721 if (isset($object->$dbName) && $object->$dbName !== 'null') {
722 $values[$dbName] = $object->$dbName;
723 if ($name != $dbName) {
724 $values[$name] = $object->$dbName;
725 }
726 }
727 }
728 }
729
730 /**
100fef9d 731 * Create an attribute for this specific field. We only do this for strings and text
6a488035 732 *
6a0b768e
TO
733 * @param array $field
734 * The field under task.
6a488035 735 *
72b3a70c
CW
736 * @return array|null
737 * the attributes for the object
6a488035 738 */
00be9182 739 public static function makeAttribute($field) {
6a488035
TO
740 if ($field) {
741 if (CRM_Utils_Array::value('type', $field) == CRM_Utils_Type::T_STRING) {
742 $maxLength = CRM_Utils_Array::value('maxlength', $field);
743 $size = CRM_Utils_Array::value('size', $field);
744 if ($maxLength || $size) {
745 $attributes = array();
746 if ($maxLength) {
747 $attributes['maxlength'] = $maxLength;
748 }
749 if ($size) {
750 $attributes['size'] = $size;
751 }
752 return $attributes;
753 }
754 }
755 elseif (CRM_Utils_Array::value('type', $field) == CRM_Utils_Type::T_TEXT) {
756 $rows = CRM_Utils_Array::value('rows', $field);
757 if (!isset($rows)) {
758 $rows = 2;
759 }
760 $cols = CRM_Utils_Array::value('cols', $field);
761 if (!isset($cols)) {
762 $cols = 80;
763 }
764
353ffa53 765 $attributes = array();
6a488035
TO
766 $attributes['rows'] = $rows;
767 $attributes['cols'] = $cols;
768 return $attributes;
769 }
770 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) {
771 $attributes['size'] = 6;
772 $attributes['maxlength'] = 14;
773 return $attributes;
774 }
775 }
776 return NULL;
777 }
778
779 /**
d09edf64 780 * Get the size and maxLength attributes for this text field.
6a488035
TO
781 * (or for all text fields) in the DAO object.
782 *
6a0b768e
TO
783 * @param string $class
784 * Name of DAO class.
785 * @param string $fieldName
786 * Field that i'm interested in or null if.
6a488035
TO
787 * you want the attributes for all DAO text fields
788 *
a6c01b45
CW
789 * @return array
790 * assoc array of name => attribute pairs
6a488035 791 */
00be9182 792 public static function getAttribute($class, $fieldName = NULL) {
353ffa53 793 $object = new $class();
44ce4aa3 794 $fields = $object->fields();
6a488035
TO
795 if ($fieldName != NULL) {
796 $field = CRM_Utils_Array::value($fieldName, $fields);
797 return self::makeAttribute($field);
798 }
799 else {
800 $attributes = array();
801 foreach ($fields as $name => $field) {
802 $attribute = self::makeAttribute($field);
803 if ($attribute) {
804 $attributes[$name] = $attribute;
805 }
806 }
807
808 if (!empty($attributes)) {
809 return $attributes;
810 }
811 }
812 return NULL;
813 }
814
6a488035 815 /**
fe482240 816 * Check if there is a record with the same name in the db.
6a488035 817 *
6a0b768e
TO
818 * @param string $value
819 * The value of the field we are checking.
820 * @param string $daoName
821 * The dao object name.
822 * @param string $daoID
823 * The id of the object being updated. u can change your name.
6a488035 824 * as long as there is no conflict
6a0b768e
TO
825 * @param string $fieldName
826 * The name of the field in the DAO.
6a488035 827 *
35b63106
DS
828 * @param string $domainID
829 * The id of the domain. Object exists only for the given domain.
830 *
795492f3 831 * @return bool
a6c01b45 832 * true if object exists
6a488035 833 */
35b63106 834 public static function objectExists($value, $daoName, $daoID, $fieldName = 'name', $domainID = NULL) {
353ffa53 835 $object = new $daoName();
6a488035 836 $object->$fieldName = $value;
35b63106
DS
837 if ($domainID) {
838 $object->domain_id = $domainID;
839 }
6a488035
TO
840
841 if ($object->find(TRUE)) {
842 return ($daoID && $object->id == $daoID) ? TRUE : FALSE;
843 }
844 else {
845 return TRUE;
846 }
847 }
848
849 /**
fe482240 850 * Check if there is a given column in a specific table.
6a488035
TO
851 *
852 * @param string $tableName
853 * @param string $columnName
6a0b768e
TO
854 * @param bool $i18nRewrite
855 * Whether to rewrite the query on multilingual setups.
6a488035 856 *
795492f3 857 * @return bool
a6c01b45 858 * true if exists, else false
6a488035 859 */
00be9182 860 public static function checkFieldExists($tableName, $columnName, $i18nRewrite = TRUE) {
6a488035
TO
861 $query = "
862SHOW COLUMNS
863FROM $tableName
864LIKE %1
865";
866 $params = array(1 => array($columnName, 'String'));
353ffa53 867 $dao = CRM_Core_DAO::executeQuery($query, $params, TRUE, NULL, FALSE, $i18nRewrite);
6a488035
TO
868 $result = $dao->fetch() ? TRUE : FALSE;
869 $dao->free();
870 return $result;
871 }
872
873 /**
3fa9688a 874 * Scans all the tables using a slow query and table name.
2a6da8d7 875 *
6a488035 876 * @return array
6a488035 877 */
3fa9688a 878 public static function getTableNames() {
879 $dao = CRM_Core_DAO::executeQuery(
880 "SELECT TABLE_NAME
881 FROM information_schema.TABLES
882 WHERE TABLE_SCHEMA = '" . CRM_Core_DAO::getDatabaseName() . "'
883 AND TABLE_NAME LIKE 'civicrm_%'
884 AND TABLE_NAME NOT LIKE 'civicrm_import_job_%'
2475b550 885 AND TABLE_NAME NOT LIKE '%_temp%'
3fa9688a 886 ");
6a488035 887
6a488035 888 while ($dao->fetch()) {
3fa9688a 889 $values[] = $dao->TABLE_NAME;
6a488035
TO
890 }
891 $dao->free();
892 return $values;
893 }
894
a0ee3941
EM
895 /**
896 * @param int $maxTablesToCheck
897 *
898 * @return bool
899 */
00be9182 900 public static function isDBMyISAM($maxTablesToCheck = 10) {
3fa9688a 901 return CRM_Core_DAO::singleValueQuery(
902 "SELECT count(*)
903 FROM information_schema.TABLES
904 WHERE ENGINE = 'MyISAM'
905 AND TABLE_SCHEMA = '" . CRM_Core_DAO::getDatabaseName() . "'
906 AND TABLE_NAME LIKE 'civicrm_%'
907 AND TABLE_NAME NOT LIKE 'civicrm_import_job_%'
2475b550 908 AND TABLE_NAME NOT LIKE '%_temp%'
3fa9688a 909 ");
910 }
911
912 /**
913 * Get the name of the CiviCRM database.
914 *
915 * @return string
916 */
917 public static function getDatabaseName() {
918 $daoObj = new CRM_Core_DAO();
919 return $daoObj->database();
6a488035
TO
920 }
921
922 /**
923 * Checks if a constraint exists for a specified table.
924 *
925 * @param string $tableName
926 * @param string $constraint
927 *
795492f3 928 * @return bool
a6c01b45 929 * true if constraint exists, false otherwise
6a488035 930 */
00be9182 931 public static function checkConstraintExists($tableName, $constraint) {
6a488035
TO
932 static $show = array();
933
934 if (!array_key_exists($tableName, $show)) {
935 $query = "SHOW CREATE TABLE $tableName";
936 $dao = CRM_Core_DAO::executeQuery($query);
937
938 if (!$dao->fetch()) {
939 CRM_Core_Error::fatal();
940 }
941
942 $dao->free();
943 $show[$tableName] = $dao->Create_Table;
944 }
945
946 return preg_match("/\b$constraint\b/i", $show[$tableName]) ? TRUE : FALSE;
947 }
948
949 /**
950 * Checks if CONSTRAINT keyword exists for a specified table.
951 *
2a6da8d7
EM
952 * @param array $tables
953 *
954 * @throws Exception
6a488035 955 *
795492f3 956 * @return bool
a6c01b45 957 * true if CONSTRAINT keyword exists, false otherwise
6a488035 958 */
00be9182 959 public static function schemaRequiresRebuilding($tables = array("civicrm_contact")) {
6a488035 960 $show = array();
9b873358 961 foreach ($tables as $tableName) {
6a488035
TO
962 if (!array_key_exists($tableName, $show)) {
963 $query = "SHOW CREATE TABLE $tableName";
964 $dao = CRM_Core_DAO::executeQuery($query);
965
966 if (!$dao->fetch()) {
967 CRM_Core_Error::fatal();
968 }
969
970 $dao->free();
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
1006 $dao->free();
1007 $show[$tableName] = $dao->Create_Table;
1008 }
1009 $constraint = "`FK_{$tableName}_{$columnName}`";
1010 $pattern = "/\bCONSTRAINT\b\s+%s\s+\bFOREIGN\s+KEY\b\s/i";
353ffa53 1011 return preg_match(sprintf($pattern, $constraint), $show[$tableName]) ? TRUE : FALSE;
6a488035
TO
1012 }
1013
1014 /**
fe482240 1015 * Check whether a specific column in a specific table has always the same value.
6a488035
TO
1016 *
1017 * @param string $tableName
1018 * @param string $columnName
1019 * @param string $columnValue
1020 *
795492f3 1021 * @return bool
a6c01b45 1022 * true if the value is always $columnValue, false otherwise
6a488035 1023 */
00be9182 1024 public static function checkFieldHasAlwaysValue($tableName, $columnName, $columnValue) {
353ffa53
TO
1025 $query = "SELECT * FROM $tableName WHERE $columnName != '$columnValue'";
1026 $dao = CRM_Core_DAO::executeQuery($query);
6a488035
TO
1027 $result = $dao->fetch() ? FALSE : TRUE;
1028 $dao->free();
1029 return $result;
1030 }
1031
1032 /**
fe482240 1033 * Check whether a specific column in a specific table is always NULL.
6a488035
TO
1034 *
1035 * @param string $tableName
1036 * @param string $columnName
1037 *
795492f3 1038 * @return bool
a6c01b45 1039 * true if if the value is always NULL, false otherwise
6a488035 1040 */
00be9182 1041 public static function checkFieldIsAlwaysNull($tableName, $columnName) {
353ffa53
TO
1042 $query = "SELECT * FROM $tableName WHERE $columnName IS NOT NULL";
1043 $dao = CRM_Core_DAO::executeQuery($query);
6a488035
TO
1044 $result = $dao->fetch() ? FALSE : TRUE;
1045 $dao->free();
1046 return $result;
1047 }
1048
1049 /**
fe482240 1050 * Check if there is a given table in the database.
6a488035
TO
1051 *
1052 * @param string $tableName
1053 *
795492f3 1054 * @return bool
a6c01b45 1055 * true if exists, else false
6a488035 1056 */
00be9182 1057 public static function checkTableExists($tableName) {
6a488035
TO
1058 $query = "
1059SHOW TABLES
1060LIKE %1
1061";
1062 $params = array(1 => array($tableName, 'String'));
1063
1064 $dao = CRM_Core_DAO::executeQuery($query, $params);
1065 $result = $dao->fetch() ? TRUE : FALSE;
1066 $dao->free();
1067 return $result;
1068 }
1069
a0ee3941
EM
1070 /**
1071 * @param $version
1072 *
1073 * @return bool
1074 */
00be9182 1075 public function checkVersion($version) {
6a488035
TO
1076 $query = "
1077SELECT version
1078FROM civicrm_domain
1079";
1080 $dbVersion = CRM_Core_DAO::singleValueQuery($query);
1081 return trim($version) == trim($dbVersion) ? TRUE : FALSE;
1082 }
1083
47ff2df7
AN
1084 /**
1085 * Find a DAO object for the given ID and return it.
1086 *
6a0b768e
TO
1087 * @param int $id
1088 * Id of the DAO object being searched for.
47ff2df7 1089 *
44ce4aa3 1090 * @return CRM_Core_DAO
a6c01b45 1091 * Object of the type of the class that called this function.
44ce4aa3
CW
1092 *
1093 * @throws Exception
47ff2df7 1094 */
00be9182 1095 public static function findById($id) {
47ff2df7
AN
1096 $object = new static();
1097 $object->id = $id;
1098 if (!$object->find(TRUE)) {
1099 throw new Exception("Unable to find a " . get_called_class() . " with id {$id}.");
1100 }
1101 return $object;
1102 }
1103
63782ba4
TO
1104 /**
1105 * Returns all results as array-encoded records.
1106 *
1107 * @return array
1108 */
1109 public function fetchAll() {
1110 $result = array();
1111 while ($this->fetch()) {
1112 $result[] = $this->toArray();
1113 }
1114 return $result;
1115 }
b5bbb074 1116
77e74ae1
TO
1117 /**
1118 * Returns a singular value.
1119 *
1120 * @return mixed|NULL
1121 */
1122 public function fetchValue() {
1123 $result = $this->getDatabaseResult();
1124 $row = $result->fetchRow();
1125 $ret = NULL;
1126 if ($row) {
1127 $ret = $row[0];
1128 }
1129 $this->free();
1130 return $ret;
1131 }
1132
b5bbb074
TO
1133 /**
1134 * Get all the result records as mapping between columns.
1135 *
1136 * @param string $keyColumn
1137 * Ex: "name"
1138 * @param string $valueColumn
1139 * Ex: "label"
1140 * @return array
1141 * Ex: ["foo" => "The Foo Bar", "baz" => "The Baz Qux"]
1142 */
1143 public function fetchMap($keyColumn, $valueColumn) {
1144 $result = array();
1145 while ($this->fetch()) {
1146 $result[$this->{$keyColumn}] = $this->{$valueColumn};
1147 }
1148 return $result;
1149 }
63782ba4 1150
6a488035
TO
1151 /**
1152 * Given a DAO name, a column name and a column value, find the record and GET the value of another column in that record
1153 *
6a0b768e
TO
1154 * @param string $daoName
1155 * Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact).
1156 * @param int $searchValue
1157 * Value of the column you want to search by.
1158 * @param string $returnColumn
1159 * Name of the column you want to GET the value of.
1160 * @param string $searchColumn
1161 * Name of the column you want to search by.
1162 * @param bool $force
1163 * Skip use of the cache.
6a488035 1164 *
72b3a70c
CW
1165 * @return string|null
1166 * Value of $returnColumn in the retrieved record
6a488035 1167 */
00be9182 1168 public static function getFieldValue($daoName, $searchValue, $returnColumn = 'name', $searchColumn = 'id', $force = FALSE) {
6a488035
TO
1169 if (
1170 empty($searchValue) ||
1171 trim(strtolower($searchValue)) == 'null'
1172 ) {
cf79ac58 1173 // adding this here since developers forget to check for an id
6a488035
TO
1174 // or for the 'null' (which is a bad DAO kludge)
1175 // and hence we get the first value in the db
1176 CRM_Core_Error::fatal();
1177 }
1178
1179 $cacheKey = "{$daoName}:{$searchValue}:{$returnColumn}:{$searchColumn}";
1180 if (self::$_dbColumnValueCache === NULL) {
1181 self::$_dbColumnValueCache = array();
1182 }
1183
1184 if (!array_key_exists($cacheKey, self::$_dbColumnValueCache) || $force) {
353ffa53 1185 $object = new $daoName();
6a488035
TO
1186 $object->$searchColumn = $searchValue;
1187 $object->selectAdd();
1188 $object->selectAdd($returnColumn);
1189
1190 $result = NULL;
1191 if ($object->find(TRUE)) {
1192 $result = $object->$returnColumn;
1193 }
1194 $object->free();
1195
1196 self::$_dbColumnValueCache[$cacheKey] = $result;
1197 }
1198 return self::$_dbColumnValueCache[$cacheKey];
1199 }
1200
1201 /**
1202 * Given a DAO name, a column name and a column value, find the record and SET the value of another column in that record
1203 *
6a0b768e
TO
1204 * @param string $daoName
1205 * Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact).
1206 * @param int $searchValue
1207 * Value of the column you want to search by.
1208 * @param string $setColumn
1209 * Name of the column you want to SET the value of.
1210 * @param string $setValue
1211 * SET the setColumn to this value.
1212 * @param string $searchColumn
1213 * Name of the column you want to search by.
6a488035 1214 *
795492f3 1215 * @return bool
a6c01b45 1216 * true if we found and updated the object, else false
6a488035 1217 */
00be9182 1218 public static function setFieldValue($daoName, $searchValue, $setColumn, $setValue, $searchColumn = 'id') {
353ffa53 1219 $object = new $daoName();
6a488035
TO
1220 $object->selectAdd();
1221 $object->selectAdd("$searchColumn, $setColumn");
1222 $object->$searchColumn = $searchValue;
1223 $result = FALSE;
1224 if ($object->find(TRUE)) {
1225 $object->$setColumn = $setValue;
1226 if ($object->save()) {
1227 $result = TRUE;
1228 }
1229 }
1230 $object->free();
1231 return $result;
1232 }
1233
1234 /**
fe482240 1235 * Get sort string.
6a488035
TO
1236 *
1237 * @param array|object $sort either array or CRM_Utils_Sort
6a0b768e
TO
1238 * @param string $default
1239 * Default sort value.
6a488035 1240 *
a6c01b45 1241 * @return string
6a488035 1242 */
00be9182 1243 public static function getSortString($sort, $default = NULL) {
6a488035
TO
1244 // check if sort is of type CRM_Utils_Sort
1245 if (is_a($sort, 'CRM_Utils_Sort')) {
1246 return $sort->orderBy();
1247 }
1248
44ce4aa3
CW
1249 $sortString = '';
1250
6a488035
TO
1251 // is it an array specified as $field => $sortDirection ?
1252 if ($sort) {
1253 foreach ($sort as $k => $v) {
1254 $sortString .= "$k $v,";
1255 }
1256 return rtrim($sortString, ',');
1257 }
1258 return $default;
1259 }
1260
1261 /**
fe482240 1262 * Fetch object based on array of properties.
6a488035 1263 *
6a0b768e
TO
1264 * @param string $daoName
1265 * Name of the dao object.
1266 * @param array $params
1267 * (reference ) an assoc array of name/value pairs.
1268 * @param array $defaults
1269 * (reference ) an assoc array to hold the flattened values.
1270 * @param array $returnProperities
1271 * An assoc array of fields that need to be returned, eg array( 'first_name', 'last_name').
6a488035 1272 *
a6c01b45
CW
1273 * @return object
1274 * an object of type referenced by daoName
6a488035 1275 */
00be9182 1276 public static function commonRetrieve($daoName, &$params, &$defaults, $returnProperities = NULL) {
353ffa53 1277 $object = new $daoName();
6a488035
TO
1278 $object->copyValues($params);
1279
1280 // return only specific fields if returnproperties are sent
1281 if (!empty($returnProperities)) {
1282 $object->selectAdd();
1283 $object->selectAdd(implode(',', $returnProperities));
1284 }
1285
1286 if ($object->find(TRUE)) {
1287 self::storeValues($object, $defaults);
1288 return $object;
1289 }
1290 return NULL;
1291 }
1292
1293 /**
fe482240 1294 * Delete the object records that are associated with this contact.
6a488035 1295 *
6a0b768e
TO
1296 * @param string $daoName
1297 * Name of the dao object.
1298 * @param int $contactId
1299 * Id of the contact to delete.
6a488035 1300 */
00be9182 1301 public static function deleteEntityContact($daoName, $contactId) {
353ffa53 1302 $object = new $daoName();
6a488035
TO
1303
1304 $object->entity_table = 'civicrm_contact';
1305 $object->entity_id = $contactId;
1306 $object->delete();
1307 }
1308
67cae873 1309 /**
bf48aa29 1310 * Execute an unbuffered query.
1311 *
1312 * This is a wrapper around new functionality exposed with CRM-17748.
67cae873
SB
1313 *
1314 * @param string $query query to be executed
3a8ce9d6 1315 *
bf48aa29 1316 * @param array $params
1317 * @param bool $abort
1318 * @param null $daoName
1319 * @param bool $freeDAO
1320 * @param bool $i18nRewrite
1321 * @param bool $trapException
1322 *
1323 * @return CRM_Core_DAO
1324 * Object that points to an unbuffered result set
67cae873 1325 */
3a8ce9d6 1326 static public function executeUnbufferedQuery(
67cae873 1327 $query,
3a8ce9d6
SB
1328 $params = array(),
1329 $abort = TRUE,
1330 $daoName = NULL,
1331 $freeDAO = FALSE,
1332 $i18nRewrite = TRUE,
67cae873
SB
1333 $trapException = FALSE
1334 ) {
67cae873 1335
4d1368d8 1336 return self::executeQuery(
1337 $query,
1338 $params,
1339 $abort,
1340 $daoName,
1341 $freeDAO,
1342 $i18nRewrite,
1343 $trapException,
1344 array('result_buffering' => 0)
1345 );
67cae873
SB
1346 }
1347
6a488035 1348 /**
fe482240 1349 * Execute a query.
6a488035 1350 *
6a0b768e
TO
1351 * @param string $query
1352 * Query to be executed.
6a488035 1353 *
2a6da8d7
EM
1354 * @param array $params
1355 * @param bool $abort
1356 * @param null $daoName
1357 * @param bool $freeDAO
1358 * @param bool $i18nRewrite
1359 * @param bool $trapException
4d1368d8 1360 * @param array $options
2a6da8d7 1361 *
5f1ebaec 1362 * @return CRM_Core_DAO|object
16b10e64 1363 * object that holds the results of the query
5f1ebaec
EM
1364 * NB - if this is defined as just returning a DAO phpstorm keeps pointing
1365 * out all the properties that are not part of the DAO
6a488035 1366 */
795492f3 1367 public static function &executeQuery(
6a488035 1368 $query,
353ffa53
TO
1369 $params = array(),
1370 $abort = TRUE,
1371 $daoName = NULL,
1372 $freeDAO = FALSE,
1373 $i18nRewrite = TRUE,
4d1368d8 1374 $trapException = FALSE,
1375 $options = array()
6a488035
TO
1376 ) {
1377 $queryStr = self::composeQuery($query, $params, $abort);
6a488035
TO
1378
1379 if (!$daoName) {
1380 $dao = new CRM_Core_DAO();
1381 }
1382 else {
353ffa53 1383 $dao = new $daoName();
6a488035
TO
1384 }
1385
1386 if ($trapException) {
6a4257d4 1387 $errorScope = CRM_Core_TemporaryErrorScope::ignoreException();
6a488035
TO
1388 }
1389
4d1368d8 1390 if ($dao->isValidOption($options)) {
1391 $dao->setOptions($options);
1392 }
1393
6a488035
TO
1394 $result = $dao->query($queryStr, $i18nRewrite);
1395
4d1368d8 1396 // since it is unbuffered, ($dao->N==0) is true. This blocks the standard fetch() mechanism.
1397 if (CRM_Utils_Array::value('result_buffering', $options) === 0) {
1398 $dao->N = TRUE;
1399 }
1400
6a488035
TO
1401 if (is_a($result, 'DB_Error')) {
1402 return $result;
1403 }
1404
1405 if ($freeDAO ||
1406 preg_match('/^(insert|update|delete|create|drop|replace)/i', $queryStr)
1407 ) {
b05b5a19 1408 // we typically do this for insert/update/delete statements OR if explicitly asked to
6a488035
TO
1409 // free the dao
1410 $dao->free();
1411 }
1412 return $dao;
1413 }
1414
4d1368d8 1415 /**
1416 * Wrapper to validate internal DAO options before passing to DB_mysql/DB_Common level
1417 *
1418 * @param array $options
1419 *
1420 * @return bool
1421 * Provided options are valid
1422 */
1423 public function isValidOption($options) {
1424 $isValid = FALSE;
1425 $validOptions = array(
1426 'result_buffering',
1427 'persistent',
1428 'ssl',
1429 'portability',
1430 );
1431
1432 if (empty($options)) {
1433 return $isValid;
1434 }
1435
1436 foreach (array_keys($options) as $option) {
1437 if (!in_array($option, $validOptions)) {
1438 return FALSE;
1439 }
1440 $isValid = TRUE;
1441 }
1442
1443 return $isValid;
1444 }
1445
6a488035 1446 /**
fe482240 1447 * Execute a query and get the single result.
6a488035 1448 *
6a0b768e
TO
1449 * @param string $query
1450 * Query to be executed.
e869b07d
CW
1451 * @param array $params
1452 * @param bool $abort
1453 * @param bool $i18nRewrite
72b3a70c
CW
1454 * @return string|null
1455 * the result of the query if any
6a488035 1456 *
6a488035 1457 */
795492f3 1458 public static function &singleValueQuery(
f9f40af3 1459 $query,
353ffa53
TO
1460 $params = array(),
1461 $abort = TRUE,
6a488035
TO
1462 $i18nRewrite = TRUE
1463 ) {
1464 $queryStr = self::composeQuery($query, $params, $abort);
1465
1466 static $_dao = NULL;
1467
1468 if (!$_dao) {
1469 $_dao = new CRM_Core_DAO();
1470 }
1471
1472 $_dao->query($queryStr, $i18nRewrite);
1473
1474 $result = $_dao->getDatabaseResult();
1475 $ret = NULL;
1476 if ($result) {
1477 $row = $result->fetchRow();
1478 if ($row) {
1479 $ret = $row[0];
1480 }
1481 }
1482 $_dao->free();
1483 return $ret;
1484 }
1485
a0ee3941 1486 /**
edc8adfc 1487 * Compose the query by merging the parameters into it.
1488 *
1489 * @param string $query
c490a46a 1490 * @param array $params
a0ee3941
EM
1491 * @param bool $abort
1492 *
1493 * @return string
1494 * @throws Exception
1495 */
edc8adfc 1496 public static function composeQuery($query, $params, $abort = TRUE) {
6a488035
TO
1497 $tr = array();
1498 foreach ($params as $key => $item) {
1499 if (is_numeric($key)) {
1500 if (CRM_Utils_Type::validate($item[0], $item[1]) !== NULL) {
1501 $item[0] = self::escapeString($item[0]);
1502 if ($item[1] == 'String' ||
1503 $item[1] == 'Memo' ||
1504 $item[1] == 'Link'
1505 ) {
887a4028
A
1506 // Support class constants stipulating wildcard characters and/or
1507 // non-quoting of strings. Also support legacy code which may be
1508 // passing in TRUE or 1 for $item[2], which used to indicate the
1509 // use of wildcard characters.
1510 if (!empty($item[2])) {
1511 if ($item[2] & CRM_Core_DAO::QUERY_FORMAT_WILDCARD || $item[2] === TRUE) {
1512 $item[0] = "'%{$item[0]}%'";
1513 }
1514 elseif (!($item[2] & CRM_Core_DAO::QUERY_FORMAT_NO_QUOTES)) {
1515 $item[0] = "'{$item[0]}'";
1516 }
6a488035
TO
1517 }
1518 else {
1519 $item[0] = "'{$item[0]}'";
1520 }
1521 }
1522
1523 if (($item[1] == 'Date' || $item[1] == 'Timestamp') &&
1524 strlen($item[0]) == 0
1525 ) {
1526 $item[0] = 'null';
1527 }
1528
1529 $tr['%' . $key] = $item[0];
1530 }
1531 elseif ($abort) {
1532 CRM_Core_Error::fatal("{$item[0]} is not of type {$item[1]}");
1533 }
1534 }
1535 }
1536
e2508c90 1537 return strtr($query, $tr);
6a488035
TO
1538 }
1539
a0ee3941
EM
1540 /**
1541 * @param null $ids
1542 */
00be9182 1543 public static function freeResult($ids = NULL) {
6a488035
TO
1544 global $_DB_DATAOBJECT;
1545
6a488035
TO
1546 if (!$ids) {
1547 if (!$_DB_DATAOBJECT ||
1548 !isset($_DB_DATAOBJECT['RESULTS'])
1549 ) {
1550 return;
1551 }
1552 $ids = array_keys($_DB_DATAOBJECT['RESULTS']);
1553 }
1554
1555 foreach ($ids as $id) {
1556 if (isset($_DB_DATAOBJECT['RESULTS'][$id])) {
8f56d1f5 1557 $_DB_DATAOBJECT['RESULTS'][$id]->free();
6a488035
TO
1558 unset($_DB_DATAOBJECT['RESULTS'][$id]);
1559 }
1560
1561 if (isset($_DB_DATAOBJECT['RESULTFIELDS'][$id])) {
1562 unset($_DB_DATAOBJECT['RESULTFIELDS'][$id]);
1563 }
1564 }
1565 }
1566
1567 /**
44ce4aa3 1568 * Make a shallow copy of an object and all the fields in the object.
6a488035 1569 *
6a0b768e
TO
1570 * @param string $daoName
1571 * Name of the dao.
1572 * @param array $criteria
1573 * Array of all the fields & values.
44ce4aa3 1574 * on which basis to copy
6a0b768e
TO
1575 * @param array $newData
1576 * Array of all the fields & values.
44ce4aa3 1577 * to be copied besides the other fields
6a0b768e
TO
1578 * @param string $fieldsFix
1579 * Array of fields that you want to prefix/suffix/replace.
1580 * @param string $blockCopyOfDependencies
1581 * Fields that you want to block from.
44ce4aa3 1582 * getting copied
6a488035 1583 *
72b3a70c
CW
1584 * @return CRM_Core_DAO
1585 * the newly created copy of the object
6a488035 1586 */
795492f3 1587 public static function &copyGeneric($daoName, $criteria, $newData = NULL, $fieldsFix = NULL, $blockCopyOfDependencies = NULL) {
353ffa53 1588 $object = new $daoName();
6a488035
TO
1589 if (!$newData) {
1590 $object->id = $criteria['id'];
1591 }
1592 else {
1593 foreach ($criteria as $key => $value) {
1594 $object->$key = $value;
1595 }
1596 }
1597
1598 $object->find();
1599 while ($object->fetch()) {
1600
1601 // all the objects except with $blockCopyOfDependencies set
1602 // be copied - addresses #CRM-1962
1603
1604 if ($blockCopyOfDependencies && $object->$blockCopyOfDependencies) {
1605 break;
1606 }
1607
353ffa53 1608 $newObject = new $daoName();
6a488035 1609
44ce4aa3 1610 $fields = $object->fields();
6a488035 1611 if (!is_array($fieldsFix)) {
353ffa53
TO
1612 $fieldsToPrefix = array();
1613 $fieldsToSuffix = array();
6a488035
TO
1614 $fieldsToReplace = array();
1615 }
a7488080 1616 if (!empty($fieldsFix['prefix'])) {
6a488035
TO
1617 $fieldsToPrefix = $fieldsFix['prefix'];
1618 }
a7488080 1619 if (!empty($fieldsFix['suffix'])) {
6a488035
TO
1620 $fieldsToSuffix = $fieldsFix['suffix'];
1621 }
a7488080 1622 if (!empty($fieldsFix['replace'])) {
6a488035
TO
1623 $fieldsToReplace = $fieldsFix['replace'];
1624 }
1625
1626 foreach ($fields as $name => $value) {
1627 if ($name == 'id' || $value['name'] == 'id') {
1628 // copy everything but the id!
1629 continue;
1630 }
1631
1632 $dbName = $value['name'];
a1305c92 1633 $type = CRM_Utils_Type::typeToString($value['type']);
6a488035
TO
1634 $newObject->$dbName = $object->$dbName;
1635 if (isset($fieldsToPrefix[$dbName])) {
1636 $newObject->$dbName = $fieldsToPrefix[$dbName] . $newObject->$dbName;
1637 }
1638 if (isset($fieldsToSuffix[$dbName])) {
1639 $newObject->$dbName .= $fieldsToSuffix[$dbName];
1640 }
1641 if (isset($fieldsToReplace[$dbName])) {
1642 $newObject->$dbName = $fieldsToReplace[$dbName];
1643 }
1644
6c71f6c7 1645 if ($type == 'Timestamp' || $type == 'Date') {
6a488035
TO
1646 $newObject->$dbName = CRM_Utils_Date::isoToMysql($newObject->$dbName);
1647 }
1648
1649 if ($newData) {
1650 foreach ($newData as $k => $v) {
1651 $newObject->$k = $v;
1652 }
1653 }
1654 }
1655 $newObject->save();
1656 }
1657 return $newObject;
1658 }
1659
7a9ab499
EM
1660 /**
1661 * Cascade update through related entities.
1662 *
1663 * @param string $daoName
1664 * @param $fromId
1665 * @param $toId
1666 * @param array $newData
1667 *
1273d77c 1668 * @return CRM_Core_DAO|null
7a9ab499 1669 */
00be9182 1670 public static function cascadeUpdate($daoName, $fromId, $toId, $newData = array()) {
353ffa53 1671 $object = new $daoName();
62933949 1672 $object->id = $fromId;
1673
1674 if ($object->find(TRUE)) {
353ffa53 1675 $newObject = new $daoName();
62933949 1676 $newObject->id = $toId;
1677
1678 if ($newObject->find(TRUE)) {
44ce4aa3 1679 $fields = $object->fields();
62933949 1680 foreach ($fields as $name => $value) {
1681 if ($name == 'id' || $value['name'] == 'id') {
1682 // copy everything but the id!
1683 continue;
1684 }
1685
1686 $colName = $value['name'];
1687 $newObject->$colName = $object->$colName;
1688
1689 if (substr($name, -5) == '_date' ||
1690 substr($name, -10) == '_date_time'
1691 ) {
1692 $newObject->$colName = CRM_Utils_Date::isoToMysql($newObject->$colName);
1693 }
1694 }
1695 foreach ($newData as $k => $v) {
1696 $newObject->$k = $v;
1697 }
1698 $newObject->save();
1699 return $newObject;
1700 }
1701 }
1273d77c 1702 return NULL;
62933949 1703 }
1704
6a488035
TO
1705 /**
1706 * Given the component id, compute the contact id
1707 * since its used for things like send email
b3342109
EM
1708 *
1709 * @param $componentIDs
100fef9d 1710 * @param string $tableName
d94a02b4 1711 * @param string $idField
6e3090fb 1712 *
b3342109 1713 * @return array
6a488035 1714 */
d94a02b4 1715 public static function getContactIDsFromComponent($componentIDs, $tableName, $idField = 'id') {
6a488035
TO
1716 $contactIDs = array();
1717
1718 if (empty($componentIDs)) {
1719 return $contactIDs;
1720 }
1721
1722 $IDs = implode(',', $componentIDs);
1723 $query = "
1724SELECT contact_id
1725 FROM $tableName
d94a02b4 1726 WHERE $idField IN ( $IDs )
6a488035
TO
1727";
1728
1729 $dao = CRM_Core_DAO::executeQuery($query);
1730 while ($dao->fetch()) {
1731 $contactIDs[] = $dao->contact_id;
1732 }
1733 return $contactIDs;
1734 }
1735
1736 /**
fe482240 1737 * Fetch object based on array of properties.
6a488035 1738 *
6a0b768e
TO
1739 * @param string $daoName
1740 * Name of the dao object.
dd244018 1741 * @param string $fieldIdName
100fef9d 1742 * @param int $fieldId
dd244018 1743 * @param $details
6a0b768e
TO
1744 * @param array $returnProperities
1745 * An assoc array of fields that need to be returned, eg array( 'first_name', 'last_name').
dd244018 1746 *
a6c01b45
CW
1747 * @return object
1748 * an object of type referenced by daoName
6a488035 1749 */
00be9182 1750 public static function commonRetrieveAll($daoName, $fieldIdName = 'id', $fieldId, &$details, $returnProperities = NULL) {
795492f3 1751 require_once str_replace('_', DIRECTORY_SEPARATOR, $daoName) . ".php";
353ffa53 1752 $object = new $daoName();
6a488035
TO
1753 $object->$fieldIdName = $fieldId;
1754
1755 // return only specific fields if returnproperties are sent
1756 if (!empty($returnProperities)) {
1757 $object->selectAdd();
1758 $object->selectAdd('id');
1759 $object->selectAdd(implode(',', $returnProperities));
1760 }
1761
1762 $object->find();
1763 while ($object->fetch()) {
1764 $defaults = array();
1765 self::storeValues($object, $defaults);
1766 $details[$object->id] = $defaults;
1767 }
1768
1769 return $details;
1770 }
1771
44ce4aa3
CW
1772 /**
1773 * Drop all CiviCRM tables.
1774 *
1775 * @throws \CRM_Exception
1776 */
00be9182 1777 public static function dropAllTables() {
6a488035
TO
1778
1779 // first drop all the custom tables we've created
1780 CRM_Core_BAO_CustomGroup::dropAllTables();
1781
1782 // drop all multilingual views
1783 CRM_Core_I18n_Schema::dropAllViews();
1784
1785 CRM_Utils_File::sourceSQLFile(CIVICRM_DSN,
1786 dirname(__FILE__) . DIRECTORY_SEPARATOR .
1787 '..' . DIRECTORY_SEPARATOR .
1788 '..' . DIRECTORY_SEPARATOR .
1789 'sql' . DIRECTORY_SEPARATOR .
1790 'civicrm_drop.mysql'
1791 );
1792 }
1793
a0ee3941
EM
1794 /**
1795 * @param $string
1796 *
1797 * @return string
1798 */
00be9182 1799 public static function escapeString($string) {
6a488035 1800 static $_dao = NULL;
6a488035 1801 if (!$_dao) {
8f56d1f5
MM
1802 // If this is an atypical case (e.g. preparing .sql file before CiviCRM
1803 // has been installed), then we fallback DB-less str_replace escaping, as
1804 // we can't use mysqli_real_escape_string, as there is no DB connection.
1805 // Note: In typical usage, escapeString() will only check one conditional
1806 // ("if !$_dao") rather than two conditionals ("if !defined(DSN)")
74032946 1807 if (!defined('CIVICRM_DSN')) {
8f56d1f5
MM
1808 // See http://php.net/manual/en/mysqli.real-escape-string.php for the
1809 // list of characters mysqli_real_escape_string escapes.
cf1d34ab
MM
1810 $search = array("\\", "\x00", "\n", "\r", "'", '"', "\x1a");
1811 $replace = array("\\\\", "\\0", "\\n", "\\r", "\'", '\"', "\\Z");
8f56d1f5 1812 return str_replace($search, $replace, $string);
74032946 1813 }
6a488035
TO
1814 $_dao = new CRM_Core_DAO();
1815 }
6a488035
TO
1816 return $_dao->escape($string);
1817 }
1818
1819 /**
1820 * Escape a list of strings for use with "WHERE X IN (...)" queries.
1821 *
5a4f6742
CW
1822 * @param array $strings
1823 * @param string $default
1824 * the value to use if $strings has no elements.
a6c01b45
CW
1825 * @return string
1826 * eg "abc","def","ghi"
6a488035 1827 */
00be9182 1828 public static function escapeStrings($strings, $default = NULL) {
6a488035
TO
1829 static $_dao = NULL;
1830 if (!$_dao) {
1831 $_dao = new CRM_Core_DAO();
1832 }
1833
1834 if (empty($strings)) {
1835 return $default;
1836 }
1837
1838 $escapes = array_map(array($_dao, 'escape'), $strings);
1839 return '"' . implode('","', $escapes) . '"';
1840 }
1841
a0ee3941
EM
1842 /**
1843 * @param $string
1844 *
1845 * @return string
1846 */
00be9182 1847 public static function escapeWildCardString($string) {
6a488035
TO
1848 // CRM-9155
1849 // ensure we escape the single characters % and _ which are mysql wild
1850 // card characters and could come in via sortByCharacter
1851 // note that mysql does not escape these characters
1852 if ($string && in_array($string,
1853 array('%', '_', '%%', '_%')
353ffa53
TO
1854 )
1855 ) {
6a488035
TO
1856 return '\\' . $string;
1857 }
1858
1859 return self::escapeString($string);
1860 }
1861
92b83508
EM
1862 /**
1863 * Creates a test object, including any required objects it needs via recursion
b3342109
EM
1864 * createOnly: only create in database, do not store or return the objects (useful for perf testing)
1865 * ONLY USE FOR TESTING
1866 *
c490a46a 1867 * @param string $daoName
b3342109
EM
1868 * @param array $params
1869 * @param int $numObjects
1870 * @param bool $createOnly
1871 *
795492f3
TO
1872 * @return object|array|NULL
1873 * NULL if $createOnly. A single object if $numObjects==1. Otherwise, an array of multiple objects.
92b83508 1874 */
795492f3 1875 public static function createTestObject(
6a488035
TO
1876 $daoName,
1877 $params = array(),
1878 $numObjects = 1,
1879 $createOnly = FALSE
1880 ) {
b6262a4c
EM
1881 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
1882 // so we re-set here in case
1883 $config = CRM_Core_Config::singleton();
1884 $config->backtrace = TRUE;
1885
6a488035
TO
1886 static $counter = 0;
1887 CRM_Core_DAO::$_testEntitiesToSkip = array(
1888 'CRM_Core_DAO_Worldregion',
1889 'CRM_Core_DAO_StateProvince',
1890 'CRM_Core_DAO_Country',
1891 'CRM_Core_DAO_Domain',
795492f3 1892 'CRM_Financial_DAO_FinancialType',
353ffa53 1893 //because valid ones exist & we use pick them due to pseudoconstant can't reliably create & delete these
6a488035
TO
1894 );
1895
2069d1b7
TO
1896 // Prefer to instantiate BAO's instead of DAO's (when possible)
1897 // so that assignTestValue()/assignTestFK() can be overloaded.
1898 $baoName = str_replace('_DAO_', '_BAO_', $daoName);
1899 if (class_exists($baoName)) {
1900 $daoName = $baoName;
1901 }
1902
6a488035
TO
1903 for ($i = 0; $i < $numObjects; ++$i) {
1904
1905 ++$counter;
e79cd558 1906 /** @var CRM_Core_DAO $object */
ab9aa379 1907 $object = new $daoName();
6a488035 1908
44ce4aa3 1909 $fields = $object->fields();
e1b64aab
TO
1910 foreach ($fields as $fieldName => $fieldDef) {
1911 $dbName = $fieldDef['name'];
f290b6ef 1912 $FKClassName = CRM_Utils_Array::value('FKClassName', $fieldDef);
e1b64aab 1913 $required = CRM_Utils_Array::value('required', $fieldDef);
f290b6ef 1914
6a488035
TO
1915 if (CRM_Utils_Array::value($dbName, $params) !== NULL && !is_array($params[$dbName])) {
1916 $object->$dbName = $params[$dbName];
1917 }
1918
1919 elseif ($dbName != 'id') {
f290b6ef 1920 if ($FKClassName != NULL) {
e79cd558 1921 $object->assignTestFK($fieldName, $fieldDef, $params);
6a488035 1922 continue;
0db6c3e1
TO
1923 }
1924 else {
f290b6ef 1925 $object->assignTestValue($fieldName, $fieldDef, $counter);
6a488035 1926 }
6a488035
TO
1927 }
1928 }
b3342109 1929
6a488035
TO
1930 $object->save();
1931
1932 if (!$createOnly) {
6a488035 1933 $objects[$i] = $object;
6a488035 1934 }
f290b6ef
TO
1935 else {
1936 unset($object);
1937 }
6a488035
TO
1938 }
1939
1940 if ($createOnly) {
795492f3 1941 return NULL;
6a488035 1942 }
f290b6ef
TO
1943 elseif ($numObjects == 1) {
1944 return $objects[0];
1945 }
1946 else {
1947 return $objects;
1948 }
6a488035
TO
1949 }
1950
92b83508 1951 /**
fe482240 1952 * Deletes the this object plus any dependent objects that are associated with it.
92b83508 1953 * ONLY USE FOR TESTING
b3342109 1954 *
c490a46a 1955 * @param string $daoName
b3342109 1956 * @param array $params
92b83508 1957 */
00be9182 1958 public static function deleteTestObjects($daoName, $params = array()) {
b6262a4c
EM
1959 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
1960 // so we re-set here in case
1961 $config = CRM_Core_Config::singleton();
1962 $config->backtrace = TRUE;
6a488035 1963
b6262a4c 1964 $object = new $daoName();
6a488035
TO
1965 $object->id = CRM_Utils_Array::value('id', $params);
1966
1967 $deletions = array(); // array(array(0 => $daoName, 1 => $daoParams))
1968 if ($object->find(TRUE)) {
1969
44ce4aa3 1970 $fields = $object->fields();
6a488035
TO
1971 foreach ($fields as $name => $value) {
1972
1973 $dbName = $value['name'];
1974
1975 $FKClassName = CRM_Utils_Array::value('FKClassName', $value);
1976 $required = CRM_Utils_Array::value('required', $value);
1977 if ($FKClassName != NULL
1978 && $object->$dbName
1979 && !in_array($FKClassName, CRM_Core_DAO::$_testEntitiesToSkip)
806e9b71
EM
1980 && ($required || $dbName == 'contact_id')
1981 //I'm a bit stuck on this one - we might need to change the singleValueAlter so that the entities don't share a contact
1982 // to make this test process pass - line below makes pass for now
353ffa53
TO
1983 && $dbName != 'member_of_contact_id'
1984 ) {
6a488035
TO
1985 $deletions[] = array($FKClassName, array('id' => $object->$dbName)); // x
1986 }
1987 }
1988 }
1989
1990 $object->delete();
1991
1992 foreach ($deletions as $deletion) {
1993 CRM_Core_DAO::deleteTestObjects($deletion[0], $deletion[1]);
353ffa53 1994 }
6a488035
TO
1995 }
1996
64d24a64 1997 /**
fe482240 1998 * Set defaults when creating new entity.
64d24a64
EM
1999 * (don't call this set defaults as already in use with different signature in some places)
2000 *
c490a46a 2001 * @param array $params
64d24a64
EM
2002 * @param $defaults
2003 */
00be9182 2004 public static function setCreateDefaults(&$params, $defaults) {
16e268ad 2005 if (!empty($params['id'])) {
64d24a64
EM
2006 return;
2007 }
2008 foreach ($defaults as $key => $value) {
2009 if (!array_key_exists($key, $params) || $params[$key] === NULL) {
2010 $params[$key] = $value;
2011 }
2012 }
2013 }
2014
a0ee3941
EM
2015 /**
2016 * @param string $prefix
2017 * @param bool $addRandomString
2018 * @param null $string
2019 *
2020 * @return string
00f8d61b
TO
2021 * @deprecated
2022 * @see CRM_Utils_SQL_TempTable
a0ee3941 2023 */
00be9182 2024 public static function createTempTableName($prefix = 'civicrm', $addRandomString = TRUE, $string = NULL) {
6a488035
TO
2025 $tableName = $prefix . "_temp";
2026
2027 if ($addRandomString) {
2028 if ($string) {
2029 $tableName .= "_" . $string;
2030 }
2031 else {
2032 $tableName .= "_" . md5(uniqid('', TRUE));
2033 }
2034 }
2035 return $tableName;
2036 }
2037
a0ee3941
EM
2038 /**
2039 * @param bool $view
2040 * @param bool $trigger
2041 *
2042 * @return bool
2043 */
00be9182 2044 public static function checkTriggerViewPermission($view = TRUE, $trigger = TRUE) {
344b05bc 2045 if (\Civi::settings()->get('logging_no_trigger_permission')) {
2046 return TRUE;
2047 }
6a488035
TO
2048 // test for create view and trigger permissions and if allowed, add the option to go multilingual
2049 // and logging
2050 // I'm not sure why we use the getStaticProperty for an error, rather than checking for DB_Error
344b05bc 2051 CRM_Core_TemporaryErrorScope::ignoreException();
6a488035
TO
2052 $dao = new CRM_Core_DAO();
2053 if ($view) {
cc7762c0 2054 $result = $dao->query('CREATE OR REPLACE VIEW civicrm_domain_view AS SELECT * FROM civicrm_domain');
2055 if (PEAR::getStaticProperty('DB_DataObject', 'lastError') || is_a($result, 'DB_Error')) {
6a488035
TO
2056 return FALSE;
2057 }
2058 }
2059
2060 if ($trigger) {
2061 $result = $dao->query('CREATE TRIGGER civicrm_domain_trigger BEFORE INSERT ON civicrm_domain FOR EACH ROW BEGIN END');
2062 if (PEAR::getStaticProperty('DB_DataObject', 'lastError') || is_a($result, 'DB_Error')) {
6a488035
TO
2063 if ($view) {
2064 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
2065 }
2066 return FALSE;
2067 }
2068
2069 $dao->query('DROP TRIGGER IF EXISTS civicrm_domain_trigger');
2070 if (PEAR::getStaticProperty('DB_DataObject', 'lastError')) {
6a488035
TO
2071 if ($view) {
2072 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
2073 }
2074 return FALSE;
2075 }
2076 }
2077
2078 if ($view) {
2079 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
2080 if (PEAR::getStaticProperty('DB_DataObject', 'lastError')) {
6a488035
TO
2081 return FALSE;
2082 }
2083 }
6a488035
TO
2084
2085 return TRUE;
2086 }
2087
a0ee3941
EM
2088 /**
2089 * @param null $message
2090 * @param bool $printDAO
2091 */
00be9182 2092 public static function debugPrint($message = NULL, $printDAO = TRUE) {
6a488035
TO
2093 CRM_Utils_System::xMemory("{$message}: ");
2094
2095 if ($printDAO) {
2096 global $_DB_DATAOBJECT;
2097 $q = array();
2098 foreach (array_keys($_DB_DATAOBJECT['RESULTS']) as $id) {
2099 $q[] = $_DB_DATAOBJECT['RESULTS'][$id]->query;
2100 }
2101 CRM_Core_Error::debug('_DB_DATAOBJECT', $q);
2102 }
2103 }
2104
77b97be7
EM
2105 /**
2106 * Build a list of triggers via hook and add them to (err, reconcile them
2107 * with) the database.
2108 *
5a4f6742
CW
2109 * @param string $tableName
2110 * the specific table requiring a rebuild; or NULL to rebuild all tables.
77b97be7 2111 * @param bool $force
4ed867e0 2112 * @deprecated
77b97be7
EM
2113 *
2114 * @see CRM-9716
2115 */
00be9182 2116 public static function triggerRebuild($tableName = NULL, $force = FALSE) {
4ed867e0 2117 Civi::service('sql_triggers')->rebuild($tableName, $force);
6a488035
TO
2118 }
2119
aca2de91
CW
2120 /**
2121 * Because sql functions are sometimes lost, esp during db migration, we check here to avoid numerous support requests
2122 * @see http://issues.civicrm.org/jira/browse/CRM-13822
2123 * TODO: Alternative solutions might be
2124 * * Stop using functions and find another way to strip numeric characters from phones
2125 * * Give better error messages (currently a missing fn fatals with "unknown error")
2126 */
00be9182 2127 public static function checkSqlFunctionsExist() {
aca2de91
CW
2128 if (!self::$_checkedSqlFunctionsExist) {
2129 self::$_checkedSqlFunctionsExist = TRUE;
2130 $dao = CRM_Core_DAO::executeQuery("SHOW function status WHERE db = database() AND name = 'civicrm_strip_non_numeric'");
2131 if (!$dao->fetch()) {
2132 self::triggerRebuild();
2133 }
2134 }
2135 }
2136
6a488035 2137 /**
fe482240 2138 * Wrapper function to drop triggers.
6a488035 2139 *
5a4f6742
CW
2140 * @param string $tableName
2141 * the specific table requiring a rebuild; or NULL to rebuild all tables.
4ed867e0 2142 * @deprecated
6a488035 2143 */
00be9182 2144 public static function dropTriggers($tableName = NULL) {
4ed867e0 2145 Civi::service('sql_triggers')->dropTriggers($tableName);
6a488035
TO
2146 }
2147
2148 /**
5a4f6742
CW
2149 * @param array $info
2150 * per hook_civicrm_triggerInfo.
2151 * @param string $onlyTableName
2152 * the specific table requiring a rebuild; or NULL to rebuild all tables.
4ed867e0 2153 * @deprecated
6a488035 2154 */
00be9182 2155 public static function createTriggers(&$info, $onlyTableName = NULL) {
4ed867e0 2156 Civi::service('sql_triggers')->createTriggers($info, $onlyTableName);
6a488035
TO
2157 }
2158
ffcef054
TO
2159 /**
2160 * Given a list of fields, create a list of references.
2161 *
6a0b768e
TO
2162 * @param string $className
2163 * BAO/DAO class name.
ffcef054
TO
2164 * @return array<CRM_Core_Reference_Interface>
2165 */
00be9182 2166 public static function createReferenceColumns($className) {
ffcef054
TO
2167 $result = array();
2168 $fields = $className::fields();
2169 foreach ($fields as $field) {
2170 if (isset($field['pseudoconstant'], $field['pseudoconstant']['optionGroupName'])) {
2171 $result[] = new CRM_Core_Reference_OptionValue(
2172 $className::getTableName(),
2173 $field['name'],
2174 'civicrm_option_value',
2175 CRM_Utils_Array::value('keyColumn', $field['pseudoconstant'], 'value'),
2176 $field['pseudoconstant']['optionGroupName']
2177 );
2178 }
2179 }
2180 return $result;
2181 }
2182
6a488035 2183 /**
71e5aa5c
ARW
2184 * Find all records which refer to this entity.
2185 *
a6c01b45 2186 * @return array
16b10e64 2187 * Array of objects referencing this
71e5aa5c 2188 */
00be9182 2189 public function findReferences() {
71e5aa5c
ARW
2190 $links = self::getReferencesToTable(static::getTableName());
2191
2192 $occurrences = array();
2193 foreach ($links as $refSpec) {
11626cf1 2194 /** @var $refSpec CRM_Core_Reference_Interface */
31bed28c 2195 $daoName = CRM_Core_DAO_AllCoreTables::getClassForTable($refSpec->getReferenceTable());
de49f39c 2196 $result = $refSpec->findReferences($this);
ffcef054
TO
2197 if ($result) {
2198 while ($result->fetch()) {
2199 $obj = new $daoName();
2200 $obj->id = $result->id;
2201 $occurrences[] = $obj;
2202 }
71e5aa5c
ARW
2203 }
2204 }
2205
2206 return $occurrences;
2207 }
2208
a0ee3941 2209 /**
a6c01b45
CW
2210 * @return array
2211 * each item has keys:
16b10e64
CW
2212 * - name: string
2213 * - type: string
2214 * - count: int
2215 * - table: string|null SQL table name
2216 * - key: string|null SQL column name
a0ee3941 2217 */
00be9182 2218 public function getReferenceCounts() {
1256c139
TO
2219 $links = self::getReferencesToTable(static::getTableName());
2220
2221 $counts = array();
2222 foreach ($links as $refSpec) {
2223 /** @var $refSpec CRM_Core_Reference_Interface */
2224 $count = $refSpec->getReferenceCount($this);
2225 if ($count['count'] != 0) {
2226 $counts[] = $count;
2227 }
2228 }
2229
91dee34b
TO
2230 foreach (CRM_Core_Component::getEnabledComponents() as $component) {
2231 /** @var $component CRM_Core_Component_Info */
2232 $counts = array_merge($counts, $component->getReferenceCounts($this));
2233 }
2234 CRM_Utils_Hook::referenceCounts($this, $counts);
2235
1256c139
TO
2236 return $counts;
2237 }
2238
71e5aa5c
ARW
2239 /**
2240 * List all tables which have hard foreign keys to this table.
6a488035 2241 *
71e5aa5c
ARW
2242 * For now, this returns a description of every entity_id/entity_table
2243 * reference.
2244 * TODO: filter dynamic entity references on the $tableName, based on
2245 * schema metadata in dynamicForeignKey which enumerates a restricted
2246 * set of possible entity_table's.
6a488035 2247 *
6a0b768e
TO
2248 * @param string $tableName
2249 * Table referred to.
6a488035 2250 *
a6c01b45
CW
2251 * @return array
2252 * structure of table and column, listing every table with a
16b10e64 2253 * foreign key reference to $tableName, and the column where the key appears.
6a488035 2254 */
00be9182 2255 public static function getReferencesToTable($tableName) {
71e5aa5c 2256 $refsFound = array();
31bed28c 2257 foreach (CRM_Core_DAO_AllCoreTables::getClasses() as $daoClassName) {
71e5aa5c
ARW
2258 $links = $daoClassName::getReferenceColumns();
2259 $daoTableName = $daoClassName::getTableName();
2260
2261 foreach ($links as $refSpec) {
11626cf1
TO
2262 /** @var $refSpec CRM_Core_Reference_Interface */
2263 if ($refSpec->matchesTargetTable($tableName)) {
71e5aa5c
ARW
2264 $refsFound[] = $refSpec;
2265 }
6a488035
TO
2266 }
2267 }
71e5aa5c 2268 return $refsFound;
6a488035 2269 }
032c9d10
TO
2270
2271 /**
2272 * Lookup the value of a MySQL global configuration variable.
2273 *
6a0b768e
TO
2274 * @param string $name
2275 * E.g. "thread_stack".
032c9d10
TO
2276 * @param mixed $default
2277 * @return mixed
2278 */
2279 public static function getGlobalSetting($name, $default = NULL) {
2280 // Alternatively, SELECT @@GLOBAL.thread_stack, but
2281 // that has been reported to fail under MySQL 5.0 for OS X
2282 $escapedName = self::escapeString($name);
2283 $dao = CRM_Core_DAO::executeQuery("SHOW VARIABLES LIKE '$escapedName'");
2284 if ($dao->fetch()) {
2285 return $dao->Value;
ab00f69d
DL
2286 }
2287 else {
032c9d10
TO
2288 return $default;
2289 }
2290 }
dc86f881 2291
9d5c7f14 2292
2293 /**
2294 * Update the fields array to also hold keys for pseudoconstant fields that relate to contained fields.
2295 *
2296 * This is relevant where we want to offer both the ID field and the label field
2297 * as an option, e.g. search builder.
2298 *
2299 * It is currently limited for optionGroupName for purposes keeping the scope of the
2300 * change small, but is appropriate for other sorts of pseudoconstants.
2301 *
2302 * @param array $fields
2303 */
2304 protected static function appendPseudoConstantsToFields(&$fields) {
2305 foreach ($fields as $field) {
2306 if (!empty($field['pseudoconstant']) && !empty($field['pseudoconstant']['optionGroupName'])) {
2307 $fields[$field['pseudoconstant']['optionGroupName']] = array(
2308 'title' => CRM_Core_BAO_OptionGroup::getTitleByName($field['pseudoconstant']['optionGroupName']),
2309 'name' => $field['pseudoconstant']['optionGroupName'],
2310 'data_type' => CRM_Utils_Type::T_STRING,
2311 );
2312 }
2313 }
2314 }
2315
dc86f881
CW
2316 /**
2317 * Get options for the called BAO object's field.
167bcb5f 2318 *
dc86f881 2319 * This function can be overridden by each BAO to add more logic related to context.
2158332a 2320 * The overriding function will generally call the lower-level CRM_Core_PseudoConstant::get
dc86f881 2321 *
2a3f958d 2322 * @param string $fieldName
6a0b768e 2323 * @param string $context
795492f3 2324 * @see CRM_Core_DAO::buildOptionsContext
6a0b768e 2325 * @param array $props
16b10e64 2326 * whatever is known about this bao object.
9a1b1948 2327 *
795492f3 2328 * @return array|bool
dc86f881
CW
2329 */
2330 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
2158332a 2331 // If a given bao does not override this function
dc86f881 2332 $baoName = get_called_class();
7bd16b05 2333 return CRM_Core_PseudoConstant::get($baoName, $fieldName, $props, $context);
dc86f881 2334 }
786ad6e1 2335
2a3f958d
CW
2336 /**
2337 * Populate option labels for this object's fields.
2338 *
2339 * @throws exception if called directly on the base class
2340 */
2341 public function getOptionLabels() {
2342 $fields = $this->fields();
2343 if ($fields === NULL) {
795492f3 2344 throw new Exception('Cannot call getOptionLabels on CRM_Core_DAO');
2a3f958d
CW
2345 }
2346 foreach ($fields as $field) {
2347 $name = CRM_Utils_Array::value('name', $field);
2348 if ($name && isset($this->$name)) {
a8c23526 2349 $label = CRM_Core_PseudoConstant::getLabel(get_class($this), $name, $this->$name);
2a3f958d
CW
2350 if ($label !== FALSE) {
2351 // Append 'label' onto the field name
2352 $labelName = $name . '_label';
2353 $this->$labelName = $label;
2354 }
2355 }
2356 }
2357 }
2358
786ad6e1
CW
2359 /**
2360 * Provides documentation and validation for the buildOptions $context param
2361 *
6a0b768e 2362 * @param string $context
77b97be7
EM
2363 *
2364 * @throws Exception
2365 * @return array
786ad6e1
CW
2366 */
2367 public static function buildOptionsContext($context = NULL) {
2368 $contexts = array(
a2407bc0
CW
2369 'get' => "get: all options are returned, even if they are disabled; labels are translated.",
2370 'create' => "create: options are filtered appropriately for the object being created/updated; labels are translated.",
2371 'search' => "search: searchable options are returned; labels are translated.",
2372 'validate' => "validate: all options are returned, even if they are disabled; machine names are used in place of labels.",
2373 'abbreviate' => "abbreviate: enabled options are returned; labels are replaced with abbreviations.",
2374 'match' => "match: enabled options are returned using machine names as keys; labels are translated.",
786ad6e1
CW
2375 );
2376 // Validation: enforce uniformity of this param
2377 if ($context !== NULL && !isset($contexts[$context])) {
395d8dc6 2378 throw new Exception("'$context' is not a valid context for buildOptions.");
786ad6e1
CW
2379 }
2380 return $contexts;
2381 }
2382
5fafc9b0 2383 /**
100fef9d 2384 * @param string $fieldName
5fafc9b0
CW
2385 * @return bool|array
2386 */
00be9182 2387 public function getFieldSpec($fieldName) {
5fafc9b0
CW
2388 $fields = $this->fields();
2389 $fieldKeys = $this->fieldKeys();
2390
2391 // Support "unique names" as well as sql names
2392 $fieldKey = $fieldName;
2393 if (empty($fields[$fieldKey])) {
2394 $fieldKey = CRM_Utils_Array::value($fieldName, $fieldKeys);
2395 }
2396 // If neither worked then this field doesn't exist. Return false.
2397 if (empty($fields[$fieldKey])) {
2398 return FALSE;
2399 }
2400 return $fields[$fieldKey];
2401 }
2402
faf8c53b 2403 /**
bb05da0c 2404 * Get SQL where clause for SQL filter syntax input parameters.
2405 *
faf8c53b 2406 * SQL version of api function to assign filters to the DAO based on the syntax
2407 * $field => array('IN' => array(4,6,9))
2408 * OR
2409 * $field => array('LIKE' => array('%me%))
2410 * etc
2411 *
6a0b768e
TO
2412 * @param string $fieldName
2413 * Name of fields.
5a4f6742
CW
2414 * @param array $filter
2415 * filter to be applied indexed by operator.
2416 * @param string $type
2417 * type of field (not actually used - nor in api @todo ).
2418 * @param string $alias
2419 * alternative field name ('as') @todo- not actually used.
6a0b768e
TO
2420 * @param bool $returnSanitisedArray
2421 * Return a sanitised array instead of a clause.
16b10e64 2422 * this is primarily so we can add filters @ the api level to the Query object based fields
9a1b1948
EM
2423 *
2424 * @throws Exception
c490a46a 2425 *
72b3a70c
CW
2426 * @return NULL|string|array
2427 * a string is returned if $returnSanitisedArray is not set, otherwise and Array or NULL
06f48f96 2428 * depending on whether it is supported as yet
9a1b1948 2429 */
e47bcddb 2430 public static function createSQLFilter($fieldName, $filter, $type = NULL, $alias = NULL, $returnSanitisedArray = FALSE) {
faf8c53b 2431 foreach ($filter as $operator => $criteria) {
6e23130a 2432 if (in_array($operator, self::acceptedSQLOperators(), TRUE)) {
faf8c53b 2433 switch ($operator) {
2434 // unary operators
faf8c53b 2435 case 'IS NULL':
2436 case 'IS NOT NULL':
c490a46a 2437 if (!$returnSanitisedArray) {
78c0bfc0 2438 return (sprintf('%s %s', $fieldName, $operator));
2439 }
c490a46a 2440 else {
a75c13cc 2441 return (sprintf('%s %s ', $fieldName, $operator));
06f48f96 2442 }
faf8c53b 2443 break;
2444
2445 // ternary operators
2446 case 'BETWEEN':
2447 case 'NOT BETWEEN':
2448 if (empty($criteria[0]) || empty($criteria[1])) {
395d8dc6 2449 throw new Exception("invalid criteria for $operator");
faf8c53b 2450 }
c490a46a 2451 if (!$returnSanitisedArray) {
78c0bfc0 2452 return (sprintf('%s ' . $operator . ' "%s" AND "%s"', $fieldName, CRM_Core_DAO::escapeString($criteria[0]), CRM_Core_DAO::escapeString($criteria[1])));
2453 }
c490a46a 2454 else {
06f48f96 2455 return NULL; // not yet implemented (tests required to implement)
2456 }
faf8c53b 2457 break;
2458
2459 // n-ary operators
2460 case 'IN':
2461 case 'NOT IN':
2462 if (empty($criteria)) {
395d8dc6 2463 throw new Exception("invalid criteria for $operator");
faf8c53b 2464 }
2465 $escapedCriteria = array_map(array(
2466 'CRM_Core_DAO',
795492f3 2467 'escapeString',
faf8c53b 2468 ), $criteria);
c490a46a 2469 if (!$returnSanitisedArray) {
78c0bfc0 2470 return (sprintf('%s %s ("%s")', $fieldName, $operator, implode('", "', $escapedCriteria)));
2471 }
2472 return $escapedCriteria;
faf8c53b 2473
2474 // binary operators
6a488035 2475
faf8c53b 2476 default:
c490a46a 2477 if (!$returnSanitisedArray) {
353ffa53 2478 return (sprintf('%s %s "%s"', $fieldName, $operator, CRM_Core_DAO::escapeString($criteria)));
78c0bfc0 2479 }
c490a46a 2480 else {
06f48f96 2481 return NULL; // not yet implemented (tests required to implement)
2482 }
faf8c53b 2483 }
2484 }
2485 }
2486 }
6842bb53 2487
e4176358
CW
2488 /**
2489 * @see http://issues.civicrm.org/jira/browse/CRM-9150
2490 * support for other syntaxes is discussed in ticket but being put off for now
2491 * @return array
2492 */
2493 public static function acceptedSQLOperators() {
353ffa53
TO
2494 return array(
2495 '=',
2496 '<=',
2497 '>=',
2498 '>',
2499 '<',
2500 'LIKE',
2501 "<>",
2502 "!=",
2503 "NOT LIKE",
2504 'IN',
2505 'NOT IN',
2506 'BETWEEN',
2507 'NOT BETWEEN',
2508 'IS NOT NULL',
795492f3 2509 'IS NULL',
353ffa53 2510 );
e4176358
CW
2511 }
2512
6842bb53
DL
2513 /**
2514 * SQL has a limit of 64 characters on various names:
2515 * table name, trigger name, column name ...
2516 *
2517 * For custom groups and fields we generated names from user entered input
2518 * which can be longer than this length, this function helps with creating
2519 * strings that meet various criteria.
2520 *
6a0b768e
TO
2521 * @param string $string
2522 * The string to be shortened.
2523 * @param int $length
2524 * The max length of the string.
9a1b1948
EM
2525 *
2526 * @param bool $makeRandom
2527 *
2528 * @return string
6842bb53
DL
2529 */
2530 public static function shortenSQLName($string, $length = 60, $makeRandom = FALSE) {
2531 // early return for strings that meet the requirements
2532 if (strlen($string) <= $length) {
2533 return $string;
2534 }
2535
2536 // easy return for calls that dont need a randomized uniq string
c490a46a 2537 if (!$makeRandom) {
6842bb53
DL
2538 return substr($string, 0, $length);
2539 }
2540
2541 // the string is longer than the length and we need a uniq string
b44e3f84 2542 // for the same tablename we need the same uniq string every time
6842bb53 2543 // hence we use md5 on the string, which is not random
a8dd306e
DL
2544 // we'll append 8 characters to the end of the tableName
2545 $md5string = substr(md5($string), 0, 8);
2546 return substr($string, 0, $length - 8) . "_{$md5string}";
6842bb53
DL
2547 }
2548
a0ee3941 2549 /**
33092c89
SB
2550 * https://issues.civicrm.org/jira/browse/CRM-17748
2551 * Sets the internal options to be used on a query
2552 *
2553 * @param array $options
2554 *
2555 */
6232119d 2556 public function setOptions($options) {
33092c89
SB
2557 if (is_array($options)) {
2558 $this->_options = $options;
2559 }
2560 }
2561
2562 /**
2563 * https://issues.civicrm.org/jira/browse/CRM-17748
2564 * wrapper to pass internal DAO options down to DB_mysql/DB_Common level
2565 *
2566 * @param array $options
2567 *
2568 */
2569 protected function _setDBOptions($options) {
2570 global $_DB_DATAOBJECT;
2571
2572 if (is_array($options) && count($options)) {
2573 $conn = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
2574 foreach ($options as $option_name => $option_value) {
2575 $conn->setOption($option_name, $option_value);
2576 }
2577 }
2578 }
2579
6232119d 2580 /**
d343069c 2581 * @deprecated
c490a46a 2582 * @param array $params
a0ee3941 2583 */
353ffa53
TO
2584 public function setApiFilter(&$params) {
2585 }
6e1bb60c 2586
d343069c 2587 /**
20e41014 2588 * Generates acl clauses suitable for adding to WHERE or ON when doing an api.get for this entity
d343069c 2589 *
b53bcc5d
CW
2590 * Return format is in the form of fieldname => clauses starting with an operator. e.g.:
2591 * @code
2592 * array(
2593 * 'location_type_id' => array('IS NOT NULL', 'IN (1,2,3)')
2594 * )
2595 * @endcode
2596 *
2597 * Note that all array keys must be actual field names in this entity. Use subqueries to filter on other tables e.g. custom values.
2598 *
2599 * @return array
d343069c 2600 */
20e41014 2601 public function addSelectWhereClause() {
032346cc 2602 $clauses = array();
c6835264
CW
2603 $fields = $this->fields();
2604 foreach ($fields as $fieldName => $field) {
2605 // Clause for contact-related entities like Email, Relationship, etc.
0b80f0b4 2606 if (strpos($fieldName, 'contact_id') === 0 && CRM_Utils_Array::value('FKClassName', $field) == 'CRM_Contact_DAO_Contact') {
d1d3c04a 2607 $clauses[$fieldName] = CRM_Utils_SQL::mergeSubquery('Contact');
0b80f0b4 2608 }
c6835264
CW
2609 // Clause for an entity_table/entity_id combo
2610 if ($fieldName == 'entity_id' && isset($fields['entity_table'])) {
2611 $relatedClauses = array();
2612 $relatedEntities = $this->buildOptions('entity_table', 'get');
2613 foreach ((array) $relatedEntities as $table => $ent) {
fb1c6b2c
SL
2614 if (!empty($ent)) {
2615 $ent = CRM_Core_DAO_AllCoreTables::getBriefName(CRM_Core_DAO_AllCoreTables::getClassForTable($table));
2616 $subquery = CRM_Utils_SQL::mergeSubquery($ent);
2617 if ($subquery) {
2618 $relatedClauses[] = "(entity_table = '$table' AND entity_id " . implode(' AND entity_id ', $subquery) . ")";
2619 }
2620 else {
2621 $relatedClauses[] = "(entity_table = '$table')";
2622 }
c6835264
CW
2623 }
2624 }
2625 if ($relatedClauses) {
2626 $clauses['id'] = 'IN (SELECT id FROM `' . $this->tableName() . '` WHERE (' . implode(') OR (', $relatedClauses) . '))';
2627 }
2628 }
d343069c 2629 }
032346cc
CW
2630 CRM_Utils_Hook::selectWhereClause($this, $clauses);
2631 return $clauses;
d343069c
CW
2632 }
2633
6c051493 2634 /**
0b80f0b4
CW
2635 * This returns the final permissioned query string for this entity
2636 *
2637 * With acls from related entities + additional clauses from hook_civicrm_selectWhereClause
2638 *
6c051493
CW
2639 * @param string $tableAlias
2640 * @return array
2641 */
20e41014 2642 public static function getSelectWhereClause($tableAlias = NULL) {
6c051493
CW
2643 $bao = new static();
2644 if ($tableAlias === NULL) {
2645 $tableAlias = $bao->tableName();
2646 }
2647 $clauses = array();
20e41014 2648 foreach ((array) $bao->addSelectWhereClause() as $field => $vals) {
6c051493
CW
2649 $clauses[$field] = NULL;
2650 if ($vals) {
8db05db8 2651 $clauses[$field] = "(`$tableAlias`.`$field` IS NULL OR (`$tableAlias`.`$field` " . implode(" AND `$tableAlias`.`$field` ", (array) $vals) . '))';
6c051493
CW
2652 }
2653 }
2654 return $clauses;
2655 }
2656
a00fe575 2657 /**
ee17d64d
MM
2658 * ensure database name is 'safe', i.e. only contains word characters (includes underscores)
2659 * and dashes, and contains at least one [a-z] case insenstive.
a00fe575
PN
2660 *
2661 * @param $database
a00fe575
PN
2662 *
2663 * @return bool
2664 */
ee17d64d 2665 public static function requireSafeDBName($database) {
a00fe575
PN
2666 $matches = array();
2667 preg_match(
ee17d64d 2668 "/^[\w\-]*[a-z]+[\w\-]*$/i",
a00fe575
PN
2669 $database,
2670 $matches
2671 );
2672 if (empty($matches)) {
a00fe575
PN
2673 return FALSE;
2674 }
a00fe575
PN
2675 return TRUE;
2676 }
2677
2a5c9b4d
CW
2678 /**
2679 * Transform an array to a serialized string for database storage.
2680 *
2681 * @param array|NULL $value
2682 * @param $serializationType
2683 * @return string|NULL
dd3ec98b 2684 * @throws \Exception
2a5c9b4d
CW
2685 */
2686 public static function serializeField($value, $serializationType) {
2687 if ($value === NULL) {
2688 return NULL;
2689 }
2690 switch ($serializationType) {
2691 case self::SERIALIZE_SEPARATOR_BOOKEND:
2692 return $value === array() ? '' : CRM_Utils_Array::implodePadded($value);
2693
2694 case self::SERIALIZE_SEPARATOR_TRIMMED:
2695 return is_array($value) ? implode(self::VALUE_SEPARATOR, $value) : $value;
2696
2a5c9b4d
CW
2697 case self::SERIALIZE_JSON:
2698 return is_array($value) ? json_encode($value) : $value;
2699
2700 case self::SERIALIZE_PHP:
2701 return is_array($value) ? serialize($value) : $value;
dd3ec98b
CW
2702
2703 case self::SERIALIZE_COMMA:
2704 return is_array($value) ? implode(',', $value) : $value;
2705
2706 default:
2707 throw new Exception('Unknown serialization method for field.');
2a5c9b4d
CW
2708 }
2709 }
2710
2711 /**
2712 * Transform a serialized string from the database into an array.
2713 *
2714 * @param string|null $value
2715 * @param $serializationType
2716 * @return array|null
dd3ec98b 2717 * @throws \Exception
2a5c9b4d
CW
2718 */
2719 public static function unSerializeField($value, $serializationType) {
2720 if ($value === NULL) {
2721 return NULL;
2722 }
2723 if ($value === '') {
2724 return array();
2725 }
2726 switch ($serializationType) {
2727 case self::SERIALIZE_SEPARATOR_BOOKEND:
2728 return (array) CRM_Utils_Array::explodePadded($value);
2729
2730 case self::SERIALIZE_SEPARATOR_TRIMMED:
2731 return explode(self::VALUE_SEPARATOR, trim($value));
2732
2a5c9b4d
CW
2733 case self::SERIALIZE_JSON:
2734 return strlen($value) ? json_decode($value, TRUE) : array();
2735
2736 case self::SERIALIZE_PHP:
2737 return strlen($value) ? unserialize($value) : array();
dd3ec98b
CW
2738
2739 case self::SERIALIZE_COMMA:
2740 return explode(',', trim(str_replace(', ', '', $value)));
2741
2742 default:
2743 throw new Exception('Unknown serialization method for field.');
2a5c9b4d
CW
2744 }
2745 }
2746
232624b1 2747}