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