3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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-2013
37 require_once 'PEAR.php';
38 require_once 'DB/DataObject.php';
40 require_once 'CRM/Core/I18n.php';
41 class CRM_Core_DAO
extends DB_DataObject
{
44 * a null object so we can pass it as reference if / when needed
46 static $_nullObject = NULL;
47 static $_nullArray = array();
49 static $_dbColumnValueCache = NULL;
50 CONST NOT_NULL
= 1, IS_NULL
= 2,
52 VALUE_SEPARATOR
= "\ 1",
53 BULK_INSERT_COUNT
= 200,
54 BULK_INSERT_HIGH_COUNT
= 200,
55 // special value for mail bulk inserts to avoid
56 // potential duplication, assuming a smaller number reduces number of queries
57 // by some factor, so some tradeoff. CRM-8678
58 BULK_MAIL_INSERT_COUNT
= 10,
59 QUERY_FORMAT_WILDCARD
= 1,
60 QUERY_FORMAT_NO_QUOTES
= 2;
63 * Define entities that shouldn't be created or deleted when creating/ deleting
64 * test objects - this prevents world regions, countries etc from being added / deleted
66 static $_testEntitiesToSkip = array();
68 * the factory class for this application
71 static $_factory = NULL;
73 static $_checkedSqlFunctionsExist = FALSE;
81 function __construct() {
83 $this->__table
= $this->getTableName();
87 * empty definition for virtual function
89 static function getTableName() {
94 * initialize the DAO object
96 * @param string $dsn the database connection string
102 static function init($dsn) {
103 $options = &PEAR
::getStaticProperty('DB_DataObject', 'options');
104 $options['database'] = $dsn;
105 if (defined('CIVICRM_DAO_DEBUG')) {
106 self
::DebugLevel(CIVICRM_DAO_DEBUG
);
111 * reset the DAO object. DAO is kinda crappy in that there is an unwritten
112 * rule of one query per DAO. We attempt to get around this crappy restricrion
113 * by resetting some of DAO's internal fields. Use this with caution
121 foreach (array_keys($this->table()) as $field) {
122 unset($this->$field);
126 * reset the various DB_DAO structures manually
128 $this->_query
= array();
134 static function getLocaleTableName($tableName) {
137 $tables = CRM_Core_I18n_Schema
::schemaStructureTables();
138 if (in_array($tableName, $tables)) {
139 return $tableName . $dbLocale;
146 * Execute a query by the current DAO, localizing it along the way (if needed).
148 * @param string $query the SQL query for execution
149 * @param bool $i18nRewrite whether to rewrite the query
151 * @return object the current DAO object after the query execution
153 function query($query, $i18nRewrite = TRUE) {
154 // rewrite queries that should use $dbLocale-based views for multi-language installs
156 if ($i18nRewrite and $dbLocale) {
157 $query = CRM_Core_I18n_Schema
::rewriteQuery($query);
160 return parent
::query($query);
164 * Static function to set the factory instance for this class.
166 * @param object $factory the factory application object
172 static function setFactory(&$factory) {
173 self
::$_factory = &$factory;
177 * Factory method to instantiate a new object from a table name.
182 function factory($table = '') {
183 if (!isset(self
::$_factory)) {
184 return parent
::factory($table);
187 return self
::$_factory->create($table);
191 * Initialization for all DAO objects. Since we access DB_DO programatically
192 * we need to set the links manually.
197 function initialize() {
202 * Defines the default key as 'id'.
217 * Tells DB_DataObject which keys use autoincrement.
218 * 'id' is autoincrementing by default.
224 function sequenceKey() {
225 static $sequenceKeys;
226 if (!isset($sequenceKeys)) {
227 $sequenceKeys = array('id', TRUE);
229 return $sequenceKeys;
233 * returns list of FK relationships
238 * @return array of CRM_Core_EntityReference
240 static function getReferenceColumns() {
245 * returns all the column names of this table
251 static function &fields() {
257 $fields = &$this->fields();
261 foreach ($fields as $name => $value) {
262 $table[$value['name']] = $value['type'];
263 if (CRM_Utils_Array
::value('required', $value)) {
264 $table[$value['name']] +
= self
::DB_DAO_NOTNULL
;
273 if (!empty($this->id
)) {
281 CRM_Utils_Hook
::postSave($this);
286 function log($created = FALSE) {
289 if (!$this->getLog()) {
294 $session = CRM_Core_Session
::singleton();
295 $cid = $session->get('userID');
298 // return is we dont have handle to FK
303 $dao = new CRM_Core_DAO_Log();
304 $dao->entity_table
= $this->getTableName();
305 $dao->entity_id
= $this->id
;
306 $dao->modified_id
= $cid;
307 $dao->modified_date
= date("YmdHis");
312 * Given an associative array of name/value pairs, extract all the values
313 * that belong to this object and initialize the object with said values
315 * @param array $params (reference ) associative array of name/value pairs
317 * @return boolean did we copy all null values into the object
320 function copyValues(&$params) {
321 $fields = &$this->fields();
323 foreach ($fields as $name => $value) {
324 $dbName = $value['name'];
325 if (array_key_exists($dbName, $params)) {
326 $pValue = $params[$dbName];
329 elseif (array_key_exists($name, $params)) {
330 $pValue = $params[$name];
337 // if there is no value then make the variable NULL
339 if ($pValue === '') {
340 $this->$dbName = 'null';
343 $this->$dbName = $pValue;
352 * Store all the values from this object in an associative array
353 * this is a destructive store, calling function is responsible
354 * for keeping sanity of id's.
356 * @param object $object the object that we are extracting data from
357 * @param array $values (reference ) associative array of name/value pairs
363 static function storeValues(&$object, &$values) {
364 $fields = &$object->fields();
365 foreach ($fields as $name => $value) {
366 $dbName = $value['name'];
367 if (isset($object->$dbName) && $object->$dbName !== 'null') {
368 $values[$dbName] = $object->$dbName;
369 if ($name != $dbName) {
370 $values[$name] = $object->$dbName;
377 * create an attribute for this specific field. We only do this for strings and text
379 * @param array $field the field under task
381 * @return array|null the attributes for the object
385 static function makeAttribute($field) {
387 if (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_STRING
) {
388 $maxLength = CRM_Utils_Array
::value('maxlength', $field);
389 $size = CRM_Utils_Array
::value('size', $field);
390 if ($maxLength ||
$size) {
391 $attributes = array();
393 $attributes['maxlength'] = $maxLength;
396 $attributes['size'] = $size;
401 elseif (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_TEXT
) {
402 $rows = CRM_Utils_Array
::value('rows', $field);
406 $cols = CRM_Utils_Array
::value('cols', $field);
411 $attributes = array();
412 $attributes['rows'] = $rows;
413 $attributes['cols'] = $cols;
416 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
) {
417 $attributes['size'] = 6;
418 $attributes['maxlength'] = 14;
426 * Get the size and maxLength attributes for this text field
427 * (or for all text fields) in the DAO object.
429 * @param string $class name of DAO class
430 * @param string $fieldName field that i'm interested in or null if
431 * you want the attributes for all DAO text fields
433 * @return array assoc array of name => attribute pairs
437 static function getAttribute($class, $fieldName = NULL) {
438 $object = new $class( );
439 $fields = &$object->fields();
440 if ($fieldName != NULL) {
441 $field = CRM_Utils_Array
::value($fieldName, $fields);
442 return self
::makeAttribute($field);
445 $attributes = array();
446 foreach ($fields as $name => $field) {
447 $attribute = self
::makeAttribute($field);
449 $attributes[$name] = $attribute;
453 if (!empty($attributes)) {
460 static function transaction($type) {
461 CRM_Core_Error
::fatal('This function is obsolete, please use CRM_Core_Transaction');
465 * Check if there is a record with the same name in the db
467 * @param string $value the value of the field we are checking
468 * @param string $daoName the dao object name
469 * @param string $daoID the id of the object being updated. u can change your name
470 * as long as there is no conflict
471 * @param string $fieldName the name of the field in the DAO
473 * @return boolean true if object exists
477 static function objectExists($value, $daoName, $daoID, $fieldName = 'name') {
478 $object = new $daoName( );
479 $object->$fieldName = $value;
481 $config = CRM_Core_Config
::singleton();
483 if ($object->find(TRUE)) {
484 return ($daoID && $object->id
== $daoID) ?
TRUE : FALSE;
492 * Check if there is a given column in a specific table
494 * @param string $tableName
495 * @param string $columnName
496 * @param bool $i18nRewrite whether to rewrite the query on multilingual setups
498 * @return boolean true if exists, else false
501 static function checkFieldExists($tableName, $columnName, $i18nRewrite = TRUE) {
507 $params = array(1 => array($columnName, 'String'));
508 $dao = CRM_Core_DAO
::executeQuery($query, $params, TRUE, NULL, FALSE, $i18nRewrite);
509 $result = $dao->fetch() ?
TRUE : FALSE;
515 * Returns the storage engine used by given table-name(optional).
516 * Otherwise scans all the tables and return an array of all the
517 * distinct storage engines being used.
519 * @param string $tableName
524 static function getStorageValues($tableName = NULL, $maxTablesToCheck = 10, $fieldName = 'Engine') {
526 $query = "SHOW TABLE STATUS LIKE %1";
530 if (isset($tableName)) {
531 $params = array(1 => array($tableName, 'String'));
534 $params = array(1 => array('civicrm_%', 'String'));
537 $dao = CRM_Core_DAO
::executeQuery($query, $params);
540 while ($dao->fetch()) {
541 if (isset($values[$dao->$fieldName]) ||
542 // ignore import and other temp tables
543 strpos($dao->Name
, 'civicrm_import_job_') !== FALSE ||
544 strpos($dao->Name
, '_temp') !== FALSE
548 $values[$dao->$fieldName] = 1;
550 if ($maxTablesToCheck &&
551 $count >= $maxTablesToCheck
560 static function isDBMyISAM($maxTablesToCheck = 10) {
561 // show error if any of the tables, use 'MyISAM' storage engine.
562 $engines = self
::getStorageValues(NULL, $maxTablesToCheck);
563 if (array_key_exists('MyISAM', $engines)) {
570 * Checks if a constraint exists for a specified table.
572 * @param string $tableName
573 * @param string $constraint
575 * @return boolean true if constraint exists, false otherwise
578 static function checkConstraintExists($tableName, $constraint) {
579 static $show = array();
581 if (!array_key_exists($tableName, $show)) {
582 $query = "SHOW CREATE TABLE $tableName";
583 $dao = CRM_Core_DAO
::executeQuery($query);
585 if (!$dao->fetch()) {
586 CRM_Core_Error
::fatal();
590 $show[$tableName] = $dao->Create_Table
;
593 return preg_match("/\b$constraint\b/i", $show[$tableName]) ?
TRUE : FALSE;
597 * Checks if CONSTRAINT keyword exists for a specified table.
599 * @param string $tableName
601 * @return boolean true if CONSTRAINT keyword exists, false otherwise
603 static function schemaRequiresRebuilding($tables = array("civicrm_contact")) {
605 foreach($tables as $tableName){
606 if (!array_key_exists($tableName, $show)) {
607 $query = "SHOW CREATE TABLE $tableName";
608 $dao = CRM_Core_DAO
::executeQuery($query);
610 if (!$dao->fetch()) {
611 CRM_Core_Error
::fatal();
615 $show[$tableName] = $dao->Create_Table
;
618 $result = preg_match("/\bCONSTRAINT\b\s/i", $show[$tableName]) ?
TRUE : FALSE;
630 * Checks if the FK constraint name is in the format 'FK_tableName_columnName'
631 * for a specified column of a table.
633 * @param string $tableName
634 * @param string $columnName
636 * @return boolean true if in format, false otherwise
639 static function checkFKConstraintInFormat($tableName, $columnName) {
640 static $show = array();
642 if (!array_key_exists($tableName, $show)) {
643 $query = "SHOW CREATE TABLE $tableName";
644 $dao = CRM_Core_DAO
::executeQuery($query);
646 if (!$dao->fetch()) {
647 CRM_Core_Error
::fatal();
651 $show[$tableName] = $dao->Create_Table
;
653 $constraint = "`FK_{$tableName}_{$columnName}`";
654 $pattern = "/\bCONSTRAINT\b\s+%s\s+\bFOREIGN\s+KEY\b\s/i";
655 return preg_match(sprintf($pattern, $constraint),$show[$tableName]) ?
TRUE : FALSE;
659 * Check whether a specific column in a specific table has always the same value
661 * @param string $tableName
662 * @param string $columnName
663 * @param string $columnValue
665 * @return boolean true if the value is always $columnValue, false otherwise
668 static function checkFieldHasAlwaysValue($tableName, $columnName, $columnValue) {
669 $query = "SELECT * FROM $tableName WHERE $columnName != '$columnValue'";
670 $dao = CRM_Core_DAO
::executeQuery($query);
671 $result = $dao->fetch() ?
FALSE : TRUE;
677 * Check whether a specific column in a specific table is always NULL
679 * @param string $tableName
680 * @param string $columnName
682 * @return boolean true if if the value is always NULL, false otherwise
685 static function checkFieldIsAlwaysNull($tableName, $columnName) {
686 $query = "SELECT * FROM $tableName WHERE $columnName IS NOT NULL";
687 $dao = CRM_Core_DAO
::executeQuery($query);
688 $result = $dao->fetch() ?
FALSE : TRUE;
694 * Check if there is a given table in the database
696 * @param string $tableName
698 * @return boolean true if exists, else false
701 static function checkTableExists($tableName) {
706 $params = array(1 => array($tableName, 'String'));
708 $dao = CRM_Core_DAO
::executeQuery($query, $params);
709 $result = $dao->fetch() ?
TRUE : FALSE;
714 function checkVersion($version) {
719 $dbVersion = CRM_Core_DAO
::singleValueQuery($query);
720 return trim($version) == trim($dbVersion) ?
TRUE : FALSE;
724 * Given a DAO name, a column name and a column value, find the record and GET the value of another column in that record
726 * @param string $daoName Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact)
727 * @param int $searchValue Value of the column you want to search by
728 * @param string $returnColumn Name of the column you want to GET the value of
729 * @param string $searchColumn Name of the column you want to search by
730 * @param boolean $force Skip use of the cache
732 * @return string|null Value of $returnColumn in the retrieved record
736 static function getFieldValue($daoName, $searchValue, $returnColumn = 'name', $searchColumn = 'id', $force = FALSE) {
738 empty($searchValue) ||
739 trim(strtolower($searchValue)) == 'null'
741 // adding this year since developers forget to check for an id
742 // or for the 'null' (which is a bad DAO kludge)
743 // and hence we get the first value in the db
744 CRM_Core_Error
::fatal();
747 $cacheKey = "{$daoName}:{$searchValue}:{$returnColumn}:{$searchColumn}";
748 if (self
::$_dbColumnValueCache === NULL) {
749 self
::$_dbColumnValueCache = array();
752 if (!array_key_exists($cacheKey, self
::$_dbColumnValueCache) ||
$force) {
753 $object = new $daoName( );
754 $object->$searchColumn = $searchValue;
755 $object->selectAdd();
756 $object->selectAdd($returnColumn);
759 if ($object->find(TRUE)) {
760 $result = $object->$returnColumn;
764 self
::$_dbColumnValueCache[$cacheKey] = $result;
766 return self
::$_dbColumnValueCache[$cacheKey];
770 * Given a DAO name, a column name and a column value, find the record and SET the value of another column in that record
772 * @param string $daoName Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact)
773 * @param int $searchValue Value of the column you want to search by
774 * @param string $setColumn Name of the column you want to SET the value of
775 * @param string $setValue SET the setColumn to this value
776 * @param string $searchColumn Name of the column you want to search by
778 * @return boolean true if we found and updated the object, else false
782 static function setFieldValue($daoName, $searchValue, $setColumn, $setValue, $searchColumn = 'id') {
783 $object = new $daoName( );
784 $object->selectAdd();
785 $object->selectAdd("$searchColumn, $setColumn");
786 $object->$searchColumn = $searchValue;
788 if ($object->find(TRUE)) {
789 $object->$setColumn = $setValue;
790 if ($object->save()) {
801 * @param array|object $sort either array or CRM_Utils_Sort
802 * @param string $default - default sort value
804 * @return string - sortString
808 static function getSortString($sort, $default = NULL) {
809 // check if sort is of type CRM_Utils_Sort
810 if (is_a($sort, 'CRM_Utils_Sort')) {
811 return $sort->orderBy();
814 // is it an array specified as $field => $sortDirection ?
816 foreach ($sort as $k => $v) {
817 $sortString .= "$k $v,";
819 return rtrim($sortString, ',');
825 * Takes a bunch of params that are needed to match certain criteria and
826 * retrieves the relevant objects. Typically the valid params are only
827 * contact_id. We'll tweak this function to be more full featured over a period
828 * of time. This is the inverse function of create. It also stores all the retrieved
829 * values in the default array
831 * @param string $daoName name of the dao object
832 * @param array $params (reference ) an assoc array of name/value pairs
833 * @param array $defaults (reference ) an assoc array to hold the flattened values
834 * @param array $returnProperities an assoc array of fields that need to be returned, eg array( 'first_name', 'last_name')
836 * @return object an object of type referenced by daoName
840 static function commonRetrieve($daoName, &$params, &$defaults, $returnProperities = NULL) {
841 $object = new $daoName( );
842 $object->copyValues($params);
844 // return only specific fields if returnproperties are sent
845 if (!empty($returnProperities)) {
846 $object->selectAdd();
847 $object->selectAdd(implode(',', $returnProperities));
850 if ($object->find(TRUE)) {
851 self
::storeValues($object, $defaults);
858 * Delete the object records that are associated with this contact
860 * @param string $daoName name of the dao object
861 * @param int $contactId id of the contact to delete
867 static function deleteEntityContact($daoName, $contactId) {
868 $object = new $daoName( );
870 $object->entity_table
= 'civicrm_contact';
871 $object->entity_id
= $contactId;
878 * @param string $query query to be executed
880 * @return Object CRM_Core_DAO object that holds the results of the query
884 static function &executeQuery(
891 $trapException = FALSE
893 $queryStr = self
::composeQuery($query, $params, $abort);
894 //CRM_Core_Error::debug( 'q', $queryStr );
897 $dao = new CRM_Core_DAO();
900 $dao = new $daoName( );
903 if ($trapException) {
904 CRM_Core_Error
::ignoreException();
907 $result = $dao->query($queryStr, $i18nRewrite);
909 if ($trapException) {
910 CRM_Core_Error
::setCallback();
913 if (is_a($result, 'DB_Error')) {
918 preg_match('/^(insert|update|delete|create|drop|replace)/i', $queryStr)
920 // we typically do this for insert/update/delete stataments OR if explicitly asked to
928 * execute a query and get the single result
930 * @param string $query query to be executed
932 * @return string the result of the query
936 static function &singleValueQuery($query,
941 $queryStr = self
::composeQuery($query, $params, $abort);
946 $_dao = new CRM_Core_DAO();
949 $_dao->query($queryStr, $i18nRewrite);
951 $result = $_dao->getDatabaseResult();
954 $row = $result->fetchRow();
963 static function composeQuery($query, &$params, $abort = TRUE) {
965 foreach ($params as $key => $item) {
966 if (is_numeric($key)) {
967 if (CRM_Utils_Type
::validate($item[0], $item[1]) !== NULL) {
968 $item[0] = self
::escapeString($item[0]);
969 if ($item[1] == 'String' ||
970 $item[1] == 'Memo' ||
973 // Support class constants stipulating wildcard characters and/or
974 // non-quoting of strings. Also support legacy code which may be
975 // passing in TRUE or 1 for $item[2], which used to indicate the
976 // use of wildcard characters.
977 if (!empty($item[2])) {
978 if ($item[2] & CRM_Core_DAO
::QUERY_FORMAT_WILDCARD ||
$item[2] === TRUE) {
979 $item[0] = "'%{$item[0]}%'";
981 elseif (!($item[2] & CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
)) {
982 $item[0] = "'{$item[0]}'";
986 $item[0] = "'{$item[0]}'";
990 if (($item[1] == 'Date' ||
$item[1] == 'Timestamp') &&
991 strlen($item[0]) == 0
996 $tr['%' . $key] = $item[0];
999 CRM_Core_Error
::fatal("{$item[0]} is not of type {$item[1]}");
1004 return strtr($query, $tr);
1007 static function freeResult($ids = NULL) {
1008 global $_DB_DATAOBJECT;
1012 foreach ( array_keys( $_DB_DATAOBJECT['RESULTS'] ) as $id ) {
1013 $q[] = $_DB_DATAOBJECT['RESULTS'][$id]->query;
1015 CRM_Core_Error::debug( 'k', $q );
1020 if (!$_DB_DATAOBJECT ||
1021 !isset($_DB_DATAOBJECT['RESULTS'])
1025 $ids = array_keys($_DB_DATAOBJECT['RESULTS']);
1028 foreach ($ids as $id) {
1029 if (isset($_DB_DATAOBJECT['RESULTS'][$id])) {
1030 if (is_resource($_DB_DATAOBJECT['RESULTS'][$id]->result
)) {
1031 mysql_free_result($_DB_DATAOBJECT['RESULTS'][$id]->result
);
1033 unset($_DB_DATAOBJECT['RESULTS'][$id]);
1036 if (isset($_DB_DATAOBJECT['RESULTFIELDS'][$id])) {
1037 unset($_DB_DATAOBJECT['RESULTFIELDS'][$id]);
1043 * This function is to make a shallow copy of an object
1044 * and all the fields in the object
1046 * @param string $daoName name of the dao
1047 * @param array $criteria array of all the fields & values
1048 * on which basis to copy
1049 * @param array $newData array of all the fields & values
1050 * to be copied besides the other fields
1051 * @param string $fieldsFix array of fields that you want to prefix/suffix/replace
1052 * @param string $blockCopyOfDependencies fields that you want to block from
1056 * @return (reference ) the newly created copy of the object
1059 static function ©Generic($daoName, $criteria, $newData = NULL, $fieldsFix = NULL, $blockCopyOfDependencies = NULL) {
1060 $object = new $daoName( );
1062 $object->id
= $criteria['id'];
1065 foreach ($criteria as $key => $value) {
1066 $object->$key = $value;
1071 while ($object->fetch()) {
1073 // all the objects except with $blockCopyOfDependencies set
1074 // be copied - addresses #CRM-1962
1076 if ($blockCopyOfDependencies && $object->$blockCopyOfDependencies) {
1080 $newObject = new $daoName( );
1082 $fields = &$object->fields();
1083 if (!is_array($fieldsFix)) {
1084 $fieldsToPrefix = array();
1085 $fieldsToSuffix = array();
1086 $fieldsToReplace = array();
1088 if (CRM_Utils_Array
::value('prefix', $fieldsFix)) {
1089 $fieldsToPrefix = $fieldsFix['prefix'];
1091 if (CRM_Utils_Array
::value('suffix', $fieldsFix)) {
1092 $fieldsToSuffix = $fieldsFix['suffix'];
1094 if (CRM_Utils_Array
::value('replace', $fieldsFix)) {
1095 $fieldsToReplace = $fieldsFix['replace'];
1098 foreach ($fields as $name => $value) {
1099 if ($name == 'id' ||
$value['name'] == 'id') {
1100 // copy everything but the id!
1104 $dbName = $value['name'];
1105 $newObject->$dbName = $object->$dbName;
1106 if (isset($fieldsToPrefix[$dbName])) {
1107 $newObject->$dbName = $fieldsToPrefix[$dbName] . $newObject->$dbName;
1109 if (isset($fieldsToSuffix[$dbName])) {
1110 $newObject->$dbName .= $fieldsToSuffix[$dbName];
1112 if (isset($fieldsToReplace[$dbName])) {
1113 $newObject->$dbName = $fieldsToReplace[$dbName];
1116 if (substr($name, -5) == '_date' ||
1117 substr($name, -10) == '_date_time'
1119 $newObject->$dbName = CRM_Utils_Date
::isoToMysql($newObject->$dbName);
1123 foreach ($newData as $k => $v) {
1124 $newObject->$k = $v;
1134 * Given the component id, compute the contact id
1135 * since its used for things like send email
1137 public static function &getContactIDsFromComponent(&$componentIDs, $tableName) {
1138 $contactIDs = array();
1140 if (empty($componentIDs)) {
1144 $IDs = implode(',', $componentIDs);
1148 WHERE id IN ( $IDs )
1151 $dao = CRM_Core_DAO
::executeQuery($query);
1152 while ($dao->fetch()) {
1153 $contactIDs[] = $dao->contact_id
;
1159 * Takes a bunch of params that are needed to match certain criteria and
1160 * retrieves the relevant objects. Typically the valid params are only
1161 * contact_id. We'll tweak this function to be more full featured over a period
1162 * of time. This is the inverse function of create. It also stores all the retrieved
1163 * values in the default array
1165 * @param string $daoName name of the dao object
1166 * @param array $params (reference ) an assoc array of name/value pairs
1167 * @param array $defaults (reference ) an assoc array to hold the flattened values
1168 * @param array $returnProperities an assoc array of fields that need to be returned, eg array( 'first_name', 'last_name')
1170 * @return object an object of type referenced by daoName
1174 static function commonRetrieveAll($daoName, $fieldIdName = 'id', $fieldId, &$details, $returnProperities = NULL) {
1175 require_once (str_replace('_', DIRECTORY_SEPARATOR
, $daoName) . ".php");
1176 $object = new $daoName( );
1177 $object->$fieldIdName = $fieldId;
1179 // return only specific fields if returnproperties are sent
1180 if (!empty($returnProperities)) {
1181 $object->selectAdd();
1182 $object->selectAdd('id');
1183 $object->selectAdd(implode(',', $returnProperities));
1187 while ($object->fetch()) {
1188 $defaults = array();
1189 self
::storeValues($object, $defaults);
1190 $details[$object->id
] = $defaults;
1196 static function dropAllTables() {
1198 // first drop all the custom tables we've created
1199 CRM_Core_BAO_CustomGroup
::dropAllTables();
1201 // drop all multilingual views
1202 CRM_Core_I18n_Schema
::dropAllViews();
1204 CRM_Utils_File
::sourceSQLFile(CIVICRM_DSN
,
1205 dirname(__FILE__
) . DIRECTORY_SEPARATOR
.
1206 '..' . DIRECTORY_SEPARATOR
.
1207 '..' . DIRECTORY_SEPARATOR
.
1208 'sql' . DIRECTORY_SEPARATOR
.
1209 'civicrm_drop.mysql'
1213 static function escapeString($string) {
1214 static $_dao = NULL;
1217 $_dao = new CRM_Core_DAO();
1220 return $_dao->escape($string);
1224 * Escape a list of strings for use with "WHERE X IN (...)" queries.
1226 * @param $strings array
1227 * @param $default string the value to use if $strings has no elements
1228 * @return string eg "abc","def","ghi"
1230 static function escapeStrings($strings, $default = NULL) {
1231 static $_dao = NULL;
1233 $_dao = new CRM_Core_DAO();
1236 if (empty($strings)) {
1240 $escapes = array_map(array($_dao, 'escape'), $strings);
1241 return '"' . implode('","', $escapes) . '"';
1244 static function escapeWildCardString($string) {
1246 // ensure we escape the single characters % and _ which are mysql wild
1247 // card characters and could come in via sortByCharacter
1248 // note that mysql does not escape these characters
1249 if ($string && in_array($string,
1250 array('%', '_', '%%', '_%')
1252 return '\\' . $string;
1255 return self
::escapeString($string);
1258 //Creates a test object, including any required objects it needs via recursion
1259 //createOnly: only create in database, do not store or return the objects (useful for perf testing)
1260 //ONLY USE FOR TESTING
1261 static function createTestObject(
1267 static $counter = 0;
1268 CRM_Core_DAO
::$_testEntitiesToSkip = array(
1269 'CRM_Core_DAO_Worldregion',
1270 'CRM_Core_DAO_StateProvince',
1271 'CRM_Core_DAO_Country',
1272 'CRM_Core_DAO_Domain',
1275 for ($i = 0; $i < $numObjects; ++
$i) {
1278 $object = new $daoName();
1280 $fields = &$object->fields();
1281 foreach ($fields as $name => $value) {
1282 $dbName = $value['name'];
1283 if($dbName == 'contact_sub_type' && empty($params['contact_sub_type'])){
1284 //coming up with a rule to set this is too complex let's not set it
1287 $FKClassName = CRM_Utils_Array
::value('FKClassName', $value);
1288 $required = CRM_Utils_Array
::value('required', $value);
1289 if (CRM_Utils_Array
::value($dbName, $params) !== NULL && !is_array($params[$dbName])) {
1290 $object->$dbName = $params[$dbName];
1293 elseif ($dbName != 'id') {
1294 if ($FKClassName != NULL) {
1295 //skip the FK if it is not required
1296 // if it's contact id we should create even if not required
1297 // we'll have a go @ fetching first though
1298 // we WILL create campaigns though for so tests with a campaign pseudoconstant will complete
1299 if($FKClassName === 'CRM_Campaign_DAO_Campaign' && $daoName != $FKClassName) {
1302 if (!$required && $dbName != 'contact_id') {
1303 $fkDAO = new $FKClassName;
1304 if($fkDAO->find(TRUE)){
1305 $object->$dbName = $fkDAO->id
;
1310 if(in_array($FKClassName, CRM_Core_DAO
::$_testEntitiesToSkip)){
1311 $depObject = new $FKClassName();
1312 $depObject->find(TRUE);
1313 } elseif ($daoName == 'CRM_Member_DAO_MembershipType' && $name == 'member_of_contact_id') {
1314 // FIXME: the fields() metadata is not specific enough
1315 $depObject = CRM_Core_DAO
::createTestObject($FKClassName, array('contact_type' => 'Organization'));
1317 //if it is required we need to generate the dependency object first
1318 $depObject = CRM_Core_DAO
::createTestObject($FKClassName, CRM_Utils_Array
::value($dbName, $params, 1));
1320 $object->$dbName = $depObject->id
;
1325 // Pick an option value if needed
1326 if ($value['type'] !== CRM_Utils_Type
::T_BOOLEAN
) {
1327 $options = $daoName::buildOptions($dbName, 'create');
1329 $object->$dbName = key($options);
1334 switch ($value['type']) {
1335 case CRM_Utils_Type
::T_INT
:
1336 case CRM_Utils_Type
::T_FLOAT
:
1337 case CRM_Utils_Type
::T_MONEY
:
1338 $object->$dbName = $counter;
1341 case CRM_Utils_Type
::T_BOOLEAN
:
1342 if (isset($value['default'])) {
1343 $object->$dbName = $value['default'];
1345 elseif ($value['name'] == 'is_deleted' ||
$value['name'] == 'is_test') {
1346 $object->$dbName = 0;
1349 $object->$dbName = 1;
1353 case CRM_Utils_Type
::T_DATE
:
1354 case CRM_Utils_Type
::T_TIMESTAMP
:
1355 case CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
:
1356 $object->$dbName = '19700101';
1357 if($dbName == 'end_date') {
1358 // put this in the future
1359 $object->$dbName = '20200101';
1363 case CRM_Utils_Type
::T_TIME
:
1364 CRM_Core_Error
::fatal('T_TIME shouldnt be used.');
1365 //$object->$dbName='000000';
1367 case CRM_Utils_Type
::T_CCNUM
:
1368 $object->$dbName = '4111 1111 1111 1111';
1371 case CRM_Utils_Type
::T_URL
:
1372 $object->$dbName = 'http://www.civicrm.org';
1375 case CRM_Utils_Type
::T_STRING
:
1376 case CRM_Utils_Type
::T_BLOB
:
1377 case CRM_Utils_Type
::T_MEDIUMBLOB
:
1378 case CRM_Utils_Type
::T_TEXT
:
1379 case CRM_Utils_Type
::T_LONGTEXT
:
1380 case CRM_Utils_Type
::T_EMAIL
:
1382 if (isset($value['enumValues'])) {
1383 if (isset($value['default'])) {
1384 $object->$dbName = $value['default'];
1387 if (is_array($value['enumValues'])) {
1388 $object->$dbName = $value['enumValues'][0];
1391 $defaultValues = explode(',', $value['enumValues']);
1392 $object->$dbName = $defaultValues[0];
1397 $object->$dbName = $dbName . '_' . $counter;
1398 $maxlength = CRM_Utils_Array
::value('maxlength', $value);
1399 if ($maxlength > 0 && strlen($object->$dbName) > $maxlength) {
1400 $object->$dbName = substr($object->$dbName, 0, $value['maxlength']);
1410 $objects[$i] = $object;
1413 else unset($object);
1421 elseif ($numObjects == 1) { return $objects[0];}
1422 else return $objects;
1425 //deletes the this object plus any dependent objects that are associated with it
1426 //ONLY USE FOR TESTING
1428 static function deleteTestObjects($daoName, $params = array(
1431 $object = new $daoName ( );
1432 $object->id
= CRM_Utils_Array
::value('id', $params);
1434 $deletions = array(); // array(array(0 => $daoName, 1 => $daoParams))
1435 if ($object->find(TRUE)) {
1437 $fields = &$object->fields();
1438 foreach ($fields as $name => $value) {
1440 $dbName = $value['name'];
1442 $FKClassName = CRM_Utils_Array
::value('FKClassName', $value);
1443 $required = CRM_Utils_Array
::value('required', $value);
1444 if ($FKClassName != NULL
1446 && !in_array($FKClassName, CRM_Core_DAO
::$_testEntitiesToSkip)
1447 && ($required ||
$dbName == 'contact_id')) {
1448 $deletions[] = array($FKClassName, array('id' => $object->$dbName)); // x
1455 foreach ($deletions as $deletion) {
1456 CRM_Core_DAO
::deleteTestObjects($deletion[0], $deletion[1]);
1460 static function createTempTableName($prefix = 'civicrm', $addRandomString = TRUE, $string = NULL) {
1461 $tableName = $prefix . "_temp";
1463 if ($addRandomString) {
1465 $tableName .= "_" . $string;
1468 $tableName .= "_" . md5(uniqid('', TRUE));
1474 static function checkTriggerViewPermission($view = TRUE, $trigger = TRUE) {
1475 // test for create view and trigger permissions and if allowed, add the option to go multilingual
1477 // I'm not sure why we use the getStaticProperty for an error, rather than checking for DB_Error
1478 CRM_Core_Error
::ignoreException();
1479 $dao = new CRM_Core_DAO();
1481 $dao->query('CREATE OR REPLACE VIEW civicrm_domain_view AS SELECT * FROM civicrm_domain');
1482 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
1483 CRM_Core_Error
::setCallback();
1489 $result = $dao->query('CREATE TRIGGER civicrm_domain_trigger BEFORE INSERT ON civicrm_domain FOR EACH ROW BEGIN END');
1490 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError') ||
is_a($result, 'DB_Error')) {
1491 CRM_Core_Error
::setCallback();
1493 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1498 $dao->query('DROP TRIGGER IF EXISTS civicrm_domain_trigger');
1499 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
1500 CRM_Core_Error
::setCallback();
1502 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1509 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1510 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
1511 CRM_Core_Error
::setCallback();
1515 CRM_Core_Error
::setCallback();
1520 static function debugPrint($message = NULL, $printDAO = TRUE) {
1521 CRM_Utils_System
::xMemory("{$message}: ");
1524 global $_DB_DATAOBJECT;
1526 foreach (array_keys($_DB_DATAOBJECT['RESULTS']) as $id) {
1527 $q[] = $_DB_DATAOBJECT['RESULTS'][$id]->query
;
1529 CRM_Core_Error
::debug('_DB_DATAOBJECT', $q);
1534 * Build a list of triggers via hook and add them to (err, reconcile them
1535 * with) the database.
1537 * @param $tableName string the specific table requiring a rebuild; or NULL to rebuild all tables
1540 static function triggerRebuild($tableName = NULL, $force = FALSE) {
1543 $logging = new CRM_Logging_Schema
;
1544 $logging->triggerInfo($info, $tableName, $force);
1546 CRM_Core_I18n_Schema
::triggerInfo($info, $tableName);
1547 CRM_Contact_BAO_Contact
::triggerInfo($info, $tableName);
1549 CRM_Utils_Hook
::triggerInfo($info, $tableName);
1551 // drop all existing triggers on all tables
1552 $logging->dropTriggers($tableName);
1554 // now create the set of new triggers
1555 self
::createTriggers($info);
1559 * Because sql functions are sometimes lost, esp during db migration, we check here to avoid numerous support requests
1560 * @see http://issues.civicrm.org/jira/browse/CRM-13822
1561 * TODO: Alternative solutions might be
1562 * * Stop using functions and find another way to strip numeric characters from phones
1563 * * Give better error messages (currently a missing fn fatals with "unknown error")
1565 static function checkSqlFunctionsExist() {
1566 if (!self
::$_checkedSqlFunctionsExist) {
1567 self
::$_checkedSqlFunctionsExist = TRUE;
1568 $dao = CRM_Core_DAO
::executeQuery("SHOW function status WHERE db = database() AND name = 'civicrm_strip_non_numeric'");
1569 if (!$dao->fetch()) {
1570 self
::triggerRebuild();
1576 * Wrapper function to drop triggers
1578 * @param $tableName string the specific table requiring a rebuild; or NULL to rebuild all tables
1580 static function dropTriggers($tableName = NULL) {
1583 $logging = new CRM_Logging_Schema
;
1584 $logging->triggerInfo($info, $tableName);
1586 // drop all existing triggers on all tables
1587 $logging->dropTriggers($tableName);
1591 * @param $info array per hook_civicrm_triggerInfo
1592 * @param $onlyTableName string the specific table requiring a rebuild; or NULL to rebuild all tables
1594 static function createTriggers(&$info, $onlyTableName = NULL) {
1595 // Validate info array, should probably raise errors?
1596 if (is_array($info) == FALSE) {
1600 $triggers = array();
1602 // now enumerate the tables and the events and collect the same set in a different format
1603 foreach ($info as $value) {
1605 // clean the incoming data, skip malformed entries
1606 // TODO: malformed entries should raise errors or get logged.
1607 if (isset($value['table']) == FALSE ||
1608 isset($value['event']) == FALSE ||
1609 isset($value['when']) == FALSE ||
1610 isset($value['sql']) == FALSE
1615 if (is_string($value['table']) == TRUE) {
1616 $tables = array($value['table']);
1619 $tables = $value['table'];
1622 if (is_string($value['event']) == TRUE) {
1623 $events = array(strtolower($value['event']));
1626 $events = array_map('strtolower', $value['event']);
1629 $whenName = strtolower($value['when']);
1631 foreach ($tables as $tableName) {
1632 if (!isset($triggers[$tableName])) {
1633 $triggers[$tableName] = array();
1636 foreach ($events as $eventName) {
1637 $template_params = array('{tableName}', '{eventName}');
1638 $template_values = array($tableName, $eventName);
1640 $sql = str_replace($template_params,
1644 $variables = str_replace($template_params,
1646 CRM_Utils_Array
::value('variables', $value)
1649 if (!isset($triggers[$tableName][$eventName])) {
1650 $triggers[$tableName][$eventName] = array();
1653 if (!isset($triggers[$tableName][$eventName][$whenName])) {
1654 // We're leaving out cursors, conditions, and handlers for now
1655 // they are kind of dangerous in this context anyway
1656 // better off putting them in stored procedures
1657 $triggers[$tableName][$eventName][$whenName] = array(
1658 'variables' => array(),
1664 $triggers[$tableName][$eventName][$whenName]['variables'][] = $variables;
1667 $triggers[$tableName][$eventName][$whenName]['sql'][] = $sql;
1672 // now spit out the sql
1673 foreach ($triggers as $tableName => $tables) {
1674 if ($onlyTableName != NULL && $onlyTableName != $tableName) {
1677 foreach ($tables as $eventName => $events) {
1678 foreach ($events as $whenName => $parts) {
1679 $varString = implode("\n", $parts['variables']);
1680 $sqlString = implode("\n", $parts['sql']);
1681 $validName = CRM_Core_DAO
::shortenSQLName($tableName, 48, TRUE);
1682 $triggerName = "{$validName}_{$whenName}_{$eventName}";
1683 $triggerSQL = "CREATE TRIGGER $triggerName $whenName $eventName ON $tableName FOR EACH ROW BEGIN $varString $sqlString END";
1685 CRM_Core_DAO
::executeQuery("DROP TRIGGER IF EXISTS $triggerName");
1686 CRM_Core_DAO
::executeQuery(
1700 * Find all records which refer to this entity.
1702 * @return array of objects referencing this
1704 function findReferences() {
1705 $links = self
::getReferencesToTable(static::getTableName());
1707 $occurrences = array();
1708 foreach ($links as $refSpec) {
1709 $refColumn = $refSpec->getReferenceKey();
1710 $targetColumn = $refSpec->getTargetKey();
1711 $params = array(1 => array($this->$targetColumn, 'String'));
1714 FROM {$refSpec->getReferenceTable()}
1715 WHERE {$refColumn} = %1
1717 if ($refSpec->isGeneric()) {
1718 $params[2] = array(static::getTableName(), 'String');
1720 AND {$refSpec->getTypeColumn()} = %2
1723 $daoName = CRM_Core_DAO_AllCoreTables
::getClassForTable($refSpec->getReferenceTable());
1724 $result = self
::executeQuery($sql, $params, TRUE, $daoName);
1725 while ($result->fetch()) {
1726 $obj = new $daoName();
1727 $obj->id
= $result->id
;
1728 $occurrences[] = $obj;
1732 return $occurrences;
1736 * List all tables which have hard foreign keys to this table.
1738 * For now, this returns a description of every entity_id/entity_table
1740 * TODO: filter dynamic entity references on the $tableName, based on
1741 * schema metadata in dynamicForeignKey which enumerates a restricted
1742 * set of possible entity_table's.
1744 * @param string $tableName table referred to
1746 * @return array structure of table and column, listing every table with a
1747 * foreign key reference to $tableName, and the column where the key appears.
1749 static function getReferencesToTable($tableName) {
1750 $refsFound = array();
1751 foreach (CRM_Core_DAO_AllCoreTables
::getClasses() as $daoClassName) {
1752 $links = $daoClassName::getReferenceColumns();
1753 $daoTableName = $daoClassName::getTableName();
1755 foreach ($links as $refSpec) {
1756 if ($refSpec->getTargetTable() === $tableName
1757 or $refSpec->isGeneric()
1759 $refsFound[] = $refSpec;
1767 * Lookup the value of a MySQL global configuration variable.
1769 * @param string $name e.g. "thread_stack"
1770 * @param mixed $default
1773 public static function getGlobalSetting($name, $default = NULL) {
1774 // Alternatively, SELECT @@GLOBAL.thread_stack, but
1775 // that has been reported to fail under MySQL 5.0 for OS X
1776 $escapedName = self
::escapeString($name);
1777 $dao = CRM_Core_DAO
::executeQuery("SHOW VARIABLES LIKE '$escapedName'");
1778 if ($dao->fetch()) {
1787 * Get options for the called BAO object's field.
1788 * This function can be overridden by each BAO to add more logic related to context.
1789 * The overriding function will generally call the lower-level CRM_Core_PseudoConstant::get
1791 * @param string $fieldName
1792 * @param string $context: @see CRM_Core_DAO::buildOptionsContext
1793 * @param array $props: whatever is known about this bao object
1795 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
1796 // If a given bao does not override this function
1797 $baoName = get_called_class();
1798 return CRM_Core_PseudoConstant
::get($baoName, $fieldName, array(), $context);
1802 * Populate option labels for this object's fields.
1804 * @throws exception if called directly on the base class
1806 public function getOptionLabels() {
1807 $fields = $this->fields();
1808 if ($fields === NULL) {
1809 throw new Exception ('Cannot call getOptionLabels on CRM_Core_DAO');
1811 foreach ($fields as $field) {
1812 $name = CRM_Utils_Array
::value('name', $field);
1813 if ($name && isset($this->$name)) {
1814 $label = CRM_Core_PseudoConstant
::getLabel(get_class($this), $name, $this->$name);
1815 if ($label !== FALSE) {
1816 // Append 'label' onto the field name
1817 $labelName = $name . '_label';
1818 $this->$labelName = $label;
1825 * Provides documentation and validation for the buildOptions $context param
1827 * @param String $context
1829 public static function buildOptionsContext($context = NULL) {
1831 'get' => "All options are returned, even if they are disabled. Labels are translated.",
1832 'create' => "Options are filtered appropriately for the object being created/updated. Labels are translated.",
1833 'search' => "Searchable options are returned. Labels are translated.",
1834 'validate' => "All options are returned, even if they are disabled. Machine names are used in place of labels.",
1836 // Validation: enforce uniformity of this param
1837 if ($context !== NULL && !isset($contexts[$context])) {
1838 throw new Exception("'$context' is not a valid context for buildOptions.");
1844 * SQL version of api function to assign filters to the DAO based on the syntax
1845 * $field => array('IN' => array(4,6,9))
1847 * $field => array('LIKE' => array('%me%))
1850 * @param $fieldname string name of fields
1851 * @param $filter array filter to be applied indexed by operator
1852 * @param $type String type of field (not actually used - nor in api @todo )
1853 * @param $alias String alternative field name ('as') @todo- not actually used
1854 * @param bool $returnSanitisedArray return a sanitised array instead of a clause
1855 * this is primarily so we can add filters @ the api level to the Query object based fields
1856 * @todo a better solutution would be for the query object to apply these filters based on the
1857 * api supported format (but we don't want to risk breakage in alpha stage & query class is scary
1858 * @todo @time of writing only IN & NOT IN are supported for the array style syntax (as test is
1859 * required to extend further & it may be the comments per above should be implemented. It may be
1860 * preferable to not double-banger the return context next refactor of this - but keeping the attention
1861 * in one place has some advantages as we try to extend this format
1863 * @return NULL|string|array a string is returned if $returnSanitisedArray is not set, otherwise and Array or NULL
1864 * depending on whether it is supported as yet
1866 public static function createSQLFilter($fieldName, $filter, $type, $alias = NULL, $returnSanitisedArray = FALSE) {
1867 // http://issues.civicrm.org/jira/browse/CRM-9150 - stick with 'simple' operators for now
1868 // support for other syntaxes is discussed in ticket but being put off for now
1869 $acceptedSQLOperators = array('=', '<=', '>=', '>', '<', 'LIKE', "<>", "!=", "NOT LIKE", 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN');
1870 foreach ($filter as $operator => $criteria) {
1871 if (in_array($operator, $acceptedSQLOperators)) {
1872 switch ($operator) {
1876 if(!$returnSanitisedArray) {
1877 return (sprintf('%s %s', $fieldName, $operator));
1880 return NULL; // not yet implemented (tests required to implement)
1884 // ternary operators
1887 if (empty($criteria[0]) ||
empty($criteria[1])) {
1888 throw new Exception("invalid criteria for $operator");
1890 if(!$returnSanitisedArray) {
1891 return (sprintf('%s ' . $operator . ' "%s" AND "%s"', $fieldName, CRM_Core_DAO
::escapeString($criteria[0]), CRM_Core_DAO
::escapeString($criteria[1])));
1894 return NULL; // not yet implemented (tests required to implement)
1901 if (empty($criteria)) {
1902 throw new Exception("invalid criteria for $operator");
1904 $escapedCriteria = array_map(array(
1908 if(!$returnSanitisedArray) {
1909 return (sprintf('%s %s ("%s")', $fieldName, $operator, implode('", "', $escapedCriteria)));
1911 return $escapedCriteria;
1917 if(!$returnSanitisedArray) {
1918 return(sprintf('%s %s "%s"', $fieldName, $operator, CRM_Core_DAO
::escapeString($criteria)));
1921 return NULL; // not yet implemented (tests required to implement)
1929 * SQL has a limit of 64 characters on various names:
1930 * table name, trigger name, column name ...
1932 * For custom groups and fields we generated names from user entered input
1933 * which can be longer than this length, this function helps with creating
1934 * strings that meet various criteria.
1936 * @param string $string - the string to be shortened
1937 * @param int $length - the max length of the string
1939 public static function shortenSQLName($string, $length = 60, $makeRandom = FALSE) {
1940 // early return for strings that meet the requirements
1941 if (strlen($string) <= $length) {
1945 // easy return for calls that dont need a randomized uniq string
1946 if (! $makeRandom) {
1947 return substr($string, 0, $length);
1950 // the string is longer than the length and we need a uniq string
1951 // for the same tablename we need the same uniq string everytime
1952 // hence we use md5 on the string, which is not random
1953 // we'll append 8 characters to the end of the tableName
1954 $md5string = substr(md5($string), 0, 8);
1955 return substr($string, 0, $length - 8) . "_{$md5string}";
1958 function setApiFilter(&$params) {}