3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
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';
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() {
199 $this->query("SET NAMES utf8");
203 * Defines the default key as 'id'.
218 * Tells DB_DataObject which keys use autoincrement.
219 * 'id' is autoincrementing by default.
225 function sequenceKey() {
226 static $sequenceKeys;
227 if (!isset($sequenceKeys)) {
228 $sequenceKeys = array('id', TRUE);
230 return $sequenceKeys;
234 * returns list of FK relationships
239 * @return array of CRM_Core_EntityReference
241 static function getReferenceColumns() {
246 * returns all the column names of this table
252 static function &fields() {
258 $fields = &$this->fields();
262 foreach ($fields as $name => $value) {
263 $table[$value['name']] = $value['type'];
264 if (!empty($value['required'])) {
265 $table[$value['name']] +
= self
::DB_DAO_NOTNULL
;
274 if (!empty($this->id
)) {
282 CRM_Utils_Hook
::postSave($this);
287 function log($created = FALSE) {
290 if (!$this->getLog()) {
295 $session = CRM_Core_Session
::singleton();
296 $cid = $session->get('userID');
299 // return is we dont have handle to FK
304 $dao = new CRM_Core_DAO_Log();
305 $dao->entity_table
= $this->getTableName();
306 $dao->entity_id
= $this->id
;
307 $dao->modified_id
= $cid;
308 $dao->modified_date
= date("YmdHis");
313 * Given an associative array of name/value pairs, extract all the values
314 * that belong to this object and initialize the object with said values
316 * @param array $params (reference ) associative array of name/value pairs
318 * @return boolean did we copy all null values into the object
321 function copyValues(&$params) {
322 $fields = &$this->fields();
324 foreach ($fields as $name => $value) {
325 $dbName = $value['name'];
326 if (array_key_exists($dbName, $params)) {
327 $pValue = $params[$dbName];
330 elseif (array_key_exists($name, $params)) {
331 $pValue = $params[$name];
338 // if there is no value then make the variable NULL
340 if ($pValue === '') {
341 $this->$dbName = 'null';
344 $this->$dbName = $pValue;
353 * Store all the values from this object in an associative array
354 * this is a destructive store, calling function is responsible
355 * for keeping sanity of id's.
357 * @param object $object the object that we are extracting data from
358 * @param array $values (reference ) associative array of name/value pairs
364 static function storeValues(&$object, &$values) {
365 $fields = &$object->fields();
366 foreach ($fields as $name => $value) {
367 $dbName = $value['name'];
368 if (isset($object->$dbName) && $object->$dbName !== 'null') {
369 $values[$dbName] = $object->$dbName;
370 if ($name != $dbName) {
371 $values[$name] = $object->$dbName;
378 * create an attribute for this specific field. We only do this for strings and text
380 * @param array $field the field under task
382 * @return array|null the attributes for the object
386 static function makeAttribute($field) {
388 if (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_STRING
) {
389 $maxLength = CRM_Utils_Array
::value('maxlength', $field);
390 $size = CRM_Utils_Array
::value('size', $field);
391 if ($maxLength ||
$size) {
392 $attributes = array();
394 $attributes['maxlength'] = $maxLength;
397 $attributes['size'] = $size;
402 elseif (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_TEXT
) {
403 $rows = CRM_Utils_Array
::value('rows', $field);
407 $cols = CRM_Utils_Array
::value('cols', $field);
412 $attributes = array();
413 $attributes['rows'] = $rows;
414 $attributes['cols'] = $cols;
417 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
) {
418 $attributes['size'] = 6;
419 $attributes['maxlength'] = 14;
427 * Get the size and maxLength attributes for this text field
428 * (or for all text fields) in the DAO object.
430 * @param string $class name of DAO class
431 * @param string $fieldName field that i'm interested in or null if
432 * you want the attributes for all DAO text fields
434 * @return array assoc array of name => attribute pairs
438 static function getAttribute($class, $fieldName = NULL) {
439 $object = new $class( );
440 $fields = &$object->fields();
441 if ($fieldName != NULL) {
442 $field = CRM_Utils_Array
::value($fieldName, $fields);
443 return self
::makeAttribute($field);
446 $attributes = array();
447 foreach ($fields as $name => $field) {
448 $attribute = self
::makeAttribute($field);
450 $attributes[$name] = $attribute;
454 if (!empty($attributes)) {
461 static function transaction($type) {
462 CRM_Core_Error
::fatal('This function is obsolete, please use CRM_Core_Transaction');
466 * Check if there is a record with the same name in the db
468 * @param string $value the value of the field we are checking
469 * @param string $daoName the dao object name
470 * @param string $daoID the id of the object being updated. u can change your name
471 * as long as there is no conflict
472 * @param string $fieldName the name of the field in the DAO
474 * @return boolean true if object exists
478 static function objectExists($value, $daoName, $daoID, $fieldName = 'name') {
479 $object = new $daoName( );
480 $object->$fieldName = $value;
482 $config = CRM_Core_Config
::singleton();
484 if ($object->find(TRUE)) {
485 return ($daoID && $object->id
== $daoID) ?
TRUE : FALSE;
493 * Check if there is a given column in a specific table
495 * @param string $tableName
496 * @param string $columnName
497 * @param bool $i18nRewrite whether to rewrite the query on multilingual setups
499 * @return boolean true if exists, else false
502 static function checkFieldExists($tableName, $columnName, $i18nRewrite = TRUE) {
508 $params = array(1 => array($columnName, 'String'));
509 $dao = CRM_Core_DAO
::executeQuery($query, $params, TRUE, NULL, FALSE, $i18nRewrite);
510 $result = $dao->fetch() ?
TRUE : FALSE;
516 * Returns the storage engine used by given table-name(optional).
517 * Otherwise scans all the tables and return an array of all the
518 * distinct storage engines being used.
520 * @param string $tableName
525 static function getStorageValues($tableName = NULL, $maxTablesToCheck = 10, $fieldName = 'Engine') {
527 $query = "SHOW TABLE STATUS LIKE %1";
531 if (isset($tableName)) {
532 $params = array(1 => array($tableName, 'String'));
535 $params = array(1 => array('civicrm_%', 'String'));
538 $dao = CRM_Core_DAO
::executeQuery($query, $params);
541 while ($dao->fetch()) {
542 if (isset($values[$dao->$fieldName]) ||
543 // ignore import and other temp tables
544 strpos($dao->Name
, 'civicrm_import_job_') !== FALSE ||
545 strpos($dao->Name
, '_temp') !== FALSE
549 $values[$dao->$fieldName] = 1;
551 if ($maxTablesToCheck &&
552 $count >= $maxTablesToCheck
561 static function isDBMyISAM($maxTablesToCheck = 10) {
562 // show error if any of the tables, use 'MyISAM' storage engine.
563 $engines = self
::getStorageValues(NULL, $maxTablesToCheck);
564 if (array_key_exists('MyISAM', $engines)) {
571 * Checks if a constraint exists for a specified table.
573 * @param string $tableName
574 * @param string $constraint
576 * @return boolean true if constraint exists, false otherwise
579 static function checkConstraintExists($tableName, $constraint) {
580 static $show = array();
582 if (!array_key_exists($tableName, $show)) {
583 $query = "SHOW CREATE TABLE $tableName";
584 $dao = CRM_Core_DAO
::executeQuery($query);
586 if (!$dao->fetch()) {
587 CRM_Core_Error
::fatal();
591 $show[$tableName] = $dao->Create_Table
;
594 return preg_match("/\b$constraint\b/i", $show[$tableName]) ?
TRUE : FALSE;
598 * Checks if CONSTRAINT keyword exists for a specified table.
600 * @param string $tableName
602 * @return boolean true if CONSTRAINT keyword exists, false otherwise
604 static function schemaRequiresRebuilding($tables = array("civicrm_contact")) {
606 foreach($tables as $tableName){
607 if (!array_key_exists($tableName, $show)) {
608 $query = "SHOW CREATE TABLE $tableName";
609 $dao = CRM_Core_DAO
::executeQuery($query);
611 if (!$dao->fetch()) {
612 CRM_Core_Error
::fatal();
616 $show[$tableName] = $dao->Create_Table
;
619 $result = preg_match("/\bCONSTRAINT\b\s/i", $show[$tableName]) ?
TRUE : FALSE;
631 * Checks if the FK constraint name is in the format 'FK_tableName_columnName'
632 * for a specified column of a table.
634 * @param string $tableName
635 * @param string $columnName
637 * @return boolean true if in format, false otherwise
640 static function checkFKConstraintInFormat($tableName, $columnName) {
641 static $show = array();
643 if (!array_key_exists($tableName, $show)) {
644 $query = "SHOW CREATE TABLE $tableName";
645 $dao = CRM_Core_DAO
::executeQuery($query);
647 if (!$dao->fetch()) {
648 CRM_Core_Error
::fatal();
652 $show[$tableName] = $dao->Create_Table
;
654 $constraint = "`FK_{$tableName}_{$columnName}`";
655 $pattern = "/\bCONSTRAINT\b\s+%s\s+\bFOREIGN\s+KEY\b\s/i";
656 return preg_match(sprintf($pattern, $constraint),$show[$tableName]) ?
TRUE : FALSE;
660 * Check whether a specific column in a specific table has always the same value
662 * @param string $tableName
663 * @param string $columnName
664 * @param string $columnValue
666 * @return boolean true if the value is always $columnValue, false otherwise
669 static function checkFieldHasAlwaysValue($tableName, $columnName, $columnValue) {
670 $query = "SELECT * FROM $tableName WHERE $columnName != '$columnValue'";
671 $dao = CRM_Core_DAO
::executeQuery($query);
672 $result = $dao->fetch() ?
FALSE : TRUE;
678 * Check whether a specific column in a specific table is always NULL
680 * @param string $tableName
681 * @param string $columnName
683 * @return boolean true if if the value is always NULL, false otherwise
686 static function checkFieldIsAlwaysNull($tableName, $columnName) {
687 $query = "SELECT * FROM $tableName WHERE $columnName IS NOT NULL";
688 $dao = CRM_Core_DAO
::executeQuery($query);
689 $result = $dao->fetch() ?
FALSE : TRUE;
695 * Check if there is a given table in the database
697 * @param string $tableName
699 * @return boolean true if exists, else false
702 static function checkTableExists($tableName) {
707 $params = array(1 => array($tableName, 'String'));
709 $dao = CRM_Core_DAO
::executeQuery($query, $params);
710 $result = $dao->fetch() ?
TRUE : FALSE;
715 function checkVersion($version) {
720 $dbVersion = CRM_Core_DAO
::singleValueQuery($query);
721 return trim($version) == trim($dbVersion) ?
TRUE : FALSE;
725 * Given a DAO name, a column name and a column value, find the record and GET the value of another column in that record
727 * @param string $daoName Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact)
728 * @param int $searchValue Value of the column you want to search by
729 * @param string $returnColumn Name of the column you want to GET the value of
730 * @param string $searchColumn Name of the column you want to search by
731 * @param boolean $force Skip use of the cache
733 * @return string|null Value of $returnColumn in the retrieved record
737 static function getFieldValue($daoName, $searchValue, $returnColumn = 'name', $searchColumn = 'id', $force = FALSE) {
739 empty($searchValue) ||
740 trim(strtolower($searchValue)) == 'null'
742 // adding this year since developers forget to check for an id
743 // or for the 'null' (which is a bad DAO kludge)
744 // and hence we get the first value in the db
745 CRM_Core_Error
::fatal();
748 $cacheKey = "{$daoName}:{$searchValue}:{$returnColumn}:{$searchColumn}";
749 if (self
::$_dbColumnValueCache === NULL) {
750 self
::$_dbColumnValueCache = array();
753 if (!array_key_exists($cacheKey, self
::$_dbColumnValueCache) ||
$force) {
754 $object = new $daoName( );
755 $object->$searchColumn = $searchValue;
756 $object->selectAdd();
757 $object->selectAdd($returnColumn);
760 if ($object->find(TRUE)) {
761 $result = $object->$returnColumn;
765 self
::$_dbColumnValueCache[$cacheKey] = $result;
767 return self
::$_dbColumnValueCache[$cacheKey];
771 * Given a DAO name, a column name and a column value, find the record and SET the value of another column in that record
773 * @param string $daoName Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact)
774 * @param int $searchValue Value of the column you want to search by
775 * @param string $setColumn Name of the column you want to SET the value of
776 * @param string $setValue SET the setColumn to this value
777 * @param string $searchColumn Name of the column you want to search by
779 * @return boolean true if we found and updated the object, else false
783 static function setFieldValue($daoName, $searchValue, $setColumn, $setValue, $searchColumn = 'id') {
784 $object = new $daoName( );
785 $object->selectAdd();
786 $object->selectAdd("$searchColumn, $setColumn");
787 $object->$searchColumn = $searchValue;
789 if ($object->find(TRUE)) {
790 $object->$setColumn = $setValue;
791 if ($object->save()) {
802 * @param array|object $sort either array or CRM_Utils_Sort
803 * @param string $default - default sort value
805 * @return string - sortString
809 static function getSortString($sort, $default = NULL) {
810 // check if sort is of type CRM_Utils_Sort
811 if (is_a($sort, 'CRM_Utils_Sort')) {
812 return $sort->orderBy();
815 // is it an array specified as $field => $sortDirection ?
817 foreach ($sort as $k => $v) {
818 $sortString .= "$k $v,";
820 return rtrim($sortString, ',');
826 * Takes a bunch of params that are needed to match certain criteria and
827 * retrieves the relevant objects. Typically the valid params are only
828 * contact_id. We'll tweak this function to be more full featured over a period
829 * of time. This is the inverse function of create. It also stores all the retrieved
830 * values in the default array
832 * @param string $daoName name of the dao object
833 * @param array $params (reference ) an assoc array of name/value pairs
834 * @param array $defaults (reference ) an assoc array to hold the flattened values
835 * @param array $returnProperities an assoc array of fields that need to be returned, eg array( 'first_name', 'last_name')
837 * @return object an object of type referenced by daoName
841 static function commonRetrieve($daoName, &$params, &$defaults, $returnProperities = NULL) {
842 $object = new $daoName( );
843 $object->copyValues($params);
845 // return only specific fields if returnproperties are sent
846 if (!empty($returnProperities)) {
847 $object->selectAdd();
848 $object->selectAdd(implode(',', $returnProperities));
851 if ($object->find(TRUE)) {
852 self
::storeValues($object, $defaults);
859 * Delete the object records that are associated with this contact
861 * @param string $daoName name of the dao object
862 * @param int $contactId id of the contact to delete
868 static function deleteEntityContact($daoName, $contactId) {
869 $object = new $daoName( );
871 $object->entity_table
= 'civicrm_contact';
872 $object->entity_id
= $contactId;
879 * @param string $query query to be executed
881 * @return Object CRM_Core_DAO object that holds the results of the query
885 static function &executeQuery(
892 $trapException = FALSE
894 $queryStr = self
::composeQuery($query, $params, $abort);
895 //CRM_Core_Error::debug( 'q', $queryStr );
898 $dao = new CRM_Core_DAO();
901 $dao = new $daoName( );
904 if ($trapException) {
905 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
908 $result = $dao->query($queryStr, $i18nRewrite);
910 if (is_a($result, 'DB_Error')) {
915 preg_match('/^(insert|update|delete|create|drop|replace)/i', $queryStr)
917 // we typically do this for insert/update/delete stataments OR if explicitly asked to
925 * execute a query and get the single result
927 * @param string $query query to be executed
928 * @param array $params
930 * @param bool $i18nRewrite
931 * @return string|null the result of the query if any
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 (!empty($fieldsFix['prefix'])) {
1089 $fieldsToPrefix = $fieldsFix['prefix'];
1091 if (!empty($fieldsFix['suffix'])) {
1092 $fieldsToSuffix = $fieldsFix['suffix'];
1094 if (!empty($fieldsFix['replace'])) {
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);
1259 * Creates a test object, including any required objects it needs via recursion
1260 *createOnly: only create in database, do not store or return the objects (useful for perf testing)
1261 *ONLY USE FOR TESTING
1263 static function createTestObject(
1269 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
1270 // so we re-set here in case
1271 $config = CRM_Core_Config
::singleton();
1272 $config->backtrace
= TRUE;
1274 static $counter = 0;
1275 CRM_Core_DAO
::$_testEntitiesToSkip = array(
1276 'CRM_Core_DAO_Worldregion',
1277 'CRM_Core_DAO_StateProvince',
1278 'CRM_Core_DAO_Country',
1279 'CRM_Core_DAO_Domain',
1282 for ($i = 0; $i < $numObjects; ++
$i) {
1285 $object = new $daoName();
1287 $fields = &$object->fields();
1288 foreach ($fields as $name => $value) {
1289 $dbName = $value['name'];
1290 if($dbName == 'contact_sub_type' && empty($params['contact_sub_type'])){
1291 //coming up with a rule to set this is too complex let's not set it
1294 $FKClassName = CRM_Utils_Array
::value('FKClassName', $value);
1295 $required = CRM_Utils_Array
::value('required', $value);
1296 if (CRM_Utils_Array
::value($dbName, $params) !== NULL && !is_array($params[$dbName])) {
1297 $object->$dbName = $params[$dbName];
1300 elseif ($dbName != 'id') {
1301 if ($FKClassName != NULL) {
1302 //skip the FK if it is not required
1303 // if it's contact id we should create even if not required
1304 // we'll have a go @ fetching first though
1305 // we WILL create campaigns though for so tests with a campaign pseudoconstant will complete
1306 if($FKClassName === 'CRM_Campaign_DAO_Campaign' && $daoName != $FKClassName) {
1309 if (!$required && $dbName != 'contact_id') {
1310 $fkDAO = new $FKClassName;
1311 if($fkDAO->find(TRUE)){
1312 $object->$dbName = $fkDAO->id
;
1317 if(in_array($FKClassName, CRM_Core_DAO
::$_testEntitiesToSkip)){
1318 $depObject = new $FKClassName();
1319 $depObject->find(TRUE);
1320 } elseif ($daoName == 'CRM_Member_DAO_MembershipType' && $name == 'member_of_contact_id') {
1321 // FIXME: the fields() metadata is not specific enough
1322 $depObject = CRM_Core_DAO
::createTestObject($FKClassName, array('contact_type' => 'Organization'));
1324 //if it is required we need to generate the dependency object first
1325 $depObject = CRM_Core_DAO
::createTestObject($FKClassName, CRM_Utils_Array
::value($dbName, $params, 1));
1327 $object->$dbName = $depObject->id
;
1332 // Pick an option value if needed
1333 if ($value['type'] !== CRM_Utils_Type
::T_BOOLEAN
) {
1334 $options = $daoName::buildOptions($dbName, 'create');
1336 $object->$dbName = key($options);
1341 switch ($value['type']) {
1342 case CRM_Utils_Type
::T_INT
:
1343 case CRM_Utils_Type
::T_FLOAT
:
1344 case CRM_Utils_Type
::T_MONEY
:
1345 if (isset($value['precision'])) {
1346 // $object->$dbName = CRM_Utils_Number::createRandomDecimal($value['precision']);
1347 $object->$dbName = CRM_Utils_Number
::createTruncatedDecimal($counter, $value['precision']);
1349 $object->$dbName = $counter;
1353 case CRM_Utils_Type
::T_BOOLEAN
:
1354 if (isset($value['default'])) {
1355 $object->$dbName = $value['default'];
1357 elseif ($value['name'] == 'is_deleted' ||
$value['name'] == 'is_test') {
1358 $object->$dbName = 0;
1361 $object->$dbName = 1;
1365 case CRM_Utils_Type
::T_DATE
:
1366 case CRM_Utils_Type
::T_TIMESTAMP
:
1367 case CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
:
1368 $object->$dbName = '19700101';
1369 if($dbName == 'end_date') {
1370 // put this in the future
1371 $object->$dbName = '20200101';
1375 case CRM_Utils_Type
::T_TIME
:
1376 CRM_Core_Error
::fatal('T_TIME shouldnt be used.');
1377 //$object->$dbName='000000';
1379 case CRM_Utils_Type
::T_CCNUM
:
1380 $object->$dbName = '4111 1111 1111 1111';
1383 case CRM_Utils_Type
::T_URL
:
1384 $object->$dbName = 'http://www.civicrm.org';
1387 case CRM_Utils_Type
::T_STRING
:
1388 case CRM_Utils_Type
::T_BLOB
:
1389 case CRM_Utils_Type
::T_MEDIUMBLOB
:
1390 case CRM_Utils_Type
::T_TEXT
:
1391 case CRM_Utils_Type
::T_LONGTEXT
:
1392 case CRM_Utils_Type
::T_EMAIL
:
1394 // WAS: if (isset($value['enumValues'])) {
1395 // TODO: see if this works with all pseudoconstants
1396 if (isset($value['pseudoconstant'], $value['pseudoconstant']['callback'])) {
1397 if (isset($value['default'])) {
1398 $object->$dbName = $value['default'];
1401 $options = CRM_Core_PseudoConstant
::get($daoName, $name);
1402 if (is_array($options)) {
1403 $object->$dbName = $options[0];
1406 $defaultValues = explode(',', $options);
1407 $object->$dbName = $defaultValues[0];
1412 $object->$dbName = $dbName . '_' . $counter;
1413 $maxlength = CRM_Utils_Array
::value('maxlength', $value);
1414 if ($maxlength > 0 && strlen($object->$dbName) > $maxlength) {
1415 $object->$dbName = substr($object->$dbName, 0, $value['maxlength']);
1425 $objects[$i] = $object;
1428 else unset($object);
1436 elseif ($numObjects == 1) { return $objects[0];}
1437 else return $objects;
1441 * deletes the this object plus any dependent objects that are associated with it
1442 * ONLY USE FOR TESTING
1444 static function deleteTestObjects($daoName, $params = array(
1446 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
1447 // so we re-set here in case
1448 $config = CRM_Core_Config
::singleton();
1449 $config->backtrace
= TRUE;
1451 $object = new $daoName();
1452 $object->id
= CRM_Utils_Array
::value('id', $params);
1454 $deletions = array(); // array(array(0 => $daoName, 1 => $daoParams))
1455 if ($object->find(TRUE)) {
1457 $fields = &$object->fields();
1458 foreach ($fields as $name => $value) {
1460 $dbName = $value['name'];
1462 $FKClassName = CRM_Utils_Array
::value('FKClassName', $value);
1463 $required = CRM_Utils_Array
::value('required', $value);
1464 if ($FKClassName != NULL
1466 && !in_array($FKClassName, CRM_Core_DAO
::$_testEntitiesToSkip)
1467 && ($required ||
$dbName == 'contact_id')) {
1468 $deletions[] = array($FKClassName, array('id' => $object->$dbName)); // x
1475 foreach ($deletions as $deletion) {
1476 CRM_Core_DAO
::deleteTestObjects($deletion[0], $deletion[1]);
1480 static function createTempTableName($prefix = 'civicrm', $addRandomString = TRUE, $string = NULL) {
1481 $tableName = $prefix . "_temp";
1483 if ($addRandomString) {
1485 $tableName .= "_" . $string;
1488 $tableName .= "_" . md5(uniqid('', TRUE));
1494 static function checkTriggerViewPermission($view = TRUE, $trigger = TRUE) {
1495 // test for create view and trigger permissions and if allowed, add the option to go multilingual
1497 // I'm not sure why we use the getStaticProperty for an error, rather than checking for DB_Error
1498 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
1499 $dao = new CRM_Core_DAO();
1501 $dao->query('CREATE OR REPLACE VIEW civicrm_domain_view AS SELECT * FROM civicrm_domain');
1502 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
1508 $result = $dao->query('CREATE TRIGGER civicrm_domain_trigger BEFORE INSERT ON civicrm_domain FOR EACH ROW BEGIN END');
1509 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError') ||
is_a($result, 'DB_Error')) {
1511 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1516 $dao->query('DROP TRIGGER IF EXISTS civicrm_domain_trigger');
1517 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
1519 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1526 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1527 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
1535 static function debugPrint($message = NULL, $printDAO = TRUE) {
1536 CRM_Utils_System
::xMemory("{$message}: ");
1539 global $_DB_DATAOBJECT;
1541 foreach (array_keys($_DB_DATAOBJECT['RESULTS']) as $id) {
1542 $q[] = $_DB_DATAOBJECT['RESULTS'][$id]->query
;
1544 CRM_Core_Error
::debug('_DB_DATAOBJECT', $q);
1549 * Build a list of triggers via hook and add them to (err, reconcile them
1550 * with) the database.
1552 * @param $tableName string the specific table requiring a rebuild; or NULL to rebuild all tables
1555 static function triggerRebuild($tableName = NULL, $force = FALSE) {
1558 $logging = new CRM_Logging_Schema
;
1559 $logging->triggerInfo($info, $tableName, $force);
1561 CRM_Core_I18n_Schema
::triggerInfo($info, $tableName);
1562 CRM_Contact_BAO_Contact
::triggerInfo($info, $tableName);
1564 CRM_Utils_Hook
::triggerInfo($info, $tableName);
1566 // drop all existing triggers on all tables
1567 $logging->dropTriggers($tableName);
1569 // now create the set of new triggers
1570 self
::createTriggers($info);
1574 * Because sql functions are sometimes lost, esp during db migration, we check here to avoid numerous support requests
1575 * @see http://issues.civicrm.org/jira/browse/CRM-13822
1576 * TODO: Alternative solutions might be
1577 * * Stop using functions and find another way to strip numeric characters from phones
1578 * * Give better error messages (currently a missing fn fatals with "unknown error")
1580 static function checkSqlFunctionsExist() {
1581 if (!self
::$_checkedSqlFunctionsExist) {
1582 self
::$_checkedSqlFunctionsExist = TRUE;
1583 $dao = CRM_Core_DAO
::executeQuery("SHOW function status WHERE db = database() AND name = 'civicrm_strip_non_numeric'");
1584 if (!$dao->fetch()) {
1585 self
::triggerRebuild();
1591 * Wrapper function to drop triggers
1593 * @param $tableName string the specific table requiring a rebuild; or NULL to rebuild all tables
1595 static function dropTriggers($tableName = NULL) {
1598 $logging = new CRM_Logging_Schema
;
1599 $logging->triggerInfo($info, $tableName);
1601 // drop all existing triggers on all tables
1602 $logging->dropTriggers($tableName);
1606 * @param $info array per hook_civicrm_triggerInfo
1607 * @param $onlyTableName string the specific table requiring a rebuild; or NULL to rebuild all tables
1609 static function createTriggers(&$info, $onlyTableName = NULL) {
1610 // Validate info array, should probably raise errors?
1611 if (is_array($info) == FALSE) {
1615 $triggers = array();
1617 // now enumerate the tables and the events and collect the same set in a different format
1618 foreach ($info as $value) {
1620 // clean the incoming data, skip malformed entries
1621 // TODO: malformed entries should raise errors or get logged.
1622 if (isset($value['table']) == FALSE ||
1623 isset($value['event']) == FALSE ||
1624 isset($value['when']) == FALSE ||
1625 isset($value['sql']) == FALSE
1630 if (is_string($value['table']) == TRUE) {
1631 $tables = array($value['table']);
1634 $tables = $value['table'];
1637 if (is_string($value['event']) == TRUE) {
1638 $events = array(strtolower($value['event']));
1641 $events = array_map('strtolower', $value['event']);
1644 $whenName = strtolower($value['when']);
1646 foreach ($tables as $tableName) {
1647 if (!isset($triggers[$tableName])) {
1648 $triggers[$tableName] = array();
1651 foreach ($events as $eventName) {
1652 $template_params = array('{tableName}', '{eventName}');
1653 $template_values = array($tableName, $eventName);
1655 $sql = str_replace($template_params,
1659 $variables = str_replace($template_params,
1661 CRM_Utils_Array
::value('variables', $value)
1664 if (!isset($triggers[$tableName][$eventName])) {
1665 $triggers[$tableName][$eventName] = array();
1668 if (!isset($triggers[$tableName][$eventName][$whenName])) {
1669 // We're leaving out cursors, conditions, and handlers for now
1670 // they are kind of dangerous in this context anyway
1671 // better off putting them in stored procedures
1672 $triggers[$tableName][$eventName][$whenName] = array(
1673 'variables' => array(),
1679 $triggers[$tableName][$eventName][$whenName]['variables'][] = $variables;
1682 $triggers[$tableName][$eventName][$whenName]['sql'][] = $sql;
1687 // now spit out the sql
1688 foreach ($triggers as $tableName => $tables) {
1689 if ($onlyTableName != NULL && $onlyTableName != $tableName) {
1692 foreach ($tables as $eventName => $events) {
1693 foreach ($events as $whenName => $parts) {
1694 $varString = implode("\n", $parts['variables']);
1695 $sqlString = implode("\n", $parts['sql']);
1696 $validName = CRM_Core_DAO
::shortenSQLName($tableName, 48, TRUE);
1697 $triggerName = "{$validName}_{$whenName}_{$eventName}";
1698 $triggerSQL = "CREATE TRIGGER $triggerName $whenName $eventName ON $tableName FOR EACH ROW BEGIN $varString $sqlString END";
1700 CRM_Core_DAO
::executeQuery("DROP TRIGGER IF EXISTS $triggerName");
1701 CRM_Core_DAO
::executeQuery(
1715 * Find all records which refer to this entity.
1717 * @return array of objects referencing this
1719 function findReferences() {
1720 $links = self
::getReferencesToTable(static::getTableName());
1722 $occurrences = array();
1723 foreach ($links as $refSpec) {
1724 $refColumn = $refSpec->getReferenceKey();
1725 $targetColumn = $refSpec->getTargetKey();
1726 $params = array(1 => array($this->$targetColumn, 'String'));
1729 FROM {$refSpec->getReferenceTable()}
1730 WHERE {$refColumn} = %1
1732 if ($refSpec->isGeneric()) {
1733 $params[2] = array(static::getTableName(), 'String');
1735 AND {$refSpec->getTypeColumn()} = %2
1738 $daoName = CRM_Core_DAO_AllCoreTables
::getClassForTable($refSpec->getReferenceTable());
1739 $result = self
::executeQuery($sql, $params, TRUE, $daoName);
1740 while ($result->fetch()) {
1741 $obj = new $daoName();
1742 $obj->id
= $result->id
;
1743 $occurrences[] = $obj;
1747 return $occurrences;
1751 * List all tables which have hard foreign keys to this table.
1753 * For now, this returns a description of every entity_id/entity_table
1755 * TODO: filter dynamic entity references on the $tableName, based on
1756 * schema metadata in dynamicForeignKey which enumerates a restricted
1757 * set of possible entity_table's.
1759 * @param string $tableName table referred to
1761 * @return array structure of table and column, listing every table with a
1762 * foreign key reference to $tableName, and the column where the key appears.
1764 static function getReferencesToTable($tableName) {
1765 $refsFound = array();
1766 foreach (CRM_Core_DAO_AllCoreTables
::getClasses() as $daoClassName) {
1767 $links = $daoClassName::getReferenceColumns();
1768 $daoTableName = $daoClassName::getTableName();
1770 foreach ($links as $refSpec) {
1771 if ($refSpec->getTargetTable() === $tableName
1772 or $refSpec->isGeneric()
1774 $refsFound[] = $refSpec;
1782 * Lookup the value of a MySQL global configuration variable.
1784 * @param string $name e.g. "thread_stack"
1785 * @param mixed $default
1788 public static function getGlobalSetting($name, $default = NULL) {
1789 // Alternatively, SELECT @@GLOBAL.thread_stack, but
1790 // that has been reported to fail under MySQL 5.0 for OS X
1791 $escapedName = self
::escapeString($name);
1792 $dao = CRM_Core_DAO
::executeQuery("SHOW VARIABLES LIKE '$escapedName'");
1793 if ($dao->fetch()) {
1802 * Get options for the called BAO object's field.
1803 * This function can be overridden by each BAO to add more logic related to context.
1804 * The overriding function will generally call the lower-level CRM_Core_PseudoConstant::get
1806 * @param string $fieldName
1807 * @param string $context: @see CRM_Core_DAO::buildOptionsContext
1808 * @param array $props: whatever is known about this bao object
1810 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
1811 // If a given bao does not override this function
1812 $baoName = get_called_class();
1813 return CRM_Core_PseudoConstant
::get($baoName, $fieldName, array(), $context);
1817 * Populate option labels for this object's fields.
1819 * @throws exception if called directly on the base class
1821 public function getOptionLabels() {
1822 $fields = $this->fields();
1823 if ($fields === NULL) {
1824 throw new Exception ('Cannot call getOptionLabels on CRM_Core_DAO');
1826 foreach ($fields as $field) {
1827 $name = CRM_Utils_Array
::value('name', $field);
1828 if ($name && isset($this->$name)) {
1829 $label = CRM_Core_PseudoConstant
::getLabel(get_class($this), $name, $this->$name);
1830 if ($label !== FALSE) {
1831 // Append 'label' onto the field name
1832 $labelName = $name . '_label';
1833 $this->$labelName = $label;
1840 * Provides documentation and validation for the buildOptions $context param
1842 * @param String $context
1844 public static function buildOptionsContext($context = NULL) {
1846 'get' => "All options are returned, even if they are disabled. Labels are translated.",
1847 'create' => "Options are filtered appropriately for the object being created/updated. Labels are translated.",
1848 'search' => "Searchable options are returned. Labels are translated.",
1849 'validate' => "All options are returned, even if they are disabled. Machine names are used in place of labels.",
1851 // Validation: enforce uniformity of this param
1852 if ($context !== NULL && !isset($contexts[$context])) {
1853 throw new Exception("'$context' is not a valid context for buildOptions.");
1860 * @return bool|array
1862 function getFieldSpec($fieldName) {
1863 $fields = $this->fields();
1864 $fieldKeys = $this->fieldKeys();
1866 // Support "unique names" as well as sql names
1867 $fieldKey = $fieldName;
1868 if (empty($fields[$fieldKey])) {
1869 $fieldKey = CRM_Utils_Array
::value($fieldName, $fieldKeys);
1871 // If neither worked then this field doesn't exist. Return false.
1872 if (empty($fields[$fieldKey])) {
1875 return $fields[$fieldKey];
1879 * SQL version of api function to assign filters to the DAO based on the syntax
1880 * $field => array('IN' => array(4,6,9))
1882 * $field => array('LIKE' => array('%me%))
1885 * @param $fieldname string name of fields
1886 * @param $filter array filter to be applied indexed by operator
1887 * @param $type String type of field (not actually used - nor in api @todo )
1888 * @param $alias String alternative field name ('as') @todo- not actually used
1889 * @param bool $returnSanitisedArray return a sanitised array instead of a clause
1890 * this is primarily so we can add filters @ the api level to the Query object based fields
1891 * @todo a better solutution would be for the query object to apply these filters based on the
1892 * api supported format (but we don't want to risk breakage in alpha stage & query class is scary
1893 * @todo @time of writing only IN & NOT IN are supported for the array style syntax (as test is
1894 * required to extend further & it may be the comments per above should be implemented. It may be
1895 * preferable to not double-banger the return context next refactor of this - but keeping the attention
1896 * in one place has some advantages as we try to extend this format
1898 * @return NULL|string|array a string is returned if $returnSanitisedArray is not set, otherwise and Array or NULL
1899 * depending on whether it is supported as yet
1901 public static function createSQLFilter($fieldName, $filter, $type, $alias = NULL, $returnSanitisedArray = FALSE) {
1902 // http://issues.civicrm.org/jira/browse/CRM-9150 - stick with 'simple' operators for now
1903 // support for other syntaxes is discussed in ticket but being put off for now
1904 foreach ($filter as $operator => $criteria) {
1905 if (in_array($operator, self
::acceptedSQLOperators())) {
1906 switch ($operator) {
1910 if(!$returnSanitisedArray) {
1911 return (sprintf('%s %s', $fieldName, $operator));
1914 return NULL; // not yet implemented (tests required to implement)
1918 // ternary operators
1921 if (empty($criteria[0]) ||
empty($criteria[1])) {
1922 throw new Exception("invalid criteria for $operator");
1924 if(!$returnSanitisedArray) {
1925 return (sprintf('%s ' . $operator . ' "%s" AND "%s"', $fieldName, CRM_Core_DAO
::escapeString($criteria[0]), CRM_Core_DAO
::escapeString($criteria[1])));
1928 return NULL; // not yet implemented (tests required to implement)
1935 if (empty($criteria)) {
1936 throw new Exception("invalid criteria for $operator");
1938 $escapedCriteria = array_map(array(
1942 if(!$returnSanitisedArray) {
1943 return (sprintf('%s %s ("%s")', $fieldName, $operator, implode('", "', $escapedCriteria)));
1945 return $escapedCriteria;
1951 if(!$returnSanitisedArray) {
1952 return(sprintf('%s %s "%s"', $fieldName, $operator, CRM_Core_DAO
::escapeString($criteria)));
1955 return NULL; // not yet implemented (tests required to implement)
1963 * @see http://issues.civicrm.org/jira/browse/CRM-9150
1964 * support for other syntaxes is discussed in ticket but being put off for now
1967 public static function acceptedSQLOperators() {
1968 return array('=', '<=', '>=', '>', '<', 'LIKE', "<>", "!=", "NOT LIKE", 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN');
1972 * SQL has a limit of 64 characters on various names:
1973 * table name, trigger name, column name ...
1975 * For custom groups and fields we generated names from user entered input
1976 * which can be longer than this length, this function helps with creating
1977 * strings that meet various criteria.
1979 * @param string $string - the string to be shortened
1980 * @param int $length - the max length of the string
1982 public static function shortenSQLName($string, $length = 60, $makeRandom = FALSE) {
1983 // early return for strings that meet the requirements
1984 if (strlen($string) <= $length) {
1988 // easy return for calls that dont need a randomized uniq string
1989 if (! $makeRandom) {
1990 return substr($string, 0, $length);
1993 // the string is longer than the length and we need a uniq string
1994 // for the same tablename we need the same uniq string everytime
1995 // hence we use md5 on the string, which is not random
1996 // we'll append 8 characters to the end of the tableName
1997 $md5string = substr(md5($string), 0, 8);
1998 return substr($string, 0, $length - 8) . "_{$md5string}";
2001 function setApiFilter(&$params) {}