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