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