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