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