3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
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 * Our base DAO class. All DAO classes should inherit from this class.
32 * @copyright CiviCRM LLC (c) 2004-2017
35 if (!defined('DB_DSN_MODE')) {
36 define('DB_DSN_MODE', 'auto');
39 require_once 'PEAR.php';
40 require_once 'DB/DataObject.php';
42 require_once 'CRM/Core/I18n.php';
47 class CRM_Core_DAO
extends DB_DataObject
{
53 static $_nullObject = NULL;
58 static $_nullArray = array();
60 static $_dbColumnValueCache = NULL;
61 const NOT_NULL
= 1, IS_NULL
= 2,
63 VALUE_SEPARATOR
= "\ 1",
64 BULK_INSERT_COUNT
= 200,
65 BULK_INSERT_HIGH_COUNT
= 200,
66 QUERY_FORMAT_WILDCARD
= 1,
67 QUERY_FORMAT_NO_QUOTES
= 2;
70 * Define entities that shouldn't be created or deleted when creating/ deleting
71 * test objects - this prevents world regions, countries etc from being added / deleted
74 static $_testEntitiesToSkip = array();
76 * The factory class for this application.
79 static $_factory = NULL;
81 static $_checkedSqlFunctionsExist = FALSE;
84 * https://issues.civicrm.org/jira/browse/CRM-17748
85 * internal variable for DAO to hold per-query settings
87 protected $_options = array();
92 * @return \CRM_Core_DAO
94 public function __construct() {
96 $this->__table
= $this->getTableName();
100 * Empty definition for virtual function.
102 public static function getTableName() {
107 * Initialize the DAO object.
110 * The database connection string.
112 public static function init($dsn) {
113 Civi
::$statics[__CLASS__
]['init'] = 1;
114 $options = &PEAR
::getStaticProperty('DB_DataObject', 'options');
115 $options['database'] = $dsn;
116 if (defined('CIVICRM_DAO_DEBUG')) {
117 self
::DebugLevel(CIVICRM_DAO_DEBUG
);
119 $factory = new CRM_Contact_DAO_Factory();
120 CRM_Core_DAO
::setFactory($factory);
121 if (CRM_Utils_Constant
::value('CIVICRM_MYSQL_STRICT', CRM_Utils_System
::isDevelopment())) {
122 CRM_Core_DAO
::executeQuery('SET SESSION sql_mode = STRICT_TRANS_TABLES');
124 CRM_Core_DAO
::executeQuery('SET NAMES utf8');
125 CRM_Core_DAO
::executeQuery('SET @uniqueID = %1', array(1 => array(CRM_Utils_Request
::id(), 'String')));
131 public static function getConnection() {
132 global $_DB_DATAOBJECT;
133 $dao = new CRM_Core_DAO();
134 return $_DB_DATAOBJECT['CONNECTIONS'][$dao->_database_dsn_md5
];
138 * @param string $fieldName
140 * @param array $params
142 protected function assignTestFK($fieldName, $fieldDef, $params) {
143 $required = CRM_Utils_Array
::value('required', $fieldDef);
144 $FKClassName = CRM_Utils_Array
::value('FKClassName', $fieldDef);
145 $dbName = $fieldDef['name'];
146 $daoName = str_replace('_BAO_', '_DAO_', get_class($this));
148 // skip the FK if it is not required
149 // if it's contact id we should create even if not required
150 // we'll have a go @ fetching first though
151 // we WILL create campaigns though for so tests with a campaign pseudoconstant will complete
152 if ($FKClassName === 'CRM_Campaign_DAO_Campaign' && $daoName != $FKClassName) {
155 if (!$required && $dbName != 'contact_id') {
156 $fkDAO = new $FKClassName();
157 if ($fkDAO->find(TRUE)) {
158 $this->$dbName = $fkDAO->id
;
163 elseif (in_array($FKClassName, CRM_Core_DAO
::$_testEntitiesToSkip)) {
164 $depObject = new $FKClassName();
165 $depObject->find(TRUE);
166 $this->$dbName = $depObject->id
;
169 elseif ($daoName == 'CRM_Member_DAO_MembershipType' && $fieldName == 'member_of_contact_id') {
170 // FIXME: the fields() metadata is not specific enough
171 $depObject = CRM_Core_DAO
::createTestObject($FKClassName, array('contact_type' => 'Organization'));
172 $this->$dbName = $depObject->id
;
176 //if it is required we need to generate the dependency object first
177 $depObject = CRM_Core_DAO
::createTestObject($FKClassName, CRM_Utils_Array
::value($dbName, $params, 1));
178 $this->$dbName = $depObject->id
;
184 * Generate and assign an arbitrary value to a field of a test object.
186 * @param string $fieldName
187 * @param array $fieldDef
188 * @param int $counter
189 * The globally-unique ID of the test object.
191 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
192 $dbName = $fieldDef['name'];
193 $daoName = get_class($this);
196 if (!$handled && $dbName == 'contact_sub_type') {
197 //coming up with a rule to set this is too complex let's not set it
201 // Pick an option value if needed
202 if (!$handled && $fieldDef['type'] !== CRM_Utils_Type
::T_BOOLEAN
) {
203 $options = $daoName::buildOptions($dbName, 'create');
205 $this->$dbName = key($options);
211 switch ($fieldDef['type']) {
212 case CRM_Utils_Type
::T_INT
:
213 case CRM_Utils_Type
::T_FLOAT
:
214 case CRM_Utils_Type
::T_MONEY
:
215 if (isset($fieldDef['precision'])) {
216 // $object->$dbName = CRM_Utils_Number::createRandomDecimal($value['precision']);
217 $this->$dbName = CRM_Utils_Number
::createTruncatedDecimal($counter, $fieldDef['precision']);
220 $this->$dbName = $counter;
224 case CRM_Utils_Type
::T_BOOLEAN
:
225 if (isset($fieldDef['default'])) {
226 $this->$dbName = $fieldDef['default'];
228 elseif ($fieldDef['name'] == 'is_deleted' ||
$fieldDef['name'] == 'is_test') {
236 case CRM_Utils_Type
::T_DATE
:
237 case CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
:
238 $this->$dbName = '19700101';
239 if ($dbName == 'end_date') {
240 // put this in the future
241 $this->$dbName = '20200101';
245 case CRM_Utils_Type
::T_TIMESTAMP
:
246 $this->$dbName = '19700201000000';
249 case CRM_Utils_Type
::T_TIME
:
250 CRM_Core_Error
::fatal("T_TIME shouldn't be used.");
251 //$object->$dbName='000000';
253 case CRM_Utils_Type
::T_CCNUM
:
254 $this->$dbName = '4111 1111 1111 1111';
257 case CRM_Utils_Type
::T_URL
:
258 $this->$dbName = 'http://www.civicrm.org';
261 case CRM_Utils_Type
::T_STRING
:
262 case CRM_Utils_Type
::T_BLOB
:
263 case CRM_Utils_Type
::T_MEDIUMBLOB
:
264 case CRM_Utils_Type
::T_TEXT
:
265 case CRM_Utils_Type
::T_LONGTEXT
:
266 case CRM_Utils_Type
::T_EMAIL
:
268 // WAS: if (isset($value['enumValues'])) {
269 // TODO: see if this works with all pseudoconstants
270 if (isset($fieldDef['pseudoconstant'], $fieldDef['pseudoconstant']['callback'])) {
271 if (isset($fieldDef['default'])) {
272 $this->$dbName = $fieldDef['default'];
275 $options = CRM_Core_PseudoConstant
::get($daoName, $fieldName);
276 if (is_array($options)) {
277 $this->$dbName = $options[0];
280 $defaultValues = explode(',', $options);
281 $this->$dbName = $defaultValues[0];
286 $this->$dbName = $dbName . '_' . $counter;
287 $maxlength = CRM_Utils_Array
::value('maxlength', $fieldDef);
288 if ($maxlength > 0 && strlen($this->$dbName) > $maxlength) {
289 $this->$dbName = substr($this->$dbName, 0, $fieldDef['maxlength']);
297 * Reset the DAO object.
299 * DAO is kinda crappy in that there is an unwritten rule of one query per DAO.
301 * We attempt to get around this crappy restriction by resetting some of DAO's internal fields. Use this with caution
303 public function reset() {
305 foreach (array_keys($this->table()) as $field) {
306 unset($this->$field);
310 * reset the various DB_DAO structures manually
312 $this->_query
= array();
319 * @param string $tableName
323 public static function getLocaleTableName($tableName) {
326 $tables = CRM_Core_I18n_Schema
::schemaStructureTables();
327 if (in_array($tableName, $tables)) {
328 return $tableName . $dbLocale;
335 * Execute a query by the current DAO, localizing it along the way (if needed).
337 * @param string $query
338 * The SQL query for execution.
339 * @param bool $i18nRewrite
340 * Whether to rewrite the query.
343 * the current DAO object after the query execution
345 public function query($query, $i18nRewrite = TRUE) {
346 // rewrite queries that should use $dbLocale-based views for multi-language installs
347 global $dbLocale, $_DB_DATAOBJECT;
349 if (empty($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5
])) {
350 // Will force connection to be populated per CRM-20541.
354 $conn = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5
];
355 $orig_options = $conn->options
;
356 $this->_setDBOptions($this->_options
);
358 if ($i18nRewrite and $dbLocale) {
359 $query = CRM_Core_I18n_Schema
::rewriteQuery($query);
362 $ret = parent
::query($query);
364 $this->_setDBOptions($orig_options);
369 * Static function to set the factory instance for this class.
371 * @param object $factory
372 * The factory application object.
374 public static function setFactory(&$factory) {
375 self
::$_factory = &$factory;
379 * Factory method to instantiate a new object from a table name.
381 * @param string $table
383 public function factory($table = '') {
384 if (!isset(self
::$_factory)) {
385 return parent
::factory($table);
388 return self
::$_factory->create($table);
392 * Initialization for all DAO objects. Since we access DB_DO programatically
393 * we need to set the links manually.
395 public function initialize() {
397 if (empty(Civi
::$statics[__CLASS__
]['init'])) {
398 // CRM_Core_DAO::init() must be called before CRM_Core_DAO->initialize().
399 // This occurs very early in bootstrap - error handlers may not be wired up.
400 echo "Inconsistent system initialization sequence. Premature access of (" . get_class($this) . ")";
401 CRM_Utils_System
::civiExit();
406 * Defines the default key as 'id'.
411 public function keys() {
420 * Tells DB_DataObject which keys use autoincrement.
421 * 'id' is autoincrementing by default.
426 public function sequenceKey() {
427 static $sequenceKeys;
428 if (!isset($sequenceKeys)) {
429 $sequenceKeys = array('id', TRUE);
431 return $sequenceKeys;
435 * Returns list of FK relationships.
439 * Array of CRM_Core_Reference_Interface
441 public static function getReferenceColumns() {
446 * Returns all the column names of this table.
451 public static function &fields() {
457 * Get/set an associative array of table columns
462 public function table() {
463 $fields = &$this->fields();
467 foreach ($fields as $name => $value) {
468 $table[$value['name']] = $value['type'];
469 if (!empty($value['required'])) {
470 $table[$value['name']] +
= self
::DB_DAO_NOTNULL
;
483 * @return CRM_Core_DAO
485 public function save($hook = TRUE) {
486 if (!empty($this->id
)) {
490 $event = new \Civi\Core\DAO\Event\
PostUpdate($this);
491 \Civi
::service('dispatcher')->dispatch("civi.dao.postUpdate", $event);
498 $event = new \Civi\Core\DAO\Event\
PostUpdate($this);
499 \Civi
::service('dispatcher')->dispatch("civi.dao.postInsert", $event);
505 CRM_Utils_Hook
::postSave($this);
512 * Deletes items from table which match current objects variables.
514 * Returns the true on success
518 * Designed to be extended
520 * $object = new mytable();
522 * echo $object->delete(); // builds a conditon
524 * $object = new mytable();
525 * $object->whereAdd('age > 12');
527 * $object->orderBy('age DESC');
528 * $object->delete(true); // dont use object vars, use the conditions, limit and order.
530 * @param bool $useWhere (optional) If DB_DATAOBJECT_WHEREADD_ONLY is passed in then
531 * we will build the condition only using the whereAdd's. Default is to
532 * build the condition only using the object parameters.
534 * * @return mixed Int (No. of rows affected) on success, false on failure, 0 on no data affected
536 public function delete($useWhere = FALSE) {
537 $preEvent = new \Civi\Core\DAO\Event\
PreDelete($this);
538 \Civi
::service('dispatcher')->dispatch("civi.dao.preDelete", $preEvent);
540 $result = parent
::delete($useWhere);
542 $event = new \Civi\Core\DAO\Event\
PostDelete($this, $result);
543 \Civi
::service('dispatcher')->dispatch("civi.dao.postDelete", $event);
550 * @param bool $created
552 public function log($created = FALSE) {
555 if (!$this->getLog()) {
560 $session = CRM_Core_Session
::singleton();
561 $cid = $session->get('userID');
564 // return is we dont have handle to FK
569 $dao = new CRM_Core_DAO_Log();
570 $dao->entity_table
= $this->getTableName();
571 $dao->entity_id
= $this->id
;
572 $dao->modified_id
= $cid;
573 $dao->modified_date
= date("YmdHis");
578 * Given an associative array of name/value pairs, extract all the values
579 * that belong to this object and initialize the object with said values
581 * @param array $params
582 * (reference ) associative array of name/value pairs.
585 * Did we copy all null values into the object
587 public function copyValues(&$params) {
588 $fields = &$this->fields();
590 foreach ($fields as $name => $value) {
591 $dbName = $value['name'];
592 if (array_key_exists($dbName, $params)) {
593 $pValue = $params[$dbName];
596 elseif (array_key_exists($name, $params)) {
597 $pValue = $params[$name];
604 // if there is no value then make the variable NULL
606 if ($pValue === '') {
607 $this->$dbName = 'null';
610 $this->$dbName = $pValue;
619 * Store all the values from this object in an associative array
620 * this is a destructive store, calling function is responsible
621 * for keeping sanity of id's.
623 * @param object $object
624 * The object that we are extracting data from.
625 * @param array $values
626 * (reference ) associative array of name/value pairs.
628 public static function storeValues(&$object, &$values) {
629 $fields = &$object->fields();
630 foreach ($fields as $name => $value) {
631 $dbName = $value['name'];
632 if (isset($object->$dbName) && $object->$dbName !== 'null') {
633 $values[$dbName] = $object->$dbName;
634 if ($name != $dbName) {
635 $values[$name] = $object->$dbName;
642 * Create an attribute for this specific field. We only do this for strings and text
644 * @param array $field
645 * The field under task.
648 * the attributes for the object
650 public static function makeAttribute($field) {
652 if (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_STRING
) {
653 $maxLength = CRM_Utils_Array
::value('maxlength', $field);
654 $size = CRM_Utils_Array
::value('size', $field);
655 if ($maxLength ||
$size) {
656 $attributes = array();
658 $attributes['maxlength'] = $maxLength;
661 $attributes['size'] = $size;
666 elseif (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_TEXT
) {
667 $rows = CRM_Utils_Array
::value('rows', $field);
671 $cols = CRM_Utils_Array
::value('cols', $field);
676 $attributes = array();
677 $attributes['rows'] = $rows;
678 $attributes['cols'] = $cols;
681 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
) {
682 $attributes['size'] = 6;
683 $attributes['maxlength'] = 14;
691 * Get the size and maxLength attributes for this text field.
692 * (or for all text fields) in the DAO object.
694 * @param string $class
696 * @param string $fieldName
697 * Field that i'm interested in or null if.
698 * you want the attributes for all DAO text fields
701 * assoc array of name => attribute pairs
703 public static function getAttribute($class, $fieldName = NULL) {
704 $object = new $class();
705 $fields = &$object->fields();
706 if ($fieldName != NULL) {
707 $field = CRM_Utils_Array
::value($fieldName, $fields);
708 return self
::makeAttribute($field);
711 $attributes = array();
712 foreach ($fields as $name => $field) {
713 $attribute = self
::makeAttribute($field);
715 $attributes[$name] = $attribute;
719 if (!empty($attributes)) {
731 public static function transaction($type) {
732 CRM_Core_Error
::fatal('This function is obsolete, please use CRM_Core_Transaction');
736 * Check if there is a record with the same name in the db.
738 * @param string $value
739 * The value of the field we are checking.
740 * @param string $daoName
741 * The dao object name.
742 * @param string $daoID
743 * The id of the object being updated. u can change your name.
744 * as long as there is no conflict
745 * @param string $fieldName
746 * The name of the field in the DAO.
748 * @param string $domainID
749 * The id of the domain. Object exists only for the given domain.
752 * true if object exists
754 public static function objectExists($value, $daoName, $daoID, $fieldName = 'name', $domainID = NULL) {
755 $object = new $daoName();
756 $object->$fieldName = $value;
758 $object->domain_id
= $domainID;
761 if ($object->find(TRUE)) {
762 return ($daoID && $object->id
== $daoID) ?
TRUE : FALSE;
770 * Check if there is a given column in a specific table.
772 * @param string $tableName
773 * @param string $columnName
774 * @param bool $i18nRewrite
775 * Whether to rewrite the query on multilingual setups.
778 * true if exists, else false
780 public static function checkFieldExists($tableName, $columnName, $i18nRewrite = TRUE) {
786 $params = array(1 => array($columnName, 'String'));
787 $dao = CRM_Core_DAO
::executeQuery($query, $params, TRUE, NULL, FALSE, $i18nRewrite);
788 $result = $dao->fetch() ?
TRUE : FALSE;
794 * Scans all the tables using a slow query and table name.
798 public static function getTableNames() {
799 $dao = CRM_Core_DAO
::executeQuery(
801 FROM information_schema.TABLES
802 WHERE TABLE_SCHEMA = '" . CRM_Core_DAO
::getDatabaseName() . "'
803 AND TABLE_NAME LIKE 'civicrm_%'
804 AND TABLE_NAME NOT LIKE 'civicrm_import_job_%'
805 AND TABLE_NAME NOT LIKE '%_temp%'
808 while ($dao->fetch()) {
809 $values[] = $dao->TABLE_NAME
;
816 * @param int $maxTablesToCheck
820 public static function isDBMyISAM($maxTablesToCheck = 10) {
821 return CRM_Core_DAO
::singleValueQuery(
823 FROM information_schema.TABLES
824 WHERE ENGINE = 'MyISAM'
825 AND TABLE_SCHEMA = '" . CRM_Core_DAO
::getDatabaseName() . "'
826 AND TABLE_NAME LIKE 'civicrm_%'
827 AND TABLE_NAME NOT LIKE 'civicrm_import_job_%'
828 AND TABLE_NAME NOT LIKE '%_temp%'
833 * Get the name of the CiviCRM database.
837 public static function getDatabaseName() {
838 $daoObj = new CRM_Core_DAO();
839 return $daoObj->database();
843 * Checks if a constraint exists for a specified table.
845 * @param string $tableName
846 * @param string $constraint
849 * true if constraint exists, false otherwise
851 public static function checkConstraintExists($tableName, $constraint) {
852 static $show = array();
854 if (!array_key_exists($tableName, $show)) {
855 $query = "SHOW CREATE TABLE $tableName";
856 $dao = CRM_Core_DAO
::executeQuery($query);
858 if (!$dao->fetch()) {
859 CRM_Core_Error
::fatal();
863 $show[$tableName] = $dao->Create_Table
;
866 return preg_match("/\b$constraint\b/i", $show[$tableName]) ?
TRUE : FALSE;
870 * Checks if CONSTRAINT keyword exists for a specified table.
872 * @param array $tables
877 * true if CONSTRAINT keyword exists, false otherwise
879 public static function schemaRequiresRebuilding($tables = array("civicrm_contact")) {
881 foreach ($tables as $tableName) {
882 if (!array_key_exists($tableName, $show)) {
883 $query = "SHOW CREATE TABLE $tableName";
884 $dao = CRM_Core_DAO
::executeQuery($query);
886 if (!$dao->fetch()) {
887 CRM_Core_Error
::fatal();
891 $show[$tableName] = $dao->Create_Table
;
894 $result = preg_match("/\bCONSTRAINT\b\s/i", $show[$tableName]) ?
TRUE : FALSE;
895 if ($result == TRUE) {
906 * Checks if the FK constraint name is in the format 'FK_tableName_columnName'
907 * for a specified column of a table.
909 * @param string $tableName
910 * @param string $columnName
913 * true if in format, false otherwise
915 public static function checkFKConstraintInFormat($tableName, $columnName) {
916 static $show = array();
918 if (!array_key_exists($tableName, $show)) {
919 $query = "SHOW CREATE TABLE $tableName";
920 $dao = CRM_Core_DAO
::executeQuery($query);
922 if (!$dao->fetch()) {
923 CRM_Core_Error
::fatal();
927 $show[$tableName] = $dao->Create_Table
;
929 $constraint = "`FK_{$tableName}_{$columnName}`";
930 $pattern = "/\bCONSTRAINT\b\s+%s\s+\bFOREIGN\s+KEY\b\s/i";
931 return preg_match(sprintf($pattern, $constraint), $show[$tableName]) ?
TRUE : FALSE;
935 * Check whether a specific column in a specific table has always the same value.
937 * @param string $tableName
938 * @param string $columnName
939 * @param string $columnValue
942 * true if the value is always $columnValue, false otherwise
944 public static function checkFieldHasAlwaysValue($tableName, $columnName, $columnValue) {
945 $query = "SELECT * FROM $tableName WHERE $columnName != '$columnValue'";
946 $dao = CRM_Core_DAO
::executeQuery($query);
947 $result = $dao->fetch() ?
FALSE : TRUE;
953 * Check whether a specific column in a specific table is always NULL.
955 * @param string $tableName
956 * @param string $columnName
959 * true if if the value is always NULL, false otherwise
961 public static function checkFieldIsAlwaysNull($tableName, $columnName) {
962 $query = "SELECT * FROM $tableName WHERE $columnName IS NOT NULL";
963 $dao = CRM_Core_DAO
::executeQuery($query);
964 $result = $dao->fetch() ?
FALSE : TRUE;
970 * Check if there is a given table in the database.
972 * @param string $tableName
975 * true if exists, else false
977 public static function checkTableExists($tableName) {
982 $params = array(1 => array($tableName, 'String'));
984 $dao = CRM_Core_DAO
::executeQuery($query, $params);
985 $result = $dao->fetch() ?
TRUE : FALSE;
995 public function checkVersion($version) {
1000 $dbVersion = CRM_Core_DAO
::singleValueQuery($query);
1001 return trim($version) == trim($dbVersion) ?
TRUE : FALSE;
1005 * Find a DAO object for the given ID and return it.
1008 * Id of the DAO object being searched for.
1011 * Object of the type of the class that called this function.
1013 public static function findById($id) {
1014 $object = new static();
1016 if (!$object->find(TRUE)) {
1017 throw new Exception("Unable to find a " . get_called_class() . " with id {$id}.");
1023 * Returns all results as array-encoded records.
1027 public function fetchAll() {
1029 while ($this->fetch()) {
1030 $result[] = $this->toArray();
1036 * Returns a singular value.
1038 * @return mixed|NULL
1040 public function fetchValue() {
1041 $result = $this->getDatabaseResult();
1042 $row = $result->fetchRow();
1052 * Get all the result records as mapping between columns.
1054 * @param string $keyColumn
1056 * @param string $valueColumn
1059 * Ex: ["foo" => "The Foo Bar", "baz" => "The Baz Qux"]
1061 public function fetchMap($keyColumn, $valueColumn) {
1063 while ($this->fetch()) {
1064 $result[$this->{$keyColumn}] = $this->{$valueColumn};
1070 * Given a DAO name, a column name and a column value, find the record and GET the value of another column in that record
1072 * @param string $daoName
1073 * Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact).
1074 * @param int $searchValue
1075 * Value of the column you want to search by.
1076 * @param string $returnColumn
1077 * Name of the column you want to GET the value of.
1078 * @param string $searchColumn
1079 * Name of the column you want to search by.
1080 * @param bool $force
1081 * Skip use of the cache.
1083 * @return string|null
1084 * Value of $returnColumn in the retrieved record
1086 public static function getFieldValue($daoName, $searchValue, $returnColumn = 'name', $searchColumn = 'id', $force = FALSE) {
1088 empty($searchValue) ||
1089 trim(strtolower($searchValue)) == 'null'
1091 // adding this here since developers forget to check for an id
1092 // or for the 'null' (which is a bad DAO kludge)
1093 // and hence we get the first value in the db
1094 CRM_Core_Error
::fatal();
1097 $cacheKey = "{$daoName}:{$searchValue}:{$returnColumn}:{$searchColumn}";
1098 if (self
::$_dbColumnValueCache === NULL) {
1099 self
::$_dbColumnValueCache = array();
1102 if (!array_key_exists($cacheKey, self
::$_dbColumnValueCache) ||
$force) {
1103 $object = new $daoName();
1104 $object->$searchColumn = $searchValue;
1105 $object->selectAdd();
1106 $object->selectAdd($returnColumn);
1109 if ($object->find(TRUE)) {
1110 $result = $object->$returnColumn;
1114 self
::$_dbColumnValueCache[$cacheKey] = $result;
1116 return self
::$_dbColumnValueCache[$cacheKey];
1120 * Given a DAO name, a column name and a column value, find the record and SET the value of another column in that record
1122 * @param string $daoName
1123 * Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact).
1124 * @param int $searchValue
1125 * Value of the column you want to search by.
1126 * @param string $setColumn
1127 * Name of the column you want to SET the value of.
1128 * @param string $setValue
1129 * SET the setColumn to this value.
1130 * @param string $searchColumn
1131 * Name of the column you want to search by.
1134 * true if we found and updated the object, else false
1136 public static function setFieldValue($daoName, $searchValue, $setColumn, $setValue, $searchColumn = 'id') {
1137 $object = new $daoName();
1138 $object->selectAdd();
1139 $object->selectAdd("$searchColumn, $setColumn");
1140 $object->$searchColumn = $searchValue;
1142 if ($object->find(TRUE)) {
1143 $object->$setColumn = $setValue;
1144 if ($object->save()) {
1155 * @param array|object $sort either array or CRM_Utils_Sort
1156 * @param string $default
1157 * Default sort value.
1162 public static function getSortString($sort, $default = NULL) {
1163 // check if sort is of type CRM_Utils_Sort
1164 if (is_a($sort, 'CRM_Utils_Sort')) {
1165 return $sort->orderBy();
1168 // is it an array specified as $field => $sortDirection ?
1170 foreach ($sort as $k => $v) {
1171 $sortString .= "$k $v,";
1173 return rtrim($sortString, ',');
1179 * Fetch object based on array of properties.
1181 * @param string $daoName
1182 * Name of the dao object.
1183 * @param array $params
1184 * (reference ) an assoc array of name/value pairs.
1185 * @param array $defaults
1186 * (reference ) an assoc array to hold the flattened values.
1187 * @param array $returnProperities
1188 * An assoc array of fields that need to be returned, eg array( 'first_name', 'last_name').
1191 * an object of type referenced by daoName
1193 public static function commonRetrieve($daoName, &$params, &$defaults, $returnProperities = NULL) {
1194 $object = new $daoName();
1195 $object->copyValues($params);
1197 // return only specific fields if returnproperties are sent
1198 if (!empty($returnProperities)) {
1199 $object->selectAdd();
1200 $object->selectAdd(implode(',', $returnProperities));
1203 if ($object->find(TRUE)) {
1204 self
::storeValues($object, $defaults);
1211 * Delete the object records that are associated with this contact.
1213 * @param string $daoName
1214 * Name of the dao object.
1215 * @param int $contactId
1216 * Id of the contact to delete.
1218 public static function deleteEntityContact($daoName, $contactId) {
1219 $object = new $daoName();
1221 $object->entity_table
= 'civicrm_contact';
1222 $object->entity_id
= $contactId;
1227 * Execute an unbuffered query.
1229 * This is a wrapper around new functionality exposed with CRM-17748.
1231 * @param string $query query to be executed
1233 * @param array $params
1234 * @param bool $abort
1235 * @param null $daoName
1236 * @param bool $freeDAO
1237 * @param bool $i18nRewrite
1238 * @param bool $trapException
1240 * @return CRM_Core_DAO
1241 * Object that points to an unbuffered result set
1243 static public function executeUnbufferedQuery(
1249 $i18nRewrite = TRUE,
1250 $trapException = FALSE
1252 $queryStr = self
::composeQuery($query, $params, $abort);
1253 //CRM_Core_Error::debug( 'q', $queryStr );
1255 $dao = new CRM_Core_DAO();
1258 $dao = new $daoName();
1261 if ($trapException) {
1262 CRM_Core_Error
::ignoreException();
1265 // set the DAO object to use an unbuffered query
1266 $dao->setOptions(array('result_buffering' => 0));
1268 $result = $dao->query($queryStr, $i18nRewrite);
1270 if ($trapException) {
1271 CRM_Core_Error
::setCallback();
1274 if (is_a($result, 'DB_Error')) {
1278 // since it is unbuffered, ($dao->N==0) is true. This blocks the standard fetch() mechanism.
1282 preg_match('/^(insert|update|delete|create|drop|replace)/i', $queryStr)
1284 // we typically do this for insert/update/delete stataments OR if explicitly asked to
1294 * @param string $query
1295 * Query to be executed.
1297 * @param array $params
1298 * @param bool $abort
1299 * @param null $daoName
1300 * @param bool $freeDAO
1301 * @param bool $i18nRewrite
1302 * @param bool $trapException
1304 * @return CRM_Core_DAO|object
1305 * object that holds the results of the query
1306 * NB - if this is defined as just returning a DAO phpstorm keeps pointing
1307 * out all the properties that are not part of the DAO
1309 public static function &executeQuery(
1315 $i18nRewrite = TRUE,
1316 $trapException = FALSE
1318 $queryStr = self
::composeQuery($query, $params, $abort);
1321 $dao = new CRM_Core_DAO();
1324 $dao = new $daoName();
1327 if ($trapException) {
1328 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
1331 $result = $dao->query($queryStr, $i18nRewrite);
1333 if (is_a($result, 'DB_Error')) {
1338 preg_match('/^(insert|update|delete|create|drop|replace)/i', $queryStr)
1340 // we typically do this for insert/update/delete statements OR if explicitly asked to
1348 * Execute a query and get the single result.
1350 * @param string $query
1351 * Query to be executed.
1352 * @param array $params
1353 * @param bool $abort
1354 * @param bool $i18nRewrite
1355 * @return string|null
1356 * the result of the query if any
1359 public static function &singleValueQuery(
1365 $queryStr = self
::composeQuery($query, $params, $abort);
1367 static $_dao = NULL;
1370 $_dao = new CRM_Core_DAO();
1373 $_dao->query($queryStr, $i18nRewrite);
1375 $result = $_dao->getDatabaseResult();
1378 $row = $result->fetchRow();
1388 * Compose the query by merging the parameters into it.
1390 * @param string $query
1391 * @param array $params
1392 * @param bool $abort
1397 public static function composeQuery($query, $params, $abort = TRUE) {
1399 foreach ($params as $key => $item) {
1400 if (is_numeric($key)) {
1401 if (CRM_Utils_Type
::validate($item[0], $item[1]) !== NULL) {
1402 $item[0] = self
::escapeString($item[0]);
1403 if ($item[1] == 'String' ||
1404 $item[1] == 'Memo' ||
1407 // Support class constants stipulating wildcard characters and/or
1408 // non-quoting of strings. Also support legacy code which may be
1409 // passing in TRUE or 1 for $item[2], which used to indicate the
1410 // use of wildcard characters.
1411 if (!empty($item[2])) {
1412 if ($item[2] & CRM_Core_DAO
::QUERY_FORMAT_WILDCARD ||
$item[2] === TRUE) {
1413 $item[0] = "'%{$item[0]}%'";
1415 elseif (!($item[2] & CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
)) {
1416 $item[0] = "'{$item[0]}'";
1420 $item[0] = "'{$item[0]}'";
1424 if (($item[1] == 'Date' ||
$item[1] == 'Timestamp') &&
1425 strlen($item[0]) == 0
1430 $tr['%' . $key] = $item[0];
1433 CRM_Core_Error
::fatal("{$item[0]} is not of type {$item[1]}");
1438 return strtr($query, $tr);
1444 public static function freeResult($ids = NULL) {
1445 global $_DB_DATAOBJECT;
1448 if (!$_DB_DATAOBJECT ||
1449 !isset($_DB_DATAOBJECT['RESULTS'])
1453 $ids = array_keys($_DB_DATAOBJECT['RESULTS']);
1456 foreach ($ids as $id) {
1457 if (isset($_DB_DATAOBJECT['RESULTS'][$id])) {
1458 $_DB_DATAOBJECT['RESULTS'][$id]->free();
1459 unset($_DB_DATAOBJECT['RESULTS'][$id]);
1462 if (isset($_DB_DATAOBJECT['RESULTFIELDS'][$id])) {
1463 unset($_DB_DATAOBJECT['RESULTFIELDS'][$id]);
1469 * make a shallow copy of an object.
1470 * and all the fields in the object
1472 * @param string $daoName
1474 * @param array $criteria
1475 * Array of all the fields & values.
1476 * on which basis to copy
1477 * @param array $newData
1478 * Array of all the fields & values.
1479 * to be copied besides the other fields
1480 * @param string $fieldsFix
1481 * Array of fields that you want to prefix/suffix/replace.
1482 * @param string $blockCopyOfDependencies
1483 * Fields that you want to block from.
1487 * @return CRM_Core_DAO
1488 * the newly created copy of the object
1490 public static function ©Generic($daoName, $criteria, $newData = NULL, $fieldsFix = NULL, $blockCopyOfDependencies = NULL) {
1491 $object = new $daoName();
1493 $object->id
= $criteria['id'];
1496 foreach ($criteria as $key => $value) {
1497 $object->$key = $value;
1502 while ($object->fetch()) {
1504 // all the objects except with $blockCopyOfDependencies set
1505 // be copied - addresses #CRM-1962
1507 if ($blockCopyOfDependencies && $object->$blockCopyOfDependencies) {
1511 $newObject = new $daoName();
1513 $fields = &$object->fields();
1514 if (!is_array($fieldsFix)) {
1515 $fieldsToPrefix = array();
1516 $fieldsToSuffix = array();
1517 $fieldsToReplace = array();
1519 if (!empty($fieldsFix['prefix'])) {
1520 $fieldsToPrefix = $fieldsFix['prefix'];
1522 if (!empty($fieldsFix['suffix'])) {
1523 $fieldsToSuffix = $fieldsFix['suffix'];
1525 if (!empty($fieldsFix['replace'])) {
1526 $fieldsToReplace = $fieldsFix['replace'];
1529 foreach ($fields as $name => $value) {
1530 if ($name == 'id' ||
$value['name'] == 'id') {
1531 // copy everything but the id!
1535 $dbName = $value['name'];
1536 $type = CRM_Utils_Type
::typeToString($value['type']);
1537 $newObject->$dbName = $object->$dbName;
1538 if (isset($fieldsToPrefix[$dbName])) {
1539 $newObject->$dbName = $fieldsToPrefix[$dbName] . $newObject->$dbName;
1541 if (isset($fieldsToSuffix[$dbName])) {
1542 $newObject->$dbName .= $fieldsToSuffix[$dbName];
1544 if (isset($fieldsToReplace[$dbName])) {
1545 $newObject->$dbName = $fieldsToReplace[$dbName];
1548 if ($type == 'Timestamp' ||
$type == 'Date') {
1549 $newObject->$dbName = CRM_Utils_Date
::isoToMysql($newObject->$dbName);
1553 foreach ($newData as $k => $v) {
1554 $newObject->$k = $v;
1564 * Cascade update through related entities.
1566 * @param string $daoName
1569 * @param array $newData
1571 * @return CRM_Core_DAO|null
1573 public static function cascadeUpdate($daoName, $fromId, $toId, $newData = array()) {
1574 $object = new $daoName();
1575 $object->id
= $fromId;
1577 if ($object->find(TRUE)) {
1578 $newObject = new $daoName();
1579 $newObject->id
= $toId;
1581 if ($newObject->find(TRUE)) {
1582 $fields = &$object->fields();
1583 foreach ($fields as $name => $value) {
1584 if ($name == 'id' ||
$value['name'] == 'id') {
1585 // copy everything but the id!
1589 $colName = $value['name'];
1590 $newObject->$colName = $object->$colName;
1592 if (substr($name, -5) == '_date' ||
1593 substr($name, -10) == '_date_time'
1595 $newObject->$colName = CRM_Utils_Date
::isoToMysql($newObject->$colName);
1598 foreach ($newData as $k => $v) {
1599 $newObject->$k = $v;
1609 * Given the component id, compute the contact id
1610 * since its used for things like send email
1612 * @param $componentIDs
1613 * @param string $tableName
1617 public static function &getContactIDsFromComponent(&$componentIDs, $tableName) {
1618 $contactIDs = array();
1620 if (empty($componentIDs)) {
1624 $IDs = implode(',', $componentIDs);
1628 WHERE id IN ( $IDs )
1631 $dao = CRM_Core_DAO
::executeQuery($query);
1632 while ($dao->fetch()) {
1633 $contactIDs[] = $dao->contact_id
;
1639 * Fetch object based on array of properties.
1641 * @param string $daoName
1642 * Name of the dao object.
1643 * @param string $fieldIdName
1644 * @param int $fieldId
1646 * @param array $returnProperities
1647 * An assoc array of fields that need to be returned, eg array( 'first_name', 'last_name').
1650 * an object of type referenced by daoName
1652 public static function commonRetrieveAll($daoName, $fieldIdName = 'id', $fieldId, &$details, $returnProperities = NULL) {
1653 require_once str_replace('_', DIRECTORY_SEPARATOR
, $daoName) . ".php";
1654 $object = new $daoName();
1655 $object->$fieldIdName = $fieldId;
1657 // return only specific fields if returnproperties are sent
1658 if (!empty($returnProperities)) {
1659 $object->selectAdd();
1660 $object->selectAdd('id');
1661 $object->selectAdd(implode(',', $returnProperities));
1665 while ($object->fetch()) {
1666 $defaults = array();
1667 self
::storeValues($object, $defaults);
1668 $details[$object->id
] = $defaults;
1674 public static function dropAllTables() {
1676 // first drop all the custom tables we've created
1677 CRM_Core_BAO_CustomGroup
::dropAllTables();
1679 // drop all multilingual views
1680 CRM_Core_I18n_Schema
::dropAllViews();
1682 CRM_Utils_File
::sourceSQLFile(CIVICRM_DSN
,
1683 dirname(__FILE__
) . DIRECTORY_SEPARATOR
.
1684 '..' . DIRECTORY_SEPARATOR
.
1685 '..' . DIRECTORY_SEPARATOR
.
1686 'sql' . DIRECTORY_SEPARATOR
.
1687 'civicrm_drop.mysql'
1696 public static function escapeString($string) {
1697 static $_dao = NULL;
1699 // If this is an atypical case (e.g. preparing .sql file before CiviCRM
1700 // has been installed), then we fallback DB-less str_replace escaping, as
1701 // we can't use mysqli_real_escape_string, as there is no DB connection.
1702 // Note: In typical usage, escapeString() will only check one conditional
1703 // ("if !$_dao") rather than two conditionals ("if !defined(DSN)")
1704 if (!defined('CIVICRM_DSN')) {
1705 // See http://php.net/manual/en/mysqli.real-escape-string.php for the
1706 // list of characters mysqli_real_escape_string escapes.
1707 $search = array("\\", "\x00", "\n", "\r", "'", '"', "\x1a");
1708 $replace = array("\\\\", "\\0", "\\n", "\\r", "\'", '\"', "\\Z");
1709 return str_replace($search, $replace, $string);
1711 $_dao = new CRM_Core_DAO();
1713 return $_dao->escape($string);
1717 * Escape a list of strings for use with "WHERE X IN (...)" queries.
1719 * @param array $strings
1720 * @param string $default
1721 * the value to use if $strings has no elements.
1723 * eg "abc","def","ghi"
1725 public static function escapeStrings($strings, $default = NULL) {
1726 static $_dao = NULL;
1728 $_dao = new CRM_Core_DAO();
1731 if (empty($strings)) {
1735 $escapes = array_map(array($_dao, 'escape'), $strings);
1736 return '"' . implode('","', $escapes) . '"';
1744 public static function escapeWildCardString($string) {
1746 // ensure we escape the single characters % and _ which are mysql wild
1747 // card characters and could come in via sortByCharacter
1748 // note that mysql does not escape these characters
1749 if ($string && in_array($string,
1750 array('%', '_', '%%', '_%')
1753 return '\\' . $string;
1756 return self
::escapeString($string);
1760 * Creates a test object, including any required objects it needs via recursion
1761 * createOnly: only create in database, do not store or return the objects (useful for perf testing)
1762 * ONLY USE FOR TESTING
1764 * @param string $daoName
1765 * @param array $params
1766 * @param int $numObjects
1767 * @param bool $createOnly
1769 * @return object|array|NULL
1770 * NULL if $createOnly. A single object if $numObjects==1. Otherwise, an array of multiple objects.
1772 public static function createTestObject(
1778 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
1779 // so we re-set here in case
1780 $config = CRM_Core_Config
::singleton();
1781 $config->backtrace
= TRUE;
1783 static $counter = 0;
1784 CRM_Core_DAO
::$_testEntitiesToSkip = array(
1785 'CRM_Core_DAO_Worldregion',
1786 'CRM_Core_DAO_StateProvince',
1787 'CRM_Core_DAO_Country',
1788 'CRM_Core_DAO_Domain',
1789 'CRM_Financial_DAO_FinancialType',
1790 //because valid ones exist & we use pick them due to pseudoconstant can't reliably create & delete these
1793 // Prefer to instantiate BAO's instead of DAO's (when possible)
1794 // so that assignTestValue()/assignTestFK() can be overloaded.
1795 $baoName = str_replace('_DAO_', '_BAO_', $daoName);
1796 if (class_exists($baoName)) {
1797 $daoName = $baoName;
1800 for ($i = 0; $i < $numObjects; ++
$i) {
1803 /** @var CRM_Core_DAO $object */
1804 $object = new $daoName();
1806 $fields = &$object->fields();
1807 foreach ($fields as $fieldName => $fieldDef) {
1808 $dbName = $fieldDef['name'];
1809 $FKClassName = CRM_Utils_Array
::value('FKClassName', $fieldDef);
1810 $required = CRM_Utils_Array
::value('required', $fieldDef);
1812 if (CRM_Utils_Array
::value($dbName, $params) !== NULL && !is_array($params[$dbName])) {
1813 $object->$dbName = $params[$dbName];
1816 elseif ($dbName != 'id') {
1817 if ($FKClassName != NULL) {
1818 $object->assignTestFK($fieldName, $fieldDef, $params);
1822 $object->assignTestValue($fieldName, $fieldDef, $counter);
1830 $objects[$i] = $object;
1840 elseif ($numObjects == 1) {
1849 * Deletes the this object plus any dependent objects that are associated with it.
1850 * ONLY USE FOR TESTING
1852 * @param string $daoName
1853 * @param array $params
1855 public static function deleteTestObjects($daoName, $params = array()) {
1856 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
1857 // so we re-set here in case
1858 $config = CRM_Core_Config
::singleton();
1859 $config->backtrace
= TRUE;
1861 $object = new $daoName();
1862 $object->id
= CRM_Utils_Array
::value('id', $params);
1864 $deletions = array(); // array(array(0 => $daoName, 1 => $daoParams))
1865 if ($object->find(TRUE)) {
1867 $fields = &$object->fields();
1868 foreach ($fields as $name => $value) {
1870 $dbName = $value['name'];
1872 $FKClassName = CRM_Utils_Array
::value('FKClassName', $value);
1873 $required = CRM_Utils_Array
::value('required', $value);
1874 if ($FKClassName != NULL
1876 && !in_array($FKClassName, CRM_Core_DAO
::$_testEntitiesToSkip)
1877 && ($required ||
$dbName == 'contact_id')
1878 //I'm a bit stuck on this one - we might need to change the singleValueAlter so that the entities don't share a contact
1879 // to make this test process pass - line below makes pass for now
1880 && $dbName != 'member_of_contact_id'
1882 $deletions[] = array($FKClassName, array('id' => $object->$dbName)); // x
1889 foreach ($deletions as $deletion) {
1890 CRM_Core_DAO
::deleteTestObjects($deletion[0], $deletion[1]);
1895 * Set defaults when creating new entity.
1896 * (don't call this set defaults as already in use with different signature in some places)
1898 * @param array $params
1901 public static function setCreateDefaults(&$params, $defaults) {
1902 if (!empty($params['id'])) {
1905 foreach ($defaults as $key => $value) {
1906 if (!array_key_exists($key, $params) ||
$params[$key] === NULL) {
1907 $params[$key] = $value;
1913 * @param string $prefix
1914 * @param bool $addRandomString
1915 * @param null $string
1919 public static function createTempTableName($prefix = 'civicrm', $addRandomString = TRUE, $string = NULL) {
1920 $tableName = $prefix . "_temp";
1922 if ($addRandomString) {
1924 $tableName .= "_" . $string;
1927 $tableName .= "_" . md5(uniqid('', TRUE));
1935 * @param bool $trigger
1939 public static function checkTriggerViewPermission($view = TRUE, $trigger = TRUE) {
1940 if (\Civi
::settings()->get('logging_no_trigger_permission')) {
1943 // test for create view and trigger permissions and if allowed, add the option to go multilingual
1945 // I'm not sure why we use the getStaticProperty for an error, rather than checking for DB_Error
1946 CRM_Core_TemporaryErrorScope
::ignoreException();
1947 $dao = new CRM_Core_DAO();
1949 $result = $dao->query('CREATE OR REPLACE VIEW civicrm_domain_view AS SELECT * FROM civicrm_domain');
1950 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError') ||
is_a($result, 'DB_Error')) {
1956 $result = $dao->query('CREATE TRIGGER civicrm_domain_trigger BEFORE INSERT ON civicrm_domain FOR EACH ROW BEGIN END');
1957 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError') ||
is_a($result, 'DB_Error')) {
1959 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1964 $dao->query('DROP TRIGGER IF EXISTS civicrm_domain_trigger');
1965 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
1967 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1974 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1975 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
1984 * @param null $message
1985 * @param bool $printDAO
1987 public static function debugPrint($message = NULL, $printDAO = TRUE) {
1988 CRM_Utils_System
::xMemory("{$message}: ");
1991 global $_DB_DATAOBJECT;
1993 foreach (array_keys($_DB_DATAOBJECT['RESULTS']) as $id) {
1994 $q[] = $_DB_DATAOBJECT['RESULTS'][$id]->query
;
1996 CRM_Core_Error
::debug('_DB_DATAOBJECT', $q);
2001 * Build a list of triggers via hook and add them to (err, reconcile them
2002 * with) the database.
2004 * @param string $tableName
2005 * the specific table requiring a rebuild; or NULL to rebuild all tables.
2006 * @param bool $force
2011 public static function triggerRebuild($tableName = NULL, $force = FALSE) {
2012 Civi
::service('sql_triggers')->rebuild($tableName, $force);
2016 * Because sql functions are sometimes lost, esp during db migration, we check here to avoid numerous support requests
2017 * @see http://issues.civicrm.org/jira/browse/CRM-13822
2018 * TODO: Alternative solutions might be
2019 * * Stop using functions and find another way to strip numeric characters from phones
2020 * * Give better error messages (currently a missing fn fatals with "unknown error")
2022 public static function checkSqlFunctionsExist() {
2023 if (!self
::$_checkedSqlFunctionsExist) {
2024 self
::$_checkedSqlFunctionsExist = TRUE;
2025 $dao = CRM_Core_DAO
::executeQuery("SHOW function status WHERE db = database() AND name = 'civicrm_strip_non_numeric'");
2026 if (!$dao->fetch()) {
2027 self
::triggerRebuild();
2033 * Wrapper function to drop triggers.
2035 * @param string $tableName
2036 * the specific table requiring a rebuild; or NULL to rebuild all tables.
2039 public static function dropTriggers($tableName = NULL) {
2040 Civi
::service('sql_triggers')->dropTriggers($tableName);
2044 * @param array $info
2045 * per hook_civicrm_triggerInfo.
2046 * @param string $onlyTableName
2047 * the specific table requiring a rebuild; or NULL to rebuild all tables.
2050 public static function createTriggers(&$info, $onlyTableName = NULL) {
2051 Civi
::service('sql_triggers')->createTriggers($info, $onlyTableName);
2055 * Given a list of fields, create a list of references.
2057 * @param string $className
2058 * BAO/DAO class name.
2059 * @return array<CRM_Core_Reference_Interface>
2061 public static function createReferenceColumns($className) {
2063 $fields = $className::fields();
2064 foreach ($fields as $field) {
2065 if (isset($field['pseudoconstant'], $field['pseudoconstant']['optionGroupName'])) {
2066 $result[] = new CRM_Core_Reference_OptionValue(
2067 $className::getTableName(),
2069 'civicrm_option_value',
2070 CRM_Utils_Array
::value('keyColumn', $field['pseudoconstant'], 'value'),
2071 $field['pseudoconstant']['optionGroupName']
2079 * Find all records which refer to this entity.
2082 * Array of objects referencing this
2084 public function findReferences() {
2085 $links = self
::getReferencesToTable(static::getTableName());
2087 $occurrences = array();
2088 foreach ($links as $refSpec) {
2089 /** @var $refSpec CRM_Core_Reference_Interface */
2090 $daoName = CRM_Core_DAO_AllCoreTables
::getClassForTable($refSpec->getReferenceTable());
2091 $result = $refSpec->findReferences($this);
2093 while ($result->fetch()) {
2094 $obj = new $daoName();
2095 $obj->id
= $result->id
;
2096 $occurrences[] = $obj;
2101 return $occurrences;
2106 * each item has keys:
2110 * - table: string|null SQL table name
2111 * - key: string|null SQL column name
2113 public function getReferenceCounts() {
2114 $links = self
::getReferencesToTable(static::getTableName());
2117 foreach ($links as $refSpec) {
2118 /** @var $refSpec CRM_Core_Reference_Interface */
2119 $count = $refSpec->getReferenceCount($this);
2120 if ($count['count'] != 0) {
2125 foreach (CRM_Core_Component
::getEnabledComponents() as $component) {
2126 /** @var $component CRM_Core_Component_Info */
2127 $counts = array_merge($counts, $component->getReferenceCounts($this));
2129 CRM_Utils_Hook
::referenceCounts($this, $counts);
2135 * List all tables which have hard foreign keys to this table.
2137 * For now, this returns a description of every entity_id/entity_table
2139 * TODO: filter dynamic entity references on the $tableName, based on
2140 * schema metadata in dynamicForeignKey which enumerates a restricted
2141 * set of possible entity_table's.
2143 * @param string $tableName
2144 * Table referred to.
2147 * structure of table and column, listing every table with a
2148 * foreign key reference to $tableName, and the column where the key appears.
2150 public static function getReferencesToTable($tableName) {
2151 $refsFound = array();
2152 foreach (CRM_Core_DAO_AllCoreTables
::getClasses() as $daoClassName) {
2153 $links = $daoClassName::getReferenceColumns();
2154 $daoTableName = $daoClassName::getTableName();
2156 foreach ($links as $refSpec) {
2157 /** @var $refSpec CRM_Core_Reference_Interface */
2158 if ($refSpec->matchesTargetTable($tableName)) {
2159 $refsFound[] = $refSpec;
2167 * Lookup the value of a MySQL global configuration variable.
2169 * @param string $name
2170 * E.g. "thread_stack".
2171 * @param mixed $default
2174 public static function getGlobalSetting($name, $default = NULL) {
2175 // Alternatively, SELECT @@GLOBAL.thread_stack, but
2176 // that has been reported to fail under MySQL 5.0 for OS X
2177 $escapedName = self
::escapeString($name);
2178 $dao = CRM_Core_DAO
::executeQuery("SHOW VARIABLES LIKE '$escapedName'");
2179 if ($dao->fetch()) {
2189 * Update the fields array to also hold keys for pseudoconstant fields that relate to contained fields.
2191 * This is relevant where we want to offer both the ID field and the label field
2192 * as an option, e.g. search builder.
2194 * It is currently limited for optionGroupName for purposes keeping the scope of the
2195 * change small, but is appropriate for other sorts of pseudoconstants.
2197 * @param array $fields
2199 protected static function appendPseudoConstantsToFields(&$fields) {
2200 foreach ($fields as $field) {
2201 if (!empty($field['pseudoconstant']) && !empty($field['pseudoconstant']['optionGroupName'])) {
2202 $fields[$field['pseudoconstant']['optionGroupName']] = array(
2203 'title' => CRM_Core_BAO_OptionGroup
::getTitleByName($field['pseudoconstant']['optionGroupName']),
2204 'name' => $field['pseudoconstant']['optionGroupName'],
2205 'data_type' => CRM_Utils_Type
::T_STRING
,
2212 * Get options for the called BAO object's field.
2214 * This function can be overridden by each BAO to add more logic related to context.
2215 * The overriding function will generally call the lower-level CRM_Core_PseudoConstant::get
2217 * @param string $fieldName
2218 * @param string $context
2219 * @see CRM_Core_DAO::buildOptionsContext
2220 * @param array $props
2221 * whatever is known about this bao object.
2223 * @return array|bool
2225 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
2226 // If a given bao does not override this function
2227 $baoName = get_called_class();
2228 return CRM_Core_PseudoConstant
::get($baoName, $fieldName, $props, $context);
2232 * Populate option labels for this object's fields.
2234 * @throws exception if called directly on the base class
2236 public function getOptionLabels() {
2237 $fields = $this->fields();
2238 if ($fields === NULL) {
2239 throw new Exception('Cannot call getOptionLabels on CRM_Core_DAO');
2241 foreach ($fields as $field) {
2242 $name = CRM_Utils_Array
::value('name', $field);
2243 if ($name && isset($this->$name)) {
2244 $label = CRM_Core_PseudoConstant
::getLabel(get_class($this), $name, $this->$name);
2245 if ($label !== FALSE) {
2246 // Append 'label' onto the field name
2247 $labelName = $name . '_label';
2248 $this->$labelName = $label;
2255 * Provides documentation and validation for the buildOptions $context param
2257 * @param string $context
2262 public static function buildOptionsContext($context = NULL) {
2264 'get' => "get: all options are returned, even if they are disabled; labels are translated.",
2265 'create' => "create: options are filtered appropriately for the object being created/updated; labels are translated.",
2266 'search' => "search: searchable options are returned; labels are translated.",
2267 'validate' => "validate: all options are returned, even if they are disabled; machine names are used in place of labels.",
2268 'abbreviate' => "abbreviate: enabled options are returned; labels are replaced with abbreviations.",
2269 'match' => "match: enabled options are returned using machine names as keys; labels are translated.",
2271 // Validation: enforce uniformity of this param
2272 if ($context !== NULL && !isset($contexts[$context])) {
2273 throw new Exception("'$context' is not a valid context for buildOptions.");
2279 * @param string $fieldName
2280 * @return bool|array
2282 public function getFieldSpec($fieldName) {
2283 $fields = $this->fields();
2284 $fieldKeys = $this->fieldKeys();
2286 // Support "unique names" as well as sql names
2287 $fieldKey = $fieldName;
2288 if (empty($fields[$fieldKey])) {
2289 $fieldKey = CRM_Utils_Array
::value($fieldName, $fieldKeys);
2291 // If neither worked then this field doesn't exist. Return false.
2292 if (empty($fields[$fieldKey])) {
2295 return $fields[$fieldKey];
2299 * Get SQL where clause for SQL filter syntax input parameters.
2301 * SQL version of api function to assign filters to the DAO based on the syntax
2302 * $field => array('IN' => array(4,6,9))
2304 * $field => array('LIKE' => array('%me%))
2307 * @param string $fieldName
2309 * @param array $filter
2310 * filter to be applied indexed by operator.
2311 * @param string $type
2312 * type of field (not actually used - nor in api @todo ).
2313 * @param string $alias
2314 * alternative field name ('as') @todo- not actually used.
2315 * @param bool $returnSanitisedArray
2316 * Return a sanitised array instead of a clause.
2317 * this is primarily so we can add filters @ the api level to the Query object based fields
2321 * @return NULL|string|array
2322 * a string is returned if $returnSanitisedArray is not set, otherwise and Array or NULL
2323 * depending on whether it is supported as yet
2325 public static function createSQLFilter($fieldName, $filter, $type = NULL, $alias = NULL, $returnSanitisedArray = FALSE) {
2326 foreach ($filter as $operator => $criteria) {
2327 if (in_array($operator, self
::acceptedSQLOperators(), TRUE)) {
2328 switch ($operator) {
2332 if (!$returnSanitisedArray) {
2333 return (sprintf('%s %s', $fieldName, $operator));
2336 return (sprintf('%s %s ', $fieldName, $operator));
2340 // ternary operators
2343 if (empty($criteria[0]) ||
empty($criteria[1])) {
2344 throw new Exception("invalid criteria for $operator");
2346 if (!$returnSanitisedArray) {
2347 return (sprintf('%s ' . $operator . ' "%s" AND "%s"', $fieldName, CRM_Core_DAO
::escapeString($criteria[0]), CRM_Core_DAO
::escapeString($criteria[1])));
2350 return NULL; // not yet implemented (tests required to implement)
2357 if (empty($criteria)) {
2358 throw new Exception("invalid criteria for $operator");
2360 $escapedCriteria = array_map(array(
2364 if (!$returnSanitisedArray) {
2365 return (sprintf('%s %s ("%s")', $fieldName, $operator, implode('", "', $escapedCriteria)));
2367 return $escapedCriteria;
2372 if (!$returnSanitisedArray) {
2373 return (sprintf('%s %s "%s"', $fieldName, $operator, CRM_Core_DAO
::escapeString($criteria)));
2376 return NULL; // not yet implemented (tests required to implement)
2384 * @see http://issues.civicrm.org/jira/browse/CRM-9150
2385 * support for other syntaxes is discussed in ticket but being put off for now
2388 public static function acceptedSQLOperators() {
2409 * SQL has a limit of 64 characters on various names:
2410 * table name, trigger name, column name ...
2412 * For custom groups and fields we generated names from user entered input
2413 * which can be longer than this length, this function helps with creating
2414 * strings that meet various criteria.
2416 * @param string $string
2417 * The string to be shortened.
2418 * @param int $length
2419 * The max length of the string.
2421 * @param bool $makeRandom
2425 public static function shortenSQLName($string, $length = 60, $makeRandom = FALSE) {
2426 // early return for strings that meet the requirements
2427 if (strlen($string) <= $length) {
2431 // easy return for calls that dont need a randomized uniq string
2433 return substr($string, 0, $length);
2436 // the string is longer than the length and we need a uniq string
2437 // for the same tablename we need the same uniq string every time
2438 // hence we use md5 on the string, which is not random
2439 // we'll append 8 characters to the end of the tableName
2440 $md5string = substr(md5($string), 0, 8);
2441 return substr($string, 0, $length - 8) . "_{$md5string}";
2445 * https://issues.civicrm.org/jira/browse/CRM-17748
2446 * Sets the internal options to be used on a query
2448 * @param array $options
2451 public function setOptions($options) {
2452 if (is_array($options)) {
2453 $this->_options
= $options;
2458 * https://issues.civicrm.org/jira/browse/CRM-17748
2459 * wrapper to pass internal DAO options down to DB_mysql/DB_Common level
2461 * @param array $options
2464 protected function _setDBOptions($options) {
2465 global $_DB_DATAOBJECT;
2467 if (is_array($options) && count($options)) {
2468 $conn = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5
];
2469 foreach ($options as $option_name => $option_value) {
2470 $conn->setOption($option_name, $option_value);
2477 * @param array $params
2479 public function setApiFilter(&$params) {
2483 * Generates acl clauses suitable for adding to WHERE or ON when doing an api.get for this entity
2485 * Return format is in the form of fieldname => clauses starting with an operator. e.g.:
2488 * 'location_type_id' => array('IS NOT NULL', 'IN (1,2,3)')
2492 * Note that all array keys must be actual field names in this entity. Use subqueries to filter on other tables e.g. custom values.
2496 public function addSelectWhereClause() {
2498 $fields = $this->fields();
2499 foreach ($fields as $fieldName => $field) {
2500 // Clause for contact-related entities like Email, Relationship, etc.
2501 if (strpos($fieldName, 'contact_id') === 0 && CRM_Utils_Array
::value('FKClassName', $field) == 'CRM_Contact_DAO_Contact') {
2502 $clauses[$fieldName] = CRM_Utils_SQL
::mergeSubquery('Contact');
2504 // Clause for an entity_table/entity_id combo
2505 if ($fieldName == 'entity_id' && isset($fields['entity_table'])) {
2506 $relatedClauses = array();
2507 $relatedEntities = $this->buildOptions('entity_table', 'get');
2508 foreach ((array) $relatedEntities as $table => $ent) {
2510 $ent = CRM_Core_DAO_AllCoreTables
::getBriefName(CRM_Core_DAO_AllCoreTables
::getClassForTable($table));
2511 $subquery = CRM_Utils_SQL
::mergeSubquery($ent);
2513 $relatedClauses[] = "(entity_table = '$table' AND entity_id " . implode(' AND entity_id ', $subquery) . ")";
2516 $relatedClauses[] = "(entity_table = '$table')";
2520 if ($relatedClauses) {
2521 $clauses['id'] = 'IN (SELECT id FROM `' . $this->tableName() . '` WHERE (' . implode(') OR (', $relatedClauses) . '))';
2525 CRM_Utils_Hook
::selectWhereClause($this, $clauses);
2530 * This returns the final permissioned query string for this entity
2532 * With acls from related entities + additional clauses from hook_civicrm_selectWhereClause
2534 * @param string $tableAlias
2537 public static function getSelectWhereClause($tableAlias = NULL) {
2538 $bao = new static();
2539 if ($tableAlias === NULL) {
2540 $tableAlias = $bao->tableName();
2543 foreach ((array) $bao->addSelectWhereClause() as $field => $vals) {
2544 $clauses[$field] = NULL;
2546 $clauses[$field] = "(`$tableAlias`.`$field` IS NULL OR (`$tableAlias`.`$field` " . implode(" AND `$tableAlias`.`$field` ", (array) $vals) . '))';
2553 * ensure database name is 'safe', i.e. only contains word characters (includes underscores)
2554 * and dashes, and contains at least one [a-z] case insenstive.
2560 public static function requireSafeDBName($database) {
2563 "/^[\w\-]*[a-z]+[\w\-]*$/i",
2567 if (empty($matches)) {