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.
126 public static function getEntityTitle() {
127 $className = static::class;
128 Civi
::log()->warning("$className needs to be regeneraged. Missing getEntityTitle method.", ['civi.tag' => 'deprecated']);
129 return CRM_Core_DAO_AllCoreTables
::getBriefName($className);
132 public function __clone() {
133 if (!empty($this->_DB_resultid
)) {
134 $this->resultCopies++
;
141 public function __destruct() {
142 if ($this->resultCopies
=== 0) {
145 $this->resultCopies
--;
149 * Empty definition for virtual function.
151 public static function getTableName() {
156 * Initialize the DAO object.
159 * The database connection string.
161 public static function init($dsn) {
162 Civi
::$statics[__CLASS__
]['init'] = 1;
163 $options = &PEAR
::getStaticProperty('DB_DataObject', 'options');
164 $options['database'] = $dsn;
165 $options['quote_identifiers'] = TRUE;
166 if (CRM_Utils_SQL
::isSSLDSN($dsn)) {
167 // There are two different options arrays.
168 $other_options = &PEAR
::getStaticProperty('DB', 'options');
169 $other_options['ssl'] = TRUE;
171 if (defined('CIVICRM_DAO_DEBUG')) {
172 self
::DebugLevel(CIVICRM_DAO_DEBUG
);
174 $factory = new CRM_Contact_DAO_Factory();
175 CRM_Core_DAO
::setFactory($factory);
176 $currentModes = CRM_Utils_SQL
::getSqlModes();
177 if (CRM_Utils_Constant
::value('CIVICRM_MYSQL_STRICT', CRM_Utils_System
::isDevelopment())) {
178 if (CRM_Utils_SQL
::supportsFullGroupBy() && !in_array('ONLY_FULL_GROUP_BY', $currentModes) && CRM_Utils_SQL
::isGroupByModeInDefault()) {
179 $currentModes[] = 'ONLY_FULL_GROUP_BY';
181 if (!in_array('STRICT_TRANS_TABLES', $currentModes)) {
182 $currentModes = array_merge(['STRICT_TRANS_TABLES'], $currentModes);
184 CRM_Core_DAO
::executeQuery("SET SESSION sql_mode = %1", [1 => [implode(',', $currentModes), 'String']]);
186 CRM_Core_DAO
::executeQuery('SET NAMES utf8mb4');
187 CRM_Core_DAO
::executeQuery('SET @uniqueID = %1', [1 => [CRM_Utils_Request
::id(), 'String']]);
193 public static function getConnection() {
194 global $_DB_DATAOBJECT;
195 $dao = new CRM_Core_DAO();
196 return $_DB_DATAOBJECT['CONNECTIONS'][$dao->_database_dsn_md5
];
200 * Disables usage of the ONLY_FULL_GROUP_BY Mode if necessary
202 public static function disableFullGroupByMode() {
203 $currentModes = CRM_Utils_SQL
::getSqlModes();
204 if (in_array('ONLY_FULL_GROUP_BY', $currentModes) && CRM_Utils_SQL
::isGroupByModeInDefault()) {
205 $key = array_search('ONLY_FULL_GROUP_BY', $currentModes);
206 unset($currentModes[$key]);
207 CRM_Core_DAO
::executeQuery("SET SESSION sql_mode = %1", [1 => [implode(',', $currentModes), 'String']]);
212 * Re-enables ONLY_FULL_GROUP_BY sql_mode as necessary..
214 public static function reenableFullGroupByMode() {
215 $currentModes = CRM_Utils_SQL
::getSqlModes();
216 if (!in_array('ONLY_FULL_GROUP_BY', $currentModes) && CRM_Utils_SQL
::isGroupByModeInDefault()) {
217 $currentModes[] = 'ONLY_FULL_GROUP_BY';
218 CRM_Core_DAO
::executeQuery("SET SESSION sql_mode = %1", [1 => [implode(',', $currentModes), 'String']]);
223 * @param string $fieldName
225 * @param array $params
227 protected function assignTestFK($fieldName, $fieldDef, $params) {
228 $required = $fieldDef['required'] ??
NULL;
229 $FKClassName = $fieldDef['FKClassName'] ??
NULL;
230 $dbName = $fieldDef['name'];
231 $daoName = str_replace('_BAO_', '_DAO_', get_class($this));
233 // skip the FK if it is not required
234 // if it's contact id we should create even if not required
235 // we'll have a go @ fetching first though
236 // we WILL create campaigns though for so tests with a campaign pseudoconstant will complete
237 if ($FKClassName === 'CRM_Campaign_DAO_Campaign' && $daoName != $FKClassName) {
240 if (!$required && $dbName != 'contact_id') {
241 $fkDAO = new $FKClassName();
242 if ($fkDAO->find(TRUE)) {
243 $this->$dbName = $fkDAO->id
;
247 elseif (in_array($FKClassName, CRM_Core_DAO
::$_testEntitiesToSkip)) {
248 $depObject = new $FKClassName();
249 $depObject->find(TRUE);
250 $this->$dbName = $depObject->id
;
252 elseif ($daoName == 'CRM_Member_DAO_MembershipType' && $fieldName == 'member_of_contact_id') {
253 // FIXME: the fields() metadata is not specific enough
254 $depObject = CRM_Core_DAO
::createTestObject($FKClassName, ['contact_type' => 'Organization']);
255 $this->$dbName = $depObject->id
;
258 //if it is required we need to generate the dependency object first
259 $depObject = CRM_Core_DAO
::createTestObject($FKClassName, CRM_Utils_Array
::value($dbName, $params, 1));
260 $this->$dbName = $depObject->id
;
265 * Generate and assign an arbitrary value to a field of a test object.
267 * @param string $fieldName
268 * @param array $fieldDef
269 * @param int $counter
270 * The globally-unique ID of the test object.
272 * @throws \CRM_Core_Exception
274 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
275 $dbName = $fieldDef['name'];
276 $daoName = get_class($this);
279 if (!$handled && $dbName == 'contact_sub_type') {
280 //coming up with a rule to set this is too complex let's not set it
284 // Pick an option value if needed
285 if (!$handled && $fieldDef['type'] !== CRM_Utils_Type
::T_BOOLEAN
) {
286 $options = $daoName::buildOptions($dbName, 'create');
288 $this->$dbName = key($options);
294 switch ($fieldDef['type']) {
295 case CRM_Utils_Type
::T_INT
:
296 case CRM_Utils_Type
::T_FLOAT
:
297 case CRM_Utils_Type
::T_MONEY
:
298 if (isset($fieldDef['precision'])) {
299 // $object->$dbName = CRM_Utils_Number::createRandomDecimal($value['precision']);
300 $this->$dbName = CRM_Utils_Number
::createTruncatedDecimal($counter, $fieldDef['precision']);
303 $this->$dbName = $counter;
307 case CRM_Utils_Type
::T_BOOLEAN
:
308 if (isset($fieldDef['default'])) {
309 $this->$dbName = $fieldDef['default'];
311 elseif ($fieldDef['name'] == 'is_deleted' ||
$fieldDef['name'] == 'is_test') {
319 case CRM_Utils_Type
::T_DATE
:
320 case CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
:
321 $this->$dbName = '19700101';
322 if ($dbName == 'end_date') {
323 // put this in the future
324 $this->$dbName = '20200101';
328 case CRM_Utils_Type
::T_TIMESTAMP
:
329 $this->$dbName = '19700201000000';
332 case CRM_Utils_Type
::T_TIME
:
333 throw new CRM_Core_Exception('T_TIME shouldn\'t be used.');
335 case CRM_Utils_Type
::T_CCNUM
:
336 $this->$dbName = '4111 1111 1111 1111';
339 case CRM_Utils_Type
::T_URL
:
340 $this->$dbName = 'http://www.civicrm.org';
343 case CRM_Utils_Type
::T_STRING
:
344 case CRM_Utils_Type
::T_BLOB
:
345 case CRM_Utils_Type
::T_MEDIUMBLOB
:
346 case CRM_Utils_Type
::T_TEXT
:
347 case CRM_Utils_Type
::T_LONGTEXT
:
348 case CRM_Utils_Type
::T_EMAIL
:
350 // WAS: if (isset($value['enumValues'])) {
351 // TODO: see if this works with all pseudoconstants
352 if (isset($fieldDef['pseudoconstant'], $fieldDef['pseudoconstant']['callback'])) {
353 if (isset($fieldDef['default'])) {
354 $this->$dbName = $fieldDef['default'];
357 $options = CRM_Core_PseudoConstant
::get($daoName, $fieldName);
358 if (is_array($options)) {
359 $this->$dbName = $options[0];
362 $defaultValues = explode(',', $options);
363 $this->$dbName = $defaultValues[0];
368 $this->$dbName = $dbName . '_' . $counter;
369 $maxlength = $fieldDef['maxlength'] ??
NULL;
370 if ($maxlength > 0 && strlen($this->$dbName) > $maxlength) {
371 $this->$dbName = substr($this->$dbName, 0, $fieldDef['maxlength']);
379 * Reset the DAO object.
381 * DAO is kinda crappy in that there is an unwritten rule of one query per DAO.
383 * We attempt to get around this crappy restriction by resetting some of DAO's internal fields. Use this with caution
385 public function reset() {
387 foreach (array_keys($this->table()) as $field) {
388 unset($this->$field);
392 * reset the various DB_DAO structures manually
401 * @param string $tableName
405 public static function getLocaleTableName($tableName) {
408 $tables = CRM_Core_I18n_Schema
::schemaStructureTables();
409 if (in_array($tableName, $tables)) {
410 return $tableName . $dbLocale;
417 * Execute a query by the current DAO, localizing it along the way (if needed).
419 * @param string $query
420 * The SQL query for execution.
421 * @param bool $i18nRewrite
422 * Whether to rewrite the query.
425 * the current DAO object after the query execution
427 public function query($query, $i18nRewrite = TRUE) {
428 // rewrite queries that should use $dbLocale-based views for multi-language installs
429 global $dbLocale, $_DB_DATAOBJECT;
431 if (empty($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5
])) {
432 // Will force connection to be populated per CRM-20541.
436 $conn = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5
];
437 $orig_options = $conn->options
;
438 $this->_setDBOptions($this->_options
);
440 if ($i18nRewrite and $dbLocale) {
441 $query = CRM_Core_I18n_Schema
::rewriteQuery($query);
444 $ret = parent
::query($query);
446 $this->_setDBOptions($orig_options);
451 * Static function to set the factory instance for this class.
453 * @param object $factory
454 * The factory application object.
456 public static function setFactory(&$factory) {
457 self
::$_factory = &$factory;
461 * Factory method to instantiate a new object from a table name.
463 * @param string $table
464 * @return \DataObject|\PEAR_Error
466 public function factory($table = '') {
467 if (!isset(self
::$_factory)) {
468 return parent
::factory($table);
471 return self
::$_factory->create($table);
475 * Initialization for all DAO objects. Since we access DB_DO programatically
476 * we need to set the links manually.
478 public function initialize() {
480 if (empty(Civi
::$statics[__CLASS__
]['init'])) {
481 // CRM_Core_DAO::init() must be called before CRM_Core_DAO->initialize().
482 // This occurs very early in bootstrap - error handlers may not be wired up.
483 echo "Inconsistent system initialization sequence. Premature access of (" . get_class($this) . ")";
484 CRM_Utils_System
::civiExit();
489 * Defines the default key as 'id'.
493 public function keys() {
502 * Tells DB_DataObject which keys use autoincrement.
503 * 'id' is autoincrementing by default.
508 public function sequenceKey() {
509 static $sequenceKeys;
510 if (!isset($sequenceKeys)) {
511 $sequenceKeys = ['id', TRUE];
513 return $sequenceKeys;
517 * Returns list of FK relationships.
521 * Array of CRM_Core_Reference_Interface
523 public static function getReferenceColumns() {
528 * Returns all the column names of this table.
533 public static function &fields() {
539 * Returns all usable fields, indexed by name.
541 * This function differs from fields() in that it indexes by name rather than unique_name.
543 * It excludes fields not added yet by pending upgrades.
544 * This avoids problems with trying to SELECT a field that exists in code but has not yet been added to the db.
546 * @param bool $checkPermissions
547 * Filter by field permissions.
550 public static function getSupportedFields($checkPermissions = FALSE) {
551 $fields = array_column((array) static::fields(), NULL, 'name');
553 // Exclude fields yet not added by pending upgrades
554 $dbVer = \CRM_Core_BAO_Domain
::version();
555 $daoExt = defined(static::class . '::EXT') ?
constant(static::class . '::EXT') : NULL;
556 if ($fields && $daoExt === 'civicrm' && version_compare($dbVer, \CRM_Utils_System
::version()) < 0) {
557 $fields = array_filter($fields, function($field) use ($dbVer) {
558 $add = $field['add'] ??
'1.0.0';
559 if (substr_count($add, '.') < 2) {
562 return version_compare($dbVer, $add, '>=');
566 // Exclude fields the user does not have permission for
567 if ($checkPermissions) {
568 $fields = array_filter($fields, function($field) {
569 return empty($field['permission']) || CRM_Core_Permission
::check($field['permission']);
577 * Get/set an associative array of table columns
582 public function table() {
583 $fields = $this->fields();
587 foreach ($fields as $name => $value) {
588 $table[$value['name']] = $value['type'];
589 if (!empty($value['required'])) {
590 $table[$value['name']] +
= self
::DB_DAO_NOTNULL
;
603 * @return CRM_Core_DAO
605 public function save($hook = TRUE) {
606 if (!empty($this->id
)) {
608 $preEvent = new \Civi\Core\DAO\Event\
PreUpdate($this);
609 \Civi
::dispatcher()->dispatch("civi.dao.preUpdate", $preEvent);
612 $result = $this->update();
615 $event = new \Civi\Core\DAO\Event\
PostUpdate($this, $result);
616 \Civi
::dispatcher()->dispatch("civi.dao.postUpdate", $event);
618 $this->clearDbColumnValueCache();
622 $preEvent = new \Civi\Core\DAO\Event\
PreUpdate($this);
623 \Civi
::dispatcher()->dispatch("civi.dao.preInsert", $preEvent);
626 $result = $this->insert();
629 $event = new \Civi\Core\DAO\Event\
PostUpdate($this, $result);
630 \Civi
::dispatcher()->dispatch("civi.dao.postInsert", $event);
636 CRM_Utils_Hook
::postSave($this);
643 * Deletes items from table which match current objects variables.
645 * Returns the true on success
649 * Designed to be extended
651 * $object = new mytable();
653 * echo $object->delete(); // builds a conditon
655 * $object = new mytable();
656 * $object->whereAdd('age > 12');
658 * $object->orderBy('age DESC');
659 * $object->delete(true); // dont use object vars, use the conditions, limit and order.
661 * @param bool $useWhere (optional) If DB_DATAOBJECT_WHEREADD_ONLY is passed in then
662 * we will build the condition only using the whereAdd's. Default is to
663 * build the condition only using the object parameters.
665 * * @return mixed Int (No. of rows affected) on success, false on failure, 0 on no data affected
667 public function delete($useWhere = FALSE) {
668 $preEvent = new \Civi\Core\DAO\Event\
PreDelete($this);
669 \Civi
::dispatcher()->dispatch("civi.dao.preDelete", $preEvent);
671 $result = parent
::delete($useWhere);
673 $event = new \Civi\Core\DAO\Event\
PostDelete($this, $result);
674 \Civi
::dispatcher()->dispatch("civi.dao.postDelete", $event);
677 $this->clearDbColumnValueCache();
683 * @param bool $created
685 public function log($created = FALSE) {
688 if (!$this->getLog()) {
693 $session = CRM_Core_Session
::singleton();
694 $cid = $session->get('userID');
697 // return is we dont have handle to FK
702 $dao = new CRM_Core_DAO_Log();
703 $dao->entity_table
= $this->getTableName();
704 $dao->entity_id
= $this->id
;
705 $dao->modified_id
= $cid;
706 $dao->modified_date
= date("YmdHis");
711 * Given an associative array of name/value pairs, extract all the values
712 * that belong to this object and initialize the object with said values
714 * @param array $params
715 * Array of name/value pairs to save.
718 * Did we copy all null values into the object
720 public function copyValues($params) {
722 foreach ($this->fields() as $uniqueName => $field) {
723 $dbName = $field['name'];
724 if (array_key_exists($dbName, $params)) {
725 $value = $params[$dbName];
728 elseif (array_key_exists($uniqueName, $params)) {
729 $value = $params[$uniqueName];
736 // if there is no value then make the variable NULL
739 $this->$dbName = 'null';
741 elseif (is_array($value) && !empty($field['serialize'])) {
742 $this->$dbName = CRM_Core_DAO
::serializeField($value, $field['serialize']);
746 $maxLength = $field['maxlength'] ??
NULL;
747 if (!is_array($value) && $maxLength && mb_strlen($value) > $maxLength && empty($field['pseudoconstant'])) {
748 Civi
::log()->warning(ts('A string for field $dbName has been truncated. The original string was %1', [CRM_Utils_Type
::escape($value, 'String')]));
749 // The string is too long - what to do what to do? Well losing data is generally bad so lets' truncate
750 $value = CRM_Utils_String
::ellipsify($value, $maxLength);
752 $this->$dbName = $value;
761 * Store all the values from this object in an associative array
762 * this is a destructive store, calling function is responsible
763 * for keeping sanity of id's.
765 * @param object $object
766 * The object that we are extracting data from.
767 * @param array $values
768 * (reference ) associative array of name/value pairs.
770 public static function storeValues(&$object, &$values) {
771 $fields = $object->fields();
772 foreach ($fields as $name => $value) {
773 $dbName = $value['name'];
774 if (isset($object->$dbName) && $object->$dbName !== 'null') {
775 $values[$dbName] = $object->$dbName;
776 if ($name != $dbName) {
777 $values[$name] = $object->$dbName;
784 * Create an attribute for this specific field. We only do this for strings and text
786 * @param array $field
787 * The field under task.
790 * the attributes for the object
792 public static function makeAttribute($field) {
794 if (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_STRING
) {
795 $maxLength = $field['maxlength'] ??
NULL;
796 $size = $field['size'] ??
NULL;
797 if ($maxLength ||
$size) {
800 $attributes['maxlength'] = $maxLength;
803 $attributes['size'] = $size;
808 elseif (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_TEXT
) {
809 $rows = $field['rows'] ??
NULL;
813 $cols = $field['cols'] ??
NULL;
819 $attributes['rows'] = $rows;
820 $attributes['cols'] = $cols;
823 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
) {
824 $attributes['size'] = 6;
825 $attributes['maxlength'] = 14;
833 * Get the size and maxLength attributes for this text field.
834 * (or for all text fields) in the DAO object.
836 * @param string $class
838 * @param string $fieldName
839 * Field that i'm interested in or null if.
840 * you want the attributes for all DAO text fields
843 * assoc array of name => attribute pairs
845 public static function getAttribute($class, $fieldName = NULL) {
846 $object = new $class();
847 $fields = $object->fields();
848 if ($fieldName != NULL) {
849 $field = $fields[$fieldName] ??
NULL;
850 return self
::makeAttribute($field);
854 foreach ($fields as $name => $field) {
855 $attribute = self
::makeAttribute($field);
857 $attributes[$name] = $attribute;
861 if (!empty($attributes)) {
869 * Create or update a record from supplied params.
871 * If 'id' is supplied, an existing record will be updated
872 * Otherwise a new record will be created.
874 * @param array $record
875 * @return CRM_Core_DAO
876 * @throws CRM_Core_Exception
878 public static function writeRecord(array $record) {
879 $hook = empty($record['id']) ?
'create' : 'edit';
880 $className = CRM_Core_DAO_AllCoreTables
::getCanonicalClassName(static::class);
881 if ($className === 'CRM_Core_DAO') {
882 throw new CRM_Core_Exception('Function writeRecord must be called on a subclass of CRM_Core_DAO');
884 $entityName = CRM_Core_DAO_AllCoreTables
::getBriefName($className);
886 \CRM_Utils_Hook
::pre($hook, $entityName, $record['id'] ??
NULL, $record);
887 $instance = new $className();
888 $instance->copyValues($record);
890 \CRM_Utils_Hook
::post($hook, $entityName, $instance->id
, $instance);
896 * Delete a record from supplied params.
898 * @param array $record
900 * @return CRM_Core_DAO
901 * @throws CRM_Core_Exception
903 public static function deleteRecord(array $record) {
904 $className = CRM_Core_DAO_AllCoreTables
::getCanonicalClassName(static::class);
905 if ($className === 'CRM_Core_DAO') {
906 throw new CRM_Core_Exception('Function deleteRecord must be called on a subclass of CRM_Core_DAO');
908 $entityName = CRM_Core_DAO_AllCoreTables
::getBriefName($className);
909 if (empty($record['id'])) {
910 throw new CRM_Core_Exception("Cannot delete {$entityName} with no id.");
913 CRM_Utils_Hook
::pre('delete', $entityName, $record['id'], $record);
914 $instance = new $className();
915 $instance->id
= $record['id'];
916 if (!$instance->delete()) {
917 throw new CRM_Core_Exception("Could not delete {$entityName} id {$record['id']}");
919 CRM_Utils_Hook
::post('delete', $entityName, $record['id'], $instance);
925 * Check if there is a record with the same name in the db.
927 * @param string $value
928 * The value of the field we are checking.
929 * @param string $daoName
930 * The dao object name.
931 * @param string $daoID
932 * The id of the object being updated. u can change your name.
933 * as long as there is no conflict
934 * @param string $fieldName
935 * The name of the field in the DAO.
937 * @param string $domainID
938 * The id of the domain. Object exists only for the given domain.
941 * true if object exists
943 public static function objectExists($value, $daoName, $daoID, $fieldName = 'name', $domainID = NULL) {
944 $object = new $daoName();
945 $object->$fieldName = $value;
947 $object->domain_id
= $domainID;
950 if ($object->find(TRUE)) {
951 return $daoID && $object->id
== $daoID;
959 * Check if there is a given column in a specific table.
962 * @see CRM_Core_BAO_SchemaHandler::checkIfFieldExists
964 * @param string $tableName
965 * @param string $columnName
966 * @param bool $i18nRewrite
967 * Whether to rewrite the query on multilingual setups.
970 * true if exists, else false
972 public static function checkFieldExists($tableName, $columnName, $i18nRewrite = TRUE) {
973 CRM_Core_Error
::deprecatedFunctionWarning('CRM_Core_BAO_SchemaHandler::checkIfFieldExists');
974 return CRM_Core_BAO_SchemaHandler
::checkIfFieldExists($tableName, $columnName, $i18nRewrite);
978 * Scans all the tables using a slow query and table name.
982 public static function getTableNames() {
983 $dao = CRM_Core_DAO
::executeQuery(
985 FROM information_schema.TABLES
986 WHERE TABLE_SCHEMA = '" . CRM_Core_DAO
::getDatabaseName() . "'
987 AND TABLE_NAME LIKE 'civicrm_%'
988 AND TABLE_NAME NOT LIKE 'civicrm_import_job_%'
989 AND TABLE_NAME NOT LIKE '%_temp%'
992 while ($dao->fetch()) {
993 $values[] = $dao->TABLE_NAME
;
999 * @param int $maxTablesToCheck
1003 public static function isDBMyISAM($maxTablesToCheck = 10) {
1004 return CRM_Core_DAO
::singleValueQuery(
1006 FROM information_schema.TABLES
1007 WHERE ENGINE = 'MyISAM'
1008 AND TABLE_SCHEMA = '" . CRM_Core_DAO
::getDatabaseName() . "'
1009 AND TABLE_NAME LIKE 'civicrm_%'
1010 AND TABLE_NAME NOT LIKE 'civicrm_import_job_%'
1011 AND TABLE_NAME NOT LIKE '%_temp%'
1012 AND TABLE_NAME NOT LIKE 'civicrm_tmp_%'
1017 * Get the name of the CiviCRM database.
1021 public static function getDatabaseName() {
1022 $daoObj = new CRM_Core_DAO();
1023 return $daoObj->database();
1027 * Checks if a constraint exists for a specified table.
1029 * @param string $tableName
1030 * @param string $constraint
1033 * true if constraint exists, false otherwise
1035 * @throws \CRM_Core_Exception
1037 public static function checkConstraintExists($tableName, $constraint) {
1040 if (!array_key_exists($tableName, $show)) {
1041 $query = "SHOW CREATE TABLE $tableName";
1042 $dao = CRM_Core_DAO
::executeQuery($query, [], TRUE, NULL, FALSE, FALSE);
1044 if (!$dao->fetch()) {
1045 throw new CRM_Core_Exception('query failed');
1048 $show[$tableName] = $dao->Create_Table
;
1051 return (bool) preg_match("/\b$constraint\b/i", $show[$tableName]);
1055 * Checks if CONSTRAINT keyword exists for a specified table.
1057 * @param array $tables
1059 * @throws CRM_Core_Exception
1062 * true if CONSTRAINT keyword exists, false otherwise
1064 public static function schemaRequiresRebuilding($tables = ["civicrm_contact"]) {
1066 foreach ($tables as $tableName) {
1067 if (!array_key_exists($tableName, $show)) {
1068 $query = "SHOW CREATE TABLE $tableName";
1069 $dao = CRM_Core_DAO
::executeQuery($query, [], TRUE, NULL, FALSE, FALSE);
1071 if (!$dao->fetch()) {
1072 throw new CRM_Core_Exception('Show create table failed.');
1075 $show[$tableName] = $dao->Create_Table
;
1078 $result = (bool) preg_match("/\bCONSTRAINT\b\s/i", $show[$tableName]);
1079 if ($result == TRUE) {
1090 * Checks if the FK constraint name is in the format 'FK_tableName_columnName'
1091 * for a specified column of a table.
1093 * @param string $tableName
1094 * @param string $columnName
1097 * true if in format, false otherwise
1099 * @throws \CRM_Core_Exception
1101 public static function checkFKConstraintInFormat($tableName, $columnName) {
1104 if (!array_key_exists($tableName, $show)) {
1105 $query = "SHOW CREATE TABLE $tableName";
1106 $dao = CRM_Core_DAO
::executeQuery($query);
1108 if (!$dao->fetch()) {
1109 throw new CRM_Core_Exception('query failed');
1112 $show[$tableName] = $dao->Create_Table
;
1114 $constraint = "`FK_{$tableName}_{$columnName}`";
1115 $pattern = "/\bCONSTRAINT\b\s+%s\s+\bFOREIGN\s+KEY\b\s/i";
1116 return (bool) preg_match(sprintf($pattern, $constraint), $show[$tableName]);
1120 * Check whether a specific column in a specific table has always the same value.
1122 * @param string $tableName
1123 * @param string $columnName
1124 * @param string $columnValue
1127 * true if the value is always $columnValue, false otherwise
1129 public static function checkFieldHasAlwaysValue($tableName, $columnName, $columnValue) {
1130 $query = "SELECT * FROM $tableName WHERE $columnName != '$columnValue'";
1131 $dao = CRM_Core_DAO
::executeQuery($query);
1132 $result = $dao->fetch() ?
FALSE : TRUE;
1137 * Check whether a specific column in a specific table is always NULL.
1139 * @param string $tableName
1140 * @param string $columnName
1143 * true if if the value is always NULL, false otherwise
1145 public static function checkFieldIsAlwaysNull($tableName, $columnName) {
1146 $query = "SELECT * FROM $tableName WHERE $columnName IS NOT NULL";
1147 $dao = CRM_Core_DAO
::executeQuery($query);
1148 $result = $dao->fetch() ?
FALSE : TRUE;
1153 * Checks if this DAO's table ought to exist.
1155 * If there are pending DB updates, this function compares the CiviCRM version of the table to the current schema version.
1158 * @throws CRM_Core_Exception
1160 public static function tableHasBeenAdded() {
1161 if (CRM_Utils_System
::version() === CRM_Core_BAO_Domain
::version()) {
1164 $daoExt = defined(static::class . '::EXT') ?
constant(static::class . '::EXT') : NULL;
1165 $daoVersion = defined(static::class . '::TABLE_ADDED') ?
constant(static::class . '::TABLE_ADDED') : '1.0';
1166 return !($daoExt === 'civicrm' && version_compare(CRM_Core_BAO_Domain
::version(), $daoVersion, '<'));
1170 * Check if there is a given table in the database.
1172 * @param string $tableName
1175 * true if exists, else false
1177 public static function checkTableExists($tableName) {
1182 $params = [1 => [$tableName, 'String']];
1184 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1185 return (bool) $dao->fetch();
1189 * Check if a given table has data.
1191 * @param string $tableName
1193 * TRUE if $tableName has at least one record.
1195 public static function checkTableHasData($tableName) {
1196 $c = CRM_Core_DAO
::singleValueQuery(sprintf('SELECT count(*) c FROM `%s`', $tableName));
1205 public function checkVersion($version) {
1206 CRM_Core_Error
::deprecatedFunctionWarning('CRM_Core_BAO_Domain::version');
1207 $dbVersion = CRM_Core_BAO_Domain
::version();
1208 return trim($version) == trim($dbVersion);
1212 * Find a DAO object for the given ID and return it.
1215 * Id of the DAO object being searched for.
1217 * @return CRM_Core_DAO
1218 * Object of the type of the class that called this function.
1222 public static function findById($id) {
1223 $object = new static();
1225 if (!$object->find(TRUE)) {
1226 throw new Exception("Unable to find a " . get_called_class() . " with id {$id}.");
1232 * Returns all results as array-encoded records.
1236 public function fetchAll($k = FALSE, $v = FALSE, $method = FALSE) {
1238 while ($this->fetch()) {
1239 $result[] = $this->toArray();
1245 * Return the results as PHP generator.
1247 * @param string $type
1248 * Whether the generator yields 'dao' objects or 'array's.
1250 public function fetchGenerator($type = 'dao') {
1251 while ($this->fetch()) {
1258 yield
$this->toArray();
1262 throw new \
RuntimeException("Invalid record type ($type)");
1268 * Returns a singular value.
1270 * @return mixed|NULL
1272 public function fetchValue() {
1273 $result = $this->getDatabaseResult();
1274 $row = $result->fetchRow();
1284 * Get all the result records as mapping between columns.
1286 * @param string $keyColumn
1288 * @param string $valueColumn
1291 * Ex: ["foo" => "The Foo Bar", "baz" => "The Baz Qux"]
1293 public function fetchMap($keyColumn, $valueColumn) {
1295 while ($this->fetch()) {
1296 $result[$this->{$keyColumn}] = $this->{$valueColumn};
1302 * Given a DAO name, a column name and a column value, find the record and GET the value of another column in that record
1304 * @param string $daoName
1305 * Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact).
1306 * @param int $searchValue
1307 * Value of the column you want to search by.
1308 * @param string $returnColumn
1309 * Name of the column you want to GET the value of.
1310 * @param string $searchColumn
1311 * Name of the column you want to search by.
1312 * @param bool $force
1313 * Skip use of the cache.
1315 * @return string|int|null
1316 * Value of $returnColumn in the retrieved record
1318 * @throws \CRM_Core_Exception
1320 public static function getFieldValue($daoName, $searchValue, $returnColumn = 'name', $searchColumn = 'id', $force = FALSE) {
1322 empty($searchValue) ||
1323 trim(strtolower($searchValue)) == 'null'
1325 // adding this here since developers forget to check for an id
1326 // or for the 'null' (which is a bad DAO kludge)
1327 // and hence we get the first value in the db
1328 throw new CRM_Core_Exception('getFieldValue failed');
1331 self
::$_dbColumnValueCache = self
::$_dbColumnValueCache ??
[];
1333 while (strpos($daoName, '_BAO_') !== FALSE) {
1334 $daoName = get_parent_class($daoName);
1338 empty(self
::$_dbColumnValueCache[$daoName][$searchColumn][$searchValue]) ||
1339 !array_key_exists($returnColumn, self
::$_dbColumnValueCache[$daoName][$searchColumn][$searchValue])
1341 $object = new $daoName();
1342 $object->$searchColumn = $searchValue;
1343 $object->selectAdd();
1344 $object->selectAdd($returnColumn);
1347 if ($object->find(TRUE)) {
1348 $result = $object->$returnColumn;
1351 self
::$_dbColumnValueCache[$daoName][$searchColumn][$searchValue][$returnColumn] = $result;
1353 return self
::$_dbColumnValueCache[$daoName][$searchColumn][$searchValue][$returnColumn];
1357 * Given a DAO name, a column name and a column value, find the record and SET the value of another column in that record
1359 * @param string $daoName
1360 * Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact).
1361 * @param int $searchValue
1362 * Value of the column you want to search by.
1363 * @param string $setColumn
1364 * Name of the column you want to SET the value of.
1365 * @param string $setValue
1366 * SET the setColumn to this value.
1367 * @param string $searchColumn
1368 * Name of the column you want to search by.
1371 * true if we found and updated the object, else false
1373 public static function setFieldValue($daoName, $searchValue, $setColumn, $setValue, $searchColumn = 'id') {
1374 $object = new $daoName();
1375 $object->selectAdd();
1376 $object->selectAdd("$searchColumn, $setColumn");
1377 $object->$searchColumn = $searchValue;
1379 if ($object->find(TRUE)) {
1380 $object->$setColumn = $setValue;
1381 if ($object->save()) {
1392 * @param array|object $sort either array or CRM_Utils_Sort
1393 * @param string $default
1394 * Default sort value.
1398 public static function getSortString($sort, $default = NULL) {
1399 // check if sort is of type CRM_Utils_Sort
1400 if (is_a($sort, 'CRM_Utils_Sort')) {
1401 return $sort->orderBy();
1406 // is it an array specified as $field => $sortDirection ?
1408 foreach ($sort as $k => $v) {
1409 $sortString .= "$k $v,";
1411 return rtrim($sortString, ',');
1417 * Fetch object based on array of properties.
1419 * @param string $daoName
1420 * Name of the dao object.
1421 * @param array $params
1422 * (reference ) an assoc array of name/value pairs.
1423 * @param array $defaults
1424 * (reference ) an assoc array to hold the flattened values.
1425 * @param array $returnProperities
1426 * An assoc array of fields that need to be returned, eg array( 'first_name', 'last_name').
1429 * an object of type referenced by daoName
1431 public static function commonRetrieve($daoName, &$params, &$defaults, $returnProperities = NULL) {
1432 $object = new $daoName();
1433 $object->copyValues($params);
1435 // return only specific fields if returnproperties are sent
1436 if (!empty($returnProperities)) {
1437 $object->selectAdd();
1438 $object->selectAdd(implode(',', $returnProperities));
1441 if ($object->find(TRUE)) {
1442 self
::storeValues($object, $defaults);
1449 * Delete the object records that are associated with this contact.
1451 * @param string $daoName
1452 * Name of the dao object.
1453 * @param int $contactId
1454 * Id of the contact to delete.
1456 public static function deleteEntityContact($daoName, $contactId) {
1457 $object = new $daoName();
1459 $object->entity_table
= 'civicrm_contact';
1460 $object->entity_id
= $contactId;
1465 * Execute an unbuffered query.
1467 * This is a wrapper around new functionality exposed with CRM-17748.
1469 * @param string $query query to be executed
1471 * @param array $params
1472 * @param bool $abort
1473 * @param null $daoName
1474 * @param bool $freeDAO
1475 * @param bool $i18nRewrite
1476 * @param bool $trapException
1478 * @return CRM_Core_DAO
1479 * Object that points to an unbuffered result set
1481 public static function executeUnbufferedQuery(
1487 $i18nRewrite = TRUE,
1488 $trapException = FALSE
1491 return self
::executeQuery(
1499 ['result_buffering' => 0]
1506 * @param string $query
1507 * Query to be executed.
1509 * @param array $params
1510 * @param bool $abort
1511 * @param null $daoName
1512 * @param bool $freeDAO
1513 * @param bool $i18nRewrite
1514 * @param bool $trapException
1515 * @param array $options
1517 * @return CRM_Core_DAO|object
1518 * object that holds the results of the query
1519 * NB - if this is defined as just returning a DAO phpstorm keeps pointing
1520 * out all the properties that are not part of the DAO
1522 public static function &executeQuery(
1528 $i18nRewrite = TRUE,
1529 $trapException = FALSE,
1532 $queryStr = self
::composeQuery($query, $params, $abort);
1535 $dao = new CRM_Core_DAO();
1538 $dao = new $daoName();
1541 if ($trapException) {
1542 CRM_Core_Error
::deprecatedFunctionWarning('calling functions should handle exceptions');
1543 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
1546 if ($dao->isValidOption($options)) {
1547 $dao->setOptions($options);
1550 $result = $dao->query($queryStr, $i18nRewrite);
1552 // since it is unbuffered, ($dao->N==0) is true. This blocks the standard fetch() mechanism.
1553 if (CRM_Utils_Array
::value('result_buffering', $options) === 0) {
1557 if (is_a($result, 'DB_Error')) {
1558 CRM_Core_Error
::deprecatedFunctionWarning('calling functions should handle exceptions');
1566 * Wrapper to validate internal DAO options before passing to DB_mysql/DB_Common level
1568 * @param array $options
1571 * Provided options are valid
1573 public function isValidOption($options) {
1582 if (empty($options)) {
1586 foreach (array_keys($options) as $option) {
1587 if (!in_array($option, $validOptions)) {
1597 * Execute a query and get the single result.
1599 * @param string $query
1600 * Query to be executed.
1601 * @param array $params
1602 * @param bool $abort
1603 * @param bool $i18nRewrite
1604 * @return string|null
1605 * the result of the query if any
1608 public static function &singleValueQuery(
1614 $queryStr = self
::composeQuery($query, $params, $abort);
1616 static $_dao = NULL;
1619 $_dao = new CRM_Core_DAO();
1622 $_dao->query($queryStr, $i18nRewrite);
1624 $result = $_dao->getDatabaseResult();
1627 $row = $result->fetchRow();
1637 * Compose the query by merging the parameters into it.
1639 * @param string $query
1640 * @param array $params
1641 * @param bool $abort
1644 * @throws CRM_Core_Exception
1646 public static function composeQuery($query, $params = [], $abort = TRUE) {
1648 foreach ($params as $key => $item) {
1649 if (is_numeric($key)) {
1650 if (CRM_Utils_Type
::validate($item[0], $item[1]) !== NULL) {
1651 $item[0] = self
::escapeString($item[0]);
1652 if ($item[1] == 'String' ||
1653 $item[1] == 'Memo' ||
1656 // Support class constants stipulating wildcard characters and/or
1657 // non-quoting of strings. Also support legacy code which may be
1658 // passing in TRUE or 1 for $item[2], which used to indicate the
1659 // use of wildcard characters.
1660 if (!empty($item[2])) {
1661 if ($item[2] & CRM_Core_DAO
::QUERY_FORMAT_WILDCARD ||
$item[2] === TRUE) {
1662 $item[0] = "'%{$item[0]}%'";
1664 elseif (!($item[2] & CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
)) {
1665 $item[0] = "'{$item[0]}'";
1669 $item[0] = "'{$item[0]}'";
1673 if (($item[1] == 'Date' ||
$item[1] == 'Timestamp') &&
1674 strlen($item[0]) == 0
1679 $tr['%' . $key] = $item[0];
1682 throw new CRM_Core_Exception("{$item[0]} is not of type {$item[1]}");
1687 return strtr($query, $tr);
1693 public static function freeResult($ids = NULL) {
1694 global $_DB_DATAOBJECT;
1697 if (!$_DB_DATAOBJECT ||
1698 !isset($_DB_DATAOBJECT['RESULTS'])
1702 $ids = array_keys($_DB_DATAOBJECT['RESULTS']);
1705 foreach ($ids as $id) {
1706 if (isset($_DB_DATAOBJECT['RESULTS'][$id])) {
1707 $_DB_DATAOBJECT['RESULTS'][$id]->free();
1708 unset($_DB_DATAOBJECT['RESULTS'][$id]);
1711 if (isset($_DB_DATAOBJECT['RESULTFIELDS'][$id])) {
1712 unset($_DB_DATAOBJECT['RESULTFIELDS'][$id]);
1718 * Make a shallow copy of an object and all the fields in the object.
1720 * @param string $daoName
1722 * @param array $criteria
1723 * Array of all the fields & values.
1724 * on which basis to copy
1725 * @param array $newData
1726 * Array of all the fields & values.
1727 * to be copied besides the other fields
1728 * @param string $fieldsFix
1729 * Array of fields that you want to prefix/suffix/replace.
1730 * @param string $blockCopyOfDependencies
1731 * Fields that you want to block from.
1733 * @param bool $blockCopyofCustomValues
1734 * Case when you don't want to copy the custom values set in a
1735 * template as it will override/ignore the submitted custom values
1737 * @return CRM_Core_DAO|bool
1738 * the newly created copy of the object. False if none created.
1740 public static function copyGeneric($daoName, $criteria, $newData = NULL, $fieldsFix = NULL, $blockCopyOfDependencies = NULL, $blockCopyofCustomValues = FALSE) {
1741 $object = new $daoName();
1744 $object->id
= $criteria['id'];
1747 foreach ($criteria as $key => $value) {
1748 $object->$key = $value;
1753 while ($object->fetch()) {
1755 // all the objects except with $blockCopyOfDependencies set
1756 // be copied - addresses #CRM-1962
1758 if ($blockCopyOfDependencies && $object->$blockCopyOfDependencies) {
1762 $newObject = new $daoName();
1764 $fields = $object->fields();
1765 if (!is_array($fieldsFix)) {
1766 $fieldsToPrefix = [];
1767 $fieldsToSuffix = [];
1768 $fieldsToReplace = [];
1770 if (!empty($fieldsFix['prefix'])) {
1771 $fieldsToPrefix = $fieldsFix['prefix'];
1773 if (!empty($fieldsFix['suffix'])) {
1774 $fieldsToSuffix = $fieldsFix['suffix'];
1776 if (!empty($fieldsFix['replace'])) {
1777 $fieldsToReplace = $fieldsFix['replace'];
1780 foreach ($fields as $name => $value) {
1781 if ($name == 'id' ||
$value['name'] == 'id') {
1782 // copy everything but the id!
1786 $dbName = $value['name'];
1787 $type = CRM_Utils_Type
::typeToString($value['type']);
1788 $newObject->$dbName = $object->$dbName;
1789 if (isset($fieldsToPrefix[$dbName])) {
1790 $newObject->$dbName = $fieldsToPrefix[$dbName] . $newObject->$dbName;
1792 if (isset($fieldsToSuffix[$dbName])) {
1793 $newObject->$dbName .= $fieldsToSuffix[$dbName];
1795 if (isset($fieldsToReplace[$dbName])) {
1796 $newObject->$dbName = $fieldsToReplace[$dbName];
1799 if ($type == 'Timestamp' ||
$type == 'Date') {
1800 $newObject->$dbName = CRM_Utils_Date
::isoToMysql($newObject->$dbName);
1804 $newObject->copyValues($newData);
1808 if (!$blockCopyofCustomValues) {
1809 $newObject->copyCustomFields($object->id
, $newObject->id
);
1811 CRM_Utils_Hook
::post('create', CRM_Core_DAO_AllCoreTables
::getBriefName($daoName), $newObject->id
, $newObject);
1818 * Method that copies custom fields values from an old entity to a new one.
1820 * Fixes bug CRM-19302,
1821 * where if a custom field of File type was present, left both events using the same file,
1822 * breaking download URL's for the old event.
1824 * @todo the goal here is to clean this up so that it works for any entity. Copy Generic already DOES some custom field stuff
1825 * but it seems to be bypassed & perhaps less good than this (or this just duplicates it...)
1827 * @param int $entityID
1828 * @param int $newEntityID
1830 public function copyCustomFields($entityID, $newEntityID) {
1831 $entity = CRM_Core_DAO_AllCoreTables
::getBriefName(get_class($this));
1832 $tableName = CRM_Core_DAO_AllCoreTables
::getTableForClass(get_class($this));
1833 // Obtain custom values for old event
1834 $customParams = $htmlType = [];
1835 $customValues = CRM_Core_BAO_CustomValueTable
::getEntityValues($entityID, $entity);
1837 // If custom values present, we copy them
1838 if (!empty($customValues)) {
1839 // Get Field ID's and identify File type attributes, to handle file copying.
1840 $fieldIds = implode(', ', array_keys($customValues));
1841 $sql = "SELECT id FROM civicrm_custom_field WHERE html_type = 'File' AND id IN ( {$fieldIds} )";
1842 $result = CRM_Core_DAO
::executeQuery($sql);
1844 // Build array of File type fields
1845 while ($result->fetch()) {
1846 $htmlType[] = $result->id
;
1849 // Build params array of custom values
1850 foreach ($customValues as $field => $value) {
1851 if ($value !== NULL) {
1852 // Handle File type attributes
1853 if (in_array($field, $htmlType)) {
1854 $fileValues = CRM_Core_BAO_File
::path($value, $entityID);
1855 $customParams["custom_{$field}_-1"] = [
1856 'name' => CRM_Utils_File
::duplicate($fileValues[0]),
1857 'type' => $fileValues[1],
1860 // Handle other types
1862 $customParams["custom_{$field}_-1"] = $value;
1867 // Save Custom Fields for new Event
1868 CRM_Core_BAO_CustomValueTable
::postProcess($customParams, $tableName, $newEntityID, $entity);
1871 // copy activity attachments ( if any )
1872 CRM_Core_BAO_File
::copyEntityFile($tableName, $entityID, $tableName, $newEntityID);
1876 * Cascade update through related entities.
1878 * @param string $daoName
1881 * @param array $newData
1883 * @return CRM_Core_DAO|null
1885 public static function cascadeUpdate($daoName, $fromId, $toId, $newData = []) {
1886 $object = new $daoName();
1887 $object->id
= $fromId;
1889 if ($object->find(TRUE)) {
1890 $newObject = new $daoName();
1891 $newObject->id
= $toId;
1893 if ($newObject->find(TRUE)) {
1894 $fields = $object->fields();
1895 foreach ($fields as $name => $value) {
1896 if ($name == 'id' ||
$value['name'] == 'id') {
1897 // copy everything but the id!
1901 $colName = $value['name'];
1902 $newObject->$colName = $object->$colName;
1904 if (substr($name, -5) == '_date' ||
1905 substr($name, -10) == '_date_time'
1907 $newObject->$colName = CRM_Utils_Date
::isoToMysql($newObject->$colName);
1910 foreach ($newData as $k => $v) {
1911 $newObject->$k = $v;
1921 * Given the component id, compute the contact id
1922 * since its used for things like send email
1924 * @param $componentIDs
1925 * @param string $tableName
1926 * @param string $idField
1930 public static function getContactIDsFromComponent($componentIDs, $tableName, $idField = 'id') {
1933 if (empty($componentIDs)) {
1937 $IDs = implode(',', $componentIDs);
1941 WHERE $idField IN ( $IDs )
1944 $dao = CRM_Core_DAO
::executeQuery($query);
1945 while ($dao->fetch()) {
1946 $contactIDs[] = $dao->contact_id
;
1952 * Fetch object based on array of properties.
1954 * @param string $daoName
1955 * Name of the dao object.
1956 * @param string $fieldIdName
1957 * @param int $fieldId
1959 * @param array $returnProperities
1960 * An assoc array of fields that need to be returned, eg array( 'first_name', 'last_name').
1963 * an object of type referenced by daoName
1965 public static function commonRetrieveAll($daoName, $fieldIdName = 'id', $fieldId, &$details, $returnProperities = NULL) {
1966 require_once str_replace('_', DIRECTORY_SEPARATOR
, $daoName) . ".php";
1967 $object = new $daoName();
1968 $object->$fieldIdName = $fieldId;
1970 // return only specific fields if returnproperties are sent
1971 if (!empty($returnProperities)) {
1972 $object->selectAdd();
1973 $object->selectAdd('id');
1974 $object->selectAdd(implode(',', $returnProperities));
1978 while ($object->fetch()) {
1980 self
::storeValues($object, $defaults);
1981 $details[$object->id
] = $defaults;
1988 * Drop all CiviCRM tables.
1990 * @throws \CRM_Core_Exception
1992 public static function dropAllTables() {
1994 // first drop all the custom tables we've created
1995 CRM_Core_BAO_CustomGroup
::dropAllTables();
1997 // drop all multilingual views
1998 CRM_Core_I18n_Schema
::dropAllViews();
2000 CRM_Utils_File
::sourceSQLFile(CIVICRM_DSN
,
2001 dirname(__FILE__
) . DIRECTORY_SEPARATOR
.
2002 '..' . DIRECTORY_SEPARATOR
.
2003 '..' . DIRECTORY_SEPARATOR
.
2004 'sql' . DIRECTORY_SEPARATOR
.
2005 'civicrm_drop.mysql'
2014 public static function escapeString($string) {
2015 static $_dao = NULL;
2017 // If this is an atypical case (e.g. preparing .sql file before CiviCRM
2018 // has been installed), then we fallback DB-less str_replace escaping, as
2019 // we can't use mysqli_real_escape_string, as there is no DB connection.
2020 // Note: In typical usage, escapeString() will only check one conditional
2021 // ("if !$_dao") rather than two conditionals ("if !defined(DSN)")
2022 if (!defined('CIVICRM_DSN')) {
2023 // See http://php.net/manual/en/mysqli.real-escape-string.php for the
2024 // list of characters mysqli_real_escape_string escapes.
2025 $search = ["\\", "\x00", "\n", "\r", "'", '"', "\x1a"];
2026 $replace = ["\\\\", "\\0", "\\n", "\\r", "\'", '\"', "\\Z"];
2027 return str_replace($search, $replace, $string);
2029 $_dao = new CRM_Core_DAO();
2031 return $_dao->escape($string);
2035 * Escape a list of strings for use with "WHERE X IN (...)" queries.
2037 * @param array $strings
2038 * @param string $default
2039 * the value to use if $strings has no elements.
2041 * eg "abc","def","ghi"
2043 public static function escapeStrings($strings, $default = NULL) {
2044 static $_dao = NULL;
2046 $_dao = new CRM_Core_DAO();
2049 if (empty($strings)) {
2053 $escapes = array_map([$_dao, 'escape'], $strings);
2054 return '"' . implode('","', $escapes) . '"';
2062 public static function escapeWildCardString($string) {
2064 // ensure we escape the single characters % and _ which are mysql wild
2065 // card characters and could come in via sortByCharacter
2066 // note that mysql does not escape these characters
2067 if ($string && in_array($string,
2068 ['%', '_', '%%', '_%']
2071 return '\\' . $string;
2074 return self
::escapeString($string);
2078 * Creates a test object, including any required objects it needs via recursion
2079 * createOnly: only create in database, do not store or return the objects (useful for perf testing)
2080 * ONLY USE FOR TESTING
2082 * @param string $daoName
2083 * @param array $params
2084 * @param int $numObjects
2085 * @param bool $createOnly
2087 * @return object|array|NULL
2088 * NULL if $createOnly. A single object if $numObjects==1. Otherwise, an array of multiple objects.
2090 public static function createTestObject(
2096 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
2097 // so we re-set here in case
2098 $config = CRM_Core_Config
::singleton();
2099 $config->backtrace
= TRUE;
2101 static $counter = 0;
2102 CRM_Core_DAO
::$_testEntitiesToSkip = [
2103 'CRM_Core_DAO_Worldregion',
2104 'CRM_Core_DAO_StateProvince',
2105 'CRM_Core_DAO_Country',
2106 'CRM_Core_DAO_Domain',
2107 'CRM_Financial_DAO_FinancialType',
2108 //because valid ones exist & we use pick them due to pseudoconstant can't reliably create & delete these
2111 // Prefer to instantiate BAO's instead of DAO's (when possible)
2112 // so that assignTestValue()/assignTestFK() can be overloaded.
2113 $baoName = str_replace('_DAO_', '_BAO_', $daoName);
2114 if ($baoName === 'CRM_Financial_BAO_FinancialTrxn') {
2115 // OMG OMG OMG this is so incredibly bad. The BAO is insanely named.
2116 // @todo create a new class called what the BAO SHOULD be
2117 // that extends BAO-crazy-name.... migrate.
2118 $baoName = 'CRM_Core_BAO_FinancialTrxn';
2120 if (class_exists($baoName)) {
2121 $daoName = $baoName;
2124 for ($i = 0; $i < $numObjects; ++
$i) {
2127 /** @var CRM_Core_DAO $object */
2128 $object = new $daoName();
2130 $fields = $object->fields();
2131 foreach ($fields as $fieldName => $fieldDef) {
2132 $dbName = $fieldDef['name'];
2133 $FKClassName = $fieldDef['FKClassName'] ??
NULL;
2135 if (isset($params[$dbName]) && !is_array($params[$dbName])) {
2136 $object->$dbName = $params[$dbName];
2139 elseif ($dbName != 'id') {
2140 if ($FKClassName != NULL) {
2141 $object->assignTestFK($fieldName, $fieldDef, $params);
2145 $object->assignTestValue($fieldName, $fieldDef, $counter);
2153 $objects[$i] = $object;
2163 elseif ($numObjects == 1) {
2172 * Deletes the this object plus any dependent objects that are associated with it.
2173 * ONLY USE FOR TESTING
2175 * @param string $daoName
2176 * @param array $params
2178 public static function deleteTestObjects($daoName, $params = []) {
2179 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
2180 // so we re-set here in case
2181 $config = CRM_Core_Config
::singleton();
2182 $config->backtrace
= TRUE;
2184 $object = new $daoName();
2185 $object->id
= $params['id'] ??
NULL;
2187 // array(array(0 => $daoName, 1 => $daoParams))
2189 if ($object->find(TRUE)) {
2191 $fields = $object->fields();
2192 foreach ($fields as $name => $value) {
2194 $dbName = $value['name'];
2196 $FKClassName = $value['FKClassName'] ??
NULL;
2197 $required = $value['required'] ??
NULL;
2198 if ($FKClassName != NULL
2200 && !in_array($FKClassName, CRM_Core_DAO
::$_testEntitiesToSkip)
2201 && ($required ||
$dbName == 'contact_id')
2202 //I'm a bit stuck on this one - we might need to change the singleValueAlter so that the entities don't share a contact
2203 // to make this test process pass - line below makes pass for now
2204 && $dbName != 'member_of_contact_id'
2207 $deletions[] = [$FKClassName, ['id' => $object->$dbName]];
2214 foreach ($deletions as $deletion) {
2215 CRM_Core_DAO
::deleteTestObjects($deletion[0], $deletion[1]);
2220 * Set defaults when creating new entity.
2221 * (don't call this set defaults as already in use with different signature in some places)
2223 * @param array $params
2226 public static function setCreateDefaults(&$params, $defaults) {
2227 if (!empty($params['id'])) {
2230 foreach ($defaults as $key => $value) {
2231 if (!array_key_exists($key, $params) ||
$params[$key] === NULL) {
2232 $params[$key] = $value;
2238 * @param string $prefix
2239 * @param bool $addRandomString
2240 * @param null $string
2244 * @see CRM_Utils_SQL_TempTable
2246 public static function createTempTableName($prefix = 'civicrm', $addRandomString = TRUE, $string = NULL) {
2247 CRM_Core_Error
::deprecatedFunctionWarning('Use CRM_Utils_SQL_TempTable interface to create temporary tables');
2248 $tableName = $prefix . "_temp";
2250 if ($addRandomString) {
2252 $tableName .= "_" . $string;
2255 $tableName .= "_" . md5(uniqid('', TRUE));
2263 * @param bool $trigger
2267 public static function checkTriggerViewPermission($view = TRUE, $trigger = TRUE) {
2268 if (\Civi
::settings()->get('logging_no_trigger_permission')) {
2271 // test for create view and trigger permissions and if allowed, add the option to go multilingual
2273 // I'm not sure why we use the getStaticProperty for an error, rather than checking for DB_Error
2274 CRM_Core_TemporaryErrorScope
::ignoreException();
2275 $dao = new CRM_Core_DAO();
2277 $result = $dao->query('CREATE OR REPLACE VIEW civicrm_domain_view AS SELECT * FROM civicrm_domain');
2278 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError') ||
is_a($result, 'DB_Error')) {
2284 $result = $dao->query('CREATE TRIGGER civicrm_domain_trigger BEFORE INSERT ON civicrm_domain FOR EACH ROW BEGIN END');
2285 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError') ||
is_a($result, 'DB_Error')) {
2287 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
2292 $dao->query('DROP TRIGGER IF EXISTS civicrm_domain_trigger');
2293 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
2295 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
2302 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
2303 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
2312 * @param null $message
2313 * @param bool $printDAO
2315 public static function debugPrint($message = NULL, $printDAO = TRUE) {
2316 CRM_Utils_System
::xMemory("{$message}: ");
2319 global $_DB_DATAOBJECT;
2321 foreach (array_keys($_DB_DATAOBJECT['RESULTS']) as $id) {
2322 $q[] = $_DB_DATAOBJECT['RESULTS'][$id]->query
;
2324 CRM_Core_Error
::debug('_DB_DATAOBJECT', $q);
2329 * Build a list of triggers via hook and add them to (err, reconcile them
2330 * with) the database.
2332 * @param string $tableName
2333 * the specific table requiring a rebuild; or NULL to rebuild all tables.
2334 * @param bool $force
2339 public static function triggerRebuild($tableName = NULL, $force = FALSE) {
2340 Civi
::service('sql_triggers')->rebuild($tableName, $force);
2344 * Because sql functions are sometimes lost, esp during db migration, we check here to avoid numerous support requests
2345 * @see http://issues.civicrm.org/jira/browse/CRM-13822
2346 * TODO: Alternative solutions might be
2347 * * Stop using functions and find another way to strip numeric characters from phones
2348 * * Give better error messages (currently a missing fn fatals with "unknown error")
2350 public static function checkSqlFunctionsExist() {
2351 if (!self
::$_checkedSqlFunctionsExist) {
2352 self
::$_checkedSqlFunctionsExist = TRUE;
2353 $dao = CRM_Core_DAO
::executeQuery("SHOW function status WHERE db = database() AND name = 'civicrm_strip_non_numeric'");
2354 if (!$dao->fetch()) {
2355 self
::triggerRebuild();
2361 * Wrapper function to drop triggers.
2363 * @param string $tableName
2364 * the specific table requiring a rebuild; or NULL to rebuild all tables.
2367 public static function dropTriggers($tableName = NULL) {
2368 Civi
::service('sql_triggers')->dropTriggers($tableName);
2372 * @param array $info
2373 * per hook_civicrm_triggerInfo.
2374 * @param string $onlyTableName
2375 * the specific table requiring a rebuild; or NULL to rebuild all tables.
2378 public static function createTriggers(&$info, $onlyTableName = NULL) {
2379 Civi
::service('sql_triggers')->createTriggers($info, $onlyTableName);
2383 * Given a list of fields, create a list of references.
2385 * @param string $className
2386 * BAO/DAO class name.
2387 * @return array<CRM_Core_Reference_Interface>
2389 public static function createReferenceColumns($className) {
2391 $fields = $className::fields();
2392 foreach ($fields as $field) {
2393 if (isset($field['pseudoconstant'], $field['pseudoconstant']['optionGroupName'])) {
2394 $result[] = new CRM_Core_Reference_OptionValue(
2395 $className::getTableName(),
2397 'civicrm_option_value',
2398 CRM_Utils_Array
::value('keyColumn', $field['pseudoconstant'], 'value'),
2399 $field['pseudoconstant']['optionGroupName']
2407 * Find all records which refer to this entity.
2410 * Array of objects referencing this
2412 public function findReferences() {
2413 $links = self
::getReferencesToTable(static::getTableName());
2416 foreach ($links as $refSpec) {
2417 /** @var $refSpec CRM_Core_Reference_Interface */
2418 $daoName = CRM_Core_DAO_AllCoreTables
::getClassForTable($refSpec->getReferenceTable());
2419 $result = $refSpec->findReferences($this);
2421 while ($result->fetch()) {
2422 $obj = new $daoName();
2423 $obj->id
= $result->id
;
2424 $occurrences[] = $obj;
2429 return $occurrences;
2434 * each item has keys:
2438 * - table: string|null SQL table name
2439 * - key: string|null SQL column name
2441 public function getReferenceCounts() {
2442 $links = self
::getReferencesToTable(static::getTableName());
2445 foreach ($links as $refSpec) {
2446 /** @var $refSpec CRM_Core_Reference_Interface */
2447 $count = $refSpec->getReferenceCount($this);
2448 if ($count['count'] != 0) {
2453 foreach (CRM_Core_Component
::getEnabledComponents() as $component) {
2454 /** @var $component CRM_Core_Component_Info */
2455 $counts = array_merge($counts, $component->getReferenceCounts($this));
2457 CRM_Utils_Hook
::referenceCounts($this, $counts);
2463 * List all tables which have hard foreign keys to this table.
2465 * For now, this returns a description of every entity_id/entity_table
2467 * TODO: filter dynamic entity references on the $tableName, based on
2468 * schema metadata in dynamicForeignKey which enumerates a restricted
2469 * set of possible entity_table's.
2471 * @param string $tableName
2472 * Table referred to.
2475 * structure of table and column, listing every table with a
2476 * foreign key reference to $tableName, and the column where the key appears.
2478 public static function getReferencesToTable($tableName) {
2480 foreach (CRM_Core_DAO_AllCoreTables
::getClasses() as $daoClassName) {
2481 $links = $daoClassName::getReferenceColumns();
2483 foreach ($links as $refSpec) {
2484 /** @var $refSpec CRM_Core_Reference_Interface */
2485 if ($refSpec->matchesTargetTable($tableName)) {
2486 $refsFound[] = $refSpec;
2494 * Get all references to contact table.
2496 * This includes core tables, custom group tables, tables added by the merge
2497 * hook and the entity_tag table.
2499 * Refer to CRM-17454 for information on the danger of querying the information
2500 * schema to derive this.
2502 * @throws \CiviCRM_API3_Exception
2504 public static function getReferencesToContactTable() {
2505 if (isset(\Civi
::$statics[__CLASS__
]) && isset(\Civi
::$statics[__CLASS__
]['contact_references'])) {
2506 return \Civi
::$statics[__CLASS__
]['contact_references'];
2508 $contactReferences = [];
2509 $coreReferences = CRM_Core_DAO
::getReferencesToTable('civicrm_contact');
2510 foreach ($coreReferences as $coreReference) {
2511 if (!is_a($coreReference, 'CRM_Core_Reference_Dynamic')) {
2512 $contactReferences[$coreReference->getReferenceTable()][] = $coreReference->getReferenceKey();
2515 self
::appendCustomTablesExtendingContacts($contactReferences);
2516 self
::appendCustomContactReferenceFields($contactReferences);
2517 \Civi
::$statics[__CLASS__
]['contact_references'] = $contactReferences;
2518 return \Civi
::$statics[__CLASS__
]['contact_references'];
2522 * Get all dynamic references to the given table.
2524 * @param string $tableName
2528 public static function getDynamicReferencesToTable($tableName) {
2529 if (!isset(\Civi
::$statics[__CLASS__
]['contact_references_dynamic'][$tableName])) {
2530 \Civi
::$statics[__CLASS__
]['contact_references_dynamic'][$tableName] = [];
2531 $coreReferences = CRM_Core_DAO
::getReferencesToTable($tableName);
2532 foreach ($coreReferences as $coreReference) {
2533 if ($coreReference instanceof \CRM_Core_Reference_Dynamic
) {
2534 \Civi
::$statics[__CLASS__
]['contact_references_dynamic'][$tableName][$coreReference->getReferenceTable()][] = [$coreReference->getReferenceKey(), $coreReference->getTypeColumn()];
2538 return \Civi
::$statics[__CLASS__
]['contact_references_dynamic'][$tableName];
2542 * Add custom tables that extend contacts to the list of contact references.
2544 * CRM_Core_BAO_CustomGroup::getAllCustomGroupsByBaseEntity seems like a safe-ish
2545 * function to be sure all are retrieved & we don't miss subtypes or inactive or multiples
2546 * - the down side is it is not cached.
2548 * Further changes should be include tests in the CRM_Core_MergerTest class
2549 * to ensure that disabled, subtype, multiple etc groups are still captured.
2551 * @param array $cidRefs
2553 public static function appendCustomTablesExtendingContacts(&$cidRefs) {
2554 $customValueTables = CRM_Core_BAO_CustomGroup
::getAllCustomGroupsByBaseEntity('Contact');
2555 $customValueTables->find();
2556 while ($customValueTables->fetch()) {
2557 $cidRefs[$customValueTables->table_name
][] = 'entity_id';
2562 * Add custom ContactReference fields to the list of contact references
2564 * This includes active and inactive fields/groups
2566 * @param array $cidRefs
2568 * @throws \CiviCRM_API3_Exception
2570 public static function appendCustomContactReferenceFields(&$cidRefs) {
2571 $fields = civicrm_api3('CustomField', 'get', [
2572 'return' => ['column_name', 'custom_group_id.table_name'],
2573 'data_type' => 'ContactReference',
2574 'options' => ['limit' => 0],
2576 foreach ($fields as $field) {
2577 $cidRefs[$field['custom_group_id.table_name']][] = $field['column_name'];
2582 * Lookup the value of a MySQL global configuration variable.
2584 * @param string $name
2585 * E.g. "thread_stack".
2586 * @param mixed $default
2589 public static function getGlobalSetting($name, $default = NULL) {
2590 // Alternatively, SELECT @@GLOBAL.thread_stack, but
2591 // that has been reported to fail under MySQL 5.0 for OS X
2592 $escapedName = self
::escapeString($name);
2593 $dao = CRM_Core_DAO
::executeQuery("SHOW VARIABLES LIKE '$escapedName'");
2594 if ($dao->fetch()) {
2603 * Update the fields array to also hold keys for pseudoconstant fields that relate to contained fields.
2605 * This is relevant where we want to offer both the ID field and the label field
2606 * as an option, e.g. search builder.
2608 * It is currently limited for optionGroupName & id+ name+ FK combos for purposes keeping the scope of the
2609 * change small, but is appropriate for other sorts of pseudoconstants.
2611 * @param array $fields
2613 public static function appendPseudoConstantsToFields(&$fields) {
2614 foreach ($fields as $fieldUniqueName => $field) {
2615 if (!empty($field['pseudoconstant'])) {
2616 $pseudoConstant = $field['pseudoconstant'];
2617 if (!empty($pseudoConstant['optionGroupName'])) {
2618 $fields[$pseudoConstant['optionGroupName']] = [
2619 'title' => CRM_Core_BAO_OptionGroup
::getTitleByName($pseudoConstant['optionGroupName']),
2620 'name' => $pseudoConstant['optionGroupName'],
2621 'data_type' => CRM_Utils_Type
::T_STRING
,
2622 'is_pseudofield_for' => $fieldUniqueName,
2625 // We restrict to id + name + FK as we are extending this a bit, but cautiously.
2627 !empty($field['FKClassName'])
2628 && CRM_Utils_Array
::value('keyColumn', $pseudoConstant) === 'id'
2629 && CRM_Utils_Array
::value('labelColumn', $pseudoConstant) === 'name'
2631 $pseudoFieldName = str_replace('_' . $pseudoConstant['keyColumn'], '', $field['name']);
2632 // This if is just an extra caution when adding change.
2633 if (!isset($fields[$pseudoFieldName])) {
2634 $daoName = $field['FKClassName'];
2635 $fkFields = $daoName::fields();
2636 foreach ($fkFields as $fkField) {
2637 if ($fkField['name'] === $pseudoConstant['labelColumn']) {
2638 $fields[$pseudoFieldName] = [
2639 'name' => $pseudoFieldName,
2640 'is_pseudofield_for' => $field['name'],
2641 'title' => $fkField['title'],
2642 'data_type' => $fkField['type'],
2643 'where' => $field['where'],
2654 * Get options for the called BAO object's field.
2656 * This function can be overridden by each BAO to add more logic related to context.
2657 * The overriding function will generally call the lower-level CRM_Core_PseudoConstant::get
2659 * @param string $fieldName
2660 * @param string $context
2661 * @see CRM_Core_DAO::buildOptionsContext
2662 * @param array $props
2663 * Raw field values; whatever is known about this bao object.
2665 * Note: $props can contain unsanitized input and should not be passed directly to CRM_Core_PseudoConstant::get
2667 * @return array|bool
2669 public static function buildOptions($fieldName, $context = NULL, $props = []) {
2670 // If a given bao does not override this function
2671 $baoName = get_called_class();
2672 return CRM_Core_PseudoConstant
::get($baoName, $fieldName, [], $context);
2676 * Populate option labels for this object's fields.
2678 * @throws exception if called directly on the base class
2680 public function getOptionLabels() {
2681 $fields = $this->fields();
2682 if ($fields === NULL) {
2683 throw new Exception('Cannot call getOptionLabels on CRM_Core_DAO');
2685 foreach ($fields as $field) {
2686 $name = $field['name'] ??
NULL;
2687 if ($name && isset($this->$name)) {
2688 $label = CRM_Core_PseudoConstant
::getLabel(get_class($this), $name, $this->$name);
2689 if ($label !== FALSE) {
2690 // Append 'label' onto the field name
2691 $labelName = $name . '_label';
2692 $this->$labelName = $label;
2699 * Provides documentation and validation for the buildOptions $context param
2701 * @param string $context
2703 * @throws CRM_Core_Exception
2706 public static function buildOptionsContext($context = NULL) {
2708 'get' => "get: all options are returned, even if they are disabled; labels are translated.",
2709 'create' => "create: options are filtered appropriately for the object being created/updated; labels are translated.",
2710 'search' => "search: searchable options are returned; labels are translated.",
2711 'validate' => "validate: all options are returned, even if they are disabled; machine names are used in place of labels.",
2712 'abbreviate' => "abbreviate: enabled options are returned; labels are replaced with abbreviations.",
2713 'match' => "match: enabled options are returned using machine names as keys; labels are translated.",
2715 // Validation: enforce uniformity of this param
2716 if ($context !== NULL && !isset($contexts[$context])) {
2717 throw new CRM_Core_Exception("'$context' is not a valid context for buildOptions.");
2723 * @param string $fieldName
2724 * @return bool|array
2726 public function getFieldSpec($fieldName) {
2727 $fields = $this->fields();
2728 $fieldKeys = $this->fieldKeys();
2730 // Support "unique names" as well as sql names
2731 $fieldKey = $fieldName;
2732 if (empty($fields[$fieldKey])) {
2733 $fieldKey = $fieldKeys[$fieldName] ??
NULL;
2735 // If neither worked then this field doesn't exist. Return false.
2736 if (empty($fields[$fieldKey])) {
2739 return $fields[$fieldKey];
2743 * Get SQL where clause for SQL filter syntax input parameters.
2745 * SQL version of api function to assign filters to the DAO based on the syntax
2746 * $field => array('IN' => array(4,6,9))
2748 * $field => array('LIKE' => array('%me%))
2751 * @param string $fieldName
2753 * @param array $filter
2754 * filter to be applied indexed by operator.
2755 * @param string $type
2756 * type of field (not actually used - nor in api @todo ).
2757 * @param string $alias
2758 * alternative field name ('as') @todo- not actually used.
2759 * @param bool $returnSanitisedArray
2760 * Return a sanitised array instead of a clause.
2761 * this is primarily so we can add filters @ the api level to the Query object based fields
2765 * @return NULL|string|array
2766 * a string is returned if $returnSanitisedArray is not set, otherwise and Array or NULL
2767 * depending on whether it is supported as yet
2769 public static function createSQLFilter($fieldName, $filter, $type = NULL, $alias = NULL, $returnSanitisedArray = FALSE) {
2770 foreach ($filter as $operator => $criteria) {
2771 if (in_array($operator, self
::acceptedSQLOperators(), TRUE)) {
2772 switch ($operator) {
2776 if (!$returnSanitisedArray) {
2777 return (sprintf('%s %s', $fieldName, $operator));
2780 return (sprintf('%s %s ', $fieldName, $operator));
2784 // ternary operators
2787 if ((empty($criteria[0]) && !in_array($criteria[0], ['0', 0]))||
(empty($criteria[1]) && !in_array($criteria[1], ['0', 0]))) {
2788 throw new Exception("invalid criteria for $operator");
2790 if (!$returnSanitisedArray) {
2791 return (sprintf('%s ' . $operator . ' "%s" AND "%s"', $fieldName, CRM_Core_DAO
::escapeString($criteria[0]), CRM_Core_DAO
::escapeString($criteria[1])));
2794 // not yet implemented (tests required to implement)
2802 if (empty($criteria)) {
2803 throw new Exception("invalid criteria for $operator");
2805 $escapedCriteria = array_map([
2809 if (!$returnSanitisedArray) {
2810 return (sprintf('%s %s ("%s")', $fieldName, $operator, implode('", "', $escapedCriteria)));
2812 return $escapedCriteria;
2817 if (!$returnSanitisedArray) {
2818 return (sprintf('%s %s "%s"', $fieldName, $operator, CRM_Core_DAO
::escapeString($criteria)));
2821 // not yet implemented (tests required to implement)
2830 * @see http://issues.civicrm.org/jira/browse/CRM-9150
2831 * support for other syntaxes is discussed in ticket but being put off for now
2834 public static function acceptedSQLOperators() {
2855 * SQL has a limit of 64 characters on various names:
2856 * table name, trigger name, column name ...
2858 * For custom groups and fields we generated names from user entered input
2859 * which can be longer than this length, this function helps with creating
2860 * strings that meet various criteria.
2862 * @param string $string
2863 * The string to be shortened.
2864 * @param int $length
2865 * The max length of the string.
2867 * @param bool $makeRandom
2871 public static function shortenSQLName($string, $length = 60, $makeRandom = FALSE) {
2872 // early return for strings that meet the requirements
2873 if (strlen($string) <= $length) {
2877 // easy return for calls that dont need a randomized uniq string
2879 return substr($string, 0, $length);
2882 // the string is longer than the length and we need a uniq string
2883 // for the same tablename we need the same uniq string every time
2884 // hence we use md5 on the string, which is not random
2885 // we'll append 8 characters to the end of the tableName
2886 $md5string = substr(md5($string), 0, 8);
2887 return substr($string, 0, $length - 8) . "_{$md5string}";
2891 * https://issues.civicrm.org/jira/browse/CRM-17748
2892 * Sets the internal options to be used on a query
2894 * @param array $options
2897 public function setOptions($options) {
2898 if (is_array($options)) {
2899 $this->_options
= $options;
2904 * https://issues.civicrm.org/jira/browse/CRM-17748
2905 * wrapper to pass internal DAO options down to DB_mysql/DB_Common level
2907 * @param array $options
2910 protected function _setDBOptions($options) {
2911 global $_DB_DATAOBJECT;
2913 if (is_array($options) && count($options)) {
2914 $conn = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5
];
2915 foreach ($options as $option_name => $option_value) {
2916 $conn->setOption($option_name, $option_value);
2923 * @param array $params
2925 public function setApiFilter(&$params) {
2929 * Generates acl clauses suitable for adding to WHERE or ON when doing an api.get for this entity
2931 * Return format is in the form of fieldname => clauses starting with an operator. e.g.:
2934 * 'location_type_id' => array('IS NOT NULL', 'IN (1,2,3)')
2938 * Note that all array keys must be actual field names in this entity. Use subqueries to filter on other tables e.g. custom values.
2942 public function addSelectWhereClause() {
2944 $fields = $this->fields();
2945 foreach ($fields as $fieldName => $field) {
2946 // Clause for contact-related entities like Email, Relationship, etc.
2947 if (strpos($fieldName, 'contact_id') === 0 && CRM_Utils_Array
::value('FKClassName', $field) == 'CRM_Contact_DAO_Contact') {
2948 $clauses[$fieldName] = CRM_Utils_SQL
::mergeSubquery('Contact');
2950 // Clause for an entity_table/entity_id combo
2951 if ($fieldName == 'entity_id' && isset($fields['entity_table'])) {
2952 $relatedClauses = [];
2953 $relatedEntities = $this->buildOptions('entity_table', 'get');
2954 foreach ((array) $relatedEntities as $table => $ent) {
2956 $ent = CRM_Core_DAO_AllCoreTables
::getBriefName(CRM_Core_DAO_AllCoreTables
::getClassForTable($table));
2957 $subquery = CRM_Utils_SQL
::mergeSubquery($ent);
2959 $relatedClauses[] = "(entity_table = '$table' AND entity_id " . implode(' AND entity_id ', $subquery) . ")";
2962 $relatedClauses[] = "(entity_table = '$table')";
2966 if ($relatedClauses) {
2967 $clauses['id'] = 'IN (SELECT id FROM `' . $this->tableName() . '` WHERE (' . implode(') OR (', $relatedClauses) . '))';
2971 CRM_Utils_Hook
::selectWhereClause($this, $clauses);
2976 * This returns the final permissioned query string for this entity
2978 * With acls from related entities + additional clauses from hook_civicrm_selectWhereClause
2980 * @param string $tableAlias
2983 public static function getSelectWhereClause($tableAlias = NULL) {
2984 $bao = new static();
2985 if ($tableAlias === NULL) {
2986 $tableAlias = $bao->tableName();
2989 foreach ((array) $bao->addSelectWhereClause() as $field => $vals) {
2990 $clauses[$field] = NULL;
2992 $clauses[$field] = "(`$tableAlias`.`$field` IS NULL OR (`$tableAlias`.`$field` " . implode(" AND `$tableAlias`.`$field` ", (array) $vals) . '))';
2999 * ensure database name is 'safe', i.e. only contains word characters (includes underscores)
3000 * and dashes, and contains at least one [a-z] case insenstive.
3006 public static function requireSafeDBName($database) {
3009 "/^[\w\-]*[a-z]+[\w\-]*$/i",
3013 if (empty($matches)) {
3020 * Transform an array to a serialized string for database storage.
3022 * @param array|null $value
3023 * @param int $serializationType
3024 * @return string|null
3026 * @throws \Exception
3028 public static function serializeField($value, $serializationType) {
3029 if ($value === NULL) {
3032 switch ($serializationType) {
3033 case self
::SERIALIZE_SEPARATOR_BOOKEND
:
3034 return $value === [] ?
'' : CRM_Utils_Array
::implodePadded($value);
3036 case self
::SERIALIZE_SEPARATOR_TRIMMED
:
3037 return is_array($value) ?
implode(self
::VALUE_SEPARATOR
, $value) : $value;
3039 case self
::SERIALIZE_JSON
:
3040 return is_array($value) ?
json_encode($value) : $value;
3042 case self
::SERIALIZE_PHP
:
3043 return is_array($value) ?
serialize($value) : $value;
3045 case self
::SERIALIZE_COMMA
:
3046 return is_array($value) ?
implode(',', $value) : $value;
3049 throw new Exception('Unknown serialization method for field.');
3054 * Transform a serialized string from the database into an array.
3056 * @param string|null $value
3057 * @param $serializationType
3059 * @return array|null
3060 * @throws CRM_Core_Exception
3062 public static function unSerializeField($value, $serializationType) {
3063 if ($value === NULL) {
3066 if ($value === '') {
3069 switch ($serializationType) {
3070 case self
::SERIALIZE_SEPARATOR_BOOKEND
:
3071 return (array) CRM_Utils_Array
::explodePadded($value);
3073 case self
::SERIALIZE_SEPARATOR_TRIMMED
:
3074 return explode(self
::VALUE_SEPARATOR
, trim($value));
3076 case self
::SERIALIZE_JSON
:
3077 return strlen($value) ?
json_decode($value, TRUE) : [];
3079 case self
::SERIALIZE_PHP
:
3080 return strlen($value) ? CRM_Utils_String
::unserialize($value) : [];
3082 case self
::SERIALIZE_COMMA
:
3083 return explode(',', trim(str_replace(', ', '', $value)));
3086 throw new CRM_Core_Exception('Unknown serialization method for field.');
3093 public static function getEntityRefFilters() {
3098 * Get exportable fields with pseudoconstants rendered as an extra field.
3100 * @param string $baoClass
3104 public static function getExportableFieldsWithPseudoConstants($baoClass) {
3105 if (method_exists($baoClass, 'exportableFields')) {
3106 $fields = $baoClass::exportableFields();
3109 $fields = $baoClass::export();
3111 CRM_Core_DAO
::appendPseudoConstantsToFields($fields);
3116 * Remove item from static cache during update/delete operations
3118 private function clearDbColumnValueCache() {
3119 $daoName = get_class($this);
3120 while (strpos($daoName, '_BAO_') !== FALSE) {
3121 $daoName = get_parent_class($daoName);
3123 if (isset($this->id
)) {
3124 unset(self
::$_dbColumnValueCache[$daoName]['id'][$this->id
]);
3126 if (isset($this->name
)) {
3127 unset(self
::$_dbColumnValueCache[$daoName]['name'][$this->name
]);