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