3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
13 * Base Database Access Object class.
15 * All DAO classes should inherit from this class.
18 * @copyright CiviCRM LLC https://civicrm.org/licensing
21 if (!defined('DB_DSN_MODE')) {
22 define('DB_DSN_MODE', 'auto');
25 require_once 'PEAR.php';
26 require_once 'DB/DataObject.php';
28 require_once 'CRM/Core/I18n.php';
33 class CRM_Core_DAO
extends DB_DataObject
{
36 * How many times has this instance been cloned.
40 protected $resultCopies = 0;
46 public static $_nullObject = NULL;
49 * Icon associated with this entity.
53 public static $_icon = NULL;
56 * Field to show when displaying a record.
60 public static $_labelField = NULL;
66 public static $_nullArray = [];
68 public static $_dbColumnValueCache = NULL;
69 const NOT_NULL
= 1, IS_NULL
= 2,
71 VALUE_SEPARATOR
= "\ 1",
72 BULK_INSERT_COUNT
= 200,
73 BULK_INSERT_HIGH_COUNT
= 200,
74 QUERY_FORMAT_WILDCARD
= 1,
75 QUERY_FORMAT_NO_QUOTES
= 2,
78 * Serialized string separated by and bookended with VALUE_SEPARATOR
80 SERIALIZE_SEPARATOR_BOOKEND
= 1,
82 * @deprecated format separated by VALUE_SEPARATOR
84 SERIALIZE_SEPARATOR_TRIMMED
= 2,
86 * Recommended serialization format
90 * @deprecated format using php serialize()
94 * Comma separated string, no quotes, no spaces
99 * Define entities that shouldn't be created or deleted when creating/ deleting
100 * test objects - this prevents world regions, countries etc from being added / deleted
103 public static $_testEntitiesToSkip = [];
105 * The factory class for this application.
108 public static $_factory = NULL;
110 public static $_checkedSqlFunctionsExist = FALSE;
113 * https://issues.civicrm.org/jira/browse/CRM-17748
114 * internal variable for DAO to hold per-query settings
117 protected $_options = [];
122 * @return \CRM_Core_DAO
124 public function __construct() {
126 $this->__table
= $this->getTableName();
130 * Returns localized title of this entity.
134 public static function getEntityTitle() {
135 $className = static::class;
136 CRM_Core_Error
::deprecatedWarning("$className needs to be regenerated. Missing getEntityTitle method.");
137 return CRM_Core_DAO_AllCoreTables
::getBriefName($className);
140 public function __clone() {
141 if (!empty($this->_DB_resultid
)) {
142 $this->resultCopies++
;
149 public function __destruct() {
150 if ($this->resultCopies
=== 0) {
153 $this->resultCopies
--;
157 * Returns the name of this table
161 public static function getTableName() {
162 return self
::getLocaleTableName(static::$_tableName ??
NULL);
166 * Returns if this table needs to be logged
170 public function getLog() {
171 return static::$_log ??
FALSE;
175 * Initialize the DAO object.
178 * The database connection string.
180 public static function init($dsn) {
181 Civi
::$statics[__CLASS__
]['init'] = 1;
182 $options = &PEAR
::getStaticProperty('DB_DataObject', 'options');
183 $dsn = CRM_Utils_SQL
::autoSwitchDSN($dsn);
184 $options['database'] = $dsn;
185 $options['quote_identifiers'] = TRUE;
186 if (CRM_Utils_SQL
::isSSLDSN($dsn)) {
187 // There are two different options arrays.
188 $other_options = &PEAR
::getStaticProperty('DB', 'options');
189 $other_options['ssl'] = TRUE;
191 if (defined('CIVICRM_DAO_DEBUG')) {
192 self
::DebugLevel(CIVICRM_DAO_DEBUG
);
194 $factory = new CRM_Contact_DAO_Factory();
195 CRM_Core_DAO
::setFactory($factory);
196 CRM_Core_DAO
::executeQuery('SET NAMES utf8mb4');
197 CRM_Core_DAO
::executeQuery('SET @uniqueID = %1', [1 => [CRM_Utils_Request
::id(), 'String']]);
203 public static function getConnection() {
204 global $_DB_DATAOBJECT;
205 $dao = new CRM_Core_DAO();
206 return $_DB_DATAOBJECT['CONNECTIONS'][$dao->_database_dsn_md5
];
210 * Disables usage of the ONLY_FULL_GROUP_BY Mode if necessary
212 public static function disableFullGroupByMode() {
213 $currentModes = CRM_Utils_SQL
::getSqlModes();
214 if (in_array('ONLY_FULL_GROUP_BY', $currentModes) && CRM_Utils_SQL
::isGroupByModeInDefault()) {
215 $key = array_search('ONLY_FULL_GROUP_BY', $currentModes);
216 unset($currentModes[$key]);
217 CRM_Core_DAO
::executeQuery("SET SESSION sql_mode = %1", [1 => [implode(',', $currentModes), 'String']]);
222 * Re-enables ONLY_FULL_GROUP_BY sql_mode as necessary..
224 public static function reenableFullGroupByMode() {
225 $currentModes = CRM_Utils_SQL
::getSqlModes();
226 if (!in_array('ONLY_FULL_GROUP_BY', $currentModes) && CRM_Utils_SQL
::isGroupByModeInDefault()) {
227 $currentModes[] = 'ONLY_FULL_GROUP_BY';
228 CRM_Core_DAO
::executeQuery("SET SESSION sql_mode = %1", [1 => [implode(',', $currentModes), 'String']]);
233 * @param string $fieldName
235 * @param array $params
237 protected function assignTestFK($fieldName, $fieldDef, $params) {
238 $required = $fieldDef['required'] ??
NULL;
239 $FKClassName = $fieldDef['FKClassName'] ??
NULL;
240 $dbName = $fieldDef['name'];
241 $daoName = str_replace('_BAO_', '_DAO_', get_class($this));
243 // skip the FK if it is not required
244 // if it's contact id we should create even if not required
245 // we'll have a go @ fetching first though
246 // we WILL create campaigns though for so tests with a campaign pseudoconstant will complete
247 if ($FKClassName === 'CRM_Campaign_DAO_Campaign' && $daoName != $FKClassName) {
250 if (!$required && $dbName != 'contact_id') {
251 $fkDAO = new $FKClassName();
252 if ($fkDAO->find(TRUE)) {
253 $this->$dbName = $fkDAO->id
;
257 elseif (in_array($FKClassName, CRM_Core_DAO
::$_testEntitiesToSkip)) {
258 $depObject = new $FKClassName();
259 $depObject->find(TRUE);
260 $this->$dbName = $depObject->id
;
262 elseif ($daoName == 'CRM_Member_DAO_MembershipType' && $fieldName == 'member_of_contact_id') {
263 // FIXME: the fields() metadata is not specific enough
264 $depObject = CRM_Core_DAO
::createTestObject($FKClassName, ['contact_type' => 'Organization']);
265 $this->$dbName = $depObject->id
;
268 //if it is required we need to generate the dependency object first
269 $depObject = CRM_Core_DAO
::createTestObject($FKClassName, CRM_Utils_Array
::value($dbName, $params, 1));
270 $this->$dbName = $depObject->id
;
275 * Generate and assign an arbitrary value to a field of a test object.
277 * @param string $fieldName
278 * @param array $fieldDef
279 * @param int $counter
280 * The globally-unique ID of the test object.
282 * @throws \CRM_Core_Exception
284 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
285 $dbName = $fieldDef['name'];
286 $daoName = get_class($this);
289 if (!$handled && $dbName == 'contact_sub_type') {
290 //coming up with a rule to set this is too complex let's not set it
294 // Pick an option value if needed
295 if (!$handled && $fieldDef['type'] !== CRM_Utils_Type
::T_BOOLEAN
) {
296 $options = $daoName::buildOptions($dbName, 'create');
298 $this->$dbName = key($options);
304 switch ($fieldDef['type']) {
305 case CRM_Utils_Type
::T_INT
:
306 case CRM_Utils_Type
::T_FLOAT
:
307 case CRM_Utils_Type
::T_MONEY
:
308 if (isset($fieldDef['precision'])) {
309 // $object->$dbName = CRM_Utils_Number::createRandomDecimal($value['precision']);
310 $this->$dbName = CRM_Utils_Number
::createTruncatedDecimal($counter, $fieldDef['precision']);
313 $this->$dbName = $counter;
317 case CRM_Utils_Type
::T_BOOLEAN
:
318 if (isset($fieldDef['default'])) {
319 $this->$dbName = $fieldDef['default'];
321 elseif ($fieldDef['name'] == 'is_deleted' ||
$fieldDef['name'] == 'is_test') {
329 case CRM_Utils_Type
::T_DATE
:
330 case CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
:
331 $this->$dbName = '19700101';
332 if ($dbName == 'end_date') {
333 // put this in the future
334 $this->$dbName = '20200101';
338 case CRM_Utils_Type
::T_TIMESTAMP
:
339 $this->$dbName = '19700201000000';
342 case CRM_Utils_Type
::T_TIME
:
343 throw new CRM_Core_Exception('T_TIME shouldn\'t be used.');
345 case CRM_Utils_Type
::T_CCNUM
:
346 $this->$dbName = '4111 1111 1111 1111';
349 case CRM_Utils_Type
::T_URL
:
350 $this->$dbName = 'http://www.civicrm.org';
353 case CRM_Utils_Type
::T_STRING
:
354 case CRM_Utils_Type
::T_BLOB
:
355 case CRM_Utils_Type
::T_MEDIUMBLOB
:
356 case CRM_Utils_Type
::T_TEXT
:
357 case CRM_Utils_Type
::T_LONGTEXT
:
358 case CRM_Utils_Type
::T_EMAIL
:
360 // WAS: if (isset($value['enumValues'])) {
361 // TODO: see if this works with all pseudoconstants
362 if (isset($fieldDef['pseudoconstant'], $fieldDef['pseudoconstant']['callback'])) {
363 if (isset($fieldDef['default'])) {
364 $this->$dbName = $fieldDef['default'];
367 $options = CRM_Core_PseudoConstant
::get($daoName, $fieldName);
368 if (is_array($options)) {
369 $this->$dbName = $options[0];
372 $defaultValues = explode(',', $options);
373 $this->$dbName = $defaultValues[0];
378 $this->$dbName = $dbName . '_' . $counter;
379 $maxlength = $fieldDef['maxlength'] ??
NULL;
380 if ($maxlength > 0 && strlen($this->$dbName) > $maxlength) {
381 $this->$dbName = substr($this->$dbName, 0, $fieldDef['maxlength']);
389 * Reset the DAO object.
391 * DAO is kinda crappy in that there is an unwritten rule of one query per DAO.
393 * We attempt to get around this crappy restriction by resetting some of DAO's internal fields. Use this with caution
395 public function reset() {
397 foreach (array_keys($this->table()) as $field) {
398 unset($this->$field);
402 * reset the various DB_DAO structures manually
411 * @param string $tableName
415 public static function getLocaleTableName($tableName) {
418 $tables = CRM_Core_I18n_Schema
::schemaStructureTables();
419 if (in_array($tableName, $tables)) {
420 return $tableName . $dbLocale;
427 * Execute a query by the current DAO, localizing it along the way (if needed).
429 * @param string $query
430 * The SQL query for execution.
431 * @param bool $i18nRewrite
432 * Whether to rewrite the query.
435 * the current DAO object after the query execution
437 public function query($query, $i18nRewrite = TRUE) {
438 // rewrite queries that should use $dbLocale-based views for multi-language installs
439 global $dbLocale, $_DB_DATAOBJECT;
441 if (empty($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5
])) {
442 // Will force connection to be populated per CRM-20541.
446 $conn = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5
];
447 $orig_options = $conn->options
;
448 $this->_setDBOptions($this->_options
);
450 if ($i18nRewrite and $dbLocale) {
451 $query = CRM_Core_I18n_Schema
::rewriteQuery($query);
454 $ret = parent
::query($query);
456 $this->_setDBOptions($orig_options);
461 * Static function to set the factory instance for this class.
463 * @param object $factory
464 * The factory application object.
466 public static function setFactory(&$factory) {
467 self
::$_factory = &$factory;
471 * Factory method to instantiate a new object from a table name.
473 * @param string $table
474 * @return \DataObject|\PEAR_Error
476 public function factory($table = '') {
477 if (!isset(self
::$_factory)) {
478 return parent
::factory($table);
481 return self
::$_factory->create($table);
485 * Initialization for all DAO objects. Since we access DB_DO programatically
486 * we need to set the links manually.
488 public function initialize() {
490 if (empty(Civi
::$statics[__CLASS__
]['init'])) {
491 // CRM_Core_DAO::init() must be called before CRM_Core_DAO->initialize().
492 // This occurs very early in bootstrap - error handlers may not be wired up.
493 echo "Inconsistent system initialization sequence. Premature access of (" . get_class($this) . ")";
494 CRM_Utils_System
::civiExit();
499 * Defines the default key as 'id'.
503 public function keys() {
512 * Tells DB_DataObject which keys use autoincrement.
513 * 'id' is autoincrementing by default.
518 public function sequenceKey() {
519 static $sequenceKeys;
520 if (!isset($sequenceKeys)) {
521 $sequenceKeys = ['id', TRUE];
523 return $sequenceKeys;
527 * Returns list of FK relationships.
530 * @return CRM_Core_Reference_Basic[]
532 public static function getReferenceColumns() {
537 * Returns all the column names of this table.
542 public static function &fields() {
548 * Returns all usable fields, indexed by name.
550 * This function differs from fields() in that it indexes by name rather than unique_name.
552 * It excludes fields not added yet by pending upgrades.
553 * This avoids problems with trying to SELECT a field that exists in code but has not yet been added to the db.
555 * @param bool $checkPermissions
556 * Filter by field permissions.
559 public static function getSupportedFields($checkPermissions = FALSE) {
560 $fields = array_column((array) static::fields(), NULL, 'name');
562 // Exclude fields yet not added by pending upgrades
563 $dbVer = \CRM_Core_BAO_Domain
::version();
564 $daoExt = defined(static::class . '::EXT') ?
constant(static::class . '::EXT') : NULL;
565 if ($fields && $daoExt === 'civicrm' && version_compare($dbVer, \CRM_Utils_System
::version()) < 0) {
566 $fields = array_filter($fields, function($field) use ($dbVer) {
567 $add = $field['add'] ??
'1.0.0';
568 if (substr_count($add, '.') < 2) {
571 return version_compare($dbVer, $add, '>=');
575 // Exclude fields the user does not have permission for
576 if ($checkPermissions) {
577 $fields = array_filter($fields, function($field) {
578 return empty($field['permission']) || CRM_Core_Permission
::check($field['permission']);
586 * Get/set an associative array of table columns
591 public function table() {
592 $fields = $this->fields();
596 foreach ($fields as $name => $value) {
597 $table[$value['name']] = $value['type'];
598 if (!empty($value['required'])) {
599 $table[$value['name']] +
= self
::DB_DAO_NOTNULL
;
612 * @return CRM_Core_DAO
614 public function save($hook = TRUE) {
616 if (!empty($this->id
)) {
618 $preEvent = new \Civi\Core\DAO\Event\
PreUpdate($this);
619 $preEvent->eventID
= $eventID;
620 \Civi
::dispatcher()->dispatch("civi.dao.preUpdate", $preEvent);
623 $result = $this->update();
626 $event = new \Civi\Core\DAO\Event\
PostUpdate($this, $result);
627 $event->eventID
= $eventID;
628 \Civi
::dispatcher()->dispatch("civi.dao.postUpdate", $event);
630 $this->clearDbColumnValueCache();
634 $preEvent = new \Civi\Core\DAO\Event\
PreUpdate($this);
635 $preEvent->eventID
= $eventID;
636 \Civi
::dispatcher()->dispatch("civi.dao.preInsert", $preEvent);
639 $result = $this->insert();
642 $event = new \Civi\Core\DAO\Event\
PostUpdate($this, $result);
643 $event->eventID
= $eventID;
644 \Civi
::dispatcher()->dispatch("civi.dao.postInsert", $event);
650 CRM_Utils_Hook
::postSave($this);
657 * Deletes items from table which match current objects variables.
659 * Returns the true on success
663 * Designed to be extended
665 * $object = new mytable();
667 * echo $object->delete(); // builds a conditon
669 * $object = new mytable();
670 * $object->whereAdd('age > 12');
672 * $object->orderBy('age DESC');
673 * $object->delete(true); // dont use object vars, use the conditions, limit and order.
675 * @param bool $useWhere (optional) If DB_DATAOBJECT_WHEREADD_ONLY is passed in then
676 * we will build the condition only using the whereAdd's. Default is to
677 * build the condition only using the object parameters.
679 * * @return mixed Int (No. of rows affected) on success, false on failure, 0 on no data affected
681 public function delete($useWhere = FALSE) {
682 $preEvent = new \Civi\Core\DAO\Event\
PreDelete($this);
683 \Civi
::dispatcher()->dispatch("civi.dao.preDelete", $preEvent);
685 $result = parent
::delete($useWhere);
687 $event = new \Civi\Core\DAO\Event\
PostDelete($this, $result);
688 \Civi
::dispatcher()->dispatch("civi.dao.postDelete", $event);
691 $this->clearDbColumnValueCache();
697 * @param bool $created
699 public function log($created = FALSE) {
702 if (!$this->getLog()) {
707 $session = CRM_Core_Session
::singleton();
708 $cid = $session->get('userID');
711 // return is we dont have handle to FK
716 $dao = new CRM_Core_DAO_Log();
717 $dao->entity_table
= $this->getTableName();
718 $dao->entity_id
= $this->id
;
719 $dao->modified_id
= $cid;
720 $dao->modified_date
= date("YmdHis");
725 * Given an associative array of name/value pairs, extract all the values
726 * that belong to this object and initialize the object with said values
728 * @param array $params
729 * Array of name/value pairs to save.
732 * Did we copy all null values into the object
734 public function copyValues($params) {
736 foreach ($this->fields() as $uniqueName => $field) {
737 $dbName = $field['name'];
738 if (array_key_exists($dbName, $params)) {
739 $value = $params[$dbName];
742 elseif (array_key_exists($uniqueName, $params)) {
743 $value = $params[$uniqueName];
750 // if there is no value then make the variable NULL
753 $this->$dbName = 'null';
755 elseif (is_array($value) && !empty($field['serialize'])) {
756 $this->$dbName = CRM_Core_DAO
::serializeField($value, $field['serialize']);
760 $maxLength = $field['maxlength'] ??
NULL;
761 if (!is_array($value) && $maxLength && mb_strlen($value) > $maxLength && empty($field['pseudoconstant'])) {
762 // No ts() since this is a sysadmin-y string not seen by general users.
763 Civi
::log()->warning('A string for field {dbName} has been truncated. The original string was {value}.', ['dbName' => $dbName, 'value' => $value]);
764 // The string is too long - what to do what to do? Well losing data is generally bad so let's truncate
765 $value = CRM_Utils_String
::ellipsify($value, $maxLength);
767 $this->$dbName = $value;
776 * Store all the values from this object in an associative array
777 * this is a destructive store, calling function is responsible
778 * for keeping sanity of id's.
780 * @param object $object
781 * The object that we are extracting data from.
782 * @param array $values
783 * (reference ) associative array of name/value pairs.
785 public static function storeValues(&$object, &$values) {
786 $fields = $object->fields();
787 foreach ($fields as $name => $value) {
788 $dbName = $value['name'];
789 if (isset($object->$dbName) && $object->$dbName !== 'null') {
790 $values[$dbName] = $object->$dbName;
791 if ($name != $dbName) {
792 $values[$name] = $object->$dbName;
799 * Create an attribute for this specific field. We only do this for strings and text
801 * @param array $field
802 * The field under task.
805 * the attributes for the object
807 public static function makeAttribute($field) {
809 if (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_STRING
) {
810 $maxLength = $field['maxlength'] ??
NULL;
811 $size = $field['size'] ??
NULL;
812 if ($maxLength ||
$size) {
815 $attributes['maxlength'] = $maxLength;
818 $attributes['size'] = $size;
823 elseif (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_TEXT
) {
824 $rows = $field['rows'] ??
NULL;
828 $cols = $field['cols'] ??
NULL;
834 $attributes['rows'] = $rows;
835 $attributes['cols'] = $cols;
838 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
) {
839 $attributes['size'] = 6;
840 $attributes['maxlength'] = 14;
848 * Get the size and maxLength attributes for this text field.
849 * (or for all text fields) in the DAO object.
851 * @param string $class
853 * @param string $fieldName
854 * Field that i'm interested in or null if.
855 * you want the attributes for all DAO text fields
858 * assoc array of name => attribute pairs
860 public static function getAttribute($class, $fieldName = NULL) {
861 $object = new $class();
862 $fields = $object->fields();
863 if ($fieldName != NULL) {
864 $field = $fields[$fieldName] ??
NULL;
865 return self
::makeAttribute($field);
869 foreach ($fields as $name => $field) {
870 $attribute = self
::makeAttribute($field);
872 $attributes[$name] = $attribute;
876 if (!empty($attributes)) {
884 * Create or update a record from supplied params.
886 * If 'id' is supplied, an existing record will be updated
887 * Otherwise a new record will be created.
889 * @param array $record
892 * @throws \CRM_Core_Exception
894 public static function writeRecord(array $record): CRM_Core_DAO
{
895 $hook = empty($record['id']) ?
'create' : 'edit';
896 $className = CRM_Core_DAO_AllCoreTables
::getCanonicalClassName(static::class);
897 if ($className === 'CRM_Core_DAO') {
898 throw new CRM_Core_Exception('Function writeRecord must be called on a subclass of CRM_Core_DAO');
900 $entityName = CRM_Core_DAO_AllCoreTables
::getBriefName($className);
902 \CRM_Utils_Hook
::pre($hook, $entityName, $record['id'] ??
NULL, $record);
903 $instance = new $className();
904 $instance->copyValues($record);
906 \CRM_Utils_Hook
::post($hook, $entityName, $instance->id
, $instance);
912 * Delete a record from supplied params.
914 * @param array $record
916 * @return CRM_Core_DAO
917 * @throws CRM_Core_Exception
919 public static function deleteRecord(array $record) {
920 $className = CRM_Core_DAO_AllCoreTables
::getCanonicalClassName(static::class);
921 if ($className === 'CRM_Core_DAO') {
922 throw new CRM_Core_Exception('Function deleteRecord must be called on a subclass of CRM_Core_DAO');
924 $entityName = CRM_Core_DAO_AllCoreTables
::getBriefName($className);
925 if (empty($record['id'])) {
926 throw new CRM_Core_Exception("Cannot delete {$entityName} with no id.");
929 CRM_Utils_Hook
::pre('delete', $entityName, $record['id'], $record);
930 $instance = new $className();
931 $instance->id
= $record['id'];
932 if (!$instance->delete()) {
933 throw new CRM_Core_Exception("Could not delete {$entityName} id {$record['id']}");
935 CRM_Utils_Hook
::post('delete', $entityName, $record['id'], $instance);
941 * Check if there is a record with the same name in the db.
943 * @param string $value
944 * The value of the field we are checking.
945 * @param string $daoName
946 * The dao object name.
947 * @param string $daoID
948 * The id of the object being updated. u can change your name.
949 * as long as there is no conflict
950 * @param string $fieldName
951 * The name of the field in the DAO.
953 * @param string $domainID
954 * The id of the domain. Object exists only for the given domain.
957 * true if object exists
959 public static function objectExists($value, $daoName, $daoID, $fieldName = 'name', $domainID = NULL) {
960 $object = new $daoName();
961 $object->$fieldName = $value;
963 $object->domain_id
= $domainID;
966 if ($object->find(TRUE)) {
967 return $daoID && $object->id
== $daoID;
975 * Check if there is a given column in a specific table.
978 * @see CRM_Core_BAO_SchemaHandler::checkIfFieldExists
980 * @param string $tableName
981 * @param string $columnName
982 * @param bool $i18nRewrite
983 * Whether to rewrite the query on multilingual setups.
986 * true if exists, else false
988 public static function checkFieldExists($tableName, $columnName, $i18nRewrite = TRUE) {
989 CRM_Core_Error
::deprecatedFunctionWarning('CRM_Core_BAO_SchemaHandler::checkIfFieldExists');
990 return CRM_Core_BAO_SchemaHandler
::checkIfFieldExists($tableName, $columnName, $i18nRewrite);
994 * Scans all the tables using a slow query and table name.
998 public static function getTableNames() {
999 $dao = CRM_Core_DAO
::executeQuery(
1001 FROM information_schema.TABLES
1002 WHERE TABLE_SCHEMA = '" . CRM_Core_DAO
::getDatabaseName() . "'
1003 AND TABLE_NAME LIKE 'civicrm_%'
1004 AND TABLE_NAME NOT LIKE 'civicrm_import_job_%'
1005 AND TABLE_NAME NOT LIKE '%_temp%'
1008 while ($dao->fetch()) {
1009 $values[] = $dao->TABLE_NAME
;
1015 * @param int $maxTablesToCheck
1019 public static function isDBMyISAM($maxTablesToCheck = 10) {
1020 return CRM_Core_DAO
::singleValueQuery(
1022 FROM information_schema.TABLES
1023 WHERE ENGINE = 'MyISAM'
1024 AND TABLE_SCHEMA = '" . CRM_Core_DAO
::getDatabaseName() . "'
1025 AND TABLE_NAME LIKE 'civicrm_%'
1026 AND TABLE_NAME NOT LIKE 'civicrm_import_job_%'
1027 AND TABLE_NAME NOT LIKE '%_temp%'
1028 AND TABLE_NAME NOT LIKE 'civicrm_tmp_%'
1033 * Get the name of the CiviCRM database.
1037 public static function getDatabaseName() {
1038 $daoObj = new CRM_Core_DAO();
1039 return $daoObj->database();
1043 * Checks if a constraint exists for a specified table.
1045 * @param string $tableName
1046 * @param string $constraint
1049 * true if constraint exists, false otherwise
1051 * @throws \CRM_Core_Exception
1053 public static function checkConstraintExists($tableName, $constraint) {
1056 if (!array_key_exists($tableName, $show)) {
1057 $query = "SHOW CREATE TABLE $tableName";
1058 $dao = CRM_Core_DAO
::executeQuery($query, [], TRUE, NULL, FALSE, FALSE);
1060 if (!$dao->fetch()) {
1061 throw new CRM_Core_Exception('query failed');
1064 $show[$tableName] = $dao->Create_Table
;
1067 return (bool) preg_match("/\b$constraint\b/i", $show[$tableName]);
1071 * Checks if CONSTRAINT keyword exists for a specified table.
1073 * @param array $tables
1075 * @throws CRM_Core_Exception
1078 * true if CONSTRAINT keyword exists, false otherwise
1080 public static function schemaRequiresRebuilding($tables = ["civicrm_contact"]) {
1082 foreach ($tables as $tableName) {
1083 if (!array_key_exists($tableName, $show)) {
1084 $query = "SHOW CREATE TABLE $tableName";
1085 $dao = CRM_Core_DAO
::executeQuery($query, [], TRUE, NULL, FALSE, FALSE);
1087 if (!$dao->fetch()) {
1088 throw new CRM_Core_Exception('Show create table failed.');
1091 $show[$tableName] = $dao->Create_Table
;
1094 $result = (bool) preg_match("/\bCONSTRAINT\b\s/i", $show[$tableName]);
1095 if ($result == TRUE) {
1106 * Checks if the FK constraint name is in the format 'FK_tableName_columnName'
1107 * for a specified column of a table.
1109 * @param string $tableName
1110 * @param string $columnName
1113 * true if in format, false otherwise
1115 * @throws \CRM_Core_Exception
1117 public static function checkFKConstraintInFormat($tableName, $columnName) {
1120 if (!array_key_exists($tableName, $show)) {
1121 $query = "SHOW CREATE TABLE $tableName";
1122 $dao = CRM_Core_DAO
::executeQuery($query);
1124 if (!$dao->fetch()) {
1125 throw new CRM_Core_Exception('query failed');
1128 $show[$tableName] = $dao->Create_Table
;
1130 $constraint = "`FK_{$tableName}_{$columnName}`";
1131 $pattern = "/\bCONSTRAINT\b\s+%s\s+\bFOREIGN\s+KEY\b\s/i";
1132 return (bool) preg_match(sprintf($pattern, $constraint), $show[$tableName]);
1136 * Check whether a specific column in a specific table has always the same value.
1138 * @param string $tableName
1139 * @param string $columnName
1140 * @param string $columnValue
1143 * true if the value is always $columnValue, false otherwise
1145 public static function checkFieldHasAlwaysValue($tableName, $columnName, $columnValue) {
1146 $query = "SELECT * FROM $tableName WHERE $columnName != '$columnValue'";
1147 $dao = CRM_Core_DAO
::executeQuery($query);
1148 $result = $dao->fetch() ?
FALSE : TRUE;
1153 * Check whether a specific column in a specific table is always NULL.
1155 * @param string $tableName
1156 * @param string $columnName
1159 * true if if the value is always NULL, false otherwise
1161 public static function checkFieldIsAlwaysNull($tableName, $columnName) {
1162 $query = "SELECT * FROM $tableName WHERE $columnName IS NOT NULL";
1163 $dao = CRM_Core_DAO
::executeQuery($query);
1164 $result = $dao->fetch() ?
FALSE : TRUE;
1169 * Checks if this DAO's table ought to exist.
1171 * If there are pending DB updates, this function compares the CiviCRM version of the table to the current schema version.
1174 * @throws CRM_Core_Exception
1176 public static function tableHasBeenAdded() {
1177 if (CRM_Utils_System
::version() === CRM_Core_BAO_Domain
::version()) {
1180 $daoExt = defined(static::class . '::EXT') ?
constant(static::class . '::EXT') : NULL;
1181 $daoVersion = defined(static::class . '::TABLE_ADDED') ?
constant(static::class . '::TABLE_ADDED') : '1.0';
1182 return !($daoExt === 'civicrm' && version_compare(CRM_Core_BAO_Domain
::version(), $daoVersion, '<'));
1186 * Check if there is a given table in the database.
1188 * @param string $tableName
1191 * true if exists, else false
1193 public static function checkTableExists($tableName) {
1198 $params = [1 => [$tableName, 'String']];
1200 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1201 return (bool) $dao->fetch();
1205 * Check if a given table has data.
1207 * @param string $tableName
1209 * TRUE if $tableName has at least one record.
1211 public static function checkTableHasData($tableName) {
1212 $c = CRM_Core_DAO
::singleValueQuery(sprintf('SELECT count(*) c FROM `%s`', $tableName));
1221 public function checkVersion($version) {
1222 CRM_Core_Error
::deprecatedFunctionWarning('CRM_Core_BAO_Domain::version');
1223 $dbVersion = CRM_Core_BAO_Domain
::version();
1224 return trim($version) == trim($dbVersion);
1228 * Find a DAO object for the given ID and return it.
1231 * Id of the DAO object being searched for.
1233 * @return CRM_Core_DAO
1234 * Object of the type of the class that called this function.
1238 public static function findById($id) {
1239 $object = new static();
1241 if (!$object->find(TRUE)) {
1242 throw new Exception("Unable to find a " . get_called_class() . " with id {$id}.");
1248 * Returns all results as array-encoded records.
1252 public function fetchAll($k = FALSE, $v = FALSE, $method = FALSE) {
1254 while ($this->fetch()) {
1255 $result[] = $this->toArray();
1261 * Return the results as PHP generator.
1263 * @param string $type
1264 * Whether the generator yields 'dao' objects or 'array's.
1266 public function fetchGenerator($type = 'dao') {
1267 while ($this->fetch()) {
1274 yield
$this->toArray();
1278 throw new \
RuntimeException("Invalid record type ($type)");
1284 * Returns a singular value.
1286 * @return mixed|NULL
1288 public function fetchValue() {
1289 $result = $this->getDatabaseResult();
1290 $row = $result->fetchRow();
1300 * Get all the result records as mapping between columns.
1302 * @param string $keyColumn
1304 * @param string $valueColumn
1307 * Ex: ["foo" => "The Foo Bar", "baz" => "The Baz Qux"]
1309 public function fetchMap($keyColumn, $valueColumn) {
1311 while ($this->fetch()) {
1312 $result[$this->{$keyColumn}] = $this->{$valueColumn};
1318 * Given a DAO name, a column name and a column value, find the record and GET the value of another column in that record
1320 * @param string $daoName
1321 * Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact).
1322 * @param int $searchValue
1323 * Value of the column you want to search by.
1324 * @param string $returnColumn
1325 * Name of the column you want to GET the value of.
1326 * @param string $searchColumn
1327 * Name of the column you want to search by.
1328 * @param bool $force
1329 * Skip use of the cache.
1331 * @return string|int|null
1332 * Value of $returnColumn in the retrieved record
1334 * @throws \CRM_Core_Exception
1336 public static function getFieldValue($daoName, $searchValue, $returnColumn = 'name', $searchColumn = 'id', $force = FALSE) {
1338 empty($searchValue) ||
1339 trim(strtolower($searchValue)) == 'null'
1341 // adding this here since developers forget to check for an id
1342 // or for the 'null' (which is a bad DAO kludge)
1343 // and hence we get the first value in the db
1344 throw new CRM_Core_Exception('getFieldValue failed');
1347 self
::$_dbColumnValueCache = self
::$_dbColumnValueCache ??
[];
1349 while (strpos($daoName, '_BAO_') !== FALSE) {
1350 $daoName = get_parent_class($daoName);
1354 empty(self
::$_dbColumnValueCache[$daoName][$searchColumn][$searchValue]) ||
1355 !array_key_exists($returnColumn, self
::$_dbColumnValueCache[$daoName][$searchColumn][$searchValue])
1357 $object = new $daoName();
1358 $object->$searchColumn = $searchValue;
1359 $object->selectAdd();
1360 $object->selectAdd($returnColumn);
1363 if ($object->find(TRUE)) {
1364 $result = $object->$returnColumn;
1367 self
::$_dbColumnValueCache[$daoName][$searchColumn][$searchValue][$returnColumn] = $result;
1369 return self
::$_dbColumnValueCache[$daoName][$searchColumn][$searchValue][$returnColumn];
1373 * Given a DAO name, a column name and a column value, find the record and SET the value of another column in that record
1375 * @param string $daoName
1376 * Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact).
1377 * @param int $searchValue
1378 * Value of the column you want to search by.
1379 * @param string $setColumn
1380 * Name of the column you want to SET the value of.
1381 * @param string $setValue
1382 * SET the setColumn to this value.
1383 * @param string $searchColumn
1384 * Name of the column you want to search by.
1387 * true if we found and updated the object, else false
1389 public static function setFieldValue($daoName, $searchValue, $setColumn, $setValue, $searchColumn = 'id') {
1390 $object = new $daoName();
1391 $object->selectAdd();
1392 $object->selectAdd("$searchColumn, $setColumn");
1393 $object->$searchColumn = $searchValue;
1395 if ($object->find(TRUE)) {
1396 $object->$setColumn = $setValue;
1397 if ($object->save()) {
1408 * @param array|object $sort either array or CRM_Utils_Sort
1409 * @param string $default
1410 * Default sort value.
1414 public static function getSortString($sort, $default = NULL) {
1415 // check if sort is of type CRM_Utils_Sort
1416 if (is_a($sort, 'CRM_Utils_Sort')) {
1417 return $sort->orderBy();
1422 // is it an array specified as $field => $sortDirection ?
1424 foreach ($sort as $k => $v) {
1425 $sortString .= "$k $v,";
1427 return rtrim($sortString, ',');
1433 * Fetch object based on array of properties.
1435 * @param string $daoName
1436 * Name of the dao object.
1437 * @param array $params
1438 * (reference ) an assoc array of name/value pairs.
1439 * @param array $defaults
1440 * (reference ) an assoc array to hold the flattened values.
1441 * @param array $returnProperities
1442 * An assoc array of fields that need to be returned, eg array( 'first_name', 'last_name').
1445 * an object of type referenced by daoName
1447 public static function commonRetrieve($daoName, &$params, &$defaults, $returnProperities = NULL) {
1448 $object = new $daoName();
1449 $object->copyValues($params);
1451 // return only specific fields if returnproperties are sent
1452 if (!empty($returnProperities)) {
1453 $object->selectAdd();
1454 $object->selectAdd(implode(',', $returnProperities));
1457 if ($object->find(TRUE)) {
1458 self
::storeValues($object, $defaults);
1465 * Delete the object records that are associated with this contact.
1467 * @param string $daoName
1468 * Name of the dao object.
1469 * @param int $contactId
1470 * Id of the contact to delete.
1472 public static function deleteEntityContact($daoName, $contactId) {
1473 $object = new $daoName();
1475 $object->entity_table
= 'civicrm_contact';
1476 $object->entity_id
= $contactId;
1481 * Execute an unbuffered query.
1483 * This is a wrapper around new functionality exposed with CRM-17748.
1485 * @param string $query query to be executed
1487 * @param array $params
1488 * @param bool $abort
1489 * @param null $daoName
1490 * @param bool $freeDAO
1491 * @param bool $i18nRewrite
1492 * @param bool $trapException
1494 * @return CRM_Core_DAO
1495 * Object that points to an unbuffered result set
1497 public static function executeUnbufferedQuery(
1503 $i18nRewrite = TRUE,
1504 $trapException = FALSE
1507 return self
::executeQuery(
1515 ['result_buffering' => 0]
1522 * @param string $query
1523 * Query to be executed.
1525 * @param array $params
1526 * @param bool $abort
1527 * @param null $daoName
1528 * @param bool $freeDAO
1529 * @param bool $i18nRewrite
1530 * @param bool $trapException
1531 * @param array $options
1533 * @return CRM_Core_DAO|object
1534 * object that holds the results of the query
1535 * NB - if this is defined as just returning a DAO phpstorm keeps pointing
1536 * out all the properties that are not part of the DAO
1538 public static function &executeQuery(
1544 $i18nRewrite = TRUE,
1545 $trapException = FALSE,
1548 $queryStr = self
::composeQuery($query, $params, $abort);
1551 $dao = new CRM_Core_DAO();
1554 $dao = new $daoName();
1557 if ($trapException) {
1558 CRM_Core_Error
::deprecatedFunctionWarning('calling functions should handle exceptions');
1559 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
1562 if ($dao->isValidOption($options)) {
1563 $dao->setOptions($options);
1566 $result = $dao->query($queryStr, $i18nRewrite);
1568 // since it is unbuffered, ($dao->N==0) is true. This blocks the standard fetch() mechanism.
1569 if (CRM_Utils_Array
::value('result_buffering', $options) === 0) {
1573 if (is_a($result, 'DB_Error')) {
1574 CRM_Core_Error
::deprecatedFunctionWarning('calling functions should handle exceptions');
1582 * Wrapper to validate internal DAO options before passing to DB_mysql/DB_Common level
1584 * @param array $options
1587 * Provided options are valid
1589 public function isValidOption($options) {
1598 if (empty($options)) {
1602 foreach (array_keys($options) as $option) {
1603 if (!in_array($option, $validOptions)) {
1613 * Execute a query and get the single result.
1615 * @param string $query
1616 * Query to be executed.
1617 * @param array $params
1618 * @param bool $abort
1619 * @param bool $i18nRewrite
1620 * @return string|null
1621 * the result of the query if any
1624 public static function &singleValueQuery(
1630 $queryStr = self
::composeQuery($query, $params, $abort);
1632 static $_dao = NULL;
1635 $_dao = new CRM_Core_DAO();
1638 $_dao->query($queryStr, $i18nRewrite);
1640 $result = $_dao->getDatabaseResult();
1643 $row = $result->fetchRow();
1653 * Compose the query by merging the parameters into it.
1655 * @param string $query
1656 * @param array $params
1657 * @param bool $abort
1660 * @throws CRM_Core_Exception
1662 public static function composeQuery($query, $params = [], $abort = TRUE) {
1664 foreach ($params as $key => $item) {
1665 if (is_numeric($key)) {
1666 if (CRM_Utils_Type
::validate($item[0], $item[1]) !== NULL) {
1667 $item[0] = self
::escapeString($item[0]);
1668 if ($item[1] == 'String' ||
1669 $item[1] == 'Memo' ||
1672 // Support class constants stipulating wildcard characters and/or
1673 // non-quoting of strings. Also support legacy code which may be
1674 // passing in TRUE or 1 for $item[2], which used to indicate the
1675 // use of wildcard characters.
1676 if (!empty($item[2])) {
1677 if ($item[2] & CRM_Core_DAO
::QUERY_FORMAT_WILDCARD ||
$item[2] === TRUE) {
1678 $item[0] = "'%{$item[0]}%'";
1680 elseif (!($item[2] & CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
)) {
1681 $item[0] = "'{$item[0]}'";
1685 $item[0] = "'{$item[0]}'";
1689 if (($item[1] == 'Date' ||
$item[1] == 'Timestamp') &&
1690 strlen($item[0]) == 0
1695 $tr['%' . $key] = $item[0];
1698 throw new CRM_Core_Exception("{$item[0]} is not of type {$item[1]}");
1703 return strtr($query, $tr);
1709 public static function freeResult($ids = NULL) {
1710 global $_DB_DATAOBJECT;
1713 if (!$_DB_DATAOBJECT ||
1714 !isset($_DB_DATAOBJECT['RESULTS'])
1718 $ids = array_keys($_DB_DATAOBJECT['RESULTS']);
1721 foreach ($ids as $id) {
1722 if (isset($_DB_DATAOBJECT['RESULTS'][$id])) {
1723 $_DB_DATAOBJECT['RESULTS'][$id]->free();
1724 unset($_DB_DATAOBJECT['RESULTS'][$id]);
1727 if (isset($_DB_DATAOBJECT['RESULTFIELDS'][$id])) {
1728 unset($_DB_DATAOBJECT['RESULTFIELDS'][$id]);
1734 * Make a shallow copy of an object and all the fields in the object.
1736 * @param string $daoName
1738 * @param array $criteria
1739 * Array of all the fields & values.
1740 * on which basis to copy
1741 * @param array $newData
1742 * Array of all the fields & values.
1743 * to be copied besides the other fields
1744 * @param string $fieldsFix
1745 * Array of fields that you want to prefix/suffix/replace.
1746 * @param string $blockCopyOfDependencies
1747 * Fields that you want to block from.
1749 * @param bool $blockCopyofCustomValues
1750 * Case when you don't want to copy the custom values set in a
1751 * template as it will override/ignore the submitted custom values
1753 * @return CRM_Core_DAO|bool
1754 * the newly created copy of the object. False if none created.
1756 public static function copyGeneric($daoName, $criteria, $newData = NULL, $fieldsFix = NULL, $blockCopyOfDependencies = NULL, $blockCopyofCustomValues = FALSE) {
1757 $object = new $daoName();
1760 $object->id
= $criteria['id'];
1763 foreach ($criteria as $key => $value) {
1764 $object->$key = $value;
1769 while ($object->fetch()) {
1771 // all the objects except with $blockCopyOfDependencies set
1772 // be copied - addresses #CRM-1962
1774 if ($blockCopyOfDependencies && $object->$blockCopyOfDependencies) {
1778 $newObject = new $daoName();
1780 $fields = $object->fields();
1781 if (!is_array($fieldsFix)) {
1782 $fieldsToPrefix = [];
1783 $fieldsToSuffix = [];
1784 $fieldsToReplace = [];
1786 if (!empty($fieldsFix['prefix'])) {
1787 $fieldsToPrefix = $fieldsFix['prefix'];
1789 if (!empty($fieldsFix['suffix'])) {
1790 $fieldsToSuffix = $fieldsFix['suffix'];
1792 if (!empty($fieldsFix['replace'])) {
1793 $fieldsToReplace = $fieldsFix['replace'];
1796 foreach ($fields as $name => $value) {
1797 if ($name == 'id' ||
$value['name'] == 'id') {
1798 // copy everything but the id!
1802 $dbName = $value['name'];
1803 $type = CRM_Utils_Type
::typeToString($value['type']);
1804 $newObject->$dbName = $object->$dbName;
1805 if (isset($fieldsToPrefix[$dbName])) {
1806 $newObject->$dbName = $fieldsToPrefix[$dbName] . $newObject->$dbName;
1808 if (isset($fieldsToSuffix[$dbName])) {
1809 $newObject->$dbName .= $fieldsToSuffix[$dbName];
1811 if (isset($fieldsToReplace[$dbName])) {
1812 $newObject->$dbName = $fieldsToReplace[$dbName];
1815 if ($type == 'Timestamp' ||
$type == 'Date') {
1816 $newObject->$dbName = CRM_Utils_Date
::isoToMysql($newObject->$dbName);
1820 $newObject->copyValues($newData);
1824 if (!$blockCopyofCustomValues) {
1825 $newObject->copyCustomFields($object->id
, $newObject->id
);
1827 CRM_Utils_Hook
::post('create', CRM_Core_DAO_AllCoreTables
::getBriefName($daoName), $newObject->id
, $newObject);
1834 * Method that copies custom fields values from an old entity to a new one.
1836 * Fixes bug CRM-19302,
1837 * where if a custom field of File type was present, left both events using the same file,
1838 * breaking download URL's for the old event.
1840 * @todo the goal here is to clean this up so that it works for any entity. Copy Generic already DOES some custom field stuff
1841 * but it seems to be bypassed & perhaps less good than this (or this just duplicates it...)
1843 * @param int $entityID
1844 * @param int $newEntityID
1846 public function copyCustomFields($entityID, $newEntityID) {
1847 $entity = CRM_Core_DAO_AllCoreTables
::getBriefName(get_class($this));
1848 $tableName = CRM_Core_DAO_AllCoreTables
::getTableForClass(get_class($this));
1849 // Obtain custom values for old event
1850 $customParams = $htmlType = [];
1851 $customValues = CRM_Core_BAO_CustomValueTable
::getEntityValues($entityID, $entity);
1853 // If custom values present, we copy them
1854 if (!empty($customValues)) {
1855 // Get Field ID's and identify File type attributes, to handle file copying.
1856 $fieldIds = implode(', ', array_keys($customValues));
1857 $sql = "SELECT id FROM civicrm_custom_field WHERE html_type = 'File' AND id IN ( {$fieldIds} )";
1858 $result = CRM_Core_DAO
::executeQuery($sql);
1860 // Build array of File type fields
1861 while ($result->fetch()) {
1862 $htmlType[] = $result->id
;
1865 // Build params array of custom values
1866 foreach ($customValues as $field => $value) {
1867 if ($value !== NULL) {
1868 // Handle File type attributes
1869 if (in_array($field, $htmlType)) {
1870 $fileValues = CRM_Core_BAO_File
::path($value, $entityID);
1871 $customParams["custom_{$field}_-1"] = [
1872 'name' => CRM_Utils_File
::duplicate($fileValues[0]),
1873 'type' => $fileValues[1],
1876 // Handle other types
1878 $customParams["custom_{$field}_-1"] = $value;
1883 // Save Custom Fields for new Event
1884 CRM_Core_BAO_CustomValueTable
::postProcess($customParams, $tableName, $newEntityID, $entity);
1887 // copy activity attachments ( if any )
1888 CRM_Core_BAO_File
::copyEntityFile($tableName, $entityID, $tableName, $newEntityID);
1892 * Cascade update through related entities.
1894 * @param string $daoName
1897 * @param array $newData
1899 * @return CRM_Core_DAO|null
1901 public static function cascadeUpdate($daoName, $fromId, $toId, $newData = []) {
1902 $object = new $daoName();
1903 $object->id
= $fromId;
1905 if ($object->find(TRUE)) {
1906 $newObject = new $daoName();
1907 $newObject->id
= $toId;
1909 if ($newObject->find(TRUE)) {
1910 $fields = $object->fields();
1911 foreach ($fields as $name => $value) {
1912 if ($name == 'id' ||
$value['name'] == 'id') {
1913 // copy everything but the id!
1917 $colName = $value['name'];
1918 $newObject->$colName = $object->$colName;
1920 if (substr($name, -5) == '_date' ||
1921 substr($name, -10) == '_date_time'
1923 $newObject->$colName = CRM_Utils_Date
::isoToMysql($newObject->$colName);
1926 foreach ($newData as $k => $v) {
1927 $newObject->$k = $v;
1937 * Given the component id, compute the contact id
1938 * since its used for things like send email
1940 * @param $componentIDs
1941 * @param string $tableName
1942 * @param string $idField
1946 public static function getContactIDsFromComponent($componentIDs, $tableName, $idField = 'id') {
1949 if (empty($componentIDs)) {
1953 $IDs = implode(',', $componentIDs);
1957 WHERE $idField IN ( $IDs )
1960 $dao = CRM_Core_DAO
::executeQuery($query);
1961 while ($dao->fetch()) {
1962 $contactIDs[] = $dao->contact_id
;
1968 * Fetch object based on array of properties.
1970 * @param string $daoName
1971 * Name of the dao object.
1972 * @param string $fieldIdName
1973 * @param int $fieldId
1975 * @param array $returnProperities
1976 * An assoc array of fields that need to be returned, eg array( 'first_name', 'last_name').
1979 * an object of type referenced by daoName
1981 public static function commonRetrieveAll($daoName, $fieldIdName = 'id', $fieldId, &$details, $returnProperities = NULL) {
1982 require_once str_replace('_', DIRECTORY_SEPARATOR
, $daoName) . ".php";
1983 $object = new $daoName();
1984 $object->$fieldIdName = $fieldId;
1986 // return only specific fields if returnproperties are sent
1987 if (!empty($returnProperities)) {
1988 $object->selectAdd();
1989 $object->selectAdd('id');
1990 $object->selectAdd(implode(',', $returnProperities));
1994 while ($object->fetch()) {
1996 self
::storeValues($object, $defaults);
1997 $details[$object->id
] = $defaults;
2004 * Drop all CiviCRM tables.
2006 * @throws \CRM_Core_Exception
2008 public static function dropAllTables() {
2010 // first drop all the custom tables we've created
2011 CRM_Core_BAO_CustomGroup
::dropAllTables();
2013 // drop all multilingual views
2014 CRM_Core_I18n_Schema
::dropAllViews();
2016 CRM_Utils_File
::sourceSQLFile(CIVICRM_DSN
,
2017 dirname(__FILE__
) . DIRECTORY_SEPARATOR
.
2018 '..' . DIRECTORY_SEPARATOR
.
2019 '..' . DIRECTORY_SEPARATOR
.
2020 'sql' . DIRECTORY_SEPARATOR
.
2021 'civicrm_drop.mysql'
2030 public static function escapeString($string) {
2031 static $_dao = NULL;
2033 // If this is an atypical case (e.g. preparing .sql file before CiviCRM
2034 // has been installed), then we fallback DB-less str_replace escaping, as
2035 // we can't use mysqli_real_escape_string, as there is no DB connection.
2036 // Note: In typical usage, escapeString() will only check one conditional
2037 // ("if !$_dao") rather than two conditionals ("if !defined(DSN)")
2038 if (!defined('CIVICRM_DSN')) {
2039 // See http://php.net/manual/en/mysqli.real-escape-string.php for the
2040 // list of characters mysqli_real_escape_string escapes.
2041 $search = ["\\", "\x00", "\n", "\r", "'", '"', "\x1a"];
2042 $replace = ["\\\\", "\\0", "\\n", "\\r", "\'", '\"', "\\Z"];
2043 return str_replace($search, $replace, $string);
2045 $_dao = new CRM_Core_DAO();
2047 return $_dao->escape($string);
2051 * Escape a list of strings for use with "WHERE X IN (...)" queries.
2053 * @param array $strings
2054 * @param string $default
2055 * the value to use if $strings has no elements.
2057 * eg "abc","def","ghi"
2059 public static function escapeStrings($strings, $default = NULL) {
2060 static $_dao = NULL;
2062 $_dao = new CRM_Core_DAO();
2065 if (empty($strings)) {
2069 $escapes = array_map([$_dao, 'escape'], $strings);
2070 return '"' . implode('","', $escapes) . '"';
2078 public static function escapeWildCardString($string) {
2080 // ensure we escape the single characters % and _ which are mysql wild
2081 // card characters and could come in via sortByCharacter
2082 // note that mysql does not escape these characters
2083 if ($string && in_array($string,
2084 ['%', '_', '%%', '_%']
2087 return '\\' . $string;
2090 return self
::escapeString($string);
2094 * Creates a test object, including any required objects it needs via recursion
2095 * createOnly: only create in database, do not store or return the objects (useful for perf testing)
2096 * ONLY USE FOR TESTING
2098 * @param string $daoName
2099 * @param array $params
2100 * @param int $numObjects
2101 * @param bool $createOnly
2103 * @return object|array|NULL
2104 * NULL if $createOnly. A single object if $numObjects==1. Otherwise, an array of multiple objects.
2106 public static function createTestObject(
2112 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
2113 // so we re-set here in case
2114 $config = CRM_Core_Config
::singleton();
2115 $config->backtrace
= TRUE;
2117 static $counter = 0;
2118 CRM_Core_DAO
::$_testEntitiesToSkip = [
2119 'CRM_Core_DAO_Worldregion',
2120 'CRM_Core_DAO_StateProvince',
2121 'CRM_Core_DAO_Country',
2122 'CRM_Core_DAO_Domain',
2123 'CRM_Financial_DAO_FinancialType',
2124 //because valid ones exist & we use pick them due to pseudoconstant can't reliably create & delete these
2127 // Prefer to instantiate BAO's instead of DAO's (when possible)
2128 // so that assignTestValue()/assignTestFK() can be overloaded.
2129 $baoName = str_replace('_DAO_', '_BAO_', $daoName);
2130 if ($baoName === 'CRM_Financial_BAO_FinancialTrxn') {
2131 // OMG OMG OMG this is so incredibly bad. The BAO is insanely named.
2132 // @todo create a new class called what the BAO SHOULD be
2133 // that extends BAO-crazy-name.... migrate.
2134 $baoName = 'CRM_Core_BAO_FinancialTrxn';
2136 if (class_exists($baoName)) {
2137 $daoName = $baoName;
2140 for ($i = 0; $i < $numObjects; ++
$i) {
2143 /** @var CRM_Core_DAO $object */
2144 $object = new $daoName();
2146 $fields = $object->fields();
2147 foreach ($fields as $fieldName => $fieldDef) {
2148 $dbName = $fieldDef['name'];
2149 $FKClassName = $fieldDef['FKClassName'] ??
NULL;
2151 if (isset($params[$dbName]) && !is_array($params[$dbName])) {
2152 $object->$dbName = $params[$dbName];
2155 elseif ($dbName != 'id') {
2156 if ($FKClassName != NULL) {
2157 $object->assignTestFK($fieldName, $fieldDef, $params);
2161 $object->assignTestValue($fieldName, $fieldDef, $counter);
2169 $objects[$i] = $object;
2179 elseif ($numObjects == 1) {
2188 * Deletes the this object plus any dependent objects that are associated with it.
2189 * ONLY USE FOR TESTING
2191 * @param string $daoName
2192 * @param array $params
2194 public static function deleteTestObjects($daoName, $params = []) {
2195 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
2196 // so we re-set here in case
2197 $config = CRM_Core_Config
::singleton();
2198 $config->backtrace
= TRUE;
2200 $object = new $daoName();
2201 $object->id
= $params['id'] ??
NULL;
2203 // array(array(0 => $daoName, 1 => $daoParams))
2205 if ($object->find(TRUE)) {
2207 $fields = $object->fields();
2208 foreach ($fields as $name => $value) {
2210 $dbName = $value['name'];
2212 $FKClassName = $value['FKClassName'] ??
NULL;
2213 $required = $value['required'] ??
NULL;
2214 if ($FKClassName != NULL
2216 && !in_array($FKClassName, CRM_Core_DAO
::$_testEntitiesToSkip)
2217 && ($required ||
$dbName == 'contact_id')
2218 //I'm a bit stuck on this one - we might need to change the singleValueAlter so that the entities don't share a contact
2219 // to make this test process pass - line below makes pass for now
2220 && $dbName != 'member_of_contact_id'
2223 $deletions[] = [$FKClassName, ['id' => $object->$dbName]];
2230 foreach ($deletions as $deletion) {
2231 CRM_Core_DAO
::deleteTestObjects($deletion[0], $deletion[1]);
2236 * Set defaults when creating new entity.
2237 * (don't call this set defaults as already in use with different signature in some places)
2239 * @param array $params
2242 public static function setCreateDefaults(&$params, $defaults) {
2243 if (!empty($params['id'])) {
2246 foreach ($defaults as $key => $value) {
2247 if (!array_key_exists($key, $params) ||
$params[$key] === NULL) {
2248 $params[$key] = $value;
2254 * @param string $prefix
2255 * @param bool $addRandomString
2256 * @param null $string
2260 * @see CRM_Utils_SQL_TempTable
2262 public static function createTempTableName($prefix = 'civicrm', $addRandomString = TRUE, $string = NULL) {
2263 CRM_Core_Error
::deprecatedFunctionWarning('Use CRM_Utils_SQL_TempTable interface to create temporary tables');
2264 $tableName = $prefix . "_temp";
2266 if ($addRandomString) {
2268 $tableName .= "_" . $string;
2271 $tableName .= "_" . md5(uniqid('', TRUE));
2279 * @param bool $trigger
2283 public static function checkTriggerViewPermission($view = TRUE, $trigger = TRUE) {
2284 if (\Civi
::settings()->get('logging_no_trigger_permission')) {
2287 // test for create view and trigger permissions and if allowed, add the option to go multilingual and logging
2288 $dao = new CRM_Core_DAO();
2291 $dao->query('CREATE OR REPLACE VIEW civicrm_domain_view AS SELECT * FROM civicrm_domain');
2292 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
2296 $dao->query('CREATE TRIGGER civicrm_domain_trigger BEFORE INSERT ON civicrm_domain FOR EACH ROW BEGIN END');
2297 $dao->query('DROP TRIGGER IF EXISTS civicrm_domain_trigger');
2300 catch (Exception
$e) {
2308 * @param null $message
2309 * @param bool $printDAO
2311 public static function debugPrint($message = NULL, $printDAO = TRUE) {
2312 CRM_Utils_System
::xMemory("{$message}: ");
2315 global $_DB_DATAOBJECT;
2317 foreach (array_keys($_DB_DATAOBJECT['RESULTS']) as $id) {
2318 $q[] = $_DB_DATAOBJECT['RESULTS'][$id]->query
;
2320 CRM_Core_Error
::debug('_DB_DATAOBJECT', $q);
2325 * Build a list of triggers via hook and add them to (err, reconcile them
2326 * with) the database.
2328 * @param string $tableName
2329 * the specific table requiring a rebuild; or NULL to rebuild all tables.
2330 * @param bool $force
2335 public static function triggerRebuild($tableName = NULL, $force = FALSE) {
2336 Civi
::service('sql_triggers')->rebuild($tableName, $force);
2340 * Because sql functions are sometimes lost, esp during db migration, we check here to avoid numerous support requests
2341 * @see http://issues.civicrm.org/jira/browse/CRM-13822
2342 * TODO: Alternative solutions might be
2343 * * Stop using functions and find another way to strip numeric characters from phones
2344 * * Give better error messages (currently a missing fn fatals with "unknown error")
2346 public static function checkSqlFunctionsExist() {
2347 if (!self
::$_checkedSqlFunctionsExist) {
2348 self
::$_checkedSqlFunctionsExist = TRUE;
2349 $dao = CRM_Core_DAO
::executeQuery("SHOW function status WHERE db = database() AND name = 'civicrm_strip_non_numeric'");
2350 if (!$dao->fetch()) {
2351 self
::triggerRebuild();
2357 * Wrapper function to drop triggers.
2359 * @param string $tableName
2360 * the specific table requiring a rebuild; or NULL to rebuild all tables.
2363 public static function dropTriggers($tableName = NULL) {
2364 Civi
::service('sql_triggers')->dropTriggers($tableName);
2368 * @param array $info
2369 * per hook_civicrm_triggerInfo.
2370 * @param string $onlyTableName
2371 * the specific table requiring a rebuild; or NULL to rebuild all tables.
2374 public static function createTriggers(&$info, $onlyTableName = NULL) {
2375 Civi
::service('sql_triggers')->createTriggers($info, $onlyTableName);
2379 * Given a list of fields, create a list of references.
2381 * @param string $className
2382 * BAO/DAO class name.
2383 * @return array<CRM_Core_Reference_Interface>
2385 public static function createReferenceColumns($className) {
2387 $fields = $className::fields();
2388 foreach ($fields as $field) {
2389 if (isset($field['pseudoconstant'], $field['pseudoconstant']['optionGroupName'])) {
2390 $result[] = new CRM_Core_Reference_OptionValue(
2391 $className::getTableName(),
2393 'civicrm_option_value',
2394 CRM_Utils_Array
::value('keyColumn', $field['pseudoconstant'], 'value'),
2395 $field['pseudoconstant']['optionGroupName']
2403 * Find all records which refer to this entity.
2406 * Array of objects referencing this
2408 public function findReferences() {
2409 $links = self
::getReferencesToTable(static::getTableName());
2412 foreach ($links as $refSpec) {
2413 /** @var $refSpec CRM_Core_Reference_Interface */
2414 $daoName = CRM_Core_DAO_AllCoreTables
::getClassForTable($refSpec->getReferenceTable());
2415 $result = $refSpec->findReferences($this);
2417 while ($result->fetch()) {
2418 $obj = new $daoName();
2419 $obj->id
= $result->id
;
2420 $occurrences[] = $obj;
2425 return $occurrences;
2430 * each item has keys:
2434 * - table: string|null SQL table name
2435 * - key: string|null SQL column name
2437 public function getReferenceCounts() {
2438 $links = self
::getReferencesToTable(static::getTableName());
2441 foreach ($links as $refSpec) {
2442 /** @var $refSpec CRM_Core_Reference_Interface */
2443 $count = $refSpec->getReferenceCount($this);
2444 if ($count['count'] != 0) {
2449 foreach (CRM_Core_Component
::getEnabledComponents() as $component) {
2450 /** @var $component CRM_Core_Component_Info */
2451 $counts = array_merge($counts, $component->getReferenceCounts($this));
2453 CRM_Utils_Hook
::referenceCounts($this, $counts);
2459 * List all tables which have hard foreign keys to this table.
2461 * For now, this returns a description of every entity_id/entity_table
2463 * TODO: filter dynamic entity references on the $tableName, based on
2464 * schema metadata in dynamicForeignKey which enumerates a restricted
2465 * set of possible entity_table's.
2467 * @param string $tableName
2468 * Table referred to.
2471 * structure of table and column, listing every table with a
2472 * foreign key reference to $tableName, and the column where the key appears.
2474 public static function getReferencesToTable($tableName) {
2476 foreach (CRM_Core_DAO_AllCoreTables
::getClasses() as $daoClassName) {
2477 $links = $daoClassName::getReferenceColumns();
2479 foreach ($links as $refSpec) {
2480 /** @var $refSpec CRM_Core_Reference_Interface */
2481 if ($refSpec->matchesTargetTable($tableName)) {
2482 $refsFound[] = $refSpec;
2490 * Get all references to contact table.
2492 * This includes core tables, custom group tables, tables added by the merge
2493 * hook and the entity_tag table.
2495 * Refer to CRM-17454 for information on the danger of querying the information
2496 * schema to derive this.
2498 * @throws \CiviCRM_API3_Exception
2500 public static function getReferencesToContactTable() {
2501 if (isset(\Civi
::$statics[__CLASS__
]) && isset(\Civi
::$statics[__CLASS__
]['contact_references'])) {
2502 return \Civi
::$statics[__CLASS__
]['contact_references'];
2504 $contactReferences = [];
2505 $coreReferences = CRM_Core_DAO
::getReferencesToTable('civicrm_contact');
2506 foreach ($coreReferences as $coreReference) {
2507 if (!is_a($coreReference, 'CRM_Core_Reference_Dynamic')) {
2508 $contactReferences[$coreReference->getReferenceTable()][] = $coreReference->getReferenceKey();
2511 self
::appendCustomTablesExtendingContacts($contactReferences);
2512 self
::appendCustomContactReferenceFields($contactReferences);
2513 \Civi
::$statics[__CLASS__
]['contact_references'] = $contactReferences;
2514 return \Civi
::$statics[__CLASS__
]['contact_references'];
2518 * Get all dynamic references to the given table.
2520 * @param string $tableName
2524 public static function getDynamicReferencesToTable($tableName) {
2525 if (!isset(\Civi
::$statics[__CLASS__
]['contact_references_dynamic'][$tableName])) {
2526 \Civi
::$statics[__CLASS__
]['contact_references_dynamic'][$tableName] = [];
2527 $coreReferences = CRM_Core_DAO
::getReferencesToTable($tableName);
2528 foreach ($coreReferences as $coreReference) {
2529 if ($coreReference instanceof \CRM_Core_Reference_Dynamic
) {
2530 \Civi
::$statics[__CLASS__
]['contact_references_dynamic'][$tableName][$coreReference->getReferenceTable()][] = [$coreReference->getReferenceKey(), $coreReference->getTypeColumn()];
2534 return \Civi
::$statics[__CLASS__
]['contact_references_dynamic'][$tableName];
2538 * Add custom tables that extend contacts to the list of contact references.
2540 * CRM_Core_BAO_CustomGroup::getAllCustomGroupsByBaseEntity seems like a safe-ish
2541 * function to be sure all are retrieved & we don't miss subtypes or inactive or multiples
2542 * - the down side is it is not cached.
2544 * Further changes should be include tests in the CRM_Core_MergerTest class
2545 * to ensure that disabled, subtype, multiple etc groups are still captured.
2547 * @param array $cidRefs
2549 public static function appendCustomTablesExtendingContacts(&$cidRefs) {
2550 $customValueTables = CRM_Core_BAO_CustomGroup
::getAllCustomGroupsByBaseEntity('Contact');
2551 $customValueTables->find();
2552 while ($customValueTables->fetch()) {
2553 $cidRefs[$customValueTables->table_name
][] = 'entity_id';
2558 * Add custom ContactReference fields to the list of contact references
2560 * This includes active and inactive fields/groups
2562 * @param array $cidRefs
2564 * @throws \CiviCRM_API3_Exception
2566 public static function appendCustomContactReferenceFields(&$cidRefs) {
2567 $fields = civicrm_api3('CustomField', 'get', [
2568 'return' => ['column_name', 'custom_group_id.table_name'],
2569 'data_type' => 'ContactReference',
2570 'options' => ['limit' => 0],
2572 foreach ($fields as $field) {
2573 $cidRefs[$field['custom_group_id.table_name']][] = $field['column_name'];
2578 * Lookup the value of a MySQL global configuration variable.
2580 * @param string $name
2581 * E.g. "thread_stack".
2582 * @param mixed $default
2585 public static function getGlobalSetting($name, $default = NULL) {
2586 // Alternatively, SELECT @@GLOBAL.thread_stack, but
2587 // that has been reported to fail under MySQL 5.0 for OS X
2588 $escapedName = self
::escapeString($name);
2589 $dao = CRM_Core_DAO
::executeQuery("SHOW VARIABLES LIKE '$escapedName'");
2590 if ($dao->fetch()) {
2599 * Update the fields array to also hold keys for pseudoconstant fields that relate to contained fields.
2601 * This is relevant where we want to offer both the ID field and the label field
2602 * as an option, e.g. search builder.
2604 * It is currently limited for optionGroupName & id+ name+ FK combos for purposes keeping the scope of the
2605 * change small, but is appropriate for other sorts of pseudoconstants.
2607 * @param array $fields
2609 public static function appendPseudoConstantsToFields(&$fields) {
2610 foreach ($fields as $fieldUniqueName => $field) {
2611 if (!empty($field['pseudoconstant'])) {
2612 $pseudoConstant = $field['pseudoconstant'];
2613 if (!empty($pseudoConstant['optionGroupName'])) {
2614 $fields[$pseudoConstant['optionGroupName']] = [
2615 'title' => CRM_Core_BAO_OptionGroup
::getTitleByName($pseudoConstant['optionGroupName']),
2616 'name' => $pseudoConstant['optionGroupName'],
2617 'data_type' => CRM_Utils_Type
::T_STRING
,
2618 'is_pseudofield_for' => $fieldUniqueName,
2621 // We restrict to id + name + FK as we are extending this a bit, but cautiously.
2623 !empty($field['FKClassName'])
2624 && CRM_Utils_Array
::value('keyColumn', $pseudoConstant) === 'id'
2625 && CRM_Utils_Array
::value('labelColumn', $pseudoConstant) === 'name'
2627 $pseudoFieldName = str_replace('_' . $pseudoConstant['keyColumn'], '', $field['name']);
2628 // This if is just an extra caution when adding change.
2629 if (!isset($fields[$pseudoFieldName])) {
2630 $daoName = $field['FKClassName'];
2631 $fkFields = $daoName::fields();
2632 foreach ($fkFields as $fkField) {
2633 if ($fkField['name'] === $pseudoConstant['labelColumn']) {
2634 $fields[$pseudoFieldName] = [
2635 'name' => $pseudoFieldName,
2636 'is_pseudofield_for' => $field['name'],
2637 'title' => $fkField['title'],
2638 'data_type' => $fkField['type'],
2639 'where' => $field['where'],
2650 * Get options for the called BAO object's field.
2652 * This function can be overridden by each BAO to add more logic related to context.
2653 * The overriding function will generally call the lower-level CRM_Core_PseudoConstant::get
2655 * @param string $fieldName
2656 * @param string $context
2657 * @see CRM_Core_DAO::buildOptionsContext
2658 * @param array $props
2659 * Raw field values; whatever is known about this bao object.
2661 * Note: $props can contain unsanitized input and should not be passed directly to CRM_Core_PseudoConstant::get
2663 * @return array|bool
2665 public static function buildOptions($fieldName, $context = NULL, $props = []) {
2666 // If a given bao does not override this function
2667 $baoName = get_called_class();
2668 return CRM_Core_PseudoConstant
::get($baoName, $fieldName, [], $context);
2672 * Populate option labels for this object's fields.
2674 * @throws exception if called directly on the base class
2676 public function getOptionLabels() {
2677 $fields = $this->fields();
2678 if ($fields === NULL) {
2679 throw new Exception('Cannot call getOptionLabels on CRM_Core_DAO');
2681 foreach ($fields as $field) {
2682 $name = $field['name'] ??
NULL;
2683 if ($name && isset($this->$name)) {
2684 $label = CRM_Core_PseudoConstant
::getLabel(get_class($this), $name, $this->$name);
2685 if ($label !== FALSE) {
2686 // Append 'label' onto the field name
2687 $labelName = $name . '_label';
2688 $this->$labelName = $label;
2695 * Provides documentation and validation for the buildOptions $context param
2697 * @param string $context
2699 * @throws CRM_Core_Exception
2702 public static function buildOptionsContext($context = NULL) {
2704 'get' => "get: all options are returned, even if they are disabled; labels are translated.",
2705 'create' => "create: options are filtered appropriately for the object being created/updated; labels are translated.",
2706 'search' => "search: searchable options are returned; labels are translated.",
2707 'validate' => "validate: all options are returned, even if they are disabled; machine names are used in place of labels.",
2708 'abbreviate' => "abbreviate: enabled options are returned; labels are replaced with abbreviations.",
2709 'match' => "match: enabled options are returned using machine names as keys; labels are translated.",
2711 // Validation: enforce uniformity of this param
2712 if ($context !== NULL && !isset($contexts[$context])) {
2713 throw new CRM_Core_Exception("'$context' is not a valid context for buildOptions.");
2719 * @param string $fieldName
2720 * @return bool|array
2722 public function getFieldSpec($fieldName) {
2723 $fields = $this->fields();
2725 // Support "unique names" as well as sql names
2726 $fieldKey = $fieldName;
2727 if (empty($fields[$fieldKey])) {
2728 $fieldKeys = $this->fieldKeys();
2729 $fieldKey = $fieldKeys[$fieldName] ??
NULL;
2731 // If neither worked then this field doesn't exist. Return false.
2732 if (empty($fields[$fieldKey])) {
2735 return $fields[$fieldKey];
2739 * Get SQL where clause for SQL filter syntax input parameters.
2741 * SQL version of api function to assign filters to the DAO based on the syntax
2742 * $field => array('IN' => array(4,6,9))
2744 * $field => array('LIKE' => array('%me%))
2747 * @param string $fieldName
2749 * @param array $filter
2750 * filter to be applied indexed by operator.
2751 * @param string $type
2752 * type of field (not actually used - nor in api @todo ).
2753 * @param string $alias
2754 * alternative field name ('as') @todo- not actually used.
2755 * @param bool $returnSanitisedArray
2756 * Return a sanitised array instead of a clause.
2757 * this is primarily so we can add filters @ the api level to the Query object based fields
2761 * @return NULL|string|array
2762 * a string is returned if $returnSanitisedArray is not set, otherwise and Array or NULL
2763 * depending on whether it is supported as yet
2765 public static function createSQLFilter($fieldName, $filter, $type = NULL, $alias = NULL, $returnSanitisedArray = FALSE) {
2766 foreach ($filter as $operator => $criteria) {
2767 if (!CRM_Core_BAO_SchemaHandler
::databaseSupportsUTF8MB4()) {
2768 foreach ((array) $criteria as $criterion) {
2769 if (!empty($criterion) && !is_numeric($criterion)
2770 // The first 2 criteria are redundant but are added as they
2771 // seem like they would
2772 // be quicker than this 3rd check.
2773 && max(array_map('ord', str_split($criterion))) >= 240) {
2774 // String contains unsupported emojis.
2775 // We return a clause that resolves to false as an emoji string by definition cannot be saved.
2776 // note that if we return just 0 for false if gets lost in empty checks.
2777 // https://stackoverflow.com/questions/16496554/can-php-detect-4-byte-encoded-utf8-chars
2783 if (in_array($operator, self
::acceptedSQLOperators(), TRUE)) {
2784 switch ($operator) {
2788 if (!$returnSanitisedArray) {
2789 return (sprintf('%s %s', $fieldName, $operator));
2792 return (sprintf('%s %s ', $fieldName, $operator));
2796 // ternary operators
2799 if ((empty($criteria[0]) && !in_array($criteria[0], ['0', 0]))||
(empty($criteria[1]) && !in_array($criteria[1], ['0', 0]))) {
2800 throw new Exception("invalid criteria for $operator");
2802 if (!$returnSanitisedArray) {
2803 return (sprintf('%s ' . $operator . ' "%s" AND "%s"', $fieldName, CRM_Core_DAO
::escapeString($criteria[0]), CRM_Core_DAO
::escapeString($criteria[1])));
2806 // not yet implemented (tests required to implement)
2814 if (empty($criteria)) {
2815 throw new Exception("invalid criteria for $operator");
2817 $escapedCriteria = array_map([
2821 if (!$returnSanitisedArray) {
2822 return (sprintf('%s %s ("%s")', $fieldName, $operator, implode('", "', $escapedCriteria)));
2824 return $escapedCriteria;
2829 if (!$returnSanitisedArray) {
2830 return (sprintf('%s %s "%s"', $fieldName, $operator, CRM_Core_DAO
::escapeString($criteria)));
2833 // not yet implemented (tests required to implement)
2842 * @see http://issues.civicrm.org/jira/browse/CRM-9150
2843 * support for other syntaxes is discussed in ticket but being put off for now
2846 public static function acceptedSQLOperators() {
2867 * SQL has a limit of 64 characters on various names:
2868 * table name, trigger name, column name ...
2870 * For custom groups and fields we generated names from user entered input
2871 * which can be longer than this length, this function helps with creating
2872 * strings that meet various criteria.
2874 * @param string $string
2875 * The string to be shortened.
2876 * @param int $length
2877 * The max length of the string.
2879 * @param bool $makeRandom
2883 public static function shortenSQLName($string, $length = 60, $makeRandom = FALSE) {
2884 // early return for strings that meet the requirements
2885 if (strlen($string) <= $length) {
2889 // easy return for calls that dont need a randomized uniq string
2891 return substr($string, 0, $length);
2894 // the string is longer than the length and we need a uniq string
2895 // for the same tablename we need the same uniq string every time
2896 // hence we use md5 on the string, which is not random
2897 // we'll append 8 characters to the end of the tableName
2898 $md5string = substr(md5($string), 0, 8);
2899 return substr($string, 0, $length - 8) . "_{$md5string}";
2903 * https://issues.civicrm.org/jira/browse/CRM-17748
2904 * Sets the internal options to be used on a query
2906 * @param array $options
2909 public function setOptions($options) {
2910 if (is_array($options)) {
2911 $this->_options
= $options;
2916 * https://issues.civicrm.org/jira/browse/CRM-17748
2917 * wrapper to pass internal DAO options down to DB_mysql/DB_Common level
2919 * @param array $options
2922 protected function _setDBOptions($options) {
2923 global $_DB_DATAOBJECT;
2925 if (is_array($options) && count($options)) {
2926 $conn = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5
];
2927 foreach ($options as $option_name => $option_value) {
2928 $conn->setOption($option_name, $option_value);
2935 * @param array $params
2937 public function setApiFilter(&$params) {
2941 * Generates acl clauses suitable for adding to WHERE or ON when doing an api.get for this entity
2943 * Return format is in the form of fieldname => clauses starting with an operator. e.g.:
2946 * 'location_type_id' => array('IS NOT NULL', 'IN (1,2,3)')
2950 * Note that all array keys must be actual field names in this entity. Use subqueries to filter on other tables e.g. custom values.
2954 public function addSelectWhereClause() {
2956 $fields = $this->fields();
2957 foreach ($fields as $fieldName => $field) {
2958 // Clause for contact-related entities like Email, Relationship, etc.
2959 if (strpos($fieldName, 'contact_id') === 0 && CRM_Utils_Array
::value('FKClassName', $field) == 'CRM_Contact_DAO_Contact') {
2960 $clauses[$fieldName] = CRM_Utils_SQL
::mergeSubquery('Contact');
2962 // Clause for an entity_table/entity_id combo
2963 if ($fieldName == 'entity_id' && isset($fields['entity_table'])) {
2964 $relatedClauses = [];
2965 $relatedEntities = $this->buildOptions('entity_table', 'get');
2966 foreach ((array) $relatedEntities as $table => $ent) {
2968 $ent = CRM_Core_DAO_AllCoreTables
::getBriefName(CRM_Core_DAO_AllCoreTables
::getClassForTable($table));
2969 $subquery = CRM_Utils_SQL
::mergeSubquery($ent);
2971 $relatedClauses[] = "(entity_table = '$table' AND entity_id " . implode(' AND entity_id ', $subquery) . ")";
2974 $relatedClauses[] = "(entity_table = '$table')";
2978 if ($relatedClauses) {
2979 $clauses['id'] = 'IN (SELECT id FROM `' . $this->tableName() . '` WHERE (' . implode(') OR (', $relatedClauses) . '))';
2983 CRM_Utils_Hook
::selectWhereClause($this, $clauses);
2988 * This returns the final permissioned query string for this entity
2990 * With acls from related entities + additional clauses from hook_civicrm_selectWhereClause
2992 * @param string $tableAlias
2995 public static function getSelectWhereClause($tableAlias = NULL) {
2996 $bao = new static();
2997 if ($tableAlias === NULL) {
2998 $tableAlias = $bao->tableName();
3001 foreach ((array) $bao->addSelectWhereClause() as $field => $vals) {
3002 $clauses[$field] = NULL;
3004 $clauses[$field] = "(`$tableAlias`.`$field` IS NULL OR (`$tableAlias`.`$field` " . implode(" AND `$tableAlias`.`$field` ", (array) $vals) . '))';
3011 * ensure database name is 'safe', i.e. only contains word characters (includes underscores)
3012 * and dashes, and contains at least one [a-z] case insenstive.
3018 public static function requireSafeDBName($database) {
3021 "/^[\w\-]*[a-z]+[\w\-]*$/i",
3025 if (empty($matches)) {
3032 * Transform an array to a serialized string for database storage.
3034 * @param array|null $value
3035 * @param int $serializationType
3036 * @return string|null
3038 * @throws \Exception
3040 public static function serializeField($value, $serializationType) {
3041 if ($value === NULL) {
3044 switch ($serializationType) {
3045 case self
::SERIALIZE_SEPARATOR_BOOKEND
:
3046 return $value === [] ?
'' : CRM_Utils_Array
::implodePadded($value);
3048 case self
::SERIALIZE_SEPARATOR_TRIMMED
:
3049 return is_array($value) ?
implode(self
::VALUE_SEPARATOR
, $value) : $value;
3051 case self
::SERIALIZE_JSON
:
3052 return is_array($value) ?
json_encode($value) : $value;
3054 case self
::SERIALIZE_PHP
:
3055 return is_array($value) ?
serialize($value) : $value;
3057 case self
::SERIALIZE_COMMA
:
3058 return is_array($value) ?
implode(',', $value) : $value;
3061 throw new Exception('Unknown serialization method for field.');
3066 * Transform a serialized string from the database into an array.
3068 * @param string|null $value
3069 * @param $serializationType
3071 * @return array|null
3072 * @throws CRM_Core_Exception
3074 public static function unSerializeField($value, $serializationType) {
3075 if ($value === NULL) {
3078 if ($value === '') {
3081 switch ($serializationType) {
3082 case self
::SERIALIZE_SEPARATOR_BOOKEND
:
3083 return (array) CRM_Utils_Array
::explodePadded($value);
3085 case self
::SERIALIZE_SEPARATOR_TRIMMED
:
3086 return explode(self
::VALUE_SEPARATOR
, trim($value));
3088 case self
::SERIALIZE_JSON
:
3089 return strlen($value) ?
json_decode($value, TRUE) : [];
3091 case self
::SERIALIZE_PHP
:
3092 return strlen($value) ? CRM_Utils_String
::unserialize($value) : [];
3094 case self
::SERIALIZE_COMMA
:
3095 return explode(',', trim(str_replace(', ', '', $value)));
3098 throw new CRM_Core_Exception('Unknown serialization method for field.');
3105 public static function getEntityRefFilters() {
3110 * Get exportable fields with pseudoconstants rendered as an extra field.
3112 * @param string $baoClass
3116 public static function getExportableFieldsWithPseudoConstants($baoClass) {
3117 if (method_exists($baoClass, 'exportableFields')) {
3118 $fields = $baoClass::exportableFields();
3121 $fields = $baoClass::export();
3123 CRM_Core_DAO
::appendPseudoConstantsToFields($fields);
3128 * Remove item from static cache during update/delete operations
3130 private function clearDbColumnValueCache() {
3131 $daoName = get_class($this);
3132 while (strpos($daoName, '_BAO_') !== FALSE) {
3133 $daoName = get_parent_class($daoName);
3135 if (isset($this->id
)) {
3136 unset(self
::$_dbColumnValueCache[$daoName]['id'][$this->id
]);
3138 if (isset($this->name
)) {
3139 unset(self
::$_dbColumnValueCache[$daoName]['name'][$this->name
]);
3144 * Return a mapping from field-name to the corresponding key (as used in fields()).
3147 * Array(string $name => string $uniqueName).
3149 public static function fieldKeys() {
3150 return array_flip(CRM_Utils_Array
::collect('name', static::fields()));
3154 * Returns system paths related to this entity (as defined in the xml schema)
3158 public static function getEntityPaths() {
3159 return static::$_paths ??
[];