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