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 // special value for mail bulk inserts to avoid
58 // potential duplication, assuming a smaller number reduces number of queries
59 // by some factor, so some tradeoff. CRM-8678
60 BULK_MAIL_INSERT_COUNT
= 10,
61 QUERY_FORMAT_WILDCARD
= 1,
62 QUERY_FORMAT_NO_QUOTES
= 2;
65 * Define entities that shouldn't be created or deleted when creating/ deleting
66 * test objects - this prevents world regions, countries etc from being added / deleted
69 static $_testEntitiesToSkip = array();
71 * The factory class for this application.
74 static $_factory = NULL;
76 static $_checkedSqlFunctionsExist = FALSE;
81 * @return \CRM_Core_DAO
83 public function __construct() {
85 $this->__table
= $this->getTableName();
89 * Empty definition for virtual function.
91 public static function getTableName() {
96 * Initialize the DAO object.
99 * The database connection string.
101 public static function init($dsn) {
102 $options = &PEAR
::getStaticProperty('DB_DataObject', 'options');
103 $options['database'] = $dsn;
104 if (defined('CIVICRM_DAO_DEBUG')) {
105 self
::DebugLevel(CIVICRM_DAO_DEBUG
);
107 CRM_Core_DAO
::setFactory(new CRM_Contact_DAO_Factory());
108 if (CRM_Utils_Constant
::value('CIVICRM_MYSQL_STRICT', CRM_Utils_System
::isDevelopment())) {
109 CRM_Core_DAO
::executeQuery('SET SESSION sql_mode = STRICT_TRANS_TABLES');
114 * @param string $fieldName
116 * @param array $params
118 protected function assignTestFK($fieldName, $fieldDef, $params) {
119 $required = CRM_Utils_Array
::value('required', $fieldDef);
120 $FKClassName = CRM_Utils_Array
::value('FKClassName', $fieldDef);
121 $dbName = $fieldDef['name'];
122 $daoName = str_replace('_BAO_', '_DAO_', get_class($this));
124 // skip the FK if it is not required
125 // if it's contact id we should create even if not required
126 // we'll have a go @ fetching first though
127 // we WILL create campaigns though for so tests with a campaign pseudoconstant will complete
128 if ($FKClassName === 'CRM_Campaign_DAO_Campaign' && $daoName != $FKClassName) {
131 if (!$required && $dbName != 'contact_id') {
132 $fkDAO = new $FKClassName();
133 if ($fkDAO->find(TRUE)) {
134 $this->$dbName = $fkDAO->id
;
139 elseif (in_array($FKClassName, CRM_Core_DAO
::$_testEntitiesToSkip)) {
140 $depObject = new $FKClassName();
141 $depObject->find(TRUE);
142 $this->$dbName = $depObject->id
;
145 elseif ($daoName == 'CRM_Member_DAO_MembershipType' && $fieldName == 'member_of_contact_id') {
146 // FIXME: the fields() metadata is not specific enough
147 $depObject = CRM_Core_DAO
::createTestObject($FKClassName, array('contact_type' => 'Organization'));
148 $this->$dbName = $depObject->id
;
152 //if it is required we need to generate the dependency object first
153 $depObject = CRM_Core_DAO
::createTestObject($FKClassName, CRM_Utils_Array
::value($dbName, $params, 1));
154 $this->$dbName = $depObject->id
;
160 * Generate and assign an arbitrary value to a field of a test object.
162 * @param string $fieldName
163 * @param array $fieldDef
164 * @param int $counter
165 * The globally-unique ID of the test object.
167 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
168 $dbName = $fieldDef['name'];
169 $daoName = get_class($this);
172 if (!$handled && $dbName == 'contact_sub_type') {
173 //coming up with a rule to set this is too complex let's not set it
177 // Pick an option value if needed
178 if (!$handled && $fieldDef['type'] !== CRM_Utils_Type
::T_BOOLEAN
) {
179 $options = $daoName::buildOptions($dbName, 'create');
181 $this->$dbName = key($options);
187 switch ($fieldDef['type']) {
188 case CRM_Utils_Type
::T_INT
:
189 case CRM_Utils_Type
::T_FLOAT
:
190 case CRM_Utils_Type
::T_MONEY
:
191 if (isset($fieldDef['precision'])) {
192 // $object->$dbName = CRM_Utils_Number::createRandomDecimal($value['precision']);
193 $this->$dbName = CRM_Utils_Number
::createTruncatedDecimal($counter, $fieldDef['precision']);
196 $this->$dbName = $counter;
200 case CRM_Utils_Type
::T_BOOLEAN
:
201 if (isset($fieldDef['default'])) {
202 $this->$dbName = $fieldDef['default'];
204 elseif ($fieldDef['name'] == 'is_deleted' ||
$fieldDef['name'] == 'is_test') {
212 case CRM_Utils_Type
::T_DATE
:
213 case CRM_Utils_Type
::T_TIMESTAMP
:
214 case CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
:
215 $this->$dbName = '19700101';
216 if ($dbName == 'end_date') {
217 // put this in the future
218 $this->$dbName = '20200101';
222 case CRM_Utils_Type
::T_TIME
:
223 CRM_Core_Error
::fatal("T_TIME shouldn't be used.");
224 //$object->$dbName='000000';
226 case CRM_Utils_Type
::T_CCNUM
:
227 $this->$dbName = '4111 1111 1111 1111';
230 case CRM_Utils_Type
::T_URL
:
231 $this->$dbName = 'http://www.civicrm.org';
234 case CRM_Utils_Type
::T_STRING
:
235 case CRM_Utils_Type
::T_BLOB
:
236 case CRM_Utils_Type
::T_MEDIUMBLOB
:
237 case CRM_Utils_Type
::T_TEXT
:
238 case CRM_Utils_Type
::T_LONGTEXT
:
239 case CRM_Utils_Type
::T_EMAIL
:
241 // WAS: if (isset($value['enumValues'])) {
242 // TODO: see if this works with all pseudoconstants
243 if (isset($fieldDef['pseudoconstant'], $fieldDef['pseudoconstant']['callback'])) {
244 if (isset($fieldDef['default'])) {
245 $this->$dbName = $fieldDef['default'];
248 $options = CRM_Core_PseudoConstant
::get($daoName, $fieldName);
249 if (is_array($options)) {
250 $this->$dbName = $options[0];
253 $defaultValues = explode(',', $options);
254 $this->$dbName = $defaultValues[0];
259 $this->$dbName = $dbName . '_' . $counter;
260 $maxlength = CRM_Utils_Array
::value('maxlength', $fieldDef);
261 if ($maxlength > 0 && strlen($this->$dbName) > $maxlength) {
262 $this->$dbName = substr($this->$dbName, 0, $fieldDef['maxlength']);
270 * Reset the DAO object.
272 * DAO is kinda crappy in that there is an unwritten rule of one query per DAO.
274 * We attempt to get around this crappy restriction by resetting some of DAO's internal fields. Use this with caution
276 public function reset() {
278 foreach (array_keys($this->table()) as $field) {
279 unset($this->$field);
283 * reset the various DB_DAO structures manually
285 $this->_query
= array();
292 * @param string $tableName
296 public static function getLocaleTableName($tableName) {
299 $tables = CRM_Core_I18n_Schema
::schemaStructureTables();
300 if (in_array($tableName, $tables)) {
301 return $tableName . $dbLocale;
308 * Execute a query by the current DAO, localizing it along the way (if needed).
310 * @param string $query
311 * The SQL query for execution.
312 * @param bool $i18nRewrite
313 * Whether to rewrite the query.
316 * the current DAO object after the query execution
318 public function query($query, $i18nRewrite = TRUE) {
319 // rewrite queries that should use $dbLocale-based views for multi-language installs
321 if ($i18nRewrite and $dbLocale) {
322 $query = CRM_Core_I18n_Schema
::rewriteQuery($query);
325 return parent
::query($query);
329 * Static function to set the factory instance for this class.
331 * @param object $factory
332 * The factory application object.
334 public static function setFactory(&$factory) {
335 self
::$_factory = &$factory;
339 * Factory method to instantiate a new object from a table name.
341 * @param string $table
343 public function factory($table = '') {
344 if (!isset(self
::$_factory)) {
345 return parent
::factory($table);
348 return self
::$_factory->create($table);
352 * Initialization for all DAO objects. Since we access DB_DO programatically
353 * we need to set the links manually.
355 public function initialize() {
357 $this->query("SET NAMES utf8");
361 * Defines the default key as 'id'.
366 public function keys() {
375 * Tells DB_DataObject which keys use autoincrement.
376 * 'id' is autoincrementing by default.
381 public function sequenceKey() {
382 static $sequenceKeys;
383 if (!isset($sequenceKeys)) {
384 $sequenceKeys = array('id', TRUE);
386 return $sequenceKeys;
390 * Returns list of FK relationships.
394 * Array of CRM_Core_Reference_Interface
396 public static function getReferenceColumns() {
401 * Returns all the column names of this table.
406 public static function &fields() {
412 * Get/set an associative array of table columns
417 public function table() {
418 $fields = &$this->fields();
422 foreach ($fields as $name => $value) {
423 $table[$value['name']] = $value['type'];
424 if (!empty($value['required'])) {
425 $table[$value['name']] +
= self
::DB_DAO_NOTNULL
;
436 public function save($hook = TRUE) {
437 if (!empty($this->id
)) {
441 $event = new \Civi\Core\DAO\Event\
PostUpdate($this);
442 \Civi
::service('dispatcher')->dispatch("DAO::post-update", $event);
449 $event = new \Civi\Core\DAO\Event\
PostUpdate($this);
450 \Civi
::service('dispatcher')->dispatch("DAO::post-insert", $event);
456 CRM_Utils_Hook
::postSave($this);
463 * Deletes items from table which match current objects variables.
465 * Returns the true on success
469 * Designed to be extended
471 * $object = new mytable();
473 * echo $object->delete(); // builds a conditon
475 * $object = new mytable();
476 * $object->whereAdd('age > 12');
478 * $object->orderBy('age DESC');
479 * $object->delete(true); // dont use object vars, use the conditions, limit and order.
481 * @param bool $useWhere (optional) If DB_DATAOBJECT_WHEREADD_ONLY is passed in then
482 * we will build the condition only using the whereAdd's. Default is to
483 * build the condition only using the object parameters.
485 * * @return mixed Int (No. of rows affected) on success, false on failure, 0 on no data affected
487 public function delete($useWhere = FALSE) {
488 $result = parent
::delete($useWhere);
490 $event = new \Civi\Core\DAO\Event\
PostDelete($this, $result);
491 \Civi
::service('dispatcher')->dispatch("DAO::post-delete", $event);
497 * @param bool $created
499 public function log($created = FALSE) {
502 if (!$this->getLog()) {
507 $session = CRM_Core_Session
::singleton();
508 $cid = $session->get('userID');
511 // return is we dont have handle to FK
516 $dao = new CRM_Core_DAO_Log();
517 $dao->entity_table
= $this->getTableName();
518 $dao->entity_id
= $this->id
;
519 $dao->modified_id
= $cid;
520 $dao->modified_date
= date("YmdHis");
525 * Given an associative array of name/value pairs, extract all the values
526 * that belong to this object and initialize the object with said values
528 * @param array $params
529 * (reference ) associative array of name/value pairs.
532 * Did we copy all null values into the object
534 public function copyValues(&$params) {
535 $fields = &$this->fields();
537 foreach ($fields as $name => $value) {
538 $dbName = $value['name'];
539 if (array_key_exists($dbName, $params)) {
540 $pValue = $params[$dbName];
543 elseif (array_key_exists($name, $params)) {
544 $pValue = $params[$name];
551 // if there is no value then make the variable NULL
553 if ($pValue === '') {
554 $this->$dbName = 'null';
557 $this->$dbName = $pValue;
566 * Store all the values from this object in an associative array
567 * this is a destructive store, calling function is responsible
568 * for keeping sanity of id's.
570 * @param object $object
571 * The object that we are extracting data from.
572 * @param array $values
573 * (reference ) associative array of name/value pairs.
575 public static function storeValues(&$object, &$values) {
576 $fields = &$object->fields();
577 foreach ($fields as $name => $value) {
578 $dbName = $value['name'];
579 if (isset($object->$dbName) && $object->$dbName !== 'null') {
580 $values[$dbName] = $object->$dbName;
581 if ($name != $dbName) {
582 $values[$name] = $object->$dbName;
589 * Create an attribute for this specific field. We only do this for strings and text
591 * @param array $field
592 * The field under task.
595 * the attributes for the object
597 public static function makeAttribute($field) {
599 if (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_STRING
) {
600 $maxLength = CRM_Utils_Array
::value('maxlength', $field);
601 $size = CRM_Utils_Array
::value('size', $field);
602 if ($maxLength ||
$size) {
603 $attributes = array();
605 $attributes['maxlength'] = $maxLength;
608 $attributes['size'] = $size;
613 elseif (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_TEXT
) {
614 $rows = CRM_Utils_Array
::value('rows', $field);
618 $cols = CRM_Utils_Array
::value('cols', $field);
623 $attributes = array();
624 $attributes['rows'] = $rows;
625 $attributes['cols'] = $cols;
628 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
) {
629 $attributes['size'] = 6;
630 $attributes['maxlength'] = 14;
638 * Get the size and maxLength attributes for this text field.
639 * (or for all text fields) in the DAO object.
641 * @param string $class
643 * @param string $fieldName
644 * Field that i'm interested in or null if.
645 * you want the attributes for all DAO text fields
648 * assoc array of name => attribute pairs
650 public static function getAttribute($class, $fieldName = NULL) {
651 $object = new $class();
652 $fields = &$object->fields();
653 if ($fieldName != NULL) {
654 $field = CRM_Utils_Array
::value($fieldName, $fields);
655 return self
::makeAttribute($field);
658 $attributes = array();
659 foreach ($fields as $name => $field) {
660 $attribute = self
::makeAttribute($field);
662 $attributes[$name] = $attribute;
666 if (!empty($attributes)) {
678 public static function transaction($type) {
679 CRM_Core_Error
::fatal('This function is obsolete, please use CRM_Core_Transaction');
683 * Check if there is a record with the same name in the db.
685 * @param string $value
686 * The value of the field we are checking.
687 * @param string $daoName
688 * The dao object name.
689 * @param string $daoID
690 * The id of the object being updated. u can change your name.
691 * as long as there is no conflict
692 * @param string $fieldName
693 * The name of the field in the DAO.
696 * true if object exists
698 public static function objectExists($value, $daoName, $daoID, $fieldName = 'name') {
699 $object = new $daoName();
700 $object->$fieldName = $value;
702 $config = CRM_Core_Config
::singleton();
704 if ($object->find(TRUE)) {
705 return ($daoID && $object->id
== $daoID) ?
TRUE : FALSE;
713 * Check if there is a given column in a specific table.
715 * @param string $tableName
716 * @param string $columnName
717 * @param bool $i18nRewrite
718 * Whether to rewrite the query on multilingual setups.
721 * true if exists, else false
723 public static function checkFieldExists($tableName, $columnName, $i18nRewrite = TRUE) {
729 $params = array(1 => array($columnName, 'String'));
730 $dao = CRM_Core_DAO
::executeQuery($query, $params, TRUE, NULL, FALSE, $i18nRewrite);
731 $result = $dao->fetch() ?
TRUE : FALSE;
737 * Returns the storage engine used by given table-name(optional).
738 * Otherwise scans all the tables and return an array of all the
739 * distinct storage engines being used.
741 * @param string $tableName
743 * @param int $maxTablesToCheck
744 * @param string $fieldName
748 public static function getStorageValues($tableName = NULL, $maxTablesToCheck = 10, $fieldName = 'Engine') {
750 $query = "SHOW TABLE STATUS LIKE %1";
754 if (isset($tableName)) {
755 $params = array(1 => array($tableName, 'String'));
758 $params = array(1 => array('civicrm_%', 'String'));
761 $dao = CRM_Core_DAO
::executeQuery($query, $params);
764 while ($dao->fetch()) {
765 if (isset($values[$dao->$fieldName]) ||
766 // ignore import and other temp tables
767 strpos($dao->Name
, 'civicrm_import_job_') !== FALSE ||
768 strpos($dao->Name
, '_temp') !== FALSE
772 $values[$dao->$fieldName] = 1;
774 if ($maxTablesToCheck &&
775 $count >= $maxTablesToCheck
785 * @param int $maxTablesToCheck
789 public static function isDBMyISAM($maxTablesToCheck = 10) {
790 // show error if any of the tables, use 'MyISAM' storage engine.
791 $engines = self
::getStorageValues(NULL, $maxTablesToCheck);
792 if (array_key_exists('MyISAM', $engines)) {
799 * Checks if a constraint exists for a specified table.
801 * @param string $tableName
802 * @param string $constraint
805 * true if constraint exists, false otherwise
807 public static function checkConstraintExists($tableName, $constraint) {
808 static $show = array();
810 if (!array_key_exists($tableName, $show)) {
811 $query = "SHOW CREATE TABLE $tableName";
812 $dao = CRM_Core_DAO
::executeQuery($query);
814 if (!$dao->fetch()) {
815 CRM_Core_Error
::fatal();
819 $show[$tableName] = $dao->Create_Table
;
822 return preg_match("/\b$constraint\b/i", $show[$tableName]) ?
TRUE : FALSE;
826 * Checks if CONSTRAINT keyword exists for a specified table.
828 * @param array $tables
833 * true if CONSTRAINT keyword exists, false otherwise
835 public static function schemaRequiresRebuilding($tables = array("civicrm_contact")) {
837 foreach ($tables as $tableName) {
838 if (!array_key_exists($tableName, $show)) {
839 $query = "SHOW CREATE TABLE $tableName";
840 $dao = CRM_Core_DAO
::executeQuery($query);
842 if (!$dao->fetch()) {
843 CRM_Core_Error
::fatal();
847 $show[$tableName] = $dao->Create_Table
;
850 $result = preg_match("/\bCONSTRAINT\b\s/i", $show[$tableName]) ?
TRUE : FALSE;
851 if ($result == TRUE) {
862 * Checks if the FK constraint name is in the format 'FK_tableName_columnName'
863 * for a specified column of a table.
865 * @param string $tableName
866 * @param string $columnName
869 * true if in format, false otherwise
871 public static function checkFKConstraintInFormat($tableName, $columnName) {
872 static $show = array();
874 if (!array_key_exists($tableName, $show)) {
875 $query = "SHOW CREATE TABLE $tableName";
876 $dao = CRM_Core_DAO
::executeQuery($query);
878 if (!$dao->fetch()) {
879 CRM_Core_Error
::fatal();
883 $show[$tableName] = $dao->Create_Table
;
885 $constraint = "`FK_{$tableName}_{$columnName}`";
886 $pattern = "/\bCONSTRAINT\b\s+%s\s+\bFOREIGN\s+KEY\b\s/i";
887 return preg_match(sprintf($pattern, $constraint), $show[$tableName]) ?
TRUE : FALSE;
891 * Check whether a specific column in a specific table has always the same value.
893 * @param string $tableName
894 * @param string $columnName
895 * @param string $columnValue
898 * true if the value is always $columnValue, false otherwise
900 public static function checkFieldHasAlwaysValue($tableName, $columnName, $columnValue) {
901 $query = "SELECT * FROM $tableName WHERE $columnName != '$columnValue'";
902 $dao = CRM_Core_DAO
::executeQuery($query);
903 $result = $dao->fetch() ?
FALSE : TRUE;
909 * Check whether a specific column in a specific table is always NULL.
911 * @param string $tableName
912 * @param string $columnName
915 * true if if the value is always NULL, false otherwise
917 public static function checkFieldIsAlwaysNull($tableName, $columnName) {
918 $query = "SELECT * FROM $tableName WHERE $columnName IS NOT NULL";
919 $dao = CRM_Core_DAO
::executeQuery($query);
920 $result = $dao->fetch() ?
FALSE : TRUE;
926 * Check if there is a given table in the database.
928 * @param string $tableName
931 * true if exists, else false
933 public static function checkTableExists($tableName) {
938 $params = array(1 => array($tableName, 'String'));
940 $dao = CRM_Core_DAO
::executeQuery($query, $params);
941 $result = $dao->fetch() ?
TRUE : FALSE;
951 public function checkVersion($version) {
956 $dbVersion = CRM_Core_DAO
::singleValueQuery($query);
957 return trim($version) == trim($dbVersion) ?
TRUE : FALSE;
961 * Find a DAO object for the given ID and return it.
964 * Id of the DAO object being searched for.
967 * Object of the type of the class that called this function.
969 public static function findById($id) {
970 $object = new static();
972 if (!$object->find(TRUE)) {
973 throw new Exception("Unable to find a " . get_called_class() . " with id {$id}.");
979 * Returns all results as array-encoded records.
983 public function fetchAll() {
985 while ($this->fetch()) {
986 $result[] = $this->toArray();
992 * Given a DAO name, a column name and a column value, find the record and GET the value of another column in that record
994 * @param string $daoName
995 * Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact).
996 * @param int $searchValue
997 * Value of the column you want to search by.
998 * @param string $returnColumn
999 * Name of the column you want to GET the value of.
1000 * @param string $searchColumn
1001 * Name of the column you want to search by.
1002 * @param bool $force
1003 * Skip use of the cache.
1005 * @return string|null
1006 * Value of $returnColumn in the retrieved record
1008 public static function getFieldValue($daoName, $searchValue, $returnColumn = 'name', $searchColumn = 'id', $force = FALSE) {
1010 empty($searchValue) ||
1011 trim(strtolower($searchValue)) == 'null'
1013 // adding this year since developers forget to check for an id
1014 // or for the 'null' (which is a bad DAO kludge)
1015 // and hence we get the first value in the db
1016 CRM_Core_Error
::fatal();
1019 $cacheKey = "{$daoName}:{$searchValue}:{$returnColumn}:{$searchColumn}";
1020 if (self
::$_dbColumnValueCache === NULL) {
1021 self
::$_dbColumnValueCache = array();
1024 if (!array_key_exists($cacheKey, self
::$_dbColumnValueCache) ||
$force) {
1025 $object = new $daoName();
1026 $object->$searchColumn = $searchValue;
1027 $object->selectAdd();
1028 $object->selectAdd($returnColumn);
1031 if ($object->find(TRUE)) {
1032 $result = $object->$returnColumn;
1036 self
::$_dbColumnValueCache[$cacheKey] = $result;
1038 return self
::$_dbColumnValueCache[$cacheKey];
1042 * Given a DAO name, a column name and a column value, find the record and SET the value of another column in that record
1044 * @param string $daoName
1045 * Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact).
1046 * @param int $searchValue
1047 * Value of the column you want to search by.
1048 * @param string $setColumn
1049 * Name of the column you want to SET the value of.
1050 * @param string $setValue
1051 * SET the setColumn to this value.
1052 * @param string $searchColumn
1053 * Name of the column you want to search by.
1056 * true if we found and updated the object, else false
1058 public static function setFieldValue($daoName, $searchValue, $setColumn, $setValue, $searchColumn = 'id') {
1059 $object = new $daoName();
1060 $object->selectAdd();
1061 $object->selectAdd("$searchColumn, $setColumn");
1062 $object->$searchColumn = $searchValue;
1064 if ($object->find(TRUE)) {
1065 $object->$setColumn = $setValue;
1066 if ($object->save()) {
1077 * @param array|object $sort either array or CRM_Utils_Sort
1078 * @param string $default
1079 * Default sort value.
1084 public static function getSortString($sort, $default = NULL) {
1085 // check if sort is of type CRM_Utils_Sort
1086 if (is_a($sort, 'CRM_Utils_Sort')) {
1087 return $sort->orderBy();
1090 // is it an array specified as $field => $sortDirection ?
1092 foreach ($sort as $k => $v) {
1093 $sortString .= "$k $v,";
1095 return rtrim($sortString, ',');
1101 * Fetch object based on array of properties.
1103 * @param string $daoName
1104 * Name of the dao object.
1105 * @param array $params
1106 * (reference ) an assoc array of name/value pairs.
1107 * @param array $defaults
1108 * (reference ) an assoc array to hold the flattened values.
1109 * @param array $returnProperities
1110 * An assoc array of fields that need to be returned, eg array( 'first_name', 'last_name').
1113 * an object of type referenced by daoName
1115 public static function commonRetrieve($daoName, &$params, &$defaults, $returnProperities = NULL) {
1116 $object = new $daoName();
1117 $object->copyValues($params);
1119 // return only specific fields if returnproperties are sent
1120 if (!empty($returnProperities)) {
1121 $object->selectAdd();
1122 $object->selectAdd(implode(',', $returnProperities));
1125 if ($object->find(TRUE)) {
1126 self
::storeValues($object, $defaults);
1133 * Delete the object records that are associated with this contact.
1135 * @param string $daoName
1136 * Name of the dao object.
1137 * @param int $contactId
1138 * Id of the contact to delete.
1140 public static function deleteEntityContact($daoName, $contactId) {
1141 $object = new $daoName();
1143 $object->entity_table
= 'civicrm_contact';
1144 $object->entity_id
= $contactId;
1151 * @param string $query
1152 * Query to be executed.
1154 * @param array $params
1155 * @param bool $abort
1156 * @param null $daoName
1157 * @param bool $freeDAO
1158 * @param bool $i18nRewrite
1159 * @param bool $trapException
1161 * @return CRM_Core_DAO|object
1162 * object that holds the results of the query
1163 * NB - if this is defined as just returning a DAO phpstorm keeps pointing
1164 * out all the properties that are not part of the DAO
1166 public static function &executeQuery(
1172 $i18nRewrite = TRUE,
1173 $trapException = FALSE
1175 $queryStr = self
::composeQuery($query, $params, $abort);
1178 $dao = new CRM_Core_DAO();
1181 $dao = new $daoName();
1184 if ($trapException) {
1185 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
1188 $result = $dao->query($queryStr, $i18nRewrite);
1190 if (is_a($result, 'DB_Error')) {
1195 preg_match('/^(insert|update|delete|create|drop|replace)/i', $queryStr)
1197 // we typically do this for insert/update/delete statements OR if explicitly asked to
1205 * Execute a query and get the single result.
1207 * @param string $query
1208 * Query to be executed.
1209 * @param array $params
1210 * @param bool $abort
1211 * @param bool $i18nRewrite
1212 * @return string|null
1213 * the result of the query if any
1216 public static function &singleValueQuery(
1222 $queryStr = self
::composeQuery($query, $params, $abort);
1224 static $_dao = NULL;
1227 $_dao = new CRM_Core_DAO();
1230 $_dao->query($queryStr, $i18nRewrite);
1232 $result = $_dao->getDatabaseResult();
1235 $row = $result->fetchRow();
1246 * @param array $params
1247 * @param bool $abort
1252 public static function composeQuery($query, &$params, $abort = TRUE) {
1254 foreach ($params as $key => $item) {
1255 if (is_numeric($key)) {
1256 if (CRM_Utils_Type
::validate($item[0], $item[1]) !== NULL) {
1257 $item[0] = self
::escapeString($item[0]);
1258 if ($item[1] == 'String' ||
1259 $item[1] == 'Memo' ||
1262 // Support class constants stipulating wildcard characters and/or
1263 // non-quoting of strings. Also support legacy code which may be
1264 // passing in TRUE or 1 for $item[2], which used to indicate the
1265 // use of wildcard characters.
1266 if (!empty($item[2])) {
1267 if ($item[2] & CRM_Core_DAO
::QUERY_FORMAT_WILDCARD ||
$item[2] === TRUE) {
1268 $item[0] = "'%{$item[0]}%'";
1270 elseif (!($item[2] & CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
)) {
1271 $item[0] = "'{$item[0]}'";
1275 $item[0] = "'{$item[0]}'";
1279 if (($item[1] == 'Date' ||
$item[1] == 'Timestamp') &&
1280 strlen($item[0]) == 0
1285 $tr['%' . $key] = $item[0];
1288 CRM_Core_Error
::fatal("{$item[0]} is not of type {$item[1]}");
1293 return strtr($query, $tr);
1299 public static function freeResult($ids = NULL) {
1300 global $_DB_DATAOBJECT;
1303 if (!$_DB_DATAOBJECT ||
1304 !isset($_DB_DATAOBJECT['RESULTS'])
1308 $ids = array_keys($_DB_DATAOBJECT['RESULTS']);
1311 foreach ($ids as $id) {
1312 if (isset($_DB_DATAOBJECT['RESULTS'][$id])) {
1313 if (is_resource($_DB_DATAOBJECT['RESULTS'][$id]->result
)) {
1314 mysql_free_result($_DB_DATAOBJECT['RESULTS'][$id]->result
);
1316 unset($_DB_DATAOBJECT['RESULTS'][$id]);
1319 if (isset($_DB_DATAOBJECT['RESULTFIELDS'][$id])) {
1320 unset($_DB_DATAOBJECT['RESULTFIELDS'][$id]);
1326 * make a shallow copy of an object.
1327 * and all the fields in the object
1329 * @param string $daoName
1331 * @param array $criteria
1332 * Array of all the fields & values.
1333 * on which basis to copy
1334 * @param array $newData
1335 * Array of all the fields & values.
1336 * to be copied besides the other fields
1337 * @param string $fieldsFix
1338 * Array of fields that you want to prefix/suffix/replace.
1339 * @param string $blockCopyOfDependencies
1340 * Fields that you want to block from.
1344 * @return CRM_Core_DAO
1345 * the newly created copy of the object
1347 public static function ©Generic($daoName, $criteria, $newData = NULL, $fieldsFix = NULL, $blockCopyOfDependencies = NULL) {
1348 $object = new $daoName();
1350 $object->id
= $criteria['id'];
1353 foreach ($criteria as $key => $value) {
1354 $object->$key = $value;
1359 while ($object->fetch()) {
1361 // all the objects except with $blockCopyOfDependencies set
1362 // be copied - addresses #CRM-1962
1364 if ($blockCopyOfDependencies && $object->$blockCopyOfDependencies) {
1368 $newObject = new $daoName();
1370 $fields = &$object->fields();
1371 if (!is_array($fieldsFix)) {
1372 $fieldsToPrefix = array();
1373 $fieldsToSuffix = array();
1374 $fieldsToReplace = array();
1376 if (!empty($fieldsFix['prefix'])) {
1377 $fieldsToPrefix = $fieldsFix['prefix'];
1379 if (!empty($fieldsFix['suffix'])) {
1380 $fieldsToSuffix = $fieldsFix['suffix'];
1382 if (!empty($fieldsFix['replace'])) {
1383 $fieldsToReplace = $fieldsFix['replace'];
1386 foreach ($fields as $name => $value) {
1387 if ($name == 'id' ||
$value['name'] == 'id') {
1388 // copy everything but the id!
1392 $dbName = $value['name'];
1393 $type = CRM_Utils_Type
::typeToString($value['type']);
1394 $newObject->$dbName = $object->$dbName;
1395 if (isset($fieldsToPrefix[$dbName])) {
1396 $newObject->$dbName = $fieldsToPrefix[$dbName] . $newObject->$dbName;
1398 if (isset($fieldsToSuffix[$dbName])) {
1399 $newObject->$dbName .= $fieldsToSuffix[$dbName];
1401 if (isset($fieldsToReplace[$dbName])) {
1402 $newObject->$dbName = $fieldsToReplace[$dbName];
1405 if ($type == 'Timestamp' ||
$type == 'Date') {
1406 $newObject->$dbName = CRM_Utils_Date
::isoToMysql($newObject->$dbName);
1410 foreach ($newData as $k => $v) {
1411 $newObject->$k = $v;
1421 * Cascade update through related entities.
1423 * @param string $daoName
1426 * @param array $newData
1430 public static function cascadeUpdate($daoName, $fromId, $toId, $newData = array()) {
1431 $object = new $daoName();
1432 $object->id
= $fromId;
1434 if ($object->find(TRUE)) {
1435 $newObject = new $daoName();
1436 $newObject->id
= $toId;
1438 if ($newObject->find(TRUE)) {
1439 $fields = &$object->fields();
1440 foreach ($fields as $name => $value) {
1441 if ($name == 'id' ||
$value['name'] == 'id') {
1442 // copy everything but the id!
1446 $colName = $value['name'];
1447 $newObject->$colName = $object->$colName;
1449 if (substr($name, -5) == '_date' ||
1450 substr($name, -10) == '_date_time'
1452 $newObject->$colName = CRM_Utils_Date
::isoToMysql($newObject->$colName);
1455 foreach ($newData as $k => $v) {
1456 $newObject->$k = $v;
1462 return CRM_Core_DAO
::$_nullObject;
1466 * Given the component id, compute the contact id
1467 * since its used for things like send email
1469 * @param $componentIDs
1470 * @param string $tableName
1474 public static function &getContactIDsFromComponent(&$componentIDs, $tableName) {
1475 $contactIDs = array();
1477 if (empty($componentIDs)) {
1481 $IDs = implode(',', $componentIDs);
1485 WHERE id IN ( $IDs )
1488 $dao = CRM_Core_DAO
::executeQuery($query);
1489 while ($dao->fetch()) {
1490 $contactIDs[] = $dao->contact_id
;
1496 * Fetch object based on array of properties.
1498 * @param string $daoName
1499 * Name of the dao object.
1500 * @param string $fieldIdName
1501 * @param int $fieldId
1503 * @param array $returnProperities
1504 * An assoc array of fields that need to be returned, eg array( 'first_name', 'last_name').
1507 * an object of type referenced by daoName
1509 public static function commonRetrieveAll($daoName, $fieldIdName = 'id', $fieldId, &$details, $returnProperities = NULL) {
1510 require_once str_replace('_', DIRECTORY_SEPARATOR
, $daoName) . ".php";
1511 $object = new $daoName();
1512 $object->$fieldIdName = $fieldId;
1514 // return only specific fields if returnproperties are sent
1515 if (!empty($returnProperities)) {
1516 $object->selectAdd();
1517 $object->selectAdd('id');
1518 $object->selectAdd(implode(',', $returnProperities));
1522 while ($object->fetch()) {
1523 $defaults = array();
1524 self
::storeValues($object, $defaults);
1525 $details[$object->id
] = $defaults;
1531 public static function dropAllTables() {
1533 // first drop all the custom tables we've created
1534 CRM_Core_BAO_CustomGroup
::dropAllTables();
1536 // drop all multilingual views
1537 CRM_Core_I18n_Schema
::dropAllViews();
1539 CRM_Utils_File
::sourceSQLFile(CIVICRM_DSN
,
1540 dirname(__FILE__
) . DIRECTORY_SEPARATOR
.
1541 '..' . DIRECTORY_SEPARATOR
.
1542 '..' . DIRECTORY_SEPARATOR
.
1543 'sql' . DIRECTORY_SEPARATOR
.
1544 'civicrm_drop.mysql'
1553 public static function escapeString($string) {
1554 static $_dao = NULL;
1557 // If this is an atypical case (e.g. preparing .sql files
1558 // before Civi has been installed), then we fallback to
1559 // DB-less escaping helper (mysql_real_escape_string).
1560 // Note: In typical usage, escapeString() will only
1561 // check one conditional ("if !$_dao") rather than
1562 // two conditionals ("if !defined(DSN)")
1563 if (!defined('CIVICRM_DSN')) {
1564 if (function_exists('mysql_real_escape_string')) {
1565 return mysql_real_escape_string($string);
1568 throw new CRM_Core_Exception("Cannot generate SQL. \"mysql_real_escape_string\" is missing. Have you installed PHP \"mysql\" extension?");
1572 $_dao = new CRM_Core_DAO();
1575 return $_dao->escape($string);
1579 * Escape a list of strings for use with "WHERE X IN (...)" queries.
1581 * @param array $strings
1582 * @param string $default
1583 * the value to use if $strings has no elements.
1585 * eg "abc","def","ghi"
1587 public static function escapeStrings($strings, $default = NULL) {
1588 static $_dao = NULL;
1590 $_dao = new CRM_Core_DAO();
1593 if (empty($strings)) {
1597 $escapes = array_map(array($_dao, 'escape'), $strings);
1598 return '"' . implode('","', $escapes) . '"';
1606 public static function escapeWildCardString($string) {
1608 // ensure we escape the single characters % and _ which are mysql wild
1609 // card characters and could come in via sortByCharacter
1610 // note that mysql does not escape these characters
1611 if ($string && in_array($string,
1612 array('%', '_', '%%', '_%')
1615 return '\\' . $string;
1618 return self
::escapeString($string);
1622 * Creates a test object, including any required objects it needs via recursion
1623 * createOnly: only create in database, do not store or return the objects (useful for perf testing)
1624 * ONLY USE FOR TESTING
1626 * @param string $daoName
1627 * @param array $params
1628 * @param int $numObjects
1629 * @param bool $createOnly
1631 * @return object|array|NULL
1632 * NULL if $createOnly. A single object if $numObjects==1. Otherwise, an array of multiple objects.
1634 public static function createTestObject(
1640 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
1641 // so we re-set here in case
1642 $config = CRM_Core_Config
::singleton();
1643 $config->backtrace
= TRUE;
1645 static $counter = 0;
1646 CRM_Core_DAO
::$_testEntitiesToSkip = array(
1647 'CRM_Core_DAO_Worldregion',
1648 'CRM_Core_DAO_StateProvince',
1649 'CRM_Core_DAO_Country',
1650 'CRM_Core_DAO_Domain',
1651 'CRM_Financial_DAO_FinancialType',
1652 //because valid ones exist & we use pick them due to pseudoconstant can't reliably create & delete these
1655 // Prefer to instantiate BAO's instead of DAO's (when possible)
1656 // so that assignTestValue()/assignTestFK() can be overloaded.
1657 $baoName = str_replace('_DAO_', '_BAO_', $daoName);
1658 if (class_exists($baoName)) {
1659 $daoName = $baoName;
1662 for ($i = 0; $i < $numObjects; ++
$i) {
1665 /** @var CRM_Core_DAO $object */
1666 $object = new $daoName();
1668 $fields = &$object->fields();
1669 foreach ($fields as $fieldName => $fieldDef) {
1670 $dbName = $fieldDef['name'];
1671 $FKClassName = CRM_Utils_Array
::value('FKClassName', $fieldDef);
1672 $required = CRM_Utils_Array
::value('required', $fieldDef);
1674 if (CRM_Utils_Array
::value($dbName, $params) !== NULL && !is_array($params[$dbName])) {
1675 $object->$dbName = $params[$dbName];
1678 elseif ($dbName != 'id') {
1679 if ($FKClassName != NULL) {
1680 $object->assignTestFK($fieldName, $fieldDef, $params);
1684 $object->assignTestValue($fieldName, $fieldDef, $counter);
1692 $objects[$i] = $object;
1702 elseif ($numObjects == 1) {
1711 * Deletes the this object plus any dependent objects that are associated with it.
1712 * ONLY USE FOR TESTING
1714 * @param string $daoName
1715 * @param array $params
1717 public static function deleteTestObjects($daoName, $params = array()) {
1718 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
1719 // so we re-set here in case
1720 $config = CRM_Core_Config
::singleton();
1721 $config->backtrace
= TRUE;
1723 $object = new $daoName();
1724 $object->id
= CRM_Utils_Array
::value('id', $params);
1726 $deletions = array(); // array(array(0 => $daoName, 1 => $daoParams))
1727 if ($object->find(TRUE)) {
1729 $fields = &$object->fields();
1730 foreach ($fields as $name => $value) {
1732 $dbName = $value['name'];
1734 $FKClassName = CRM_Utils_Array
::value('FKClassName', $value);
1735 $required = CRM_Utils_Array
::value('required', $value);
1736 if ($FKClassName != NULL
1738 && !in_array($FKClassName, CRM_Core_DAO
::$_testEntitiesToSkip)
1739 && ($required ||
$dbName == 'contact_id')
1740 //I'm a bit stuck on this one - we might need to change the singleValueAlter so that the entities don't share a contact
1741 // to make this test process pass - line below makes pass for now
1742 && $dbName != 'member_of_contact_id'
1744 $deletions[] = array($FKClassName, array('id' => $object->$dbName)); // x
1751 foreach ($deletions as $deletion) {
1752 CRM_Core_DAO
::deleteTestObjects($deletion[0], $deletion[1]);
1757 * Set defaults when creating new entity.
1758 * (don't call this set defaults as already in use with different signature in some places)
1760 * @param array $params
1763 public static function setCreateDefaults(&$params, $defaults) {
1764 if (isset($params['id'])) {
1767 foreach ($defaults as $key => $value) {
1768 if (!array_key_exists($key, $params) ||
$params[$key] === NULL) {
1769 $params[$key] = $value;
1775 * @param string $prefix
1776 * @param bool $addRandomString
1777 * @param null $string
1781 public static function createTempTableName($prefix = 'civicrm', $addRandomString = TRUE, $string = NULL) {
1782 $tableName = $prefix . "_temp";
1784 if ($addRandomString) {
1786 $tableName .= "_" . $string;
1789 $tableName .= "_" . md5(uniqid('', TRUE));
1797 * @param bool $trigger
1801 public static function checkTriggerViewPermission($view = TRUE, $trigger = TRUE) {
1802 // test for create view and trigger permissions and if allowed, add the option to go multilingual
1804 // I'm not sure why we use the getStaticProperty for an error, rather than checking for DB_Error
1805 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
1806 $dao = new CRM_Core_DAO();
1808 $dao->query('CREATE OR REPLACE VIEW civicrm_domain_view AS SELECT * FROM civicrm_domain');
1809 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
1815 $result = $dao->query('CREATE TRIGGER civicrm_domain_trigger BEFORE INSERT ON civicrm_domain FOR EACH ROW BEGIN END');
1816 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError') ||
is_a($result, 'DB_Error')) {
1818 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1823 $dao->query('DROP TRIGGER IF EXISTS civicrm_domain_trigger');
1824 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
1826 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1833 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1834 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
1843 * @param null $message
1844 * @param bool $printDAO
1846 public static function debugPrint($message = NULL, $printDAO = TRUE) {
1847 CRM_Utils_System
::xMemory("{$message}: ");
1850 global $_DB_DATAOBJECT;
1852 foreach (array_keys($_DB_DATAOBJECT['RESULTS']) as $id) {
1853 $q[] = $_DB_DATAOBJECT['RESULTS'][$id]->query
;
1855 CRM_Core_Error
::debug('_DB_DATAOBJECT', $q);
1860 * Build a list of triggers via hook and add them to (err, reconcile them
1861 * with) the database.
1863 * @param string $tableName
1864 * the specific table requiring a rebuild; or NULL to rebuild all tables.
1865 * @param bool $force
1869 public static function triggerRebuild($tableName = NULL, $force = FALSE) {
1872 $logging = new CRM_Logging_Schema();
1873 $logging->triggerInfo($info, $tableName, $force);
1875 CRM_Core_I18n_Schema
::triggerInfo($info, $tableName);
1876 CRM_Contact_BAO_Contact
::triggerInfo($info, $tableName);
1878 CRM_Utils_Hook
::triggerInfo($info, $tableName);
1880 // drop all existing triggers on all tables
1881 $logging->dropTriggers($tableName);
1883 // now create the set of new triggers
1884 self
::createTriggers($info, $tableName);
1888 * Because sql functions are sometimes lost, esp during db migration, we check here to avoid numerous support requests
1889 * @see http://issues.civicrm.org/jira/browse/CRM-13822
1890 * TODO: Alternative solutions might be
1891 * * Stop using functions and find another way to strip numeric characters from phones
1892 * * Give better error messages (currently a missing fn fatals with "unknown error")
1894 public static function checkSqlFunctionsExist() {
1895 if (!self
::$_checkedSqlFunctionsExist) {
1896 self
::$_checkedSqlFunctionsExist = TRUE;
1897 $dao = CRM_Core_DAO
::executeQuery("SHOW function status WHERE db = database() AND name = 'civicrm_strip_non_numeric'");
1898 if (!$dao->fetch()) {
1899 self
::triggerRebuild();
1905 * Wrapper function to drop triggers.
1907 * @param string $tableName
1908 * the specific table requiring a rebuild; or NULL to rebuild all tables.
1910 public static function dropTriggers($tableName = NULL) {
1913 $logging = new CRM_Logging_Schema();
1914 $logging->triggerInfo($info, $tableName);
1916 // drop all existing triggers on all tables
1917 $logging->dropTriggers($tableName);
1921 * @param array $info
1922 * per hook_civicrm_triggerInfo.
1923 * @param string $onlyTableName
1924 * the specific table requiring a rebuild; or NULL to rebuild all tables.
1926 public static function createTriggers(&$info, $onlyTableName = NULL) {
1927 // Validate info array, should probably raise errors?
1928 if (is_array($info) == FALSE) {
1932 $triggers = array();
1934 // now enumerate the tables and the events and collect the same set in a different format
1935 foreach ($info as $value) {
1937 // clean the incoming data, skip malformed entries
1938 // TODO: malformed entries should raise errors or get logged.
1939 if (isset($value['table']) == FALSE ||
1940 isset($value['event']) == FALSE ||
1941 isset($value['when']) == FALSE ||
1942 isset($value['sql']) == FALSE
1947 if (is_string($value['table']) == TRUE) {
1948 $tables = array($value['table']);
1951 $tables = $value['table'];
1954 if (is_string($value['event']) == TRUE) {
1955 $events = array(strtolower($value['event']));
1958 $events = array_map('strtolower', $value['event']);
1961 $whenName = strtolower($value['when']);
1963 foreach ($tables as $tableName) {
1964 if (!isset($triggers[$tableName])) {
1965 $triggers[$tableName] = array();
1968 foreach ($events as $eventName) {
1969 $template_params = array('{tableName}', '{eventName}');
1970 $template_values = array($tableName, $eventName);
1972 $sql = str_replace($template_params,
1976 $variables = str_replace($template_params,
1978 CRM_Utils_Array
::value('variables', $value)
1981 if (!isset($triggers[$tableName][$eventName])) {
1982 $triggers[$tableName][$eventName] = array();
1985 if (!isset($triggers[$tableName][$eventName][$whenName])) {
1986 // We're leaving out cursors, conditions, and handlers for now
1987 // they are kind of dangerous in this context anyway
1988 // better off putting them in stored procedures
1989 $triggers[$tableName][$eventName][$whenName] = array(
1990 'variables' => array(),
1996 $triggers[$tableName][$eventName][$whenName]['variables'][] = $variables;
1999 $triggers[$tableName][$eventName][$whenName]['sql'][] = $sql;
2004 // now spit out the sql
2005 foreach ($triggers as $tableName => $tables) {
2006 if ($onlyTableName != NULL && $onlyTableName != $tableName) {
2009 foreach ($tables as $eventName => $events) {
2010 foreach ($events as $whenName => $parts) {
2011 $varString = implode("\n", $parts['variables']);
2012 $sqlString = implode("\n", $parts['sql']);
2013 $validName = CRM_Core_DAO
::shortenSQLName($tableName, 48, TRUE);
2014 $triggerName = "{$validName}_{$whenName}_{$eventName}";
2015 $triggerSQL = "CREATE TRIGGER $triggerName $whenName $eventName ON $tableName FOR EACH ROW BEGIN $varString $sqlString END";
2017 CRM_Core_DAO
::executeQuery("DROP TRIGGER IF EXISTS $triggerName");
2018 CRM_Core_DAO
::executeQuery(
2032 * Given a list of fields, create a list of references.
2034 * @param string $className
2035 * BAO/DAO class name.
2036 * @return array<CRM_Core_Reference_Interface>
2038 public static function createReferenceColumns($className) {
2040 $fields = $className::fields();
2041 foreach ($fields as $field) {
2042 if (isset($field['pseudoconstant'], $field['pseudoconstant']['optionGroupName'])) {
2043 $result[] = new CRM_Core_Reference_OptionValue(
2044 $className::getTableName(),
2046 'civicrm_option_value',
2047 CRM_Utils_Array
::value('keyColumn', $field['pseudoconstant'], 'value'),
2048 $field['pseudoconstant']['optionGroupName']
2056 * Find all records which refer to this entity.
2059 * Array of objects referencing this
2061 public function findReferences() {
2062 $links = self
::getReferencesToTable(static::getTableName());
2064 $occurrences = array();
2065 foreach ($links as $refSpec) {
2066 /** @var $refSpec CRM_Core_Reference_Interface */
2067 $daoName = CRM_Core_DAO_AllCoreTables
::getClassForTable($refSpec->getReferenceTable());
2068 $result = $refSpec->findReferences($this);
2070 while ($result->fetch()) {
2071 $obj = new $daoName();
2072 $obj->id
= $result->id
;
2073 $occurrences[] = $obj;
2078 return $occurrences;
2083 * each item has keys:
2087 * - table: string|null SQL table name
2088 * - key: string|null SQL column name
2090 public function getReferenceCounts() {
2091 $links = self
::getReferencesToTable(static::getTableName());
2094 foreach ($links as $refSpec) {
2095 /** @var $refSpec CRM_Core_Reference_Interface */
2096 $count = $refSpec->getReferenceCount($this);
2097 if ($count['count'] != 0) {
2102 foreach (CRM_Core_Component
::getEnabledComponents() as $component) {
2103 /** @var $component CRM_Core_Component_Info */
2104 $counts = array_merge($counts, $component->getReferenceCounts($this));
2106 CRM_Utils_Hook
::referenceCounts($this, $counts);
2112 * List all tables which have hard foreign keys to this table.
2114 * For now, this returns a description of every entity_id/entity_table
2116 * TODO: filter dynamic entity references on the $tableName, based on
2117 * schema metadata in dynamicForeignKey which enumerates a restricted
2118 * set of possible entity_table's.
2120 * @param string $tableName
2121 * Table referred to.
2124 * structure of table and column, listing every table with a
2125 * foreign key reference to $tableName, and the column where the key appears.
2127 public static function getReferencesToTable($tableName) {
2128 $refsFound = array();
2129 foreach (CRM_Core_DAO_AllCoreTables
::getClasses() as $daoClassName) {
2130 $links = $daoClassName::getReferenceColumns();
2131 $daoTableName = $daoClassName::getTableName();
2133 foreach ($links as $refSpec) {
2134 /** @var $refSpec CRM_Core_Reference_Interface */
2135 if ($refSpec->matchesTargetTable($tableName)) {
2136 $refsFound[] = $refSpec;
2144 * Lookup the value of a MySQL global configuration variable.
2146 * @param string $name
2147 * E.g. "thread_stack".
2148 * @param mixed $default
2151 public static function getGlobalSetting($name, $default = NULL) {
2152 // Alternatively, SELECT @@GLOBAL.thread_stack, but
2153 // that has been reported to fail under MySQL 5.0 for OS X
2154 $escapedName = self
::escapeString($name);
2155 $dao = CRM_Core_DAO
::executeQuery("SHOW VARIABLES LIKE '$escapedName'");
2156 if ($dao->fetch()) {
2165 * Get options for the called BAO object's field.
2166 * This function can be overridden by each BAO to add more logic related to context.
2167 * The overriding function will generally call the lower-level CRM_Core_PseudoConstant::get
2169 * @param string $fieldName
2170 * @param string $context
2171 * @see CRM_Core_DAO::buildOptionsContext
2172 * @param array $props
2173 * whatever is known about this bao object.
2175 * @return array|bool
2177 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
2178 // If a given bao does not override this function
2179 $baoName = get_called_class();
2180 return CRM_Core_PseudoConstant
::get($baoName, $fieldName, array(), $context);
2184 * Populate option labels for this object's fields.
2186 * @throws exception if called directly on the base class
2188 public function getOptionLabels() {
2189 $fields = $this->fields();
2190 if ($fields === NULL) {
2191 throw new Exception('Cannot call getOptionLabels on CRM_Core_DAO');
2193 foreach ($fields as $field) {
2194 $name = CRM_Utils_Array
::value('name', $field);
2195 if ($name && isset($this->$name)) {
2196 $label = CRM_Core_PseudoConstant
::getLabel(get_class($this), $name, $this->$name);
2197 if ($label !== FALSE) {
2198 // Append 'label' onto the field name
2199 $labelName = $name . '_label';
2200 $this->$labelName = $label;
2207 * Provides documentation and validation for the buildOptions $context param
2209 * @param string $context
2214 public static function buildOptionsContext($context = NULL) {
2216 'get' => "get: all options are returned, even if they are disabled; labels are translated.",
2217 'create' => "create: options are filtered appropriately for the object being created/updated; labels are translated.",
2218 'search' => "search: searchable options are returned; labels are translated.",
2219 'validate' => "validate: all options are returned, even if they are disabled; machine names are used in place of labels.",
2220 'abbreviate' => "abbreviate: enabled options are returned; labels are replaced with abbreviations.",
2221 'match' => "match: enabled options are returned using machine names as keys; labels are translated.",
2223 // Validation: enforce uniformity of this param
2224 if ($context !== NULL && !isset($contexts[$context])) {
2225 throw new Exception("'$context' is not a valid context for buildOptions.");
2231 * @param string $fieldName
2232 * @return bool|array
2234 public function getFieldSpec($fieldName) {
2235 $fields = $this->fields();
2236 $fieldKeys = $this->fieldKeys();
2238 // Support "unique names" as well as sql names
2239 $fieldKey = $fieldName;
2240 if (empty($fields[$fieldKey])) {
2241 $fieldKey = CRM_Utils_Array
::value($fieldName, $fieldKeys);
2243 // If neither worked then this field doesn't exist. Return false.
2244 if (empty($fields[$fieldKey])) {
2247 return $fields[$fieldKey];
2251 * Get SQL where clause for SQL filter syntax input parameters.
2253 * SQL version of api function to assign filters to the DAO based on the syntax
2254 * $field => array('IN' => array(4,6,9))
2256 * $field => array('LIKE' => array('%me%))
2259 * @param string $fieldName
2261 * @param array $filter
2262 * filter to be applied indexed by operator.
2263 * @param string $type
2264 * type of field (not actually used - nor in api @todo ).
2265 * @param string $alias
2266 * alternative field name ('as') @todo- not actually used.
2267 * @param bool $returnSanitisedArray
2268 * Return a sanitised array instead of a clause.
2269 * this is primarily so we can add filters @ the api level to the Query object based fields
2273 * @return NULL|string|array
2274 * a string is returned if $returnSanitisedArray is not set, otherwise and Array or NULL
2275 * depending on whether it is supported as yet
2277 public static function createSQLFilter($fieldName, $filter, $type, $alias = NULL, $returnSanitisedArray = FALSE) {
2278 foreach ($filter as $operator => $criteria) {
2279 if (in_array($operator, self
::acceptedSQLOperators(), TRUE)) {
2280 switch ($operator) {
2284 if (!$returnSanitisedArray) {
2285 return (sprintf('%s %s', $fieldName, $operator));
2288 return (sprintf('%s %s ', $fieldName, $operator));
2292 // ternary operators
2295 if (empty($criteria[0]) ||
empty($criteria[1])) {
2296 throw new Exception("invalid criteria for $operator");
2298 if (!$returnSanitisedArray) {
2299 return (sprintf('%s ' . $operator . ' "%s" AND "%s"', $fieldName, CRM_Core_DAO
::escapeString($criteria[0]), CRM_Core_DAO
::escapeString($criteria[1])));
2302 return NULL; // not yet implemented (tests required to implement)
2309 if (empty($criteria)) {
2310 throw new Exception("invalid criteria for $operator");
2312 $escapedCriteria = array_map(array(
2316 if (!$returnSanitisedArray) {
2317 return (sprintf('%s %s ("%s")', $fieldName, $operator, implode('", "', $escapedCriteria)));
2319 return $escapedCriteria;
2324 if (!$returnSanitisedArray) {
2325 return (sprintf('%s %s "%s"', $fieldName, $operator, CRM_Core_DAO
::escapeString($criteria)));
2328 return NULL; // not yet implemented (tests required to implement)
2336 * @see http://issues.civicrm.org/jira/browse/CRM-9150
2337 * support for other syntaxes is discussed in ticket but being put off for now
2340 public static function acceptedSQLOperators() {
2361 * SQL has a limit of 64 characters on various names:
2362 * table name, trigger name, column name ...
2364 * For custom groups and fields we generated names from user entered input
2365 * which can be longer than this length, this function helps with creating
2366 * strings that meet various criteria.
2368 * @param string $string
2369 * The string to be shortened.
2370 * @param int $length
2371 * The max length of the string.
2373 * @param bool $makeRandom
2377 public static function shortenSQLName($string, $length = 60, $makeRandom = FALSE) {
2378 // early return for strings that meet the requirements
2379 if (strlen($string) <= $length) {
2383 // easy return for calls that dont need a randomized uniq string
2385 return substr($string, 0, $length);
2388 // the string is longer than the length and we need a uniq string
2389 // for the same tablename we need the same uniq string every time
2390 // hence we use md5 on the string, which is not random
2391 // we'll append 8 characters to the end of the tableName
2392 $md5string = substr(md5($string), 0, 8);
2393 return substr($string, 0, $length - 8) . "_{$md5string}";
2397 * @param array $params
2399 public function setApiFilter(&$params) {