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