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