3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2016 |
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-2016
35 require_once 'PEAR.php';
36 require_once 'DB/DataObject.php';
38 require_once 'CRM/Core/I18n.php';
43 class CRM_Core_DAO
extends DB_DataObject
{
46 * A null object so we can pass it as reference if / when needed
48 static $_nullObject = NULL;
49 static $_nullArray = array();
51 static $_dbColumnValueCache = NULL;
52 const NOT_NULL
= 1, IS_NULL
= 2,
54 VALUE_SEPARATOR
= "\ 1",
55 BULK_INSERT_COUNT
= 200,
56 BULK_INSERT_HIGH_COUNT
= 200,
57 // special value for mail bulk inserts to avoid
58 // potential duplication, assuming a smaller number reduces number of queries
59 // by some factor, so some tradeoff. CRM-8678
60 BULK_MAIL_INSERT_COUNT
= 10,
61 QUERY_FORMAT_WILDCARD
= 1,
62 QUERY_FORMAT_NO_QUOTES
= 2;
65 * Define entities that shouldn't be created or deleted when creating/ deleting
66 * test objects - this prevents world regions, countries etc from being added / deleted
69 static $_testEntitiesToSkip = array();
71 * The factory class for this application.
74 static $_factory = NULL;
76 static $_checkedSqlFunctionsExist = FALSE;
81 * @return \CRM_Core_DAO
83 public function __construct() {
85 $this->__table
= $this->getTableName();
89 * Empty definition for virtual function.
91 public static function getTableName() {
96 * Initialize the DAO object.
99 * The database connection string.
101 public static function init($dsn) {
102 $options = &PEAR
::getStaticProperty('DB_DataObject', 'options');
103 $options['database'] = $dsn;
104 if (defined('CIVICRM_DAO_DEBUG')) {
105 self
::DebugLevel(CIVICRM_DAO_DEBUG
);
110 * @param string $fieldName
112 * @param array $params
114 protected function assignTestFK($fieldName, $fieldDef, $params) {
115 $required = CRM_Utils_Array
::value('required', $fieldDef);
116 $FKClassName = CRM_Utils_Array
::value('FKClassName', $fieldDef);
117 $dbName = $fieldDef['name'];
118 $daoName = str_replace('_BAO_', '_DAO_', get_class($this));
120 // skip the FK if it is not required
121 // if it's contact id we should create even if not required
122 // we'll have a go @ fetching first though
123 // we WILL create campaigns though for so tests with a campaign pseudoconstant will complete
124 if ($FKClassName === 'CRM_Campaign_DAO_Campaign' && $daoName != $FKClassName) {
127 if (!$required && $dbName != 'contact_id') {
128 $fkDAO = new $FKClassName();
129 if ($fkDAO->find(TRUE)) {
130 $this->$dbName = $fkDAO->id
;
135 elseif (in_array($FKClassName, CRM_Core_DAO
::$_testEntitiesToSkip)) {
136 $depObject = new $FKClassName();
137 $depObject->find(TRUE);
138 $this->$dbName = $depObject->id
;
141 elseif ($daoName == 'CRM_Member_DAO_MembershipType' && $fieldName == 'member_of_contact_id') {
142 // FIXME: the fields() metadata is not specific enough
143 $depObject = CRM_Core_DAO
::createTestObject($FKClassName, array('contact_type' => 'Organization'));
144 $this->$dbName = $depObject->id
;
148 //if it is required we need to generate the dependency object first
149 $depObject = CRM_Core_DAO
::createTestObject($FKClassName, CRM_Utils_Array
::value($dbName, $params, 1));
150 $this->$dbName = $depObject->id
;
156 * Generate and assign an arbitrary value to a field of a test object.
158 * @param string $fieldName
159 * @param array $fieldDef
160 * @param int $counter
161 * The globally-unique ID of the test object.
163 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
164 $dbName = $fieldDef['name'];
165 $daoName = get_class($this);
168 if (!$handled && $dbName == 'contact_sub_type') {
169 //coming up with a rule to set this is too complex let's not set it
173 // Pick an option value if needed
174 if (!$handled && $fieldDef['type'] !== CRM_Utils_Type
::T_BOOLEAN
) {
175 $options = $daoName::buildOptions($dbName, 'create');
177 $this->$dbName = key($options);
183 switch ($fieldDef['type']) {
184 case CRM_Utils_Type
::T_INT
:
185 case CRM_Utils_Type
::T_FLOAT
:
186 case CRM_Utils_Type
::T_MONEY
:
187 if (isset($fieldDef['precision'])) {
188 // $object->$dbName = CRM_Utils_Number::createRandomDecimal($value['precision']);
189 $this->$dbName = CRM_Utils_Number
::createTruncatedDecimal($counter, $fieldDef['precision']);
192 $this->$dbName = $counter;
196 case CRM_Utils_Type
::T_BOOLEAN
:
197 if (isset($fieldDef['default'])) {
198 $this->$dbName = $fieldDef['default'];
200 elseif ($fieldDef['name'] == 'is_deleted' ||
$fieldDef['name'] == 'is_test') {
208 case CRM_Utils_Type
::T_DATE
:
209 case CRM_Utils_Type
::T_TIMESTAMP
:
210 case CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
:
211 $this->$dbName = '19700101';
212 if ($dbName == 'end_date') {
213 // put this in the future
214 $this->$dbName = '20200101';
218 case CRM_Utils_Type
::T_TIME
:
219 CRM_Core_Error
::fatal("T_TIME shouldn't be used.");
220 //$object->$dbName='000000';
222 case CRM_Utils_Type
::T_CCNUM
:
223 $this->$dbName = '4111 1111 1111 1111';
226 case CRM_Utils_Type
::T_URL
:
227 $this->$dbName = 'http://www.civicrm.org';
230 case CRM_Utils_Type
::T_STRING
:
231 case CRM_Utils_Type
::T_BLOB
:
232 case CRM_Utils_Type
::T_MEDIUMBLOB
:
233 case CRM_Utils_Type
::T_TEXT
:
234 case CRM_Utils_Type
::T_LONGTEXT
:
235 case CRM_Utils_Type
::T_EMAIL
:
237 // WAS: if (isset($value['enumValues'])) {
238 // TODO: see if this works with all pseudoconstants
239 if (isset($fieldDef['pseudoconstant'], $fieldDef['pseudoconstant']['callback'])) {
240 if (isset($fieldDef['default'])) {
241 $this->$dbName = $fieldDef['default'];
244 $options = CRM_Core_PseudoConstant
::get($daoName, $fieldName);
245 if (is_array($options)) {
246 $this->$dbName = $options[0];
249 $defaultValues = explode(',', $options);
250 $this->$dbName = $defaultValues[0];
255 $this->$dbName = $dbName . '_' . $counter;
256 $maxlength = CRM_Utils_Array
::value('maxlength', $fieldDef);
257 if ($maxlength > 0 && strlen($this->$dbName) > $maxlength) {
258 $this->$dbName = substr($this->$dbName, 0, $fieldDef['maxlength']);
266 * Reset the DAO object.
268 * DAO is kinda crappy in that there is an unwritten rule of one query per DAO.
270 * We attempt to get around this crappy restriction by resetting some of DAO's internal fields. Use this with caution
272 public function reset() {
274 foreach (array_keys($this->table()) as $field) {
275 unset($this->$field);
279 * reset the various DB_DAO structures manually
281 $this->_query
= array();
288 * @param string $tableName
292 public static function getLocaleTableName($tableName) {
295 $tables = CRM_Core_I18n_Schema
::schemaStructureTables();
296 if (in_array($tableName, $tables)) {
297 return $tableName . $dbLocale;
304 * Execute a query by the current DAO, localizing it along the way (if needed).
306 * @param string $query
307 * The SQL query for execution.
308 * @param bool $i18nRewrite
309 * Whether to rewrite the query.
312 * the current DAO object after the query execution
314 public function query($query, $i18nRewrite = TRUE) {
315 // rewrite queries that should use $dbLocale-based views for multi-language installs
317 if ($i18nRewrite and $dbLocale) {
318 $query = CRM_Core_I18n_Schema
::rewriteQuery($query);
321 return parent
::query($query);
325 * Static function to set the factory instance for this class.
327 * @param object $factory
328 * The factory application object.
330 public static function setFactory(&$factory) {
331 self
::$_factory = &$factory;
335 * Factory method to instantiate a new object from a table name.
337 * @param string $table
339 public function factory($table = '') {
340 if (!isset(self
::$_factory)) {
341 return parent
::factory($table);
344 return self
::$_factory->create($table);
348 * Initialization for all DAO objects. Since we access DB_DO programatically
349 * we need to set the links manually.
351 public function initialize() {
353 $this->query("SET NAMES utf8");
357 * Defines the default key as 'id'.
362 public function keys() {
371 * Tells DB_DataObject which keys use autoincrement.
372 * 'id' is autoincrementing by default.
377 public function sequenceKey() {
378 static $sequenceKeys;
379 if (!isset($sequenceKeys)) {
380 $sequenceKeys = array('id', TRUE);
382 return $sequenceKeys;
386 * Returns list of FK relationships.
390 * Array of CRM_Core_Reference_Interface
392 public static function getReferenceColumns() {
397 * Returns all the column names of this table.
402 public static function &fields() {
408 * Get/set an associative array of table columns
413 public function table() {
414 $fields = &$this->fields();
418 foreach ($fields as $name => $value) {
419 $table[$value['name']] = $value['type'];
420 if (!empty($value['required'])) {
421 $table[$value['name']] +
= self
::DB_DAO_NOTNULL
;
434 public function save() {
435 if (!empty($this->id
)) {
438 $event = new \Civi\Core\DAO\Event\
PostUpdate($this);
439 \Civi\Core\Container
::singleton()->get('dispatcher')->dispatch("DAO::post-update", $event);
444 $event = new \Civi\Core\DAO\Event\
PostUpdate($this);
445 \Civi\Core\Container
::singleton()->get('dispatcher')->dispatch("DAO::post-insert", $event);
449 CRM_Utils_Hook
::postSave($this);
455 * Deletes items from table which match current objects variables.
457 * Returns the true on success
461 * Designed to be extended
463 * $object = new mytable();
465 * echo $object->delete(); // builds a conditon
467 * $object = new mytable();
468 * $object->whereAdd('age > 12');
470 * $object->orderBy('age DESC');
471 * $object->delete(true); // dont use object vars, use the conditions, limit and order.
473 * @param bool $useWhere (optional) If DB_DATAOBJECT_WHEREADD_ONLY is passed in then
474 * we will build the condition only using the whereAdd's. Default is to
475 * build the condition only using the object parameters.
477 * * @return mixed Int (No. of rows affected) on success, false on failure, 0 on no data affected
479 public function delete($useWhere = FALSE) {
480 $result = parent
::delete($useWhere);
482 $event = new \Civi\Core\DAO\Event\
PostDelete($this, $result);
483 \Civi\Core\Container
::singleton()->get('dispatcher')->dispatch("DAO::post-delete", $event);
490 * @param bool $created
492 public function log($created = FALSE) {
495 if (!$this->getLog()) {
500 $session = CRM_Core_Session
::singleton();
501 $cid = $session->get('userID');
504 // return is we dont have handle to FK
509 $dao = new CRM_Core_DAO_Log();
510 $dao->entity_table
= $this->getTableName();
511 $dao->entity_id
= $this->id
;
512 $dao->modified_id
= $cid;
513 $dao->modified_date
= date("YmdHis");
518 * Given an associative array of name/value pairs, extract all the values
519 * that belong to this object and initialize the object with said values
521 * @param array $params
522 * (reference ) associative array of name/value pairs.
525 * Did we copy all null values into the object
527 public function copyValues(&$params) {
528 $fields = &$this->fields();
530 foreach ($fields as $name => $value) {
531 $dbName = $value['name'];
532 if (array_key_exists($dbName, $params)) {
533 $pValue = $params[$dbName];
536 elseif (array_key_exists($name, $params)) {
537 $pValue = $params[$name];
544 // if there is no value then make the variable NULL
546 if ($pValue === '') {
547 $this->$dbName = 'null';
550 $this->$dbName = $pValue;
559 * Store all the values from this object in an associative array
560 * this is a destructive store, calling function is responsible
561 * for keeping sanity of id's.
563 * @param object $object
564 * The object that we are extracting data from.
565 * @param array $values
566 * (reference ) associative array of name/value pairs.
568 public static function storeValues(&$object, &$values) {
569 $fields = &$object->fields();
570 foreach ($fields as $name => $value) {
571 $dbName = $value['name'];
572 if (isset($object->$dbName) && $object->$dbName !== 'null') {
573 $values[$dbName] = $object->$dbName;
574 if ($name != $dbName) {
575 $values[$name] = $object->$dbName;
582 * Create an attribute for this specific field. We only do this for strings and text
584 * @param array $field
585 * The field under task.
588 * the attributes for the object
590 public static function makeAttribute($field) {
592 if (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_STRING
) {
593 $maxLength = CRM_Utils_Array
::value('maxlength', $field);
594 $size = CRM_Utils_Array
::value('size', $field);
595 if ($maxLength ||
$size) {
596 $attributes = array();
598 $attributes['maxlength'] = $maxLength;
601 $attributes['size'] = $size;
606 elseif (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_TEXT
) {
607 $rows = CRM_Utils_Array
::value('rows', $field);
611 $cols = CRM_Utils_Array
::value('cols', $field);
616 $attributes = array();
617 $attributes['rows'] = $rows;
618 $attributes['cols'] = $cols;
621 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
) {
622 $attributes['size'] = 6;
623 $attributes['maxlength'] = 14;
631 * Get the size and maxLength attributes for this text field.
632 * (or for all text fields) in the DAO object.
634 * @param string $class
636 * @param string $fieldName
637 * Field that i'm interested in or null if.
638 * you want the attributes for all DAO text fields
641 * assoc array of name => attribute pairs
643 public static function getAttribute($class, $fieldName = NULL) {
644 $object = new $class();
645 $fields = &$object->fields();
646 if ($fieldName != NULL) {
647 $field = CRM_Utils_Array
::value($fieldName, $fields);
648 return self
::makeAttribute($field);
651 $attributes = array();
652 foreach ($fields as $name => $field) {
653 $attribute = self
::makeAttribute($field);
655 $attributes[$name] = $attribute;
659 if (!empty($attributes)) {
671 public static function transaction($type) {
672 CRM_Core_Error
::fatal('This function is obsolete, please use CRM_Core_Transaction');
676 * Check if there is a record with the same name in the db.
678 * @param string $value
679 * The value of the field we are checking.
680 * @param string $daoName
681 * The dao object name.
682 * @param string $daoID
683 * The id of the object being updated. u can change your name.
684 * as long as there is no conflict
685 * @param string $fieldName
686 * The name of the field in the DAO.
689 * true if object exists
691 public static function objectExists($value, $daoName, $daoID, $fieldName = 'name') {
692 $object = new $daoName();
693 $object->$fieldName = $value;
695 $config = CRM_Core_Config
::singleton();
697 if ($object->find(TRUE)) {
698 return ($daoID && $object->id
== $daoID) ?
TRUE : FALSE;
706 * Check if there is a given column in a specific table.
708 * @param string $tableName
709 * @param string $columnName
710 * @param bool $i18nRewrite
711 * Whether to rewrite the query on multilingual setups.
714 * true if exists, else false
716 public static function checkFieldExists($tableName, $columnName, $i18nRewrite = TRUE) {
722 $params = array(1 => array($columnName, 'String'));
723 $dao = CRM_Core_DAO
::executeQuery($query, $params, TRUE, NULL, FALSE, $i18nRewrite);
724 $result = $dao->fetch() ?
TRUE : FALSE;
730 * Returns the storage engine used by given table-name(optional).
731 * Otherwise scans all the tables and return an array of all the
732 * distinct storage engines being used.
734 * @param string $tableName
736 * @param int $maxTablesToCheck
737 * @param string $fieldName
741 public static function getStorageValues($tableName = NULL, $maxTablesToCheck = 10, $fieldName = 'Engine') {
743 $query = "SHOW TABLE STATUS LIKE %1";
747 if (isset($tableName)) {
748 $params = array(1 => array($tableName, 'String'));
751 $params = array(1 => array('civicrm_%', 'String'));
754 $dao = CRM_Core_DAO
::executeQuery($query, $params);
757 while ($dao->fetch()) {
758 if (isset($values[$dao->$fieldName]) ||
759 // ignore import and other temp tables
760 strpos($dao->Name
, 'civicrm_import_job_') !== FALSE ||
761 strpos($dao->Name
, '_temp') !== FALSE
765 $values[$dao->$fieldName] = 1;
767 if ($maxTablesToCheck &&
768 $count >= $maxTablesToCheck
778 * @param int $maxTablesToCheck
782 public static function isDBMyISAM($maxTablesToCheck = 10) {
783 // show error if any of the tables, use 'MyISAM' storage engine.
784 $engines = self
::getStorageValues(NULL, $maxTablesToCheck);
785 if (array_key_exists('MyISAM', $engines)) {
792 * Checks if a constraint exists for a specified table.
794 * @param string $tableName
795 * @param string $constraint
798 * true if constraint exists, false otherwise
800 public static function checkConstraintExists($tableName, $constraint) {
801 static $show = array();
803 if (!array_key_exists($tableName, $show)) {
804 $query = "SHOW CREATE TABLE $tableName";
805 $dao = CRM_Core_DAO
::executeQuery($query);
807 if (!$dao->fetch()) {
808 CRM_Core_Error
::fatal();
812 $show[$tableName] = $dao->Create_Table
;
815 return preg_match("/\b$constraint\b/i", $show[$tableName]) ?
TRUE : FALSE;
819 * Checks if CONSTRAINT keyword exists for a specified table.
821 * @param array $tables
826 * true if CONSTRAINT keyword exists, false otherwise
828 public static function schemaRequiresRebuilding($tables = array("civicrm_contact")) {
830 foreach ($tables as $tableName) {
831 if (!array_key_exists($tableName, $show)) {
832 $query = "SHOW CREATE TABLE $tableName";
833 $dao = CRM_Core_DAO
::executeQuery($query);
835 if (!$dao->fetch()) {
836 CRM_Core_Error
::fatal();
840 $show[$tableName] = $dao->Create_Table
;
843 $result = preg_match("/\bCONSTRAINT\b\s/i", $show[$tableName]) ?
TRUE : FALSE;
844 if ($result == TRUE) {
855 * Checks if the FK constraint name is in the format 'FK_tableName_columnName'
856 * for a specified column of a table.
858 * @param string $tableName
859 * @param string $columnName
862 * true if in format, false otherwise
864 public static function checkFKConstraintInFormat($tableName, $columnName) {
865 static $show = array();
867 if (!array_key_exists($tableName, $show)) {
868 $query = "SHOW CREATE TABLE $tableName";
869 $dao = CRM_Core_DAO
::executeQuery($query);
871 if (!$dao->fetch()) {
872 CRM_Core_Error
::fatal();
876 $show[$tableName] = $dao->Create_Table
;
878 $constraint = "`FK_{$tableName}_{$columnName}`";
879 $pattern = "/\bCONSTRAINT\b\s+%s\s+\bFOREIGN\s+KEY\b\s/i";
880 return preg_match(sprintf($pattern, $constraint), $show[$tableName]) ?
TRUE : FALSE;
884 * Check whether a specific column in a specific table has always the same value.
886 * @param string $tableName
887 * @param string $columnName
888 * @param string $columnValue
891 * true if the value is always $columnValue, false otherwise
893 public static function checkFieldHasAlwaysValue($tableName, $columnName, $columnValue) {
894 $query = "SELECT * FROM $tableName WHERE $columnName != '$columnValue'";
895 $dao = CRM_Core_DAO
::executeQuery($query);
896 $result = $dao->fetch() ?
FALSE : TRUE;
902 * Check whether a specific column in a specific table is always NULL.
904 * @param string $tableName
905 * @param string $columnName
908 * true if if the value is always NULL, false otherwise
910 public static function checkFieldIsAlwaysNull($tableName, $columnName) {
911 $query = "SELECT * FROM $tableName WHERE $columnName IS NOT NULL";
912 $dao = CRM_Core_DAO
::executeQuery($query);
913 $result = $dao->fetch() ?
FALSE : TRUE;
919 * Check if there is a given table in the database.
921 * @param string $tableName
924 * true if exists, else false
926 public static function checkTableExists($tableName) {
931 $params = array(1 => array($tableName, 'String'));
933 $dao = CRM_Core_DAO
::executeQuery($query, $params);
934 $result = $dao->fetch() ?
TRUE : FALSE;
944 public function checkVersion($version) {
949 $dbVersion = CRM_Core_DAO
::singleValueQuery($query);
950 return trim($version) == trim($dbVersion) ?
TRUE : FALSE;
954 * Find a DAO object for the given ID and return it.
957 * Id of the DAO object being searched for.
960 * Object of the type of the class that called this function.
962 public static function findById($id) {
963 $object = new static();
965 if (!$object->find(TRUE)) {
966 throw new Exception("Unable to find a " . get_called_class() . " with id {$id}.");
972 * Returns all results as array-encoded records.
976 public function fetchAll() {
978 while ($this->fetch()) {
979 $result[] = $this->toArray();
985 * Given a DAO name, a column name and a column value, find the record and GET the value of another column in that record
987 * @param string $daoName
988 * Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact).
989 * @param int $searchValue
990 * Value of the column you want to search by.
991 * @param string $returnColumn
992 * Name of the column you want to GET the value of.
993 * @param string $searchColumn
994 * Name of the column you want to search by.
996 * Skip use of the cache.
998 * @return string|null
999 * Value of $returnColumn in the retrieved record
1001 public static function getFieldValue($daoName, $searchValue, $returnColumn = 'name', $searchColumn = 'id', $force = FALSE) {
1003 empty($searchValue) ||
1004 trim(strtolower($searchValue)) == 'null'
1006 // adding this year since developers forget to check for an id
1007 // or for the 'null' (which is a bad DAO kludge)
1008 // and hence we get the first value in the db
1009 CRM_Core_Error
::fatal();
1012 $cacheKey = "{$daoName}:{$searchValue}:{$returnColumn}:{$searchColumn}";
1013 if (self
::$_dbColumnValueCache === NULL) {
1014 self
::$_dbColumnValueCache = array();
1017 if (!array_key_exists($cacheKey, self
::$_dbColumnValueCache) ||
$force) {
1018 $object = new $daoName();
1019 $object->$searchColumn = $searchValue;
1020 $object->selectAdd();
1021 $object->selectAdd($returnColumn);
1024 if ($object->find(TRUE)) {
1025 $result = $object->$returnColumn;
1029 self
::$_dbColumnValueCache[$cacheKey] = $result;
1031 return self
::$_dbColumnValueCache[$cacheKey];
1035 * Given a DAO name, a column name and a column value, find the record and SET the value of another column in that record
1037 * @param string $daoName
1038 * Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact).
1039 * @param int $searchValue
1040 * Value of the column you want to search by.
1041 * @param string $setColumn
1042 * Name of the column you want to SET the value of.
1043 * @param string $setValue
1044 * SET the setColumn to this value.
1045 * @param string $searchColumn
1046 * Name of the column you want to search by.
1049 * true if we found and updated the object, else false
1051 public static function setFieldValue($daoName, $searchValue, $setColumn, $setValue, $searchColumn = 'id') {
1052 $object = new $daoName();
1053 $object->selectAdd();
1054 $object->selectAdd("$searchColumn, $setColumn");
1055 $object->$searchColumn = $searchValue;
1057 if ($object->find(TRUE)) {
1058 $object->$setColumn = $setValue;
1059 if ($object->save()) {
1070 * @param array|object $sort either array or CRM_Utils_Sort
1071 * @param string $default
1072 * Default sort value.
1077 public static function getSortString($sort, $default = NULL) {
1078 // check if sort is of type CRM_Utils_Sort
1079 if (is_a($sort, 'CRM_Utils_Sort')) {
1080 return $sort->orderBy();
1083 // is it an array specified as $field => $sortDirection ?
1085 foreach ($sort as $k => $v) {
1086 $sortString .= "$k $v,";
1088 return rtrim($sortString, ',');
1094 * Fetch object based on array of properties.
1096 * @param string $daoName
1097 * Name of the dao object.
1098 * @param array $params
1099 * (reference ) an assoc array of name/value pairs.
1100 * @param array $defaults
1101 * (reference ) an assoc array to hold the flattened values.
1102 * @param array $returnProperities
1103 * An assoc array of fields that need to be returned, eg array( 'first_name', 'last_name').
1106 * an object of type referenced by daoName
1108 public static function commonRetrieve($daoName, &$params, &$defaults, $returnProperities = NULL) {
1109 $object = new $daoName();
1110 $object->copyValues($params);
1112 // return only specific fields if returnproperties are sent
1113 if (!empty($returnProperities)) {
1114 $object->selectAdd();
1115 $object->selectAdd(implode(',', $returnProperities));
1118 if ($object->find(TRUE)) {
1119 self
::storeValues($object, $defaults);
1126 * Delete the object records that are associated with this contact.
1128 * @param string $daoName
1129 * Name of the dao object.
1130 * @param int $contactId
1131 * Id of the contact to delete.
1133 public static function deleteEntityContact($daoName, $contactId) {
1134 $object = new $daoName();
1136 $object->entity_table
= 'civicrm_contact';
1137 $object->entity_id
= $contactId;
1144 * @param string $query
1145 * Query to be executed.
1147 * @param array $params
1148 * @param bool $abort
1149 * @param null $daoName
1150 * @param bool $freeDAO
1151 * @param bool $i18nRewrite
1152 * @param bool $trapException
1154 * @return CRM_Core_DAO|object
1155 * object that holds the results of the query
1156 * NB - if this is defined as just returning a DAO phpstorm keeps pointing
1157 * out all the properties that are not part of the DAO
1159 public static function &executeQuery(
1165 $i18nRewrite = TRUE,
1166 $trapException = FALSE
1168 $queryStr = self
::composeQuery($query, $params, $abort);
1171 $dao = new CRM_Core_DAO();
1174 $dao = new $daoName();
1177 if ($trapException) {
1178 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
1181 $result = $dao->query($queryStr, $i18nRewrite);
1183 if (is_a($result, 'DB_Error')) {
1188 preg_match('/^(insert|update|delete|create|drop|replace)/i', $queryStr)
1190 // we typically do this for insert/update/delete statements OR if explicitly asked to
1198 * Execute a query and get the single result.
1200 * @param string $query
1201 * Query to be executed.
1202 * @param array $params
1203 * @param bool $abort
1204 * @param bool $i18nRewrite
1205 * @return string|null
1206 * the result of the query if any
1209 public static function &singleValueQuery(
1215 $queryStr = self
::composeQuery($query, $params, $abort);
1217 static $_dao = NULL;
1220 $_dao = new CRM_Core_DAO();
1223 $_dao->query($queryStr, $i18nRewrite);
1225 $result = $_dao->getDatabaseResult();
1228 $row = $result->fetchRow();
1238 * Compose the query by merging the parameters into it.
1240 * @param string $query
1241 * @param array $params
1242 * @param bool $abort
1247 public static function composeQuery($query, $params, $abort = TRUE) {
1249 foreach ($params as $key => $item) {
1250 if (is_numeric($key)) {
1251 if (CRM_Utils_Type
::validate($item[0], $item[1]) !== NULL) {
1252 $item[0] = self
::escapeString($item[0]);
1253 if ($item[1] == 'String' ||
1254 $item[1] == 'Memo' ||
1257 // Support class constants stipulating wildcard characters and/or
1258 // non-quoting of strings. Also support legacy code which may be
1259 // passing in TRUE or 1 for $item[2], which used to indicate the
1260 // use of wildcard characters.
1261 if (!empty($item[2])) {
1262 if ($item[2] & CRM_Core_DAO
::QUERY_FORMAT_WILDCARD ||
$item[2] === TRUE) {
1263 $item[0] = "'%{$item[0]}%'";
1265 elseif (!($item[2] & CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
)) {
1266 $item[0] = "'{$item[0]}'";
1270 $item[0] = "'{$item[0]}'";
1274 if (($item[1] == 'Date' ||
$item[1] == 'Timestamp') &&
1275 strlen($item[0]) == 0
1280 $tr['%' . $key] = $item[0];
1283 CRM_Core_Error
::fatal("{$item[0]} is not of type {$item[1]}");
1288 return strtr($query, $tr);
1294 public static function freeResult($ids = NULL) {
1295 global $_DB_DATAOBJECT;
1298 if (!$_DB_DATAOBJECT ||
1299 !isset($_DB_DATAOBJECT['RESULTS'])
1303 $ids = array_keys($_DB_DATAOBJECT['RESULTS']);
1306 foreach ($ids as $id) {
1307 if (isset($_DB_DATAOBJECT['RESULTS'][$id])) {
1308 if (is_resource($_DB_DATAOBJECT['RESULTS'][$id]->result
)) {
1309 mysql_free_result($_DB_DATAOBJECT['RESULTS'][$id]->result
);
1311 unset($_DB_DATAOBJECT['RESULTS'][$id]);
1314 if (isset($_DB_DATAOBJECT['RESULTFIELDS'][$id])) {
1315 unset($_DB_DATAOBJECT['RESULTFIELDS'][$id]);
1321 * make a shallow copy of an object.
1322 * and all the fields in the object
1324 * @param string $daoName
1326 * @param array $criteria
1327 * Array of all the fields & values.
1328 * on which basis to copy
1329 * @param array $newData
1330 * Array of all the fields & values.
1331 * to be copied besides the other fields
1332 * @param string $fieldsFix
1333 * Array of fields that you want to prefix/suffix/replace.
1334 * @param string $blockCopyOfDependencies
1335 * Fields that you want to block from.
1339 * @return CRM_Core_DAO
1340 * the newly created copy of the object
1342 public static function ©Generic($daoName, $criteria, $newData = NULL, $fieldsFix = NULL, $blockCopyOfDependencies = NULL) {
1343 $object = new $daoName();
1345 $object->id
= $criteria['id'];
1348 foreach ($criteria as $key => $value) {
1349 $object->$key = $value;
1354 while ($object->fetch()) {
1356 // all the objects except with $blockCopyOfDependencies set
1357 // be copied - addresses #CRM-1962
1359 if ($blockCopyOfDependencies && $object->$blockCopyOfDependencies) {
1363 $newObject = new $daoName();
1365 $fields = &$object->fields();
1366 if (!is_array($fieldsFix)) {
1367 $fieldsToPrefix = array();
1368 $fieldsToSuffix = array();
1369 $fieldsToReplace = array();
1371 if (!empty($fieldsFix['prefix'])) {
1372 $fieldsToPrefix = $fieldsFix['prefix'];
1374 if (!empty($fieldsFix['suffix'])) {
1375 $fieldsToSuffix = $fieldsFix['suffix'];
1377 if (!empty($fieldsFix['replace'])) {
1378 $fieldsToReplace = $fieldsFix['replace'];
1381 foreach ($fields as $name => $value) {
1382 if ($name == 'id' ||
$value['name'] == 'id') {
1383 // copy everything but the id!
1387 $dbName = $value['name'];
1388 $type = CRM_Utils_Type
::typeToString($value['type']);
1389 $newObject->$dbName = $object->$dbName;
1390 if (isset($fieldsToPrefix[$dbName])) {
1391 $newObject->$dbName = $fieldsToPrefix[$dbName] . $newObject->$dbName;
1393 if (isset($fieldsToSuffix[$dbName])) {
1394 $newObject->$dbName .= $fieldsToSuffix[$dbName];
1396 if (isset($fieldsToReplace[$dbName])) {
1397 $newObject->$dbName = $fieldsToReplace[$dbName];
1400 if ($type == 'Timestamp' ||
$type == 'Date') {
1401 $newObject->$dbName = CRM_Utils_Date
::isoToMysql($newObject->$dbName);
1405 foreach ($newData as $k => $v) {
1406 $newObject->$k = $v;
1416 * Cascade update through related entities.
1418 * @param string $daoName
1421 * @param array $newData
1425 public static function cascadeUpdate($daoName, $fromId, $toId, $newData = array()) {
1426 $object = new $daoName();
1427 $object->id
= $fromId;
1429 if ($object->find(TRUE)) {
1430 $newObject = new $daoName();
1431 $newObject->id
= $toId;
1433 if ($newObject->find(TRUE)) {
1434 $fields = &$object->fields();
1435 foreach ($fields as $name => $value) {
1436 if ($name == 'id' ||
$value['name'] == 'id') {
1437 // copy everything but the id!
1441 $colName = $value['name'];
1442 $newObject->$colName = $object->$colName;
1444 if (substr($name, -5) == '_date' ||
1445 substr($name, -10) == '_date_time'
1447 $newObject->$colName = CRM_Utils_Date
::isoToMysql($newObject->$colName);
1450 foreach ($newData as $k => $v) {
1451 $newObject->$k = $v;
1457 return CRM_Core_DAO
::$_nullObject;
1461 * Given the component id, compute the contact id
1462 * since its used for things like send email
1464 * @param $componentIDs
1465 * @param string $tableName
1469 public static function &getContactIDsFromComponent(&$componentIDs, $tableName) {
1470 $contactIDs = array();
1472 if (empty($componentIDs)) {
1476 $IDs = implode(',', $componentIDs);
1480 WHERE id IN ( $IDs )
1483 $dao = CRM_Core_DAO
::executeQuery($query);
1484 while ($dao->fetch()) {
1485 $contactIDs[] = $dao->contact_id
;
1491 * Fetch object based on array of properties.
1493 * @param string $daoName
1494 * Name of the dao object.
1495 * @param string $fieldIdName
1496 * @param int $fieldId
1498 * @param array $returnProperities
1499 * An assoc array of fields that need to be returned, eg array( 'first_name', 'last_name').
1502 * an object of type referenced by daoName
1504 public static function commonRetrieveAll($daoName, $fieldIdName = 'id', $fieldId, &$details, $returnProperities = NULL) {
1505 require_once str_replace('_', DIRECTORY_SEPARATOR
, $daoName) . ".php";
1506 $object = new $daoName();
1507 $object->$fieldIdName = $fieldId;
1509 // return only specific fields if returnproperties are sent
1510 if (!empty($returnProperities)) {
1511 $object->selectAdd();
1512 $object->selectAdd('id');
1513 $object->selectAdd(implode(',', $returnProperities));
1517 while ($object->fetch()) {
1518 $defaults = array();
1519 self
::storeValues($object, $defaults);
1520 $details[$object->id
] = $defaults;
1526 public static function dropAllTables() {
1528 // first drop all the custom tables we've created
1529 CRM_Core_BAO_CustomGroup
::dropAllTables();
1531 // drop all multilingual views
1532 CRM_Core_I18n_Schema
::dropAllViews();
1534 CRM_Utils_File
::sourceSQLFile(CIVICRM_DSN
,
1535 dirname(__FILE__
) . DIRECTORY_SEPARATOR
.
1536 '..' . DIRECTORY_SEPARATOR
.
1537 '..' . DIRECTORY_SEPARATOR
.
1538 'sql' . DIRECTORY_SEPARATOR
.
1539 'civicrm_drop.mysql'
1548 public static function escapeString($string) {
1549 static $_dao = NULL;
1552 // If this is an atypical case (e.g. preparing .sql files
1553 // before Civi has been installed), then we fallback to
1554 // DB-less escaping helper (mysql_real_escape_string).
1555 // Note: In typical usage, escapeString() will only
1556 // check one conditional ("if !$_dao") rather than
1557 // two conditionals ("if !defined(DSN)")
1558 if (!defined('CIVICRM_DSN')) {
1559 if (function_exists('mysql_real_escape_string')) {
1560 return mysql_real_escape_string($string);
1563 throw new CRM_Core_Exception("Cannot generate SQL. \"mysql_real_escape_string\" is missing. Have you installed PHP \"mysql\" extension?");
1567 $_dao = new CRM_Core_DAO();
1570 return $_dao->escape($string);
1574 * Escape a list of strings for use with "WHERE X IN (...)" queries.
1576 * @param array $strings
1577 * @param string $default
1578 * the value to use if $strings has no elements.
1580 * eg "abc","def","ghi"
1582 public static function escapeStrings($strings, $default = NULL) {
1583 static $_dao = NULL;
1585 $_dao = new CRM_Core_DAO();
1588 if (empty($strings)) {
1592 $escapes = array_map(array($_dao, 'escape'), $strings);
1593 return '"' . implode('","', $escapes) . '"';
1601 public static function escapeWildCardString($string) {
1603 // ensure we escape the single characters % and _ which are mysql wild
1604 // card characters and could come in via sortByCharacter
1605 // note that mysql does not escape these characters
1606 if ($string && in_array($string,
1607 array('%', '_', '%%', '_%')
1610 return '\\' . $string;
1613 return self
::escapeString($string);
1617 * Creates a test object, including any required objects it needs via recursion
1618 * createOnly: only create in database, do not store or return the objects (useful for perf testing)
1619 * ONLY USE FOR TESTING
1621 * @param string $daoName
1622 * @param array $params
1623 * @param int $numObjects
1624 * @param bool $createOnly
1626 * @return object|array|NULL
1627 * NULL if $createOnly. A single object if $numObjects==1. Otherwise, an array of multiple objects.
1629 public static function createTestObject(
1635 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
1636 // so we re-set here in case
1637 $config = CRM_Core_Config
::singleton();
1638 $config->backtrace
= TRUE;
1640 static $counter = 0;
1641 CRM_Core_DAO
::$_testEntitiesToSkip = array(
1642 'CRM_Core_DAO_Worldregion',
1643 'CRM_Core_DAO_StateProvince',
1644 'CRM_Core_DAO_Country',
1645 'CRM_Core_DAO_Domain',
1646 'CRM_Financial_DAO_FinancialType',
1647 //because valid ones exist & we use pick them due to pseudoconstant can't reliably create & delete these
1650 // Prefer to instantiate BAO's instead of DAO's (when possible)
1651 // so that assignTestValue()/assignTestFK() can be overloaded.
1652 $baoName = str_replace('_DAO_', '_BAO_', $daoName);
1653 if (class_exists($baoName)) {
1654 $daoName = $baoName;
1657 for ($i = 0; $i < $numObjects; ++
$i) {
1660 /** @var CRM_Core_DAO $object */
1661 $object = new $daoName();
1663 $fields = &$object->fields();
1664 foreach ($fields as $fieldName => $fieldDef) {
1665 $dbName = $fieldDef['name'];
1666 $FKClassName = CRM_Utils_Array
::value('FKClassName', $fieldDef);
1667 $required = CRM_Utils_Array
::value('required', $fieldDef);
1669 if (CRM_Utils_Array
::value($dbName, $params) !== NULL && !is_array($params[$dbName])) {
1670 $object->$dbName = $params[$dbName];
1673 elseif ($dbName != 'id') {
1674 if ($FKClassName != NULL) {
1675 $object->assignTestFK($fieldName, $fieldDef, $params);
1679 $object->assignTestValue($fieldName, $fieldDef, $counter);
1687 $objects[$i] = $object;
1697 elseif ($numObjects == 1) {
1706 * Deletes the this object plus any dependent objects that are associated with it.
1707 * ONLY USE FOR TESTING
1709 * @param string $daoName
1710 * @param array $params
1712 public static function deleteTestObjects($daoName, $params = array()) {
1713 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
1714 // so we re-set here in case
1715 $config = CRM_Core_Config
::singleton();
1716 $config->backtrace
= TRUE;
1718 $object = new $daoName();
1719 $object->id
= CRM_Utils_Array
::value('id', $params);
1721 $deletions = array(); // array(array(0 => $daoName, 1 => $daoParams))
1722 if ($object->find(TRUE)) {
1724 $fields = &$object->fields();
1725 foreach ($fields as $name => $value) {
1727 $dbName = $value['name'];
1729 $FKClassName = CRM_Utils_Array
::value('FKClassName', $value);
1730 $required = CRM_Utils_Array
::value('required', $value);
1731 if ($FKClassName != NULL
1733 && !in_array($FKClassName, CRM_Core_DAO
::$_testEntitiesToSkip)
1734 && ($required ||
$dbName == 'contact_id')
1735 //I'm a bit stuck on this one - we might need to change the singleValueAlter so that the entities don't share a contact
1736 // to make this test process pass - line below makes pass for now
1737 && $dbName != 'member_of_contact_id'
1739 $deletions[] = array($FKClassName, array('id' => $object->$dbName)); // x
1746 foreach ($deletions as $deletion) {
1747 CRM_Core_DAO
::deleteTestObjects($deletion[0], $deletion[1]);
1752 * Set defaults when creating new entity.
1753 * (don't call this set defaults as already in use with different signature in some places)
1755 * @param array $params
1758 public static function setCreateDefaults(&$params, $defaults) {
1759 if (isset($params['id'])) {
1762 foreach ($defaults as $key => $value) {
1763 if (!array_key_exists($key, $params) ||
$params[$key] === NULL) {
1764 $params[$key] = $value;
1770 * @param string $prefix
1771 * @param bool $addRandomString
1772 * @param null $string
1776 public static function createTempTableName($prefix = 'civicrm', $addRandomString = TRUE, $string = NULL) {
1777 $tableName = $prefix . "_temp";
1779 if ($addRandomString) {
1781 $tableName .= "_" . $string;
1784 $tableName .= "_" . md5(uniqid('', TRUE));
1792 * @param bool $trigger
1796 public static function checkTriggerViewPermission($view = TRUE, $trigger = TRUE) {
1797 // test for create view and trigger permissions and if allowed, add the option to go multilingual
1799 // I'm not sure why we use the getStaticProperty for an error, rather than checking for DB_Error
1800 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
1801 $dao = new CRM_Core_DAO();
1803 $dao->query('CREATE OR REPLACE VIEW civicrm_domain_view AS SELECT * FROM civicrm_domain');
1804 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
1810 $result = $dao->query('CREATE TRIGGER civicrm_domain_trigger BEFORE INSERT ON civicrm_domain FOR EACH ROW BEGIN END');
1811 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError') ||
is_a($result, 'DB_Error')) {
1813 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1818 $dao->query('DROP TRIGGER IF EXISTS civicrm_domain_trigger');
1819 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
1821 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1828 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1829 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
1838 * @param null $message
1839 * @param bool $printDAO
1841 public static function debugPrint($message = NULL, $printDAO = TRUE) {
1842 CRM_Utils_System
::xMemory("{$message}: ");
1845 global $_DB_DATAOBJECT;
1847 foreach (array_keys($_DB_DATAOBJECT['RESULTS']) as $id) {
1848 $q[] = $_DB_DATAOBJECT['RESULTS'][$id]->query
;
1850 CRM_Core_Error
::debug('_DB_DATAOBJECT', $q);
1855 * Build a list of triggers via hook and add them to (err, reconcile them
1856 * with) the database.
1858 * @param string $tableName
1859 * the specific table requiring a rebuild; or NULL to rebuild all tables.
1860 * @param bool $force
1864 public static function triggerRebuild($tableName = NULL, $force = FALSE) {
1867 $logging = new CRM_Logging_Schema();
1868 $logging->triggerInfo($info, $tableName, $force);
1870 CRM_Core_I18n_Schema
::triggerInfo($info, $tableName);
1871 CRM_Contact_BAO_Contact
::triggerInfo($info, $tableName);
1873 CRM_Utils_Hook
::triggerInfo($info, $tableName);
1875 // drop all existing triggers on all tables
1876 $logging->dropTriggers($tableName);
1878 // now create the set of new triggers
1879 self
::createTriggers($info, $tableName);
1883 * Because sql functions are sometimes lost, esp during db migration, we check here to avoid numerous support requests
1884 * @see http://issues.civicrm.org/jira/browse/CRM-13822
1885 * TODO: Alternative solutions might be
1886 * * Stop using functions and find another way to strip numeric characters from phones
1887 * * Give better error messages (currently a missing fn fatals with "unknown error")
1889 public static function checkSqlFunctionsExist() {
1890 if (!self
::$_checkedSqlFunctionsExist) {
1891 self
::$_checkedSqlFunctionsExist = TRUE;
1892 $dao = CRM_Core_DAO
::executeQuery("SHOW function status WHERE db = database() AND name = 'civicrm_strip_non_numeric'");
1893 if (!$dao->fetch()) {
1894 self
::triggerRebuild();
1900 * Wrapper function to drop triggers.
1902 * @param string $tableName
1903 * the specific table requiring a rebuild; or NULL to rebuild all tables.
1905 public static function dropTriggers($tableName = NULL) {
1908 $logging = new CRM_Logging_Schema();
1909 $logging->triggerInfo($info, $tableName);
1911 // drop all existing triggers on all tables
1912 $logging->dropTriggers($tableName);
1916 * @param array $info
1917 * per hook_civicrm_triggerInfo.
1918 * @param string $onlyTableName
1919 * the specific table requiring a rebuild; or NULL to rebuild all tables.
1921 public static function createTriggers(&$info, $onlyTableName = NULL) {
1922 // Validate info array, should probably raise errors?
1923 if (is_array($info) == FALSE) {
1927 $triggers = array();
1929 // now enumerate the tables and the events and collect the same set in a different format
1930 foreach ($info as $value) {
1932 // clean the incoming data, skip malformed entries
1933 // TODO: malformed entries should raise errors or get logged.
1934 if (isset($value['table']) == FALSE ||
1935 isset($value['event']) == FALSE ||
1936 isset($value['when']) == FALSE ||
1937 isset($value['sql']) == FALSE
1942 if (is_string($value['table']) == TRUE) {
1943 $tables = array($value['table']);
1946 $tables = $value['table'];
1949 if (is_string($value['event']) == TRUE) {
1950 $events = array(strtolower($value['event']));
1953 $events = array_map('strtolower', $value['event']);
1956 $whenName = strtolower($value['when']);
1958 foreach ($tables as $tableName) {
1959 if (!isset($triggers[$tableName])) {
1960 $triggers[$tableName] = array();
1963 foreach ($events as $eventName) {
1964 $template_params = array('{tableName}', '{eventName}');
1965 $template_values = array($tableName, $eventName);
1967 $sql = str_replace($template_params,
1971 $variables = str_replace($template_params,
1973 CRM_Utils_Array
::value('variables', $value)
1976 if (!isset($triggers[$tableName][$eventName])) {
1977 $triggers[$tableName][$eventName] = array();
1980 if (!isset($triggers[$tableName][$eventName][$whenName])) {
1981 // We're leaving out cursors, conditions, and handlers for now
1982 // they are kind of dangerous in this context anyway
1983 // better off putting them in stored procedures
1984 $triggers[$tableName][$eventName][$whenName] = array(
1985 'variables' => array(),
1991 $triggers[$tableName][$eventName][$whenName]['variables'][] = $variables;
1994 $triggers[$tableName][$eventName][$whenName]['sql'][] = $sql;
1999 // now spit out the sql
2000 foreach ($triggers as $tableName => $tables) {
2001 if ($onlyTableName != NULL && $onlyTableName != $tableName) {
2004 foreach ($tables as $eventName => $events) {
2005 foreach ($events as $whenName => $parts) {
2006 $varString = implode("\n", $parts['variables']);
2007 $sqlString = implode("\n", $parts['sql']);
2008 $validName = CRM_Core_DAO
::shortenSQLName($tableName, 48, TRUE);
2009 $triggerName = "{$validName}_{$whenName}_{$eventName}";
2010 $triggerSQL = "CREATE TRIGGER $triggerName $whenName $eventName ON $tableName FOR EACH ROW BEGIN $varString $sqlString END";
2012 CRM_Core_DAO
::executeQuery("DROP TRIGGER IF EXISTS $triggerName");
2013 CRM_Core_DAO
::executeQuery(
2027 * Given a list of fields, create a list of references.
2029 * @param string $className
2030 * BAO/DAO class name.
2031 * @return array<CRM_Core_Reference_Interface>
2033 public static function createReferenceColumns($className) {
2035 $fields = $className::fields();
2036 foreach ($fields as $field) {
2037 if (isset($field['pseudoconstant'], $field['pseudoconstant']['optionGroupName'])) {
2038 $result[] = new CRM_Core_Reference_OptionValue(
2039 $className::getTableName(),
2041 'civicrm_option_value',
2042 CRM_Utils_Array
::value('keyColumn', $field['pseudoconstant'], 'value'),
2043 $field['pseudoconstant']['optionGroupName']
2051 * Find all records which refer to this entity.
2054 * Array of objects referencing this
2056 public function findReferences() {
2057 $links = self
::getReferencesToTable(static::getTableName());
2059 $occurrences = array();
2060 foreach ($links as $refSpec) {
2061 /** @var $refSpec CRM_Core_Reference_Interface */
2062 $daoName = CRM_Core_DAO_AllCoreTables
::getClassForTable($refSpec->getReferenceTable());
2063 $result = $refSpec->findReferences($this);
2065 while ($result->fetch()) {
2066 $obj = new $daoName();
2067 $obj->id
= $result->id
;
2068 $occurrences[] = $obj;
2073 return $occurrences;
2078 * each item has keys:
2082 * - table: string|null SQL table name
2083 * - key: string|null SQL column name
2085 public function getReferenceCounts() {
2086 $links = self
::getReferencesToTable(static::getTableName());
2089 foreach ($links as $refSpec) {
2090 /** @var $refSpec CRM_Core_Reference_Interface */
2091 $count = $refSpec->getReferenceCount($this);
2092 if ($count['count'] != 0) {
2097 foreach (CRM_Core_Component
::getEnabledComponents() as $component) {
2098 /** @var $component CRM_Core_Component_Info */
2099 $counts = array_merge($counts, $component->getReferenceCounts($this));
2101 CRM_Utils_Hook
::referenceCounts($this, $counts);
2107 * List all tables which have hard foreign keys to this table.
2109 * For now, this returns a description of every entity_id/entity_table
2111 * TODO: filter dynamic entity references on the $tableName, based on
2112 * schema metadata in dynamicForeignKey which enumerates a restricted
2113 * set of possible entity_table's.
2115 * @param string $tableName
2116 * Table referred to.
2119 * structure of table and column, listing every table with a
2120 * foreign key reference to $tableName, and the column where the key appears.
2122 public static function getReferencesToTable($tableName) {
2123 $refsFound = array();
2124 foreach (CRM_Core_DAO_AllCoreTables
::getClasses() as $daoClassName) {
2125 $links = $daoClassName::getReferenceColumns();
2126 $daoTableName = $daoClassName::getTableName();
2128 foreach ($links as $refSpec) {
2129 /** @var $refSpec CRM_Core_Reference_Interface */
2130 if ($refSpec->matchesTargetTable($tableName)) {
2131 $refsFound[] = $refSpec;
2139 * Lookup the value of a MySQL global configuration variable.
2141 * @param string $name
2142 * E.g. "thread_stack".
2143 * @param mixed $default
2146 public static function getGlobalSetting($name, $default = NULL) {
2147 // Alternatively, SELECT @@GLOBAL.thread_stack, but
2148 // that has been reported to fail under MySQL 5.0 for OS X
2149 $escapedName = self
::escapeString($name);
2150 $dao = CRM_Core_DAO
::executeQuery("SHOW VARIABLES LIKE '$escapedName'");
2151 if ($dao->fetch()) {
2160 * Get options for the called BAO object's field.
2161 * This function can be overridden by each BAO to add more logic related to context.
2162 * The overriding function will generally call the lower-level CRM_Core_PseudoConstant::get
2164 * @param string $fieldName
2165 * @param string $context
2166 * @see CRM_Core_DAO::buildOptionsContext
2167 * @param array $props
2168 * whatever is known about this bao object.
2170 * @return array|bool
2172 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
2173 // If a given bao does not override this function
2174 $baoName = get_called_class();
2175 return CRM_Core_PseudoConstant
::get($baoName, $fieldName, array(), $context);
2179 * Populate option labels for this object's fields.
2181 * @throws exception if called directly on the base class
2183 public function getOptionLabels() {
2184 $fields = $this->fields();
2185 if ($fields === NULL) {
2186 throw new Exception('Cannot call getOptionLabels on CRM_Core_DAO');
2188 foreach ($fields as $field) {
2189 $name = CRM_Utils_Array
::value('name', $field);
2190 if ($name && isset($this->$name)) {
2191 $label = CRM_Core_PseudoConstant
::getLabel(get_class($this), $name, $this->$name);
2192 if ($label !== FALSE) {
2193 // Append 'label' onto the field name
2194 $labelName = $name . '_label';
2195 $this->$labelName = $label;
2202 * Provides documentation and validation for the buildOptions $context param
2204 * @param string $context
2209 public static function buildOptionsContext($context = NULL) {
2211 'get' => "get: all options are returned, even if they are disabled; labels are translated.",
2212 'create' => "create: options are filtered appropriately for the object being created/updated; labels are translated.",
2213 'search' => "search: searchable options are returned; labels are translated.",
2214 'validate' => "validate: all options are returned, even if they are disabled; machine names are used in place of labels.",
2215 'abbreviate' => "abbreviate: enabled options are returned; labels are replaced with abbreviations.",
2216 'match' => "match: enabled options are returned using machine names as keys; labels are translated.",
2218 // Validation: enforce uniformity of this param
2219 if ($context !== NULL && !isset($contexts[$context])) {
2220 throw new Exception("'$context' is not a valid context for buildOptions.");
2226 * @param string $fieldName
2227 * @return bool|array
2229 public function getFieldSpec($fieldName) {
2230 $fields = $this->fields();
2231 $fieldKeys = $this->fieldKeys();
2233 // Support "unique names" as well as sql names
2234 $fieldKey = $fieldName;
2235 if (empty($fields[$fieldKey])) {
2236 $fieldKey = CRM_Utils_Array
::value($fieldName, $fieldKeys);
2238 // If neither worked then this field doesn't exist. Return false.
2239 if (empty($fields[$fieldKey])) {
2242 return $fields[$fieldKey];
2246 * Get SQL where clause for SQL filter syntax input parameters.
2248 * SQL version of api function to assign filters to the DAO based on the syntax
2249 * $field => array('IN' => array(4,6,9))
2251 * $field => array('LIKE' => array('%me%))
2254 * @param string $fieldName
2256 * @param array $filter
2257 * filter to be applied indexed by operator.
2258 * @param string $type
2259 * type of field (not actually used - nor in api @todo ).
2260 * @param string $alias
2261 * alternative field name ('as') @todo- not actually used.
2262 * @param bool $returnSanitisedArray
2263 * Return a sanitised array instead of a clause.
2264 * this is primarily so we can add filters @ the api level to the Query object based fields
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 = NULL, $alias = NULL, $returnSanitisedArray = FALSE) {
2273 foreach ($filter as $operator => $criteria) {
2274 if (in_array($operator, self
::acceptedSQLOperators(), TRUE)) {
2275 switch ($operator) {
2279 if (!$returnSanitisedArray) {
2280 return (sprintf('%s %s', $fieldName, $operator));
2283 return (sprintf('%s %s ', $fieldName, $operator));
2287 // ternary operators
2290 if (empty($criteria[0]) ||
empty($criteria[1])) {
2291 throw new Exception("invalid criteria for $operator");
2293 if (!$returnSanitisedArray) {
2294 return (sprintf('%s ' . $operator . ' "%s" AND "%s"', $fieldName, CRM_Core_DAO
::escapeString($criteria[0]), CRM_Core_DAO
::escapeString($criteria[1])));
2297 return NULL; // not yet implemented (tests required to implement)
2304 if (empty($criteria)) {
2305 throw new Exception("invalid criteria for $operator");
2307 $escapedCriteria = array_map(array(
2311 if (!$returnSanitisedArray) {
2312 return (sprintf('%s %s ("%s")', $fieldName, $operator, implode('", "', $escapedCriteria)));
2314 return $escapedCriteria;
2319 if (!$returnSanitisedArray) {
2320 return (sprintf('%s %s "%s"', $fieldName, $operator, CRM_Core_DAO
::escapeString($criteria)));
2323 return NULL; // not yet implemented (tests required to implement)
2331 * @see http://issues.civicrm.org/jira/browse/CRM-9150
2332 * support for other syntaxes is discussed in ticket but being put off for now
2335 public static function acceptedSQLOperators() {
2356 * SQL has a limit of 64 characters on various names:
2357 * table name, trigger name, column name ...
2359 * For custom groups and fields we generated names from user entered input
2360 * which can be longer than this length, this function helps with creating
2361 * strings that meet various criteria.
2363 * @param string $string
2364 * The string to be shortened.
2365 * @param int $length
2366 * The max length of the string.
2368 * @param bool $makeRandom
2372 public static function shortenSQLName($string, $length = 60, $makeRandom = FALSE) {
2373 // early return for strings that meet the requirements
2374 if (strlen($string) <= $length) {
2378 // easy return for calls that dont need a randomized uniq string
2380 return substr($string, 0, $length);
2383 // the string is longer than the length and we need a uniq string
2384 // for the same tablename we need the same uniq string every time
2385 // hence we use md5 on the string, which is not random
2386 // we'll append 8 characters to the end of the tableName
2387 $md5string = substr(md5($string), 0, 8);
2388 return substr($string, 0, $length - 8) . "_{$md5string}";
2392 * @param array $params
2394 public function setApiFilter(&$params) {
2398 * Generates acl clauses suitable for adding to WHERE or ON when doing an api.get for this entity
2400 * Return format is in the form of fieldname => clauses starting with an operator. e.g.:
2403 * 'location_type_id' => array('IS NOT NULL', 'IN (1,2,3)')
2407 * Note that all array keys must be actual field names in this entity. Use subqueries to filter on other tables e.g. custom values.
2411 public function addSelectWhereClause() {
2412 // This is the default fallback, and works for contact-related entities like Email, Relationship, etc.
2414 foreach ($this->fields() as $fieldName => $field) {
2415 if (strpos($fieldName, 'contact_id') === 0 && CRM_Utils_Array
::value('FKClassName', $field) == 'CRM_Contact_DAO_Contact') {
2416 $clauses[$fieldName] = CRM_Utils_SQL
::mergeSubquery('Contact');
2419 CRM_Utils_Hook
::selectWhereClause($this, $clauses);
2424 * This returns the final permissioned query string for this entity
2426 * With acls from related entities + additional clauses from hook_civicrm_selectWhereClause
2428 * @param string $tableAlias
2431 public static function getSelectWhereClause($tableAlias = NULL) {
2432 $bao = new static();
2433 if ($tableAlias === NULL) {
2434 $tableAlias = $bao->tableName();
2437 foreach ((array) $bao->addSelectWhereClause() as $field => $vals) {
2438 $clauses[$field] = NULL;
2440 $clauses[$field] = "`$tableAlias`.`$field` " . implode(" AND `$tableAlias`.`$field` ", (array) $vals);
2447 * function to check valid db name containing only characters in [0-9,a-z,A-Z_]
2453 public static function requireValidDBName($database) {
2456 "/^[0-9]*[a-zA-Z_]+[a-zA-Z0-9_]*$/",
2460 if (empty($matches)) {