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 * Primary key field(s).
40 public static $_primaryKey = ['id'];
43 * How many times has this instance been cloned.
47 protected $resultCopies = 0;
53 public static $_nullObject = NULL;
56 * Icon associated with this entity.
60 public static $_icon = NULL;
63 * Field to show when displaying a record.
67 public static $_labelField = NULL;
73 public static $_nullArray = [];
75 public static $_dbColumnValueCache = NULL;
76 const NOT_NULL
= 1, IS_NULL
= 2,
78 VALUE_SEPARATOR
= "\ 1",
79 BULK_INSERT_COUNT
= 200,
80 BULK_INSERT_HIGH_COUNT
= 200,
81 QUERY_FORMAT_WILDCARD
= 1,
82 QUERY_FORMAT_NO_QUOTES
= 2,
85 * Serialized string separated by and bookended with VALUE_SEPARATOR
87 SERIALIZE_SEPARATOR_BOOKEND
= 1,
89 * @deprecated format separated by VALUE_SEPARATOR
91 SERIALIZE_SEPARATOR_TRIMMED
= 2,
93 * Recommended serialization format
97 * @deprecated format using php serialize()
101 * Comma separated string, no quotes, no spaces
106 * Define entities that shouldn't be created or deleted when creating/ deleting
107 * test objects - this prevents world regions, countries etc from being added / deleted
110 public static $_testEntitiesToSkip = [];
112 * The factory class for this application.
115 public static $_factory = NULL;
118 * https://issues.civicrm.org/jira/browse/CRM-17748
119 * internal variable for DAO to hold per-query settings
122 protected $_options = [];
127 * @return \CRM_Core_DAO
129 public function __construct() {
131 $this->__table
= $this->getTableName();
135 * Returns localized title of this entity.
139 public static function getEntityTitle() {
140 $className = static::class;
141 CRM_Core_Error
::deprecatedWarning("$className needs to be regenerated. Missing getEntityTitle method.");
142 return CRM_Core_DAO_AllCoreTables
::getBriefName($className);
146 * Returns user-friendly description of this entity.
148 * @return string|null
150 public static function getEntityDescription() {
154 public function __clone() {
155 if (!empty($this->_DB_resultid
)) {
156 $this->resultCopies++
;
163 public function __destruct() {
164 if ($this->resultCopies
=== 0) {
167 $this->resultCopies
--;
171 * Returns the name of this table
175 public static function getTableName() {
176 return self
::getLocaleTableName(static::$_tableName ??
NULL);
180 * Returns if this table needs to be logged
184 public function getLog() {
185 return static::$_log ??
FALSE;
189 * Initialize the DAO object.
192 * The database connection string.
194 public static function init($dsn) {
195 Civi
::$statics[__CLASS__
]['init'] = 1;
196 $options = &PEAR
::getStaticProperty('DB_DataObject', 'options');
197 $dsn = CRM_Utils_SQL
::autoSwitchDSN($dsn);
198 $options['database'] = $dsn;
199 $options['quote_identifiers'] = TRUE;
200 if (CRM_Utils_SQL
::isSSLDSN($dsn)) {
201 // There are two different options arrays.
202 $other_options = &PEAR
::getStaticProperty('DB', 'options');
203 $other_options['ssl'] = TRUE;
205 if (defined('CIVICRM_DAO_DEBUG')) {
206 self
::DebugLevel(CIVICRM_DAO_DEBUG
);
208 $factory = new CRM_Contact_DAO_Factory();
209 CRM_Core_DAO
::setFactory($factory);
210 CRM_Core_DAO
::executeQuery('SET NAMES utf8mb4');
211 CRM_Core_DAO
::executeQuery('SET @uniqueID = %1', [1 => [CRM_Utils_Request
::id(), 'String']]);
217 public static function getConnection() {
218 global $_DB_DATAOBJECT;
219 $dao = new CRM_Core_DAO();
220 return $_DB_DATAOBJECT['CONNECTIONS'][$dao->_database_dsn_md5
];
224 * Disables usage of the ONLY_FULL_GROUP_BY Mode if necessary
226 public static function disableFullGroupByMode() {
227 $currentModes = CRM_Utils_SQL
::getSqlModes();
228 if (in_array('ONLY_FULL_GROUP_BY', $currentModes) && CRM_Utils_SQL
::isGroupByModeInDefault()) {
229 $key = array_search('ONLY_FULL_GROUP_BY', $currentModes);
230 unset($currentModes[$key]);
231 CRM_Core_DAO
::executeQuery("SET SESSION sql_mode = %1", [1 => [implode(',', $currentModes), 'String']]);
236 * Re-enables ONLY_FULL_GROUP_BY sql_mode as necessary..
238 public static function reenableFullGroupByMode() {
239 $currentModes = CRM_Utils_SQL
::getSqlModes();
240 if (!in_array('ONLY_FULL_GROUP_BY', $currentModes) && CRM_Utils_SQL
::isGroupByModeInDefault()) {
241 $currentModes[] = 'ONLY_FULL_GROUP_BY';
242 CRM_Core_DAO
::executeQuery("SET SESSION sql_mode = %1", [1 => [implode(',', $currentModes), 'String']]);
247 * @param string $fieldName
249 * @param array $params
251 protected function assignTestFK($fieldName, $fieldDef, $params) {
252 $required = $fieldDef['required'] ??
NULL;
253 $FKClassName = $fieldDef['FKClassName'] ??
NULL;
254 $dbName = $fieldDef['name'];
255 $daoName = str_replace('_BAO_', '_DAO_', get_class($this));
257 // skip the FK if it is not required
258 // if it's contact id we should create even if not required
259 // we'll have a go @ fetching first though
260 // we WILL create campaigns though for so tests with a campaign pseudoconstant will complete
261 if ($FKClassName === 'CRM_Campaign_DAO_Campaign' && $daoName != $FKClassName) {
264 if (!$required && $dbName != 'contact_id') {
265 $fkDAO = new $FKClassName();
266 if ($fkDAO->find(TRUE)) {
267 $this->$dbName = $fkDAO->id
;
271 elseif (in_array($FKClassName, CRM_Core_DAO
::$_testEntitiesToSkip)) {
272 $depObject = new $FKClassName();
273 $depObject->find(TRUE);
274 $this->$dbName = $depObject->id
;
276 elseif ($daoName == 'CRM_Member_DAO_MembershipType' && $fieldName == 'member_of_contact_id') {
277 // FIXME: the fields() metadata is not specific enough
278 $depObject = CRM_Core_DAO
::createTestObject($FKClassName, ['contact_type' => 'Organization']);
279 $this->$dbName = $depObject->id
;
282 //if it is required we need to generate the dependency object first
283 $depObject = CRM_Core_DAO
::createTestObject($FKClassName, CRM_Utils_Array
::value($dbName, $params, 1));
284 $this->$dbName = $depObject->id
;
289 * Generate and assign an arbitrary value to a field of a test object.
291 * @param string $fieldName
292 * @param array $fieldDef
293 * @param int $counter
294 * The globally-unique ID of the test object.
296 * @throws \CRM_Core_Exception
298 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
299 $dbName = $fieldDef['name'];
300 $daoName = get_class($this);
303 if (in_array($dbName, ['contact_sub_type', 'email_greeting_id', 'postal_greeting_id', 'addressee_id'], TRUE)) {
304 //coming up with a rule to set these is too complex - skip
308 // Pick an option value if needed
309 if (!$handled && $fieldDef['type'] !== CRM_Utils_Type
::T_BOOLEAN
) {
310 $options = $daoName::buildOptions($dbName, 'create');
312 $this->$dbName = key($options);
318 switch ($fieldDef['type']) {
319 case CRM_Utils_Type
::T_INT
:
320 case CRM_Utils_Type
::T_FLOAT
:
321 case CRM_Utils_Type
::T_MONEY
:
322 if (isset($fieldDef['precision'])) {
323 // $object->$dbName = CRM_Utils_Number::createRandomDecimal($value['precision']);
324 $this->$dbName = CRM_Utils_Number
::createTruncatedDecimal($counter, $fieldDef['precision']);
327 $this->$dbName = $counter;
331 case CRM_Utils_Type
::T_BOOLEAN
:
332 if (isset($fieldDef['default'])) {
333 $this->$dbName = $fieldDef['default'];
335 elseif ($fieldDef['name'] == 'is_deleted' ||
$fieldDef['name'] == 'is_test') {
343 case CRM_Utils_Type
::T_DATE
:
344 case CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
:
345 $this->$dbName = '19700101';
346 if ($dbName == 'end_date') {
347 // put this in the future
348 $this->$dbName = '20200101';
352 case CRM_Utils_Type
::T_TIMESTAMP
:
353 $this->$dbName = '19700201000000';
356 case CRM_Utils_Type
::T_TIME
:
357 throw new CRM_Core_Exception('T_TIME shouldn\'t be used.');
359 case CRM_Utils_Type
::T_CCNUM
:
360 $this->$dbName = '4111 1111 1111 1111';
363 case CRM_Utils_Type
::T_URL
:
364 $this->$dbName = 'http://www.civicrm.org';
367 case CRM_Utils_Type
::T_STRING
:
368 case CRM_Utils_Type
::T_BLOB
:
369 case CRM_Utils_Type
::T_MEDIUMBLOB
:
370 case CRM_Utils_Type
::T_TEXT
:
371 case CRM_Utils_Type
::T_LONGTEXT
:
372 case CRM_Utils_Type
::T_EMAIL
:
374 // WAS: if (isset($value['enumValues'])) {
375 // TODO: see if this works with all pseudoconstants
376 if (isset($fieldDef['pseudoconstant'], $fieldDef['pseudoconstant']['callback'])) {
377 if (isset($fieldDef['default'])) {
378 $this->$dbName = $fieldDef['default'];
381 $options = CRM_Core_PseudoConstant
::get($daoName, $fieldName);
382 if (is_array($options)) {
383 $this->$dbName = $options[0];
386 $defaultValues = explode(',', $options);
387 $this->$dbName = $defaultValues[0];
392 $this->$dbName = $dbName . '_' . $counter;
393 $maxlength = $fieldDef['maxlength'] ??
NULL;
394 if ($maxlength > 0 && strlen($this->$dbName) > $maxlength) {
395 $this->$dbName = substr($this->$dbName, 0, $fieldDef['maxlength']);
403 * Reset the DAO object.
405 * DAO is kinda crappy in that there is an unwritten rule of one query per DAO.
407 * We attempt to get around this crappy restriction by resetting some of DAO's internal fields. Use this with caution
409 public function reset() {
411 foreach (array_keys($this->table()) as $field) {
412 unset($this->$field);
416 * reset the various DB_DAO structures manually
425 * @param string $tableName
429 public static function getLocaleTableName($tableName) {
432 $tables = CRM_Core_I18n_Schema
::schemaStructureTables();
433 if (in_array($tableName, $tables)) {
434 return $tableName . $dbLocale;
441 * Execute a query by the current DAO, localizing it along the way (if needed).
443 * @param string $query
444 * The SQL query for execution.
445 * @param bool $i18nRewrite
446 * Whether to rewrite the query.
449 * the current DAO object after the query execution
451 public function query($query, $i18nRewrite = TRUE) {
452 // rewrite queries that should use $dbLocale-based views for multi-language installs
453 global $dbLocale, $_DB_DATAOBJECT;
455 if (empty($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5
])) {
456 // Will force connection to be populated per CRM-20541.
460 $conn = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5
];
461 $orig_options = $conn->options
;
462 $this->_setDBOptions($this->_options
);
464 if ($i18nRewrite and $dbLocale) {
465 $query = CRM_Core_I18n_Schema
::rewriteQuery($query);
468 $ret = parent
::query($query);
470 $this->_setDBOptions($orig_options);
475 * Static function to set the factory instance for this class.
477 * @param object $factory
478 * The factory application object.
480 public static function setFactory(&$factory) {
481 self
::$_factory = &$factory;
485 * Factory method to instantiate a new object from a table name.
487 * @param string $table
488 * @return \DataObject|\PEAR_Error
490 public function factory($table = '') {
491 if (!isset(self
::$_factory)) {
492 return parent
::factory($table);
495 return self
::$_factory->create($table);
499 * Initialization for all DAO objects. Since we access DB_DO programatically
500 * we need to set the links manually.
502 public function initialize() {
504 if (empty(Civi
::$statics[__CLASS__
]['init'])) {
505 // CRM_Core_DAO::init() must be called before CRM_Core_DAO->initialize().
506 // This occurs very early in bootstrap - error handlers may not be wired up.
507 echo "Inconsistent system initialization sequence. Premature access of (" . get_class($this) . ")";
508 CRM_Utils_System
::civiExit();
513 * Defines the default key as 'id'.
517 public function keys() {
526 * Tells DB_DataObject which keys use autoincrement.
527 * 'id' is autoincrementing by default.
532 public function sequenceKey() {
533 static $sequenceKeys;
534 if (!isset($sequenceKeys)) {
535 $sequenceKeys = ['id', TRUE];
537 return $sequenceKeys;
541 * Returns list of FK relationships.
543 * @return CRM_Core_Reference_Basic[]
545 public static function getReferenceColumns() {
546 if (!isset(Civi
::$statics[static::class]['links'])) {
547 Civi
::$statics[static::class]['links'] = static::createReferenceColumns(static::class);
548 CRM_Core_DAO_AllCoreTables
::invoke(static::class, 'links_callback', Civi
::$statics[static::class]['links']);
550 return Civi
::$statics[static::class]['links'];
554 * Returns all the column names of this table.
559 public static function &fields() {
565 * Returns all usable fields, indexed by name.
567 * This function differs from fields() in that it indexes by name rather than unique_name.
569 * It excludes fields not added yet by pending upgrades.
570 * This avoids problems with trying to SELECT a field that exists in code but has not yet been added to the db.
572 * @param bool $checkPermissions
573 * Filter by field permissions.
576 public static function getSupportedFields($checkPermissions = FALSE) {
577 $fields = array_column((array) static::fields(), NULL, 'name');
579 // Exclude fields yet not added by pending upgrades
580 $dbVer = \CRM_Core_BAO_Domain
::version();
581 $daoExt = defined(static::class . '::EXT') ?
constant(static::class . '::EXT') : NULL;
582 if ($fields && $daoExt === 'civicrm' && version_compare($dbVer, \CRM_Utils_System
::version()) < 0) {
583 $fields = array_filter($fields, function($field) use ($dbVer) {
584 $add = $field['add'] ??
'1.0.0';
585 if (substr_count($add, '.') < 2) {
588 return version_compare($dbVer, $add, '>=');
592 // Exclude fields the user does not have permission for
593 if ($checkPermissions) {
594 $fields = array_filter($fields, function($field) {
595 return empty($field['permission']) || CRM_Core_Permission
::check($field['permission']);
603 * Get/set an associative array of table columns
608 public function table() {
609 $fields = $this->fields();
613 foreach ($fields as $name => $value) {
614 $table[$value['name']] = $value['type'];
615 if (!empty($value['required'])) {
616 $table[$value['name']] +
= self
::DB_DAO_NOTNULL
;
629 * @return CRM_Core_DAO
631 public function save($hook = TRUE) {
633 if (!empty($this->id
)) {
635 $preEvent = new \Civi\Core\DAO\Event\
PreUpdate($this);
636 $preEvent->eventID
= $eventID;
637 \Civi
::dispatcher()->dispatch("civi.dao.preUpdate", $preEvent);
640 $result = $this->update();
643 $event = new \Civi\Core\DAO\Event\
PostUpdate($this, $result);
644 $event->eventID
= $eventID;
645 \Civi
::dispatcher()->dispatch("civi.dao.postUpdate", $event);
647 $this->clearDbColumnValueCache();
651 $preEvent = new \Civi\Core\DAO\Event\
PreUpdate($this);
652 $preEvent->eventID
= $eventID;
653 \Civi
::dispatcher()->dispatch("civi.dao.preInsert", $preEvent);
656 $result = $this->insert();
659 $event = new \Civi\Core\DAO\Event\
PostUpdate($this, $result);
660 $event->eventID
= $eventID;
661 \Civi
::dispatcher()->dispatch("civi.dao.postInsert", $event);
667 CRM_Utils_Hook
::postSave($this);
674 * Deletes items from table which match current objects variables.
676 * Returns the true on success
680 * Designed to be extended
682 * $object = new mytable();
684 * echo $object->delete(); // builds a conditon
686 * $object = new mytable();
687 * $object->whereAdd('age > 12');
689 * $object->orderBy('age DESC');
690 * $object->delete(true); // dont use object vars, use the conditions, limit and order.
692 * @param bool $useWhere (optional) If DB_DATAOBJECT_WHEREADD_ONLY is passed in then
693 * we will build the condition only using the whereAdd's. Default is to
694 * build the condition only using the object parameters.
696 * * @return mixed Int (No. of rows affected) on success, false on failure, 0 on no data affected
698 public function delete($useWhere = FALSE) {
699 $preEvent = new \Civi\Core\DAO\Event\
PreDelete($this);
700 \Civi
::dispatcher()->dispatch("civi.dao.preDelete", $preEvent);
702 $result = parent
::delete($useWhere);
704 $event = new \Civi\Core\DAO\Event\
PostDelete($this, $result);
705 \Civi
::dispatcher()->dispatch("civi.dao.postDelete", $event);
708 $this->clearDbColumnValueCache();
714 * @param bool $created
716 public function log($created = FALSE) {
719 if (!$this->getLog()) {
724 $session = CRM_Core_Session
::singleton();
725 $cid = $session->get('userID');
728 // return is we dont have handle to FK
733 $dao = new CRM_Core_DAO_Log();
734 $dao->entity_table
= $this->getTableName();
735 $dao->entity_id
= $this->id
;
736 $dao->modified_id
= $cid;
737 $dao->modified_date
= date("YmdHis");
742 * Given an associative array of name/value pairs, extract all the values
743 * that belong to this object and initialize the object with said values
745 * @param array $params
746 * Array of name/value pairs to save.
749 * Did we copy all null values into the object
751 public function copyValues($params) {
753 foreach ($this->fields() as $uniqueName => $field) {
754 $dbName = $field['name'];
755 if (array_key_exists($dbName, $params)) {
756 $value = $params[$dbName];
759 elseif (array_key_exists($uniqueName, $params)) {
760 $value = $params[$uniqueName];
767 // if there is no value then make the variable NULL
770 $this->$dbName = 'null';
772 elseif (is_array($value) && !empty($field['serialize'])) {
773 $this->$dbName = CRM_Core_DAO
::serializeField($value, $field['serialize']);
777 $maxLength = $field['maxlength'] ??
NULL;
778 if (!is_array($value) && $maxLength && mb_strlen($value) > $maxLength && empty($field['pseudoconstant'])) {
779 // No ts() since this is a sysadmin-y string not seen by general users.
780 Civi
::log()->warning('A string for field {dbName} has been truncated. The original string was {value}.', ['dbName' => $dbName, 'value' => $value]);
781 // The string is too long - what to do what to do? Well losing data is generally bad so let's truncate
782 $value = CRM_Utils_String
::ellipsify($value, $maxLength);
784 $this->$dbName = $value;
793 * Store all the values from this object in an associative array
794 * this is a destructive store, calling function is responsible
795 * for keeping sanity of id's.
797 * @param object $object
798 * The object that we are extracting data from.
799 * @param array $values
800 * (reference ) associative array of name/value pairs.
802 public static function storeValues(&$object, &$values) {
803 $fields = $object->fields();
804 foreach ($fields as $name => $value) {
805 $dbName = $value['name'];
806 if (isset($object->$dbName) && $object->$dbName !== 'null') {
807 $values[$dbName] = $object->$dbName;
808 if ($name != $dbName) {
809 $values[$name] = $object->$dbName;
816 * Create an attribute for this specific field. We only do this for strings and text
818 * @param array $field
819 * The field under task.
822 * the attributes for the object
824 public static function makeAttribute($field) {
826 if (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_STRING
) {
827 $maxLength = $field['maxlength'] ??
NULL;
828 $size = $field['size'] ??
NULL;
829 if ($maxLength ||
$size) {
832 $attributes['maxlength'] = $maxLength;
835 $attributes['size'] = $size;
840 elseif (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_TEXT
) {
841 $rows = $field['rows'] ??
NULL;
845 $cols = $field['cols'] ??
NULL;
851 $attributes['rows'] = $rows;
852 $attributes['cols'] = $cols;
855 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
) {
856 $attributes['size'] = 6;
857 $attributes['maxlength'] = 14;
865 * Get the size and maxLength attributes for this text field.
866 * (or for all text fields) in the DAO object.
868 * @param string $class
870 * @param string $fieldName
871 * Field that i'm interested in or null if.
872 * you want the attributes for all DAO text fields
875 * assoc array of name => attribute pairs
877 public static function getAttribute($class, $fieldName = NULL) {
878 $object = new $class();
879 $fields = $object->fields();
880 if ($fieldName != NULL) {
881 $field = $fields[$fieldName] ??
NULL;
882 return self
::makeAttribute($field);
886 foreach ($fields as $name => $field) {
887 $attribute = self
::makeAttribute($field);
889 $attributes[$name] = $attribute;
893 if (!empty($attributes)) {
901 * Create or update a record from supplied params.
903 * If 'id' is supplied, an existing record will be updated
904 * Otherwise a new record will be created.
906 * @param array $record
909 * @throws \CRM_Core_Exception
911 public static function writeRecord(array $record): CRM_Core_DAO
{
912 $hook = empty($record['id']) ?
'create' : 'edit';
913 $className = CRM_Core_DAO_AllCoreTables
::getCanonicalClassName(static::class);
914 if ($className === 'CRM_Core_DAO') {
915 throw new CRM_Core_Exception('Function writeRecord must be called on a subclass of CRM_Core_DAO');
917 $entityName = CRM_Core_DAO_AllCoreTables
::getBriefName($className);
919 \CRM_Utils_Hook
::pre($hook, $entityName, $record['id'] ??
NULL, $record);
920 $instance = new $className();
921 // Ensure fields exist before attempting to write to them
922 $values = array_intersect_key($record, self
::getSupportedFields());
923 $instance->copyValues($values);
925 \CRM_Utils_Hook
::post($hook, $entityName, $instance->id
, $instance);
931 * Bulk save multiple records
933 * @param array[] $records
935 * @throws CRM_Core_Exception
937 public static function writeRecords(array $records): array {
939 foreach ($records as $record) {
940 $results[] = static::writeRecord($record);
946 * Delete a record from supplied params.
948 * @param array $record
951 * @throws CRM_Core_Exception
953 public static function deleteRecord(array $record) {
954 $className = CRM_Core_DAO_AllCoreTables
::getCanonicalClassName(static::class);
955 if ($className === 'CRM_Core_DAO') {
956 throw new CRM_Core_Exception('Function deleteRecord must be called on a subclass of CRM_Core_DAO');
958 $entityName = CRM_Core_DAO_AllCoreTables
::getBriefName($className);
959 if (empty($record['id'])) {
960 throw new CRM_Core_Exception("Cannot delete {$entityName} with no id.");
962 CRM_Utils_Type
::validate($record['id'], 'Positive');
964 CRM_Utils_Hook
::pre('delete', $entityName, $record['id'], $record);
965 $instance = new $className();
966 $instance->id
= $record['id'];
967 // Load complete object for the sake of hook_civicrm_post, below
968 $instance->find(TRUE);
969 if (!$instance ||
!$instance->delete()) {
970 throw new CRM_Core_Exception("Could not delete {$entityName} id {$record['id']}");
972 // For other operations this hook is passed an incomplete object and hook listeners can load if needed.
973 // But that's not possible with delete because it's gone from the database by the time this hook is called.
974 // So in this case the object has been pre-loaded so hook listeners have access to the complete record.
975 CRM_Utils_Hook
::post('delete', $entityName, $record['id'], $instance);
981 * Bulk delete multiple records.
983 * @param array[] $records
985 * @throws CRM_Core_Exception
987 public static function deleteRecords(array $records) {
989 foreach ($records as $record) {
990 $results[] = static::deleteRecord($record);
996 * Check if there is a record with the same name in the db.
998 * @param string $value
999 * The value of the field we are checking.
1000 * @param string $daoName
1001 * The dao object name.
1002 * @param string $daoID
1003 * The id of the object being updated. u can change your name.
1004 * as long as there is no conflict
1005 * @param string $fieldName
1006 * The name of the field in the DAO.
1008 * @param string $domainID
1009 * The id of the domain. Object exists only for the given domain.
1012 * true if object exists
1014 public static function objectExists($value, $daoName, $daoID, $fieldName = 'name', $domainID = NULL) {
1015 $object = new $daoName();
1016 $object->$fieldName = $value;
1018 $object->domain_id
= $domainID;
1021 if ($object->find(TRUE)) {
1022 return $daoID && $object->id
== $daoID;
1030 * Check if there is a given column in a specific table.
1033 * @see CRM_Core_BAO_SchemaHandler::checkIfFieldExists
1035 * @param string $tableName
1036 * @param string $columnName
1037 * @param bool $i18nRewrite
1038 * Whether to rewrite the query on multilingual setups.
1041 * true if exists, else false
1043 public static function checkFieldExists($tableName, $columnName, $i18nRewrite = TRUE) {
1044 CRM_Core_Error
::deprecatedFunctionWarning('CRM_Core_BAO_SchemaHandler::checkIfFieldExists');
1045 return CRM_Core_BAO_SchemaHandler
::checkIfFieldExists($tableName, $columnName, $i18nRewrite);
1049 * Scans all the tables using a slow query and table name.
1053 public static function getTableNames() {
1054 $dao = CRM_Core_DAO
::executeQuery(
1056 FROM information_schema.TABLES
1057 WHERE TABLE_SCHEMA = '" . CRM_Core_DAO
::getDatabaseName() . "'
1058 AND TABLE_NAME LIKE 'civicrm_%'
1059 AND TABLE_NAME NOT LIKE 'civicrm_import_job_%'
1060 AND TABLE_NAME NOT LIKE '%_temp%'
1063 while ($dao->fetch()) {
1064 $values[] = $dao->TABLE_NAME
;
1070 * @param int $maxTablesToCheck
1074 public static function isDBMyISAM($maxTablesToCheck = 10) {
1075 return CRM_Core_DAO
::singleValueQuery(
1077 FROM information_schema.TABLES
1078 WHERE ENGINE = 'MyISAM'
1079 AND TABLE_SCHEMA = '" . CRM_Core_DAO
::getDatabaseName() . "'
1080 AND TABLE_NAME LIKE 'civicrm_%'
1081 AND TABLE_NAME NOT LIKE 'civicrm_import_job_%'
1082 AND TABLE_NAME NOT LIKE '%_temp%'
1083 AND TABLE_NAME NOT LIKE 'civicrm_tmp_%'
1088 * Get the name of the CiviCRM database.
1092 public static function getDatabaseName() {
1093 $daoObj = new CRM_Core_DAO();
1094 return $daoObj->database();
1098 * Checks if a constraint exists for a specified table.
1100 * @param string $tableName
1101 * @param string $constraint
1104 * true if constraint exists, false otherwise
1106 * @throws \CRM_Core_Exception
1108 public static function checkConstraintExists($tableName, $constraint) {
1111 if (!array_key_exists($tableName, $show)) {
1112 $query = "SHOW CREATE TABLE $tableName";
1113 $dao = CRM_Core_DAO
::executeQuery($query, [], TRUE, NULL, FALSE, FALSE);
1115 if (!$dao->fetch()) {
1116 throw new CRM_Core_Exception('query failed');
1119 $show[$tableName] = $dao->Create_Table
;
1122 return (bool) preg_match("/\b$constraint\b/i", $show[$tableName]);
1126 * Checks if CONSTRAINT keyword exists for a specified table.
1128 * @param array $tables
1130 * @throws CRM_Core_Exception
1133 * true if CONSTRAINT keyword exists, false otherwise
1135 public static function schemaRequiresRebuilding($tables = ["civicrm_contact"]) {
1137 foreach ($tables as $tableName) {
1138 if (!array_key_exists($tableName, $show)) {
1139 $query = "SHOW CREATE TABLE $tableName";
1140 $dao = CRM_Core_DAO
::executeQuery($query, [], TRUE, NULL, FALSE, FALSE);
1142 if (!$dao->fetch()) {
1143 throw new CRM_Core_Exception('Show create table failed.');
1146 $show[$tableName] = $dao->Create_Table
;
1149 $result = (bool) preg_match("/\bCONSTRAINT\b\s/i", $show[$tableName]);
1150 if ($result == TRUE) {
1161 * Checks if the FK constraint name is in the format 'FK_tableName_columnName'
1162 * for a specified column of a table.
1164 * @param string $tableName
1165 * @param string $columnName
1168 * true if in format, false otherwise
1170 * @throws \CRM_Core_Exception
1172 public static function checkFKConstraintInFormat($tableName, $columnName) {
1175 if (!array_key_exists($tableName, $show)) {
1176 $query = "SHOW CREATE TABLE $tableName";
1177 $dao = CRM_Core_DAO
::executeQuery($query);
1179 if (!$dao->fetch()) {
1180 throw new CRM_Core_Exception('query failed');
1183 $show[$tableName] = $dao->Create_Table
;
1185 $constraint = "`FK_{$tableName}_{$columnName}`";
1186 $pattern = "/\bCONSTRAINT\b\s+%s\s+\bFOREIGN\s+KEY\b\s/i";
1187 return (bool) preg_match(sprintf($pattern, $constraint), $show[$tableName]);
1191 * Check whether a specific column in a specific table has always the same value.
1193 * @param string $tableName
1194 * @param string $columnName
1195 * @param string $columnValue
1198 * true if the value is always $columnValue, false otherwise
1200 public static function checkFieldHasAlwaysValue($tableName, $columnName, $columnValue) {
1201 $query = "SELECT * FROM $tableName WHERE $columnName != '$columnValue'";
1202 $dao = CRM_Core_DAO
::executeQuery($query);
1203 $result = $dao->fetch() ?
FALSE : TRUE;
1208 * Check whether a specific column in a specific table is always NULL.
1210 * @param string $tableName
1211 * @param string $columnName
1214 * true if if the value is always NULL, false otherwise
1216 public static function checkFieldIsAlwaysNull($tableName, $columnName) {
1217 $query = "SELECT * FROM $tableName WHERE $columnName IS NOT NULL";
1218 $dao = CRM_Core_DAO
::executeQuery($query);
1219 $result = $dao->fetch() ?
FALSE : TRUE;
1224 * Checks if this DAO's table ought to exist.
1226 * If there are pending DB updates, this function compares the CiviCRM version of the table to the current schema version.
1229 * @throws CRM_Core_Exception
1231 public static function tableHasBeenAdded() {
1232 if (CRM_Utils_System
::version() === CRM_Core_BAO_Domain
::version()) {
1235 $daoExt = defined(static::class . '::EXT') ?
constant(static::class . '::EXT') : NULL;
1236 $daoVersion = defined(static::class . '::TABLE_ADDED') ?
constant(static::class . '::TABLE_ADDED') : '1.0';
1237 return !($daoExt === 'civicrm' && version_compare(CRM_Core_BAO_Domain
::version(), $daoVersion, '<'));
1241 * Check if there is a given table in the database.
1243 * @param string $tableName
1246 * true if exists, else false
1248 public static function checkTableExists($tableName) {
1253 $params = [1 => [$tableName, 'String']];
1255 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1256 return (bool) $dao->fetch();
1260 * Check if a given table has data.
1262 * @param string $tableName
1264 * TRUE if $tableName has at least one record.
1266 public static function checkTableHasData($tableName) {
1267 $c = CRM_Core_DAO
::singleValueQuery(sprintf('SELECT count(*) c FROM `%s`', $tableName));
1276 public function checkVersion($version) {
1277 CRM_Core_Error
::deprecatedFunctionWarning('CRM_Core_BAO_Domain::version');
1278 $dbVersion = CRM_Core_BAO_Domain
::version();
1279 return trim($version) == trim($dbVersion);
1283 * Find a DAO object for the given ID and return it.
1286 * Id of the DAO object being searched for.
1288 * @return CRM_Core_DAO
1289 * Object of the type of the class that called this function.
1293 public static function findById($id) {
1294 $object = new static();
1296 if (!$object->find(TRUE)) {
1297 throw new Exception("Unable to find a " . get_called_class() . " with id {$id}.");
1303 * Returns all results as array-encoded records.
1307 public function fetchAll($k = FALSE, $v = FALSE, $method = FALSE) {
1309 while ($this->fetch()) {
1310 $result[] = $this->toArray();
1316 * Return the results as PHP generator.
1318 * @param string $type
1319 * Whether the generator yields 'dao' objects or 'array's.
1321 public function fetchGenerator($type = 'dao') {
1322 while ($this->fetch()) {
1329 yield
$this->toArray();
1333 throw new \
RuntimeException("Invalid record type ($type)");
1339 * Returns a singular value.
1341 * @return mixed|NULL
1343 public function fetchValue() {
1344 $result = $this->getDatabaseResult();
1345 $row = $result->fetchRow();
1355 * Get all the result records as mapping between columns.
1357 * @param string $keyColumn
1359 * @param string $valueColumn
1362 * Ex: ["foo" => "The Foo Bar", "baz" => "The Baz Qux"]
1364 public function fetchMap($keyColumn, $valueColumn) {
1366 while ($this->fetch()) {
1367 $result[$this->{$keyColumn}] = $this->{$valueColumn};
1373 * Given a DAO name, a column name and a column value, find the record and GET the value of another column in that record
1375 * @param string $daoName
1376 * Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact).
1377 * @param int $searchValue
1378 * Value of the column you want to search by.
1379 * @param string $returnColumn
1380 * Name of the column you want to GET the value of.
1381 * @param string $searchColumn
1382 * Name of the column you want to search by.
1383 * @param bool $force
1384 * Skip use of the cache.
1386 * @return string|int|null
1387 * Value of $returnColumn in the retrieved record
1389 * @throws \CRM_Core_Exception
1391 public static function getFieldValue($daoName, $searchValue, $returnColumn = 'name', $searchColumn = 'id', $force = FALSE) {
1393 empty($searchValue) ||
1394 trim(strtolower($searchValue)) == 'null'
1396 // adding this here since developers forget to check for an id
1397 // or for the 'null' (which is a bad DAO kludge)
1398 // and hence we get the first value in the db
1399 throw new CRM_Core_Exception('getFieldValue failed');
1402 self
::$_dbColumnValueCache = self
::$_dbColumnValueCache ??
[];
1404 while (strpos($daoName, '_BAO_') !== FALSE) {
1405 $daoName = get_parent_class($daoName);
1409 empty(self
::$_dbColumnValueCache[$daoName][$searchColumn][$searchValue]) ||
1410 !array_key_exists($returnColumn, self
::$_dbColumnValueCache[$daoName][$searchColumn][$searchValue])
1412 $object = new $daoName();
1413 $object->$searchColumn = $searchValue;
1414 $object->selectAdd();
1415 $object->selectAdd($returnColumn);
1418 if ($object->find(TRUE)) {
1419 $result = $object->$returnColumn;
1422 self
::$_dbColumnValueCache[$daoName][$searchColumn][$searchValue][$returnColumn] = $result;
1424 return self
::$_dbColumnValueCache[$daoName][$searchColumn][$searchValue][$returnColumn];
1428 * Given a DAO name, a column name and a column value, find the record and SET the value of another column in that record
1430 * @param string $daoName
1431 * Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact).
1432 * @param int $searchValue
1433 * Value of the column you want to search by.
1434 * @param string $setColumn
1435 * Name of the column you want to SET the value of.
1436 * @param string $setValue
1437 * SET the setColumn to this value.
1438 * @param string $searchColumn
1439 * Name of the column you want to search by.
1442 * true if we found and updated the object, else false
1444 public static function setFieldValue($daoName, $searchValue, $setColumn, $setValue, $searchColumn = 'id') {
1445 $object = new $daoName();
1446 $object->selectAdd();
1447 $object->selectAdd("$searchColumn, $setColumn");
1448 $object->$searchColumn = $searchValue;
1450 if ($object->find(TRUE)) {
1451 $object->$setColumn = $setValue;
1452 if ($object->save()) {
1463 * @param array|object $sort either array or CRM_Utils_Sort
1464 * @param string $default
1465 * Default sort value.
1469 public static function getSortString($sort, $default = NULL) {
1470 // check if sort is of type CRM_Utils_Sort
1471 if (is_a($sort, 'CRM_Utils_Sort')) {
1472 return $sort->orderBy();
1477 // is it an array specified as $field => $sortDirection ?
1479 foreach ($sort as $k => $v) {
1480 $sortString .= "$k $v,";
1482 return rtrim($sortString, ',');
1488 * Fetch object based on array of properties.
1490 * @param string $daoName
1491 * Name of the dao object.
1492 * @param array $params
1493 * (reference ) an assoc array of name/value pairs.
1494 * @param array $defaults
1495 * (reference ) an assoc array to hold the flattened values.
1496 * @param array $returnProperities
1497 * An assoc array of fields that need to be returned, eg array( 'first_name', 'last_name').
1500 * an object of type referenced by daoName
1502 public static function commonRetrieve($daoName, &$params, &$defaults, $returnProperities = NULL) {
1503 $object = new $daoName();
1504 $object->copyValues($params);
1506 // return only specific fields if returnproperties are sent
1507 if (!empty($returnProperities)) {
1508 $object->selectAdd();
1509 $object->selectAdd(implode(',', $returnProperities));
1512 if ($object->find(TRUE)) {
1513 self
::storeValues($object, $defaults);
1520 * Delete the object records that are associated with this contact.
1522 * @param string $daoName
1523 * Name of the dao object.
1524 * @param int $contactId
1525 * Id of the contact to delete.
1527 public static function deleteEntityContact($daoName, $contactId) {
1528 $object = new $daoName();
1530 $object->entity_table
= 'civicrm_contact';
1531 $object->entity_id
= $contactId;
1536 * Execute an unbuffered query.
1538 * This is a wrapper around new functionality exposed with CRM-17748.
1540 * @param string $query query to be executed
1542 * @param array $params
1543 * @param bool $abort
1544 * @param null $daoName
1545 * @param bool $freeDAO
1546 * @param bool $i18nRewrite
1547 * @param bool $trapException
1549 * @return CRM_Core_DAO
1550 * Object that points to an unbuffered result set
1552 public static function executeUnbufferedQuery(
1558 $i18nRewrite = TRUE,
1559 $trapException = FALSE
1562 return self
::executeQuery(
1570 ['result_buffering' => 0]
1577 * @param string $query
1578 * Query to be executed.
1580 * @param array $params
1581 * @param bool $abort
1582 * @param null $daoName
1583 * @param bool $freeDAO
1584 * @param bool $i18nRewrite
1585 * @param bool $trapException
1586 * @param array $options
1588 * @return CRM_Core_DAO|object
1589 * object that holds the results of the query
1590 * NB - if this is defined as just returning a DAO phpstorm keeps pointing
1591 * out all the properties that are not part of the DAO
1593 public static function &executeQuery(
1599 $i18nRewrite = TRUE,
1600 $trapException = FALSE,
1603 $queryStr = self
::composeQuery($query, $params, $abort);
1606 $dao = new CRM_Core_DAO();
1609 $dao = new $daoName();
1612 if ($trapException) {
1613 CRM_Core_Error
::deprecatedFunctionWarning('calling functions should handle exceptions');
1614 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
1617 if ($dao->isValidOption($options)) {
1618 $dao->setOptions($options);
1621 $result = $dao->query($queryStr, $i18nRewrite);
1623 // since it is unbuffered, ($dao->N==0) is true. This blocks the standard fetch() mechanism.
1624 if (CRM_Utils_Array
::value('result_buffering', $options) === 0) {
1628 if (is_a($result, 'DB_Error')) {
1629 CRM_Core_Error
::deprecatedFunctionWarning('calling functions should handle exceptions');
1637 * Wrapper to validate internal DAO options before passing to DB_mysql/DB_Common level
1639 * @param array $options
1642 * Provided options are valid
1644 public function isValidOption($options) {
1653 if (empty($options)) {
1657 foreach (array_keys($options) as $option) {
1658 if (!in_array($option, $validOptions)) {
1668 * Execute a query and get the single result.
1670 * @param string $query
1671 * Query to be executed.
1672 * @param array $params
1673 * @param bool $abort
1674 * @param bool $i18nRewrite
1675 * @return string|null
1676 * the result of the query if any
1679 public static function &singleValueQuery(
1685 $queryStr = self
::composeQuery($query, $params, $abort);
1687 static $_dao = NULL;
1690 $_dao = new CRM_Core_DAO();
1693 $_dao->query($queryStr, $i18nRewrite);
1695 $result = $_dao->getDatabaseResult();
1698 $row = $result->fetchRow();
1708 * Compose the query by merging the parameters into it.
1710 * @param string $query
1711 * @param array $params
1712 * @param bool $abort
1715 * @throws CRM_Core_Exception
1717 public static function composeQuery($query, $params = [], $abort = TRUE) {
1719 foreach ($params as $key => $item) {
1720 if (is_numeric($key)) {
1721 if (CRM_Utils_Type
::validate($item[0], $item[1]) !== NULL) {
1722 $item[0] = self
::escapeString($item[0]);
1723 if ($item[1] == 'String' ||
1724 $item[1] == 'Memo' ||
1727 // Support class constants stipulating wildcard characters and/or
1728 // non-quoting of strings. Also support legacy code which may be
1729 // passing in TRUE or 1 for $item[2], which used to indicate the
1730 // use of wildcard characters.
1731 if (!empty($item[2])) {
1732 if ($item[2] & CRM_Core_DAO
::QUERY_FORMAT_WILDCARD ||
$item[2] === TRUE) {
1733 $item[0] = "'%{$item[0]}%'";
1735 elseif (!($item[2] & CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
)) {
1736 $item[0] = "'{$item[0]}'";
1740 $item[0] = "'{$item[0]}'";
1744 if (($item[1] == 'Date' ||
$item[1] == 'Timestamp') &&
1745 strlen($item[0]) == 0
1750 $tr['%' . $key] = $item[0];
1753 throw new CRM_Core_Exception("{$item[0]} is not of type {$item[1]}");
1758 return strtr($query, $tr);
1764 public static function freeResult($ids = NULL) {
1765 global $_DB_DATAOBJECT;
1768 if (!$_DB_DATAOBJECT ||
1769 !isset($_DB_DATAOBJECT['RESULTS'])
1773 $ids = array_keys($_DB_DATAOBJECT['RESULTS']);
1776 foreach ($ids as $id) {
1777 if (isset($_DB_DATAOBJECT['RESULTS'][$id])) {
1778 $_DB_DATAOBJECT['RESULTS'][$id]->free();
1779 unset($_DB_DATAOBJECT['RESULTS'][$id]);
1782 if (isset($_DB_DATAOBJECT['RESULTFIELDS'][$id])) {
1783 unset($_DB_DATAOBJECT['RESULTFIELDS'][$id]);
1789 * Make a shallow copy of an object and all the fields in the object.
1791 * @param string $daoName
1793 * @param array $criteria
1794 * Array of all the fields & values.
1795 * on which basis to copy
1796 * @param array $newData
1797 * Array of all the fields & values.
1798 * to be copied besides the other fields
1799 * @param string $fieldsFix
1800 * Array of fields that you want to prefix/suffix/replace.
1801 * @param string $blockCopyOfDependencies
1802 * Fields that you want to block from.
1804 * @param bool $blockCopyofCustomValues
1805 * Case when you don't want to copy the custom values set in a
1806 * template as it will override/ignore the submitted custom values
1808 * @return CRM_Core_DAO|bool
1809 * the newly created copy of the object. False if none created.
1811 public static function copyGeneric($daoName, $criteria, $newData = NULL, $fieldsFix = NULL, $blockCopyOfDependencies = NULL, $blockCopyofCustomValues = FALSE) {
1812 $object = new $daoName();
1815 $object->id
= $criteria['id'];
1818 foreach ($criteria as $key => $value) {
1819 $object->$key = $value;
1824 while ($object->fetch()) {
1826 // all the objects except with $blockCopyOfDependencies set
1827 // be copied - addresses #CRM-1962
1829 if ($blockCopyOfDependencies && $object->$blockCopyOfDependencies) {
1833 $newObject = new $daoName();
1835 $fields = $object->fields();
1836 $fieldsToPrefix = [];
1837 $fieldsToSuffix = [];
1838 $fieldsToReplace = [];
1839 if (!empty($fieldsFix['prefix'])) {
1840 $fieldsToPrefix = $fieldsFix['prefix'];
1842 if (!empty($fieldsFix['suffix'])) {
1843 $fieldsToSuffix = $fieldsFix['suffix'];
1845 if (!empty($fieldsFix['replace'])) {
1846 $fieldsToReplace = $fieldsFix['replace'];
1849 $localizableFields = FALSE;
1850 foreach ($fields as $name => $value) {
1851 if ($name == 'id' ||
$value['name'] == 'id') {
1852 // copy everything but the id!
1856 $dbName = $value['name'];
1857 $type = CRM_Utils_Type
::typeToString($value['type']);
1858 $newObject->$dbName = $object->$dbName;
1859 if (isset($fieldsToPrefix[$dbName])) {
1860 $newObject->$dbName = $fieldsToPrefix[$dbName] . $newObject->$dbName;
1862 if (isset($fieldsToSuffix[$dbName])) {
1863 $newObject->$dbName .= $fieldsToSuffix[$dbName];
1865 if (isset($fieldsToReplace[$dbName])) {
1866 $newObject->$dbName = $fieldsToReplace[$dbName];
1869 if ($type == 'Timestamp' ||
$type == 'Date') {
1870 $newObject->$dbName = CRM_Utils_Date
::isoToMysql($newObject->$dbName);
1873 if (!empty($value['localizable'])) {
1874 $localizableFields = TRUE;
1878 $newObject->copyValues($newData);
1883 // ensure we copy all localized fields as well
1884 if (CRM_Core_I18n
::isMultilingual() && $localizableFields) {
1886 $locales = CRM_Core_I18n
::getMultilingual();
1887 $curLocale = CRM_Core_I18n
::getLocale();
1888 // loop on other locales
1889 foreach ($locales as $locale) {
1890 if ($locale != $curLocale) {
1891 // setLocale doesn't seems to be reliable to set dbLocale and we only need to change the db locale
1892 $dbLocale = '_' . $locale;
1893 $newObject->copyLocalizable($object->id
, $newObject->id
, $fieldsToPrefix, $fieldsToSuffix, $fieldsToReplace);
1896 // restore dbLocale to starting value
1897 $dbLocale = '_' . $curLocale;
1900 if (!$blockCopyofCustomValues) {
1901 $newObject->copyCustomFields($object->id
, $newObject->id
);
1903 CRM_Utils_Hook
::post('create', CRM_Core_DAO_AllCoreTables
::getBriefName($daoName), $newObject->id
, $newObject);
1910 * Method that copies localizable fields from an old entity to a new one.
1912 * Fixes bug dev/core#2479,
1913 * where non current locale fields are copied from current locale losing translation when copying
1915 * @param int $entityID
1916 * @param int $newEntityID
1917 * @param array $fieldsToPrefix
1918 * @param array $fieldsToSuffix
1919 * @param array $fieldsToReplace
1921 protected function copyLocalizable($entityID, $newEntityID, $fieldsToPrefix, $fieldsToSuffix, $fieldsToReplace) {
1922 $entity = get_class($this);
1923 $object = new $entity();
1924 $object->id
= $entityID;
1927 $newObject = new $entity();
1928 $newObject->id
= $newEntityID;
1932 if ($object->fetch() && $newObject->fetch()) {
1934 $fields = $object->fields();
1935 foreach ($fields as $name => $value) {
1937 if ($name == 'id' ||
$value['name'] == 'id') {
1938 // copy everything but the id!
1942 // only copy localizable fields
1943 if (!$value['localizable']) {
1947 $dbName = $value['name'];
1948 $type = CRM_Utils_Type
::typeToString($value['type']);
1949 $newObject->$dbName = $object->$dbName;
1950 if (isset($fieldsToPrefix[$dbName])) {
1951 $newObject->$dbName = $fieldsToPrefix[$dbName] . $newObject->$dbName;
1953 if (isset($fieldsToSuffix[$dbName])) {
1954 $newObject->$dbName .= $fieldsToSuffix[$dbName];
1956 if (isset($fieldsToReplace[$dbName])) {
1957 $newObject->$dbName = $fieldsToReplace[$dbName];
1960 if ($type == 'Timestamp' ||
$type == 'Date') {
1961 $newObject->$dbName = CRM_Utils_Date
::isoToMysql($newObject->$dbName);
1971 * Method that copies custom fields values from an old entity to a new one.
1973 * Fixes bug CRM-19302,
1974 * where if a custom field of File type was present, left both events using the same file,
1975 * breaking download URL's for the old event.
1977 * @todo the goal here is to clean this up so that it works for any entity. Copy Generic already DOES some custom field stuff
1978 * but it seems to be bypassed & perhaps less good than this (or this just duplicates it...)
1980 * @param int $entityID
1981 * @param int $newEntityID
1982 * @param string $parentOperation
1984 public function copyCustomFields($entityID, $newEntityID, $parentOperation = NULL) {
1985 $entity = CRM_Core_DAO_AllCoreTables
::getBriefName(get_class($this));
1986 $tableName = CRM_Core_DAO_AllCoreTables
::getTableForClass(get_class($this));
1987 // Obtain custom values for the old entity.
1988 $customParams = $htmlType = [];
1989 $customValues = CRM_Core_BAO_CustomValueTable
::getEntityValues($entityID, $entity);
1991 // If custom values present, we copy them
1992 if (!empty($customValues)) {
1993 // Get Field ID's and identify File type attributes, to handle file copying.
1994 $fieldIds = implode(', ', array_keys($customValues));
1995 $sql = "SELECT id FROM civicrm_custom_field WHERE html_type = 'File' AND id IN ( {$fieldIds} )";
1996 $result = CRM_Core_DAO
::executeQuery($sql);
1998 // Build array of File type fields
1999 while ($result->fetch()) {
2000 $htmlType[] = $result->id
;
2003 // Build params array of custom values
2004 foreach ($customValues as $field => $value) {
2005 if ($value !== NULL) {
2006 // Handle File type attributes
2007 if (in_array($field, $htmlType)) {
2008 $fileValues = CRM_Core_BAO_File
::path($value, $entityID);
2009 $customParams["custom_{$field}_-1"] = [
2010 'name' => CRM_Utils_File
::duplicate($fileValues[0]),
2011 'type' => $fileValues[1],
2014 // Handle other types
2016 $customParams["custom_{$field}_-1"] = $value;
2021 // Save Custom Fields for new Entity.
2022 CRM_Core_BAO_CustomValueTable
::postProcess($customParams, $tableName, $newEntityID, $entity, $parentOperation ??
'create');
2025 // copy activity attachments ( if any )
2026 CRM_Core_BAO_File
::copyEntityFile($tableName, $entityID, $tableName, $newEntityID);
2030 * Cascade update through related entities.
2032 * @param string $daoName
2035 * @param array $newData
2037 * @return CRM_Core_DAO|null
2039 public static function cascadeUpdate($daoName, $fromId, $toId, $newData = []) {
2040 $object = new $daoName();
2041 $object->id
= $fromId;
2043 if ($object->find(TRUE)) {
2044 $newObject = new $daoName();
2045 $newObject->id
= $toId;
2047 if ($newObject->find(TRUE)) {
2048 $fields = $object->fields();
2049 foreach ($fields as $name => $value) {
2050 if ($name == 'id' ||
$value['name'] == 'id') {
2051 // copy everything but the id!
2055 $colName = $value['name'];
2056 $newObject->$colName = $object->$colName;
2058 if (substr($name, -5) == '_date' ||
2059 substr($name, -10) == '_date_time'
2061 $newObject->$colName = CRM_Utils_Date
::isoToMysql($newObject->$colName);
2064 foreach ($newData as $k => $v) {
2065 $newObject->$k = $v;
2075 * Given the component id, compute the contact id
2076 * since its used for things like send email
2078 * @param $componentIDs
2079 * @param string $tableName
2080 * @param string $idField
2084 public static function getContactIDsFromComponent($componentIDs, $tableName, $idField = 'id') {
2087 if (empty($componentIDs)) {
2091 $IDs = implode(',', $componentIDs);
2095 WHERE $idField IN ( $IDs )
2098 $dao = CRM_Core_DAO
::executeQuery($query);
2099 while ($dao->fetch()) {
2100 $contactIDs[] = $dao->contact_id
;
2106 * Fetch object based on array of properties.
2108 * @param string $daoName
2109 * Name of the dao object.
2110 * @param string $fieldIdName
2111 * @param int $fieldId
2113 * @param array $returnProperities
2114 * An assoc array of fields that need to be returned, eg array( 'first_name', 'last_name').
2117 * an object of type referenced by daoName
2119 public static function commonRetrieveAll($daoName, $fieldIdName, $fieldId, &$details, $returnProperities = NULL) {
2120 require_once str_replace('_', DIRECTORY_SEPARATOR
, $daoName) . ".php";
2121 $object = new $daoName();
2122 $object->$fieldIdName = $fieldId;
2124 // return only specific fields if returnproperties are sent
2125 if (!empty($returnProperities)) {
2126 $object->selectAdd();
2127 $object->selectAdd('id');
2128 $object->selectAdd(implode(',', $returnProperities));
2132 while ($object->fetch()) {
2134 self
::storeValues($object, $defaults);
2135 $details[$object->id
] = $defaults;
2142 * Drop all CiviCRM tables.
2144 * @throws \CRM_Core_Exception
2146 public static function dropAllTables() {
2148 // first drop all the custom tables we've created
2149 CRM_Core_BAO_CustomGroup
::dropAllTables();
2151 // drop all multilingual views
2152 CRM_Core_I18n_Schema
::dropAllViews();
2154 CRM_Utils_File
::sourceSQLFile(CIVICRM_DSN
,
2155 dirname(__FILE__
) . DIRECTORY_SEPARATOR
.
2156 '..' . DIRECTORY_SEPARATOR
.
2157 '..' . DIRECTORY_SEPARATOR
.
2158 'sql' . DIRECTORY_SEPARATOR
.
2159 'civicrm_drop.mysql'
2168 public static function escapeString($string) {
2169 static $_dao = NULL;
2171 // If this is an atypical case (e.g. preparing .sql file before CiviCRM
2172 // has been installed), then we fallback DB-less str_replace escaping, as
2173 // we can't use mysqli_real_escape_string, as there is no DB connection.
2174 // Note: In typical usage, escapeString() will only check one conditional
2175 // ("if !$_dao") rather than two conditionals ("if !defined(DSN)")
2176 if (!defined('CIVICRM_DSN')) {
2177 // See http://php.net/manual/en/mysqli.real-escape-string.php for the
2178 // list of characters mysqli_real_escape_string escapes.
2179 $search = ["\\", "\x00", "\n", "\r", "'", '"', "\x1a"];
2180 $replace = ["\\\\", "\\0", "\\n", "\\r", "\'", '\"', "\\Z"];
2181 return str_replace($search, $replace, $string);
2183 $_dao = new CRM_Core_DAO();
2185 return $_dao->escape($string);
2189 * Escape a list of strings for use with "WHERE X IN (...)" queries.
2191 * @param array $strings
2192 * @param string $default
2193 * the value to use if $strings has no elements.
2195 * eg "abc","def","ghi"
2197 public static function escapeStrings($strings, $default = NULL) {
2198 static $_dao = NULL;
2200 $_dao = new CRM_Core_DAO();
2203 if (empty($strings)) {
2207 $escapes = array_map([$_dao, 'escape'], $strings);
2208 return '"' . implode('","', $escapes) . '"';
2216 public static function escapeWildCardString($string) {
2218 // ensure we escape the single characters % and _ which are mysql wild
2219 // card characters and could come in via sortByCharacter
2220 // note that mysql does not escape these characters
2221 if ($string && in_array($string,
2222 ['%', '_', '%%', '_%']
2225 return '\\' . $string;
2228 return self
::escapeString($string);
2232 * Creates a test object, including any required objects it needs via recursion
2233 * createOnly: only create in database, do not store or return the objects (useful for perf testing)
2234 * ONLY USE FOR TESTING
2236 * @param string $daoName
2237 * @param array $params
2238 * @param int $numObjects
2239 * @param bool $createOnly
2241 * @return object|array|NULL
2242 * NULL if $createOnly. A single object if $numObjects==1. Otherwise, an array of multiple objects.
2244 public static function createTestObject(
2250 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
2251 // so we re-set here in case
2252 $config = CRM_Core_Config
::singleton();
2253 $config->backtrace
= TRUE;
2255 static $counter = 0;
2256 CRM_Core_DAO
::$_testEntitiesToSkip = [
2257 'CRM_Core_DAO_Worldregion',
2258 'CRM_Core_DAO_StateProvince',
2259 'CRM_Core_DAO_Country',
2260 'CRM_Core_DAO_Domain',
2261 'CRM_Financial_DAO_FinancialType',
2262 //because valid ones exist & we use pick them due to pseudoconstant can't reliably create & delete these
2265 // Prefer to instantiate BAO's instead of DAO's (when possible)
2266 // so that assignTestValue()/assignTestFK() can be overloaded.
2267 $baoName = str_replace('_DAO_', '_BAO_', $daoName);
2268 if ($baoName === 'CRM_Financial_BAO_FinancialTrxn') {
2269 // OMG OMG OMG this is so incredibly bad. The BAO is insanely named.
2270 // @todo create a new class called what the BAO SHOULD be
2271 // that extends BAO-crazy-name.... migrate.
2272 $baoName = 'CRM_Core_BAO_FinancialTrxn';
2274 if (class_exists($baoName)) {
2275 $daoName = $baoName;
2278 for ($i = 0; $i < $numObjects; ++
$i) {
2281 /** @var CRM_Core_DAO $object */
2282 $object = new $daoName();
2284 $fields = $object->fields();
2285 foreach ($fields as $fieldName => $fieldDef) {
2286 $dbName = $fieldDef['name'];
2287 $FKClassName = $fieldDef['FKClassName'] ??
NULL;
2289 if (isset($params[$dbName]) && !is_array($params[$dbName])) {
2290 $object->$dbName = $params[$dbName];
2293 elseif ($dbName != 'id') {
2294 if ($FKClassName != NULL) {
2295 $object->assignTestFK($fieldName, $fieldDef, $params);
2299 $object->assignTestValue($fieldName, $fieldDef, $counter);
2307 $objects[$i] = $object;
2317 elseif ($numObjects == 1) {
2326 * Deletes the this object plus any dependent objects that are associated with it.
2327 * ONLY USE FOR TESTING
2329 * @param string $daoName
2330 * @param array $params
2332 public static function deleteTestObjects($daoName, $params = []) {
2333 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
2334 // so we re-set here in case
2335 $config = CRM_Core_Config
::singleton();
2336 $config->backtrace
= TRUE;
2338 $object = new $daoName();
2339 $object->id
= $params['id'] ??
NULL;
2341 // array(array(0 => $daoName, 1 => $daoParams))
2343 if ($object->find(TRUE)) {
2345 $fields = $object->fields();
2346 foreach ($fields as $name => $value) {
2348 $dbName = $value['name'];
2350 $FKClassName = $value['FKClassName'] ??
NULL;
2351 $required = $value['required'] ??
NULL;
2352 if ($FKClassName != NULL
2354 && !in_array($FKClassName, CRM_Core_DAO
::$_testEntitiesToSkip)
2355 && ($required ||
$dbName == 'contact_id')
2356 //I'm a bit stuck on this one - we might need to change the singleValueAlter so that the entities don't share a contact
2357 // to make this test process pass - line below makes pass for now
2358 && $dbName != 'member_of_contact_id'
2361 $deletions[] = [$FKClassName, ['id' => $object->$dbName]];
2368 foreach ($deletions as $deletion) {
2369 CRM_Core_DAO
::deleteTestObjects($deletion[0], $deletion[1]);
2374 * Set defaults when creating new entity.
2375 * (don't call this set defaults as already in use with different signature in some places)
2377 * @param array $params
2380 public static function setCreateDefaults(&$params, $defaults) {
2381 if (!empty($params['id'])) {
2384 foreach ($defaults as $key => $value) {
2385 if (!array_key_exists($key, $params) ||
$params[$key] === NULL) {
2386 $params[$key] = $value;
2392 * @param string $prefix
2393 * @param bool $addRandomString
2394 * @param null $string
2398 * @see CRM_Utils_SQL_TempTable
2400 public static function createTempTableName($prefix = 'civicrm', $addRandomString = TRUE, $string = NULL) {
2401 CRM_Core_Error
::deprecatedFunctionWarning('Use CRM_Utils_SQL_TempTable interface to create temporary tables');
2402 $tableName = $prefix . "_temp";
2404 if ($addRandomString) {
2406 $tableName .= "_" . $string;
2409 $tableName .= "_" . md5(uniqid('', TRUE));
2417 * @param bool $trigger
2421 public static function checkTriggerViewPermission($view = TRUE, $trigger = TRUE) {
2422 if (\Civi
::settings()->get('logging_no_trigger_permission')) {
2425 // test for create view and trigger permissions and if allowed, add the option to go multilingual and logging
2426 $dao = new CRM_Core_DAO();
2429 $dao->query('CREATE OR REPLACE VIEW civicrm_domain_view AS SELECT * FROM civicrm_domain');
2430 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
2434 $dao->query('CREATE TRIGGER civicrm_domain_trigger BEFORE INSERT ON civicrm_domain FOR EACH ROW BEGIN END');
2435 $dao->query('DROP TRIGGER IF EXISTS civicrm_domain_trigger');
2438 catch (Exception
$e) {
2446 * @param null $message
2447 * @param bool $printDAO
2449 public static function debugPrint($message = NULL, $printDAO = TRUE) {
2450 CRM_Utils_System
::xMemory("{$message}: ");
2453 global $_DB_DATAOBJECT;
2455 foreach (array_keys($_DB_DATAOBJECT['RESULTS']) as $id) {
2456 $q[] = $_DB_DATAOBJECT['RESULTS'][$id]->query
;
2458 CRM_Core_Error
::debug('_DB_DATAOBJECT', $q);
2463 * Build a list of triggers via hook and add them to (err, reconcile them
2464 * with) the database.
2466 * @param string $tableName
2467 * the specific table requiring a rebuild; or NULL to rebuild all tables.
2468 * @param bool $force
2473 public static function triggerRebuild($tableName = NULL, $force = FALSE) {
2474 Civi
::service('sql_triggers')->rebuild($tableName, $force);
2478 * Wrapper function to drop triggers.
2480 * @param string $tableName
2481 * the specific table requiring a rebuild; or NULL to rebuild all tables.
2484 public static function dropTriggers($tableName = NULL) {
2485 Civi
::service('sql_triggers')->dropTriggers($tableName);
2489 * @param array $info
2490 * per hook_civicrm_triggerInfo.
2491 * @param string $onlyTableName
2492 * the specific table requiring a rebuild; or NULL to rebuild all tables.
2495 public static function createTriggers(&$info, $onlyTableName = NULL) {
2496 Civi
::service('sql_triggers')->createTriggers($info, $onlyTableName);
2500 * Given a list of fields, create a list of references.
2502 * @param string $className
2503 * BAO/DAO class name.
2504 * @return array<CRM_Core_Reference_Interface>
2506 public static function createReferenceColumns($className) {
2508 $fields = $className::fields();
2509 foreach ($fields as $field) {
2510 if (isset($field['pseudoconstant'], $field['pseudoconstant']['optionGroupName'])) {
2511 $result[] = new CRM_Core_Reference_OptionValue(
2512 $className::getTableName(),
2514 'civicrm_option_value',
2515 CRM_Utils_Array
::value('keyColumn', $field['pseudoconstant'], 'value'),
2516 $field['pseudoconstant']['optionGroupName']
2524 * Find all records which refer to this entity.
2526 * @return CRM_Core_DAO[]
2528 public function findReferences() {
2529 $links = self
::getReferencesToTable(static::getTableName());
2532 foreach ($links as $refSpec) {
2533 /** @var $refSpec CRM_Core_Reference_Interface */
2534 $daoName = CRM_Core_DAO_AllCoreTables
::getClassForTable($refSpec->getReferenceTable());
2535 $result = $refSpec->findReferences($this);
2537 while ($result->fetch()) {
2538 $obj = new $daoName();
2539 $obj->id
= $result->id
;
2540 $occurrences[] = $obj;
2545 return $occurrences;
2549 * @return array{name: string, type: string, count: int, table: string|null, key: string|null}[]
2550 * each item has keys:
2554 * - table: string|null SQL table name
2555 * - key: string|null SQL column name
2557 public function getReferenceCounts() {
2558 $links = self
::getReferencesToTable(static::getTableName());
2561 foreach ($links as $refSpec) {
2562 /** @var $refSpec CRM_Core_Reference_Interface */
2563 $count = $refSpec->getReferenceCount($this);
2564 if (!empty($count['count'])) {
2569 foreach (CRM_Core_Component
::getEnabledComponents() as $component) {
2570 /** @var $component CRM_Core_Component_Info */
2571 $counts = array_merge($counts, $component->getReferenceCounts($this));
2573 CRM_Utils_Hook
::referenceCounts($this, $counts);
2579 * List all tables which have hard foreign keys to this table.
2581 * For now, this returns a description of every entity_id/entity_table
2583 * TODO: filter dynamic entity references on the $tableName, based on
2584 * schema metadata in dynamicForeignKey which enumerates a restricted
2585 * set of possible entity_table's.
2587 * @param string $tableName
2588 * Table referred to.
2590 * @return CRM_Core_Reference_Interface[]
2591 * structure of table and column, listing every table with a
2592 * foreign key reference to $tableName, and the column where the key appears.
2594 public static function getReferencesToTable($tableName) {
2596 foreach (CRM_Core_DAO_AllCoreTables
::getClasses() as $daoClassName) {
2597 $links = $daoClassName::getReferenceColumns();
2599 foreach ($links as $refSpec) {
2600 /** @var $refSpec CRM_Core_Reference_Interface */
2601 if ($refSpec->matchesTargetTable($tableName)) {
2602 $refsFound[] = $refSpec;
2610 * Get all references to contact table.
2612 * This includes core tables, custom group tables, tables added by the merge
2613 * hook and the entity_tag table.
2615 * Refer to CRM-17454 for information on the danger of querying the information
2616 * schema to derive this.
2618 * @throws \CiviCRM_API3_Exception
2620 public static function getReferencesToContactTable() {
2621 if (isset(\Civi
::$statics[__CLASS__
]) && isset(\Civi
::$statics[__CLASS__
]['contact_references'])) {
2622 return \Civi
::$statics[__CLASS__
]['contact_references'];
2624 $contactReferences = [];
2625 $coreReferences = CRM_Core_DAO
::getReferencesToTable('civicrm_contact');
2626 foreach ($coreReferences as $coreReference) {
2628 // Exclude option values
2629 !is_a($coreReference, 'CRM_Core_Reference_Dynamic') &&
2630 // Exclude references to other columns
2631 $coreReference->getTargetKey() === 'id'
2633 $contactReferences[$coreReference->getReferenceTable()][] = $coreReference->getReferenceKey();
2636 self
::appendCustomTablesExtendingContacts($contactReferences);
2637 self
::appendCustomContactReferenceFields($contactReferences);
2638 \Civi
::$statics[__CLASS__
]['contact_references'] = $contactReferences;
2639 return \Civi
::$statics[__CLASS__
]['contact_references'];
2643 * Get all dynamic references to the given table.
2645 * @param string $tableName
2649 public static function getDynamicReferencesToTable($tableName) {
2650 if (!isset(\Civi
::$statics[__CLASS__
]['contact_references_dynamic'][$tableName])) {
2651 \Civi
::$statics[__CLASS__
]['contact_references_dynamic'][$tableName] = [];
2652 $coreReferences = CRM_Core_DAO
::getReferencesToTable($tableName);
2653 foreach ($coreReferences as $coreReference) {
2654 if ($coreReference instanceof \CRM_Core_Reference_Dynamic
) {
2655 \Civi
::$statics[__CLASS__
]['contact_references_dynamic'][$tableName][$coreReference->getReferenceTable()][] = [$coreReference->getReferenceKey(), $coreReference->getTypeColumn()];
2659 return \Civi
::$statics[__CLASS__
]['contact_references_dynamic'][$tableName];
2663 * Add custom tables that extend contacts to the list of contact references.
2665 * CRM_Core_BAO_CustomGroup::getAllCustomGroupsByBaseEntity seems like a safe-ish
2666 * function to be sure all are retrieved & we don't miss subtypes or inactive or multiples
2667 * - the down side is it is not cached.
2669 * Further changes should be include tests in the CRM_Core_MergerTest class
2670 * to ensure that disabled, subtype, multiple etc groups are still captured.
2672 * @param array $cidRefs
2674 public static function appendCustomTablesExtendingContacts(&$cidRefs) {
2675 $customValueTables = CRM_Core_BAO_CustomGroup
::getAllCustomGroupsByBaseEntity('Contact');
2676 $customValueTables->find();
2677 while ($customValueTables->fetch()) {
2678 $cidRefs[$customValueTables->table_name
][] = 'entity_id';
2683 * Add custom ContactReference fields to the list of contact references
2685 * This includes active and inactive fields/groups
2687 * @param array $cidRefs
2689 * @throws \CiviCRM_API3_Exception
2691 public static function appendCustomContactReferenceFields(&$cidRefs) {
2692 $fields = civicrm_api3('CustomField', 'get', [
2693 'return' => ['column_name', 'custom_group_id.table_name'],
2694 'data_type' => 'ContactReference',
2695 'options' => ['limit' => 0],
2697 foreach ($fields as $field) {
2698 $cidRefs[$field['custom_group_id.table_name']][] = $field['column_name'];
2703 * Lookup the value of a MySQL global configuration variable.
2705 * @param string $name
2706 * E.g. "thread_stack".
2707 * @param mixed $default
2710 public static function getGlobalSetting($name, $default = NULL) {
2711 // Alternatively, SELECT @@GLOBAL.thread_stack, but
2712 // that has been reported to fail under MySQL 5.0 for OS X
2713 $escapedName = self
::escapeString($name);
2714 $dao = CRM_Core_DAO
::executeQuery("SHOW VARIABLES LIKE '$escapedName'");
2715 if ($dao->fetch()) {
2724 * Update the fields array to also hold keys for pseudoconstant fields that relate to contained fields.
2726 * This is relevant where we want to offer both the ID field and the label field
2727 * as an option, e.g. search builder.
2729 * It is currently limited for optionGroupName & id+ name+ FK combos for purposes keeping the scope of the
2730 * change small, but is appropriate for other sorts of pseudoconstants.
2732 * @param array $fields
2734 public static function appendPseudoConstantsToFields(&$fields) {
2735 foreach ($fields as $fieldUniqueName => $field) {
2736 if (!empty($field['pseudoconstant'])) {
2737 $pseudoConstant = $field['pseudoconstant'];
2738 if (!empty($pseudoConstant['optionGroupName'])) {
2739 $fields[$pseudoConstant['optionGroupName']] = [
2740 'title' => CRM_Core_BAO_OptionGroup
::getTitleByName($pseudoConstant['optionGroupName']),
2741 'name' => $pseudoConstant['optionGroupName'],
2742 'data_type' => CRM_Utils_Type
::T_STRING
,
2743 'is_pseudofield_for' => $fieldUniqueName,
2746 // We restrict to id + name + FK as we are extending this a bit, but cautiously.
2748 !empty($field['FKClassName'])
2749 && CRM_Utils_Array
::value('keyColumn', $pseudoConstant) === 'id'
2750 && CRM_Utils_Array
::value('labelColumn', $pseudoConstant) === 'name'
2752 $pseudoFieldName = str_replace('_' . $pseudoConstant['keyColumn'], '', $field['name']);
2753 // This if is just an extra caution when adding change.
2754 if (!isset($fields[$pseudoFieldName])) {
2755 $daoName = $field['FKClassName'];
2756 $fkFields = $daoName::fields();
2757 foreach ($fkFields as $fkField) {
2758 if ($fkField['name'] === $pseudoConstant['labelColumn']) {
2759 $fields[$pseudoFieldName] = [
2760 'name' => $pseudoFieldName,
2761 'is_pseudofield_for' => $field['name'],
2762 'title' => $fkField['title'],
2763 'data_type' => $fkField['type'],
2764 'where' => $field['where'],
2775 * Get options for the called BAO object's field.
2777 * This function can be overridden by each BAO to add more logic related to context.
2778 * The overriding function will generally call the lower-level CRM_Core_PseudoConstant::get
2780 * @param string $fieldName
2781 * @param string $context
2782 * @see CRM_Core_DAO::buildOptionsContext
2783 * @param array $props
2784 * Raw field values; whatever is known about this bao object.
2786 * Note: $props can contain unsanitized input and should not be passed directly to CRM_Core_PseudoConstant::get
2788 * @return array|bool
2790 public static function buildOptions($fieldName, $context = NULL, $props = []) {
2791 // If a given bao does not override this function
2792 $baoName = get_called_class();
2793 return CRM_Core_PseudoConstant
::get($baoName, $fieldName, [], $context);
2797 * Populate option labels for this object's fields.
2799 * @throws exception if called directly on the base class
2801 public function getOptionLabels() {
2802 $fields = $this->fields();
2803 if ($fields === NULL) {
2804 throw new Exception('Cannot call getOptionLabels on CRM_Core_DAO');
2806 foreach ($fields as $field) {
2807 $name = $field['name'] ??
NULL;
2808 if ($name && isset($this->$name)) {
2809 $label = CRM_Core_PseudoConstant
::getLabel(get_class($this), $name, $this->$name);
2810 if ($label !== FALSE) {
2811 // Append 'label' onto the field name
2812 $labelName = $name . '_label';
2813 $this->$labelName = $label;
2820 * Provides documentation and validation for the buildOptions $context param
2822 * @param string $context
2824 * @throws CRM_Core_Exception
2827 public static function buildOptionsContext($context = NULL) {
2829 'get' => "get: all options are returned, even if they are disabled; labels are translated.",
2830 'create' => "create: options are filtered appropriately for the object being created/updated; labels are translated.",
2831 'search' => "search: searchable options are returned; labels are translated.",
2832 'validate' => "validate: all options are returned, even if they are disabled; machine names are used in place of labels.",
2833 'abbreviate' => "abbreviate: enabled options are returned; labels are replaced with abbreviations.",
2834 'match' => "match: enabled options are returned using machine names as keys; labels are translated.",
2836 // Validation: enforce uniformity of this param
2837 if ($context !== NULL && !isset($contexts[$context])) {
2838 throw new CRM_Core_Exception("'$context' is not a valid context for buildOptions.");
2844 * @param string $fieldName
2845 * @return bool|array
2847 public function getFieldSpec($fieldName) {
2848 $fields = $this->fields();
2850 // Support "unique names" as well as sql names
2851 $fieldKey = $fieldName;
2852 if (empty($fields[$fieldKey])) {
2853 $fieldKeys = $this->fieldKeys();
2854 $fieldKey = $fieldKeys[$fieldName] ??
NULL;
2856 // If neither worked then this field doesn't exist. Return false.
2857 if (empty($fields[$fieldKey])) {
2860 return $fields[$fieldKey];
2864 * Get SQL where clause for SQL filter syntax input parameters.
2866 * SQL version of api function to assign filters to the DAO based on the syntax
2867 * $field => array('IN' => array(4,6,9))
2869 * $field => array('LIKE' => array('%me%))
2872 * @param string $fieldName
2874 * @param array $filter
2875 * filter to be applied indexed by operator.
2876 * @param string $type
2877 * type of field (not actually used - nor in api @todo ).
2878 * @param string $alias
2879 * alternative field name ('as') @todo- not actually used.
2880 * @param bool $returnSanitisedArray
2881 * Return a sanitised array instead of a clause.
2882 * this is primarily so we can add filters @ the api level to the Query object based fields
2886 * @return NULL|string|array
2887 * a string is returned if $returnSanitisedArray is not set, otherwise and Array or NULL
2888 * depending on whether it is supported as yet
2890 public static function createSQLFilter($fieldName, $filter, $type = NULL, $alias = NULL, $returnSanitisedArray = FALSE) {
2891 foreach ($filter as $operator => $criteria) {
2892 $emojiFilter = CRM_Utils_SQL
::handleEmojiInQuery($criteria);
2893 if ($emojiFilter === '0 = 1') {
2894 return $emojiFilter;
2897 if (in_array($operator, self
::acceptedSQLOperators(), TRUE)) {
2898 switch ($operator) {
2902 if (!$returnSanitisedArray) {
2903 return (sprintf('%s %s', $fieldName, $operator));
2906 return (sprintf('%s %s ', $fieldName, $operator));
2910 // ternary operators
2913 if ((empty($criteria[0]) && !in_array($criteria[0], ['0', 0]))||
(empty($criteria[1]) && !in_array($criteria[1], ['0', 0]))) {
2914 throw new Exception("invalid criteria for $operator");
2916 if (!$returnSanitisedArray) {
2917 return (sprintf('%s ' . $operator . ' "%s" AND "%s"', $fieldName, CRM_Core_DAO
::escapeString($criteria[0]), CRM_Core_DAO
::escapeString($criteria[1])));
2920 // not yet implemented (tests required to implement)
2928 if (empty($criteria)) {
2929 throw new Exception("invalid criteria for $operator");
2931 $escapedCriteria = array_map([
2935 if (!$returnSanitisedArray) {
2936 return (sprintf('%s %s ("%s")', $fieldName, $operator, implode('", "', $escapedCriteria)));
2938 return $escapedCriteria;
2943 if (!$returnSanitisedArray) {
2944 return (sprintf('%s %s "%s"', $fieldName, $operator, CRM_Core_DAO
::escapeString($criteria)));
2947 // not yet implemented (tests required to implement)
2956 * @see http://issues.civicrm.org/jira/browse/CRM-9150
2957 * support for other syntaxes is discussed in ticket but being put off for now
2960 public static function acceptedSQLOperators() {
2981 * SQL has a limit of 64 characters on various names:
2982 * table name, trigger name, column name ...
2984 * For custom groups and fields we generated names from user entered input
2985 * which can be longer than this length, this function helps with creating
2986 * strings that meet various criteria.
2988 * @param string $string
2989 * The string to be shortened.
2990 * @param int $length
2991 * The max length of the string.
2993 * @param bool $makeRandom
2997 public static function shortenSQLName($string, $length = 60, $makeRandom = FALSE) {
2998 // early return for strings that meet the requirements
2999 if (strlen($string) <= $length) {
3003 // easy return for calls that dont need a randomized uniq string
3005 return substr($string, 0, $length);
3008 // the string is longer than the length and we need a uniq string
3009 // for the same tablename we need the same uniq string every time
3010 // hence we use md5 on the string, which is not random
3011 // we'll append 8 characters to the end of the tableName
3012 $md5string = substr(md5($string), 0, 8);
3013 return substr($string, 0, $length - 8) . "_{$md5string}";
3017 * https://issues.civicrm.org/jira/browse/CRM-17748
3018 * Sets the internal options to be used on a query
3020 * @param array $options
3023 public function setOptions($options) {
3024 if (is_array($options)) {
3025 $this->_options
= $options;
3030 * https://issues.civicrm.org/jira/browse/CRM-17748
3031 * wrapper to pass internal DAO options down to DB_mysql/DB_Common level
3033 * @param array $options
3036 protected function _setDBOptions($options) {
3037 global $_DB_DATAOBJECT;
3039 if (is_array($options) && count($options)) {
3040 $conn = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5
];
3041 foreach ($options as $option_name => $option_value) {
3042 $conn->setOption($option_name, $option_value);
3049 * @param array $params
3051 public function setApiFilter(&$params) {
3055 * Generates acl clauses suitable for adding to WHERE or ON when doing an api.get for this entity
3057 * Return format is in the form of fieldname => clauses starting with an operator. e.g.:
3060 * 'location_type_id' => array('IS NOT NULL', 'IN (1,2,3)')
3064 * Note that all array keys must be actual field names in this entity. Use subqueries to filter on other tables e.g. custom values.
3068 public function addSelectWhereClause() {
3070 $fields = $this->fields();
3071 foreach ($fields as $fieldName => $field) {
3072 // Clause for contact-related entities like Email, Relationship, etc.
3073 if (strpos($fieldName, 'contact_id') === 0 && CRM_Utils_Array
::value('FKClassName', $field) == 'CRM_Contact_DAO_Contact') {
3074 $clauses[$fieldName] = CRM_Utils_SQL
::mergeSubquery('Contact');
3076 // Clause for an entity_table/entity_id combo
3077 if ($fieldName === 'entity_id' && isset($fields['entity_table'])) {
3078 $relatedClauses = [];
3079 $relatedEntities = $this->buildOptions('entity_table', 'get');
3080 foreach ((array) $relatedEntities as $table => $ent) {
3082 $ent = CRM_Core_DAO_AllCoreTables
::getEntityNameForTable($table);
3083 $subquery = CRM_Utils_SQL
::mergeSubquery($ent);
3085 $relatedClauses[] = "(entity_table = '$table' AND entity_id " . implode(' AND entity_id ', $subquery) . ")";
3088 $relatedClauses[] = "(entity_table = '$table')";
3092 if ($relatedClauses) {
3093 $clauses['id'] = 'IN (SELECT id FROM `' . $this->tableName() . '` WHERE (' . implode(') OR (', $relatedClauses) . '))';
3097 CRM_Utils_Hook
::selectWhereClause($this, $clauses);
3102 * This returns the final permissioned query string for this entity
3104 * With acls from related entities + additional clauses from hook_civicrm_selectWhereClause
3106 * @param string $tableAlias
3109 public static function getSelectWhereClause($tableAlias = NULL) {
3110 $bao = new static();
3111 if ($tableAlias === NULL) {
3112 $tableAlias = $bao->tableName();
3115 foreach ((array) $bao->addSelectWhereClause() as $field => $vals) {
3116 $clauses[$field] = NULL;
3118 $clauses[$field] = "(`$tableAlias`.`$field` IS NULL OR (`$tableAlias`.`$field` " . implode(" AND `$tableAlias`.`$field` ", (array) $vals) . '))';
3125 * ensure database name is 'safe', i.e. only contains word characters (includes underscores)
3126 * and dashes, and contains at least one [a-z] case insensitive.
3132 public static function requireSafeDBName($database) {
3135 "/^[\w\-]*[a-z]+[\w\-]*$/i",
3139 if (empty($matches)) {
3146 * Transform an array to a serialized string for database storage.
3148 * @param array|null $value
3149 * @param int $serializationType
3150 * @return string|null
3152 * @throws \Exception
3154 public static function serializeField($value, $serializationType) {
3155 if ($value === NULL) {
3158 switch ($serializationType) {
3159 case self
::SERIALIZE_SEPARATOR_BOOKEND
:
3160 return $value === [] ?
'' : CRM_Utils_Array
::implodePadded($value);
3162 case self
::SERIALIZE_SEPARATOR_TRIMMED
:
3163 return is_array($value) ?
implode(self
::VALUE_SEPARATOR
, $value) : $value;
3165 case self
::SERIALIZE_JSON
:
3166 return is_array($value) ?
json_encode($value) : $value;
3168 case self
::SERIALIZE_PHP
:
3169 return is_array($value) ?
serialize($value) : $value;
3171 case self
::SERIALIZE_COMMA
:
3172 return is_array($value) ?
implode(',', $value) : $value;
3175 throw new Exception('Unknown serialization method for field.');
3180 * Transform a serialized string from the database into an array.
3182 * @param string|null $value
3183 * @param $serializationType
3185 * @return array|null
3186 * @throws CRM_Core_Exception
3188 public static function unSerializeField($value, $serializationType) {
3189 if ($value === NULL) {
3192 if ($value === '') {
3195 switch ($serializationType) {
3196 case self
::SERIALIZE_SEPARATOR_BOOKEND
:
3197 return (array) CRM_Utils_Array
::explodePadded($value);
3199 case self
::SERIALIZE_SEPARATOR_TRIMMED
:
3200 return explode(self
::VALUE_SEPARATOR
, trim($value));
3202 case self
::SERIALIZE_JSON
:
3203 return strlen($value) ?
json_decode($value, TRUE) : [];
3205 case self
::SERIALIZE_PHP
:
3206 return strlen($value) ? CRM_Utils_String
::unserialize($value) : [];
3208 case self
::SERIALIZE_COMMA
:
3209 return explode(',', trim(str_replace(', ', '', $value)));
3212 throw new CRM_Core_Exception('Unknown serialization method for field.');
3219 public static function getEntityRefFilters() {
3224 * Get exportable fields with pseudoconstants rendered as an extra field.
3226 * @param string $baoClass
3230 public static function getExportableFieldsWithPseudoConstants($baoClass) {
3231 if (method_exists($baoClass, 'exportableFields')) {
3232 $fields = $baoClass::exportableFields();
3235 $fields = $baoClass::export();
3237 CRM_Core_DAO
::appendPseudoConstantsToFields($fields);
3242 * Remove item from static cache during update/delete operations
3244 private function clearDbColumnValueCache() {
3245 $daoName = get_class($this);
3246 while (strpos($daoName, '_BAO_') !== FALSE) {
3247 $daoName = get_parent_class($daoName);
3249 if (isset($this->id
)) {
3250 unset(self
::$_dbColumnValueCache[$daoName]['id'][$this->id
]);
3252 if (isset($this->name
)) {
3253 unset(self
::$_dbColumnValueCache[$daoName]['name'][$this->name
]);
3258 * Return a mapping from field-name to the corresponding key (as used in fields()).
3261 * Array(string $name => string $uniqueName).
3263 public static function fieldKeys() {
3264 return array_flip(CRM_Utils_Array
::collect('name', static::fields()));
3268 * Returns system paths related to this entity (as defined in the xml schema)
3272 public static function getEntityPaths() {
3273 return static::$_paths ??
[];