public function tearDown() { global $civicrm_setting; $civicrm_setting = $this->origSetting; CRM_Utils_Cache::singleton()->flush(); parent::tearDown(); }
/** * Create civicrm settings. This is the same as add but it clears the cache and * reloads the config object * * @param array $params * Associated array of civicrm variables. * * @return void */ public static function create($params) { self::add($params); $cache = CRM_Utils_Cache::singleton(); $cache->delete('CRM_Core_Config'); $cache->delete('CRM_Core_Config' . CRM_Core_Config::domainID()); $config = CRM_Core_Config::singleton(TRUE, TRUE); }
/** * @param bool $fresh * @return CRM_Cxn_CiviCxnHttp */ public static function singleton($fresh = FALSE) { if (self::$singleton === NULL || $fresh) { $cache = CRM_Utils_Cache::create(array('name' => 'CiviCxnHttp', 'type' => Civi::settings()->get('debug_enabled') ? 'ArrayCache' : array('SqlGroup', 'ArrayCache'), 'prefetch' => FALSE)); self::$singleton = new CRM_Cxn_CiviCxnHttp($cache); } return self::$singleton; }
static function setCache($values, $group, $componentID = NULL, $contactID = NULL) { if (!isset(self::$_cache)) { self::$_cache = array(); } $cacheKey = "CRM_Setting_{$group}_{$componentID}_{$contactID}"; self::$_cache[$cacheKey] = $values; $globalCache = CRM_Utils_Cache::singleton(); $result = $globalCache->set($cacheKey, $values); return $cacheKey; }
/** * singleton function used to manage this object * * @param string $host the memcached server host * @param int $port the memcached server port * @param int $timeout the default timeout * * @return object * @static * */ static function &singleton($host = 'localhost', $port = 11211, $timeout = 3600) { if (self::$_singleton === null) { if (defined('CIVICRM_USE_MEMCACHE') && CIVICRM_USE_MEMCACHE) { require_once 'CRM/Utils/Cache/Memcache.php'; self::$_singleton = new CRM_Utils_Cache_Memcache($host, $port, $timeout); } else { self::$_singleton = new CRM_Utils_Cache(); } } return self::$_singleton; }
public function testSetGetItem() { $originalValue = array('abc' => 'def'); CRM_Core_BAO_Cache::setItem($originalValue, __CLASS__, 'testSetGetItem'); $return_1 = CRM_Core_BAO_Cache::getItem(__CLASS__, 'testSetGetItem'); $this->assertEquals($originalValue, $return_1); // Wipe out any in-memory copies of the cache. Check to see if the SQL // read is correct. CRM_Core_BAO_Cache::$_cache = NULL; CRM_Utils_Cache::$_singleton = NULL; $return_2 = CRM_Core_BAO_Cache::getItem(__CLASS__, 'testSetGetItem'); $this->assertEquals($originalValue, $return_2); }
/** * Find the activity type ID for petitions. * * @return int * The activity type ID. */ public static function getPetitionActivityType() { $cache = CRM_Utils_Cache::singleton(); $petitionActivityType = $cache->get('petitionemail_petitionActivityType'); if (empty($petitionActivityType)) { try { $petitionTypeParams = array('name' => "activity_type", 'api.OptionValue.getsingle' => array('option_group_id' => '$value.id', 'name' => "Petition", 'options' => array('limit' => 1)), 'options' => array('limit' => 1)); $petitionTypeInfo = civicrm_api3('OptionGroup', 'getsingle', $petitionTypeParams); } catch (CiviCRM_API3_Exception $e) { $error = $e->getMessage(); CRM_Core_Error::debug_log_message(t('API Error: %1', array(1 => $error, 'domain' => 'com.aghstrategies.petitionemail'))); } if (empty($petitionTypeInfo['api.OptionValue.getsingle']['value'])) { return; } else { $petitionActivityType = $petitionTypeInfo['api.OptionValue.getsingle']['value']; $cache->set('petitionemail_petitionActivityType', $petitionActivityType); } } return $petitionActivityType; }
/** * Singleton function used to manage this object. * * @return CRM_Utils_Cache_Interface */ public static function &singleton() { if (self::$_singleton === NULL) { $className = 'ArrayCache'; // default to ArrayCache for now // Maintain backward compatibility for now. // Setting CIVICRM_USE_MEMCACHE or CIVICRM_USE_ARRAYCACHE will // override the CIVICRM_DB_CACHE_CLASS setting. // Going forward, CIVICRM_USE_xxxCACHE should be deprecated. if (defined('CIVICRM_USE_MEMCACHE') && CIVICRM_USE_MEMCACHE) { $className = 'Memcache'; } elseif (defined('CIVICRM_USE_ARRAYCACHE') && CIVICRM_USE_ARRAYCACHE) { $className = 'ArrayCache'; } elseif (defined('CIVICRM_DB_CACHE_CLASS') && CIVICRM_DB_CACHE_CLASS) { $className = CIVICRM_DB_CACHE_CLASS; } // a generic method for utilizing any of the available db caches. $dbCacheClass = 'CRM_Utils_Cache_' . $className; $settings = self::getCacheSettings($className); self::$_singleton = new $dbCacheClass($settings); } return self::$_singleton; }
/** * DEPRECATED generic populate method * All pseudoconstant functions that use this method are also deprecated. * * The static array $var is populated from the db * using the <b>$name DAO</b>. * * Note: any database errors will be trapped by the DAO. * * @param array $var the associative array we will fill * @param string $name the name of the DAO * @param boolean $all get all objects. default is to get only active ones. * @param string $retrieve the field that we are interested in (normally name, differs in some objects) * @param string $filter the field that we want to filter the result set with * @param string $condition the condition that gets passed to the final query as the WHERE clause * * @return void * @access public * @static */ public static function populate(&$var, $name, $all = FALSE, $retrieve = 'name', $filter = 'is_active', $condition = NULL, $orderby = NULL, $key = 'id', $force = NULL) { $cacheKey = "CRM_PC_{$name}_{$all}_{$key}_{$retrieve}_{$filter}_{$condition}_{$orderby}"; $cache = CRM_Utils_Cache::singleton(); $var = $cache->get($cacheKey); if ($var && empty($force)) { return $var; } $object = new $name(); $object->selectAdd(); $object->selectAdd("{$key}, {$retrieve}"); if ($condition) { $object->whereAdd($condition); } if (!$orderby) { $object->orderBy($retrieve); } else { $object->orderBy($orderby); } if (!$all) { $object->{$filter} = 1; } $object->find(); $var = array(); while ($object->fetch()) { $var[$object->{$key}] = $object->{$retrieve}; } $cache->set($cacheKey, $var); }
/** * Get the database table name and column name for a custom field. * * @param int $fieldID * The fieldID of the custom field. * @param bool $force * Force the sql to be run again (primarily used for tests). * * @return array * fatal is fieldID does not exists, else array of tableName, columnName */ public static function getTableColumnGroup($fieldID, $force = FALSE) { $cacheKey = "CRM_Core_DAO_CustomField_CustomGroup_TableColumn_{$fieldID}"; $cache = CRM_Utils_Cache::singleton(); $fieldValues = $cache->get($cacheKey); if (empty($fieldValues) || $force) { $query = "\nSELECT cg.table_name, cf.column_name, cg.id\nFROM civicrm_custom_group cg,\n civicrm_custom_field cf\nWHERE cf.custom_group_id = cg.id\nAND cf.id = %1"; $params = array(1 => array($fieldID, 'Integer')); $dao = CRM_Core_DAO::executeQuery($query, $params); if (!$dao->fetch()) { CRM_Core_Error::fatal(); } $dao->free(); $fieldValues = array($dao->table_name, $dao->column_name, $dao->id); $cache->set($cacheKey, $fieldValues); } return $fieldValues; }
/** * Find the site's default "from" address. * * @return string * The default "from" name and address. */ public function getDefaultFromAddress() { if (empty($this->defaultFromAddress)) { $cache = CRM_Utils_Cache::singleton(); $this->defaultFromAddress = $cache->get('petitionemail_defaultFromAddress'); } if (empty($this->defaultFromAddress)) { try { $defaultMailParams = array('name' => "from_email_address", 'options' => array('limit' => 1), 'api.OptionValue.getsingle' => array('is_default' => 1, 'options' => array('limit' => 1))); $defaultMail = civicrm_api3('OptionGroup', 'getsingle', $defaultMailParams); if (empty($defaultMail['api.OptionValue.getsingle']['label']) || $defaultMail['api.OptionValue.getsingle']['label'] == $defaultMail['api.OptionValue.getsingle']['name']) { // No site email. // TODO: leave some kind of message with explanation. return NULL; } $this->defaultFromAddress = $defaultMail['api.OptionValue.getsingle']['label']; $cache->set('petitionemail_defaultFromAddress', $this->defaultFromAddress); } catch (CiviCRM_API3_Exception $e) { $error = $e->getMessage(); CRM_Core_Error::debug_log_message(t('API Error: %1', array(1 => $error, 'domain' => 'com.aghstrategies.petitionemail'))); } } return $this->defaultFromAddress; }
/** * populate the object from the database. generic populate * method * * The static array $var is populated from the db * using the <b>$name DAO</b>. * * Note: any database errors will be trapped by the DAO. * * @param array $var the associative array we will fill * @param string $name the name of the DAO * @param boolean $all get all objects. default is to get only active ones. * @param string $retrieve the field that we are interested in (normally name, differs in some objects) * @param string $filter the field that we want to filter the result set with * @param string $condition the condition that gets passed to the final query as the WHERE clause * * @return void * @access public * @static */ public static function populate(&$var, $name, $all = false, $retrieve = 'name', $filter = 'is_active', $condition = null, $orderby = null, $key = 'id') { $cacheKey = "CRM_PC_{$name}_{$all}_{$key}_{$retrieve}_{$filter}_{$condition}_{$orderby}"; $cache =& CRM_Utils_Cache::singleton(); $var = $cache->get($cacheKey); if ($var) { return $var; } require_once str_replace('_', DIRECTORY_SEPARATOR, $name) . ".php"; eval('$object = new ' . $name . '( );'); $object->selectAdd(); $object->selectAdd("{$key}, {$retrieve}"); if ($condition) { $object->whereAdd($condition); } if (!$orderby) { $object->orderBy($retrieve); } else { $object->orderBy($orderby); } if (!$all) { $object->{$filter} = 1; } $object->find(); $var = array(); while ($object->fetch()) { $var[$object->{$key}] = $object->{$retrieve}; } $cache->set($cacheKey, $var); }
/** * @param $type * @param null $contactID * @param string $tableName * @param null $allGroups * @param null $includedGroups * * @return array */ public static function group($type, $contactID = NULL, $tableName = 'civicrm_saved_search', $allGroups = NULL, $includedGroups = NULL) { $acls = CRM_ACL_BAO_Cache::build($contactID); $ids = array(); if (!empty($acls)) { $aclKeys = array_keys($acls); $aclKeys = implode(',', $aclKeys); $cacheKey = "{$tableName}-{$aclKeys}"; $cache = CRM_Utils_Cache::singleton(); $ids = $cache->get($cacheKey); if (!$ids) { $query = "\nSELECT a.operation, a.object_id\n FROM civicrm_acl_cache c, civicrm_acl a\n WHERE c.acl_id = a.id\n AND a.is_active = 1\n AND a.object_table = %1\n AND a.id IN ( {$aclKeys} )\nGROUP BY a.operation,a.object_id\nORDER BY a.object_id\n"; $params = array(1 => array($tableName, 'String')); $dao = CRM_Core_DAO::executeQuery($query, $params); while ($dao->fetch()) { if ($dao->object_id) { if (self::matchType($type, $dao->operation)) { $ids[] = $dao->object_id; } } else { // this user has got the permission for all objects of this type // check if the type matches if (self::matchType($type, $dao->operation)) { foreach ($allGroups as $id => $dontCare) { $ids[] = $id; } } break; } } $cache->set($cacheKey, $ids); } } if (empty($ids) && !empty($includedGroups) && is_array($includedGroups)) { $ids = $includedGroups; } CRM_Utils_Hook::aclGroup($type, $contactID, $tableName, $allGroups, $ids); return $ids; }
/** * Get the values of all option values given an option group ID. Store in system cache * Does not take any filtering arguments. The object is to avoid hitting the DB and retrieve * from memory * * @param int $optionGroupID * The option group for which we want the values from. * * @return array * an array of array of values for this option group */ public static function getOptionValuesArray($optionGroupID) { // check if we can get the field values from the system cache $cacheKey = "CRM_Core_BAO_OptionValue_OptionGroupID_{$optionGroupID}"; $cache = CRM_Utils_Cache::singleton(); $optionValues = $cache->get($cacheKey); if (empty($optionValues)) { $dao = new CRM_Core_DAO_OptionValue(); $dao->option_group_id = $optionGroupID; $dao->orderBy('weight ASC, label ASC'); $dao->find(); $optionValues = array(); while ($dao->fetch()) { $optionValues[$dao->id] = array(); CRM_Core_DAO::storeValues($dao, $optionValues[$dao->id]); } $cache->set($cacheKey, $optionValues); } return $optionValues; }
public function commonProcess(&$params) { require_once "CRM/Core/BAO/Setting.php"; CRM_Core_BAO_Setting::add($params); // also delete the CRM_Core_Config key from the database $cache =& CRM_Utils_Cache::singleton(); $cache->delete('CRM_Core_Config'); // save autocomplete search options if (CRM_Utils_Array::value('autocompleteContactSearch', $params)) { $config =& new CRM_Core_DAO_Preferences(); $config->domain_id = CRM_Core_Config::domainID(); $config->find(true); $config->contact_autocomplete_options = CRM_Core_BAO_CustomOption::VALUE_SEPERATOR . implode(CRM_Core_BAO_CustomOption::VALUE_SEPERATOR, array_keys($params['autocompleteContactSearch'])) . CRM_Core_BAO_CustomOption::VALUE_SEPERATOR; $config->save(); } CRM_Core_Session::setStatus(ts('Your changes have been saved.')); }
/** * @param array $params * * @return mixed */ public function membershipTypeCreate($params = array()) { CRM_Member_PseudoConstant::flush('membershipType'); CRM_Core_Config::clearDBCache(); $this->setupIDs['contact'] = $memberOfOrganization = $this->organizationCreate(); $params = array_merge(array('name' => 'General', 'duration_unit' => 'year', 'duration_interval' => 1, 'period_type' => 'rolling', 'member_of_contact_id' => $memberOfOrganization, 'domain_id' => 1, 'financial_type_id' => 2, 'is_active' => 1, 'sequential' => 1, 'visibility' => 'Public'), $params); $result = $this->callAPISuccess('MembershipType', 'Create', $params); CRM_Member_PseudoConstant::flush('membershipType'); CRM_Utils_Cache::singleton()->flush(); return $result['id']; }
/** * Reset the memory cache, typically memcached */ static function flushCache($daoName = null) { // flush out all cache entries so we can reload new data // a bit aggressive, but livable for now require_once 'CRM/Utils/Cache.php'; $cache =& CRM_Utils_Cache::singleton(); $cache->flush(); }
/** * @return CRM_Utils_Cache_Interface */ public function getCache() { if ($this->cache === NULL) { $cacheGroup = md5(serialize(array('ext', $this->parameters))); // Extension system starts before container. Manage our own cache. $this->cache = CRM_Utils_Cache::create(array('name' => $cacheGroup, 'type' => array('*memory*', 'SqlGroup', 'ArrayCache'), 'prefetch' => TRUE)); } return $this->cache; }
/** * Get all payment processors as an array of objects. * * @param string|NULL $mode * only return this mode - test|live or NULL for all * @param bool $reset * * @throws CiviCRM_API3_Exception * @return array */ public static function getAllPaymentProcessors($mode, $reset = FALSE) { $cacheKey = 'CRM_Financial_BAO_Payment_Processor_' . ($mode ? 'test' : 'all') . '_' . CRM_Core_Config::domainID(); if (!$reset) { $processors = CRM_Utils_Cache::singleton()->get($cacheKey); if (!empty($processors)) { return $processors; } } $retrievalParameters = array('is_active' => TRUE, 'domain_id' => CRM_Core_Config::domainID(), 'options' => array('sort' => 'is_default DESC, name'), 'api.payment_processor_type.getsingle' => 1); if ($mode == 'test') { $retrievalParameters['is_test'] = 1; } elseif ($mode == 'live') { $retrievalParameters['is_test'] = 0; } $processors = civicrm_api3('payment_processor', 'get', $retrievalParameters); foreach ($processors['values'] as $processor) { $fieldsToProvide = array('user_name', 'password', 'signature', 'subject', 'is_recur'); foreach ($fieldsToProvide as $field) { // Prevent e-notices in processor classes when not configured. if (!isset($processor[$field])) { $processors['values'][$processor['id']][$field] = NULL; } } $processors['values'][$processor['id']]['payment_processor_type'] = $processor['payment_processor_type'] = $processors['values'][$processor['id']]['api.payment_processor_type.getsingle']['name']; $processors['values'][$processor['id']]['object'] = Civi\Payment\System::singleton()->getByProcessor($processor); } CRM_Utils_Cache::singleton()->set($cacheKey, $processors['values']); return $processors['values']; }
/** * Get a list of elements for select box. * Note that this used to default to using the hex(01) character - which results in an invalid character being used in form fields * which was not handled well be anything that loaded & resaved the html (outside core) * The use of this separator is now explicit in the calling functions as a step towards it's removal * * @param bool $all * @param bool $isSeparator * @param string $separator * * @return mixed */ public static function getSelectElements($all = FALSE, $isSeparator = TRUE, $separator = '__') { static $_cache = NULL; if ($_cache === NULL) { $_cache = array(); } $argString = $all ? 'CRM_CT_GSE_1' : 'CRM_CT_GSE_0'; $argString .= $isSeparator ? '_1' : '_0'; $argString .= $separator; if (!array_key_exists($argString, $_cache)) { $cache = CRM_Utils_Cache::singleton(); $_cache[$argString] = $cache->get($argString); if (!$_cache[$argString]) { $_cache[$argString] = array(); $sql = "\nSELECT c.name as child_name , c.label as child_label , c.id as child_id,\n p.name as parent_name, p.label as parent_label, p.id as parent_id\nFROM civicrm_contact_type c\nLEFT JOIN civicrm_contact_type p ON ( c.parent_id = p.id )\nWHERE ( c.name IS NOT NULL )\n"; if ($all === FALSE) { $sql .= "\nAND c.is_active = 1\nAND ( p.is_active = 1 OR p.id IS NULL )\n"; } $sql .= " ORDER BY c.id"; $values = array(); $dao = CRM_Core_DAO::executeQuery($sql); while ($dao->fetch()) { if (!empty($dao->parent_id)) { $key = $isSeparator ? $dao->parent_name . $separator . $dao->child_name : $dao->child_name; $label = "- {$dao->child_label}"; $pName = $dao->parent_name; } else { $key = $dao->child_name; $label = $dao->child_label; $pName = $dao->child_name; } if (!isset($values[$pName])) { $values[$pName] = array(); } $values[$pName][] = array('key' => $key, 'label' => $label); } $selectElements = array(); foreach ($values as $pName => $elements) { foreach ($elements as $element) { $selectElements[$element['key']] = $element['label']; } } $_cache[$argString] = $selectElements; $cache->set($argString, $_cache[$argString]); } } return $_cache[$argString]; }
/** * Get custom groups/fields data for type of entity in a tree structure representing group->field hierarchy * This may also include entity specific data values. * * An array containing all custom groups and their custom fields is returned. * * @param string $entityType * Of the contact whose contact type is needed. * @param CRM_Core_Form $deprecated * Not used. * @param int $entityID * @param int $groupID * @param array $subTypes * @param string $subName * @param bool $fromCache * @param bool $onlySubType * Only return specified subtype or return specified subtype + unrestricted fields. * @param bool $returnAll * Do not restrict by subtype at all. (The parameter feels a bit cludgey but is only used from the * api - through which it is properly tested - so can be refactored with some comfort.) * * @param bool $checkPermission * * @return array * Custom field 'tree'. * * The returned array is keyed by group id and has the custom group table fields * and a subkey 'fields' holding the specific custom fields. * If entityId is passed in the fields keys have a subkey 'customValue' which holds custom data * if set for the given entity. This is structured as an array of values with each one having the keys 'id', 'data' * * @todo - review this - It also returns an array called 'info' with tables, select, from, where keys * The reason for the info array in unclear and it could be determined from parsing the group tree after creation * With caching the performance impact would be small & the function would be cleaner */ public static function getTree($entityType, $deprecated = NULL, $entityID = NULL, $groupID = NULL, $subTypes = array(), $subName = NULL, $fromCache = TRUE, $onlySubType = NULL, $returnAll = FALSE, $checkPermission = TRUE) { if ($entityID) { $entityID = CRM_Utils_Type::escape($entityID, 'Integer'); } if (!is_array($subTypes)) { if (empty($subTypes)) { $subTypes = array(); } else { if (stristr(',', $subTypes)) { $subTypes = explode(',', $subTypes); } else { $subTypes = explode(CRM_Core_DAO::VALUE_SEPARATOR, trim($subTypes, CRM_Core_DAO::VALUE_SEPARATOR)); } } } // create a new tree $strWhere = $orderBy = ''; // using tableData to build the queryString $tableData = array('civicrm_custom_field' => array('id', 'label', 'column_name', 'data_type', 'html_type', 'default_value', 'attributes', 'is_required', 'is_view', 'help_pre', 'help_post', 'options_per_line', 'start_date_years', 'end_date_years', 'date_format', 'time_format', 'option_group_id', 'in_selector'), 'civicrm_custom_group' => array('id', 'name', 'table_name', 'title', 'help_pre', 'help_post', 'collapse_display', 'is_multiple', 'extends', 'extends_entity_column_id', 'extends_entity_column_value', 'max_multiple')); // create select $select = array(); foreach ($tableData as $tableName => $tableColumn) { foreach ($tableColumn as $columnName) { $alias = $tableName . "_" . $columnName; $select[] = "{$tableName}.{$columnName} as {$tableName}_{$columnName}"; } } $strSelect = "SELECT " . implode(', ', $select); // from, where, order by $strFrom = "\nFROM civicrm_custom_group\nLEFT JOIN civicrm_custom_field ON (civicrm_custom_field.custom_group_id = civicrm_custom_group.id)\n"; // if entity is either individual, organization or household pls get custom groups for 'contact' too. if ($entityType == "Individual" || $entityType == 'Organization' || $entityType == 'Household') { $in = "'{$entityType}', 'Contact'"; } elseif (strpos($entityType, "'") !== FALSE) { // this allows the calling function to send in multiple entity types $in = $entityType; } else { // quote it $in = "'{$entityType}'"; } if (!empty($subTypes)) { foreach ($subTypes as $key => $subType) { $subTypeClauses[] = self::whereListHas("civicrm_custom_group.extends_entity_column_value", self::validateSubTypeByEntity($entityType, $subType)); } $subTypeClause = '(' . implode(' OR ', $subTypeClauses) . ')'; if (!$onlySubType) { $subTypeClause = '(' . $subTypeClause . ' OR civicrm_custom_group.extends_entity_column_value IS NULL )'; } $strWhere = "\nWHERE civicrm_custom_group.is_active = 1\n AND civicrm_custom_field.is_active = 1\n AND civicrm_custom_group.extends IN ({$in})\n AND {$subTypeClause}\n"; if ($subName) { $strWhere .= " AND civicrm_custom_group.extends_entity_column_id = {$subName} "; } } else { $strWhere = "\nWHERE civicrm_custom_group.is_active = 1\n AND civicrm_custom_field.is_active = 1\n AND civicrm_custom_group.extends IN ({$in})\n"; if (!$returnAll) { $strWhere .= "AND civicrm_custom_group.extends_entity_column_value IS NULL"; } } $params = array(); if ($groupID > 0) { // since we want a specific group id we add it to the where clause $strWhere .= " AND civicrm_custom_group.id = %1"; $params[1] = array($groupID, 'Integer'); } elseif (!$groupID) { // since groupID is false we need to show all Inline groups $strWhere .= " AND civicrm_custom_group.style = 'Inline'"; } if ($checkPermission) { // ensure that the user has access to these custom groups $strWhere .= " AND " . CRM_Core_Permission::customGroupClause(CRM_Core_Permission::VIEW, 'civicrm_custom_group.'); } $orderBy = "\nORDER BY civicrm_custom_group.weight,\n civicrm_custom_group.title,\n civicrm_custom_field.weight,\n civicrm_custom_field.label\n"; // final query string $queryString = "{$strSelect} {$strFrom} {$strWhere} {$orderBy}"; // lets see if we can retrieve the groupTree from cache $cacheString = $queryString; if ($groupID > 0) { $cacheString .= "_{$groupID}"; } else { $cacheString .= "_Inline"; } $cacheKey = "CRM_Core_DAO_CustomGroup_Query " . md5($cacheString); $multipleFieldGroupCacheKey = "CRM_Core_DAO_CustomGroup_QueryMultipleFields " . md5($cacheString); $cache = CRM_Utils_Cache::singleton(); $tablesWithEntityData = array(); if ($fromCache) { $groupTree = $cache->get($cacheKey); $multipleFieldGroups = $cache->get($multipleFieldGroupCacheKey); } if (empty($groupTree)) { $groupTree = $multipleFieldGroups = array(); $crmDAO = CRM_Core_DAO::executeQuery($queryString, $params); $customValueTables = array(); // process records while ($crmDAO->fetch()) { // get the id's $groupID = $crmDAO->civicrm_custom_group_id; $fieldId = $crmDAO->civicrm_custom_field_id; if ($crmDAO->civicrm_custom_group_is_multiple) { $multipleFieldGroups[$groupID] = $crmDAO->civicrm_custom_group_table_name; } // create an array for groups if it does not exist if (!array_key_exists($groupID, $groupTree)) { $groupTree[$groupID] = array(); $groupTree[$groupID]['id'] = $groupID; // populate the group information foreach ($tableData['civicrm_custom_group'] as $fieldName) { $fullFieldName = "civicrm_custom_group_{$fieldName}"; if ($fieldName == 'id' || is_null($crmDAO->{$fullFieldName})) { continue; } // CRM-5507 // This is an old bit of code - per the CRM number & probably does not work reliably if // that one contact sub-type exists. if ($fieldName == 'extends_entity_column_value' && !empty($subTypes[0])) { $groupTree[$groupID]['subtype'] = self::validateSubTypeByEntity($entityType, $subType); } $groupTree[$groupID][$fieldName] = $crmDAO->{$fullFieldName}; } $groupTree[$groupID]['fields'] = array(); $customValueTables[$crmDAO->civicrm_custom_group_table_name] = array(); } // add the fields now (note - the query row will always contain a field) // we only reset this once, since multiple values come is as multiple rows if (!array_key_exists($fieldId, $groupTree[$groupID]['fields'])) { $groupTree[$groupID]['fields'][$fieldId] = array(); } $customValueTables[$crmDAO->civicrm_custom_group_table_name][$crmDAO->civicrm_custom_field_column_name] = 1; $groupTree[$groupID]['fields'][$fieldId]['id'] = $fieldId; // populate information for a custom field foreach ($tableData['civicrm_custom_field'] as $fieldName) { $fullFieldName = "civicrm_custom_field_{$fieldName}"; if ($fieldName == 'id' || is_null($crmDAO->{$fullFieldName})) { continue; } $groupTree[$groupID]['fields'][$fieldId][$fieldName] = $crmDAO->{$fullFieldName}; } } if (!empty($customValueTables)) { $groupTree['info'] = array('tables' => $customValueTables); } $cache->set($cacheKey, $groupTree); $cache->set($multipleFieldGroupCacheKey, $multipleFieldGroups); } //entitySelectClauses is an array of select clauses for custom value tables which are not multiple // and have data for the given entities. $entityMultipleSelectClauses is the same for ones with multiple $entitySingleSelectClauses = $entityMultipleSelectClauses = $groupTree['info']['select'] = array(); $singleFieldTables = array(); // now that we have all the groups and fields, lets get the values // since we need to know the table and field names // add info to groupTree if (isset($groupTree['info']) && !empty($groupTree['info']) && !empty($groupTree['info']['tables'])) { $select = $from = $where = array(); $groupTree['info']['where'] = NULL; foreach ($groupTree['info']['tables'] as $table => $fields) { $groupTree['info']['from'][] = $table; $select = array("{$table}.id as {$table}_id", "{$table}.entity_id as {$table}_entity_id"); foreach ($fields as $column => $dontCare) { $select[] = "{$table}.{$column} as {$table}_{$column}"; } $groupTree['info']['select'] = array_merge($groupTree['info']['select'], $select); if ($entityID) { $groupTree['info']['where'][] = "{$table}.entity_id = {$entityID}"; if (in_array($table, $multipleFieldGroups) && self::customGroupDataExistsForEntity($entityID, $table)) { $entityMultipleSelectClauses[$table] = $select; } else { $singleFieldTables[] = $table; $entitySingleSelectClauses = array_merge($entitySingleSelectClauses, $select); } } } if ($entityID && !empty($singleFieldTables)) { self::buildEntityTreeSingleFields($groupTree, $entityID, $entitySingleSelectClauses, $singleFieldTables); } $multipleFieldTablesWithEntityData = array_keys($entityMultipleSelectClauses); if (!empty($multipleFieldTablesWithEntityData)) { self::buildEntityTreeMultipleFields($groupTree, $entityID, $entityMultipleSelectClauses, $multipleFieldTablesWithEntityData); } } return $groupTree; }
public function __construct() { $this->cache = CRM_Utils_Cache::create(array('name' => 'hooks', 'type' => array('ArrayCache'), 'prefetch' => 1)); }
/** * Singleton function used to manage this object. * * @param $loadFromDB boolean whether to load from the database * @param $force boolean whether to force a reconstruction * * @return object * @static */ static function &singleton($loadFromDB = true, $force = false) { if (self::$_singleton === null || $force) { // first, attempt to get configuration object from cache require_once 'CRM/Utils/Cache.php'; $cache =& CRM_Utils_Cache::singleton(); self::$_singleton = $cache->get('CRM_Core_Config'); // if not in cache, fire off config construction if (!self::$_singleton) { self::$_singleton = new CRM_Core_Config(); self::$_singleton->_initialize(); //initialize variables. for gencode we cannot load from the //db since the db might not be initialized if ($loadFromDB) { self::$_singleton->_initVariables(); // retrieve and overwrite stuff from the settings file self::$_singleton->setCoreVariables(); } $cache->set('CRM_Core_Config', self::$_singleton); } else { // we retrieve the object from memcache, so we now initialize the objects self::$_singleton->_initialize(); } self::$_singleton->initialized = 1; if (isset(self::$_singleton->customPHPPathDir) && self::$_singleton->customPHPPathDir) { $include_path = self::$_singleton->customPHPPathDir . PATH_SEPARATOR . get_include_path(); set_include_path($include_path); } // set the callback at the very very end, to avoid an infinite loop // set the error callback CRM_Core_Error::setCallback(); } return self::$_singleton; }
static function &valuesByID($id, $flip = false, $grouping = false, $localize = false, $valueColumnName = 'label') { $cacheKey = "CRM_OG_ID_{$id}_{$flip}_{$grouping}_{$localize}_{$valueColumnName}"; $cache =& CRM_Utils_Cache::singleton(); $var = $cache->get($cacheKey); if ($var) { return $var; } $query = "\nSELECT v.{$valueColumnName} as {$valueColumnName} ,v.value as value, v.grouping as grouping\nFROM civicrm_option_value v,\n civicrm_option_group g\nWHERE v.option_group_id = g.id\n AND g.id = %1\n AND v.is_active = 1 \n AND g.is_active = 1 \n ORDER BY v.weight, v.label; \n"; $p = array(1 => array($id, 'Integer')); $dao =& CRM_Core_DAO::executeQuery($query, $p); $var =& self::valuesCommon($dao, $flip, $grouping, $localize, $valueColumnName); $cache->set($cacheKey, $var); return $var; }
public function commonProcess(&$params) { require_once "CRM/Core/BAO/Setting.php"; CRM_Core_BAO_Setting::add($params); // also delete the CRM_Core_Config key from the database $cache =& CRM_Utils_Cache::singleton(); $cache->delete('CRM_Core_Config'); // save autocomplete search options if (CRM_Utils_Array::value('autocompleteContactSearch', $params)) { $config =& new CRM_Core_DAO_Preferences(); $config->domain_id = CRM_Core_Config::domainID(); $config->find(true); $config->contact_autocomplete_options = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, array_keys($params['autocompleteContactSearch'])) . CRM_Core_DAO::VALUE_SEPARATOR; $config->save(); } // update time for date formats when global time is changed if (CRM_Utils_Array::value('timeInputFormat', $params)) { $query = "UPDATE civicrm_preferences_date SET time_format = " . $params['timeInputFormat'] . " \n WHERE time_format IS NOT NULL AND time_format <> ''"; CRM_Core_DAO::executeQuery($query); } CRM_Core_Session::setStatus(ts('Your changes have been saved.')); }
/** * Store an item in the DB cache. * * @param object $data * (required) A reference to the data that will be serialized and stored. * @param string $group * (required) The group name of the item. * @param string $path * (required) The path under which this item is stored. * @param int $componentID * The optional component ID (so componenets can share the same name space). */ public static function setItem(&$data, $group, $path, $componentID = NULL) { if (self::$_cache === NULL) { self::$_cache = array(); } $dao = new CRM_Core_DAO_Cache(); $dao->group_name = $group; $dao->path = $path; $dao->component_id = $componentID; // get a lock so that multiple ajax requests on the same page // dont trample on each other // CRM-11234 $lock = Civi::lockManager()->acquire("cache.{$group}_{$path}._{$componentID}"); if (!$lock->isAcquired()) { CRM_Core_Error::fatal(); } $dao->find(TRUE); $dao->data = serialize($data); $dao->created_date = date('YmdHis'); $dao->save(FALSE); $lock->release(); $dao->free(); // cache coherency - refresh or remove dependent caches $argString = "CRM_CT_{$group}_{$path}_{$componentID}"; $cache = CRM_Utils_Cache::singleton(); $data = unserialize($dao->data); self::$_cache[$argString] = $data; $cache->set($argString, $data); $argString = "CRM_CT_CI_{$group}_{$componentID}"; unset(self::$_cache[$argString]); $cache->delete($argString); }
/** * Reset the various system caches and some important static variables. */ public static function flushCache() { // flush out all cache entries so we can reload new data // a bit aggressive, but livable for now $cache = CRM_Utils_Cache::singleton(); $cache->flush(); // also reset the various static memory caches // reset the memory or array cache CRM_Core_BAO_Cache::deleteGroup('contact fields', NULL, FALSE); // reset ACL cache CRM_ACL_BAO_Cache::resetCache(); // reset various static arrays used here CRM_Contact_BAO_Contact::$_importableFields = CRM_Contact_BAO_Contact::$_exportableFields = CRM_Contribute_BAO_Contribution::$_importableFields = CRM_Contribute_BAO_Contribution::$_exportableFields = CRM_Pledge_BAO_Pledge::$_exportableFields = CRM_Contribute_BAO_Query::$_contributionFields = CRM_Core_BAO_CustomField::$_importFields = CRM_Core_BAO_Cache::$_cache = CRM_Core_DAO::$_dbColumnValueCache = NULL; CRM_Core_OptionGroup::flushAll(); CRM_Utils_PseudoConstant::flushAll(); }
/** * Singleton function used to manage this object. * * @param bool $loadFromDB * whether to load from the database. * @param bool $force * whether to force a reconstruction. * * @return CRM_Core_Config */ public static function &singleton($loadFromDB = TRUE, $force = FALSE) { if (self::$_singleton === NULL || $force) { // goto a simple error handler $GLOBALS['civicrm_default_error_scope'] = CRM_Core_TemporaryErrorScope::create(array('CRM_Core_Error', 'handle')); $errorScope = CRM_Core_TemporaryErrorScope::create(array('CRM_Core_Error', 'simpleHandler')); // lets ensure we set E_DEPRECATED to minimize errors // CRM-6327 if (defined('E_DEPRECATED')) { error_reporting(error_reporting() & ~E_DEPRECATED); } // first, attempt to get configuration object from cache $cache = CRM_Utils_Cache::singleton(); self::$_singleton = $cache->get('CRM_Core_Config' . CRM_Core_Config::domainID()); // if not in cache, fire off config construction if (!self::$_singleton) { self::$_singleton = new CRM_Core_Config(); self::$_singleton->_initialize($loadFromDB); //initialize variables. for gencode we cannot load from the //db since the db might not be initialized if ($loadFromDB) { // initialize stuff from the settings file self::$_singleton->setCoreVariables(); self::$_singleton->_initVariables(); // I don't think we need to do this twice // however just keeping this commented for now in 4.4 // in case we hit any issues - CRM-13064 // We can safely delete this once we release 4.4.4 // self::$_singleton->setCoreVariables(); } $cache->set('CRM_Core_Config' . CRM_Core_Config::domainID(), self::$_singleton); } else { // we retrieve the object from memcache, so we now initialize the objects self::$_singleton->_initialize($loadFromDB); // CRM-9803, NYSS-4822 // this causes various settings to be reset and hence we should // only use the config object that we retrieved from memcache } self::$_singleton->initialized = 1; if (isset(self::$_singleton->customPHPPathDir) && self::$_singleton->customPHPPathDir) { $include_path = self::$_singleton->customPHPPathDir . PATH_SEPARATOR . get_include_path(); set_include_path($include_path); } // set the callback at the very very end, to avoid an infinite loop // set the error callback unset($errorScope); // call the hook so other modules can add to the config // again doing this at the very very end CRM_Utils_Hook::config(self::$_singleton); // make sure session is always initialised $session = CRM_Core_Session::singleton(); // for logging purposes, pass the userID to the db $userID = $session->get('userID'); if ($userID) { CRM_Core_DAO::executeQuery('SET @civicrm_user_id = %1', array(1 => array($userID, 'Integer'))); } // initialize authentication source self::$_singleton->initAuthSrc(); } return self::$_singleton; }
public static function flushAll() { self::$_values = array(); self::$_cache = array(); CRM_Utils_Cache::singleton()->flush(); }
/** * Get a list of boot services. * * These are services which must be setup *before* the container can operate. * * @param bool $loadFromDB * @throws \CRM_Core_Exception */ public static function boot($loadFromDB) { $bootServices = array(); \Civi::$statics[__CLASS__]['boot'] =& $bootServices; $bootServices['runtime'] = array('class' => 'CRM_Core_Config_Runtime', 'obj' => $runtime = new \CRM_Core_Config_Runtime()); $runtime->initialize($loadFromDB); if ($loadFromDB && $runtime->dsn) { \CRM_Core_DAO::init($runtime->dsn); } $bootServices['paths'] = array('class' => 'Civi\\Core\\Paths', 'obj' => new \Civi\Core\Paths()); $class = $runtime->userFrameworkClass; $bootServices['userSystem'] = array('class' => 'CRM_Utils_Cache_Interface', 'obj' => $userSystem = new $class()); $userSystem->initialize(); $userPermissionClass = 'CRM_Core_Permission_' . $runtime->userFramework; $bootServices['userPermissionClass'] = array('class' => 'CRM_Core_Permission_Base', 'obj' => new $userPermissionClass()); $bootServices['cache.settings'] = array('class' => 'CRM_Utils_Cache_Interface', 'obj' => \CRM_Utils_Cache::create(array('name' => 'settings', 'type' => array('*memory*', 'SqlGroup', 'ArrayCache')))); $bootServices['settings_manager'] = array('class' => 'Civi\\Core\\SettingsManager', 'obj' => new \Civi\Core\SettingsManager($bootServices['cache.settings']['obj'])); $bootServices['lockManager'] = array('class' => 'Civi\\Core\\Lock\\LockManager', 'obj' => self::createLockManager()); if ($loadFromDB && $runtime->dsn) { \CRM_Utils_Hook::singleton(TRUE); \CRM_Extension_System::singleton(TRUE); $c = new self(); \Civi::$statics[__CLASS__]['container'] = $c->loadContainer(); } }