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;
59 public static $_nullArray = [];
61 public static $_dbColumnValueCache = NULL;
62 const NOT_NULL
= 1, IS_NULL
= 2,
64 VALUE_SEPARATOR
= "\ 1",
65 BULK_INSERT_COUNT
= 200,
66 BULK_INSERT_HIGH_COUNT
= 200,
67 QUERY_FORMAT_WILDCARD
= 1,
68 QUERY_FORMAT_NO_QUOTES
= 2,
71 * Serialized string separated by and bookended with VALUE_SEPARATOR
73 SERIALIZE_SEPARATOR_BOOKEND
= 1,
75 * @deprecated format separated by VALUE_SEPARATOR
77 SERIALIZE_SEPARATOR_TRIMMED
= 2,
79 * Recommended serialization format
83 * @deprecated format using php serialize()
87 * Comma separated string, no quotes, no spaces
92 * Define entities that shouldn't be created or deleted when creating/ deleting
93 * test objects - this prevents world regions, countries etc from being added / deleted
96 public static $_testEntitiesToSkip = [];
98 * The factory class for this application.
101 public static $_factory = NULL;
103 public static $_checkedSqlFunctionsExist = FALSE;
106 * https://issues.civicrm.org/jira/browse/CRM-17748
107 * internal variable for DAO to hold per-query settings
110 protected $_options = [];
115 * @return \CRM_Core_DAO
117 public function __construct() {
119 $this->__table
= $this->getTableName();
123 * Returns localized title of this entity.
127 public static function getEntityTitle() {
128 $className = static::class;
129 CRM_Core_Error
::deprecatedWarning("$className needs to be regenerated. Missing getEntityTitle method.");
130 return CRM_Core_DAO_AllCoreTables
::getBriefName($className);
133 public function __clone() {
134 if (!empty($this->_DB_resultid
)) {
135 $this->resultCopies++
;
142 public function __destruct() {
143 if ($this->resultCopies
=== 0) {
146 $this->resultCopies
--;
150 * Returns the name of this table
154 public static function getTableName() {
155 return self
::getLocaleTableName(static::$_tableName ??
NULL);
159 * Returns if this table needs to be logged
163 public function getLog() {
164 return static::$_log ??
FALSE;
168 * Initialize the DAO object.
171 * The database connection string.
173 public static function init($dsn) {
174 Civi
::$statics[__CLASS__
]['init'] = 1;
175 $options = &PEAR
::getStaticProperty('DB_DataObject', 'options');
176 $dsn = CRM_Utils_SQL
::autoSwitchDSN($dsn);
177 $options['database'] = $dsn;
178 $options['quote_identifiers'] = TRUE;
179 if (CRM_Utils_SQL
::isSSLDSN($dsn)) {
180 // There are two different options arrays.
181 $other_options = &PEAR
::getStaticProperty('DB', 'options');
182 $other_options['ssl'] = TRUE;
184 if (defined('CIVICRM_DAO_DEBUG')) {
185 self
::DebugLevel(CIVICRM_DAO_DEBUG
);
187 $factory = new CRM_Contact_DAO_Factory();
188 CRM_Core_DAO
::setFactory($factory);
189 CRM_Core_DAO
::executeQuery('SET NAMES utf8mb4');
190 CRM_Core_DAO
::executeQuery('SET @uniqueID = %1', [1 => [CRM_Utils_Request
::id(), 'String']]);
196 public static function getConnection() {
197 global $_DB_DATAOBJECT;
198 $dao = new CRM_Core_DAO();
199 return $_DB_DATAOBJECT['CONNECTIONS'][$dao->_database_dsn_md5
];
203 * Disables usage of the ONLY_FULL_GROUP_BY Mode if necessary
205 public static function disableFullGroupByMode() {
206 $currentModes = CRM_Utils_SQL
::getSqlModes();
207 if (in_array('ONLY_FULL_GROUP_BY', $currentModes) && CRM_Utils_SQL
::isGroupByModeInDefault()) {
208 $key = array_search('ONLY_FULL_GROUP_BY', $currentModes);
209 unset($currentModes[$key]);
210 CRM_Core_DAO
::executeQuery("SET SESSION sql_mode = %1", [1 => [implode(',', $currentModes), 'String']]);
215 * Re-enables ONLY_FULL_GROUP_BY sql_mode as necessary..
217 public static function reenableFullGroupByMode() {
218 $currentModes = CRM_Utils_SQL
::getSqlModes();
219 if (!in_array('ONLY_FULL_GROUP_BY', $currentModes) && CRM_Utils_SQL
::isGroupByModeInDefault()) {
220 $currentModes[] = 'ONLY_FULL_GROUP_BY';
221 CRM_Core_DAO
::executeQuery("SET SESSION sql_mode = %1", [1 => [implode(',', $currentModes), 'String']]);
226 * @param string $fieldName
228 * @param array $params
230 protected function assignTestFK($fieldName, $fieldDef, $params) {
231 $required = $fieldDef['required'] ??
NULL;
232 $FKClassName = $fieldDef['FKClassName'] ??
NULL;
233 $dbName = $fieldDef['name'];
234 $daoName = str_replace('_BAO_', '_DAO_', get_class($this));
236 // skip the FK if it is not required
237 // if it's contact id we should create even if not required
238 // we'll have a go @ fetching first though
239 // we WILL create campaigns though for so tests with a campaign pseudoconstant will complete
240 if ($FKClassName === 'CRM_Campaign_DAO_Campaign' && $daoName != $FKClassName) {
243 if (!$required && $dbName != 'contact_id') {
244 $fkDAO = new $FKClassName();
245 if ($fkDAO->find(TRUE)) {
246 $this->$dbName = $fkDAO->id
;
250 elseif (in_array($FKClassName, CRM_Core_DAO
::$_testEntitiesToSkip)) {
251 $depObject = new $FKClassName();
252 $depObject->find(TRUE);
253 $this->$dbName = $depObject->id
;
255 elseif ($daoName == 'CRM_Member_DAO_MembershipType' && $fieldName == 'member_of_contact_id') {
256 // FIXME: the fields() metadata is not specific enough
257 $depObject = CRM_Core_DAO
::createTestObject($FKClassName, ['contact_type' => 'Organization']);
258 $this->$dbName = $depObject->id
;
261 //if it is required we need to generate the dependency object first
262 $depObject = CRM_Core_DAO
::createTestObject($FKClassName, CRM_Utils_Array
::value($dbName, $params, 1));
263 $this->$dbName = $depObject->id
;
268 * Generate and assign an arbitrary value to a field of a test object.
270 * @param string $fieldName
271 * @param array $fieldDef
272 * @param int $counter
273 * The globally-unique ID of the test object.
275 * @throws \CRM_Core_Exception
277 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
278 $dbName = $fieldDef['name'];
279 $daoName = get_class($this);
282 if (!$handled && $dbName == 'contact_sub_type') {
283 //coming up with a rule to set this is too complex let's not set it
287 // Pick an option value if needed
288 if (!$handled && $fieldDef['type'] !== CRM_Utils_Type
::T_BOOLEAN
) {
289 $options = $daoName::buildOptions($dbName, 'create');
291 $this->$dbName = key($options);
297 switch ($fieldDef['type']) {
298 case CRM_Utils_Type
::T_INT
:
299 case CRM_Utils_Type
::T_FLOAT
:
300 case CRM_Utils_Type
::T_MONEY
:
301 if (isset($fieldDef['precision'])) {
302 // $object->$dbName = CRM_Utils_Number::createRandomDecimal($value['precision']);
303 $this->$dbName = CRM_Utils_Number
::createTruncatedDecimal($counter, $fieldDef['precision']);
306 $this->$dbName = $counter;
310 case CRM_Utils_Type
::T_BOOLEAN
:
311 if (isset($fieldDef['default'])) {
312 $this->$dbName = $fieldDef['default'];
314 elseif ($fieldDef['name'] == 'is_deleted' ||
$fieldDef['name'] == 'is_test') {
322 case CRM_Utils_Type
::T_DATE
:
323 case CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
:
324 $this->$dbName = '19700101';
325 if ($dbName == 'end_date') {
326 // put this in the future
327 $this->$dbName = '20200101';
331 case CRM_Utils_Type
::T_TIMESTAMP
:
332 $this->$dbName = '19700201000000';
335 case CRM_Utils_Type
::T_TIME
:
336 throw new CRM_Core_Exception('T_TIME shouldn\'t be used.');
338 case CRM_Utils_Type
::T_CCNUM
:
339 $this->$dbName = '4111 1111 1111 1111';
342 case CRM_Utils_Type
::T_URL
:
343 $this->$dbName = 'http://www.civicrm.org';
346 case CRM_Utils_Type
::T_STRING
:
347 case CRM_Utils_Type
::T_BLOB
:
348 case CRM_Utils_Type
::T_MEDIUMBLOB
:
349 case CRM_Utils_Type
::T_TEXT
:
350 case CRM_Utils_Type
::T_LONGTEXT
:
351 case CRM_Utils_Type
::T_EMAIL
:
353 // WAS: if (isset($value['enumValues'])) {
354 // TODO: see if this works with all pseudoconstants
355 if (isset($fieldDef['pseudoconstant'], $fieldDef['pseudoconstant']['callback'])) {
356 if (isset($fieldDef['default'])) {
357 $this->$dbName = $fieldDef['default'];
360 $options = CRM_Core_PseudoConstant
::get($daoName, $fieldName);
361 if (is_array($options)) {
362 $this->$dbName = $options[0];
365 $defaultValues = explode(',', $options);
366 $this->$dbName = $defaultValues[0];
371 $this->$dbName = $dbName . '_' . $counter;
372 $maxlength = $fieldDef['maxlength'] ??
NULL;
373 if ($maxlength > 0 && strlen($this->$dbName) > $maxlength) {
374 $this->$dbName = substr($this->$dbName, 0, $fieldDef['maxlength']);
382 * Reset the DAO object.
384 * DAO is kinda crappy in that there is an unwritten rule of one query per DAO.
386 * We attempt to get around this crappy restriction by resetting some of DAO's internal fields. Use this with caution
388 public function reset() {
390 foreach (array_keys($this->table()) as $field) {
391 unset($this->$field);
395 * reset the various DB_DAO structures manually
404 * @param string $tableName
408 public static function getLocaleTableName($tableName) {
411 $tables = CRM_Core_I18n_Schema
::schemaStructureTables();
412 if (in_array($tableName, $tables)) {
413 return $tableName . $dbLocale;
420 * Execute a query by the current DAO, localizing it along the way (if needed).
422 * @param string $query
423 * The SQL query for execution.
424 * @param bool $i18nRewrite
425 * Whether to rewrite the query.
428 * the current DAO object after the query execution
430 public function query($query, $i18nRewrite = TRUE) {
431 // rewrite queries that should use $dbLocale-based views for multi-language installs
432 global $dbLocale, $_DB_DATAOBJECT;
434 if (empty($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5
])) {
435 // Will force connection to be populated per CRM-20541.
439 $conn = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5
];
440 $orig_options = $conn->options
;
441 $this->_setDBOptions($this->_options
);
443 if ($i18nRewrite and $dbLocale) {
444 $query = CRM_Core_I18n_Schema
::rewriteQuery($query);
447 $ret = parent
::query($query);
449 $this->_setDBOptions($orig_options);
454 * Static function to set the factory instance for this class.
456 * @param object $factory
457 * The factory application object.
459 public static function setFactory(&$factory) {
460 self
::$_factory = &$factory;
464 * Factory method to instantiate a new object from a table name.
466 * @param string $table
467 * @return \DataObject|\PEAR_Error
469 public function factory($table = '') {
470 if (!isset(self
::$_factory)) {
471 return parent
::factory($table);
474 return self
::$_factory->create($table);
478 * Initialization for all DAO objects. Since we access DB_DO programatically
479 * we need to set the links manually.
481 public function initialize() {
483 if (empty(Civi
::$statics[__CLASS__
]['init'])) {
484 // CRM_Core_DAO::init() must be called before CRM_Core_DAO->initialize().
485 // This occurs very early in bootstrap - error handlers may not be wired up.
486 echo "Inconsistent system initialization sequence. Premature access of (" . get_class($this) . ")";
487 CRM_Utils_System
::civiExit();
492 * Defines the default key as 'id'.
496 public function keys() {
505 * Tells DB_DataObject which keys use autoincrement.
506 * 'id' is autoincrementing by default.
511 public function sequenceKey() {
512 static $sequenceKeys;
513 if (!isset($sequenceKeys)) {
514 $sequenceKeys = ['id', TRUE];
516 return $sequenceKeys;
520 * Returns list of FK relationships.
523 * @return CRM_Core_Reference_Basic[]
525 public static function getReferenceColumns() {
530 * Returns all the column names of this table.
535 public static function &fields() {
541 * Returns all usable fields, indexed by name.
543 * This function differs from fields() in that it indexes by name rather than unique_name.
545 * It excludes fields not added yet by pending upgrades.
546 * This avoids problems with trying to SELECT a field that exists in code but has not yet been added to the db.
548 * @param bool $checkPermissions
549 * Filter by field permissions.
552 public static function getSupportedFields($checkPermissions = FALSE) {
553 $fields = array_column((array) static::fields(), NULL, 'name');
555 // Exclude fields yet not added by pending upgrades
556 $dbVer = \CRM_Core_BAO_Domain
::version();
557 $daoExt = defined(static::class . '::EXT') ?
constant(static::class . '::EXT') : NULL;
558 if ($fields && $daoExt === 'civicrm' && version_compare($dbVer, \CRM_Utils_System
::version()) < 0) {
559 $fields = array_filter($fields, function($field) use ($dbVer) {
560 $add = $field['add'] ??
'1.0.0';
561 if (substr_count($add, '.') < 2) {
564 return version_compare($dbVer, $add, '>=');
568 // Exclude fields the user does not have permission for
569 if ($checkPermissions) {
570 $fields = array_filter($fields, function($field) {
571 return empty($field['permission']) || CRM_Core_Permission
::check($field['permission']);
579 * Get/set an associative array of table columns
584 public function table() {
585 $fields = $this->fields();
589 foreach ($fields as $name => $value) {
590 $table[$value['name']] = $value['type'];
591 if (!empty($value['required'])) {
592 $table[$value['name']] +
= self
::DB_DAO_NOTNULL
;
605 * @return CRM_Core_DAO
607 public function save($hook = TRUE) {
609 if (!empty($this->id
)) {
611 $preEvent = new \Civi\Core\DAO\Event\
PreUpdate($this);
612 $preEvent->eventID
= $eventID;
613 \Civi
::dispatcher()->dispatch("civi.dao.preUpdate", $preEvent);
616 $result = $this->update();
619 $event = new \Civi\Core\DAO\Event\
PostUpdate($this, $result);
620 $event->eventID
= $eventID;
621 \Civi
::dispatcher()->dispatch("civi.dao.postUpdate", $event);
623 $this->clearDbColumnValueCache();
627 $preEvent = new \Civi\Core\DAO\Event\
PreUpdate($this);
628 $preEvent->eventID
= $eventID;
629 \Civi
::dispatcher()->dispatch("civi.dao.preInsert", $preEvent);
632 $result = $this->insert();
635 $event = new \Civi\Core\DAO\Event\
PostUpdate($this, $result);
636 $event->eventID
= $eventID;
637 \Civi
::dispatcher()->dispatch("civi.dao.postInsert", $event);
643 CRM_Utils_Hook
::postSave($this);
650 * Deletes items from table which match current objects variables.
652 * Returns the true on success
656 * Designed to be extended
658 * $object = new mytable();
660 * echo $object->delete(); // builds a conditon
662 * $object = new mytable();
663 * $object->whereAdd('age > 12');
665 * $object->orderBy('age DESC');
666 * $object->delete(true); // dont use object vars, use the conditions, limit and order.
668 * @param bool $useWhere (optional) If DB_DATAOBJECT_WHEREADD_ONLY is passed in then
669 * we will build the condition only using the whereAdd's. Default is to
670 * build the condition only using the object parameters.
672 * * @return mixed Int (No. of rows affected) on success, false on failure, 0 on no data affected
674 public function delete($useWhere = FALSE) {
675 $preEvent = new \Civi\Core\DAO\Event\
PreDelete($this);
676 \Civi
::dispatcher()->dispatch("civi.dao.preDelete", $preEvent);
678 $result = parent
::delete($useWhere);
680 $event = new \Civi\Core\DAO\Event\
PostDelete($this, $result);
681 \Civi
::dispatcher()->dispatch("civi.dao.postDelete", $event);
684 $this->clearDbColumnValueCache();
690 * @param bool $created
692 public function log($created = FALSE) {
695 if (!$this->getLog()) {
700 $session = CRM_Core_Session
::singleton();
701 $cid = $session->get('userID');
704 // return is we dont have handle to FK
709 $dao = new CRM_Core_DAO_Log();
710 $dao->entity_table
= $this->getTableName();
711 $dao->entity_id
= $this->id
;
712 $dao->modified_id
= $cid;
713 $dao->modified_date
= date("YmdHis");
718 * Given an associative array of name/value pairs, extract all the values
719 * that belong to this object and initialize the object with said values
721 * @param array $params
722 * Array of name/value pairs to save.
725 * Did we copy all null values into the object
727 public function copyValues($params) {
729 foreach ($this->fields() as $uniqueName => $field) {
730 $dbName = $field['name'];
731 if (array_key_exists($dbName, $params)) {
732 $value = $params[$dbName];
735 elseif (array_key_exists($uniqueName, $params)) {
736 $value = $params[$uniqueName];
743 // if there is no value then make the variable NULL
746 $this->$dbName = 'null';
748 elseif (is_array($value) && !empty($field['serialize'])) {
749 $this->$dbName = CRM_Core_DAO
::serializeField($value, $field['serialize']);
753 $maxLength = $field['maxlength'] ??
NULL;
754 if (!is_array($value) && $maxLength && mb_strlen($value) > $maxLength && empty($field['pseudoconstant'])) {
755 // No ts() since this is a sysadmin-y string not seen by general users.
756 Civi
::log()->warning('A string for field {dbName} has been truncated. The original string was {value}.', ['dbName' => $dbName, 'value' => $value]);
757 // The string is too long - what to do what to do? Well losing data is generally bad so let's truncate
758 $value = CRM_Utils_String
::ellipsify($value, $maxLength);
760 $this->$dbName = $value;
769 * Store all the values from this object in an associative array
770 * this is a destructive store, calling function is responsible
771 * for keeping sanity of id's.
773 * @param object $object
774 * The object that we are extracting data from.
775 * @param array $values
776 * (reference ) associative array of name/value pairs.
778 public static function storeValues(&$object, &$values) {
779 $fields = $object->fields();
780 foreach ($fields as $name => $value) {
781 $dbName = $value['name'];
782 if (isset($object->$dbName) && $object->$dbName !== 'null') {
783 $values[$dbName] = $object->$dbName;
784 if ($name != $dbName) {
785 $values[$name] = $object->$dbName;
792 * Create an attribute for this specific field. We only do this for strings and text
794 * @param array $field
795 * The field under task.
798 * the attributes for the object
800 public static function makeAttribute($field) {
802 if (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_STRING
) {
803 $maxLength = $field['maxlength'] ??
NULL;
804 $size = $field['size'] ??
NULL;
805 if ($maxLength ||
$size) {
808 $attributes['maxlength'] = $maxLength;
811 $attributes['size'] = $size;
816 elseif (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_TEXT
) {
817 $rows = $field['rows'] ??
NULL;
821 $cols = $field['cols'] ??
NULL;
827 $attributes['rows'] = $rows;
828 $attributes['cols'] = $cols;
831 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
) {
832 $attributes['size'] = 6;
833 $attributes['maxlength'] = 14;
841 * Get the size and maxLength attributes for this text field.
842 * (or for all text fields) in the DAO object.
844 * @param string $class
846 * @param string $fieldName
847 * Field that i'm interested in or null if.
848 * you want the attributes for all DAO text fields
851 * assoc array of name => attribute pairs
853 public static function getAttribute($class, $fieldName = NULL) {
854 $object = new $class();
855 $fields = $object->fields();
856 if ($fieldName != NULL) {
857 $field = $fields[$fieldName] ??
NULL;
858 return self
::makeAttribute($field);
862 foreach ($fields as $name => $field) {
863 $attribute = self
::makeAttribute($field);
865 $attributes[$name] = $attribute;
869 if (!empty($attributes)) {
877 * Create or update a record from supplied params.
879 * If 'id' is supplied, an existing record will be updated
880 * Otherwise a new record will be created.
882 * @param array $record
883 * @return CRM_Core_DAO
884 * @throws CRM_Core_Exception
886 public static function writeRecord(array $record) {
887 $hook = empty($record['id']) ?
'create' : 'edit';
888 $className = CRM_Core_DAO_AllCoreTables
::getCanonicalClassName(static::class);
889 if ($className === 'CRM_Core_DAO') {
890 throw new CRM_Core_Exception('Function writeRecord must be called on a subclass of CRM_Core_DAO');
892 $entityName = CRM_Core_DAO_AllCoreTables
::getBriefName($className);
894 \CRM_Utils_Hook
::pre($hook, $entityName, $record['id'] ??
NULL, $record);
895 $instance = new $className();
896 $instance->copyValues($record);
898 \CRM_Utils_Hook
::post($hook, $entityName, $instance->id
, $instance);
904 * Delete a record from supplied params.
906 * @param array $record
908 * @return CRM_Core_DAO
909 * @throws CRM_Core_Exception
911 public static function deleteRecord(array $record) {
912 $className = CRM_Core_DAO_AllCoreTables
::getCanonicalClassName(static::class);
913 if ($className === 'CRM_Core_DAO') {
914 throw new CRM_Core_Exception('Function deleteRecord must be called on a subclass of CRM_Core_DAO');
916 $entityName = CRM_Core_DAO_AllCoreTables
::getBriefName($className);
917 if (empty($record['id'])) {
918 throw new CRM_Core_Exception("Cannot delete {$entityName} with no id.");
921 CRM_Utils_Hook
::pre('delete', $entityName, $record['id'], $record);
922 $instance = new $className();
923 $instance->id
= $record['id'];
924 if (!$instance->delete()) {
925 throw new CRM_Core_Exception("Could not delete {$entityName} id {$record['id']}");
927 CRM_Utils_Hook
::post('delete', $entityName, $record['id'], $instance);
933 * Check if there is a record with the same name in the db.
935 * @param string $value
936 * The value of the field we are checking.
937 * @param string $daoName
938 * The dao object name.
939 * @param string $daoID
940 * The id of the object being updated. u can change your name.
941 * as long as there is no conflict
942 * @param string $fieldName
943 * The name of the field in the DAO.
945 * @param string $domainID
946 * The id of the domain. Object exists only for the given domain.
949 * true if object exists
951 public static function objectExists($value, $daoName, $daoID, $fieldName = 'name', $domainID = NULL) {
952 $object = new $daoName();
953 $object->$fieldName = $value;
955 $object->domain_id
= $domainID;
958 if ($object->find(TRUE)) {
959 return $daoID && $object->id
== $daoID;
967 * Check if there is a given column in a specific table.
970 * @see CRM_Core_BAO_SchemaHandler::checkIfFieldExists
972 * @param string $tableName
973 * @param string $columnName
974 * @param bool $i18nRewrite
975 * Whether to rewrite the query on multilingual setups.
978 * true if exists, else false
980 public static function checkFieldExists($tableName, $columnName, $i18nRewrite = TRUE) {
981 CRM_Core_Error
::deprecatedFunctionWarning('CRM_Core_BAO_SchemaHandler::checkIfFieldExists');
982 return CRM_Core_BAO_SchemaHandler
::checkIfFieldExists($tableName, $columnName, $i18nRewrite);
986 * Scans all the tables using a slow query and table name.
990 public static function getTableNames() {
991 $dao = CRM_Core_DAO
::executeQuery(
993 FROM information_schema.TABLES
994 WHERE TABLE_SCHEMA = '" . CRM_Core_DAO
::getDatabaseName() . "'
995 AND TABLE_NAME LIKE 'civicrm_%'
996 AND TABLE_NAME NOT LIKE 'civicrm_import_job_%'
997 AND TABLE_NAME NOT LIKE '%_temp%'
1000 while ($dao->fetch()) {
1001 $values[] = $dao->TABLE_NAME
;
1007 * @param int $maxTablesToCheck
1011 public static function isDBMyISAM($maxTablesToCheck = 10) {
1012 return CRM_Core_DAO
::singleValueQuery(
1014 FROM information_schema.TABLES
1015 WHERE ENGINE = 'MyISAM'
1016 AND TABLE_SCHEMA = '" . CRM_Core_DAO
::getDatabaseName() . "'
1017 AND TABLE_NAME LIKE 'civicrm_%'
1018 AND TABLE_NAME NOT LIKE 'civicrm_import_job_%'
1019 AND TABLE_NAME NOT LIKE '%_temp%'
1020 AND TABLE_NAME NOT LIKE 'civicrm_tmp_%'
1025 * Get the name of the CiviCRM database.
1029 public static function getDatabaseName() {
1030 $daoObj = new CRM_Core_DAO();
1031 return $daoObj->database();
1035 * Checks if a constraint exists for a specified table.
1037 * @param string $tableName
1038 * @param string $constraint
1041 * true if constraint exists, false otherwise
1043 * @throws \CRM_Core_Exception
1045 public static function checkConstraintExists($tableName, $constraint) {
1048 if (!array_key_exists($tableName, $show)) {
1049 $query = "SHOW CREATE TABLE $tableName";
1050 $dao = CRM_Core_DAO
::executeQuery($query, [], TRUE, NULL, FALSE, FALSE);
1052 if (!$dao->fetch()) {
1053 throw new CRM_Core_Exception('query failed');
1056 $show[$tableName] = $dao->Create_Table
;
1059 return (bool) preg_match("/\b$constraint\b/i", $show[$tableName]);
1063 * Checks if CONSTRAINT keyword exists for a specified table.
1065 * @param array $tables
1067 * @throws CRM_Core_Exception
1070 * true if CONSTRAINT keyword exists, false otherwise
1072 public static function schemaRequiresRebuilding($tables = ["civicrm_contact"]) {
1074 foreach ($tables as $tableName) {
1075 if (!array_key_exists($tableName, $show)) {
1076 $query = "SHOW CREATE TABLE $tableName";
1077 $dao = CRM_Core_DAO
::executeQuery($query, [], TRUE, NULL, FALSE, FALSE);
1079 if (!$dao->fetch()) {
1080 throw new CRM_Core_Exception('Show create table failed.');
1083 $show[$tableName] = $dao->Create_Table
;
1086 $result = (bool) preg_match("/\bCONSTRAINT\b\s/i", $show[$tableName]);
1087 if ($result == TRUE) {
1098 * Checks if the FK constraint name is in the format 'FK_tableName_columnName'
1099 * for a specified column of a table.
1101 * @param string $tableName
1102 * @param string $columnName
1105 * true if in format, false otherwise
1107 * @throws \CRM_Core_Exception
1109 public static function checkFKConstraintInFormat($tableName, $columnName) {
1112 if (!array_key_exists($tableName, $show)) {
1113 $query = "SHOW CREATE TABLE $tableName";
1114 $dao = CRM_Core_DAO
::executeQuery($query);
1116 if (!$dao->fetch()) {
1117 throw new CRM_Core_Exception('query failed');
1120 $show[$tableName] = $dao->Create_Table
;
1122 $constraint = "`FK_{$tableName}_{$columnName}`";
1123 $pattern = "/\bCONSTRAINT\b\s+%s\s+\bFOREIGN\s+KEY\b\s/i";
1124 return (bool) preg_match(sprintf($pattern, $constraint), $show[$tableName]);
1128 * Check whether a specific column in a specific table has always the same value.
1130 * @param string $tableName
1131 * @param string $columnName
1132 * @param string $columnValue
1135 * true if the value is always $columnValue, false otherwise
1137 public static function checkFieldHasAlwaysValue($tableName, $columnName, $columnValue) {
1138 $query = "SELECT * FROM $tableName WHERE $columnName != '$columnValue'";
1139 $dao = CRM_Core_DAO
::executeQuery($query);
1140 $result = $dao->fetch() ?
FALSE : TRUE;
1145 * Check whether a specific column in a specific table is always NULL.
1147 * @param string $tableName
1148 * @param string $columnName
1151 * true if if the value is always NULL, false otherwise
1153 public static function checkFieldIsAlwaysNull($tableName, $columnName) {
1154 $query = "SELECT * FROM $tableName WHERE $columnName IS NOT NULL";
1155 $dao = CRM_Core_DAO
::executeQuery($query);
1156 $result = $dao->fetch() ?
FALSE : TRUE;
1161 * Checks if this DAO's table ought to exist.
1163 * If there are pending DB updates, this function compares the CiviCRM version of the table to the current schema version.
1166 * @throws CRM_Core_Exception
1168 public static function tableHasBeenAdded() {
1169 if (CRM_Utils_System
::version() === CRM_Core_BAO_Domain
::version()) {
1172 $daoExt = defined(static::class . '::EXT') ?
constant(static::class . '::EXT') : NULL;
1173 $daoVersion = defined(static::class . '::TABLE_ADDED') ?
constant(static::class . '::TABLE_ADDED') : '1.0';
1174 return !($daoExt === 'civicrm' && version_compare(CRM_Core_BAO_Domain
::version(), $daoVersion, '<'));
1178 * Check if there is a given table in the database.
1180 * @param string $tableName
1183 * true if exists, else false
1185 public static function checkTableExists($tableName) {
1190 $params = [1 => [$tableName, 'String']];
1192 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1193 return (bool) $dao->fetch();
1197 * Check if a given table has data.
1199 * @param string $tableName
1201 * TRUE if $tableName has at least one record.
1203 public static function checkTableHasData($tableName) {
1204 $c = CRM_Core_DAO
::singleValueQuery(sprintf('SELECT count(*) c FROM `%s`', $tableName));
1213 public function checkVersion($version) {
1214 CRM_Core_Error
::deprecatedFunctionWarning('CRM_Core_BAO_Domain::version');
1215 $dbVersion = CRM_Core_BAO_Domain
::version();
1216 return trim($version) == trim($dbVersion);
1220 * Find a DAO object for the given ID and return it.
1223 * Id of the DAO object being searched for.
1225 * @return CRM_Core_DAO
1226 * Object of the type of the class that called this function.
1230 public static function findById($id) {
1231 $object = new static();
1233 if (!$object->find(TRUE)) {
1234 throw new Exception("Unable to find a " . get_called_class() . " with id {$id}.");
1240 * Returns all results as array-encoded records.
1244 public function fetchAll($k = FALSE, $v = FALSE, $method = FALSE) {
1246 while ($this->fetch()) {
1247 $result[] = $this->toArray();
1253 * Return the results as PHP generator.
1255 * @param string $type
1256 * Whether the generator yields 'dao' objects or 'array's.
1258 public function fetchGenerator($type = 'dao') {
1259 while ($this->fetch()) {
1266 yield
$this->toArray();
1270 throw new \
RuntimeException("Invalid record type ($type)");
1276 * Returns a singular value.
1278 * @return mixed|NULL
1280 public function fetchValue() {
1281 $result = $this->getDatabaseResult();
1282 $row = $result->fetchRow();
1292 * Get all the result records as mapping between columns.
1294 * @param string $keyColumn
1296 * @param string $valueColumn
1299 * Ex: ["foo" => "The Foo Bar", "baz" => "The Baz Qux"]
1301 public function fetchMap($keyColumn, $valueColumn) {
1303 while ($this->fetch()) {
1304 $result[$this->{$keyColumn}] = $this->{$valueColumn};
1310 * Given a DAO name, a column name and a column value, find the record and GET the value of another column in that record
1312 * @param string $daoName
1313 * Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact).
1314 * @param int $searchValue
1315 * Value of the column you want to search by.
1316 * @param string $returnColumn
1317 * Name of the column you want to GET the value of.
1318 * @param string $searchColumn
1319 * Name of the column you want to search by.
1320 * @param bool $force
1321 * Skip use of the cache.
1323 * @return string|int|null
1324 * Value of $returnColumn in the retrieved record
1326 * @throws \CRM_Core_Exception
1328 public static function getFieldValue($daoName, $searchValue, $returnColumn = 'name', $searchColumn = 'id', $force = FALSE) {
1330 empty($searchValue) ||
1331 trim(strtolower($searchValue)) == 'null'
1333 // adding this here since developers forget to check for an id
1334 // or for the 'null' (which is a bad DAO kludge)
1335 // and hence we get the first value in the db
1336 throw new CRM_Core_Exception('getFieldValue failed');
1339 self
::$_dbColumnValueCache = self
::$_dbColumnValueCache ??
[];
1341 while (strpos($daoName, '_BAO_') !== FALSE) {
1342 $daoName = get_parent_class($daoName);
1346 empty(self
::$_dbColumnValueCache[$daoName][$searchColumn][$searchValue]) ||
1347 !array_key_exists($returnColumn, self
::$_dbColumnValueCache[$daoName][$searchColumn][$searchValue])
1349 $object = new $daoName();
1350 $object->$searchColumn = $searchValue;
1351 $object->selectAdd();
1352 $object->selectAdd($returnColumn);
1355 if ($object->find(TRUE)) {
1356 $result = $object->$returnColumn;
1359 self
::$_dbColumnValueCache[$daoName][$searchColumn][$searchValue][$returnColumn] = $result;
1361 return self
::$_dbColumnValueCache[$daoName][$searchColumn][$searchValue][$returnColumn];
1365 * Given a DAO name, a column name and a column value, find the record and SET the value of another column in that record
1367 * @param string $daoName
1368 * Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact).
1369 * @param int $searchValue
1370 * Value of the column you want to search by.
1371 * @param string $setColumn
1372 * Name of the column you want to SET the value of.
1373 * @param string $setValue
1374 * SET the setColumn to this value.
1375 * @param string $searchColumn
1376 * Name of the column you want to search by.
1379 * true if we found and updated the object, else false
1381 public static function setFieldValue($daoName, $searchValue, $setColumn, $setValue, $searchColumn = 'id') {
1382 $object = new $daoName();
1383 $object->selectAdd();
1384 $object->selectAdd("$searchColumn, $setColumn");
1385 $object->$searchColumn = $searchValue;
1387 if ($object->find(TRUE)) {
1388 $object->$setColumn = $setValue;
1389 if ($object->save()) {
1400 * @param array|object $sort either array or CRM_Utils_Sort
1401 * @param string $default
1402 * Default sort value.
1406 public static function getSortString($sort, $default = NULL) {
1407 // check if sort is of type CRM_Utils_Sort
1408 if (is_a($sort, 'CRM_Utils_Sort')) {
1409 return $sort->orderBy();
1414 // is it an array specified as $field => $sortDirection ?
1416 foreach ($sort as $k => $v) {
1417 $sortString .= "$k $v,";
1419 return rtrim($sortString, ',');
1425 * Fetch object based on array of properties.
1427 * @param string $daoName
1428 * Name of the dao object.
1429 * @param array $params
1430 * (reference ) an assoc array of name/value pairs.
1431 * @param array $defaults
1432 * (reference ) an assoc array to hold the flattened values.
1433 * @param array $returnProperities
1434 * An assoc array of fields that need to be returned, eg array( 'first_name', 'last_name').
1437 * an object of type referenced by daoName
1439 public static function commonRetrieve($daoName, &$params, &$defaults, $returnProperities = NULL) {
1440 $object = new $daoName();
1441 $object->copyValues($params);
1443 // return only specific fields if returnproperties are sent
1444 if (!empty($returnProperities)) {
1445 $object->selectAdd();
1446 $object->selectAdd(implode(',', $returnProperities));
1449 if ($object->find(TRUE)) {
1450 self
::storeValues($object, $defaults);
1457 * Delete the object records that are associated with this contact.
1459 * @param string $daoName
1460 * Name of the dao object.
1461 * @param int $contactId
1462 * Id of the contact to delete.
1464 public static function deleteEntityContact($daoName, $contactId) {
1465 $object = new $daoName();
1467 $object->entity_table
= 'civicrm_contact';
1468 $object->entity_id
= $contactId;
1473 * Execute an unbuffered query.
1475 * This is a wrapper around new functionality exposed with CRM-17748.
1477 * @param string $query query to be executed
1479 * @param array $params
1480 * @param bool $abort
1481 * @param null $daoName
1482 * @param bool $freeDAO
1483 * @param bool $i18nRewrite
1484 * @param bool $trapException
1486 * @return CRM_Core_DAO
1487 * Object that points to an unbuffered result set
1489 public static function executeUnbufferedQuery(
1495 $i18nRewrite = TRUE,
1496 $trapException = FALSE
1499 return self
::executeQuery(
1507 ['result_buffering' => 0]
1514 * @param string $query
1515 * Query to be executed.
1517 * @param array $params
1518 * @param bool $abort
1519 * @param null $daoName
1520 * @param bool $freeDAO
1521 * @param bool $i18nRewrite
1522 * @param bool $trapException
1523 * @param array $options
1525 * @return CRM_Core_DAO|object
1526 * object that holds the results of the query
1527 * NB - if this is defined as just returning a DAO phpstorm keeps pointing
1528 * out all the properties that are not part of the DAO
1530 public static function &executeQuery(
1536 $i18nRewrite = TRUE,
1537 $trapException = FALSE,
1540 $queryStr = self
::composeQuery($query, $params, $abort);
1543 $dao = new CRM_Core_DAO();
1546 $dao = new $daoName();
1549 if ($trapException) {
1550 CRM_Core_Error
::deprecatedFunctionWarning('calling functions should handle exceptions');
1551 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
1554 if ($dao->isValidOption($options)) {
1555 $dao->setOptions($options);
1558 $result = $dao->query($queryStr, $i18nRewrite);
1560 // since it is unbuffered, ($dao->N==0) is true. This blocks the standard fetch() mechanism.
1561 if (CRM_Utils_Array
::value('result_buffering', $options) === 0) {
1565 if (is_a($result, 'DB_Error')) {
1566 CRM_Core_Error
::deprecatedFunctionWarning('calling functions should handle exceptions');
1574 * Wrapper to validate internal DAO options before passing to DB_mysql/DB_Common level
1576 * @param array $options
1579 * Provided options are valid
1581 public function isValidOption($options) {
1590 if (empty($options)) {
1594 foreach (array_keys($options) as $option) {
1595 if (!in_array($option, $validOptions)) {
1605 * Execute a query and get the single result.
1607 * @param string $query
1608 * Query to be executed.
1609 * @param array $params
1610 * @param bool $abort
1611 * @param bool $i18nRewrite
1612 * @return string|null
1613 * the result of the query if any
1616 public static function &singleValueQuery(
1622 $queryStr = self
::composeQuery($query, $params, $abort);
1624 static $_dao = NULL;
1627 $_dao = new CRM_Core_DAO();
1630 $_dao->query($queryStr, $i18nRewrite);
1632 $result = $_dao->getDatabaseResult();
1635 $row = $result->fetchRow();
1645 * Compose the query by merging the parameters into it.
1647 * @param string $query
1648 * @param array $params
1649 * @param bool $abort
1652 * @throws CRM_Core_Exception
1654 public static function composeQuery($query, $params = [], $abort = TRUE) {
1656 foreach ($params as $key => $item) {
1657 if (is_numeric($key)) {
1658 if (CRM_Utils_Type
::validate($item[0], $item[1]) !== NULL) {
1659 $item[0] = self
::escapeString($item[0]);
1660 if ($item[1] == 'String' ||
1661 $item[1] == 'Memo' ||
1664 // Support class constants stipulating wildcard characters and/or
1665 // non-quoting of strings. Also support legacy code which may be
1666 // passing in TRUE or 1 for $item[2], which used to indicate the
1667 // use of wildcard characters.
1668 if (!empty($item[2])) {
1669 if ($item[2] & CRM_Core_DAO
::QUERY_FORMAT_WILDCARD ||
$item[2] === TRUE) {
1670 $item[0] = "'%{$item[0]}%'";
1672 elseif (!($item[2] & CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
)) {
1673 $item[0] = "'{$item[0]}'";
1677 $item[0] = "'{$item[0]}'";
1681 if (($item[1] == 'Date' ||
$item[1] == 'Timestamp') &&
1682 strlen($item[0]) == 0
1687 $tr['%' . $key] = $item[0];
1690 throw new CRM_Core_Exception("{$item[0]} is not of type {$item[1]}");
1695 return strtr($query, $tr);
1701 public static function freeResult($ids = NULL) {
1702 global $_DB_DATAOBJECT;
1705 if (!$_DB_DATAOBJECT ||
1706 !isset($_DB_DATAOBJECT['RESULTS'])
1710 $ids = array_keys($_DB_DATAOBJECT['RESULTS']);
1713 foreach ($ids as $id) {
1714 if (isset($_DB_DATAOBJECT['RESULTS'][$id])) {
1715 $_DB_DATAOBJECT['RESULTS'][$id]->free();
1716 unset($_DB_DATAOBJECT['RESULTS'][$id]);
1719 if (isset($_DB_DATAOBJECT['RESULTFIELDS'][$id])) {
1720 unset($_DB_DATAOBJECT['RESULTFIELDS'][$id]);
1726 * Make a shallow copy of an object and all the fields in the object.
1728 * @param string $daoName
1730 * @param array $criteria
1731 * Array of all the fields & values.
1732 * on which basis to copy
1733 * @param array $newData
1734 * Array of all the fields & values.
1735 * to be copied besides the other fields
1736 * @param string $fieldsFix
1737 * Array of fields that you want to prefix/suffix/replace.
1738 * @param string $blockCopyOfDependencies
1739 * Fields that you want to block from.
1741 * @param bool $blockCopyofCustomValues
1742 * Case when you don't want to copy the custom values set in a
1743 * template as it will override/ignore the submitted custom values
1745 * @return CRM_Core_DAO|bool
1746 * the newly created copy of the object. False if none created.
1748 public static function copyGeneric($daoName, $criteria, $newData = NULL, $fieldsFix = NULL, $blockCopyOfDependencies = NULL, $blockCopyofCustomValues = FALSE) {
1749 $object = new $daoName();
1752 $object->id
= $criteria['id'];
1755 foreach ($criteria as $key => $value) {
1756 $object->$key = $value;
1761 while ($object->fetch()) {
1763 // all the objects except with $blockCopyOfDependencies set
1764 // be copied - addresses #CRM-1962
1766 if ($blockCopyOfDependencies && $object->$blockCopyOfDependencies) {
1770 $newObject = new $daoName();
1772 $fields = $object->fields();
1773 if (!is_array($fieldsFix)) {
1774 $fieldsToPrefix = [];
1775 $fieldsToSuffix = [];
1776 $fieldsToReplace = [];
1778 if (!empty($fieldsFix['prefix'])) {
1779 $fieldsToPrefix = $fieldsFix['prefix'];
1781 if (!empty($fieldsFix['suffix'])) {
1782 $fieldsToSuffix = $fieldsFix['suffix'];
1784 if (!empty($fieldsFix['replace'])) {
1785 $fieldsToReplace = $fieldsFix['replace'];
1788 foreach ($fields as $name => $value) {
1789 if ($name == 'id' ||
$value['name'] == 'id') {
1790 // copy everything but the id!
1794 $dbName = $value['name'];
1795 $type = CRM_Utils_Type
::typeToString($value['type']);
1796 $newObject->$dbName = $object->$dbName;
1797 if (isset($fieldsToPrefix[$dbName])) {
1798 $newObject->$dbName = $fieldsToPrefix[$dbName] . $newObject->$dbName;
1800 if (isset($fieldsToSuffix[$dbName])) {
1801 $newObject->$dbName .= $fieldsToSuffix[$dbName];
1803 if (isset($fieldsToReplace[$dbName])) {
1804 $newObject->$dbName = $fieldsToReplace[$dbName];
1807 if ($type == 'Timestamp' ||
$type == 'Date') {
1808 $newObject->$dbName = CRM_Utils_Date
::isoToMysql($newObject->$dbName);
1812 $newObject->copyValues($newData);
1816 if (!$blockCopyofCustomValues) {
1817 $newObject->copyCustomFields($object->id
, $newObject->id
);
1819 CRM_Utils_Hook
::post('create', CRM_Core_DAO_AllCoreTables
::getBriefName($daoName), $newObject->id
, $newObject);
1826 * Method that copies custom fields values from an old entity to a new one.
1828 * Fixes bug CRM-19302,
1829 * where if a custom field of File type was present, left both events using the same file,
1830 * breaking download URL's for the old event.
1832 * @todo the goal here is to clean this up so that it works for any entity. Copy Generic already DOES some custom field stuff
1833 * but it seems to be bypassed & perhaps less good than this (or this just duplicates it...)
1835 * @param int $entityID
1836 * @param int $newEntityID
1838 public function copyCustomFields($entityID, $newEntityID) {
1839 $entity = CRM_Core_DAO_AllCoreTables
::getBriefName(get_class($this));
1840 $tableName = CRM_Core_DAO_AllCoreTables
::getTableForClass(get_class($this));
1841 // Obtain custom values for old event
1842 $customParams = $htmlType = [];
1843 $customValues = CRM_Core_BAO_CustomValueTable
::getEntityValues($entityID, $entity);
1845 // If custom values present, we copy them
1846 if (!empty($customValues)) {
1847 // Get Field ID's and identify File type attributes, to handle file copying.
1848 $fieldIds = implode(', ', array_keys($customValues));
1849 $sql = "SELECT id FROM civicrm_custom_field WHERE html_type = 'File' AND id IN ( {$fieldIds} )";
1850 $result = CRM_Core_DAO
::executeQuery($sql);
1852 // Build array of File type fields
1853 while ($result->fetch()) {
1854 $htmlType[] = $result->id
;
1857 // Build params array of custom values
1858 foreach ($customValues as $field => $value) {
1859 if ($value !== NULL) {
1860 // Handle File type attributes
1861 if (in_array($field, $htmlType)) {
1862 $fileValues = CRM_Core_BAO_File
::path($value, $entityID);
1863 $customParams["custom_{$field}_-1"] = [
1864 'name' => CRM_Utils_File
::duplicate($fileValues[0]),
1865 'type' => $fileValues[1],
1868 // Handle other types
1870 $customParams["custom_{$field}_-1"] = $value;
1875 // Save Custom Fields for new Event
1876 CRM_Core_BAO_CustomValueTable
::postProcess($customParams, $tableName, $newEntityID, $entity);
1879 // copy activity attachments ( if any )
1880 CRM_Core_BAO_File
::copyEntityFile($tableName, $entityID, $tableName, $newEntityID);
1884 * Cascade update through related entities.
1886 * @param string $daoName
1889 * @param array $newData
1891 * @return CRM_Core_DAO|null
1893 public static function cascadeUpdate($daoName, $fromId, $toId, $newData = []) {
1894 $object = new $daoName();
1895 $object->id
= $fromId;
1897 if ($object->find(TRUE)) {
1898 $newObject = new $daoName();
1899 $newObject->id
= $toId;
1901 if ($newObject->find(TRUE)) {
1902 $fields = $object->fields();
1903 foreach ($fields as $name => $value) {
1904 if ($name == 'id' ||
$value['name'] == 'id') {
1905 // copy everything but the id!
1909 $colName = $value['name'];
1910 $newObject->$colName = $object->$colName;
1912 if (substr($name, -5) == '_date' ||
1913 substr($name, -10) == '_date_time'
1915 $newObject->$colName = CRM_Utils_Date
::isoToMysql($newObject->$colName);
1918 foreach ($newData as $k => $v) {
1919 $newObject->$k = $v;
1929 * Given the component id, compute the contact id
1930 * since its used for things like send email
1932 * @param $componentIDs
1933 * @param string $tableName
1934 * @param string $idField
1938 public static function getContactIDsFromComponent($componentIDs, $tableName, $idField = 'id') {
1941 if (empty($componentIDs)) {
1945 $IDs = implode(',', $componentIDs);
1949 WHERE $idField IN ( $IDs )
1952 $dao = CRM_Core_DAO
::executeQuery($query);
1953 while ($dao->fetch()) {
1954 $contactIDs[] = $dao->contact_id
;
1960 * Fetch object based on array of properties.
1962 * @param string $daoName
1963 * Name of the dao object.
1964 * @param string $fieldIdName
1965 * @param int $fieldId
1967 * @param array $returnProperities
1968 * An assoc array of fields that need to be returned, eg array( 'first_name', 'last_name').
1971 * an object of type referenced by daoName
1973 public static function commonRetrieveAll($daoName, $fieldIdName = 'id', $fieldId, &$details, $returnProperities = NULL) {
1974 require_once str_replace('_', DIRECTORY_SEPARATOR
, $daoName) . ".php";
1975 $object = new $daoName();
1976 $object->$fieldIdName = $fieldId;
1978 // return only specific fields if returnproperties are sent
1979 if (!empty($returnProperities)) {
1980 $object->selectAdd();
1981 $object->selectAdd('id');
1982 $object->selectAdd(implode(',', $returnProperities));
1986 while ($object->fetch()) {
1988 self
::storeValues($object, $defaults);
1989 $details[$object->id
] = $defaults;
1996 * Drop all CiviCRM tables.
1998 * @throws \CRM_Core_Exception
2000 public static function dropAllTables() {
2002 // first drop all the custom tables we've created
2003 CRM_Core_BAO_CustomGroup
::dropAllTables();
2005 // drop all multilingual views
2006 CRM_Core_I18n_Schema
::dropAllViews();
2008 CRM_Utils_File
::sourceSQLFile(CIVICRM_DSN
,
2009 dirname(__FILE__
) . DIRECTORY_SEPARATOR
.
2010 '..' . DIRECTORY_SEPARATOR
.
2011 '..' . DIRECTORY_SEPARATOR
.
2012 'sql' . DIRECTORY_SEPARATOR
.
2013 'civicrm_drop.mysql'
2022 public static function escapeString($string) {
2023 static $_dao = NULL;
2025 // If this is an atypical case (e.g. preparing .sql file before CiviCRM
2026 // has been installed), then we fallback DB-less str_replace escaping, as
2027 // we can't use mysqli_real_escape_string, as there is no DB connection.
2028 // Note: In typical usage, escapeString() will only check one conditional
2029 // ("if !$_dao") rather than two conditionals ("if !defined(DSN)")
2030 if (!defined('CIVICRM_DSN')) {
2031 // See http://php.net/manual/en/mysqli.real-escape-string.php for the
2032 // list of characters mysqli_real_escape_string escapes.
2033 $search = ["\\", "\x00", "\n", "\r", "'", '"', "\x1a"];
2034 $replace = ["\\\\", "\\0", "\\n", "\\r", "\'", '\"', "\\Z"];
2035 return str_replace($search, $replace, $string);
2037 $_dao = new CRM_Core_DAO();
2039 return $_dao->escape($string);
2043 * Escape a list of strings for use with "WHERE X IN (...)" queries.
2045 * @param array $strings
2046 * @param string $default
2047 * the value to use if $strings has no elements.
2049 * eg "abc","def","ghi"
2051 public static function escapeStrings($strings, $default = NULL) {
2052 static $_dao = NULL;
2054 $_dao = new CRM_Core_DAO();
2057 if (empty($strings)) {
2061 $escapes = array_map([$_dao, 'escape'], $strings);
2062 return '"' . implode('","', $escapes) . '"';
2070 public static function escapeWildCardString($string) {
2072 // ensure we escape the single characters % and _ which are mysql wild
2073 // card characters and could come in via sortByCharacter
2074 // note that mysql does not escape these characters
2075 if ($string && in_array($string,
2076 ['%', '_', '%%', '_%']
2079 return '\\' . $string;
2082 return self
::escapeString($string);
2086 * Creates a test object, including any required objects it needs via recursion
2087 * createOnly: only create in database, do not store or return the objects (useful for perf testing)
2088 * ONLY USE FOR TESTING
2090 * @param string $daoName
2091 * @param array $params
2092 * @param int $numObjects
2093 * @param bool $createOnly
2095 * @return object|array|NULL
2096 * NULL if $createOnly. A single object if $numObjects==1. Otherwise, an array of multiple objects.
2098 public static function createTestObject(
2104 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
2105 // so we re-set here in case
2106 $config = CRM_Core_Config
::singleton();
2107 $config->backtrace
= TRUE;
2109 static $counter = 0;
2110 CRM_Core_DAO
::$_testEntitiesToSkip = [
2111 'CRM_Core_DAO_Worldregion',
2112 'CRM_Core_DAO_StateProvince',
2113 'CRM_Core_DAO_Country',
2114 'CRM_Core_DAO_Domain',
2115 'CRM_Financial_DAO_FinancialType',
2116 //because valid ones exist & we use pick them due to pseudoconstant can't reliably create & delete these
2119 // Prefer to instantiate BAO's instead of DAO's (when possible)
2120 // so that assignTestValue()/assignTestFK() can be overloaded.
2121 $baoName = str_replace('_DAO_', '_BAO_', $daoName);
2122 if ($baoName === 'CRM_Financial_BAO_FinancialTrxn') {
2123 // OMG OMG OMG this is so incredibly bad. The BAO is insanely named.
2124 // @todo create a new class called what the BAO SHOULD be
2125 // that extends BAO-crazy-name.... migrate.
2126 $baoName = 'CRM_Core_BAO_FinancialTrxn';
2128 if (class_exists($baoName)) {
2129 $daoName = $baoName;
2132 for ($i = 0; $i < $numObjects; ++
$i) {
2135 /** @var CRM_Core_DAO $object */
2136 $object = new $daoName();
2138 $fields = $object->fields();
2139 foreach ($fields as $fieldName => $fieldDef) {
2140 $dbName = $fieldDef['name'];
2141 $FKClassName = $fieldDef['FKClassName'] ??
NULL;
2143 if (isset($params[$dbName]) && !is_array($params[$dbName])) {
2144 $object->$dbName = $params[$dbName];
2147 elseif ($dbName != 'id') {
2148 if ($FKClassName != NULL) {
2149 $object->assignTestFK($fieldName, $fieldDef, $params);
2153 $object->assignTestValue($fieldName, $fieldDef, $counter);
2161 $objects[$i] = $object;
2171 elseif ($numObjects == 1) {
2180 * Deletes the this object plus any dependent objects that are associated with it.
2181 * ONLY USE FOR TESTING
2183 * @param string $daoName
2184 * @param array $params
2186 public static function deleteTestObjects($daoName, $params = []) {
2187 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
2188 // so we re-set here in case
2189 $config = CRM_Core_Config
::singleton();
2190 $config->backtrace
= TRUE;
2192 $object = new $daoName();
2193 $object->id
= $params['id'] ??
NULL;
2195 // array(array(0 => $daoName, 1 => $daoParams))
2197 if ($object->find(TRUE)) {
2199 $fields = $object->fields();
2200 foreach ($fields as $name => $value) {
2202 $dbName = $value['name'];
2204 $FKClassName = $value['FKClassName'] ??
NULL;
2205 $required = $value['required'] ??
NULL;
2206 if ($FKClassName != NULL
2208 && !in_array($FKClassName, CRM_Core_DAO
::$_testEntitiesToSkip)
2209 && ($required ||
$dbName == 'contact_id')
2210 //I'm a bit stuck on this one - we might need to change the singleValueAlter so that the entities don't share a contact
2211 // to make this test process pass - line below makes pass for now
2212 && $dbName != 'member_of_contact_id'
2215 $deletions[] = [$FKClassName, ['id' => $object->$dbName]];
2222 foreach ($deletions as $deletion) {
2223 CRM_Core_DAO
::deleteTestObjects($deletion[0], $deletion[1]);
2228 * Set defaults when creating new entity.
2229 * (don't call this set defaults as already in use with different signature in some places)
2231 * @param array $params
2234 public static function setCreateDefaults(&$params, $defaults) {
2235 if (!empty($params['id'])) {
2238 foreach ($defaults as $key => $value) {
2239 if (!array_key_exists($key, $params) ||
$params[$key] === NULL) {
2240 $params[$key] = $value;
2246 * @param string $prefix
2247 * @param bool $addRandomString
2248 * @param null $string
2252 * @see CRM_Utils_SQL_TempTable
2254 public static function createTempTableName($prefix = 'civicrm', $addRandomString = TRUE, $string = NULL) {
2255 CRM_Core_Error
::deprecatedFunctionWarning('Use CRM_Utils_SQL_TempTable interface to create temporary tables');
2256 $tableName = $prefix . "_temp";
2258 if ($addRandomString) {
2260 $tableName .= "_" . $string;
2263 $tableName .= "_" . md5(uniqid('', TRUE));
2271 * @param bool $trigger
2275 public static function checkTriggerViewPermission($view = TRUE, $trigger = TRUE) {
2276 if (\Civi
::settings()->get('logging_no_trigger_permission')) {
2279 // test for create view and trigger permissions and if allowed, add the option to go multilingual
2281 // I'm not sure why we use the getStaticProperty for an error, rather than checking for DB_Error
2282 $dao = new CRM_Core_DAO();
2284 $result = $dao->query('CREATE OR REPLACE VIEW civicrm_domain_view AS SELECT * FROM civicrm_domain');
2285 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError') ||
is_a($result, 'DB_Error')) {
2291 $result = $dao->query('CREATE TRIGGER civicrm_domain_trigger BEFORE INSERT ON civicrm_domain FOR EACH ROW BEGIN END');
2292 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError') ||
is_a($result, 'DB_Error')) {
2294 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
2299 $dao->query('DROP TRIGGER IF EXISTS civicrm_domain_trigger');
2300 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
2302 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
2309 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
2310 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
2319 * @param null $message
2320 * @param bool $printDAO
2322 public static function debugPrint($message = NULL, $printDAO = TRUE) {
2323 CRM_Utils_System
::xMemory("{$message}: ");
2326 global $_DB_DATAOBJECT;
2328 foreach (array_keys($_DB_DATAOBJECT['RESULTS']) as $id) {
2329 $q[] = $_DB_DATAOBJECT['RESULTS'][$id]->query
;
2331 CRM_Core_Error
::debug('_DB_DATAOBJECT', $q);
2336 * Build a list of triggers via hook and add them to (err, reconcile them
2337 * with) the database.
2339 * @param string $tableName
2340 * the specific table requiring a rebuild; or NULL to rebuild all tables.
2341 * @param bool $force
2346 public static function triggerRebuild($tableName = NULL, $force = FALSE) {
2347 Civi
::service('sql_triggers')->rebuild($tableName, $force);
2351 * Because sql functions are sometimes lost, esp during db migration, we check here to avoid numerous support requests
2352 * @see http://issues.civicrm.org/jira/browse/CRM-13822
2353 * TODO: Alternative solutions might be
2354 * * Stop using functions and find another way to strip numeric characters from phones
2355 * * Give better error messages (currently a missing fn fatals with "unknown error")
2357 public static function checkSqlFunctionsExist() {
2358 if (!self
::$_checkedSqlFunctionsExist) {
2359 self
::$_checkedSqlFunctionsExist = TRUE;
2360 $dao = CRM_Core_DAO
::executeQuery("SHOW function status WHERE db = database() AND name = 'civicrm_strip_non_numeric'");
2361 if (!$dao->fetch()) {
2362 self
::triggerRebuild();
2368 * Wrapper function to drop triggers.
2370 * @param string $tableName
2371 * the specific table requiring a rebuild; or NULL to rebuild all tables.
2374 public static function dropTriggers($tableName = NULL) {
2375 Civi
::service('sql_triggers')->dropTriggers($tableName);
2379 * @param array $info
2380 * per hook_civicrm_triggerInfo.
2381 * @param string $onlyTableName
2382 * the specific table requiring a rebuild; or NULL to rebuild all tables.
2385 public static function createTriggers(&$info, $onlyTableName = NULL) {
2386 Civi
::service('sql_triggers')->createTriggers($info, $onlyTableName);
2390 * Given a list of fields, create a list of references.
2392 * @param string $className
2393 * BAO/DAO class name.
2394 * @return array<CRM_Core_Reference_Interface>
2396 public static function createReferenceColumns($className) {
2398 $fields = $className::fields();
2399 foreach ($fields as $field) {
2400 if (isset($field['pseudoconstant'], $field['pseudoconstant']['optionGroupName'])) {
2401 $result[] = new CRM_Core_Reference_OptionValue(
2402 $className::getTableName(),
2404 'civicrm_option_value',
2405 CRM_Utils_Array
::value('keyColumn', $field['pseudoconstant'], 'value'),
2406 $field['pseudoconstant']['optionGroupName']
2414 * Find all records which refer to this entity.
2417 * Array of objects referencing this
2419 public function findReferences() {
2420 $links = self
::getReferencesToTable(static::getTableName());
2423 foreach ($links as $refSpec) {
2424 /** @var $refSpec CRM_Core_Reference_Interface */
2425 $daoName = CRM_Core_DAO_AllCoreTables
::getClassForTable($refSpec->getReferenceTable());
2426 $result = $refSpec->findReferences($this);
2428 while ($result->fetch()) {
2429 $obj = new $daoName();
2430 $obj->id
= $result->id
;
2431 $occurrences[] = $obj;
2436 return $occurrences;
2441 * each item has keys:
2445 * - table: string|null SQL table name
2446 * - key: string|null SQL column name
2448 public function getReferenceCounts() {
2449 $links = self
::getReferencesToTable(static::getTableName());
2452 foreach ($links as $refSpec) {
2453 /** @var $refSpec CRM_Core_Reference_Interface */
2454 $count = $refSpec->getReferenceCount($this);
2455 if ($count['count'] != 0) {
2460 foreach (CRM_Core_Component
::getEnabledComponents() as $component) {
2461 /** @var $component CRM_Core_Component_Info */
2462 $counts = array_merge($counts, $component->getReferenceCounts($this));
2464 CRM_Utils_Hook
::referenceCounts($this, $counts);
2470 * List all tables which have hard foreign keys to this table.
2472 * For now, this returns a description of every entity_id/entity_table
2474 * TODO: filter dynamic entity references on the $tableName, based on
2475 * schema metadata in dynamicForeignKey which enumerates a restricted
2476 * set of possible entity_table's.
2478 * @param string $tableName
2479 * Table referred to.
2482 * structure of table and column, listing every table with a
2483 * foreign key reference to $tableName, and the column where the key appears.
2485 public static function getReferencesToTable($tableName) {
2487 foreach (CRM_Core_DAO_AllCoreTables
::getClasses() as $daoClassName) {
2488 $links = $daoClassName::getReferenceColumns();
2490 foreach ($links as $refSpec) {
2491 /** @var $refSpec CRM_Core_Reference_Interface */
2492 if ($refSpec->matchesTargetTable($tableName)) {
2493 $refsFound[] = $refSpec;
2501 * Get all references to contact table.
2503 * This includes core tables, custom group tables, tables added by the merge
2504 * hook and the entity_tag table.
2506 * Refer to CRM-17454 for information on the danger of querying the information
2507 * schema to derive this.
2509 * @throws \CiviCRM_API3_Exception
2511 public static function getReferencesToContactTable() {
2512 if (isset(\Civi
::$statics[__CLASS__
]) && isset(\Civi
::$statics[__CLASS__
]['contact_references'])) {
2513 return \Civi
::$statics[__CLASS__
]['contact_references'];
2515 $contactReferences = [];
2516 $coreReferences = CRM_Core_DAO
::getReferencesToTable('civicrm_contact');
2517 foreach ($coreReferences as $coreReference) {
2518 if (!is_a($coreReference, 'CRM_Core_Reference_Dynamic')) {
2519 $contactReferences[$coreReference->getReferenceTable()][] = $coreReference->getReferenceKey();
2522 self
::appendCustomTablesExtendingContacts($contactReferences);
2523 self
::appendCustomContactReferenceFields($contactReferences);
2524 \Civi
::$statics[__CLASS__
]['contact_references'] = $contactReferences;
2525 return \Civi
::$statics[__CLASS__
]['contact_references'];
2529 * Get all dynamic references to the given table.
2531 * @param string $tableName
2535 public static function getDynamicReferencesToTable($tableName) {
2536 if (!isset(\Civi
::$statics[__CLASS__
]['contact_references_dynamic'][$tableName])) {
2537 \Civi
::$statics[__CLASS__
]['contact_references_dynamic'][$tableName] = [];
2538 $coreReferences = CRM_Core_DAO
::getReferencesToTable($tableName);
2539 foreach ($coreReferences as $coreReference) {
2540 if ($coreReference instanceof \CRM_Core_Reference_Dynamic
) {
2541 \Civi
::$statics[__CLASS__
]['contact_references_dynamic'][$tableName][$coreReference->getReferenceTable()][] = [$coreReference->getReferenceKey(), $coreReference->getTypeColumn()];
2545 return \Civi
::$statics[__CLASS__
]['contact_references_dynamic'][$tableName];
2549 * Add custom tables that extend contacts to the list of contact references.
2551 * CRM_Core_BAO_CustomGroup::getAllCustomGroupsByBaseEntity seems like a safe-ish
2552 * function to be sure all are retrieved & we don't miss subtypes or inactive or multiples
2553 * - the down side is it is not cached.
2555 * Further changes should be include tests in the CRM_Core_MergerTest class
2556 * to ensure that disabled, subtype, multiple etc groups are still captured.
2558 * @param array $cidRefs
2560 public static function appendCustomTablesExtendingContacts(&$cidRefs) {
2561 $customValueTables = CRM_Core_BAO_CustomGroup
::getAllCustomGroupsByBaseEntity('Contact');
2562 $customValueTables->find();
2563 while ($customValueTables->fetch()) {
2564 $cidRefs[$customValueTables->table_name
][] = 'entity_id';
2569 * Add custom ContactReference fields to the list of contact references
2571 * This includes active and inactive fields/groups
2573 * @param array $cidRefs
2575 * @throws \CiviCRM_API3_Exception
2577 public static function appendCustomContactReferenceFields(&$cidRefs) {
2578 $fields = civicrm_api3('CustomField', 'get', [
2579 'return' => ['column_name', 'custom_group_id.table_name'],
2580 'data_type' => 'ContactReference',
2581 'options' => ['limit' => 0],
2583 foreach ($fields as $field) {
2584 $cidRefs[$field['custom_group_id.table_name']][] = $field['column_name'];
2589 * Lookup the value of a MySQL global configuration variable.
2591 * @param string $name
2592 * E.g. "thread_stack".
2593 * @param mixed $default
2596 public static function getGlobalSetting($name, $default = NULL) {
2597 // Alternatively, SELECT @@GLOBAL.thread_stack, but
2598 // that has been reported to fail under MySQL 5.0 for OS X
2599 $escapedName = self
::escapeString($name);
2600 $dao = CRM_Core_DAO
::executeQuery("SHOW VARIABLES LIKE '$escapedName'");
2601 if ($dao->fetch()) {
2610 * Update the fields array to also hold keys for pseudoconstant fields that relate to contained fields.
2612 * This is relevant where we want to offer both the ID field and the label field
2613 * as an option, e.g. search builder.
2615 * It is currently limited for optionGroupName & id+ name+ FK combos for purposes keeping the scope of the
2616 * change small, but is appropriate for other sorts of pseudoconstants.
2618 * @param array $fields
2620 public static function appendPseudoConstantsToFields(&$fields) {
2621 foreach ($fields as $fieldUniqueName => $field) {
2622 if (!empty($field['pseudoconstant'])) {
2623 $pseudoConstant = $field['pseudoconstant'];
2624 if (!empty($pseudoConstant['optionGroupName'])) {
2625 $fields[$pseudoConstant['optionGroupName']] = [
2626 'title' => CRM_Core_BAO_OptionGroup
::getTitleByName($pseudoConstant['optionGroupName']),
2627 'name' => $pseudoConstant['optionGroupName'],
2628 'data_type' => CRM_Utils_Type
::T_STRING
,
2629 'is_pseudofield_for' => $fieldUniqueName,
2632 // We restrict to id + name + FK as we are extending this a bit, but cautiously.
2634 !empty($field['FKClassName'])
2635 && CRM_Utils_Array
::value('keyColumn', $pseudoConstant) === 'id'
2636 && CRM_Utils_Array
::value('labelColumn', $pseudoConstant) === 'name'
2638 $pseudoFieldName = str_replace('_' . $pseudoConstant['keyColumn'], '', $field['name']);
2639 // This if is just an extra caution when adding change.
2640 if (!isset($fields[$pseudoFieldName])) {
2641 $daoName = $field['FKClassName'];
2642 $fkFields = $daoName::fields();
2643 foreach ($fkFields as $fkField) {
2644 if ($fkField['name'] === $pseudoConstant['labelColumn']) {
2645 $fields[$pseudoFieldName] = [
2646 'name' => $pseudoFieldName,
2647 'is_pseudofield_for' => $field['name'],
2648 'title' => $fkField['title'],
2649 'data_type' => $fkField['type'],
2650 'where' => $field['where'],
2661 * Get options for the called BAO object's field.
2663 * This function can be overridden by each BAO to add more logic related to context.
2664 * The overriding function will generally call the lower-level CRM_Core_PseudoConstant::get
2666 * @param string $fieldName
2667 * @param string $context
2668 * @see CRM_Core_DAO::buildOptionsContext
2669 * @param array $props
2670 * Raw field values; whatever is known about this bao object.
2672 * Note: $props can contain unsanitized input and should not be passed directly to CRM_Core_PseudoConstant::get
2674 * @return array|bool
2676 public static function buildOptions($fieldName, $context = NULL, $props = []) {
2677 // If a given bao does not override this function
2678 $baoName = get_called_class();
2679 return CRM_Core_PseudoConstant
::get($baoName, $fieldName, [], $context);
2683 * Populate option labels for this object's fields.
2685 * @throws exception if called directly on the base class
2687 public function getOptionLabels() {
2688 $fields = $this->fields();
2689 if ($fields === NULL) {
2690 throw new Exception('Cannot call getOptionLabels on CRM_Core_DAO');
2692 foreach ($fields as $field) {
2693 $name = $field['name'] ??
NULL;
2694 if ($name && isset($this->$name)) {
2695 $label = CRM_Core_PseudoConstant
::getLabel(get_class($this), $name, $this->$name);
2696 if ($label !== FALSE) {
2697 // Append 'label' onto the field name
2698 $labelName = $name . '_label';
2699 $this->$labelName = $label;
2706 * Provides documentation and validation for the buildOptions $context param
2708 * @param string $context
2710 * @throws CRM_Core_Exception
2713 public static function buildOptionsContext($context = NULL) {
2715 'get' => "get: all options are returned, even if they are disabled; labels are translated.",
2716 'create' => "create: options are filtered appropriately for the object being created/updated; labels are translated.",
2717 'search' => "search: searchable options are returned; labels are translated.",
2718 'validate' => "validate: all options are returned, even if they are disabled; machine names are used in place of labels.",
2719 'abbreviate' => "abbreviate: enabled options are returned; labels are replaced with abbreviations.",
2720 'match' => "match: enabled options are returned using machine names as keys; labels are translated.",
2722 // Validation: enforce uniformity of this param
2723 if ($context !== NULL && !isset($contexts[$context])) {
2724 throw new CRM_Core_Exception("'$context' is not a valid context for buildOptions.");
2730 * @param string $fieldName
2731 * @return bool|array
2733 public function getFieldSpec($fieldName) {
2734 $fields = $this->fields();
2736 // Support "unique names" as well as sql names
2737 $fieldKey = $fieldName;
2738 if (empty($fields[$fieldKey])) {
2739 $fieldKeys = $this->fieldKeys();
2740 $fieldKey = $fieldKeys[$fieldName] ??
NULL;
2742 // If neither worked then this field doesn't exist. Return false.
2743 if (empty($fields[$fieldKey])) {
2746 return $fields[$fieldKey];
2750 * Get SQL where clause for SQL filter syntax input parameters.
2752 * SQL version of api function to assign filters to the DAO based on the syntax
2753 * $field => array('IN' => array(4,6,9))
2755 * $field => array('LIKE' => array('%me%))
2758 * @param string $fieldName
2760 * @param array $filter
2761 * filter to be applied indexed by operator.
2762 * @param string $type
2763 * type of field (not actually used - nor in api @todo ).
2764 * @param string $alias
2765 * alternative field name ('as') @todo- not actually used.
2766 * @param bool $returnSanitisedArray
2767 * Return a sanitised array instead of a clause.
2768 * this is primarily so we can add filters @ the api level to the Query object based fields
2772 * @return NULL|string|array
2773 * a string is returned if $returnSanitisedArray is not set, otherwise and Array or NULL
2774 * depending on whether it is supported as yet
2776 public static function createSQLFilter($fieldName, $filter, $type = NULL, $alias = NULL, $returnSanitisedArray = FALSE) {
2777 foreach ($filter as $operator => $criteria) {
2778 if (!CRM_Core_BAO_SchemaHandler
::databaseSupportsUTF8MB4()) {
2779 foreach ((array) $criteria as $criterion) {
2780 if (!empty($criterion) && !is_numeric($criterion)
2781 // The first 2 criteria are redundant but are added as they
2782 // seem like they would
2783 // be quicker than this 3rd check.
2784 && max(array_map('ord', str_split($criterion))) >= 240) {
2785 // String contains unsupported emojis.
2786 // We return a clause that resolves to false as an emoji string by definition cannot be saved.
2787 // note that if we return just 0 for false if gets lost in empty checks.
2788 // https://stackoverflow.com/questions/16496554/can-php-detect-4-byte-encoded-utf8-chars
2794 if (in_array($operator, self
::acceptedSQLOperators(), TRUE)) {
2795 switch ($operator) {
2799 if (!$returnSanitisedArray) {
2800 return (sprintf('%s %s', $fieldName, $operator));
2803 return (sprintf('%s %s ', $fieldName, $operator));
2807 // ternary operators
2810 if ((empty($criteria[0]) && !in_array($criteria[0], ['0', 0]))||
(empty($criteria[1]) && !in_array($criteria[1], ['0', 0]))) {
2811 throw new Exception("invalid criteria for $operator");
2813 if (!$returnSanitisedArray) {
2814 return (sprintf('%s ' . $operator . ' "%s" AND "%s"', $fieldName, CRM_Core_DAO
::escapeString($criteria[0]), CRM_Core_DAO
::escapeString($criteria[1])));
2817 // not yet implemented (tests required to implement)
2825 if (empty($criteria)) {
2826 throw new Exception("invalid criteria for $operator");
2828 $escapedCriteria = array_map([
2832 if (!$returnSanitisedArray) {
2833 return (sprintf('%s %s ("%s")', $fieldName, $operator, implode('", "', $escapedCriteria)));
2835 return $escapedCriteria;
2840 if (!$returnSanitisedArray) {
2841 return (sprintf('%s %s "%s"', $fieldName, $operator, CRM_Core_DAO
::escapeString($criteria)));
2844 // not yet implemented (tests required to implement)
2853 * @see http://issues.civicrm.org/jira/browse/CRM-9150
2854 * support for other syntaxes is discussed in ticket but being put off for now
2857 public static function acceptedSQLOperators() {
2878 * SQL has a limit of 64 characters on various names:
2879 * table name, trigger name, column name ...
2881 * For custom groups and fields we generated names from user entered input
2882 * which can be longer than this length, this function helps with creating
2883 * strings that meet various criteria.
2885 * @param string $string
2886 * The string to be shortened.
2887 * @param int $length
2888 * The max length of the string.
2890 * @param bool $makeRandom
2894 public static function shortenSQLName($string, $length = 60, $makeRandom = FALSE) {
2895 // early return for strings that meet the requirements
2896 if (strlen($string) <= $length) {
2900 // easy return for calls that dont need a randomized uniq string
2902 return substr($string, 0, $length);
2905 // the string is longer than the length and we need a uniq string
2906 // for the same tablename we need the same uniq string every time
2907 // hence we use md5 on the string, which is not random
2908 // we'll append 8 characters to the end of the tableName
2909 $md5string = substr(md5($string), 0, 8);
2910 return substr($string, 0, $length - 8) . "_{$md5string}";
2914 * https://issues.civicrm.org/jira/browse/CRM-17748
2915 * Sets the internal options to be used on a query
2917 * @param array $options
2920 public function setOptions($options) {
2921 if (is_array($options)) {
2922 $this->_options
= $options;
2927 * https://issues.civicrm.org/jira/browse/CRM-17748
2928 * wrapper to pass internal DAO options down to DB_mysql/DB_Common level
2930 * @param array $options
2933 protected function _setDBOptions($options) {
2934 global $_DB_DATAOBJECT;
2936 if (is_array($options) && count($options)) {
2937 $conn = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5
];
2938 foreach ($options as $option_name => $option_value) {
2939 $conn->setOption($option_name, $option_value);
2946 * @param array $params
2948 public function setApiFilter(&$params) {
2952 * Generates acl clauses suitable for adding to WHERE or ON when doing an api.get for this entity
2954 * Return format is in the form of fieldname => clauses starting with an operator. e.g.:
2957 * 'location_type_id' => array('IS NOT NULL', 'IN (1,2,3)')
2961 * Note that all array keys must be actual field names in this entity. Use subqueries to filter on other tables e.g. custom values.
2965 public function addSelectWhereClause() {
2967 $fields = $this->fields();
2968 foreach ($fields as $fieldName => $field) {
2969 // Clause for contact-related entities like Email, Relationship, etc.
2970 if (strpos($fieldName, 'contact_id') === 0 && CRM_Utils_Array
::value('FKClassName', $field) == 'CRM_Contact_DAO_Contact') {
2971 $clauses[$fieldName] = CRM_Utils_SQL
::mergeSubquery('Contact');
2973 // Clause for an entity_table/entity_id combo
2974 if ($fieldName == 'entity_id' && isset($fields['entity_table'])) {
2975 $relatedClauses = [];
2976 $relatedEntities = $this->buildOptions('entity_table', 'get');
2977 foreach ((array) $relatedEntities as $table => $ent) {
2979 $ent = CRM_Core_DAO_AllCoreTables
::getBriefName(CRM_Core_DAO_AllCoreTables
::getClassForTable($table));
2980 $subquery = CRM_Utils_SQL
::mergeSubquery($ent);
2982 $relatedClauses[] = "(entity_table = '$table' AND entity_id " . implode(' AND entity_id ', $subquery) . ")";
2985 $relatedClauses[] = "(entity_table = '$table')";
2989 if ($relatedClauses) {
2990 $clauses['id'] = 'IN (SELECT id FROM `' . $this->tableName() . '` WHERE (' . implode(') OR (', $relatedClauses) . '))';
2994 CRM_Utils_Hook
::selectWhereClause($this, $clauses);
2999 * This returns the final permissioned query string for this entity
3001 * With acls from related entities + additional clauses from hook_civicrm_selectWhereClause
3003 * @param string $tableAlias
3006 public static function getSelectWhereClause($tableAlias = NULL) {
3007 $bao = new static();
3008 if ($tableAlias === NULL) {
3009 $tableAlias = $bao->tableName();
3012 foreach ((array) $bao->addSelectWhereClause() as $field => $vals) {
3013 $clauses[$field] = NULL;
3015 $clauses[$field] = "(`$tableAlias`.`$field` IS NULL OR (`$tableAlias`.`$field` " . implode(" AND `$tableAlias`.`$field` ", (array) $vals) . '))';
3022 * ensure database name is 'safe', i.e. only contains word characters (includes underscores)
3023 * and dashes, and contains at least one [a-z] case insenstive.
3029 public static function requireSafeDBName($database) {
3032 "/^[\w\-]*[a-z]+[\w\-]*$/i",
3036 if (empty($matches)) {
3043 * Transform an array to a serialized string for database storage.
3045 * @param array|null $value
3046 * @param int $serializationType
3047 * @return string|null
3049 * @throws \Exception
3051 public static function serializeField($value, $serializationType) {
3052 if ($value === NULL) {
3055 switch ($serializationType) {
3056 case self
::SERIALIZE_SEPARATOR_BOOKEND
:
3057 return $value === [] ?
'' : CRM_Utils_Array
::implodePadded($value);
3059 case self
::SERIALIZE_SEPARATOR_TRIMMED
:
3060 return is_array($value) ?
implode(self
::VALUE_SEPARATOR
, $value) : $value;
3062 case self
::SERIALIZE_JSON
:
3063 return is_array($value) ?
json_encode($value) : $value;
3065 case self
::SERIALIZE_PHP
:
3066 return is_array($value) ?
serialize($value) : $value;
3068 case self
::SERIALIZE_COMMA
:
3069 return is_array($value) ?
implode(',', $value) : $value;
3072 throw new Exception('Unknown serialization method for field.');
3077 * Transform a serialized string from the database into an array.
3079 * @param string|null $value
3080 * @param $serializationType
3082 * @return array|null
3083 * @throws CRM_Core_Exception
3085 public static function unSerializeField($value, $serializationType) {
3086 if ($value === NULL) {
3089 if ($value === '') {
3092 switch ($serializationType) {
3093 case self
::SERIALIZE_SEPARATOR_BOOKEND
:
3094 return (array) CRM_Utils_Array
::explodePadded($value);
3096 case self
::SERIALIZE_SEPARATOR_TRIMMED
:
3097 return explode(self
::VALUE_SEPARATOR
, trim($value));
3099 case self
::SERIALIZE_JSON
:
3100 return strlen($value) ?
json_decode($value, TRUE) : [];
3102 case self
::SERIALIZE_PHP
:
3103 return strlen($value) ? CRM_Utils_String
::unserialize($value) : [];
3105 case self
::SERIALIZE_COMMA
:
3106 return explode(',', trim(str_replace(', ', '', $value)));
3109 throw new CRM_Core_Exception('Unknown serialization method for field.');
3116 public static function getEntityRefFilters() {
3121 * Get exportable fields with pseudoconstants rendered as an extra field.
3123 * @param string $baoClass
3127 public static function getExportableFieldsWithPseudoConstants($baoClass) {
3128 if (method_exists($baoClass, 'exportableFields')) {
3129 $fields = $baoClass::exportableFields();
3132 $fields = $baoClass::export();
3134 CRM_Core_DAO
::appendPseudoConstantsToFields($fields);
3139 * Remove item from static cache during update/delete operations
3141 private function clearDbColumnValueCache() {
3142 $daoName = get_class($this);
3143 while (strpos($daoName, '_BAO_') !== FALSE) {
3144 $daoName = get_parent_class($daoName);
3146 if (isset($this->id
)) {
3147 unset(self
::$_dbColumnValueCache[$daoName]['id'][$this->id
]);
3149 if (isset($this->name
)) {
3150 unset(self
::$_dbColumnValueCache[$daoName]['name'][$this->name
]);
3155 * Return a mapping from field-name to the corresponding key (as used in fields()).
3158 * Array(string $name => string $uniqueName).
3160 public static function fieldKeys() {
3161 return array_flip(CRM_Utils_Array
::collect('name', static::fields()));
3165 * Returns system paths related to this entity (as defined in the xml schema)
3169 public static function getEntityPaths() {
3170 return static::$_paths ??
[];