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