a few 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 +--------------------------------------------------------------------+
ced9bfed 26 */
6a488035
TO
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
1cd3ffa9
EM
462 /**
463 * Deletes items from table which match current objects variables
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 /**
640 * Get the size and maxLength attributes for this text field
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 /**
685 * Check if there is a record with the same name in the db
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 /**
715 * Check if there is a given column in a specific table
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 /**
893 * Check whether a specific column in a specific table has always the same value
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 /**
911 * Check whether a specific column in a specific table is always NULL
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 /**
928 * Check if there is a given table in the database
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
6a488035
TO
980 /**
981 * Given a DAO name, a column name and a column value, find the record and GET the value of another column in that record
982 *
6a0b768e
TO
983 * @param string $daoName
984 * Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact).
985 * @param int $searchValue
986 * Value of the column you want to search by.
987 * @param string $returnColumn
988 * Name of the column you want to GET the value of.
989 * @param string $searchColumn
990 * Name of the column you want to search by.
991 * @param bool $force
992 * Skip use of the cache.
6a488035 993 *
72b3a70c
CW
994 * @return string|null
995 * Value of $returnColumn in the retrieved record
6a488035 996 */
00be9182 997 public static function getFieldValue($daoName, $searchValue, $returnColumn = 'name', $searchColumn = 'id', $force = FALSE) {
6a488035
TO
998 if (
999 empty($searchValue) ||
1000 trim(strtolower($searchValue)) == 'null'
1001 ) {
1002 // adding this year since developers forget to check for an id
1003 // or for the 'null' (which is a bad DAO kludge)
1004 // and hence we get the first value in the db
1005 CRM_Core_Error::fatal();
1006 }
1007
1008 $cacheKey = "{$daoName}:{$searchValue}:{$returnColumn}:{$searchColumn}";
1009 if (self::$_dbColumnValueCache === NULL) {
1010 self::$_dbColumnValueCache = array();
1011 }
1012
1013 if (!array_key_exists($cacheKey, self::$_dbColumnValueCache) || $force) {
353ffa53 1014 $object = new $daoName();
6a488035
TO
1015 $object->$searchColumn = $searchValue;
1016 $object->selectAdd();
1017 $object->selectAdd($returnColumn);
1018
1019 $result = NULL;
1020 if ($object->find(TRUE)) {
1021 $result = $object->$returnColumn;
1022 }
1023 $object->free();
1024
1025 self::$_dbColumnValueCache[$cacheKey] = $result;
1026 }
1027 return self::$_dbColumnValueCache[$cacheKey];
1028 }
1029
1030 /**
1031 * Given a DAO name, a column name and a column value, find the record and SET the value of another column in that record
1032 *
6a0b768e
TO
1033 * @param string $daoName
1034 * Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact).
1035 * @param int $searchValue
1036 * Value of the column you want to search by.
1037 * @param string $setColumn
1038 * Name of the column you want to SET the value of.
1039 * @param string $setValue
1040 * SET the setColumn to this value.
1041 * @param string $searchColumn
1042 * Name of the column you want to search by.
6a488035 1043 *
795492f3 1044 * @return bool
a6c01b45 1045 * true if we found and updated the object, else false
6a488035 1046 */
00be9182 1047 public static function setFieldValue($daoName, $searchValue, $setColumn, $setValue, $searchColumn = 'id') {
353ffa53 1048 $object = new $daoName();
6a488035
TO
1049 $object->selectAdd();
1050 $object->selectAdd("$searchColumn, $setColumn");
1051 $object->$searchColumn = $searchValue;
1052 $result = FALSE;
1053 if ($object->find(TRUE)) {
1054 $object->$setColumn = $setValue;
1055 if ($object->save()) {
1056 $result = TRUE;
1057 }
1058 }
1059 $object->free();
1060 return $result;
1061 }
1062
1063 /**
1064 * Get sort string
1065 *
1066 * @param array|object $sort either array or CRM_Utils_Sort
6a0b768e
TO
1067 * @param string $default
1068 * Default sort value.
6a488035 1069 *
a6c01b45
CW
1070 * @return string
1071 * sortString
6a488035 1072 */
00be9182 1073 public static function getSortString($sort, $default = NULL) {
6a488035
TO
1074 // check if sort is of type CRM_Utils_Sort
1075 if (is_a($sort, 'CRM_Utils_Sort')) {
1076 return $sort->orderBy();
1077 }
1078
1079 // is it an array specified as $field => $sortDirection ?
1080 if ($sort) {
1081 foreach ($sort as $k => $v) {
1082 $sortString .= "$k $v,";
1083 }
1084 return rtrim($sortString, ',');
1085 }
1086 return $default;
1087 }
1088
1089 /**
c490a46a 1090 * Fetch object based on array of properties
6a488035 1091 *
6a0b768e
TO
1092 * @param string $daoName
1093 * Name of the dao object.
1094 * @param array $params
1095 * (reference ) an assoc array of name/value pairs.
1096 * @param array $defaults
1097 * (reference ) an assoc array to hold the flattened values.
1098 * @param array $returnProperities
1099 * An assoc array of fields that need to be returned, eg array( 'first_name', 'last_name').
6a488035 1100 *
a6c01b45
CW
1101 * @return object
1102 * an object of type referenced by daoName
6a488035 1103 */
00be9182 1104 public static function commonRetrieve($daoName, &$params, &$defaults, $returnProperities = NULL) {
353ffa53 1105 $object = new $daoName();
6a488035
TO
1106 $object->copyValues($params);
1107
1108 // return only specific fields if returnproperties are sent
1109 if (!empty($returnProperities)) {
1110 $object->selectAdd();
1111 $object->selectAdd(implode(',', $returnProperities));
1112 }
1113
1114 if ($object->find(TRUE)) {
1115 self::storeValues($object, $defaults);
1116 return $object;
1117 }
1118 return NULL;
1119 }
1120
1121 /**
1122 * Delete the object records that are associated with this contact
1123 *
6a0b768e
TO
1124 * @param string $daoName
1125 * Name of the dao object.
1126 * @param int $contactId
1127 * Id of the contact to delete.
6a488035
TO
1128 *
1129 * @return void
6a488035 1130 */
00be9182 1131 public static function deleteEntityContact($daoName, $contactId) {
353ffa53 1132 $object = new $daoName();
6a488035
TO
1133
1134 $object->entity_table = 'civicrm_contact';
1135 $object->entity_id = $contactId;
1136 $object->delete();
1137 }
1138
1139 /**
100fef9d 1140 * Execute a query
6a488035 1141 *
6a0b768e
TO
1142 * @param string $query
1143 * Query to be executed.
6a488035 1144 *
2a6da8d7
EM
1145 * @param array $params
1146 * @param bool $abort
1147 * @param null $daoName
1148 * @param bool $freeDAO
1149 * @param bool $i18nRewrite
1150 * @param bool $trapException
1151 *
5f1ebaec 1152 * @return CRM_Core_DAO|object
16b10e64 1153 * object that holds the results of the query
5f1ebaec
EM
1154 * NB - if this is defined as just returning a DAO phpstorm keeps pointing
1155 * out all the properties that are not part of the DAO
6a488035 1156 */
795492f3 1157 public static function &executeQuery(
6a488035 1158 $query,
353ffa53
TO
1159 $params = array(),
1160 $abort = TRUE,
1161 $daoName = NULL,
1162 $freeDAO = FALSE,
1163 $i18nRewrite = TRUE,
6a488035
TO
1164 $trapException = FALSE
1165 ) {
1166 $queryStr = self::composeQuery($query, $params, $abort);
6a488035
TO
1167
1168 if (!$daoName) {
1169 $dao = new CRM_Core_DAO();
1170 }
1171 else {
353ffa53 1172 $dao = new $daoName();
6a488035
TO
1173 }
1174
1175 if ($trapException) {
6a4257d4 1176 $errorScope = CRM_Core_TemporaryErrorScope::ignoreException();
6a488035
TO
1177 }
1178
1179 $result = $dao->query($queryStr, $i18nRewrite);
1180
6a488035
TO
1181 if (is_a($result, 'DB_Error')) {
1182 return $result;
1183 }
1184
1185 if ($freeDAO ||
1186 preg_match('/^(insert|update|delete|create|drop|replace)/i', $queryStr)
1187 ) {
b05b5a19 1188 // we typically do this for insert/update/delete statements OR if explicitly asked to
6a488035
TO
1189 // free the dao
1190 $dao->free();
1191 }
1192 return $dao;
1193 }
1194
1195 /**
100fef9d 1196 * Execute a query and get the single result
6a488035 1197 *
6a0b768e
TO
1198 * @param string $query
1199 * Query to be executed.
e869b07d
CW
1200 * @param array $params
1201 * @param bool $abort
1202 * @param bool $i18nRewrite
72b3a70c
CW
1203 * @return string|null
1204 * the result of the query if any
6a488035 1205 *
6a488035 1206 */
795492f3 1207 public static function &singleValueQuery(
f9f40af3 1208 $query,
353ffa53
TO
1209 $params = array(),
1210 $abort = TRUE,
6a488035
TO
1211 $i18nRewrite = TRUE
1212 ) {
1213 $queryStr = self::composeQuery($query, $params, $abort);
1214
1215 static $_dao = NULL;
1216
1217 if (!$_dao) {
1218 $_dao = new CRM_Core_DAO();
1219 }
1220
1221 $_dao->query($queryStr, $i18nRewrite);
1222
1223 $result = $_dao->getDatabaseResult();
1224 $ret = NULL;
1225 if ($result) {
1226 $row = $result->fetchRow();
1227 if ($row) {
1228 $ret = $row[0];
1229 }
1230 }
1231 $_dao->free();
1232 return $ret;
1233 }
1234
a0ee3941
EM
1235 /**
1236 * @param $query
c490a46a 1237 * @param array $params
a0ee3941
EM
1238 * @param bool $abort
1239 *
1240 * @return string
1241 * @throws Exception
1242 */
00be9182 1243 public static function composeQuery($query, &$params, $abort = TRUE) {
6a488035
TO
1244 $tr = array();
1245 foreach ($params as $key => $item) {
1246 if (is_numeric($key)) {
1247 if (CRM_Utils_Type::validate($item[0], $item[1]) !== NULL) {
1248 $item[0] = self::escapeString($item[0]);
1249 if ($item[1] == 'String' ||
1250 $item[1] == 'Memo' ||
1251 $item[1] == 'Link'
1252 ) {
887a4028
A
1253 // Support class constants stipulating wildcard characters and/or
1254 // non-quoting of strings. Also support legacy code which may be
1255 // passing in TRUE or 1 for $item[2], which used to indicate the
1256 // use of wildcard characters.
1257 if (!empty($item[2])) {
1258 if ($item[2] & CRM_Core_DAO::QUERY_FORMAT_WILDCARD || $item[2] === TRUE) {
1259 $item[0] = "'%{$item[0]}%'";
1260 }
1261 elseif (!($item[2] & CRM_Core_DAO::QUERY_FORMAT_NO_QUOTES)) {
1262 $item[0] = "'{$item[0]}'";
1263 }
6a488035
TO
1264 }
1265 else {
1266 $item[0] = "'{$item[0]}'";
1267 }
1268 }
1269
1270 if (($item[1] == 'Date' || $item[1] == 'Timestamp') &&
1271 strlen($item[0]) == 0
1272 ) {
1273 $item[0] = 'null';
1274 }
1275
1276 $tr['%' . $key] = $item[0];
1277 }
1278 elseif ($abort) {
1279 CRM_Core_Error::fatal("{$item[0]} is not of type {$item[1]}");
1280 }
1281 }
1282 }
1283
e2508c90 1284 return strtr($query, $tr);
6a488035
TO
1285 }
1286
a0ee3941
EM
1287 /**
1288 * @param null $ids
1289 */
00be9182 1290 public static function freeResult($ids = NULL) {
6a488035
TO
1291 global $_DB_DATAOBJECT;
1292
6a488035
TO
1293 if (!$ids) {
1294 if (!$_DB_DATAOBJECT ||
1295 !isset($_DB_DATAOBJECT['RESULTS'])
1296 ) {
1297 return;
1298 }
1299 $ids = array_keys($_DB_DATAOBJECT['RESULTS']);
1300 }
1301
1302 foreach ($ids as $id) {
1303 if (isset($_DB_DATAOBJECT['RESULTS'][$id])) {
1304 if (is_resource($_DB_DATAOBJECT['RESULTS'][$id]->result)) {
1305 mysql_free_result($_DB_DATAOBJECT['RESULTS'][$id]->result);
1306 }
1307 unset($_DB_DATAOBJECT['RESULTS'][$id]);
1308 }
1309
1310 if (isset($_DB_DATAOBJECT['RESULTFIELDS'][$id])) {
1311 unset($_DB_DATAOBJECT['RESULTFIELDS'][$id]);
1312 }
1313 }
1314 }
1315
1316 /**
dc195289 1317 * make a shallow copy of an object
6a488035
TO
1318 * and all the fields in the object
1319 *
6a0b768e
TO
1320 * @param string $daoName
1321 * Name of the dao.
1322 * @param array $criteria
1323 * Array of all the fields & values.
6a488035 1324 * on which basis to copy
6a0b768e
TO
1325 * @param array $newData
1326 * Array of all the fields & values.
6a488035 1327 * to be copied besides the other fields
6a0b768e
TO
1328 * @param string $fieldsFix
1329 * Array of fields that you want to prefix/suffix/replace.
1330 * @param string $blockCopyOfDependencies
1331 * Fields that you want to block from.
6a488035
TO
1332 * getting copied
1333 *
1334 *
72b3a70c
CW
1335 * @return CRM_Core_DAO
1336 * the newly created copy of the object
6a488035 1337 */
795492f3 1338 public static function &copyGeneric($daoName, $criteria, $newData = NULL, $fieldsFix = NULL, $blockCopyOfDependencies = NULL) {
353ffa53 1339 $object = new $daoName();
6a488035
TO
1340 if (!$newData) {
1341 $object->id = $criteria['id'];
1342 }
1343 else {
1344 foreach ($criteria as $key => $value) {
1345 $object->$key = $value;
1346 }
1347 }
1348
1349 $object->find();
1350 while ($object->fetch()) {
1351
1352 // all the objects except with $blockCopyOfDependencies set
1353 // be copied - addresses #CRM-1962
1354
1355 if ($blockCopyOfDependencies && $object->$blockCopyOfDependencies) {
1356 break;
1357 }
1358
353ffa53 1359 $newObject = new $daoName();
6a488035
TO
1360
1361 $fields = &$object->fields();
1362 if (!is_array($fieldsFix)) {
353ffa53
TO
1363 $fieldsToPrefix = array();
1364 $fieldsToSuffix = array();
6a488035
TO
1365 $fieldsToReplace = array();
1366 }
a7488080 1367 if (!empty($fieldsFix['prefix'])) {
6a488035
TO
1368 $fieldsToPrefix = $fieldsFix['prefix'];
1369 }
a7488080 1370 if (!empty($fieldsFix['suffix'])) {
6a488035
TO
1371 $fieldsToSuffix = $fieldsFix['suffix'];
1372 }
a7488080 1373 if (!empty($fieldsFix['replace'])) {
6a488035
TO
1374 $fieldsToReplace = $fieldsFix['replace'];
1375 }
1376
1377 foreach ($fields as $name => $value) {
1378 if ($name == 'id' || $value['name'] == 'id') {
1379 // copy everything but the id!
1380 continue;
1381 }
1382
1383 $dbName = $value['name'];
a1305c92 1384 $type = CRM_Utils_Type::typeToString($value['type']);
6a488035
TO
1385 $newObject->$dbName = $object->$dbName;
1386 if (isset($fieldsToPrefix[$dbName])) {
1387 $newObject->$dbName = $fieldsToPrefix[$dbName] . $newObject->$dbName;
1388 }
1389 if (isset($fieldsToSuffix[$dbName])) {
1390 $newObject->$dbName .= $fieldsToSuffix[$dbName];
1391 }
1392 if (isset($fieldsToReplace[$dbName])) {
1393 $newObject->$dbName = $fieldsToReplace[$dbName];
1394 }
1395
6c71f6c7 1396 if ($type == 'Timestamp' || $type == 'Date') {
6a488035
TO
1397 $newObject->$dbName = CRM_Utils_Date::isoToMysql($newObject->$dbName);
1398 }
1399
1400 if ($newData) {
1401 foreach ($newData as $k => $v) {
1402 $newObject->$k = $v;
1403 }
1404 }
1405 }
1406 $newObject->save();
1407 }
1408 return $newObject;
1409 }
1410
00be9182 1411 public static function cascadeUpdate($daoName, $fromId, $toId, $newData = array()) {
353ffa53 1412 $object = new $daoName();
62933949 1413 $object->id = $fromId;
1414
1415 if ($object->find(TRUE)) {
353ffa53 1416 $newObject = new $daoName();
62933949 1417 $newObject->id = $toId;
1418
1419 if ($newObject->find(TRUE)) {
1420 $fields = &$object->fields();
1421 foreach ($fields as $name => $value) {
1422 if ($name == 'id' || $value['name'] == 'id') {
1423 // copy everything but the id!
1424 continue;
1425 }
1426
1427 $colName = $value['name'];
1428 $newObject->$colName = $object->$colName;
1429
1430 if (substr($name, -5) == '_date' ||
1431 substr($name, -10) == '_date_time'
1432 ) {
1433 $newObject->$colName = CRM_Utils_Date::isoToMysql($newObject->$colName);
1434 }
1435 }
1436 foreach ($newData as $k => $v) {
1437 $newObject->$k = $v;
1438 }
1439 $newObject->save();
1440 return $newObject;
1441 }
1442 }
1443 return CRM_Core_DAO::$_nullObject;
1444 }
1445
6a488035
TO
1446 /**
1447 * Given the component id, compute the contact id
1448 * since its used for things like send email
b3342109
EM
1449 *
1450 * @param $componentIDs
100fef9d 1451 * @param string $tableName
b3342109
EM
1452 *
1453 * @return array
6a488035 1454 */
a5611c8e 1455 public static function &getContactIDsFromComponent(&$componentIDs, $tableName) {
6a488035
TO
1456 $contactIDs = array();
1457
1458 if (empty($componentIDs)) {
1459 return $contactIDs;
1460 }
1461
1462 $IDs = implode(',', $componentIDs);
1463 $query = "
1464SELECT contact_id
1465 FROM $tableName
1466 WHERE id IN ( $IDs )
1467";
1468
1469 $dao = CRM_Core_DAO::executeQuery($query);
1470 while ($dao->fetch()) {
1471 $contactIDs[] = $dao->contact_id;
1472 }
1473 return $contactIDs;
1474 }
1475
1476 /**
c490a46a 1477 * Fetch object based on array of properties
6a488035 1478 *
6a0b768e
TO
1479 * @param string $daoName
1480 * Name of the dao object.
dd244018 1481 * @param string $fieldIdName
100fef9d 1482 * @param int $fieldId
dd244018 1483 * @param $details
6a0b768e
TO
1484 * @param array $returnProperities
1485 * An assoc array of fields that need to be returned, eg array( 'first_name', 'last_name').
dd244018 1486 *
a6c01b45
CW
1487 * @return object
1488 * an object of type referenced by daoName
6a488035 1489 */
00be9182 1490 public static function commonRetrieveAll($daoName, $fieldIdName = 'id', $fieldId, &$details, $returnProperities = NULL) {
795492f3 1491 require_once str_replace('_', DIRECTORY_SEPARATOR, $daoName) . ".php";
353ffa53 1492 $object = new $daoName();
6a488035
TO
1493 $object->$fieldIdName = $fieldId;
1494
1495 // return only specific fields if returnproperties are sent
1496 if (!empty($returnProperities)) {
1497 $object->selectAdd();
1498 $object->selectAdd('id');
1499 $object->selectAdd(implode(',', $returnProperities));
1500 }
1501
1502 $object->find();
1503 while ($object->fetch()) {
1504 $defaults = array();
1505 self::storeValues($object, $defaults);
1506 $details[$object->id] = $defaults;
1507 }
1508
1509 return $details;
1510 }
1511
00be9182 1512 public static function dropAllTables() {
6a488035
TO
1513
1514 // first drop all the custom tables we've created
1515 CRM_Core_BAO_CustomGroup::dropAllTables();
1516
1517 // drop all multilingual views
1518 CRM_Core_I18n_Schema::dropAllViews();
1519
1520 CRM_Utils_File::sourceSQLFile(CIVICRM_DSN,
1521 dirname(__FILE__) . DIRECTORY_SEPARATOR .
1522 '..' . DIRECTORY_SEPARATOR .
1523 '..' . DIRECTORY_SEPARATOR .
1524 'sql' . DIRECTORY_SEPARATOR .
1525 'civicrm_drop.mysql'
1526 );
1527 }
1528
a0ee3941
EM
1529 /**
1530 * @param $string
1531 *
1532 * @return string
1533 */
00be9182 1534 public static function escapeString($string) {
6a488035
TO
1535 static $_dao = NULL;
1536
1537 if (!$_dao) {
74032946
TO
1538 // If this is an atypical case (e.g. preparing .sql files
1539 // before Civi has been installed), then we fallback to
1540 // DB-less escaping helper (mysql_real_escape_string).
1541 // Note: In typical usage, escapeString() will only
1542 // check one conditional ("if !$_dao") rather than
1543 // two conditionals ("if !defined(DSN)")
1544 if (!defined('CIVICRM_DSN')) {
1545 if (function_exists('mysql_real_escape_string')) {
1546 return mysql_real_escape_string($string);
0db6c3e1
TO
1547 }
1548 else {
74032946
TO
1549 throw new CRM_Core_Exception("Cannot generate SQL. \"mysql_real_escape_string\" is missing. Have you installed PHP \"mysql\" extension?");
1550 }
1551 }
1552
6a488035
TO
1553 $_dao = new CRM_Core_DAO();
1554 }
1555
1556 return $_dao->escape($string);
1557 }
1558
1559 /**
1560 * Escape a list of strings for use with "WHERE X IN (...)" queries.
1561 *
5a4f6742
CW
1562 * @param array $strings
1563 * @param string $default
1564 * the value to use if $strings has no elements.
a6c01b45
CW
1565 * @return string
1566 * eg "abc","def","ghi"
6a488035 1567 */
00be9182 1568 public static function escapeStrings($strings, $default = NULL) {
6a488035
TO
1569 static $_dao = NULL;
1570 if (!$_dao) {
1571 $_dao = new CRM_Core_DAO();
1572 }
1573
1574 if (empty($strings)) {
1575 return $default;
1576 }
1577
1578 $escapes = array_map(array($_dao, 'escape'), $strings);
1579 return '"' . implode('","', $escapes) . '"';
1580 }
1581
a0ee3941
EM
1582 /**
1583 * @param $string
1584 *
1585 * @return string
1586 */
00be9182 1587 public static function escapeWildCardString($string) {
6a488035
TO
1588 // CRM-9155
1589 // ensure we escape the single characters % and _ which are mysql wild
1590 // card characters and could come in via sortByCharacter
1591 // note that mysql does not escape these characters
1592 if ($string && in_array($string,
1593 array('%', '_', '%%', '_%')
353ffa53
TO
1594 )
1595 ) {
6a488035
TO
1596 return '\\' . $string;
1597 }
1598
1599 return self::escapeString($string);
1600 }
1601
92b83508
EM
1602 /**
1603 * Creates a test object, including any required objects it needs via recursion
b3342109
EM
1604 * createOnly: only create in database, do not store or return the objects (useful for perf testing)
1605 * ONLY USE FOR TESTING
1606 *
c490a46a 1607 * @param string $daoName
b3342109
EM
1608 * @param array $params
1609 * @param int $numObjects
1610 * @param bool $createOnly
1611 *
795492f3
TO
1612 * @return object|array|NULL
1613 * NULL if $createOnly. A single object if $numObjects==1. Otherwise, an array of multiple objects.
92b83508 1614 */
795492f3 1615 public static function createTestObject(
6a488035
TO
1616 $daoName,
1617 $params = array(),
1618 $numObjects = 1,
1619 $createOnly = FALSE
1620 ) {
b6262a4c
EM
1621 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
1622 // so we re-set here in case
1623 $config = CRM_Core_Config::singleton();
1624 $config->backtrace = TRUE;
1625
6a488035
TO
1626 static $counter = 0;
1627 CRM_Core_DAO::$_testEntitiesToSkip = array(
1628 'CRM_Core_DAO_Worldregion',
1629 'CRM_Core_DAO_StateProvince',
1630 'CRM_Core_DAO_Country',
1631 'CRM_Core_DAO_Domain',
795492f3 1632 'CRM_Financial_DAO_FinancialType',
353ffa53 1633 //because valid ones exist & we use pick them due to pseudoconstant can't reliably create & delete these
6a488035
TO
1634 );
1635
2069d1b7
TO
1636 // Prefer to instantiate BAO's instead of DAO's (when possible)
1637 // so that assignTestValue()/assignTestFK() can be overloaded.
1638 $baoName = str_replace('_DAO_', '_BAO_', $daoName);
1639 if (class_exists($baoName)) {
1640 $daoName = $baoName;
1641 }
1642
6a488035
TO
1643 for ($i = 0; $i < $numObjects; ++$i) {
1644
1645 ++$counter;
e79cd558 1646 /** @var CRM_Core_DAO $object */
ab9aa379 1647 $object = new $daoName();
6a488035 1648
353ffa53 1649 $fields = &$object->fields();
e1b64aab
TO
1650 foreach ($fields as $fieldName => $fieldDef) {
1651 $dbName = $fieldDef['name'];
f290b6ef 1652 $FKClassName = CRM_Utils_Array::value('FKClassName', $fieldDef);
e1b64aab 1653 $required = CRM_Utils_Array::value('required', $fieldDef);
f290b6ef 1654
6a488035
TO
1655 if (CRM_Utils_Array::value($dbName, $params) !== NULL && !is_array($params[$dbName])) {
1656 $object->$dbName = $params[$dbName];
1657 }
1658
1659 elseif ($dbName != 'id') {
f290b6ef 1660 if ($FKClassName != NULL) {
e79cd558 1661 $object->assignTestFK($fieldName, $fieldDef, $params);
6a488035 1662 continue;
0db6c3e1
TO
1663 }
1664 else {
f290b6ef 1665 $object->assignTestValue($fieldName, $fieldDef, $counter);
6a488035 1666 }
6a488035
TO
1667 }
1668 }
b3342109 1669
6a488035
TO
1670 $object->save();
1671
1672 if (!$createOnly) {
6a488035 1673 $objects[$i] = $object;
6a488035 1674 }
f290b6ef
TO
1675 else {
1676 unset($object);
1677 }
6a488035
TO
1678 }
1679
1680 if ($createOnly) {
795492f3 1681 return NULL;
6a488035 1682 }
f290b6ef
TO
1683 elseif ($numObjects == 1) {
1684 return $objects[0];
1685 }
1686 else {
1687 return $objects;
1688 }
6a488035
TO
1689 }
1690
92b83508 1691 /**
100fef9d 1692 * Deletes the this object plus any dependent objects that are associated with it
92b83508 1693 * ONLY USE FOR TESTING
b3342109 1694 *
c490a46a 1695 * @param string $daoName
b3342109 1696 * @param array $params
92b83508 1697 */
00be9182 1698 public static function deleteTestObjects($daoName, $params = array()) {
b6262a4c
EM
1699 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
1700 // so we re-set here in case
1701 $config = CRM_Core_Config::singleton();
1702 $config->backtrace = TRUE;
6a488035 1703
b6262a4c 1704 $object = new $daoName();
6a488035
TO
1705 $object->id = CRM_Utils_Array::value('id', $params);
1706
1707 $deletions = array(); // array(array(0 => $daoName, 1 => $daoParams))
1708 if ($object->find(TRUE)) {
1709
1710 $fields = &$object->fields();
1711 foreach ($fields as $name => $value) {
1712
1713 $dbName = $value['name'];
1714
1715 $FKClassName = CRM_Utils_Array::value('FKClassName', $value);
1716 $required = CRM_Utils_Array::value('required', $value);
1717 if ($FKClassName != NULL
1718 && $object->$dbName
1719 && !in_array($FKClassName, CRM_Core_DAO::$_testEntitiesToSkip)
806e9b71
EM
1720 && ($required || $dbName == 'contact_id')
1721 //I'm a bit stuck on this one - we might need to change the singleValueAlter so that the entities don't share a contact
1722 // to make this test process pass - line below makes pass for now
353ffa53
TO
1723 && $dbName != 'member_of_contact_id'
1724 ) {
6a488035
TO
1725 $deletions[] = array($FKClassName, array('id' => $object->$dbName)); // x
1726 }
1727 }
1728 }
1729
1730 $object->delete();
1731
1732 foreach ($deletions as $deletion) {
1733 CRM_Core_DAO::deleteTestObjects($deletion[0], $deletion[1]);
353ffa53 1734 }
6a488035
TO
1735 }
1736
64d24a64
EM
1737 /**
1738 * Set defaults when creating new entity
1739 * (don't call this set defaults as already in use with different signature in some places)
1740 *
c490a46a 1741 * @param array $params
64d24a64
EM
1742 * @param $defaults
1743 */
00be9182 1744 public static function setCreateDefaults(&$params, $defaults) {
64d24a64
EM
1745 if (isset($params['id'])) {
1746 return;
1747 }
1748 foreach ($defaults as $key => $value) {
1749 if (!array_key_exists($key, $params) || $params[$key] === NULL) {
1750 $params[$key] = $value;
1751 }
1752 }
1753 }
1754
a0ee3941
EM
1755 /**
1756 * @param string $prefix
1757 * @param bool $addRandomString
1758 * @param null $string
1759 *
1760 * @return string
1761 */
00be9182 1762 public static function createTempTableName($prefix = 'civicrm', $addRandomString = TRUE, $string = NULL) {
6a488035
TO
1763 $tableName = $prefix . "_temp";
1764
1765 if ($addRandomString) {
1766 if ($string) {
1767 $tableName .= "_" . $string;
1768 }
1769 else {
1770 $tableName .= "_" . md5(uniqid('', TRUE));
1771 }
1772 }
1773 return $tableName;
1774 }
1775
a0ee3941
EM
1776 /**
1777 * @param bool $view
1778 * @param bool $trigger
1779 *
1780 * @return bool
1781 */
00be9182 1782 public static function checkTriggerViewPermission($view = TRUE, $trigger = TRUE) {
6a488035
TO
1783 // test for create view and trigger permissions and if allowed, add the option to go multilingual
1784 // and logging
1785 // I'm not sure why we use the getStaticProperty for an error, rather than checking for DB_Error
6a4257d4 1786 $errorScope = CRM_Core_TemporaryErrorScope::ignoreException();
6a488035
TO
1787 $dao = new CRM_Core_DAO();
1788 if ($view) {
1789 $dao->query('CREATE OR REPLACE VIEW civicrm_domain_view AS SELECT * FROM civicrm_domain');
1790 if (PEAR::getStaticProperty('DB_DataObject', 'lastError')) {
6a488035
TO
1791 return FALSE;
1792 }
1793 }
1794
1795 if ($trigger) {
1796 $result = $dao->query('CREATE TRIGGER civicrm_domain_trigger BEFORE INSERT ON civicrm_domain FOR EACH ROW BEGIN END');
1797 if (PEAR::getStaticProperty('DB_DataObject', 'lastError') || is_a($result, 'DB_Error')) {
6a488035
TO
1798 if ($view) {
1799 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1800 }
1801 return FALSE;
1802 }
1803
1804 $dao->query('DROP TRIGGER IF EXISTS civicrm_domain_trigger');
1805 if (PEAR::getStaticProperty('DB_DataObject', 'lastError')) {
6a488035
TO
1806 if ($view) {
1807 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1808 }
1809 return FALSE;
1810 }
1811 }
1812
1813 if ($view) {
1814 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1815 if (PEAR::getStaticProperty('DB_DataObject', 'lastError')) {
6a488035
TO
1816 return FALSE;
1817 }
1818 }
6a488035
TO
1819
1820 return TRUE;
1821 }
1822
a0ee3941
EM
1823 /**
1824 * @param null $message
1825 * @param bool $printDAO
1826 */
00be9182 1827 public static function debugPrint($message = NULL, $printDAO = TRUE) {
6a488035
TO
1828 CRM_Utils_System::xMemory("{$message}: ");
1829
1830 if ($printDAO) {
1831 global $_DB_DATAOBJECT;
1832 $q = array();
1833 foreach (array_keys($_DB_DATAOBJECT['RESULTS']) as $id) {
1834 $q[] = $_DB_DATAOBJECT['RESULTS'][$id]->query;
1835 }
1836 CRM_Core_Error::debug('_DB_DATAOBJECT', $q);
1837 }
1838 }
1839
77b97be7
EM
1840 /**
1841 * Build a list of triggers via hook and add them to (err, reconcile them
1842 * with) the database.
1843 *
5a4f6742
CW
1844 * @param string $tableName
1845 * the specific table requiring a rebuild; or NULL to rebuild all tables.
77b97be7
EM
1846 * @param bool $force
1847 *
1848 * @see CRM-9716
1849 */
00be9182 1850 public static function triggerRebuild($tableName = NULL, $force = FALSE) {
6a488035
TO
1851 $info = array();
1852
795492f3 1853 $logging = new CRM_Logging_Schema();
e53944ef 1854 $logging->triggerInfo($info, $tableName, $force);
6a488035
TO
1855
1856 CRM_Core_I18n_Schema::triggerInfo($info, $tableName);
1857 CRM_Contact_BAO_Contact::triggerInfo($info, $tableName);
1858
1859 CRM_Utils_Hook::triggerInfo($info, $tableName);
1860
1861 // drop all existing triggers on all tables
1862 $logging->dropTriggers($tableName);
1863
1864 // now create the set of new triggers
0590c631 1865 self::createTriggers($info, $tableName);
6a488035
TO
1866 }
1867
aca2de91
CW
1868 /**
1869 * Because sql functions are sometimes lost, esp during db migration, we check here to avoid numerous support requests
1870 * @see http://issues.civicrm.org/jira/browse/CRM-13822
1871 * TODO: Alternative solutions might be
1872 * * Stop using functions and find another way to strip numeric characters from phones
1873 * * Give better error messages (currently a missing fn fatals with "unknown error")
1874 */
00be9182 1875 public static function checkSqlFunctionsExist() {
aca2de91
CW
1876 if (!self::$_checkedSqlFunctionsExist) {
1877 self::$_checkedSqlFunctionsExist = TRUE;
1878 $dao = CRM_Core_DAO::executeQuery("SHOW function status WHERE db = database() AND name = 'civicrm_strip_non_numeric'");
1879 if (!$dao->fetch()) {
1880 self::triggerRebuild();
1881 }
1882 }
1883 }
1884
6a488035
TO
1885 /**
1886 * Wrapper function to drop triggers
1887 *
5a4f6742
CW
1888 * @param string $tableName
1889 * the specific table requiring a rebuild; or NULL to rebuild all tables.
6a488035 1890 */
00be9182 1891 public static function dropTriggers($tableName = NULL) {
6a488035
TO
1892 $info = array();
1893
795492f3 1894 $logging = new CRM_Logging_Schema();
6a488035
TO
1895 $logging->triggerInfo($info, $tableName);
1896
1897 // drop all existing triggers on all tables
1898 $logging->dropTriggers($tableName);
1899 }
1900
1901 /**
5a4f6742
CW
1902 * @param array $info
1903 * per hook_civicrm_triggerInfo.
1904 * @param string $onlyTableName
1905 * the specific table requiring a rebuild; or NULL to rebuild all tables.
6a488035 1906 */
00be9182 1907 public static function createTriggers(&$info, $onlyTableName = NULL) {
6a488035
TO
1908 // Validate info array, should probably raise errors?
1909 if (is_array($info) == FALSE) {
1910 return;
1911 }
1912
1913 $triggers = array();
1914
1915 // now enumerate the tables and the events and collect the same set in a different format
1916 foreach ($info as $value) {
1917
1918 // clean the incoming data, skip malformed entries
1919 // TODO: malformed entries should raise errors or get logged.
1920 if (isset($value['table']) == FALSE ||
1921 isset($value['event']) == FALSE ||
1922 isset($value['when']) == FALSE ||
1923 isset($value['sql']) == FALSE
1924 ) {
1925 continue;
1926 }
1927
1928 if (is_string($value['table']) == TRUE) {
1929 $tables = array($value['table']);
1930 }
1931 else {
1932 $tables = $value['table'];
1933 }
1934
1935 if (is_string($value['event']) == TRUE) {
1936 $events = array(strtolower($value['event']));
1937 }
1938 else {
1939 $events = array_map('strtolower', $value['event']);
1940 }
1941
1942 $whenName = strtolower($value['when']);
1943
1944 foreach ($tables as $tableName) {
1945 if (!isset($triggers[$tableName])) {
1946 $triggers[$tableName] = array();
1947 }
1948
1949 foreach ($events as $eventName) {
1950 $template_params = array('{tableName}', '{eventName}');
1951 $template_values = array($tableName, $eventName);
1952
1953 $sql = str_replace($template_params,
1954 $template_values,
1955 $value['sql']
1956 );
1957 $variables = str_replace($template_params,
1958 $template_values,
1959 CRM_Utils_Array::value('variables', $value)
1960 );
1961
1962 if (!isset($triggers[$tableName][$eventName])) {
1963 $triggers[$tableName][$eventName] = array();
1964 }
1965
1966 if (!isset($triggers[$tableName][$eventName][$whenName])) {
1967 // We're leaving out cursors, conditions, and handlers for now
1968 // they are kind of dangerous in this context anyway
1969 // better off putting them in stored procedures
1970 $triggers[$tableName][$eventName][$whenName] = array(
1971 'variables' => array(),
1972 'sql' => array(),
1973 );
1974 }
1975
1976 if ($variables) {
1977 $triggers[$tableName][$eventName][$whenName]['variables'][] = $variables;
1978 }
1979
1980 $triggers[$tableName][$eventName][$whenName]['sql'][] = $sql;
1981 }
1982 }
1983 }
1984
1985 // now spit out the sql
1986 foreach ($triggers as $tableName => $tables) {
1987 if ($onlyTableName != NULL && $onlyTableName != $tableName) {
1988 continue;
1989 }
1990 foreach ($tables as $eventName => $events) {
1991 foreach ($events as $whenName => $parts) {
353ffa53
TO
1992 $varString = implode("\n", $parts['variables']);
1993 $sqlString = implode("\n", $parts['sql']);
1994 $validName = CRM_Core_DAO::shortenSQLName($tableName, 48, TRUE);
6842bb53 1995 $triggerName = "{$validName}_{$whenName}_{$eventName}";
353ffa53 1996 $triggerSQL = "CREATE TRIGGER $triggerName $whenName $eventName ON $tableName FOR EACH ROW BEGIN $varString $sqlString END";
6a488035
TO
1997
1998 CRM_Core_DAO::executeQuery("DROP TRIGGER IF EXISTS $triggerName");
1999 CRM_Core_DAO::executeQuery(
2000 $triggerSQL,
2001 array(),
2002 TRUE,
2003 NULL,
2004 FALSE,
2005 FALSE
2006 );
2007 }
2008 }
2009 }
2010 }
2011
ffcef054
TO
2012 /**
2013 * Given a list of fields, create a list of references.
2014 *
6a0b768e
TO
2015 * @param string $className
2016 * BAO/DAO class name.
ffcef054
TO
2017 * @return array<CRM_Core_Reference_Interface>
2018 */
00be9182 2019 public static function createReferenceColumns($className) {
ffcef054
TO
2020 $result = array();
2021 $fields = $className::fields();
2022 foreach ($fields as $field) {
2023 if (isset($field['pseudoconstant'], $field['pseudoconstant']['optionGroupName'])) {
2024 $result[] = new CRM_Core_Reference_OptionValue(
2025 $className::getTableName(),
2026 $field['name'],
2027 'civicrm_option_value',
2028 CRM_Utils_Array::value('keyColumn', $field['pseudoconstant'], 'value'),
2029 $field['pseudoconstant']['optionGroupName']
2030 );
2031 }
2032 }
2033 return $result;
2034 }
2035
6a488035 2036 /**
71e5aa5c
ARW
2037 * Find all records which refer to this entity.
2038 *
a6c01b45 2039 * @return array
16b10e64 2040 * Array of objects referencing this
71e5aa5c 2041 */
00be9182 2042 public function findReferences() {
71e5aa5c
ARW
2043 $links = self::getReferencesToTable(static::getTableName());
2044
2045 $occurrences = array();
2046 foreach ($links as $refSpec) {
11626cf1 2047 /** @var $refSpec CRM_Core_Reference_Interface */
31bed28c 2048 $daoName = CRM_Core_DAO_AllCoreTables::getClassForTable($refSpec->getReferenceTable());
de49f39c 2049 $result = $refSpec->findReferences($this);
ffcef054
TO
2050 if ($result) {
2051 while ($result->fetch()) {
2052 $obj = new $daoName();
2053 $obj->id = $result->id;
2054 $occurrences[] = $obj;
2055 }
71e5aa5c
ARW
2056 }
2057 }
2058
2059 return $occurrences;
2060 }
2061
a0ee3941 2062 /**
a6c01b45
CW
2063 * @return array
2064 * each item has keys:
16b10e64
CW
2065 * - name: string
2066 * - type: string
2067 * - count: int
2068 * - table: string|null SQL table name
2069 * - key: string|null SQL column name
a0ee3941 2070 */
00be9182 2071 public function getReferenceCounts() {
1256c139
TO
2072 $links = self::getReferencesToTable(static::getTableName());
2073
2074 $counts = array();
2075 foreach ($links as $refSpec) {
2076 /** @var $refSpec CRM_Core_Reference_Interface */
2077 $count = $refSpec->getReferenceCount($this);
2078 if ($count['count'] != 0) {
2079 $counts[] = $count;
2080 }
2081 }
2082
91dee34b
TO
2083 foreach (CRM_Core_Component::getEnabledComponents() as $component) {
2084 /** @var $component CRM_Core_Component_Info */
2085 $counts = array_merge($counts, $component->getReferenceCounts($this));
2086 }
2087 CRM_Utils_Hook::referenceCounts($this, $counts);
2088
1256c139
TO
2089 return $counts;
2090 }
2091
71e5aa5c
ARW
2092 /**
2093 * List all tables which have hard foreign keys to this table.
6a488035 2094 *
71e5aa5c
ARW
2095 * For now, this returns a description of every entity_id/entity_table
2096 * reference.
2097 * TODO: filter dynamic entity references on the $tableName, based on
2098 * schema metadata in dynamicForeignKey which enumerates a restricted
2099 * set of possible entity_table's.
6a488035 2100 *
6a0b768e
TO
2101 * @param string $tableName
2102 * Table referred to.
6a488035 2103 *
a6c01b45
CW
2104 * @return array
2105 * structure of table and column, listing every table with a
16b10e64 2106 * foreign key reference to $tableName, and the column where the key appears.
6a488035 2107 */
00be9182 2108 public static function getReferencesToTable($tableName) {
71e5aa5c 2109 $refsFound = array();
31bed28c 2110 foreach (CRM_Core_DAO_AllCoreTables::getClasses() as $daoClassName) {
71e5aa5c
ARW
2111 $links = $daoClassName::getReferenceColumns();
2112 $daoTableName = $daoClassName::getTableName();
2113
2114 foreach ($links as $refSpec) {
11626cf1
TO
2115 /** @var $refSpec CRM_Core_Reference_Interface */
2116 if ($refSpec->matchesTargetTable($tableName)) {
71e5aa5c
ARW
2117 $refsFound[] = $refSpec;
2118 }
6a488035
TO
2119 }
2120 }
71e5aa5c 2121 return $refsFound;
6a488035 2122 }
032c9d10
TO
2123
2124 /**
2125 * Lookup the value of a MySQL global configuration variable.
2126 *
6a0b768e
TO
2127 * @param string $name
2128 * E.g. "thread_stack".
032c9d10
TO
2129 * @param mixed $default
2130 * @return mixed
2131 */
2132 public static function getGlobalSetting($name, $default = NULL) {
2133 // Alternatively, SELECT @@GLOBAL.thread_stack, but
2134 // that has been reported to fail under MySQL 5.0 for OS X
2135 $escapedName = self::escapeString($name);
2136 $dao = CRM_Core_DAO::executeQuery("SHOW VARIABLES LIKE '$escapedName'");
2137 if ($dao->fetch()) {
2138 return $dao->Value;
ab00f69d
DL
2139 }
2140 else {
032c9d10
TO
2141 return $default;
2142 }
2143 }
dc86f881
CW
2144
2145 /**
2146 * Get options for the called BAO object's field.
2147 * This function can be overridden by each BAO to add more logic related to context.
2158332a 2148 * The overriding function will generally call the lower-level CRM_Core_PseudoConstant::get
dc86f881 2149 *
2a3f958d 2150 * @param string $fieldName
6a0b768e 2151 * @param string $context
795492f3 2152 * @see CRM_Core_DAO::buildOptionsContext
6a0b768e 2153 * @param array $props
16b10e64 2154 * whatever is known about this bao object.
9a1b1948 2155 *
795492f3 2156 * @return array|bool
dc86f881
CW
2157 */
2158 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
2158332a 2159 // If a given bao does not override this function
dc86f881 2160 $baoName = get_called_class();
786ad6e1 2161 return CRM_Core_PseudoConstant::get($baoName, $fieldName, array(), $context);
dc86f881 2162 }
786ad6e1 2163
2a3f958d
CW
2164 /**
2165 * Populate option labels for this object's fields.
2166 *
2167 * @throws exception if called directly on the base class
2168 */
2169 public function getOptionLabels() {
2170 $fields = $this->fields();
2171 if ($fields === NULL) {
795492f3 2172 throw new Exception('Cannot call getOptionLabels on CRM_Core_DAO');
2a3f958d
CW
2173 }
2174 foreach ($fields as $field) {
2175 $name = CRM_Utils_Array::value('name', $field);
2176 if ($name && isset($this->$name)) {
a8c23526 2177 $label = CRM_Core_PseudoConstant::getLabel(get_class($this), $name, $this->$name);
2a3f958d
CW
2178 if ($label !== FALSE) {
2179 // Append 'label' onto the field name
2180 $labelName = $name . '_label';
2181 $this->$labelName = $label;
2182 }
2183 }
2184 }
2185 }
2186
786ad6e1
CW
2187 /**
2188 * Provides documentation and validation for the buildOptions $context param
2189 *
6a0b768e 2190 * @param string $context
77b97be7
EM
2191 *
2192 * @throws Exception
2193 * @return array
786ad6e1
CW
2194 */
2195 public static function buildOptionsContext($context = NULL) {
2196 $contexts = array(
2197 'get' => "All options are returned, even if they are disabled. Labels are translated.",
2198 'create' => "Options are filtered appropriately for the object being created/updated. Labels are translated.",
2199 'search' => "Searchable options are returned. Labels are translated.",
2200 'validate' => "All options are returned, even if they are disabled. Machine names are used in place of labels.",
2201 );
2202 // Validation: enforce uniformity of this param
2203 if ($context !== NULL && !isset($contexts[$context])) {
395d8dc6 2204 throw new Exception("'$context' is not a valid context for buildOptions.");
786ad6e1
CW
2205 }
2206 return $contexts;
2207 }
2208
5fafc9b0 2209 /**
100fef9d 2210 * @param string $fieldName
5fafc9b0
CW
2211 * @return bool|array
2212 */
00be9182 2213 public function getFieldSpec($fieldName) {
5fafc9b0
CW
2214 $fields = $this->fields();
2215 $fieldKeys = $this->fieldKeys();
2216
2217 // Support "unique names" as well as sql names
2218 $fieldKey = $fieldName;
2219 if (empty($fields[$fieldKey])) {
2220 $fieldKey = CRM_Utils_Array::value($fieldName, $fieldKeys);
2221 }
2222 // If neither worked then this field doesn't exist. Return false.
2223 if (empty($fields[$fieldKey])) {
2224 return FALSE;
2225 }
2226 return $fields[$fieldKey];
2227 }
2228
faf8c53b 2229 /**
2230 * SQL version of api function to assign filters to the DAO based on the syntax
2231 * $field => array('IN' => array(4,6,9))
2232 * OR
2233 * $field => array('LIKE' => array('%me%))
2234 * etc
2235 *
6a0b768e
TO
2236 * @param string $fieldName
2237 * Name of fields.
5a4f6742
CW
2238 * @param array $filter
2239 * filter to be applied indexed by operator.
2240 * @param string $type
2241 * type of field (not actually used - nor in api @todo ).
2242 * @param string $alias
2243 * alternative field name ('as') @todo- not actually used.
6a0b768e
TO
2244 * @param bool $returnSanitisedArray
2245 * Return a sanitised array instead of a clause.
16b10e64 2246 * this is primarily so we can add filters @ the api level to the Query object based fields
9a1b1948
EM
2247 *
2248 * @throws Exception
c490a46a 2249 *
a75c13cc 2250 * @todo a better solution would be for the query object to apply these filters based on the
78c0bfc0 2251 * api supported format (but we don't want to risk breakage in alpha stage & query class is scary
9a1b1948 2252 * @todo @time of writing only IN & NOT IN are supported for the array style syntax (as test is
06f48f96 2253 * required to extend further & it may be the comments per above should be implemented. It may be
2254 * preferable to not double-banger the return context next refactor of this - but keeping the attention
2255 * in one place has some advantages as we try to extend this format
2256 *
72b3a70c
CW
2257 * @return NULL|string|array
2258 * a string is returned if $returnSanitisedArray is not set, otherwise and Array or NULL
06f48f96 2259 * depending on whether it is supported as yet
9a1b1948 2260 */
3f2d6002 2261 public static function createSQLFilter($fieldName, $filter, $type, $alias = NULL, $returnSanitisedArray = FALSE) {
faf8c53b 2262 // http://issues.civicrm.org/jira/browse/CRM-9150 - stick with 'simple' operators for now
2263 // support for other syntaxes is discussed in ticket but being put off for now
faf8c53b 2264 foreach ($filter as $operator => $criteria) {
e4176358 2265 if (in_array($operator, self::acceptedSQLOperators())) {
faf8c53b 2266 switch ($operator) {
2267 // unary operators
faf8c53b 2268 case 'IS NULL':
2269 case 'IS NOT NULL':
c490a46a 2270 if (!$returnSanitisedArray) {
78c0bfc0 2271 return (sprintf('%s %s', $fieldName, $operator));
2272 }
c490a46a 2273 else {
a75c13cc 2274 return (sprintf('%s %s ', $fieldName, $operator));
06f48f96 2275 }
faf8c53b 2276 break;
2277
2278 // ternary operators
2279 case 'BETWEEN':
2280 case 'NOT BETWEEN':
2281 if (empty($criteria[0]) || empty($criteria[1])) {
395d8dc6 2282 throw new Exception("invalid criteria for $operator");
faf8c53b 2283 }
c490a46a 2284 if (!$returnSanitisedArray) {
78c0bfc0 2285 return (sprintf('%s ' . $operator . ' "%s" AND "%s"', $fieldName, CRM_Core_DAO::escapeString($criteria[0]), CRM_Core_DAO::escapeString($criteria[1])));
2286 }
c490a46a 2287 else {
06f48f96 2288 return NULL; // not yet implemented (tests required to implement)
2289 }
faf8c53b 2290 break;
2291
2292 // n-ary operators
2293 case 'IN':
2294 case 'NOT IN':
2295 if (empty($criteria)) {
395d8dc6 2296 throw new Exception("invalid criteria for $operator");
faf8c53b 2297 }
2298 $escapedCriteria = array_map(array(
2299 'CRM_Core_DAO',
795492f3 2300 'escapeString',
faf8c53b 2301 ), $criteria);
c490a46a 2302 if (!$returnSanitisedArray) {
78c0bfc0 2303 return (sprintf('%s %s ("%s")', $fieldName, $operator, implode('", "', $escapedCriteria)));
2304 }
2305 return $escapedCriteria;
faf8c53b 2306
2307 // binary operators
6a488035 2308
faf8c53b 2309 default:
c490a46a 2310 if (!$returnSanitisedArray) {
353ffa53 2311 return (sprintf('%s %s "%s"', $fieldName, $operator, CRM_Core_DAO::escapeString($criteria)));
78c0bfc0 2312 }
c490a46a 2313 else {
06f48f96 2314 return NULL; // not yet implemented (tests required to implement)
2315 }
faf8c53b 2316 }
2317 }
2318 }
2319 }
6842bb53 2320
e4176358
CW
2321 /**
2322 * @see http://issues.civicrm.org/jira/browse/CRM-9150
2323 * support for other syntaxes is discussed in ticket but being put off for now
2324 * @return array
2325 */
2326 public static function acceptedSQLOperators() {
353ffa53
TO
2327 return array(
2328 '=',
2329 '<=',
2330 '>=',
2331 '>',
2332 '<',
2333 'LIKE',
2334 "<>",
2335 "!=",
2336 "NOT LIKE",
2337 'IN',
2338 'NOT IN',
2339 'BETWEEN',
2340 'NOT BETWEEN',
2341 'IS NOT NULL',
795492f3 2342 'IS NULL',
353ffa53 2343 );
e4176358
CW
2344 }
2345
6842bb53
DL
2346 /**
2347 * SQL has a limit of 64 characters on various names:
2348 * table name, trigger name, column name ...
2349 *
2350 * For custom groups and fields we generated names from user entered input
2351 * which can be longer than this length, this function helps with creating
2352 * strings that meet various criteria.
2353 *
6a0b768e
TO
2354 * @param string $string
2355 * The string to be shortened.
2356 * @param int $length
2357 * The max length of the string.
9a1b1948
EM
2358 *
2359 * @param bool $makeRandom
2360 *
2361 * @return string
6842bb53
DL
2362 */
2363 public static function shortenSQLName($string, $length = 60, $makeRandom = FALSE) {
2364 // early return for strings that meet the requirements
2365 if (strlen($string) <= $length) {
2366 return $string;
2367 }
2368
2369 // easy return for calls that dont need a randomized uniq string
c490a46a 2370 if (!$makeRandom) {
6842bb53
DL
2371 return substr($string, 0, $length);
2372 }
2373
2374 // the string is longer than the length and we need a uniq string
2375 // for the same tablename we need the same uniq string everytime
2376 // hence we use md5 on the string, which is not random
a8dd306e
DL
2377 // we'll append 8 characters to the end of the tableName
2378 $md5string = substr(md5($string), 0, 8);
2379 return substr($string, 0, $length - 8) . "_{$md5string}";
6842bb53
DL
2380 }
2381
a0ee3941 2382 /**
c490a46a 2383 * @param array $params
a0ee3941 2384 */
353ffa53
TO
2385 public function setApiFilter(&$params) {
2386 }
6e1bb60c 2387
232624b1 2388}