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
70 static $_testEntitiesToSkip = array();
72 * The factory class for this application
75 static $_factory = NULL;
77 static $_checkedSqlFunctionsExist = FALSE;
82 * @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
100 * @param string $dsn 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
119 protected function assignTestFK($fieldName, $fieldDef, $params) {
120 $required = CRM_Utils_Array
::value('required', $fieldDef);
121 $FKClassName = CRM_Utils_Array
::value('FKClassName', $fieldDef);
122 $dbName = $fieldDef['name'];
123 $daoName = get_class($this);
125 // skip the FK if it is not required
126 // if it's contact id we should create even if not required
127 // we'll have a go @ fetching first though
128 // we WILL create campaigns though for so tests with a campaign pseudoconstant will complete
129 if ($FKClassName === 'CRM_Campaign_DAO_Campaign' && $daoName != $FKClassName) {
132 if (!$required && $dbName != 'contact_id') {
133 $fkDAO = new $FKClassName;
134 if ($fkDAO->find(TRUE)) {
135 $this->$dbName = $fkDAO->id
;
140 elseif (in_array($FKClassName, CRM_Core_DAO
::$_testEntitiesToSkip)) {
141 $depObject = new $FKClassName();
142 $depObject->find(TRUE);
143 $this->$dbName = $depObject->id
;
146 elseif ($daoName == 'CRM_Member_DAO_MembershipType' && $fieldName == 'member_of_contact_id') {
147 // FIXME: the fields() metadata is not specific enough
148 $depObject = CRM_Core_DAO
::createTestObject($FKClassName, array('contact_type' => 'Organization'));
149 $this->$dbName = $depObject->id
;
153 //if it is required we need to generate the dependency object first
154 $depObject = CRM_Core_DAO
::createTestObject($FKClassName, CRM_Utils_Array
::value($dbName, $params, 1));
155 $this->$dbName = $depObject->id
;
161 * Generate and assign an arbitrary value to a field of a test object.
163 * @param string $fieldName
164 * @param array $fieldDef
165 * @param int $counter 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
277 public function reset() {
279 foreach (array_keys($this->table()) as $field) {
280 unset($this->$field);
284 * reset the various DB_DAO structures manually
286 $this->_query
= array();
293 * @param string $tableName
297 public static function getLocaleTableName($tableName) {
300 $tables = CRM_Core_I18n_Schema
::schemaStructureTables();
301 if (in_array($tableName, $tables)) {
302 return $tableName . $dbLocale;
309 * Execute a query by the current DAO, localizing it along the way (if needed).
311 * @param string $query the SQL query for execution
312 * @param bool $i18nRewrite whether to rewrite the query
314 * @return object the current DAO object after the query execution
316 public function query($query, $i18nRewrite = TRUE) {
317 // rewrite queries that should use $dbLocale-based views for multi-language installs
319 if ($i18nRewrite and $dbLocale) {
320 $query = CRM_Core_I18n_Schema
::rewriteQuery($query);
323 return parent
::query($query);
327 * Static function to set the factory instance for this class.
329 * @param object $factory the factory application object
334 public static function setFactory(&$factory) {
335 self
::$_factory = &$factory;
339 * Factory method to instantiate a new object from a table name.
341 * @param string $table
345 public function factory($table = '') {
346 if (!isset(self
::$_factory)) {
347 return parent
::factory($table);
350 return self
::$_factory->create($table);
354 * Initialization for all DAO objects. Since we access DB_DO programatically
355 * we need to set the links manually.
359 public function initialize() {
361 $this->query("SET NAMES utf8");
365 * Defines the default key as 'id'.
370 public function keys() {
379 * Tells DB_DataObject which keys use autoincrement.
380 * 'id' is autoincrementing by default.
385 public function sequenceKey() {
386 static $sequenceKeys;
387 if (!isset($sequenceKeys)) {
388 $sequenceKeys = array('id', TRUE);
390 return $sequenceKeys;
394 * Returns list of FK relationships
398 * @return array of CRM_Core_Reference_Interface
400 public static function getReferenceColumns() {
405 * Returns all the column names of this table
410 static function &fields() {
416 * Get/set an associative array of table columns
418 * @param array key=>type array
419 * @return array (associative)
421 public function table() {
422 $fields = &$this->fields();
426 foreach ($fields as $name => $value) {
427 $table[$value['name']] = $value['type'];
428 if (!empty($value['required'])) {
429 $table[$value['name']] +
= self
::DB_DAO_NOTNULL
;
440 public function save() {
441 if (!empty($this->id
)) {
444 $event = new \Civi\Core\DAO\Event\
PostUpdate($this);
445 \Civi\Core\Container
::singleton()->get('dispatcher')->dispatch("DAO::post-update", $event);
450 $event = new \Civi\Core\DAO\Event\
PostUpdate($this);
451 \Civi\Core\Container
::singleton()->get('dispatcher')->dispatch("DAO::post-insert", $event);
455 CRM_Utils_Hook
::postSave($this);
460 public function delete($useWhere = FALSE) {
461 $result = parent
::delete($useWhere);
463 $event = new \Civi\Core\DAO\Event\
PostDelete($this, $result);
464 \Civi\Core\Container
::singleton()->get('dispatcher')->dispatch("DAO::post-delete", $event);
470 * @param bool $created
472 public function log($created = FALSE) {
475 if (!$this->getLog()) {
480 $session = CRM_Core_Session
::singleton();
481 $cid = $session->get('userID');
484 // return is we dont have handle to FK
489 $dao = new CRM_Core_DAO_Log();
490 $dao->entity_table
= $this->getTableName();
491 $dao->entity_id
= $this->id
;
492 $dao->modified_id
= $cid;
493 $dao->modified_date
= date("YmdHis");
498 * Given an associative array of name/value pairs, extract all the values
499 * that belong to this object and initialize the object with said values
501 * @param array $params (reference ) associative array of name/value pairs
503 * @return boolean did we copy all null values into the object
505 public function copyValues(&$params) {
506 $fields = &$this->fields();
508 foreach ($fields as $name => $value) {
509 $dbName = $value['name'];
510 if (array_key_exists($dbName, $params)) {
511 $pValue = $params[$dbName];
514 elseif (array_key_exists($name, $params)) {
515 $pValue = $params[$name];
522 // if there is no value then make the variable NULL
524 if ($pValue === '') {
525 $this->$dbName = 'null';
528 $this->$dbName = $pValue;
537 * Store all the values from this object in an associative array
538 * this is a destructive store, calling function is responsible
539 * for keeping sanity of id's.
541 * @param object $object the object that we are extracting data from
542 * @param array $values (reference ) associative array of name/value pairs
547 public static function storeValues(&$object, &$values) {
548 $fields = &$object->fields();
549 foreach ($fields as $name => $value) {
550 $dbName = $value['name'];
551 if (isset($object->$dbName) && $object->$dbName !== 'null') {
552 $values[$dbName] = $object->$dbName;
553 if ($name != $dbName) {
554 $values[$name] = $object->$dbName;
561 * Create an attribute for this specific field. We only do this for strings and text
563 * @param array $field the field under task
565 * @return array|null the attributes for the object
568 public static function makeAttribute($field) {
570 if (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_STRING
) {
571 $maxLength = CRM_Utils_Array
::value('maxlength', $field);
572 $size = CRM_Utils_Array
::value('size', $field);
573 if ($maxLength ||
$size) {
574 $attributes = array();
576 $attributes['maxlength'] = $maxLength;
579 $attributes['size'] = $size;
584 elseif (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_TEXT
) {
585 $rows = CRM_Utils_Array
::value('rows', $field);
589 $cols = CRM_Utils_Array
::value('cols', $field);
594 $attributes = array();
595 $attributes['rows'] = $rows;
596 $attributes['cols'] = $cols;
599 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
) {
600 $attributes['size'] = 6;
601 $attributes['maxlength'] = 14;
609 * Get the size and maxLength attributes for this text field
610 * (or for all text fields) in the DAO object.
612 * @param string $class name of DAO class
613 * @param string $fieldName field that i'm interested in or null if
614 * you want the attributes for all DAO text fields
616 * @return array assoc array of name => attribute pairs
619 public static function getAttribute($class, $fieldName = NULL) {
620 $object = new $class( );
621 $fields = &$object->fields();
622 if ($fieldName != NULL) {
623 $field = CRM_Utils_Array
::value($fieldName, $fields);
624 return self
::makeAttribute($field);
627 $attributes = array();
628 foreach ($fields as $name => $field) {
629 $attribute = self
::makeAttribute($field);
631 $attributes[$name] = $attribute;
635 if (!empty($attributes)) {
647 public static function transaction($type) {
648 CRM_Core_Error
::fatal('This function is obsolete, please use CRM_Core_Transaction');
652 * Check if there is a record with the same name in the db
654 * @param string $value the value of the field we are checking
655 * @param string $daoName the dao object name
656 * @param string $daoID the id of the object being updated. u can change your name
657 * as long as there is no conflict
658 * @param string $fieldName the name of the field in the DAO
660 * @return boolean true if object exists
663 public static function objectExists($value, $daoName, $daoID, $fieldName = 'name') {
664 $object = new $daoName( );
665 $object->$fieldName = $value;
667 $config = CRM_Core_Config
::singleton();
669 if ($object->find(TRUE)) {
670 return ($daoID && $object->id
== $daoID) ?
TRUE : FALSE;
678 * Check if there is a given column in a specific table
680 * @param string $tableName
681 * @param string $columnName
682 * @param bool $i18nRewrite whether to rewrite the query on multilingual setups
684 * @return boolean true if exists, else false
687 public static function checkFieldExists($tableName, $columnName, $i18nRewrite = TRUE) {
693 $params = array(1 => array($columnName, 'String'));
694 $dao = CRM_Core_DAO
::executeQuery($query, $params, TRUE, NULL, FALSE, $i18nRewrite);
695 $result = $dao->fetch() ?
TRUE : FALSE;
701 * Returns the storage engine used by given table-name(optional).
702 * Otherwise scans all the tables and return an array of all the
703 * distinct storage engines being used.
705 * @param string $tableName
707 * @param int $maxTablesToCheck
708 * @param string $fieldName
713 public static function getStorageValues($tableName = NULL, $maxTablesToCheck = 10, $fieldName = 'Engine') {
715 $query = "SHOW TABLE STATUS LIKE %1";
719 if (isset($tableName)) {
720 $params = array(1 => array($tableName, 'String'));
723 $params = array(1 => array('civicrm_%', 'String'));
726 $dao = CRM_Core_DAO
::executeQuery($query, $params);
729 while ($dao->fetch()) {
730 if (isset($values[$dao->$fieldName]) ||
731 // ignore import and other temp tables
732 strpos($dao->Name
, 'civicrm_import_job_') !== FALSE ||
733 strpos($dao->Name
, '_temp') !== FALSE
737 $values[$dao->$fieldName] = 1;
739 if ($maxTablesToCheck &&
740 $count >= $maxTablesToCheck
750 * @param int $maxTablesToCheck
754 public static function isDBMyISAM($maxTablesToCheck = 10) {
755 // show error if any of the tables, use 'MyISAM' storage engine.
756 $engines = self
::getStorageValues(NULL, $maxTablesToCheck);
757 if (array_key_exists('MyISAM', $engines)) {
764 * Checks if a constraint exists for a specified table.
766 * @param string $tableName
767 * @param string $constraint
769 * @return boolean true if constraint exists, false otherwise
772 public static function checkConstraintExists($tableName, $constraint) {
773 static $show = array();
775 if (!array_key_exists($tableName, $show)) {
776 $query = "SHOW CREATE TABLE $tableName";
777 $dao = CRM_Core_DAO
::executeQuery($query);
779 if (!$dao->fetch()) {
780 CRM_Core_Error
::fatal();
784 $show[$tableName] = $dao->Create_Table
;
787 return preg_match("/\b$constraint\b/i", $show[$tableName]) ?
TRUE : FALSE;
791 * Checks if CONSTRAINT keyword exists for a specified table.
793 * @param array $tables
797 * @return boolean true if CONSTRAINT keyword exists, false otherwise
799 public static function schemaRequiresRebuilding($tables = array("civicrm_contact")) {
801 foreach($tables as $tableName){
802 if (!array_key_exists($tableName, $show)) {
803 $query = "SHOW CREATE TABLE $tableName";
804 $dao = CRM_Core_DAO
::executeQuery($query);
806 if (!$dao->fetch()) {
807 CRM_Core_Error
::fatal();
811 $show[$tableName] = $dao->Create_Table
;
814 $result = preg_match("/\bCONSTRAINT\b\s/i", $show[$tableName]) ?
TRUE : FALSE;
815 if ($result == TRUE){
826 * Checks if the FK constraint name is in the format 'FK_tableName_columnName'
827 * for a specified column of a table.
829 * @param string $tableName
830 * @param string $columnName
832 * @return boolean true if in format, false otherwise
835 public static function checkFKConstraintInFormat($tableName, $columnName) {
836 static $show = array();
838 if (!array_key_exists($tableName, $show)) {
839 $query = "SHOW CREATE TABLE $tableName";
840 $dao = CRM_Core_DAO
::executeQuery($query);
842 if (!$dao->fetch()) {
843 CRM_Core_Error
::fatal();
847 $show[$tableName] = $dao->Create_Table
;
849 $constraint = "`FK_{$tableName}_{$columnName}`";
850 $pattern = "/\bCONSTRAINT\b\s+%s\s+\bFOREIGN\s+KEY\b\s/i";
851 return preg_match(sprintf($pattern, $constraint),$show[$tableName]) ?
TRUE : FALSE;
855 * Check whether a specific column in a specific table has always the same value
857 * @param string $tableName
858 * @param string $columnName
859 * @param string $columnValue
861 * @return boolean true if the value is always $columnValue, false otherwise
864 public static function checkFieldHasAlwaysValue($tableName, $columnName, $columnValue) {
865 $query = "SELECT * FROM $tableName WHERE $columnName != '$columnValue'";
866 $dao = CRM_Core_DAO
::executeQuery($query);
867 $result = $dao->fetch() ?
FALSE : TRUE;
873 * Check whether a specific column in a specific table is always NULL
875 * @param string $tableName
876 * @param string $columnName
878 * @return boolean true if if the value is always NULL, false otherwise
881 public static function checkFieldIsAlwaysNull($tableName, $columnName) {
882 $query = "SELECT * FROM $tableName WHERE $columnName IS NOT NULL";
883 $dao = CRM_Core_DAO
::executeQuery($query);
884 $result = $dao->fetch() ?
FALSE : TRUE;
890 * Check if there is a given table in the database
892 * @param string $tableName
894 * @return boolean true if exists, else false
897 public static function checkTableExists($tableName) {
902 $params = array(1 => array($tableName, 'String'));
904 $dao = CRM_Core_DAO
::executeQuery($query, $params);
905 $result = $dao->fetch() ?
TRUE : FALSE;
915 public function checkVersion($version) {
920 $dbVersion = CRM_Core_DAO
::singleValueQuery($query);
921 return trim($version) == trim($dbVersion) ?
TRUE : FALSE;
925 * Find a DAO object for the given ID and return it.
927 * @param int $id Id of the DAO object being searched for.
929 * @return object Object of the type of the class that called this function.
931 public static function findById($id) {
932 $object = new static();
934 if (!$object->find(TRUE)) {
935 throw new Exception("Unable to find a " . get_called_class() . " with id {$id}.");
941 * Given a DAO name, a column name and a column value, find the record and GET the value of another column in that record
943 * @param string $daoName Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact)
944 * @param int $searchValue Value of the column you want to search by
945 * @param string $returnColumn Name of the column you want to GET the value of
946 * @param string $searchColumn Name of the column you want to search by
947 * @param boolean $force Skip use of the cache
949 * @return string|null Value of $returnColumn in the retrieved record
952 public static function getFieldValue($daoName, $searchValue, $returnColumn = 'name', $searchColumn = 'id', $force = FALSE) {
954 empty($searchValue) ||
955 trim(strtolower($searchValue)) == 'null'
957 // adding this year since developers forget to check for an id
958 // or for the 'null' (which is a bad DAO kludge)
959 // and hence we get the first value in the db
960 CRM_Core_Error
::fatal();
963 $cacheKey = "{$daoName}:{$searchValue}:{$returnColumn}:{$searchColumn}";
964 if (self
::$_dbColumnValueCache === NULL) {
965 self
::$_dbColumnValueCache = array();
968 if (!array_key_exists($cacheKey, self
::$_dbColumnValueCache) ||
$force) {
969 $object = new $daoName( );
970 $object->$searchColumn = $searchValue;
971 $object->selectAdd();
972 $object->selectAdd($returnColumn);
975 if ($object->find(TRUE)) {
976 $result = $object->$returnColumn;
980 self
::$_dbColumnValueCache[$cacheKey] = $result;
982 return self
::$_dbColumnValueCache[$cacheKey];
986 * Given a DAO name, a column name and a column value, find the record and SET the value of another column in that record
988 * @param string $daoName Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact)
989 * @param int $searchValue Value of the column you want to search by
990 * @param string $setColumn Name of the column you want to SET the value of
991 * @param string $setValue SET the setColumn to this value
992 * @param string $searchColumn Name of the column you want to search by
994 * @return boolean true if we found and updated the object, else false
997 public static function setFieldValue($daoName, $searchValue, $setColumn, $setValue, $searchColumn = 'id') {
998 $object = new $daoName( );
999 $object->selectAdd();
1000 $object->selectAdd("$searchColumn, $setColumn");
1001 $object->$searchColumn = $searchValue;
1003 if ($object->find(TRUE)) {
1004 $object->$setColumn = $setValue;
1005 if ($object->save()) {
1016 * @param array|object $sort either array or CRM_Utils_Sort
1017 * @param string $default - default sort value
1019 * @return string - sortString
1022 public static function getSortString($sort, $default = NULL) {
1023 // check if sort is of type CRM_Utils_Sort
1024 if (is_a($sort, 'CRM_Utils_Sort')) {
1025 return $sort->orderBy();
1028 // is it an array specified as $field => $sortDirection ?
1030 foreach ($sort as $k => $v) {
1031 $sortString .= "$k $v,";
1033 return rtrim($sortString, ',');
1039 * Fetch object based on array of properties
1041 * @param string $daoName name of the dao object
1042 * @param array $params (reference ) an assoc array of name/value pairs
1043 * @param array $defaults (reference ) an assoc array to hold the flattened values
1044 * @param array $returnProperities an assoc array of fields that need to be returned, eg array( 'first_name', 'last_name')
1046 * @return object an object of type referenced by daoName
1049 public static function commonRetrieve($daoName, &$params, &$defaults, $returnProperities = NULL) {
1050 $object = new $daoName( );
1051 $object->copyValues($params);
1053 // return only specific fields if returnproperties are sent
1054 if (!empty($returnProperities)) {
1055 $object->selectAdd();
1056 $object->selectAdd(implode(',', $returnProperities));
1059 if ($object->find(TRUE)) {
1060 self
::storeValues($object, $defaults);
1067 * Delete the object records that are associated with this contact
1069 * @param string $daoName name of the dao object
1070 * @param int $contactId id of the contact to delete
1075 public static function deleteEntityContact($daoName, $contactId) {
1076 $object = new $daoName( );
1078 $object->entity_table
= 'civicrm_contact';
1079 $object->entity_id
= $contactId;
1086 * @param string $query query to be executed
1088 * @param array $params
1089 * @param bool $abort
1090 * @param null $daoName
1091 * @param bool $freeDAO
1092 * @param bool $i18nRewrite
1093 * @param bool $trapException
1095 * @return CRM_Core_DAO object that holds the results of the query
1098 static function &executeQuery(
1104 $i18nRewrite = TRUE,
1105 $trapException = FALSE
1107 $queryStr = self
::composeQuery($query, $params, $abort);
1110 $dao = new CRM_Core_DAO();
1113 $dao = new $daoName( );
1116 if ($trapException) {
1117 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
1120 $result = $dao->query($queryStr, $i18nRewrite);
1122 if (is_a($result, 'DB_Error')) {
1127 preg_match('/^(insert|update|delete|create|drop|replace)/i', $queryStr)
1129 // we typically do this for insert/update/delete stataments OR if explicitly asked to
1137 * Execute a query and get the single result
1139 * @param string $query query to be executed
1140 * @param array $params
1141 * @param bool $abort
1142 * @param bool $i18nRewrite
1143 * @return string|null the result of the query if any
1147 static function &singleValueQuery($query,
1152 $queryStr = self
::composeQuery($query, $params, $abort);
1154 static $_dao = NULL;
1157 $_dao = new CRM_Core_DAO();
1160 $_dao->query($queryStr, $i18nRewrite);
1162 $result = $_dao->getDatabaseResult();
1165 $row = $result->fetchRow();
1176 * @param array $params
1177 * @param bool $abort
1182 public static function composeQuery($query, &$params, $abort = TRUE) {
1184 foreach ($params as $key => $item) {
1185 if (is_numeric($key)) {
1186 if (CRM_Utils_Type
::validate($item[0], $item[1]) !== NULL) {
1187 $item[0] = self
::escapeString($item[0]);
1188 if ($item[1] == 'String' ||
1189 $item[1] == 'Memo' ||
1192 // Support class constants stipulating wildcard characters and/or
1193 // non-quoting of strings. Also support legacy code which may be
1194 // passing in TRUE or 1 for $item[2], which used to indicate the
1195 // use of wildcard characters.
1196 if (!empty($item[2])) {
1197 if ($item[2] & CRM_Core_DAO
::QUERY_FORMAT_WILDCARD ||
$item[2] === TRUE) {
1198 $item[0] = "'%{$item[0]}%'";
1200 elseif (!($item[2] & CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
)) {
1201 $item[0] = "'{$item[0]}'";
1205 $item[0] = "'{$item[0]}'";
1209 if (($item[1] == 'Date' ||
$item[1] == 'Timestamp') &&
1210 strlen($item[0]) == 0
1215 $tr['%' . $key] = $item[0];
1218 CRM_Core_Error
::fatal("{$item[0]} is not of type {$item[1]}");
1223 return strtr($query, $tr);
1229 public static function freeResult($ids = NULL) {
1230 global $_DB_DATAOBJECT;
1233 if (!$_DB_DATAOBJECT ||
1234 !isset($_DB_DATAOBJECT['RESULTS'])
1238 $ids = array_keys($_DB_DATAOBJECT['RESULTS']);
1241 foreach ($ids as $id) {
1242 if (isset($_DB_DATAOBJECT['RESULTS'][$id])) {
1243 if (is_resource($_DB_DATAOBJECT['RESULTS'][$id]->result
)) {
1244 mysql_free_result($_DB_DATAOBJECT['RESULTS'][$id]->result
);
1246 unset($_DB_DATAOBJECT['RESULTS'][$id]);
1249 if (isset($_DB_DATAOBJECT['RESULTFIELDS'][$id])) {
1250 unset($_DB_DATAOBJECT['RESULTFIELDS'][$id]);
1256 * This function is to make a shallow copy of an object
1257 * and all the fields in the object
1259 * @param string $daoName name of the dao
1260 * @param array $criteria array of all the fields & values
1261 * on which basis to copy
1262 * @param array $newData array of all the fields & values
1263 * to be copied besides the other fields
1264 * @param string $fieldsFix array of fields that you want to prefix/suffix/replace
1265 * @param string $blockCopyOfDependencies fields that you want to block from
1269 * @return (reference ) the newly created copy of the object
1271 static function ©Generic($daoName, $criteria, $newData = NULL, $fieldsFix = NULL, $blockCopyOfDependencies = NULL) {
1272 $object = new $daoName( );
1274 $object->id
= $criteria['id'];
1277 foreach ($criteria as $key => $value) {
1278 $object->$key = $value;
1283 while ($object->fetch()) {
1285 // all the objects except with $blockCopyOfDependencies set
1286 // be copied - addresses #CRM-1962
1288 if ($blockCopyOfDependencies && $object->$blockCopyOfDependencies) {
1292 $newObject = new $daoName( );
1294 $fields = &$object->fields();
1295 if (!is_array($fieldsFix)) {
1296 $fieldsToPrefix = array();
1297 $fieldsToSuffix = array();
1298 $fieldsToReplace = array();
1300 if (!empty($fieldsFix['prefix'])) {
1301 $fieldsToPrefix = $fieldsFix['prefix'];
1303 if (!empty($fieldsFix['suffix'])) {
1304 $fieldsToSuffix = $fieldsFix['suffix'];
1306 if (!empty($fieldsFix['replace'])) {
1307 $fieldsToReplace = $fieldsFix['replace'];
1310 foreach ($fields as $name => $value) {
1311 if ($name == 'id' ||
$value['name'] == 'id') {
1312 // copy everything but the id!
1316 $dbName = $value['name'];
1317 $type = CRM_Utils_Type
::typeToString($value['type']);
1318 $newObject->$dbName = $object->$dbName;
1319 if (isset($fieldsToPrefix[$dbName])) {
1320 $newObject->$dbName = $fieldsToPrefix[$dbName] . $newObject->$dbName;
1322 if (isset($fieldsToSuffix[$dbName])) {
1323 $newObject->$dbName .= $fieldsToSuffix[$dbName];
1325 if (isset($fieldsToReplace[$dbName])) {
1326 $newObject->$dbName = $fieldsToReplace[$dbName];
1329 if ($type == 'Timestamp' ||
$type == 'Date') {
1330 $newObject->$dbName = CRM_Utils_Date
::isoToMysql($newObject->$dbName);
1334 foreach ($newData as $k => $v) {
1335 $newObject->$k = $v;
1344 public static function cascadeUpdate($daoName, $fromId, $toId, $newData = array()) {
1345 $object = new $daoName( );
1346 $object->id
= $fromId;
1348 if ($object->find(TRUE)) {
1349 $newObject = new $daoName( );
1350 $newObject->id
= $toId;
1352 if ($newObject->find(TRUE)) {
1353 $fields = &$object->fields();
1354 foreach ($fields as $name => $value) {
1355 if ($name == 'id' ||
$value['name'] == 'id') {
1356 // copy everything but the id!
1360 $colName = $value['name'];
1361 $newObject->$colName = $object->$colName;
1363 if (substr($name, -5) == '_date' ||
1364 substr($name, -10) == '_date_time'
1366 $newObject->$colName = CRM_Utils_Date
::isoToMysql($newObject->$colName);
1369 foreach ($newData as $k => $v) {
1370 $newObject->$k = $v;
1376 return CRM_Core_DAO
::$_nullObject;
1380 * Given the component id, compute the contact id
1381 * since its used for things like send email
1383 * @param $componentIDs
1384 * @param string $tableName
1388 public static function &getContactIDsFromComponent(&$componentIDs, $tableName) {
1389 $contactIDs = array();
1391 if (empty($componentIDs)) {
1395 $IDs = implode(',', $componentIDs);
1399 WHERE id IN ( $IDs )
1402 $dao = CRM_Core_DAO
::executeQuery($query);
1403 while ($dao->fetch()) {
1404 $contactIDs[] = $dao->contact_id
;
1410 * Fetch object based on array of properties
1412 * @param string $daoName name of the dao object
1413 * @param string $fieldIdName
1414 * @param int $fieldId
1416 * @param array $returnProperities an assoc array of fields that need to be returned, eg array( 'first_name', 'last_name')
1418 * @return object an object of type referenced by daoName
1421 public static function commonRetrieveAll($daoName, $fieldIdName = 'id', $fieldId, &$details, $returnProperities = NULL) {
1422 require_once (str_replace('_', DIRECTORY_SEPARATOR
, $daoName) . ".php");
1423 $object = new $daoName( );
1424 $object->$fieldIdName = $fieldId;
1426 // return only specific fields if returnproperties are sent
1427 if (!empty($returnProperities)) {
1428 $object->selectAdd();
1429 $object->selectAdd('id');
1430 $object->selectAdd(implode(',', $returnProperities));
1434 while ($object->fetch()) {
1435 $defaults = array();
1436 self
::storeValues($object, $defaults);
1437 $details[$object->id
] = $defaults;
1443 public static function dropAllTables() {
1445 // first drop all the custom tables we've created
1446 CRM_Core_BAO_CustomGroup
::dropAllTables();
1448 // drop all multilingual views
1449 CRM_Core_I18n_Schema
::dropAllViews();
1451 CRM_Utils_File
::sourceSQLFile(CIVICRM_DSN
,
1452 dirname(__FILE__
) . DIRECTORY_SEPARATOR
.
1453 '..' . DIRECTORY_SEPARATOR
.
1454 '..' . DIRECTORY_SEPARATOR
.
1455 'sql' . DIRECTORY_SEPARATOR
.
1456 'civicrm_drop.mysql'
1465 public static function escapeString($string) {
1466 static $_dao = NULL;
1469 // If this is an atypical case (e.g. preparing .sql files
1470 // before Civi has been installed), then we fallback to
1471 // DB-less escaping helper (mysql_real_escape_string).
1472 // Note: In typical usage, escapeString() will only
1473 // check one conditional ("if !$_dao") rather than
1474 // two conditionals ("if !defined(DSN)")
1475 if (!defined('CIVICRM_DSN')) {
1476 if (function_exists('mysql_real_escape_string')) {
1477 return mysql_real_escape_string($string);
1479 throw new CRM_Core_Exception("Cannot generate SQL. \"mysql_real_escape_string\" is missing. Have you installed PHP \"mysql\" extension?");
1483 $_dao = new CRM_Core_DAO();
1486 return $_dao->escape($string);
1490 * Escape a list of strings for use with "WHERE X IN (...)" queries.
1492 * @param $strings array
1493 * @param $default string the value to use if $strings has no elements
1494 * @return string eg "abc","def","ghi"
1496 public static function escapeStrings($strings, $default = NULL) {
1497 static $_dao = NULL;
1499 $_dao = new CRM_Core_DAO();
1502 if (empty($strings)) {
1506 $escapes = array_map(array($_dao, 'escape'), $strings);
1507 return '"' . implode('","', $escapes) . '"';
1515 public static function escapeWildCardString($string) {
1517 // ensure we escape the single characters % and _ which are mysql wild
1518 // card characters and could come in via sortByCharacter
1519 // note that mysql does not escape these characters
1520 if ($string && in_array($string,
1521 array('%', '_', '%%', '_%')
1523 return '\\' . $string;
1526 return self
::escapeString($string);
1530 * Creates a test object, including any required objects it needs via recursion
1531 * createOnly: only create in database, do not store or return the objects (useful for perf testing)
1532 * ONLY USE FOR TESTING
1534 * @param string $daoName
1535 * @param array $params
1536 * @param int $numObjects
1537 * @param bool $createOnly
1541 static function createTestObject(
1547 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
1548 // so we re-set here in case
1549 $config = CRM_Core_Config
::singleton();
1550 $config->backtrace
= TRUE;
1552 static $counter = 0;
1553 CRM_Core_DAO
::$_testEntitiesToSkip = array(
1554 'CRM_Core_DAO_Worldregion',
1555 'CRM_Core_DAO_StateProvince',
1556 'CRM_Core_DAO_Country',
1557 'CRM_Core_DAO_Domain',
1558 'CRM_Financial_DAO_FinancialType'//because valid ones exist & we use pick them due to pseudoconstant can't reliably create & delete these
1561 for ($i = 0; $i < $numObjects; ++
$i) {
1564 /** @var CRM_Core_DAO $object */
1565 $object = new $daoName();
1567 $fields = & $object->fields();
1568 foreach ($fields as $fieldName => $fieldDef) {
1569 $dbName = $fieldDef['name'];
1570 $FKClassName = CRM_Utils_Array
::value('FKClassName', $fieldDef);
1571 $required = CRM_Utils_Array
::value('required', $fieldDef);
1573 if (CRM_Utils_Array
::value($dbName, $params) !== NULL && !is_array($params[$dbName])) {
1574 $object->$dbName = $params[$dbName];
1577 elseif ($dbName != 'id') {
1578 if ($FKClassName != NULL) {
1579 $object->assignTestFK($fieldName, $fieldDef, $params);
1582 $object->assignTestValue($fieldName, $fieldDef, $counter);
1590 $objects[$i] = $object;
1600 elseif ($numObjects == 1) {
1609 * Deletes the this object plus any dependent objects that are associated with it
1610 * ONLY USE FOR TESTING
1612 * @param string $daoName
1613 * @param array $params
1615 public static function deleteTestObjects($daoName, $params = array()) {
1616 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
1617 // so we re-set here in case
1618 $config = CRM_Core_Config
::singleton();
1619 $config->backtrace
= TRUE;
1621 $object = new $daoName();
1622 $object->id
= CRM_Utils_Array
::value('id', $params);
1624 $deletions = array(); // array(array(0 => $daoName, 1 => $daoParams))
1625 if ($object->find(TRUE)) {
1627 $fields = &$object->fields();
1628 foreach ($fields as $name => $value) {
1630 $dbName = $value['name'];
1632 $FKClassName = CRM_Utils_Array
::value('FKClassName', $value);
1633 $required = CRM_Utils_Array
::value('required', $value);
1634 if ($FKClassName != NULL
1636 && !in_array($FKClassName, CRM_Core_DAO
::$_testEntitiesToSkip)
1637 && ($required ||
$dbName == 'contact_id')
1638 //I'm a bit stuck on this one - we might need to change the singleValueAlter so that the entities don't share a contact
1639 // to make this test process pass - line below makes pass for now
1640 && $dbName != 'member_of_contact_id') {
1641 $deletions[] = array($FKClassName, array('id' => $object->$dbName)); // x
1648 foreach ($deletions as $deletion) {
1649 CRM_Core_DAO
::deleteTestObjects($deletion[0], $deletion[1]);
1654 * Set defaults when creating new entity
1655 * (don't call this set defaults as already in use with different signature in some places)
1657 * @param array $params
1660 public static function setCreateDefaults(&$params, $defaults) {
1661 if (isset($params['id'])) {
1664 foreach ($defaults as $key => $value) {
1665 if (!array_key_exists($key, $params) ||
$params[$key] === NULL) {
1666 $params[$key] = $value;
1672 * @param string $prefix
1673 * @param bool $addRandomString
1674 * @param null $string
1678 public static function createTempTableName($prefix = 'civicrm', $addRandomString = TRUE, $string = NULL) {
1679 $tableName = $prefix . "_temp";
1681 if ($addRandomString) {
1683 $tableName .= "_" . $string;
1686 $tableName .= "_" . md5(uniqid('', TRUE));
1694 * @param bool $trigger
1698 public static function checkTriggerViewPermission($view = TRUE, $trigger = TRUE) {
1699 // test for create view and trigger permissions and if allowed, add the option to go multilingual
1701 // I'm not sure why we use the getStaticProperty for an error, rather than checking for DB_Error
1702 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
1703 $dao = new CRM_Core_DAO();
1705 $dao->query('CREATE OR REPLACE VIEW civicrm_domain_view AS SELECT * FROM civicrm_domain');
1706 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
1712 $result = $dao->query('CREATE TRIGGER civicrm_domain_trigger BEFORE INSERT ON civicrm_domain FOR EACH ROW BEGIN END');
1713 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError') ||
is_a($result, 'DB_Error')) {
1715 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1720 $dao->query('DROP TRIGGER IF EXISTS civicrm_domain_trigger');
1721 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
1723 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1730 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1731 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
1740 * @param null $message
1741 * @param bool $printDAO
1743 public static function debugPrint($message = NULL, $printDAO = TRUE) {
1744 CRM_Utils_System
::xMemory("{$message}: ");
1747 global $_DB_DATAOBJECT;
1749 foreach (array_keys($_DB_DATAOBJECT['RESULTS']) as $id) {
1750 $q[] = $_DB_DATAOBJECT['RESULTS'][$id]->query
;
1752 CRM_Core_Error
::debug('_DB_DATAOBJECT', $q);
1757 * Build a list of triggers via hook and add them to (err, reconcile them
1758 * with) the database.
1760 * @param $tableName string the specific table requiring a rebuild; or NULL to rebuild all tables
1761 * @param bool $force
1765 public static function triggerRebuild($tableName = NULL, $force = FALSE) {
1768 $logging = new CRM_Logging_Schema
;
1769 $logging->triggerInfo($info, $tableName, $force);
1771 CRM_Core_I18n_Schema
::triggerInfo($info, $tableName);
1772 CRM_Contact_BAO_Contact
::triggerInfo($info, $tableName);
1774 CRM_Utils_Hook
::triggerInfo($info, $tableName);
1776 // drop all existing triggers on all tables
1777 $logging->dropTriggers($tableName);
1779 // now create the set of new triggers
1780 self
::createTriggers($info, $tableName);
1784 * Because sql functions are sometimes lost, esp during db migration, we check here to avoid numerous support requests
1785 * @see http://issues.civicrm.org/jira/browse/CRM-13822
1786 * TODO: Alternative solutions might be
1787 * * Stop using functions and find another way to strip numeric characters from phones
1788 * * Give better error messages (currently a missing fn fatals with "unknown error")
1790 public static function checkSqlFunctionsExist() {
1791 if (!self
::$_checkedSqlFunctionsExist) {
1792 self
::$_checkedSqlFunctionsExist = TRUE;
1793 $dao = CRM_Core_DAO
::executeQuery("SHOW function status WHERE db = database() AND name = 'civicrm_strip_non_numeric'");
1794 if (!$dao->fetch()) {
1795 self
::triggerRebuild();
1801 * Wrapper function to drop triggers
1803 * @param $tableName string the specific table requiring a rebuild; or NULL to rebuild all tables
1805 public static function dropTriggers($tableName = NULL) {
1808 $logging = new CRM_Logging_Schema
;
1809 $logging->triggerInfo($info, $tableName);
1811 // drop all existing triggers on all tables
1812 $logging->dropTriggers($tableName);
1816 * @param $info array per hook_civicrm_triggerInfo
1817 * @param $onlyTableName string the specific table requiring a rebuild; or NULL to rebuild all tables
1819 public static function createTriggers(&$info, $onlyTableName = NULL) {
1820 // Validate info array, should probably raise errors?
1821 if (is_array($info) == FALSE) {
1825 $triggers = array();
1827 // now enumerate the tables and the events and collect the same set in a different format
1828 foreach ($info as $value) {
1830 // clean the incoming data, skip malformed entries
1831 // TODO: malformed entries should raise errors or get logged.
1832 if (isset($value['table']) == FALSE ||
1833 isset($value['event']) == FALSE ||
1834 isset($value['when']) == FALSE ||
1835 isset($value['sql']) == FALSE
1840 if (is_string($value['table']) == TRUE) {
1841 $tables = array($value['table']);
1844 $tables = $value['table'];
1847 if (is_string($value['event']) == TRUE) {
1848 $events = array(strtolower($value['event']));
1851 $events = array_map('strtolower', $value['event']);
1854 $whenName = strtolower($value['when']);
1856 foreach ($tables as $tableName) {
1857 if (!isset($triggers[$tableName])) {
1858 $triggers[$tableName] = array();
1861 foreach ($events as $eventName) {
1862 $template_params = array('{tableName}', '{eventName}');
1863 $template_values = array($tableName, $eventName);
1865 $sql = str_replace($template_params,
1869 $variables = str_replace($template_params,
1871 CRM_Utils_Array
::value('variables', $value)
1874 if (!isset($triggers[$tableName][$eventName])) {
1875 $triggers[$tableName][$eventName] = array();
1878 if (!isset($triggers[$tableName][$eventName][$whenName])) {
1879 // We're leaving out cursors, conditions, and handlers for now
1880 // they are kind of dangerous in this context anyway
1881 // better off putting them in stored procedures
1882 $triggers[$tableName][$eventName][$whenName] = array(
1883 'variables' => array(),
1889 $triggers[$tableName][$eventName][$whenName]['variables'][] = $variables;
1892 $triggers[$tableName][$eventName][$whenName]['sql'][] = $sql;
1897 // now spit out the sql
1898 foreach ($triggers as $tableName => $tables) {
1899 if ($onlyTableName != NULL && $onlyTableName != $tableName) {
1902 foreach ($tables as $eventName => $events) {
1903 foreach ($events as $whenName => $parts) {
1904 $varString = implode("\n", $parts['variables']);
1905 $sqlString = implode("\n", $parts['sql']);
1906 $validName = CRM_Core_DAO
::shortenSQLName($tableName, 48, TRUE);
1907 $triggerName = "{$validName}_{$whenName}_{$eventName}";
1908 $triggerSQL = "CREATE TRIGGER $triggerName $whenName $eventName ON $tableName FOR EACH ROW BEGIN $varString $sqlString END";
1910 CRM_Core_DAO
::executeQuery("DROP TRIGGER IF EXISTS $triggerName");
1911 CRM_Core_DAO
::executeQuery(
1925 * Given a list of fields, create a list of references.
1927 * @param string $className BAO/DAO class name
1928 * @return array<CRM_Core_Reference_Interface>
1930 public static function createReferenceColumns($className) {
1932 $fields = $className::fields();
1933 foreach ($fields as $field) {
1934 if (isset($field['pseudoconstant'], $field['pseudoconstant']['optionGroupName'])) {
1935 $result[] = new CRM_Core_Reference_OptionValue(
1936 $className::getTableName(),
1938 'civicrm_option_value',
1939 CRM_Utils_Array
::value('keyColumn', $field['pseudoconstant'], 'value'),
1940 $field['pseudoconstant']['optionGroupName']
1948 * Find all records which refer to this entity.
1950 * @return array of objects referencing this
1952 public function findReferences() {
1953 $links = self
::getReferencesToTable(static::getTableName());
1955 $occurrences = array();
1956 foreach ($links as $refSpec) {
1957 /** @var $refSpec CRM_Core_Reference_Interface */
1958 $daoName = CRM_Core_DAO_AllCoreTables
::getClassForTable($refSpec->getReferenceTable());
1959 $result = $refSpec->findReferences($this);
1961 while ($result->fetch()) {
1962 $obj = new $daoName();
1963 $obj->id
= $result->id
;
1964 $occurrences[] = $obj;
1969 return $occurrences;
1973 * @return array each item has keys:
1977 * - table: string|null SQL table name
1978 * - key: string|null SQL column name
1980 public function getReferenceCounts() {
1981 $links = self
::getReferencesToTable(static::getTableName());
1984 foreach ($links as $refSpec) {
1985 /** @var $refSpec CRM_Core_Reference_Interface */
1986 $count = $refSpec->getReferenceCount($this);
1987 if ($count['count'] != 0) {
1992 foreach (CRM_Core_Component
::getEnabledComponents() as $component) {
1993 /** @var $component CRM_Core_Component_Info */
1994 $counts = array_merge($counts, $component->getReferenceCounts($this));
1996 CRM_Utils_Hook
::referenceCounts($this, $counts);
2002 * List all tables which have hard foreign keys to this table.
2004 * For now, this returns a description of every entity_id/entity_table
2006 * TODO: filter dynamic entity references on the $tableName, based on
2007 * schema metadata in dynamicForeignKey which enumerates a restricted
2008 * set of possible entity_table's.
2010 * @param string $tableName table referred to
2012 * @return array structure of table and column, listing every table with a
2013 * foreign key reference to $tableName, and the column where the key appears.
2015 public static function getReferencesToTable($tableName) {
2016 $refsFound = array();
2017 foreach (CRM_Core_DAO_AllCoreTables
::getClasses() as $daoClassName) {
2018 $links = $daoClassName::getReferenceColumns();
2019 $daoTableName = $daoClassName::getTableName();
2021 foreach ($links as $refSpec) {
2022 /** @var $refSpec CRM_Core_Reference_Interface */
2023 if ($refSpec->matchesTargetTable($tableName)) {
2024 $refsFound[] = $refSpec;
2032 * Lookup the value of a MySQL global configuration variable.
2034 * @param string $name e.g. "thread_stack"
2035 * @param mixed $default
2038 public static function getGlobalSetting($name, $default = NULL) {
2039 // Alternatively, SELECT @@GLOBAL.thread_stack, but
2040 // that has been reported to fail under MySQL 5.0 for OS X
2041 $escapedName = self
::escapeString($name);
2042 $dao = CRM_Core_DAO
::executeQuery("SHOW VARIABLES LIKE '$escapedName'");
2043 if ($dao->fetch()) {
2052 * Get options for the called BAO object's field.
2053 * This function can be overridden by each BAO to add more logic related to context.
2054 * The overriding function will generally call the lower-level CRM_Core_PseudoConstant::get
2056 * @param string $fieldName
2057 * @param string $context : @see CRM_Core_DAO::buildOptionsContext
2058 * @param array $props : whatever is known about this bao object
2060 * @return Array|bool
2062 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
2063 // If a given bao does not override this function
2064 $baoName = get_called_class();
2065 return CRM_Core_PseudoConstant
::get($baoName, $fieldName, array(), $context);
2069 * Populate option labels for this object's fields.
2071 * @throws exception if called directly on the base class
2073 public function getOptionLabels() {
2074 $fields = $this->fields();
2075 if ($fields === NULL) {
2076 throw new Exception ('Cannot call getOptionLabels on CRM_Core_DAO');
2078 foreach ($fields as $field) {
2079 $name = CRM_Utils_Array
::value('name', $field);
2080 if ($name && isset($this->$name)) {
2081 $label = CRM_Core_PseudoConstant
::getLabel(get_class($this), $name, $this->$name);
2082 if ($label !== FALSE) {
2083 // Append 'label' onto the field name
2084 $labelName = $name . '_label';
2085 $this->$labelName = $label;
2092 * Provides documentation and validation for the buildOptions $context param
2094 * @param String $context
2099 public static function buildOptionsContext($context = NULL) {
2101 'get' => "All options are returned, even if they are disabled. Labels are translated.",
2102 'create' => "Options are filtered appropriately for the object being created/updated. Labels are translated.",
2103 'search' => "Searchable options are returned. Labels are translated.",
2104 'validate' => "All options are returned, even if they are disabled. Machine names are used in place of labels.",
2106 // Validation: enforce uniformity of this param
2107 if ($context !== NULL && !isset($contexts[$context])) {
2108 throw new Exception("'$context' is not a valid context for buildOptions.");
2114 * @param string $fieldName
2115 * @return bool|array
2117 public function getFieldSpec($fieldName) {
2118 $fields = $this->fields();
2119 $fieldKeys = $this->fieldKeys();
2121 // Support "unique names" as well as sql names
2122 $fieldKey = $fieldName;
2123 if (empty($fields[$fieldKey])) {
2124 $fieldKey = CRM_Utils_Array
::value($fieldName, $fieldKeys);
2126 // If neither worked then this field doesn't exist. Return false.
2127 if (empty($fields[$fieldKey])) {
2130 return $fields[$fieldKey];
2134 * SQL version of api function to assign filters to the DAO based on the syntax
2135 * $field => array('IN' => array(4,6,9))
2137 * $field => array('LIKE' => array('%me%))
2140 * @param string $fieldName name of fields
2141 * @param $filter array filter to be applied indexed by operator
2142 * @param $type String type of field (not actually used - nor in api @todo )
2143 * @param $alias String alternative field name ('as') @todo- not actually used
2144 * @param bool $returnSanitisedArray return a sanitised array instead of a clause
2145 * this is primarily so we can add filters @ the api level to the Query object based fields
2149 * @todo a better solution would be for the query object to apply these filters based on the
2150 * api supported format (but we don't want to risk breakage in alpha stage & query class is scary
2151 * @todo @time of writing only IN & NOT IN are supported for the array style syntax (as test is
2152 * required to extend further & it may be the comments per above should be implemented. It may be
2153 * preferable to not double-banger the return context next refactor of this - but keeping the attention
2154 * in one place has some advantages as we try to extend this format
2156 * @return NULL|string|array a string is returned if $returnSanitisedArray is not set, otherwise and Array or NULL
2157 * depending on whether it is supported as yet
2159 public static function createSQLFilter($fieldName, $filter, $type, $alias = NULL, $returnSanitisedArray = FALSE) {
2160 // http://issues.civicrm.org/jira/browse/CRM-9150 - stick with 'simple' operators for now
2161 // support for other syntaxes is discussed in ticket but being put off for now
2162 foreach ($filter as $operator => $criteria) {
2163 if (in_array($operator, self
::acceptedSQLOperators())) {
2164 switch ($operator) {
2168 if (!$returnSanitisedArray) {
2169 return (sprintf('%s %s', $fieldName, $operator));
2172 return (sprintf('%s %s ', $fieldName, $operator));
2176 // ternary operators
2179 if (empty($criteria[0]) ||
empty($criteria[1])) {
2180 throw new Exception("invalid criteria for $operator");
2182 if (!$returnSanitisedArray) {
2183 return (sprintf('%s ' . $operator . ' "%s" AND "%s"', $fieldName, CRM_Core_DAO
::escapeString($criteria[0]), CRM_Core_DAO
::escapeString($criteria[1])));
2186 return NULL; // not yet implemented (tests required to implement)
2193 if (empty($criteria)) {
2194 throw new Exception("invalid criteria for $operator");
2196 $escapedCriteria = array_map(array(
2200 if (!$returnSanitisedArray) {
2201 return (sprintf('%s %s ("%s")', $fieldName, $operator, implode('", "', $escapedCriteria)));
2203 return $escapedCriteria;
2209 if (!$returnSanitisedArray) {
2210 return(sprintf('%s %s "%s"', $fieldName, $operator, CRM_Core_DAO
::escapeString($criteria)));
2213 return NULL; // not yet implemented (tests required to implement)
2221 * @see http://issues.civicrm.org/jira/browse/CRM-9150
2222 * support for other syntaxes is discussed in ticket but being put off for now
2225 public static function acceptedSQLOperators() {
2226 return array('=', '<=', '>=', '>', '<', 'LIKE', "<>", "!=", "NOT LIKE", 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN', 'IS NOT NULL', 'IS NULL');
2230 * SQL has a limit of 64 characters on various names:
2231 * table name, trigger name, column name ...
2233 * For custom groups and fields we generated names from user entered input
2234 * which can be longer than this length, this function helps with creating
2235 * strings that meet various criteria.
2237 * @param string $string - the string to be shortened
2238 * @param int $length - the max length of the string
2240 * @param bool $makeRandom
2244 public static function shortenSQLName($string, $length = 60, $makeRandom = FALSE) {
2245 // early return for strings that meet the requirements
2246 if (strlen($string) <= $length) {
2250 // easy return for calls that dont need a randomized uniq string
2252 return substr($string, 0, $length);
2255 // the string is longer than the length and we need a uniq string
2256 // for the same tablename we need the same uniq string everytime
2257 // hence we use md5 on the string, which is not random
2258 // we'll append 8 characters to the end of the tableName
2259 $md5string = substr(md5($string), 0, 8);
2260 return substr($string, 0, $length - 8) . "_{$md5string}";
2264 * @param array $params
2266 public function setApiFilter(&$params) {}