3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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-2015
35 require_once 'PEAR.php';
36 require_once 'DB/DataObject.php';
38 require_once 'CRM/Core/I18n.php';
43 class CRM_Core_DAO
extends DB_DataObject
{
46 * A null object so we can pass it as reference if / when needed
48 static $_nullObject = NULL;
49 static $_nullArray = array();
51 static $_dbColumnValueCache = NULL;
52 const NOT_NULL
= 1, IS_NULL
= 2,
54 VALUE_SEPARATOR
= "\ 1",
55 BULK_INSERT_COUNT
= 200,
56 BULK_INSERT_HIGH_COUNT
= 200,
57 QUERY_FORMAT_WILDCARD
= 1,
58 QUERY_FORMAT_NO_QUOTES
= 2;
61 * Define entities that shouldn't be created or deleted when creating/ deleting
62 * test objects - this prevents world regions, countries etc from being added / deleted
65 static $_testEntitiesToSkip = array();
67 * The factory class for this application.
70 static $_factory = NULL;
72 static $_checkedSqlFunctionsExist = FALSE;
75 * https://issues.civicrm.org/jira/browse/CRM-17748
76 * internal variable for DAO to hold per-query settings
78 protected $_options = array();
83 * @return \CRM_Core_DAO
85 public function __construct() {
87 $this->__table
= $this->getTableName();
91 * Empty definition for virtual function.
93 public static function getTableName() {
98 * Initialize the DAO object.
101 * The database connection string.
103 public static function init($dsn) {
104 Civi
::$statics[__CLASS__
]['init'] = 1;
105 $options = &PEAR
::getStaticProperty('DB_DataObject', 'options');
106 $options['database'] = $dsn;
107 if (defined('CIVICRM_DAO_DEBUG')) {
108 self
::DebugLevel(CIVICRM_DAO_DEBUG
);
110 CRM_Core_DAO
::setFactory(new CRM_Contact_DAO_Factory());
111 if (CRM_Utils_Constant
::value('CIVICRM_MYSQL_STRICT', CRM_Utils_System
::isDevelopment())) {
112 CRM_Core_DAO
::executeQuery('SET SESSION sql_mode = STRICT_TRANS_TABLES');
114 CRM_Core_DAO
::executeQuery('SET NAMES utf8');
118 * @param string $fieldName
120 * @param array $params
122 protected function assignTestFK($fieldName, $fieldDef, $params) {
123 $required = CRM_Utils_Array
::value('required', $fieldDef);
124 $FKClassName = CRM_Utils_Array
::value('FKClassName', $fieldDef);
125 $dbName = $fieldDef['name'];
126 $daoName = str_replace('_BAO_', '_DAO_', get_class($this));
128 // skip the FK if it is not required
129 // if it's contact id we should create even if not required
130 // we'll have a go @ fetching first though
131 // we WILL create campaigns though for so tests with a campaign pseudoconstant will complete
132 if ($FKClassName === 'CRM_Campaign_DAO_Campaign' && $daoName != $FKClassName) {
135 if (!$required && $dbName != 'contact_id') {
136 $fkDAO = new $FKClassName();
137 if ($fkDAO->find(TRUE)) {
138 $this->$dbName = $fkDAO->id
;
143 elseif (in_array($FKClassName, CRM_Core_DAO
::$_testEntitiesToSkip)) {
144 $depObject = new $FKClassName();
145 $depObject->find(TRUE);
146 $this->$dbName = $depObject->id
;
149 elseif ($daoName == 'CRM_Member_DAO_MembershipType' && $fieldName == 'member_of_contact_id') {
150 // FIXME: the fields() metadata is not specific enough
151 $depObject = CRM_Core_DAO
::createTestObject($FKClassName, array('contact_type' => 'Organization'));
152 $this->$dbName = $depObject->id
;
156 //if it is required we need to generate the dependency object first
157 $depObject = CRM_Core_DAO
::createTestObject($FKClassName, CRM_Utils_Array
::value($dbName, $params, 1));
158 $this->$dbName = $depObject->id
;
164 * Generate and assign an arbitrary value to a field of a test object.
166 * @param string $fieldName
167 * @param array $fieldDef
168 * @param int $counter
169 * The globally-unique ID of the test object.
171 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
172 $dbName = $fieldDef['name'];
173 $daoName = get_class($this);
176 if (!$handled && $dbName == 'contact_sub_type') {
177 //coming up with a rule to set this is too complex let's not set it
181 // Pick an option value if needed
182 if (!$handled && $fieldDef['type'] !== CRM_Utils_Type
::T_BOOLEAN
) {
183 $options = $daoName::buildOptions($dbName, 'create');
185 $this->$dbName = key($options);
191 switch ($fieldDef['type']) {
192 case CRM_Utils_Type
::T_INT
:
193 case CRM_Utils_Type
::T_FLOAT
:
194 case CRM_Utils_Type
::T_MONEY
:
195 if (isset($fieldDef['precision'])) {
196 // $object->$dbName = CRM_Utils_Number::createRandomDecimal($value['precision']);
197 $this->$dbName = CRM_Utils_Number
::createTruncatedDecimal($counter, $fieldDef['precision']);
200 $this->$dbName = $counter;
204 case CRM_Utils_Type
::T_BOOLEAN
:
205 if (isset($fieldDef['default'])) {
206 $this->$dbName = $fieldDef['default'];
208 elseif ($fieldDef['name'] == 'is_deleted' ||
$fieldDef['name'] == 'is_test') {
216 case CRM_Utils_Type
::T_DATE
:
217 case CRM_Utils_Type
::T_TIMESTAMP
:
218 case CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
:
219 $this->$dbName = '19700101';
220 if ($dbName == 'end_date') {
221 // put this in the future
222 $this->$dbName = '20200101';
226 case CRM_Utils_Type
::T_TIME
:
227 CRM_Core_Error
::fatal("T_TIME shouldn't be used.");
228 //$object->$dbName='000000';
230 case CRM_Utils_Type
::T_CCNUM
:
231 $this->$dbName = '4111 1111 1111 1111';
234 case CRM_Utils_Type
::T_URL
:
235 $this->$dbName = 'http://www.civicrm.org';
238 case CRM_Utils_Type
::T_STRING
:
239 case CRM_Utils_Type
::T_BLOB
:
240 case CRM_Utils_Type
::T_MEDIUMBLOB
:
241 case CRM_Utils_Type
::T_TEXT
:
242 case CRM_Utils_Type
::T_LONGTEXT
:
243 case CRM_Utils_Type
::T_EMAIL
:
245 // WAS: if (isset($value['enumValues'])) {
246 // TODO: see if this works with all pseudoconstants
247 if (isset($fieldDef['pseudoconstant'], $fieldDef['pseudoconstant']['callback'])) {
248 if (isset($fieldDef['default'])) {
249 $this->$dbName = $fieldDef['default'];
252 $options = CRM_Core_PseudoConstant
::get($daoName, $fieldName);
253 if (is_array($options)) {
254 $this->$dbName = $options[0];
257 $defaultValues = explode(',', $options);
258 $this->$dbName = $defaultValues[0];
263 $this->$dbName = $dbName . '_' . $counter;
264 $maxlength = CRM_Utils_Array
::value('maxlength', $fieldDef);
265 if ($maxlength > 0 && strlen($this->$dbName) > $maxlength) {
266 $this->$dbName = substr($this->$dbName, 0, $fieldDef['maxlength']);
274 * Reset the DAO object.
276 * DAO is kinda crappy in that there is an unwritten rule of one query per DAO.
278 * We attempt to get around this crappy restriction by resetting some of DAO's internal fields. Use this with caution
280 public function reset() {
282 foreach (array_keys($this->table()) as $field) {
283 unset($this->$field);
287 * reset the various DB_DAO structures manually
289 $this->_query
= array();
296 * @param string $tableName
300 public static function getLocaleTableName($tableName) {
303 $tables = CRM_Core_I18n_Schema
::schemaStructureTables();
304 if (in_array($tableName, $tables)) {
305 return $tableName . $dbLocale;
312 * Execute a query by the current DAO, localizing it along the way (if needed).
314 * @param string $query
315 * The SQL query for execution.
316 * @param bool $i18nRewrite
317 * Whether to rewrite the query.
320 * the current DAO object after the query execution
322 public function query($query, $i18nRewrite = TRUE) {
323 // rewrite queries that should use $dbLocale-based views for multi-language installs
324 global $dbLocale, $_DB_DATAOBJECT;
326 $conn = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5
];
327 $orig_options = $conn->options
;
328 $this->_setDBOptions($this->_options
);
330 if ($i18nRewrite and $dbLocale) {
331 $query = CRM_Core_I18n_Schema
::rewriteQuery($query);
334 $ret = parent
::query($query);
336 $this->_setDBOptions($orig_options);
341 * Static function to set the factory instance for this class.
343 * @param object $factory
344 * The factory application object.
346 public static function setFactory(&$factory) {
347 self
::$_factory = &$factory;
351 * Factory method to instantiate a new object from a table name.
353 * @param string $table
355 public function factory($table = '') {
356 if (!isset(self
::$_factory)) {
357 return parent
::factory($table);
360 return self
::$_factory->create($table);
364 * Initialization for all DAO objects. Since we access DB_DO programatically
365 * we need to set the links manually.
367 public function initialize() {
369 if (empty(Civi
::$statics[__CLASS__
]['init'])) {
370 // CRM_Core_DAO::init() must be called before CRM_Core_DAO->initialize().
371 // This occurs very early in bootstrap - error handlers may not be wired up.
372 echo "Inconsistent system initialization sequence. Premature access of (" . get_class($this) . ")";
373 CRM_Utils_System
::civiExit();
378 * Defines the default key as 'id'.
383 public function keys() {
392 * Tells DB_DataObject which keys use autoincrement.
393 * 'id' is autoincrementing by default.
398 public function sequenceKey() {
399 static $sequenceKeys;
400 if (!isset($sequenceKeys)) {
401 $sequenceKeys = array('id', TRUE);
403 return $sequenceKeys;
407 * Returns list of FK relationships.
411 * Array of CRM_Core_Reference_Interface
413 public static function getReferenceColumns() {
418 * Returns all the column names of this table.
423 public static function &fields() {
429 * Get/set an associative array of table columns
434 public function table() {
435 $fields = &$this->fields();
439 foreach ($fields as $name => $value) {
440 $table[$value['name']] = $value['type'];
441 if (!empty($value['required'])) {
442 $table[$value['name']] +
= self
::DB_DAO_NOTNULL
;
457 public function save($hook = TRUE) {
458 if (!empty($this->id
)) {
462 $event = new \Civi\Core\DAO\Event\
PostUpdate($this);
463 \Civi
::service('dispatcher')->dispatch("DAO::post-update", $event);
470 $event = new \Civi\Core\DAO\Event\
PostUpdate($this);
471 \Civi
::service('dispatcher')->dispatch("DAO::post-insert", $event);
477 CRM_Utils_Hook
::postSave($this);
484 * Deletes items from table which match current objects variables.
486 * Returns the true on success
490 * Designed to be extended
492 * $object = new mytable();
494 * echo $object->delete(); // builds a conditon
496 * $object = new mytable();
497 * $object->whereAdd('age > 12');
499 * $object->orderBy('age DESC');
500 * $object->delete(true); // dont use object vars, use the conditions, limit and order.
502 * @param bool $useWhere (optional) If DB_DATAOBJECT_WHEREADD_ONLY is passed in then
503 * we will build the condition only using the whereAdd's. Default is to
504 * build the condition only using the object parameters.
506 * * @return mixed Int (No. of rows affected) on success, false on failure, 0 on no data affected
508 public function delete($useWhere = FALSE) {
509 $result = parent
::delete($useWhere);
511 $event = new \Civi\Core\DAO\Event\
PostDelete($this, $result);
512 \Civi
::service('dispatcher')->dispatch("DAO::post-delete", $event);
518 * @param bool $created
520 public function log($created = FALSE) {
523 if (!$this->getLog()) {
528 $session = CRM_Core_Session
::singleton();
529 $cid = $session->get('userID');
532 // return is we dont have handle to FK
537 $dao = new CRM_Core_DAO_Log();
538 $dao->entity_table
= $this->getTableName();
539 $dao->entity_id
= $this->id
;
540 $dao->modified_id
= $cid;
541 $dao->modified_date
= date("YmdHis");
546 * Given an associative array of name/value pairs, extract all the values
547 * that belong to this object and initialize the object with said values
549 * @param array $params
550 * (reference ) associative array of name/value pairs.
553 * Did we copy all null values into the object
555 public function copyValues(&$params) {
556 $fields = &$this->fields();
558 foreach ($fields as $name => $value) {
559 $dbName = $value['name'];
560 if (array_key_exists($dbName, $params)) {
561 $pValue = $params[$dbName];
564 elseif (array_key_exists($name, $params)) {
565 $pValue = $params[$name];
572 // if there is no value then make the variable NULL
574 if ($pValue === '') {
575 $this->$dbName = 'null';
578 $this->$dbName = $pValue;
587 * Store all the values from this object in an associative array
588 * this is a destructive store, calling function is responsible
589 * for keeping sanity of id's.
591 * @param object $object
592 * The object that we are extracting data from.
593 * @param array $values
594 * (reference ) associative array of name/value pairs.
596 public static function storeValues(&$object, &$values) {
597 $fields = &$object->fields();
598 foreach ($fields as $name => $value) {
599 $dbName = $value['name'];
600 if (isset($object->$dbName) && $object->$dbName !== 'null') {
601 $values[$dbName] = $object->$dbName;
602 if ($name != $dbName) {
603 $values[$name] = $object->$dbName;
610 * Create an attribute for this specific field. We only do this for strings and text
612 * @param array $field
613 * The field under task.
616 * the attributes for the object
618 public static function makeAttribute($field) {
620 if (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_STRING
) {
621 $maxLength = CRM_Utils_Array
::value('maxlength', $field);
622 $size = CRM_Utils_Array
::value('size', $field);
623 if ($maxLength ||
$size) {
624 $attributes = array();
626 $attributes['maxlength'] = $maxLength;
629 $attributes['size'] = $size;
634 elseif (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_TEXT
) {
635 $rows = CRM_Utils_Array
::value('rows', $field);
639 $cols = CRM_Utils_Array
::value('cols', $field);
644 $attributes = array();
645 $attributes['rows'] = $rows;
646 $attributes['cols'] = $cols;
649 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
) {
650 $attributes['size'] = 6;
651 $attributes['maxlength'] = 14;
659 * Get the size and maxLength attributes for this text field.
660 * (or for all text fields) in the DAO object.
662 * @param string $class
664 * @param string $fieldName
665 * Field that i'm interested in or null if.
666 * you want the attributes for all DAO text fields
669 * assoc array of name => attribute pairs
671 public static function getAttribute($class, $fieldName = NULL) {
672 $object = new $class();
673 $fields = &$object->fields();
674 if ($fieldName != NULL) {
675 $field = CRM_Utils_Array
::value($fieldName, $fields);
676 return self
::makeAttribute($field);
679 $attributes = array();
680 foreach ($fields as $name => $field) {
681 $attribute = self
::makeAttribute($field);
683 $attributes[$name] = $attribute;
687 if (!empty($attributes)) {
699 public static function transaction($type) {
700 CRM_Core_Error
::fatal('This function is obsolete, please use CRM_Core_Transaction');
704 * Check if there is a record with the same name in the db.
706 * @param string $value
707 * The value of the field we are checking.
708 * @param string $daoName
709 * The dao object name.
710 * @param string $daoID
711 * The id of the object being updated. u can change your name.
712 * as long as there is no conflict
713 * @param string $fieldName
714 * The name of the field in the DAO.
717 * true if object exists
719 public static function objectExists($value, $daoName, $daoID, $fieldName = 'name') {
720 $object = new $daoName();
721 $object->$fieldName = $value;
723 $config = CRM_Core_Config
::singleton();
725 if ($object->find(TRUE)) {
726 return ($daoID && $object->id
== $daoID) ?
TRUE : FALSE;
734 * Check if there is a given column in a specific table.
736 * @param string $tableName
737 * @param string $columnName
738 * @param bool $i18nRewrite
739 * Whether to rewrite the query on multilingual setups.
742 * true if exists, else false
744 public static function checkFieldExists($tableName, $columnName, $i18nRewrite = TRUE) {
750 $params = array(1 => array($columnName, 'String'));
751 $dao = CRM_Core_DAO
::executeQuery($query, $params, TRUE, NULL, FALSE, $i18nRewrite);
752 $result = $dao->fetch() ?
TRUE : FALSE;
758 * Returns the storage engine used by given table-name(optional).
759 * Otherwise scans all the tables and return an array of all the
760 * distinct storage engines being used.
762 * @param string $tableName
764 * @param int $maxTablesToCheck
765 * @param string $fieldName
769 public static function getStorageValues($tableName = NULL, $maxTablesToCheck = 10, $fieldName = 'Engine') {
771 $query = "SHOW TABLE STATUS LIKE %1";
775 if (isset($tableName)) {
776 $params = array(1 => array($tableName, 'String'));
779 $params = array(1 => array('civicrm_%', 'String'));
782 $dao = CRM_Core_DAO
::executeQuery($query, $params);
785 while ($dao->fetch()) {
786 if (isset($values[$dao->$fieldName]) ||
787 // ignore import and other temp tables
788 strpos($dao->Name
, 'civicrm_import_job_') !== FALSE ||
789 strpos($dao->Name
, '_temp') !== FALSE
793 $values[$dao->$fieldName] = 1;
795 if ($maxTablesToCheck &&
796 $count >= $maxTablesToCheck
806 * @param int $maxTablesToCheck
810 public static function isDBMyISAM($maxTablesToCheck = 10) {
811 // show error if any of the tables, use 'MyISAM' storage engine.
812 $engines = self
::getStorageValues(NULL, $maxTablesToCheck);
813 if (array_key_exists('MyISAM', $engines)) {
820 * Checks if a constraint exists for a specified table.
822 * @param string $tableName
823 * @param string $constraint
826 * true if constraint exists, false otherwise
828 public static function checkConstraintExists($tableName, $constraint) {
829 static $show = array();
831 if (!array_key_exists($tableName, $show)) {
832 $query = "SHOW CREATE TABLE $tableName";
833 $dao = CRM_Core_DAO
::executeQuery($query);
835 if (!$dao->fetch()) {
836 CRM_Core_Error
::fatal();
840 $show[$tableName] = $dao->Create_Table
;
843 return preg_match("/\b$constraint\b/i", $show[$tableName]) ?
TRUE : FALSE;
847 * Checks if CONSTRAINT keyword exists for a specified table.
849 * @param array $tables
854 * true if CONSTRAINT keyword exists, false otherwise
856 public static function schemaRequiresRebuilding($tables = array("civicrm_contact")) {
858 foreach ($tables as $tableName) {
859 if (!array_key_exists($tableName, $show)) {
860 $query = "SHOW CREATE TABLE $tableName";
861 $dao = CRM_Core_DAO
::executeQuery($query);
863 if (!$dao->fetch()) {
864 CRM_Core_Error
::fatal();
868 $show[$tableName] = $dao->Create_Table
;
871 $result = preg_match("/\bCONSTRAINT\b\s/i", $show[$tableName]) ?
TRUE : FALSE;
872 if ($result == TRUE) {
883 * Checks if the FK constraint name is in the format 'FK_tableName_columnName'
884 * for a specified column of a table.
886 * @param string $tableName
887 * @param string $columnName
890 * true if in format, false otherwise
892 public static function checkFKConstraintInFormat($tableName, $columnName) {
893 static $show = array();
895 if (!array_key_exists($tableName, $show)) {
896 $query = "SHOW CREATE TABLE $tableName";
897 $dao = CRM_Core_DAO
::executeQuery($query);
899 if (!$dao->fetch()) {
900 CRM_Core_Error
::fatal();
904 $show[$tableName] = $dao->Create_Table
;
906 $constraint = "`FK_{$tableName}_{$columnName}`";
907 $pattern = "/\bCONSTRAINT\b\s+%s\s+\bFOREIGN\s+KEY\b\s/i";
908 return preg_match(sprintf($pattern, $constraint), $show[$tableName]) ?
TRUE : FALSE;
912 * Check whether a specific column in a specific table has always the same value.
914 * @param string $tableName
915 * @param string $columnName
916 * @param string $columnValue
919 * true if the value is always $columnValue, false otherwise
921 public static function checkFieldHasAlwaysValue($tableName, $columnName, $columnValue) {
922 $query = "SELECT * FROM $tableName WHERE $columnName != '$columnValue'";
923 $dao = CRM_Core_DAO
::executeQuery($query);
924 $result = $dao->fetch() ?
FALSE : TRUE;
930 * Check whether a specific column in a specific table is always NULL.
932 * @param string $tableName
933 * @param string $columnName
936 * true if if the value is always NULL, false otherwise
938 public static function checkFieldIsAlwaysNull($tableName, $columnName) {
939 $query = "SELECT * FROM $tableName WHERE $columnName IS NOT NULL";
940 $dao = CRM_Core_DAO
::executeQuery($query);
941 $result = $dao->fetch() ?
FALSE : TRUE;
947 * Check if there is a given table in the database.
949 * @param string $tableName
952 * true if exists, else false
954 public static function checkTableExists($tableName) {
959 $params = array(1 => array($tableName, 'String'));
961 $dao = CRM_Core_DAO
::executeQuery($query, $params);
962 $result = $dao->fetch() ?
TRUE : FALSE;
972 public function checkVersion($version) {
977 $dbVersion = CRM_Core_DAO
::singleValueQuery($query);
978 return trim($version) == trim($dbVersion) ?
TRUE : FALSE;
982 * Find a DAO object for the given ID and return it.
985 * Id of the DAO object being searched for.
988 * Object of the type of the class that called this function.
990 public static function findById($id) {
991 $object = new static();
993 if (!$object->find(TRUE)) {
994 throw new Exception("Unable to find a " . get_called_class() . " with id {$id}.");
1000 * Returns all results as array-encoded records.
1004 public function fetchAll() {
1006 while ($this->fetch()) {
1007 $result[] = $this->toArray();
1013 * Given a DAO name, a column name and a column value, find the record and GET the value of another column in that record
1015 * @param string $daoName
1016 * Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact).
1017 * @param int $searchValue
1018 * Value of the column you want to search by.
1019 * @param string $returnColumn
1020 * Name of the column you want to GET the value of.
1021 * @param string $searchColumn
1022 * Name of the column you want to search by.
1023 * @param bool $force
1024 * Skip use of the cache.
1026 * @return string|null
1027 * Value of $returnColumn in the retrieved record
1029 public static function getFieldValue($daoName, $searchValue, $returnColumn = 'name', $searchColumn = 'id', $force = FALSE) {
1031 empty($searchValue) ||
1032 trim(strtolower($searchValue)) == 'null'
1034 // adding this year since developers forget to check for an id
1035 // or for the 'null' (which is a bad DAO kludge)
1036 // and hence we get the first value in the db
1037 CRM_Core_Error
::fatal();
1040 $cacheKey = "{$daoName}:{$searchValue}:{$returnColumn}:{$searchColumn}";
1041 if (self
::$_dbColumnValueCache === NULL) {
1042 self
::$_dbColumnValueCache = array();
1045 if (!array_key_exists($cacheKey, self
::$_dbColumnValueCache) ||
$force) {
1046 $object = new $daoName();
1047 $object->$searchColumn = $searchValue;
1048 $object->selectAdd();
1049 $object->selectAdd($returnColumn);
1052 if ($object->find(TRUE)) {
1053 $result = $object->$returnColumn;
1057 self
::$_dbColumnValueCache[$cacheKey] = $result;
1059 return self
::$_dbColumnValueCache[$cacheKey];
1063 * Given a DAO name, a column name and a column value, find the record and SET the value of another column in that record
1065 * @param string $daoName
1066 * Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact).
1067 * @param int $searchValue
1068 * Value of the column you want to search by.
1069 * @param string $setColumn
1070 * Name of the column you want to SET the value of.
1071 * @param string $setValue
1072 * SET the setColumn to this value.
1073 * @param string $searchColumn
1074 * Name of the column you want to search by.
1077 * true if we found and updated the object, else false
1079 public static function setFieldValue($daoName, $searchValue, $setColumn, $setValue, $searchColumn = 'id') {
1080 $object = new $daoName();
1081 $object->selectAdd();
1082 $object->selectAdd("$searchColumn, $setColumn");
1083 $object->$searchColumn = $searchValue;
1085 if ($object->find(TRUE)) {
1086 $object->$setColumn = $setValue;
1087 if ($object->save()) {
1098 * @param array|object $sort either array or CRM_Utils_Sort
1099 * @param string $default
1100 * Default sort value.
1105 public static function getSortString($sort, $default = NULL) {
1106 // check if sort is of type CRM_Utils_Sort
1107 if (is_a($sort, 'CRM_Utils_Sort')) {
1108 return $sort->orderBy();
1111 // is it an array specified as $field => $sortDirection ?
1113 foreach ($sort as $k => $v) {
1114 $sortString .= "$k $v,";
1116 return rtrim($sortString, ',');
1122 * Fetch object based on array of properties.
1124 * @param string $daoName
1125 * Name of the dao object.
1126 * @param array $params
1127 * (reference ) an assoc array of name/value pairs.
1128 * @param array $defaults
1129 * (reference ) an assoc array to hold the flattened values.
1130 * @param array $returnProperities
1131 * An assoc array of fields that need to be returned, eg array( 'first_name', 'last_name').
1134 * an object of type referenced by daoName
1136 public static function commonRetrieve($daoName, &$params, &$defaults, $returnProperities = NULL) {
1137 $object = new $daoName();
1138 $object->copyValues($params);
1140 // return only specific fields if returnproperties are sent
1141 if (!empty($returnProperities)) {
1142 $object->selectAdd();
1143 $object->selectAdd(implode(',', $returnProperities));
1146 if ($object->find(TRUE)) {
1147 self
::storeValues($object, $defaults);
1154 * Delete the object records that are associated with this contact.
1156 * @param string $daoName
1157 * Name of the dao object.
1158 * @param int $contactId
1159 * Id of the contact to delete.
1161 public static function deleteEntityContact($daoName, $contactId) {
1162 $object = new $daoName();
1164 $object->entity_table
= 'civicrm_contact';
1165 $object->entity_id
= $contactId;
1172 * @param string $query
1173 * Query to be executed.
1175 * @param array $params
1176 * @param bool $abort
1177 * @param null $daoName
1178 * @param bool $freeDAO
1179 * @param bool $i18nRewrite
1180 * @param bool $trapException
1182 * @return CRM_Core_DAO|object
1183 * object that holds the results of the query
1184 * NB - if this is defined as just returning a DAO phpstorm keeps pointing
1185 * out all the properties that are not part of the DAO
1187 public static function &executeQuery(
1193 $i18nRewrite = TRUE,
1194 $trapException = FALSE
1196 $queryStr = self
::composeQuery($query, $params, $abort);
1199 $dao = new CRM_Core_DAO();
1202 $dao = new $daoName();
1205 if ($trapException) {
1206 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
1209 $result = $dao->query($queryStr, $i18nRewrite);
1211 if (is_a($result, 'DB_Error')) {
1216 preg_match('/^(insert|update|delete|create|drop|replace)/i', $queryStr)
1218 // we typically do this for insert/update/delete statements OR if explicitly asked to
1226 * Execute a query and get the single result.
1228 * @param string $query
1229 * Query to be executed.
1230 * @param array $params
1231 * @param bool $abort
1232 * @param bool $i18nRewrite
1233 * @return string|null
1234 * the result of the query if any
1237 public static function &singleValueQuery(
1243 $queryStr = self
::composeQuery($query, $params, $abort);
1245 static $_dao = NULL;
1248 $_dao = new CRM_Core_DAO();
1251 $_dao->query($queryStr, $i18nRewrite);
1253 $result = $_dao->getDatabaseResult();
1256 $row = $result->fetchRow();
1267 * @param array $params
1268 * @param bool $abort
1273 public static function composeQuery($query, &$params, $abort = TRUE) {
1275 foreach ($params as $key => $item) {
1276 if (is_numeric($key)) {
1277 if (CRM_Utils_Type
::validate($item[0], $item[1]) !== NULL) {
1278 $item[0] = self
::escapeString($item[0]);
1279 if ($item[1] == 'String' ||
1280 $item[1] == 'Memo' ||
1283 // Support class constants stipulating wildcard characters and/or
1284 // non-quoting of strings. Also support legacy code which may be
1285 // passing in TRUE or 1 for $item[2], which used to indicate the
1286 // use of wildcard characters.
1287 if (!empty($item[2])) {
1288 if ($item[2] & CRM_Core_DAO
::QUERY_FORMAT_WILDCARD ||
$item[2] === TRUE) {
1289 $item[0] = "'%{$item[0]}%'";
1291 elseif (!($item[2] & CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
)) {
1292 $item[0] = "'{$item[0]}'";
1296 $item[0] = "'{$item[0]}'";
1300 if (($item[1] == 'Date' ||
$item[1] == 'Timestamp') &&
1301 strlen($item[0]) == 0
1306 $tr['%' . $key] = $item[0];
1309 CRM_Core_Error
::fatal("{$item[0]} is not of type {$item[1]}");
1314 return strtr($query, $tr);
1320 public static function freeResult($ids = NULL) {
1321 global $_DB_DATAOBJECT;
1324 if (!$_DB_DATAOBJECT ||
1325 !isset($_DB_DATAOBJECT['RESULTS'])
1329 $ids = array_keys($_DB_DATAOBJECT['RESULTS']);
1332 foreach ($ids as $id) {
1333 if (isset($_DB_DATAOBJECT['RESULTS'][$id])) {
1334 if (is_resource($_DB_DATAOBJECT['RESULTS'][$id]->result
)) {
1335 mysql_free_result($_DB_DATAOBJECT['RESULTS'][$id]->result
);
1337 unset($_DB_DATAOBJECT['RESULTS'][$id]);
1340 if (isset($_DB_DATAOBJECT['RESULTFIELDS'][$id])) {
1341 unset($_DB_DATAOBJECT['RESULTFIELDS'][$id]);
1347 * make a shallow copy of an object.
1348 * and all the fields in the object
1350 * @param string $daoName
1352 * @param array $criteria
1353 * Array of all the fields & values.
1354 * on which basis to copy
1355 * @param array $newData
1356 * Array of all the fields & values.
1357 * to be copied besides the other fields
1358 * @param string $fieldsFix
1359 * Array of fields that you want to prefix/suffix/replace.
1360 * @param string $blockCopyOfDependencies
1361 * Fields that you want to block from.
1365 * @return CRM_Core_DAO
1366 * the newly created copy of the object
1368 public static function ©Generic($daoName, $criteria, $newData = NULL, $fieldsFix = NULL, $blockCopyOfDependencies = NULL) {
1369 $object = new $daoName();
1371 $object->id
= $criteria['id'];
1374 foreach ($criteria as $key => $value) {
1375 $object->$key = $value;
1380 while ($object->fetch()) {
1382 // all the objects except with $blockCopyOfDependencies set
1383 // be copied - addresses #CRM-1962
1385 if ($blockCopyOfDependencies && $object->$blockCopyOfDependencies) {
1389 $newObject = new $daoName();
1391 $fields = &$object->fields();
1392 if (!is_array($fieldsFix)) {
1393 $fieldsToPrefix = array();
1394 $fieldsToSuffix = array();
1395 $fieldsToReplace = array();
1397 if (!empty($fieldsFix['prefix'])) {
1398 $fieldsToPrefix = $fieldsFix['prefix'];
1400 if (!empty($fieldsFix['suffix'])) {
1401 $fieldsToSuffix = $fieldsFix['suffix'];
1403 if (!empty($fieldsFix['replace'])) {
1404 $fieldsToReplace = $fieldsFix['replace'];
1407 foreach ($fields as $name => $value) {
1408 if ($name == 'id' ||
$value['name'] == 'id') {
1409 // copy everything but the id!
1413 $dbName = $value['name'];
1414 $type = CRM_Utils_Type
::typeToString($value['type']);
1415 $newObject->$dbName = $object->$dbName;
1416 if (isset($fieldsToPrefix[$dbName])) {
1417 $newObject->$dbName = $fieldsToPrefix[$dbName] . $newObject->$dbName;
1419 if (isset($fieldsToSuffix[$dbName])) {
1420 $newObject->$dbName .= $fieldsToSuffix[$dbName];
1422 if (isset($fieldsToReplace[$dbName])) {
1423 $newObject->$dbName = $fieldsToReplace[$dbName];
1426 if ($type == 'Timestamp' ||
$type == 'Date') {
1427 $newObject->$dbName = CRM_Utils_Date
::isoToMysql($newObject->$dbName);
1431 foreach ($newData as $k => $v) {
1432 $newObject->$k = $v;
1442 * Cascade update through related entities.
1444 * @param string $daoName
1447 * @param array $newData
1451 public static function cascadeUpdate($daoName, $fromId, $toId, $newData = array()) {
1452 $object = new $daoName();
1453 $object->id
= $fromId;
1455 if ($object->find(TRUE)) {
1456 $newObject = new $daoName();
1457 $newObject->id
= $toId;
1459 if ($newObject->find(TRUE)) {
1460 $fields = &$object->fields();
1461 foreach ($fields as $name => $value) {
1462 if ($name == 'id' ||
$value['name'] == 'id') {
1463 // copy everything but the id!
1467 $colName = $value['name'];
1468 $newObject->$colName = $object->$colName;
1470 if (substr($name, -5) == '_date' ||
1471 substr($name, -10) == '_date_time'
1473 $newObject->$colName = CRM_Utils_Date
::isoToMysql($newObject->$colName);
1476 foreach ($newData as $k => $v) {
1477 $newObject->$k = $v;
1483 return CRM_Core_DAO
::$_nullObject;
1487 * Given the component id, compute the contact id
1488 * since its used for things like send email
1490 * @param $componentIDs
1491 * @param string $tableName
1495 public static function &getContactIDsFromComponent(&$componentIDs, $tableName) {
1496 $contactIDs = array();
1498 if (empty($componentIDs)) {
1502 $IDs = implode(',', $componentIDs);
1506 WHERE id IN ( $IDs )
1509 $dao = CRM_Core_DAO
::executeQuery($query);
1510 while ($dao->fetch()) {
1511 $contactIDs[] = $dao->contact_id
;
1517 * Fetch object based on array of properties.
1519 * @param string $daoName
1520 * Name of the dao object.
1521 * @param string $fieldIdName
1522 * @param int $fieldId
1524 * @param array $returnProperities
1525 * An assoc array of fields that need to be returned, eg array( 'first_name', 'last_name').
1528 * an object of type referenced by daoName
1530 public static function commonRetrieveAll($daoName, $fieldIdName = 'id', $fieldId, &$details, $returnProperities = NULL) {
1531 require_once str_replace('_', DIRECTORY_SEPARATOR
, $daoName) . ".php";
1532 $object = new $daoName();
1533 $object->$fieldIdName = $fieldId;
1535 // return only specific fields if returnproperties are sent
1536 if (!empty($returnProperities)) {
1537 $object->selectAdd();
1538 $object->selectAdd('id');
1539 $object->selectAdd(implode(',', $returnProperities));
1543 while ($object->fetch()) {
1544 $defaults = array();
1545 self
::storeValues($object, $defaults);
1546 $details[$object->id
] = $defaults;
1552 public static function dropAllTables() {
1554 // first drop all the custom tables we've created
1555 CRM_Core_BAO_CustomGroup
::dropAllTables();
1557 // drop all multilingual views
1558 CRM_Core_I18n_Schema
::dropAllViews();
1560 CRM_Utils_File
::sourceSQLFile(CIVICRM_DSN
,
1561 dirname(__FILE__
) . DIRECTORY_SEPARATOR
.
1562 '..' . DIRECTORY_SEPARATOR
.
1563 '..' . DIRECTORY_SEPARATOR
.
1564 'sql' . DIRECTORY_SEPARATOR
.
1565 'civicrm_drop.mysql'
1574 public static function escapeString($string) {
1575 static $_dao = NULL;
1578 // If this is an atypical case (e.g. preparing .sql files
1579 // before Civi has been installed), then we fallback to
1580 // DB-less escaping helper (mysql_real_escape_string).
1581 // Note: In typical usage, escapeString() will only
1582 // check one conditional ("if !$_dao") rather than
1583 // two conditionals ("if !defined(DSN)")
1584 if (!defined('CIVICRM_DSN')) {
1585 if (function_exists('mysql_real_escape_string')) {
1586 return mysql_real_escape_string($string);
1589 throw new CRM_Core_Exception("Cannot generate SQL. \"mysql_real_escape_string\" is missing. Have you installed PHP \"mysql\" extension?");
1593 $_dao = new CRM_Core_DAO();
1596 return $_dao->escape($string);
1600 * Escape a list of strings for use with "WHERE X IN (...)" queries.
1602 * @param array $strings
1603 * @param string $default
1604 * the value to use if $strings has no elements.
1606 * eg "abc","def","ghi"
1608 public static function escapeStrings($strings, $default = NULL) {
1609 static $_dao = NULL;
1611 $_dao = new CRM_Core_DAO();
1614 if (empty($strings)) {
1618 $escapes = array_map(array($_dao, 'escape'), $strings);
1619 return '"' . implode('","', $escapes) . '"';
1627 public static function escapeWildCardString($string) {
1629 // ensure we escape the single characters % and _ which are mysql wild
1630 // card characters and could come in via sortByCharacter
1631 // note that mysql does not escape these characters
1632 if ($string && in_array($string,
1633 array('%', '_', '%%', '_%')
1636 return '\\' . $string;
1639 return self
::escapeString($string);
1643 * Creates a test object, including any required objects it needs via recursion
1644 * createOnly: only create in database, do not store or return the objects (useful for perf testing)
1645 * ONLY USE FOR TESTING
1647 * @param string $daoName
1648 * @param array $params
1649 * @param int $numObjects
1650 * @param bool $createOnly
1652 * @return object|array|NULL
1653 * NULL if $createOnly. A single object if $numObjects==1. Otherwise, an array of multiple objects.
1655 public static function createTestObject(
1661 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
1662 // so we re-set here in case
1663 $config = CRM_Core_Config
::singleton();
1664 $config->backtrace
= TRUE;
1666 static $counter = 0;
1667 CRM_Core_DAO
::$_testEntitiesToSkip = array(
1668 'CRM_Core_DAO_Worldregion',
1669 'CRM_Core_DAO_StateProvince',
1670 'CRM_Core_DAO_Country',
1671 'CRM_Core_DAO_Domain',
1672 'CRM_Financial_DAO_FinancialType',
1673 //because valid ones exist & we use pick them due to pseudoconstant can't reliably create & delete these
1676 // Prefer to instantiate BAO's instead of DAO's (when possible)
1677 // so that assignTestValue()/assignTestFK() can be overloaded.
1678 $baoName = str_replace('_DAO_', '_BAO_', $daoName);
1679 if (class_exists($baoName)) {
1680 $daoName = $baoName;
1683 for ($i = 0; $i < $numObjects; ++
$i) {
1686 /** @var CRM_Core_DAO $object */
1687 $object = new $daoName();
1689 $fields = &$object->fields();
1690 foreach ($fields as $fieldName => $fieldDef) {
1691 $dbName = $fieldDef['name'];
1692 $FKClassName = CRM_Utils_Array
::value('FKClassName', $fieldDef);
1693 $required = CRM_Utils_Array
::value('required', $fieldDef);
1695 if (CRM_Utils_Array
::value($dbName, $params) !== NULL && !is_array($params[$dbName])) {
1696 $object->$dbName = $params[$dbName];
1699 elseif ($dbName != 'id') {
1700 if ($FKClassName != NULL) {
1701 $object->assignTestFK($fieldName, $fieldDef, $params);
1705 $object->assignTestValue($fieldName, $fieldDef, $counter);
1713 $objects[$i] = $object;
1723 elseif ($numObjects == 1) {
1732 * Deletes the this object plus any dependent objects that are associated with it.
1733 * ONLY USE FOR TESTING
1735 * @param string $daoName
1736 * @param array $params
1738 public static function deleteTestObjects($daoName, $params = array()) {
1739 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
1740 // so we re-set here in case
1741 $config = CRM_Core_Config
::singleton();
1742 $config->backtrace
= TRUE;
1744 $object = new $daoName();
1745 $object->id
= CRM_Utils_Array
::value('id', $params);
1747 $deletions = array(); // array(array(0 => $daoName, 1 => $daoParams))
1748 if ($object->find(TRUE)) {
1750 $fields = &$object->fields();
1751 foreach ($fields as $name => $value) {
1753 $dbName = $value['name'];
1755 $FKClassName = CRM_Utils_Array
::value('FKClassName', $value);
1756 $required = CRM_Utils_Array
::value('required', $value);
1757 if ($FKClassName != NULL
1759 && !in_array($FKClassName, CRM_Core_DAO
::$_testEntitiesToSkip)
1760 && ($required ||
$dbName == 'contact_id')
1761 //I'm a bit stuck on this one - we might need to change the singleValueAlter so that the entities don't share a contact
1762 // to make this test process pass - line below makes pass for now
1763 && $dbName != 'member_of_contact_id'
1765 $deletions[] = array($FKClassName, array('id' => $object->$dbName)); // x
1772 foreach ($deletions as $deletion) {
1773 CRM_Core_DAO
::deleteTestObjects($deletion[0], $deletion[1]);
1778 * Set defaults when creating new entity.
1779 * (don't call this set defaults as already in use with different signature in some places)
1781 * @param array $params
1784 public static function setCreateDefaults(&$params, $defaults) {
1785 if (!empty($params['id'])) {
1788 foreach ($defaults as $key => $value) {
1789 if (!array_key_exists($key, $params) ||
$params[$key] === NULL) {
1790 $params[$key] = $value;
1796 * @param string $prefix
1797 * @param bool $addRandomString
1798 * @param null $string
1802 public static function createTempTableName($prefix = 'civicrm', $addRandomString = TRUE, $string = NULL) {
1803 $tableName = $prefix . "_temp";
1805 if ($addRandomString) {
1807 $tableName .= "_" . $string;
1810 $tableName .= "_" . md5(uniqid('', TRUE));
1818 * @param bool $trigger
1822 public static function checkTriggerViewPermission($view = TRUE, $trigger = TRUE) {
1823 // test for create view and trigger permissions and if allowed, add the option to go multilingual
1825 // I'm not sure why we use the getStaticProperty for an error, rather than checking for DB_Error
1826 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
1827 $dao = new CRM_Core_DAO();
1829 $dao->query('CREATE OR REPLACE VIEW civicrm_domain_view AS SELECT * FROM civicrm_domain');
1830 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
1836 $result = $dao->query('CREATE TRIGGER civicrm_domain_trigger BEFORE INSERT ON civicrm_domain FOR EACH ROW BEGIN END');
1837 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError') ||
is_a($result, 'DB_Error')) {
1839 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1844 $dao->query('DROP TRIGGER IF EXISTS civicrm_domain_trigger');
1845 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
1847 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1854 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1855 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
1864 * @param null $message
1865 * @param bool $printDAO
1867 public static function debugPrint($message = NULL, $printDAO = TRUE) {
1868 CRM_Utils_System
::xMemory("{$message}: ");
1871 global $_DB_DATAOBJECT;
1873 foreach (array_keys($_DB_DATAOBJECT['RESULTS']) as $id) {
1874 $q[] = $_DB_DATAOBJECT['RESULTS'][$id]->query
;
1876 CRM_Core_Error
::debug('_DB_DATAOBJECT', $q);
1881 * Build a list of triggers via hook and add them to (err, reconcile them
1882 * with) the database.
1884 * @param string $tableName
1885 * the specific table requiring a rebuild; or NULL to rebuild all tables.
1886 * @param bool $force
1890 public static function triggerRebuild($tableName = NULL, $force = FALSE) {
1893 $logging = new CRM_Logging_Schema();
1894 $logging->triggerInfo($info, $tableName, $force);
1896 CRM_Core_I18n_Schema
::triggerInfo($info, $tableName);
1897 CRM_Contact_BAO_Contact
::triggerInfo($info, $tableName);
1899 CRM_Utils_Hook
::triggerInfo($info, $tableName);
1901 // drop all existing triggers on all tables
1902 $logging->dropTriggers($tableName);
1904 // now create the set of new triggers
1905 self
::createTriggers($info, $tableName);
1909 * Because sql functions are sometimes lost, esp during db migration, we check here to avoid numerous support requests
1910 * @see http://issues.civicrm.org/jira/browse/CRM-13822
1911 * TODO: Alternative solutions might be
1912 * * Stop using functions and find another way to strip numeric characters from phones
1913 * * Give better error messages (currently a missing fn fatals with "unknown error")
1915 public static function checkSqlFunctionsExist() {
1916 if (!self
::$_checkedSqlFunctionsExist) {
1917 self
::$_checkedSqlFunctionsExist = TRUE;
1918 $dao = CRM_Core_DAO
::executeQuery("SHOW function status WHERE db = database() AND name = 'civicrm_strip_non_numeric'");
1919 if (!$dao->fetch()) {
1920 self
::triggerRebuild();
1926 * Wrapper function to drop triggers.
1928 * @param string $tableName
1929 * the specific table requiring a rebuild; or NULL to rebuild all tables.
1931 public static function dropTriggers($tableName = NULL) {
1934 $logging = new CRM_Logging_Schema();
1935 $logging->triggerInfo($info, $tableName);
1937 // drop all existing triggers on all tables
1938 $logging->dropTriggers($tableName);
1942 * @param array $info
1943 * per hook_civicrm_triggerInfo.
1944 * @param string $onlyTableName
1945 * the specific table requiring a rebuild; or NULL to rebuild all tables.
1947 public static function createTriggers(&$info, $onlyTableName = NULL) {
1948 // Validate info array, should probably raise errors?
1949 if (is_array($info) == FALSE) {
1953 $triggers = array();
1955 // now enumerate the tables and the events and collect the same set in a different format
1956 foreach ($info as $value) {
1958 // clean the incoming data, skip malformed entries
1959 // TODO: malformed entries should raise errors or get logged.
1960 if (isset($value['table']) == FALSE ||
1961 isset($value['event']) == FALSE ||
1962 isset($value['when']) == FALSE ||
1963 isset($value['sql']) == FALSE
1968 if (is_string($value['table']) == TRUE) {
1969 $tables = array($value['table']);
1972 $tables = $value['table'];
1975 if (is_string($value['event']) == TRUE) {
1976 $events = array(strtolower($value['event']));
1979 $events = array_map('strtolower', $value['event']);
1982 $whenName = strtolower($value['when']);
1984 foreach ($tables as $tableName) {
1985 if (!isset($triggers[$tableName])) {
1986 $triggers[$tableName] = array();
1989 foreach ($events as $eventName) {
1990 $template_params = array('{tableName}', '{eventName}');
1991 $template_values = array($tableName, $eventName);
1993 $sql = str_replace($template_params,
1997 $variables = str_replace($template_params,
1999 CRM_Utils_Array
::value('variables', $value)
2002 if (!isset($triggers[$tableName][$eventName])) {
2003 $triggers[$tableName][$eventName] = array();
2006 if (!isset($triggers[$tableName][$eventName][$whenName])) {
2007 // We're leaving out cursors, conditions, and handlers for now
2008 // they are kind of dangerous in this context anyway
2009 // better off putting them in stored procedures
2010 $triggers[$tableName][$eventName][$whenName] = array(
2011 'variables' => array(),
2017 $triggers[$tableName][$eventName][$whenName]['variables'][] = $variables;
2020 $triggers[$tableName][$eventName][$whenName]['sql'][] = $sql;
2025 // now spit out the sql
2026 foreach ($triggers as $tableName => $tables) {
2027 if ($onlyTableName != NULL && $onlyTableName != $tableName) {
2030 foreach ($tables as $eventName => $events) {
2031 foreach ($events as $whenName => $parts) {
2032 $varString = implode("\n", $parts['variables']);
2033 $sqlString = implode("\n", $parts['sql']);
2034 $validName = CRM_Core_DAO
::shortenSQLName($tableName, 48, TRUE);
2035 $triggerName = "{$validName}_{$whenName}_{$eventName}";
2036 $triggerSQL = "CREATE TRIGGER $triggerName $whenName $eventName ON $tableName FOR EACH ROW BEGIN $varString $sqlString END";
2038 CRM_Core_DAO
::executeQuery("DROP TRIGGER IF EXISTS $triggerName");
2039 CRM_Core_DAO
::executeQuery(
2053 * Given a list of fields, create a list of references.
2055 * @param string $className
2056 * BAO/DAO class name.
2057 * @return array<CRM_Core_Reference_Interface>
2059 public static function createReferenceColumns($className) {
2061 $fields = $className::fields();
2062 foreach ($fields as $field) {
2063 if (isset($field['pseudoconstant'], $field['pseudoconstant']['optionGroupName'])) {
2064 $result[] = new CRM_Core_Reference_OptionValue(
2065 $className::getTableName(),
2067 'civicrm_option_value',
2068 CRM_Utils_Array
::value('keyColumn', $field['pseudoconstant'], 'value'),
2069 $field['pseudoconstant']['optionGroupName']
2077 * Find all records which refer to this entity.
2080 * Array of objects referencing this
2082 public function findReferences() {
2083 $links = self
::getReferencesToTable(static::getTableName());
2085 $occurrences = array();
2086 foreach ($links as $refSpec) {
2087 /** @var $refSpec CRM_Core_Reference_Interface */
2088 $daoName = CRM_Core_DAO_AllCoreTables
::getClassForTable($refSpec->getReferenceTable());
2089 $result = $refSpec->findReferences($this);
2091 while ($result->fetch()) {
2092 $obj = new $daoName();
2093 $obj->id
= $result->id
;
2094 $occurrences[] = $obj;
2099 return $occurrences;
2104 * each item has keys:
2108 * - table: string|null SQL table name
2109 * - key: string|null SQL column name
2111 public function getReferenceCounts() {
2112 $links = self
::getReferencesToTable(static::getTableName());
2115 foreach ($links as $refSpec) {
2116 /** @var $refSpec CRM_Core_Reference_Interface */
2117 $count = $refSpec->getReferenceCount($this);
2118 if ($count['count'] != 0) {
2123 foreach (CRM_Core_Component
::getEnabledComponents() as $component) {
2124 /** @var $component CRM_Core_Component_Info */
2125 $counts = array_merge($counts, $component->getReferenceCounts($this));
2127 CRM_Utils_Hook
::referenceCounts($this, $counts);
2133 * List all tables which have hard foreign keys to this table.
2135 * For now, this returns a description of every entity_id/entity_table
2137 * TODO: filter dynamic entity references on the $tableName, based on
2138 * schema metadata in dynamicForeignKey which enumerates a restricted
2139 * set of possible entity_table's.
2141 * @param string $tableName
2142 * Table referred to.
2145 * structure of table and column, listing every table with a
2146 * foreign key reference to $tableName, and the column where the key appears.
2148 public static function getReferencesToTable($tableName) {
2149 $refsFound = array();
2150 foreach (CRM_Core_DAO_AllCoreTables
::getClasses() as $daoClassName) {
2151 $links = $daoClassName::getReferenceColumns();
2152 $daoTableName = $daoClassName::getTableName();
2154 foreach ($links as $refSpec) {
2155 /** @var $refSpec CRM_Core_Reference_Interface */
2156 if ($refSpec->matchesTargetTable($tableName)) {
2157 $refsFound[] = $refSpec;
2165 * Lookup the value of a MySQL global configuration variable.
2167 * @param string $name
2168 * E.g. "thread_stack".
2169 * @param mixed $default
2172 public static function getGlobalSetting($name, $default = NULL) {
2173 // Alternatively, SELECT @@GLOBAL.thread_stack, but
2174 // that has been reported to fail under MySQL 5.0 for OS X
2175 $escapedName = self
::escapeString($name);
2176 $dao = CRM_Core_DAO
::executeQuery("SHOW VARIABLES LIKE '$escapedName'");
2177 if ($dao->fetch()) {
2186 * Get options for the called BAO object's field.
2187 * This function can be overridden by each BAO to add more logic related to context.
2188 * The overriding function will generally call the lower-level CRM_Core_PseudoConstant::get
2190 * @param string $fieldName
2191 * @param string $context
2192 * @see CRM_Core_DAO::buildOptionsContext
2193 * @param array $props
2194 * whatever is known about this bao object.
2196 * @return array|bool
2198 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
2199 // If a given bao does not override this function
2200 $baoName = get_called_class();
2201 return CRM_Core_PseudoConstant
::get($baoName, $fieldName, array(), $context);
2205 * Populate option labels for this object's fields.
2207 * @throws exception if called directly on the base class
2209 public function getOptionLabels() {
2210 $fields = $this->fields();
2211 if ($fields === NULL) {
2212 throw new Exception('Cannot call getOptionLabels on CRM_Core_DAO');
2214 foreach ($fields as $field) {
2215 $name = CRM_Utils_Array
::value('name', $field);
2216 if ($name && isset($this->$name)) {
2217 $label = CRM_Core_PseudoConstant
::getLabel(get_class($this), $name, $this->$name);
2218 if ($label !== FALSE) {
2219 // Append 'label' onto the field name
2220 $labelName = $name . '_label';
2221 $this->$labelName = $label;
2228 * Provides documentation and validation for the buildOptions $context param
2230 * @param string $context
2235 public static function buildOptionsContext($context = NULL) {
2237 'get' => "get: all options are returned, even if they are disabled; labels are translated.",
2238 'create' => "create: options are filtered appropriately for the object being created/updated; labels are translated.",
2239 'search' => "search: searchable options are returned; labels are translated.",
2240 'validate' => "validate: all options are returned, even if they are disabled; machine names are used in place of labels.",
2241 'abbreviate' => "abbreviate: enabled options are returned; labels are replaced with abbreviations.",
2242 'match' => "match: enabled options are returned using machine names as keys; labels are translated.",
2244 // Validation: enforce uniformity of this param
2245 if ($context !== NULL && !isset($contexts[$context])) {
2246 throw new Exception("'$context' is not a valid context for buildOptions.");
2252 * @param string $fieldName
2253 * @return bool|array
2255 public function getFieldSpec($fieldName) {
2256 $fields = $this->fields();
2257 $fieldKeys = $this->fieldKeys();
2259 // Support "unique names" as well as sql names
2260 $fieldKey = $fieldName;
2261 if (empty($fields[$fieldKey])) {
2262 $fieldKey = CRM_Utils_Array
::value($fieldName, $fieldKeys);
2264 // If neither worked then this field doesn't exist. Return false.
2265 if (empty($fields[$fieldKey])) {
2268 return $fields[$fieldKey];
2272 * Get SQL where clause for SQL filter syntax input parameters.
2274 * SQL version of api function to assign filters to the DAO based on the syntax
2275 * $field => array('IN' => array(4,6,9))
2277 * $field => array('LIKE' => array('%me%))
2280 * @param string $fieldName
2282 * @param array $filter
2283 * filter to be applied indexed by operator.
2284 * @param string $type
2285 * type of field (not actually used - nor in api @todo ).
2286 * @param string $alias
2287 * alternative field name ('as') @todo- not actually used.
2288 * @param bool $returnSanitisedArray
2289 * Return a sanitised array instead of a clause.
2290 * this is primarily so we can add filters @ the api level to the Query object based fields
2294 * @return NULL|string|array
2295 * a string is returned if $returnSanitisedArray is not set, otherwise and Array or NULL
2296 * depending on whether it is supported as yet
2298 public static function createSQLFilter($fieldName, $filter, $type = NULL, $alias = NULL, $returnSanitisedArray = FALSE) {
2299 foreach ($filter as $operator => $criteria) {
2300 if (in_array($operator, self
::acceptedSQLOperators(), TRUE)) {
2301 switch ($operator) {
2305 if (!$returnSanitisedArray) {
2306 return (sprintf('%s %s', $fieldName, $operator));
2309 return (sprintf('%s %s ', $fieldName, $operator));
2313 // ternary operators
2316 if (empty($criteria[0]) ||
empty($criteria[1])) {
2317 throw new Exception("invalid criteria for $operator");
2319 if (!$returnSanitisedArray) {
2320 return (sprintf('%s ' . $operator . ' "%s" AND "%s"', $fieldName, CRM_Core_DAO
::escapeString($criteria[0]), CRM_Core_DAO
::escapeString($criteria[1])));
2323 return NULL; // not yet implemented (tests required to implement)
2330 if (empty($criteria)) {
2331 throw new Exception("invalid criteria for $operator");
2333 $escapedCriteria = array_map(array(
2337 if (!$returnSanitisedArray) {
2338 return (sprintf('%s %s ("%s")', $fieldName, $operator, implode('", "', $escapedCriteria)));
2340 return $escapedCriteria;
2345 if (!$returnSanitisedArray) {
2346 return (sprintf('%s %s "%s"', $fieldName, $operator, CRM_Core_DAO
::escapeString($criteria)));
2349 return NULL; // not yet implemented (tests required to implement)
2357 * @see http://issues.civicrm.org/jira/browse/CRM-9150
2358 * support for other syntaxes is discussed in ticket but being put off for now
2361 public static function acceptedSQLOperators() {
2382 * SQL has a limit of 64 characters on various names:
2383 * table name, trigger name, column name ...
2385 * For custom groups and fields we generated names from user entered input
2386 * which can be longer than this length, this function helps with creating
2387 * strings that meet various criteria.
2389 * @param string $string
2390 * The string to be shortened.
2391 * @param int $length
2392 * The max length of the string.
2394 * @param bool $makeRandom
2398 public static function shortenSQLName($string, $length = 60, $makeRandom = FALSE) {
2399 // early return for strings that meet the requirements
2400 if (strlen($string) <= $length) {
2404 // easy return for calls that dont need a randomized uniq string
2406 return substr($string, 0, $length);
2409 // the string is longer than the length and we need a uniq string
2410 // for the same tablename we need the same uniq string every time
2411 // hence we use md5 on the string, which is not random
2412 // we'll append 8 characters to the end of the tableName
2413 $md5string = substr(md5($string), 0, 8);
2414 return substr($string, 0, $length - 8) . "_{$md5string}";
2418 * https://issues.civicrm.org/jira/browse/CRM-17748
2419 * Sets the internal options to be used on a query
2421 * @param array $options
2424 public function setOptions($options) {
2425 if (is_array($options)) {
2426 $this->_options
= $options;
2431 * https://issues.civicrm.org/jira/browse/CRM-17748
2432 * wrapper to pass internal DAO options down to DB_mysql/DB_Common level
2434 * @param array $options
2437 protected function _setDBOptions($options) {
2438 global $_DB_DATAOBJECT;
2440 if (is_array($options) && count($options)) {
2441 $conn = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5
];
2442 foreach ($options as $option_name => $option_value) {
2443 $conn->setOption($option_name, $option_value);
2450 * @param array $params
2452 public function setApiFilter(&$params) {
2456 * Generates acl clauses suitable for adding to WHERE or ON when doing an api.get for this entity
2458 * Return format is in the form of fieldname => clauses starting with an operator. e.g.:
2461 * 'location_type_id' => array('IS NOT NULL', 'IN (1,2,3)')
2465 * Note that all array keys must be actual field names in this entity. Use subqueries to filter on other tables e.g. custom values.
2469 public function addSelectWhereClause() {
2470 // This is the default fallback, and works for contact-related entities like Email, Relationship, etc.
2472 foreach ($this->fields() as $fieldName => $field) {
2473 if (strpos($fieldName, 'contact_id') === 0 && CRM_Utils_Array
::value('FKClassName', $field) == 'CRM_Contact_DAO_Contact') {
2474 $clauses[$fieldName] = CRM_Utils_SQL
::mergeSubquery('Contact');
2477 CRM_Utils_Hook
::selectWhereClause($this, $clauses);
2482 * This returns the final permissioned query string for this entity
2484 * With acls from related entities + additional clauses from hook_civicrm_selectWhereClause
2486 * @param string $tableAlias
2489 public static function getSelectWhereClause($tableAlias = NULL) {
2490 $bao = new static();
2491 if ($tableAlias === NULL) {
2492 $tableAlias = $bao->tableName();
2495 foreach ((array) $bao->addSelectWhereClause() as $field => $vals) {
2496 $clauses[$field] = NULL;
2498 $clauses[$field] = "`$tableAlias`.`$field` " . implode(" AND `$tableAlias`.`$field` ", (array) $vals);