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');
115 CRM_Core_DAO
::executeQuery('SET @uniqueID = %1', array(1 => array(CRM_Utils_Request
::id(), 'String')));
119 * @param string $fieldName
121 * @param array $params
123 protected function assignTestFK($fieldName, $fieldDef, $params) {
124 $required = CRM_Utils_Array
::value('required', $fieldDef);
125 $FKClassName = CRM_Utils_Array
::value('FKClassName', $fieldDef);
126 $dbName = $fieldDef['name'];
127 $daoName = str_replace('_BAO_', '_DAO_', get_class($this));
129 // skip the FK if it is not required
130 // if it's contact id we should create even if not required
131 // we'll have a go @ fetching first though
132 // we WILL create campaigns though for so tests with a campaign pseudoconstant will complete
133 if ($FKClassName === 'CRM_Campaign_DAO_Campaign' && $daoName != $FKClassName) {
136 if (!$required && $dbName != 'contact_id') {
137 $fkDAO = new $FKClassName();
138 if ($fkDAO->find(TRUE)) {
139 $this->$dbName = $fkDAO->id
;
144 elseif (in_array($FKClassName, CRM_Core_DAO
::$_testEntitiesToSkip)) {
145 $depObject = new $FKClassName();
146 $depObject->find(TRUE);
147 $this->$dbName = $depObject->id
;
150 elseif ($daoName == 'CRM_Member_DAO_MembershipType' && $fieldName == 'member_of_contact_id') {
151 // FIXME: the fields() metadata is not specific enough
152 $depObject = CRM_Core_DAO
::createTestObject($FKClassName, array('contact_type' => 'Organization'));
153 $this->$dbName = $depObject->id
;
157 //if it is required we need to generate the dependency object first
158 $depObject = CRM_Core_DAO
::createTestObject($FKClassName, CRM_Utils_Array
::value($dbName, $params, 1));
159 $this->$dbName = $depObject->id
;
165 * Generate and assign an arbitrary value to a field of a test object.
167 * @param string $fieldName
168 * @param array $fieldDef
169 * @param int $counter
170 * The globally-unique ID of the test object.
172 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
173 $dbName = $fieldDef['name'];
174 $daoName = get_class($this);
177 if (!$handled && $dbName == 'contact_sub_type') {
178 //coming up with a rule to set this is too complex let's not set it
182 // Pick an option value if needed
183 if (!$handled && $fieldDef['type'] !== CRM_Utils_Type
::T_BOOLEAN
) {
184 $options = $daoName::buildOptions($dbName, 'create');
186 $this->$dbName = key($options);
192 switch ($fieldDef['type']) {
193 case CRM_Utils_Type
::T_INT
:
194 case CRM_Utils_Type
::T_FLOAT
:
195 case CRM_Utils_Type
::T_MONEY
:
196 if (isset($fieldDef['precision'])) {
197 // $object->$dbName = CRM_Utils_Number::createRandomDecimal($value['precision']);
198 $this->$dbName = CRM_Utils_Number
::createTruncatedDecimal($counter, $fieldDef['precision']);
201 $this->$dbName = $counter;
205 case CRM_Utils_Type
::T_BOOLEAN
:
206 if (isset($fieldDef['default'])) {
207 $this->$dbName = $fieldDef['default'];
209 elseif ($fieldDef['name'] == 'is_deleted' ||
$fieldDef['name'] == 'is_test') {
217 case CRM_Utils_Type
::T_DATE
:
218 case CRM_Utils_Type
::T_TIMESTAMP
:
219 case CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
:
220 $this->$dbName = '19700101';
221 if ($dbName == 'end_date') {
222 // put this in the future
223 $this->$dbName = '20200101';
227 case CRM_Utils_Type
::T_TIME
:
228 CRM_Core_Error
::fatal("T_TIME shouldn't be used.");
229 //$object->$dbName='000000';
231 case CRM_Utils_Type
::T_CCNUM
:
232 $this->$dbName = '4111 1111 1111 1111';
235 case CRM_Utils_Type
::T_URL
:
236 $this->$dbName = 'http://www.civicrm.org';
239 case CRM_Utils_Type
::T_STRING
:
240 case CRM_Utils_Type
::T_BLOB
:
241 case CRM_Utils_Type
::T_MEDIUMBLOB
:
242 case CRM_Utils_Type
::T_TEXT
:
243 case CRM_Utils_Type
::T_LONGTEXT
:
244 case CRM_Utils_Type
::T_EMAIL
:
246 // WAS: if (isset($value['enumValues'])) {
247 // TODO: see if this works with all pseudoconstants
248 if (isset($fieldDef['pseudoconstant'], $fieldDef['pseudoconstant']['callback'])) {
249 if (isset($fieldDef['default'])) {
250 $this->$dbName = $fieldDef['default'];
253 $options = CRM_Core_PseudoConstant
::get($daoName, $fieldName);
254 if (is_array($options)) {
255 $this->$dbName = $options[0];
258 $defaultValues = explode(',', $options);
259 $this->$dbName = $defaultValues[0];
264 $this->$dbName = $dbName . '_' . $counter;
265 $maxlength = CRM_Utils_Array
::value('maxlength', $fieldDef);
266 if ($maxlength > 0 && strlen($this->$dbName) > $maxlength) {
267 $this->$dbName = substr($this->$dbName, 0, $fieldDef['maxlength']);
275 * Reset the DAO object.
277 * DAO is kinda crappy in that there is an unwritten rule of one query per DAO.
279 * We attempt to get around this crappy restriction by resetting some of DAO's internal fields. Use this with caution
281 public function reset() {
283 foreach (array_keys($this->table()) as $field) {
284 unset($this->$field);
288 * reset the various DB_DAO structures manually
290 $this->_query
= array();
297 * @param string $tableName
301 public static function getLocaleTableName($tableName) {
304 $tables = CRM_Core_I18n_Schema
::schemaStructureTables();
305 if (in_array($tableName, $tables)) {
306 return $tableName . $dbLocale;
313 * Execute a query by the current DAO, localizing it along the way (if needed).
315 * @param string $query
316 * The SQL query for execution.
317 * @param bool $i18nRewrite
318 * Whether to rewrite the query.
321 * the current DAO object after the query execution
323 public function query($query, $i18nRewrite = TRUE) {
324 // rewrite queries that should use $dbLocale-based views for multi-language installs
325 global $dbLocale, $_DB_DATAOBJECT;
327 $conn = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5
];
328 $orig_options = $conn->options
;
329 $this->_setDBOptions($this->_options
);
331 if ($i18nRewrite and $dbLocale) {
332 $query = CRM_Core_I18n_Schema
::rewriteQuery($query);
335 $ret = parent
::query($query);
337 $this->_setDBOptions($orig_options);
342 * Static function to set the factory instance for this class.
344 * @param object $factory
345 * The factory application object.
347 public static function setFactory(&$factory) {
348 self
::$_factory = &$factory;
352 * Factory method to instantiate a new object from a table name.
354 * @param string $table
356 public function factory($table = '') {
357 if (!isset(self
::$_factory)) {
358 return parent
::factory($table);
361 return self
::$_factory->create($table);
365 * Initialization for all DAO objects. Since we access DB_DO programatically
366 * we need to set the links manually.
368 public function initialize() {
370 if (empty(Civi
::$statics[__CLASS__
]['init'])) {
371 // CRM_Core_DAO::init() must be called before CRM_Core_DAO->initialize().
372 // This occurs very early in bootstrap - error handlers may not be wired up.
373 echo "Inconsistent system initialization sequence. Premature access of (" . get_class($this) . ")";
374 CRM_Utils_System
::civiExit();
379 * Defines the default key as 'id'.
384 public function keys() {
393 * Tells DB_DataObject which keys use autoincrement.
394 * 'id' is autoincrementing by default.
399 public function sequenceKey() {
400 static $sequenceKeys;
401 if (!isset($sequenceKeys)) {
402 $sequenceKeys = array('id', TRUE);
404 return $sequenceKeys;
408 * Returns list of FK relationships.
412 * Array of CRM_Core_Reference_Interface
414 public static function getReferenceColumns() {
419 * Returns all the column names of this table.
424 public static function &fields() {
430 * Get/set an associative array of table columns
435 public function table() {
436 $fields = &$this->fields();
440 foreach ($fields as $name => $value) {
441 $table[$value['name']] = $value['type'];
442 if (!empty($value['required'])) {
443 $table[$value['name']] +
= self
::DB_DAO_NOTNULL
;
458 public function save($hook = TRUE) {
459 if (!empty($this->id
)) {
463 $event = new \Civi\Core\DAO\Event\
PostUpdate($this);
464 \Civi
::service('dispatcher')->dispatch("DAO::post-update", $event);
471 $event = new \Civi\Core\DAO\Event\
PostUpdate($this);
472 \Civi
::service('dispatcher')->dispatch("DAO::post-insert", $event);
478 CRM_Utils_Hook
::postSave($this);
485 * Deletes items from table which match current objects variables.
487 * Returns the true on success
491 * Designed to be extended
493 * $object = new mytable();
495 * echo $object->delete(); // builds a conditon
497 * $object = new mytable();
498 * $object->whereAdd('age > 12');
500 * $object->orderBy('age DESC');
501 * $object->delete(true); // dont use object vars, use the conditions, limit and order.
503 * @param bool $useWhere (optional) If DB_DATAOBJECT_WHEREADD_ONLY is passed in then
504 * we will build the condition only using the whereAdd's. Default is to
505 * build the condition only using the object parameters.
507 * * @return mixed Int (No. of rows affected) on success, false on failure, 0 on no data affected
509 public function delete($useWhere = FALSE) {
510 $result = parent
::delete($useWhere);
512 $event = new \Civi\Core\DAO\Event\
PostDelete($this, $result);
513 \Civi
::service('dispatcher')->dispatch("DAO::post-delete", $event);
519 * @param bool $created
521 public function log($created = FALSE) {
524 if (!$this->getLog()) {
529 $session = CRM_Core_Session
::singleton();
530 $cid = $session->get('userID');
533 // return is we dont have handle to FK
538 $dao = new CRM_Core_DAO_Log();
539 $dao->entity_table
= $this->getTableName();
540 $dao->entity_id
= $this->id
;
541 $dao->modified_id
= $cid;
542 $dao->modified_date
= date("YmdHis");
547 * Given an associative array of name/value pairs, extract all the values
548 * that belong to this object and initialize the object with said values
550 * @param array $params
551 * (reference ) associative array of name/value pairs.
554 * Did we copy all null values into the object
556 public function copyValues(&$params) {
557 $fields = &$this->fields();
559 foreach ($fields as $name => $value) {
560 $dbName = $value['name'];
561 if (array_key_exists($dbName, $params)) {
562 $pValue = $params[$dbName];
565 elseif (array_key_exists($name, $params)) {
566 $pValue = $params[$name];
573 // if there is no value then make the variable NULL
575 if ($pValue === '') {
576 $this->$dbName = 'null';
579 $this->$dbName = $pValue;
588 * Store all the values from this object in an associative array
589 * this is a destructive store, calling function is responsible
590 * for keeping sanity of id's.
592 * @param object $object
593 * The object that we are extracting data from.
594 * @param array $values
595 * (reference ) associative array of name/value pairs.
597 public static function storeValues(&$object, &$values) {
598 $fields = &$object->fields();
599 foreach ($fields as $name => $value) {
600 $dbName = $value['name'];
601 if (isset($object->$dbName) && $object->$dbName !== 'null') {
602 $values[$dbName] = $object->$dbName;
603 if ($name != $dbName) {
604 $values[$name] = $object->$dbName;
611 * Create an attribute for this specific field. We only do this for strings and text
613 * @param array $field
614 * The field under task.
617 * the attributes for the object
619 public static function makeAttribute($field) {
621 if (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_STRING
) {
622 $maxLength = CRM_Utils_Array
::value('maxlength', $field);
623 $size = CRM_Utils_Array
::value('size', $field);
624 if ($maxLength ||
$size) {
625 $attributes = array();
627 $attributes['maxlength'] = $maxLength;
630 $attributes['size'] = $size;
635 elseif (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_TEXT
) {
636 $rows = CRM_Utils_Array
::value('rows', $field);
640 $cols = CRM_Utils_Array
::value('cols', $field);
645 $attributes = array();
646 $attributes['rows'] = $rows;
647 $attributes['cols'] = $cols;
650 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
) {
651 $attributes['size'] = 6;
652 $attributes['maxlength'] = 14;
660 * Get the size and maxLength attributes for this text field.
661 * (or for all text fields) in the DAO object.
663 * @param string $class
665 * @param string $fieldName
666 * Field that i'm interested in or null if.
667 * you want the attributes for all DAO text fields
670 * assoc array of name => attribute pairs
672 public static function getAttribute($class, $fieldName = NULL) {
673 $object = new $class();
674 $fields = &$object->fields();
675 if ($fieldName != NULL) {
676 $field = CRM_Utils_Array
::value($fieldName, $fields);
677 return self
::makeAttribute($field);
680 $attributes = array();
681 foreach ($fields as $name => $field) {
682 $attribute = self
::makeAttribute($field);
684 $attributes[$name] = $attribute;
688 if (!empty($attributes)) {
700 public static function transaction($type) {
701 CRM_Core_Error
::fatal('This function is obsolete, please use CRM_Core_Transaction');
705 * Check if there is a record with the same name in the db.
707 * @param string $value
708 * The value of the field we are checking.
709 * @param string $daoName
710 * The dao object name.
711 * @param string $daoID
712 * The id of the object being updated. u can change your name.
713 * as long as there is no conflict
714 * @param string $fieldName
715 * The name of the field in the DAO.
718 * true if object exists
720 public static function objectExists($value, $daoName, $daoID, $fieldName = 'name') {
721 $object = new $daoName();
722 $object->$fieldName = $value;
724 $config = CRM_Core_Config
::singleton();
726 if ($object->find(TRUE)) {
727 return ($daoID && $object->id
== $daoID) ?
TRUE : FALSE;
735 * Check if there is a given column in a specific table.
737 * @param string $tableName
738 * @param string $columnName
739 * @param bool $i18nRewrite
740 * Whether to rewrite the query on multilingual setups.
743 * true if exists, else false
745 public static function checkFieldExists($tableName, $columnName, $i18nRewrite = TRUE) {
751 $params = array(1 => array($columnName, 'String'));
752 $dao = CRM_Core_DAO
::executeQuery($query, $params, TRUE, NULL, FALSE, $i18nRewrite);
753 $result = $dao->fetch() ?
TRUE : FALSE;
759 * Returns the storage engine used by given table-name(optional).
760 * Otherwise scans all the tables and return an array of all the
761 * distinct storage engines being used.
763 * @param string $tableName
765 * @param int $maxTablesToCheck
766 * @param string $fieldName
770 public static function getStorageValues($tableName = NULL, $maxTablesToCheck = 10, $fieldName = 'Engine') {
772 $query = "SHOW TABLE STATUS LIKE %1";
776 if (isset($tableName)) {
777 $params = array(1 => array($tableName, 'String'));
780 $params = array(1 => array('civicrm_%', 'String'));
783 $dao = CRM_Core_DAO
::executeQuery($query, $params);
786 while ($dao->fetch()) {
787 if (isset($values[$dao->$fieldName]) ||
788 // ignore import and other temp tables
789 strpos($dao->Name
, 'civicrm_import_job_') !== FALSE ||
790 strpos($dao->Name
, '_temp') !== FALSE
794 $values[$dao->$fieldName] = 1;
796 if ($maxTablesToCheck &&
797 $count >= $maxTablesToCheck
807 * @param int $maxTablesToCheck
811 public static function isDBMyISAM($maxTablesToCheck = 10) {
812 // show error if any of the tables, use 'MyISAM' storage engine.
813 $engines = self
::getStorageValues(NULL, $maxTablesToCheck);
814 if (array_key_exists('MyISAM', $engines)) {
821 * Checks if a constraint exists for a specified table.
823 * @param string $tableName
824 * @param string $constraint
827 * true if constraint exists, false otherwise
829 public static function checkConstraintExists($tableName, $constraint) {
830 static $show = array();
832 if (!array_key_exists($tableName, $show)) {
833 $query = "SHOW CREATE TABLE $tableName";
834 $dao = CRM_Core_DAO
::executeQuery($query);
836 if (!$dao->fetch()) {
837 CRM_Core_Error
::fatal();
841 $show[$tableName] = $dao->Create_Table
;
844 return preg_match("/\b$constraint\b/i", $show[$tableName]) ?
TRUE : FALSE;
848 * Checks if CONSTRAINT keyword exists for a specified table.
850 * @param array $tables
855 * true if CONSTRAINT keyword exists, false otherwise
857 public static function schemaRequiresRebuilding($tables = array("civicrm_contact")) {
859 foreach ($tables as $tableName) {
860 if (!array_key_exists($tableName, $show)) {
861 $query = "SHOW CREATE TABLE $tableName";
862 $dao = CRM_Core_DAO
::executeQuery($query);
864 if (!$dao->fetch()) {
865 CRM_Core_Error
::fatal();
869 $show[$tableName] = $dao->Create_Table
;
872 $result = preg_match("/\bCONSTRAINT\b\s/i", $show[$tableName]) ?
TRUE : FALSE;
873 if ($result == TRUE) {
884 * Checks if the FK constraint name is in the format 'FK_tableName_columnName'
885 * for a specified column of a table.
887 * @param string $tableName
888 * @param string $columnName
891 * true if in format, false otherwise
893 public static function checkFKConstraintInFormat($tableName, $columnName) {
894 static $show = array();
896 if (!array_key_exists($tableName, $show)) {
897 $query = "SHOW CREATE TABLE $tableName";
898 $dao = CRM_Core_DAO
::executeQuery($query);
900 if (!$dao->fetch()) {
901 CRM_Core_Error
::fatal();
905 $show[$tableName] = $dao->Create_Table
;
907 $constraint = "`FK_{$tableName}_{$columnName}`";
908 $pattern = "/\bCONSTRAINT\b\s+%s\s+\bFOREIGN\s+KEY\b\s/i";
909 return preg_match(sprintf($pattern, $constraint), $show[$tableName]) ?
TRUE : FALSE;
913 * Check whether a specific column in a specific table has always the same value.
915 * @param string $tableName
916 * @param string $columnName
917 * @param string $columnValue
920 * true if the value is always $columnValue, false otherwise
922 public static function checkFieldHasAlwaysValue($tableName, $columnName, $columnValue) {
923 $query = "SELECT * FROM $tableName WHERE $columnName != '$columnValue'";
924 $dao = CRM_Core_DAO
::executeQuery($query);
925 $result = $dao->fetch() ?
FALSE : TRUE;
931 * Check whether a specific column in a specific table is always NULL.
933 * @param string $tableName
934 * @param string $columnName
937 * true if if the value is always NULL, false otherwise
939 public static function checkFieldIsAlwaysNull($tableName, $columnName) {
940 $query = "SELECT * FROM $tableName WHERE $columnName IS NOT NULL";
941 $dao = CRM_Core_DAO
::executeQuery($query);
942 $result = $dao->fetch() ?
FALSE : TRUE;
948 * Check if there is a given table in the database.
950 * @param string $tableName
953 * true if exists, else false
955 public static function checkTableExists($tableName) {
960 $params = array(1 => array($tableName, 'String'));
962 $dao = CRM_Core_DAO
::executeQuery($query, $params);
963 $result = $dao->fetch() ?
TRUE : FALSE;
973 public function checkVersion($version) {
978 $dbVersion = CRM_Core_DAO
::singleValueQuery($query);
979 return trim($version) == trim($dbVersion) ?
TRUE : FALSE;
983 * Find a DAO object for the given ID and return it.
986 * Id of the DAO object being searched for.
989 * Object of the type of the class that called this function.
991 public static function findById($id) {
992 $object = new static();
994 if (!$object->find(TRUE)) {
995 throw new Exception("Unable to find a " . get_called_class() . " with id {$id}.");
1001 * Returns all results as array-encoded records.
1005 public function fetchAll() {
1007 while ($this->fetch()) {
1008 $result[] = $this->toArray();
1014 * Given a DAO name, a column name and a column value, find the record and GET the value of another column in that record
1016 * @param string $daoName
1017 * Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact).
1018 * @param int $searchValue
1019 * Value of the column you want to search by.
1020 * @param string $returnColumn
1021 * Name of the column you want to GET the value of.
1022 * @param string $searchColumn
1023 * Name of the column you want to search by.
1024 * @param bool $force
1025 * Skip use of the cache.
1027 * @return string|null
1028 * Value of $returnColumn in the retrieved record
1030 public static function getFieldValue($daoName, $searchValue, $returnColumn = 'name', $searchColumn = 'id', $force = FALSE) {
1032 empty($searchValue) ||
1033 trim(strtolower($searchValue)) == 'null'
1035 // adding this year since developers forget to check for an id
1036 // or for the 'null' (which is a bad DAO kludge)
1037 // and hence we get the first value in the db
1038 CRM_Core_Error
::fatal();
1041 $cacheKey = "{$daoName}:{$searchValue}:{$returnColumn}:{$searchColumn}";
1042 if (self
::$_dbColumnValueCache === NULL) {
1043 self
::$_dbColumnValueCache = array();
1046 if (!array_key_exists($cacheKey, self
::$_dbColumnValueCache) ||
$force) {
1047 $object = new $daoName();
1048 $object->$searchColumn = $searchValue;
1049 $object->selectAdd();
1050 $object->selectAdd($returnColumn);
1053 if ($object->find(TRUE)) {
1054 $result = $object->$returnColumn;
1058 self
::$_dbColumnValueCache[$cacheKey] = $result;
1060 return self
::$_dbColumnValueCache[$cacheKey];
1064 * Given a DAO name, a column name and a column value, find the record and SET the value of another column in that record
1066 * @param string $daoName
1067 * Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact).
1068 * @param int $searchValue
1069 * Value of the column you want to search by.
1070 * @param string $setColumn
1071 * Name of the column you want to SET the value of.
1072 * @param string $setValue
1073 * SET the setColumn to this value.
1074 * @param string $searchColumn
1075 * Name of the column you want to search by.
1078 * true if we found and updated the object, else false
1080 public static function setFieldValue($daoName, $searchValue, $setColumn, $setValue, $searchColumn = 'id') {
1081 $object = new $daoName();
1082 $object->selectAdd();
1083 $object->selectAdd("$searchColumn, $setColumn");
1084 $object->$searchColumn = $searchValue;
1086 if ($object->find(TRUE)) {
1087 $object->$setColumn = $setValue;
1088 if ($object->save()) {
1099 * @param array|object $sort either array or CRM_Utils_Sort
1100 * @param string $default
1101 * Default sort value.
1106 public static function getSortString($sort, $default = NULL) {
1107 // check if sort is of type CRM_Utils_Sort
1108 if (is_a($sort, 'CRM_Utils_Sort')) {
1109 return $sort->orderBy();
1112 // is it an array specified as $field => $sortDirection ?
1114 foreach ($sort as $k => $v) {
1115 $sortString .= "$k $v,";
1117 return rtrim($sortString, ',');
1123 * Fetch object based on array of properties.
1125 * @param string $daoName
1126 * Name of the dao object.
1127 * @param array $params
1128 * (reference ) an assoc array of name/value pairs.
1129 * @param array $defaults
1130 * (reference ) an assoc array to hold the flattened values.
1131 * @param array $returnProperities
1132 * An assoc array of fields that need to be returned, eg array( 'first_name', 'last_name').
1135 * an object of type referenced by daoName
1137 public static function commonRetrieve($daoName, &$params, &$defaults, $returnProperities = NULL) {
1138 $object = new $daoName();
1139 $object->copyValues($params);
1141 // return only specific fields if returnproperties are sent
1142 if (!empty($returnProperities)) {
1143 $object->selectAdd();
1144 $object->selectAdd(implode(',', $returnProperities));
1147 if ($object->find(TRUE)) {
1148 self
::storeValues($object, $defaults);
1155 * Delete the object records that are associated with this contact.
1157 * @param string $daoName
1158 * Name of the dao object.
1159 * @param int $contactId
1160 * Id of the contact to delete.
1162 public static function deleteEntityContact($daoName, $contactId) {
1163 $object = new $daoName();
1165 $object->entity_table
= 'civicrm_contact';
1166 $object->entity_id
= $contactId;
1171 * execute an unbuffered query. This is a wrapper around new functionality
1172 * exposed with CRM-17748.
1174 * @param string $query query to be executed
1176 * @return Object CRM_Core_DAO object that points to an unbuffered result set
1180 static public function executeUnbufferedQuery(
1186 $i18nRewrite = TRUE,
1187 $trapException = FALSE
1189 $queryStr = self
::composeQuery($query, $params, $abort);
1190 //CRM_Core_Error::debug( 'q', $queryStr );
1192 $dao = new CRM_Core_DAO();
1195 $dao = new $daoName();
1198 if ($trapException) {
1199 CRM_Core_Error
::ignoreException();
1202 // set the DAO object to use an unbuffered query
1203 $dao->setOptions(array('result_buffering' => 0));
1205 $result = $dao->query($queryStr, $i18nRewrite);
1207 if ($trapException) {
1208 CRM_Core_Error
::setCallback();
1211 if (is_a($result, 'DB_Error')) {
1215 // since it is unbuffered, ($dao->N==0) is true. This blocks the standard fetch() mechanism.
1219 preg_match('/^(insert|update|delete|create|drop|replace)/i', $queryStr)
1221 // we typically do this for insert/update/delete stataments OR if explicitly asked to
1231 * @param string $query
1232 * Query to be executed.
1234 * @param array $params
1235 * @param bool $abort
1236 * @param null $daoName
1237 * @param bool $freeDAO
1238 * @param bool $i18nRewrite
1239 * @param bool $trapException
1241 * @return CRM_Core_DAO|object
1242 * object that holds the results of the query
1243 * NB - if this is defined as just returning a DAO phpstorm keeps pointing
1244 * out all the properties that are not part of the DAO
1246 public static function &executeQuery(
1252 $i18nRewrite = TRUE,
1253 $trapException = FALSE
1255 $queryStr = self
::composeQuery($query, $params, $abort);
1258 $dao = new CRM_Core_DAO();
1261 $dao = new $daoName();
1264 if ($trapException) {
1265 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
1268 $result = $dao->query($queryStr, $i18nRewrite);
1270 if (is_a($result, 'DB_Error')) {
1275 preg_match('/^(insert|update|delete|create|drop|replace)/i', $queryStr)
1277 // we typically do this for insert/update/delete statements OR if explicitly asked to
1285 * Execute a query and get the single result.
1287 * @param string $query
1288 * Query to be executed.
1289 * @param array $params
1290 * @param bool $abort
1291 * @param bool $i18nRewrite
1292 * @return string|null
1293 * the result of the query if any
1296 public static function &singleValueQuery(
1302 $queryStr = self
::composeQuery($query, $params, $abort);
1304 static $_dao = NULL;
1307 $_dao = new CRM_Core_DAO();
1310 $_dao->query($queryStr, $i18nRewrite);
1312 $result = $_dao->getDatabaseResult();
1315 $row = $result->fetchRow();
1326 * @param array $params
1327 * @param bool $abort
1332 public static function composeQuery($query, &$params, $abort = TRUE) {
1334 foreach ($params as $key => $item) {
1335 if (is_numeric($key)) {
1336 if (CRM_Utils_Type
::validate($item[0], $item[1]) !== NULL) {
1337 $item[0] = self
::escapeString($item[0]);
1338 if ($item[1] == 'String' ||
1339 $item[1] == 'Memo' ||
1342 // Support class constants stipulating wildcard characters and/or
1343 // non-quoting of strings. Also support legacy code which may be
1344 // passing in TRUE or 1 for $item[2], which used to indicate the
1345 // use of wildcard characters.
1346 if (!empty($item[2])) {
1347 if ($item[2] & CRM_Core_DAO
::QUERY_FORMAT_WILDCARD ||
$item[2] === TRUE) {
1348 $item[0] = "'%{$item[0]}%'";
1350 elseif (!($item[2] & CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
)) {
1351 $item[0] = "'{$item[0]}'";
1355 $item[0] = "'{$item[0]}'";
1359 if (($item[1] == 'Date' ||
$item[1] == 'Timestamp') &&
1360 strlen($item[0]) == 0
1365 $tr['%' . $key] = $item[0];
1368 CRM_Core_Error
::fatal("{$item[0]} is not of type {$item[1]}");
1373 return strtr($query, $tr);
1379 public static function freeResult($ids = NULL) {
1380 global $_DB_DATAOBJECT;
1383 if (!$_DB_DATAOBJECT ||
1384 !isset($_DB_DATAOBJECT['RESULTS'])
1388 $ids = array_keys($_DB_DATAOBJECT['RESULTS']);
1391 foreach ($ids as $id) {
1392 if (isset($_DB_DATAOBJECT['RESULTS'][$id])) {
1393 if (is_resource($_DB_DATAOBJECT['RESULTS'][$id]->result
)) {
1394 mysql_free_result($_DB_DATAOBJECT['RESULTS'][$id]->result
);
1396 unset($_DB_DATAOBJECT['RESULTS'][$id]);
1399 if (isset($_DB_DATAOBJECT['RESULTFIELDS'][$id])) {
1400 unset($_DB_DATAOBJECT['RESULTFIELDS'][$id]);
1406 * make a shallow copy of an object.
1407 * and all the fields in the object
1409 * @param string $daoName
1411 * @param array $criteria
1412 * Array of all the fields & values.
1413 * on which basis to copy
1414 * @param array $newData
1415 * Array of all the fields & values.
1416 * to be copied besides the other fields
1417 * @param string $fieldsFix
1418 * Array of fields that you want to prefix/suffix/replace.
1419 * @param string $blockCopyOfDependencies
1420 * Fields that you want to block from.
1424 * @return CRM_Core_DAO
1425 * the newly created copy of the object
1427 public static function ©Generic($daoName, $criteria, $newData = NULL, $fieldsFix = NULL, $blockCopyOfDependencies = NULL) {
1428 $object = new $daoName();
1430 $object->id
= $criteria['id'];
1433 foreach ($criteria as $key => $value) {
1434 $object->$key = $value;
1439 while ($object->fetch()) {
1441 // all the objects except with $blockCopyOfDependencies set
1442 // be copied - addresses #CRM-1962
1444 if ($blockCopyOfDependencies && $object->$blockCopyOfDependencies) {
1448 $newObject = new $daoName();
1450 $fields = &$object->fields();
1451 if (!is_array($fieldsFix)) {
1452 $fieldsToPrefix = array();
1453 $fieldsToSuffix = array();
1454 $fieldsToReplace = array();
1456 if (!empty($fieldsFix['prefix'])) {
1457 $fieldsToPrefix = $fieldsFix['prefix'];
1459 if (!empty($fieldsFix['suffix'])) {
1460 $fieldsToSuffix = $fieldsFix['suffix'];
1462 if (!empty($fieldsFix['replace'])) {
1463 $fieldsToReplace = $fieldsFix['replace'];
1466 foreach ($fields as $name => $value) {
1467 if ($name == 'id' ||
$value['name'] == 'id') {
1468 // copy everything but the id!
1472 $dbName = $value['name'];
1473 $type = CRM_Utils_Type
::typeToString($value['type']);
1474 $newObject->$dbName = $object->$dbName;
1475 if (isset($fieldsToPrefix[$dbName])) {
1476 $newObject->$dbName = $fieldsToPrefix[$dbName] . $newObject->$dbName;
1478 if (isset($fieldsToSuffix[$dbName])) {
1479 $newObject->$dbName .= $fieldsToSuffix[$dbName];
1481 if (isset($fieldsToReplace[$dbName])) {
1482 $newObject->$dbName = $fieldsToReplace[$dbName];
1485 if ($type == 'Timestamp' ||
$type == 'Date') {
1486 $newObject->$dbName = CRM_Utils_Date
::isoToMysql($newObject->$dbName);
1490 foreach ($newData as $k => $v) {
1491 $newObject->$k = $v;
1501 * Cascade update through related entities.
1503 * @param string $daoName
1506 * @param array $newData
1510 public static function cascadeUpdate($daoName, $fromId, $toId, $newData = array()) {
1511 $object = new $daoName();
1512 $object->id
= $fromId;
1514 if ($object->find(TRUE)) {
1515 $newObject = new $daoName();
1516 $newObject->id
= $toId;
1518 if ($newObject->find(TRUE)) {
1519 $fields = &$object->fields();
1520 foreach ($fields as $name => $value) {
1521 if ($name == 'id' ||
$value['name'] == 'id') {
1522 // copy everything but the id!
1526 $colName = $value['name'];
1527 $newObject->$colName = $object->$colName;
1529 if (substr($name, -5) == '_date' ||
1530 substr($name, -10) == '_date_time'
1532 $newObject->$colName = CRM_Utils_Date
::isoToMysql($newObject->$colName);
1535 foreach ($newData as $k => $v) {
1536 $newObject->$k = $v;
1542 return CRM_Core_DAO
::$_nullObject;
1546 * Given the component id, compute the contact id
1547 * since its used for things like send email
1549 * @param $componentIDs
1550 * @param string $tableName
1554 public static function &getContactIDsFromComponent(&$componentIDs, $tableName) {
1555 $contactIDs = array();
1557 if (empty($componentIDs)) {
1561 $IDs = implode(',', $componentIDs);
1565 WHERE id IN ( $IDs )
1568 $dao = CRM_Core_DAO
::executeQuery($query);
1569 while ($dao->fetch()) {
1570 $contactIDs[] = $dao->contact_id
;
1576 * Fetch object based on array of properties.
1578 * @param string $daoName
1579 * Name of the dao object.
1580 * @param string $fieldIdName
1581 * @param int $fieldId
1583 * @param array $returnProperities
1584 * An assoc array of fields that need to be returned, eg array( 'first_name', 'last_name').
1587 * an object of type referenced by daoName
1589 public static function commonRetrieveAll($daoName, $fieldIdName = 'id', $fieldId, &$details, $returnProperities = NULL) {
1590 require_once str_replace('_', DIRECTORY_SEPARATOR
, $daoName) . ".php";
1591 $object = new $daoName();
1592 $object->$fieldIdName = $fieldId;
1594 // return only specific fields if returnproperties are sent
1595 if (!empty($returnProperities)) {
1596 $object->selectAdd();
1597 $object->selectAdd('id');
1598 $object->selectAdd(implode(',', $returnProperities));
1602 while ($object->fetch()) {
1603 $defaults = array();
1604 self
::storeValues($object, $defaults);
1605 $details[$object->id
] = $defaults;
1611 public static function dropAllTables() {
1613 // first drop all the custom tables we've created
1614 CRM_Core_BAO_CustomGroup
::dropAllTables();
1616 // drop all multilingual views
1617 CRM_Core_I18n_Schema
::dropAllViews();
1619 CRM_Utils_File
::sourceSQLFile(CIVICRM_DSN
,
1620 dirname(__FILE__
) . DIRECTORY_SEPARATOR
.
1621 '..' . DIRECTORY_SEPARATOR
.
1622 '..' . DIRECTORY_SEPARATOR
.
1623 'sql' . DIRECTORY_SEPARATOR
.
1624 'civicrm_drop.mysql'
1633 public static function escapeString($string) {
1634 static $_dao = NULL;
1637 // If this is an atypical case (e.g. preparing .sql files
1638 // before Civi has been installed), then we fallback to
1639 // DB-less escaping helper (mysql_real_escape_string).
1640 // Note: In typical usage, escapeString() will only
1641 // check one conditional ("if !$_dao") rather than
1642 // two conditionals ("if !defined(DSN)")
1643 if (!defined('CIVICRM_DSN')) {
1644 if (function_exists('mysql_real_escape_string')) {
1645 return mysql_real_escape_string($string);
1648 throw new CRM_Core_Exception("Cannot generate SQL. \"mysql_real_escape_string\" is missing. Have you installed PHP \"mysql\" extension?");
1652 $_dao = new CRM_Core_DAO();
1655 return $_dao->escape($string);
1659 * Escape a list of strings for use with "WHERE X IN (...)" queries.
1661 * @param array $strings
1662 * @param string $default
1663 * the value to use if $strings has no elements.
1665 * eg "abc","def","ghi"
1667 public static function escapeStrings($strings, $default = NULL) {
1668 static $_dao = NULL;
1670 $_dao = new CRM_Core_DAO();
1673 if (empty($strings)) {
1677 $escapes = array_map(array($_dao, 'escape'), $strings);
1678 return '"' . implode('","', $escapes) . '"';
1686 public static function escapeWildCardString($string) {
1688 // ensure we escape the single characters % and _ which are mysql wild
1689 // card characters and could come in via sortByCharacter
1690 // note that mysql does not escape these characters
1691 if ($string && in_array($string,
1692 array('%', '_', '%%', '_%')
1695 return '\\' . $string;
1698 return self
::escapeString($string);
1702 * Creates a test object, including any required objects it needs via recursion
1703 * createOnly: only create in database, do not store or return the objects (useful for perf testing)
1704 * ONLY USE FOR TESTING
1706 * @param string $daoName
1707 * @param array $params
1708 * @param int $numObjects
1709 * @param bool $createOnly
1711 * @return object|array|NULL
1712 * NULL if $createOnly. A single object if $numObjects==1. Otherwise, an array of multiple objects.
1714 public static function createTestObject(
1720 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
1721 // so we re-set here in case
1722 $config = CRM_Core_Config
::singleton();
1723 $config->backtrace
= TRUE;
1725 static $counter = 0;
1726 CRM_Core_DAO
::$_testEntitiesToSkip = array(
1727 'CRM_Core_DAO_Worldregion',
1728 'CRM_Core_DAO_StateProvince',
1729 'CRM_Core_DAO_Country',
1730 'CRM_Core_DAO_Domain',
1731 'CRM_Financial_DAO_FinancialType',
1732 //because valid ones exist & we use pick them due to pseudoconstant can't reliably create & delete these
1735 // Prefer to instantiate BAO's instead of DAO's (when possible)
1736 // so that assignTestValue()/assignTestFK() can be overloaded.
1737 $baoName = str_replace('_DAO_', '_BAO_', $daoName);
1738 if (class_exists($baoName)) {
1739 $daoName = $baoName;
1742 for ($i = 0; $i < $numObjects; ++
$i) {
1745 /** @var CRM_Core_DAO $object */
1746 $object = new $daoName();
1748 $fields = &$object->fields();
1749 foreach ($fields as $fieldName => $fieldDef) {
1750 $dbName = $fieldDef['name'];
1751 $FKClassName = CRM_Utils_Array
::value('FKClassName', $fieldDef);
1752 $required = CRM_Utils_Array
::value('required', $fieldDef);
1754 if (CRM_Utils_Array
::value($dbName, $params) !== NULL && !is_array($params[$dbName])) {
1755 $object->$dbName = $params[$dbName];
1758 elseif ($dbName != 'id') {
1759 if ($FKClassName != NULL) {
1760 $object->assignTestFK($fieldName, $fieldDef, $params);
1764 $object->assignTestValue($fieldName, $fieldDef, $counter);
1772 $objects[$i] = $object;
1782 elseif ($numObjects == 1) {
1791 * Deletes the this object plus any dependent objects that are associated with it.
1792 * ONLY USE FOR TESTING
1794 * @param string $daoName
1795 * @param array $params
1797 public static function deleteTestObjects($daoName, $params = array()) {
1798 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
1799 // so we re-set here in case
1800 $config = CRM_Core_Config
::singleton();
1801 $config->backtrace
= TRUE;
1803 $object = new $daoName();
1804 $object->id
= CRM_Utils_Array
::value('id', $params);
1806 $deletions = array(); // array(array(0 => $daoName, 1 => $daoParams))
1807 if ($object->find(TRUE)) {
1809 $fields = &$object->fields();
1810 foreach ($fields as $name => $value) {
1812 $dbName = $value['name'];
1814 $FKClassName = CRM_Utils_Array
::value('FKClassName', $value);
1815 $required = CRM_Utils_Array
::value('required', $value);
1816 if ($FKClassName != NULL
1818 && !in_array($FKClassName, CRM_Core_DAO
::$_testEntitiesToSkip)
1819 && ($required ||
$dbName == 'contact_id')
1820 //I'm a bit stuck on this one - we might need to change the singleValueAlter so that the entities don't share a contact
1821 // to make this test process pass - line below makes pass for now
1822 && $dbName != 'member_of_contact_id'
1824 $deletions[] = array($FKClassName, array('id' => $object->$dbName)); // x
1831 foreach ($deletions as $deletion) {
1832 CRM_Core_DAO
::deleteTestObjects($deletion[0], $deletion[1]);
1837 * Set defaults when creating new entity.
1838 * (don't call this set defaults as already in use with different signature in some places)
1840 * @param array $params
1843 public static function setCreateDefaults(&$params, $defaults) {
1844 if (!empty($params['id'])) {
1847 foreach ($defaults as $key => $value) {
1848 if (!array_key_exists($key, $params) ||
$params[$key] === NULL) {
1849 $params[$key] = $value;
1855 * @param string $prefix
1856 * @param bool $addRandomString
1857 * @param null $string
1861 public static function createTempTableName($prefix = 'civicrm', $addRandomString = TRUE, $string = NULL) {
1862 $tableName = $prefix . "_temp";
1864 if ($addRandomString) {
1866 $tableName .= "_" . $string;
1869 $tableName .= "_" . md5(uniqid('', TRUE));
1877 * @param bool $trigger
1881 public static function checkTriggerViewPermission($view = TRUE, $trigger = TRUE) {
1882 // test for create view and trigger permissions and if allowed, add the option to go multilingual
1884 // I'm not sure why we use the getStaticProperty for an error, rather than checking for DB_Error
1885 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
1886 $dao = new CRM_Core_DAO();
1888 $dao->query('CREATE OR REPLACE VIEW civicrm_domain_view AS SELECT * FROM civicrm_domain');
1889 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
1895 $result = $dao->query('CREATE TRIGGER civicrm_domain_trigger BEFORE INSERT ON civicrm_domain FOR EACH ROW BEGIN END');
1896 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError') ||
is_a($result, 'DB_Error')) {
1898 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1903 $dao->query('DROP TRIGGER IF EXISTS civicrm_domain_trigger');
1904 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
1906 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1913 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1914 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
1923 * @param null $message
1924 * @param bool $printDAO
1926 public static function debugPrint($message = NULL, $printDAO = TRUE) {
1927 CRM_Utils_System
::xMemory("{$message}: ");
1930 global $_DB_DATAOBJECT;
1932 foreach (array_keys($_DB_DATAOBJECT['RESULTS']) as $id) {
1933 $q[] = $_DB_DATAOBJECT['RESULTS'][$id]->query
;
1935 CRM_Core_Error
::debug('_DB_DATAOBJECT', $q);
1940 * Build a list of triggers via hook and add them to (err, reconcile them
1941 * with) the database.
1943 * @param string $tableName
1944 * the specific table requiring a rebuild; or NULL to rebuild all tables.
1945 * @param bool $force
1949 public static function triggerRebuild($tableName = NULL, $force = FALSE) {
1952 $logging = new CRM_Logging_Schema();
1953 $logging->triggerInfo($info, $tableName, $force);
1955 CRM_Core_I18n_Schema
::triggerInfo($info, $tableName);
1956 CRM_Contact_BAO_Contact
::triggerInfo($info, $tableName);
1958 CRM_Utils_Hook
::triggerInfo($info, $tableName);
1960 // drop all existing triggers on all tables
1961 $logging->dropTriggers($tableName);
1963 // now create the set of new triggers
1964 self
::createTriggers($info, $tableName);
1968 * Because sql functions are sometimes lost, esp during db migration, we check here to avoid numerous support requests
1969 * @see http://issues.civicrm.org/jira/browse/CRM-13822
1970 * TODO: Alternative solutions might be
1971 * * Stop using functions and find another way to strip numeric characters from phones
1972 * * Give better error messages (currently a missing fn fatals with "unknown error")
1974 public static function checkSqlFunctionsExist() {
1975 if (!self
::$_checkedSqlFunctionsExist) {
1976 self
::$_checkedSqlFunctionsExist = TRUE;
1977 $dao = CRM_Core_DAO
::executeQuery("SHOW function status WHERE db = database() AND name = 'civicrm_strip_non_numeric'");
1978 if (!$dao->fetch()) {
1979 self
::triggerRebuild();
1985 * Wrapper function to drop triggers.
1987 * @param string $tableName
1988 * the specific table requiring a rebuild; or NULL to rebuild all tables.
1990 public static function dropTriggers($tableName = NULL) {
1993 $logging = new CRM_Logging_Schema();
1994 $logging->triggerInfo($info, $tableName);
1996 // drop all existing triggers on all tables
1997 $logging->dropTriggers($tableName);
2001 * @param array $info
2002 * per hook_civicrm_triggerInfo.
2003 * @param string $onlyTableName
2004 * the specific table requiring a rebuild; or NULL to rebuild all tables.
2006 public static function createTriggers(&$info, $onlyTableName = NULL) {
2007 // Validate info array, should probably raise errors?
2008 if (is_array($info) == FALSE) {
2012 $triggers = array();
2014 // now enumerate the tables and the events and collect the same set in a different format
2015 foreach ($info as $value) {
2017 // clean the incoming data, skip malformed entries
2018 // TODO: malformed entries should raise errors or get logged.
2019 if (isset($value['table']) == FALSE ||
2020 isset($value['event']) == FALSE ||
2021 isset($value['when']) == FALSE ||
2022 isset($value['sql']) == FALSE
2027 if (is_string($value['table']) == TRUE) {
2028 $tables = array($value['table']);
2031 $tables = $value['table'];
2034 if (is_string($value['event']) == TRUE) {
2035 $events = array(strtolower($value['event']));
2038 $events = array_map('strtolower', $value['event']);
2041 $whenName = strtolower($value['when']);
2043 foreach ($tables as $tableName) {
2044 if (!isset($triggers[$tableName])) {
2045 $triggers[$tableName] = array();
2048 foreach ($events as $eventName) {
2049 $template_params = array('{tableName}', '{eventName}');
2050 $template_values = array($tableName, $eventName);
2052 $sql = str_replace($template_params,
2056 $variables = str_replace($template_params,
2058 CRM_Utils_Array
::value('variables', $value)
2061 if (!isset($triggers[$tableName][$eventName])) {
2062 $triggers[$tableName][$eventName] = array();
2065 if (!isset($triggers[$tableName][$eventName][$whenName])) {
2066 // We're leaving out cursors, conditions, and handlers for now
2067 // they are kind of dangerous in this context anyway
2068 // better off putting them in stored procedures
2069 $triggers[$tableName][$eventName][$whenName] = array(
2070 'variables' => array(),
2076 $triggers[$tableName][$eventName][$whenName]['variables'][] = $variables;
2079 $triggers[$tableName][$eventName][$whenName]['sql'][] = $sql;
2084 // now spit out the sql
2085 foreach ($triggers as $tableName => $tables) {
2086 if ($onlyTableName != NULL && $onlyTableName != $tableName) {
2089 foreach ($tables as $eventName => $events) {
2090 foreach ($events as $whenName => $parts) {
2091 $varString = implode("\n", $parts['variables']);
2092 $sqlString = implode("\n", $parts['sql']);
2093 $validName = CRM_Core_DAO
::shortenSQLName($tableName, 48, TRUE);
2094 $triggerName = "{$validName}_{$whenName}_{$eventName}";
2095 $triggerSQL = "CREATE TRIGGER $triggerName $whenName $eventName ON $tableName FOR EACH ROW BEGIN $varString $sqlString END";
2097 CRM_Core_DAO
::executeQuery("DROP TRIGGER IF EXISTS $triggerName");
2098 CRM_Core_DAO
::executeQuery(
2112 * Given a list of fields, create a list of references.
2114 * @param string $className
2115 * BAO/DAO class name.
2116 * @return array<CRM_Core_Reference_Interface>
2118 public static function createReferenceColumns($className) {
2120 $fields = $className::fields();
2121 foreach ($fields as $field) {
2122 if (isset($field['pseudoconstant'], $field['pseudoconstant']['optionGroupName'])) {
2123 $result[] = new CRM_Core_Reference_OptionValue(
2124 $className::getTableName(),
2126 'civicrm_option_value',
2127 CRM_Utils_Array
::value('keyColumn', $field['pseudoconstant'], 'value'),
2128 $field['pseudoconstant']['optionGroupName']
2136 * Find all records which refer to this entity.
2139 * Array of objects referencing this
2141 public function findReferences() {
2142 $links = self
::getReferencesToTable(static::getTableName());
2144 $occurrences = array();
2145 foreach ($links as $refSpec) {
2146 /** @var $refSpec CRM_Core_Reference_Interface */
2147 $daoName = CRM_Core_DAO_AllCoreTables
::getClassForTable($refSpec->getReferenceTable());
2148 $result = $refSpec->findReferences($this);
2150 while ($result->fetch()) {
2151 $obj = new $daoName();
2152 $obj->id
= $result->id
;
2153 $occurrences[] = $obj;
2158 return $occurrences;
2163 * each item has keys:
2167 * - table: string|null SQL table name
2168 * - key: string|null SQL column name
2170 public function getReferenceCounts() {
2171 $links = self
::getReferencesToTable(static::getTableName());
2174 foreach ($links as $refSpec) {
2175 /** @var $refSpec CRM_Core_Reference_Interface */
2176 $count = $refSpec->getReferenceCount($this);
2177 if ($count['count'] != 0) {
2182 foreach (CRM_Core_Component
::getEnabledComponents() as $component) {
2183 /** @var $component CRM_Core_Component_Info */
2184 $counts = array_merge($counts, $component->getReferenceCounts($this));
2186 CRM_Utils_Hook
::referenceCounts($this, $counts);
2192 * List all tables which have hard foreign keys to this table.
2194 * For now, this returns a description of every entity_id/entity_table
2196 * TODO: filter dynamic entity references on the $tableName, based on
2197 * schema metadata in dynamicForeignKey which enumerates a restricted
2198 * set of possible entity_table's.
2200 * @param string $tableName
2201 * Table referred to.
2204 * structure of table and column, listing every table with a
2205 * foreign key reference to $tableName, and the column where the key appears.
2207 public static function getReferencesToTable($tableName) {
2208 $refsFound = array();
2209 foreach (CRM_Core_DAO_AllCoreTables
::getClasses() as $daoClassName) {
2210 $links = $daoClassName::getReferenceColumns();
2211 $daoTableName = $daoClassName::getTableName();
2213 foreach ($links as $refSpec) {
2214 /** @var $refSpec CRM_Core_Reference_Interface */
2215 if ($refSpec->matchesTargetTable($tableName)) {
2216 $refsFound[] = $refSpec;
2224 * Lookup the value of a MySQL global configuration variable.
2226 * @param string $name
2227 * E.g. "thread_stack".
2228 * @param mixed $default
2231 public static function getGlobalSetting($name, $default = NULL) {
2232 // Alternatively, SELECT @@GLOBAL.thread_stack, but
2233 // that has been reported to fail under MySQL 5.0 for OS X
2234 $escapedName = self
::escapeString($name);
2235 $dao = CRM_Core_DAO
::executeQuery("SHOW VARIABLES LIKE '$escapedName'");
2236 if ($dao->fetch()) {
2245 * Get options for the called BAO object's field.
2246 * This function can be overridden by each BAO to add more logic related to context.
2247 * The overriding function will generally call the lower-level CRM_Core_PseudoConstant::get
2249 * @param string $fieldName
2250 * @param string $context
2251 * @see CRM_Core_DAO::buildOptionsContext
2252 * @param array $props
2253 * whatever is known about this bao object.
2255 * @return array|bool
2257 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
2258 // If a given bao does not override this function
2259 $baoName = get_called_class();
2260 return CRM_Core_PseudoConstant
::get($baoName, $fieldName, array(), $context);
2264 * Populate option labels for this object's fields.
2266 * @throws exception if called directly on the base class
2268 public function getOptionLabels() {
2269 $fields = $this->fields();
2270 if ($fields === NULL) {
2271 throw new Exception('Cannot call getOptionLabels on CRM_Core_DAO');
2273 foreach ($fields as $field) {
2274 $name = CRM_Utils_Array
::value('name', $field);
2275 if ($name && isset($this->$name)) {
2276 $label = CRM_Core_PseudoConstant
::getLabel(get_class($this), $name, $this->$name);
2277 if ($label !== FALSE) {
2278 // Append 'label' onto the field name
2279 $labelName = $name . '_label';
2280 $this->$labelName = $label;
2287 * Provides documentation and validation for the buildOptions $context param
2289 * @param string $context
2294 public static function buildOptionsContext($context = NULL) {
2296 'get' => "get: all options are returned, even if they are disabled; labels are translated.",
2297 'create' => "create: options are filtered appropriately for the object being created/updated; labels are translated.",
2298 'search' => "search: searchable options are returned; labels are translated.",
2299 'validate' => "validate: all options are returned, even if they are disabled; machine names are used in place of labels.",
2300 'abbreviate' => "abbreviate: enabled options are returned; labels are replaced with abbreviations.",
2301 'match' => "match: enabled options are returned using machine names as keys; labels are translated.",
2303 // Validation: enforce uniformity of this param
2304 if ($context !== NULL && !isset($contexts[$context])) {
2305 throw new Exception("'$context' is not a valid context for buildOptions.");
2311 * @param string $fieldName
2312 * @return bool|array
2314 public function getFieldSpec($fieldName) {
2315 $fields = $this->fields();
2316 $fieldKeys = $this->fieldKeys();
2318 // Support "unique names" as well as sql names
2319 $fieldKey = $fieldName;
2320 if (empty($fields[$fieldKey])) {
2321 $fieldKey = CRM_Utils_Array
::value($fieldName, $fieldKeys);
2323 // If neither worked then this field doesn't exist. Return false.
2324 if (empty($fields[$fieldKey])) {
2327 return $fields[$fieldKey];
2331 * Get SQL where clause for SQL filter syntax input parameters.
2333 * SQL version of api function to assign filters to the DAO based on the syntax
2334 * $field => array('IN' => array(4,6,9))
2336 * $field => array('LIKE' => array('%me%))
2339 * @param string $fieldName
2341 * @param array $filter
2342 * filter to be applied indexed by operator.
2343 * @param string $type
2344 * type of field (not actually used - nor in api @todo ).
2345 * @param string $alias
2346 * alternative field name ('as') @todo- not actually used.
2347 * @param bool $returnSanitisedArray
2348 * Return a sanitised array instead of a clause.
2349 * this is primarily so we can add filters @ the api level to the Query object based fields
2353 * @return NULL|string|array
2354 * a string is returned if $returnSanitisedArray is not set, otherwise and Array or NULL
2355 * depending on whether it is supported as yet
2357 public static function createSQLFilter($fieldName, $filter, $type = NULL, $alias = NULL, $returnSanitisedArray = FALSE) {
2358 foreach ($filter as $operator => $criteria) {
2359 if (in_array($operator, self
::acceptedSQLOperators(), TRUE)) {
2360 switch ($operator) {
2364 if (!$returnSanitisedArray) {
2365 return (sprintf('%s %s', $fieldName, $operator));
2368 return (sprintf('%s %s ', $fieldName, $operator));
2372 // ternary operators
2375 if (empty($criteria[0]) ||
empty($criteria[1])) {
2376 throw new Exception("invalid criteria for $operator");
2378 if (!$returnSanitisedArray) {
2379 return (sprintf('%s ' . $operator . ' "%s" AND "%s"', $fieldName, CRM_Core_DAO
::escapeString($criteria[0]), CRM_Core_DAO
::escapeString($criteria[1])));
2382 return NULL; // not yet implemented (tests required to implement)
2389 if (empty($criteria)) {
2390 throw new Exception("invalid criteria for $operator");
2392 $escapedCriteria = array_map(array(
2396 if (!$returnSanitisedArray) {
2397 return (sprintf('%s %s ("%s")', $fieldName, $operator, implode('", "', $escapedCriteria)));
2399 return $escapedCriteria;
2404 if (!$returnSanitisedArray) {
2405 return (sprintf('%s %s "%s"', $fieldName, $operator, CRM_Core_DAO
::escapeString($criteria)));
2408 return NULL; // not yet implemented (tests required to implement)
2416 * @see http://issues.civicrm.org/jira/browse/CRM-9150
2417 * support for other syntaxes is discussed in ticket but being put off for now
2420 public static function acceptedSQLOperators() {
2441 * SQL has a limit of 64 characters on various names:
2442 * table name, trigger name, column name ...
2444 * For custom groups and fields we generated names from user entered input
2445 * which can be longer than this length, this function helps with creating
2446 * strings that meet various criteria.
2448 * @param string $string
2449 * The string to be shortened.
2450 * @param int $length
2451 * The max length of the string.
2453 * @param bool $makeRandom
2457 public static function shortenSQLName($string, $length = 60, $makeRandom = FALSE) {
2458 // early return for strings that meet the requirements
2459 if (strlen($string) <= $length) {
2463 // easy return for calls that dont need a randomized uniq string
2465 return substr($string, 0, $length);
2468 // the string is longer than the length and we need a uniq string
2469 // for the same tablename we need the same uniq string every time
2470 // hence we use md5 on the string, which is not random
2471 // we'll append 8 characters to the end of the tableName
2472 $md5string = substr(md5($string), 0, 8);
2473 return substr($string, 0, $length - 8) . "_{$md5string}";
2477 * https://issues.civicrm.org/jira/browse/CRM-17748
2478 * Sets the internal options to be used on a query
2480 * @param array $options
2483 public function setOptions($options) {
2484 if (is_array($options)) {
2485 $this->_options
= $options;
2490 * https://issues.civicrm.org/jira/browse/CRM-17748
2491 * wrapper to pass internal DAO options down to DB_mysql/DB_Common level
2493 * @param array $options
2496 protected function _setDBOptions($options) {
2497 global $_DB_DATAOBJECT;
2499 if (is_array($options) && count($options)) {
2500 $conn = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5
];
2501 foreach ($options as $option_name => $option_value) {
2502 $conn->setOption($option_name, $option_value);
2509 * @param array $params
2511 public function setApiFilter(&$params) {
2515 * Generates acl clauses suitable for adding to WHERE or ON when doing an api.get for this entity
2517 * Return format is in the form of fieldname => clauses starting with an operator. e.g.:
2520 * 'location_type_id' => array('IS NOT NULL', 'IN (1,2,3)')
2524 * Note that all array keys must be actual field names in this entity. Use subqueries to filter on other tables e.g. custom values.
2528 public function addSelectWhereClause() {
2529 // This is the default fallback, and works for contact-related entities like Email, Relationship, etc.
2531 foreach ($this->fields() as $fieldName => $field) {
2532 if (strpos($fieldName, 'contact_id') === 0 && CRM_Utils_Array
::value('FKClassName', $field) == 'CRM_Contact_DAO_Contact') {
2533 $clauses[$fieldName] = CRM_Utils_SQL
::mergeSubquery('Contact');
2536 CRM_Utils_Hook
::selectWhereClause($this, $clauses);
2541 * This returns the final permissioned query string for this entity
2543 * With acls from related entities + additional clauses from hook_civicrm_selectWhereClause
2545 * @param string $tableAlias
2548 public static function getSelectWhereClause($tableAlias = NULL) {
2549 $bao = new static();
2550 if ($tableAlias === NULL) {
2551 $tableAlias = $bao->tableName();
2554 foreach ((array) $bao->addSelectWhereClause() as $field => $vals) {
2555 $clauses[$field] = NULL;
2557 $clauses[$field] = "`$tableAlias`.`$field` " . implode(" AND `$tableAlias`.`$field` ", (array) $vals);