3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
13 * Base Database Access Object class.
15 * All DAO classes should inherit from this class.
18 * @copyright CiviCRM LLC https://civicrm.org/licensing
21 if (!defined('DB_DSN_MODE')) {
22 define('DB_DSN_MODE', 'auto');
25 require_once 'PEAR.php';
26 require_once 'DB/DataObject.php';
28 require_once 'CRM/Core/I18n.php';
33 class CRM_Core_DAO
extends DB_DataObject
{
36 * How many times has this instance been cloned.
40 protected $resultCopies = 0;
46 public static $_nullObject = NULL;
51 public static $_nullArray = [];
53 public static $_dbColumnValueCache = NULL;
54 const NOT_NULL
= 1, IS_NULL
= 2,
56 VALUE_SEPARATOR
= "\ 1",
57 BULK_INSERT_COUNT
= 200,
58 BULK_INSERT_HIGH_COUNT
= 200,
59 QUERY_FORMAT_WILDCARD
= 1,
60 QUERY_FORMAT_NO_QUOTES
= 2,
63 * Serialized string separated by and bookended with VALUE_SEPARATOR
65 SERIALIZE_SEPARATOR_BOOKEND
= 1,
67 * @deprecated format separated by VALUE_SEPARATOR
69 SERIALIZE_SEPARATOR_TRIMMED
= 2,
71 * Recommended serialization format
75 * @deprecated format using php serialize()
79 * Comma separated string, no quotes, no spaces
84 * Define entities that shouldn't be created or deleted when creating/ deleting
85 * test objects - this prevents world regions, countries etc from being added / deleted
88 public static $_testEntitiesToSkip = [];
90 * The factory class for this application.
93 public static $_factory = NULL;
95 public static $_checkedSqlFunctionsExist = FALSE;
98 * https://issues.civicrm.org/jira/browse/CRM-17748
99 * internal variable for DAO to hold per-query settings
102 protected $_options = [];
107 * @return \CRM_Core_DAO
109 public function __construct() {
111 $this->__table
= $this->getTableName();
114 public function __clone() {
115 if (!empty($this->_DB_resultid
)) {
116 $this->resultCopies++
;
123 public function __destruct() {
124 if ($this->resultCopies
=== 0) {
127 $this->resultCopies
--;
131 * Empty definition for virtual function.
133 public static function getTableName() {
138 * Initialize the DAO object.
141 * The database connection string.
143 public static function init($dsn) {
144 Civi
::$statics[__CLASS__
]['init'] = 1;
145 $options = &PEAR
::getStaticProperty('DB_DataObject', 'options');
146 $options['database'] = $dsn;
147 if (defined('CIVICRM_DAO_DEBUG')) {
148 self
::DebugLevel(CIVICRM_DAO_DEBUG
);
150 $factory = new CRM_Contact_DAO_Factory();
151 CRM_Core_DAO
::setFactory($factory);
152 $currentModes = CRM_Utils_SQL
::getSqlModes();
153 if (CRM_Utils_Constant
::value('CIVICRM_MYSQL_STRICT', CRM_Utils_System
::isDevelopment())) {
154 if (CRM_Utils_SQL
::supportsFullGroupBy() && !in_array('ONLY_FULL_GROUP_BY', $currentModes) && CRM_Utils_SQL
::isGroupByModeInDefault()) {
155 $currentModes[] = 'ONLY_FULL_GROUP_BY';
157 if (!in_array('STRICT_TRANS_TABLES', $currentModes)) {
158 $currentModes = array_merge(['STRICT_TRANS_TABLES'], $currentModes);
160 CRM_Core_DAO
::executeQuery("SET SESSION sql_mode = %1", [1 => [implode(',', $currentModes), 'String']]);
162 CRM_Core_DAO
::executeQuery('SET NAMES utf8');
163 CRM_Core_DAO
::executeQuery('SET @uniqueID = %1', [1 => [CRM_Utils_Request
::id(), 'String']]);
169 public static function getConnection() {
170 global $_DB_DATAOBJECT;
171 $dao = new CRM_Core_DAO();
172 return $_DB_DATAOBJECT['CONNECTIONS'][$dao->_database_dsn_md5
];
176 * Disables usage of the ONLY_FULL_GROUP_BY Mode if necessary
178 public static function disableFullGroupByMode() {
179 $currentModes = CRM_Utils_SQL
::getSqlModes();
180 if (in_array('ONLY_FULL_GROUP_BY', $currentModes) && CRM_Utils_SQL
::isGroupByModeInDefault()) {
181 $key = array_search('ONLY_FULL_GROUP_BY', $currentModes);
182 unset($currentModes[$key]);
183 CRM_Core_DAO
::executeQuery("SET SESSION sql_mode = %1", [1 => [implode(',', $currentModes), 'String']]);
188 * Re-enables ONLY_FULL_GROUP_BY sql_mode as necessary..
190 public static function reenableFullGroupByMode() {
191 $currentModes = CRM_Utils_SQL
::getSqlModes();
192 if (!in_array('ONLY_FULL_GROUP_BY', $currentModes) && CRM_Utils_SQL
::isGroupByModeInDefault()) {
193 $currentModes[] = 'ONLY_FULL_GROUP_BY';
194 CRM_Core_DAO
::executeQuery("SET SESSION sql_mode = %1", [1 => [implode(',', $currentModes), 'String']]);
199 * @param string $fieldName
201 * @param array $params
203 protected function assignTestFK($fieldName, $fieldDef, $params) {
204 $required = CRM_Utils_Array
::value('required', $fieldDef);
205 $FKClassName = CRM_Utils_Array
::value('FKClassName', $fieldDef);
206 $dbName = $fieldDef['name'];
207 $daoName = str_replace('_BAO_', '_DAO_', get_class($this));
209 // skip the FK if it is not required
210 // if it's contact id we should create even if not required
211 // we'll have a go @ fetching first though
212 // we WILL create campaigns though for so tests with a campaign pseudoconstant will complete
213 if ($FKClassName === 'CRM_Campaign_DAO_Campaign' && $daoName != $FKClassName) {
216 if (!$required && $dbName != 'contact_id') {
217 $fkDAO = new $FKClassName();
218 if ($fkDAO->find(TRUE)) {
219 $this->$dbName = $fkDAO->id
;
223 elseif (in_array($FKClassName, CRM_Core_DAO
::$_testEntitiesToSkip)) {
224 $depObject = new $FKClassName();
225 $depObject->find(TRUE);
226 $this->$dbName = $depObject->id
;
228 elseif ($daoName == 'CRM_Member_DAO_MembershipType' && $fieldName == 'member_of_contact_id') {
229 // FIXME: the fields() metadata is not specific enough
230 $depObject = CRM_Core_DAO
::createTestObject($FKClassName, ['contact_type' => 'Organization']);
231 $this->$dbName = $depObject->id
;
234 //if it is required we need to generate the dependency object first
235 $depObject = CRM_Core_DAO
::createTestObject($FKClassName, CRM_Utils_Array
::value($dbName, $params, 1));
236 $this->$dbName = $depObject->id
;
241 * Generate and assign an arbitrary value to a field of a test object.
243 * @param string $fieldName
244 * @param array $fieldDef
245 * @param int $counter
246 * The globally-unique ID of the test object.
248 * @throws \CRM_Core_Exception
250 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
251 $dbName = $fieldDef['name'];
252 $daoName = get_class($this);
255 if (!$handled && $dbName == 'contact_sub_type') {
256 //coming up with a rule to set this is too complex let's not set it
260 // Pick an option value if needed
261 if (!$handled && $fieldDef['type'] !== CRM_Utils_Type
::T_BOOLEAN
) {
262 $options = $daoName::buildOptions($dbName, 'create');
264 $this->$dbName = key($options);
270 switch ($fieldDef['type']) {
271 case CRM_Utils_Type
::T_INT
:
272 case CRM_Utils_Type
::T_FLOAT
:
273 case CRM_Utils_Type
::T_MONEY
:
274 if (isset($fieldDef['precision'])) {
275 // $object->$dbName = CRM_Utils_Number::createRandomDecimal($value['precision']);
276 $this->$dbName = CRM_Utils_Number
::createTruncatedDecimal($counter, $fieldDef['precision']);
279 $this->$dbName = $counter;
283 case CRM_Utils_Type
::T_BOOLEAN
:
284 if (isset($fieldDef['default'])) {
285 $this->$dbName = $fieldDef['default'];
287 elseif ($fieldDef['name'] == 'is_deleted' ||
$fieldDef['name'] == 'is_test') {
295 case CRM_Utils_Type
::T_DATE
:
296 case CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
:
297 $this->$dbName = '19700101';
298 if ($dbName == 'end_date') {
299 // put this in the future
300 $this->$dbName = '20200101';
304 case CRM_Utils_Type
::T_TIMESTAMP
:
305 $this->$dbName = '19700201000000';
308 case CRM_Utils_Type
::T_TIME
:
309 throw new CRM_Core_Exception('T_TIME shouldn\'t be used.');
311 case CRM_Utils_Type
::T_CCNUM
:
312 $this->$dbName = '4111 1111 1111 1111';
315 case CRM_Utils_Type
::T_URL
:
316 $this->$dbName = 'http://www.civicrm.org';
319 case CRM_Utils_Type
::T_STRING
:
320 case CRM_Utils_Type
::T_BLOB
:
321 case CRM_Utils_Type
::T_MEDIUMBLOB
:
322 case CRM_Utils_Type
::T_TEXT
:
323 case CRM_Utils_Type
::T_LONGTEXT
:
324 case CRM_Utils_Type
::T_EMAIL
:
326 // WAS: if (isset($value['enumValues'])) {
327 // TODO: see if this works with all pseudoconstants
328 if (isset($fieldDef['pseudoconstant'], $fieldDef['pseudoconstant']['callback'])) {
329 if (isset($fieldDef['default'])) {
330 $this->$dbName = $fieldDef['default'];
333 $options = CRM_Core_PseudoConstant
::get($daoName, $fieldName);
334 if (is_array($options)) {
335 $this->$dbName = $options[0];
338 $defaultValues = explode(',', $options);
339 $this->$dbName = $defaultValues[0];
344 $this->$dbName = $dbName . '_' . $counter;
345 $maxlength = CRM_Utils_Array
::value('maxlength', $fieldDef);
346 if ($maxlength > 0 && strlen($this->$dbName) > $maxlength) {
347 $this->$dbName = substr($this->$dbName, 0, $fieldDef['maxlength']);
355 * Reset the DAO object.
357 * DAO is kinda crappy in that there is an unwritten rule of one query per DAO.
359 * We attempt to get around this crappy restriction by resetting some of DAO's internal fields. Use this with caution
361 public function reset() {
363 foreach (array_keys($this->table()) as $field) {
364 unset($this->$field);
368 * reset the various DB_DAO structures manually
377 * @param string $tableName
381 public static function getLocaleTableName($tableName) {
384 $tables = CRM_Core_I18n_Schema
::schemaStructureTables();
385 if (in_array($tableName, $tables)) {
386 return $tableName . $dbLocale;
393 * Execute a query by the current DAO, localizing it along the way (if needed).
395 * @param string $query
396 * The SQL query for execution.
397 * @param bool $i18nRewrite
398 * Whether to rewrite the query.
401 * the current DAO object after the query execution
403 public function query($query, $i18nRewrite = TRUE) {
404 // rewrite queries that should use $dbLocale-based views for multi-language installs
405 global $dbLocale, $_DB_DATAOBJECT;
407 if (empty($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5
])) {
408 // Will force connection to be populated per CRM-20541.
412 $conn = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5
];
413 $orig_options = $conn->options
;
414 $this->_setDBOptions($this->_options
);
416 if ($i18nRewrite and $dbLocale) {
417 $query = CRM_Core_I18n_Schema
::rewriteQuery($query);
420 $ret = parent
::query($query);
422 $this->_setDBOptions($orig_options);
427 * Static function to set the factory instance for this class.
429 * @param object $factory
430 * The factory application object.
432 public static function setFactory(&$factory) {
433 self
::$_factory = &$factory;
437 * Factory method to instantiate a new object from a table name.
439 * @param string $table
440 * @return \DataObject|\PEAR_Error
442 public function factory($table = '') {
443 if (!isset(self
::$_factory)) {
444 return parent
::factory($table);
447 return self
::$_factory->create($table);
451 * Initialization for all DAO objects. Since we access DB_DO programatically
452 * we need to set the links manually.
454 public function initialize() {
456 if (empty(Civi
::$statics[__CLASS__
]['init'])) {
457 // CRM_Core_DAO::init() must be called before CRM_Core_DAO->initialize().
458 // This occurs very early in bootstrap - error handlers may not be wired up.
459 echo "Inconsistent system initialization sequence. Premature access of (" . get_class($this) . ")";
460 CRM_Utils_System
::civiExit();
465 * Defines the default key as 'id'.
469 public function keys() {
478 * Tells DB_DataObject which keys use autoincrement.
479 * 'id' is autoincrementing by default.
484 public function sequenceKey() {
485 static $sequenceKeys;
486 if (!isset($sequenceKeys)) {
487 $sequenceKeys = ['id', TRUE];
489 return $sequenceKeys;
493 * Returns list of FK relationships.
497 * Array of CRM_Core_Reference_Interface
499 public static function getReferenceColumns() {
504 * Returns all the column names of this table.
509 public static function &fields() {
515 * Get/set an associative array of table columns
520 public function table() {
521 $fields = $this->fields();
525 foreach ($fields as $name => $value) {
526 $table[$value['name']] = $value['type'];
527 if (!empty($value['required'])) {
528 $table[$value['name']] +
= self
::DB_DAO_NOTNULL
;
541 * @return CRM_Core_DAO
543 public function save($hook = TRUE) {
544 if (!empty($this->id
)) {
548 $event = new \Civi\Core\DAO\Event\
PostUpdate($this);
549 \Civi
::service('dispatcher')->dispatch("civi.dao.postUpdate", $event);
551 $this->clearDbColumnValueCache();
557 $event = new \Civi\Core\DAO\Event\
PostUpdate($this);
558 \Civi
::service('dispatcher')->dispatch("civi.dao.postInsert", $event);
564 CRM_Utils_Hook
::postSave($this);
571 * Deletes items from table which match current objects variables.
573 * Returns the true on success
577 * Designed to be extended
579 * $object = new mytable();
581 * echo $object->delete(); // builds a conditon
583 * $object = new mytable();
584 * $object->whereAdd('age > 12');
586 * $object->orderBy('age DESC');
587 * $object->delete(true); // dont use object vars, use the conditions, limit and order.
589 * @param bool $useWhere (optional) If DB_DATAOBJECT_WHEREADD_ONLY is passed in then
590 * we will build the condition only using the whereAdd's. Default is to
591 * build the condition only using the object parameters.
593 * * @return mixed Int (No. of rows affected) on success, false on failure, 0 on no data affected
595 public function delete($useWhere = FALSE) {
596 $preEvent = new \Civi\Core\DAO\Event\
PreDelete($this);
597 \Civi
::service('dispatcher')->dispatch("civi.dao.preDelete", $preEvent);
599 $result = parent
::delete($useWhere);
601 $event = new \Civi\Core\DAO\Event\
PostDelete($this, $result);
602 \Civi
::service('dispatcher')->dispatch("civi.dao.postDelete", $event);
605 $this->clearDbColumnValueCache();
611 * @param bool $created
613 public function log($created = FALSE) {
616 if (!$this->getLog()) {
621 $session = CRM_Core_Session
::singleton();
622 $cid = $session->get('userID');
625 // return is we dont have handle to FK
630 $dao = new CRM_Core_DAO_Log();
631 $dao->entity_table
= $this->getTableName();
632 $dao->entity_id
= $this->id
;
633 $dao->modified_id
= $cid;
634 $dao->modified_date
= date("YmdHis");
639 * Given an associative array of name/value pairs, extract all the values
640 * that belong to this object and initialize the object with said values
642 * @param array $params
643 * (reference ) associative array of name/value pairs.
644 * @param bool $serializeArrays
645 * Should arrays that are passed in be serialised according to the metadata.
646 * Eventually this should be always true / gone, but in the interests of caution
647 * it is being grandfathered in. In general an array is not valid on the DAO
648 * but there may be instances where this function is called & then some handling
649 * takes place on the would-be array.
652 * Did we copy all null values into the object
654 public function copyValues(&$params, $serializeArrays = FALSE) {
655 $fields = $this->fields();
657 foreach ($fields as $name => $value) {
658 $dbName = $value['name'];
659 if (array_key_exists($dbName, $params)) {
660 $pValue = $params[$dbName];
663 elseif (array_key_exists($name, $params)) {
664 $pValue = $params[$name];
671 // if there is no value then make the variable NULL
673 if ($pValue === '') {
674 $this->$dbName = 'null';
676 elseif ($serializeArrays && is_array($pValue) && !empty($value['serialize'])) {
677 $this->$dbName = CRM_Core_DAO
::serializeField($pValue, $value['serialize']);
681 if (!$serializeArrays && is_array($pValue) && !empty($value['serialize'])) {
682 Civi
::log()->warning(ts('use copyParams to serialize arrays (' . __CLASS__
. '.' . $name . ')'), ['civi.tag' => 'deprecated']);
684 $maxLength = CRM_Utils_Array
::value('maxlength', $value);
685 if (!is_array($pValue) && $maxLength && mb_strlen($pValue) > $maxLength
686 && empty($value['pseudoconstant'])
688 Civi
::log()->warning(ts('A string for field $dbName has been truncated. The original string was %1', [CRM_Utils_Type
::escape($pValue, 'String')]));
689 // The string is too long - what to do what to do? Well losing data is generally bad so lets' truncate
690 $pValue = CRM_Utils_String
::ellipsify($pValue, $maxLength);
692 $this->$dbName = $pValue;
701 * Store all the values from this object in an associative array
702 * this is a destructive store, calling function is responsible
703 * for keeping sanity of id's.
705 * @param object $object
706 * The object that we are extracting data from.
707 * @param array $values
708 * (reference ) associative array of name/value pairs.
710 public static function storeValues(&$object, &$values) {
711 $fields = $object->fields();
712 foreach ($fields as $name => $value) {
713 $dbName = $value['name'];
714 if (isset($object->$dbName) && $object->$dbName !== 'null') {
715 $values[$dbName] = $object->$dbName;
716 if ($name != $dbName) {
717 $values[$name] = $object->$dbName;
724 * Create an attribute for this specific field. We only do this for strings and text
726 * @param array $field
727 * The field under task.
730 * the attributes for the object
732 public static function makeAttribute($field) {
734 if (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_STRING
) {
735 $maxLength = CRM_Utils_Array
::value('maxlength', $field);
736 $size = CRM_Utils_Array
::value('size', $field);
737 if ($maxLength ||
$size) {
740 $attributes['maxlength'] = $maxLength;
743 $attributes['size'] = $size;
748 elseif (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_TEXT
) {
749 $rows = CRM_Utils_Array
::value('rows', $field);
753 $cols = CRM_Utils_Array
::value('cols', $field);
759 $attributes['rows'] = $rows;
760 $attributes['cols'] = $cols;
763 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
) {
764 $attributes['size'] = 6;
765 $attributes['maxlength'] = 14;
773 * Get the size and maxLength attributes for this text field.
774 * (or for all text fields) in the DAO object.
776 * @param string $class
778 * @param string $fieldName
779 * Field that i'm interested in or null if.
780 * you want the attributes for all DAO text fields
783 * assoc array of name => attribute pairs
785 public static function getAttribute($class, $fieldName = NULL) {
786 $object = new $class();
787 $fields = $object->fields();
788 if ($fieldName != NULL) {
789 $field = CRM_Utils_Array
::value($fieldName, $fields);
790 return self
::makeAttribute($field);
794 foreach ($fields as $name => $field) {
795 $attribute = self
::makeAttribute($field);
797 $attributes[$name] = $attribute;
801 if (!empty($attributes)) {
809 * Check if there is a record with the same name in the db.
811 * @param string $value
812 * The value of the field we are checking.
813 * @param string $daoName
814 * The dao object name.
815 * @param string $daoID
816 * The id of the object being updated. u can change your name.
817 * as long as there is no conflict
818 * @param string $fieldName
819 * The name of the field in the DAO.
821 * @param string $domainID
822 * The id of the domain. Object exists only for the given domain.
825 * true if object exists
827 public static function objectExists($value, $daoName, $daoID, $fieldName = 'name', $domainID = NULL) {
828 $object = new $daoName();
829 $object->$fieldName = $value;
831 $object->domain_id
= $domainID;
834 if ($object->find(TRUE)) {
835 return ($daoID && $object->id
== $daoID) ?
TRUE : FALSE;
843 * Check if there is a given column in a specific table.
846 * @see CRM_Core_BAO_SchemaHandler::checkIfFieldExists
848 * @param string $tableName
849 * @param string $columnName
850 * @param bool $i18nRewrite
851 * Whether to rewrite the query on multilingual setups.
854 * true if exists, else false
856 public static function checkFieldExists($tableName, $columnName, $i18nRewrite = TRUE) {
857 return CRM_Core_BAO_SchemaHandler
::checkIfFieldExists($tableName, $columnName, $i18nRewrite);
861 * Scans all the tables using a slow query and table name.
865 public static function getTableNames() {
866 $dao = CRM_Core_DAO
::executeQuery(
868 FROM information_schema.TABLES
869 WHERE TABLE_SCHEMA = '" . CRM_Core_DAO
::getDatabaseName() . "'
870 AND TABLE_NAME LIKE 'civicrm_%'
871 AND TABLE_NAME NOT LIKE 'civicrm_import_job_%'
872 AND TABLE_NAME NOT LIKE '%_temp%'
875 while ($dao->fetch()) {
876 $values[] = $dao->TABLE_NAME
;
882 * @param int $maxTablesToCheck
886 public static function isDBMyISAM($maxTablesToCheck = 10) {
887 return CRM_Core_DAO
::singleValueQuery(
889 FROM information_schema.TABLES
890 WHERE ENGINE = 'MyISAM'
891 AND TABLE_SCHEMA = '" . CRM_Core_DAO
::getDatabaseName() . "'
892 AND TABLE_NAME LIKE 'civicrm_%'
893 AND TABLE_NAME NOT LIKE 'civicrm_import_job_%'
894 AND TABLE_NAME NOT LIKE '%_temp%'
895 AND TABLE_NAME NOT LIKE 'civicrm_tmp_%'
900 * Get the name of the CiviCRM database.
904 public static function getDatabaseName() {
905 $daoObj = new CRM_Core_DAO();
906 return $daoObj->database();
910 * Checks if a constraint exists for a specified table.
912 * @param string $tableName
913 * @param string $constraint
916 * true if constraint exists, false otherwise
918 * @throws \CRM_Core_Exception
920 public static function checkConstraintExists($tableName, $constraint) {
923 if (!array_key_exists($tableName, $show)) {
924 $query = "SHOW CREATE TABLE $tableName";
925 $dao = CRM_Core_DAO
::executeQuery($query, [], TRUE, NULL, FALSE, FALSE);
927 if (!$dao->fetch()) {
928 throw new CRM_Core_Exception('query failed');
931 $show[$tableName] = $dao->Create_Table
;
934 return preg_match("/\b$constraint\b/i", $show[$tableName]) ?
TRUE : FALSE;
938 * Checks if CONSTRAINT keyword exists for a specified table.
940 * @param array $tables
942 * @throws CRM_Core_Exception
945 * true if CONSTRAINT keyword exists, false otherwise
947 public static function schemaRequiresRebuilding($tables = ["civicrm_contact"]) {
949 foreach ($tables as $tableName) {
950 if (!array_key_exists($tableName, $show)) {
951 $query = "SHOW CREATE TABLE $tableName";
952 $dao = CRM_Core_DAO
::executeQuery($query, [], TRUE, NULL, FALSE, FALSE);
954 if (!$dao->fetch()) {
955 throw new CRM_Core_Exception('Show create table failed.');
958 $show[$tableName] = $dao->Create_Table
;
961 $result = preg_match("/\bCONSTRAINT\b\s/i", $show[$tableName]) ?
TRUE : FALSE;
962 if ($result == TRUE) {
973 * Checks if the FK constraint name is in the format 'FK_tableName_columnName'
974 * for a specified column of a table.
976 * @param string $tableName
977 * @param string $columnName
980 * true if in format, false otherwise
982 * @throws \CRM_Core_Exception
984 public static function checkFKConstraintInFormat($tableName, $columnName) {
987 if (!array_key_exists($tableName, $show)) {
988 $query = "SHOW CREATE TABLE $tableName";
989 $dao = CRM_Core_DAO
::executeQuery($query);
991 if (!$dao->fetch()) {
992 throw new CRM_Core_Exception('query failed');
995 $show[$tableName] = $dao->Create_Table
;
997 $constraint = "`FK_{$tableName}_{$columnName}`";
998 $pattern = "/\bCONSTRAINT\b\s+%s\s+\bFOREIGN\s+KEY\b\s/i";
999 return preg_match(sprintf($pattern, $constraint), $show[$tableName]) ?
TRUE : FALSE;
1003 * Check whether a specific column in a specific table has always the same value.
1005 * @param string $tableName
1006 * @param string $columnName
1007 * @param string $columnValue
1010 * true if the value is always $columnValue, false otherwise
1012 public static function checkFieldHasAlwaysValue($tableName, $columnName, $columnValue) {
1013 $query = "SELECT * FROM $tableName WHERE $columnName != '$columnValue'";
1014 $dao = CRM_Core_DAO
::executeQuery($query);
1015 $result = $dao->fetch() ?
FALSE : TRUE;
1020 * Check whether a specific column in a specific table is always NULL.
1022 * @param string $tableName
1023 * @param string $columnName
1026 * true if if the value is always NULL, false otherwise
1028 public static function checkFieldIsAlwaysNull($tableName, $columnName) {
1029 $query = "SELECT * FROM $tableName WHERE $columnName IS NOT NULL";
1030 $dao = CRM_Core_DAO
::executeQuery($query);
1031 $result = $dao->fetch() ?
FALSE : TRUE;
1036 * Check if there is a given table in the database.
1038 * @param string $tableName
1041 * true if exists, else false
1043 public static function checkTableExists($tableName) {
1048 $params = [1 => [$tableName, 'String']];
1050 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1051 $result = $dao->fetch() ?
TRUE : FALSE;
1056 * Check if a given table has data.
1058 * @param string $tableName
1060 * TRUE if $tableName has at least one record.
1062 public static function checkTableHasData($tableName) {
1063 $c = CRM_Core_DAO
::singleValueQuery(sprintf('SELECT count(*) c FROM `%s`', $tableName));
1072 public function checkVersion($version) {
1077 $dbVersion = CRM_Core_DAO
::singleValueQuery($query);
1078 return trim($version) == trim($dbVersion) ?
TRUE : FALSE;
1082 * Find a DAO object for the given ID and return it.
1085 * Id of the DAO object being searched for.
1087 * @return CRM_Core_DAO
1088 * Object of the type of the class that called this function.
1092 public static function findById($id) {
1093 $object = new static();
1095 if (!$object->find(TRUE)) {
1096 throw new Exception("Unable to find a " . get_called_class() . " with id {$id}.");
1102 * Returns all results as array-encoded records.
1106 public function fetchAll() {
1108 while ($this->fetch()) {
1109 $result[] = $this->toArray();
1115 * Return the results as PHP generator.
1117 * @param string $type
1118 * Whether the generator yields 'dao' objects or 'array's.
1120 public function fetchGenerator($type = 'dao') {
1121 while ($this->fetch()) {
1128 yield
$this->toArray();
1132 throw new \
RuntimeException("Invalid record type ($type)");
1138 * Returns a singular value.
1140 * @return mixed|NULL
1142 public function fetchValue() {
1143 $result = $this->getDatabaseResult();
1144 $row = $result->fetchRow();
1154 * Get all the result records as mapping between columns.
1156 * @param string $keyColumn
1158 * @param string $valueColumn
1161 * Ex: ["foo" => "The Foo Bar", "baz" => "The Baz Qux"]
1163 public function fetchMap($keyColumn, $valueColumn) {
1165 while ($this->fetch()) {
1166 $result[$this->{$keyColumn}] = $this->{$valueColumn};
1172 * Given a DAO name, a column name and a column value, find the record and GET the value of another column in that record
1174 * @param string $daoName
1175 * Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact).
1176 * @param int $searchValue
1177 * Value of the column you want to search by.
1178 * @param string $returnColumn
1179 * Name of the column you want to GET the value of.
1180 * @param string $searchColumn
1181 * Name of the column you want to search by.
1182 * @param bool $force
1183 * Skip use of the cache.
1185 * @return string|null
1186 * Value of $returnColumn in the retrieved record
1188 * @throws \CRM_Core_Exception
1190 public static function getFieldValue($daoName, $searchValue, $returnColumn = 'name', $searchColumn = 'id', $force = FALSE) {
1192 empty($searchValue) ||
1193 trim(strtolower($searchValue)) == 'null'
1195 // adding this here since developers forget to check for an id
1196 // or for the 'null' (which is a bad DAO kludge)
1197 // and hence we get the first value in the db
1198 throw new CRM_Core_Exception('getFieldValue failed');
1201 self
::$_dbColumnValueCache = self
::$_dbColumnValueCache ??
[];
1203 while (strpos($daoName, '_BAO_') !== FALSE) {
1204 $daoName = get_parent_class($daoName);
1208 empty(self
::$_dbColumnValueCache[$daoName][$searchColumn][$searchValue]) ||
1209 !array_key_exists($returnColumn, self
::$_dbColumnValueCache[$daoName][$searchColumn][$searchValue])
1211 $object = new $daoName();
1212 $object->$searchColumn = $searchValue;
1213 $object->selectAdd();
1214 $object->selectAdd($returnColumn);
1217 if ($object->find(TRUE)) {
1218 $result = $object->$returnColumn;
1221 self
::$_dbColumnValueCache[$daoName][$searchColumn][$searchValue][$returnColumn] = $result;
1223 return self
::$_dbColumnValueCache[$daoName][$searchColumn][$searchValue][$returnColumn];
1227 * Given a DAO name, a column name and a column value, find the record and SET the value of another column in that record
1229 * @param string $daoName
1230 * Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact).
1231 * @param int $searchValue
1232 * Value of the column you want to search by.
1233 * @param string $setColumn
1234 * Name of the column you want to SET the value of.
1235 * @param string $setValue
1236 * SET the setColumn to this value.
1237 * @param string $searchColumn
1238 * Name of the column you want to search by.
1241 * true if we found and updated the object, else false
1243 public static function setFieldValue($daoName, $searchValue, $setColumn, $setValue, $searchColumn = 'id') {
1244 $object = new $daoName();
1245 $object->selectAdd();
1246 $object->selectAdd("$searchColumn, $setColumn");
1247 $object->$searchColumn = $searchValue;
1249 if ($object->find(TRUE)) {
1250 $object->$setColumn = $setValue;
1251 if ($object->save()) {
1262 * @param array|object $sort either array or CRM_Utils_Sort
1263 * @param string $default
1264 * Default sort value.
1268 public static function getSortString($sort, $default = NULL) {
1269 // check if sort is of type CRM_Utils_Sort
1270 if (is_a($sort, 'CRM_Utils_Sort')) {
1271 return $sort->orderBy();
1276 // is it an array specified as $field => $sortDirection ?
1278 foreach ($sort as $k => $v) {
1279 $sortString .= "$k $v,";
1281 return rtrim($sortString, ',');
1287 * Fetch object based on array of properties.
1289 * @param string $daoName
1290 * Name of the dao object.
1291 * @param array $params
1292 * (reference ) an assoc array of name/value pairs.
1293 * @param array $defaults
1294 * (reference ) an assoc array to hold the flattened values.
1295 * @param array $returnProperities
1296 * An assoc array of fields that need to be returned, eg array( 'first_name', 'last_name').
1299 * an object of type referenced by daoName
1301 public static function commonRetrieve($daoName, &$params, &$defaults, $returnProperities = NULL) {
1302 $object = new $daoName();
1303 $object->copyValues($params);
1305 // return only specific fields if returnproperties are sent
1306 if (!empty($returnProperities)) {
1307 $object->selectAdd();
1308 $object->selectAdd(implode(',', $returnProperities));
1311 if ($object->find(TRUE)) {
1312 self
::storeValues($object, $defaults);
1319 * Delete the object records that are associated with this contact.
1321 * @param string $daoName
1322 * Name of the dao object.
1323 * @param int $contactId
1324 * Id of the contact to delete.
1326 public static function deleteEntityContact($daoName, $contactId) {
1327 $object = new $daoName();
1329 $object->entity_table
= 'civicrm_contact';
1330 $object->entity_id
= $contactId;
1335 * Execute an unbuffered query.
1337 * This is a wrapper around new functionality exposed with CRM-17748.
1339 * @param string $query query to be executed
1341 * @param array $params
1342 * @param bool $abort
1343 * @param null $daoName
1344 * @param bool $freeDAO
1345 * @param bool $i18nRewrite
1346 * @param bool $trapException
1348 * @return CRM_Core_DAO
1349 * Object that points to an unbuffered result set
1351 public static function executeUnbufferedQuery(
1357 $i18nRewrite = TRUE,
1358 $trapException = FALSE
1361 return self
::executeQuery(
1369 ['result_buffering' => 0]
1376 * @param string $query
1377 * Query to be executed.
1379 * @param array $params
1380 * @param bool $abort
1381 * @param null $daoName
1382 * @param bool $freeDAO
1383 * @param bool $i18nRewrite
1384 * @param bool $trapException
1385 * @param array $options
1387 * @return CRM_Core_DAO|object
1388 * object that holds the results of the query
1389 * NB - if this is defined as just returning a DAO phpstorm keeps pointing
1390 * out all the properties that are not part of the DAO
1392 public static function &executeQuery(
1398 $i18nRewrite = TRUE,
1399 $trapException = FALSE,
1402 $queryStr = self
::composeQuery($query, $params, $abort);
1405 $dao = new CRM_Core_DAO();
1408 $dao = new $daoName();
1411 if ($trapException) {
1412 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
1415 if ($dao->isValidOption($options)) {
1416 $dao->setOptions($options);
1419 $result = $dao->query($queryStr, $i18nRewrite);
1421 // since it is unbuffered, ($dao->N==0) is true. This blocks the standard fetch() mechanism.
1422 if (CRM_Utils_Array
::value('result_buffering', $options) === 0) {
1426 if (is_a($result, 'DB_Error')) {
1431 preg_match('/^(insert|update|delete|create|drop|replace)/i', $queryStr)
1433 // we typically do this for insert/update/delete statements OR if explicitly asked to
1440 * Wrapper to validate internal DAO options before passing to DB_mysql/DB_Common level
1442 * @param array $options
1445 * Provided options are valid
1447 public function isValidOption($options) {
1456 if (empty($options)) {
1460 foreach (array_keys($options) as $option) {
1461 if (!in_array($option, $validOptions)) {
1471 * Execute a query and get the single result.
1473 * @param string $query
1474 * Query to be executed.
1475 * @param array $params
1476 * @param bool $abort
1477 * @param bool $i18nRewrite
1478 * @return string|null
1479 * the result of the query if any
1482 public static function &singleValueQuery(
1488 $queryStr = self
::composeQuery($query, $params, $abort);
1490 static $_dao = NULL;
1493 $_dao = new CRM_Core_DAO();
1496 $_dao->query($queryStr, $i18nRewrite);
1498 $result = $_dao->getDatabaseResult();
1501 $row = $result->fetchRow();
1511 * Compose the query by merging the parameters into it.
1513 * @param string $query
1514 * @param array $params
1515 * @param bool $abort
1518 * @throws CRM_Core_Exception
1520 public static function composeQuery($query, $params = [], $abort = TRUE) {
1522 foreach ($params as $key => $item) {
1523 if (is_numeric($key)) {
1524 if (CRM_Utils_Type
::validate($item[0], $item[1]) !== NULL) {
1525 $item[0] = self
::escapeString($item[0]);
1526 if ($item[1] == 'String' ||
1527 $item[1] == 'Memo' ||
1530 // Support class constants stipulating wildcard characters and/or
1531 // non-quoting of strings. Also support legacy code which may be
1532 // passing in TRUE or 1 for $item[2], which used to indicate the
1533 // use of wildcard characters.
1534 if (!empty($item[2])) {
1535 if ($item[2] & CRM_Core_DAO
::QUERY_FORMAT_WILDCARD ||
$item[2] === TRUE) {
1536 $item[0] = "'%{$item[0]}%'";
1538 elseif (!($item[2] & CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
)) {
1539 $item[0] = "'{$item[0]}'";
1543 $item[0] = "'{$item[0]}'";
1547 if (($item[1] == 'Date' ||
$item[1] == 'Timestamp') &&
1548 strlen($item[0]) == 0
1553 $tr['%' . $key] = $item[0];
1556 throw new CRM_Core_Exception("{$item[0]} is not of type {$item[1]}");
1561 return strtr($query, $tr);
1567 public static function freeResult($ids = NULL) {
1568 global $_DB_DATAOBJECT;
1571 if (!$_DB_DATAOBJECT ||
1572 !isset($_DB_DATAOBJECT['RESULTS'])
1576 $ids = array_keys($_DB_DATAOBJECT['RESULTS']);
1579 foreach ($ids as $id) {
1580 if (isset($_DB_DATAOBJECT['RESULTS'][$id])) {
1581 $_DB_DATAOBJECT['RESULTS'][$id]->free();
1582 unset($_DB_DATAOBJECT['RESULTS'][$id]);
1585 if (isset($_DB_DATAOBJECT['RESULTFIELDS'][$id])) {
1586 unset($_DB_DATAOBJECT['RESULTFIELDS'][$id]);
1592 * Make a shallow copy of an object and all the fields in the object.
1594 * @param string $daoName
1596 * @param array $criteria
1597 * Array of all the fields & values.
1598 * on which basis to copy
1599 * @param array $newData
1600 * Array of all the fields & values.
1601 * to be copied besides the other fields
1602 * @param string $fieldsFix
1603 * Array of fields that you want to prefix/suffix/replace.
1604 * @param string $blockCopyOfDependencies
1605 * Fields that you want to block from.
1607 * @param bool $blockCopyofCustomValues
1608 * Case when you don't want to copy the custom values set in a
1609 * template as it will override/ignore the submitted custom values
1611 * @return CRM_Core_DAO|bool
1612 * the newly created copy of the object. False if none created.
1614 public static function copyGeneric($daoName, $criteria, $newData = NULL, $fieldsFix = NULL, $blockCopyOfDependencies = NULL, $blockCopyofCustomValues = FALSE) {
1615 $object = new $daoName();
1618 $object->id
= $criteria['id'];
1621 foreach ($criteria as $key => $value) {
1622 $object->$key = $value;
1627 while ($object->fetch()) {
1629 // all the objects except with $blockCopyOfDependencies set
1630 // be copied - addresses #CRM-1962
1632 if ($blockCopyOfDependencies && $object->$blockCopyOfDependencies) {
1636 $newObject = new $daoName();
1638 $fields = $object->fields();
1639 if (!is_array($fieldsFix)) {
1640 $fieldsToPrefix = [];
1641 $fieldsToSuffix = [];
1642 $fieldsToReplace = [];
1644 if (!empty($fieldsFix['prefix'])) {
1645 $fieldsToPrefix = $fieldsFix['prefix'];
1647 if (!empty($fieldsFix['suffix'])) {
1648 $fieldsToSuffix = $fieldsFix['suffix'];
1650 if (!empty($fieldsFix['replace'])) {
1651 $fieldsToReplace = $fieldsFix['replace'];
1654 foreach ($fields as $name => $value) {
1655 if ($name == 'id' ||
$value['name'] == 'id') {
1656 // copy everything but the id!
1660 $dbName = $value['name'];
1661 $type = CRM_Utils_Type
::typeToString($value['type']);
1662 $newObject->$dbName = $object->$dbName;
1663 if (isset($fieldsToPrefix[$dbName])) {
1664 $newObject->$dbName = $fieldsToPrefix[$dbName] . $newObject->$dbName;
1666 if (isset($fieldsToSuffix[$dbName])) {
1667 $newObject->$dbName .= $fieldsToSuffix[$dbName];
1669 if (isset($fieldsToReplace[$dbName])) {
1670 $newObject->$dbName = $fieldsToReplace[$dbName];
1673 if ($type == 'Timestamp' ||
$type == 'Date') {
1674 $newObject->$dbName = CRM_Utils_Date
::isoToMysql($newObject->$dbName);
1678 $newObject->copyValues($newData);
1682 if (!$blockCopyofCustomValues) {
1683 $newObject->copyCustomFields($object->id
, $newObject->id
);
1685 CRM_Utils_Hook
::post('create', CRM_Core_DAO_AllCoreTables
::getBriefName(str_replace('_BAO_', '_DAO_', $daoName)), $newObject->id
, $newObject);
1692 * Method that copies custom fields values from an old entity to a new one.
1694 * Fixes bug CRM-19302,
1695 * where if a custom field of File type was present, left both events using the same file,
1696 * breaking download URL's for the old event.
1698 * @todo the goal here is to clean this up so that it works for any entity. Copy Generic already DOES some custom field stuff
1699 * but it seems to be bypassed & perhaps less good than this (or this just duplicates it...)
1701 * @param int $entityID
1702 * @param int $newEntityID
1704 public function copyCustomFields($entityID, $newEntityID) {
1705 $entity = CRM_Core_DAO_AllCoreTables
::getBriefName(get_class($this));
1706 $tableName = CRM_Core_DAO_AllCoreTables
::getTableForClass(get_class($this));
1707 // Obtain custom values for old event
1708 $customParams = $htmlType = [];
1709 $customValues = CRM_Core_BAO_CustomValueTable
::getEntityValues($entityID, $entity);
1711 // If custom values present, we copy them
1712 if (!empty($customValues)) {
1713 // Get Field ID's and identify File type attributes, to handle file copying.
1714 $fieldIds = implode(', ', array_keys($customValues));
1715 $sql = "SELECT id FROM civicrm_custom_field WHERE html_type = 'File' AND id IN ( {$fieldIds} )";
1716 $result = CRM_Core_DAO
::executeQuery($sql);
1718 // Build array of File type fields
1719 while ($result->fetch()) {
1720 $htmlType[] = $result->id
;
1723 // Build params array of custom values
1724 foreach ($customValues as $field => $value) {
1725 if ($value !== NULL) {
1726 // Handle File type attributes
1727 if (in_array($field, $htmlType)) {
1728 $fileValues = CRM_Core_BAO_File
::path($value, $entityID);
1729 $customParams["custom_{$field}_-1"] = [
1730 'name' => CRM_Utils_File
::duplicate($fileValues[0]),
1731 'type' => $fileValues[1],
1734 // Handle other types
1736 $customParams["custom_{$field}_-1"] = $value;
1741 // Save Custom Fields for new Event
1742 CRM_Core_BAO_CustomValueTable
::postProcess($customParams, $tableName, $newEntityID, $entity);
1745 // copy activity attachments ( if any )
1746 CRM_Core_BAO_File
::copyEntityFile($tableName, $entityID, $tableName, $newEntityID);
1750 * Cascade update through related entities.
1752 * @param string $daoName
1755 * @param array $newData
1757 * @return CRM_Core_DAO|null
1759 public static function cascadeUpdate($daoName, $fromId, $toId, $newData = []) {
1760 $object = new $daoName();
1761 $object->id
= $fromId;
1763 if ($object->find(TRUE)) {
1764 $newObject = new $daoName();
1765 $newObject->id
= $toId;
1767 if ($newObject->find(TRUE)) {
1768 $fields = $object->fields();
1769 foreach ($fields as $name => $value) {
1770 if ($name == 'id' ||
$value['name'] == 'id') {
1771 // copy everything but the id!
1775 $colName = $value['name'];
1776 $newObject->$colName = $object->$colName;
1778 if (substr($name, -5) == '_date' ||
1779 substr($name, -10) == '_date_time'
1781 $newObject->$colName = CRM_Utils_Date
::isoToMysql($newObject->$colName);
1784 foreach ($newData as $k => $v) {
1785 $newObject->$k = $v;
1795 * Given the component id, compute the contact id
1796 * since its used for things like send email
1798 * @param $componentIDs
1799 * @param string $tableName
1800 * @param string $idField
1804 public static function getContactIDsFromComponent($componentIDs, $tableName, $idField = 'id') {
1807 if (empty($componentIDs)) {
1811 $IDs = implode(',', $componentIDs);
1815 WHERE $idField IN ( $IDs )
1818 $dao = CRM_Core_DAO
::executeQuery($query);
1819 while ($dao->fetch()) {
1820 $contactIDs[] = $dao->contact_id
;
1826 * Fetch object based on array of properties.
1828 * @param string $daoName
1829 * Name of the dao object.
1830 * @param string $fieldIdName
1831 * @param int $fieldId
1833 * @param array $returnProperities
1834 * An assoc array of fields that need to be returned, eg array( 'first_name', 'last_name').
1837 * an object of type referenced by daoName
1839 public static function commonRetrieveAll($daoName, $fieldIdName = 'id', $fieldId, &$details, $returnProperities = NULL) {
1840 require_once str_replace('_', DIRECTORY_SEPARATOR
, $daoName) . ".php";
1841 $object = new $daoName();
1842 $object->$fieldIdName = $fieldId;
1844 // return only specific fields if returnproperties are sent
1845 if (!empty($returnProperities)) {
1846 $object->selectAdd();
1847 $object->selectAdd('id');
1848 $object->selectAdd(implode(',', $returnProperities));
1852 while ($object->fetch()) {
1854 self
::storeValues($object, $defaults);
1855 $details[$object->id
] = $defaults;
1862 * Drop all CiviCRM tables.
1864 * @throws \CRM_Core_Exception
1866 public static function dropAllTables() {
1868 // first drop all the custom tables we've created
1869 CRM_Core_BAO_CustomGroup
::dropAllTables();
1871 // drop all multilingual views
1872 CRM_Core_I18n_Schema
::dropAllViews();
1874 CRM_Utils_File
::sourceSQLFile(CIVICRM_DSN
,
1875 dirname(__FILE__
) . DIRECTORY_SEPARATOR
.
1876 '..' . DIRECTORY_SEPARATOR
.
1877 '..' . DIRECTORY_SEPARATOR
.
1878 'sql' . DIRECTORY_SEPARATOR
.
1879 'civicrm_drop.mysql'
1888 public static function escapeString($string) {
1889 static $_dao = NULL;
1891 // If this is an atypical case (e.g. preparing .sql file before CiviCRM
1892 // has been installed), then we fallback DB-less str_replace escaping, as
1893 // we can't use mysqli_real_escape_string, as there is no DB connection.
1894 // Note: In typical usage, escapeString() will only check one conditional
1895 // ("if !$_dao") rather than two conditionals ("if !defined(DSN)")
1896 if (!defined('CIVICRM_DSN')) {
1897 // See http://php.net/manual/en/mysqli.real-escape-string.php for the
1898 // list of characters mysqli_real_escape_string escapes.
1899 $search = ["\\", "\x00", "\n", "\r", "'", '"', "\x1a"];
1900 $replace = ["\\\\", "\\0", "\\n", "\\r", "\'", '\"', "\\Z"];
1901 return str_replace($search, $replace, $string);
1903 $_dao = new CRM_Core_DAO();
1905 return $_dao->escape($string);
1909 * Escape a list of strings for use with "WHERE X IN (...)" queries.
1911 * @param array $strings
1912 * @param string $default
1913 * the value to use if $strings has no elements.
1915 * eg "abc","def","ghi"
1917 public static function escapeStrings($strings, $default = NULL) {
1918 static $_dao = NULL;
1920 $_dao = new CRM_Core_DAO();
1923 if (empty($strings)) {
1927 $escapes = array_map([$_dao, 'escape'], $strings);
1928 return '"' . implode('","', $escapes) . '"';
1936 public static function escapeWildCardString($string) {
1938 // ensure we escape the single characters % and _ which are mysql wild
1939 // card characters and could come in via sortByCharacter
1940 // note that mysql does not escape these characters
1941 if ($string && in_array($string,
1942 ['%', '_', '%%', '_%']
1945 return '\\' . $string;
1948 return self
::escapeString($string);
1952 * Creates a test object, including any required objects it needs via recursion
1953 * createOnly: only create in database, do not store or return the objects (useful for perf testing)
1954 * ONLY USE FOR TESTING
1956 * @param string $daoName
1957 * @param array $params
1958 * @param int $numObjects
1959 * @param bool $createOnly
1961 * @return object|array|NULL
1962 * NULL if $createOnly. A single object if $numObjects==1. Otherwise, an array of multiple objects.
1964 public static function createTestObject(
1970 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
1971 // so we re-set here in case
1972 $config = CRM_Core_Config
::singleton();
1973 $config->backtrace
= TRUE;
1975 static $counter = 0;
1976 CRM_Core_DAO
::$_testEntitiesToSkip = [
1977 'CRM_Core_DAO_Worldregion',
1978 'CRM_Core_DAO_StateProvince',
1979 'CRM_Core_DAO_Country',
1980 'CRM_Core_DAO_Domain',
1981 'CRM_Financial_DAO_FinancialType',
1982 //because valid ones exist & we use pick them due to pseudoconstant can't reliably create & delete these
1985 // Prefer to instantiate BAO's instead of DAO's (when possible)
1986 // so that assignTestValue()/assignTestFK() can be overloaded.
1987 $baoName = str_replace('_DAO_', '_BAO_', $daoName);
1988 if ($baoName === 'CRM_Financial_BAO_FinancialTrxn') {
1989 // OMG OMG OMG this is so incredibly bad. The BAO is insanely named.
1990 // @todo create a new class called what the BAO SHOULD be
1991 // that extends BAO-crazy-name.... migrate.
1992 $baoName = 'CRM_Core_BAO_FinancialTrxn';
1994 if (class_exists($baoName)) {
1995 $daoName = $baoName;
1998 for ($i = 0; $i < $numObjects; ++
$i) {
2001 /** @var CRM_Core_DAO $object */
2002 $object = new $daoName();
2004 $fields = $object->fields();
2005 foreach ($fields as $fieldName => $fieldDef) {
2006 $dbName = $fieldDef['name'];
2007 $FKClassName = CRM_Utils_Array
::value('FKClassName', $fieldDef);
2008 $required = CRM_Utils_Array
::value('required', $fieldDef);
2010 if (CRM_Utils_Array
::value($dbName, $params) !== NULL && !is_array($params[$dbName])) {
2011 $object->$dbName = $params[$dbName];
2014 elseif ($dbName != 'id') {
2015 if ($FKClassName != NULL) {
2016 $object->assignTestFK($fieldName, $fieldDef, $params);
2020 $object->assignTestValue($fieldName, $fieldDef, $counter);
2028 $objects[$i] = $object;
2038 elseif ($numObjects == 1) {
2047 * Deletes the this object plus any dependent objects that are associated with it.
2048 * ONLY USE FOR TESTING
2050 * @param string $daoName
2051 * @param array $params
2053 public static function deleteTestObjects($daoName, $params = []) {
2054 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
2055 // so we re-set here in case
2056 $config = CRM_Core_Config
::singleton();
2057 $config->backtrace
= TRUE;
2059 $object = new $daoName();
2060 $object->id
= CRM_Utils_Array
::value('id', $params);
2062 // array(array(0 => $daoName, 1 => $daoParams))
2064 if ($object->find(TRUE)) {
2066 $fields = $object->fields();
2067 foreach ($fields as $name => $value) {
2069 $dbName = $value['name'];
2071 $FKClassName = CRM_Utils_Array
::value('FKClassName', $value);
2072 $required = CRM_Utils_Array
::value('required', $value);
2073 if ($FKClassName != NULL
2075 && !in_array($FKClassName, CRM_Core_DAO
::$_testEntitiesToSkip)
2076 && ($required ||
$dbName == 'contact_id')
2077 //I'm a bit stuck on this one - we might need to change the singleValueAlter so that the entities don't share a contact
2078 // to make this test process pass - line below makes pass for now
2079 && $dbName != 'member_of_contact_id'
2082 $deletions[] = [$FKClassName, ['id' => $object->$dbName]];
2089 foreach ($deletions as $deletion) {
2090 CRM_Core_DAO
::deleteTestObjects($deletion[0], $deletion[1]);
2095 * Set defaults when creating new entity.
2096 * (don't call this set defaults as already in use with different signature in some places)
2098 * @param array $params
2101 public static function setCreateDefaults(&$params, $defaults) {
2102 if (!empty($params['id'])) {
2105 foreach ($defaults as $key => $value) {
2106 if (!array_key_exists($key, $params) ||
$params[$key] === NULL) {
2107 $params[$key] = $value;
2113 * @param string $prefix
2114 * @param bool $addRandomString
2115 * @param null $string
2119 * @see CRM_Utils_SQL_TempTable
2121 public static function createTempTableName($prefix = 'civicrm', $addRandomString = TRUE, $string = NULL) {
2122 $tableName = $prefix . "_temp";
2124 if ($addRandomString) {
2126 $tableName .= "_" . $string;
2129 $tableName .= "_" . md5(uniqid('', TRUE));
2137 * @param bool $trigger
2141 public static function checkTriggerViewPermission($view = TRUE, $trigger = TRUE) {
2142 if (\Civi
::settings()->get('logging_no_trigger_permission')) {
2145 // test for create view and trigger permissions and if allowed, add the option to go multilingual
2147 // I'm not sure why we use the getStaticProperty for an error, rather than checking for DB_Error
2148 CRM_Core_TemporaryErrorScope
::ignoreException();
2149 $dao = new CRM_Core_DAO();
2151 $result = $dao->query('CREATE OR REPLACE VIEW civicrm_domain_view AS SELECT * FROM civicrm_domain');
2152 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError') ||
is_a($result, 'DB_Error')) {
2158 $result = $dao->query('CREATE TRIGGER civicrm_domain_trigger BEFORE INSERT ON civicrm_domain FOR EACH ROW BEGIN END');
2159 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError') ||
is_a($result, 'DB_Error')) {
2161 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
2166 $dao->query('DROP TRIGGER IF EXISTS civicrm_domain_trigger');
2167 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
2169 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
2176 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
2177 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
2186 * @param null $message
2187 * @param bool $printDAO
2189 public static function debugPrint($message = NULL, $printDAO = TRUE) {
2190 CRM_Utils_System
::xMemory("{$message}: ");
2193 global $_DB_DATAOBJECT;
2195 foreach (array_keys($_DB_DATAOBJECT['RESULTS']) as $id) {
2196 $q[] = $_DB_DATAOBJECT['RESULTS'][$id]->query
;
2198 CRM_Core_Error
::debug('_DB_DATAOBJECT', $q);
2203 * Build a list of triggers via hook and add them to (err, reconcile them
2204 * with) the database.
2206 * @param string $tableName
2207 * the specific table requiring a rebuild; or NULL to rebuild all tables.
2208 * @param bool $force
2213 public static function triggerRebuild($tableName = NULL, $force = FALSE) {
2214 Civi
::service('sql_triggers')->rebuild($tableName, $force);
2218 * Because sql functions are sometimes lost, esp during db migration, we check here to avoid numerous support requests
2219 * @see http://issues.civicrm.org/jira/browse/CRM-13822
2220 * TODO: Alternative solutions might be
2221 * * Stop using functions and find another way to strip numeric characters from phones
2222 * * Give better error messages (currently a missing fn fatals with "unknown error")
2224 public static function checkSqlFunctionsExist() {
2225 if (!self
::$_checkedSqlFunctionsExist) {
2226 self
::$_checkedSqlFunctionsExist = TRUE;
2227 $dao = CRM_Core_DAO
::executeQuery("SHOW function status WHERE db = database() AND name = 'civicrm_strip_non_numeric'");
2228 if (!$dao->fetch()) {
2229 self
::triggerRebuild();
2235 * Wrapper function to drop triggers.
2237 * @param string $tableName
2238 * the specific table requiring a rebuild; or NULL to rebuild all tables.
2241 public static function dropTriggers($tableName = NULL) {
2242 Civi
::service('sql_triggers')->dropTriggers($tableName);
2246 * @param array $info
2247 * per hook_civicrm_triggerInfo.
2248 * @param string $onlyTableName
2249 * the specific table requiring a rebuild; or NULL to rebuild all tables.
2252 public static function createTriggers(&$info, $onlyTableName = NULL) {
2253 Civi
::service('sql_triggers')->createTriggers($info, $onlyTableName);
2257 * Given a list of fields, create a list of references.
2259 * @param string $className
2260 * BAO/DAO class name.
2261 * @return array<CRM_Core_Reference_Interface>
2263 public static function createReferenceColumns($className) {
2265 $fields = $className::fields();
2266 foreach ($fields as $field) {
2267 if (isset($field['pseudoconstant'], $field['pseudoconstant']['optionGroupName'])) {
2268 $result[] = new CRM_Core_Reference_OptionValue(
2269 $className::getTableName(),
2271 'civicrm_option_value',
2272 CRM_Utils_Array
::value('keyColumn', $field['pseudoconstant'], 'value'),
2273 $field['pseudoconstant']['optionGroupName']
2281 * Find all records which refer to this entity.
2284 * Array of objects referencing this
2286 public function findReferences() {
2287 $links = self
::getReferencesToTable(static::getTableName());
2290 foreach ($links as $refSpec) {
2291 /** @var $refSpec CRM_Core_Reference_Interface */
2292 $daoName = CRM_Core_DAO_AllCoreTables
::getClassForTable($refSpec->getReferenceTable());
2293 $result = $refSpec->findReferences($this);
2295 while ($result->fetch()) {
2296 $obj = new $daoName();
2297 $obj->id
= $result->id
;
2298 $occurrences[] = $obj;
2303 return $occurrences;
2308 * each item has keys:
2312 * - table: string|null SQL table name
2313 * - key: string|null SQL column name
2315 public function getReferenceCounts() {
2316 $links = self
::getReferencesToTable(static::getTableName());
2319 foreach ($links as $refSpec) {
2320 /** @var $refSpec CRM_Core_Reference_Interface */
2321 $count = $refSpec->getReferenceCount($this);
2322 if ($count['count'] != 0) {
2327 foreach (CRM_Core_Component
::getEnabledComponents() as $component) {
2328 /** @var $component CRM_Core_Component_Info */
2329 $counts = array_merge($counts, $component->getReferenceCounts($this));
2331 CRM_Utils_Hook
::referenceCounts($this, $counts);
2337 * List all tables which have hard foreign keys to this table.
2339 * For now, this returns a description of every entity_id/entity_table
2341 * TODO: filter dynamic entity references on the $tableName, based on
2342 * schema metadata in dynamicForeignKey which enumerates a restricted
2343 * set of possible entity_table's.
2345 * @param string $tableName
2346 * Table referred to.
2349 * structure of table and column, listing every table with a
2350 * foreign key reference to $tableName, and the column where the key appears.
2352 public static function getReferencesToTable($tableName) {
2354 foreach (CRM_Core_DAO_AllCoreTables
::getClasses() as $daoClassName) {
2355 $links = $daoClassName::getReferenceColumns();
2356 $daoTableName = $daoClassName::getTableName();
2358 foreach ($links as $refSpec) {
2359 /** @var $refSpec CRM_Core_Reference_Interface */
2360 if ($refSpec->matchesTargetTable($tableName)) {
2361 $refsFound[] = $refSpec;
2369 * Get all references to contact table.
2371 * This includes core tables, custom group tables, tables added by the merge
2372 * hook and the entity_tag table.
2374 * Refer to CRM-17454 for information on the danger of querying the information
2375 * schema to derive this.
2377 public static function getReferencesToContactTable() {
2378 if (isset(\Civi
::$statics[__CLASS__
]) && isset(\Civi
::$statics[__CLASS__
]['contact_references'])) {
2379 return \Civi
::$statics[__CLASS__
]['contact_references'];
2381 $contactReferences = [];
2382 $coreReferences = CRM_Core_DAO
::getReferencesToTable('civicrm_contact');
2383 foreach ($coreReferences as $coreReference) {
2384 if (!is_a($coreReference, 'CRM_Core_Reference_Dynamic')) {
2385 $contactReferences[$coreReference->getReferenceTable()][] = $coreReference->getReferenceKey();
2388 self
::appendCustomTablesExtendingContacts($contactReferences);
2389 self
::appendCustomContactReferenceFields($contactReferences);
2391 // FixME for time being adding below line statically as no Foreign key constraint defined for table 'civicrm_entity_tag'
2392 $contactReferences['civicrm_entity_tag'][] = 'entity_id';
2393 \Civi
::$statics[__CLASS__
]['contact_references'] = $contactReferences;
2394 return \Civi
::$statics[__CLASS__
]['contact_references'];
2398 * Add custom tables that extend contacts to the list of contact references.
2400 * CRM_Core_BAO_CustomGroup::getAllCustomGroupsByBaseEntity seems like a safe-ish
2401 * function to be sure all are retrieved & we don't miss subtypes or inactive or multiples
2402 * - the down side is it is not cached.
2404 * Further changes should be include tests in the CRM_Core_MergerTest class
2405 * to ensure that disabled, subtype, multiple etc groups are still captured.
2407 * @param array $cidRefs
2409 public static function appendCustomTablesExtendingContacts(&$cidRefs) {
2410 $customValueTables = CRM_Core_BAO_CustomGroup
::getAllCustomGroupsByBaseEntity('Contact');
2411 $customValueTables->find();
2412 while ($customValueTables->fetch()) {
2413 $cidRefs[$customValueTables->table_name
][] = 'entity_id';
2418 * Add custom ContactReference fields to the list of contact references
2420 * This includes active and inactive fields/groups
2422 * @param array $cidRefs
2424 * @throws \CiviCRM_API3_Exception
2426 public static function appendCustomContactReferenceFields(&$cidRefs) {
2427 $fields = civicrm_api3('CustomField', 'get', [
2428 'return' => ['column_name', 'custom_group_id.table_name'],
2429 'data_type' => 'ContactReference',
2431 foreach ($fields as $field) {
2432 $cidRefs[$field['custom_group_id.table_name']][] = $field['column_name'];
2437 * Lookup the value of a MySQL global configuration variable.
2439 * @param string $name
2440 * E.g. "thread_stack".
2441 * @param mixed $default
2444 public static function getGlobalSetting($name, $default = NULL) {
2445 // Alternatively, SELECT @@GLOBAL.thread_stack, but
2446 // that has been reported to fail under MySQL 5.0 for OS X
2447 $escapedName = self
::escapeString($name);
2448 $dao = CRM_Core_DAO
::executeQuery("SHOW VARIABLES LIKE '$escapedName'");
2449 if ($dao->fetch()) {
2458 * Update the fields array to also hold keys for pseudoconstant fields that relate to contained fields.
2460 * This is relevant where we want to offer both the ID field and the label field
2461 * as an option, e.g. search builder.
2463 * It is currently limited for optionGroupName & id+ name+ FK combos for purposes keeping the scope of the
2464 * change small, but is appropriate for other sorts of pseudoconstants.
2466 * @param array $fields
2468 public static function appendPseudoConstantsToFields(&$fields) {
2469 foreach ($fields as $field) {
2470 if (!empty($field['pseudoconstant'])) {
2471 $pseudoConstant = $field['pseudoconstant'];
2472 if (!empty($pseudoConstant['optionGroupName'])) {
2473 $fields[$pseudoConstant['optionGroupName']] = [
2474 'title' => CRM_Core_BAO_OptionGroup
::getTitleByName($pseudoConstant['optionGroupName']),
2475 'name' => $pseudoConstant['optionGroupName'],
2476 'data_type' => CRM_Utils_Type
::T_STRING
,
2477 'is_pseudofield_for' => $field['name'],
2480 // We restrict to id + name + FK as we are extending this a bit, but cautiously.
2482 !empty($field['FKClassName'])
2483 && CRM_Utils_Array
::value('keyColumn', $pseudoConstant) === 'id'
2484 && CRM_Utils_Array
::value('labelColumn', $pseudoConstant) === 'name'
2486 $pseudoFieldName = str_replace('_' . $pseudoConstant['keyColumn'], '', $field['name']);
2487 // This if is just an extra caution when adding change.
2488 if (!isset($fields[$pseudoFieldName])) {
2489 $daoName = $field['FKClassName'];
2490 $fkFields = $daoName::fields();
2491 foreach ($fkFields as $fkField) {
2492 if ($fkField['name'] === $pseudoConstant['labelColumn']) {
2493 $fields[$pseudoFieldName] = [
2494 'name' => $pseudoFieldName,
2495 'is_pseudofield_for' => $field['name'],
2496 'title' => $fkField['title'],
2497 'data_type' => $fkField['type'],
2498 'where' => $field['where'],
2509 * Get options for the called BAO object's field.
2511 * This function can be overridden by each BAO to add more logic related to context.
2512 * The overriding function will generally call the lower-level CRM_Core_PseudoConstant::get
2514 * @param string $fieldName
2515 * @param string $context
2516 * @see CRM_Core_DAO::buildOptionsContext
2517 * @param array $props
2518 * whatever is known about this bao object.
2520 * @return array|bool
2522 public static function buildOptions($fieldName, $context = NULL, $props = []) {
2523 // If a given bao does not override this function
2524 $baoName = get_called_class();
2525 return CRM_Core_PseudoConstant
::get($baoName, $fieldName, $props, $context);
2529 * Populate option labels for this object's fields.
2531 * @throws exception if called directly on the base class
2533 public function getOptionLabels() {
2534 $fields = $this->fields();
2535 if ($fields === NULL) {
2536 throw new Exception('Cannot call getOptionLabels on CRM_Core_DAO');
2538 foreach ($fields as $field) {
2539 $name = CRM_Utils_Array
::value('name', $field);
2540 if ($name && isset($this->$name)) {
2541 $label = CRM_Core_PseudoConstant
::getLabel(get_class($this), $name, $this->$name);
2542 if ($label !== FALSE) {
2543 // Append 'label' onto the field name
2544 $labelName = $name . '_label';
2545 $this->$labelName = $label;
2552 * Provides documentation and validation for the buildOptions $context param
2554 * @param string $context
2559 public static function buildOptionsContext($context = NULL) {
2561 'get' => "get: all options are returned, even if they are disabled; labels are translated.",
2562 'create' => "create: options are filtered appropriately for the object being created/updated; labels are translated.",
2563 'search' => "search: searchable options are returned; labels are translated.",
2564 'validate' => "validate: all options are returned, even if they are disabled; machine names are used in place of labels.",
2565 'abbreviate' => "abbreviate: enabled options are returned; labels are replaced with abbreviations.",
2566 'match' => "match: enabled options are returned using machine names as keys; labels are translated.",
2568 // Validation: enforce uniformity of this param
2569 if ($context !== NULL && !isset($contexts[$context])) {
2570 throw new Exception("'$context' is not a valid context for buildOptions.");
2576 * @param string $fieldName
2577 * @return bool|array
2579 public function getFieldSpec($fieldName) {
2580 $fields = $this->fields();
2581 $fieldKeys = $this->fieldKeys();
2583 // Support "unique names" as well as sql names
2584 $fieldKey = $fieldName;
2585 if (empty($fields[$fieldKey])) {
2586 $fieldKey = CRM_Utils_Array
::value($fieldName, $fieldKeys);
2588 // If neither worked then this field doesn't exist. Return false.
2589 if (empty($fields[$fieldKey])) {
2592 return $fields[$fieldKey];
2596 * Get SQL where clause for SQL filter syntax input parameters.
2598 * SQL version of api function to assign filters to the DAO based on the syntax
2599 * $field => array('IN' => array(4,6,9))
2601 * $field => array('LIKE' => array('%me%))
2604 * @param string $fieldName
2606 * @param array $filter
2607 * filter to be applied indexed by operator.
2608 * @param string $type
2609 * type of field (not actually used - nor in api @todo ).
2610 * @param string $alias
2611 * alternative field name ('as') @todo- not actually used.
2612 * @param bool $returnSanitisedArray
2613 * Return a sanitised array instead of a clause.
2614 * this is primarily so we can add filters @ the api level to the Query object based fields
2618 * @return NULL|string|array
2619 * a string is returned if $returnSanitisedArray is not set, otherwise and Array or NULL
2620 * depending on whether it is supported as yet
2622 public static function createSQLFilter($fieldName, $filter, $type = NULL, $alias = NULL, $returnSanitisedArray = FALSE) {
2623 foreach ($filter as $operator => $criteria) {
2624 if (in_array($operator, self
::acceptedSQLOperators(), TRUE)) {
2625 switch ($operator) {
2629 if (!$returnSanitisedArray) {
2630 return (sprintf('%s %s', $fieldName, $operator));
2633 return (sprintf('%s %s ', $fieldName, $operator));
2637 // ternary operators
2640 if ((empty($criteria[0]) && !in_array($criteria[0], ['0', 0]))||
(empty($criteria[1]) && !in_array($criteria[1], ['0', 0]))) {
2641 throw new Exception("invalid criteria for $operator");
2643 if (!$returnSanitisedArray) {
2644 return (sprintf('%s ' . $operator . ' "%s" AND "%s"', $fieldName, CRM_Core_DAO
::escapeString($criteria[0]), CRM_Core_DAO
::escapeString($criteria[1])));
2647 // not yet implemented (tests required to implement)
2655 if (empty($criteria)) {
2656 throw new Exception("invalid criteria for $operator");
2658 $escapedCriteria = array_map([
2662 if (!$returnSanitisedArray) {
2663 return (sprintf('%s %s ("%s")', $fieldName, $operator, implode('", "', $escapedCriteria)));
2665 return $escapedCriteria;
2670 if (!$returnSanitisedArray) {
2671 return (sprintf('%s %s "%s"', $fieldName, $operator, CRM_Core_DAO
::escapeString($criteria)));
2674 // not yet implemented (tests required to implement)
2683 * @see http://issues.civicrm.org/jira/browse/CRM-9150
2684 * support for other syntaxes is discussed in ticket but being put off for now
2687 public static function acceptedSQLOperators() {
2708 * SQL has a limit of 64 characters on various names:
2709 * table name, trigger name, column name ...
2711 * For custom groups and fields we generated names from user entered input
2712 * which can be longer than this length, this function helps with creating
2713 * strings that meet various criteria.
2715 * @param string $string
2716 * The string to be shortened.
2717 * @param int $length
2718 * The max length of the string.
2720 * @param bool $makeRandom
2724 public static function shortenSQLName($string, $length = 60, $makeRandom = FALSE) {
2725 // early return for strings that meet the requirements
2726 if (strlen($string) <= $length) {
2730 // easy return for calls that dont need a randomized uniq string
2732 return substr($string, 0, $length);
2735 // the string is longer than the length and we need a uniq string
2736 // for the same tablename we need the same uniq string every time
2737 // hence we use md5 on the string, which is not random
2738 // we'll append 8 characters to the end of the tableName
2739 $md5string = substr(md5($string), 0, 8);
2740 return substr($string, 0, $length - 8) . "_{$md5string}";
2744 * https://issues.civicrm.org/jira/browse/CRM-17748
2745 * Sets the internal options to be used on a query
2747 * @param array $options
2750 public function setOptions($options) {
2751 if (is_array($options)) {
2752 $this->_options
= $options;
2757 * https://issues.civicrm.org/jira/browse/CRM-17748
2758 * wrapper to pass internal DAO options down to DB_mysql/DB_Common level
2760 * @param array $options
2763 protected function _setDBOptions($options) {
2764 global $_DB_DATAOBJECT;
2766 if (is_array($options) && count($options)) {
2767 $conn = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5
];
2768 foreach ($options as $option_name => $option_value) {
2769 $conn->setOption($option_name, $option_value);
2776 * @param array $params
2778 public function setApiFilter(&$params) {
2782 * Generates acl clauses suitable for adding to WHERE or ON when doing an api.get for this entity
2784 * Return format is in the form of fieldname => clauses starting with an operator. e.g.:
2787 * 'location_type_id' => array('IS NOT NULL', 'IN (1,2,3)')
2791 * Note that all array keys must be actual field names in this entity. Use subqueries to filter on other tables e.g. custom values.
2795 public function addSelectWhereClause() {
2797 $fields = $this->fields();
2798 foreach ($fields as $fieldName => $field) {
2799 // Clause for contact-related entities like Email, Relationship, etc.
2800 if (strpos($fieldName, 'contact_id') === 0 && CRM_Utils_Array
::value('FKClassName', $field) == 'CRM_Contact_DAO_Contact') {
2801 $clauses[$fieldName] = CRM_Utils_SQL
::mergeSubquery('Contact');
2803 // Clause for an entity_table/entity_id combo
2804 if ($fieldName == 'entity_id' && isset($fields['entity_table'])) {
2805 $relatedClauses = [];
2806 $relatedEntities = $this->buildOptions('entity_table', 'get');
2807 foreach ((array) $relatedEntities as $table => $ent) {
2809 $ent = CRM_Core_DAO_AllCoreTables
::getBriefName(CRM_Core_DAO_AllCoreTables
::getClassForTable($table));
2810 $subquery = CRM_Utils_SQL
::mergeSubquery($ent);
2812 $relatedClauses[] = "(entity_table = '$table' AND entity_id " . implode(' AND entity_id ', $subquery) . ")";
2815 $relatedClauses[] = "(entity_table = '$table')";
2819 if ($relatedClauses) {
2820 $clauses['id'] = 'IN (SELECT id FROM `' . $this->tableName() . '` WHERE (' . implode(') OR (', $relatedClauses) . '))';
2824 CRM_Utils_Hook
::selectWhereClause($this, $clauses);
2829 * This returns the final permissioned query string for this entity
2831 * With acls from related entities + additional clauses from hook_civicrm_selectWhereClause
2833 * @param string $tableAlias
2836 public static function getSelectWhereClause($tableAlias = NULL) {
2837 $bao = new static();
2838 if ($tableAlias === NULL) {
2839 $tableAlias = $bao->tableName();
2842 foreach ((array) $bao->addSelectWhereClause() as $field => $vals) {
2843 $clauses[$field] = NULL;
2845 $clauses[$field] = "(`$tableAlias`.`$field` IS NULL OR (`$tableAlias`.`$field` " . implode(" AND `$tableAlias`.`$field` ", (array) $vals) . '))';
2852 * ensure database name is 'safe', i.e. only contains word characters (includes underscores)
2853 * and dashes, and contains at least one [a-z] case insenstive.
2859 public static function requireSafeDBName($database) {
2862 "/^[\w\-]*[a-z]+[\w\-]*$/i",
2866 if (empty($matches)) {
2873 * Transform an array to a serialized string for database storage.
2875 * @param array|null $value
2876 * @param int $serializationType
2877 * @return string|null
2879 * @throws \Exception
2881 public static function serializeField($value, $serializationType) {
2882 if ($value === NULL) {
2885 switch ($serializationType) {
2886 case self
::SERIALIZE_SEPARATOR_BOOKEND
:
2887 return $value === [] ?
'' : CRM_Utils_Array
::implodePadded($value);
2889 case self
::SERIALIZE_SEPARATOR_TRIMMED
:
2890 return is_array($value) ?
implode(self
::VALUE_SEPARATOR
, $value) : $value;
2892 case self
::SERIALIZE_JSON
:
2893 return is_array($value) ?
json_encode($value) : $value;
2895 case self
::SERIALIZE_PHP
:
2896 return is_array($value) ?
serialize($value) : $value;
2898 case self
::SERIALIZE_COMMA
:
2899 return is_array($value) ?
implode(',', $value) : $value;
2902 throw new Exception('Unknown serialization method for field.');
2907 * Transform a serialized string from the database into an array.
2909 * @param string|null $value
2910 * @param $serializationType
2912 * @return array|null
2913 * @throws CRM_Core_Exception
2915 public static function unSerializeField($value, $serializationType) {
2916 if ($value === NULL) {
2919 if ($value === '') {
2922 switch ($serializationType) {
2923 case self
::SERIALIZE_SEPARATOR_BOOKEND
:
2924 return (array) CRM_Utils_Array
::explodePadded($value);
2926 case self
::SERIALIZE_SEPARATOR_TRIMMED
:
2927 return explode(self
::VALUE_SEPARATOR
, trim($value));
2929 case self
::SERIALIZE_JSON
:
2930 return strlen($value) ?
json_decode($value, TRUE) : [];
2932 case self
::SERIALIZE_PHP
:
2933 return strlen($value) ?
unserialize($value, ['allowed_classes' => FALSE]) : [];
2935 case self
::SERIALIZE_COMMA
:
2936 return explode(',', trim(str_replace(', ', '', $value)));
2939 throw new CRM_Core_Exception('Unknown serialization method for field.');
2946 public static function getEntityRefFilters() {
2951 * Get exportable fields with pseudoconstants rendered as an extra field.
2953 * @param string $baoClass
2957 public static function getExportableFieldsWithPseudoConstants($baoClass) {
2958 if (method_exists($baoClass, 'exportableFields')) {
2959 $fields = $baoClass::exportableFields();
2962 $fields = $baoClass::export();
2964 CRM_Core_DAO
::appendPseudoConstantsToFields($fields);
2969 * Remove item from static cache during update/delete operations
2971 private function clearDbColumnValueCache() {
2972 $daoName = get_class($this);
2973 while (strpos($daoName, '_BAO_') !== FALSE) {
2974 $daoName = get_parent_class($daoName);
2976 if (isset($this->id
)) {
2977 unset(self
::$_dbColumnValueCache[$daoName]['id'][$this->id
]);
2979 if (isset($this->name
)) {
2980 unset(self
::$_dbColumnValueCache[$daoName]['name'][$this->name
]);