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);
571 $event = new \Civi\Core\DAO\Event\
PostUpdate($this);
572 \Civi
::service('dispatcher')->dispatch("civi.dao.postInsert", $event);
578 CRM_Utils_Hook
::postSave($this);
585 * Deletes items from table which match current objects variables.
587 * Returns the true on success
591 * Designed to be extended
593 * $object = new mytable();
595 * echo $object->delete(); // builds a conditon
597 * $object = new mytable();
598 * $object->whereAdd('age > 12');
600 * $object->orderBy('age DESC');
601 * $object->delete(true); // dont use object vars, use the conditions, limit and order.
603 * @param bool $useWhere (optional) If DB_DATAOBJECT_WHEREADD_ONLY is passed in then
604 * we will build the condition only using the whereAdd's. Default is to
605 * build the condition only using the object parameters.
607 * * @return mixed Int (No. of rows affected) on success, false on failure, 0 on no data affected
609 public function delete($useWhere = FALSE) {
610 $preEvent = new \Civi\Core\DAO\Event\
PreDelete($this);
611 \Civi
::service('dispatcher')->dispatch("civi.dao.preDelete", $preEvent);
613 $result = parent
::delete($useWhere);
615 $event = new \Civi\Core\DAO\Event\
PostDelete($this, $result);
616 \Civi
::service('dispatcher')->dispatch("civi.dao.postDelete", $event);
623 * @param bool $created
625 public function log($created = FALSE) {
628 if (!$this->getLog()) {
633 $session = CRM_Core_Session
::singleton();
634 $cid = $session->get('userID');
637 // return is we dont have handle to FK
642 $dao = new CRM_Core_DAO_Log();
643 $dao->entity_table
= $this->getTableName();
644 $dao->entity_id
= $this->id
;
645 $dao->modified_id
= $cid;
646 $dao->modified_date
= date("YmdHis");
651 * Given an associative array of name/value pairs, extract all the values
652 * that belong to this object and initialize the object with said values
654 * @param array $params
655 * (reference ) associative array of name/value pairs.
656 * @param bool $serializeArrays
657 * Should arrays that are passed in be serialised according to the metadata.
658 * Eventually this should be always true / gone, but in the interests of caution
659 * it is being grandfathered in. In general an array is not valid on the DAO
660 * but there may be instances where this function is called & then some handling
661 * takes place on the would-be array.
664 * Did we copy all null values into the object
666 public function copyValues(&$params, $serializeArrays = FALSE) {
667 $fields = $this->fields();
669 foreach ($fields as $name => $value) {
670 $dbName = $value['name'];
671 if (array_key_exists($dbName, $params)) {
672 $pValue = $params[$dbName];
675 elseif (array_key_exists($name, $params)) {
676 $pValue = $params[$name];
683 // if there is no value then make the variable NULL
685 if ($pValue === '') {
686 $this->$dbName = 'null';
688 elseif ($serializeArrays && is_array($pValue) && !empty($value['serialize'])) {
689 $this->$dbName = CRM_Core_DAO
::serializeField($pValue, $value['serialize']);
693 if (!$serializeArrays && is_array($pValue) && !empty($value['serialize'])) {
694 Civi
::log()->warning(ts('use copyParams to serialize arrays (' . __CLASS__
. '.' . $name . ')'), ['civi.tag' => 'deprecated']);
696 $maxLength = CRM_Utils_Array
::value('maxlength', $value);
697 if (!is_array($pValue) && $maxLength && mb_strlen($pValue) > $maxLength
698 && empty($value['pseudoconstant'])
700 Civi
::log()->warning(ts('A string for field $dbName has been truncated. The original string was %1', [CRM_Utils_Type
::escape($pValue, 'String')]));
701 // The string is too long - what to do what to do? Well losing data is generally bad so lets' truncate
702 $pValue = CRM_Utils_String
::ellipsify($pValue, $maxLength);
704 $this->$dbName = $pValue;
713 * Store all the values from this object in an associative array
714 * this is a destructive store, calling function is responsible
715 * for keeping sanity of id's.
717 * @param object $object
718 * The object that we are extracting data from.
719 * @param array $values
720 * (reference ) associative array of name/value pairs.
722 public static function storeValues(&$object, &$values) {
723 $fields = $object->fields();
724 foreach ($fields as $name => $value) {
725 $dbName = $value['name'];
726 if (isset($object->$dbName) && $object->$dbName !== 'null') {
727 $values[$dbName] = $object->$dbName;
728 if ($name != $dbName) {
729 $values[$name] = $object->$dbName;
736 * Create an attribute for this specific field. We only do this for strings and text
738 * @param array $field
739 * The field under task.
742 * the attributes for the object
744 public static function makeAttribute($field) {
746 if (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_STRING
) {
747 $maxLength = CRM_Utils_Array
::value('maxlength', $field);
748 $size = CRM_Utils_Array
::value('size', $field);
749 if ($maxLength ||
$size) {
752 $attributes['maxlength'] = $maxLength;
755 $attributes['size'] = $size;
760 elseif (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_TEXT
) {
761 $rows = CRM_Utils_Array
::value('rows', $field);
765 $cols = CRM_Utils_Array
::value('cols', $field);
771 $attributes['rows'] = $rows;
772 $attributes['cols'] = $cols;
775 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
) {
776 $attributes['size'] = 6;
777 $attributes['maxlength'] = 14;
785 * Get the size and maxLength attributes for this text field.
786 * (or for all text fields) in the DAO object.
788 * @param string $class
790 * @param string $fieldName
791 * Field that i'm interested in or null if.
792 * you want the attributes for all DAO text fields
795 * assoc array of name => attribute pairs
797 public static function getAttribute($class, $fieldName = NULL) {
798 $object = new $class();
799 $fields = $object->fields();
800 if ($fieldName != NULL) {
801 $field = CRM_Utils_Array
::value($fieldName, $fields);
802 return self
::makeAttribute($field);
806 foreach ($fields as $name => $field) {
807 $attribute = self
::makeAttribute($field);
809 $attributes[$name] = $attribute;
813 if (!empty($attributes)) {
821 * Check if there is a record with the same name in the db.
823 * @param string $value
824 * The value of the field we are checking.
825 * @param string $daoName
826 * The dao object name.
827 * @param string $daoID
828 * The id of the object being updated. u can change your name.
829 * as long as there is no conflict
830 * @param string $fieldName
831 * The name of the field in the DAO.
833 * @param string $domainID
834 * The id of the domain. Object exists only for the given domain.
837 * true if object exists
839 public static function objectExists($value, $daoName, $daoID, $fieldName = 'name', $domainID = NULL) {
840 $object = new $daoName();
841 $object->$fieldName = $value;
843 $object->domain_id
= $domainID;
846 if ($object->find(TRUE)) {
847 return ($daoID && $object->id
== $daoID) ?
TRUE : FALSE;
855 * Check if there is a given column in a specific table.
858 * @see CRM_Core_BAO_SchemaHandler::checkIfFieldExists
860 * @param string $tableName
861 * @param string $columnName
862 * @param bool $i18nRewrite
863 * Whether to rewrite the query on multilingual setups.
866 * true if exists, else false
868 public static function checkFieldExists($tableName, $columnName, $i18nRewrite = TRUE) {
869 return CRM_Core_BAO_SchemaHandler
::checkIfFieldExists($tableName, $columnName, $i18nRewrite);
873 * Scans all the tables using a slow query and table name.
877 public static function getTableNames() {
878 $dao = CRM_Core_DAO
::executeQuery(
880 FROM information_schema.TABLES
881 WHERE TABLE_SCHEMA = '" . CRM_Core_DAO
::getDatabaseName() . "'
882 AND TABLE_NAME LIKE 'civicrm_%'
883 AND TABLE_NAME NOT LIKE 'civicrm_import_job_%'
884 AND TABLE_NAME NOT LIKE '%_temp%'
887 while ($dao->fetch()) {
888 $values[] = $dao->TABLE_NAME
;
894 * @param int $maxTablesToCheck
898 public static function isDBMyISAM($maxTablesToCheck = 10) {
899 return CRM_Core_DAO
::singleValueQuery(
901 FROM information_schema.TABLES
902 WHERE ENGINE = 'MyISAM'
903 AND TABLE_SCHEMA = '" . CRM_Core_DAO
::getDatabaseName() . "'
904 AND TABLE_NAME LIKE 'civicrm_%'
905 AND TABLE_NAME NOT LIKE 'civicrm_import_job_%'
906 AND TABLE_NAME NOT LIKE '%_temp%'
907 AND TABLE_NAME NOT LIKE 'civicrm_tmp_%'
912 * Get the name of the CiviCRM database.
916 public static function getDatabaseName() {
917 $daoObj = new CRM_Core_DAO();
918 return $daoObj->database();
922 * Checks if a constraint exists for a specified table.
924 * @param string $tableName
925 * @param string $constraint
928 * true if constraint exists, false otherwise
930 public static function checkConstraintExists($tableName, $constraint) {
933 if (!array_key_exists($tableName, $show)) {
934 $query = "SHOW CREATE TABLE $tableName";
935 $dao = CRM_Core_DAO
::executeQuery($query, [], TRUE, NULL, FALSE, FALSE);
937 if (!$dao->fetch()) {
938 CRM_Core_Error
::fatal();
941 $show[$tableName] = $dao->Create_Table
;
944 return preg_match("/\b$constraint\b/i", $show[$tableName]) ?
TRUE : FALSE;
948 * Checks if CONSTRAINT keyword exists for a specified table.
950 * @param array $tables
955 * true if CONSTRAINT keyword exists, false otherwise
957 public static function schemaRequiresRebuilding($tables = ["civicrm_contact"]) {
959 foreach ($tables as $tableName) {
960 if (!array_key_exists($tableName, $show)) {
961 $query = "SHOW CREATE TABLE $tableName";
962 $dao = CRM_Core_DAO
::executeQuery($query, [], TRUE, NULL, FALSE, FALSE);
964 if (!$dao->fetch()) {
965 CRM_Core_Error
::fatal();
968 $show[$tableName] = $dao->Create_Table
;
971 $result = preg_match("/\bCONSTRAINT\b\s/i", $show[$tableName]) ?
TRUE : FALSE;
972 if ($result == TRUE) {
983 * Checks if the FK constraint name is in the format 'FK_tableName_columnName'
984 * for a specified column of a table.
986 * @param string $tableName
987 * @param string $columnName
990 * true if in format, false otherwise
992 public static function checkFKConstraintInFormat($tableName, $columnName) {
995 if (!array_key_exists($tableName, $show)) {
996 $query = "SHOW CREATE TABLE $tableName";
997 $dao = CRM_Core_DAO
::executeQuery($query);
999 if (!$dao->fetch()) {
1000 CRM_Core_Error
::fatal();
1003 $show[$tableName] = $dao->Create_Table
;
1005 $constraint = "`FK_{$tableName}_{$columnName}`";
1006 $pattern = "/\bCONSTRAINT\b\s+%s\s+\bFOREIGN\s+KEY\b\s/i";
1007 return preg_match(sprintf($pattern, $constraint), $show[$tableName]) ?
TRUE : FALSE;
1011 * Check whether a specific column in a specific table has always the same value.
1013 * @param string $tableName
1014 * @param string $columnName
1015 * @param string $columnValue
1018 * true if the value is always $columnValue, false otherwise
1020 public static function checkFieldHasAlwaysValue($tableName, $columnName, $columnValue) {
1021 $query = "SELECT * FROM $tableName WHERE $columnName != '$columnValue'";
1022 $dao = CRM_Core_DAO
::executeQuery($query);
1023 $result = $dao->fetch() ?
FALSE : TRUE;
1028 * Check whether a specific column in a specific table is always NULL.
1030 * @param string $tableName
1031 * @param string $columnName
1034 * true if if the value is always NULL, false otherwise
1036 public static function checkFieldIsAlwaysNull($tableName, $columnName) {
1037 $query = "SELECT * FROM $tableName WHERE $columnName IS NOT NULL";
1038 $dao = CRM_Core_DAO
::executeQuery($query);
1039 $result = $dao->fetch() ?
FALSE : TRUE;
1044 * Check if there is a given table in the database.
1046 * @param string $tableName
1049 * true if exists, else false
1051 public static function checkTableExists($tableName) {
1056 $params = [1 => [$tableName, 'String']];
1058 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1059 $result = $dao->fetch() ?
TRUE : FALSE;
1068 public function checkVersion($version) {
1073 $dbVersion = CRM_Core_DAO
::singleValueQuery($query);
1074 return trim($version) == trim($dbVersion) ?
TRUE : FALSE;
1078 * Find a DAO object for the given ID and return it.
1081 * Id of the DAO object being searched for.
1083 * @return CRM_Core_DAO
1084 * Object of the type of the class that called this function.
1088 public static function findById($id) {
1089 $object = new static();
1091 if (!$object->find(TRUE)) {
1092 throw new Exception("Unable to find a " . get_called_class() . " with id {$id}.");
1098 * Returns all results as array-encoded records.
1102 public function fetchAll() {
1104 while ($this->fetch()) {
1105 $result[] = $this->toArray();
1111 * Return the results as PHP generator.
1113 * @param string $type
1114 * Whether the generator yields 'dao' objects or 'array's.
1116 public function fetchGenerator($type = 'dao') {
1117 while ($this->fetch()) {
1124 yield
$this->toArray();
1128 throw new \
RuntimeException("Invalid record type ($type)");
1134 * Returns a singular value.
1136 * @return mixed|NULL
1138 public function fetchValue() {
1139 $result = $this->getDatabaseResult();
1140 $row = $result->fetchRow();
1150 * Get all the result records as mapping between columns.
1152 * @param string $keyColumn
1154 * @param string $valueColumn
1157 * Ex: ["foo" => "The Foo Bar", "baz" => "The Baz Qux"]
1159 public function fetchMap($keyColumn, $valueColumn) {
1161 while ($this->fetch()) {
1162 $result[$this->{$keyColumn}] = $this->{$valueColumn};
1168 * Given a DAO name, a column name and a column value, find the record and GET the value of another column in that record
1170 * @param string $daoName
1171 * Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact).
1172 * @param int $searchValue
1173 * Value of the column you want to search by.
1174 * @param string $returnColumn
1175 * Name of the column you want to GET the value of.
1176 * @param string $searchColumn
1177 * Name of the column you want to search by.
1178 * @param bool $force
1179 * Skip use of the cache.
1181 * @return string|null
1182 * Value of $returnColumn in the retrieved record
1184 public static function getFieldValue($daoName, $searchValue, $returnColumn = 'name', $searchColumn = 'id', $force = FALSE) {
1186 empty($searchValue) ||
1187 trim(strtolower($searchValue)) == 'null'
1189 // adding this here since developers forget to check for an id
1190 // or for the 'null' (which is a bad DAO kludge)
1191 // and hence we get the first value in the db
1192 CRM_Core_Error
::fatal();
1195 $cacheKey = "{$daoName}:{$searchValue}:{$returnColumn}:{$searchColumn}";
1196 if (self
::$_dbColumnValueCache === NULL) {
1197 self
::$_dbColumnValueCache = [];
1200 if (!array_key_exists($cacheKey, self
::$_dbColumnValueCache) ||
$force) {
1201 $object = new $daoName();
1202 $object->$searchColumn = $searchValue;
1203 $object->selectAdd();
1204 $object->selectAdd($returnColumn);
1207 if ($object->find(TRUE)) {
1208 $result = $object->$returnColumn;
1212 self
::$_dbColumnValueCache[$cacheKey] = $result;
1214 return self
::$_dbColumnValueCache[$cacheKey];
1218 * Given a DAO name, a column name and a column value, find the record and SET the value of another column in that record
1220 * @param string $daoName
1221 * Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact).
1222 * @param int $searchValue
1223 * Value of the column you want to search by.
1224 * @param string $setColumn
1225 * Name of the column you want to SET the value of.
1226 * @param string $setValue
1227 * SET the setColumn to this value.
1228 * @param string $searchColumn
1229 * Name of the column you want to search by.
1232 * true if we found and updated the object, else false
1234 public static function setFieldValue($daoName, $searchValue, $setColumn, $setValue, $searchColumn = 'id') {
1235 $object = new $daoName();
1236 $object->selectAdd();
1237 $object->selectAdd("$searchColumn, $setColumn");
1238 $object->$searchColumn = $searchValue;
1240 if ($object->find(TRUE)) {
1241 $object->$setColumn = $setValue;
1242 if ($object->save()) {
1253 * @param array|object $sort either array or CRM_Utils_Sort
1254 * @param string $default
1255 * Default sort value.
1259 public static function getSortString($sort, $default = NULL) {
1260 // check if sort is of type CRM_Utils_Sort
1261 if (is_a($sort, 'CRM_Utils_Sort')) {
1262 return $sort->orderBy();
1267 // is it an array specified as $field => $sortDirection ?
1269 foreach ($sort as $k => $v) {
1270 $sortString .= "$k $v,";
1272 return rtrim($sortString, ',');
1278 * Fetch object based on array of properties.
1280 * @param string $daoName
1281 * Name of the dao object.
1282 * @param array $params
1283 * (reference ) an assoc array of name/value pairs.
1284 * @param array $defaults
1285 * (reference ) an assoc array to hold the flattened values.
1286 * @param array $returnProperities
1287 * An assoc array of fields that need to be returned, eg array( 'first_name', 'last_name').
1290 * an object of type referenced by daoName
1292 public static function commonRetrieve($daoName, &$params, &$defaults, $returnProperities = NULL) {
1293 $object = new $daoName();
1294 $object->copyValues($params);
1296 // return only specific fields if returnproperties are sent
1297 if (!empty($returnProperities)) {
1298 $object->selectAdd();
1299 $object->selectAdd(implode(',', $returnProperities));
1302 if ($object->find(TRUE)) {
1303 self
::storeValues($object, $defaults);
1310 * Delete the object records that are associated with this contact.
1312 * @param string $daoName
1313 * Name of the dao object.
1314 * @param int $contactId
1315 * Id of the contact to delete.
1317 public static function deleteEntityContact($daoName, $contactId) {
1318 $object = new $daoName();
1320 $object->entity_table
= 'civicrm_contact';
1321 $object->entity_id
= $contactId;
1326 * Execute an unbuffered query.
1328 * This is a wrapper around new functionality exposed with CRM-17748.
1330 * @param string $query query to be executed
1332 * @param array $params
1333 * @param bool $abort
1334 * @param null $daoName
1335 * @param bool $freeDAO
1336 * @param bool $i18nRewrite
1337 * @param bool $trapException
1339 * @return CRM_Core_DAO
1340 * Object that points to an unbuffered result set
1342 public static function executeUnbufferedQuery(
1348 $i18nRewrite = TRUE,
1349 $trapException = FALSE
1352 return self
::executeQuery(
1360 ['result_buffering' => 0]
1367 * @param string $query
1368 * Query to be executed.
1370 * @param array $params
1371 * @param bool $abort
1372 * @param null $daoName
1373 * @param bool $freeDAO
1374 * @param bool $i18nRewrite
1375 * @param bool $trapException
1376 * @param array $options
1378 * @return CRM_Core_DAO|object
1379 * object that holds the results of the query
1380 * NB - if this is defined as just returning a DAO phpstorm keeps pointing
1381 * out all the properties that are not part of the DAO
1383 public static function &executeQuery(
1389 $i18nRewrite = TRUE,
1390 $trapException = FALSE,
1393 $queryStr = self
::composeQuery($query, $params, $abort);
1396 $dao = new CRM_Core_DAO();
1399 $dao = new $daoName();
1402 if ($trapException) {
1403 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
1406 if ($dao->isValidOption($options)) {
1407 $dao->setOptions($options);
1410 $result = $dao->query($queryStr, $i18nRewrite);
1412 // since it is unbuffered, ($dao->N==0) is true. This blocks the standard fetch() mechanism.
1413 if (CRM_Utils_Array
::value('result_buffering', $options) === 0) {
1417 if (is_a($result, 'DB_Error')) {
1422 preg_match('/^(insert|update|delete|create|drop|replace)/i', $queryStr)
1424 // we typically do this for insert/update/delete statements OR if explicitly asked to
1431 * Wrapper to validate internal DAO options before passing to DB_mysql/DB_Common level
1433 * @param array $options
1436 * Provided options are valid
1438 public function isValidOption($options) {
1447 if (empty($options)) {
1451 foreach (array_keys($options) as $option) {
1452 if (!in_array($option, $validOptions)) {
1462 * Execute a query and get the single result.
1464 * @param string $query
1465 * Query to be executed.
1466 * @param array $params
1467 * @param bool $abort
1468 * @param bool $i18nRewrite
1469 * @return string|null
1470 * the result of the query if any
1473 public static function &singleValueQuery(
1479 $queryStr = self
::composeQuery($query, $params, $abort);
1481 static $_dao = NULL;
1484 $_dao = new CRM_Core_DAO();
1487 $_dao->query($queryStr, $i18nRewrite);
1489 $result = $_dao->getDatabaseResult();
1492 $row = $result->fetchRow();
1502 * Compose the query by merging the parameters into it.
1504 * @param string $query
1505 * @param array $params
1506 * @param bool $abort
1511 public static function composeQuery($query, $params = [], $abort = TRUE) {
1513 foreach ($params as $key => $item) {
1514 if (is_numeric($key)) {
1515 if (CRM_Utils_Type
::validate($item[0], $item[1]) !== NULL) {
1516 $item[0] = self
::escapeString($item[0]);
1517 if ($item[1] == 'String' ||
1518 $item[1] == 'Memo' ||
1521 // Support class constants stipulating wildcard characters and/or
1522 // non-quoting of strings. Also support legacy code which may be
1523 // passing in TRUE or 1 for $item[2], which used to indicate the
1524 // use of wildcard characters.
1525 if (!empty($item[2])) {
1526 if ($item[2] & CRM_Core_DAO
::QUERY_FORMAT_WILDCARD ||
$item[2] === TRUE) {
1527 $item[0] = "'%{$item[0]}%'";
1529 elseif (!($item[2] & CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
)) {
1530 $item[0] = "'{$item[0]}'";
1534 $item[0] = "'{$item[0]}'";
1538 if (($item[1] == 'Date' ||
$item[1] == 'Timestamp') &&
1539 strlen($item[0]) == 0
1544 $tr['%' . $key] = $item[0];
1547 CRM_Core_Error
::fatal("{$item[0]} is not of type {$item[1]}");
1552 return strtr($query, $tr);
1558 public static function freeResult($ids = NULL) {
1559 global $_DB_DATAOBJECT;
1562 if (!$_DB_DATAOBJECT ||
1563 !isset($_DB_DATAOBJECT['RESULTS'])
1567 $ids = array_keys($_DB_DATAOBJECT['RESULTS']);
1570 foreach ($ids as $id) {
1571 if (isset($_DB_DATAOBJECT['RESULTS'][$id])) {
1572 $_DB_DATAOBJECT['RESULTS'][$id]->free();
1573 unset($_DB_DATAOBJECT['RESULTS'][$id]);
1576 if (isset($_DB_DATAOBJECT['RESULTFIELDS'][$id])) {
1577 unset($_DB_DATAOBJECT['RESULTFIELDS'][$id]);
1583 * Make a shallow copy of an object and all the fields in the object.
1585 * @param string $daoName
1587 * @param array $criteria
1588 * Array of all the fields & values.
1589 * on which basis to copy
1590 * @param array $newData
1591 * Array of all the fields & values.
1592 * to be copied besides the other fields
1593 * @param string $fieldsFix
1594 * Array of fields that you want to prefix/suffix/replace.
1595 * @param string $blockCopyOfDependencies
1596 * Fields that you want to block from.
1598 * @param bool $blockCopyofCustomValues
1599 * Case when you don't want to copy the custom values set in a
1600 * template as it will override/ignore the submitted custom values
1602 * @return CRM_Core_DAO|bool
1603 * the newly created copy of the object. False if none created.
1605 public static function copyGeneric($daoName, $criteria, $newData = NULL, $fieldsFix = NULL, $blockCopyOfDependencies = NULL, $blockCopyofCustomValues = FALSE) {
1606 $object = new $daoName();
1609 $object->id
= $criteria['id'];
1612 foreach ($criteria as $key => $value) {
1613 $object->$key = $value;
1618 while ($object->fetch()) {
1620 // all the objects except with $blockCopyOfDependencies set
1621 // be copied - addresses #CRM-1962
1623 if ($blockCopyOfDependencies && $object->$blockCopyOfDependencies) {
1627 $newObject = new $daoName();
1629 $fields = $object->fields();
1630 if (!is_array($fieldsFix)) {
1631 $fieldsToPrefix = [];
1632 $fieldsToSuffix = [];
1633 $fieldsToReplace = [];
1635 if (!empty($fieldsFix['prefix'])) {
1636 $fieldsToPrefix = $fieldsFix['prefix'];
1638 if (!empty($fieldsFix['suffix'])) {
1639 $fieldsToSuffix = $fieldsFix['suffix'];
1641 if (!empty($fieldsFix['replace'])) {
1642 $fieldsToReplace = $fieldsFix['replace'];
1645 foreach ($fields as $name => $value) {
1646 if ($name == 'id' ||
$value['name'] == 'id') {
1647 // copy everything but the id!
1651 $dbName = $value['name'];
1652 $type = CRM_Utils_Type
::typeToString($value['type']);
1653 $newObject->$dbName = $object->$dbName;
1654 if (isset($fieldsToPrefix[$dbName])) {
1655 $newObject->$dbName = $fieldsToPrefix[$dbName] . $newObject->$dbName;
1657 if (isset($fieldsToSuffix[$dbName])) {
1658 $newObject->$dbName .= $fieldsToSuffix[$dbName];
1660 if (isset($fieldsToReplace[$dbName])) {
1661 $newObject->$dbName = $fieldsToReplace[$dbName];
1664 if ($type == 'Timestamp' ||
$type == 'Date') {
1665 $newObject->$dbName = CRM_Utils_Date
::isoToMysql($newObject->$dbName);
1669 $newObject->copyValues($newData);
1673 if (!$blockCopyofCustomValues) {
1674 $newObject->copyCustomFields($object->id
, $newObject->id
);
1676 CRM_Utils_Hook
::post('create', CRM_Core_DAO_AllCoreTables
::getBriefName(str_replace('_BAO_', '_DAO_', $daoName)), $newObject->id
, $newObject);
1683 * Method that copies custom fields values from an old entity to a new one.
1685 * Fixes bug CRM-19302,
1686 * where if a custom field of File type was present, left both events using the same file,
1687 * breaking download URL's for the old event.
1689 * @todo the goal here is to clean this up so that it works for any entity. Copy Generic already DOES some custom field stuff
1690 * but it seems to be bypassed & perhaps less good than this (or this just duplicates it...)
1692 * @param int $entityID
1693 * @param int $newEntityID
1695 public function copyCustomFields($entityID, $newEntityID) {
1696 $entity = CRM_Core_DAO_AllCoreTables
::getBriefName(get_class($this));
1697 $tableName = CRM_Core_DAO_AllCoreTables
::getTableForClass(get_class($this));
1698 // Obtain custom values for old event
1699 $customParams = $htmlType = [];
1700 $customValues = CRM_Core_BAO_CustomValueTable
::getEntityValues($entityID, $entity);
1702 // If custom values present, we copy them
1703 if (!empty($customValues)) {
1704 // Get Field ID's and identify File type attributes, to handle file copying.
1705 $fieldIds = implode(', ', array_keys($customValues));
1706 $sql = "SELECT id FROM civicrm_custom_field WHERE html_type = 'File' AND id IN ( {$fieldIds} )";
1707 $result = CRM_Core_DAO
::executeQuery($sql);
1709 // Build array of File type fields
1710 while ($result->fetch()) {
1711 $htmlType[] = $result->id
;
1714 // Build params array of custom values
1715 foreach ($customValues as $field => $value) {
1716 if ($value !== NULL) {
1717 // Handle File type attributes
1718 if (in_array($field, $htmlType)) {
1719 $fileValues = CRM_Core_BAO_File
::path($value, $entityID);
1720 $customParams["custom_{$field}_-1"] = [
1721 'name' => CRM_Utils_File
::duplicate($fileValues[0]),
1722 'type' => $fileValues[1],
1725 // Handle other types
1727 $customParams["custom_{$field}_-1"] = $value;
1732 // Save Custom Fields for new Event
1733 CRM_Core_BAO_CustomValueTable
::postProcess($customParams, $tableName, $newEntityID, $entity);
1736 // copy activity attachments ( if any )
1737 CRM_Core_BAO_File
::copyEntityFile($tableName, $entityID, $tableName, $newEntityID);
1741 * Cascade update through related entities.
1743 * @param string $daoName
1746 * @param array $newData
1748 * @return CRM_Core_DAO|null
1750 public static function cascadeUpdate($daoName, $fromId, $toId, $newData = []) {
1751 $object = new $daoName();
1752 $object->id
= $fromId;
1754 if ($object->find(TRUE)) {
1755 $newObject = new $daoName();
1756 $newObject->id
= $toId;
1758 if ($newObject->find(TRUE)) {
1759 $fields = $object->fields();
1760 foreach ($fields as $name => $value) {
1761 if ($name == 'id' ||
$value['name'] == 'id') {
1762 // copy everything but the id!
1766 $colName = $value['name'];
1767 $newObject->$colName = $object->$colName;
1769 if (substr($name, -5) == '_date' ||
1770 substr($name, -10) == '_date_time'
1772 $newObject->$colName = CRM_Utils_Date
::isoToMysql($newObject->$colName);
1775 foreach ($newData as $k => $v) {
1776 $newObject->$k = $v;
1786 * Given the component id, compute the contact id
1787 * since its used for things like send email
1789 * @param $componentIDs
1790 * @param string $tableName
1791 * @param string $idField
1795 public static function getContactIDsFromComponent($componentIDs, $tableName, $idField = 'id') {
1798 if (empty($componentIDs)) {
1802 $IDs = implode(',', $componentIDs);
1806 WHERE $idField IN ( $IDs )
1809 $dao = CRM_Core_DAO
::executeQuery($query);
1810 while ($dao->fetch()) {
1811 $contactIDs[] = $dao->contact_id
;
1817 * Fetch object based on array of properties.
1819 * @param string $daoName
1820 * Name of the dao object.
1821 * @param string $fieldIdName
1822 * @param int $fieldId
1824 * @param array $returnProperities
1825 * An assoc array of fields that need to be returned, eg array( 'first_name', 'last_name').
1828 * an object of type referenced by daoName
1830 public static function commonRetrieveAll($daoName, $fieldIdName = 'id', $fieldId, &$details, $returnProperities = NULL) {
1831 require_once str_replace('_', DIRECTORY_SEPARATOR
, $daoName) . ".php";
1832 $object = new $daoName();
1833 $object->$fieldIdName = $fieldId;
1835 // return only specific fields if returnproperties are sent
1836 if (!empty($returnProperities)) {
1837 $object->selectAdd();
1838 $object->selectAdd('id');
1839 $object->selectAdd(implode(',', $returnProperities));
1843 while ($object->fetch()) {
1845 self
::storeValues($object, $defaults);
1846 $details[$object->id
] = $defaults;
1853 * Drop all CiviCRM tables.
1855 * @throws \CRM_Exception
1857 public static function dropAllTables() {
1859 // first drop all the custom tables we've created
1860 CRM_Core_BAO_CustomGroup
::dropAllTables();
1862 // drop all multilingual views
1863 CRM_Core_I18n_Schema
::dropAllViews();
1865 CRM_Utils_File
::sourceSQLFile(CIVICRM_DSN
,
1866 dirname(__FILE__
) . DIRECTORY_SEPARATOR
.
1867 '..' . DIRECTORY_SEPARATOR
.
1868 '..' . DIRECTORY_SEPARATOR
.
1869 'sql' . DIRECTORY_SEPARATOR
.
1870 'civicrm_drop.mysql'
1879 public static function escapeString($string) {
1880 static $_dao = NULL;
1882 // If this is an atypical case (e.g. preparing .sql file before CiviCRM
1883 // has been installed), then we fallback DB-less str_replace escaping, as
1884 // we can't use mysqli_real_escape_string, as there is no DB connection.
1885 // Note: In typical usage, escapeString() will only check one conditional
1886 // ("if !$_dao") rather than two conditionals ("if !defined(DSN)")
1887 if (!defined('CIVICRM_DSN')) {
1888 // See http://php.net/manual/en/mysqli.real-escape-string.php for the
1889 // list of characters mysqli_real_escape_string escapes.
1890 $search = ["\\", "\x00", "\n", "\r", "'", '"', "\x1a"];
1891 $replace = ["\\\\", "\\0", "\\n", "\\r", "\'", '\"', "\\Z"];
1892 return str_replace($search, $replace, $string);
1894 $_dao = new CRM_Core_DAO();
1896 return $_dao->escape($string);
1900 * Escape a list of strings for use with "WHERE X IN (...)" queries.
1902 * @param array $strings
1903 * @param string $default
1904 * the value to use if $strings has no elements.
1906 * eg "abc","def","ghi"
1908 public static function escapeStrings($strings, $default = NULL) {
1909 static $_dao = NULL;
1911 $_dao = new CRM_Core_DAO();
1914 if (empty($strings)) {
1918 $escapes = array_map([$_dao, 'escape'], $strings);
1919 return '"' . implode('","', $escapes) . '"';
1927 public static function escapeWildCardString($string) {
1929 // ensure we escape the single characters % and _ which are mysql wild
1930 // card characters and could come in via sortByCharacter
1931 // note that mysql does not escape these characters
1932 if ($string && in_array($string,
1933 ['%', '_', '%%', '_%']
1936 return '\\' . $string;
1939 return self
::escapeString($string);
1943 * Creates a test object, including any required objects it needs via recursion
1944 * createOnly: only create in database, do not store or return the objects (useful for perf testing)
1945 * ONLY USE FOR TESTING
1947 * @param string $daoName
1948 * @param array $params
1949 * @param int $numObjects
1950 * @param bool $createOnly
1952 * @return object|array|NULL
1953 * NULL if $createOnly. A single object if $numObjects==1. Otherwise, an array of multiple objects.
1955 public static function createTestObject(
1961 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
1962 // so we re-set here in case
1963 $config = CRM_Core_Config
::singleton();
1964 $config->backtrace
= TRUE;
1966 static $counter = 0;
1967 CRM_Core_DAO
::$_testEntitiesToSkip = [
1968 'CRM_Core_DAO_Worldregion',
1969 'CRM_Core_DAO_StateProvince',
1970 'CRM_Core_DAO_Country',
1971 'CRM_Core_DAO_Domain',
1972 'CRM_Financial_DAO_FinancialType',
1973 //because valid ones exist & we use pick them due to pseudoconstant can't reliably create & delete these
1976 // Prefer to instantiate BAO's instead of DAO's (when possible)
1977 // so that assignTestValue()/assignTestFK() can be overloaded.
1978 $baoName = str_replace('_DAO_', '_BAO_', $daoName);
1979 if (class_exists($baoName)) {
1980 $daoName = $baoName;
1983 for ($i = 0; $i < $numObjects; ++
$i) {
1986 /** @var CRM_Core_DAO $object */
1987 $object = new $daoName();
1989 $fields = $object->fields();
1990 foreach ($fields as $fieldName => $fieldDef) {
1991 $dbName = $fieldDef['name'];
1992 $FKClassName = CRM_Utils_Array
::value('FKClassName', $fieldDef);
1993 $required = CRM_Utils_Array
::value('required', $fieldDef);
1995 if (CRM_Utils_Array
::value($dbName, $params) !== NULL && !is_array($params[$dbName])) {
1996 $object->$dbName = $params[$dbName];
1999 elseif ($dbName != 'id') {
2000 if ($FKClassName != NULL) {
2001 $object->assignTestFK($fieldName, $fieldDef, $params);
2005 $object->assignTestValue($fieldName, $fieldDef, $counter);
2013 $objects[$i] = $object;
2023 elseif ($numObjects == 1) {
2032 * Deletes the this object plus any dependent objects that are associated with it.
2033 * ONLY USE FOR TESTING
2035 * @param string $daoName
2036 * @param array $params
2038 public static function deleteTestObjects($daoName, $params = []) {
2039 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
2040 // so we re-set here in case
2041 $config = CRM_Core_Config
::singleton();
2042 $config->backtrace
= TRUE;
2044 $object = new $daoName();
2045 $object->id
= CRM_Utils_Array
::value('id', $params);
2047 // array(array(0 => $daoName, 1 => $daoParams))
2049 if ($object->find(TRUE)) {
2051 $fields = $object->fields();
2052 foreach ($fields as $name => $value) {
2054 $dbName = $value['name'];
2056 $FKClassName = CRM_Utils_Array
::value('FKClassName', $value);
2057 $required = CRM_Utils_Array
::value('required', $value);
2058 if ($FKClassName != NULL
2060 && !in_array($FKClassName, CRM_Core_DAO
::$_testEntitiesToSkip)
2061 && ($required ||
$dbName == 'contact_id')
2062 //I'm a bit stuck on this one - we might need to change the singleValueAlter so that the entities don't share a contact
2063 // to make this test process pass - line below makes pass for now
2064 && $dbName != 'member_of_contact_id'
2067 $deletions[] = [$FKClassName, ['id' => $object->$dbName]];
2074 foreach ($deletions as $deletion) {
2075 CRM_Core_DAO
::deleteTestObjects($deletion[0], $deletion[1]);
2080 * Set defaults when creating new entity.
2081 * (don't call this set defaults as already in use with different signature in some places)
2083 * @param array $params
2086 public static function setCreateDefaults(&$params, $defaults) {
2087 if (!empty($params['id'])) {
2090 foreach ($defaults as $key => $value) {
2091 if (!array_key_exists($key, $params) ||
$params[$key] === NULL) {
2092 $params[$key] = $value;
2098 * @param string $prefix
2099 * @param bool $addRandomString
2100 * @param null $string
2104 * @see CRM_Utils_SQL_TempTable
2106 public static function createTempTableName($prefix = 'civicrm', $addRandomString = TRUE, $string = NULL) {
2107 $tableName = $prefix . "_temp";
2109 if ($addRandomString) {
2111 $tableName .= "_" . $string;
2114 $tableName .= "_" . md5(uniqid('', TRUE));
2122 * @param bool $trigger
2126 public static function checkTriggerViewPermission($view = TRUE, $trigger = TRUE) {
2127 if (\Civi
::settings()->get('logging_no_trigger_permission')) {
2130 // test for create view and trigger permissions and if allowed, add the option to go multilingual
2132 // I'm not sure why we use the getStaticProperty for an error, rather than checking for DB_Error
2133 CRM_Core_TemporaryErrorScope
::ignoreException();
2134 $dao = new CRM_Core_DAO();
2136 $result = $dao->query('CREATE OR REPLACE VIEW civicrm_domain_view AS SELECT * FROM civicrm_domain');
2137 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError') ||
is_a($result, 'DB_Error')) {
2143 $result = $dao->query('CREATE TRIGGER civicrm_domain_trigger BEFORE INSERT ON civicrm_domain FOR EACH ROW BEGIN END');
2144 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError') ||
is_a($result, 'DB_Error')) {
2146 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
2151 $dao->query('DROP TRIGGER IF EXISTS civicrm_domain_trigger');
2152 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
2154 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
2161 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
2162 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
2171 * @param null $message
2172 * @param bool $printDAO
2174 public static function debugPrint($message = NULL, $printDAO = TRUE) {
2175 CRM_Utils_System
::xMemory("{$message}: ");
2178 global $_DB_DATAOBJECT;
2180 foreach (array_keys($_DB_DATAOBJECT['RESULTS']) as $id) {
2181 $q[] = $_DB_DATAOBJECT['RESULTS'][$id]->query
;
2183 CRM_Core_Error
::debug('_DB_DATAOBJECT', $q);
2188 * Build a list of triggers via hook and add them to (err, reconcile them
2189 * with) the database.
2191 * @param string $tableName
2192 * the specific table requiring a rebuild; or NULL to rebuild all tables.
2193 * @param bool $force
2198 public static function triggerRebuild($tableName = NULL, $force = FALSE) {
2199 Civi
::service('sql_triggers')->rebuild($tableName, $force);
2203 * Because sql functions are sometimes lost, esp during db migration, we check here to avoid numerous support requests
2204 * @see http://issues.civicrm.org/jira/browse/CRM-13822
2205 * TODO: Alternative solutions might be
2206 * * Stop using functions and find another way to strip numeric characters from phones
2207 * * Give better error messages (currently a missing fn fatals with "unknown error")
2209 public static function checkSqlFunctionsExist() {
2210 if (!self
::$_checkedSqlFunctionsExist) {
2211 self
::$_checkedSqlFunctionsExist = TRUE;
2212 $dao = CRM_Core_DAO
::executeQuery("SHOW function status WHERE db = database() AND name = 'civicrm_strip_non_numeric'");
2213 if (!$dao->fetch()) {
2214 self
::triggerRebuild();
2220 * Wrapper function to drop triggers.
2222 * @param string $tableName
2223 * the specific table requiring a rebuild; or NULL to rebuild all tables.
2226 public static function dropTriggers($tableName = NULL) {
2227 Civi
::service('sql_triggers')->dropTriggers($tableName);
2231 * @param array $info
2232 * per hook_civicrm_triggerInfo.
2233 * @param string $onlyTableName
2234 * the specific table requiring a rebuild; or NULL to rebuild all tables.
2237 public static function createTriggers(&$info, $onlyTableName = NULL) {
2238 Civi
::service('sql_triggers')->createTriggers($info, $onlyTableName);
2242 * Given a list of fields, create a list of references.
2244 * @param string $className
2245 * BAO/DAO class name.
2246 * @return array<CRM_Core_Reference_Interface>
2248 public static function createReferenceColumns($className) {
2250 $fields = $className::fields();
2251 foreach ($fields as $field) {
2252 if (isset($field['pseudoconstant'], $field['pseudoconstant']['optionGroupName'])) {
2253 $result[] = new CRM_Core_Reference_OptionValue(
2254 $className::getTableName(),
2256 'civicrm_option_value',
2257 CRM_Utils_Array
::value('keyColumn', $field['pseudoconstant'], 'value'),
2258 $field['pseudoconstant']['optionGroupName']
2266 * Find all records which refer to this entity.
2269 * Array of objects referencing this
2271 public function findReferences() {
2272 $links = self
::getReferencesToTable(static::getTableName());
2275 foreach ($links as $refSpec) {
2276 /** @var $refSpec CRM_Core_Reference_Interface */
2277 $daoName = CRM_Core_DAO_AllCoreTables
::getClassForTable($refSpec->getReferenceTable());
2278 $result = $refSpec->findReferences($this);
2280 while ($result->fetch()) {
2281 $obj = new $daoName();
2282 $obj->id
= $result->id
;
2283 $occurrences[] = $obj;
2288 return $occurrences;
2293 * each item has keys:
2297 * - table: string|null SQL table name
2298 * - key: string|null SQL column name
2300 public function getReferenceCounts() {
2301 $links = self
::getReferencesToTable(static::getTableName());
2304 foreach ($links as $refSpec) {
2305 /** @var $refSpec CRM_Core_Reference_Interface */
2306 $count = $refSpec->getReferenceCount($this);
2307 if ($count['count'] != 0) {
2312 foreach (CRM_Core_Component
::getEnabledComponents() as $component) {
2313 /** @var $component CRM_Core_Component_Info */
2314 $counts = array_merge($counts, $component->getReferenceCounts($this));
2316 CRM_Utils_Hook
::referenceCounts($this, $counts);
2322 * List all tables which have hard foreign keys to this table.
2324 * For now, this returns a description of every entity_id/entity_table
2326 * TODO: filter dynamic entity references on the $tableName, based on
2327 * schema metadata in dynamicForeignKey which enumerates a restricted
2328 * set of possible entity_table's.
2330 * @param string $tableName
2331 * Table referred to.
2334 * structure of table and column, listing every table with a
2335 * foreign key reference to $tableName, and the column where the key appears.
2337 public static function getReferencesToTable($tableName) {
2339 foreach (CRM_Core_DAO_AllCoreTables
::getClasses() as $daoClassName) {
2340 $links = $daoClassName::getReferenceColumns();
2341 $daoTableName = $daoClassName::getTableName();
2343 foreach ($links as $refSpec) {
2344 /** @var $refSpec CRM_Core_Reference_Interface */
2345 if ($refSpec->matchesTargetTable($tableName)) {
2346 $refsFound[] = $refSpec;
2354 * Get all references to contact table.
2356 * This includes core tables, custom group tables, tables added by the merge
2357 * hook and the entity_tag table.
2359 * Refer to CRM-17454 for information on the danger of querying the information
2360 * schema to derive this.
2362 public static function getReferencesToContactTable() {
2363 if (isset(\Civi
::$statics[__CLASS__
]) && isset(\Civi
::$statics[__CLASS__
]['contact_references'])) {
2364 return \Civi
::$statics[__CLASS__
]['contact_references'];
2366 $contactReferences = [];
2367 $coreReferences = CRM_Core_DAO
::getReferencesToTable('civicrm_contact');
2368 foreach ($coreReferences as $coreReference) {
2369 if (!is_a($coreReference, 'CRM_Core_Reference_Dynamic')) {
2370 $contactReferences[$coreReference->getReferenceTable()][] = $coreReference->getReferenceKey();
2373 self
::appendCustomTablesExtendingContacts($contactReferences);
2374 self
::appendCustomContactReferenceFields($contactReferences);
2376 // FixME for time being adding below line statically as no Foreign key constraint defined for table 'civicrm_entity_tag'
2377 $contactReferences['civicrm_entity_tag'][] = 'entity_id';
2378 \Civi
::$statics[__CLASS__
]['contact_references'] = $contactReferences;
2379 return \Civi
::$statics[__CLASS__
]['contact_references'];
2383 * Add custom tables that extend contacts to the list of contact references.
2385 * CRM_Core_BAO_CustomGroup::getAllCustomGroupsByBaseEntity seems like a safe-ish
2386 * function to be sure all are retrieved & we don't miss subtypes or inactive or multiples
2387 * - the down side is it is not cached.
2389 * Further changes should be include tests in the CRM_Core_MergerTest class
2390 * to ensure that disabled, subtype, multiple etc groups are still captured.
2392 * @param array $cidRefs
2394 public static function appendCustomTablesExtendingContacts(&$cidRefs) {
2395 $customValueTables = CRM_Core_BAO_CustomGroup
::getAllCustomGroupsByBaseEntity('Contact');
2396 $customValueTables->find();
2397 while ($customValueTables->fetch()) {
2398 $cidRefs[$customValueTables->table_name
][] = 'entity_id';
2403 * Add custom ContactReference fields to the list of contact references
2405 * This includes active and inactive fields/groups
2407 * @param array $cidRefs
2409 * @throws \CiviCRM_API3_Exception
2411 public static function appendCustomContactReferenceFields(&$cidRefs) {
2412 $fields = civicrm_api3('CustomField', 'get', [
2413 'return' => ['column_name', 'custom_group_id.table_name'],
2414 'data_type' => 'ContactReference',
2416 foreach ($fields as $field) {
2417 $cidRefs[$field['custom_group_id.table_name']][] = $field['column_name'];
2422 * Lookup the value of a MySQL global configuration variable.
2424 * @param string $name
2425 * E.g. "thread_stack".
2426 * @param mixed $default
2429 public static function getGlobalSetting($name, $default = NULL) {
2430 // Alternatively, SELECT @@GLOBAL.thread_stack, but
2431 // that has been reported to fail under MySQL 5.0 for OS X
2432 $escapedName = self
::escapeString($name);
2433 $dao = CRM_Core_DAO
::executeQuery("SHOW VARIABLES LIKE '$escapedName'");
2434 if ($dao->fetch()) {
2443 * Update the fields array to also hold keys for pseudoconstant fields that relate to contained fields.
2445 * This is relevant where we want to offer both the ID field and the label field
2446 * as an option, e.g. search builder.
2448 * It is currently limited for optionGroupName & id+ name+ FK combos for purposes keeping the scope of the
2449 * change small, but is appropriate for other sorts of pseudoconstants.
2451 * @param array $fields
2453 public static function appendPseudoConstantsToFields(&$fields) {
2454 foreach ($fields as $field) {
2455 if (!empty($field['pseudoconstant'])) {
2456 $pseudoConstant = $field['pseudoconstant'];
2457 if (!empty($pseudoConstant['optionGroupName'])) {
2458 $fields[$pseudoConstant['optionGroupName']] = [
2459 'title' => CRM_Core_BAO_OptionGroup
::getTitleByName($pseudoConstant['optionGroupName']),
2460 'name' => $pseudoConstant['optionGroupName'],
2461 'data_type' => CRM_Utils_Type
::T_STRING
,
2462 'is_pseudofield_for' => $field['name'],
2465 // We restrict to id + name + FK as we are extending this a bit, but cautiously.
2467 !empty($field['FKClassName'])
2468 && CRM_Utils_Array
::value('keyColumn', $pseudoConstant) === 'id'
2469 && CRM_Utils_Array
::value('labelColumn', $pseudoConstant) === 'name'
2471 $pseudoFieldName = str_replace('_' . $pseudoConstant['keyColumn'], '', $field['name']);
2472 // This if is just an extra caution when adding change.
2473 if (!isset($fields[$pseudoFieldName])) {
2474 $daoName = $field['FKClassName'];
2475 $fkFields = $daoName::fields();
2476 foreach ($fkFields as $fkField) {
2477 if ($fkField['name'] === $pseudoConstant['labelColumn']) {
2478 $fields[$pseudoFieldName] = [
2479 'name' => $pseudoFieldName,
2480 'is_pseudofield_for' => $field['name'],
2481 'title' => $fkField['title'],
2482 'data_type' => $fkField['type'],
2483 'where' => $field['where'],
2494 * Get options for the called BAO object's field.
2496 * This function can be overridden by each BAO to add more logic related to context.
2497 * The overriding function will generally call the lower-level CRM_Core_PseudoConstant::get
2499 * @param string $fieldName
2500 * @param string $context
2501 * @see CRM_Core_DAO::buildOptionsContext
2502 * @param array $props
2503 * whatever is known about this bao object.
2505 * @return array|bool
2507 public static function buildOptions($fieldName, $context = NULL, $props = []) {
2508 // If a given bao does not override this function
2509 $baoName = get_called_class();
2510 return CRM_Core_PseudoConstant
::get($baoName, $fieldName, $props, $context);
2514 * Populate option labels for this object's fields.
2516 * @throws exception if called directly on the base class
2518 public function getOptionLabels() {
2519 $fields = $this->fields();
2520 if ($fields === NULL) {
2521 throw new Exception('Cannot call getOptionLabels on CRM_Core_DAO');
2523 foreach ($fields as $field) {
2524 $name = CRM_Utils_Array
::value('name', $field);
2525 if ($name && isset($this->$name)) {
2526 $label = CRM_Core_PseudoConstant
::getLabel(get_class($this), $name, $this->$name);
2527 if ($label !== FALSE) {
2528 // Append 'label' onto the field name
2529 $labelName = $name . '_label';
2530 $this->$labelName = $label;
2537 * Provides documentation and validation for the buildOptions $context param
2539 * @param string $context
2544 public static function buildOptionsContext($context = NULL) {
2546 'get' => "get: all options are returned, even if they are disabled; labels are translated.",
2547 'create' => "create: options are filtered appropriately for the object being created/updated; labels are translated.",
2548 'search' => "search: searchable options are returned; labels are translated.",
2549 'validate' => "validate: all options are returned, even if they are disabled; machine names are used in place of labels.",
2550 'abbreviate' => "abbreviate: enabled options are returned; labels are replaced with abbreviations.",
2551 'match' => "match: enabled options are returned using machine names as keys; labels are translated.",
2553 // Validation: enforce uniformity of this param
2554 if ($context !== NULL && !isset($contexts[$context])) {
2555 throw new Exception("'$context' is not a valid context for buildOptions.");
2561 * @param string $fieldName
2562 * @return bool|array
2564 public function getFieldSpec($fieldName) {
2565 $fields = $this->fields();
2566 $fieldKeys = $this->fieldKeys();
2568 // Support "unique names" as well as sql names
2569 $fieldKey = $fieldName;
2570 if (empty($fields[$fieldKey])) {
2571 $fieldKey = CRM_Utils_Array
::value($fieldName, $fieldKeys);
2573 // If neither worked then this field doesn't exist. Return false.
2574 if (empty($fields[$fieldKey])) {
2577 return $fields[$fieldKey];
2581 * Get SQL where clause for SQL filter syntax input parameters.
2583 * SQL version of api function to assign filters to the DAO based on the syntax
2584 * $field => array('IN' => array(4,6,9))
2586 * $field => array('LIKE' => array('%me%))
2589 * @param string $fieldName
2591 * @param array $filter
2592 * filter to be applied indexed by operator.
2593 * @param string $type
2594 * type of field (not actually used - nor in api @todo ).
2595 * @param string $alias
2596 * alternative field name ('as') @todo- not actually used.
2597 * @param bool $returnSanitisedArray
2598 * Return a sanitised array instead of a clause.
2599 * this is primarily so we can add filters @ the api level to the Query object based fields
2603 * @return NULL|string|array
2604 * a string is returned if $returnSanitisedArray is not set, otherwise and Array or NULL
2605 * depending on whether it is supported as yet
2607 public static function createSQLFilter($fieldName, $filter, $type = NULL, $alias = NULL, $returnSanitisedArray = FALSE) {
2608 foreach ($filter as $operator => $criteria) {
2609 if (in_array($operator, self
::acceptedSQLOperators(), TRUE)) {
2610 switch ($operator) {
2614 if (!$returnSanitisedArray) {
2615 return (sprintf('%s %s', $fieldName, $operator));
2618 return (sprintf('%s %s ', $fieldName, $operator));
2622 // ternary operators
2625 if ((empty($criteria[0]) && !in_array($criteria[0], ['0', 0]))||
(empty($criteria[1]) && !in_array($criteria[1], ['0', 0]))) {
2626 throw new Exception("invalid criteria for $operator");
2628 if (!$returnSanitisedArray) {
2629 return (sprintf('%s ' . $operator . ' "%s" AND "%s"', $fieldName, CRM_Core_DAO
::escapeString($criteria[0]), CRM_Core_DAO
::escapeString($criteria[1])));
2632 // not yet implemented (tests required to implement)
2640 if (empty($criteria)) {
2641 throw new Exception("invalid criteria for $operator");
2643 $escapedCriteria = array_map([
2647 if (!$returnSanitisedArray) {
2648 return (sprintf('%s %s ("%s")', $fieldName, $operator, implode('", "', $escapedCriteria)));
2650 return $escapedCriteria;
2655 if (!$returnSanitisedArray) {
2656 return (sprintf('%s %s "%s"', $fieldName, $operator, CRM_Core_DAO
::escapeString($criteria)));
2659 // not yet implemented (tests required to implement)
2668 * @see http://issues.civicrm.org/jira/browse/CRM-9150
2669 * support for other syntaxes is discussed in ticket but being put off for now
2672 public static function acceptedSQLOperators() {
2693 * SQL has a limit of 64 characters on various names:
2694 * table name, trigger name, column name ...
2696 * For custom groups and fields we generated names from user entered input
2697 * which can be longer than this length, this function helps with creating
2698 * strings that meet various criteria.
2700 * @param string $string
2701 * The string to be shortened.
2702 * @param int $length
2703 * The max length of the string.
2705 * @param bool $makeRandom
2709 public static function shortenSQLName($string, $length = 60, $makeRandom = FALSE) {
2710 // early return for strings that meet the requirements
2711 if (strlen($string) <= $length) {
2715 // easy return for calls that dont need a randomized uniq string
2717 return substr($string, 0, $length);
2720 // the string is longer than the length and we need a uniq string
2721 // for the same tablename we need the same uniq string every time
2722 // hence we use md5 on the string, which is not random
2723 // we'll append 8 characters to the end of the tableName
2724 $md5string = substr(md5($string), 0, 8);
2725 return substr($string, 0, $length - 8) . "_{$md5string}";
2729 * https://issues.civicrm.org/jira/browse/CRM-17748
2730 * Sets the internal options to be used on a query
2732 * @param array $options
2735 public function setOptions($options) {
2736 if (is_array($options)) {
2737 $this->_options
= $options;
2742 * https://issues.civicrm.org/jira/browse/CRM-17748
2743 * wrapper to pass internal DAO options down to DB_mysql/DB_Common level
2745 * @param array $options
2748 protected function _setDBOptions($options) {
2749 global $_DB_DATAOBJECT;
2751 if (is_array($options) && count($options)) {
2752 $conn = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5
];
2753 foreach ($options as $option_name => $option_value) {
2754 $conn->setOption($option_name, $option_value);
2761 * @param array $params
2763 public function setApiFilter(&$params) {
2767 * Generates acl clauses suitable for adding to WHERE or ON when doing an api.get for this entity
2769 * Return format is in the form of fieldname => clauses starting with an operator. e.g.:
2772 * 'location_type_id' => array('IS NOT NULL', 'IN (1,2,3)')
2776 * Note that all array keys must be actual field names in this entity. Use subqueries to filter on other tables e.g. custom values.
2780 public function addSelectWhereClause() {
2782 $fields = $this->fields();
2783 foreach ($fields as $fieldName => $field) {
2784 // Clause for contact-related entities like Email, Relationship, etc.
2785 if (strpos($fieldName, 'contact_id') === 0 && CRM_Utils_Array
::value('FKClassName', $field) == 'CRM_Contact_DAO_Contact') {
2786 $clauses[$fieldName] = CRM_Utils_SQL
::mergeSubquery('Contact');
2788 // Clause for an entity_table/entity_id combo
2789 if ($fieldName == 'entity_id' && isset($fields['entity_table'])) {
2790 $relatedClauses = [];
2791 $relatedEntities = $this->buildOptions('entity_table', 'get');
2792 foreach ((array) $relatedEntities as $table => $ent) {
2794 $ent = CRM_Core_DAO_AllCoreTables
::getBriefName(CRM_Core_DAO_AllCoreTables
::getClassForTable($table));
2795 $subquery = CRM_Utils_SQL
::mergeSubquery($ent);
2797 $relatedClauses[] = "(entity_table = '$table' AND entity_id " . implode(' AND entity_id ', $subquery) . ")";
2800 $relatedClauses[] = "(entity_table = '$table')";
2804 if ($relatedClauses) {
2805 $clauses['id'] = 'IN (SELECT id FROM `' . $this->tableName() . '` WHERE (' . implode(') OR (', $relatedClauses) . '))';
2809 CRM_Utils_Hook
::selectWhereClause($this, $clauses);
2814 * This returns the final permissioned query string for this entity
2816 * With acls from related entities + additional clauses from hook_civicrm_selectWhereClause
2818 * @param string $tableAlias
2821 public static function getSelectWhereClause($tableAlias = NULL) {
2822 $bao = new static();
2823 if ($tableAlias === NULL) {
2824 $tableAlias = $bao->tableName();
2827 foreach ((array) $bao->addSelectWhereClause() as $field => $vals) {
2828 $clauses[$field] = NULL;
2830 $clauses[$field] = "(`$tableAlias`.`$field` IS NULL OR (`$tableAlias`.`$field` " . implode(" AND `$tableAlias`.`$field` ", (array) $vals) . '))';
2837 * ensure database name is 'safe', i.e. only contains word characters (includes underscores)
2838 * and dashes, and contains at least one [a-z] case insenstive.
2844 public static function requireSafeDBName($database) {
2847 "/^[\w\-]*[a-z]+[\w\-]*$/i",
2851 if (empty($matches)) {
2858 * Transform an array to a serialized string for database storage.
2860 * @param array|null $value
2861 * @param int $serializationType
2862 * @return string|null
2864 * @throws \Exception
2866 public static function serializeField($value, $serializationType) {
2867 if ($value === NULL) {
2870 switch ($serializationType) {
2871 case self
::SERIALIZE_SEPARATOR_BOOKEND
:
2872 return $value === [] ?
'' : CRM_Utils_Array
::implodePadded($value);
2874 case self
::SERIALIZE_SEPARATOR_TRIMMED
:
2875 return is_array($value) ?
implode(self
::VALUE_SEPARATOR
, $value) : $value;
2877 case self
::SERIALIZE_JSON
:
2878 return is_array($value) ?
json_encode($value) : $value;
2880 case self
::SERIALIZE_PHP
:
2881 return is_array($value) ?
serialize($value) : $value;
2883 case self
::SERIALIZE_COMMA
:
2884 return is_array($value) ?
implode(',', $value) : $value;
2887 throw new Exception('Unknown serialization method for field.');
2892 * Transform a serialized string from the database into an array.
2894 * @param string|null $value
2895 * @param $serializationType
2897 * @return array|null
2898 * @throws CRM_Core_Exception
2900 public static function unSerializeField($value, $serializationType) {
2901 if ($value === NULL) {
2904 if ($value === '') {
2907 switch ($serializationType) {
2908 case self
::SERIALIZE_SEPARATOR_BOOKEND
:
2909 return (array) CRM_Utils_Array
::explodePadded($value);
2911 case self
::SERIALIZE_SEPARATOR_TRIMMED
:
2912 return explode(self
::VALUE_SEPARATOR
, trim($value));
2914 case self
::SERIALIZE_JSON
:
2915 return strlen($value) ?
json_decode($value, TRUE) : [];
2917 case self
::SERIALIZE_PHP
:
2918 return strlen($value) ?
unserialize($value, ['allowed_classes' => FALSE]) : [];
2920 case self
::SERIALIZE_COMMA
:
2921 return explode(',', trim(str_replace(', ', '', $value)));
2924 throw new CRM_Core_Exception('Unknown serialization method for field.');
2931 public static function getEntityRefFilters() {
2936 * Get exportable fields with pseudoconstants rendered as an extra field.
2938 * @param string $baoClass
2942 public static function getExportableFieldsWithPseudoConstants($baoClass) {
2943 if (method_exists($baoClass, 'exportableFields')) {
2944 $fields = $baoClass::exportableFields();
2947 $fields = $baoClass::export();
2949 CRM_Core_DAO
::appendPseudoConstantsToFields($fields);