3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
37 require_once 'PEAR.php';
38 require_once 'DB/DataObject.php';
40 require_once 'CRM/Core/I18n.php';
45 class CRM_Core_DAO
extends DB_DataObject
{
48 * A null object so we can pass it as reference if / when needed
50 static $_nullObject = NULL;
51 static $_nullArray = array();
53 static $_dbColumnValueCache = NULL;
54 const NOT_NULL
= 1, IS_NULL
= 2,
56 VALUE_SEPARATOR
= "\ 1",
57 BULK_INSERT_COUNT
= 200,
58 BULK_INSERT_HIGH_COUNT
= 200,
59 // special value for mail bulk inserts to avoid
60 // potential duplication, assuming a smaller number reduces number of queries
61 // by some factor, so some tradeoff. CRM-8678
62 BULK_MAIL_INSERT_COUNT
= 10,
63 QUERY_FORMAT_WILDCARD
= 1,
64 QUERY_FORMAT_NO_QUOTES
= 2;
67 * Define entities that shouldn't be created or deleted when creating/ deleting
68 * test objects - this prevents world regions, countries etc from being added / deleted
71 static $_testEntitiesToSkip = array();
73 * The factory class for this application.
76 static $_factory = NULL;
78 static $_checkedSqlFunctionsExist = FALSE;
83 * @return \CRM_Core_DAO
85 public function __construct() {
87 $this->__table
= $this->getTableName();
91 * Empty definition for virtual function.
93 public static function getTableName() {
98 * Initialize the DAO object.
101 * The database connection string.
105 public static function init($dsn) {
106 $options = &PEAR
::getStaticProperty('DB_DataObject', 'options');
107 $options['database'] = $dsn;
108 if (defined('CIVICRM_DAO_DEBUG')) {
109 self
::DebugLevel(CIVICRM_DAO_DEBUG
);
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 shouldnt 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. DAO is kinda crappy in that there is an unwritten
271 * rule of one query per DAO. We attempt to get around this crappy restricrion
272 * 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.
336 public static function setFactory(&$factory) {
337 self
::$_factory = &$factory;
341 * Factory method to instantiate a new object from a table name.
343 * @param string $table
347 public function factory($table = '') {
348 if (!isset(self
::$_factory)) {
349 return parent
::factory($table);
352 return self
::$_factory->create($table);
356 * Initialization for all DAO objects. Since we access DB_DO programatically
357 * we need to set the links manually.
361 public function initialize() {
363 $this->query("SET NAMES utf8");
367 * Defines the default key as 'id'.
372 public function keys() {
381 * Tells DB_DataObject which keys use autoincrement.
382 * 'id' is autoincrementing by default.
387 public function sequenceKey() {
388 static $sequenceKeys;
389 if (!isset($sequenceKeys)) {
390 $sequenceKeys = array('id', TRUE);
392 return $sequenceKeys;
396 * Returns list of FK relationships.
400 * Array of CRM_Core_Reference_Interface
402 public static function getReferenceColumns() {
407 * Returns all the column names of this table.
412 public static function &fields() {
418 * Get/set an associative array of table columns
423 public function table() {
424 $fields = &$this->fields();
428 foreach ($fields as $name => $value) {
429 $table[$value['name']] = $value['type'];
430 if (!empty($value['required'])) {
431 $table[$value['name']] +
= self
::DB_DAO_NOTNULL
;
442 public function save() {
443 if (!empty($this->id
)) {
446 $event = new \Civi\Core\DAO\Event\
PostUpdate($this);
447 \Civi\Core\Container
::singleton()->get('dispatcher')->dispatch("DAO::post-update", $event);
452 $event = new \Civi\Core\DAO\Event\
PostUpdate($this);
453 \Civi\Core\Container
::singleton()->get('dispatcher')->dispatch("DAO::post-insert", $event);
457 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\Core\Container
::singleton()->get('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.
577 public static function storeValues(&$object, &$values) {
578 $fields = &$object->fields();
579 foreach ($fields as $name => $value) {
580 $dbName = $value['name'];
581 if (isset($object->$dbName) && $object->$dbName !== 'null') {
582 $values[$dbName] = $object->$dbName;
583 if ($name != $dbName) {
584 $values[$name] = $object->$dbName;
591 * Create an attribute for this specific field. We only do this for strings and text
593 * @param array $field
594 * The field under task.
597 * the attributes for the object
599 public static function makeAttribute($field) {
601 if (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_STRING
) {
602 $maxLength = CRM_Utils_Array
::value('maxlength', $field);
603 $size = CRM_Utils_Array
::value('size', $field);
604 if ($maxLength ||
$size) {
605 $attributes = array();
607 $attributes['maxlength'] = $maxLength;
610 $attributes['size'] = $size;
615 elseif (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_TEXT
) {
616 $rows = CRM_Utils_Array
::value('rows', $field);
620 $cols = CRM_Utils_Array
::value('cols', $field);
625 $attributes = array();
626 $attributes['rows'] = $rows;
627 $attributes['cols'] = $cols;
630 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
) {
631 $attributes['size'] = 6;
632 $attributes['maxlength'] = 14;
640 * Get the size and maxLength attributes for this text field.
641 * (or for all text fields) in the DAO object.
643 * @param string $class
645 * @param string $fieldName
646 * Field that i'm interested in or null if.
647 * you want the attributes for all DAO text fields
650 * assoc array of name => attribute pairs
652 public static function getAttribute($class, $fieldName = NULL) {
653 $object = new $class();
654 $fields = &$object->fields();
655 if ($fieldName != NULL) {
656 $field = CRM_Utils_Array
::value($fieldName, $fields);
657 return self
::makeAttribute($field);
660 $attributes = array();
661 foreach ($fields as $name => $field) {
662 $attribute = self
::makeAttribute($field);
664 $attributes[$name] = $attribute;
668 if (!empty($attributes)) {
680 public static function transaction($type) {
681 CRM_Core_Error
::fatal('This function is obsolete, please use CRM_Core_Transaction');
685 * Check if there is a record with the same name in the db.
687 * @param string $value
688 * The value of the field we are checking.
689 * @param string $daoName
690 * The dao object name.
691 * @param string $daoID
692 * The id of the object being updated. u can change your name.
693 * as long as there is no conflict
694 * @param string $fieldName
695 * The name of the field in the DAO.
698 * true if object exists
700 public static function objectExists($value, $daoName, $daoID, $fieldName = 'name') {
701 $object = new $daoName();
702 $object->$fieldName = $value;
704 $config = CRM_Core_Config
::singleton();
706 if ($object->find(TRUE)) {
707 return ($daoID && $object->id
== $daoID) ?
TRUE : FALSE;
715 * Check if there is a given column in a specific table.
717 * @param string $tableName
718 * @param string $columnName
719 * @param bool $i18nRewrite
720 * Whether to rewrite the query on multilingual setups.
723 * true if exists, else false
725 public static function checkFieldExists($tableName, $columnName, $i18nRewrite = TRUE) {
731 $params = array(1 => array($columnName, 'String'));
732 $dao = CRM_Core_DAO
::executeQuery($query, $params, TRUE, NULL, FALSE, $i18nRewrite);
733 $result = $dao->fetch() ?
TRUE : FALSE;
739 * Returns the storage engine used by given table-name(optional).
740 * Otherwise scans all the tables and return an array of all the
741 * distinct storage engines being used.
743 * @param string $tableName
745 * @param int $maxTablesToCheck
746 * @param string $fieldName
750 public static function getStorageValues($tableName = NULL, $maxTablesToCheck = 10, $fieldName = 'Engine') {
752 $query = "SHOW TABLE STATUS LIKE %1";
756 if (isset($tableName)) {
757 $params = array(1 => array($tableName, 'String'));
760 $params = array(1 => array('civicrm_%', 'String'));
763 $dao = CRM_Core_DAO
::executeQuery($query, $params);
766 while ($dao->fetch()) {
767 if (isset($values[$dao->$fieldName]) ||
768 // ignore import and other temp tables
769 strpos($dao->Name
, 'civicrm_import_job_') !== FALSE ||
770 strpos($dao->Name
, '_temp') !== FALSE
774 $values[$dao->$fieldName] = 1;
776 if ($maxTablesToCheck &&
777 $count >= $maxTablesToCheck
787 * @param int $maxTablesToCheck
791 public static function isDBMyISAM($maxTablesToCheck = 10) {
792 // show error if any of the tables, use 'MyISAM' storage engine.
793 $engines = self
::getStorageValues(NULL, $maxTablesToCheck);
794 if (array_key_exists('MyISAM', $engines)) {
801 * Checks if a constraint exists for a specified table.
803 * @param string $tableName
804 * @param string $constraint
807 * true if constraint exists, false otherwise
809 public static function checkConstraintExists($tableName, $constraint) {
810 static $show = array();
812 if (!array_key_exists($tableName, $show)) {
813 $query = "SHOW CREATE TABLE $tableName";
814 $dao = CRM_Core_DAO
::executeQuery($query);
816 if (!$dao->fetch()) {
817 CRM_Core_Error
::fatal();
821 $show[$tableName] = $dao->Create_Table
;
824 return preg_match("/\b$constraint\b/i", $show[$tableName]) ?
TRUE : FALSE;
828 * Checks if CONSTRAINT keyword exists for a specified table.
830 * @param array $tables
835 * true if CONSTRAINT keyword exists, false otherwise
837 public static function schemaRequiresRebuilding($tables = array("civicrm_contact")) {
839 foreach ($tables as $tableName) {
840 if (!array_key_exists($tableName, $show)) {
841 $query = "SHOW CREATE TABLE $tableName";
842 $dao = CRM_Core_DAO
::executeQuery($query);
844 if (!$dao->fetch()) {
845 CRM_Core_Error
::fatal();
849 $show[$tableName] = $dao->Create_Table
;
852 $result = preg_match("/\bCONSTRAINT\b\s/i", $show[$tableName]) ?
TRUE : FALSE;
853 if ($result == TRUE) {
864 * Checks if the FK constraint name is in the format 'FK_tableName_columnName'
865 * for a specified column of a table.
867 * @param string $tableName
868 * @param string $columnName
871 * true if in format, false otherwise
873 public static function checkFKConstraintInFormat($tableName, $columnName) {
874 static $show = array();
876 if (!array_key_exists($tableName, $show)) {
877 $query = "SHOW CREATE TABLE $tableName";
878 $dao = CRM_Core_DAO
::executeQuery($query);
880 if (!$dao->fetch()) {
881 CRM_Core_Error
::fatal();
885 $show[$tableName] = $dao->Create_Table
;
887 $constraint = "`FK_{$tableName}_{$columnName}`";
888 $pattern = "/\bCONSTRAINT\b\s+%s\s+\bFOREIGN\s+KEY\b\s/i";
889 return preg_match(sprintf($pattern, $constraint), $show[$tableName]) ?
TRUE : FALSE;
893 * Check whether a specific column in a specific table has always the same value.
895 * @param string $tableName
896 * @param string $columnName
897 * @param string $columnValue
900 * true if the value is always $columnValue, false otherwise
902 public static function checkFieldHasAlwaysValue($tableName, $columnName, $columnValue) {
903 $query = "SELECT * FROM $tableName WHERE $columnName != '$columnValue'";
904 $dao = CRM_Core_DAO
::executeQuery($query);
905 $result = $dao->fetch() ?
FALSE : TRUE;
911 * Check whether a specific column in a specific table is always NULL.
913 * @param string $tableName
914 * @param string $columnName
917 * true if if the value is always NULL, false otherwise
919 public static function checkFieldIsAlwaysNull($tableName, $columnName) {
920 $query = "SELECT * FROM $tableName WHERE $columnName IS NOT NULL";
921 $dao = CRM_Core_DAO
::executeQuery($query);
922 $result = $dao->fetch() ?
FALSE : TRUE;
928 * Check if there is a given table in the database.
930 * @param string $tableName
933 * true if exists, else false
935 public static function checkTableExists($tableName) {
940 $params = array(1 => array($tableName, 'String'));
942 $dao = CRM_Core_DAO
::executeQuery($query, $params);
943 $result = $dao->fetch() ?
TRUE : FALSE;
953 public function checkVersion($version) {
958 $dbVersion = CRM_Core_DAO
::singleValueQuery($query);
959 return trim($version) == trim($dbVersion) ?
TRUE : FALSE;
963 * Find a DAO object for the given ID and return it.
966 * Id of the DAO object being searched for.
969 * Object of the type of the class that called this function.
971 public static function findById($id) {
972 $object = new static();
974 if (!$object->find(TRUE)) {
975 throw new Exception("Unable to find a " . get_called_class() . " with id {$id}.");
981 * Given a DAO name, a column name and a column value, find the record and GET the value of another column in that record
983 * @param string $daoName
984 * Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact).
985 * @param int $searchValue
986 * Value of the column you want to search by.
987 * @param string $returnColumn
988 * Name of the column you want to GET the value of.
989 * @param string $searchColumn
990 * Name of the column you want to search by.
992 * Skip use of the cache.
994 * @return string|null
995 * Value of $returnColumn in the retrieved record
997 public static function getFieldValue($daoName, $searchValue, $returnColumn = 'name', $searchColumn = 'id', $force = FALSE) {
999 empty($searchValue) ||
1000 trim(strtolower($searchValue)) == 'null'
1002 // adding this year since developers forget to check for an id
1003 // or for the 'null' (which is a bad DAO kludge)
1004 // and hence we get the first value in the db
1005 CRM_Core_Error
::fatal();
1008 $cacheKey = "{$daoName}:{$searchValue}:{$returnColumn}:{$searchColumn}";
1009 if (self
::$_dbColumnValueCache === NULL) {
1010 self
::$_dbColumnValueCache = array();
1013 if (!array_key_exists($cacheKey, self
::$_dbColumnValueCache) ||
$force) {
1014 $object = new $daoName();
1015 $object->$searchColumn = $searchValue;
1016 $object->selectAdd();
1017 $object->selectAdd($returnColumn);
1020 if ($object->find(TRUE)) {
1021 $result = $object->$returnColumn;
1025 self
::$_dbColumnValueCache[$cacheKey] = $result;
1027 return self
::$_dbColumnValueCache[$cacheKey];
1031 * Given a DAO name, a column name and a column value, find the record and SET the value of another column in that record
1033 * @param string $daoName
1034 * Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact).
1035 * @param int $searchValue
1036 * Value of the column you want to search by.
1037 * @param string $setColumn
1038 * Name of the column you want to SET the value of.
1039 * @param string $setValue
1040 * SET the setColumn to this value.
1041 * @param string $searchColumn
1042 * Name of the column you want to search by.
1045 * true if we found and updated the object, else false
1047 public static function setFieldValue($daoName, $searchValue, $setColumn, $setValue, $searchColumn = 'id') {
1048 $object = new $daoName();
1049 $object->selectAdd();
1050 $object->selectAdd("$searchColumn, $setColumn");
1051 $object->$searchColumn = $searchValue;
1053 if ($object->find(TRUE)) {
1054 $object->$setColumn = $setValue;
1055 if ($object->save()) {
1066 * @param array|object $sort either array or CRM_Utils_Sort
1067 * @param string $default
1068 * Default sort value.
1073 public static function getSortString($sort, $default = NULL) {
1074 // check if sort is of type CRM_Utils_Sort
1075 if (is_a($sort, 'CRM_Utils_Sort')) {
1076 return $sort->orderBy();
1079 // is it an array specified as $field => $sortDirection ?
1081 foreach ($sort as $k => $v) {
1082 $sortString .= "$k $v,";
1084 return rtrim($sortString, ',');
1090 * Fetch object based on array of properties.
1092 * @param string $daoName
1093 * Name of the dao object.
1094 * @param array $params
1095 * (reference ) an assoc array of name/value pairs.
1096 * @param array $defaults
1097 * (reference ) an assoc array to hold the flattened values.
1098 * @param array $returnProperities
1099 * An assoc array of fields that need to be returned, eg array( 'first_name', 'last_name').
1102 * an object of type referenced by daoName
1104 public static function commonRetrieve($daoName, &$params, &$defaults, $returnProperities = NULL) {
1105 $object = new $daoName();
1106 $object->copyValues($params);
1108 // return only specific fields if returnproperties are sent
1109 if (!empty($returnProperities)) {
1110 $object->selectAdd();
1111 $object->selectAdd(implode(',', $returnProperities));
1114 if ($object->find(TRUE)) {
1115 self
::storeValues($object, $defaults);
1122 * Delete the object records that are associated with this contact.
1124 * @param string $daoName
1125 * Name of the dao object.
1126 * @param int $contactId
1127 * Id of the contact to delete.
1131 public static function deleteEntityContact($daoName, $contactId) {
1132 $object = new $daoName();
1134 $object->entity_table
= 'civicrm_contact';
1135 $object->entity_id
= $contactId;
1142 * @param string $query
1143 * Query to be executed.
1145 * @param array $params
1146 * @param bool $abort
1147 * @param null $daoName
1148 * @param bool $freeDAO
1149 * @param bool $i18nRewrite
1150 * @param bool $trapException
1152 * @return CRM_Core_DAO|object
1153 * object that holds the results of the query
1154 * NB - if this is defined as just returning a DAO phpstorm keeps pointing
1155 * out all the properties that are not part of the DAO
1157 public static function &executeQuery(
1163 $i18nRewrite = TRUE,
1164 $trapException = FALSE
1166 $queryStr = self
::composeQuery($query, $params, $abort);
1169 $dao = new CRM_Core_DAO();
1172 $dao = new $daoName();
1175 if ($trapException) {
1176 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
1179 $result = $dao->query($queryStr, $i18nRewrite);
1181 if (is_a($result, 'DB_Error')) {
1186 preg_match('/^(insert|update|delete|create|drop|replace)/i', $queryStr)
1188 // we typically do this for insert/update/delete statements OR if explicitly asked to
1196 * Execute a query and get the single result.
1198 * @param string $query
1199 * Query to be executed.
1200 * @param array $params
1201 * @param bool $abort
1202 * @param bool $i18nRewrite
1203 * @return string|null
1204 * the result of the query if any
1207 public static function &singleValueQuery(
1213 $queryStr = self
::composeQuery($query, $params, $abort);
1215 static $_dao = NULL;
1218 $_dao = new CRM_Core_DAO();
1221 $_dao->query($queryStr, $i18nRewrite);
1223 $result = $_dao->getDatabaseResult();
1226 $row = $result->fetchRow();
1237 * @param array $params
1238 * @param bool $abort
1243 public static function composeQuery($query, &$params, $abort = TRUE) {
1245 foreach ($params as $key => $item) {
1246 if (is_numeric($key)) {
1247 if (CRM_Utils_Type
::validate($item[0], $item[1]) !== NULL) {
1248 $item[0] = self
::escapeString($item[0]);
1249 if ($item[1] == 'String' ||
1250 $item[1] == 'Memo' ||
1253 // Support class constants stipulating wildcard characters and/or
1254 // non-quoting of strings. Also support legacy code which may be
1255 // passing in TRUE or 1 for $item[2], which used to indicate the
1256 // use of wildcard characters.
1257 if (!empty($item[2])) {
1258 if ($item[2] & CRM_Core_DAO
::QUERY_FORMAT_WILDCARD ||
$item[2] === TRUE) {
1259 $item[0] = "'%{$item[0]}%'";
1261 elseif (!($item[2] & CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
)) {
1262 $item[0] = "'{$item[0]}'";
1266 $item[0] = "'{$item[0]}'";
1270 if (($item[1] == 'Date' ||
$item[1] == 'Timestamp') &&
1271 strlen($item[0]) == 0
1276 $tr['%' . $key] = $item[0];
1279 CRM_Core_Error
::fatal("{$item[0]} is not of type {$item[1]}");
1284 return strtr($query, $tr);
1290 public static function freeResult($ids = NULL) {
1291 global $_DB_DATAOBJECT;
1294 if (!$_DB_DATAOBJECT ||
1295 !isset($_DB_DATAOBJECT['RESULTS'])
1299 $ids = array_keys($_DB_DATAOBJECT['RESULTS']);
1302 foreach ($ids as $id) {
1303 if (isset($_DB_DATAOBJECT['RESULTS'][$id])) {
1304 if (is_resource($_DB_DATAOBJECT['RESULTS'][$id]->result
)) {
1305 mysql_free_result($_DB_DATAOBJECT['RESULTS'][$id]->result
);
1307 unset($_DB_DATAOBJECT['RESULTS'][$id]);
1310 if (isset($_DB_DATAOBJECT['RESULTFIELDS'][$id])) {
1311 unset($_DB_DATAOBJECT['RESULTFIELDS'][$id]);
1317 * make a shallow copy of an object.
1318 * and all the fields in the object
1320 * @param string $daoName
1322 * @param array $criteria
1323 * Array of all the fields & values.
1324 * on which basis to copy
1325 * @param array $newData
1326 * Array of all the fields & values.
1327 * to be copied besides the other fields
1328 * @param string $fieldsFix
1329 * Array of fields that you want to prefix/suffix/replace.
1330 * @param string $blockCopyOfDependencies
1331 * Fields that you want to block from.
1335 * @return CRM_Core_DAO
1336 * the newly created copy of the object
1338 public static function ©Generic($daoName, $criteria, $newData = NULL, $fieldsFix = NULL, $blockCopyOfDependencies = NULL) {
1339 $object = new $daoName();
1341 $object->id
= $criteria['id'];
1344 foreach ($criteria as $key => $value) {
1345 $object->$key = $value;
1350 while ($object->fetch()) {
1352 // all the objects except with $blockCopyOfDependencies set
1353 // be copied - addresses #CRM-1962
1355 if ($blockCopyOfDependencies && $object->$blockCopyOfDependencies) {
1359 $newObject = new $daoName();
1361 $fields = &$object->fields();
1362 if (!is_array($fieldsFix)) {
1363 $fieldsToPrefix = array();
1364 $fieldsToSuffix = array();
1365 $fieldsToReplace = array();
1367 if (!empty($fieldsFix['prefix'])) {
1368 $fieldsToPrefix = $fieldsFix['prefix'];
1370 if (!empty($fieldsFix['suffix'])) {
1371 $fieldsToSuffix = $fieldsFix['suffix'];
1373 if (!empty($fieldsFix['replace'])) {
1374 $fieldsToReplace = $fieldsFix['replace'];
1377 foreach ($fields as $name => $value) {
1378 if ($name == 'id' ||
$value['name'] == 'id') {
1379 // copy everything but the id!
1383 $dbName = $value['name'];
1384 $type = CRM_Utils_Type
::typeToString($value['type']);
1385 $newObject->$dbName = $object->$dbName;
1386 if (isset($fieldsToPrefix[$dbName])) {
1387 $newObject->$dbName = $fieldsToPrefix[$dbName] . $newObject->$dbName;
1389 if (isset($fieldsToSuffix[$dbName])) {
1390 $newObject->$dbName .= $fieldsToSuffix[$dbName];
1392 if (isset($fieldsToReplace[$dbName])) {
1393 $newObject->$dbName = $fieldsToReplace[$dbName];
1396 if ($type == 'Timestamp' ||
$type == 'Date') {
1397 $newObject->$dbName = CRM_Utils_Date
::isoToMysql($newObject->$dbName);
1401 foreach ($newData as $k => $v) {
1402 $newObject->$k = $v;
1412 * Cascade update through related entities.
1414 * @param string $daoName
1417 * @param array $newData
1421 public static function cascadeUpdate($daoName, $fromId, $toId, $newData = array()) {
1422 $object = new $daoName();
1423 $object->id
= $fromId;
1425 if ($object->find(TRUE)) {
1426 $newObject = new $daoName();
1427 $newObject->id
= $toId;
1429 if ($newObject->find(TRUE)) {
1430 $fields = &$object->fields();
1431 foreach ($fields as $name => $value) {
1432 if ($name == 'id' ||
$value['name'] == 'id') {
1433 // copy everything but the id!
1437 $colName = $value['name'];
1438 $newObject->$colName = $object->$colName;
1440 if (substr($name, -5) == '_date' ||
1441 substr($name, -10) == '_date_time'
1443 $newObject->$colName = CRM_Utils_Date
::isoToMysql($newObject->$colName);
1446 foreach ($newData as $k => $v) {
1447 $newObject->$k = $v;
1453 return CRM_Core_DAO
::$_nullObject;
1457 * Given the component id, compute the contact id
1458 * since its used for things like send email
1460 * @param $componentIDs
1461 * @param string $tableName
1465 public static function &getContactIDsFromComponent(&$componentIDs, $tableName) {
1466 $contactIDs = array();
1468 if (empty($componentIDs)) {
1472 $IDs = implode(',', $componentIDs);
1476 WHERE id IN ( $IDs )
1479 $dao = CRM_Core_DAO
::executeQuery($query);
1480 while ($dao->fetch()) {
1481 $contactIDs[] = $dao->contact_id
;
1487 * Fetch object based on array of properties.
1489 * @param string $daoName
1490 * Name of the dao object.
1491 * @param string $fieldIdName
1492 * @param int $fieldId
1494 * @param array $returnProperities
1495 * An assoc array of fields that need to be returned, eg array( 'first_name', 'last_name').
1498 * an object of type referenced by daoName
1500 public static function commonRetrieveAll($daoName, $fieldIdName = 'id', $fieldId, &$details, $returnProperities = NULL) {
1501 require_once str_replace('_', DIRECTORY_SEPARATOR
, $daoName) . ".php";
1502 $object = new $daoName();
1503 $object->$fieldIdName = $fieldId;
1505 // return only specific fields if returnproperties are sent
1506 if (!empty($returnProperities)) {
1507 $object->selectAdd();
1508 $object->selectAdd('id');
1509 $object->selectAdd(implode(',', $returnProperities));
1513 while ($object->fetch()) {
1514 $defaults = array();
1515 self
::storeValues($object, $defaults);
1516 $details[$object->id
] = $defaults;
1522 public static function dropAllTables() {
1524 // first drop all the custom tables we've created
1525 CRM_Core_BAO_CustomGroup
::dropAllTables();
1527 // drop all multilingual views
1528 CRM_Core_I18n_Schema
::dropAllViews();
1530 CRM_Utils_File
::sourceSQLFile(CIVICRM_DSN
,
1531 dirname(__FILE__
) . DIRECTORY_SEPARATOR
.
1532 '..' . DIRECTORY_SEPARATOR
.
1533 '..' . DIRECTORY_SEPARATOR
.
1534 'sql' . DIRECTORY_SEPARATOR
.
1535 'civicrm_drop.mysql'
1544 public static function escapeString($string) {
1545 static $_dao = NULL;
1548 // If this is an atypical case (e.g. preparing .sql files
1549 // before Civi has been installed), then we fallback to
1550 // DB-less escaping helper (mysql_real_escape_string).
1551 // Note: In typical usage, escapeString() will only
1552 // check one conditional ("if !$_dao") rather than
1553 // two conditionals ("if !defined(DSN)")
1554 if (!defined('CIVICRM_DSN')) {
1555 if (function_exists('mysql_real_escape_string')) {
1556 return mysql_real_escape_string($string);
1559 throw new CRM_Core_Exception("Cannot generate SQL. \"mysql_real_escape_string\" is missing. Have you installed PHP \"mysql\" extension?");
1563 $_dao = new CRM_Core_DAO();
1566 return $_dao->escape($string);
1570 * Escape a list of strings for use with "WHERE X IN (...)" queries.
1572 * @param array $strings
1573 * @param string $default
1574 * the value to use if $strings has no elements.
1576 * eg "abc","def","ghi"
1578 public static function escapeStrings($strings, $default = NULL) {
1579 static $_dao = NULL;
1581 $_dao = new CRM_Core_DAO();
1584 if (empty($strings)) {
1588 $escapes = array_map(array($_dao, 'escape'), $strings);
1589 return '"' . implode('","', $escapes) . '"';
1597 public static function escapeWildCardString($string) {
1599 // ensure we escape the single characters % and _ which are mysql wild
1600 // card characters and could come in via sortByCharacter
1601 // note that mysql does not escape these characters
1602 if ($string && in_array($string,
1603 array('%', '_', '%%', '_%')
1606 return '\\' . $string;
1609 return self
::escapeString($string);
1613 * Creates a test object, including any required objects it needs via recursion
1614 * createOnly: only create in database, do not store or return the objects (useful for perf testing)
1615 * ONLY USE FOR TESTING
1617 * @param string $daoName
1618 * @param array $params
1619 * @param int $numObjects
1620 * @param bool $createOnly
1622 * @return object|array|NULL
1623 * NULL if $createOnly. A single object if $numObjects==1. Otherwise, an array of multiple objects.
1625 public static function createTestObject(
1631 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
1632 // so we re-set here in case
1633 $config = CRM_Core_Config
::singleton();
1634 $config->backtrace
= TRUE;
1636 static $counter = 0;
1637 CRM_Core_DAO
::$_testEntitiesToSkip = array(
1638 'CRM_Core_DAO_Worldregion',
1639 'CRM_Core_DAO_StateProvince',
1640 'CRM_Core_DAO_Country',
1641 'CRM_Core_DAO_Domain',
1642 'CRM_Financial_DAO_FinancialType',
1643 //because valid ones exist & we use pick them due to pseudoconstant can't reliably create & delete these
1646 // Prefer to instantiate BAO's instead of DAO's (when possible)
1647 // so that assignTestValue()/assignTestFK() can be overloaded.
1648 $baoName = str_replace('_DAO_', '_BAO_', $daoName);
1649 if (class_exists($baoName)) {
1650 $daoName = $baoName;
1653 for ($i = 0; $i < $numObjects; ++
$i) {
1656 /** @var CRM_Core_DAO $object */
1657 $object = new $daoName();
1659 $fields = &$object->fields();
1660 foreach ($fields as $fieldName => $fieldDef) {
1661 $dbName = $fieldDef['name'];
1662 $FKClassName = CRM_Utils_Array
::value('FKClassName', $fieldDef);
1663 $required = CRM_Utils_Array
::value('required', $fieldDef);
1665 if (CRM_Utils_Array
::value($dbName, $params) !== NULL && !is_array($params[$dbName])) {
1666 $object->$dbName = $params[$dbName];
1669 elseif ($dbName != 'id') {
1670 if ($FKClassName != NULL) {
1671 $object->assignTestFK($fieldName, $fieldDef, $params);
1675 $object->assignTestValue($fieldName, $fieldDef, $counter);
1683 $objects[$i] = $object;
1693 elseif ($numObjects == 1) {
1702 * Deletes the this object plus any dependent objects that are associated with it.
1703 * ONLY USE FOR TESTING
1705 * @param string $daoName
1706 * @param array $params
1708 public static function deleteTestObjects($daoName, $params = array()) {
1709 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
1710 // so we re-set here in case
1711 $config = CRM_Core_Config
::singleton();
1712 $config->backtrace
= TRUE;
1714 $object = new $daoName();
1715 $object->id
= CRM_Utils_Array
::value('id', $params);
1717 $deletions = array(); // array(array(0 => $daoName, 1 => $daoParams))
1718 if ($object->find(TRUE)) {
1720 $fields = &$object->fields();
1721 foreach ($fields as $name => $value) {
1723 $dbName = $value['name'];
1725 $FKClassName = CRM_Utils_Array
::value('FKClassName', $value);
1726 $required = CRM_Utils_Array
::value('required', $value);
1727 if ($FKClassName != NULL
1729 && !in_array($FKClassName, CRM_Core_DAO
::$_testEntitiesToSkip)
1730 && ($required ||
$dbName == 'contact_id')
1731 //I'm a bit stuck on this one - we might need to change the singleValueAlter so that the entities don't share a contact
1732 // to make this test process pass - line below makes pass for now
1733 && $dbName != 'member_of_contact_id'
1735 $deletions[] = array($FKClassName, array('id' => $object->$dbName)); // x
1742 foreach ($deletions as $deletion) {
1743 CRM_Core_DAO
::deleteTestObjects($deletion[0], $deletion[1]);
1748 * Set defaults when creating new entity.
1749 * (don't call this set defaults as already in use with different signature in some places)
1751 * @param array $params
1754 public static function setCreateDefaults(&$params, $defaults) {
1755 if (isset($params['id'])) {
1758 foreach ($defaults as $key => $value) {
1759 if (!array_key_exists($key, $params) ||
$params[$key] === NULL) {
1760 $params[$key] = $value;
1766 * @param string $prefix
1767 * @param bool $addRandomString
1768 * @param null $string
1772 public static function createTempTableName($prefix = 'civicrm', $addRandomString = TRUE, $string = NULL) {
1773 $tableName = $prefix . "_temp";
1775 if ($addRandomString) {
1777 $tableName .= "_" . $string;
1780 $tableName .= "_" . md5(uniqid('', TRUE));
1788 * @param bool $trigger
1792 public static function checkTriggerViewPermission($view = TRUE, $trigger = TRUE) {
1793 // test for create view and trigger permissions and if allowed, add the option to go multilingual
1795 // I'm not sure why we use the getStaticProperty for an error, rather than checking for DB_Error
1796 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
1797 $dao = new CRM_Core_DAO();
1799 $dao->query('CREATE OR REPLACE VIEW civicrm_domain_view AS SELECT * FROM civicrm_domain');
1800 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
1806 $result = $dao->query('CREATE TRIGGER civicrm_domain_trigger BEFORE INSERT ON civicrm_domain FOR EACH ROW BEGIN END');
1807 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError') ||
is_a($result, 'DB_Error')) {
1809 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1814 $dao->query('DROP TRIGGER IF EXISTS civicrm_domain_trigger');
1815 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
1817 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1824 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1825 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
1834 * @param null $message
1835 * @param bool $printDAO
1837 public static function debugPrint($message = NULL, $printDAO = TRUE) {
1838 CRM_Utils_System
::xMemory("{$message}: ");
1841 global $_DB_DATAOBJECT;
1843 foreach (array_keys($_DB_DATAOBJECT['RESULTS']) as $id) {
1844 $q[] = $_DB_DATAOBJECT['RESULTS'][$id]->query
;
1846 CRM_Core_Error
::debug('_DB_DATAOBJECT', $q);
1851 * Build a list of triggers via hook and add them to (err, reconcile them
1852 * with) the database.
1854 * @param string $tableName
1855 * the specific table requiring a rebuild; or NULL to rebuild all tables.
1856 * @param bool $force
1860 public static function triggerRebuild($tableName = NULL, $force = FALSE) {
1863 $logging = new CRM_Logging_Schema();
1864 $logging->triggerInfo($info, $tableName, $force);
1866 CRM_Core_I18n_Schema
::triggerInfo($info, $tableName);
1867 CRM_Contact_BAO_Contact
::triggerInfo($info, $tableName);
1869 CRM_Utils_Hook
::triggerInfo($info, $tableName);
1871 // drop all existing triggers on all tables
1872 $logging->dropTriggers($tableName);
1874 // now create the set of new triggers
1875 self
::createTriggers($info, $tableName);
1879 * Because sql functions are sometimes lost, esp during db migration, we check here to avoid numerous support requests
1880 * @see http://issues.civicrm.org/jira/browse/CRM-13822
1881 * TODO: Alternative solutions might be
1882 * * Stop using functions and find another way to strip numeric characters from phones
1883 * * Give better error messages (currently a missing fn fatals with "unknown error")
1885 public static function checkSqlFunctionsExist() {
1886 if (!self
::$_checkedSqlFunctionsExist) {
1887 self
::$_checkedSqlFunctionsExist = TRUE;
1888 $dao = CRM_Core_DAO
::executeQuery("SHOW function status WHERE db = database() AND name = 'civicrm_strip_non_numeric'");
1889 if (!$dao->fetch()) {
1890 self
::triggerRebuild();
1896 * Wrapper function to drop triggers.
1898 * @param string $tableName
1899 * the specific table requiring a rebuild; or NULL to rebuild all tables.
1901 public static function dropTriggers($tableName = NULL) {
1904 $logging = new CRM_Logging_Schema();
1905 $logging->triggerInfo($info, $tableName);
1907 // drop all existing triggers on all tables
1908 $logging->dropTriggers($tableName);
1912 * @param array $info
1913 * per hook_civicrm_triggerInfo.
1914 * @param string $onlyTableName
1915 * the specific table requiring a rebuild; or NULL to rebuild all tables.
1917 public static function createTriggers(&$info, $onlyTableName = NULL) {
1918 // Validate info array, should probably raise errors?
1919 if (is_array($info) == FALSE) {
1923 $triggers = array();
1925 // now enumerate the tables and the events and collect the same set in a different format
1926 foreach ($info as $value) {
1928 // clean the incoming data, skip malformed entries
1929 // TODO: malformed entries should raise errors or get logged.
1930 if (isset($value['table']) == FALSE ||
1931 isset($value['event']) == FALSE ||
1932 isset($value['when']) == FALSE ||
1933 isset($value['sql']) == FALSE
1938 if (is_string($value['table']) == TRUE) {
1939 $tables = array($value['table']);
1942 $tables = $value['table'];
1945 if (is_string($value['event']) == TRUE) {
1946 $events = array(strtolower($value['event']));
1949 $events = array_map('strtolower', $value['event']);
1952 $whenName = strtolower($value['when']);
1954 foreach ($tables as $tableName) {
1955 if (!isset($triggers[$tableName])) {
1956 $triggers[$tableName] = array();
1959 foreach ($events as $eventName) {
1960 $template_params = array('{tableName}', '{eventName}');
1961 $template_values = array($tableName, $eventName);
1963 $sql = str_replace($template_params,
1967 $variables = str_replace($template_params,
1969 CRM_Utils_Array
::value('variables', $value)
1972 if (!isset($triggers[$tableName][$eventName])) {
1973 $triggers[$tableName][$eventName] = array();
1976 if (!isset($triggers[$tableName][$eventName][$whenName])) {
1977 // We're leaving out cursors, conditions, and handlers for now
1978 // they are kind of dangerous in this context anyway
1979 // better off putting them in stored procedures
1980 $triggers[$tableName][$eventName][$whenName] = array(
1981 'variables' => array(),
1987 $triggers[$tableName][$eventName][$whenName]['variables'][] = $variables;
1990 $triggers[$tableName][$eventName][$whenName]['sql'][] = $sql;
1995 // now spit out the sql
1996 foreach ($triggers as $tableName => $tables) {
1997 if ($onlyTableName != NULL && $onlyTableName != $tableName) {
2000 foreach ($tables as $eventName => $events) {
2001 foreach ($events as $whenName => $parts) {
2002 $varString = implode("\n", $parts['variables']);
2003 $sqlString = implode("\n", $parts['sql']);
2004 $validName = CRM_Core_DAO
::shortenSQLName($tableName, 48, TRUE);
2005 $triggerName = "{$validName}_{$whenName}_{$eventName}";
2006 $triggerSQL = "CREATE TRIGGER $triggerName $whenName $eventName ON $tableName FOR EACH ROW BEGIN $varString $sqlString END";
2008 CRM_Core_DAO
::executeQuery("DROP TRIGGER IF EXISTS $triggerName");
2009 CRM_Core_DAO
::executeQuery(
2023 * Given a list of fields, create a list of references.
2025 * @param string $className
2026 * BAO/DAO class name.
2027 * @return array<CRM_Core_Reference_Interface>
2029 public static function createReferenceColumns($className) {
2031 $fields = $className::fields();
2032 foreach ($fields as $field) {
2033 if (isset($field['pseudoconstant'], $field['pseudoconstant']['optionGroupName'])) {
2034 $result[] = new CRM_Core_Reference_OptionValue(
2035 $className::getTableName(),
2037 'civicrm_option_value',
2038 CRM_Utils_Array
::value('keyColumn', $field['pseudoconstant'], 'value'),
2039 $field['pseudoconstant']['optionGroupName']
2047 * Find all records which refer to this entity.
2050 * Array of objects referencing this
2052 public function findReferences() {
2053 $links = self
::getReferencesToTable(static::getTableName());
2055 $occurrences = array();
2056 foreach ($links as $refSpec) {
2057 /** @var $refSpec CRM_Core_Reference_Interface */
2058 $daoName = CRM_Core_DAO_AllCoreTables
::getClassForTable($refSpec->getReferenceTable());
2059 $result = $refSpec->findReferences($this);
2061 while ($result->fetch()) {
2062 $obj = new $daoName();
2063 $obj->id
= $result->id
;
2064 $occurrences[] = $obj;
2069 return $occurrences;
2074 * each item has keys:
2078 * - table: string|null SQL table name
2079 * - key: string|null SQL column name
2081 public function getReferenceCounts() {
2082 $links = self
::getReferencesToTable(static::getTableName());
2085 foreach ($links as $refSpec) {
2086 /** @var $refSpec CRM_Core_Reference_Interface */
2087 $count = $refSpec->getReferenceCount($this);
2088 if ($count['count'] != 0) {
2093 foreach (CRM_Core_Component
::getEnabledComponents() as $component) {
2094 /** @var $component CRM_Core_Component_Info */
2095 $counts = array_merge($counts, $component->getReferenceCounts($this));
2097 CRM_Utils_Hook
::referenceCounts($this, $counts);
2103 * List all tables which have hard foreign keys to this table.
2105 * For now, this returns a description of every entity_id/entity_table
2107 * TODO: filter dynamic entity references on the $tableName, based on
2108 * schema metadata in dynamicForeignKey which enumerates a restricted
2109 * set of possible entity_table's.
2111 * @param string $tableName
2112 * Table referred to.
2115 * structure of table and column, listing every table with a
2116 * foreign key reference to $tableName, and the column where the key appears.
2118 public static function getReferencesToTable($tableName) {
2119 $refsFound = array();
2120 foreach (CRM_Core_DAO_AllCoreTables
::getClasses() as $daoClassName) {
2121 $links = $daoClassName::getReferenceColumns();
2122 $daoTableName = $daoClassName::getTableName();
2124 foreach ($links as $refSpec) {
2125 /** @var $refSpec CRM_Core_Reference_Interface */
2126 if ($refSpec->matchesTargetTable($tableName)) {
2127 $refsFound[] = $refSpec;
2135 * Lookup the value of a MySQL global configuration variable.
2137 * @param string $name
2138 * E.g. "thread_stack".
2139 * @param mixed $default
2142 public static function getGlobalSetting($name, $default = NULL) {
2143 // Alternatively, SELECT @@GLOBAL.thread_stack, but
2144 // that has been reported to fail under MySQL 5.0 for OS X
2145 $escapedName = self
::escapeString($name);
2146 $dao = CRM_Core_DAO
::executeQuery("SHOW VARIABLES LIKE '$escapedName'");
2147 if ($dao->fetch()) {
2156 * Get options for the called BAO object's field.
2157 * This function can be overridden by each BAO to add more logic related to context.
2158 * The overriding function will generally call the lower-level CRM_Core_PseudoConstant::get
2160 * @param string $fieldName
2161 * @param string $context
2162 * @see CRM_Core_DAO::buildOptionsContext
2163 * @param array $props
2164 * whatever is known about this bao object.
2166 * @return array|bool
2168 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
2169 // If a given bao does not override this function
2170 $baoName = get_called_class();
2171 return CRM_Core_PseudoConstant
::get($baoName, $fieldName, array(), $context);
2175 * Populate option labels for this object's fields.
2177 * @throws exception if called directly on the base class
2179 public function getOptionLabels() {
2180 $fields = $this->fields();
2181 if ($fields === NULL) {
2182 throw new Exception('Cannot call getOptionLabels on CRM_Core_DAO');
2184 foreach ($fields as $field) {
2185 $name = CRM_Utils_Array
::value('name', $field);
2186 if ($name && isset($this->$name)) {
2187 $label = CRM_Core_PseudoConstant
::getLabel(get_class($this), $name, $this->$name);
2188 if ($label !== FALSE) {
2189 // Append 'label' onto the field name
2190 $labelName = $name . '_label';
2191 $this->$labelName = $label;
2198 * Provides documentation and validation for the buildOptions $context param
2200 * @param string $context
2205 public static function buildOptionsContext($context = NULL) {
2207 'get' => "All options are returned, even if they are disabled. Labels are translated.",
2208 'create' => "Options are filtered appropriately for the object being created/updated. Labels are translated.",
2209 'search' => "Searchable options are returned. Labels are translated.",
2210 'validate' => "All options are returned, even if they are disabled. Machine names are used in place of labels.",
2211 'abbreviate' => "Active options are returned, and labels are replaced with abbreviations.",
2213 // Validation: enforce uniformity of this param
2214 if ($context !== NULL && !isset($contexts[$context])) {
2215 throw new Exception("'$context' is not a valid context for buildOptions.");
2221 * @param string $fieldName
2222 * @return bool|array
2224 public function getFieldSpec($fieldName) {
2225 $fields = $this->fields();
2226 $fieldKeys = $this->fieldKeys();
2228 // Support "unique names" as well as sql names
2229 $fieldKey = $fieldName;
2230 if (empty($fields[$fieldKey])) {
2231 $fieldKey = CRM_Utils_Array
::value($fieldName, $fieldKeys);
2233 // If neither worked then this field doesn't exist. Return false.
2234 if (empty($fields[$fieldKey])) {
2237 return $fields[$fieldKey];
2241 * SQL version of api function to assign filters to the DAO based on the syntax
2242 * $field => array('IN' => array(4,6,9))
2244 * $field => array('LIKE' => array('%me%))
2247 * @param string $fieldName
2249 * @param array $filter
2250 * filter to be applied indexed by operator.
2251 * @param string $type
2252 * type of field (not actually used - nor in api @todo ).
2253 * @param string $alias
2254 * alternative field name ('as') @todo- not actually used.
2255 * @param bool $returnSanitisedArray
2256 * Return a sanitised array instead of a clause.
2257 * this is primarily so we can add filters @ the api level to the Query object based fields
2261 * @todo a better solution would be for the query object to apply these filters based on the
2262 * api supported format (but we don't want to risk breakage in alpha stage & query class is scary
2263 * @todo @time of writing only IN & NOT IN are supported for the array style syntax (as test is
2264 * required to extend further & it may be the comments per above should be implemented. It may be
2265 * preferable to not double-banger the return context next refactor of this - but keeping the attention
2266 * in one place has some advantages as we try to extend this format
2268 * @return NULL|string|array
2269 * a string is returned if $returnSanitisedArray is not set, otherwise and Array or NULL
2270 * depending on whether it is supported as yet
2272 public static function createSQLFilter($fieldName, $filter, $type, $alias = NULL, $returnSanitisedArray = FALSE) {
2273 // http://issues.civicrm.org/jira/browse/CRM-9150 - stick with 'simple' operators for now
2274 // support for other syntaxes is discussed in ticket but being put off for now
2275 foreach ($filter as $operator => $criteria) {
2276 if (in_array($operator, self
::acceptedSQLOperators())) {
2277 switch ($operator) {
2281 if (!$returnSanitisedArray) {
2282 return (sprintf('%s %s', $fieldName, $operator));
2285 return (sprintf('%s %s ', $fieldName, $operator));
2289 // ternary operators
2292 if (empty($criteria[0]) ||
empty($criteria[1])) {
2293 throw new Exception("invalid criteria for $operator");
2295 if (!$returnSanitisedArray) {
2296 return (sprintf('%s ' . $operator . ' "%s" AND "%s"', $fieldName, CRM_Core_DAO
::escapeString($criteria[0]), CRM_Core_DAO
::escapeString($criteria[1])));
2299 return NULL; // not yet implemented (tests required to implement)
2306 if (empty($criteria)) {
2307 throw new Exception("invalid criteria for $operator");
2309 $escapedCriteria = array_map(array(
2313 if (!$returnSanitisedArray) {
2314 return (sprintf('%s %s ("%s")', $fieldName, $operator, implode('", "', $escapedCriteria)));
2316 return $escapedCriteria;
2321 if (!$returnSanitisedArray) {
2322 return (sprintf('%s %s "%s"', $fieldName, $operator, CRM_Core_DAO
::escapeString($criteria)));
2325 return NULL; // not yet implemented (tests required to implement)
2333 * @see http://issues.civicrm.org/jira/browse/CRM-9150
2334 * support for other syntaxes is discussed in ticket but being put off for now
2337 public static function acceptedSQLOperators() {
2358 * SQL has a limit of 64 characters on various names:
2359 * table name, trigger name, column name ...
2361 * For custom groups and fields we generated names from user entered input
2362 * which can be longer than this length, this function helps with creating
2363 * strings that meet various criteria.
2365 * @param string $string
2366 * The string to be shortened.
2367 * @param int $length
2368 * The max length of the string.
2370 * @param bool $makeRandom
2374 public static function shortenSQLName($string, $length = 60, $makeRandom = FALSE) {
2375 // early return for strings that meet the requirements
2376 if (strlen($string) <= $length) {
2380 // easy return for calls that dont need a randomized uniq string
2382 return substr($string, 0, $length);
2385 // the string is longer than the length and we need a uniq string
2386 // for the same tablename we need the same uniq string everytime
2387 // hence we use md5 on the string, which is not random
2388 // we'll append 8 characters to the end of the tableName
2389 $md5string = substr(md5($string), 0, 8);
2390 return substr($string, 0, $length - 8) . "_{$md5string}";
2394 * @param array $params
2396 public function setApiFilter(&$params) {