3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
29 * Base Database Access Object class.
31 * All DAO classes should inherit from this class.
34 * @copyright CiviCRM LLC (c) 2004-2019
37 if (!defined('DB_DSN_MODE')) {
38 define('DB_DSN_MODE', 'auto');
41 require_once 'PEAR.php';
42 require_once 'DB/DataObject.php';
44 require_once 'CRM/Core/I18n.php';
49 class CRM_Core_DAO
extends DB_DataObject
{
52 * How many times has this instance been cloned.
56 protected $resultCopies = 0;
62 public static $_nullObject = NULL;
67 public static $_nullArray = [];
69 public static $_dbColumnValueCache = NULL;
70 const NOT_NULL
= 1, IS_NULL
= 2,
72 VALUE_SEPARATOR
= "\ 1",
73 BULK_INSERT_COUNT
= 200,
74 BULK_INSERT_HIGH_COUNT
= 200,
75 QUERY_FORMAT_WILDCARD
= 1,
76 QUERY_FORMAT_NO_QUOTES
= 2,
79 * Serialized string separated by and bookended with VALUE_SEPARATOR
81 SERIALIZE_SEPARATOR_BOOKEND
= 1,
83 * @deprecated format separated by VALUE_SEPARATOR
85 SERIALIZE_SEPARATOR_TRIMMED
= 2,
87 * Recommended serialization format
91 * @deprecated format using php serialize()
95 * Comma separated string, no quotes, no spaces
100 * Define entities that shouldn't be created or deleted when creating/ deleting
101 * test objects - this prevents world regions, countries etc from being added / deleted
104 public static $_testEntitiesToSkip = [];
106 * The factory class for this application.
109 public static $_factory = NULL;
111 public static $_checkedSqlFunctionsExist = FALSE;
114 * https://issues.civicrm.org/jira/browse/CRM-17748
115 * internal variable for DAO to hold per-query settings
118 protected $_options = [];
123 * @return \CRM_Core_DAO
125 public function __construct() {
127 $this->__table
= $this->getTableName();
130 public function __clone() {
131 if (!empty($this->_DB_resultid
)) {
132 $this->resultCopies++
;
139 public function __destruct() {
140 if ($this->resultCopies
=== 0) {
143 $this->resultCopies
--;
147 * Empty definition for virtual function.
149 public static function getTableName() {
154 * Initialize the DAO object.
157 * The database connection string.
159 public static function init($dsn) {
160 Civi
::$statics[__CLASS__
]['init'] = 1;
161 $options = &PEAR
::getStaticProperty('DB_DataObject', 'options');
162 $options['database'] = $dsn;
163 if (defined('CIVICRM_DAO_DEBUG')) {
164 self
::DebugLevel(CIVICRM_DAO_DEBUG
);
166 $factory = new CRM_Contact_DAO_Factory();
167 CRM_Core_DAO
::setFactory($factory);
168 $currentModes = CRM_Utils_SQL
::getSqlModes();
169 if (CRM_Utils_Constant
::value('CIVICRM_MYSQL_STRICT', CRM_Utils_System
::isDevelopment())) {
170 if (CRM_Utils_SQL
::supportsFullGroupBy() && !in_array('ONLY_FULL_GROUP_BY', $currentModes) && CRM_Utils_SQL
::isGroupByModeInDefault()) {
171 $currentModes[] = 'ONLY_FULL_GROUP_BY';
173 if (!in_array('STRICT_TRANS_TABLES', $currentModes)) {
174 $currentModes = array_merge(['STRICT_TRANS_TABLES'], $currentModes);
176 CRM_Core_DAO
::executeQuery("SET SESSION sql_mode = %1", [1 => [implode(',', $currentModes), 'String']]);
178 CRM_Core_DAO
::executeQuery('SET NAMES utf8');
179 CRM_Core_DAO
::executeQuery('SET @uniqueID = %1', [1 => [CRM_Utils_Request
::id(), 'String']]);
185 public static function getConnection() {
186 global $_DB_DATAOBJECT;
187 $dao = new CRM_Core_DAO();
188 return $_DB_DATAOBJECT['CONNECTIONS'][$dao->_database_dsn_md5
];
192 * Disables usage of the ONLY_FULL_GROUP_BY Mode if necessary
194 public static function disableFullGroupByMode() {
195 $currentModes = CRM_Utils_SQL
::getSqlModes();
196 if (in_array('ONLY_FULL_GROUP_BY', $currentModes) && CRM_Utils_SQL
::isGroupByModeInDefault()) {
197 $key = array_search('ONLY_FULL_GROUP_BY', $currentModes);
198 unset($currentModes[$key]);
199 CRM_Core_DAO
::executeQuery("SET SESSION sql_mode = %1", [1 => [implode(',', $currentModes), 'String']]);
204 * Re-enables ONLY_FULL_GROUP_BY sql_mode as necessary..
206 public static function reenableFullGroupByMode() {
207 $currentModes = CRM_Utils_SQL
::getSqlModes();
208 if (!in_array('ONLY_FULL_GROUP_BY', $currentModes) && CRM_Utils_SQL
::isGroupByModeInDefault()) {
209 $currentModes[] = 'ONLY_FULL_GROUP_BY';
210 CRM_Core_DAO
::executeQuery("SET SESSION sql_mode = %1", [1 => [implode(',', $currentModes), 'String']]);
215 * @param string $fieldName
217 * @param array $params
219 protected function assignTestFK($fieldName, $fieldDef, $params) {
220 $required = CRM_Utils_Array
::value('required', $fieldDef);
221 $FKClassName = CRM_Utils_Array
::value('FKClassName', $fieldDef);
222 $dbName = $fieldDef['name'];
223 $daoName = str_replace('_BAO_', '_DAO_', get_class($this));
225 // skip the FK if it is not required
226 // if it's contact id we should create even if not required
227 // we'll have a go @ fetching first though
228 // we WILL create campaigns though for so tests with a campaign pseudoconstant will complete
229 if ($FKClassName === 'CRM_Campaign_DAO_Campaign' && $daoName != $FKClassName) {
232 if (!$required && $dbName != 'contact_id') {
233 $fkDAO = new $FKClassName();
234 if ($fkDAO->find(TRUE)) {
235 $this->$dbName = $fkDAO->id
;
239 elseif (in_array($FKClassName, CRM_Core_DAO
::$_testEntitiesToSkip)) {
240 $depObject = new $FKClassName();
241 $depObject->find(TRUE);
242 $this->$dbName = $depObject->id
;
244 elseif ($daoName == 'CRM_Member_DAO_MembershipType' && $fieldName == 'member_of_contact_id') {
245 // FIXME: the fields() metadata is not specific enough
246 $depObject = CRM_Core_DAO
::createTestObject($FKClassName, ['contact_type' => 'Organization']);
247 $this->$dbName = $depObject->id
;
250 //if it is required we need to generate the dependency object first
251 $depObject = CRM_Core_DAO
::createTestObject($FKClassName, CRM_Utils_Array
::value($dbName, $params, 1));
252 $this->$dbName = $depObject->id
;
257 * Generate and assign an arbitrary value to a field of a test object.
259 * @param string $fieldName
260 * @param array $fieldDef
261 * @param int $counter
262 * The globally-unique ID of the test object.
264 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
265 $dbName = $fieldDef['name'];
266 $daoName = get_class($this);
269 if (!$handled && $dbName == 'contact_sub_type') {
270 //coming up with a rule to set this is too complex let's not set it
274 // Pick an option value if needed
275 if (!$handled && $fieldDef['type'] !== CRM_Utils_Type
::T_BOOLEAN
) {
276 $options = $daoName::buildOptions($dbName, 'create');
278 $this->$dbName = key($options);
284 switch ($fieldDef['type']) {
285 case CRM_Utils_Type
::T_INT
:
286 case CRM_Utils_Type
::T_FLOAT
:
287 case CRM_Utils_Type
::T_MONEY
:
288 if (isset($fieldDef['precision'])) {
289 // $object->$dbName = CRM_Utils_Number::createRandomDecimal($value['precision']);
290 $this->$dbName = CRM_Utils_Number
::createTruncatedDecimal($counter, $fieldDef['precision']);
293 $this->$dbName = $counter;
297 case CRM_Utils_Type
::T_BOOLEAN
:
298 if (isset($fieldDef['default'])) {
299 $this->$dbName = $fieldDef['default'];
301 elseif ($fieldDef['name'] == 'is_deleted' ||
$fieldDef['name'] == 'is_test') {
309 case CRM_Utils_Type
::T_DATE
:
310 case CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
:
311 $this->$dbName = '19700101';
312 if ($dbName == 'end_date') {
313 // put this in the future
314 $this->$dbName = '20200101';
318 case CRM_Utils_Type
::T_TIMESTAMP
:
319 $this->$dbName = '19700201000000';
322 case CRM_Utils_Type
::T_TIME
:
323 CRM_Core_Error
::fatal("T_TIME shouldn't be used.");
324 //$object->$dbName='000000';
326 case CRM_Utils_Type
::T_CCNUM
:
327 $this->$dbName = '4111 1111 1111 1111';
330 case CRM_Utils_Type
::T_URL
:
331 $this->$dbName = 'http://www.civicrm.org';
334 case CRM_Utils_Type
::T_STRING
:
335 case CRM_Utils_Type
::T_BLOB
:
336 case CRM_Utils_Type
::T_MEDIUMBLOB
:
337 case CRM_Utils_Type
::T_TEXT
:
338 case CRM_Utils_Type
::T_LONGTEXT
:
339 case CRM_Utils_Type
::T_EMAIL
:
341 // WAS: if (isset($value['enumValues'])) {
342 // TODO: see if this works with all pseudoconstants
343 if (isset($fieldDef['pseudoconstant'], $fieldDef['pseudoconstant']['callback'])) {
344 if (isset($fieldDef['default'])) {
345 $this->$dbName = $fieldDef['default'];
348 $options = CRM_Core_PseudoConstant
::get($daoName, $fieldName);
349 if (is_array($options)) {
350 $this->$dbName = $options[0];
353 $defaultValues = explode(',', $options);
354 $this->$dbName = $defaultValues[0];
359 $this->$dbName = $dbName . '_' . $counter;
360 $maxlength = CRM_Utils_Array
::value('maxlength', $fieldDef);
361 if ($maxlength > 0 && strlen($this->$dbName) > $maxlength) {
362 $this->$dbName = substr($this->$dbName, 0, $fieldDef['maxlength']);
370 * Reset the DAO object.
372 * DAO is kinda crappy in that there is an unwritten rule of one query per DAO.
374 * We attempt to get around this crappy restriction by resetting some of DAO's internal fields. Use this with caution
376 public function reset() {
378 foreach (array_keys($this->table()) as $field) {
379 unset($this->$field);
383 * reset the various DB_DAO structures manually
392 * @param string $tableName
396 public static function getLocaleTableName($tableName) {
399 $tables = CRM_Core_I18n_Schema
::schemaStructureTables();
400 if (in_array($tableName, $tables)) {
401 return $tableName . $dbLocale;
408 * Execute a query by the current DAO, localizing it along the way (if needed).
410 * @param string $query
411 * The SQL query for execution.
412 * @param bool $i18nRewrite
413 * Whether to rewrite the query.
416 * the current DAO object after the query execution
418 public function query($query, $i18nRewrite = TRUE) {
419 // rewrite queries that should use $dbLocale-based views for multi-language installs
420 global $dbLocale, $_DB_DATAOBJECT;
422 if (empty($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5
])) {
423 // Will force connection to be populated per CRM-20541.
427 $conn = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5
];
428 $orig_options = $conn->options
;
429 $this->_setDBOptions($this->_options
);
431 if ($i18nRewrite and $dbLocale) {
432 $query = CRM_Core_I18n_Schema
::rewriteQuery($query);
435 $ret = parent
::query($query);
437 $this->_setDBOptions($orig_options);
442 * Static function to set the factory instance for this class.
444 * @param object $factory
445 * The factory application object.
447 public static function setFactory(&$factory) {
448 self
::$_factory = &$factory;
452 * Factory method to instantiate a new object from a table name.
454 * @param string $table
455 * @return \DataObject|\PEAR_Error
457 public function factory($table = '') {
458 if (!isset(self
::$_factory)) {
459 return parent
::factory($table);
462 return self
::$_factory->create($table);
466 * Initialization for all DAO objects. Since we access DB_DO programatically
467 * we need to set the links manually.
469 public function initialize() {
471 if (empty(Civi
::$statics[__CLASS__
]['init'])) {
472 // CRM_Core_DAO::init() must be called before CRM_Core_DAO->initialize().
473 // This occurs very early in bootstrap - error handlers may not be wired up.
474 echo "Inconsistent system initialization sequence. Premature access of (" . get_class($this) . ")";
475 CRM_Utils_System
::civiExit();
480 * Defines the default key as 'id'.
484 public function keys() {
493 * Tells DB_DataObject which keys use autoincrement.
494 * 'id' is autoincrementing by default.
499 public function sequenceKey() {
500 static $sequenceKeys;
501 if (!isset($sequenceKeys)) {
502 $sequenceKeys = ['id', TRUE];
504 return $sequenceKeys;
508 * Returns list of FK relationships.
512 * Array of CRM_Core_Reference_Interface
514 public static function getReferenceColumns() {
519 * Returns all the column names of this table.
524 public static function &fields() {
530 * Get/set an associative array of table columns
535 public function table() {
536 $fields = $this->fields();
540 foreach ($fields as $name => $value) {
541 $table[$value['name']] = $value['type'];
542 if (!empty($value['required'])) {
543 $table[$value['name']] +
= self
::DB_DAO_NOTNULL
;
556 * @return CRM_Core_DAO
558 public function save($hook = TRUE) {
559 if (!empty($this->id
)) {
563 $event = new \Civi\Core\DAO\Event\
PostUpdate($this);
564 \Civi
::service('dispatcher')->dispatch("civi.dao.postUpdate", $event);
566 $this->clearDbColumnValueCache();
572 $event = new \Civi\Core\DAO\Event\
PostUpdate($this);
573 \Civi
::service('dispatcher')->dispatch("civi.dao.postInsert", $event);
579 CRM_Utils_Hook
::postSave($this);
586 * Deletes items from table which match current objects variables.
588 * Returns the true on success
592 * Designed to be extended
594 * $object = new mytable();
596 * echo $object->delete(); // builds a conditon
598 * $object = new mytable();
599 * $object->whereAdd('age > 12');
601 * $object->orderBy('age DESC');
602 * $object->delete(true); // dont use object vars, use the conditions, limit and order.
604 * @param bool $useWhere (optional) If DB_DATAOBJECT_WHEREADD_ONLY is passed in then
605 * we will build the condition only using the whereAdd's. Default is to
606 * build the condition only using the object parameters.
608 * * @return mixed Int (No. of rows affected) on success, false on failure, 0 on no data affected
610 public function delete($useWhere = FALSE) {
611 $preEvent = new \Civi\Core\DAO\Event\
PreDelete($this);
612 \Civi
::service('dispatcher')->dispatch("civi.dao.preDelete", $preEvent);
614 $result = parent
::delete($useWhere);
616 $event = new \Civi\Core\DAO\Event\
PostDelete($this, $result);
617 \Civi
::service('dispatcher')->dispatch("civi.dao.postDelete", $event);
620 $this->clearDbColumnValueCache();
626 * @param bool $created
628 public function log($created = FALSE) {
631 if (!$this->getLog()) {
636 $session = CRM_Core_Session
::singleton();
637 $cid = $session->get('userID');
640 // return is we dont have handle to FK
645 $dao = new CRM_Core_DAO_Log();
646 $dao->entity_table
= $this->getTableName();
647 $dao->entity_id
= $this->id
;
648 $dao->modified_id
= $cid;
649 $dao->modified_date
= date("YmdHis");
654 * Given an associative array of name/value pairs, extract all the values
655 * that belong to this object and initialize the object with said values
657 * @param array $params
658 * (reference ) associative array of name/value pairs.
659 * @param bool $serializeArrays
660 * Should arrays that are passed in be serialised according to the metadata.
661 * Eventually this should be always true / gone, but in the interests of caution
662 * it is being grandfathered in. In general an array is not valid on the DAO
663 * but there may be instances where this function is called & then some handling
664 * takes place on the would-be array.
667 * Did we copy all null values into the object
669 public function copyValues(&$params, $serializeArrays = FALSE) {
670 $fields = $this->fields();
672 foreach ($fields as $name => $value) {
673 $dbName = $value['name'];
674 if (array_key_exists($dbName, $params)) {
675 $pValue = $params[$dbName];
678 elseif (array_key_exists($name, $params)) {
679 $pValue = $params[$name];
686 // if there is no value then make the variable NULL
688 if ($pValue === '') {
689 $this->$dbName = 'null';
691 elseif ($serializeArrays && is_array($pValue) && !empty($value['serialize'])) {
692 $this->$dbName = CRM_Core_DAO
::serializeField($pValue, $value['serialize']);
696 if (!$serializeArrays && is_array($pValue) && !empty($value['serialize'])) {
697 Civi
::log()->warning(ts('use copyParams to serialize arrays (' . __CLASS__
. '.' . $name . ')'), ['civi.tag' => 'deprecated']);
699 $maxLength = CRM_Utils_Array
::value('maxlength', $value);
700 if (!is_array($pValue) && $maxLength && mb_strlen($pValue) > $maxLength
701 && empty($value['pseudoconstant'])
703 Civi
::log()->warning(ts('A string for field $dbName has been truncated. The original string was %1', [CRM_Utils_Type
::escape($pValue, 'String')]));
704 // The string is too long - what to do what to do? Well losing data is generally bad so lets' truncate
705 $pValue = CRM_Utils_String
::ellipsify($pValue, $maxLength);
707 $this->$dbName = $pValue;
716 * Store all the values from this object in an associative array
717 * this is a destructive store, calling function is responsible
718 * for keeping sanity of id's.
720 * @param object $object
721 * The object that we are extracting data from.
722 * @param array $values
723 * (reference ) associative array of name/value pairs.
725 public static function storeValues(&$object, &$values) {
726 $fields = $object->fields();
727 foreach ($fields as $name => $value) {
728 $dbName = $value['name'];
729 if (isset($object->$dbName) && $object->$dbName !== 'null') {
730 $values[$dbName] = $object->$dbName;
731 if ($name != $dbName) {
732 $values[$name] = $object->$dbName;
739 * Create an attribute for this specific field. We only do this for strings and text
741 * @param array $field
742 * The field under task.
745 * the attributes for the object
747 public static function makeAttribute($field) {
749 if (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_STRING
) {
750 $maxLength = CRM_Utils_Array
::value('maxlength', $field);
751 $size = CRM_Utils_Array
::value('size', $field);
752 if ($maxLength ||
$size) {
755 $attributes['maxlength'] = $maxLength;
758 $attributes['size'] = $size;
763 elseif (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_TEXT
) {
764 $rows = CRM_Utils_Array
::value('rows', $field);
768 $cols = CRM_Utils_Array
::value('cols', $field);
774 $attributes['rows'] = $rows;
775 $attributes['cols'] = $cols;
778 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
) {
779 $attributes['size'] = 6;
780 $attributes['maxlength'] = 14;
788 * Get the size and maxLength attributes for this text field.
789 * (or for all text fields) in the DAO object.
791 * @param string $class
793 * @param string $fieldName
794 * Field that i'm interested in or null if.
795 * you want the attributes for all DAO text fields
798 * assoc array of name => attribute pairs
800 public static function getAttribute($class, $fieldName = NULL) {
801 $object = new $class();
802 $fields = $object->fields();
803 if ($fieldName != NULL) {
804 $field = CRM_Utils_Array
::value($fieldName, $fields);
805 return self
::makeAttribute($field);
809 foreach ($fields as $name => $field) {
810 $attribute = self
::makeAttribute($field);
812 $attributes[$name] = $attribute;
816 if (!empty($attributes)) {
824 * Check if there is a record with the same name in the db.
826 * @param string $value
827 * The value of the field we are checking.
828 * @param string $daoName
829 * The dao object name.
830 * @param string $daoID
831 * The id of the object being updated. u can change your name.
832 * as long as there is no conflict
833 * @param string $fieldName
834 * The name of the field in the DAO.
836 * @param string $domainID
837 * The id of the domain. Object exists only for the given domain.
840 * true if object exists
842 public static function objectExists($value, $daoName, $daoID, $fieldName = 'name', $domainID = NULL) {
843 $object = new $daoName();
844 $object->$fieldName = $value;
846 $object->domain_id
= $domainID;
849 if ($object->find(TRUE)) {
850 return ($daoID && $object->id
== $daoID) ?
TRUE : FALSE;
858 * Check if there is a given column in a specific table.
861 * @see CRM_Core_BAO_SchemaHandler::checkIfFieldExists
863 * @param string $tableName
864 * @param string $columnName
865 * @param bool $i18nRewrite
866 * Whether to rewrite the query on multilingual setups.
869 * true if exists, else false
871 public static function checkFieldExists($tableName, $columnName, $i18nRewrite = TRUE) {
872 return CRM_Core_BAO_SchemaHandler
::checkIfFieldExists($tableName, $columnName, $i18nRewrite);
876 * Scans all the tables using a slow query and table name.
880 public static function getTableNames() {
881 $dao = CRM_Core_DAO
::executeQuery(
883 FROM information_schema.TABLES
884 WHERE TABLE_SCHEMA = '" . CRM_Core_DAO
::getDatabaseName() . "'
885 AND TABLE_NAME LIKE 'civicrm_%'
886 AND TABLE_NAME NOT LIKE 'civicrm_import_job_%'
887 AND TABLE_NAME NOT LIKE '%_temp%'
890 while ($dao->fetch()) {
891 $values[] = $dao->TABLE_NAME
;
897 * @param int $maxTablesToCheck
901 public static function isDBMyISAM($maxTablesToCheck = 10) {
902 return CRM_Core_DAO
::singleValueQuery(
904 FROM information_schema.TABLES
905 WHERE ENGINE = 'MyISAM'
906 AND TABLE_SCHEMA = '" . CRM_Core_DAO
::getDatabaseName() . "'
907 AND TABLE_NAME LIKE 'civicrm_%'
908 AND TABLE_NAME NOT LIKE 'civicrm_import_job_%'
909 AND TABLE_NAME NOT LIKE '%_temp%'
910 AND TABLE_NAME NOT LIKE 'civicrm_tmp_%'
915 * Get the name of the CiviCRM database.
919 public static function getDatabaseName() {
920 $daoObj = new CRM_Core_DAO();
921 return $daoObj->database();
925 * Checks if a constraint exists for a specified table.
927 * @param string $tableName
928 * @param string $constraint
931 * true if constraint exists, false otherwise
933 public static function checkConstraintExists($tableName, $constraint) {
936 if (!array_key_exists($tableName, $show)) {
937 $query = "SHOW CREATE TABLE $tableName";
938 $dao = CRM_Core_DAO
::executeQuery($query, [], TRUE, NULL, FALSE, FALSE);
940 if (!$dao->fetch()) {
941 CRM_Core_Error
::fatal();
944 $show[$tableName] = $dao->Create_Table
;
947 return preg_match("/\b$constraint\b/i", $show[$tableName]) ?
TRUE : FALSE;
951 * Checks if CONSTRAINT keyword exists for a specified table.
953 * @param array $tables
958 * true if CONSTRAINT keyword exists, false otherwise
960 public static function schemaRequiresRebuilding($tables = ["civicrm_contact"]) {
962 foreach ($tables as $tableName) {
963 if (!array_key_exists($tableName, $show)) {
964 $query = "SHOW CREATE TABLE $tableName";
965 $dao = CRM_Core_DAO
::executeQuery($query, [], TRUE, NULL, FALSE, FALSE);
967 if (!$dao->fetch()) {
968 CRM_Core_Error
::fatal();
971 $show[$tableName] = $dao->Create_Table
;
974 $result = preg_match("/\bCONSTRAINT\b\s/i", $show[$tableName]) ?
TRUE : FALSE;
975 if ($result == TRUE) {
986 * Checks if the FK constraint name is in the format 'FK_tableName_columnName'
987 * for a specified column of a table.
989 * @param string $tableName
990 * @param string $columnName
993 * true if in format, false otherwise
995 public static function checkFKConstraintInFormat($tableName, $columnName) {
998 if (!array_key_exists($tableName, $show)) {
999 $query = "SHOW CREATE TABLE $tableName";
1000 $dao = CRM_Core_DAO
::executeQuery($query);
1002 if (!$dao->fetch()) {
1003 CRM_Core_Error
::fatal();
1006 $show[$tableName] = $dao->Create_Table
;
1008 $constraint = "`FK_{$tableName}_{$columnName}`";
1009 $pattern = "/\bCONSTRAINT\b\s+%s\s+\bFOREIGN\s+KEY\b\s/i";
1010 return preg_match(sprintf($pattern, $constraint), $show[$tableName]) ?
TRUE : FALSE;
1014 * Check whether a specific column in a specific table has always the same value.
1016 * @param string $tableName
1017 * @param string $columnName
1018 * @param string $columnValue
1021 * true if the value is always $columnValue, false otherwise
1023 public static function checkFieldHasAlwaysValue($tableName, $columnName, $columnValue) {
1024 $query = "SELECT * FROM $tableName WHERE $columnName != '$columnValue'";
1025 $dao = CRM_Core_DAO
::executeQuery($query);
1026 $result = $dao->fetch() ?
FALSE : TRUE;
1031 * Check whether a specific column in a specific table is always NULL.
1033 * @param string $tableName
1034 * @param string $columnName
1037 * true if if the value is always NULL, false otherwise
1039 public static function checkFieldIsAlwaysNull($tableName, $columnName) {
1040 $query = "SELECT * FROM $tableName WHERE $columnName IS NOT NULL";
1041 $dao = CRM_Core_DAO
::executeQuery($query);
1042 $result = $dao->fetch() ?
FALSE : TRUE;
1047 * Check if there is a given table in the database.
1049 * @param string $tableName
1052 * true if exists, else false
1054 public static function checkTableExists($tableName) {
1059 $params = [1 => [$tableName, 'String']];
1061 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1062 $result = $dao->fetch() ?
TRUE : FALSE;
1071 public function checkVersion($version) {
1076 $dbVersion = CRM_Core_DAO
::singleValueQuery($query);
1077 return trim($version) == trim($dbVersion) ?
TRUE : FALSE;
1081 * Find a DAO object for the given ID and return it.
1084 * Id of the DAO object being searched for.
1086 * @return CRM_Core_DAO
1087 * Object of the type of the class that called this function.
1091 public static function findById($id) {
1092 $object = new static();
1094 if (!$object->find(TRUE)) {
1095 throw new Exception("Unable to find a " . get_called_class() . " with id {$id}.");
1101 * Returns all results as array-encoded records.
1105 public function fetchAll() {
1107 while ($this->fetch()) {
1108 $result[] = $this->toArray();
1114 * Return the results as PHP generator.
1116 * @param string $type
1117 * Whether the generator yields 'dao' objects or 'array's.
1119 public function fetchGenerator($type = 'dao') {
1120 while ($this->fetch()) {
1127 yield
$this->toArray();
1131 throw new \
RuntimeException("Invalid record type ($type)");
1137 * Returns a singular value.
1139 * @return mixed|NULL
1141 public function fetchValue() {
1142 $result = $this->getDatabaseResult();
1143 $row = $result->fetchRow();
1153 * Get all the result records as mapping between columns.
1155 * @param string $keyColumn
1157 * @param string $valueColumn
1160 * Ex: ["foo" => "The Foo Bar", "baz" => "The Baz Qux"]
1162 public function fetchMap($keyColumn, $valueColumn) {
1164 while ($this->fetch()) {
1165 $result[$this->{$keyColumn}] = $this->{$valueColumn};
1171 * Given a DAO name, a column name and a column value, find the record and GET the value of another column in that record
1173 * @param string $daoName
1174 * Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact).
1175 * @param int $searchValue
1176 * Value of the column you want to search by.
1177 * @param string $returnColumn
1178 * Name of the column you want to GET the value of.
1179 * @param string $searchColumn
1180 * Name of the column you want to search by.
1181 * @param bool $force
1182 * Skip use of the cache.
1184 * @return string|null
1185 * Value of $returnColumn in the retrieved record
1187 public static function getFieldValue($daoName, $searchValue, $returnColumn = 'name', $searchColumn = 'id', $force = FALSE) {
1189 empty($searchValue) ||
1190 trim(strtolower($searchValue)) == 'null'
1192 // adding this here since developers forget to check for an id
1193 // or for the 'null' (which is a bad DAO kludge)
1194 // and hence we get the first value in the db
1195 CRM_Core_Error
::fatal();
1198 self
::$_dbColumnValueCache = self
::$_dbColumnValueCache ??
[];
1200 while (strpos($daoName, '_BAO_') !== FALSE) {
1201 $daoName = get_parent_class($daoName);
1205 empty(self
::$_dbColumnValueCache[$daoName][$searchColumn][$searchValue]) ||
1206 !array_key_exists($returnColumn, self
::$_dbColumnValueCache[$daoName][$searchColumn][$searchValue])
1208 $object = new $daoName();
1209 $object->$searchColumn = $searchValue;
1210 $object->selectAdd();
1211 $object->selectAdd($returnColumn);
1214 if ($object->find(TRUE)) {
1215 $result = $object->$returnColumn;
1218 self
::$_dbColumnValueCache[$daoName][$searchColumn][$searchValue][$returnColumn] = $result;
1220 return self
::$_dbColumnValueCache[$daoName][$searchColumn][$searchValue][$returnColumn];
1224 * Given a DAO name, a column name and a column value, find the record and SET the value of another column in that record
1226 * @param string $daoName
1227 * Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact).
1228 * @param int $searchValue
1229 * Value of the column you want to search by.
1230 * @param string $setColumn
1231 * Name of the column you want to SET the value of.
1232 * @param string $setValue
1233 * SET the setColumn to this value.
1234 * @param string $searchColumn
1235 * Name of the column you want to search by.
1238 * true if we found and updated the object, else false
1240 public static function setFieldValue($daoName, $searchValue, $setColumn, $setValue, $searchColumn = 'id') {
1241 $object = new $daoName();
1242 $object->selectAdd();
1243 $object->selectAdd("$searchColumn, $setColumn");
1244 $object->$searchColumn = $searchValue;
1246 if ($object->find(TRUE)) {
1247 $object->$setColumn = $setValue;
1248 if ($object->save()) {
1259 * @param array|object $sort either array or CRM_Utils_Sort
1260 * @param string $default
1261 * Default sort value.
1265 public static function getSortString($sort, $default = NULL) {
1266 // check if sort is of type CRM_Utils_Sort
1267 if (is_a($sort, 'CRM_Utils_Sort')) {
1268 return $sort->orderBy();
1273 // is it an array specified as $field => $sortDirection ?
1275 foreach ($sort as $k => $v) {
1276 $sortString .= "$k $v,";
1278 return rtrim($sortString, ',');
1284 * Fetch object based on array of properties.
1286 * @param string $daoName
1287 * Name of the dao object.
1288 * @param array $params
1289 * (reference ) an assoc array of name/value pairs.
1290 * @param array $defaults
1291 * (reference ) an assoc array to hold the flattened values.
1292 * @param array $returnProperities
1293 * An assoc array of fields that need to be returned, eg array( 'first_name', 'last_name').
1296 * an object of type referenced by daoName
1298 public static function commonRetrieve($daoName, &$params, &$defaults, $returnProperities = NULL) {
1299 $object = new $daoName();
1300 $object->copyValues($params);
1302 // return only specific fields if returnproperties are sent
1303 if (!empty($returnProperities)) {
1304 $object->selectAdd();
1305 $object->selectAdd(implode(',', $returnProperities));
1308 if ($object->find(TRUE)) {
1309 self
::storeValues($object, $defaults);
1316 * Delete the object records that are associated with this contact.
1318 * @param string $daoName
1319 * Name of the dao object.
1320 * @param int $contactId
1321 * Id of the contact to delete.
1323 public static function deleteEntityContact($daoName, $contactId) {
1324 $object = new $daoName();
1326 $object->entity_table
= 'civicrm_contact';
1327 $object->entity_id
= $contactId;
1332 * Execute an unbuffered query.
1334 * This is a wrapper around new functionality exposed with CRM-17748.
1336 * @param string $query query to be executed
1338 * @param array $params
1339 * @param bool $abort
1340 * @param null $daoName
1341 * @param bool $freeDAO
1342 * @param bool $i18nRewrite
1343 * @param bool $trapException
1345 * @return CRM_Core_DAO
1346 * Object that points to an unbuffered result set
1348 public static function executeUnbufferedQuery(
1354 $i18nRewrite = TRUE,
1355 $trapException = FALSE
1358 return self
::executeQuery(
1366 ['result_buffering' => 0]
1373 * @param string $query
1374 * Query to be executed.
1376 * @param array $params
1377 * @param bool $abort
1378 * @param null $daoName
1379 * @param bool $freeDAO
1380 * @param bool $i18nRewrite
1381 * @param bool $trapException
1382 * @param array $options
1384 * @return CRM_Core_DAO|object
1385 * object that holds the results of the query
1386 * NB - if this is defined as just returning a DAO phpstorm keeps pointing
1387 * out all the properties that are not part of the DAO
1389 public static function &executeQuery(
1395 $i18nRewrite = TRUE,
1396 $trapException = FALSE,
1399 $queryStr = self
::composeQuery($query, $params, $abort);
1402 $dao = new CRM_Core_DAO();
1405 $dao = new $daoName();
1408 if ($trapException) {
1409 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
1412 if ($dao->isValidOption($options)) {
1413 $dao->setOptions($options);
1416 $result = $dao->query($queryStr, $i18nRewrite);
1418 // since it is unbuffered, ($dao->N==0) is true. This blocks the standard fetch() mechanism.
1419 if (CRM_Utils_Array
::value('result_buffering', $options) === 0) {
1423 if (is_a($result, 'DB_Error')) {
1428 preg_match('/^(insert|update|delete|create|drop|replace)/i', $queryStr)
1430 // we typically do this for insert/update/delete statements OR if explicitly asked to
1437 * Wrapper to validate internal DAO options before passing to DB_mysql/DB_Common level
1439 * @param array $options
1442 * Provided options are valid
1444 public function isValidOption($options) {
1453 if (empty($options)) {
1457 foreach (array_keys($options) as $option) {
1458 if (!in_array($option, $validOptions)) {
1468 * Execute a query and get the single result.
1470 * @param string $query
1471 * Query to be executed.
1472 * @param array $params
1473 * @param bool $abort
1474 * @param bool $i18nRewrite
1475 * @return string|null
1476 * the result of the query if any
1479 public static function &singleValueQuery(
1485 $queryStr = self
::composeQuery($query, $params, $abort);
1487 static $_dao = NULL;
1490 $_dao = new CRM_Core_DAO();
1493 $_dao->query($queryStr, $i18nRewrite);
1495 $result = $_dao->getDatabaseResult();
1498 $row = $result->fetchRow();
1508 * Compose the query by merging the parameters into it.
1510 * @param string $query
1511 * @param array $params
1512 * @param bool $abort
1517 public static function composeQuery($query, $params = [], $abort = TRUE) {
1519 foreach ($params as $key => $item) {
1520 if (is_numeric($key)) {
1521 if (CRM_Utils_Type
::validate($item[0], $item[1]) !== NULL) {
1522 $item[0] = self
::escapeString($item[0]);
1523 if ($item[1] == 'String' ||
1524 $item[1] == 'Memo' ||
1527 // Support class constants stipulating wildcard characters and/or
1528 // non-quoting of strings. Also support legacy code which may be
1529 // passing in TRUE or 1 for $item[2], which used to indicate the
1530 // use of wildcard characters.
1531 if (!empty($item[2])) {
1532 if ($item[2] & CRM_Core_DAO
::QUERY_FORMAT_WILDCARD ||
$item[2] === TRUE) {
1533 $item[0] = "'%{$item[0]}%'";
1535 elseif (!($item[2] & CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
)) {
1536 $item[0] = "'{$item[0]}'";
1540 $item[0] = "'{$item[0]}'";
1544 if (($item[1] == 'Date' ||
$item[1] == 'Timestamp') &&
1545 strlen($item[0]) == 0
1550 $tr['%' . $key] = $item[0];
1553 CRM_Core_Error
::fatal("{$item[0]} is not of type {$item[1]}");
1558 return strtr($query, $tr);
1564 public static function freeResult($ids = NULL) {
1565 global $_DB_DATAOBJECT;
1568 if (!$_DB_DATAOBJECT ||
1569 !isset($_DB_DATAOBJECT['RESULTS'])
1573 $ids = array_keys($_DB_DATAOBJECT['RESULTS']);
1576 foreach ($ids as $id) {
1577 if (isset($_DB_DATAOBJECT['RESULTS'][$id])) {
1578 $_DB_DATAOBJECT['RESULTS'][$id]->free();
1579 unset($_DB_DATAOBJECT['RESULTS'][$id]);
1582 if (isset($_DB_DATAOBJECT['RESULTFIELDS'][$id])) {
1583 unset($_DB_DATAOBJECT['RESULTFIELDS'][$id]);
1589 * Make a shallow copy of an object and all the fields in the object.
1591 * @param string $daoName
1593 * @param array $criteria
1594 * Array of all the fields & values.
1595 * on which basis to copy
1596 * @param array $newData
1597 * Array of all the fields & values.
1598 * to be copied besides the other fields
1599 * @param string $fieldsFix
1600 * Array of fields that you want to prefix/suffix/replace.
1601 * @param string $blockCopyOfDependencies
1602 * Fields that you want to block from.
1604 * @param bool $blockCopyofCustomValues
1605 * Case when you don't want to copy the custom values set in a
1606 * template as it will override/ignore the submitted custom values
1608 * @return CRM_Core_DAO|bool
1609 * the newly created copy of the object. False if none created.
1611 public static function copyGeneric($daoName, $criteria, $newData = NULL, $fieldsFix = NULL, $blockCopyOfDependencies = NULL, $blockCopyofCustomValues = FALSE) {
1612 $object = new $daoName();
1615 $object->id
= $criteria['id'];
1618 foreach ($criteria as $key => $value) {
1619 $object->$key = $value;
1624 while ($object->fetch()) {
1626 // all the objects except with $blockCopyOfDependencies set
1627 // be copied - addresses #CRM-1962
1629 if ($blockCopyOfDependencies && $object->$blockCopyOfDependencies) {
1633 $newObject = new $daoName();
1635 $fields = $object->fields();
1636 if (!is_array($fieldsFix)) {
1637 $fieldsToPrefix = [];
1638 $fieldsToSuffix = [];
1639 $fieldsToReplace = [];
1641 if (!empty($fieldsFix['prefix'])) {
1642 $fieldsToPrefix = $fieldsFix['prefix'];
1644 if (!empty($fieldsFix['suffix'])) {
1645 $fieldsToSuffix = $fieldsFix['suffix'];
1647 if (!empty($fieldsFix['replace'])) {
1648 $fieldsToReplace = $fieldsFix['replace'];
1651 foreach ($fields as $name => $value) {
1652 if ($name == 'id' ||
$value['name'] == 'id') {
1653 // copy everything but the id!
1657 $dbName = $value['name'];
1658 $type = CRM_Utils_Type
::typeToString($value['type']);
1659 $newObject->$dbName = $object->$dbName;
1660 if (isset($fieldsToPrefix[$dbName])) {
1661 $newObject->$dbName = $fieldsToPrefix[$dbName] . $newObject->$dbName;
1663 if (isset($fieldsToSuffix[$dbName])) {
1664 $newObject->$dbName .= $fieldsToSuffix[$dbName];
1666 if (isset($fieldsToReplace[$dbName])) {
1667 $newObject->$dbName = $fieldsToReplace[$dbName];
1670 if ($type == 'Timestamp' ||
$type == 'Date') {
1671 $newObject->$dbName = CRM_Utils_Date
::isoToMysql($newObject->$dbName);
1675 $newObject->copyValues($newData);
1679 if (!$blockCopyofCustomValues) {
1680 $newObject->copyCustomFields($object->id
, $newObject->id
);
1682 CRM_Utils_Hook
::post('create', CRM_Core_DAO_AllCoreTables
::getBriefName(str_replace('_BAO_', '_DAO_', $daoName)), $newObject->id
, $newObject);
1689 * Method that copies custom fields values from an old entity to a new one.
1691 * Fixes bug CRM-19302,
1692 * where if a custom field of File type was present, left both events using the same file,
1693 * breaking download URL's for the old event.
1695 * @todo the goal here is to clean this up so that it works for any entity. Copy Generic already DOES some custom field stuff
1696 * but it seems to be bypassed & perhaps less good than this (or this just duplicates it...)
1698 * @param int $entityID
1699 * @param int $newEntityID
1701 public function copyCustomFields($entityID, $newEntityID) {
1702 $entity = CRM_Core_DAO_AllCoreTables
::getBriefName(get_class($this));
1703 $tableName = CRM_Core_DAO_AllCoreTables
::getTableForClass(get_class($this));
1704 // Obtain custom values for old event
1705 $customParams = $htmlType = [];
1706 $customValues = CRM_Core_BAO_CustomValueTable
::getEntityValues($entityID, $entity);
1708 // If custom values present, we copy them
1709 if (!empty($customValues)) {
1710 // Get Field ID's and identify File type attributes, to handle file copying.
1711 $fieldIds = implode(', ', array_keys($customValues));
1712 $sql = "SELECT id FROM civicrm_custom_field WHERE html_type = 'File' AND id IN ( {$fieldIds} )";
1713 $result = CRM_Core_DAO
::executeQuery($sql);
1715 // Build array of File type fields
1716 while ($result->fetch()) {
1717 $htmlType[] = $result->id
;
1720 // Build params array of custom values
1721 foreach ($customValues as $field => $value) {
1722 if ($value !== NULL) {
1723 // Handle File type attributes
1724 if (in_array($field, $htmlType)) {
1725 $fileValues = CRM_Core_BAO_File
::path($value, $entityID);
1726 $customParams["custom_{$field}_-1"] = [
1727 'name' => CRM_Utils_File
::duplicate($fileValues[0]),
1728 'type' => $fileValues[1],
1731 // Handle other types
1733 $customParams["custom_{$field}_-1"] = $value;
1738 // Save Custom Fields for new Event
1739 CRM_Core_BAO_CustomValueTable
::postProcess($customParams, $tableName, $newEntityID, $entity);
1742 // copy activity attachments ( if any )
1743 CRM_Core_BAO_File
::copyEntityFile($tableName, $entityID, $tableName, $newEntityID);
1747 * Cascade update through related entities.
1749 * @param string $daoName
1752 * @param array $newData
1754 * @return CRM_Core_DAO|null
1756 public static function cascadeUpdate($daoName, $fromId, $toId, $newData = []) {
1757 $object = new $daoName();
1758 $object->id
= $fromId;
1760 if ($object->find(TRUE)) {
1761 $newObject = new $daoName();
1762 $newObject->id
= $toId;
1764 if ($newObject->find(TRUE)) {
1765 $fields = $object->fields();
1766 foreach ($fields as $name => $value) {
1767 if ($name == 'id' ||
$value['name'] == 'id') {
1768 // copy everything but the id!
1772 $colName = $value['name'];
1773 $newObject->$colName = $object->$colName;
1775 if (substr($name, -5) == '_date' ||
1776 substr($name, -10) == '_date_time'
1778 $newObject->$colName = CRM_Utils_Date
::isoToMysql($newObject->$colName);
1781 foreach ($newData as $k => $v) {
1782 $newObject->$k = $v;
1792 * Given the component id, compute the contact id
1793 * since its used for things like send email
1795 * @param $componentIDs
1796 * @param string $tableName
1797 * @param string $idField
1801 public static function getContactIDsFromComponent($componentIDs, $tableName, $idField = 'id') {
1804 if (empty($componentIDs)) {
1808 $IDs = implode(',', $componentIDs);
1812 WHERE $idField IN ( $IDs )
1815 $dao = CRM_Core_DAO
::executeQuery($query);
1816 while ($dao->fetch()) {
1817 $contactIDs[] = $dao->contact_id
;
1823 * Fetch object based on array of properties.
1825 * @param string $daoName
1826 * Name of the dao object.
1827 * @param string $fieldIdName
1828 * @param int $fieldId
1830 * @param array $returnProperities
1831 * An assoc array of fields that need to be returned, eg array( 'first_name', 'last_name').
1834 * an object of type referenced by daoName
1836 public static function commonRetrieveAll($daoName, $fieldIdName = 'id', $fieldId, &$details, $returnProperities = NULL) {
1837 require_once str_replace('_', DIRECTORY_SEPARATOR
, $daoName) . ".php";
1838 $object = new $daoName();
1839 $object->$fieldIdName = $fieldId;
1841 // return only specific fields if returnproperties are sent
1842 if (!empty($returnProperities)) {
1843 $object->selectAdd();
1844 $object->selectAdd('id');
1845 $object->selectAdd(implode(',', $returnProperities));
1849 while ($object->fetch()) {
1851 self
::storeValues($object, $defaults);
1852 $details[$object->id
] = $defaults;
1859 * Drop all CiviCRM tables.
1861 * @throws \CRM_Exception
1863 public static function dropAllTables() {
1865 // first drop all the custom tables we've created
1866 CRM_Core_BAO_CustomGroup
::dropAllTables();
1868 // drop all multilingual views
1869 CRM_Core_I18n_Schema
::dropAllViews();
1871 CRM_Utils_File
::sourceSQLFile(CIVICRM_DSN
,
1872 dirname(__FILE__
) . DIRECTORY_SEPARATOR
.
1873 '..' . DIRECTORY_SEPARATOR
.
1874 '..' . DIRECTORY_SEPARATOR
.
1875 'sql' . DIRECTORY_SEPARATOR
.
1876 'civicrm_drop.mysql'
1885 public static function escapeString($string) {
1886 static $_dao = NULL;
1888 // If this is an atypical case (e.g. preparing .sql file before CiviCRM
1889 // has been installed), then we fallback DB-less str_replace escaping, as
1890 // we can't use mysqli_real_escape_string, as there is no DB connection.
1891 // Note: In typical usage, escapeString() will only check one conditional
1892 // ("if !$_dao") rather than two conditionals ("if !defined(DSN)")
1893 if (!defined('CIVICRM_DSN')) {
1894 // See http://php.net/manual/en/mysqli.real-escape-string.php for the
1895 // list of characters mysqli_real_escape_string escapes.
1896 $search = ["\\", "\x00", "\n", "\r", "'", '"', "\x1a"];
1897 $replace = ["\\\\", "\\0", "\\n", "\\r", "\'", '\"', "\\Z"];
1898 return str_replace($search, $replace, $string);
1900 $_dao = new CRM_Core_DAO();
1902 return $_dao->escape($string);
1906 * Escape a list of strings for use with "WHERE X IN (...)" queries.
1908 * @param array $strings
1909 * @param string $default
1910 * the value to use if $strings has no elements.
1912 * eg "abc","def","ghi"
1914 public static function escapeStrings($strings, $default = NULL) {
1915 static $_dao = NULL;
1917 $_dao = new CRM_Core_DAO();
1920 if (empty($strings)) {
1924 $escapes = array_map([$_dao, 'escape'], $strings);
1925 return '"' . implode('","', $escapes) . '"';
1933 public static function escapeWildCardString($string) {
1935 // ensure we escape the single characters % and _ which are mysql wild
1936 // card characters and could come in via sortByCharacter
1937 // note that mysql does not escape these characters
1938 if ($string && in_array($string,
1939 ['%', '_', '%%', '_%']
1942 return '\\' . $string;
1945 return self
::escapeString($string);
1949 * Creates a test object, including any required objects it needs via recursion
1950 * createOnly: only create in database, do not store or return the objects (useful for perf testing)
1951 * ONLY USE FOR TESTING
1953 * @param string $daoName
1954 * @param array $params
1955 * @param int $numObjects
1956 * @param bool $createOnly
1958 * @return object|array|NULL
1959 * NULL if $createOnly. A single object if $numObjects==1. Otherwise, an array of multiple objects.
1961 public static function createTestObject(
1967 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
1968 // so we re-set here in case
1969 $config = CRM_Core_Config
::singleton();
1970 $config->backtrace
= TRUE;
1972 static $counter = 0;
1973 CRM_Core_DAO
::$_testEntitiesToSkip = [
1974 'CRM_Core_DAO_Worldregion',
1975 'CRM_Core_DAO_StateProvince',
1976 'CRM_Core_DAO_Country',
1977 'CRM_Core_DAO_Domain',
1978 'CRM_Financial_DAO_FinancialType',
1979 //because valid ones exist & we use pick them due to pseudoconstant can't reliably create & delete these
1982 // Prefer to instantiate BAO's instead of DAO's (when possible)
1983 // so that assignTestValue()/assignTestFK() can be overloaded.
1984 $baoName = str_replace('_DAO_', '_BAO_', $daoName);
1985 if ($baoName === 'CRM_Financial_BAO_FinancialTrxn') {
1986 // OMG OMG OMG this is so incredibly bad. The BAO is insanely named.
1987 // @todo create a new class called what the BAO SHOULD be
1988 // that extends BAO-crazy-name.... migrate.
1989 $baoName = 'CRM_Core_BAO_FinancialTrxn';
1991 if (class_exists($baoName)) {
1992 $daoName = $baoName;
1995 for ($i = 0; $i < $numObjects; ++
$i) {
1998 /** @var CRM_Core_DAO $object */
1999 $object = new $daoName();
2001 $fields = $object->fields();
2002 foreach ($fields as $fieldName => $fieldDef) {
2003 $dbName = $fieldDef['name'];
2004 $FKClassName = CRM_Utils_Array
::value('FKClassName', $fieldDef);
2005 $required = CRM_Utils_Array
::value('required', $fieldDef);
2007 if (CRM_Utils_Array
::value($dbName, $params) !== NULL && !is_array($params[$dbName])) {
2008 $object->$dbName = $params[$dbName];
2011 elseif ($dbName != 'id') {
2012 if ($FKClassName != NULL) {
2013 $object->assignTestFK($fieldName, $fieldDef, $params);
2017 $object->assignTestValue($fieldName, $fieldDef, $counter);
2025 $objects[$i] = $object;
2035 elseif ($numObjects == 1) {
2044 * Deletes the this object plus any dependent objects that are associated with it.
2045 * ONLY USE FOR TESTING
2047 * @param string $daoName
2048 * @param array $params
2050 public static function deleteTestObjects($daoName, $params = []) {
2051 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
2052 // so we re-set here in case
2053 $config = CRM_Core_Config
::singleton();
2054 $config->backtrace
= TRUE;
2056 $object = new $daoName();
2057 $object->id
= CRM_Utils_Array
::value('id', $params);
2059 // array(array(0 => $daoName, 1 => $daoParams))
2061 if ($object->find(TRUE)) {
2063 $fields = $object->fields();
2064 foreach ($fields as $name => $value) {
2066 $dbName = $value['name'];
2068 $FKClassName = CRM_Utils_Array
::value('FKClassName', $value);
2069 $required = CRM_Utils_Array
::value('required', $value);
2070 if ($FKClassName != NULL
2072 && !in_array($FKClassName, CRM_Core_DAO
::$_testEntitiesToSkip)
2073 && ($required ||
$dbName == 'contact_id')
2074 //I'm a bit stuck on this one - we might need to change the singleValueAlter so that the entities don't share a contact
2075 // to make this test process pass - line below makes pass for now
2076 && $dbName != 'member_of_contact_id'
2079 $deletions[] = [$FKClassName, ['id' => $object->$dbName]];
2086 foreach ($deletions as $deletion) {
2087 CRM_Core_DAO
::deleteTestObjects($deletion[0], $deletion[1]);
2092 * Set defaults when creating new entity.
2093 * (don't call this set defaults as already in use with different signature in some places)
2095 * @param array $params
2098 public static function setCreateDefaults(&$params, $defaults) {
2099 if (!empty($params['id'])) {
2102 foreach ($defaults as $key => $value) {
2103 if (!array_key_exists($key, $params) ||
$params[$key] === NULL) {
2104 $params[$key] = $value;
2110 * @param string $prefix
2111 * @param bool $addRandomString
2112 * @param null $string
2116 * @see CRM_Utils_SQL_TempTable
2118 public static function createTempTableName($prefix = 'civicrm', $addRandomString = TRUE, $string = NULL) {
2119 $tableName = $prefix . "_temp";
2121 if ($addRandomString) {
2123 $tableName .= "_" . $string;
2126 $tableName .= "_" . md5(uniqid('', TRUE));
2134 * @param bool $trigger
2138 public static function checkTriggerViewPermission($view = TRUE, $trigger = TRUE) {
2139 if (\Civi
::settings()->get('logging_no_trigger_permission')) {
2142 // test for create view and trigger permissions and if allowed, add the option to go multilingual
2144 // I'm not sure why we use the getStaticProperty for an error, rather than checking for DB_Error
2145 CRM_Core_TemporaryErrorScope
::ignoreException();
2146 $dao = new CRM_Core_DAO();
2148 $result = $dao->query('CREATE OR REPLACE VIEW civicrm_domain_view AS SELECT * FROM civicrm_domain');
2149 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError') ||
is_a($result, 'DB_Error')) {
2155 $result = $dao->query('CREATE TRIGGER civicrm_domain_trigger BEFORE INSERT ON civicrm_domain FOR EACH ROW BEGIN END');
2156 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError') ||
is_a($result, 'DB_Error')) {
2158 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
2163 $dao->query('DROP TRIGGER IF EXISTS civicrm_domain_trigger');
2164 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
2166 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
2173 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
2174 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
2183 * @param null $message
2184 * @param bool $printDAO
2186 public static function debugPrint($message = NULL, $printDAO = TRUE) {
2187 CRM_Utils_System
::xMemory("{$message}: ");
2190 global $_DB_DATAOBJECT;
2192 foreach (array_keys($_DB_DATAOBJECT['RESULTS']) as $id) {
2193 $q[] = $_DB_DATAOBJECT['RESULTS'][$id]->query
;
2195 CRM_Core_Error
::debug('_DB_DATAOBJECT', $q);
2200 * Build a list of triggers via hook and add them to (err, reconcile them
2201 * with) the database.
2203 * @param string $tableName
2204 * the specific table requiring a rebuild; or NULL to rebuild all tables.
2205 * @param bool $force
2210 public static function triggerRebuild($tableName = NULL, $force = FALSE) {
2211 Civi
::service('sql_triggers')->rebuild($tableName, $force);
2215 * Because sql functions are sometimes lost, esp during db migration, we check here to avoid numerous support requests
2216 * @see http://issues.civicrm.org/jira/browse/CRM-13822
2217 * TODO: Alternative solutions might be
2218 * * Stop using functions and find another way to strip numeric characters from phones
2219 * * Give better error messages (currently a missing fn fatals with "unknown error")
2221 public static function checkSqlFunctionsExist() {
2222 if (!self
::$_checkedSqlFunctionsExist) {
2223 self
::$_checkedSqlFunctionsExist = TRUE;
2224 $dao = CRM_Core_DAO
::executeQuery("SHOW function status WHERE db = database() AND name = 'civicrm_strip_non_numeric'");
2225 if (!$dao->fetch()) {
2226 self
::triggerRebuild();
2232 * Wrapper function to drop triggers.
2234 * @param string $tableName
2235 * the specific table requiring a rebuild; or NULL to rebuild all tables.
2238 public static function dropTriggers($tableName = NULL) {
2239 Civi
::service('sql_triggers')->dropTriggers($tableName);
2243 * @param array $info
2244 * per hook_civicrm_triggerInfo.
2245 * @param string $onlyTableName
2246 * the specific table requiring a rebuild; or NULL to rebuild all tables.
2249 public static function createTriggers(&$info, $onlyTableName = NULL) {
2250 Civi
::service('sql_triggers')->createTriggers($info, $onlyTableName);
2254 * Given a list of fields, create a list of references.
2256 * @param string $className
2257 * BAO/DAO class name.
2258 * @return array<CRM_Core_Reference_Interface>
2260 public static function createReferenceColumns($className) {
2262 $fields = $className::fields();
2263 foreach ($fields as $field) {
2264 if (isset($field['pseudoconstant'], $field['pseudoconstant']['optionGroupName'])) {
2265 $result[] = new CRM_Core_Reference_OptionValue(
2266 $className::getTableName(),
2268 'civicrm_option_value',
2269 CRM_Utils_Array
::value('keyColumn', $field['pseudoconstant'], 'value'),
2270 $field['pseudoconstant']['optionGroupName']
2278 * Find all records which refer to this entity.
2281 * Array of objects referencing this
2283 public function findReferences() {
2284 $links = self
::getReferencesToTable(static::getTableName());
2287 foreach ($links as $refSpec) {
2288 /** @var $refSpec CRM_Core_Reference_Interface */
2289 $daoName = CRM_Core_DAO_AllCoreTables
::getClassForTable($refSpec->getReferenceTable());
2290 $result = $refSpec->findReferences($this);
2292 while ($result->fetch()) {
2293 $obj = new $daoName();
2294 $obj->id
= $result->id
;
2295 $occurrences[] = $obj;
2300 return $occurrences;
2305 * each item has keys:
2309 * - table: string|null SQL table name
2310 * - key: string|null SQL column name
2312 public function getReferenceCounts() {
2313 $links = self
::getReferencesToTable(static::getTableName());
2316 foreach ($links as $refSpec) {
2317 /** @var $refSpec CRM_Core_Reference_Interface */
2318 $count = $refSpec->getReferenceCount($this);
2319 if ($count['count'] != 0) {
2324 foreach (CRM_Core_Component
::getEnabledComponents() as $component) {
2325 /** @var $component CRM_Core_Component_Info */
2326 $counts = array_merge($counts, $component->getReferenceCounts($this));
2328 CRM_Utils_Hook
::referenceCounts($this, $counts);
2334 * List all tables which have hard foreign keys to this table.
2336 * For now, this returns a description of every entity_id/entity_table
2338 * TODO: filter dynamic entity references on the $tableName, based on
2339 * schema metadata in dynamicForeignKey which enumerates a restricted
2340 * set of possible entity_table's.
2342 * @param string $tableName
2343 * Table referred to.
2346 * structure of table and column, listing every table with a
2347 * foreign key reference to $tableName, and the column where the key appears.
2349 public static function getReferencesToTable($tableName) {
2351 foreach (CRM_Core_DAO_AllCoreTables
::getClasses() as $daoClassName) {
2352 $links = $daoClassName::getReferenceColumns();
2353 $daoTableName = $daoClassName::getTableName();
2355 foreach ($links as $refSpec) {
2356 /** @var $refSpec CRM_Core_Reference_Interface */
2357 if ($refSpec->matchesTargetTable($tableName)) {
2358 $refsFound[] = $refSpec;
2366 * Get all references to contact table.
2368 * This includes core tables, custom group tables, tables added by the merge
2369 * hook and the entity_tag table.
2371 * Refer to CRM-17454 for information on the danger of querying the information
2372 * schema to derive this.
2374 public static function getReferencesToContactTable() {
2375 if (isset(\Civi
::$statics[__CLASS__
]) && isset(\Civi
::$statics[__CLASS__
]['contact_references'])) {
2376 return \Civi
::$statics[__CLASS__
]['contact_references'];
2378 $contactReferences = [];
2379 $coreReferences = CRM_Core_DAO
::getReferencesToTable('civicrm_contact');
2380 foreach ($coreReferences as $coreReference) {
2381 if (!is_a($coreReference, 'CRM_Core_Reference_Dynamic')) {
2382 $contactReferences[$coreReference->getReferenceTable()][] = $coreReference->getReferenceKey();
2385 self
::appendCustomTablesExtendingContacts($contactReferences);
2386 self
::appendCustomContactReferenceFields($contactReferences);
2388 // FixME for time being adding below line statically as no Foreign key constraint defined for table 'civicrm_entity_tag'
2389 $contactReferences['civicrm_entity_tag'][] = 'entity_id';
2390 \Civi
::$statics[__CLASS__
]['contact_references'] = $contactReferences;
2391 return \Civi
::$statics[__CLASS__
]['contact_references'];
2395 * Add custom tables that extend contacts to the list of contact references.
2397 * CRM_Core_BAO_CustomGroup::getAllCustomGroupsByBaseEntity seems like a safe-ish
2398 * function to be sure all are retrieved & we don't miss subtypes or inactive or multiples
2399 * - the down side is it is not cached.
2401 * Further changes should be include tests in the CRM_Core_MergerTest class
2402 * to ensure that disabled, subtype, multiple etc groups are still captured.
2404 * @param array $cidRefs
2406 public static function appendCustomTablesExtendingContacts(&$cidRefs) {
2407 $customValueTables = CRM_Core_BAO_CustomGroup
::getAllCustomGroupsByBaseEntity('Contact');
2408 $customValueTables->find();
2409 while ($customValueTables->fetch()) {
2410 $cidRefs[$customValueTables->table_name
][] = 'entity_id';
2415 * Add custom ContactReference fields to the list of contact references
2417 * This includes active and inactive fields/groups
2419 * @param array $cidRefs
2421 * @throws \CiviCRM_API3_Exception
2423 public static function appendCustomContactReferenceFields(&$cidRefs) {
2424 $fields = civicrm_api3('CustomField', 'get', [
2425 'return' => ['column_name', 'custom_group_id.table_name'],
2426 'data_type' => 'ContactReference',
2428 foreach ($fields as $field) {
2429 $cidRefs[$field['custom_group_id.table_name']][] = $field['column_name'];
2434 * Lookup the value of a MySQL global configuration variable.
2436 * @param string $name
2437 * E.g. "thread_stack".
2438 * @param mixed $default
2441 public static function getGlobalSetting($name, $default = NULL) {
2442 // Alternatively, SELECT @@GLOBAL.thread_stack, but
2443 // that has been reported to fail under MySQL 5.0 for OS X
2444 $escapedName = self
::escapeString($name);
2445 $dao = CRM_Core_DAO
::executeQuery("SHOW VARIABLES LIKE '$escapedName'");
2446 if ($dao->fetch()) {
2455 * Update the fields array to also hold keys for pseudoconstant fields that relate to contained fields.
2457 * This is relevant where we want to offer both the ID field and the label field
2458 * as an option, e.g. search builder.
2460 * It is currently limited for optionGroupName & id+ name+ FK combos for purposes keeping the scope of the
2461 * change small, but is appropriate for other sorts of pseudoconstants.
2463 * @param array $fields
2465 public static function appendPseudoConstantsToFields(&$fields) {
2466 foreach ($fields as $field) {
2467 if (!empty($field['pseudoconstant'])) {
2468 $pseudoConstant = $field['pseudoconstant'];
2469 if (!empty($pseudoConstant['optionGroupName'])) {
2470 $fields[$pseudoConstant['optionGroupName']] = [
2471 'title' => CRM_Core_BAO_OptionGroup
::getTitleByName($pseudoConstant['optionGroupName']),
2472 'name' => $pseudoConstant['optionGroupName'],
2473 'data_type' => CRM_Utils_Type
::T_STRING
,
2474 'is_pseudofield_for' => $field['name'],
2477 // We restrict to id + name + FK as we are extending this a bit, but cautiously.
2479 !empty($field['FKClassName'])
2480 && CRM_Utils_Array
::value('keyColumn', $pseudoConstant) === 'id'
2481 && CRM_Utils_Array
::value('labelColumn', $pseudoConstant) === 'name'
2483 $pseudoFieldName = str_replace('_' . $pseudoConstant['keyColumn'], '', $field['name']);
2484 // This if is just an extra caution when adding change.
2485 if (!isset($fields[$pseudoFieldName])) {
2486 $daoName = $field['FKClassName'];
2487 $fkFields = $daoName::fields();
2488 foreach ($fkFields as $fkField) {
2489 if ($fkField['name'] === $pseudoConstant['labelColumn']) {
2490 $fields[$pseudoFieldName] = [
2491 'name' => $pseudoFieldName,
2492 'is_pseudofield_for' => $field['name'],
2493 'title' => $fkField['title'],
2494 'data_type' => $fkField['type'],
2495 'where' => $field['where'],
2506 * Get options for the called BAO object's field.
2508 * This function can be overridden by each BAO to add more logic related to context.
2509 * The overriding function will generally call the lower-level CRM_Core_PseudoConstant::get
2511 * @param string $fieldName
2512 * @param string $context
2513 * @see CRM_Core_DAO::buildOptionsContext
2514 * @param array $props
2515 * whatever is known about this bao object.
2517 * @return array|bool
2519 public static function buildOptions($fieldName, $context = NULL, $props = []) {
2520 // If a given bao does not override this function
2521 $baoName = get_called_class();
2522 return CRM_Core_PseudoConstant
::get($baoName, $fieldName, $props, $context);
2526 * Populate option labels for this object's fields.
2528 * @throws exception if called directly on the base class
2530 public function getOptionLabels() {
2531 $fields = $this->fields();
2532 if ($fields === NULL) {
2533 throw new Exception('Cannot call getOptionLabels on CRM_Core_DAO');
2535 foreach ($fields as $field) {
2536 $name = CRM_Utils_Array
::value('name', $field);
2537 if ($name && isset($this->$name)) {
2538 $label = CRM_Core_PseudoConstant
::getLabel(get_class($this), $name, $this->$name);
2539 if ($label !== FALSE) {
2540 // Append 'label' onto the field name
2541 $labelName = $name . '_label';
2542 $this->$labelName = $label;
2549 * Provides documentation and validation for the buildOptions $context param
2551 * @param string $context
2556 public static function buildOptionsContext($context = NULL) {
2558 'get' => "get: all options are returned, even if they are disabled; labels are translated.",
2559 'create' => "create: options are filtered appropriately for the object being created/updated; labels are translated.",
2560 'search' => "search: searchable options are returned; labels are translated.",
2561 'validate' => "validate: all options are returned, even if they are disabled; machine names are used in place of labels.",
2562 'abbreviate' => "abbreviate: enabled options are returned; labels are replaced with abbreviations.",
2563 'match' => "match: enabled options are returned using machine names as keys; labels are translated.",
2565 // Validation: enforce uniformity of this param
2566 if ($context !== NULL && !isset($contexts[$context])) {
2567 throw new Exception("'$context' is not a valid context for buildOptions.");
2573 * @param string $fieldName
2574 * @return bool|array
2576 public function getFieldSpec($fieldName) {
2577 $fields = $this->fields();
2578 $fieldKeys = $this->fieldKeys();
2580 // Support "unique names" as well as sql names
2581 $fieldKey = $fieldName;
2582 if (empty($fields[$fieldKey])) {
2583 $fieldKey = CRM_Utils_Array
::value($fieldName, $fieldKeys);
2585 // If neither worked then this field doesn't exist. Return false.
2586 if (empty($fields[$fieldKey])) {
2589 return $fields[$fieldKey];
2593 * Get SQL where clause for SQL filter syntax input parameters.
2595 * SQL version of api function to assign filters to the DAO based on the syntax
2596 * $field => array('IN' => array(4,6,9))
2598 * $field => array('LIKE' => array('%me%))
2601 * @param string $fieldName
2603 * @param array $filter
2604 * filter to be applied indexed by operator.
2605 * @param string $type
2606 * type of field (not actually used - nor in api @todo ).
2607 * @param string $alias
2608 * alternative field name ('as') @todo- not actually used.
2609 * @param bool $returnSanitisedArray
2610 * Return a sanitised array instead of a clause.
2611 * this is primarily so we can add filters @ the api level to the Query object based fields
2615 * @return NULL|string|array
2616 * a string is returned if $returnSanitisedArray is not set, otherwise and Array or NULL
2617 * depending on whether it is supported as yet
2619 public static function createSQLFilter($fieldName, $filter, $type = NULL, $alias = NULL, $returnSanitisedArray = FALSE) {
2620 foreach ($filter as $operator => $criteria) {
2621 if (in_array($operator, self
::acceptedSQLOperators(), TRUE)) {
2622 switch ($operator) {
2626 if (!$returnSanitisedArray) {
2627 return (sprintf('%s %s', $fieldName, $operator));
2630 return (sprintf('%s %s ', $fieldName, $operator));
2634 // ternary operators
2637 if ((empty($criteria[0]) && !in_array($criteria[0], ['0', 0]))||
(empty($criteria[1]) && !in_array($criteria[1], ['0', 0]))) {
2638 throw new Exception("invalid criteria for $operator");
2640 if (!$returnSanitisedArray) {
2641 return (sprintf('%s ' . $operator . ' "%s" AND "%s"', $fieldName, CRM_Core_DAO
::escapeString($criteria[0]), CRM_Core_DAO
::escapeString($criteria[1])));
2644 // not yet implemented (tests required to implement)
2652 if (empty($criteria)) {
2653 throw new Exception("invalid criteria for $operator");
2655 $escapedCriteria = array_map([
2659 if (!$returnSanitisedArray) {
2660 return (sprintf('%s %s ("%s")', $fieldName, $operator, implode('", "', $escapedCriteria)));
2662 return $escapedCriteria;
2667 if (!$returnSanitisedArray) {
2668 return (sprintf('%s %s "%s"', $fieldName, $operator, CRM_Core_DAO
::escapeString($criteria)));
2671 // not yet implemented (tests required to implement)
2680 * @see http://issues.civicrm.org/jira/browse/CRM-9150
2681 * support for other syntaxes is discussed in ticket but being put off for now
2684 public static function acceptedSQLOperators() {
2705 * SQL has a limit of 64 characters on various names:
2706 * table name, trigger name, column name ...
2708 * For custom groups and fields we generated names from user entered input
2709 * which can be longer than this length, this function helps with creating
2710 * strings that meet various criteria.
2712 * @param string $string
2713 * The string to be shortened.
2714 * @param int $length
2715 * The max length of the string.
2717 * @param bool $makeRandom
2721 public static function shortenSQLName($string, $length = 60, $makeRandom = FALSE) {
2722 // early return for strings that meet the requirements
2723 if (strlen($string) <= $length) {
2727 // easy return for calls that dont need a randomized uniq string
2729 return substr($string, 0, $length);
2732 // the string is longer than the length and we need a uniq string
2733 // for the same tablename we need the same uniq string every time
2734 // hence we use md5 on the string, which is not random
2735 // we'll append 8 characters to the end of the tableName
2736 $md5string = substr(md5($string), 0, 8);
2737 return substr($string, 0, $length - 8) . "_{$md5string}";
2741 * https://issues.civicrm.org/jira/browse/CRM-17748
2742 * Sets the internal options to be used on a query
2744 * @param array $options
2747 public function setOptions($options) {
2748 if (is_array($options)) {
2749 $this->_options
= $options;
2754 * https://issues.civicrm.org/jira/browse/CRM-17748
2755 * wrapper to pass internal DAO options down to DB_mysql/DB_Common level
2757 * @param array $options
2760 protected function _setDBOptions($options) {
2761 global $_DB_DATAOBJECT;
2763 if (is_array($options) && count($options)) {
2764 $conn = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5
];
2765 foreach ($options as $option_name => $option_value) {
2766 $conn->setOption($option_name, $option_value);
2773 * @param array $params
2775 public function setApiFilter(&$params) {
2779 * Generates acl clauses suitable for adding to WHERE or ON when doing an api.get for this entity
2781 * Return format is in the form of fieldname => clauses starting with an operator. e.g.:
2784 * 'location_type_id' => array('IS NOT NULL', 'IN (1,2,3)')
2788 * Note that all array keys must be actual field names in this entity. Use subqueries to filter on other tables e.g. custom values.
2792 public function addSelectWhereClause() {
2794 $fields = $this->fields();
2795 foreach ($fields as $fieldName => $field) {
2796 // Clause for contact-related entities like Email, Relationship, etc.
2797 if (strpos($fieldName, 'contact_id') === 0 && CRM_Utils_Array
::value('FKClassName', $field) == 'CRM_Contact_DAO_Contact') {
2798 $clauses[$fieldName] = CRM_Utils_SQL
::mergeSubquery('Contact');
2800 // Clause for an entity_table/entity_id combo
2801 if ($fieldName == 'entity_id' && isset($fields['entity_table'])) {
2802 $relatedClauses = [];
2803 $relatedEntities = $this->buildOptions('entity_table', 'get');
2804 foreach ((array) $relatedEntities as $table => $ent) {
2806 $ent = CRM_Core_DAO_AllCoreTables
::getBriefName(CRM_Core_DAO_AllCoreTables
::getClassForTable($table));
2807 $subquery = CRM_Utils_SQL
::mergeSubquery($ent);
2809 $relatedClauses[] = "(entity_table = '$table' AND entity_id " . implode(' AND entity_id ', $subquery) . ")";
2812 $relatedClauses[] = "(entity_table = '$table')";
2816 if ($relatedClauses) {
2817 $clauses['id'] = 'IN (SELECT id FROM `' . $this->tableName() . '` WHERE (' . implode(') OR (', $relatedClauses) . '))';
2821 CRM_Utils_Hook
::selectWhereClause($this, $clauses);
2826 * This returns the final permissioned query string for this entity
2828 * With acls from related entities + additional clauses from hook_civicrm_selectWhereClause
2830 * @param string $tableAlias
2833 public static function getSelectWhereClause($tableAlias = NULL) {
2834 $bao = new static();
2835 if ($tableAlias === NULL) {
2836 $tableAlias = $bao->tableName();
2839 foreach ((array) $bao->addSelectWhereClause() as $field => $vals) {
2840 $clauses[$field] = NULL;
2842 $clauses[$field] = "(`$tableAlias`.`$field` IS NULL OR (`$tableAlias`.`$field` " . implode(" AND `$tableAlias`.`$field` ", (array) $vals) . '))';
2849 * ensure database name is 'safe', i.e. only contains word characters (includes underscores)
2850 * and dashes, and contains at least one [a-z] case insenstive.
2856 public static function requireSafeDBName($database) {
2859 "/^[\w\-]*[a-z]+[\w\-]*$/i",
2863 if (empty($matches)) {
2870 * Transform an array to a serialized string for database storage.
2872 * @param array|null $value
2873 * @param int $serializationType
2874 * @return string|null
2876 * @throws \Exception
2878 public static function serializeField($value, $serializationType) {
2879 if ($value === NULL) {
2882 switch ($serializationType) {
2883 case self
::SERIALIZE_SEPARATOR_BOOKEND
:
2884 return $value === [] ?
'' : CRM_Utils_Array
::implodePadded($value);
2886 case self
::SERIALIZE_SEPARATOR_TRIMMED
:
2887 return is_array($value) ?
implode(self
::VALUE_SEPARATOR
, $value) : $value;
2889 case self
::SERIALIZE_JSON
:
2890 return is_array($value) ?
json_encode($value) : $value;
2892 case self
::SERIALIZE_PHP
:
2893 return is_array($value) ?
serialize($value) : $value;
2895 case self
::SERIALIZE_COMMA
:
2896 return is_array($value) ?
implode(',', $value) : $value;
2899 throw new Exception('Unknown serialization method for field.');
2904 * Transform a serialized string from the database into an array.
2906 * @param string|null $value
2907 * @param $serializationType
2909 * @return array|null
2910 * @throws CRM_Core_Exception
2912 public static function unSerializeField($value, $serializationType) {
2913 if ($value === NULL) {
2916 if ($value === '') {
2919 switch ($serializationType) {
2920 case self
::SERIALIZE_SEPARATOR_BOOKEND
:
2921 return (array) CRM_Utils_Array
::explodePadded($value);
2923 case self
::SERIALIZE_SEPARATOR_TRIMMED
:
2924 return explode(self
::VALUE_SEPARATOR
, trim($value));
2926 case self
::SERIALIZE_JSON
:
2927 return strlen($value) ?
json_decode($value, TRUE) : [];
2929 case self
::SERIALIZE_PHP
:
2930 return strlen($value) ?
unserialize($value, ['allowed_classes' => FALSE]) : [];
2932 case self
::SERIALIZE_COMMA
:
2933 return explode(',', trim(str_replace(', ', '', $value)));
2936 throw new CRM_Core_Exception('Unknown serialization method for field.');
2943 public static function getEntityRefFilters() {
2948 * Get exportable fields with pseudoconstants rendered as an extra field.
2950 * @param string $baoClass
2954 public static function getExportableFieldsWithPseudoConstants($baoClass) {
2955 if (method_exists($baoClass, 'exportableFields')) {
2956 $fields = $baoClass::exportableFields();
2959 $fields = $baoClass::export();
2961 CRM_Core_DAO
::appendPseudoConstantsToFields($fields);
2966 * Remove item from static cache during update/delete operations
2968 private function clearDbColumnValueCache() {
2969 $daoName = get_class($this);
2970 while (strpos($daoName, '_BAO_') !== FALSE) {
2971 $daoName = get_parent_class($daoName);
2973 if (isset($this->id
)) {
2974 unset(self
::$_dbColumnValueCache[$daoName]['id'][$this->id
]);
2976 if (isset($this->name
)) {
2977 unset(self
::$_dbColumnValueCache[$daoName]['name'][$this->name
]);