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 $options['quote_identifiers'] = TRUE;
148 if (defined('CIVICRM_DAO_DEBUG')) {
149 self
::DebugLevel(CIVICRM_DAO_DEBUG
);
151 $factory = new CRM_Contact_DAO_Factory();
152 CRM_Core_DAO
::setFactory($factory);
153 $currentModes = CRM_Utils_SQL
::getSqlModes();
154 if (CRM_Utils_Constant
::value('CIVICRM_MYSQL_STRICT', CRM_Utils_System
::isDevelopment())) {
155 if (CRM_Utils_SQL
::supportsFullGroupBy() && !in_array('ONLY_FULL_GROUP_BY', $currentModes) && CRM_Utils_SQL
::isGroupByModeInDefault()) {
156 $currentModes[] = 'ONLY_FULL_GROUP_BY';
158 if (!in_array('STRICT_TRANS_TABLES', $currentModes)) {
159 $currentModes = array_merge(['STRICT_TRANS_TABLES'], $currentModes);
161 CRM_Core_DAO
::executeQuery("SET SESSION sql_mode = %1", [1 => [implode(',', $currentModes), 'String']]);
163 CRM_Core_DAO
::executeQuery('SET NAMES utf8');
164 CRM_Core_DAO
::executeQuery('SET @uniqueID = %1', [1 => [CRM_Utils_Request
::id(), 'String']]);
170 public static function getConnection() {
171 global $_DB_DATAOBJECT;
172 $dao = new CRM_Core_DAO();
173 return $_DB_DATAOBJECT['CONNECTIONS'][$dao->_database_dsn_md5
];
177 * Disables usage of the ONLY_FULL_GROUP_BY Mode if necessary
179 public static function disableFullGroupByMode() {
180 $currentModes = CRM_Utils_SQL
::getSqlModes();
181 if (in_array('ONLY_FULL_GROUP_BY', $currentModes) && CRM_Utils_SQL
::isGroupByModeInDefault()) {
182 $key = array_search('ONLY_FULL_GROUP_BY', $currentModes);
183 unset($currentModes[$key]);
184 CRM_Core_DAO
::executeQuery("SET SESSION sql_mode = %1", [1 => [implode(',', $currentModes), 'String']]);
189 * Re-enables ONLY_FULL_GROUP_BY sql_mode as necessary..
191 public static function reenableFullGroupByMode() {
192 $currentModes = CRM_Utils_SQL
::getSqlModes();
193 if (!in_array('ONLY_FULL_GROUP_BY', $currentModes) && CRM_Utils_SQL
::isGroupByModeInDefault()) {
194 $currentModes[] = 'ONLY_FULL_GROUP_BY';
195 CRM_Core_DAO
::executeQuery("SET SESSION sql_mode = %1", [1 => [implode(',', $currentModes), 'String']]);
200 * @param string $fieldName
202 * @param array $params
204 protected function assignTestFK($fieldName, $fieldDef, $params) {
205 $required = CRM_Utils_Array
::value('required', $fieldDef);
206 $FKClassName = CRM_Utils_Array
::value('FKClassName', $fieldDef);
207 $dbName = $fieldDef['name'];
208 $daoName = str_replace('_BAO_', '_DAO_', get_class($this));
210 // skip the FK if it is not required
211 // if it's contact id we should create even if not required
212 // we'll have a go @ fetching first though
213 // we WILL create campaigns though for so tests with a campaign pseudoconstant will complete
214 if ($FKClassName === 'CRM_Campaign_DAO_Campaign' && $daoName != $FKClassName) {
217 if (!$required && $dbName != 'contact_id') {
218 $fkDAO = new $FKClassName();
219 if ($fkDAO->find(TRUE)) {
220 $this->$dbName = $fkDAO->id
;
224 elseif (in_array($FKClassName, CRM_Core_DAO
::$_testEntitiesToSkip)) {
225 $depObject = new $FKClassName();
226 $depObject->find(TRUE);
227 $this->$dbName = $depObject->id
;
229 elseif ($daoName == 'CRM_Member_DAO_MembershipType' && $fieldName == 'member_of_contact_id') {
230 // FIXME: the fields() metadata is not specific enough
231 $depObject = CRM_Core_DAO
::createTestObject($FKClassName, ['contact_type' => 'Organization']);
232 $this->$dbName = $depObject->id
;
235 //if it is required we need to generate the dependency object first
236 $depObject = CRM_Core_DAO
::createTestObject($FKClassName, CRM_Utils_Array
::value($dbName, $params, 1));
237 $this->$dbName = $depObject->id
;
242 * Generate and assign an arbitrary value to a field of a test object.
244 * @param string $fieldName
245 * @param array $fieldDef
246 * @param int $counter
247 * The globally-unique ID of the test object.
249 * @throws \CRM_Core_Exception
251 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
252 $dbName = $fieldDef['name'];
253 $daoName = get_class($this);
256 if (!$handled && $dbName == 'contact_sub_type') {
257 //coming up with a rule to set this is too complex let's not set it
261 // Pick an option value if needed
262 if (!$handled && $fieldDef['type'] !== CRM_Utils_Type
::T_BOOLEAN
) {
263 $options = $daoName::buildOptions($dbName, 'create');
265 $this->$dbName = key($options);
271 switch ($fieldDef['type']) {
272 case CRM_Utils_Type
::T_INT
:
273 case CRM_Utils_Type
::T_FLOAT
:
274 case CRM_Utils_Type
::T_MONEY
:
275 if (isset($fieldDef['precision'])) {
276 // $object->$dbName = CRM_Utils_Number::createRandomDecimal($value['precision']);
277 $this->$dbName = CRM_Utils_Number
::createTruncatedDecimal($counter, $fieldDef['precision']);
280 $this->$dbName = $counter;
284 case CRM_Utils_Type
::T_BOOLEAN
:
285 if (isset($fieldDef['default'])) {
286 $this->$dbName = $fieldDef['default'];
288 elseif ($fieldDef['name'] == 'is_deleted' ||
$fieldDef['name'] == 'is_test') {
296 case CRM_Utils_Type
::T_DATE
:
297 case CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
:
298 $this->$dbName = '19700101';
299 if ($dbName == 'end_date') {
300 // put this in the future
301 $this->$dbName = '20200101';
305 case CRM_Utils_Type
::T_TIMESTAMP
:
306 $this->$dbName = '19700201000000';
309 case CRM_Utils_Type
::T_TIME
:
310 throw new CRM_Core_Exception('T_TIME shouldn\'t be used.');
312 case CRM_Utils_Type
::T_CCNUM
:
313 $this->$dbName = '4111 1111 1111 1111';
316 case CRM_Utils_Type
::T_URL
:
317 $this->$dbName = 'http://www.civicrm.org';
320 case CRM_Utils_Type
::T_STRING
:
321 case CRM_Utils_Type
::T_BLOB
:
322 case CRM_Utils_Type
::T_MEDIUMBLOB
:
323 case CRM_Utils_Type
::T_TEXT
:
324 case CRM_Utils_Type
::T_LONGTEXT
:
325 case CRM_Utils_Type
::T_EMAIL
:
327 // WAS: if (isset($value['enumValues'])) {
328 // TODO: see if this works with all pseudoconstants
329 if (isset($fieldDef['pseudoconstant'], $fieldDef['pseudoconstant']['callback'])) {
330 if (isset($fieldDef['default'])) {
331 $this->$dbName = $fieldDef['default'];
334 $options = CRM_Core_PseudoConstant
::get($daoName, $fieldName);
335 if (is_array($options)) {
336 $this->$dbName = $options[0];
339 $defaultValues = explode(',', $options);
340 $this->$dbName = $defaultValues[0];
345 $this->$dbName = $dbName . '_' . $counter;
346 $maxlength = CRM_Utils_Array
::value('maxlength', $fieldDef);
347 if ($maxlength > 0 && strlen($this->$dbName) > $maxlength) {
348 $this->$dbName = substr($this->$dbName, 0, $fieldDef['maxlength']);
356 * Reset the DAO object.
358 * DAO is kinda crappy in that there is an unwritten rule of one query per DAO.
360 * We attempt to get around this crappy restriction by resetting some of DAO's internal fields. Use this with caution
362 public function reset() {
364 foreach (array_keys($this->table()) as $field) {
365 unset($this->$field);
369 * reset the various DB_DAO structures manually
378 * @param string $tableName
382 public static function getLocaleTableName($tableName) {
385 $tables = CRM_Core_I18n_Schema
::schemaStructureTables();
386 if (in_array($tableName, $tables)) {
387 return $tableName . $dbLocale;
394 * Execute a query by the current DAO, localizing it along the way (if needed).
396 * @param string $query
397 * The SQL query for execution.
398 * @param bool $i18nRewrite
399 * Whether to rewrite the query.
402 * the current DAO object after the query execution
404 public function query($query, $i18nRewrite = TRUE) {
405 // rewrite queries that should use $dbLocale-based views for multi-language installs
406 global $dbLocale, $_DB_DATAOBJECT;
408 if (empty($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5
])) {
409 // Will force connection to be populated per CRM-20541.
413 $conn = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5
];
414 $orig_options = $conn->options
;
415 $this->_setDBOptions($this->_options
);
417 if ($i18nRewrite and $dbLocale) {
418 $query = CRM_Core_I18n_Schema
::rewriteQuery($query);
421 $ret = parent
::query($query);
423 $this->_setDBOptions($orig_options);
428 * Static function to set the factory instance for this class.
430 * @param object $factory
431 * The factory application object.
433 public static function setFactory(&$factory) {
434 self
::$_factory = &$factory;
438 * Factory method to instantiate a new object from a table name.
440 * @param string $table
441 * @return \DataObject|\PEAR_Error
443 public function factory($table = '') {
444 if (!isset(self
::$_factory)) {
445 return parent
::factory($table);
448 return self
::$_factory->create($table);
452 * Initialization for all DAO objects. Since we access DB_DO programatically
453 * we need to set the links manually.
455 public function initialize() {
457 if (empty(Civi
::$statics[__CLASS__
]['init'])) {
458 // CRM_Core_DAO::init() must be called before CRM_Core_DAO->initialize().
459 // This occurs very early in bootstrap - error handlers may not be wired up.
460 echo "Inconsistent system initialization sequence. Premature access of (" . get_class($this) . ")";
461 CRM_Utils_System
::civiExit();
466 * Defines the default key as 'id'.
470 public function keys() {
479 * Tells DB_DataObject which keys use autoincrement.
480 * 'id' is autoincrementing by default.
485 public function sequenceKey() {
486 static $sequenceKeys;
487 if (!isset($sequenceKeys)) {
488 $sequenceKeys = ['id', TRUE];
490 return $sequenceKeys;
494 * Returns list of FK relationships.
498 * Array of CRM_Core_Reference_Interface
500 public static function getReferenceColumns() {
505 * Returns all the column names of this table.
510 public static function &fields() {
516 * Get/set an associative array of table columns
521 public function table() {
522 $fields = $this->fields();
526 foreach ($fields as $name => $value) {
527 $table[$value['name']] = $value['type'];
528 if (!empty($value['required'])) {
529 $table[$value['name']] +
= self
::DB_DAO_NOTNULL
;
542 * @return CRM_Core_DAO
544 public function save($hook = TRUE) {
545 if (!empty($this->id
)) {
549 $event = new \Civi\Core\DAO\Event\
PostUpdate($this);
550 \Civi
::service('dispatcher')->dispatch("civi.dao.postUpdate", $event);
552 $this->clearDbColumnValueCache();
558 $event = new \Civi\Core\DAO\Event\
PostUpdate($this);
559 \Civi
::service('dispatcher')->dispatch("civi.dao.postInsert", $event);
565 CRM_Utils_Hook
::postSave($this);
572 * Deletes items from table which match current objects variables.
574 * Returns the true on success
578 * Designed to be extended
580 * $object = new mytable();
582 * echo $object->delete(); // builds a conditon
584 * $object = new mytable();
585 * $object->whereAdd('age > 12');
587 * $object->orderBy('age DESC');
588 * $object->delete(true); // dont use object vars, use the conditions, limit and order.
590 * @param bool $useWhere (optional) If DB_DATAOBJECT_WHEREADD_ONLY is passed in then
591 * we will build the condition only using the whereAdd's. Default is to
592 * build the condition only using the object parameters.
594 * * @return mixed Int (No. of rows affected) on success, false on failure, 0 on no data affected
596 public function delete($useWhere = FALSE) {
597 $preEvent = new \Civi\Core\DAO\Event\
PreDelete($this);
598 \Civi
::service('dispatcher')->dispatch("civi.dao.preDelete", $preEvent);
600 $result = parent
::delete($useWhere);
602 $event = new \Civi\Core\DAO\Event\
PostDelete($this, $result);
603 \Civi
::service('dispatcher')->dispatch("civi.dao.postDelete", $event);
606 $this->clearDbColumnValueCache();
612 * @param bool $created
614 public function log($created = FALSE) {
617 if (!$this->getLog()) {
622 $session = CRM_Core_Session
::singleton();
623 $cid = $session->get('userID');
626 // return is we dont have handle to FK
631 $dao = new CRM_Core_DAO_Log();
632 $dao->entity_table
= $this->getTableName();
633 $dao->entity_id
= $this->id
;
634 $dao->modified_id
= $cid;
635 $dao->modified_date
= date("YmdHis");
640 * Given an associative array of name/value pairs, extract all the values
641 * that belong to this object and initialize the object with said values
643 * @param array $params
644 * Array of name/value pairs to save.
647 * Did we copy all null values into the object
649 public function copyValues($params) {
651 foreach ($this->fields() as $uniqueName => $field) {
652 $dbName = $field['name'];
653 if (array_key_exists($dbName, $params)) {
654 $value = $params[$dbName];
657 elseif (array_key_exists($uniqueName, $params)) {
658 $value = $params[$uniqueName];
665 // if there is no value then make the variable NULL
668 $this->$dbName = 'null';
670 elseif (is_array($value) && !empty($field['serialize'])) {
671 $this->$dbName = CRM_Core_DAO
::serializeField($value, $field['serialize']);
675 $maxLength = CRM_Utils_Array
::value('maxlength', $field);
676 if (!is_array($value) && $maxLength && mb_strlen($value) > $maxLength && empty($field['pseudoconstant'])) {
677 Civi
::log()->warning(ts('A string for field $dbName has been truncated. The original string was %1', [CRM_Utils_Type
::escape($value, 'String')]));
678 // The string is too long - what to do what to do? Well losing data is generally bad so lets' truncate
679 $value = CRM_Utils_String
::ellipsify($value, $maxLength);
681 $this->$dbName = $value;
690 * Store all the values from this object in an associative array
691 * this is a destructive store, calling function is responsible
692 * for keeping sanity of id's.
694 * @param object $object
695 * The object that we are extracting data from.
696 * @param array $values
697 * (reference ) associative array of name/value pairs.
699 public static function storeValues(&$object, &$values) {
700 $fields = $object->fields();
701 foreach ($fields as $name => $value) {
702 $dbName = $value['name'];
703 if (isset($object->$dbName) && $object->$dbName !== 'null') {
704 $values[$dbName] = $object->$dbName;
705 if ($name != $dbName) {
706 $values[$name] = $object->$dbName;
713 * Create an attribute for this specific field. We only do this for strings and text
715 * @param array $field
716 * The field under task.
719 * the attributes for the object
721 public static function makeAttribute($field) {
723 if (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_STRING
) {
724 $maxLength = CRM_Utils_Array
::value('maxlength', $field);
725 $size = CRM_Utils_Array
::value('size', $field);
726 if ($maxLength ||
$size) {
729 $attributes['maxlength'] = $maxLength;
732 $attributes['size'] = $size;
737 elseif (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_TEXT
) {
738 $rows = CRM_Utils_Array
::value('rows', $field);
742 $cols = CRM_Utils_Array
::value('cols', $field);
748 $attributes['rows'] = $rows;
749 $attributes['cols'] = $cols;
752 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
) {
753 $attributes['size'] = 6;
754 $attributes['maxlength'] = 14;
762 * Get the size and maxLength attributes for this text field.
763 * (or for all text fields) in the DAO object.
765 * @param string $class
767 * @param string $fieldName
768 * Field that i'm interested in or null if.
769 * you want the attributes for all DAO text fields
772 * assoc array of name => attribute pairs
774 public static function getAttribute($class, $fieldName = NULL) {
775 $object = new $class();
776 $fields = $object->fields();
777 if ($fieldName != NULL) {
778 $field = CRM_Utils_Array
::value($fieldName, $fields);
779 return self
::makeAttribute($field);
783 foreach ($fields as $name => $field) {
784 $attribute = self
::makeAttribute($field);
786 $attributes[$name] = $attribute;
790 if (!empty($attributes)) {
798 * Check if there is a record with the same name in the db.
800 * @param string $value
801 * The value of the field we are checking.
802 * @param string $daoName
803 * The dao object name.
804 * @param string $daoID
805 * The id of the object being updated. u can change your name.
806 * as long as there is no conflict
807 * @param string $fieldName
808 * The name of the field in the DAO.
810 * @param string $domainID
811 * The id of the domain. Object exists only for the given domain.
814 * true if object exists
816 public static function objectExists($value, $daoName, $daoID, $fieldName = 'name', $domainID = NULL) {
817 $object = new $daoName();
818 $object->$fieldName = $value;
820 $object->domain_id
= $domainID;
823 if ($object->find(TRUE)) {
824 return ($daoID && $object->id
== $daoID) ?
TRUE : FALSE;
832 * Check if there is a given column in a specific table.
835 * @see CRM_Core_BAO_SchemaHandler::checkIfFieldExists
837 * @param string $tableName
838 * @param string $columnName
839 * @param bool $i18nRewrite
840 * Whether to rewrite the query on multilingual setups.
843 * true if exists, else false
845 public static function checkFieldExists($tableName, $columnName, $i18nRewrite = TRUE) {
846 return CRM_Core_BAO_SchemaHandler
::checkIfFieldExists($tableName, $columnName, $i18nRewrite);
850 * Scans all the tables using a slow query and table name.
854 public static function getTableNames() {
855 $dao = CRM_Core_DAO
::executeQuery(
857 FROM information_schema.TABLES
858 WHERE TABLE_SCHEMA = '" . CRM_Core_DAO
::getDatabaseName() . "'
859 AND TABLE_NAME LIKE 'civicrm_%'
860 AND TABLE_NAME NOT LIKE 'civicrm_import_job_%'
861 AND TABLE_NAME NOT LIKE '%_temp%'
864 while ($dao->fetch()) {
865 $values[] = $dao->TABLE_NAME
;
871 * @param int $maxTablesToCheck
875 public static function isDBMyISAM($maxTablesToCheck = 10) {
876 return CRM_Core_DAO
::singleValueQuery(
878 FROM information_schema.TABLES
879 WHERE ENGINE = 'MyISAM'
880 AND TABLE_SCHEMA = '" . CRM_Core_DAO
::getDatabaseName() . "'
881 AND TABLE_NAME LIKE 'civicrm_%'
882 AND TABLE_NAME NOT LIKE 'civicrm_import_job_%'
883 AND TABLE_NAME NOT LIKE '%_temp%'
884 AND TABLE_NAME NOT LIKE 'civicrm_tmp_%'
889 * Get the name of the CiviCRM database.
893 public static function getDatabaseName() {
894 $daoObj = new CRM_Core_DAO();
895 return $daoObj->database();
899 * Checks if a constraint exists for a specified table.
901 * @param string $tableName
902 * @param string $constraint
905 * true if constraint exists, false otherwise
907 * @throws \CRM_Core_Exception
909 public static function checkConstraintExists($tableName, $constraint) {
912 if (!array_key_exists($tableName, $show)) {
913 $query = "SHOW CREATE TABLE $tableName";
914 $dao = CRM_Core_DAO
::executeQuery($query, [], TRUE, NULL, FALSE, FALSE);
916 if (!$dao->fetch()) {
917 throw new CRM_Core_Exception('query failed');
920 $show[$tableName] = $dao->Create_Table
;
923 return preg_match("/\b$constraint\b/i", $show[$tableName]) ?
TRUE : FALSE;
927 * Checks if CONSTRAINT keyword exists for a specified table.
929 * @param array $tables
931 * @throws CRM_Core_Exception
934 * true if CONSTRAINT keyword exists, false otherwise
936 public static function schemaRequiresRebuilding($tables = ["civicrm_contact"]) {
938 foreach ($tables as $tableName) {
939 if (!array_key_exists($tableName, $show)) {
940 $query = "SHOW CREATE TABLE $tableName";
941 $dao = CRM_Core_DAO
::executeQuery($query, [], TRUE, NULL, FALSE, FALSE);
943 if (!$dao->fetch()) {
944 throw new CRM_Core_Exception('Show create table failed.');
947 $show[$tableName] = $dao->Create_Table
;
950 $result = preg_match("/\bCONSTRAINT\b\s/i", $show[$tableName]) ?
TRUE : FALSE;
951 if ($result == TRUE) {
962 * Checks if the FK constraint name is in the format 'FK_tableName_columnName'
963 * for a specified column of a table.
965 * @param string $tableName
966 * @param string $columnName
969 * true if in format, false otherwise
971 * @throws \CRM_Core_Exception
973 public static function checkFKConstraintInFormat($tableName, $columnName) {
976 if (!array_key_exists($tableName, $show)) {
977 $query = "SHOW CREATE TABLE $tableName";
978 $dao = CRM_Core_DAO
::executeQuery($query);
980 if (!$dao->fetch()) {
981 throw new CRM_Core_Exception('query failed');
984 $show[$tableName] = $dao->Create_Table
;
986 $constraint = "`FK_{$tableName}_{$columnName}`";
987 $pattern = "/\bCONSTRAINT\b\s+%s\s+\bFOREIGN\s+KEY\b\s/i";
988 return preg_match(sprintf($pattern, $constraint), $show[$tableName]) ?
TRUE : FALSE;
992 * Check whether a specific column in a specific table has always the same value.
994 * @param string $tableName
995 * @param string $columnName
996 * @param string $columnValue
999 * true if the value is always $columnValue, false otherwise
1001 public static function checkFieldHasAlwaysValue($tableName, $columnName, $columnValue) {
1002 $query = "SELECT * FROM $tableName WHERE $columnName != '$columnValue'";
1003 $dao = CRM_Core_DAO
::executeQuery($query);
1004 $result = $dao->fetch() ?
FALSE : TRUE;
1009 * Check whether a specific column in a specific table is always NULL.
1011 * @param string $tableName
1012 * @param string $columnName
1015 * true if if the value is always NULL, false otherwise
1017 public static function checkFieldIsAlwaysNull($tableName, $columnName) {
1018 $query = "SELECT * FROM $tableName WHERE $columnName IS NOT NULL";
1019 $dao = CRM_Core_DAO
::executeQuery($query);
1020 $result = $dao->fetch() ?
FALSE : TRUE;
1025 * Check if there is a given table in the database.
1027 * @param string $tableName
1030 * true if exists, else false
1032 public static function checkTableExists($tableName) {
1037 $params = [1 => [$tableName, 'String']];
1039 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1040 $result = $dao->fetch() ?
TRUE : FALSE;
1045 * Check if a given table has data.
1047 * @param string $tableName
1049 * TRUE if $tableName has at least one record.
1051 public static function checkTableHasData($tableName) {
1052 $c = CRM_Core_DAO
::singleValueQuery(sprintf('SELECT count(*) c FROM `%s`', $tableName));
1061 public function checkVersion($version) {
1066 $dbVersion = CRM_Core_DAO
::singleValueQuery($query);
1067 return trim($version) == trim($dbVersion) ?
TRUE : FALSE;
1071 * Find a DAO object for the given ID and return it.
1074 * Id of the DAO object being searched for.
1076 * @return CRM_Core_DAO
1077 * Object of the type of the class that called this function.
1081 public static function findById($id) {
1082 $object = new static();
1084 if (!$object->find(TRUE)) {
1085 throw new Exception("Unable to find a " . get_called_class() . " with id {$id}.");
1091 * Returns all results as array-encoded records.
1095 public function fetchAll($k = FALSE, $v = FALSE, $method = FALSE) {
1097 while ($this->fetch()) {
1098 $result[] = $this->toArray();
1104 * Return the results as PHP generator.
1106 * @param string $type
1107 * Whether the generator yields 'dao' objects or 'array's.
1109 public function fetchGenerator($type = 'dao') {
1110 while ($this->fetch()) {
1117 yield
$this->toArray();
1121 throw new \
RuntimeException("Invalid record type ($type)");
1127 * Returns a singular value.
1129 * @return mixed|NULL
1131 public function fetchValue() {
1132 $result = $this->getDatabaseResult();
1133 $row = $result->fetchRow();
1143 * Get all the result records as mapping between columns.
1145 * @param string $keyColumn
1147 * @param string $valueColumn
1150 * Ex: ["foo" => "The Foo Bar", "baz" => "The Baz Qux"]
1152 public function fetchMap($keyColumn, $valueColumn) {
1154 while ($this->fetch()) {
1155 $result[$this->{$keyColumn}] = $this->{$valueColumn};
1161 * Given a DAO name, a column name and a column value, find the record and GET the value of another column in that record
1163 * @param string $daoName
1164 * Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact).
1165 * @param int $searchValue
1166 * Value of the column you want to search by.
1167 * @param string $returnColumn
1168 * Name of the column you want to GET the value of.
1169 * @param string $searchColumn
1170 * Name of the column you want to search by.
1171 * @param bool $force
1172 * Skip use of the cache.
1174 * @return string|int|null
1175 * Value of $returnColumn in the retrieved record
1177 * @throws \CRM_Core_Exception
1179 public static function getFieldValue($daoName, $searchValue, $returnColumn = 'name', $searchColumn = 'id', $force = FALSE) {
1181 empty($searchValue) ||
1182 trim(strtolower($searchValue)) == 'null'
1184 // adding this here since developers forget to check for an id
1185 // or for the 'null' (which is a bad DAO kludge)
1186 // and hence we get the first value in the db
1187 throw new CRM_Core_Exception('getFieldValue failed');
1190 self
::$_dbColumnValueCache = self
::$_dbColumnValueCache ??
[];
1192 while (strpos($daoName, '_BAO_') !== FALSE) {
1193 $daoName = get_parent_class($daoName);
1197 empty(self
::$_dbColumnValueCache[$daoName][$searchColumn][$searchValue]) ||
1198 !array_key_exists($returnColumn, self
::$_dbColumnValueCache[$daoName][$searchColumn][$searchValue])
1200 $object = new $daoName();
1201 $object->$searchColumn = $searchValue;
1202 $object->selectAdd();
1203 $object->selectAdd($returnColumn);
1206 if ($object->find(TRUE)) {
1207 $result = $object->$returnColumn;
1210 self
::$_dbColumnValueCache[$daoName][$searchColumn][$searchValue][$returnColumn] = $result;
1212 return self
::$_dbColumnValueCache[$daoName][$searchColumn][$searchValue][$returnColumn];
1216 * Given a DAO name, a column name and a column value, find the record and SET the value of another column in that record
1218 * @param string $daoName
1219 * Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact).
1220 * @param int $searchValue
1221 * Value of the column you want to search by.
1222 * @param string $setColumn
1223 * Name of the column you want to SET the value of.
1224 * @param string $setValue
1225 * SET the setColumn to this value.
1226 * @param string $searchColumn
1227 * Name of the column you want to search by.
1230 * true if we found and updated the object, else false
1232 public static function setFieldValue($daoName, $searchValue, $setColumn, $setValue, $searchColumn = 'id') {
1233 $object = new $daoName();
1234 $object->selectAdd();
1235 $object->selectAdd("$searchColumn, $setColumn");
1236 $object->$searchColumn = $searchValue;
1238 if ($object->find(TRUE)) {
1239 $object->$setColumn = $setValue;
1240 if ($object->save()) {
1251 * @param array|object $sort either array or CRM_Utils_Sort
1252 * @param string $default
1253 * Default sort value.
1257 public static function getSortString($sort, $default = NULL) {
1258 // check if sort is of type CRM_Utils_Sort
1259 if (is_a($sort, 'CRM_Utils_Sort')) {
1260 return $sort->orderBy();
1265 // is it an array specified as $field => $sortDirection ?
1267 foreach ($sort as $k => $v) {
1268 $sortString .= "$k $v,";
1270 return rtrim($sortString, ',');
1276 * Fetch object based on array of properties.
1278 * @param string $daoName
1279 * Name of the dao object.
1280 * @param array $params
1281 * (reference ) an assoc array of name/value pairs.
1282 * @param array $defaults
1283 * (reference ) an assoc array to hold the flattened values.
1284 * @param array $returnProperities
1285 * An assoc array of fields that need to be returned, eg array( 'first_name', 'last_name').
1288 * an object of type referenced by daoName
1290 public static function commonRetrieve($daoName, &$params, &$defaults, $returnProperities = NULL) {
1291 $object = new $daoName();
1292 $object->copyValues($params);
1294 // return only specific fields if returnproperties are sent
1295 if (!empty($returnProperities)) {
1296 $object->selectAdd();
1297 $object->selectAdd(implode(',', $returnProperities));
1300 if ($object->find(TRUE)) {
1301 self
::storeValues($object, $defaults);
1308 * Delete the object records that are associated with this contact.
1310 * @param string $daoName
1311 * Name of the dao object.
1312 * @param int $contactId
1313 * Id of the contact to delete.
1315 public static function deleteEntityContact($daoName, $contactId) {
1316 $object = new $daoName();
1318 $object->entity_table
= 'civicrm_contact';
1319 $object->entity_id
= $contactId;
1324 * Execute an unbuffered query.
1326 * This is a wrapper around new functionality exposed with CRM-17748.
1328 * @param string $query query to be executed
1330 * @param array $params
1331 * @param bool $abort
1332 * @param null $daoName
1333 * @param bool $freeDAO
1334 * @param bool $i18nRewrite
1335 * @param bool $trapException
1337 * @return CRM_Core_DAO
1338 * Object that points to an unbuffered result set
1340 public static function executeUnbufferedQuery(
1346 $i18nRewrite = TRUE,
1347 $trapException = FALSE
1350 return self
::executeQuery(
1358 ['result_buffering' => 0]
1365 * @param string $query
1366 * Query to be executed.
1368 * @param array $params
1369 * @param bool $abort
1370 * @param null $daoName
1371 * @param bool $freeDAO
1372 * @param bool $i18nRewrite
1373 * @param bool $trapException
1374 * @param array $options
1376 * @return CRM_Core_DAO|object
1377 * object that holds the results of the query
1378 * NB - if this is defined as just returning a DAO phpstorm keeps pointing
1379 * out all the properties that are not part of the DAO
1381 public static function &executeQuery(
1387 $i18nRewrite = TRUE,
1388 $trapException = FALSE,
1391 $queryStr = self
::composeQuery($query, $params, $abort);
1394 $dao = new CRM_Core_DAO();
1397 $dao = new $daoName();
1400 if ($trapException) {
1401 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
1404 if ($dao->isValidOption($options)) {
1405 $dao->setOptions($options);
1408 $result = $dao->query($queryStr, $i18nRewrite);
1410 // since it is unbuffered, ($dao->N==0) is true. This blocks the standard fetch() mechanism.
1411 if (CRM_Utils_Array
::value('result_buffering', $options) === 0) {
1415 if (is_a($result, 'DB_Error')) {
1420 preg_match('/^(insert|update|delete|create|drop|replace)/i', $queryStr)
1422 // we typically do this for insert/update/delete statements OR if explicitly asked to
1429 * Wrapper to validate internal DAO options before passing to DB_mysql/DB_Common level
1431 * @param array $options
1434 * Provided options are valid
1436 public function isValidOption($options) {
1445 if (empty($options)) {
1449 foreach (array_keys($options) as $option) {
1450 if (!in_array($option, $validOptions)) {
1460 * Execute a query and get the single result.
1462 * @param string $query
1463 * Query to be executed.
1464 * @param array $params
1465 * @param bool $abort
1466 * @param bool $i18nRewrite
1467 * @return string|null
1468 * the result of the query if any
1471 public static function &singleValueQuery(
1477 $queryStr = self
::composeQuery($query, $params, $abort);
1479 static $_dao = NULL;
1482 $_dao = new CRM_Core_DAO();
1485 $_dao->query($queryStr, $i18nRewrite);
1487 $result = $_dao->getDatabaseResult();
1490 $row = $result->fetchRow();
1500 * Compose the query by merging the parameters into it.
1502 * @param string $query
1503 * @param array $params
1504 * @param bool $abort
1507 * @throws CRM_Core_Exception
1509 public static function composeQuery($query, $params = [], $abort = TRUE) {
1511 foreach ($params as $key => $item) {
1512 if (is_numeric($key)) {
1513 if (CRM_Utils_Type
::validate($item[0], $item[1]) !== NULL) {
1514 $item[0] = self
::escapeString($item[0]);
1515 if ($item[1] == 'String' ||
1516 $item[1] == 'Memo' ||
1519 // Support class constants stipulating wildcard characters and/or
1520 // non-quoting of strings. Also support legacy code which may be
1521 // passing in TRUE or 1 for $item[2], which used to indicate the
1522 // use of wildcard characters.
1523 if (!empty($item[2])) {
1524 if ($item[2] & CRM_Core_DAO
::QUERY_FORMAT_WILDCARD ||
$item[2] === TRUE) {
1525 $item[0] = "'%{$item[0]}%'";
1527 elseif (!($item[2] & CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
)) {
1528 $item[0] = "'{$item[0]}'";
1532 $item[0] = "'{$item[0]}'";
1536 if (($item[1] == 'Date' ||
$item[1] == 'Timestamp') &&
1537 strlen($item[0]) == 0
1542 $tr['%' . $key] = $item[0];
1545 throw new CRM_Core_Exception("{$item[0]} is not of type {$item[1]}");
1550 return strtr($query, $tr);
1556 public static function freeResult($ids = NULL) {
1557 global $_DB_DATAOBJECT;
1560 if (!$_DB_DATAOBJECT ||
1561 !isset($_DB_DATAOBJECT['RESULTS'])
1565 $ids = array_keys($_DB_DATAOBJECT['RESULTS']);
1568 foreach ($ids as $id) {
1569 if (isset($_DB_DATAOBJECT['RESULTS'][$id])) {
1570 $_DB_DATAOBJECT['RESULTS'][$id]->free();
1571 unset($_DB_DATAOBJECT['RESULTS'][$id]);
1574 if (isset($_DB_DATAOBJECT['RESULTFIELDS'][$id])) {
1575 unset($_DB_DATAOBJECT['RESULTFIELDS'][$id]);
1581 * Make a shallow copy of an object and all the fields in the object.
1583 * @param string $daoName
1585 * @param array $criteria
1586 * Array of all the fields & values.
1587 * on which basis to copy
1588 * @param array $newData
1589 * Array of all the fields & values.
1590 * to be copied besides the other fields
1591 * @param string $fieldsFix
1592 * Array of fields that you want to prefix/suffix/replace.
1593 * @param string $blockCopyOfDependencies
1594 * Fields that you want to block from.
1596 * @param bool $blockCopyofCustomValues
1597 * Case when you don't want to copy the custom values set in a
1598 * template as it will override/ignore the submitted custom values
1600 * @return CRM_Core_DAO|bool
1601 * the newly created copy of the object. False if none created.
1603 public static function copyGeneric($daoName, $criteria, $newData = NULL, $fieldsFix = NULL, $blockCopyOfDependencies = NULL, $blockCopyofCustomValues = FALSE) {
1604 $object = new $daoName();
1607 $object->id
= $criteria['id'];
1610 foreach ($criteria as $key => $value) {
1611 $object->$key = $value;
1616 while ($object->fetch()) {
1618 // all the objects except with $blockCopyOfDependencies set
1619 // be copied - addresses #CRM-1962
1621 if ($blockCopyOfDependencies && $object->$blockCopyOfDependencies) {
1625 $newObject = new $daoName();
1627 $fields = $object->fields();
1628 if (!is_array($fieldsFix)) {
1629 $fieldsToPrefix = [];
1630 $fieldsToSuffix = [];
1631 $fieldsToReplace = [];
1633 if (!empty($fieldsFix['prefix'])) {
1634 $fieldsToPrefix = $fieldsFix['prefix'];
1636 if (!empty($fieldsFix['suffix'])) {
1637 $fieldsToSuffix = $fieldsFix['suffix'];
1639 if (!empty($fieldsFix['replace'])) {
1640 $fieldsToReplace = $fieldsFix['replace'];
1643 foreach ($fields as $name => $value) {
1644 if ($name == 'id' ||
$value['name'] == 'id') {
1645 // copy everything but the id!
1649 $dbName = $value['name'];
1650 $type = CRM_Utils_Type
::typeToString($value['type']);
1651 $newObject->$dbName = $object->$dbName;
1652 if (isset($fieldsToPrefix[$dbName])) {
1653 $newObject->$dbName = $fieldsToPrefix[$dbName] . $newObject->$dbName;
1655 if (isset($fieldsToSuffix[$dbName])) {
1656 $newObject->$dbName .= $fieldsToSuffix[$dbName];
1658 if (isset($fieldsToReplace[$dbName])) {
1659 $newObject->$dbName = $fieldsToReplace[$dbName];
1662 if ($type == 'Timestamp' ||
$type == 'Date') {
1663 $newObject->$dbName = CRM_Utils_Date
::isoToMysql($newObject->$dbName);
1667 $newObject->copyValues($newData);
1671 if (!$blockCopyofCustomValues) {
1672 $newObject->copyCustomFields($object->id
, $newObject->id
);
1674 CRM_Utils_Hook
::post('create', CRM_Core_DAO_AllCoreTables
::getBriefName(str_replace('_BAO_', '_DAO_', $daoName)), $newObject->id
, $newObject);
1681 * Method that copies custom fields values from an old entity to a new one.
1683 * Fixes bug CRM-19302,
1684 * where if a custom field of File type was present, left both events using the same file,
1685 * breaking download URL's for the old event.
1687 * @todo the goal here is to clean this up so that it works for any entity. Copy Generic already DOES some custom field stuff
1688 * but it seems to be bypassed & perhaps less good than this (or this just duplicates it...)
1690 * @param int $entityID
1691 * @param int $newEntityID
1693 public function copyCustomFields($entityID, $newEntityID) {
1694 $entity = CRM_Core_DAO_AllCoreTables
::getBriefName(get_class($this));
1695 $tableName = CRM_Core_DAO_AllCoreTables
::getTableForClass(get_class($this));
1696 // Obtain custom values for old event
1697 $customParams = $htmlType = [];
1698 $customValues = CRM_Core_BAO_CustomValueTable
::getEntityValues($entityID, $entity);
1700 // If custom values present, we copy them
1701 if (!empty($customValues)) {
1702 // Get Field ID's and identify File type attributes, to handle file copying.
1703 $fieldIds = implode(', ', array_keys($customValues));
1704 $sql = "SELECT id FROM civicrm_custom_field WHERE html_type = 'File' AND id IN ( {$fieldIds} )";
1705 $result = CRM_Core_DAO
::executeQuery($sql);
1707 // Build array of File type fields
1708 while ($result->fetch()) {
1709 $htmlType[] = $result->id
;
1712 // Build params array of custom values
1713 foreach ($customValues as $field => $value) {
1714 if ($value !== NULL) {
1715 // Handle File type attributes
1716 if (in_array($field, $htmlType)) {
1717 $fileValues = CRM_Core_BAO_File
::path($value, $entityID);
1718 $customParams["custom_{$field}_-1"] = [
1719 'name' => CRM_Utils_File
::duplicate($fileValues[0]),
1720 'type' => $fileValues[1],
1723 // Handle other types
1725 $customParams["custom_{$field}_-1"] = $value;
1730 // Save Custom Fields for new Event
1731 CRM_Core_BAO_CustomValueTable
::postProcess($customParams, $tableName, $newEntityID, $entity);
1734 // copy activity attachments ( if any )
1735 CRM_Core_BAO_File
::copyEntityFile($tableName, $entityID, $tableName, $newEntityID);
1739 * Cascade update through related entities.
1741 * @param string $daoName
1744 * @param array $newData
1746 * @return CRM_Core_DAO|null
1748 public static function cascadeUpdate($daoName, $fromId, $toId, $newData = []) {
1749 $object = new $daoName();
1750 $object->id
= $fromId;
1752 if ($object->find(TRUE)) {
1753 $newObject = new $daoName();
1754 $newObject->id
= $toId;
1756 if ($newObject->find(TRUE)) {
1757 $fields = $object->fields();
1758 foreach ($fields as $name => $value) {
1759 if ($name == 'id' ||
$value['name'] == 'id') {
1760 // copy everything but the id!
1764 $colName = $value['name'];
1765 $newObject->$colName = $object->$colName;
1767 if (substr($name, -5) == '_date' ||
1768 substr($name, -10) == '_date_time'
1770 $newObject->$colName = CRM_Utils_Date
::isoToMysql($newObject->$colName);
1773 foreach ($newData as $k => $v) {
1774 $newObject->$k = $v;
1784 * Given the component id, compute the contact id
1785 * since its used for things like send email
1787 * @param $componentIDs
1788 * @param string $tableName
1789 * @param string $idField
1793 public static function getContactIDsFromComponent($componentIDs, $tableName, $idField = 'id') {
1796 if (empty($componentIDs)) {
1800 $IDs = implode(',', $componentIDs);
1804 WHERE $idField IN ( $IDs )
1807 $dao = CRM_Core_DAO
::executeQuery($query);
1808 while ($dao->fetch()) {
1809 $contactIDs[] = $dao->contact_id
;
1815 * Fetch object based on array of properties.
1817 * @param string $daoName
1818 * Name of the dao object.
1819 * @param string $fieldIdName
1820 * @param int $fieldId
1822 * @param array $returnProperities
1823 * An assoc array of fields that need to be returned, eg array( 'first_name', 'last_name').
1826 * an object of type referenced by daoName
1828 public static function commonRetrieveAll($daoName, $fieldIdName = 'id', $fieldId, &$details, $returnProperities = NULL) {
1829 require_once str_replace('_', DIRECTORY_SEPARATOR
, $daoName) . ".php";
1830 $object = new $daoName();
1831 $object->$fieldIdName = $fieldId;
1833 // return only specific fields if returnproperties are sent
1834 if (!empty($returnProperities)) {
1835 $object->selectAdd();
1836 $object->selectAdd('id');
1837 $object->selectAdd(implode(',', $returnProperities));
1841 while ($object->fetch()) {
1843 self
::storeValues($object, $defaults);
1844 $details[$object->id
] = $defaults;
1851 * Drop all CiviCRM tables.
1853 * @throws \CRM_Core_Exception
1855 public static function dropAllTables() {
1857 // first drop all the custom tables we've created
1858 CRM_Core_BAO_CustomGroup
::dropAllTables();
1860 // drop all multilingual views
1861 CRM_Core_I18n_Schema
::dropAllViews();
1863 CRM_Utils_File
::sourceSQLFile(CIVICRM_DSN
,
1864 dirname(__FILE__
) . DIRECTORY_SEPARATOR
.
1865 '..' . DIRECTORY_SEPARATOR
.
1866 '..' . DIRECTORY_SEPARATOR
.
1867 'sql' . DIRECTORY_SEPARATOR
.
1868 'civicrm_drop.mysql'
1877 public static function escapeString($string) {
1878 static $_dao = NULL;
1880 // If this is an atypical case (e.g. preparing .sql file before CiviCRM
1881 // has been installed), then we fallback DB-less str_replace escaping, as
1882 // we can't use mysqli_real_escape_string, as there is no DB connection.
1883 // Note: In typical usage, escapeString() will only check one conditional
1884 // ("if !$_dao") rather than two conditionals ("if !defined(DSN)")
1885 if (!defined('CIVICRM_DSN')) {
1886 // See http://php.net/manual/en/mysqli.real-escape-string.php for the
1887 // list of characters mysqli_real_escape_string escapes.
1888 $search = ["\\", "\x00", "\n", "\r", "'", '"', "\x1a"];
1889 $replace = ["\\\\", "\\0", "\\n", "\\r", "\'", '\"', "\\Z"];
1890 return str_replace($search, $replace, $string);
1892 $_dao = new CRM_Core_DAO();
1894 return $_dao->escape($string);
1898 * Escape a list of strings for use with "WHERE X IN (...)" queries.
1900 * @param array $strings
1901 * @param string $default
1902 * the value to use if $strings has no elements.
1904 * eg "abc","def","ghi"
1906 public static function escapeStrings($strings, $default = NULL) {
1907 static $_dao = NULL;
1909 $_dao = new CRM_Core_DAO();
1912 if (empty($strings)) {
1916 $escapes = array_map([$_dao, 'escape'], $strings);
1917 return '"' . implode('","', $escapes) . '"';
1925 public static function escapeWildCardString($string) {
1927 // ensure we escape the single characters % and _ which are mysql wild
1928 // card characters and could come in via sortByCharacter
1929 // note that mysql does not escape these characters
1930 if ($string && in_array($string,
1931 ['%', '_', '%%', '_%']
1934 return '\\' . $string;
1937 return self
::escapeString($string);
1941 * Creates a test object, including any required objects it needs via recursion
1942 * createOnly: only create in database, do not store or return the objects (useful for perf testing)
1943 * ONLY USE FOR TESTING
1945 * @param string $daoName
1946 * @param array $params
1947 * @param int $numObjects
1948 * @param bool $createOnly
1950 * @return object|array|NULL
1951 * NULL if $createOnly. A single object if $numObjects==1. Otherwise, an array of multiple objects.
1953 public static function createTestObject(
1959 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
1960 // so we re-set here in case
1961 $config = CRM_Core_Config
::singleton();
1962 $config->backtrace
= TRUE;
1964 static $counter = 0;
1965 CRM_Core_DAO
::$_testEntitiesToSkip = [
1966 'CRM_Core_DAO_Worldregion',
1967 'CRM_Core_DAO_StateProvince',
1968 'CRM_Core_DAO_Country',
1969 'CRM_Core_DAO_Domain',
1970 'CRM_Financial_DAO_FinancialType',
1971 //because valid ones exist & we use pick them due to pseudoconstant can't reliably create & delete these
1974 // Prefer to instantiate BAO's instead of DAO's (when possible)
1975 // so that assignTestValue()/assignTestFK() can be overloaded.
1976 $baoName = str_replace('_DAO_', '_BAO_', $daoName);
1977 if ($baoName === 'CRM_Financial_BAO_FinancialTrxn') {
1978 // OMG OMG OMG this is so incredibly bad. The BAO is insanely named.
1979 // @todo create a new class called what the BAO SHOULD be
1980 // that extends BAO-crazy-name.... migrate.
1981 $baoName = 'CRM_Core_BAO_FinancialTrxn';
1983 if (class_exists($baoName)) {
1984 $daoName = $baoName;
1987 for ($i = 0; $i < $numObjects; ++
$i) {
1990 /** @var CRM_Core_DAO $object */
1991 $object = new $daoName();
1993 $fields = $object->fields();
1994 foreach ($fields as $fieldName => $fieldDef) {
1995 $dbName = $fieldDef['name'];
1996 $FKClassName = CRM_Utils_Array
::value('FKClassName', $fieldDef);
1997 $required = CRM_Utils_Array
::value('required', $fieldDef);
1999 if (CRM_Utils_Array
::value($dbName, $params) !== NULL && !is_array($params[$dbName])) {
2000 $object->$dbName = $params[$dbName];
2003 elseif ($dbName != 'id') {
2004 if ($FKClassName != NULL) {
2005 $object->assignTestFK($fieldName, $fieldDef, $params);
2009 $object->assignTestValue($fieldName, $fieldDef, $counter);
2017 $objects[$i] = $object;
2027 elseif ($numObjects == 1) {
2036 * Deletes the this object plus any dependent objects that are associated with it.
2037 * ONLY USE FOR TESTING
2039 * @param string $daoName
2040 * @param array $params
2042 public static function deleteTestObjects($daoName, $params = []) {
2043 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
2044 // so we re-set here in case
2045 $config = CRM_Core_Config
::singleton();
2046 $config->backtrace
= TRUE;
2048 $object = new $daoName();
2049 $object->id
= CRM_Utils_Array
::value('id', $params);
2051 // array(array(0 => $daoName, 1 => $daoParams))
2053 if ($object->find(TRUE)) {
2055 $fields = $object->fields();
2056 foreach ($fields as $name => $value) {
2058 $dbName = $value['name'];
2060 $FKClassName = CRM_Utils_Array
::value('FKClassName', $value);
2061 $required = CRM_Utils_Array
::value('required', $value);
2062 if ($FKClassName != NULL
2064 && !in_array($FKClassName, CRM_Core_DAO
::$_testEntitiesToSkip)
2065 && ($required ||
$dbName == 'contact_id')
2066 //I'm a bit stuck on this one - we might need to change the singleValueAlter so that the entities don't share a contact
2067 // to make this test process pass - line below makes pass for now
2068 && $dbName != 'member_of_contact_id'
2071 $deletions[] = [$FKClassName, ['id' => $object->$dbName]];
2078 foreach ($deletions as $deletion) {
2079 CRM_Core_DAO
::deleteTestObjects($deletion[0], $deletion[1]);
2084 * Set defaults when creating new entity.
2085 * (don't call this set defaults as already in use with different signature in some places)
2087 * @param array $params
2090 public static function setCreateDefaults(&$params, $defaults) {
2091 if (!empty($params['id'])) {
2094 foreach ($defaults as $key => $value) {
2095 if (!array_key_exists($key, $params) ||
$params[$key] === NULL) {
2096 $params[$key] = $value;
2102 * @param string $prefix
2103 * @param bool $addRandomString
2104 * @param null $string
2108 * @see CRM_Utils_SQL_TempTable
2110 public static function createTempTableName($prefix = 'civicrm', $addRandomString = TRUE, $string = NULL) {
2111 CRM_Core_Error
::deprecatedFunctionWarning('Use CRM_Utils_SQL_TempTable interface to create temporary tables');
2112 $tableName = $prefix . "_temp";
2114 if ($addRandomString) {
2116 $tableName .= "_" . $string;
2119 $tableName .= "_" . md5(uniqid('', TRUE));
2127 * @param bool $trigger
2131 public static function checkTriggerViewPermission($view = TRUE, $trigger = TRUE) {
2132 if (\Civi
::settings()->get('logging_no_trigger_permission')) {
2135 // test for create view and trigger permissions and if allowed, add the option to go multilingual
2137 // I'm not sure why we use the getStaticProperty for an error, rather than checking for DB_Error
2138 CRM_Core_TemporaryErrorScope
::ignoreException();
2139 $dao = new CRM_Core_DAO();
2141 $result = $dao->query('CREATE OR REPLACE VIEW civicrm_domain_view AS SELECT * FROM civicrm_domain');
2142 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError') ||
is_a($result, 'DB_Error')) {
2148 $result = $dao->query('CREATE TRIGGER civicrm_domain_trigger BEFORE INSERT ON civicrm_domain FOR EACH ROW BEGIN END');
2149 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError') ||
is_a($result, 'DB_Error')) {
2151 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
2156 $dao->query('DROP TRIGGER IF EXISTS civicrm_domain_trigger');
2157 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
2159 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
2166 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
2167 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
2176 * @param null $message
2177 * @param bool $printDAO
2179 public static function debugPrint($message = NULL, $printDAO = TRUE) {
2180 CRM_Utils_System
::xMemory("{$message}: ");
2183 global $_DB_DATAOBJECT;
2185 foreach (array_keys($_DB_DATAOBJECT['RESULTS']) as $id) {
2186 $q[] = $_DB_DATAOBJECT['RESULTS'][$id]->query
;
2188 CRM_Core_Error
::debug('_DB_DATAOBJECT', $q);
2193 * Build a list of triggers via hook and add them to (err, reconcile them
2194 * with) the database.
2196 * @param string $tableName
2197 * the specific table requiring a rebuild; or NULL to rebuild all tables.
2198 * @param bool $force
2203 public static function triggerRebuild($tableName = NULL, $force = FALSE) {
2204 Civi
::service('sql_triggers')->rebuild($tableName, $force);
2208 * Because sql functions are sometimes lost, esp during db migration, we check here to avoid numerous support requests
2209 * @see http://issues.civicrm.org/jira/browse/CRM-13822
2210 * TODO: Alternative solutions might be
2211 * * Stop using functions and find another way to strip numeric characters from phones
2212 * * Give better error messages (currently a missing fn fatals with "unknown error")
2214 public static function checkSqlFunctionsExist() {
2215 if (!self
::$_checkedSqlFunctionsExist) {
2216 self
::$_checkedSqlFunctionsExist = TRUE;
2217 $dao = CRM_Core_DAO
::executeQuery("SHOW function status WHERE db = database() AND name = 'civicrm_strip_non_numeric'");
2218 if (!$dao->fetch()) {
2219 self
::triggerRebuild();
2225 * Wrapper function to drop triggers.
2227 * @param string $tableName
2228 * the specific table requiring a rebuild; or NULL to rebuild all tables.
2231 public static function dropTriggers($tableName = NULL) {
2232 Civi
::service('sql_triggers')->dropTriggers($tableName);
2236 * @param array $info
2237 * per hook_civicrm_triggerInfo.
2238 * @param string $onlyTableName
2239 * the specific table requiring a rebuild; or NULL to rebuild all tables.
2242 public static function createTriggers(&$info, $onlyTableName = NULL) {
2243 Civi
::service('sql_triggers')->createTriggers($info, $onlyTableName);
2247 * Given a list of fields, create a list of references.
2249 * @param string $className
2250 * BAO/DAO class name.
2251 * @return array<CRM_Core_Reference_Interface>
2253 public static function createReferenceColumns($className) {
2255 $fields = $className::fields();
2256 foreach ($fields as $field) {
2257 if (isset($field['pseudoconstant'], $field['pseudoconstant']['optionGroupName'])) {
2258 $result[] = new CRM_Core_Reference_OptionValue(
2259 $className::getTableName(),
2261 'civicrm_option_value',
2262 CRM_Utils_Array
::value('keyColumn', $field['pseudoconstant'], 'value'),
2263 $field['pseudoconstant']['optionGroupName']
2271 * Find all records which refer to this entity.
2274 * Array of objects referencing this
2276 public function findReferences() {
2277 $links = self
::getReferencesToTable(static::getTableName());
2280 foreach ($links as $refSpec) {
2281 /** @var $refSpec CRM_Core_Reference_Interface */
2282 $daoName = CRM_Core_DAO_AllCoreTables
::getClassForTable($refSpec->getReferenceTable());
2283 $result = $refSpec->findReferences($this);
2285 while ($result->fetch()) {
2286 $obj = new $daoName();
2287 $obj->id
= $result->id
;
2288 $occurrences[] = $obj;
2293 return $occurrences;
2298 * each item has keys:
2302 * - table: string|null SQL table name
2303 * - key: string|null SQL column name
2305 public function getReferenceCounts() {
2306 $links = self
::getReferencesToTable(static::getTableName());
2309 foreach ($links as $refSpec) {
2310 /** @var $refSpec CRM_Core_Reference_Interface */
2311 $count = $refSpec->getReferenceCount($this);
2312 if ($count['count'] != 0) {
2317 foreach (CRM_Core_Component
::getEnabledComponents() as $component) {
2318 /** @var $component CRM_Core_Component_Info */
2319 $counts = array_merge($counts, $component->getReferenceCounts($this));
2321 CRM_Utils_Hook
::referenceCounts($this, $counts);
2327 * List all tables which have hard foreign keys to this table.
2329 * For now, this returns a description of every entity_id/entity_table
2331 * TODO: filter dynamic entity references on the $tableName, based on
2332 * schema metadata in dynamicForeignKey which enumerates a restricted
2333 * set of possible entity_table's.
2335 * @param string $tableName
2336 * Table referred to.
2339 * structure of table and column, listing every table with a
2340 * foreign key reference to $tableName, and the column where the key appears.
2342 public static function getReferencesToTable($tableName) {
2344 foreach (CRM_Core_DAO_AllCoreTables
::getClasses() as $daoClassName) {
2345 $links = $daoClassName::getReferenceColumns();
2346 $daoTableName = $daoClassName::getTableName();
2348 foreach ($links as $refSpec) {
2349 /** @var $refSpec CRM_Core_Reference_Interface */
2350 if ($refSpec->matchesTargetTable($tableName)) {
2351 $refsFound[] = $refSpec;
2359 * Get all references to contact table.
2361 * This includes core tables, custom group tables, tables added by the merge
2362 * hook and the entity_tag table.
2364 * Refer to CRM-17454 for information on the danger of querying the information
2365 * schema to derive this.
2367 public static function getReferencesToContactTable() {
2368 if (isset(\Civi
::$statics[__CLASS__
]) && isset(\Civi
::$statics[__CLASS__
]['contact_references'])) {
2369 return \Civi
::$statics[__CLASS__
]['contact_references'];
2371 $contactReferences = [];
2372 $coreReferences = CRM_Core_DAO
::getReferencesToTable('civicrm_contact');
2373 foreach ($coreReferences as $coreReference) {
2374 if (!is_a($coreReference, 'CRM_Core_Reference_Dynamic')) {
2375 $contactReferences[$coreReference->getReferenceTable()][] = $coreReference->getReferenceKey();
2378 self
::appendCustomTablesExtendingContacts($contactReferences);
2379 self
::appendCustomContactReferenceFields($contactReferences);
2381 // FixME for time being adding below line statically as no Foreign key constraint defined for table 'civicrm_entity_tag'
2382 $contactReferences['civicrm_entity_tag'][] = 'entity_id';
2383 \Civi
::$statics[__CLASS__
]['contact_references'] = $contactReferences;
2384 return \Civi
::$statics[__CLASS__
]['contact_references'];
2388 * Add custom tables that extend contacts to the list of contact references.
2390 * CRM_Core_BAO_CustomGroup::getAllCustomGroupsByBaseEntity seems like a safe-ish
2391 * function to be sure all are retrieved & we don't miss subtypes or inactive or multiples
2392 * - the down side is it is not cached.
2394 * Further changes should be include tests in the CRM_Core_MergerTest class
2395 * to ensure that disabled, subtype, multiple etc groups are still captured.
2397 * @param array $cidRefs
2399 public static function appendCustomTablesExtendingContacts(&$cidRefs) {
2400 $customValueTables = CRM_Core_BAO_CustomGroup
::getAllCustomGroupsByBaseEntity('Contact');
2401 $customValueTables->find();
2402 while ($customValueTables->fetch()) {
2403 $cidRefs[$customValueTables->table_name
][] = 'entity_id';
2408 * Add custom ContactReference fields to the list of contact references
2410 * This includes active and inactive fields/groups
2412 * @param array $cidRefs
2414 * @throws \CiviCRM_API3_Exception
2416 public static function appendCustomContactReferenceFields(&$cidRefs) {
2417 $fields = civicrm_api3('CustomField', 'get', [
2418 'return' => ['column_name', 'custom_group_id.table_name'],
2419 'data_type' => 'ContactReference',
2421 foreach ($fields as $field) {
2422 $cidRefs[$field['custom_group_id.table_name']][] = $field['column_name'];
2427 * Lookup the value of a MySQL global configuration variable.
2429 * @param string $name
2430 * E.g. "thread_stack".
2431 * @param mixed $default
2434 public static function getGlobalSetting($name, $default = NULL) {
2435 // Alternatively, SELECT @@GLOBAL.thread_stack, but
2436 // that has been reported to fail under MySQL 5.0 for OS X
2437 $escapedName = self
::escapeString($name);
2438 $dao = CRM_Core_DAO
::executeQuery("SHOW VARIABLES LIKE '$escapedName'");
2439 if ($dao->fetch()) {
2448 * Update the fields array to also hold keys for pseudoconstant fields that relate to contained fields.
2450 * This is relevant where we want to offer both the ID field and the label field
2451 * as an option, e.g. search builder.
2453 * It is currently limited for optionGroupName & id+ name+ FK combos for purposes keeping the scope of the
2454 * change small, but is appropriate for other sorts of pseudoconstants.
2456 * @param array $fields
2458 public static function appendPseudoConstantsToFields(&$fields) {
2459 foreach ($fields as $fieldUniqueName => $field) {
2460 if (!empty($field['pseudoconstant'])) {
2461 $pseudoConstant = $field['pseudoconstant'];
2462 if (!empty($pseudoConstant['optionGroupName'])) {
2463 $fields[$pseudoConstant['optionGroupName']] = [
2464 'title' => CRM_Core_BAO_OptionGroup
::getTitleByName($pseudoConstant['optionGroupName']),
2465 'name' => $pseudoConstant['optionGroupName'],
2466 'data_type' => CRM_Utils_Type
::T_STRING
,
2467 'is_pseudofield_for' => $fieldUniqueName,
2470 // We restrict to id + name + FK as we are extending this a bit, but cautiously.
2472 !empty($field['FKClassName'])
2473 && CRM_Utils_Array
::value('keyColumn', $pseudoConstant) === 'id'
2474 && CRM_Utils_Array
::value('labelColumn', $pseudoConstant) === 'name'
2476 $pseudoFieldName = str_replace('_' . $pseudoConstant['keyColumn'], '', $field['name']);
2477 // This if is just an extra caution when adding change.
2478 if (!isset($fields[$pseudoFieldName])) {
2479 $daoName = $field['FKClassName'];
2480 $fkFields = $daoName::fields();
2481 foreach ($fkFields as $fkField) {
2482 if ($fkField['name'] === $pseudoConstant['labelColumn']) {
2483 $fields[$pseudoFieldName] = [
2484 'name' => $pseudoFieldName,
2485 'is_pseudofield_for' => $field['name'],
2486 'title' => $fkField['title'],
2487 'data_type' => $fkField['type'],
2488 'where' => $field['where'],
2499 * Get options for the called BAO object's field.
2501 * This function can be overridden by each BAO to add more logic related to context.
2502 * The overriding function will generally call the lower-level CRM_Core_PseudoConstant::get
2504 * @param string $fieldName
2505 * @param string $context
2506 * @see CRM_Core_DAO::buildOptionsContext
2507 * @param array $props
2508 * whatever is known about this bao object.
2510 * @return array|bool
2512 public static function buildOptions($fieldName, $context = NULL, $props = []) {
2513 // If a given bao does not override this function
2514 $baoName = get_called_class();
2515 return CRM_Core_PseudoConstant
::get($baoName, $fieldName, $props, $context);
2519 * Populate option labels for this object's fields.
2521 * @throws exception if called directly on the base class
2523 public function getOptionLabels() {
2524 $fields = $this->fields();
2525 if ($fields === NULL) {
2526 throw new Exception('Cannot call getOptionLabels on CRM_Core_DAO');
2528 foreach ($fields as $field) {
2529 $name = CRM_Utils_Array
::value('name', $field);
2530 if ($name && isset($this->$name)) {
2531 $label = CRM_Core_PseudoConstant
::getLabel(get_class($this), $name, $this->$name);
2532 if ($label !== FALSE) {
2533 // Append 'label' onto the field name
2534 $labelName = $name . '_label';
2535 $this->$labelName = $label;
2542 * Provides documentation and validation for the buildOptions $context param
2544 * @param string $context
2549 public static function buildOptionsContext($context = NULL) {
2551 'get' => "get: all options are returned, even if they are disabled; labels are translated.",
2552 'create' => "create: options are filtered appropriately for the object being created/updated; labels are translated.",
2553 'search' => "search: searchable options are returned; labels are translated.",
2554 'validate' => "validate: all options are returned, even if they are disabled; machine names are used in place of labels.",
2555 'abbreviate' => "abbreviate: enabled options are returned; labels are replaced with abbreviations.",
2556 'match' => "match: enabled options are returned using machine names as keys; labels are translated.",
2558 // Validation: enforce uniformity of this param
2559 if ($context !== NULL && !isset($contexts[$context])) {
2560 throw new Exception("'$context' is not a valid context for buildOptions.");
2566 * @param string $fieldName
2567 * @return bool|array
2569 public function getFieldSpec($fieldName) {
2570 $fields = $this->fields();
2571 $fieldKeys = $this->fieldKeys();
2573 // Support "unique names" as well as sql names
2574 $fieldKey = $fieldName;
2575 if (empty($fields[$fieldKey])) {
2576 $fieldKey = CRM_Utils_Array
::value($fieldName, $fieldKeys);
2578 // If neither worked then this field doesn't exist. Return false.
2579 if (empty($fields[$fieldKey])) {
2582 return $fields[$fieldKey];
2586 * Get SQL where clause for SQL filter syntax input parameters.
2588 * SQL version of api function to assign filters to the DAO based on the syntax
2589 * $field => array('IN' => array(4,6,9))
2591 * $field => array('LIKE' => array('%me%))
2594 * @param string $fieldName
2596 * @param array $filter
2597 * filter to be applied indexed by operator.
2598 * @param string $type
2599 * type of field (not actually used - nor in api @todo ).
2600 * @param string $alias
2601 * alternative field name ('as') @todo- not actually used.
2602 * @param bool $returnSanitisedArray
2603 * Return a sanitised array instead of a clause.
2604 * this is primarily so we can add filters @ the api level to the Query object based fields
2608 * @return NULL|string|array
2609 * a string is returned if $returnSanitisedArray is not set, otherwise and Array or NULL
2610 * depending on whether it is supported as yet
2612 public static function createSQLFilter($fieldName, $filter, $type = NULL, $alias = NULL, $returnSanitisedArray = FALSE) {
2613 foreach ($filter as $operator => $criteria) {
2614 if (in_array($operator, self
::acceptedSQLOperators(), TRUE)) {
2615 switch ($operator) {
2619 if (!$returnSanitisedArray) {
2620 return (sprintf('%s %s', $fieldName, $operator));
2623 return (sprintf('%s %s ', $fieldName, $operator));
2627 // ternary operators
2630 if ((empty($criteria[0]) && !in_array($criteria[0], ['0', 0]))||
(empty($criteria[1]) && !in_array($criteria[1], ['0', 0]))) {
2631 throw new Exception("invalid criteria for $operator");
2633 if (!$returnSanitisedArray) {
2634 return (sprintf('%s ' . $operator . ' "%s" AND "%s"', $fieldName, CRM_Core_DAO
::escapeString($criteria[0]), CRM_Core_DAO
::escapeString($criteria[1])));
2637 // not yet implemented (tests required to implement)
2645 if (empty($criteria)) {
2646 throw new Exception("invalid criteria for $operator");
2648 $escapedCriteria = array_map([
2652 if (!$returnSanitisedArray) {
2653 return (sprintf('%s %s ("%s")', $fieldName, $operator, implode('", "', $escapedCriteria)));
2655 return $escapedCriteria;
2660 if (!$returnSanitisedArray) {
2661 return (sprintf('%s %s "%s"', $fieldName, $operator, CRM_Core_DAO
::escapeString($criteria)));
2664 // not yet implemented (tests required to implement)
2673 * @see http://issues.civicrm.org/jira/browse/CRM-9150
2674 * support for other syntaxes is discussed in ticket but being put off for now
2677 public static function acceptedSQLOperators() {
2698 * SQL has a limit of 64 characters on various names:
2699 * table name, trigger name, column name ...
2701 * For custom groups and fields we generated names from user entered input
2702 * which can be longer than this length, this function helps with creating
2703 * strings that meet various criteria.
2705 * @param string $string
2706 * The string to be shortened.
2707 * @param int $length
2708 * The max length of the string.
2710 * @param bool $makeRandom
2714 public static function shortenSQLName($string, $length = 60, $makeRandom = FALSE) {
2715 // early return for strings that meet the requirements
2716 if (strlen($string) <= $length) {
2720 // easy return for calls that dont need a randomized uniq string
2722 return substr($string, 0, $length);
2725 // the string is longer than the length and we need a uniq string
2726 // for the same tablename we need the same uniq string every time
2727 // hence we use md5 on the string, which is not random
2728 // we'll append 8 characters to the end of the tableName
2729 $md5string = substr(md5($string), 0, 8);
2730 return substr($string, 0, $length - 8) . "_{$md5string}";
2734 * https://issues.civicrm.org/jira/browse/CRM-17748
2735 * Sets the internal options to be used on a query
2737 * @param array $options
2740 public function setOptions($options) {
2741 if (is_array($options)) {
2742 $this->_options
= $options;
2747 * https://issues.civicrm.org/jira/browse/CRM-17748
2748 * wrapper to pass internal DAO options down to DB_mysql/DB_Common level
2750 * @param array $options
2753 protected function _setDBOptions($options) {
2754 global $_DB_DATAOBJECT;
2756 if (is_array($options) && count($options)) {
2757 $conn = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5
];
2758 foreach ($options as $option_name => $option_value) {
2759 $conn->setOption($option_name, $option_value);
2766 * @param array $params
2768 public function setApiFilter(&$params) {
2772 * Generates acl clauses suitable for adding to WHERE or ON when doing an api.get for this entity
2774 * Return format is in the form of fieldname => clauses starting with an operator. e.g.:
2777 * 'location_type_id' => array('IS NOT NULL', 'IN (1,2,3)')
2781 * Note that all array keys must be actual field names in this entity. Use subqueries to filter on other tables e.g. custom values.
2785 public function addSelectWhereClause() {
2787 $fields = $this->fields();
2788 foreach ($fields as $fieldName => $field) {
2789 // Clause for contact-related entities like Email, Relationship, etc.
2790 if (strpos($fieldName, 'contact_id') === 0 && CRM_Utils_Array
::value('FKClassName', $field) == 'CRM_Contact_DAO_Contact') {
2791 $clauses[$fieldName] = CRM_Utils_SQL
::mergeSubquery('Contact');
2793 // Clause for an entity_table/entity_id combo
2794 if ($fieldName == 'entity_id' && isset($fields['entity_table'])) {
2795 $relatedClauses = [];
2796 $relatedEntities = $this->buildOptions('entity_table', 'get');
2797 foreach ((array) $relatedEntities as $table => $ent) {
2799 $ent = CRM_Core_DAO_AllCoreTables
::getBriefName(CRM_Core_DAO_AllCoreTables
::getClassForTable($table));
2800 $subquery = CRM_Utils_SQL
::mergeSubquery($ent);
2802 $relatedClauses[] = "(entity_table = '$table' AND entity_id " . implode(' AND entity_id ', $subquery) . ")";
2805 $relatedClauses[] = "(entity_table = '$table')";
2809 if ($relatedClauses) {
2810 $clauses['id'] = 'IN (SELECT id FROM `' . $this->tableName() . '` WHERE (' . implode(') OR (', $relatedClauses) . '))';
2814 CRM_Utils_Hook
::selectWhereClause($this, $clauses);
2819 * This returns the final permissioned query string for this entity
2821 * With acls from related entities + additional clauses from hook_civicrm_selectWhereClause
2823 * @param string $tableAlias
2826 public static function getSelectWhereClause($tableAlias = NULL) {
2827 $bao = new static();
2828 if ($tableAlias === NULL) {
2829 $tableAlias = $bao->tableName();
2832 foreach ((array) $bao->addSelectWhereClause() as $field => $vals) {
2833 $clauses[$field] = NULL;
2835 $clauses[$field] = "(`$tableAlias`.`$field` IS NULL OR (`$tableAlias`.`$field` " . implode(" AND `$tableAlias`.`$field` ", (array) $vals) . '))';
2842 * ensure database name is 'safe', i.e. only contains word characters (includes underscores)
2843 * and dashes, and contains at least one [a-z] case insenstive.
2849 public static function requireSafeDBName($database) {
2852 "/^[\w\-]*[a-z]+[\w\-]*$/i",
2856 if (empty($matches)) {
2863 * Transform an array to a serialized string for database storage.
2865 * @param array|null $value
2866 * @param int $serializationType
2867 * @return string|null
2869 * @throws \Exception
2871 public static function serializeField($value, $serializationType) {
2872 if ($value === NULL) {
2875 switch ($serializationType) {
2876 case self
::SERIALIZE_SEPARATOR_BOOKEND
:
2877 return $value === [] ?
'' : CRM_Utils_Array
::implodePadded($value);
2879 case self
::SERIALIZE_SEPARATOR_TRIMMED
:
2880 return is_array($value) ?
implode(self
::VALUE_SEPARATOR
, $value) : $value;
2882 case self
::SERIALIZE_JSON
:
2883 return is_array($value) ?
json_encode($value) : $value;
2885 case self
::SERIALIZE_PHP
:
2886 return is_array($value) ?
serialize($value) : $value;
2888 case self
::SERIALIZE_COMMA
:
2889 return is_array($value) ?
implode(',', $value) : $value;
2892 throw new Exception('Unknown serialization method for field.');
2897 * Transform a serialized string from the database into an array.
2899 * @param string|null $value
2900 * @param $serializationType
2902 * @return array|null
2903 * @throws CRM_Core_Exception
2905 public static function unSerializeField($value, $serializationType) {
2906 if ($value === NULL) {
2909 if ($value === '') {
2912 switch ($serializationType) {
2913 case self
::SERIALIZE_SEPARATOR_BOOKEND
:
2914 return (array) CRM_Utils_Array
::explodePadded($value);
2916 case self
::SERIALIZE_SEPARATOR_TRIMMED
:
2917 return explode(self
::VALUE_SEPARATOR
, trim($value));
2919 case self
::SERIALIZE_JSON
:
2920 return strlen($value) ?
json_decode($value, TRUE) : [];
2922 case self
::SERIALIZE_PHP
:
2923 return strlen($value) ? CRM_Utils_String
::unserialize($value) : [];
2925 case self
::SERIALIZE_COMMA
:
2926 return explode(',', trim(str_replace(', ', '', $value)));
2929 throw new CRM_Core_Exception('Unknown serialization method for field.');
2936 public static function getEntityRefFilters() {
2941 * Get exportable fields with pseudoconstants rendered as an extra field.
2943 * @param string $baoClass
2947 public static function getExportableFieldsWithPseudoConstants($baoClass) {
2948 if (method_exists($baoClass, 'exportableFields')) {
2949 $fields = $baoClass::exportableFields();
2952 $fields = $baoClass::export();
2954 CRM_Core_DAO
::appendPseudoConstantsToFields($fields);
2959 * Remove item from static cache during update/delete operations
2961 private function clearDbColumnValueCache() {
2962 $daoName = get_class($this);
2963 while (strpos($daoName, '_BAO_') !== FALSE) {
2964 $daoName = get_parent_class($daoName);
2966 if (isset($this->id
)) {
2967 unset(self
::$_dbColumnValueCache[$daoName]['id'][$this->id
]);
2969 if (isset($this->name
)) {
2970 unset(self
::$_dbColumnValueCache[$daoName]['name'][$this->name
]);