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