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 $dsn = CRM_Utils_SQL
::autoSwitchDSN($dsn);
165 $options['database'] = $dsn;
166 $options['quote_identifiers'] = TRUE;
167 if (CRM_Utils_SQL
::isSSLDSN($dsn)) {
168 // There are two different options arrays.
169 $other_options = &PEAR
::getStaticProperty('DB', 'options');
170 $other_options['ssl'] = TRUE;
172 if (defined('CIVICRM_DAO_DEBUG')) {
173 self
::DebugLevel(CIVICRM_DAO_DEBUG
);
175 $factory = new CRM_Contact_DAO_Factory();
176 CRM_Core_DAO
::setFactory($factory);
177 $currentModes = CRM_Utils_SQL
::getSqlModes();
178 if (CRM_Utils_Constant
::value('CIVICRM_MYSQL_STRICT', CRM_Utils_System
::isDevelopment())) {
179 if (CRM_Utils_SQL
::supportsFullGroupBy() && !in_array('ONLY_FULL_GROUP_BY', $currentModes) && CRM_Utils_SQL
::isGroupByModeInDefault()) {
180 $currentModes[] = 'ONLY_FULL_GROUP_BY';
182 if (!in_array('STRICT_TRANS_TABLES', $currentModes)) {
183 $currentModes = array_merge(['STRICT_TRANS_TABLES'], $currentModes);
185 CRM_Core_DAO
::executeQuery("SET SESSION sql_mode = %1", [1 => [implode(',', $currentModes), 'String']]);
187 CRM_Core_DAO
::executeQuery('SET NAMES utf8mb4');
188 CRM_Core_DAO
::executeQuery('SET @uniqueID = %1', [1 => [CRM_Utils_Request
::id(), 'String']]);
194 public static function getConnection() {
195 global $_DB_DATAOBJECT;
196 $dao = new CRM_Core_DAO();
197 return $_DB_DATAOBJECT['CONNECTIONS'][$dao->_database_dsn_md5
];
201 * Disables usage of the ONLY_FULL_GROUP_BY Mode if necessary
203 public static function disableFullGroupByMode() {
204 $currentModes = CRM_Utils_SQL
::getSqlModes();
205 if (in_array('ONLY_FULL_GROUP_BY', $currentModes) && CRM_Utils_SQL
::isGroupByModeInDefault()) {
206 $key = array_search('ONLY_FULL_GROUP_BY', $currentModes);
207 unset($currentModes[$key]);
208 CRM_Core_DAO
::executeQuery("SET SESSION sql_mode = %1", [1 => [implode(',', $currentModes), 'String']]);
213 * Re-enables ONLY_FULL_GROUP_BY sql_mode as necessary..
215 public static function reenableFullGroupByMode() {
216 $currentModes = CRM_Utils_SQL
::getSqlModes();
217 if (!in_array('ONLY_FULL_GROUP_BY', $currentModes) && CRM_Utils_SQL
::isGroupByModeInDefault()) {
218 $currentModes[] = 'ONLY_FULL_GROUP_BY';
219 CRM_Core_DAO
::executeQuery("SET SESSION sql_mode = %1", [1 => [implode(',', $currentModes), 'String']]);
224 * @param string $fieldName
226 * @param array $params
228 protected function assignTestFK($fieldName, $fieldDef, $params) {
229 $required = $fieldDef['required'] ??
NULL;
230 $FKClassName = $fieldDef['FKClassName'] ??
NULL;
231 $dbName = $fieldDef['name'];
232 $daoName = str_replace('_BAO_', '_DAO_', get_class($this));
234 // skip the FK if it is not required
235 // if it's contact id we should create even if not required
236 // we'll have a go @ fetching first though
237 // we WILL create campaigns though for so tests with a campaign pseudoconstant will complete
238 if ($FKClassName === 'CRM_Campaign_DAO_Campaign' && $daoName != $FKClassName) {
241 if (!$required && $dbName != 'contact_id') {
242 $fkDAO = new $FKClassName();
243 if ($fkDAO->find(TRUE)) {
244 $this->$dbName = $fkDAO->id
;
248 elseif (in_array($FKClassName, CRM_Core_DAO
::$_testEntitiesToSkip)) {
249 $depObject = new $FKClassName();
250 $depObject->find(TRUE);
251 $this->$dbName = $depObject->id
;
253 elseif ($daoName == 'CRM_Member_DAO_MembershipType' && $fieldName == 'member_of_contact_id') {
254 // FIXME: the fields() metadata is not specific enough
255 $depObject = CRM_Core_DAO
::createTestObject($FKClassName, ['contact_type' => 'Organization']);
256 $this->$dbName = $depObject->id
;
259 //if it is required we need to generate the dependency object first
260 $depObject = CRM_Core_DAO
::createTestObject($FKClassName, CRM_Utils_Array
::value($dbName, $params, 1));
261 $this->$dbName = $depObject->id
;
266 * Generate and assign an arbitrary value to a field of a test object.
268 * @param string $fieldName
269 * @param array $fieldDef
270 * @param int $counter
271 * The globally-unique ID of the test object.
273 * @throws \CRM_Core_Exception
275 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
276 $dbName = $fieldDef['name'];
277 $daoName = get_class($this);
280 if (!$handled && $dbName == 'contact_sub_type') {
281 //coming up with a rule to set this is too complex let's not set it
285 // Pick an option value if needed
286 if (!$handled && $fieldDef['type'] !== CRM_Utils_Type
::T_BOOLEAN
) {
287 $options = $daoName::buildOptions($dbName, 'create');
289 $this->$dbName = key($options);
295 switch ($fieldDef['type']) {
296 case CRM_Utils_Type
::T_INT
:
297 case CRM_Utils_Type
::T_FLOAT
:
298 case CRM_Utils_Type
::T_MONEY
:
299 if (isset($fieldDef['precision'])) {
300 // $object->$dbName = CRM_Utils_Number::createRandomDecimal($value['precision']);
301 $this->$dbName = CRM_Utils_Number
::createTruncatedDecimal($counter, $fieldDef['precision']);
304 $this->$dbName = $counter;
308 case CRM_Utils_Type
::T_BOOLEAN
:
309 if (isset($fieldDef['default'])) {
310 $this->$dbName = $fieldDef['default'];
312 elseif ($fieldDef['name'] == 'is_deleted' ||
$fieldDef['name'] == 'is_test') {
320 case CRM_Utils_Type
::T_DATE
:
321 case CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
:
322 $this->$dbName = '19700101';
323 if ($dbName == 'end_date') {
324 // put this in the future
325 $this->$dbName = '20200101';
329 case CRM_Utils_Type
::T_TIMESTAMP
:
330 $this->$dbName = '19700201000000';
333 case CRM_Utils_Type
::T_TIME
:
334 throw new CRM_Core_Exception('T_TIME shouldn\'t be used.');
336 case CRM_Utils_Type
::T_CCNUM
:
337 $this->$dbName = '4111 1111 1111 1111';
340 case CRM_Utils_Type
::T_URL
:
341 $this->$dbName = 'http://www.civicrm.org';
344 case CRM_Utils_Type
::T_STRING
:
345 case CRM_Utils_Type
::T_BLOB
:
346 case CRM_Utils_Type
::T_MEDIUMBLOB
:
347 case CRM_Utils_Type
::T_TEXT
:
348 case CRM_Utils_Type
::T_LONGTEXT
:
349 case CRM_Utils_Type
::T_EMAIL
:
351 // WAS: if (isset($value['enumValues'])) {
352 // TODO: see if this works with all pseudoconstants
353 if (isset($fieldDef['pseudoconstant'], $fieldDef['pseudoconstant']['callback'])) {
354 if (isset($fieldDef['default'])) {
355 $this->$dbName = $fieldDef['default'];
358 $options = CRM_Core_PseudoConstant
::get($daoName, $fieldName);
359 if (is_array($options)) {
360 $this->$dbName = $options[0];
363 $defaultValues = explode(',', $options);
364 $this->$dbName = $defaultValues[0];
369 $this->$dbName = $dbName . '_' . $counter;
370 $maxlength = $fieldDef['maxlength'] ??
NULL;
371 if ($maxlength > 0 && strlen($this->$dbName) > $maxlength) {
372 $this->$dbName = substr($this->$dbName, 0, $fieldDef['maxlength']);
380 * Reset the DAO object.
382 * DAO is kinda crappy in that there is an unwritten rule of one query per DAO.
384 * We attempt to get around this crappy restriction by resetting some of DAO's internal fields. Use this with caution
386 public function reset() {
388 foreach (array_keys($this->table()) as $field) {
389 unset($this->$field);
393 * reset the various DB_DAO structures manually
402 * @param string $tableName
406 public static function getLocaleTableName($tableName) {
409 $tables = CRM_Core_I18n_Schema
::schemaStructureTables();
410 if (in_array($tableName, $tables)) {
411 return $tableName . $dbLocale;
418 * Execute a query by the current DAO, localizing it along the way (if needed).
420 * @param string $query
421 * The SQL query for execution.
422 * @param bool $i18nRewrite
423 * Whether to rewrite the query.
426 * the current DAO object after the query execution
428 public function query($query, $i18nRewrite = TRUE) {
429 // rewrite queries that should use $dbLocale-based views for multi-language installs
430 global $dbLocale, $_DB_DATAOBJECT;
432 if (empty($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5
])) {
433 // Will force connection to be populated per CRM-20541.
437 $conn = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5
];
438 $orig_options = $conn->options
;
439 $this->_setDBOptions($this->_options
);
441 if ($i18nRewrite and $dbLocale) {
442 $query = CRM_Core_I18n_Schema
::rewriteQuery($query);
445 $ret = parent
::query($query);
447 $this->_setDBOptions($orig_options);
452 * Static function to set the factory instance for this class.
454 * @param object $factory
455 * The factory application object.
457 public static function setFactory(&$factory) {
458 self
::$_factory = &$factory;
462 * Factory method to instantiate a new object from a table name.
464 * @param string $table
465 * @return \DataObject|\PEAR_Error
467 public function factory($table = '') {
468 if (!isset(self
::$_factory)) {
469 return parent
::factory($table);
472 return self
::$_factory->create($table);
476 * Initialization for all DAO objects. Since we access DB_DO programatically
477 * we need to set the links manually.
479 public function initialize() {
481 if (empty(Civi
::$statics[__CLASS__
]['init'])) {
482 // CRM_Core_DAO::init() must be called before CRM_Core_DAO->initialize().
483 // This occurs very early in bootstrap - error handlers may not be wired up.
484 echo "Inconsistent system initialization sequence. Premature access of (" . get_class($this) . ")";
485 CRM_Utils_System
::civiExit();
490 * Defines the default key as 'id'.
494 public function keys() {
503 * Tells DB_DataObject which keys use autoincrement.
504 * 'id' is autoincrementing by default.
509 public function sequenceKey() {
510 static $sequenceKeys;
511 if (!isset($sequenceKeys)) {
512 $sequenceKeys = ['id', TRUE];
514 return $sequenceKeys;
518 * Returns list of FK relationships.
522 * Array of CRM_Core_Reference_Interface
524 public static function getReferenceColumns() {
529 * Returns all the column names of this table.
534 public static function &fields() {
540 * Returns all usable fields, indexed by name.
542 * This function differs from fields() in that it indexes by name rather than unique_name.
544 * It excludes fields not added yet by pending upgrades.
545 * This avoids problems with trying to SELECT a field that exists in code but has not yet been added to the db.
547 * @param bool $checkPermissions
548 * Filter by field permissions.
551 public static function getSupportedFields($checkPermissions = FALSE) {
552 $fields = array_column((array) static::fields(), NULL, 'name');
554 // Exclude fields yet not added by pending upgrades
555 $dbVer = \CRM_Core_BAO_Domain
::version();
556 $daoExt = defined(static::class . '::EXT') ?
constant(static::class . '::EXT') : NULL;
557 if ($fields && $daoExt === 'civicrm' && version_compare($dbVer, \CRM_Utils_System
::version()) < 0) {
558 $fields = array_filter($fields, function($field) use ($dbVer) {
559 $add = $field['add'] ??
'1.0.0';
560 if (substr_count($add, '.') < 2) {
563 return version_compare($dbVer, $add, '>=');
567 // Exclude fields the user does not have permission for
568 if ($checkPermissions) {
569 $fields = array_filter($fields, function($field) {
570 return empty($field['permission']) || CRM_Core_Permission
::check($field['permission']);
578 * Get/set an associative array of table columns
583 public function table() {
584 $fields = $this->fields();
588 foreach ($fields as $name => $value) {
589 $table[$value['name']] = $value['type'];
590 if (!empty($value['required'])) {
591 $table[$value['name']] +
= self
::DB_DAO_NOTNULL
;
604 * @return CRM_Core_DAO
606 public function save($hook = TRUE) {
607 if (!empty($this->id
)) {
609 $preEvent = new \Civi\Core\DAO\Event\
PreUpdate($this);
610 \Civi
::dispatcher()->dispatch("civi.dao.preUpdate", $preEvent);
613 $result = $this->update();
616 $event = new \Civi\Core\DAO\Event\
PostUpdate($this, $result);
617 \Civi
::dispatcher()->dispatch("civi.dao.postUpdate", $event);
619 $this->clearDbColumnValueCache();
623 $preEvent = new \Civi\Core\DAO\Event\
PreUpdate($this);
624 \Civi
::dispatcher()->dispatch("civi.dao.preInsert", $preEvent);
627 $result = $this->insert();
630 $event = new \Civi\Core\DAO\Event\
PostUpdate($this, $result);
631 \Civi
::dispatcher()->dispatch("civi.dao.postInsert", $event);
637 CRM_Utils_Hook
::postSave($this);
644 * Deletes items from table which match current objects variables.
646 * Returns the true on success
650 * Designed to be extended
652 * $object = new mytable();
654 * echo $object->delete(); // builds a conditon
656 * $object = new mytable();
657 * $object->whereAdd('age > 12');
659 * $object->orderBy('age DESC');
660 * $object->delete(true); // dont use object vars, use the conditions, limit and order.
662 * @param bool $useWhere (optional) If DB_DATAOBJECT_WHEREADD_ONLY is passed in then
663 * we will build the condition only using the whereAdd's. Default is to
664 * build the condition only using the object parameters.
666 * * @return mixed Int (No. of rows affected) on success, false on failure, 0 on no data affected
668 public function delete($useWhere = FALSE) {
669 $preEvent = new \Civi\Core\DAO\Event\
PreDelete($this);
670 \Civi
::dispatcher()->dispatch("civi.dao.preDelete", $preEvent);
672 $result = parent
::delete($useWhere);
674 $event = new \Civi\Core\DAO\Event\
PostDelete($this, $result);
675 \Civi
::dispatcher()->dispatch("civi.dao.postDelete", $event);
678 $this->clearDbColumnValueCache();
684 * @param bool $created
686 public function log($created = FALSE) {
689 if (!$this->getLog()) {
694 $session = CRM_Core_Session
::singleton();
695 $cid = $session->get('userID');
698 // return is we dont have handle to FK
703 $dao = new CRM_Core_DAO_Log();
704 $dao->entity_table
= $this->getTableName();
705 $dao->entity_id
= $this->id
;
706 $dao->modified_id
= $cid;
707 $dao->modified_date
= date("YmdHis");
712 * Given an associative array of name/value pairs, extract all the values
713 * that belong to this object and initialize the object with said values
715 * @param array $params
716 * Array of name/value pairs to save.
719 * Did we copy all null values into the object
721 public function copyValues($params) {
723 foreach ($this->fields() as $uniqueName => $field) {
724 $dbName = $field['name'];
725 if (array_key_exists($dbName, $params)) {
726 $value = $params[$dbName];
729 elseif (array_key_exists($uniqueName, $params)) {
730 $value = $params[$uniqueName];
737 // if there is no value then make the variable NULL
740 $this->$dbName = 'null';
742 elseif (is_array($value) && !empty($field['serialize'])) {
743 $this->$dbName = CRM_Core_DAO
::serializeField($value, $field['serialize']);
747 $maxLength = $field['maxlength'] ??
NULL;
748 if (!is_array($value) && $maxLength && mb_strlen($value) > $maxLength && empty($field['pseudoconstant'])) {
749 Civi
::log()->warning(ts('A string for field $dbName has been truncated. The original string was %1', [CRM_Utils_Type
::escape($value, 'String')]));
750 // The string is too long - what to do what to do? Well losing data is generally bad so lets' truncate
751 $value = CRM_Utils_String
::ellipsify($value, $maxLength);
753 $this->$dbName = $value;
762 * Store all the values from this object in an associative array
763 * this is a destructive store, calling function is responsible
764 * for keeping sanity of id's.
766 * @param object $object
767 * The object that we are extracting data from.
768 * @param array $values
769 * (reference ) associative array of name/value pairs.
771 public static function storeValues(&$object, &$values) {
772 $fields = $object->fields();
773 foreach ($fields as $name => $value) {
774 $dbName = $value['name'];
775 if (isset($object->$dbName) && $object->$dbName !== 'null') {
776 $values[$dbName] = $object->$dbName;
777 if ($name != $dbName) {
778 $values[$name] = $object->$dbName;
785 * Create an attribute for this specific field. We only do this for strings and text
787 * @param array $field
788 * The field under task.
791 * the attributes for the object
793 public static function makeAttribute($field) {
795 if (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_STRING
) {
796 $maxLength = $field['maxlength'] ??
NULL;
797 $size = $field['size'] ??
NULL;
798 if ($maxLength ||
$size) {
801 $attributes['maxlength'] = $maxLength;
804 $attributes['size'] = $size;
809 elseif (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_TEXT
) {
810 $rows = $field['rows'] ??
NULL;
814 $cols = $field['cols'] ??
NULL;
820 $attributes['rows'] = $rows;
821 $attributes['cols'] = $cols;
824 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
) {
825 $attributes['size'] = 6;
826 $attributes['maxlength'] = 14;
834 * Get the size and maxLength attributes for this text field.
835 * (or for all text fields) in the DAO object.
837 * @param string $class
839 * @param string $fieldName
840 * Field that i'm interested in or null if.
841 * you want the attributes for all DAO text fields
844 * assoc array of name => attribute pairs
846 public static function getAttribute($class, $fieldName = NULL) {
847 $object = new $class();
848 $fields = $object->fields();
849 if ($fieldName != NULL) {
850 $field = $fields[$fieldName] ??
NULL;
851 return self
::makeAttribute($field);
855 foreach ($fields as $name => $field) {
856 $attribute = self
::makeAttribute($field);
858 $attributes[$name] = $attribute;
862 if (!empty($attributes)) {
870 * Create or update a record from supplied params.
872 * If 'id' is supplied, an existing record will be updated
873 * Otherwise a new record will be created.
875 * @param array $record
876 * @return CRM_Core_DAO
877 * @throws CRM_Core_Exception
879 public static function writeRecord(array $record) {
880 $hook = empty($record['id']) ?
'create' : 'edit';
881 $className = CRM_Core_DAO_AllCoreTables
::getCanonicalClassName(static::class);
882 if ($className === 'CRM_Core_DAO') {
883 throw new CRM_Core_Exception('Function writeRecord must be called on a subclass of CRM_Core_DAO');
885 $entityName = CRM_Core_DAO_AllCoreTables
::getBriefName($className);
887 \CRM_Utils_Hook
::pre($hook, $entityName, $record['id'] ??
NULL, $record);
888 $instance = new $className();
889 $instance->copyValues($record);
891 \CRM_Utils_Hook
::post($hook, $entityName, $instance->id
, $instance);
897 * Delete a record from supplied params.
899 * @param array $record
901 * @return CRM_Core_DAO
902 * @throws CRM_Core_Exception
904 public static function deleteRecord(array $record) {
905 $className = CRM_Core_DAO_AllCoreTables
::getCanonicalClassName(static::class);
906 if ($className === 'CRM_Core_DAO') {
907 throw new CRM_Core_Exception('Function deleteRecord must be called on a subclass of CRM_Core_DAO');
909 $entityName = CRM_Core_DAO_AllCoreTables
::getBriefName($className);
910 if (empty($record['id'])) {
911 throw new CRM_Core_Exception("Cannot delete {$entityName} with no id.");
914 CRM_Utils_Hook
::pre('delete', $entityName, $record['id'], $record);
915 $instance = new $className();
916 $instance->id
= $record['id'];
917 if (!$instance->delete()) {
918 throw new CRM_Core_Exception("Could not delete {$entityName} id {$record['id']}");
920 CRM_Utils_Hook
::post('delete', $entityName, $record['id'], $instance);
926 * Check if there is a record with the same name in the db.
928 * @param string $value
929 * The value of the field we are checking.
930 * @param string $daoName
931 * The dao object name.
932 * @param string $daoID
933 * The id of the object being updated. u can change your name.
934 * as long as there is no conflict
935 * @param string $fieldName
936 * The name of the field in the DAO.
938 * @param string $domainID
939 * The id of the domain. Object exists only for the given domain.
942 * true if object exists
944 public static function objectExists($value, $daoName, $daoID, $fieldName = 'name', $domainID = NULL) {
945 $object = new $daoName();
946 $object->$fieldName = $value;
948 $object->domain_id
= $domainID;
951 if ($object->find(TRUE)) {
952 return $daoID && $object->id
== $daoID;
960 * Check if there is a given column in a specific table.
963 * @see CRM_Core_BAO_SchemaHandler::checkIfFieldExists
965 * @param string $tableName
966 * @param string $columnName
967 * @param bool $i18nRewrite
968 * Whether to rewrite the query on multilingual setups.
971 * true if exists, else false
973 public static function checkFieldExists($tableName, $columnName, $i18nRewrite = TRUE) {
974 CRM_Core_Error
::deprecatedFunctionWarning('CRM_Core_BAO_SchemaHandler::checkIfFieldExists');
975 return CRM_Core_BAO_SchemaHandler
::checkIfFieldExists($tableName, $columnName, $i18nRewrite);
979 * Scans all the tables using a slow query and table name.
983 public static function getTableNames() {
984 $dao = CRM_Core_DAO
::executeQuery(
986 FROM information_schema.TABLES
987 WHERE TABLE_SCHEMA = '" . CRM_Core_DAO
::getDatabaseName() . "'
988 AND TABLE_NAME LIKE 'civicrm_%'
989 AND TABLE_NAME NOT LIKE 'civicrm_import_job_%'
990 AND TABLE_NAME NOT LIKE '%_temp%'
993 while ($dao->fetch()) {
994 $values[] = $dao->TABLE_NAME
;
1000 * @param int $maxTablesToCheck
1004 public static function isDBMyISAM($maxTablesToCheck = 10) {
1005 return CRM_Core_DAO
::singleValueQuery(
1007 FROM information_schema.TABLES
1008 WHERE ENGINE = 'MyISAM'
1009 AND TABLE_SCHEMA = '" . CRM_Core_DAO
::getDatabaseName() . "'
1010 AND TABLE_NAME LIKE 'civicrm_%'
1011 AND TABLE_NAME NOT LIKE 'civicrm_import_job_%'
1012 AND TABLE_NAME NOT LIKE '%_temp%'
1013 AND TABLE_NAME NOT LIKE 'civicrm_tmp_%'
1018 * Get the name of the CiviCRM database.
1022 public static function getDatabaseName() {
1023 $daoObj = new CRM_Core_DAO();
1024 return $daoObj->database();
1028 * Checks if a constraint exists for a specified table.
1030 * @param string $tableName
1031 * @param string $constraint
1034 * true if constraint exists, false otherwise
1036 * @throws \CRM_Core_Exception
1038 public static function checkConstraintExists($tableName, $constraint) {
1041 if (!array_key_exists($tableName, $show)) {
1042 $query = "SHOW CREATE TABLE $tableName";
1043 $dao = CRM_Core_DAO
::executeQuery($query, [], TRUE, NULL, FALSE, FALSE);
1045 if (!$dao->fetch()) {
1046 throw new CRM_Core_Exception('query failed');
1049 $show[$tableName] = $dao->Create_Table
;
1052 return (bool) preg_match("/\b$constraint\b/i", $show[$tableName]);
1056 * Checks if CONSTRAINT keyword exists for a specified table.
1058 * @param array $tables
1060 * @throws CRM_Core_Exception
1063 * true if CONSTRAINT keyword exists, false otherwise
1065 public static function schemaRequiresRebuilding($tables = ["civicrm_contact"]) {
1067 foreach ($tables as $tableName) {
1068 if (!array_key_exists($tableName, $show)) {
1069 $query = "SHOW CREATE TABLE $tableName";
1070 $dao = CRM_Core_DAO
::executeQuery($query, [], TRUE, NULL, FALSE, FALSE);
1072 if (!$dao->fetch()) {
1073 throw new CRM_Core_Exception('Show create table failed.');
1076 $show[$tableName] = $dao->Create_Table
;
1079 $result = (bool) preg_match("/\bCONSTRAINT\b\s/i", $show[$tableName]);
1080 if ($result == TRUE) {
1091 * Checks if the FK constraint name is in the format 'FK_tableName_columnName'
1092 * for a specified column of a table.
1094 * @param string $tableName
1095 * @param string $columnName
1098 * true if in format, false otherwise
1100 * @throws \CRM_Core_Exception
1102 public static function checkFKConstraintInFormat($tableName, $columnName) {
1105 if (!array_key_exists($tableName, $show)) {
1106 $query = "SHOW CREATE TABLE $tableName";
1107 $dao = CRM_Core_DAO
::executeQuery($query);
1109 if (!$dao->fetch()) {
1110 throw new CRM_Core_Exception('query failed');
1113 $show[$tableName] = $dao->Create_Table
;
1115 $constraint = "`FK_{$tableName}_{$columnName}`";
1116 $pattern = "/\bCONSTRAINT\b\s+%s\s+\bFOREIGN\s+KEY\b\s/i";
1117 return (bool) preg_match(sprintf($pattern, $constraint), $show[$tableName]);
1121 * Check whether a specific column in a specific table has always the same value.
1123 * @param string $tableName
1124 * @param string $columnName
1125 * @param string $columnValue
1128 * true if the value is always $columnValue, false otherwise
1130 public static function checkFieldHasAlwaysValue($tableName, $columnName, $columnValue) {
1131 $query = "SELECT * FROM $tableName WHERE $columnName != '$columnValue'";
1132 $dao = CRM_Core_DAO
::executeQuery($query);
1133 $result = $dao->fetch() ?
FALSE : TRUE;
1138 * Check whether a specific column in a specific table is always NULL.
1140 * @param string $tableName
1141 * @param string $columnName
1144 * true if if the value is always NULL, false otherwise
1146 public static function checkFieldIsAlwaysNull($tableName, $columnName) {
1147 $query = "SELECT * FROM $tableName WHERE $columnName IS NOT NULL";
1148 $dao = CRM_Core_DAO
::executeQuery($query);
1149 $result = $dao->fetch() ?
FALSE : TRUE;
1154 * Checks if this DAO's table ought to exist.
1156 * If there are pending DB updates, this function compares the CiviCRM version of the table to the current schema version.
1159 * @throws CRM_Core_Exception
1161 public static function tableHasBeenAdded() {
1162 if (CRM_Utils_System
::version() === CRM_Core_BAO_Domain
::version()) {
1165 $daoExt = defined(static::class . '::EXT') ?
constant(static::class . '::EXT') : NULL;
1166 $daoVersion = defined(static::class . '::TABLE_ADDED') ?
constant(static::class . '::TABLE_ADDED') : '1.0';
1167 return !($daoExt === 'civicrm' && version_compare(CRM_Core_BAO_Domain
::version(), $daoVersion, '<'));
1171 * Check if there is a given table in the database.
1173 * @param string $tableName
1176 * true if exists, else false
1178 public static function checkTableExists($tableName) {
1183 $params = [1 => [$tableName, 'String']];
1185 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1186 return (bool) $dao->fetch();
1190 * Check if a given table has data.
1192 * @param string $tableName
1194 * TRUE if $tableName has at least one record.
1196 public static function checkTableHasData($tableName) {
1197 $c = CRM_Core_DAO
::singleValueQuery(sprintf('SELECT count(*) c FROM `%s`', $tableName));
1206 public function checkVersion($version) {
1207 CRM_Core_Error
::deprecatedFunctionWarning('CRM_Core_BAO_Domain::version');
1208 $dbVersion = CRM_Core_BAO_Domain
::version();
1209 return trim($version) == trim($dbVersion);
1213 * Find a DAO object for the given ID and return it.
1216 * Id of the DAO object being searched for.
1218 * @return CRM_Core_DAO
1219 * Object of the type of the class that called this function.
1223 public static function findById($id) {
1224 $object = new static();
1226 if (!$object->find(TRUE)) {
1227 throw new Exception("Unable to find a " . get_called_class() . " with id {$id}.");
1233 * Returns all results as array-encoded records.
1237 public function fetchAll($k = FALSE, $v = FALSE, $method = FALSE) {
1239 while ($this->fetch()) {
1240 $result[] = $this->toArray();
1246 * Return the results as PHP generator.
1248 * @param string $type
1249 * Whether the generator yields 'dao' objects or 'array's.
1251 public function fetchGenerator($type = 'dao') {
1252 while ($this->fetch()) {
1259 yield
$this->toArray();
1263 throw new \
RuntimeException("Invalid record type ($type)");
1269 * Returns a singular value.
1271 * @return mixed|NULL
1273 public function fetchValue() {
1274 $result = $this->getDatabaseResult();
1275 $row = $result->fetchRow();
1285 * Get all the result records as mapping between columns.
1287 * @param string $keyColumn
1289 * @param string $valueColumn
1292 * Ex: ["foo" => "The Foo Bar", "baz" => "The Baz Qux"]
1294 public function fetchMap($keyColumn, $valueColumn) {
1296 while ($this->fetch()) {
1297 $result[$this->{$keyColumn}] = $this->{$valueColumn};
1303 * Given a DAO name, a column name and a column value, find the record and GET the value of another column in that record
1305 * @param string $daoName
1306 * Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact).
1307 * @param int $searchValue
1308 * Value of the column you want to search by.
1309 * @param string $returnColumn
1310 * Name of the column you want to GET the value of.
1311 * @param string $searchColumn
1312 * Name of the column you want to search by.
1313 * @param bool $force
1314 * Skip use of the cache.
1316 * @return string|int|null
1317 * Value of $returnColumn in the retrieved record
1319 * @throws \CRM_Core_Exception
1321 public static function getFieldValue($daoName, $searchValue, $returnColumn = 'name', $searchColumn = 'id', $force = FALSE) {
1323 empty($searchValue) ||
1324 trim(strtolower($searchValue)) == 'null'
1326 // adding this here since developers forget to check for an id
1327 // or for the 'null' (which is a bad DAO kludge)
1328 // and hence we get the first value in the db
1329 throw new CRM_Core_Exception('getFieldValue failed');
1332 self
::$_dbColumnValueCache = self
::$_dbColumnValueCache ??
[];
1334 while (strpos($daoName, '_BAO_') !== FALSE) {
1335 $daoName = get_parent_class($daoName);
1339 empty(self
::$_dbColumnValueCache[$daoName][$searchColumn][$searchValue]) ||
1340 !array_key_exists($returnColumn, self
::$_dbColumnValueCache[$daoName][$searchColumn][$searchValue])
1342 $object = new $daoName();
1343 $object->$searchColumn = $searchValue;
1344 $object->selectAdd();
1345 $object->selectAdd($returnColumn);
1348 if ($object->find(TRUE)) {
1349 $result = $object->$returnColumn;
1352 self
::$_dbColumnValueCache[$daoName][$searchColumn][$searchValue][$returnColumn] = $result;
1354 return self
::$_dbColumnValueCache[$daoName][$searchColumn][$searchValue][$returnColumn];
1358 * Given a DAO name, a column name and a column value, find the record and SET the value of another column in that record
1360 * @param string $daoName
1361 * Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact).
1362 * @param int $searchValue
1363 * Value of the column you want to search by.
1364 * @param string $setColumn
1365 * Name of the column you want to SET the value of.
1366 * @param string $setValue
1367 * SET the setColumn to this value.
1368 * @param string $searchColumn
1369 * Name of the column you want to search by.
1372 * true if we found and updated the object, else false
1374 public static function setFieldValue($daoName, $searchValue, $setColumn, $setValue, $searchColumn = 'id') {
1375 $object = new $daoName();
1376 $object->selectAdd();
1377 $object->selectAdd("$searchColumn, $setColumn");
1378 $object->$searchColumn = $searchValue;
1380 if ($object->find(TRUE)) {
1381 $object->$setColumn = $setValue;
1382 if ($object->save()) {
1393 * @param array|object $sort either array or CRM_Utils_Sort
1394 * @param string $default
1395 * Default sort value.
1399 public static function getSortString($sort, $default = NULL) {
1400 // check if sort is of type CRM_Utils_Sort
1401 if (is_a($sort, 'CRM_Utils_Sort')) {
1402 return $sort->orderBy();
1407 // is it an array specified as $field => $sortDirection ?
1409 foreach ($sort as $k => $v) {
1410 $sortString .= "$k $v,";
1412 return rtrim($sortString, ',');
1418 * Fetch object based on array of properties.
1420 * @param string $daoName
1421 * Name of the dao object.
1422 * @param array $params
1423 * (reference ) an assoc array of name/value pairs.
1424 * @param array $defaults
1425 * (reference ) an assoc array to hold the flattened values.
1426 * @param array $returnProperities
1427 * An assoc array of fields that need to be returned, eg array( 'first_name', 'last_name').
1430 * an object of type referenced by daoName
1432 public static function commonRetrieve($daoName, &$params, &$defaults, $returnProperities = NULL) {
1433 $object = new $daoName();
1434 $object->copyValues($params);
1436 // return only specific fields if returnproperties are sent
1437 if (!empty($returnProperities)) {
1438 $object->selectAdd();
1439 $object->selectAdd(implode(',', $returnProperities));
1442 if ($object->find(TRUE)) {
1443 self
::storeValues($object, $defaults);
1450 * Delete the object records that are associated with this contact.
1452 * @param string $daoName
1453 * Name of the dao object.
1454 * @param int $contactId
1455 * Id of the contact to delete.
1457 public static function deleteEntityContact($daoName, $contactId) {
1458 $object = new $daoName();
1460 $object->entity_table
= 'civicrm_contact';
1461 $object->entity_id
= $contactId;
1466 * Execute an unbuffered query.
1468 * This is a wrapper around new functionality exposed with CRM-17748.
1470 * @param string $query query to be executed
1472 * @param array $params
1473 * @param bool $abort
1474 * @param null $daoName
1475 * @param bool $freeDAO
1476 * @param bool $i18nRewrite
1477 * @param bool $trapException
1479 * @return CRM_Core_DAO
1480 * Object that points to an unbuffered result set
1482 public static function executeUnbufferedQuery(
1488 $i18nRewrite = TRUE,
1489 $trapException = FALSE
1492 return self
::executeQuery(
1500 ['result_buffering' => 0]
1507 * @param string $query
1508 * Query to be executed.
1510 * @param array $params
1511 * @param bool $abort
1512 * @param null $daoName
1513 * @param bool $freeDAO
1514 * @param bool $i18nRewrite
1515 * @param bool $trapException
1516 * @param array $options
1518 * @return CRM_Core_DAO|object
1519 * object that holds the results of the query
1520 * NB - if this is defined as just returning a DAO phpstorm keeps pointing
1521 * out all the properties that are not part of the DAO
1523 public static function &executeQuery(
1529 $i18nRewrite = TRUE,
1530 $trapException = FALSE,
1533 $queryStr = self
::composeQuery($query, $params, $abort);
1536 $dao = new CRM_Core_DAO();
1539 $dao = new $daoName();
1542 if ($trapException) {
1543 CRM_Core_Error
::deprecatedFunctionWarning('calling functions should handle exceptions');
1544 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
1547 if ($dao->isValidOption($options)) {
1548 $dao->setOptions($options);
1551 $result = $dao->query($queryStr, $i18nRewrite);
1553 // since it is unbuffered, ($dao->N==0) is true. This blocks the standard fetch() mechanism.
1554 if (CRM_Utils_Array
::value('result_buffering', $options) === 0) {
1558 if (is_a($result, 'DB_Error')) {
1559 CRM_Core_Error
::deprecatedFunctionWarning('calling functions should handle exceptions');
1567 * Wrapper to validate internal DAO options before passing to DB_mysql/DB_Common level
1569 * @param array $options
1572 * Provided options are valid
1574 public function isValidOption($options) {
1583 if (empty($options)) {
1587 foreach (array_keys($options) as $option) {
1588 if (!in_array($option, $validOptions)) {
1598 * Execute a query and get the single result.
1600 * @param string $query
1601 * Query to be executed.
1602 * @param array $params
1603 * @param bool $abort
1604 * @param bool $i18nRewrite
1605 * @return string|null
1606 * the result of the query if any
1609 public static function &singleValueQuery(
1615 $queryStr = self
::composeQuery($query, $params, $abort);
1617 static $_dao = NULL;
1620 $_dao = new CRM_Core_DAO();
1623 $_dao->query($queryStr, $i18nRewrite);
1625 $result = $_dao->getDatabaseResult();
1628 $row = $result->fetchRow();
1638 * Compose the query by merging the parameters into it.
1640 * @param string $query
1641 * @param array $params
1642 * @param bool $abort
1645 * @throws CRM_Core_Exception
1647 public static function composeQuery($query, $params = [], $abort = TRUE) {
1649 foreach ($params as $key => $item) {
1650 if (is_numeric($key)) {
1651 if (CRM_Utils_Type
::validate($item[0], $item[1]) !== NULL) {
1652 $item[0] = self
::escapeString($item[0]);
1653 if ($item[1] == 'String' ||
1654 $item[1] == 'Memo' ||
1657 // Support class constants stipulating wildcard characters and/or
1658 // non-quoting of strings. Also support legacy code which may be
1659 // passing in TRUE or 1 for $item[2], which used to indicate the
1660 // use of wildcard characters.
1661 if (!empty($item[2])) {
1662 if ($item[2] & CRM_Core_DAO
::QUERY_FORMAT_WILDCARD ||
$item[2] === TRUE) {
1663 $item[0] = "'%{$item[0]}%'";
1665 elseif (!($item[2] & CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
)) {
1666 $item[0] = "'{$item[0]}'";
1670 $item[0] = "'{$item[0]}'";
1674 if (($item[1] == 'Date' ||
$item[1] == 'Timestamp') &&
1675 strlen($item[0]) == 0
1680 $tr['%' . $key] = $item[0];
1683 throw new CRM_Core_Exception("{$item[0]} is not of type {$item[1]}");
1688 return strtr($query, $tr);
1694 public static function freeResult($ids = NULL) {
1695 global $_DB_DATAOBJECT;
1698 if (!$_DB_DATAOBJECT ||
1699 !isset($_DB_DATAOBJECT['RESULTS'])
1703 $ids = array_keys($_DB_DATAOBJECT['RESULTS']);
1706 foreach ($ids as $id) {
1707 if (isset($_DB_DATAOBJECT['RESULTS'][$id])) {
1708 $_DB_DATAOBJECT['RESULTS'][$id]->free();
1709 unset($_DB_DATAOBJECT['RESULTS'][$id]);
1712 if (isset($_DB_DATAOBJECT['RESULTFIELDS'][$id])) {
1713 unset($_DB_DATAOBJECT['RESULTFIELDS'][$id]);
1719 * Make a shallow copy of an object and all the fields in the object.
1721 * @param string $daoName
1723 * @param array $criteria
1724 * Array of all the fields & values.
1725 * on which basis to copy
1726 * @param array $newData
1727 * Array of all the fields & values.
1728 * to be copied besides the other fields
1729 * @param string $fieldsFix
1730 * Array of fields that you want to prefix/suffix/replace.
1731 * @param string $blockCopyOfDependencies
1732 * Fields that you want to block from.
1734 * @param bool $blockCopyofCustomValues
1735 * Case when you don't want to copy the custom values set in a
1736 * template as it will override/ignore the submitted custom values
1738 * @return CRM_Core_DAO|bool
1739 * the newly created copy of the object. False if none created.
1741 public static function copyGeneric($daoName, $criteria, $newData = NULL, $fieldsFix = NULL, $blockCopyOfDependencies = NULL, $blockCopyofCustomValues = FALSE) {
1742 $object = new $daoName();
1745 $object->id
= $criteria['id'];
1748 foreach ($criteria as $key => $value) {
1749 $object->$key = $value;
1754 while ($object->fetch()) {
1756 // all the objects except with $blockCopyOfDependencies set
1757 // be copied - addresses #CRM-1962
1759 if ($blockCopyOfDependencies && $object->$blockCopyOfDependencies) {
1763 $newObject = new $daoName();
1765 $fields = $object->fields();
1766 if (!is_array($fieldsFix)) {
1767 $fieldsToPrefix = [];
1768 $fieldsToSuffix = [];
1769 $fieldsToReplace = [];
1771 if (!empty($fieldsFix['prefix'])) {
1772 $fieldsToPrefix = $fieldsFix['prefix'];
1774 if (!empty($fieldsFix['suffix'])) {
1775 $fieldsToSuffix = $fieldsFix['suffix'];
1777 if (!empty($fieldsFix['replace'])) {
1778 $fieldsToReplace = $fieldsFix['replace'];
1781 foreach ($fields as $name => $value) {
1782 if ($name == 'id' ||
$value['name'] == 'id') {
1783 // copy everything but the id!
1787 $dbName = $value['name'];
1788 $type = CRM_Utils_Type
::typeToString($value['type']);
1789 $newObject->$dbName = $object->$dbName;
1790 if (isset($fieldsToPrefix[$dbName])) {
1791 $newObject->$dbName = $fieldsToPrefix[$dbName] . $newObject->$dbName;
1793 if (isset($fieldsToSuffix[$dbName])) {
1794 $newObject->$dbName .= $fieldsToSuffix[$dbName];
1796 if (isset($fieldsToReplace[$dbName])) {
1797 $newObject->$dbName = $fieldsToReplace[$dbName];
1800 if ($type == 'Timestamp' ||
$type == 'Date') {
1801 $newObject->$dbName = CRM_Utils_Date
::isoToMysql($newObject->$dbName);
1805 $newObject->copyValues($newData);
1809 if (!$blockCopyofCustomValues) {
1810 $newObject->copyCustomFields($object->id
, $newObject->id
);
1812 CRM_Utils_Hook
::post('create', CRM_Core_DAO_AllCoreTables
::getBriefName($daoName), $newObject->id
, $newObject);
1819 * Method that copies custom fields values from an old entity to a new one.
1821 * Fixes bug CRM-19302,
1822 * where if a custom field of File type was present, left both events using the same file,
1823 * breaking download URL's for the old event.
1825 * @todo the goal here is to clean this up so that it works for any entity. Copy Generic already DOES some custom field stuff
1826 * but it seems to be bypassed & perhaps less good than this (or this just duplicates it...)
1828 * @param int $entityID
1829 * @param int $newEntityID
1831 public function copyCustomFields($entityID, $newEntityID) {
1832 $entity = CRM_Core_DAO_AllCoreTables
::getBriefName(get_class($this));
1833 $tableName = CRM_Core_DAO_AllCoreTables
::getTableForClass(get_class($this));
1834 // Obtain custom values for old event
1835 $customParams = $htmlType = [];
1836 $customValues = CRM_Core_BAO_CustomValueTable
::getEntityValues($entityID, $entity);
1838 // If custom values present, we copy them
1839 if (!empty($customValues)) {
1840 // Get Field ID's and identify File type attributes, to handle file copying.
1841 $fieldIds = implode(', ', array_keys($customValues));
1842 $sql = "SELECT id FROM civicrm_custom_field WHERE html_type = 'File' AND id IN ( {$fieldIds} )";
1843 $result = CRM_Core_DAO
::executeQuery($sql);
1845 // Build array of File type fields
1846 while ($result->fetch()) {
1847 $htmlType[] = $result->id
;
1850 // Build params array of custom values
1851 foreach ($customValues as $field => $value) {
1852 if ($value !== NULL) {
1853 // Handle File type attributes
1854 if (in_array($field, $htmlType)) {
1855 $fileValues = CRM_Core_BAO_File
::path($value, $entityID);
1856 $customParams["custom_{$field}_-1"] = [
1857 'name' => CRM_Utils_File
::duplicate($fileValues[0]),
1858 'type' => $fileValues[1],
1861 // Handle other types
1863 $customParams["custom_{$field}_-1"] = $value;
1868 // Save Custom Fields for new Event
1869 CRM_Core_BAO_CustomValueTable
::postProcess($customParams, $tableName, $newEntityID, $entity);
1872 // copy activity attachments ( if any )
1873 CRM_Core_BAO_File
::copyEntityFile($tableName, $entityID, $tableName, $newEntityID);
1877 * Cascade update through related entities.
1879 * @param string $daoName
1882 * @param array $newData
1884 * @return CRM_Core_DAO|null
1886 public static function cascadeUpdate($daoName, $fromId, $toId, $newData = []) {
1887 $object = new $daoName();
1888 $object->id
= $fromId;
1890 if ($object->find(TRUE)) {
1891 $newObject = new $daoName();
1892 $newObject->id
= $toId;
1894 if ($newObject->find(TRUE)) {
1895 $fields = $object->fields();
1896 foreach ($fields as $name => $value) {
1897 if ($name == 'id' ||
$value['name'] == 'id') {
1898 // copy everything but the id!
1902 $colName = $value['name'];
1903 $newObject->$colName = $object->$colName;
1905 if (substr($name, -5) == '_date' ||
1906 substr($name, -10) == '_date_time'
1908 $newObject->$colName = CRM_Utils_Date
::isoToMysql($newObject->$colName);
1911 foreach ($newData as $k => $v) {
1912 $newObject->$k = $v;
1922 * Given the component id, compute the contact id
1923 * since its used for things like send email
1925 * @param $componentIDs
1926 * @param string $tableName
1927 * @param string $idField
1931 public static function getContactIDsFromComponent($componentIDs, $tableName, $idField = 'id') {
1934 if (empty($componentIDs)) {
1938 $IDs = implode(',', $componentIDs);
1942 WHERE $idField IN ( $IDs )
1945 $dao = CRM_Core_DAO
::executeQuery($query);
1946 while ($dao->fetch()) {
1947 $contactIDs[] = $dao->contact_id
;
1953 * Fetch object based on array of properties.
1955 * @param string $daoName
1956 * Name of the dao object.
1957 * @param string $fieldIdName
1958 * @param int $fieldId
1960 * @param array $returnProperities
1961 * An assoc array of fields that need to be returned, eg array( 'first_name', 'last_name').
1964 * an object of type referenced by daoName
1966 public static function commonRetrieveAll($daoName, $fieldIdName = 'id', $fieldId, &$details, $returnProperities = NULL) {
1967 require_once str_replace('_', DIRECTORY_SEPARATOR
, $daoName) . ".php";
1968 $object = new $daoName();
1969 $object->$fieldIdName = $fieldId;
1971 // return only specific fields if returnproperties are sent
1972 if (!empty($returnProperities)) {
1973 $object->selectAdd();
1974 $object->selectAdd('id');
1975 $object->selectAdd(implode(',', $returnProperities));
1979 while ($object->fetch()) {
1981 self
::storeValues($object, $defaults);
1982 $details[$object->id
] = $defaults;
1989 * Drop all CiviCRM tables.
1991 * @throws \CRM_Core_Exception
1993 public static function dropAllTables() {
1995 // first drop all the custom tables we've created
1996 CRM_Core_BAO_CustomGroup
::dropAllTables();
1998 // drop all multilingual views
1999 CRM_Core_I18n_Schema
::dropAllViews();
2001 CRM_Utils_File
::sourceSQLFile(CIVICRM_DSN
,
2002 dirname(__FILE__
) . DIRECTORY_SEPARATOR
.
2003 '..' . DIRECTORY_SEPARATOR
.
2004 '..' . DIRECTORY_SEPARATOR
.
2005 'sql' . DIRECTORY_SEPARATOR
.
2006 'civicrm_drop.mysql'
2015 public static function escapeString($string) {
2016 static $_dao = NULL;
2018 // If this is an atypical case (e.g. preparing .sql file before CiviCRM
2019 // has been installed), then we fallback DB-less str_replace escaping, as
2020 // we can't use mysqli_real_escape_string, as there is no DB connection.
2021 // Note: In typical usage, escapeString() will only check one conditional
2022 // ("if !$_dao") rather than two conditionals ("if !defined(DSN)")
2023 if (!defined('CIVICRM_DSN')) {
2024 // See http://php.net/manual/en/mysqli.real-escape-string.php for the
2025 // list of characters mysqli_real_escape_string escapes.
2026 $search = ["\\", "\x00", "\n", "\r", "'", '"', "\x1a"];
2027 $replace = ["\\\\", "\\0", "\\n", "\\r", "\'", '\"', "\\Z"];
2028 return str_replace($search, $replace, $string);
2030 $_dao = new CRM_Core_DAO();
2032 return $_dao->escape($string);
2036 * Escape a list of strings for use with "WHERE X IN (...)" queries.
2038 * @param array $strings
2039 * @param string $default
2040 * the value to use if $strings has no elements.
2042 * eg "abc","def","ghi"
2044 public static function escapeStrings($strings, $default = NULL) {
2045 static $_dao = NULL;
2047 $_dao = new CRM_Core_DAO();
2050 if (empty($strings)) {
2054 $escapes = array_map([$_dao, 'escape'], $strings);
2055 return '"' . implode('","', $escapes) . '"';
2063 public static function escapeWildCardString($string) {
2065 // ensure we escape the single characters % and _ which are mysql wild
2066 // card characters and could come in via sortByCharacter
2067 // note that mysql does not escape these characters
2068 if ($string && in_array($string,
2069 ['%', '_', '%%', '_%']
2072 return '\\' . $string;
2075 return self
::escapeString($string);
2079 * Creates a test object, including any required objects it needs via recursion
2080 * createOnly: only create in database, do not store or return the objects (useful for perf testing)
2081 * ONLY USE FOR TESTING
2083 * @param string $daoName
2084 * @param array $params
2085 * @param int $numObjects
2086 * @param bool $createOnly
2088 * @return object|array|NULL
2089 * NULL if $createOnly. A single object if $numObjects==1. Otherwise, an array of multiple objects.
2091 public static function createTestObject(
2097 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
2098 // so we re-set here in case
2099 $config = CRM_Core_Config
::singleton();
2100 $config->backtrace
= TRUE;
2102 static $counter = 0;
2103 CRM_Core_DAO
::$_testEntitiesToSkip = [
2104 'CRM_Core_DAO_Worldregion',
2105 'CRM_Core_DAO_StateProvince',
2106 'CRM_Core_DAO_Country',
2107 'CRM_Core_DAO_Domain',
2108 'CRM_Financial_DAO_FinancialType',
2109 //because valid ones exist & we use pick them due to pseudoconstant can't reliably create & delete these
2112 // Prefer to instantiate BAO's instead of DAO's (when possible)
2113 // so that assignTestValue()/assignTestFK() can be overloaded.
2114 $baoName = str_replace('_DAO_', '_BAO_', $daoName);
2115 if ($baoName === 'CRM_Financial_BAO_FinancialTrxn') {
2116 // OMG OMG OMG this is so incredibly bad. The BAO is insanely named.
2117 // @todo create a new class called what the BAO SHOULD be
2118 // that extends BAO-crazy-name.... migrate.
2119 $baoName = 'CRM_Core_BAO_FinancialTrxn';
2121 if (class_exists($baoName)) {
2122 $daoName = $baoName;
2125 for ($i = 0; $i < $numObjects; ++
$i) {
2128 /** @var CRM_Core_DAO $object */
2129 $object = new $daoName();
2131 $fields = $object->fields();
2132 foreach ($fields as $fieldName => $fieldDef) {
2133 $dbName = $fieldDef['name'];
2134 $FKClassName = $fieldDef['FKClassName'] ??
NULL;
2136 if (isset($params[$dbName]) && !is_array($params[$dbName])) {
2137 $object->$dbName = $params[$dbName];
2140 elseif ($dbName != 'id') {
2141 if ($FKClassName != NULL) {
2142 $object->assignTestFK($fieldName, $fieldDef, $params);
2146 $object->assignTestValue($fieldName, $fieldDef, $counter);
2154 $objects[$i] = $object;
2164 elseif ($numObjects == 1) {
2173 * Deletes the this object plus any dependent objects that are associated with it.
2174 * ONLY USE FOR TESTING
2176 * @param string $daoName
2177 * @param array $params
2179 public static function deleteTestObjects($daoName, $params = []) {
2180 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
2181 // so we re-set here in case
2182 $config = CRM_Core_Config
::singleton();
2183 $config->backtrace
= TRUE;
2185 $object = new $daoName();
2186 $object->id
= $params['id'] ??
NULL;
2188 // array(array(0 => $daoName, 1 => $daoParams))
2190 if ($object->find(TRUE)) {
2192 $fields = $object->fields();
2193 foreach ($fields as $name => $value) {
2195 $dbName = $value['name'];
2197 $FKClassName = $value['FKClassName'] ??
NULL;
2198 $required = $value['required'] ??
NULL;
2199 if ($FKClassName != NULL
2201 && !in_array($FKClassName, CRM_Core_DAO
::$_testEntitiesToSkip)
2202 && ($required ||
$dbName == 'contact_id')
2203 //I'm a bit stuck on this one - we might need to change the singleValueAlter so that the entities don't share a contact
2204 // to make this test process pass - line below makes pass for now
2205 && $dbName != 'member_of_contact_id'
2208 $deletions[] = [$FKClassName, ['id' => $object->$dbName]];
2215 foreach ($deletions as $deletion) {
2216 CRM_Core_DAO
::deleteTestObjects($deletion[0], $deletion[1]);
2221 * Set defaults when creating new entity.
2222 * (don't call this set defaults as already in use with different signature in some places)
2224 * @param array $params
2227 public static function setCreateDefaults(&$params, $defaults) {
2228 if (!empty($params['id'])) {
2231 foreach ($defaults as $key => $value) {
2232 if (!array_key_exists($key, $params) ||
$params[$key] === NULL) {
2233 $params[$key] = $value;
2239 * @param string $prefix
2240 * @param bool $addRandomString
2241 * @param null $string
2245 * @see CRM_Utils_SQL_TempTable
2247 public static function createTempTableName($prefix = 'civicrm', $addRandomString = TRUE, $string = NULL) {
2248 CRM_Core_Error
::deprecatedFunctionWarning('Use CRM_Utils_SQL_TempTable interface to create temporary tables');
2249 $tableName = $prefix . "_temp";
2251 if ($addRandomString) {
2253 $tableName .= "_" . $string;
2256 $tableName .= "_" . md5(uniqid('', TRUE));
2264 * @param bool $trigger
2268 public static function checkTriggerViewPermission($view = TRUE, $trigger = TRUE) {
2269 if (\Civi
::settings()->get('logging_no_trigger_permission')) {
2272 // test for create view and trigger permissions and if allowed, add the option to go multilingual
2274 // I'm not sure why we use the getStaticProperty for an error, rather than checking for DB_Error
2275 CRM_Core_TemporaryErrorScope
::ignoreException();
2276 $dao = new CRM_Core_DAO();
2278 $result = $dao->query('CREATE OR REPLACE VIEW civicrm_domain_view AS SELECT * FROM civicrm_domain');
2279 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError') ||
is_a($result, 'DB_Error')) {
2285 $result = $dao->query('CREATE TRIGGER civicrm_domain_trigger BEFORE INSERT ON civicrm_domain FOR EACH ROW BEGIN END');
2286 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError') ||
is_a($result, 'DB_Error')) {
2288 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
2293 $dao->query('DROP TRIGGER IF EXISTS civicrm_domain_trigger');
2294 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
2296 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
2303 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
2304 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
2313 * @param null $message
2314 * @param bool $printDAO
2316 public static function debugPrint($message = NULL, $printDAO = TRUE) {
2317 CRM_Utils_System
::xMemory("{$message}: ");
2320 global $_DB_DATAOBJECT;
2322 foreach (array_keys($_DB_DATAOBJECT['RESULTS']) as $id) {
2323 $q[] = $_DB_DATAOBJECT['RESULTS'][$id]->query
;
2325 CRM_Core_Error
::debug('_DB_DATAOBJECT', $q);
2330 * Build a list of triggers via hook and add them to (err, reconcile them
2331 * with) the database.
2333 * @param string $tableName
2334 * the specific table requiring a rebuild; or NULL to rebuild all tables.
2335 * @param bool $force
2340 public static function triggerRebuild($tableName = NULL, $force = FALSE) {
2341 Civi
::service('sql_triggers')->rebuild($tableName, $force);
2345 * Because sql functions are sometimes lost, esp during db migration, we check here to avoid numerous support requests
2346 * @see http://issues.civicrm.org/jira/browse/CRM-13822
2347 * TODO: Alternative solutions might be
2348 * * Stop using functions and find another way to strip numeric characters from phones
2349 * * Give better error messages (currently a missing fn fatals with "unknown error")
2351 public static function checkSqlFunctionsExist() {
2352 if (!self
::$_checkedSqlFunctionsExist) {
2353 self
::$_checkedSqlFunctionsExist = TRUE;
2354 $dao = CRM_Core_DAO
::executeQuery("SHOW function status WHERE db = database() AND name = 'civicrm_strip_non_numeric'");
2355 if (!$dao->fetch()) {
2356 self
::triggerRebuild();
2362 * Wrapper function to drop triggers.
2364 * @param string $tableName
2365 * the specific table requiring a rebuild; or NULL to rebuild all tables.
2368 public static function dropTriggers($tableName = NULL) {
2369 Civi
::service('sql_triggers')->dropTriggers($tableName);
2373 * @param array $info
2374 * per hook_civicrm_triggerInfo.
2375 * @param string $onlyTableName
2376 * the specific table requiring a rebuild; or NULL to rebuild all tables.
2379 public static function createTriggers(&$info, $onlyTableName = NULL) {
2380 Civi
::service('sql_triggers')->createTriggers($info, $onlyTableName);
2384 * Given a list of fields, create a list of references.
2386 * @param string $className
2387 * BAO/DAO class name.
2388 * @return array<CRM_Core_Reference_Interface>
2390 public static function createReferenceColumns($className) {
2392 $fields = $className::fields();
2393 foreach ($fields as $field) {
2394 if (isset($field['pseudoconstant'], $field['pseudoconstant']['optionGroupName'])) {
2395 $result[] = new CRM_Core_Reference_OptionValue(
2396 $className::getTableName(),
2398 'civicrm_option_value',
2399 CRM_Utils_Array
::value('keyColumn', $field['pseudoconstant'], 'value'),
2400 $field['pseudoconstant']['optionGroupName']
2408 * Find all records which refer to this entity.
2411 * Array of objects referencing this
2413 public function findReferences() {
2414 $links = self
::getReferencesToTable(static::getTableName());
2417 foreach ($links as $refSpec) {
2418 /** @var $refSpec CRM_Core_Reference_Interface */
2419 $daoName = CRM_Core_DAO_AllCoreTables
::getClassForTable($refSpec->getReferenceTable());
2420 $result = $refSpec->findReferences($this);
2422 while ($result->fetch()) {
2423 $obj = new $daoName();
2424 $obj->id
= $result->id
;
2425 $occurrences[] = $obj;
2430 return $occurrences;
2435 * each item has keys:
2439 * - table: string|null SQL table name
2440 * - key: string|null SQL column name
2442 public function getReferenceCounts() {
2443 $links = self
::getReferencesToTable(static::getTableName());
2446 foreach ($links as $refSpec) {
2447 /** @var $refSpec CRM_Core_Reference_Interface */
2448 $count = $refSpec->getReferenceCount($this);
2449 if ($count['count'] != 0) {
2454 foreach (CRM_Core_Component
::getEnabledComponents() as $component) {
2455 /** @var $component CRM_Core_Component_Info */
2456 $counts = array_merge($counts, $component->getReferenceCounts($this));
2458 CRM_Utils_Hook
::referenceCounts($this, $counts);
2464 * List all tables which have hard foreign keys to this table.
2466 * For now, this returns a description of every entity_id/entity_table
2468 * TODO: filter dynamic entity references on the $tableName, based on
2469 * schema metadata in dynamicForeignKey which enumerates a restricted
2470 * set of possible entity_table's.
2472 * @param string $tableName
2473 * Table referred to.
2476 * structure of table and column, listing every table with a
2477 * foreign key reference to $tableName, and the column where the key appears.
2479 public static function getReferencesToTable($tableName) {
2481 foreach (CRM_Core_DAO_AllCoreTables
::getClasses() as $daoClassName) {
2482 $links = $daoClassName::getReferenceColumns();
2484 foreach ($links as $refSpec) {
2485 /** @var $refSpec CRM_Core_Reference_Interface */
2486 if ($refSpec->matchesTargetTable($tableName)) {
2487 $refsFound[] = $refSpec;
2495 * Get all references to contact table.
2497 * This includes core tables, custom group tables, tables added by the merge
2498 * hook and the entity_tag table.
2500 * Refer to CRM-17454 for information on the danger of querying the information
2501 * schema to derive this.
2503 * @throws \CiviCRM_API3_Exception
2505 public static function getReferencesToContactTable() {
2506 if (isset(\Civi
::$statics[__CLASS__
]) && isset(\Civi
::$statics[__CLASS__
]['contact_references'])) {
2507 return \Civi
::$statics[__CLASS__
]['contact_references'];
2509 $contactReferences = [];
2510 $coreReferences = CRM_Core_DAO
::getReferencesToTable('civicrm_contact');
2511 foreach ($coreReferences as $coreReference) {
2512 if (!is_a($coreReference, 'CRM_Core_Reference_Dynamic')) {
2513 $contactReferences[$coreReference->getReferenceTable()][] = $coreReference->getReferenceKey();
2516 self
::appendCustomTablesExtendingContacts($contactReferences);
2517 self
::appendCustomContactReferenceFields($contactReferences);
2518 \Civi
::$statics[__CLASS__
]['contact_references'] = $contactReferences;
2519 return \Civi
::$statics[__CLASS__
]['contact_references'];
2523 * Get all dynamic references to the given table.
2525 * @param string $tableName
2529 public static function getDynamicReferencesToTable($tableName) {
2530 if (!isset(\Civi
::$statics[__CLASS__
]['contact_references_dynamic'][$tableName])) {
2531 \Civi
::$statics[__CLASS__
]['contact_references_dynamic'][$tableName] = [];
2532 $coreReferences = CRM_Core_DAO
::getReferencesToTable($tableName);
2533 foreach ($coreReferences as $coreReference) {
2534 if ($coreReference instanceof \CRM_Core_Reference_Dynamic
) {
2535 \Civi
::$statics[__CLASS__
]['contact_references_dynamic'][$tableName][$coreReference->getReferenceTable()][] = [$coreReference->getReferenceKey(), $coreReference->getTypeColumn()];
2539 return \Civi
::$statics[__CLASS__
]['contact_references_dynamic'][$tableName];
2543 * Add custom tables that extend contacts to the list of contact references.
2545 * CRM_Core_BAO_CustomGroup::getAllCustomGroupsByBaseEntity seems like a safe-ish
2546 * function to be sure all are retrieved & we don't miss subtypes or inactive or multiples
2547 * - the down side is it is not cached.
2549 * Further changes should be include tests in the CRM_Core_MergerTest class
2550 * to ensure that disabled, subtype, multiple etc groups are still captured.
2552 * @param array $cidRefs
2554 public static function appendCustomTablesExtendingContacts(&$cidRefs) {
2555 $customValueTables = CRM_Core_BAO_CustomGroup
::getAllCustomGroupsByBaseEntity('Contact');
2556 $customValueTables->find();
2557 while ($customValueTables->fetch()) {
2558 $cidRefs[$customValueTables->table_name
][] = 'entity_id';
2563 * Add custom ContactReference fields to the list of contact references
2565 * This includes active and inactive fields/groups
2567 * @param array $cidRefs
2569 * @throws \CiviCRM_API3_Exception
2571 public static function appendCustomContactReferenceFields(&$cidRefs) {
2572 $fields = civicrm_api3('CustomField', 'get', [
2573 'return' => ['column_name', 'custom_group_id.table_name'],
2574 'data_type' => 'ContactReference',
2575 'options' => ['limit' => 0],
2577 foreach ($fields as $field) {
2578 $cidRefs[$field['custom_group_id.table_name']][] = $field['column_name'];
2583 * Lookup the value of a MySQL global configuration variable.
2585 * @param string $name
2586 * E.g. "thread_stack".
2587 * @param mixed $default
2590 public static function getGlobalSetting($name, $default = NULL) {
2591 // Alternatively, SELECT @@GLOBAL.thread_stack, but
2592 // that has been reported to fail under MySQL 5.0 for OS X
2593 $escapedName = self
::escapeString($name);
2594 $dao = CRM_Core_DAO
::executeQuery("SHOW VARIABLES LIKE '$escapedName'");
2595 if ($dao->fetch()) {
2604 * Update the fields array to also hold keys for pseudoconstant fields that relate to contained fields.
2606 * This is relevant where we want to offer both the ID field and the label field
2607 * as an option, e.g. search builder.
2609 * It is currently limited for optionGroupName & id+ name+ FK combos for purposes keeping the scope of the
2610 * change small, but is appropriate for other sorts of pseudoconstants.
2612 * @param array $fields
2614 public static function appendPseudoConstantsToFields(&$fields) {
2615 foreach ($fields as $fieldUniqueName => $field) {
2616 if (!empty($field['pseudoconstant'])) {
2617 $pseudoConstant = $field['pseudoconstant'];
2618 if (!empty($pseudoConstant['optionGroupName'])) {
2619 $fields[$pseudoConstant['optionGroupName']] = [
2620 'title' => CRM_Core_BAO_OptionGroup
::getTitleByName($pseudoConstant['optionGroupName']),
2621 'name' => $pseudoConstant['optionGroupName'],
2622 'data_type' => CRM_Utils_Type
::T_STRING
,
2623 'is_pseudofield_for' => $fieldUniqueName,
2626 // We restrict to id + name + FK as we are extending this a bit, but cautiously.
2628 !empty($field['FKClassName'])
2629 && CRM_Utils_Array
::value('keyColumn', $pseudoConstant) === 'id'
2630 && CRM_Utils_Array
::value('labelColumn', $pseudoConstant) === 'name'
2632 $pseudoFieldName = str_replace('_' . $pseudoConstant['keyColumn'], '', $field['name']);
2633 // This if is just an extra caution when adding change.
2634 if (!isset($fields[$pseudoFieldName])) {
2635 $daoName = $field['FKClassName'];
2636 $fkFields = $daoName::fields();
2637 foreach ($fkFields as $fkField) {
2638 if ($fkField['name'] === $pseudoConstant['labelColumn']) {
2639 $fields[$pseudoFieldName] = [
2640 'name' => $pseudoFieldName,
2641 'is_pseudofield_for' => $field['name'],
2642 'title' => $fkField['title'],
2643 'data_type' => $fkField['type'],
2644 'where' => $field['where'],
2655 * Get options for the called BAO object's field.
2657 * This function can be overridden by each BAO to add more logic related to context.
2658 * The overriding function will generally call the lower-level CRM_Core_PseudoConstant::get
2660 * @param string $fieldName
2661 * @param string $context
2662 * @see CRM_Core_DAO::buildOptionsContext
2663 * @param array $props
2664 * Raw field values; whatever is known about this bao object.
2666 * Note: $props can contain unsanitized input and should not be passed directly to CRM_Core_PseudoConstant::get
2668 * @return array|bool
2670 public static function buildOptions($fieldName, $context = NULL, $props = []) {
2671 // If a given bao does not override this function
2672 $baoName = get_called_class();
2673 return CRM_Core_PseudoConstant
::get($baoName, $fieldName, [], $context);
2677 * Populate option labels for this object's fields.
2679 * @throws exception if called directly on the base class
2681 public function getOptionLabels() {
2682 $fields = $this->fields();
2683 if ($fields === NULL) {
2684 throw new Exception('Cannot call getOptionLabels on CRM_Core_DAO');
2686 foreach ($fields as $field) {
2687 $name = $field['name'] ??
NULL;
2688 if ($name && isset($this->$name)) {
2689 $label = CRM_Core_PseudoConstant
::getLabel(get_class($this), $name, $this->$name);
2690 if ($label !== FALSE) {
2691 // Append 'label' onto the field name
2692 $labelName = $name . '_label';
2693 $this->$labelName = $label;
2700 * Provides documentation and validation for the buildOptions $context param
2702 * @param string $context
2704 * @throws CRM_Core_Exception
2707 public static function buildOptionsContext($context = NULL) {
2709 'get' => "get: all options are returned, even if they are disabled; labels are translated.",
2710 'create' => "create: options are filtered appropriately for the object being created/updated; labels are translated.",
2711 'search' => "search: searchable options are returned; labels are translated.",
2712 'validate' => "validate: all options are returned, even if they are disabled; machine names are used in place of labels.",
2713 'abbreviate' => "abbreviate: enabled options are returned; labels are replaced with abbreviations.",
2714 'match' => "match: enabled options are returned using machine names as keys; labels are translated.",
2716 // Validation: enforce uniformity of this param
2717 if ($context !== NULL && !isset($contexts[$context])) {
2718 throw new CRM_Core_Exception("'$context' is not a valid context for buildOptions.");
2724 * @param string $fieldName
2725 * @return bool|array
2727 public function getFieldSpec($fieldName) {
2728 $fields = $this->fields();
2729 $fieldKeys = $this->fieldKeys();
2731 // Support "unique names" as well as sql names
2732 $fieldKey = $fieldName;
2733 if (empty($fields[$fieldKey])) {
2734 $fieldKey = $fieldKeys[$fieldName] ??
NULL;
2736 // If neither worked then this field doesn't exist. Return false.
2737 if (empty($fields[$fieldKey])) {
2740 return $fields[$fieldKey];
2744 * Get SQL where clause for SQL filter syntax input parameters.
2746 * SQL version of api function to assign filters to the DAO based on the syntax
2747 * $field => array('IN' => array(4,6,9))
2749 * $field => array('LIKE' => array('%me%))
2752 * @param string $fieldName
2754 * @param array $filter
2755 * filter to be applied indexed by operator.
2756 * @param string $type
2757 * type of field (not actually used - nor in api @todo ).
2758 * @param string $alias
2759 * alternative field name ('as') @todo- not actually used.
2760 * @param bool $returnSanitisedArray
2761 * Return a sanitised array instead of a clause.
2762 * this is primarily so we can add filters @ the api level to the Query object based fields
2766 * @return NULL|string|array
2767 * a string is returned if $returnSanitisedArray is not set, otherwise and Array or NULL
2768 * depending on whether it is supported as yet
2770 public static function createSQLFilter($fieldName, $filter, $type = NULL, $alias = NULL, $returnSanitisedArray = FALSE) {
2771 foreach ($filter as $operator => $criteria) {
2772 if (in_array($operator, self
::acceptedSQLOperators(), TRUE)) {
2773 switch ($operator) {
2777 if (!$returnSanitisedArray) {
2778 return (sprintf('%s %s', $fieldName, $operator));
2781 return (sprintf('%s %s ', $fieldName, $operator));
2785 // ternary operators
2788 if ((empty($criteria[0]) && !in_array($criteria[0], ['0', 0]))||
(empty($criteria[1]) && !in_array($criteria[1], ['0', 0]))) {
2789 throw new Exception("invalid criteria for $operator");
2791 if (!$returnSanitisedArray) {
2792 return (sprintf('%s ' . $operator . ' "%s" AND "%s"', $fieldName, CRM_Core_DAO
::escapeString($criteria[0]), CRM_Core_DAO
::escapeString($criteria[1])));
2795 // not yet implemented (tests required to implement)
2803 if (empty($criteria)) {
2804 throw new Exception("invalid criteria for $operator");
2806 $escapedCriteria = array_map([
2810 if (!$returnSanitisedArray) {
2811 return (sprintf('%s %s ("%s")', $fieldName, $operator, implode('", "', $escapedCriteria)));
2813 return $escapedCriteria;
2818 if (!$returnSanitisedArray) {
2819 return (sprintf('%s %s "%s"', $fieldName, $operator, CRM_Core_DAO
::escapeString($criteria)));
2822 // not yet implemented (tests required to implement)
2831 * @see http://issues.civicrm.org/jira/browse/CRM-9150
2832 * support for other syntaxes is discussed in ticket but being put off for now
2835 public static function acceptedSQLOperators() {
2856 * SQL has a limit of 64 characters on various names:
2857 * table name, trigger name, column name ...
2859 * For custom groups and fields we generated names from user entered input
2860 * which can be longer than this length, this function helps with creating
2861 * strings that meet various criteria.
2863 * @param string $string
2864 * The string to be shortened.
2865 * @param int $length
2866 * The max length of the string.
2868 * @param bool $makeRandom
2872 public static function shortenSQLName($string, $length = 60, $makeRandom = FALSE) {
2873 // early return for strings that meet the requirements
2874 if (strlen($string) <= $length) {
2878 // easy return for calls that dont need a randomized uniq string
2880 return substr($string, 0, $length);
2883 // the string is longer than the length and we need a uniq string
2884 // for the same tablename we need the same uniq string every time
2885 // hence we use md5 on the string, which is not random
2886 // we'll append 8 characters to the end of the tableName
2887 $md5string = substr(md5($string), 0, 8);
2888 return substr($string, 0, $length - 8) . "_{$md5string}";
2892 * https://issues.civicrm.org/jira/browse/CRM-17748
2893 * Sets the internal options to be used on a query
2895 * @param array $options
2898 public function setOptions($options) {
2899 if (is_array($options)) {
2900 $this->_options
= $options;
2905 * https://issues.civicrm.org/jira/browse/CRM-17748
2906 * wrapper to pass internal DAO options down to DB_mysql/DB_Common level
2908 * @param array $options
2911 protected function _setDBOptions($options) {
2912 global $_DB_DATAOBJECT;
2914 if (is_array($options) && count($options)) {
2915 $conn = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5
];
2916 foreach ($options as $option_name => $option_value) {
2917 $conn->setOption($option_name, $option_value);
2924 * @param array $params
2926 public function setApiFilter(&$params) {
2930 * Generates acl clauses suitable for adding to WHERE or ON when doing an api.get for this entity
2932 * Return format is in the form of fieldname => clauses starting with an operator. e.g.:
2935 * 'location_type_id' => array('IS NOT NULL', 'IN (1,2,3)')
2939 * Note that all array keys must be actual field names in this entity. Use subqueries to filter on other tables e.g. custom values.
2943 public function addSelectWhereClause() {
2945 $fields = $this->fields();
2946 foreach ($fields as $fieldName => $field) {
2947 // Clause for contact-related entities like Email, Relationship, etc.
2948 if (strpos($fieldName, 'contact_id') === 0 && CRM_Utils_Array
::value('FKClassName', $field) == 'CRM_Contact_DAO_Contact') {
2949 $clauses[$fieldName] = CRM_Utils_SQL
::mergeSubquery('Contact');
2951 // Clause for an entity_table/entity_id combo
2952 if ($fieldName == 'entity_id' && isset($fields['entity_table'])) {
2953 $relatedClauses = [];
2954 $relatedEntities = $this->buildOptions('entity_table', 'get');
2955 foreach ((array) $relatedEntities as $table => $ent) {
2957 $ent = CRM_Core_DAO_AllCoreTables
::getBriefName(CRM_Core_DAO_AllCoreTables
::getClassForTable($table));
2958 $subquery = CRM_Utils_SQL
::mergeSubquery($ent);
2960 $relatedClauses[] = "(entity_table = '$table' AND entity_id " . implode(' AND entity_id ', $subquery) . ")";
2963 $relatedClauses[] = "(entity_table = '$table')";
2967 if ($relatedClauses) {
2968 $clauses['id'] = 'IN (SELECT id FROM `' . $this->tableName() . '` WHERE (' . implode(') OR (', $relatedClauses) . '))';
2972 CRM_Utils_Hook
::selectWhereClause($this, $clauses);
2977 * This returns the final permissioned query string for this entity
2979 * With acls from related entities + additional clauses from hook_civicrm_selectWhereClause
2981 * @param string $tableAlias
2984 public static function getSelectWhereClause($tableAlias = NULL) {
2985 $bao = new static();
2986 if ($tableAlias === NULL) {
2987 $tableAlias = $bao->tableName();
2990 foreach ((array) $bao->addSelectWhereClause() as $field => $vals) {
2991 $clauses[$field] = NULL;
2993 $clauses[$field] = "(`$tableAlias`.`$field` IS NULL OR (`$tableAlias`.`$field` " . implode(" AND `$tableAlias`.`$field` ", (array) $vals) . '))';
3000 * ensure database name is 'safe', i.e. only contains word characters (includes underscores)
3001 * and dashes, and contains at least one [a-z] case insenstive.
3007 public static function requireSafeDBName($database) {
3010 "/^[\w\-]*[a-z]+[\w\-]*$/i",
3014 if (empty($matches)) {
3021 * Transform an array to a serialized string for database storage.
3023 * @param array|null $value
3024 * @param int $serializationType
3025 * @return string|null
3027 * @throws \Exception
3029 public static function serializeField($value, $serializationType) {
3030 if ($value === NULL) {
3033 switch ($serializationType) {
3034 case self
::SERIALIZE_SEPARATOR_BOOKEND
:
3035 return $value === [] ?
'' : CRM_Utils_Array
::implodePadded($value);
3037 case self
::SERIALIZE_SEPARATOR_TRIMMED
:
3038 return is_array($value) ?
implode(self
::VALUE_SEPARATOR
, $value) : $value;
3040 case self
::SERIALIZE_JSON
:
3041 return is_array($value) ?
json_encode($value) : $value;
3043 case self
::SERIALIZE_PHP
:
3044 return is_array($value) ?
serialize($value) : $value;
3046 case self
::SERIALIZE_COMMA
:
3047 return is_array($value) ?
implode(',', $value) : $value;
3050 throw new Exception('Unknown serialization method for field.');
3055 * Transform a serialized string from the database into an array.
3057 * @param string|null $value
3058 * @param $serializationType
3060 * @return array|null
3061 * @throws CRM_Core_Exception
3063 public static function unSerializeField($value, $serializationType) {
3064 if ($value === NULL) {
3067 if ($value === '') {
3070 switch ($serializationType) {
3071 case self
::SERIALIZE_SEPARATOR_BOOKEND
:
3072 return (array) CRM_Utils_Array
::explodePadded($value);
3074 case self
::SERIALIZE_SEPARATOR_TRIMMED
:
3075 return explode(self
::VALUE_SEPARATOR
, trim($value));
3077 case self
::SERIALIZE_JSON
:
3078 return strlen($value) ?
json_decode($value, TRUE) : [];
3080 case self
::SERIALIZE_PHP
:
3081 return strlen($value) ? CRM_Utils_String
::unserialize($value) : [];
3083 case self
::SERIALIZE_COMMA
:
3084 return explode(',', trim(str_replace(', ', '', $value)));
3087 throw new CRM_Core_Exception('Unknown serialization method for field.');
3094 public static function getEntityRefFilters() {
3099 * Get exportable fields with pseudoconstants rendered as an extra field.
3101 * @param string $baoClass
3105 public static function getExportableFieldsWithPseudoConstants($baoClass) {
3106 if (method_exists($baoClass, 'exportableFields')) {
3107 $fields = $baoClass::exportableFields();
3110 $fields = $baoClass::export();
3112 CRM_Core_DAO
::appendPseudoConstantsToFields($fields);
3117 * Remove item from static cache during update/delete operations
3119 private function clearDbColumnValueCache() {
3120 $daoName = get_class($this);
3121 while (strpos($daoName, '_BAO_') !== FALSE) {
3122 $daoName = get_parent_class($daoName);
3124 if (isset($this->id
)) {
3125 unset(self
::$_dbColumnValueCache[$daoName]['id'][$this->id
]);
3127 if (isset($this->name
)) {
3128 unset(self
::$_dbColumnValueCache[$daoName]['name'][$this->name
]);