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;
77 * @return \CRM_Core_DAO
79 public function __construct() {
81 $this->__table
= $this->getTableName();
85 * Empty definition for virtual function.
87 public static function getTableName() {
92 * Initialize the DAO object.
95 * The database connection string.
97 public static function init($dsn) {
98 Civi
::$statics[__CLASS__
]['init'] = 1;
99 $options = &PEAR
::getStaticProperty('DB_DataObject', 'options');
100 $options['database'] = $dsn;
101 if (defined('CIVICRM_DAO_DEBUG')) {
102 self
::DebugLevel(CIVICRM_DAO_DEBUG
);
104 CRM_Core_DAO
::setFactory(new CRM_Contact_DAO_Factory());
105 if (CRM_Utils_Constant
::value('CIVICRM_MYSQL_STRICT', CRM_Utils_System
::isDevelopment())) {
106 CRM_Core_DAO
::executeQuery('SET SESSION sql_mode = STRICT_TRANS_TABLES');
108 CRM_Core_DAO
::executeQuery('SET NAMES utf8');
112 * @param string $fieldName
114 * @param array $params
116 protected function assignTestFK($fieldName, $fieldDef, $params) {
117 $required = CRM_Utils_Array
::value('required', $fieldDef);
118 $FKClassName = CRM_Utils_Array
::value('FKClassName', $fieldDef);
119 $dbName = $fieldDef['name'];
120 $daoName = str_replace('_BAO_', '_DAO_', get_class($this));
122 // skip the FK if it is not required
123 // if it's contact id we should create even if not required
124 // we'll have a go @ fetching first though
125 // we WILL create campaigns though for so tests with a campaign pseudoconstant will complete
126 if ($FKClassName === 'CRM_Campaign_DAO_Campaign' && $daoName != $FKClassName) {
129 if (!$required && $dbName != 'contact_id') {
130 $fkDAO = new $FKClassName();
131 if ($fkDAO->find(TRUE)) {
132 $this->$dbName = $fkDAO->id
;
137 elseif (in_array($FKClassName, CRM_Core_DAO
::$_testEntitiesToSkip)) {
138 $depObject = new $FKClassName();
139 $depObject->find(TRUE);
140 $this->$dbName = $depObject->id
;
143 elseif ($daoName == 'CRM_Member_DAO_MembershipType' && $fieldName == 'member_of_contact_id') {
144 // FIXME: the fields() metadata is not specific enough
145 $depObject = CRM_Core_DAO
::createTestObject($FKClassName, array('contact_type' => 'Organization'));
146 $this->$dbName = $depObject->id
;
150 //if it is required we need to generate the dependency object first
151 $depObject = CRM_Core_DAO
::createTestObject($FKClassName, CRM_Utils_Array
::value($dbName, $params, 1));
152 $this->$dbName = $depObject->id
;
158 * Generate and assign an arbitrary value to a field of a test object.
160 * @param string $fieldName
161 * @param array $fieldDef
162 * @param int $counter
163 * The globally-unique ID of the test object.
165 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
166 $dbName = $fieldDef['name'];
167 $daoName = get_class($this);
170 if (!$handled && $dbName == 'contact_sub_type') {
171 //coming up with a rule to set this is too complex let's not set it
175 // Pick an option value if needed
176 if (!$handled && $fieldDef['type'] !== CRM_Utils_Type
::T_BOOLEAN
) {
177 $options = $daoName::buildOptions($dbName, 'create');
179 $this->$dbName = key($options);
185 switch ($fieldDef['type']) {
186 case CRM_Utils_Type
::T_INT
:
187 case CRM_Utils_Type
::T_FLOAT
:
188 case CRM_Utils_Type
::T_MONEY
:
189 if (isset($fieldDef['precision'])) {
190 // $object->$dbName = CRM_Utils_Number::createRandomDecimal($value['precision']);
191 $this->$dbName = CRM_Utils_Number
::createTruncatedDecimal($counter, $fieldDef['precision']);
194 $this->$dbName = $counter;
198 case CRM_Utils_Type
::T_BOOLEAN
:
199 if (isset($fieldDef['default'])) {
200 $this->$dbName = $fieldDef['default'];
202 elseif ($fieldDef['name'] == 'is_deleted' ||
$fieldDef['name'] == 'is_test') {
210 case CRM_Utils_Type
::T_DATE
:
211 case CRM_Utils_Type
::T_TIMESTAMP
:
212 case CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
:
213 $this->$dbName = '19700101';
214 if ($dbName == 'end_date') {
215 // put this in the future
216 $this->$dbName = '20200101';
220 case CRM_Utils_Type
::T_TIME
:
221 CRM_Core_Error
::fatal("T_TIME shouldn't be used.");
222 //$object->$dbName='000000';
224 case CRM_Utils_Type
::T_CCNUM
:
225 $this->$dbName = '4111 1111 1111 1111';
228 case CRM_Utils_Type
::T_URL
:
229 $this->$dbName = 'http://www.civicrm.org';
232 case CRM_Utils_Type
::T_STRING
:
233 case CRM_Utils_Type
::T_BLOB
:
234 case CRM_Utils_Type
::T_MEDIUMBLOB
:
235 case CRM_Utils_Type
::T_TEXT
:
236 case CRM_Utils_Type
::T_LONGTEXT
:
237 case CRM_Utils_Type
::T_EMAIL
:
239 // WAS: if (isset($value['enumValues'])) {
240 // TODO: see if this works with all pseudoconstants
241 if (isset($fieldDef['pseudoconstant'], $fieldDef['pseudoconstant']['callback'])) {
242 if (isset($fieldDef['default'])) {
243 $this->$dbName = $fieldDef['default'];
246 $options = CRM_Core_PseudoConstant
::get($daoName, $fieldName);
247 if (is_array($options)) {
248 $this->$dbName = $options[0];
251 $defaultValues = explode(',', $options);
252 $this->$dbName = $defaultValues[0];
257 $this->$dbName = $dbName . '_' . $counter;
258 $maxlength = CRM_Utils_Array
::value('maxlength', $fieldDef);
259 if ($maxlength > 0 && strlen($this->$dbName) > $maxlength) {
260 $this->$dbName = substr($this->$dbName, 0, $fieldDef['maxlength']);
268 * Reset the DAO object.
270 * DAO is kinda crappy in that there is an unwritten rule of one query per DAO.
272 * We attempt to get around this crappy restriction by resetting some of DAO's internal fields. Use this with caution
274 public function reset() {
276 foreach (array_keys($this->table()) as $field) {
277 unset($this->$field);
281 * reset the various DB_DAO structures manually
283 $this->_query
= array();
290 * @param string $tableName
294 public static function getLocaleTableName($tableName) {
297 $tables = CRM_Core_I18n_Schema
::schemaStructureTables();
298 if (in_array($tableName, $tables)) {
299 return $tableName . $dbLocale;
306 * Execute a query by the current DAO, localizing it along the way (if needed).
308 * @param string $query
309 * The SQL query for execution.
310 * @param bool $i18nRewrite
311 * Whether to rewrite the query.
314 * the current DAO object after the query execution
316 public function query($query, $i18nRewrite = TRUE) {
317 // rewrite queries that should use $dbLocale-based views for multi-language installs
319 if ($i18nRewrite and $dbLocale) {
320 $query = CRM_Core_I18n_Schema
::rewriteQuery($query);
323 return parent
::query($query);
327 * Static function to set the factory instance for this class.
329 * @param object $factory
330 * The factory application object.
332 public static function setFactory(&$factory) {
333 self
::$_factory = &$factory;
337 * Factory method to instantiate a new object from a table name.
339 * @param string $table
341 public function factory($table = '') {
342 if (!isset(self
::$_factory)) {
343 return parent
::factory($table);
346 return self
::$_factory->create($table);
350 * Initialization for all DAO objects. Since we access DB_DO programatically
351 * we need to set the links manually.
353 public function initialize() {
355 if (empty(Civi
::$statics[__CLASS__
]['init'])) {
356 // CRM_Core_DAO::init() must be called before CRM_Core_DAO->initialize().
357 // This occurs very early in bootstrap - error handlers may not be wired up.
358 echo "Inconsistent system initialization sequence. Premature access of (" . get_class($this) . ")";
359 CRM_Utils_System
::civiExit();
364 * Defines the default key as 'id'.
369 public function keys() {
378 * Tells DB_DataObject which keys use autoincrement.
379 * 'id' is autoincrementing by default.
384 public function sequenceKey() {
385 static $sequenceKeys;
386 if (!isset($sequenceKeys)) {
387 $sequenceKeys = array('id', TRUE);
389 return $sequenceKeys;
393 * Returns list of FK relationships.
397 * Array of CRM_Core_Reference_Interface
399 public static function getReferenceColumns() {
404 * Returns all the column names of this table.
409 public static function &fields() {
415 * Get/set an associative array of table columns
420 public function table() {
421 $fields = &$this->fields();
425 foreach ($fields as $name => $value) {
426 $table[$value['name']] = $value['type'];
427 if (!empty($value['required'])) {
428 $table[$value['name']] +
= self
::DB_DAO_NOTNULL
;
443 public function save($hook = TRUE) {
444 if (!empty($this->id
)) {
448 $event = new \Civi\Core\DAO\Event\
PostUpdate($this);
449 \Civi
::service('dispatcher')->dispatch("DAO::post-update", $event);
456 $event = new \Civi\Core\DAO\Event\
PostUpdate($this);
457 \Civi
::service('dispatcher')->dispatch("DAO::post-insert", $event);
463 CRM_Utils_Hook
::postSave($this);
470 * Deletes items from table which match current objects variables.
472 * Returns the true on success
476 * Designed to be extended
478 * $object = new mytable();
480 * echo $object->delete(); // builds a conditon
482 * $object = new mytable();
483 * $object->whereAdd('age > 12');
485 * $object->orderBy('age DESC');
486 * $object->delete(true); // dont use object vars, use the conditions, limit and order.
488 * @param bool $useWhere (optional) If DB_DATAOBJECT_WHEREADD_ONLY is passed in then
489 * we will build the condition only using the whereAdd's. Default is to
490 * build the condition only using the object parameters.
492 * * @return mixed Int (No. of rows affected) on success, false on failure, 0 on no data affected
494 public function delete($useWhere = FALSE) {
495 $result = parent
::delete($useWhere);
497 $event = new \Civi\Core\DAO\Event\
PostDelete($this, $result);
498 \Civi
::service('dispatcher')->dispatch("DAO::post-delete", $event);
504 * @param bool $created
506 public function log($created = FALSE) {
509 if (!$this->getLog()) {
514 $session = CRM_Core_Session
::singleton();
515 $cid = $session->get('userID');
518 // return is we dont have handle to FK
523 $dao = new CRM_Core_DAO_Log();
524 $dao->entity_table
= $this->getTableName();
525 $dao->entity_id
= $this->id
;
526 $dao->modified_id
= $cid;
527 $dao->modified_date
= date("YmdHis");
532 * Given an associative array of name/value pairs, extract all the values
533 * that belong to this object and initialize the object with said values
535 * @param array $params
536 * (reference ) associative array of name/value pairs.
539 * Did we copy all null values into the object
541 public function copyValues(&$params) {
542 $fields = &$this->fields();
544 foreach ($fields as $name => $value) {
545 $dbName = $value['name'];
546 if (array_key_exists($dbName, $params)) {
547 $pValue = $params[$dbName];
550 elseif (array_key_exists($name, $params)) {
551 $pValue = $params[$name];
558 // if there is no value then make the variable NULL
560 if ($pValue === '') {
561 $this->$dbName = 'null';
564 $this->$dbName = $pValue;
573 * Store all the values from this object in an associative array
574 * this is a destructive store, calling function is responsible
575 * for keeping sanity of id's.
577 * @param object $object
578 * The object that we are extracting data from.
579 * @param array $values
580 * (reference ) associative array of name/value pairs.
582 public static function storeValues(&$object, &$values) {
583 $fields = &$object->fields();
584 foreach ($fields as $name => $value) {
585 $dbName = $value['name'];
586 if (isset($object->$dbName) && $object->$dbName !== 'null') {
587 $values[$dbName] = $object->$dbName;
588 if ($name != $dbName) {
589 $values[$name] = $object->$dbName;
596 * Create an attribute for this specific field. We only do this for strings and text
598 * @param array $field
599 * The field under task.
602 * the attributes for the object
604 public static function makeAttribute($field) {
606 if (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_STRING
) {
607 $maxLength = CRM_Utils_Array
::value('maxlength', $field);
608 $size = CRM_Utils_Array
::value('size', $field);
609 if ($maxLength ||
$size) {
610 $attributes = array();
612 $attributes['maxlength'] = $maxLength;
615 $attributes['size'] = $size;
620 elseif (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_TEXT
) {
621 $rows = CRM_Utils_Array
::value('rows', $field);
625 $cols = CRM_Utils_Array
::value('cols', $field);
630 $attributes = array();
631 $attributes['rows'] = $rows;
632 $attributes['cols'] = $cols;
635 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
) {
636 $attributes['size'] = 6;
637 $attributes['maxlength'] = 14;
645 * Get the size and maxLength attributes for this text field.
646 * (or for all text fields) in the DAO object.
648 * @param string $class
650 * @param string $fieldName
651 * Field that i'm interested in or null if.
652 * you want the attributes for all DAO text fields
655 * assoc array of name => attribute pairs
657 public static function getAttribute($class, $fieldName = NULL) {
658 $object = new $class();
659 $fields = &$object->fields();
660 if ($fieldName != NULL) {
661 $field = CRM_Utils_Array
::value($fieldName, $fields);
662 return self
::makeAttribute($field);
665 $attributes = array();
666 foreach ($fields as $name => $field) {
667 $attribute = self
::makeAttribute($field);
669 $attributes[$name] = $attribute;
673 if (!empty($attributes)) {
685 public static function transaction($type) {
686 CRM_Core_Error
::fatal('This function is obsolete, please use CRM_Core_Transaction');
690 * Check if there is a record with the same name in the db.
692 * @param string $value
693 * The value of the field we are checking.
694 * @param string $daoName
695 * The dao object name.
696 * @param string $daoID
697 * The id of the object being updated. u can change your name.
698 * as long as there is no conflict
699 * @param string $fieldName
700 * The name of the field in the DAO.
703 * true if object exists
705 public static function objectExists($value, $daoName, $daoID, $fieldName = 'name') {
706 $object = new $daoName();
707 $object->$fieldName = $value;
709 $config = CRM_Core_Config
::singleton();
711 if ($object->find(TRUE)) {
712 return ($daoID && $object->id
== $daoID) ?
TRUE : FALSE;
720 * Check if there is a given column in a specific table.
722 * @param string $tableName
723 * @param string $columnName
724 * @param bool $i18nRewrite
725 * Whether to rewrite the query on multilingual setups.
728 * true if exists, else false
730 public static function checkFieldExists($tableName, $columnName, $i18nRewrite = TRUE) {
736 $params = array(1 => array($columnName, 'String'));
737 $dao = CRM_Core_DAO
::executeQuery($query, $params, TRUE, NULL, FALSE, $i18nRewrite);
738 $result = $dao->fetch() ?
TRUE : FALSE;
744 * Returns the storage engine used by given table-name(optional).
745 * Otherwise scans all the tables and return an array of all the
746 * distinct storage engines being used.
748 * @param string $tableName
750 * @param int $maxTablesToCheck
751 * @param string $fieldName
755 public static function getStorageValues($tableName = NULL, $maxTablesToCheck = 10, $fieldName = 'Engine') {
757 $query = "SHOW TABLE STATUS LIKE %1";
761 if (isset($tableName)) {
762 $params = array(1 => array($tableName, 'String'));
765 $params = array(1 => array('civicrm_%', 'String'));
768 $dao = CRM_Core_DAO
::executeQuery($query, $params);
771 while ($dao->fetch()) {
772 if (isset($values[$dao->$fieldName]) ||
773 // ignore import and other temp tables
774 strpos($dao->Name
, 'civicrm_import_job_') !== FALSE ||
775 strpos($dao->Name
, '_temp') !== FALSE
779 $values[$dao->$fieldName] = 1;
781 if ($maxTablesToCheck &&
782 $count >= $maxTablesToCheck
792 * @param int $maxTablesToCheck
796 public static function isDBMyISAM($maxTablesToCheck = 10) {
797 // show error if any of the tables, use 'MyISAM' storage engine.
798 $engines = self
::getStorageValues(NULL, $maxTablesToCheck);
799 if (array_key_exists('MyISAM', $engines)) {
806 * Checks if a constraint exists for a specified table.
808 * @param string $tableName
809 * @param string $constraint
812 * true if constraint exists, false otherwise
814 public static function checkConstraintExists($tableName, $constraint) {
815 static $show = array();
817 if (!array_key_exists($tableName, $show)) {
818 $query = "SHOW CREATE TABLE $tableName";
819 $dao = CRM_Core_DAO
::executeQuery($query);
821 if (!$dao->fetch()) {
822 CRM_Core_Error
::fatal();
826 $show[$tableName] = $dao->Create_Table
;
829 return preg_match("/\b$constraint\b/i", $show[$tableName]) ?
TRUE : FALSE;
833 * Checks if CONSTRAINT keyword exists for a specified table.
835 * @param array $tables
840 * true if CONSTRAINT keyword exists, false otherwise
842 public static function schemaRequiresRebuilding($tables = array("civicrm_contact")) {
844 foreach ($tables as $tableName) {
845 if (!array_key_exists($tableName, $show)) {
846 $query = "SHOW CREATE TABLE $tableName";
847 $dao = CRM_Core_DAO
::executeQuery($query);
849 if (!$dao->fetch()) {
850 CRM_Core_Error
::fatal();
854 $show[$tableName] = $dao->Create_Table
;
857 $result = preg_match("/\bCONSTRAINT\b\s/i", $show[$tableName]) ?
TRUE : FALSE;
858 if ($result == TRUE) {
869 * Checks if the FK constraint name is in the format 'FK_tableName_columnName'
870 * for a specified column of a table.
872 * @param string $tableName
873 * @param string $columnName
876 * true if in format, false otherwise
878 public static function checkFKConstraintInFormat($tableName, $columnName) {
879 static $show = array();
881 if (!array_key_exists($tableName, $show)) {
882 $query = "SHOW CREATE TABLE $tableName";
883 $dao = CRM_Core_DAO
::executeQuery($query);
885 if (!$dao->fetch()) {
886 CRM_Core_Error
::fatal();
890 $show[$tableName] = $dao->Create_Table
;
892 $constraint = "`FK_{$tableName}_{$columnName}`";
893 $pattern = "/\bCONSTRAINT\b\s+%s\s+\bFOREIGN\s+KEY\b\s/i";
894 return preg_match(sprintf($pattern, $constraint), $show[$tableName]) ?
TRUE : FALSE;
898 * Check whether a specific column in a specific table has always the same value.
900 * @param string $tableName
901 * @param string $columnName
902 * @param string $columnValue
905 * true if the value is always $columnValue, false otherwise
907 public static function checkFieldHasAlwaysValue($tableName, $columnName, $columnValue) {
908 $query = "SELECT * FROM $tableName WHERE $columnName != '$columnValue'";
909 $dao = CRM_Core_DAO
::executeQuery($query);
910 $result = $dao->fetch() ?
FALSE : TRUE;
916 * Check whether a specific column in a specific table is always NULL.
918 * @param string $tableName
919 * @param string $columnName
922 * true if if the value is always NULL, false otherwise
924 public static function checkFieldIsAlwaysNull($tableName, $columnName) {
925 $query = "SELECT * FROM $tableName WHERE $columnName IS NOT NULL";
926 $dao = CRM_Core_DAO
::executeQuery($query);
927 $result = $dao->fetch() ?
FALSE : TRUE;
933 * Check if there is a given table in the database.
935 * @param string $tableName
938 * true if exists, else false
940 public static function checkTableExists($tableName) {
945 $params = array(1 => array($tableName, 'String'));
947 $dao = CRM_Core_DAO
::executeQuery($query, $params);
948 $result = $dao->fetch() ?
TRUE : FALSE;
958 public function checkVersion($version) {
963 $dbVersion = CRM_Core_DAO
::singleValueQuery($query);
964 return trim($version) == trim($dbVersion) ?
TRUE : FALSE;
968 * Find a DAO object for the given ID and return it.
971 * Id of the DAO object being searched for.
974 * Object of the type of the class that called this function.
976 public static function findById($id) {
977 $object = new static();
979 if (!$object->find(TRUE)) {
980 throw new Exception("Unable to find a " . get_called_class() . " with id {$id}.");
986 * Returns all results as array-encoded records.
990 public function fetchAll() {
992 while ($this->fetch()) {
993 $result[] = $this->toArray();
999 * Given a DAO name, a column name and a column value, find the record and GET the value of another column in that record
1001 * @param string $daoName
1002 * Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact).
1003 * @param int $searchValue
1004 * Value of the column you want to search by.
1005 * @param string $returnColumn
1006 * Name of the column you want to GET the value of.
1007 * @param string $searchColumn
1008 * Name of the column you want to search by.
1009 * @param bool $force
1010 * Skip use of the cache.
1012 * @return string|null
1013 * Value of $returnColumn in the retrieved record
1015 public static function getFieldValue($daoName, $searchValue, $returnColumn = 'name', $searchColumn = 'id', $force = FALSE) {
1017 empty($searchValue) ||
1018 trim(strtolower($searchValue)) == 'null'
1020 // adding this year since developers forget to check for an id
1021 // or for the 'null' (which is a bad DAO kludge)
1022 // and hence we get the first value in the db
1023 CRM_Core_Error
::fatal();
1026 $cacheKey = "{$daoName}:{$searchValue}:{$returnColumn}:{$searchColumn}";
1027 if (self
::$_dbColumnValueCache === NULL) {
1028 self
::$_dbColumnValueCache = array();
1031 if (!array_key_exists($cacheKey, self
::$_dbColumnValueCache) ||
$force) {
1032 $object = new $daoName();
1033 $object->$searchColumn = $searchValue;
1034 $object->selectAdd();
1035 $object->selectAdd($returnColumn);
1038 if ($object->find(TRUE)) {
1039 $result = $object->$returnColumn;
1043 self
::$_dbColumnValueCache[$cacheKey] = $result;
1045 return self
::$_dbColumnValueCache[$cacheKey];
1049 * Given a DAO name, a column name and a column value, find the record and SET the value of another column in that record
1051 * @param string $daoName
1052 * Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact).
1053 * @param int $searchValue
1054 * Value of the column you want to search by.
1055 * @param string $setColumn
1056 * Name of the column you want to SET the value of.
1057 * @param string $setValue
1058 * SET the setColumn to this value.
1059 * @param string $searchColumn
1060 * Name of the column you want to search by.
1063 * true if we found and updated the object, else false
1065 public static function setFieldValue($daoName, $searchValue, $setColumn, $setValue, $searchColumn = 'id') {
1066 $object = new $daoName();
1067 $object->selectAdd();
1068 $object->selectAdd("$searchColumn, $setColumn");
1069 $object->$searchColumn = $searchValue;
1071 if ($object->find(TRUE)) {
1072 $object->$setColumn = $setValue;
1073 if ($object->save()) {
1084 * @param array|object $sort either array or CRM_Utils_Sort
1085 * @param string $default
1086 * Default sort value.
1091 public static function getSortString($sort, $default = NULL) {
1092 // check if sort is of type CRM_Utils_Sort
1093 if (is_a($sort, 'CRM_Utils_Sort')) {
1094 return $sort->orderBy();
1097 // is it an array specified as $field => $sortDirection ?
1099 foreach ($sort as $k => $v) {
1100 $sortString .= "$k $v,";
1102 return rtrim($sortString, ',');
1108 * Fetch object based on array of properties.
1110 * @param string $daoName
1111 * Name of the dao object.
1112 * @param array $params
1113 * (reference ) an assoc array of name/value pairs.
1114 * @param array $defaults
1115 * (reference ) an assoc array to hold the flattened values.
1116 * @param array $returnProperities
1117 * An assoc array of fields that need to be returned, eg array( 'first_name', 'last_name').
1120 * an object of type referenced by daoName
1122 public static function commonRetrieve($daoName, &$params, &$defaults, $returnProperities = NULL) {
1123 $object = new $daoName();
1124 $object->copyValues($params);
1126 // return only specific fields if returnproperties are sent
1127 if (!empty($returnProperities)) {
1128 $object->selectAdd();
1129 $object->selectAdd(implode(',', $returnProperities));
1132 if ($object->find(TRUE)) {
1133 self
::storeValues($object, $defaults);
1140 * Delete the object records that are associated with this contact.
1142 * @param string $daoName
1143 * Name of the dao object.
1144 * @param int $contactId
1145 * Id of the contact to delete.
1147 public static function deleteEntityContact($daoName, $contactId) {
1148 $object = new $daoName();
1150 $object->entity_table
= 'civicrm_contact';
1151 $object->entity_id
= $contactId;
1158 * @param string $query
1159 * Query to be executed.
1161 * @param array $params
1162 * @param bool $abort
1163 * @param null $daoName
1164 * @param bool $freeDAO
1165 * @param bool $i18nRewrite
1166 * @param bool $trapException
1168 * @return CRM_Core_DAO|object
1169 * object that holds the results of the query
1170 * NB - if this is defined as just returning a DAO phpstorm keeps pointing
1171 * out all the properties that are not part of the DAO
1173 public static function &executeQuery(
1179 $i18nRewrite = TRUE,
1180 $trapException = FALSE
1182 $queryStr = self
::composeQuery($query, $params, $abort);
1185 $dao = new CRM_Core_DAO();
1188 $dao = new $daoName();
1191 if ($trapException) {
1192 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
1195 $result = $dao->query($queryStr, $i18nRewrite);
1197 if (is_a($result, 'DB_Error')) {
1202 preg_match('/^(insert|update|delete|create|drop|replace)/i', $queryStr)
1204 // we typically do this for insert/update/delete statements OR if explicitly asked to
1212 * Execute a query and get the single result.
1214 * @param string $query
1215 * Query to be executed.
1216 * @param array $params
1217 * @param bool $abort
1218 * @param bool $i18nRewrite
1219 * @return string|null
1220 * the result of the query if any
1223 public static function &singleValueQuery(
1229 $queryStr = self
::composeQuery($query, $params, $abort);
1231 static $_dao = NULL;
1234 $_dao = new CRM_Core_DAO();
1237 $_dao->query($queryStr, $i18nRewrite);
1239 $result = $_dao->getDatabaseResult();
1242 $row = $result->fetchRow();
1253 * @param array $params
1254 * @param bool $abort
1259 public static function composeQuery($query, &$params, $abort = TRUE) {
1261 foreach ($params as $key => $item) {
1262 if (is_numeric($key)) {
1263 if (CRM_Utils_Type
::validate($item[0], $item[1]) !== NULL) {
1264 $item[0] = self
::escapeString($item[0]);
1265 if ($item[1] == 'String' ||
1266 $item[1] == 'Memo' ||
1269 // Support class constants stipulating wildcard characters and/or
1270 // non-quoting of strings. Also support legacy code which may be
1271 // passing in TRUE or 1 for $item[2], which used to indicate the
1272 // use of wildcard characters.
1273 if (!empty($item[2])) {
1274 if ($item[2] & CRM_Core_DAO
::QUERY_FORMAT_WILDCARD ||
$item[2] === TRUE) {
1275 $item[0] = "'%{$item[0]}%'";
1277 elseif (!($item[2] & CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
)) {
1278 $item[0] = "'{$item[0]}'";
1282 $item[0] = "'{$item[0]}'";
1286 if (($item[1] == 'Date' ||
$item[1] == 'Timestamp') &&
1287 strlen($item[0]) == 0
1292 $tr['%' . $key] = $item[0];
1295 CRM_Core_Error
::fatal("{$item[0]} is not of type {$item[1]}");
1300 return strtr($query, $tr);
1306 public static function freeResult($ids = NULL) {
1307 global $_DB_DATAOBJECT;
1310 if (!$_DB_DATAOBJECT ||
1311 !isset($_DB_DATAOBJECT['RESULTS'])
1315 $ids = array_keys($_DB_DATAOBJECT['RESULTS']);
1318 foreach ($ids as $id) {
1319 if (isset($_DB_DATAOBJECT['RESULTS'][$id])) {
1320 if (is_resource($_DB_DATAOBJECT['RESULTS'][$id]->result
)) {
1321 mysql_free_result($_DB_DATAOBJECT['RESULTS'][$id]->result
);
1323 unset($_DB_DATAOBJECT['RESULTS'][$id]);
1326 if (isset($_DB_DATAOBJECT['RESULTFIELDS'][$id])) {
1327 unset($_DB_DATAOBJECT['RESULTFIELDS'][$id]);
1333 * make a shallow copy of an object.
1334 * and all the fields in the object
1336 * @param string $daoName
1338 * @param array $criteria
1339 * Array of all the fields & values.
1340 * on which basis to copy
1341 * @param array $newData
1342 * Array of all the fields & values.
1343 * to be copied besides the other fields
1344 * @param string $fieldsFix
1345 * Array of fields that you want to prefix/suffix/replace.
1346 * @param string $blockCopyOfDependencies
1347 * Fields that you want to block from.
1351 * @return CRM_Core_DAO
1352 * the newly created copy of the object
1354 public static function ©Generic($daoName, $criteria, $newData = NULL, $fieldsFix = NULL, $blockCopyOfDependencies = NULL) {
1355 $object = new $daoName();
1357 $object->id
= $criteria['id'];
1360 foreach ($criteria as $key => $value) {
1361 $object->$key = $value;
1366 while ($object->fetch()) {
1368 // all the objects except with $blockCopyOfDependencies set
1369 // be copied - addresses #CRM-1962
1371 if ($blockCopyOfDependencies && $object->$blockCopyOfDependencies) {
1375 $newObject = new $daoName();
1377 $fields = &$object->fields();
1378 if (!is_array($fieldsFix)) {
1379 $fieldsToPrefix = array();
1380 $fieldsToSuffix = array();
1381 $fieldsToReplace = array();
1383 if (!empty($fieldsFix['prefix'])) {
1384 $fieldsToPrefix = $fieldsFix['prefix'];
1386 if (!empty($fieldsFix['suffix'])) {
1387 $fieldsToSuffix = $fieldsFix['suffix'];
1389 if (!empty($fieldsFix['replace'])) {
1390 $fieldsToReplace = $fieldsFix['replace'];
1393 foreach ($fields as $name => $value) {
1394 if ($name == 'id' ||
$value['name'] == 'id') {
1395 // copy everything but the id!
1399 $dbName = $value['name'];
1400 $type = CRM_Utils_Type
::typeToString($value['type']);
1401 $newObject->$dbName = $object->$dbName;
1402 if (isset($fieldsToPrefix[$dbName])) {
1403 $newObject->$dbName = $fieldsToPrefix[$dbName] . $newObject->$dbName;
1405 if (isset($fieldsToSuffix[$dbName])) {
1406 $newObject->$dbName .= $fieldsToSuffix[$dbName];
1408 if (isset($fieldsToReplace[$dbName])) {
1409 $newObject->$dbName = $fieldsToReplace[$dbName];
1412 if ($type == 'Timestamp' ||
$type == 'Date') {
1413 $newObject->$dbName = CRM_Utils_Date
::isoToMysql($newObject->$dbName);
1417 foreach ($newData as $k => $v) {
1418 $newObject->$k = $v;
1428 * Cascade update through related entities.
1430 * @param string $daoName
1433 * @param array $newData
1437 public static function cascadeUpdate($daoName, $fromId, $toId, $newData = array()) {
1438 $object = new $daoName();
1439 $object->id
= $fromId;
1441 if ($object->find(TRUE)) {
1442 $newObject = new $daoName();
1443 $newObject->id
= $toId;
1445 if ($newObject->find(TRUE)) {
1446 $fields = &$object->fields();
1447 foreach ($fields as $name => $value) {
1448 if ($name == 'id' ||
$value['name'] == 'id') {
1449 // copy everything but the id!
1453 $colName = $value['name'];
1454 $newObject->$colName = $object->$colName;
1456 if (substr($name, -5) == '_date' ||
1457 substr($name, -10) == '_date_time'
1459 $newObject->$colName = CRM_Utils_Date
::isoToMysql($newObject->$colName);
1462 foreach ($newData as $k => $v) {
1463 $newObject->$k = $v;
1469 return CRM_Core_DAO
::$_nullObject;
1473 * Given the component id, compute the contact id
1474 * since its used for things like send email
1476 * @param $componentIDs
1477 * @param string $tableName
1481 public static function &getContactIDsFromComponent(&$componentIDs, $tableName) {
1482 $contactIDs = array();
1484 if (empty($componentIDs)) {
1488 $IDs = implode(',', $componentIDs);
1492 WHERE id IN ( $IDs )
1495 $dao = CRM_Core_DAO
::executeQuery($query);
1496 while ($dao->fetch()) {
1497 $contactIDs[] = $dao->contact_id
;
1503 * Fetch object based on array of properties.
1505 * @param string $daoName
1506 * Name of the dao object.
1507 * @param string $fieldIdName
1508 * @param int $fieldId
1510 * @param array $returnProperities
1511 * An assoc array of fields that need to be returned, eg array( 'first_name', 'last_name').
1514 * an object of type referenced by daoName
1516 public static function commonRetrieveAll($daoName, $fieldIdName = 'id', $fieldId, &$details, $returnProperities = NULL) {
1517 require_once str_replace('_', DIRECTORY_SEPARATOR
, $daoName) . ".php";
1518 $object = new $daoName();
1519 $object->$fieldIdName = $fieldId;
1521 // return only specific fields if returnproperties are sent
1522 if (!empty($returnProperities)) {
1523 $object->selectAdd();
1524 $object->selectAdd('id');
1525 $object->selectAdd(implode(',', $returnProperities));
1529 while ($object->fetch()) {
1530 $defaults = array();
1531 self
::storeValues($object, $defaults);
1532 $details[$object->id
] = $defaults;
1538 public static function dropAllTables() {
1540 // first drop all the custom tables we've created
1541 CRM_Core_BAO_CustomGroup
::dropAllTables();
1543 // drop all multilingual views
1544 CRM_Core_I18n_Schema
::dropAllViews();
1546 CRM_Utils_File
::sourceSQLFile(CIVICRM_DSN
,
1547 dirname(__FILE__
) . DIRECTORY_SEPARATOR
.
1548 '..' . DIRECTORY_SEPARATOR
.
1549 '..' . DIRECTORY_SEPARATOR
.
1550 'sql' . DIRECTORY_SEPARATOR
.
1551 'civicrm_drop.mysql'
1560 public static function escapeString($string) {
1561 static $_dao = NULL;
1564 // If this is an atypical case (e.g. preparing .sql files
1565 // before Civi has been installed), then we fallback to
1566 // DB-less escaping helper (mysql_real_escape_string).
1567 // Note: In typical usage, escapeString() will only
1568 // check one conditional ("if !$_dao") rather than
1569 // two conditionals ("if !defined(DSN)")
1570 if (!defined('CIVICRM_DSN')) {
1571 if (function_exists('mysql_real_escape_string')) {
1572 return mysql_real_escape_string($string);
1575 throw new CRM_Core_Exception("Cannot generate SQL. \"mysql_real_escape_string\" is missing. Have you installed PHP \"mysql\" extension?");
1579 $_dao = new CRM_Core_DAO();
1582 return $_dao->escape($string);
1586 * Escape a list of strings for use with "WHERE X IN (...)" queries.
1588 * @param array $strings
1589 * @param string $default
1590 * the value to use if $strings has no elements.
1592 * eg "abc","def","ghi"
1594 public static function escapeStrings($strings, $default = NULL) {
1595 static $_dao = NULL;
1597 $_dao = new CRM_Core_DAO();
1600 if (empty($strings)) {
1604 $escapes = array_map(array($_dao, 'escape'), $strings);
1605 return '"' . implode('","', $escapes) . '"';
1613 public static function escapeWildCardString($string) {
1615 // ensure we escape the single characters % and _ which are mysql wild
1616 // card characters and could come in via sortByCharacter
1617 // note that mysql does not escape these characters
1618 if ($string && in_array($string,
1619 array('%', '_', '%%', '_%')
1622 return '\\' . $string;
1625 return self
::escapeString($string);
1629 * Creates a test object, including any required objects it needs via recursion
1630 * createOnly: only create in database, do not store or return the objects (useful for perf testing)
1631 * ONLY USE FOR TESTING
1633 * @param string $daoName
1634 * @param array $params
1635 * @param int $numObjects
1636 * @param bool $createOnly
1638 * @return object|array|NULL
1639 * NULL if $createOnly. A single object if $numObjects==1. Otherwise, an array of multiple objects.
1641 public static function createTestObject(
1647 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
1648 // so we re-set here in case
1649 $config = CRM_Core_Config
::singleton();
1650 $config->backtrace
= TRUE;
1652 static $counter = 0;
1653 CRM_Core_DAO
::$_testEntitiesToSkip = array(
1654 'CRM_Core_DAO_Worldregion',
1655 'CRM_Core_DAO_StateProvince',
1656 'CRM_Core_DAO_Country',
1657 'CRM_Core_DAO_Domain',
1658 'CRM_Financial_DAO_FinancialType',
1659 //because valid ones exist & we use pick them due to pseudoconstant can't reliably create & delete these
1662 // Prefer to instantiate BAO's instead of DAO's (when possible)
1663 // so that assignTestValue()/assignTestFK() can be overloaded.
1664 $baoName = str_replace('_DAO_', '_BAO_', $daoName);
1665 if (class_exists($baoName)) {
1666 $daoName = $baoName;
1669 for ($i = 0; $i < $numObjects; ++
$i) {
1672 /** @var CRM_Core_DAO $object */
1673 $object = new $daoName();
1675 $fields = &$object->fields();
1676 foreach ($fields as $fieldName => $fieldDef) {
1677 $dbName = $fieldDef['name'];
1678 $FKClassName = CRM_Utils_Array
::value('FKClassName', $fieldDef);
1679 $required = CRM_Utils_Array
::value('required', $fieldDef);
1681 if (CRM_Utils_Array
::value($dbName, $params) !== NULL && !is_array($params[$dbName])) {
1682 $object->$dbName = $params[$dbName];
1685 elseif ($dbName != 'id') {
1686 if ($FKClassName != NULL) {
1687 $object->assignTestFK($fieldName, $fieldDef, $params);
1691 $object->assignTestValue($fieldName, $fieldDef, $counter);
1699 $objects[$i] = $object;
1709 elseif ($numObjects == 1) {
1718 * Deletes the this object plus any dependent objects that are associated with it.
1719 * ONLY USE FOR TESTING
1721 * @param string $daoName
1722 * @param array $params
1724 public static function deleteTestObjects($daoName, $params = array()) {
1725 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
1726 // so we re-set here in case
1727 $config = CRM_Core_Config
::singleton();
1728 $config->backtrace
= TRUE;
1730 $object = new $daoName();
1731 $object->id
= CRM_Utils_Array
::value('id', $params);
1733 $deletions = array(); // array(array(0 => $daoName, 1 => $daoParams))
1734 if ($object->find(TRUE)) {
1736 $fields = &$object->fields();
1737 foreach ($fields as $name => $value) {
1739 $dbName = $value['name'];
1741 $FKClassName = CRM_Utils_Array
::value('FKClassName', $value);
1742 $required = CRM_Utils_Array
::value('required', $value);
1743 if ($FKClassName != NULL
1745 && !in_array($FKClassName, CRM_Core_DAO
::$_testEntitiesToSkip)
1746 && ($required ||
$dbName == 'contact_id')
1747 //I'm a bit stuck on this one - we might need to change the singleValueAlter so that the entities don't share a contact
1748 // to make this test process pass - line below makes pass for now
1749 && $dbName != 'member_of_contact_id'
1751 $deletions[] = array($FKClassName, array('id' => $object->$dbName)); // x
1758 foreach ($deletions as $deletion) {
1759 CRM_Core_DAO
::deleteTestObjects($deletion[0], $deletion[1]);
1764 * Set defaults when creating new entity.
1765 * (don't call this set defaults as already in use with different signature in some places)
1767 * @param array $params
1770 public static function setCreateDefaults(&$params, $defaults) {
1771 if (isset($params['id'])) {
1774 foreach ($defaults as $key => $value) {
1775 if (!array_key_exists($key, $params) ||
$params[$key] === NULL) {
1776 $params[$key] = $value;
1782 * @param string $prefix
1783 * @param bool $addRandomString
1784 * @param null $string
1788 public static function createTempTableName($prefix = 'civicrm', $addRandomString = TRUE, $string = NULL) {
1789 $tableName = $prefix . "_temp";
1791 if ($addRandomString) {
1793 $tableName .= "_" . $string;
1796 $tableName .= "_" . md5(uniqid('', TRUE));
1804 * @param bool $trigger
1808 public static function checkTriggerViewPermission($view = TRUE, $trigger = TRUE) {
1809 // test for create view and trigger permissions and if allowed, add the option to go multilingual
1811 // I'm not sure why we use the getStaticProperty for an error, rather than checking for DB_Error
1812 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
1813 $dao = new CRM_Core_DAO();
1815 $dao->query('CREATE OR REPLACE VIEW civicrm_domain_view AS SELECT * FROM civicrm_domain');
1816 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
1822 $result = $dao->query('CREATE TRIGGER civicrm_domain_trigger BEFORE INSERT ON civicrm_domain FOR EACH ROW BEGIN END');
1823 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError') ||
is_a($result, 'DB_Error')) {
1825 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1830 $dao->query('DROP TRIGGER IF EXISTS civicrm_domain_trigger');
1831 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
1833 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1840 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1841 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
1850 * @param null $message
1851 * @param bool $printDAO
1853 public static function debugPrint($message = NULL, $printDAO = TRUE) {
1854 CRM_Utils_System
::xMemory("{$message}: ");
1857 global $_DB_DATAOBJECT;
1859 foreach (array_keys($_DB_DATAOBJECT['RESULTS']) as $id) {
1860 $q[] = $_DB_DATAOBJECT['RESULTS'][$id]->query
;
1862 CRM_Core_Error
::debug('_DB_DATAOBJECT', $q);
1867 * Build a list of triggers via hook and add them to (err, reconcile them
1868 * with) the database.
1870 * @param string $tableName
1871 * the specific table requiring a rebuild; or NULL to rebuild all tables.
1872 * @param bool $force
1876 public static function triggerRebuild($tableName = NULL, $force = FALSE) {
1879 $logging = new CRM_Logging_Schema();
1880 $logging->triggerInfo($info, $tableName, $force);
1882 CRM_Core_I18n_Schema
::triggerInfo($info, $tableName);
1883 CRM_Contact_BAO_Contact
::triggerInfo($info, $tableName);
1885 CRM_Utils_Hook
::triggerInfo($info, $tableName);
1887 // drop all existing triggers on all tables
1888 $logging->dropTriggers($tableName);
1890 // now create the set of new triggers
1891 self
::createTriggers($info, $tableName);
1895 * Because sql functions are sometimes lost, esp during db migration, we check here to avoid numerous support requests
1896 * @see http://issues.civicrm.org/jira/browse/CRM-13822
1897 * TODO: Alternative solutions might be
1898 * * Stop using functions and find another way to strip numeric characters from phones
1899 * * Give better error messages (currently a missing fn fatals with "unknown error")
1901 public static function checkSqlFunctionsExist() {
1902 if (!self
::$_checkedSqlFunctionsExist) {
1903 self
::$_checkedSqlFunctionsExist = TRUE;
1904 $dao = CRM_Core_DAO
::executeQuery("SHOW function status WHERE db = database() AND name = 'civicrm_strip_non_numeric'");
1905 if (!$dao->fetch()) {
1906 self
::triggerRebuild();
1912 * Wrapper function to drop triggers.
1914 * @param string $tableName
1915 * the specific table requiring a rebuild; or NULL to rebuild all tables.
1917 public static function dropTriggers($tableName = NULL) {
1920 $logging = new CRM_Logging_Schema();
1921 $logging->triggerInfo($info, $tableName);
1923 // drop all existing triggers on all tables
1924 $logging->dropTriggers($tableName);
1928 * @param array $info
1929 * per hook_civicrm_triggerInfo.
1930 * @param string $onlyTableName
1931 * the specific table requiring a rebuild; or NULL to rebuild all tables.
1933 public static function createTriggers(&$info, $onlyTableName = NULL) {
1934 // Validate info array, should probably raise errors?
1935 if (is_array($info) == FALSE) {
1939 $triggers = array();
1941 // now enumerate the tables and the events and collect the same set in a different format
1942 foreach ($info as $value) {
1944 // clean the incoming data, skip malformed entries
1945 // TODO: malformed entries should raise errors or get logged.
1946 if (isset($value['table']) == FALSE ||
1947 isset($value['event']) == FALSE ||
1948 isset($value['when']) == FALSE ||
1949 isset($value['sql']) == FALSE
1954 if (is_string($value['table']) == TRUE) {
1955 $tables = array($value['table']);
1958 $tables = $value['table'];
1961 if (is_string($value['event']) == TRUE) {
1962 $events = array(strtolower($value['event']));
1965 $events = array_map('strtolower', $value['event']);
1968 $whenName = strtolower($value['when']);
1970 foreach ($tables as $tableName) {
1971 if (!isset($triggers[$tableName])) {
1972 $triggers[$tableName] = array();
1975 foreach ($events as $eventName) {
1976 $template_params = array('{tableName}', '{eventName}');
1977 $template_values = array($tableName, $eventName);
1979 $sql = str_replace($template_params,
1983 $variables = str_replace($template_params,
1985 CRM_Utils_Array
::value('variables', $value)
1988 if (!isset($triggers[$tableName][$eventName])) {
1989 $triggers[$tableName][$eventName] = array();
1992 if (!isset($triggers[$tableName][$eventName][$whenName])) {
1993 // We're leaving out cursors, conditions, and handlers for now
1994 // they are kind of dangerous in this context anyway
1995 // better off putting them in stored procedures
1996 $triggers[$tableName][$eventName][$whenName] = array(
1997 'variables' => array(),
2003 $triggers[$tableName][$eventName][$whenName]['variables'][] = $variables;
2006 $triggers[$tableName][$eventName][$whenName]['sql'][] = $sql;
2011 // now spit out the sql
2012 foreach ($triggers as $tableName => $tables) {
2013 if ($onlyTableName != NULL && $onlyTableName != $tableName) {
2016 foreach ($tables as $eventName => $events) {
2017 foreach ($events as $whenName => $parts) {
2018 $varString = implode("\n", $parts['variables']);
2019 $sqlString = implode("\n", $parts['sql']);
2020 $validName = CRM_Core_DAO
::shortenSQLName($tableName, 48, TRUE);
2021 $triggerName = "{$validName}_{$whenName}_{$eventName}";
2022 $triggerSQL = "CREATE TRIGGER $triggerName $whenName $eventName ON $tableName FOR EACH ROW BEGIN $varString $sqlString END";
2024 CRM_Core_DAO
::executeQuery("DROP TRIGGER IF EXISTS $triggerName");
2025 CRM_Core_DAO
::executeQuery(
2039 * Given a list of fields, create a list of references.
2041 * @param string $className
2042 * BAO/DAO class name.
2043 * @return array<CRM_Core_Reference_Interface>
2045 public static function createReferenceColumns($className) {
2047 $fields = $className::fields();
2048 foreach ($fields as $field) {
2049 if (isset($field['pseudoconstant'], $field['pseudoconstant']['optionGroupName'])) {
2050 $result[] = new CRM_Core_Reference_OptionValue(
2051 $className::getTableName(),
2053 'civicrm_option_value',
2054 CRM_Utils_Array
::value('keyColumn', $field['pseudoconstant'], 'value'),
2055 $field['pseudoconstant']['optionGroupName']
2063 * Find all records which refer to this entity.
2066 * Array of objects referencing this
2068 public function findReferences() {
2069 $links = self
::getReferencesToTable(static::getTableName());
2071 $occurrences = array();
2072 foreach ($links as $refSpec) {
2073 /** @var $refSpec CRM_Core_Reference_Interface */
2074 $daoName = CRM_Core_DAO_AllCoreTables
::getClassForTable($refSpec->getReferenceTable());
2075 $result = $refSpec->findReferences($this);
2077 while ($result->fetch()) {
2078 $obj = new $daoName();
2079 $obj->id
= $result->id
;
2080 $occurrences[] = $obj;
2085 return $occurrences;
2090 * each item has keys:
2094 * - table: string|null SQL table name
2095 * - key: string|null SQL column name
2097 public function getReferenceCounts() {
2098 $links = self
::getReferencesToTable(static::getTableName());
2101 foreach ($links as $refSpec) {
2102 /** @var $refSpec CRM_Core_Reference_Interface */
2103 $count = $refSpec->getReferenceCount($this);
2104 if ($count['count'] != 0) {
2109 foreach (CRM_Core_Component
::getEnabledComponents() as $component) {
2110 /** @var $component CRM_Core_Component_Info */
2111 $counts = array_merge($counts, $component->getReferenceCounts($this));
2113 CRM_Utils_Hook
::referenceCounts($this, $counts);
2119 * List all tables which have hard foreign keys to this table.
2121 * For now, this returns a description of every entity_id/entity_table
2123 * TODO: filter dynamic entity references on the $tableName, based on
2124 * schema metadata in dynamicForeignKey which enumerates a restricted
2125 * set of possible entity_table's.
2127 * @param string $tableName
2128 * Table referred to.
2131 * structure of table and column, listing every table with a
2132 * foreign key reference to $tableName, and the column where the key appears.
2134 public static function getReferencesToTable($tableName) {
2135 $refsFound = array();
2136 foreach (CRM_Core_DAO_AllCoreTables
::getClasses() as $daoClassName) {
2137 $links = $daoClassName::getReferenceColumns();
2138 $daoTableName = $daoClassName::getTableName();
2140 foreach ($links as $refSpec) {
2141 /** @var $refSpec CRM_Core_Reference_Interface */
2142 if ($refSpec->matchesTargetTable($tableName)) {
2143 $refsFound[] = $refSpec;
2151 * Lookup the value of a MySQL global configuration variable.
2153 * @param string $name
2154 * E.g. "thread_stack".
2155 * @param mixed $default
2158 public static function getGlobalSetting($name, $default = NULL) {
2159 // Alternatively, SELECT @@GLOBAL.thread_stack, but
2160 // that has been reported to fail under MySQL 5.0 for OS X
2161 $escapedName = self
::escapeString($name);
2162 $dao = CRM_Core_DAO
::executeQuery("SHOW VARIABLES LIKE '$escapedName'");
2163 if ($dao->fetch()) {
2172 * Get options for the called BAO object's field.
2173 * This function can be overridden by each BAO to add more logic related to context.
2174 * The overriding function will generally call the lower-level CRM_Core_PseudoConstant::get
2176 * @param string $fieldName
2177 * @param string $context
2178 * @see CRM_Core_DAO::buildOptionsContext
2179 * @param array $props
2180 * whatever is known about this bao object.
2182 * @return array|bool
2184 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
2185 // If a given bao does not override this function
2186 $baoName = get_called_class();
2187 return CRM_Core_PseudoConstant
::get($baoName, $fieldName, array(), $context);
2191 * Populate option labels for this object's fields.
2193 * @throws exception if called directly on the base class
2195 public function getOptionLabels() {
2196 $fields = $this->fields();
2197 if ($fields === NULL) {
2198 throw new Exception('Cannot call getOptionLabels on CRM_Core_DAO');
2200 foreach ($fields as $field) {
2201 $name = CRM_Utils_Array
::value('name', $field);
2202 if ($name && isset($this->$name)) {
2203 $label = CRM_Core_PseudoConstant
::getLabel(get_class($this), $name, $this->$name);
2204 if ($label !== FALSE) {
2205 // Append 'label' onto the field name
2206 $labelName = $name . '_label';
2207 $this->$labelName = $label;
2214 * Provides documentation and validation for the buildOptions $context param
2216 * @param string $context
2221 public static function buildOptionsContext($context = NULL) {
2223 'get' => "get: all options are returned, even if they are disabled; labels are translated.",
2224 'create' => "create: options are filtered appropriately for the object being created/updated; labels are translated.",
2225 'search' => "search: searchable options are returned; labels are translated.",
2226 'validate' => "validate: all options are returned, even if they are disabled; machine names are used in place of labels.",
2227 'abbreviate' => "abbreviate: enabled options are returned; labels are replaced with abbreviations.",
2228 'match' => "match: enabled options are returned using machine names as keys; labels are translated.",
2230 // Validation: enforce uniformity of this param
2231 if ($context !== NULL && !isset($contexts[$context])) {
2232 throw new Exception("'$context' is not a valid context for buildOptions.");
2238 * @param string $fieldName
2239 * @return bool|array
2241 public function getFieldSpec($fieldName) {
2242 $fields = $this->fields();
2243 $fieldKeys = $this->fieldKeys();
2245 // Support "unique names" as well as sql names
2246 $fieldKey = $fieldName;
2247 if (empty($fields[$fieldKey])) {
2248 $fieldKey = CRM_Utils_Array
::value($fieldName, $fieldKeys);
2250 // If neither worked then this field doesn't exist. Return false.
2251 if (empty($fields[$fieldKey])) {
2254 return $fields[$fieldKey];
2258 * Get SQL where clause for SQL filter syntax input parameters.
2260 * SQL version of api function to assign filters to the DAO based on the syntax
2261 * $field => array('IN' => array(4,6,9))
2263 * $field => array('LIKE' => array('%me%))
2266 * @param string $fieldName
2268 * @param array $filter
2269 * filter to be applied indexed by operator.
2270 * @param string $type
2271 * type of field (not actually used - nor in api @todo ).
2272 * @param string $alias
2273 * alternative field name ('as') @todo- not actually used.
2274 * @param bool $returnSanitisedArray
2275 * Return a sanitised array instead of a clause.
2276 * this is primarily so we can add filters @ the api level to the Query object based fields
2280 * @return NULL|string|array
2281 * a string is returned if $returnSanitisedArray is not set, otherwise and Array or NULL
2282 * depending on whether it is supported as yet
2284 public static function createSQLFilter($fieldName, $filter, $type, $alias = NULL, $returnSanitisedArray = FALSE) {
2285 foreach ($filter as $operator => $criteria) {
2286 if (in_array($operator, self
::acceptedSQLOperators(), TRUE)) {
2287 switch ($operator) {
2291 if (!$returnSanitisedArray) {
2292 return (sprintf('%s %s', $fieldName, $operator));
2295 return (sprintf('%s %s ', $fieldName, $operator));
2299 // ternary operators
2302 if (empty($criteria[0]) ||
empty($criteria[1])) {
2303 throw new Exception("invalid criteria for $operator");
2305 if (!$returnSanitisedArray) {
2306 return (sprintf('%s ' . $operator . ' "%s" AND "%s"', $fieldName, CRM_Core_DAO
::escapeString($criteria[0]), CRM_Core_DAO
::escapeString($criteria[1])));
2309 return NULL; // not yet implemented (tests required to implement)
2316 if (empty($criteria)) {
2317 throw new Exception("invalid criteria for $operator");
2319 $escapedCriteria = array_map(array(
2323 if (!$returnSanitisedArray) {
2324 return (sprintf('%s %s ("%s")', $fieldName, $operator, implode('", "', $escapedCriteria)));
2326 return $escapedCriteria;
2331 if (!$returnSanitisedArray) {
2332 return (sprintf('%s %s "%s"', $fieldName, $operator, CRM_Core_DAO
::escapeString($criteria)));
2335 return NULL; // not yet implemented (tests required to implement)
2343 * @see http://issues.civicrm.org/jira/browse/CRM-9150
2344 * support for other syntaxes is discussed in ticket but being put off for now
2347 public static function acceptedSQLOperators() {
2368 * SQL has a limit of 64 characters on various names:
2369 * table name, trigger name, column name ...
2371 * For custom groups and fields we generated names from user entered input
2372 * which can be longer than this length, this function helps with creating
2373 * strings that meet various criteria.
2375 * @param string $string
2376 * The string to be shortened.
2377 * @param int $length
2378 * The max length of the string.
2380 * @param bool $makeRandom
2384 public static function shortenSQLName($string, $length = 60, $makeRandom = FALSE) {
2385 // early return for strings that meet the requirements
2386 if (strlen($string) <= $length) {
2390 // easy return for calls that dont need a randomized uniq string
2392 return substr($string, 0, $length);
2395 // the string is longer than the length and we need a uniq string
2396 // for the same tablename we need the same uniq string every time
2397 // hence we use md5 on the string, which is not random
2398 // we'll append 8 characters to the end of the tableName
2399 $md5string = substr(md5($string), 0, 8);
2400 return substr($string, 0, $length - 8) . "_{$md5string}";
2404 * @param array $params
2406 public function setApiFilter(&$params) {