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,
89 * Serialized string separated by and bookended with VALUE_SEPARATOR
91 SERIALIZE_SEPARATOR_BOOKEND
= 1,
93 * @deprecated format separated by VALUE_SEPARATOR
95 SERIALIZE_SEPARATOR_TRIMMED
= 2,
97 * Recommended serialization format
101 * @deprecated format using php serialize()
105 * Comma separated string, no quotes, no spaces
110 * Define entities that shouldn't be created or deleted when creating/ deleting
111 * test objects - this prevents world regions, countries etc from being added / deleted
114 public static $_testEntitiesToSkip = [];
116 * The factory class for this application.
119 public static $_factory = NULL;
122 * https://issues.civicrm.org/jira/browse/CRM-17748
123 * internal variable for DAO to hold per-query settings
126 protected $_options = [];
133 public function __construct() {
135 $this->__table
= $this->getTableName();
139 * Returns localized title of this entity.
143 public static function getEntityTitle() {
144 $className = static::class;
145 CRM_Core_Error
::deprecatedWarning("$className needs to be regenerated. Missing getEntityTitle method.");
146 return CRM_Core_DAO_AllCoreTables
::getBriefName($className);
150 * Returns user-friendly description of this entity.
152 * @return string|null
154 public static function getEntityDescription() {
158 public function __clone() {
159 if (!empty($this->_DB_resultid
)) {
160 $this->resultCopies++
;
167 public function __destruct() {
168 if ($this->resultCopies
=== 0) {
171 $this->resultCopies
--;
175 * Returns the name of this table
179 public static function getTableName() {
180 return self
::getLocaleTableName(static::$_tableName ??
NULL);
184 * Returns if this table needs to be logged
188 public function getLog() {
189 return static::$_log ??
FALSE;
193 * Initialize the DAO object.
196 * The database connection string.
198 public static function init($dsn) {
199 Civi
::$statics[__CLASS__
]['init'] = 1;
200 $options = &PEAR
::getStaticProperty('DB_DataObject', 'options');
201 $dsn = CRM_Utils_SQL
::autoSwitchDSN($dsn);
202 $options['database'] = $dsn;
203 $options['quote_identifiers'] = TRUE;
204 if (CRM_Utils_SQL
::isSSLDSN($dsn)) {
205 // There are two different options arrays.
206 $other_options = &PEAR
::getStaticProperty('DB', 'options');
207 $other_options['ssl'] = TRUE;
209 if (defined('CIVICRM_DAO_DEBUG')) {
210 self
::DebugLevel(CIVICRM_DAO_DEBUG
);
212 $factory = new CRM_Contact_DAO_Factory();
213 CRM_Core_DAO
::setFactory($factory);
214 CRM_Core_DAO
::executeQuery('SET NAMES utf8mb4');
215 CRM_Core_DAO
::executeQuery('SET @uniqueID = %1', [1 => [CRM_Utils_Request
::id(), 'String']]);
221 public static function getConnection() {
222 global $_DB_DATAOBJECT;
223 $dao = new CRM_Core_DAO();
224 return $_DB_DATAOBJECT['CONNECTIONS'][$dao->_database_dsn_md5
];
228 * Disables usage of the ONLY_FULL_GROUP_BY Mode if necessary
230 public static function disableFullGroupByMode() {
231 $currentModes = CRM_Utils_SQL
::getSqlModes();
232 if (in_array('ONLY_FULL_GROUP_BY', $currentModes) && CRM_Utils_SQL
::isGroupByModeInDefault()) {
233 $key = array_search('ONLY_FULL_GROUP_BY', $currentModes);
234 unset($currentModes[$key]);
235 CRM_Core_DAO
::executeQuery("SET SESSION sql_mode = %1", [1 => [implode(',', $currentModes), 'String']]);
240 * Re-enables ONLY_FULL_GROUP_BY sql_mode as necessary..
242 public static function reenableFullGroupByMode() {
243 $currentModes = CRM_Utils_SQL
::getSqlModes();
244 if (!in_array('ONLY_FULL_GROUP_BY', $currentModes) && CRM_Utils_SQL
::isGroupByModeInDefault()) {
245 $currentModes[] = 'ONLY_FULL_GROUP_BY';
246 CRM_Core_DAO
::executeQuery("SET SESSION sql_mode = %1", [1 => [implode(',', $currentModes), 'String']]);
251 * @param string $fieldName
253 * @param array $params
255 protected function assignTestFK($fieldName, $fieldDef, $params) {
256 $required = $fieldDef['required'] ??
NULL;
257 $FKClassName = $fieldDef['FKClassName'] ??
NULL;
258 $dbName = $fieldDef['name'];
259 $daoName = str_replace('_BAO_', '_DAO_', get_class($this));
261 // skip the FK if it is not required
262 // if it's contact id we should create even if not required
263 // we'll have a go @ fetching first though
264 // we WILL create campaigns though for so tests with a campaign pseudoconstant will complete
265 if ($FKClassName === 'CRM_Campaign_DAO_Campaign' && $daoName != $FKClassName) {
268 if (!$required && $dbName != 'contact_id') {
269 $fkDAO = new $FKClassName();
270 if ($fkDAO->find(TRUE)) {
271 $this->$dbName = $fkDAO->id
;
275 elseif (in_array($FKClassName, CRM_Core_DAO
::$_testEntitiesToSkip)) {
276 $depObject = new $FKClassName();
277 $depObject->find(TRUE);
278 $this->$dbName = $depObject->id
;
280 elseif ($daoName == 'CRM_Member_DAO_MembershipType' && $fieldName == 'member_of_contact_id') {
281 // FIXME: the fields() metadata is not specific enough
282 $depObject = CRM_Core_DAO
::createTestObject($FKClassName, ['contact_type' => 'Organization']);
283 $this->$dbName = $depObject->id
;
286 //if it is required we need to generate the dependency object first
287 $depObject = CRM_Core_DAO
::createTestObject($FKClassName, CRM_Utils_Array
::value($dbName, $params, 1));
288 $this->$dbName = $depObject->id
;
293 * Generate and assign an arbitrary value to a field of a test object.
295 * @param string $fieldName
296 * @param array $fieldDef
297 * @param int $counter
298 * The globally-unique ID of the test object.
300 * @throws \CRM_Core_Exception
302 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
303 $dbName = $fieldDef['name'];
304 $daoName = get_class($this);
307 if (in_array($dbName, ['contact_sub_type', 'email_greeting_id', 'postal_greeting_id', 'addressee_id'], TRUE)) {
308 //coming up with a rule to set these is too complex - skip
312 // Pick an option value if needed
313 if (!$handled && $fieldDef['type'] !== CRM_Utils_Type
::T_BOOLEAN
) {
314 $options = $daoName::buildOptions($dbName, 'create');
316 $this->$dbName = key($options);
322 switch ($fieldDef['type']) {
323 case CRM_Utils_Type
::T_INT
:
324 case CRM_Utils_Type
::T_FLOAT
:
325 case CRM_Utils_Type
::T_MONEY
:
326 if (isset($fieldDef['precision'])) {
327 // $object->$dbName = CRM_Utils_Number::createRandomDecimal($value['precision']);
328 $this->$dbName = CRM_Utils_Number
::createTruncatedDecimal($counter, $fieldDef['precision']);
331 $this->$dbName = $counter;
335 case CRM_Utils_Type
::T_BOOLEAN
:
336 if (isset($fieldDef['default'])) {
337 $this->$dbName = $fieldDef['default'];
339 elseif ($fieldDef['name'] == 'is_deleted' ||
$fieldDef['name'] == 'is_test') {
347 case CRM_Utils_Type
::T_DATE
:
348 case CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
:
349 $this->$dbName = '19700101';
350 if ($dbName == 'end_date') {
351 // put this in the future
352 $this->$dbName = '20200101';
356 case CRM_Utils_Type
::T_TIMESTAMP
:
357 $this->$dbName = '19700201000000';
360 case CRM_Utils_Type
::T_TIME
:
361 throw new CRM_Core_Exception('T_TIME shouldn\'t be used.');
363 case CRM_Utils_Type
::T_CCNUM
:
364 $this->$dbName = '4111 1111 1111 1111';
367 case CRM_Utils_Type
::T_URL
:
368 $this->$dbName = 'http://www.civicrm.org';
371 case CRM_Utils_Type
::T_STRING
:
372 case CRM_Utils_Type
::T_BLOB
:
373 case CRM_Utils_Type
::T_MEDIUMBLOB
:
374 case CRM_Utils_Type
::T_TEXT
:
375 case CRM_Utils_Type
::T_LONGTEXT
:
376 case CRM_Utils_Type
::T_EMAIL
:
378 // WAS: if (isset($value['enumValues'])) {
379 // TODO: see if this works with all pseudoconstants
380 if (isset($fieldDef['pseudoconstant'], $fieldDef['pseudoconstant']['callback'])) {
381 if (isset($fieldDef['default'])) {
382 $this->$dbName = $fieldDef['default'];
385 $options = CRM_Core_PseudoConstant
::get($daoName, $fieldName);
386 if (is_array($options)) {
387 $this->$dbName = $options[0];
390 $defaultValues = explode(',', $options);
391 $this->$dbName = $defaultValues[0];
396 $this->$dbName = $dbName . '_' . $counter;
397 $maxlength = $fieldDef['maxlength'] ??
NULL;
398 if ($maxlength > 0 && strlen($this->$dbName) > $maxlength) {
399 $this->$dbName = substr($this->$dbName, 0, $fieldDef['maxlength']);
407 * Reset the DAO object.
409 * DAO is kinda crappy in that there is an unwritten rule of one query per DAO.
411 * We attempt to get around this crappy restriction by resetting some of DAO's internal fields. Use this with caution
413 public function reset() {
415 foreach (array_keys($this->table()) as $field) {
416 unset($this->$field);
420 * reset the various DB_DAO structures manually
429 * @param string $tableName
433 public static function getLocaleTableName($tableName) {
436 $tables = CRM_Core_I18n_Schema
::schemaStructureTables();
437 if (in_array($tableName, $tables)) {
438 return $tableName . $dbLocale;
445 * Execute a query by the current DAO, localizing it along the way (if needed).
447 * @param string $query
448 * The SQL query for execution.
449 * @param bool $i18nRewrite
450 * Whether to rewrite the query.
453 * the current DAO object after the query execution
455 public function query($query, $i18nRewrite = TRUE) {
456 // rewrite queries that should use $dbLocale-based views for multi-language installs
457 global $dbLocale, $_DB_DATAOBJECT;
459 if (empty($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5
])) {
460 // Will force connection to be populated per CRM-20541.
464 $conn = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5
];
465 $orig_options = $conn->options
;
466 $this->_setDBOptions($this->_options
);
468 if ($i18nRewrite and $dbLocale) {
469 $query = CRM_Core_I18n_Schema
::rewriteQuery($query);
472 $ret = parent
::query($query);
474 $this->_setDBOptions($orig_options);
479 * Static function to set the factory instance for this class.
481 * @param object $factory
482 * The factory application object.
484 public static function setFactory(&$factory) {
485 self
::$_factory = &$factory;
489 * Factory method to instantiate a new object from a table name.
491 * @param string $table
492 * @return \DataObject|\PEAR_Error
494 public function factory($table = '') {
495 if (!isset(self
::$_factory)) {
496 return parent
::factory($table);
499 return self
::$_factory->create($table);
503 * Initialization for all DAO objects. Since we access DB_DO programatically
504 * we need to set the links manually.
506 public function initialize() {
508 if (empty(Civi
::$statics[__CLASS__
]['init'])) {
509 // CRM_Core_DAO::init() must be called before CRM_Core_DAO->initialize().
510 // This occurs very early in bootstrap - error handlers may not be wired up.
511 echo "Inconsistent system initialization sequence. Premature access of (" . get_class($this) . ")";
512 CRM_Utils_System
::civiExit();
517 * Defines the default key as 'id'.
521 public function keys() {
530 * Tells DB_DataObject which keys use autoincrement.
531 * 'id' is autoincrementing by default.
536 public function sequenceKey() {
537 static $sequenceKeys;
538 if (!isset($sequenceKeys)) {
539 $sequenceKeys = ['id', TRUE];
541 return $sequenceKeys;
545 * Returns list of FK relationships.
547 * @return CRM_Core_Reference_Basic[]
549 public static function getReferenceColumns() {
550 if (!isset(Civi
::$statics[static::class]['links'])) {
551 Civi
::$statics[static::class]['links'] = static::createReferenceColumns(static::class);
552 CRM_Core_DAO_AllCoreTables
::invoke(static::class, 'links_callback', Civi
::$statics[static::class]['links']);
554 return Civi
::$statics[static::class]['links'];
558 * Returns all the column names of this table.
563 public static function &fields() {
569 * Returns all usable fields, indexed by name.
571 * This function differs from fields() in that it indexes by name rather than unique_name.
573 * It excludes fields not added yet by pending upgrades.
574 * This avoids problems with trying to SELECT a field that exists in code but has not yet been added to the db.
576 * @param bool $checkPermissions
577 * Filter by field permissions.
580 public static function getSupportedFields($checkPermissions = FALSE) {
581 $fields = array_column((array) static::fields(), NULL, 'name');
583 // Exclude fields yet not added by pending upgrades
584 $dbVer = \CRM_Core_BAO_Domain
::version();
585 $daoExt = defined(static::class . '::EXT') ?
constant(static::class . '::EXT') : NULL;
586 if ($fields && $daoExt === 'civicrm' && version_compare($dbVer, \CRM_Utils_System
::version()) < 0) {
587 $fields = array_filter($fields, function($field) use ($dbVer) {
588 $add = $field['add'] ??
'1.0.0';
589 if (substr_count($add, '.') < 2) {
592 return version_compare($dbVer, $add, '>=');
596 // Exclude fields the user does not have permission for
597 if ($checkPermissions) {
598 $fields = array_filter($fields, function($field) {
599 return empty($field['permission']) || CRM_Core_Permission
::check($field['permission']);
607 * Get/set an associative array of table columns
612 public function table() {
613 $fields = $this->fields();
617 foreach ($fields as $name => $value) {
618 $table[$value['name']] = $value['type'];
619 if (!empty($value['required'])) {
620 $table[$value['name']] +
= self
::DB_DAO_NOTNULL
;
633 * @return CRM_Core_DAO
635 public function save($hook = TRUE) {
637 if (!empty($this->id
)) {
639 $preEvent = new \Civi\Core\DAO\Event\
PreUpdate($this);
640 $preEvent->eventID
= $eventID;
641 \Civi
::dispatcher()->dispatch("civi.dao.preUpdate", $preEvent);
644 $result = $this->update();
647 $event = new \Civi\Core\DAO\Event\
PostUpdate($this, $result);
648 $event->eventID
= $eventID;
649 \Civi
::dispatcher()->dispatch("civi.dao.postUpdate", $event);
651 $this->clearDbColumnValueCache();
655 $preEvent = new \Civi\Core\DAO\Event\
PreUpdate($this);
656 $preEvent->eventID
= $eventID;
657 \Civi
::dispatcher()->dispatch("civi.dao.preInsert", $preEvent);
660 $result = $this->insert();
663 $event = new \Civi\Core\DAO\Event\
PostUpdate($this, $result);
664 $event->eventID
= $eventID;
665 \Civi
::dispatcher()->dispatch("civi.dao.postInsert", $event);
671 CRM_Utils_Hook
::postSave($this);
678 * Deletes items from table which match current objects variables.
680 * Returns the true on success
684 * Designed to be extended
686 * $object = new mytable();
688 * echo $object->delete(); // builds a conditon
690 * $object = new mytable();
691 * $object->whereAdd('age > 12');
693 * $object->orderBy('age DESC');
694 * $object->delete(true); // dont use object vars, use the conditions, limit and order.
696 * @param bool $useWhere (optional) If DB_DATAOBJECT_WHEREADD_ONLY is passed in then
697 * we will build the condition only using the whereAdd's. Default is to
698 * build the condition only using the object parameters.
701 * Int (No. of rows affected) on success, false on failure, 0 on no data affected
703 public function delete($useWhere = FALSE) {
704 $preEvent = new \Civi\Core\DAO\Event\
PreDelete($this);
705 \Civi
::dispatcher()->dispatch("civi.dao.preDelete", $preEvent);
707 $result = parent
::delete($useWhere);
709 $event = new \Civi\Core\DAO\Event\
PostDelete($this, $result);
710 \Civi
::dispatcher()->dispatch("civi.dao.postDelete", $event);
713 $this->clearDbColumnValueCache();
719 * @param bool $created
721 public function log($created = FALSE) {
724 if (!$this->getLog()) {
729 $session = CRM_Core_Session
::singleton();
730 $cid = $session->get('userID');
733 // return is we dont have handle to FK
738 $dao = new CRM_Core_DAO_Log();
739 $dao->entity_table
= $this->getTableName();
740 $dao->entity_id
= $this->id
;
741 $dao->modified_id
= $cid;
742 $dao->modified_date
= date("YmdHis");
747 * Given an associative array of name/value pairs, extract all the values
748 * that belong to this object and initialize the object with said values
750 * @param array $params
751 * Array of name/value pairs to save.
754 * Did we copy all null values into the object
756 public function copyValues($params) {
758 foreach ($this->fields() as $uniqueName => $field) {
759 $dbName = $field['name'];
760 if (array_key_exists($dbName, $params)) {
761 $value = $params[$dbName];
764 elseif (array_key_exists($uniqueName, $params)) {
765 $value = $params[$uniqueName];
772 // if there is no value then make the variable NULL
775 $this->$dbName = 'null';
777 elseif (is_array($value) && !empty($field['serialize'])) {
778 $this->$dbName = CRM_Core_DAO
::serializeField($value, $field['serialize']);
782 $maxLength = $field['maxlength'] ??
NULL;
783 if (!is_array($value) && $maxLength && mb_strlen($value) > $maxLength && empty($field['pseudoconstant'])) {
784 // No ts() since this is a sysadmin-y string not seen by general users.
785 Civi
::log()->warning('A string for field {dbName} has been truncated. The original string was {value}.', ['dbName' => $dbName, 'value' => $value]);
786 // The string is too long - what to do what to do? Well losing data is generally bad so let's truncate
787 $value = CRM_Utils_String
::ellipsify($value, $maxLength);
789 $this->$dbName = $value;
798 * Store all the values from this object in an associative array
799 * this is a destructive store, calling function is responsible
800 * for keeping sanity of id's.
802 * @param object $object
803 * The object that we are extracting data from.
804 * @param array $values
805 * (reference ) associative array of name/value pairs.
807 public static function storeValues(&$object, &$values) {
808 $fields = $object->fields();
809 foreach ($fields as $name => $value) {
810 $dbName = $value['name'];
811 if (isset($object->$dbName) && $object->$dbName !== 'null') {
812 $values[$dbName] = $object->$dbName;
813 if ($name != $dbName) {
814 $values[$name] = $object->$dbName;
821 * Create an attribute for this specific field. We only do this for strings and text
823 * @param array $field
824 * The field under task.
827 * the attributes for the object
829 public static function makeAttribute($field) {
831 if (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_STRING
) {
832 $maxLength = $field['maxlength'] ??
NULL;
833 $size = $field['size'] ??
NULL;
834 if ($maxLength ||
$size) {
837 $attributes['maxlength'] = $maxLength;
840 $attributes['size'] = $size;
845 elseif (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_TEXT
) {
846 $rows = $field['rows'] ??
NULL;
850 $cols = $field['cols'] ??
NULL;
856 $attributes['rows'] = $rows;
857 $attributes['cols'] = $cols;
860 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
) {
861 $attributes['size'] = 6;
862 $attributes['maxlength'] = 14;
870 * Get the size and maxLength attributes for this text field.
871 * (or for all text fields) in the DAO object.
873 * @param string $class
875 * @param string $fieldName
876 * Field that i'm interested in or null if.
877 * you want the attributes for all DAO text fields
880 * assoc array of name => attribute pairs
882 public static function getAttribute($class, $fieldName = NULL) {
883 $object = new $class();
884 $fields = $object->fields();
885 if ($fieldName != NULL) {
886 $field = $fields[$fieldName] ??
NULL;
887 return self
::makeAttribute($field);
891 foreach ($fields as $name => $field) {
892 $attribute = self
::makeAttribute($field);
894 $attributes[$name] = $attribute;
898 if (!empty($attributes)) {
906 * Create or update a record from supplied params.
908 * If 'id' is supplied, an existing record will be updated
909 * Otherwise a new record will be created.
911 * @param array $record
914 * @throws \CRM_Core_Exception
916 public static function writeRecord(array $record): CRM_Core_DAO
{
917 $op = empty($record['id']) ?
'create' : 'edit';
918 $className = CRM_Core_DAO_AllCoreTables
::getCanonicalClassName(static::class);
919 if ($className === 'CRM_Core_DAO') {
920 throw new CRM_Core_Exception('Function writeRecord must be called on a subclass of CRM_Core_DAO');
922 $entityName = CRM_Core_DAO_AllCoreTables
::getBriefName($className);
924 \CRM_Utils_Hook
::pre($op, $entityName, $record['id'] ??
NULL, $record);
925 $fields = static::getSupportedFields();
926 $instance = new static();
927 // Ensure fields exist before attempting to write to them
928 $values = array_intersect_key($record, $fields);
929 $instance->copyValues($values);
930 if (empty($values['id']) && array_key_exists('name', $fields) && empty($values['name'])) {
931 $instance->makeNameFromLabel(!empty($fields['name']['required']));
935 if (!empty($record['custom']) && is_array($record['custom'])) {
936 CRM_Core_BAO_CustomValueTable
::store($record['custom'], static::$_tableName, $instance->id
, $op);
939 \CRM_Utils_Hook
::post($op, $entityName, $instance->id
, $instance);
945 * Bulk save multiple records
947 * @param array[] $records
949 * @throws CRM_Core_Exception
951 public static function writeRecords(array $records): array {
953 foreach ($records as $record) {
954 $results[] = static::writeRecord($record);
960 * Delete a record from supplied params.
962 * @param array $record
965 * @throws CRM_Core_Exception
967 public static function deleteRecord(array $record) {
968 $className = CRM_Core_DAO_AllCoreTables
::getCanonicalClassName(static::class);
969 if ($className === 'CRM_Core_DAO') {
970 throw new CRM_Core_Exception('Function deleteRecord must be called on a subclass of CRM_Core_DAO');
972 $entityName = CRM_Core_DAO_AllCoreTables
::getBriefName($className);
973 if (empty($record['id'])) {
974 throw new CRM_Core_Exception("Cannot delete {$entityName} with no id.");
976 CRM_Utils_Type
::validate($record['id'], 'Positive');
978 CRM_Utils_Hook
::pre('delete', $entityName, $record['id'], $record);
979 $instance = new $className();
980 $instance->id
= $record['id'];
981 // Load complete object for the sake of hook_civicrm_post, below
982 $instance->find(TRUE);
983 if (!$instance ||
!$instance->delete()) {
984 throw new CRM_Core_Exception("Could not delete {$entityName} id {$record['id']}");
986 // For other operations this hook is passed an incomplete object and hook listeners can load if needed.
987 // But that's not possible with delete because it's gone from the database by the time this hook is called.
988 // So in this case the object has been pre-loaded so hook listeners have access to the complete record.
989 CRM_Utils_Hook
::post('delete', $entityName, $record['id'], $instance);
995 * Bulk delete multiple records.
997 * @param array[] $records
999 * @throws CRM_Core_Exception
1001 public static function deleteRecords(array $records) {
1003 foreach ($records as $record) {
1004 $results[] = static::deleteRecord($record);
1010 * Check if there is a record with the same name in the db.
1012 * @param string $value
1013 * The value of the field we are checking.
1014 * @param string $daoName
1015 * The dao object name.
1016 * @param string $daoID
1017 * The id of the object being updated. u can change your name.
1018 * as long as there is no conflict
1019 * @param string $fieldName
1020 * The name of the field in the DAO.
1022 * @param string $domainID
1023 * The id of the domain. Object exists only for the given domain.
1026 * true if object exists
1028 public static function objectExists($value, $daoName, $daoID, $fieldName = 'name', $domainID = NULL) {
1029 $object = new $daoName();
1030 $object->$fieldName = $value;
1032 $object->domain_id
= $domainID;
1035 if ($object->find(TRUE)) {
1036 return $daoID && $object->id
== $daoID;
1044 * Check if there is a given column in a specific table.
1047 * @see CRM_Core_BAO_SchemaHandler::checkIfFieldExists
1049 * @param string $tableName
1050 * @param string $columnName
1051 * @param bool $i18nRewrite
1052 * Whether to rewrite the query on multilingual setups.
1055 * true if exists, else false
1057 public static function checkFieldExists($tableName, $columnName, $i18nRewrite = TRUE) {
1058 CRM_Core_Error
::deprecatedFunctionWarning('CRM_Core_BAO_SchemaHandler::checkIfFieldExists');
1059 return CRM_Core_BAO_SchemaHandler
::checkIfFieldExists($tableName, $columnName, $i18nRewrite);
1063 * Scans all the tables using a slow query and table name.
1067 public static function getTableNames() {
1068 $dao = CRM_Core_DAO
::executeQuery(
1070 FROM information_schema.TABLES
1071 WHERE TABLE_SCHEMA = '" . CRM_Core_DAO
::getDatabaseName() . "'
1072 AND TABLE_NAME LIKE 'civicrm_%'
1073 AND TABLE_NAME NOT LIKE 'civicrm_import_job_%'
1074 AND TABLE_NAME NOT LIKE '%_temp%'
1077 while ($dao->fetch()) {
1078 $values[] = $dao->TABLE_NAME
;
1084 * @param int $maxTablesToCheck
1088 public static function isDBMyISAM($maxTablesToCheck = 10) {
1089 return CRM_Core_DAO
::singleValueQuery(
1091 FROM information_schema.TABLES
1092 WHERE ENGINE = 'MyISAM'
1093 AND TABLE_SCHEMA = '" . CRM_Core_DAO
::getDatabaseName() . "'
1094 AND TABLE_NAME LIKE 'civicrm_%'
1095 AND TABLE_NAME NOT LIKE 'civicrm_import_job_%'
1096 AND TABLE_NAME NOT LIKE '%_temp%'
1097 AND TABLE_NAME NOT LIKE 'civicrm_tmp_%'
1102 * Get the name of the CiviCRM database.
1106 public static function getDatabaseName() {
1107 $daoObj = new CRM_Core_DAO();
1108 return $daoObj->database();
1112 * Checks if a constraint exists for a specified table.
1114 * @param string $tableName
1115 * @param string $constraint
1118 * true if constraint exists, false otherwise
1120 * @throws \CRM_Core_Exception
1122 public static function checkConstraintExists($tableName, $constraint) {
1125 if (!array_key_exists($tableName, $show)) {
1126 $query = "SHOW CREATE TABLE $tableName";
1127 $dao = CRM_Core_DAO
::executeQuery($query, [], TRUE, NULL, FALSE, FALSE);
1129 if (!$dao->fetch()) {
1130 throw new CRM_Core_Exception('query failed');
1133 $show[$tableName] = $dao->Create_Table
;
1136 return (bool) preg_match("/\b$constraint\b/i", $show[$tableName]);
1140 * Checks if CONSTRAINT keyword exists for a specified table.
1142 * @param array $tables
1144 * @throws CRM_Core_Exception
1147 * true if CONSTRAINT keyword exists, false otherwise
1149 public static function schemaRequiresRebuilding($tables = ["civicrm_contact"]) {
1151 foreach ($tables as $tableName) {
1152 if (!array_key_exists($tableName, $show)) {
1153 $query = "SHOW CREATE TABLE $tableName";
1154 $dao = CRM_Core_DAO
::executeQuery($query, [], TRUE, NULL, FALSE, FALSE);
1156 if (!$dao->fetch()) {
1157 throw new CRM_Core_Exception('Show create table failed.');
1160 $show[$tableName] = $dao->Create_Table
;
1163 $result = (bool) preg_match("/\bCONSTRAINT\b\s/i", $show[$tableName]);
1164 if ($result == TRUE) {
1175 * Checks if the FK constraint name is in the format 'FK_tableName_columnName'
1176 * for a specified column of a table.
1178 * @param string $tableName
1179 * @param string $columnName
1182 * true if in format, false otherwise
1184 * @throws \CRM_Core_Exception
1186 public static function checkFKConstraintInFormat($tableName, $columnName) {
1189 if (!array_key_exists($tableName, $show)) {
1190 $query = "SHOW CREATE TABLE $tableName";
1191 $dao = CRM_Core_DAO
::executeQuery($query);
1193 if (!$dao->fetch()) {
1194 throw new CRM_Core_Exception('query failed');
1197 $show[$tableName] = $dao->Create_Table
;
1199 $constraint = "`FK_{$tableName}_{$columnName}`";
1200 $pattern = "/\bCONSTRAINT\b\s+%s\s+\bFOREIGN\s+KEY\b\s/i";
1201 return (bool) preg_match(sprintf($pattern, $constraint), $show[$tableName]);
1205 * Check whether a specific column in a specific table has always the same value.
1207 * @param string $tableName
1208 * @param string $columnName
1209 * @param string $columnValue
1212 * true if the value is always $columnValue, false otherwise
1214 public static function checkFieldHasAlwaysValue($tableName, $columnName, $columnValue) {
1215 $query = "SELECT * FROM $tableName WHERE $columnName != '$columnValue'";
1216 $dao = CRM_Core_DAO
::executeQuery($query);
1217 $result = $dao->fetch() ?
FALSE : TRUE;
1222 * Check whether a specific column in a specific table is always NULL.
1224 * @param string $tableName
1225 * @param string $columnName
1228 * true if if the value is always NULL, false otherwise
1230 public static function checkFieldIsAlwaysNull($tableName, $columnName) {
1231 $query = "SELECT * FROM $tableName WHERE $columnName IS NOT NULL";
1232 $dao = CRM_Core_DAO
::executeQuery($query);
1233 $result = $dao->fetch() ?
FALSE : TRUE;
1238 * Checks if this DAO's table ought to exist.
1240 * If there are pending DB updates, this function compares the CiviCRM version of the table to the current schema version.
1243 * @throws CRM_Core_Exception
1245 public static function tableHasBeenAdded() {
1246 if (CRM_Utils_System
::version() === CRM_Core_BAO_Domain
::version()) {
1249 $daoExt = defined(static::class . '::EXT') ?
constant(static::class . '::EXT') : NULL;
1250 $daoVersion = defined(static::class . '::TABLE_ADDED') ?
constant(static::class . '::TABLE_ADDED') : '1.0';
1251 return !($daoExt === 'civicrm' && version_compare(CRM_Core_BAO_Domain
::version(), $daoVersion, '<'));
1255 * Check if there is a given table in the database.
1257 * @param string $tableName
1260 * true if exists, else false
1262 public static function checkTableExists($tableName) {
1267 $params = [1 => [$tableName, 'String']];
1269 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1270 return (bool) $dao->fetch();
1274 * Check if a given table has data.
1276 * @param string $tableName
1278 * TRUE if $tableName has at least one record.
1280 public static function checkTableHasData($tableName) {
1281 $c = CRM_Core_DAO
::singleValueQuery(sprintf('SELECT count(*) c FROM `%s`', $tableName));
1290 public function checkVersion($version) {
1291 CRM_Core_Error
::deprecatedFunctionWarning('CRM_Core_BAO_Domain::version');
1292 $dbVersion = CRM_Core_BAO_Domain
::version();
1293 return trim($version) == trim($dbVersion);
1297 * Find a DAO object for the given ID and return it.
1300 * Id of the DAO object being searched for.
1302 * @return CRM_Core_DAO
1303 * Object of the type of the class that called this function.
1307 public static function findById($id) {
1308 $object = new static();
1310 if (!$object->find(TRUE)) {
1311 throw new Exception("Unable to find a " . get_called_class() . " with id {$id}.");
1317 * Returns all results as array-encoded records.
1321 public function fetchAll($k = FALSE, $v = FALSE, $method = FALSE) {
1323 while ($this->fetch()) {
1324 $result[] = $this->toArray();
1330 * Return the results as PHP generator.
1332 * @param string $type
1333 * Whether the generator yields 'dao' objects or 'array's.
1335 public function fetchGenerator($type = 'dao') {
1336 while ($this->fetch()) {
1343 yield
$this->toArray();
1347 throw new \
RuntimeException("Invalid record type ($type)");
1353 * Returns a singular value.
1355 * @return mixed|NULL
1357 public function fetchValue() {
1358 $result = $this->getDatabaseResult();
1359 $row = $result->fetchRow();
1369 * Get all the result records as mapping between columns.
1371 * @param string $keyColumn
1373 * @param string $valueColumn
1376 * Ex: ["foo" => "The Foo Bar", "baz" => "The Baz Qux"]
1378 public function fetchMap($keyColumn, $valueColumn) {
1380 while ($this->fetch()) {
1381 $result[$this->{$keyColumn}] = $this->{$valueColumn};
1387 * Given a DAO name, a column name and a column value, find the record and GET the value of another column in that record
1389 * @param string $daoName
1390 * Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact).
1391 * @param int $searchValue
1392 * Value of the column you want to search by.
1393 * @param string $returnColumn
1394 * Name of the column you want to GET the value of.
1395 * @param string $searchColumn
1396 * Name of the column you want to search by.
1397 * @param bool $force
1398 * Skip use of the cache.
1400 * @return string|int|null
1401 * Value of $returnColumn in the retrieved record
1403 * @throws \CRM_Core_Exception
1405 public static function getFieldValue($daoName, $searchValue, $returnColumn = 'name', $searchColumn = 'id', $force = FALSE) {
1407 empty($searchValue) ||
1408 trim(strtolower($searchValue)) == 'null'
1410 // adding this here since developers forget to check for an id
1411 // or for the 'null' (which is a bad DAO kludge)
1412 // and hence we get the first value in the db
1413 throw new CRM_Core_Exception('getFieldValue failed');
1416 self
::$_dbColumnValueCache = self
::$_dbColumnValueCache ??
[];
1418 while (strpos($daoName, '_BAO_') !== FALSE) {
1419 $daoName = get_parent_class($daoName);
1423 empty(self
::$_dbColumnValueCache[$daoName][$searchColumn][$searchValue]) ||
1424 !array_key_exists($returnColumn, self
::$_dbColumnValueCache[$daoName][$searchColumn][$searchValue])
1426 $object = new $daoName();
1427 $object->$searchColumn = $searchValue;
1428 $object->selectAdd();
1429 $object->selectAdd($returnColumn);
1432 if ($object->find(TRUE)) {
1433 $result = $object->$returnColumn;
1436 self
::$_dbColumnValueCache[$daoName][$searchColumn][$searchValue][$returnColumn] = $result;
1438 return self
::$_dbColumnValueCache[$daoName][$searchColumn][$searchValue][$returnColumn];
1442 * Given a DAO name, a column name and a column value, find the record and SET the value of another column in that record
1444 * @param string $daoName
1445 * Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact).
1446 * @param int $searchValue
1447 * Value of the column you want to search by.
1448 * @param string $setColumn
1449 * Name of the column you want to SET the value of.
1450 * @param string $setValue
1451 * SET the setColumn to this value.
1452 * @param string $searchColumn
1453 * Name of the column you want to search by.
1456 * true if we found and updated the object, else false
1458 public static function setFieldValue($daoName, $searchValue, $setColumn, $setValue, $searchColumn = 'id') {
1459 $object = new $daoName();
1460 $object->selectAdd();
1461 $object->selectAdd("$searchColumn, $setColumn");
1462 $object->$searchColumn = $searchValue;
1464 if ($object->find(TRUE)) {
1465 $object->$setColumn = $setValue;
1466 if ($object->save()) {
1477 * @param array|object $sort either array or CRM_Utils_Sort
1478 * @param string $default
1479 * Default sort value.
1483 public static function getSortString($sort, $default = NULL) {
1484 // check if sort is of type CRM_Utils_Sort
1485 if (is_a($sort, 'CRM_Utils_Sort')) {
1486 return $sort->orderBy();
1491 // is it an array specified as $field => $sortDirection ?
1493 foreach ($sort as $k => $v) {
1494 $sortString .= "$k $v,";
1496 return rtrim($sortString, ',');
1502 * Fetch object based on array of properties.
1504 * @param string $daoName
1505 * Name of the dao class.
1506 * @param array $params
1507 * (reference) an assoc array of name/value pairs.
1508 * @param array $defaults
1509 * (reference) an assoc array to hold the flattened values.
1510 * @param array $returnProperities
1511 * An assoc array of fields that need to be returned, e.g. ['first_name', 'last_name'].
1513 * @return static|null
1515 public static function commonRetrieve($daoName, &$params, &$defaults, $returnProperities = NULL) {
1516 $object = new $daoName();
1517 $object->copyValues($params);
1519 // return only specific fields if returnproperties are sent
1520 if (!empty($returnProperities)) {
1521 $object->selectAdd();
1522 $object->selectAdd(implode(',', $returnProperities));
1525 if ($object->find(TRUE)) {
1526 self
::storeValues($object, $defaults);
1533 * Delete the object records that are associated with this contact.
1537 * @param string $daoName
1538 * Name of the dao object.
1539 * @param int $contactId
1540 * Id of the contact to delete.
1542 public static function deleteEntityContact($daoName, $contactId) {
1543 CRM_Core_Error
::deprecatedFunctionWarning('APIv4');
1544 $object = new $daoName();
1546 $object->entity_table
= 'civicrm_contact';
1547 $object->entity_id
= $contactId;
1552 * Execute an unbuffered query.
1554 * This is a wrapper around new functionality exposed with CRM-17748.
1556 * @param string $query query to be executed
1558 * @param array $params
1559 * @param bool $abort
1560 * @param null $daoName
1561 * @param bool $freeDAO
1562 * @param bool $i18nRewrite
1563 * @param bool $trapException
1565 * @return CRM_Core_DAO
1566 * Object that points to an unbuffered result set
1568 public static function executeUnbufferedQuery(
1574 $i18nRewrite = TRUE,
1575 $trapException = FALSE
1578 return self
::executeQuery(
1586 ['result_buffering' => 0]
1593 * @param string $query
1594 * Query to be executed.
1596 * @param array $params
1597 * @param bool $abort
1598 * @param null $daoName
1599 * @param bool $freeDAO
1600 * @param bool $i18nRewrite
1601 * @param bool $trapException
1602 * @param array $options
1604 * @return CRM_Core_DAO|object
1605 * object that holds the results of the query
1606 * NB - if this is defined as just returning a DAO phpstorm keeps pointing
1607 * out all the properties that are not part of the DAO
1609 public static function &executeQuery(
1615 $i18nRewrite = TRUE,
1616 $trapException = FALSE,
1619 $queryStr = self
::composeQuery($query, $params, $abort);
1622 $dao = new CRM_Core_DAO();
1625 $dao = new $daoName();
1628 if ($trapException) {
1629 CRM_Core_Error
::deprecatedFunctionWarning('calling functions should handle exceptions');
1630 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
1633 if ($dao->isValidOption($options)) {
1634 $dao->setOptions($options);
1637 $result = $dao->query($queryStr, $i18nRewrite);
1639 // since it is unbuffered, ($dao->N==0) is true. This blocks the standard fetch() mechanism.
1640 if (CRM_Utils_Array
::value('result_buffering', $options) === 0) {
1644 if (is_a($result, 'DB_Error')) {
1645 CRM_Core_Error
::deprecatedFunctionWarning('calling functions should handle exceptions');
1653 * Wrapper to validate internal DAO options before passing to DB_mysql/DB_Common level
1655 * @param array $options
1658 * Provided options are valid
1660 public function isValidOption($options) {
1669 if (empty($options)) {
1673 foreach (array_keys($options) as $option) {
1674 if (!in_array($option, $validOptions)) {
1684 * Execute a query and get the single result.
1686 * @param string $query
1687 * Query to be executed.
1688 * @param array $params
1689 * @param bool $abort
1690 * @param bool $i18nRewrite
1691 * @return string|null
1692 * the result of the query if any
1695 public static function &singleValueQuery(
1701 $queryStr = self
::composeQuery($query, $params, $abort);
1703 static $_dao = NULL;
1706 $_dao = new CRM_Core_DAO();
1709 $_dao->query($queryStr, $i18nRewrite);
1711 $result = $_dao->getDatabaseResult();
1714 $row = $result->fetchRow();
1724 * Compose the query by merging the parameters into it.
1726 * @param string $query
1727 * @param array $params
1728 * @param bool $abort
1731 * @throws CRM_Core_Exception
1733 public static function composeQuery($query, $params = [], $abort = TRUE) {
1735 foreach ($params as $key => $item) {
1736 if (is_numeric($key)) {
1737 if (CRM_Utils_Type
::validate($item[0], $item[1]) !== NULL) {
1738 $item[0] = self
::escapeString($item[0]);
1739 if ($item[1] == 'String' ||
1740 $item[1] == 'Memo' ||
1743 // Support class constants stipulating wildcard characters and/or
1744 // non-quoting of strings. Also support legacy code which may be
1745 // passing in TRUE or 1 for $item[2], which used to indicate the
1746 // use of wildcard characters.
1747 if (!empty($item[2])) {
1748 if ($item[2] & CRM_Core_DAO
::QUERY_FORMAT_WILDCARD ||
$item[2] === TRUE) {
1749 $item[0] = "'%{$item[0]}%'";
1751 elseif (!($item[2] & CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
)) {
1752 $item[0] = "'{$item[0]}'";
1756 $item[0] = "'{$item[0]}'";
1760 if (($item[1] == 'Date' ||
$item[1] == 'Timestamp') &&
1761 strlen($item[0]) == 0
1766 $tr['%' . $key] = $item[0];
1769 throw new CRM_Core_Exception("{$item[0]} is not of type {$item[1]}");
1774 return strtr($query, $tr);
1780 public static function freeResult($ids = NULL) {
1781 global $_DB_DATAOBJECT;
1784 if (!$_DB_DATAOBJECT ||
1785 !isset($_DB_DATAOBJECT['RESULTS'])
1789 $ids = array_keys($_DB_DATAOBJECT['RESULTS']);
1792 foreach ($ids as $id) {
1793 if (isset($_DB_DATAOBJECT['RESULTS'][$id])) {
1794 $_DB_DATAOBJECT['RESULTS'][$id]->free();
1795 unset($_DB_DATAOBJECT['RESULTS'][$id]);
1798 if (isset($_DB_DATAOBJECT['RESULTFIELDS'][$id])) {
1799 unset($_DB_DATAOBJECT['RESULTFIELDS'][$id]);
1805 * Make a shallow copy of an object and all the fields in the object.
1807 * @param string $daoName
1809 * @param array $criteria
1810 * Array of all the fields & values.
1811 * on which basis to copy
1812 * @param array $newData
1813 * Array of all the fields & values.
1814 * to be copied besides the other fields
1815 * @param string $fieldsFix
1816 * Array of fields that you want to prefix/suffix/replace.
1817 * @param string $blockCopyOfDependencies
1818 * Fields that you want to block from.
1820 * @param bool $blockCopyofCustomValues
1821 * Case when you don't want to copy the custom values set in a
1822 * template as it will override/ignore the submitted custom values
1824 * @return CRM_Core_DAO|bool
1825 * the newly created copy of the object. False if none created.
1827 public static function copyGeneric($daoName, $criteria, $newData = NULL, $fieldsFix = NULL, $blockCopyOfDependencies = NULL, $blockCopyofCustomValues = FALSE) {
1828 $object = new $daoName();
1831 $object->id
= $criteria['id'];
1834 foreach ($criteria as $key => $value) {
1835 $object->$key = $value;
1840 while ($object->fetch()) {
1842 // all the objects except with $blockCopyOfDependencies set
1843 // be copied - addresses #CRM-1962
1845 if ($blockCopyOfDependencies && $object->$blockCopyOfDependencies) {
1849 $newObject = new $daoName();
1851 $fields = $object->fields();
1852 $fieldsToPrefix = [];
1853 $fieldsToSuffix = [];
1854 $fieldsToReplace = [];
1855 if (!empty($fieldsFix['prefix'])) {
1856 $fieldsToPrefix = $fieldsFix['prefix'];
1858 if (!empty($fieldsFix['suffix'])) {
1859 $fieldsToSuffix = $fieldsFix['suffix'];
1861 if (!empty($fieldsFix['replace'])) {
1862 $fieldsToReplace = $fieldsFix['replace'];
1865 $localizableFields = FALSE;
1866 foreach ($fields as $name => $value) {
1867 if ($name == 'id' ||
$value['name'] == 'id') {
1868 // copy everything but the id!
1872 $dbName = $value['name'];
1873 $type = CRM_Utils_Type
::typeToString($value['type']);
1874 $newObject->$dbName = $object->$dbName;
1875 if (isset($fieldsToPrefix[$dbName])) {
1876 $newObject->$dbName = $fieldsToPrefix[$dbName] . $newObject->$dbName;
1878 if (isset($fieldsToSuffix[$dbName])) {
1879 $newObject->$dbName .= $fieldsToSuffix[$dbName];
1881 if (isset($fieldsToReplace[$dbName])) {
1882 $newObject->$dbName = $fieldsToReplace[$dbName];
1885 if ($type == 'Timestamp' ||
$type == 'Date') {
1886 $newObject->$dbName = CRM_Utils_Date
::isoToMysql($newObject->$dbName);
1889 if (!empty($value['localizable'])) {
1890 $localizableFields = TRUE;
1894 $newObject->copyValues($newData);
1899 // ensure we copy all localized fields as well
1900 if (CRM_Core_I18n
::isMultilingual() && $localizableFields) {
1902 $locales = CRM_Core_I18n
::getMultilingual();
1903 $curLocale = CRM_Core_I18n
::getLocale();
1904 // loop on other locales
1905 foreach ($locales as $locale) {
1906 if ($locale != $curLocale) {
1907 // setLocale doesn't seems to be reliable to set dbLocale and we only need to change the db locale
1908 $dbLocale = '_' . $locale;
1909 $newObject->copyLocalizable($object->id
, $newObject->id
, $fieldsToPrefix, $fieldsToSuffix, $fieldsToReplace);
1912 // restore dbLocale to starting value
1913 $dbLocale = '_' . $curLocale;
1916 if (!$blockCopyofCustomValues) {
1917 $newObject->copyCustomFields($object->id
, $newObject->id
);
1919 CRM_Utils_Hook
::post('create', CRM_Core_DAO_AllCoreTables
::getBriefName($daoName), $newObject->id
, $newObject);
1926 * Method that copies localizable fields from an old entity to a new one.
1928 * Fixes bug dev/core#2479,
1929 * where non current locale fields are copied from current locale losing translation when copying
1931 * @param int $entityID
1932 * @param int $newEntityID
1933 * @param array $fieldsToPrefix
1934 * @param array $fieldsToSuffix
1935 * @param array $fieldsToReplace
1937 protected function copyLocalizable($entityID, $newEntityID, $fieldsToPrefix, $fieldsToSuffix, $fieldsToReplace) {
1938 $entity = get_class($this);
1939 $object = new $entity();
1940 $object->id
= $entityID;
1943 $newObject = new $entity();
1944 $newObject->id
= $newEntityID;
1948 if ($object->fetch() && $newObject->fetch()) {
1950 $fields = $object->fields();
1951 foreach ($fields as $name => $value) {
1953 if ($name == 'id' ||
$value['name'] == 'id') {
1954 // copy everything but the id!
1958 // only copy localizable fields
1959 if (!$value['localizable']) {
1963 $dbName = $value['name'];
1964 $type = CRM_Utils_Type
::typeToString($value['type']);
1965 $newObject->$dbName = $object->$dbName;
1966 if (isset($fieldsToPrefix[$dbName])) {
1967 $newObject->$dbName = $fieldsToPrefix[$dbName] . $newObject->$dbName;
1969 if (isset($fieldsToSuffix[$dbName])) {
1970 $newObject->$dbName .= $fieldsToSuffix[$dbName];
1972 if (isset($fieldsToReplace[$dbName])) {
1973 $newObject->$dbName = $fieldsToReplace[$dbName];
1976 if ($type == 'Timestamp' ||
$type == 'Date') {
1977 $newObject->$dbName = CRM_Utils_Date
::isoToMysql($newObject->$dbName);
1987 * Method that copies custom fields values from an old entity to a new one.
1989 * Fixes bug CRM-19302,
1990 * where if a custom field of File type was present, left both events using the same file,
1991 * breaking download URL's for the old event.
1993 * @todo the goal here is to clean this up so that it works for any entity. Copy Generic already DOES some custom field stuff
1994 * but it seems to be bypassed & perhaps less good than this (or this just duplicates it...)
1996 * @param int $entityID
1997 * @param int $newEntityID
1998 * @param string $parentOperation
2000 public function copyCustomFields($entityID, $newEntityID, $parentOperation = NULL) {
2001 $entity = CRM_Core_DAO_AllCoreTables
::getBriefName(get_class($this));
2002 $tableName = CRM_Core_DAO_AllCoreTables
::getTableForClass(get_class($this));
2003 // Obtain custom values for the old entity.
2004 $customParams = $htmlType = [];
2005 $customValues = CRM_Core_BAO_CustomValueTable
::getEntityValues($entityID, $entity);
2007 // If custom values present, we copy them
2008 if (!empty($customValues)) {
2009 // Get Field ID's and identify File type attributes, to handle file copying.
2010 $fieldIds = implode(', ', array_keys($customValues));
2011 $sql = "SELECT id FROM civicrm_custom_field WHERE html_type = 'File' AND id IN ( {$fieldIds} )";
2012 $result = CRM_Core_DAO
::executeQuery($sql);
2014 // Build array of File type fields
2015 while ($result->fetch()) {
2016 $htmlType[] = $result->id
;
2019 // Build params array of custom values
2020 foreach ($customValues as $field => $value) {
2021 if ($value !== NULL) {
2022 // Handle File type attributes
2023 if (in_array($field, $htmlType)) {
2024 $fileValues = CRM_Core_BAO_File
::path($value, $entityID);
2025 $customParams["custom_{$field}_-1"] = [
2026 'name' => CRM_Utils_File
::duplicate($fileValues[0]),
2027 'type' => $fileValues[1],
2030 // Handle other types
2032 $customParams["custom_{$field}_-1"] = $value;
2037 // Save Custom Fields for new Entity.
2038 CRM_Core_BAO_CustomValueTable
::postProcess($customParams, $tableName, $newEntityID, $entity, $parentOperation ??
'create');
2041 // copy activity attachments ( if any )
2042 CRM_Core_BAO_File
::copyEntityFile($tableName, $entityID, $tableName, $newEntityID);
2046 * Cascade update through related entities.
2048 * @param string $daoName
2051 * @param array $newData
2053 * @return CRM_Core_DAO|null
2055 public static function cascadeUpdate($daoName, $fromId, $toId, $newData = []) {
2056 $object = new $daoName();
2057 $object->id
= $fromId;
2059 if ($object->find(TRUE)) {
2060 $newObject = new $daoName();
2061 $newObject->id
= $toId;
2063 if ($newObject->find(TRUE)) {
2064 $fields = $object->fields();
2065 foreach ($fields as $name => $value) {
2066 if ($name == 'id' ||
$value['name'] == 'id') {
2067 // copy everything but the id!
2071 $colName = $value['name'];
2072 $newObject->$colName = $object->$colName;
2074 if (substr($name, -5) == '_date' ||
2075 substr($name, -10) == '_date_time'
2077 $newObject->$colName = CRM_Utils_Date
::isoToMysql($newObject->$colName);
2080 foreach ($newData as $k => $v) {
2081 $newObject->$k = $v;
2091 * Given the component id, compute the contact id
2092 * since its used for things like send email
2094 * @param $componentIDs
2095 * @param string $tableName
2096 * @param string $idField
2100 public static function getContactIDsFromComponent($componentIDs, $tableName, $idField = 'id') {
2103 if (empty($componentIDs)) {
2107 $IDs = implode(',', $componentIDs);
2111 WHERE $idField IN ( $IDs )
2114 $dao = CRM_Core_DAO
::executeQuery($query);
2115 while ($dao->fetch()) {
2116 $contactIDs[] = $dao->contact_id
;
2122 * Fetch object based on array of properties.
2124 * @param string $daoName
2125 * Name of the dao object.
2126 * @param string $fieldIdName
2127 * @param int $fieldId
2129 * @param array $returnProperities
2130 * An assoc array of fields that need to be returned, eg array( 'first_name', 'last_name').
2133 * an object of type referenced by daoName
2135 public static function commonRetrieveAll($daoName, $fieldIdName, $fieldId, &$details, $returnProperities = NULL) {
2136 $object = new $daoName();
2137 $object->$fieldIdName = $fieldId;
2139 // return only specific fields if returnproperties are sent
2140 if (!empty($returnProperities)) {
2141 $object->selectAdd();
2142 $object->selectAdd('id');
2143 $object->selectAdd(implode(',', $returnProperities));
2147 while ($object->fetch()) {
2149 self
::storeValues($object, $defaults);
2150 $details[$object->id
] = $defaults;
2157 * Drop all CiviCRM tables.
2159 * @throws \CRM_Core_Exception
2161 public static function dropAllTables() {
2163 // first drop all the custom tables we've created
2164 CRM_Core_BAO_CustomGroup
::dropAllTables();
2166 // drop all multilingual views
2167 CRM_Core_I18n_Schema
::dropAllViews();
2169 CRM_Utils_File
::sourceSQLFile(CIVICRM_DSN
,
2170 dirname(__FILE__
) . DIRECTORY_SEPARATOR
.
2171 '..' . DIRECTORY_SEPARATOR
.
2172 '..' . DIRECTORY_SEPARATOR
.
2173 'sql' . DIRECTORY_SEPARATOR
.
2174 'civicrm_drop.mysql'
2183 public static function escapeString($string) {
2184 static $_dao = NULL;
2186 // If this is an atypical case (e.g. preparing .sql file before CiviCRM
2187 // has been installed), then we fallback DB-less str_replace escaping, as
2188 // we can't use mysqli_real_escape_string, as there is no DB connection.
2189 // Note: In typical usage, escapeString() will only check one conditional
2190 // ("if !$_dao") rather than two conditionals ("if !defined(DSN)")
2191 if (!defined('CIVICRM_DSN')) {
2192 // See http://php.net/manual/en/mysqli.real-escape-string.php for the
2193 // list of characters mysqli_real_escape_string escapes.
2194 $search = ["\\", "\x00", "\n", "\r", "'", '"', "\x1a"];
2195 $replace = ["\\\\", "\\0", "\\n", "\\r", "\'", '\"', "\\Z"];
2196 return str_replace($search, $replace, $string);
2198 $_dao = new CRM_Core_DAO();
2200 return $_dao->escape($string);
2204 * Escape a list of strings for use with "WHERE X IN (...)" queries.
2206 * @param array $strings
2207 * @param string $default
2208 * the value to use if $strings has no elements.
2210 * eg "abc","def","ghi"
2212 public static function escapeStrings($strings, $default = NULL) {
2213 static $_dao = NULL;
2215 $_dao = new CRM_Core_DAO();
2218 if (empty($strings)) {
2222 $escapes = array_map([$_dao, 'escape'], $strings);
2223 return '"' . implode('","', $escapes) . '"';
2231 public static function escapeWildCardString($string) {
2233 // ensure we escape the single characters % and _ which are mysql wild
2234 // card characters and could come in via sortByCharacter
2235 // note that mysql does not escape these characters
2236 if ($string && in_array($string,
2237 ['%', '_', '%%', '_%']
2240 return '\\' . $string;
2243 return self
::escapeString($string);
2247 * Creates a test object, including any required objects it needs via recursion
2248 * createOnly: only create in database, do not store or return the objects (useful for perf testing)
2249 * ONLY USE FOR TESTING
2251 * @param string $daoName
2252 * @param array $params
2253 * @param int $numObjects
2254 * @param bool $createOnly
2256 * @return object|array|NULL
2257 * NULL if $createOnly. A single object if $numObjects==1. Otherwise, an array of multiple objects.
2259 public static function createTestObject(
2265 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
2266 // so we re-set here in case
2267 $config = CRM_Core_Config
::singleton();
2268 $config->backtrace
= TRUE;
2270 static $counter = 0;
2271 CRM_Core_DAO
::$_testEntitiesToSkip = [
2272 'CRM_Core_DAO_Worldregion',
2273 'CRM_Core_DAO_StateProvince',
2274 'CRM_Core_DAO_Country',
2275 'CRM_Core_DAO_Domain',
2276 'CRM_Financial_DAO_FinancialType',
2277 //because valid ones exist & we use pick them due to pseudoconstant can't reliably create & delete these
2280 // Prefer to instantiate BAO's instead of DAO's (when possible)
2281 // so that assignTestValue()/assignTestFK() can be overloaded.
2282 $baoName = str_replace('_DAO_', '_BAO_', $daoName);
2283 if ($baoName === 'CRM_Financial_BAO_FinancialTrxn') {
2284 // OMG OMG OMG this is so incredibly bad. The BAO is insanely named.
2285 // @todo create a new class called what the BAO SHOULD be
2286 // that extends BAO-crazy-name.... migrate.
2287 $baoName = 'CRM_Core_BAO_FinancialTrxn';
2289 if (class_exists($baoName)) {
2290 $daoName = $baoName;
2293 for ($i = 0; $i < $numObjects; ++
$i) {
2296 /** @var CRM_Core_DAO $object */
2297 $object = new $daoName();
2299 $fields = $object->fields();
2300 foreach ($fields as $fieldName => $fieldDef) {
2301 $dbName = $fieldDef['name'];
2302 $FKClassName = $fieldDef['FKClassName'] ??
NULL;
2304 if (isset($params[$dbName]) && !is_array($params[$dbName])) {
2305 $object->$dbName = $params[$dbName];
2308 elseif ($dbName != 'id') {
2309 if ($FKClassName != NULL) {
2310 $object->assignTestFK($fieldName, $fieldDef, $params);
2314 $object->assignTestValue($fieldName, $fieldDef, $counter);
2322 $objects[$i] = $object;
2332 elseif ($numObjects == 1) {
2341 * Deletes the this object plus any dependent objects that are associated with it.
2342 * ONLY USE FOR TESTING
2344 * @param string $daoName
2345 * @param array $params
2347 public static function deleteTestObjects($daoName, $params = []) {
2348 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
2349 // so we re-set here in case
2350 $config = CRM_Core_Config
::singleton();
2351 $config->backtrace
= TRUE;
2353 $object = new $daoName();
2354 $object->id
= $params['id'] ??
NULL;
2356 // array(array(0 => $daoName, 1 => $daoParams))
2358 if ($object->find(TRUE)) {
2360 $fields = $object->fields();
2361 foreach ($fields as $name => $value) {
2363 $dbName = $value['name'];
2365 $FKClassName = $value['FKClassName'] ??
NULL;
2366 $required = $value['required'] ??
NULL;
2367 if ($FKClassName != NULL
2369 && !in_array($FKClassName, CRM_Core_DAO
::$_testEntitiesToSkip)
2370 && ($required ||
$dbName == 'contact_id')
2371 //I'm a bit stuck on this one - we might need to change the singleValueAlter so that the entities don't share a contact
2372 // to make this test process pass - line below makes pass for now
2373 && $dbName != 'member_of_contact_id'
2376 $deletions[] = [$FKClassName, ['id' => $object->$dbName]];
2383 foreach ($deletions as $deletion) {
2384 CRM_Core_DAO
::deleteTestObjects($deletion[0], $deletion[1]);
2389 * Set defaults when creating new entity.
2390 * (don't call this set defaults as already in use with different signature in some places)
2392 * @param array $params
2395 public static function setCreateDefaults(&$params, $defaults) {
2396 if (!empty($params['id'])) {
2399 foreach ($defaults as $key => $value) {
2400 if (!array_key_exists($key, $params) ||
$params[$key] === NULL) {
2401 $params[$key] = $value;
2407 * @param string $prefix
2408 * @param bool $addRandomString
2409 * @param null $string
2413 * @see CRM_Utils_SQL_TempTable
2415 public static function createTempTableName($prefix = 'civicrm', $addRandomString = TRUE, $string = NULL) {
2416 CRM_Core_Error
::deprecatedFunctionWarning('Use CRM_Utils_SQL_TempTable interface to create temporary tables');
2417 $tableName = $prefix . "_temp";
2419 if ($addRandomString) {
2421 $tableName .= "_" . $string;
2424 $tableName .= "_" . md5(uniqid('', TRUE));
2432 * @param bool $trigger
2436 public static function checkTriggerViewPermission($view = TRUE, $trigger = TRUE) {
2437 if (\Civi
::settings()->get('logging_no_trigger_permission')) {
2440 // test for create view and trigger permissions and if allowed, add the option to go multilingual and logging
2441 $dao = new CRM_Core_DAO();
2444 $dao->query('CREATE OR REPLACE VIEW civicrm_domain_view AS SELECT * FROM civicrm_domain');
2445 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
2449 $dao->query('CREATE TRIGGER civicrm_domain_trigger BEFORE INSERT ON civicrm_domain FOR EACH ROW BEGIN END');
2450 $dao->query('DROP TRIGGER IF EXISTS civicrm_domain_trigger');
2453 catch (Exception
$e) {
2461 * @param null $message
2462 * @param bool $printDAO
2464 public static function debugPrint($message = NULL, $printDAO = TRUE) {
2465 CRM_Utils_System
::xMemory("{$message}: ");
2468 global $_DB_DATAOBJECT;
2470 foreach (array_keys($_DB_DATAOBJECT['RESULTS']) as $id) {
2471 $q[] = $_DB_DATAOBJECT['RESULTS'][$id]->query
;
2473 CRM_Core_Error
::debug('_DB_DATAOBJECT', $q);
2478 * Build a list of triggers via hook and add them to (err, reconcile them
2479 * with) the database.
2481 * @param string $tableName
2482 * the specific table requiring a rebuild; or NULL to rebuild all tables.
2483 * @param bool $force
2488 public static function triggerRebuild($tableName = NULL, $force = FALSE) {
2489 Civi
::service('sql_triggers')->rebuild($tableName, $force);
2493 * Wrapper function to drop triggers.
2495 * @param string $tableName
2496 * the specific table requiring a rebuild; or NULL to rebuild all tables.
2499 public static function dropTriggers($tableName = NULL) {
2500 Civi
::service('sql_triggers')->dropTriggers($tableName);
2504 * @param array $info
2505 * per hook_civicrm_triggerInfo.
2506 * @param string $onlyTableName
2507 * the specific table requiring a rebuild; or NULL to rebuild all tables.
2510 public static function createTriggers(&$info, $onlyTableName = NULL) {
2511 Civi
::service('sql_triggers')->createTriggers($info, $onlyTableName);
2515 * Given a list of fields, create a list of references.
2517 * @param string $className
2518 * BAO/DAO class name.
2519 * @return array<CRM_Core_Reference_Interface>
2521 public static function createReferenceColumns($className) {
2523 $fields = $className::fields();
2524 foreach ($fields as $field) {
2525 if (isset($field['pseudoconstant'], $field['pseudoconstant']['optionGroupName'])) {
2526 $result[] = new CRM_Core_Reference_OptionValue(
2527 $className::getTableName(),
2529 'civicrm_option_value',
2530 CRM_Utils_Array
::value('keyColumn', $field['pseudoconstant'], 'value'),
2531 $field['pseudoconstant']['optionGroupName']
2539 * Find all records which refer to this entity.
2541 * @return CRM_Core_DAO[]
2543 public function findReferences() {
2544 $links = self
::getReferencesToTable(static::getTableName());
2547 foreach ($links as $refSpec) {
2548 /** @var $refSpec CRM_Core_Reference_Interface */
2549 $daoName = CRM_Core_DAO_AllCoreTables
::getClassForTable($refSpec->getReferenceTable());
2550 $result = $refSpec->findReferences($this);
2552 while ($result->fetch()) {
2553 $obj = new $daoName();
2554 $obj->id
= $result->id
;
2555 $occurrences[] = $obj;
2560 return $occurrences;
2564 * @return array{name: string, type: string, count: int, table: string|null, key: string|null}[]
2565 * each item has keys:
2569 * - table: string|null SQL table name
2570 * - key: string|null SQL column name
2572 public function getReferenceCounts() {
2573 $links = self
::getReferencesToTable(static::getTableName());
2576 foreach ($links as $refSpec) {
2577 /** @var $refSpec CRM_Core_Reference_Interface */
2578 $count = $refSpec->getReferenceCount($this);
2579 if (!empty($count['count'])) {
2584 foreach (CRM_Core_Component
::getEnabledComponents() as $component) {
2585 /** @var $component CRM_Core_Component_Info */
2586 $counts = array_merge($counts, $component->getReferenceCounts($this));
2588 CRM_Utils_Hook
::referenceCounts($this, $counts);
2594 * List all tables which have hard foreign keys to this table.
2596 * For now, this returns a description of every entity_id/entity_table
2598 * TODO: filter dynamic entity references on the $tableName, based on
2599 * schema metadata in dynamicForeignKey which enumerates a restricted
2600 * set of possible entity_table's.
2602 * @param string $tableName
2603 * Table referred to.
2605 * @return CRM_Core_Reference_Interface[]
2606 * structure of table and column, listing every table with a
2607 * foreign key reference to $tableName, and the column where the key appears.
2609 public static function getReferencesToTable($tableName) {
2611 foreach (CRM_Core_DAO_AllCoreTables
::getClasses() as $daoClassName) {
2612 $links = $daoClassName::getReferenceColumns();
2614 foreach ($links as $refSpec) {
2615 /** @var $refSpec CRM_Core_Reference_Interface */
2616 if ($refSpec->matchesTargetTable($tableName)) {
2617 $refsFound[] = $refSpec;
2625 * Get all references to contact table.
2627 * This includes core tables, custom group tables, tables added by the merge
2628 * hook and the entity_tag table.
2630 * Refer to CRM-17454 for information on the danger of querying the information
2631 * schema to derive this.
2633 * @throws \CiviCRM_API3_Exception
2635 public static function getReferencesToContactTable() {
2636 if (isset(\Civi
::$statics[__CLASS__
]) && isset(\Civi
::$statics[__CLASS__
]['contact_references'])) {
2637 return \Civi
::$statics[__CLASS__
]['contact_references'];
2639 $contactReferences = [];
2640 $coreReferences = CRM_Core_DAO
::getReferencesToTable('civicrm_contact');
2641 foreach ($coreReferences as $coreReference) {
2643 // Exclude option values
2644 !is_a($coreReference, 'CRM_Core_Reference_Dynamic') &&
2645 // Exclude references to other columns
2646 $coreReference->getTargetKey() === 'id'
2648 $contactReferences[$coreReference->getReferenceTable()][] = $coreReference->getReferenceKey();
2651 self
::appendCustomTablesExtendingContacts($contactReferences);
2652 self
::appendCustomContactReferenceFields($contactReferences);
2653 \Civi
::$statics[__CLASS__
]['contact_references'] = $contactReferences;
2654 return \Civi
::$statics[__CLASS__
]['contact_references'];
2658 * Get all dynamic references to the given table.
2660 * @param string $tableName
2664 public static function getDynamicReferencesToTable($tableName) {
2665 if (!isset(\Civi
::$statics[__CLASS__
]['contact_references_dynamic'][$tableName])) {
2666 \Civi
::$statics[__CLASS__
]['contact_references_dynamic'][$tableName] = [];
2667 $coreReferences = CRM_Core_DAO
::getReferencesToTable($tableName);
2668 foreach ($coreReferences as $coreReference) {
2669 if ($coreReference instanceof \CRM_Core_Reference_Dynamic
) {
2670 \Civi
::$statics[__CLASS__
]['contact_references_dynamic'][$tableName][$coreReference->getReferenceTable()][] = [$coreReference->getReferenceKey(), $coreReference->getTypeColumn()];
2674 return \Civi
::$statics[__CLASS__
]['contact_references_dynamic'][$tableName];
2678 * Add custom tables that extend contacts to the list of contact references.
2680 * CRM_Core_BAO_CustomGroup::getAllCustomGroupsByBaseEntity seems like a safe-ish
2681 * function to be sure all are retrieved & we don't miss subtypes or inactive or multiples
2682 * - the down side is it is not cached.
2684 * Further changes should be include tests in the CRM_Core_MergerTest class
2685 * to ensure that disabled, subtype, multiple etc groups are still captured.
2687 * @param array $cidRefs
2689 public static function appendCustomTablesExtendingContacts(&$cidRefs) {
2690 $customValueTables = CRM_Core_BAO_CustomGroup
::getAllCustomGroupsByBaseEntity('Contact');
2691 $customValueTables->find();
2692 while ($customValueTables->fetch()) {
2693 $cidRefs[$customValueTables->table_name
][] = 'entity_id';
2698 * Add custom ContactReference fields to the list of contact references
2700 * This includes active and inactive fields/groups
2702 * @param array $cidRefs
2704 * @throws \CiviCRM_API3_Exception
2706 public static function appendCustomContactReferenceFields(&$cidRefs) {
2707 $fields = civicrm_api3('CustomField', 'get', [
2708 'return' => ['column_name', 'custom_group_id.table_name'],
2709 'data_type' => 'ContactReference',
2710 'options' => ['limit' => 0],
2712 foreach ($fields as $field) {
2713 $cidRefs[$field['custom_group_id.table_name']][] = $field['column_name'];
2718 * Lookup the value of a MySQL global configuration variable.
2720 * @param string $name
2721 * E.g. "thread_stack".
2722 * @param mixed $default
2725 public static function getGlobalSetting($name, $default = NULL) {
2726 // Alternatively, SELECT @@GLOBAL.thread_stack, but
2727 // that has been reported to fail under MySQL 5.0 for OS X
2728 $escapedName = self
::escapeString($name);
2729 $dao = CRM_Core_DAO
::executeQuery("SHOW VARIABLES LIKE '$escapedName'");
2730 if ($dao->fetch()) {
2739 * Update the fields array to also hold keys for pseudoconstant fields that relate to contained fields.
2741 * This is relevant where we want to offer both the ID field and the label field
2742 * as an option, e.g. search builder.
2744 * It is currently limited for optionGroupName & id+ name+ FK combos for purposes keeping the scope of the
2745 * change small, but is appropriate for other sorts of pseudoconstants.
2747 * @param array $fields
2749 public static function appendPseudoConstantsToFields(&$fields) {
2750 foreach ($fields as $fieldUniqueName => $field) {
2751 if (!empty($field['pseudoconstant'])) {
2752 $pseudoConstant = $field['pseudoconstant'];
2753 if (!empty($pseudoConstant['optionGroupName'])) {
2754 $fields[$pseudoConstant['optionGroupName']] = [
2755 'title' => CRM_Core_BAO_OptionGroup
::getTitleByName($pseudoConstant['optionGroupName']),
2756 'name' => $pseudoConstant['optionGroupName'],
2757 'data_type' => CRM_Utils_Type
::T_STRING
,
2758 'is_pseudofield_for' => $fieldUniqueName,
2761 // We restrict to id + name + FK as we are extending this a bit, but cautiously.
2763 !empty($field['FKClassName'])
2764 && CRM_Utils_Array
::value('keyColumn', $pseudoConstant) === 'id'
2765 && CRM_Utils_Array
::value('labelColumn', $pseudoConstant) === 'name'
2767 $pseudoFieldName = str_replace('_' . $pseudoConstant['keyColumn'], '', $field['name']);
2768 // This if is just an extra caution when adding change.
2769 if (!isset($fields[$pseudoFieldName])) {
2770 $daoName = $field['FKClassName'];
2771 $fkFields = $daoName::fields();
2772 foreach ($fkFields as $fkField) {
2773 if ($fkField['name'] === $pseudoConstant['labelColumn']) {
2774 $fields[$pseudoFieldName] = [
2775 'name' => $pseudoFieldName,
2776 'is_pseudofield_for' => $field['name'],
2777 'title' => $fkField['title'],
2778 'data_type' => $fkField['type'],
2779 'where' => $field['where'],
2790 * Get options for the called BAO object's field.
2792 * This function can be overridden by each BAO to add more logic related to context.
2793 * The overriding function will generally call the lower-level CRM_Core_PseudoConstant::get
2795 * @param string $fieldName
2796 * @param string $context
2797 * @see CRM_Core_DAO::buildOptionsContext
2798 * @param array $props
2799 * Raw field values; whatever is known about this bao object.
2801 * Note: $props can contain unsanitized input and should not be passed directly to CRM_Core_PseudoConstant::get
2803 * @return array|bool
2805 public static function buildOptions($fieldName, $context = NULL, $props = []) {
2806 // If a given bao does not override this function
2807 $baoName = get_called_class();
2808 return CRM_Core_PseudoConstant
::get($baoName, $fieldName, [], $context);
2812 * Populate option labels for this object's fields.
2814 * @throws exception if called directly on the base class
2816 public function getOptionLabels() {
2817 $fields = $this->fields();
2818 if ($fields === NULL) {
2819 throw new Exception('Cannot call getOptionLabels on CRM_Core_DAO');
2821 foreach ($fields as $field) {
2822 $name = $field['name'] ??
NULL;
2823 if ($name && isset($this->$name)) {
2824 $label = CRM_Core_PseudoConstant
::getLabel(get_class($this), $name, $this->$name);
2825 if ($label !== FALSE) {
2826 // Append 'label' onto the field name
2827 $labelName = $name . '_label';
2828 $this->$labelName = $label;
2835 * Provides documentation and validation for the buildOptions $context param
2837 * @param string $context
2839 * @throws CRM_Core_Exception
2842 public static function buildOptionsContext($context = NULL) {
2844 'get' => "get: all options are returned, even if they are disabled; labels are translated.",
2845 'create' => "create: options are filtered appropriately for the object being created/updated; labels are translated.",
2846 'search' => "search: searchable options are returned; labels are translated.",
2847 'validate' => "validate: all options are returned, even if they are disabled; machine names are used in place of labels.",
2848 'abbreviate' => "abbreviate: enabled options are returned; labels are replaced with abbreviations.",
2849 'match' => "match: enabled options are returned using machine names as keys; labels are translated.",
2851 // Validation: enforce uniformity of this param
2852 if ($context !== NULL && !isset($contexts[$context])) {
2853 throw new CRM_Core_Exception("'$context' is not a valid context for buildOptions.");
2859 * @param string $fieldName
2860 * @return bool|array
2862 public function getFieldSpec($fieldName) {
2863 $fields = $this->fields();
2865 // Support "unique names" as well as sql names
2866 $fieldKey = $fieldName;
2867 if (empty($fields[$fieldKey])) {
2868 $fieldKeys = $this->fieldKeys();
2869 $fieldKey = $fieldKeys[$fieldName] ??
NULL;
2871 // If neither worked then this field doesn't exist. Return false.
2872 if (empty($fields[$fieldKey])) {
2875 return $fields[$fieldKey];
2879 * Get SQL where clause for SQL filter syntax input parameters.
2881 * SQL version of api function to assign filters to the DAO based on the syntax
2882 * $field => array('IN' => array(4,6,9))
2884 * $field => array('LIKE' => array('%me%))
2887 * @param string $fieldName
2889 * @param array $filter
2890 * filter to be applied indexed by operator.
2891 * @param string $type
2892 * type of field (not actually used - nor in api @todo ).
2893 * @param string $alias
2894 * alternative field name ('as') @todo- not actually used.
2895 * @param bool $returnSanitisedArray
2896 * Return a sanitised array instead of a clause.
2897 * this is primarily so we can add filters @ the api level to the Query object based fields
2901 * @return NULL|string|array
2902 * a string is returned if $returnSanitisedArray is not set, otherwise and Array or NULL
2903 * depending on whether it is supported as yet
2905 public static function createSQLFilter($fieldName, $filter, $type = NULL, $alias = NULL, $returnSanitisedArray = FALSE) {
2906 foreach ($filter as $operator => $criteria) {
2907 $emojiFilter = CRM_Utils_SQL
::handleEmojiInQuery($criteria);
2908 if ($emojiFilter === '0 = 1') {
2909 return $emojiFilter;
2912 if (in_array($operator, self
::acceptedSQLOperators(), TRUE)) {
2913 switch ($operator) {
2917 if (!$returnSanitisedArray) {
2918 return (sprintf('%s %s', $fieldName, $operator));
2921 return (sprintf('%s %s ', $fieldName, $operator));
2925 // ternary operators
2928 if ((empty($criteria[0]) && !in_array($criteria[0], ['0', 0]))||
(empty($criteria[1]) && !in_array($criteria[1], ['0', 0]))) {
2929 throw new Exception("invalid criteria for $operator");
2931 if (!$returnSanitisedArray) {
2932 return (sprintf('%s ' . $operator . ' "%s" AND "%s"', $fieldName, CRM_Core_DAO
::escapeString($criteria[0]), CRM_Core_DAO
::escapeString($criteria[1])));
2935 // not yet implemented (tests required to implement)
2943 if (empty($criteria)) {
2944 throw new Exception("invalid criteria for $operator");
2946 $escapedCriteria = array_map([
2950 if (!$returnSanitisedArray) {
2951 return (sprintf('%s %s ("%s")', $fieldName, $operator, implode('", "', $escapedCriteria)));
2953 return $escapedCriteria;
2958 if (!$returnSanitisedArray) {
2959 return (sprintf('%s %s "%s"', $fieldName, $operator, CRM_Core_DAO
::escapeString($criteria)));
2962 // not yet implemented (tests required to implement)
2971 * @see http://issues.civicrm.org/jira/browse/CRM-9150
2972 * support for other syntaxes is discussed in ticket but being put off for now
2975 public static function acceptedSQLOperators() {
2996 * SQL has a limit of 64 characters on various names:
2997 * table name, trigger name, column name ...
2999 * For custom groups and fields we generated names from user entered input
3000 * which can be longer than this length, this function helps with creating
3001 * strings that meet various criteria.
3003 * @param string $string
3004 * The string to be shortened.
3005 * @param int $length
3006 * The max length of the string.
3008 * @param bool $makeRandom
3012 public static function shortenSQLName($string, $length = 60, $makeRandom = FALSE) {
3013 // early return for strings that meet the requirements
3014 if (strlen($string) <= $length) {
3018 // easy return for calls that dont need a randomized uniq string
3020 return substr($string, 0, $length);
3023 // the string is longer than the length and we need a uniq string
3024 // for the same tablename we need the same uniq string every time
3025 // hence we use md5 on the string, which is not random
3026 // we'll append 8 characters to the end of the tableName
3027 $md5string = substr(md5($string), 0, 8);
3028 return substr($string, 0, $length - 8) . "_{$md5string}";
3032 * https://issues.civicrm.org/jira/browse/CRM-17748
3033 * Sets the internal options to be used on a query
3035 * @param array $options
3038 public function setOptions($options) {
3039 if (is_array($options)) {
3040 $this->_options
= $options;
3045 * https://issues.civicrm.org/jira/browse/CRM-17748
3046 * wrapper to pass internal DAO options down to DB_mysql/DB_Common level
3048 * @param array $options
3051 protected function _setDBOptions($options) {
3052 global $_DB_DATAOBJECT;
3054 if (is_array($options) && count($options)) {
3055 $conn = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5
];
3056 foreach ($options as $option_name => $option_value) {
3057 $conn->setOption($option_name, $option_value);
3064 * @param array $params
3066 public function setApiFilter(&$params) {
3070 * Generates acl clauses suitable for adding to WHERE or ON when doing an api.get for this entity
3072 * Return format is in the form of fieldname => clauses starting with an operator. e.g.:
3075 * 'location_type_id' => array('IS NOT NULL', 'IN (1,2,3)')
3079 * Note that all array keys must be actual field names in this entity. Use subqueries to filter on other tables e.g. custom values.
3083 public function addSelectWhereClause() {
3085 $fields = $this->fields();
3086 foreach ($fields as $fieldName => $field) {
3087 // Clause for contact-related entities like Email, Relationship, etc.
3088 if (strpos($field['name'], 'contact_id') === 0 && CRM_Utils_Array
::value('FKClassName', $field) == 'CRM_Contact_DAO_Contact') {
3089 $contactClause = CRM_Utils_SQL
::mergeSubquery('Contact');
3090 if (!empty($contactClause)) {
3091 $clauses[$field['name']] = $contactClause;
3094 // Clause for an entity_table/entity_id combo
3095 if ($field['name'] === 'entity_id' && isset($fields['entity_table'])) {
3096 $relatedClauses = [];
3097 $relatedEntities = $this->buildOptions('entity_table', 'get');
3098 foreach ((array) $relatedEntities as $table => $ent) {
3100 $ent = CRM_Core_DAO_AllCoreTables
::getEntityNameForTable($table);
3101 $subquery = CRM_Utils_SQL
::mergeSubquery($ent);
3103 $relatedClauses[] = "(entity_table = '$table' AND entity_id " . implode(' AND entity_id ', $subquery) . ")";
3106 $relatedClauses[] = "(entity_table = '$table')";
3110 if ($relatedClauses) {
3111 $clauses['id'] = 'IN (SELECT id FROM `' . $this->tableName() . '` WHERE (' . implode(') OR (', $relatedClauses) . '))';
3115 CRM_Utils_Hook
::selectWhereClause($this, $clauses);
3120 * This returns the final permissioned query string for this entity
3122 * With acls from related entities + additional clauses from hook_civicrm_selectWhereClause
3124 * @param string $tableAlias
3127 public static function getSelectWhereClause($tableAlias = NULL) {
3128 $bao = new static();
3129 if ($tableAlias === NULL) {
3130 $tableAlias = $bao->tableName();
3133 foreach ((array) $bao->addSelectWhereClause() as $field => $vals) {
3134 $clauses[$field] = NULL;
3136 $clauses[$field] = "(`$tableAlias`.`$field` IS NULL OR (`$tableAlias`.`$field` " . implode(" AND `$tableAlias`.`$field` ", (array) $vals) . '))';
3143 * ensure database name is 'safe', i.e. only contains word characters (includes underscores)
3144 * and dashes, and contains at least one [a-z] case insensitive.
3150 public static function requireSafeDBName($database) {
3153 "/^[\w\-]*[a-z]+[\w\-]*$/i",
3157 if (empty($matches)) {
3164 * Transform an array to a serialized string for database storage.
3166 * @param array|null $value
3167 * @param int $serializationType
3168 * @return string|null
3170 * @throws \Exception
3172 public static function serializeField($value, $serializationType) {
3173 if ($value === NULL) {
3176 switch ($serializationType) {
3177 case self
::SERIALIZE_SEPARATOR_BOOKEND
:
3178 return $value === [] ?
'' : CRM_Utils_Array
::implodePadded($value);
3180 case self
::SERIALIZE_SEPARATOR_TRIMMED
:
3181 return is_array($value) ?
implode(self
::VALUE_SEPARATOR
, $value) : $value;
3183 case self
::SERIALIZE_JSON
:
3184 return is_array($value) ?
json_encode($value) : $value;
3186 case self
::SERIALIZE_PHP
:
3187 return is_array($value) ?
serialize($value) : $value;
3189 case self
::SERIALIZE_COMMA
:
3190 return is_array($value) ?
implode(',', $value) : $value;
3193 throw new Exception('Unknown serialization method for field.');
3198 * Transform a serialized string from the database into an array.
3200 * @param string|null $value
3201 * @param $serializationType
3203 * @return array|null
3204 * @throws CRM_Core_Exception
3206 public static function unSerializeField($value, $serializationType) {
3207 if ($value === NULL) {
3210 if ($value === '') {
3213 switch ($serializationType) {
3214 case self
::SERIALIZE_SEPARATOR_BOOKEND
:
3215 return (array) CRM_Utils_Array
::explodePadded($value);
3217 case self
::SERIALIZE_SEPARATOR_TRIMMED
:
3218 return explode(self
::VALUE_SEPARATOR
, trim($value));
3220 case self
::SERIALIZE_JSON
:
3221 return strlen($value) ?
json_decode($value, TRUE) : [];
3223 case self
::SERIALIZE_PHP
:
3224 return strlen($value) ? CRM_Utils_String
::unserialize($value) : [];
3226 case self
::SERIALIZE_COMMA
:
3227 return explode(',', trim(str_replace(', ', '', $value)));
3230 throw new CRM_Core_Exception('Unknown serialization method for field.');
3237 public static function getEntityRefFilters() {
3242 * Get exportable fields with pseudoconstants rendered as an extra field.
3244 * @param string $baoClass
3248 public static function getExportableFieldsWithPseudoConstants($baoClass) {
3249 if (method_exists($baoClass, 'exportableFields')) {
3250 $fields = $baoClass::exportableFields();
3253 $fields = $baoClass::export();
3255 CRM_Core_DAO
::appendPseudoConstantsToFields($fields);
3260 * Remove item from static cache during update/delete operations
3262 private function clearDbColumnValueCache() {
3263 $daoName = get_class($this);
3264 while (strpos($daoName, '_BAO_') !== FALSE) {
3265 $daoName = get_parent_class($daoName);
3267 if (isset($this->id
)) {
3268 unset(self
::$_dbColumnValueCache[$daoName]['id'][$this->id
]);
3270 if (isset($this->name
)) {
3271 unset(self
::$_dbColumnValueCache[$daoName]['name'][$this->name
]);
3276 * Return a mapping from field-name to the corresponding key (as used in fields()).
3279 * Array(string $name => string $uniqueName).
3281 public static function fieldKeys() {
3282 return array_flip(CRM_Utils_Array
::collect('name', static::fields()));
3286 * Returns system paths related to this entity (as defined in the xml schema)
3290 public static function getEntityPaths() {
3291 return static::$_paths ??
[];
3295 * When creating a record without a supplied name,
3296 * create a unique, clean name derived from the label.
3298 * Note: this function does nothing unless a unique index exists for "name" column.
3300 * @var bool $isRequired
3302 private function makeNameFromLabel(bool $isRequired): void
{
3303 $indexNameWith = NULL;
3304 // Look for a unique index which includes the "name" field
3305 if (method_exists($this, 'indices')) {
3306 foreach ($this->indices(FALSE) as $index) {
3307 if (!empty($index['unique']) && in_array('name', $index['field'], TRUE)) {
3308 $indexNameWith = $index['field'];
3312 if (!$indexNameWith) {
3313 // No unique index on "name", do nothing
3316 $label = $this->label ??
$this->title ??
NULL;
3317 if (!$label && $label !== '0' && !$isRequired) {
3318 // No label supplied and name not required, do nothing
3321 $maxLen = static::getSupportedFields()['name']['maxlength'] ??
255;
3322 // Strip unsafe characters and trim to max length (-3 characters leaves room for a unique suffix)
3323 $name = CRM_Utils_String
::munge($label, '_', $maxLen - 3);
3325 // Find existing records with the same name
3326 $sql = new CRM_Utils_SQL_Select($this::getTableName());
3327 $sql->select(['id', 'name']);
3328 $sql->where('name LIKE @name', ['@name' => $name . '%']);
3329 // Include all fields that are part of the index
3330 foreach (array_diff($indexNameWith, ['name']) as $field) {
3331 $sql->where("`$field` = @val", ['@val' => $this->$field]);
3333 $query = $sql->toSQL();
3334 $existing = self
::executeQuery($query)->fetchMap('id', 'name');
3337 // Add unique suffix if existing records have the same name
3338 while (in_array($name . $suffix, $existing)) {
3339 $suffix = '_' . ++
$dupes;
3341 $this->name
= $name . $suffix;