First commit

This commit is contained in:
Theodotos Andreou 2018-01-14 13:10:16 +00:00
commit c6e2478c40
13918 changed files with 2303184 additions and 0 deletions

View file

@ -0,0 +1,373 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* Upgrade logic for 4.5
*/
class CRM_Upgrade_Incremental_php_FourFive extends CRM_Upgrade_Incremental_Base {
/**
* Compute any messages which should be displayed after upgrade.
*
* @param string $postUpgradeMessage
* alterable.
* @param string $rev
* an intermediate version; note that setPostUpgradeMessage is called repeatedly with different $revs.
*/
public function setPostUpgradeMessage(&$postUpgradeMessage, $rev) {
if ($rev == '4.5.alpha1') {
$postUpgradeMessage .= '<br /><br />' . ts('Default versions of the following System Workflow Message Templates have been modified to handle new functionality: <ul><li>Contributions - Receipt (off-line)</li><li>Contributions - Receipt (on-line)</li><li>Contributions - Recurring Start and End Notification</li><li>Contributions - Recurring Updates</li><li>Memberships - Receipt (on-line)</li><li>Memberships - Signup and Renewal Receipts (off-line)</li><li>Pledges - Acknowledgement</li></ul> If you have modified these templates, please review the new default versions and implement updates as needed to your copies (Administer > Communications > Message Templates > System Workflow Messages). (<a href="%1">learn more...</a>)', array(1 => 'http://wiki.civicrm.org/confluence/display/CRMDOC/Updating+System+Workflow+Message+Templates+after+Upgrades+-+method+1+-+kdiff'));
$postUpgradeMessage .= '<br /><br />' . ts('This release allows you to view and edit multiple-record custom field sets in a table format which will be more usable in some cases. You can try out the format by navigating to Administer > Custom Data & Screens > Custom Fields. Click Settings for a custom field set and change Display Style to "Tab with Tables".');
$postUpgradeMessage .= '<br /><br />' . ts('This release changes the way that anonymous event registrations match participants with existing contacts. By default, all event participants will be matched with existing individuals using the Unsupervised rule, even if multiple registrations with the same email address are allowed. However, you can now select a different matching rule to use for each event. Please review your events to make sure you choose the appropriate matching rule and collect sufficient information for it to match contacts.');
}
if ($rev == '4.5.beta2') {
$postUpgradeMessage .= '<br /><br />' . ts('If you use CiviMail for newsletters or other communications, check out the new sample CiviMail templates which use responsive design to optimize display on mobile devices (Administer > Communications > Message Templates ).');
}
if ($rev == '4.5.1') {
$postUpgradeMessage .= '<br /><br />' . ts('WARNING: If you use CiviCase with v4.5.alpha*, v4.5.beta*, or v4.5.0, it is possible that previous upgrades corrupted some CiviCase metadata. If you have not already done so, please identify any custom field sets, smart groups, or reports which refer to CiviCase and ensure that they are properly configured.');
}
}
/**
* @param $rev
*
* @return bool
*/
public function upgrade_4_5_alpha1($rev) {
// task to process sql
$this->addTask('Migrate honoree information to module_data', 'migrateHonoreeInfo');
$this->addTask(ts('Upgrade DB to %1: SQL', array(1 => '4.5.alpha1')), 'runSql', $rev);
$this->addTask('Set default for Individual name fields configuration', 'addNameFieldOptions');
// CRM-14522 - The below schema checking is done as foreign key name
// for pdf_format_id column varies for different databases
// if DB is been into upgrade for 3.4.2 version, it would have pdf_format_id name for FK
// else FK_civicrm_msg_template_pdf_format_id
$config = CRM_Core_Config::singleton();
$dbUf = DB::parseDSN($config->dsn);
$query = "
SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE TABLE_NAME = 'civicrm_msg_template'
AND CONSTRAINT_TYPE = 'FOREIGN KEY'
AND TABLE_SCHEMA = %1
";
$params = array(1 => array($dbUf['database'], 'String'));
$dao = CRM_Core_DAO::executeQuery($query, $params, TRUE, NULL, FALSE, FALSE);
if ($dao->fetch()) {
if ($dao->CONSTRAINT_NAME == 'FK_civicrm_msg_template_pdf_format_id' ||
$dao->CONSTRAINT_NAME == 'pdf_format_id'
) {
$sqlDropFK = "ALTER TABLE `civicrm_msg_template`
DROP FOREIGN KEY `{$dao->CONSTRAINT_NAME}`,
DROP KEY `{$dao->CONSTRAINT_NAME}`";
CRM_Core_DAO::executeQuery($sqlDropFK, CRM_Core_DAO::$_nullArray, TRUE, NULL, FALSE, FALSE);
}
}
return TRUE;
}
/**
* @param $rev
*
* @return bool
*/
public function upgrade_4_5_beta9($rev) {
$this->addTask(ts('Upgrade DB to %1: SQL', array(1 => '4.5.beta9')), 'runSql', $rev);
$entityTable = array(
'Participant' => 'civicrm_participant_payment',
'Contribution' => 'civicrm_contribution',
'Membership' => 'civicrm_membership',
);
foreach ($entityTable as $label => $tableName) {
list($minId, $maxId) = CRM_Core_DAO::executeQuery("SELECT coalesce(min(id),0), coalesce(max(id),0)
FROM {$tableName}")->getDatabaseResult()->fetchRow();
for ($startId = $minId; $startId <= $maxId; $startId += self::BATCH_SIZE) {
$endId = $startId + self::BATCH_SIZE - 1;
$title = ts("Upgrade DB to 4.5.beta9: Fix line items for {$label} (%1 => %2)", array(
1 => $startId,
2 => $endId,
));
$this->addTask($title, 'task_4_5_0_fixLineItem', $startId, $endId, $label);
}
}
return TRUE;
}
/**
* (Queue Task Callback)
*
* update the line items
*
*
* @param CRM_Queue_TaskContext $ctx
* @param int $startId
* the first/lowest entity ID to convert.
* @param int $endId
* the last/highest entity ID to convert.
* @param
*
* @return bool
*/
public static function task_4_5_0_fixLineItem(CRM_Queue_TaskContext $ctx, $startId, $endId, $entityTable) {
$sqlParams = array(
1 => array($startId, 'Integer'),
2 => array($endId, 'Integer'),
);
switch ($entityTable) {
case 'Contribution':
// update all the line item entity_table and entity_id with contribution due to bug CRM-15055
CRM_Core_DAO::executeQuery("UPDATE civicrm_line_item li
INNER JOIN civicrm_contribution cc ON cc.id = li.contribution_id
SET entity_id = li.contribution_id, entity_table = 'civicrm_contribution'
WHERE li.contribution_id IS NOT NULL AND li.entity_table <> 'civicrm_participant' AND (cc.id BETWEEN %1 AND %2)", $sqlParams);
// update the civicrm_line_item.contribution_id
CRM_Core_DAO::executeQuery("UPDATE civicrm_line_item li
INNER JOIN civicrm_contribution cc ON cc.id = li.entity_id
SET contribution_id = entity_id
WHERE li.contribution_id IS NULL AND li.entity_table = 'civicrm_contribution' AND (cc.id BETWEEN %1 AND %2)", $sqlParams);
break;
case 'Participant':
// update the civicrm_line_item.contribution_id
CRM_Core_DAO::executeQuery("UPDATE civicrm_line_item li
INNER JOIN civicrm_participant_payment pp ON pp.participant_id = li.entity_id
SET li.contribution_id = pp.contribution_id
WHERE li.entity_table = 'civicrm_participant' AND li.contribution_id IS NULL AND (pp.id BETWEEN %1 AND %2)", $sqlParams);
break;
case 'Membership':
$upgrade = new CRM_Upgrade_Form();
// update the line item of membership
CRM_Core_DAO::executeQuery("UPDATE civicrm_line_item li
INNER JOIN civicrm_membership_payment mp ON mp.contribution_id = li.contribution_id
INNER JOIN civicrm_membership cm ON mp.membership_id = cm.id
INNER JOIN civicrm_price_field_value pv ON pv.id = li.price_field_value_id
SET li.entity_table = 'civicrm_membership', li.entity_id = mp.membership_id
WHERE li.entity_table = 'civicrm_contribution'
AND pv.membership_type_id IS NOT NULL AND cm.membership_type_id = pv.membership_type_id AND (cm.id BETWEEN %1 AND %2)", $sqlParams);
CRM_Core_DAO::executeQuery("UPDATE civicrm_line_item li
INNER JOIN civicrm_membership_payment mp ON mp.contribution_id = li.contribution_id
INNER JOIN civicrm_price_field_value pv ON pv.id = li.price_field_value_id
SET li.entity_table = 'civicrm_membership', li.entity_id = mp.membership_id
WHERE li.entity_table = 'civicrm_contribution'
AND pv.membership_type_id IS NOT NULL AND (mp.membership_id BETWEEN %1 AND %2)", $sqlParams);
CRM_Core_DAO::executeQuery("INSERT INTO civicrm_line_item (entity_table, entity_id, price_field_id, label,
qty, unit_price, line_total, price_field_value_id, financial_type_id)
SELECT 'civicrm_membership', cm.id, cpf.id price_field_id, cpfv.label, 1 as qty, cpfv.amount, cpfv.amount line_total,
cpfv.id price_field_value_id, cpfv.financial_type_id FROM civicrm_membership cm
LEFT JOIN civicrm_membership_payment cmp ON cmp.membership_id = cm.id
INNER JOIN civicrm_price_field_value cpfv ON cpfv.membership_type_id = cm.membership_type_id
INNER JOIN civicrm_price_field cpf ON cpf.id = cpfv.price_field_id
INNER JOIN civicrm_price_set cps ON cps.id = cpf.price_set_id
WHERE cmp.contribution_id IS NULL AND cps.name = 'default_membership_type_amount' AND (cm.id BETWEEN %1 AND %2)", $sqlParams);
break;
}
return TRUE;
}
/**
* Add defaults for the newly introduced name fields configuration in 'contact_edit_options' setting
*
* @param CRM_Queue_TaskContext $ctx
*
* @return bool
* TRUE for success
*/
public static function addNameFieldOptions(CRM_Queue_TaskContext $ctx) {
$query = "SELECT `value` FROM `civicrm_setting` WHERE `group_name` = 'CiviCRM Preferences' AND `name` = 'contact_edit_options'";
$dao = CRM_Core_DAO::executeQuery($query);
$dao->fetch();
$oldValue = unserialize($dao->value);
$newValue = $oldValue . '1214151617';
$query = "UPDATE `civicrm_setting` SET `value` = %1 WHERE `group_name` = 'CiviCRM Preferences' AND `name` = 'contact_edit_options'";
$params = array(1 => array(serialize($newValue), 'String'));
CRM_Core_DAO::executeQuery($query, $params);
return TRUE;
}
/**
* Migrate honoree information to uf_join.module_data as honoree columns (text and title) will be dropped
* on DB upgrade
*
* @param CRM_Queue_TaskContext $ctx
*
* @return bool
* TRUE for success
*/
public static function migrateHonoreeInfo(CRM_Queue_TaskContext $ctx) {
$query = "ALTER TABLE `civicrm_uf_join`
ADD COLUMN `module_data` longtext COMMENT 'Json serialized array of data used by the ufjoin.module'";
CRM_Core_DAO::executeQuery($query);
$honorTypes = array_keys(CRM_Core_OptionGroup::values('honor_type'));
$ufGroupDAO = new CRM_Core_DAO_UFGroup();
$ufGroupDAO->name = 'new_individual';
$ufGroupDAO->find(TRUE);
$query = "SELECT * FROM civicrm_contribution_page";
$dao = CRM_Core_DAO::executeQuery($query);
if ($dao->N) {
$domain = new CRM_Core_DAO_Domain();
$domain->find(TRUE);
while ($dao->fetch()) {
$honorParams = array('soft_credit' => array('soft_credit_types' => $honorTypes));
if ($domain->locales) {
$locales = explode(CRM_Core_DAO::VALUE_SEPARATOR, $domain->locales);
foreach ($locales as $locale) {
$honor_block_title = "honor_block_title_{$locale}";
$honor_block_text = "honor_block_text_{$locale}";
$honorParams['soft_credit'] += array(
$locale => array(
'honor_block_title' => $dao->$honor_block_title,
'honor_block_text' => $dao->$honor_block_text,
),
);
}
}
else {
$honorParams['soft_credit'] += array(
'default' => array(
'honor_block_title' => $dao->honor_block_title,
'honor_block_text' => $dao->honor_block_text,
),
);
}
$ufJoinParam = array(
'module' => 'soft_credit',
'entity_table' => 'civicrm_contribution_page',
'is_active' => $dao->honor_block_is_active,
'entity_id' => $dao->id,
'uf_group_id' => $ufGroupDAO->id,
'module_data' => json_encode($honorParams),
);
CRM_Core_BAO_UFJoin::create($ufJoinParam);
}
}
return TRUE;
}
/**
* Upgrade function.
*
* @param string $rev
* @return bool
*/
public function upgrade_4_5_9($rev) {
// Task to process sql.
$this->addTask('Upgrade DB to 4.5.9: Fix saved searches consisting of multi-choice custom field(s)', 'updateSavedSearch');
return TRUE;
}
/**
* Update saved search for multi-select custom fields on DB upgrade
*
* @param CRM_Queue_TaskContext $ctx
*
* @return bool TRUE for success
*/
public static function updateSavedSearch(CRM_Queue_TaskContext $ctx) {
$sql = "SELECT id, form_values FROM civicrm_saved_search";
$dao = CRM_Core_DAO::executeQuery($sql);
while ($dao->fetch()) {
$copy = $formValues = unserialize($dao->form_values);
$update = FALSE;
foreach ($copy as $field => $data_value) {
if (preg_match('/^custom_/', $field) && is_array($data_value) && !array_key_exists("${field}_operator", $formValues)) {
// Now check for CiviCRM_OP_OR as either key or value in the data_value array.
// This is the conclusive evidence of an old-style data format.
if (array_key_exists('CiviCRM_OP_OR', $data_value) || FALSE !== array_search('CiviCRM_OP_OR', $data_value)) {
// We have old style data. Mark this record to be updated.
$update = TRUE;
$op = 'and';
if (!preg_match('/^custom_([0-9]+)/', $field, $matches)) {
// fatal error?
continue;
}
$fieldID = $matches[1];
if (array_key_exists('CiviCRM_OP_OR', $data_value)) {
// This indicates data structure identified by jamie in the form:
// value1 => 1, value2 => , value3 => 1.
$data_value = array_keys($data_value, 1);
// If CiviCRM_OP_OR - change OP from default to OR
if ($data_value['CiviCRM_OP_OR'] == 1) {
$op = 'or';
}
unset($data_value['CiviCRM_OP_OR']);
}
else {
// The value is here, but it is not set as a key.
// This is using the style identified by Monish - the existence of the value
// indicates an OR search and values are set in the form of:
// 0 => value1, 1 => value1, 3 => value2.
$key = array_search('CiviCRM_OP_OR', $data_value);
$op = 'or';
unset($data_value[$key]);
}
//If only Or operator has been chosen, means we need to select all values and
//so to execute OR operation between these values according to new data structure
if (count($data_value) == 0 && $op == 'or') {
$customOption = CRM_Core_BAO_CustomOption::getCustomOption($fieldID);
foreach ($customOption as $option) {
$data_value[] = CRM_Utils_Array::value('value', $option);
}
}
$formValues[$field] = $data_value;
$formValues["${field}_operator"] = $op;
}
}
}
if ($update) {
$sql = "UPDATE civicrm_saved_search SET form_values = %0 WHERE id = %1";
CRM_Core_DAO::executeQuery($sql,
array(
array(serialize($formValues), 'String'),
array($dao->id, 'Integer'),
)
);
}
}
return TRUE;
}
}

View file

@ -0,0 +1,819 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* Upgrade logic for 4.4
*/
class CRM_Upgrade_Incremental_php_FourFour extends CRM_Upgrade_Incremental_Base {
const MAX_WORD_REPLACEMENT_SIZE = 255;
/**
* Compute any messages which should be displayed beforeupgrade.
*
* Note: This function is called iteratively for each upcoming
* revision to the database.
*
* @param $preUpgradeMessage
* @param string $rev
* a version number, e.g. '4.4.alpha1', '4.4.beta3', '4.4.0'.
* @param string $currentVer
*/
public function setPreUpgradeMessage(&$preUpgradeMessage, $rev, $currentVer = NULL) {
if ($rev == '4.4.beta1') {
$apiCalls = self::getConfigArraysAsAPIParams(FALSE);
$oversizedEntries = 0;
foreach ($apiCalls as $params) {
if (!self::isValidWordReplacement($params)) {
$oversizedEntries++;
}
}
if ($oversizedEntries > 0) {
$preUpgradeMessage .= '<br/>' . ts("WARNING: There are %1 word-replacement entries which will not be valid in v4.4+ (eg with over 255 characters). They will be dropped during upgrade. For details, consult the CiviCRM log.", array(
1 => $oversizedEntries,
));
}
}
}
/**
* Compute any messages which should be displayed after upgrade.
*
* @param string $postUpgradeMessage
* alterable.
* @param string $rev
* an intermediate version; note that setPostUpgradeMessage is called repeatedly with different $revs.
*/
public function setPostUpgradeMessage(&$postUpgradeMessage, $rev) {
if ($rev == '4.4.1') {
$config = CRM_Core_Config::singleton();
if (!empty($config->useIDS)) {
$postUpgradeMessage .= '<br />' . ts("The setting to skip IDS check has been removed. Your site has this configured in civicrm.settings.php but it will no longer work. Instead, use the new permission 'skip IDS check' to bypass the IDS system.");
}
}
if ($rev == '4.4.3') {
$postUpgradeMessage .= '<br /><br />' . ts('Default versions of the following System Workflow Message Templates have been modified to handle new functionality: <ul><li>Events - Registration Confirmation and Receipt (on-line)</li></ul> If you have modified these templates, please review the new default versions and implement updates as needed to your copies (Administer > Communications > Message Templates > System Workflow Messages).');
}
if ($rev == '4.4.3') {
$query = "SELECT cft.id financial_trxn
FROM civicrm_financial_trxn cft
LEFT JOIN civicrm_entity_financial_trxn ceft ON ceft.financial_trxn_id = cft.id
LEFT JOIN civicrm_contribution cc ON ceft.entity_id = cc.id
WHERE ceft.entity_table = 'civicrm_contribution' AND cft.payment_instrument_id IS NULL;";
$dao = CRM_Core_DAO::executeQuery($query);
if ($dao->N) {
$postUpgradeMessage .= '<br /><br /><strong>' . ts('Your database contains %1 financial transaction records with no payment instrument (Paid By is empty). If you use the Accounting Batches feature this may result in unbalanced transactions. If you do not use this feature, you can ignore the condition (although you will be required to select a Paid By value for new transactions). <a href="%2" target="_blank">You can review steps to correct transactions with missing payment instruments on the wiki.</a>', array(
1 => $dao->N,
2 => 'http://wiki.civicrm.org/confluence/display/CRMDOC/Fixing+Transactions+Missing+a+Payment+Instrument+-+4.4.3+Upgrades',
)) . '</strong>';
}
}
if ($rev == '4.4.6') {
$postUpgradeMessage .= '<br /><br /><strong>' . ts('Your contact image urls have been upgraded. If your contact image urls did not follow the standard format for image Urls they have not been upgraded. Please check the log to see image urls that were not upgraded.');
}
}
/**
* Upgrade 4.4.alpha1.
*
* @param string $rev
*
* @return bool
*/
public function upgrade_4_4_alpha1($rev) {
// task to process sql
$this->addTask(ts('Upgrade DB to %1: SQL', array(1 => '4.4.alpha1')), 'runSql', $rev);
// Consolidate activity contacts CRM-12274.
$this->addTask('Consolidate activity contacts', 'activityContacts');
return TRUE;
}
/**
* @param $rev
*/
public function upgrade_4_4_beta1($rev) {
$this->addTask(ts('Upgrade DB to %1: SQL', array(1 => '4.4.beta1')), 'runSql', $rev);
// add new 'data' column in civicrm_batch
$query = 'ALTER TABLE civicrm_batch ADD data LONGTEXT NULL COMMENT "cache entered data"';
CRM_Core_DAO::executeQuery($query, array(), TRUE, NULL, FALSE, FALSE);
// check if batch entry data exists in civicrm_cache table
$query = 'SELECT path, data FROM civicrm_cache WHERE group_name = "batch entry"';
$dao = CRM_Core_DAO::executeQuery($query);
while ($dao->fetch()) {
// get batch id $batchId[2]
$batchId = explode('-', $dao->path);
$data = unserialize($dao->data);
// move the data to civicrm_batch table
CRM_Core_DAO::setFieldValue('CRM_Batch_DAO_Batch', $batchId[2], 'data', json_encode(array('values' => $data)));
}
// delete entries from civicrm_cache table
$query = 'DELETE FROM civicrm_cache WHERE group_name = "batch entry"';
CRM_Core_DAO::executeQuery($query);
$this->addTask('Migrate custom word-replacements', 'wordReplacements');
}
/**
* @param $rev
*/
public function upgrade_4_4_1($rev) {
$config = CRM_Core_Config::singleton();
// CRM-13327 upgrade handling for the newly added name badges
$ogID = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup', 'name_badge', 'id', 'name');
$nameBadges = array_flip(array_values(CRM_Core_BAO_OptionValue::getOptionValuesAssocArrayFromName('name_badge')));
unset($nameBadges['Avery 5395']);
if (!empty($nameBadges)) {
$dimension = '{"paper-size":"a4","orientation":"portrait","font-name":"times","font-size":6,"font-style":"","NX":2,"NY":4,"metric":"mm","lMargin":6,"tMargin":19,"SpaceX":0,"SpaceY":0,"width":100,"height":65,"lPadding":0,"tPadding":0}';
$query = "UPDATE civicrm_option_value
SET value = '{$dimension}'
WHERE option_group_id = %1 AND name = 'Fattorini Name Badge 100x65'";
CRM_Core_DAO::executeQuery($query, array(1 => array($ogID, 'Integer')));
}
else {
$dimensions = array(
1 => '{"paper-size":"a4","orientation":"landscape","font-name":"times","font-size":6,"font-style":"","NX":2,"NY":1,"metric":"mm","lMargin":25,"tMargin":27,"SpaceX":0,"SpaceY":35,"width":106,"height":150,"lPadding":5,"tPadding":5}',
2 => '{"paper-size":"a4","orientation":"portrait","font-name":"times","font-size":6,"font-style":"","NX":2,"NY":4,"metric":"mm","lMargin":6,"tMargin":19,"SpaceX":0,"SpaceY":0,"width":100,"height":65,"lPadding":0,"tPadding":0}',
3 => '{"paper-size":"a4","orientation":"portrait","font-name":"times","font-size":6,"font-style":"","NX":2,"NY":2,"metric":"mm","lMargin":10,"tMargin":28,"SpaceX":0,"SpaceY":0,"width":96,"height":121,"lPadding":5,"tPadding":5}',
);
$insertStatements = array(
1 => "($ogID, %1, '{$dimensions[1]}', %1, NULL, 0, NULL, 2, NULL, 0, 0, 1, NULL, NULL)",
2 => "($ogID, %2, '{$dimensions[2]}', %2, NULL, 0, NULL, 3, NULL, 0, 0, 1, NULL, NULL)",
3 => "($ogID, %3, '{$dimensions[3]}', %3, NULL, 0, NULL, 4, NULL, 0, 0, 1, NULL, NULL)",
);
$queryParams = array(
1 => array('A6 Badge Portrait 150x106', 'String'),
2 => array('Fattorini Name Badge 100x65', 'String'),
3 => array('Hanging Badge 3-3/4" x 4-3"/4', 'String'),
);
foreach ($insertStatements as $values) {
$query = 'INSERT INTO civicrm_option_value (`option_group_id`, `label`, `value`, `name`, `grouping`, `filter`, `is_default`, `weight`, `description`, `is_optgroup`, `is_reserved`, `is_active`, `component_id`, `visibility_id`) VALUES' . $values;
CRM_Core_DAO::executeQuery($query, $queryParams);
}
}
// CRM-12578 - Prior to this version a CSS file under drupal would disable core css
if (!empty($config->customCSSURL) && strpos($config->userFramework, 'Drupal') === 0) {
// The new setting doesn't exist yet - need to create it first
$sql = '
INSERT INTO civicrm_setting (group_name, name , value , domain_id , is_domain , created_date)
VALUES (%1, %2, %3, %4, %5, now())';
CRM_Core_DAO::executeQuery($sql, array(
1 => array(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'String'),
2 => array('disable_core_css', 'String'),
3 => array(serialize(1), 'String'),
4 => array(CRM_Core_Config::domainID(), 'Positive'),
5 => array(1, 'Int'),
));
Civi::service('settings_manager')->flush();
}
// CRM-13701 - Fix $config->timeInputFormat
$sql = "
SELECT time_format
FROM civicrm_preferences_date
WHERE time_format IS NOT NULL
AND time_format <> ''
LIMIT 1
";
$timeInputFormat = CRM_Core_DAO::singleValueQuery($sql);
if ($timeInputFormat && $timeInputFormat != $config->timeInputFormat) {
$params = array('timeInputFormat' => $timeInputFormat);
CRM_Core_BAO_ConfigSetting::add($params);
}
// CRM-13698 - add 'Available' and 'No-show' activity statuses
$insertStatus = array();
$nsinc = $avinc = $inc = 0;
if (!CRM_Core_OptionGroup::getValue('activity_status', 'Available', 'name')) {
$insertStatus[] = "(%1, 'Available', %2, 'Available', NULL, 0, NULL, %3, 0, 0, 1, NULL, NULL)";
$avinc = $inc = 1;
}
if (!CRM_Core_OptionGroup::getValue('activity_status', 'No_show', 'name')) {
$insertStatus[] = "(%1, 'No-show', %4, 'No_show', NULL, 0, NULL, %5, 0, 0, 1, NULL, NULL)";
$nsinc = $inc + 1;
}
if (!empty($insertStatus)) {
$acOptionGroupID = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup', 'activity_status', 'id', 'name');
$maxVal = CRM_Core_DAO::singleValueQuery("SELECT MAX(ROUND(op.value)) FROM civicrm_option_value op WHERE op.option_group_id = $acOptionGroupID");
$maxWeight = CRM_Core_DAO::singleValueQuery("SELECT MAX(weight) FROM civicrm_option_value WHERE option_group_id = $acOptionGroupID");
$p[1] = array($acOptionGroupID, 'Integer');
if ($avinc) {
$p[2] = array($avinc + $maxVal, 'Integer');
$p[3] = array($avinc + $maxWeight, 'Integer');
}
if ($nsinc) {
$p[4] = array($nsinc + $maxVal, 'Integer');
$p[5] = array($nsinc + $maxWeight, 'Integer');
}
$insertStatus = implode(',', $insertStatus);
$sql = "
INSERT INTO
civicrm_option_value (`option_group_id`, label, `value`, `name`, `grouping`, `filter`, `is_default`, `weight`, `is_optgroup`, `is_reserved`, `is_active`, `component_id`, `visibility_id`)
VALUES {$insertStatus}";
CRM_Core_DAO::executeQuery($sql, $p);
}
$this->addTask(ts('Upgrade DB to %1: SQL', array(1 => '4.4.1')), 'runSql', $rev);
$this->addTask('Patch word-replacement schema', 'wordReplacements_patch', $rev);
}
/**
* @param $rev
*
* @return bool
*/
public function upgrade_4_4_4($rev) {
$fkConstraint = array();
if (!CRM_Core_DAO::checkFKConstraintInFormat('civicrm_activity_contact', 'activity_id')) {
$fkConstraint[] = "ADD CONSTRAINT `FK_civicrm_activity_contact_activity_id` FOREIGN KEY (`activity_id`) REFERENCES `civicrm_activity` (`id`) ON DELETE CASCADE";
}
if (!CRM_Core_DAO::checkFKConstraintInFormat('civicrm_activity_contact', 'contact_id')) {
$fkConstraint[] = "ADD CONSTRAINT `FK_civicrm_activity_contact_contact_id` FOREIGN KEY (`contact_id`) REFERENCES `civicrm_contact` (`id`) ON DELETE CASCADE;
";
}
if (!empty($fkConstraint)) {
$fkConstraint = implode(',', $fkConstraint);
$sql = "ALTER TABLE `civicrm_activity_contact`
{$fkConstraint}
";
// CRM-14036 : delete entries of un-mapped contacts
CRM_Core_DAO::executeQuery("DELETE ac FROM civicrm_activity_contact ac
LEFT JOIN civicrm_contact c
ON c.id = ac.contact_id
WHERE c.id IS NULL;
");
// delete entries of un-mapped activities
CRM_Core_DAO::executeQuery("DELETE ac FROM civicrm_activity_contact ac
LEFT JOIN civicrm_activity a
ON a.id = ac.activity_id
WHERE a.id IS NULL;
");
CRM_Core_DAO::executeQuery("SET FOREIGN_KEY_CHECKS=0;");
CRM_Core_DAO::executeQuery($sql);
CRM_Core_DAO::executeQuery("SET FOREIGN_KEY_CHECKS=1;");
}
// task to process sql
$this->addTask(ts('Upgrade DB to %1: SQL', array(1 => '4.4.4')), 'runSql', $rev);
// CRM-13892 : add `name` column to dashboard schema
$query = "
ALTER TABLE civicrm_dashboard
ADD name varchar(64) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'Internal name of dashlet.' AFTER domain_id ";
CRM_Core_DAO::executeQuery($query, array(), TRUE, NULL, FALSE, FALSE);
$dashboard = new CRM_Core_DAO_Dashboard();
$dashboard->find();
while ($dashboard->fetch()) {
$urlElements = explode('/', $dashboard->url);
if ($urlElements[1] == 'dashlet') {
$url = explode('&', $urlElements[2]);
$name = $url[0];
}
elseif ($urlElements[1] == 'report') {
$url = explode('&', $urlElements[3]);
$name = 'report/' . $url[0];
}
$values .= "
WHEN {$dashboard->id} THEN '{$name}'
";
}
$query = "
UPDATE civicrm_dashboard
SET name = CASE id
{$values}
END;
";
CRM_Core_DAO::executeQuery($query, array(), TRUE, NULL, FALSE, FALSE);
// CRM-13998 : missing alter statements for civicrm_report_instance
$this->addTask(ts('Confirm civicrm_report_instance sql table for upgrades'), 'updateReportInstanceTable');
return TRUE;
}
/**
* @param $rev
*/
public function upgrade_4_4_6($rev) {
$sql = "SELECT count(*) AS count FROM INFORMATION_SCHEMA.STATISTICS where " .
"TABLE_SCHEMA = database() AND INDEX_NAME = 'index_image_url' AND TABLE_NAME = 'civicrm_contact';";
$dao = CRM_Core_DAO::executeQuery($sql);
$dao->fetch();
if ($dao->count < 1) {
$sql = "CREATE INDEX index_image_url ON civicrm_contact (image_url);";
$dao = CRM_Core_DAO::executeQuery($sql);
}
$minId = CRM_Core_DAO::singleValueQuery('SELECT coalesce(min(id),0) FROM civicrm_contact WHERE image_URL IS NOT NULL');
$maxId = CRM_Core_DAO::singleValueQuery('SELECT coalesce(max(id),0) FROM civicrm_contact WHERE image_URL IS NOT NULL');
for ($startId = $minId; $startId <= $maxId; $startId += self::BATCH_SIZE) {
$endId = $startId + self::BATCH_SIZE - 1;
$title = "Upgrade image_urls ($startId => $endId)";
$this->addTask($title, 'upgradeImageUrls', $startId, $endId);
}
}
/**
* Upgrade script for 4.4.7.
*
* @param string $rev
* @param string $originalVer
* @param string $latestVer
*/
public function upgrade_4_4_7($rev, $originalVer, $latestVer) {
// For WordPress/Joomla(?), cleanup broken image_URL from 4.4.6 upgrades - https://issues.civicrm.org/jira/browse/CRM-14971
$exBackendUrl = CRM_Utils_System::url('civicrm/contact/imagefile', 'photo=XXX', TRUE); // URL formula from 4.4.6 upgrade
$exFrontendUrl = CRM_Utils_System::url('civicrm/contact/imagefile', 'photo=XXX', TRUE, NULL, TRUE, TRUE);
if ($originalVer == '4.4.6' && $exBackendUrl != $exFrontendUrl) {
$minId = CRM_Core_DAO::singleValueQuery('SELECT coalesce(min(id),0) FROM civicrm_contact WHERE image_URL IS NOT NULL');
$maxId = CRM_Core_DAO::singleValueQuery('SELECT coalesce(max(id),0) FROM civicrm_contact WHERE image_URL IS NOT NULL');
for ($startId = $minId; $startId <= $maxId; $startId += self::BATCH_SIZE) {
$endId = $startId + self::BATCH_SIZE - 1;
$title = "Upgrade image_urls ($startId => $endId)";
$this->addTask($title, 'cleanupBackendImageUrls', $startId, $endId);
}
}
$this->addTask(ts('Update saved search information'), 'changeSavedSearch');
}
/**
* Upgrade image URLs.
*
* @param \CRM_Queue_TaskContext $ctx
* @param $startId
* @param $endId
*
* @return bool
*/
public static function upgradeImageUrls(CRM_Queue_TaskContext $ctx, $startId, $endId) {
$dao = self::findContactImageUrls($startId, $endId);
$failures = array();
$config = CRM_Core_Config::singleton();
while ($dao->fetch()) {
$imageURL = $dao->image_url;
$baseurl = CIVICRM_UF_BASEURL;
//CRM-15897 - gross hack for joomla to remove the administrator/
if ($config->userFramework == 'Joomla') {
$baseurl = str_replace("/administrator/", "/", $baseurl);
}
$baselen = strlen($baseurl);
if (substr($imageURL, 0, $baselen) == $baseurl) {
$photo = basename($dao->image_url);
$fullpath = $config->customFileUploadDir . $photo;
if (file_exists($fullpath)) {
// For anyone who upgraded 4.4.6 release (eg 4.4.0=>4.4.6), the $newImageUrl incorrectly used backend URLs.
// For anyone who skipped 4.4.6 (eg 4.4.0=>4.4.7), the $newImageUrl correctly uses frontend URLs
self::setContactImageUrl($dao->id,
CRM_Utils_System::url('civicrm/contact/imagefile', 'photo=' . $photo, TRUE, NULL, TRUE, TRUE));
}
else {
$failures[$dao->id] = $dao->image_url;
}
}
else {
$failures[$dao->id] = $dao->image_url;
}
}
CRM_Core_Error::debug_var('imageUrlsNotUpgraded', $failures);
return TRUE;
}
/**
* Change saved search.
*
* @param \CRM_Queue_TaskContext $ctx
*
* @return bool
*/
public static function changeSavedSearch(CRM_Queue_TaskContext $ctx) {
$membershipStatuses = array_flip(CRM_Member_PseudoConstant::membershipStatus());
$dao = new CRM_Contact_DAO_SavedSearch();
$dao->find();
while ($dao->fetch()) {
$formValues = NULL;
if (!empty($dao->form_values)) {
$formValues = unserialize($dao->form_values);
}
if (!empty($formValues['mapper'])) {
foreach ($formValues['mapper'] as $key => $value) {
foreach ($value as $k => $v) {
if ($v[0] == 'Membership' && in_array($v[1], array('membership_status', 'membership_status_id'))) {
$value = $formValues['value'][$key][$k];
$op = $formValues['operator'][$key][$k];
if ($op == 'IN') {
$value = trim($value);
$value = str_replace('(', '', $value);
$value = str_replace(')', '', $value);
$v = explode(',', $value);
$value = array();
foreach ($v as $k1 => $v2) {
if (is_numeric($v2)) {
break 2;
}
$value[$k1] = $membershipStatuses[$v2];
}
$formValues['value'][$key][$k] = "(" . implode(',', $value) . ")";
}
elseif (in_array($op, array('=', '!='))) {
if (is_numeric($value)) {
break;
}
$formValues['value'][$key][$k] = $membershipStatuses[$value];
}
}
}
}
$dao->form_values = serialize($formValues);
$dao->save();
}
}
return TRUE;
}
/**
* For WordPress/Joomla(?) sites which upgraded to 4.4.6, find back-end image_URLs
* (e.g. "http://example.com/wp-admin/admin.php?page=CiviCRM&amp;q=civicrm/contact/imagefile&amp;photo=123.jpg")
* and convert them to front-end URLs
* (e.g. "http://example.com/?page=CiviCRM&amp;q=civicrm/contact/imagefile&amp;photo=123.jpg").
*
* @param CRM_Queue_TaskContext $ctx
* @param int $startId
* @param int $endId
* @return bool
*/
public static function cleanupBackendImageUrls(CRM_Queue_TaskContext $ctx, $startId, $endId) {
$dao = self::findContactImageUrls($startId, $endId);
while ($dao->fetch()) {
$imageUrl = str_replace('&amp;', '&', $dao->image_url);
if (preg_match(":civicrm/contact/imagefile.*photo=:", $imageUrl)) {
// looks like one of ours
$imageUrlParts = parse_url($imageUrl);
parse_str($imageUrlParts['query'], $imageUrlQuery);
self::setContactImageUrl($dao->id,
CRM_Utils_System::url('civicrm/contact/imagefile', 'photo=' . $imageUrlQuery['photo'], TRUE, NULL, TRUE, TRUE));
}
}
return TRUE;
}
/**
* @param int $startId
* @param int $endId
* @return CRM_Core_DAO
* columns include "id" and "image_URL"
*/
public static function findContactImageUrls($startId, $endId) {
$sql = "
SELECT id, image_url
FROM civicrm_contact
WHERE 1
AND id BETWEEN %1 AND %2
AND image_URL IS NOT NULL
";
$params = array(
1 => array($startId, 'Integer'),
2 => array($endId, 'Integer'),
);
$dao = CRM_Core_DAO::executeQuery($sql, $params, TRUE, NULL, FALSE, FALSE);
return $dao;
}
/**
* @param int $cid
* @param string $newImageUrl
*/
public static function setContactImageUrl($cid, $newImageUrl) {
$sql = 'UPDATE civicrm_contact SET image_url=%1 WHERE id=%2';
$params = array(
1 => array($newImageUrl, 'String'),
2 => array($cid, 'Integer'),
);
$updatedao = CRM_Core_DAO::executeQuery($sql, $params);
}
/**
* Update activity contacts CRM-12274
*
* @param CRM_Queue_TaskContext $ctx
*
* @return bool
* TRUE for success
*/
public static function activityContacts(CRM_Queue_TaskContext $ctx) {
$upgrade = new CRM_Upgrade_Form();
$activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
$ovValue[] = $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
$ovValue[] = $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
$ovValue[] = $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
$optionGroupID = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup', 'activity_contacts', 'id', 'name');
if (!empty($ovValue)) {
$ovValues = implode(', ', $ovValue);
$query = "
UPDATE civicrm_option_value
SET is_reserved = 1
WHERE option_group_id = {$optionGroupID} AND value IN ($ovValues)";
$dao = CRM_Core_DAO::executeQuery($query);
}
if (!$assigneeID) {
$assigneeID = 1;
$value[] = "({$optionGroupID}, 'Activity Assignees', 1, 'Activity Assignees', 1, 1, 1)";
}
if (!$sourceID) {
$sourceID = 2;
$value[] = "({$optionGroupID}, 'Activity Source', 2, 'Activity Source', 2, 1, 1)";
}
if (!$targetID) {
$targetID = 3;
$value[] = "({$optionGroupID}, 'Activity Targets', 3, 'Activity Targets', 3, 1, 1)";
}
if (!$assigneeID || !$sourceID || !$targetID) {
$insert = "
INSERT INTO civicrm_option_value
(option_group_id, label, value, name, weight, is_reserved, is_active)
VALUES
";
$values = implode(', ', $value);
$query = $insert . $values;
$dao = CRM_Core_DAO::executeQuery($query);
}
// sometimes an user does not make a clean backup and the above table
// already exists, so lets delete this table - CRM-13665
$query = "DROP TABLE IF EXISTS civicrm_activity_contact";
$dao = CRM_Core_DAO::executeQuery($query);
$query = "
CREATE TABLE IF NOT EXISTS civicrm_activity_contact (
id int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'Activity contact id',
activity_id int(10) unsigned NOT NULL COMMENT 'Foreign key to the activity for this record.',
contact_id int(10) unsigned NOT NULL COMMENT 'Foreign key to the contact for this record.',
record_type_id int(10) unsigned DEFAULT NULL COMMENT 'The record type id for this row',
PRIMARY KEY (id),
UNIQUE KEY UI_activity_contact (contact_id,activity_id,record_type_id),
KEY FK_civicrm_activity_contact_activity_id (activity_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
";
$dao = CRM_Core_DAO::executeQuery($query);
$query = "
INSERT INTO civicrm_activity_contact (activity_id, contact_id, record_type_id)
SELECT activity_id, target_contact_id, {$targetID} as record_type_id
FROM civicrm_activity_target";
$dao = CRM_Core_DAO::executeQuery($query);
$query = "
INSERT INTO civicrm_activity_contact (activity_id, contact_id, record_type_id)
SELECT activity_id, assignee_contact_id, {$assigneeID} as record_type_id
FROM civicrm_activity_assignment";
$dao = CRM_Core_DAO::executeQuery($query);
$query = "
INSERT INTO civicrm_activity_contact (activity_id, contact_id, record_type_id)
SELECT id, source_contact_id, {$sourceID} as record_type_id
FROM civicrm_activity
WHERE source_contact_id IS NOT NULL";
$dao = CRM_Core_DAO::executeQuery($query);
$query = "DROP TABLE civicrm_activity_target";
$dao = CRM_Core_DAO::executeQuery($query);
$query = "DROP TABLE civicrm_activity_assignment";
$dao = CRM_Core_DAO::executeQuery($query);
$query = "ALTER TABLE civicrm_activity
DROP FOREIGN KEY FK_civicrm_activity_source_contact_id";
$dao = CRM_Core_DAO::executeQuery($query);
$query = "ALTER TABLE civicrm_activity DROP COLUMN source_contact_id";
$dao = CRM_Core_DAO::executeQuery($query);
return TRUE;
}
/**
* Migrate word-replacements from $config to civicrm_word_replacement
*
* @param CRM_Queue_TaskContext $ctx
*
* @return bool
* TRUE for success
* @see http://issues.civicrm.org/jira/browse/CRM-13187
*/
public static function wordReplacements(CRM_Queue_TaskContext $ctx) {
$query = "
CREATE TABLE IF NOT EXISTS `civicrm_word_replacement` (
`id` int unsigned NOT NULL AUTO_INCREMENT COMMENT 'Word replacement ID',
`find_word` varchar(255) COLLATE utf8_bin COMMENT 'Word which need to be replaced',
`replace_word` varchar(255) COLLATE utf8_bin COMMENT 'Word which will replace the word in find',
`is_active` tinyint COMMENT 'Is this entry active?',
`match_type` enum('wildcardMatch', 'exactMatch') DEFAULT 'wildcardMatch',
`domain_id` int unsigned COMMENT 'FK to Domain ID. This is for Domain specific word replacement',
PRIMARY KEY ( `id` ),
UNIQUE INDEX `UI_domain_find` (domain_id, find_word),
CONSTRAINT FK_civicrm_word_replacement_domain_id FOREIGN KEY (`domain_id`) REFERENCES `civicrm_domain`(`id`)
) ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
";
$dao = CRM_Core_DAO::executeQuery($query);
self::rebuildWordReplacementTable();
return TRUE;
}
/**
* Fix misconfigured constraints created in 4.4.0. To distinguish the good
* and bad configurations, we change the constraint name from "UI_find"
* (the original name in 4.4.0) to "UI_domain_find" (the new name in
* 4.4.1).
*
* @param CRM_Queue_TaskContext $ctx
* @param $rev
*
* @return bool
* TRUE for success
* @see http://issues.civicrm.org/jira/browse/CRM-13655
*/
public static function wordReplacements_patch(CRM_Queue_TaskContext $ctx, $rev) {
if (CRM_Core_DAO::checkConstraintExists('civicrm_word_replacement', 'UI_find')) {
CRM_Core_DAO::executeQuery("ALTER TABLE civicrm_word_replacement DROP FOREIGN KEY FK_civicrm_word_replacement_domain_id;");
CRM_Core_DAO::executeQuery("ALTER TABLE civicrm_word_replacement DROP KEY FK_civicrm_word_replacement_domain_id;");
CRM_Core_DAO::executeQuery("ALTER TABLE civicrm_word_replacement DROP KEY UI_find;");
CRM_Core_DAO::executeQuery("ALTER TABLE civicrm_word_replacement MODIFY COLUMN `find_word` varchar(255) COLLATE utf8_bin DEFAULT NULL COMMENT 'Word which need to be replaced';");
CRM_Core_DAO::executeQuery("ALTER TABLE civicrm_word_replacement MODIFY COLUMN `replace_word` varchar(255) COLLATE utf8_bin DEFAULT NULL COMMENT 'Word which will replace the word in find';");
CRM_Core_DAO::executeQuery("ALTER TABLE civicrm_word_replacement ADD CONSTRAINT UI_domain_find UNIQUE KEY `UI_domain_find` (`domain_id`,`find_word`);");
CRM_Core_DAO::executeQuery("ALTER TABLE civicrm_word_replacement ADD CONSTRAINT FK_civicrm_word_replacement_domain_id FOREIGN KEY (`domain_id`) REFERENCES `civicrm_domain` (`id`);");
}
return TRUE;
}
/**
* Get all the word-replacements stored in config-arrays
* and convert them to params for the WordReplacement.create API.
*
* Note: This function is duplicated in CRM_Core_BAO_WordReplacement and
* CRM_Upgrade_Incremental_php_FourFour to ensure that the incremental upgrade
* step behaves consistently even as the BAO evolves in future versions.
* However, if there's a bug in here prior to 4.4.0, we should apply the
* bugfix in both places.
*
* @param bool $rebuildEach
* Whether to perform rebuild after each individual API call.
* @return array
* Each item is $params for WordReplacement.create
* @see CRM_Core_BAO_WordReplacement::convertConfigArraysToAPIParams
*/
public static function getConfigArraysAsAPIParams($rebuildEach) {
$wordReplacementCreateParams = array();
// get all domains
$result = civicrm_api3('domain', 'get', array(
'return' => array('locale_custom_strings'),
));
if (!empty($result["values"])) {
foreach ($result["values"] as $value) {
$params = array();
$params["domain_id"] = $value["id"];
$params["options"] = array('wp-rebuild' => $rebuildEach);
// unserialize word match string
$localeCustomArray = array();
if (!empty($value["locale_custom_strings"])) {
$localeCustomArray = unserialize($value["locale_custom_strings"]);
}
if (!empty($localeCustomArray)) {
$wordMatchArray = array();
// Traverse Language array
foreach ($localeCustomArray as $localCustomData) {
// Traverse status array "enabled" "disabled"
foreach ($localCustomData as $status => $matchTypes) {
$params["is_active"] = ($status == "enabled") ? TRUE : FALSE;
// Traverse Match Type array "wildcardMatch" "exactMatch"
foreach ($matchTypes as $matchType => $words) {
$params["match_type"] = $matchType;
foreach ($words as $word => $replace) {
$params["find_word"] = $word;
$params["replace_word"] = $replace;
$wordReplacementCreateParams[] = $params;
}
}
}
}
}
}
}
return $wordReplacementCreateParams;
}
/**
* Get all the word-replacements stored in config-arrays
* and write them out as records in civicrm_word_replacement.
*
* Note: This function is duplicated in CRM_Core_BAO_WordReplacement and
* CRM_Upgrade_Incremental_php_FourFour to ensure that the incremental upgrade
* step behaves consistently even as the BAO evolves in future versions.
* However, if there's a bug in here prior to 4.4.0, we should apply the
* bugfix in both places.
*/
public static function rebuildWordReplacementTable() {
civicrm_api3('word_replacement', 'replace', array(
'options' => array('match' => array('domain_id', 'find_word')),
'values' => array_filter(self::getConfigArraysAsAPIParams(FALSE), array(__CLASS__, 'isValidWordReplacement')),
));
CRM_Core_BAO_WordReplacement::rebuild();
}
/**
* CRM-13998 missing alter statements for civicrm_report_instance
*/
public function updateReportInstanceTable() {
// add civicrm_report_instance.name
$sql = "SELECT count(*) FROM information_schema.columns "
. "WHERE table_schema = database() AND table_name = 'civicrm_report_instance' AND COLUMN_NAME = 'name' ";
$res = CRM_Core_DAO::singleValueQuery($sql);
if ($res <= 0) {
$sql = "ALTER TABLE civicrm_report_instance ADD `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'when combined with report_id/template uniquely identifies the instance'";
$res = CRM_Core_DAO::executeQuery($sql);
}
// add civicrm_report_instance args
$sql = "SELECT count(*) FROM information_schema.columns WHERE table_schema = database() AND table_name = 'civicrm_report_instance' AND COLUMN_NAME = 'args' ";
$res = CRM_Core_DAO::singleValueQuery($sql);
if ($res <= 0) {
$sql = "ALTER TABLE civicrm_report_instance ADD `args` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'arguments that are passed in the url when invoking the instance'";
$res = CRM_Core_DAO::executeQuery($sql);
}
return TRUE;
}
/**
* @param array $params
* @return bool
* TRUE if $params is valid
*/
public static function isValidWordReplacement($params) {
$result = strlen($params['find_word']) <= self::MAX_WORD_REPLACEMENT_SIZE && strlen($params['replace_word']) <= self::MAX_WORD_REPLACEMENT_SIZE;
if (!$result) {
CRM_Core_Error::debug_var('invalidWordReplacement', $params);
}
return $result;
}
}

View file

@ -0,0 +1,430 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
class CRM_Upgrade_Incremental_php_FourOne {
// This was changed in 4.3 so we define it locally for compatibility with older dbs
const NAVIGATION_NAME = "Navigation Menu";
/**
* @param $errors
*
* @return bool
*/
public function verifyPreDBstate(&$errors) {
$config = CRM_Core_Config::singleton();
if (in_array('CiviCase', $config->enableComponents)) {
if (!CRM_Core_DAO::checkTriggerViewPermission(TRUE, FALSE)) {
$errors[] = 'CiviCase now requires CREATE VIEW and DROP VIEW permissions for the database user.';
return FALSE;
}
}
return TRUE;
}
/**
* Compute any messages which should be displayed after upgrade.
*
* @param string $postUpgradeMessage
* alterable.
* @param string $rev
* an intermediate version; note that setPostUpgradeMessage is called repeatedly with different $revs.
*/
public function setPostUpgradeMessage(&$postUpgradeMessage, $rev) {
if ($rev == '4.1.alpha1') {
$postUpgradeMessage .= '<br />' .
ts('WARNING! CiviCRM 4.1 introduces an improved way of handling cron jobs. However the new method is NOT backwards compatible. <strong>Please notify your system administrator that all CiviCRM related cron jobs will cease to work, and will need to be re-configured (this includes sending CiviMail mailings, updating membership statuses, etc.).</strong> Refer to the <a href="%1">online documentation</a> for detailed instructions.', array(1 => 'http://wiki.civicrm.org/confluence/display/CRMDOC41/Managing+Scheduled+Jobs'));
$postUpgradeMessage .= '<br />' .
ts('The CiviCRM Administration menu structure has been re-organized during this upgrade to make it easier to find things and reduce the number of keystrokes. If you have customized this portion of the navigation menu - you should take a few minutes to review the changes. You may need to reimplement or move your customizations.');
$postUpgradeMessage .= '<br />Yahoo recently discontinued their geocoding and mapping API service. If you previously used Yahoo, you will need to select and configure an alternate service in order to continue using geocoding/mapping tools.';
$postUpgradeMessage .= '<br />' .
ts('We have integrated KCFinder with CKEditor and TinyMCE, which enables user to upload images. Note that all the images uploaded using KCFinder will be public.');
}
}
/**
* @param $rev
*/
public function upgrade_4_1_alpha1($rev) {
$config = CRM_Core_Config::singleton();
if (in_array('CiviCase', $config->enableComponents)) {
if (!CRM_Case_BAO_Case::createCaseViews()) {
$template = CRM_Core_Smarty::singleton();
$afterUpgradeMessage = '';
if ($afterUpgradeMessage = $template->get_template_vars('afterUpgradeMessage')) {
$afterUpgradeMessage .= "<br/><br/>";
}
$afterUpgradeMessage .=
'<div class="crm-upgrade-case-views-error" style="background-color: #E43D2B; padding: 10px;">' .
ts("There was a problem creating CiviCase database views. Please create the following views manually before using CiviCase:");
$afterUpgradeMessage .=
'<div class="crm-upgrade-case-views-query"><div>' .
CRM_Case_BAO_Case::createCaseViewsQuery('upcoming') . '</div><div>' .
CRM_Case_BAO_Case::createCaseViewsQuery('recent') . '</div>' .
'</div></div>';
$template->assign('afterUpgradeMessage', $afterUpgradeMessage);
}
}
$upgrade = new CRM_Upgrade_Form();
$upgrade->processSQL($rev);
$this->transferPreferencesToSettings();
$this->createNewSettings();
// now modify the config so that the directories are now stored in the settings table
// CRM-8780
$params = array();
CRM_Core_BAO_ConfigSetting::add($params);
// also reset navigation
CRM_Core_BAO_Navigation::resetNavigation();
}
public function transferPreferencesToSettings() {
// first transfer system preferences
$domainColumnNames = array(
CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME => array(
'contact_view_options',
'contact_edit_options',
'advanced_search_options',
'user_dashboard_options',
'address_options',
'address_format',
'mailing_format',
'display_name_format',
'sort_name_format',
'editor_id',
'contact_autocomplete_options',
),
CRM_Core_BAO_Setting::ADDRESS_STANDARDIZATION_PREFERENCES_NAME => array(
'address_standardization_provider',
'address_standardization_userid',
'address_standardization_url',
),
CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME => array(
'mailing_backend',
),
);
$userColumnNames = array(
self::NAVIGATION_NAME => array(
'navigation',
),
);
$sql = "
SELECT *
FROM civicrm_preferences
WHERE domain_id = %1
";
$params = array(1 => array(CRM_Core_Config::domainID(), 'Integer'));
$dao = CRM_Core_DAO::executeQuery($sql, $params);
$domainID = CRM_Core_Config::domainID();
$createdDate = date('YmdHis');
while ($dao->fetch()) {
if ($dao->is_domain) {
$values = array();
foreach ($domainColumnNames as $groupName => $settingNames) {
foreach ($settingNames as $settingName) {
if (empty($dao->$settingName)) {
$value = NULL;
}
else {
if ($settingName == 'mailing_backend') {
$value = $dao->$settingName;
}
else {
$value = serialize($dao->$settingName);
}
}
if ($value) {
$value = addslashes($value);
}
$value = $value ? "'{$value}'" : 'null';
$values[] = " ('{$groupName}','{$settingName}', {$value}, {$domainID}, null, 1, '{$createdDate}', null )";
}
}
}
else {
// this is a user setting
foreach ($userColumnNames as $groupName => $settingNames) {
foreach ($settingNames as $settingName) {
$value = empty($dao->$settingName) ? NULL : serialize($dao->$settingName);
if ($value) {
$value = addslashes($value);
}
$value = $value ? "'{$value}'" : 'null';
$values[] = " ('{$groupName}', '{$settingName}', {$value}, {$domainID}, {$dao->contact_id}, 0, '{$createdDate}', null )";
}
}
}
}
$sql = "
INSERT INTO civicrm_setting( group_name, name, value, domain_id, contact_id, is_domain, created_date, created_id )
VALUES
";
$sql .= implode(",\n", $values);
CRM_Core_DAO::executeQuery($sql);
// now drop the civicrm_preferences table
$sql = "DROP TABLE civicrm_preferences";
CRM_Core_DAO::executeQuery($sql);
}
public function createNewSettings() {
$domainColumns = array(
CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME => array(
array('contact_ajax_check_similar', 1),
array('activity_assignee_notification', 1),
),
CRM_Core_BAO_Setting::CAMPAIGN_PREFERENCES_NAME => array(
array('tag_unconfirmed', 'Unconfirmed'),
array('petition_contacts', 'Petition Contacts'),
),
CRM_Core_BAO_Setting::EVENT_PREFERENCES_NAME => array(
array('enable_cart', 0),
),
CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME => array(
array('profile_double_optin', 1),
array('profile_add_to_group_double_optin', 0),
array('track_civimail_replies', 0),
array('civimail_workflow', 0),
array('civimail_server_wide_lock', 0),
),
CRM_Core_BAO_Setting::MEMBER_PREFERENCES_NAME => array(
array('default_renewal_contribution_page', NULL),
),
CRM_Core_BAO_Setting::MULTISITE_PREFERENCES_NAME => array(
array('is_enabled', 0),
array('uniq_email_per_site', 0),
array('domain_group_id', 0),
array('event_price_set_domain_id', 0),
),
CRM_Core_BAO_Setting::DIRECTORY_PREFERENCES_NAME => array(
array('uploadDir', NULL),
array('imageUploadDir', NULL),
array('customFileUploadDir', NULL),
array('customTemplateDir', NULL),
array('customPHPPathDir', NULL),
array('extensionsDir', NULL),
),
CRM_Core_BAO_Setting::URL_PREFERENCES_NAME => array(
array('userFrameworkResourceURL', NULL),
array('imageUploadURL', NULL),
array('customCSSURL', NULL),
),
);
$domainID = CRM_Core_Config::domainID();
$createdDate = date('YmdHis');
$dbSettings = array();
self::retrieveDirectoryAndURLPaths($dbSettings);
foreach ($domainColumns as $groupName => $settings) {
foreach ($settings as $setting) {
if (isset($dbSettings[$groupName][$setting[0]]) &&
!empty($dbSettings[$groupName][$setting[0]])
) {
$setting[1] = $dbSettings[$groupName][$setting[0]];
}
$value = $setting[1] === NULL ? NULL : serialize($setting[1]);
if ($value) {
$value = addslashes($value);
}
$value = $value ? "'{$value}'" : 'null';
$values[] = "( '{$groupName}', '{$setting[0]}', {$value}, {$domainID}, null, 0, '{$createdDate}', null )";
}
}
$sql = "
INSERT INTO civicrm_setting( group_name, name, value, domain_id, contact_id, is_domain, created_date, created_id )
VALUES
";
$sql .= implode(",\n", $values);
CRM_Core_DAO::executeQuery($sql);
}
/**
* @param array $params
*/
public static function retrieveDirectoryAndURLPaths(&$params) {
$sql = "
SELECT v.name as valueName, v.value, g.name as optionName
FROM civicrm_option_value v,
civicrm_option_group g
WHERE ( g.name = 'directory_preferences'
OR g.name = 'url_preferences' )
AND v.option_group_id = g.id
AND v.is_active = 1
";
$dao = CRM_Core_DAO::executeQuery($sql);
while ($dao->fetch()) {
if (!$dao->value) {
continue;
}
$groupName = CRM_Core_BAO_Setting::DIRECTORY_PREFERENCES_NAME;
if ($dao->optionName == 'url_preferences') {
$groupName = CRM_Core_BAO_Setting::URL_PREFERENCES_NAME;
}
$params[$groupName][$dao->valueName] = $dao->value;
}
}
/**
* @param $rev
*/
public function upgrade_4_1_alpha2($rev) {
$dao = new CRM_Core_DAO_Setting();
$dao->group_name = 'Directory Preferences';
$dao->name = 'customTemplateDir';
if (!($dao->find(TRUE))) {
$dao->domain_id = CRM_Core_Config::domainID();
$dao->created_date = date('YmdHis');
$dao->is_domain = 0;
$dao->save();
}
$dao->free();
// Do the regular upgrade
$upgrade = new CRM_Upgrade_Form();
$upgrade->processSQL($rev);
}
/**
* @param $rev
*/
public function upgrade_4_1_beta1($rev) {
//CRM-9311
$groupNames = array('directory_preferences', 'url_preferences');
foreach ($groupNames as $groupName) {
CRM_Core_OptionGroup::deleteAssoc($groupName);
}
$domainCols = array(
CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME => array(
'contact_ajax_check_similar',
'activity_assignee_notification',
),
CRM_Core_BAO_Setting::CAMPAIGN_PREFERENCES_NAME => array(
'tag_unconfirmed',
'petition_contacts',
),
CRM_Core_BAO_Setting::EVENT_PREFERENCES_NAME => array(
'enable_cart',
),
CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME => array(
'profile_double_optin',
'profile_add_to_group_double_optin',
'track_civimail_replies',
'civimail_workflow',
'civimail_server_wide_lock',
),
CRM_Core_BAO_Setting::MEMBER_PREFERENCES_NAME => array(
'default_renewal_contribution_page',
),
CRM_Core_BAO_Setting::MULTISITE_PREFERENCES_NAME => array(
'is_enabled',
'uniq_email_per_site',
'domain_group_id',
'event_price_set_domain_id',
),
CRM_Core_BAO_Setting::DIRECTORY_PREFERENCES_NAME => array(
'uploadDir',
'imageUploadDir',
'customFileUploadDir',
'customTemplateDir',
'customPHPPathDir',
'extensionsDir',
),
CRM_Core_BAO_Setting::URL_PREFERENCES_NAME => array(
'userFrameworkResourceURL',
'imageUploadURL',
'customCSSURL',
),
);
$arrGroupNames = array_keys($domainCols);
$groupNames = implode("','", $arrGroupNames);
$arrNames = array();
foreach ($domainCols as $groupName => $names) {
$arrNames[] = implode("','", $names);
}
$name = implode("','", $arrNames);
$sql = "
update civicrm_setting set is_domain = 1 where is_domain = 0 and group_name in ( '{$groupNames}' ) and name in ('{$name}')";
CRM_Core_DAO::executeQuery($sql);
$upgrade = new CRM_Upgrade_Form();
$upgrade->assign('addWightForActivity', !(CRM_Core_DAO::checkFieldExists('civicrm_activity', 'weight')));
$upgrade->processSQL($rev);
}
/**
* @param $rev
*/
public function upgrade_4_1_1($rev) {
$upgrade = new CRM_Upgrade_Form();
$upgrade->assign('addDedupeEmail', !(CRM_Core_DAO::checkFieldExists('civicrm_mailing', 'dedupe_email')));
$sql = "SELECT id FROM civicrm_worldregion LIMIT 1";
$upgrade->assign('worldRegionEmpty', !CRM_Core_DAO::singleValueQuery($sql));
$upgrade->processSQL($rev);
}
/**
* @return string
*/
public function getTemplateMessage() {
return "Blah";
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,201 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7.alpha1 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* Upgrade logic for 4.6
*/
class CRM_Upgrade_Incremental_php_FourSix extends CRM_Upgrade_Incremental_Base {
/**
* Compute any messages which should be displayed after upgrade.
*
* @param string $postUpgradeMessage
* alterable.
* @param string $rev
* an intermediate version; note that setPostUpgradeMessage is called repeatedly with different $revs.
*/
public function setPostUpgradeMessage(&$postUpgradeMessage, $rev) {
if ($rev == '4.6.alpha1') {
$postUpgradeMessage .= '<br /><br />' . ts('Default versions of the following System Workflow Message Templates have been modified to handle new functionality: <ul><li>Events - Registration Confirmation and Receipt (on-line)</li><li>Events - Registration Confirmation and Receipt (off-line)</li><li>Contributions - Receipt (on-line)</li><li>Contributions - Receipt (off-line)</li><li>Memberships - Receipt (on-line)</li><li>Memberships - Signup and Renewal Receipts (off-line)</li></ul> If you have modified these templates, please review the new default versions and implement updates as needed to your copies (Administer > Communications > Message Templates > System Workflow Messages).');
}
if ($rev == '4.6.alpha3') {
$postUpgradeMessage .= '<br /><br />' . ts('A new permission has been added for editing message templates. Previously, users needed the "administer CiviCRM" permission. Now, users need the new permission called "edit message templates." Please check your CMS permissions to ensure that users who should be able to edit message templates are assigned this new permission.');
}
}
/**
* CRM-16846 - This function incorrectly omits running the 4.6.alpha3 sql file.
*
* Instead of correcting it here (which would not run again for sites already on 4.6),
* the file is re-run conditionally during 4.6.6
* @see upgrade_4_6_6
*
* @param string $rev
*/
public function upgrade_4_6_alpha3($rev) {
// Task to process sql.
$this->addTask('Add and update reference_date column for Schedule Reminders', 'updateReferenceDate');
}
/**
* Add new column reference_date to civicrm_action_log in order to track.
*
* CRM-15728, actual action_start_date for membership entity for only those schedule reminders which are not repeatable
*
* @param \CRM_Queue_TaskContext $ctx
*
* @return bool
*/
public static function updateReferenceDate(CRM_Queue_TaskContext $ctx) {
//Add column civicrm_action_log.reference_date if not exists.
$sql = "SELECT count(*) FROM information_schema.columns WHERE table_schema = database() AND table_name = 'civicrm_action_log' AND COLUMN_NAME = 'reference_date' ";
$res = CRM_Core_DAO::singleValueQuery($sql);
if ($res <= 0) {
$query = "ALTER TABLE `civicrm_action_log`
ADD COLUMN `reference_date` date COMMENT 'Stores the date from the entity which triggered this reminder action (e.g. membership.end_date for most membership renewal reminders)'";
CRM_Core_DAO::executeQuery($query);
}
//Retrieve schedule reminders for membership entity and is not repeatable and no absolute date chosen.
$query = "SELECT schedule.* FROM civicrm_action_schedule schedule
INNER JOIN civicrm_action_mapping mapper ON mapper.id = schedule.mapping_id AND
mapper.entity = 'civicrm_membership' AND
schedule.is_repeat = 0 AND
schedule.start_action_date IS NOT NULL";
// construct basic where clauses
$where = array(
'reminder.action_date_time >= DATE_SUB(reminder.action_date_time, INTERVAL 9 MONTH)',
); //choose reminder older then 9 months
$dao = CRM_Core_DAO::executeQuery($query);
while ($dao->fetch()) {
$referenceColumn = str_replace('membership_', "m.", $dao->start_action_date);
$value = implode(', ', explode(CRM_Core_DAO::VALUE_SEPARATOR, trim($dao->entity_value, CRM_Core_DAO::VALUE_SEPARATOR)));
if (!empty($value)) {
$where[] = "m.membership_type_id IN ({$value})";
}
else {
$where[] = "m.membership_type_id IS NULL";
}
//Create new action_log records where action_start_date changes and exclude reminders for additional contacts
//and select contacts are active
$sql = "UPDATE civicrm_action_log reminder
LEFT JOIN civicrm_membership m
ON reminder.entity_id = m.id AND
reminder.entity_table = 'civicrm_membership' AND
( m.is_override IS NULL OR m.is_override = 0 )
INNER JOIN civicrm_contact c
ON c.id = m.contact_id AND
c.is_deleted = 0 AND c.is_deceased = 0
SET reminder.reference_date = {$referenceColumn}
WHERE " . implode(" AND ", $where);
CRM_Core_DAO::executeQuery($sql);
}
return TRUE;
}
/**
* Upgrade function.
*
* @param string $rev
*/
public function upgrade_4_6_1($rev) {
// CRM-16289 - Fix invalid data in log_civicrm_case.case_type_id.
$this->addTask('Cleanup case type id data in log table.', 'fixCaseLog');
}
/**
* Upgrade function.
*
* @param string $rev
*/
public function upgrade_4_6_6($rev) {
// CRM-16846 - This sql file may have been previously skipped. Conditionally run it again if it doesn't appear to have run before.
if (!CRM_Core_DAO::singleValueQuery("SELECT id FROM civicrm_state_province WHERE abbreviation = '100' AND country_id = 1193")) {
$this->addTask('Update Slovenian municipalities', 'task_4_6_x_runOnlySql', '4.6.alpha3');
}
// CRM-16846 - This sql file may have been previously skipped. No harm in running it again because it's just UPDATE statements.
$this->addTask('State-province update from 4.4.7', 'task_4_6_x_runOnlySql', '4.4.7');
$this->addTask(ts('Upgrade DB to %1: SQL', array(1 => $rev)), 'runSql', $rev);
}
/**
* Remove special characters from case_type_id column in log_civicrm_case.
*
* CRM-16289 - If logging enabled and upgrading from 4.4 or earlier, log_civicrm_case.case_type_id will contain special characters.
* This will cause ALTER TABLE to fail when changing this column to an INT
*
* @param \CRM_Queue_TaskContext $ctx
*
* @return bool
*/
public static function fixCaseLog(CRM_Queue_TaskContext $ctx) {
$sql = "SELECT count(*) FROM information_schema.columns WHERE table_schema = database() AND table_name = 'log_civicrm_case'";
$res = CRM_Core_DAO::singleValueQuery($sql);
if ($res) {
// executeQuery doesn't like running multiple engine changes in one pass, so have to break it up. dgg
$query = "ALTER TABLE `log_civicrm_case` ENGINE = InnoDB;";
CRM_Core_DAO::executeQuery($query);
$query = "UPDATE log_civicrm_case SET case_type_id = replace(case_type_id, 0x01, '');";
CRM_Core_DAO::executeQuery($query);
$query = "ALTER TABLE `log_civicrm_case` ENGINE = ARCHIVE;";
CRM_Core_DAO::executeQuery($query);
$query = "ALTER TABLE log_civicrm_case MODIFY `case_type_id` int(10) unsigned DEFAULT NULL COMMENT 'FK to civicrm_case_type.id';";
CRM_Core_DAO::executeQuery($query);
}
return TRUE;
}
/**
* Queue Task Callback for CRM-16846
*
* Run a sql file without resetting locale to that version
*
* @param \CRM_Queue_TaskContext $ctx
* @param string $rev
*
* @return bool
*/
public static function task_4_6_x_runOnlySql(CRM_Queue_TaskContext $ctx, $rev) {
$upgrade = new CRM_Upgrade_Form();
$smarty = CRM_Core_Smarty::singleton();
$smarty->assign('domainID', CRM_Core_Config::domainID());
$fileName = dirname(__DIR__) . "/sql/$rev.mysql.tpl";
$upgrade->source($smarty->fetch($fileName), TRUE);
return TRUE;
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,948 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* Upgrade logic for 4.2
*/
class CRM_Upgrade_Incremental_php_FourTwo extends CRM_Upgrade_Incremental_Base {
const SETTINGS_SNIPPET_PATTERN = '/CRM_Core_ClassLoader::singleton\(\)-\>register/';
const SETTINGS_SNIPPET = "\nrequire_once 'CRM/Core/ClassLoader.php';\nCRM_Core_ClassLoader::singleton()->register();\n";
/**
* Compute any messages which should be displayed beforeupgrade.
*
* Note: This function is called iteratively for each upcoming
* revision to the database.
*
* @param string $preUpgradeMessage
* @param string $rev
* a version number, e.g. '4.2.alpha1', '4.2.beta3', '4.2.0'.
* @param null $currentVer
*
* @return bool
*/
public function setPreUpgradeMessage(&$preUpgradeMessage, $rev, $currentVer = NULL) {
if ($rev == '4.2.alpha1') {
$tables = array('civicrm_contribution_page', 'civicrm_event', 'civicrm_group', 'civicrm_contact');
if (!CRM_Core_DAO::schemaRequiresRebuilding($tables)) {
$errors = "The upgrade has identified some schema integrity issues in the database. It seems some of your constraints are missing. You will have to rebuild your schema before re-trying the upgrade. Please refer to " . CRM_Utils_System::docURL2("Ensuring Schema Integrity on Upgrades", FALSE, "Ensuring Schema Integrity on Upgrades", NULL, NULL, "wiki");
CRM_Core_Error::fatal($errors);
return FALSE;
}
// CRM-10613, CRM-11120
$query = "
SELECT mp.contribution_id, mp.membership_id, mem.membership_type_id, mem.start_date, mem.end_date, mem.status_id, mem.contact_id
FROM civicrm_membership_payment mp
INNER JOIN ( SELECT cmp.contribution_id
FROM civicrm_membership_payment cmp
LEFT JOIN civicrm_line_item cli ON cmp.contribution_id=cli.entity_id and cli.entity_table = 'civicrm_contribution'
WHERE cli.entity_id IS NULL
GROUP BY cmp.contribution_id
HAVING COUNT(cmp.membership_id) > 1) submp ON submp.contribution_id = mp.contribution_id
INNER JOIN civicrm_membership mem ON mem.id = mp.membership_id
ORDER BY mp.contribution_id, mp.membership_id";
$invalidData = CRM_Core_DAO::executeQuery($query);
if ($invalidData->N) {
$invalidDataMessage = "<br /><strong>" . 'The upgrade is being aborted due to data integrity issues in your database. There are multiple membership records linked to the same contribution record. This is unexpected, and some of the membership records may be duplicates. The problem record sets are listed below. Refer to <a href="http://wiki.civicrm.org/confluence/display/CRMDOC42/Repair+database+script+for+4.2+upgrades">this wiki page for instructions on repairing your database</a> so that you can run the upgrade successfully.' . "</strong>";
$membershipType = CRM_Member_PseudoConstant::membershipType();
$membershipStatus = CRM_Member_PseudoConstant::membershipStatus();
$invalidDataMessage .= "<table border=1><tr><th>Contact-ID</th><th>Contribution-ID</th><th>Membership-ID</th><th>Membership Type</th><th>Start Date</th><th>End Date</th><th>Membership Status</th></tr>";
while ($invalidData->fetch()) {
$invalidDataMessage .= "<tr>";
$invalidDataMessage .= "<td>{$invalidData->contact_id}</td>";
$invalidDataMessage .= "<td>{$invalidData->contribution_id}</td>";
$invalidDataMessage .= "<td>{$invalidData->membership_id}</td>";
$invalidDataMessage .= "<td>" . CRM_Utils_Array::value($invalidData->membership_type_id, $membershipType) . "</td>";
$invalidDataMessage .= "<td>{$invalidData->start_date}</td>";
$invalidDataMessage .= "<td>{$invalidData->end_date}</td>";
$invalidDataMessage .= "<td>" . CRM_Utils_Array::value($invalidData->status_id, $membershipStatus) . "</td>";
$invalidDataMessage .= "</tr>";
}
$clickHere = CRM_Utils_System::url('civicrm/upgrade/cleanup425', 'reset=1');
$invalidDataMessage .= "</table><p>If you have reviewed the cleanup script documentation on the wiki and you are ready to run the cleanup now - <a href='$clickHere'>click here</a>.</p>";
CRM_Core_Error::fatal($invalidDataMessage);
return FALSE;
}
}
if ($rev == '4.2.beta2') {
// note: error conditions are also checked in upgrade_4_2_beta2()
if (!defined('CIVICRM_SETTINGS_PATH')) {
$preUpgradeMessage .= '<br />' . ts('Could not determine path to civicrm.settings.php. Please manually locate it and add these lines at the bottom: <pre>%1</pre>', array(
1 => self::SETTINGS_SNIPPET,
));
}
elseif (preg_match(self::SETTINGS_SNIPPET_PATTERN, file_get_contents(CIVICRM_SETTINGS_PATH))) {
// OK, nothing to do
}
elseif (!is_writable(CIVICRM_SETTINGS_PATH)) {
$preUpgradeMessage .= '<br />' . ts('The settings file (%1) must be updated. Please make it writable or manually add these lines:<pre>%2</pre>', array(
1 => CIVICRM_SETTINGS_PATH,
2 => self::SETTINGS_SNIPPET,
));
}
}
if ($rev == '4.2.2' && version_compare($currentVer, '3.3.alpha1') >= 0) {
$query = " SELECT cli.id
FROM `civicrm_line_item` cli
INNER JOIN civicrm_membership_payment cmp ON cmp.contribution_id = cli.entity_id AND cli.entity_table = 'civicrm_contribution'
INNER JOIN civicrm_price_field_value cpfv ON cpfv.id = cli.price_field_value_id
INNER JOIN civicrm_price_field cpf ON cpf.id = cpfv.price_field_id and cpf.id != cli.price_field_id
INNER JOIN civicrm_price_set cps ON cps.id = cpf.price_set_id AND cps.name <>'default_membership_type_amount' ";
$dao = CRM_Core_DAO::executeQuery($query);
if ($dao->N) {
$preUpgradeMessage .= "<br /><strong>We have identified extraneous data in your database that a previous upgrade likely introduced. We STRONGLY recommend making a backup of your site before continuing. We also STRONGLY suggest fixing this issue with unneeded records BEFORE you upgrade. You can find more information about this issue and the way to fix it by visiting <a href='http://forum.civicrm.org/index.php/topic,26181.0.html'>http://forum.civicrm.org/index.php/topic,26181.0.html</a>.</strong>";
}
}
if (version_compare($rev, '4.2.9') >= 0) {
//CRM-11980
$sql = "SELECT id FROM civicrm_option_group WHERE name LIKE 'civicrm_price_field.amount.%' LIMIT 1";
$dao = CRM_Core_DAO::executeQuery($sql);
if ($dao->fetch()) {
$errors = "We found unexpected data values from an older version of CiviCRM in your database. The upgrade can not be run until this condition is corrected.<br /><br />Details: One or more rows are present in the civicrm_option_group with name like 'civicrm_price_field.amount.%'. <a href='http://forum.civicrm.org/index.php/topic,27744.msg118748.html#msg118748'>Check here for information on diagnosing and correcting this problem.</a>";
CRM_Core_Error::fatal($errors);
return FALSE;
}
}
}
/**
* Compute any messages which should be displayed after upgrade.
*
* @param string $postUpgradeMessage
* alterable.
* @param string $rev
* an intermediate version; note that setPostUpgradeMessage is called repeatedly with different $revs.
*/
public function setPostUpgradeMessage(&$postUpgradeMessage, $rev) {
if ($rev == '4.2.beta5') {
$config = CRM_Core_Config::singleton();
if (!empty($config->extensionsDir)) {
$postUpgradeMessage .= '<br />' . ts('Please <a href="%1" target="_blank">configure the Extension Resource URL</a>.', array(
1 => CRM_Utils_System::url('civicrm/admin/setting/url', 'reset=1'),
));
}
}
if ($rev == '4.2.7') {
$postUpgradeMessage .= '<br />' . ts('If you have configured a report instance to allow anonymous access, you will need to reset the permission to Everyone for that instance (under the Report Settings pane).');
}
}
/**
* @param $rev
*/
public function upgrade_4_2_alpha1($rev) {
//checking whether the foreign key exists before dropping it
//drop foreign key queries of CRM-9850
$params = array();
$tables = array(
'civicrm_contribution_page' => 'FK_civicrm_contribution_page_payment_processor_id',
'civicrm_event' => 'FK_civicrm_event_payment_processor_id',
'civicrm_group' => 'FK_civicrm_group_saved_search_id',
);
foreach ($tables as $tableName => $fKey) {
$foreignKeyExists = CRM_Core_DAO::checkConstraintExists($tableName, $fKey);
if ($foreignKeyExists) {
CRM_Core_DAO::executeQuery("ALTER TABLE {$tableName} DROP FOREIGN KEY {$fKey}", $params, TRUE, NULL, FALSE, FALSE);
CRM_Core_DAO::executeQuery("ALTER TABLE {$tableName} DROP INDEX {$fKey}", $params, TRUE, NULL, FALSE, FALSE);
}
}
// Drop index UI_title for civicrm_price_set
$domain = new CRM_Core_DAO_Domain();
$domain->find(TRUE);
if ($domain->locales) {
$locales = explode(CRM_Core_DAO::VALUE_SEPARATOR, $domain->locales);
foreach ($locales as $locale) {
$query = "SHOW KEYS FROM `civicrm_price_set` WHERE key_name = 'UI_title_{$locale}'";
$dao = CRM_Core_DAO::executeQuery($query, $params, TRUE, NULL, FALSE, FALSE);
if ($dao->N) {
CRM_Core_DAO::executeQuery("ALTER TABLE `civicrm_price_set` DROP INDEX `UI_title_{$locale}`", $params, TRUE, NULL, FALSE, FALSE);
}
}
}
else {
$query = "SHOW KEYS FROM `civicrm_price_set` WHERE key_name = 'UI_title'";
$dao = CRM_Core_DAO::executeQuery($query);
if ($dao->N) {
CRM_Core_DAO::executeQuery("ALTER TABLE `civicrm_price_set` DROP INDEX `UI_title`");
}
}
// Some steps take a long time, so we break them up into separate
// tasks and enqueue them separately.
$this->addTask(ts('Upgrade DB to %1: SQL', array(1 => '4.2.alpha1')), 'runSql', $rev);
$this->addTask('Upgrade DB to 4.2.alpha1: Price Sets', 'task_4_2_alpha1_createPriceSets', $rev);
self::convertContribution();
$this->addTask('Upgrade DB to 4.2.alpha1: Event Profile', 'task_4_2_alpha1_eventProfile');
}
/**
* @param $rev
*/
public function upgrade_4_2_beta2($rev) {
// note: error conditions are also checked in setPreUpgradeMessage()
if (defined('CIVICRM_SETTINGS_PATH')) {
if (!preg_match(self::SETTINGS_SNIPPET_PATTERN, file_get_contents(CIVICRM_SETTINGS_PATH))) {
if (is_writable(CIVICRM_SETTINGS_PATH)) {
file_put_contents(CIVICRM_SETTINGS_PATH, self::SETTINGS_SNIPPET, FILE_APPEND);
}
}
}
}
/**
* @param $rev
*/
public function upgrade_4_2_beta3($rev) {
$this->addTask(ts('Upgrade DB to %1: SQL', array(1 => '4.2.beta3')), 'runSql', $rev);
$minParticipantId = CRM_Core_DAO::singleValueQuery('SELECT coalesce(min(id),0) FROM civicrm_participant');
$maxParticipantId = CRM_Core_DAO::singleValueQuery('SELECT coalesce(max(id),0) FROM civicrm_participant');
for ($startId = $minParticipantId; $startId <= $maxParticipantId; $startId += self::BATCH_SIZE) {
$endId = $startId + self::BATCH_SIZE - 1;
$title = "Upgrade DB to 4.2.alpha1: Participant ($startId => $endId)";
$this->addTask($title, 'task_4_2_alpha1_convertParticipants', $startId, $endId);
}
}
/**
* @param $rev
*/
public function upgrade_4_2_beta5($rev) {
// CRM-10629 Create a setting for extension URLs
// For some reason, this isn't working when placed in the .sql file
CRM_Core_DAO::executeQuery("
INSERT INTO civicrm_setting(group_name,name,value,domain_id,is_domain)
VALUES ('URL Preferences', 'extensionsURL',NULL,1,1);
");
}
/**
* @param $rev
*/
public function upgrade_4_2_0($rev) {
$this->addTask(ts('Upgrade DB to %1: SQL', array(1 => '4.2.0')), 'runSql', $rev);
}
/**
* @param $rev
*/
public function upgrade_4_2_2($rev) {
$this->addTask(ts('Upgrade DB to %1: SQL', array(1 => '4.2.2')), 'runSql', $rev);
//create line items for memberships and participants for api/import
self::convertContribution();
// CRM-10937 Fix the title on civicrm_dedupe_rule_group
$upgrade = new CRM_Upgrade_Form();
if ($upgrade->multilingual) {
// Check if the 'title' field exists
$query = "SELECT column_name
FROM information_schema.COLUMNS
WHERE table_name = 'civicrm_dedupe_rule_group'
AND table_schema = DATABASE()
AND column_name = 'title'";
$dao = CRM_Core_DAO::executeQuery($query);
if (!$dao->N) {
$domain = new CRM_Core_DAO_Domain();
$domain->find(TRUE);
if ($domain->locales) {
$locales = explode(CRM_Core_DAO::VALUE_SEPARATOR, $domain->locales);
$locale = array_shift($locales);
// Use the first language (they should all have the same value)
CRM_Core_DAO::executeQuery("ALTER TABLE `civicrm_dedupe_rule_group` CHANGE `title_{$locale}` `title` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'Label of the rule group'", $params, TRUE, NULL, FALSE, FALSE);
// Drop remaining the column for the remaining languages
foreach ($locales as $locale) {
CRM_Core_DAO::executeQuery("ALTER TABLE `civicrm_dedupe_rule_group` DROP `title_{$locale}`", $params, TRUE, NULL, FALSE, FALSE);
}
}
}
}
}
/**
* @param $rev
*/
public function upgrade_4_2_3($rev) {
$this->addTask(ts('Upgrade DB to %1: SQL', array(1 => '4.2.3')), 'runSql', $rev);
// CRM-10953 Remove duplicate activity type for 'Reminder Sent' which is mistakenly inserted by 4.2.alpha1 upgrade script
$queryMin = "
SELECT coalesce(min(value),0) from civicrm_option_value ov
WHERE ov.option_group_id =
(SELECT id from civicrm_option_group og WHERE og.name = 'activity_type') AND
ov.name = 'Reminder Sent'";
$minReminderSent = CRM_Core_DAO::singleValueQuery($queryMin);
$queryMax = "
SELECT coalesce(max(value),0) from civicrm_option_value ov
WHERE ov.option_group_id =
(SELECT id from civicrm_option_group og WHERE og.name = 'activity_type') AND
ov.name = 'Reminder Sent'";
$maxReminderSent = CRM_Core_DAO::singleValueQuery($queryMax);
// If we have two different values, replace new value with original in any activities
if ($maxReminderSent > $minReminderSent) {
$query = "
UPDATE civicrm_activity
SET activity_type_id = {$minReminderSent}
WHERE activity_type_id = {$maxReminderSent}";
CRM_Core_DAO::executeQuery($query);
// Then delete the newer (duplicate) option_value row
$query = "
DELETE from civicrm_option_value
WHERE option_group_id =
(SELECT id from civicrm_option_group og WHERE og.name = 'activity_type') AND
value = '{$maxReminderSent}'";
CRM_Core_DAO::executeQuery($query);
}
}
/**
* @param $rev
*/
public function upgrade_4_2_5($rev) {
$this->addTask(ts('Upgrade DB to %1: SQL', array(1 => '4.2.5')), 'runSql', $rev);
//CRM-11077
$sql = " SELECT cpse.entity_id, cpse.price_set_id
FROM `civicrm_price_set_entity` cpse
LEFT JOIN civicrm_price_set cps ON cps.id = cpse.price_set_id
LEFT JOIN civicrm_price_set_entity cpse1 ON cpse1.price_set_id = cpse.price_set_id
WHERE cpse.entity_table = 'civicrm_event' AND cps.is_quick_config = 1
GROUP BY cpse.id
HAVING COUNT(cpse.price_set_id) > 1 AND MIN(cpse1.id) <> cpse.id ";
$dao = CRM_Core_DAO::executeQuery($sql);
while ($dao->fetch()) {
if ($dao->price_set_id) {
$copyPriceSet = &CRM_Upgrade_Snapshot_V4p2_Price_BAO_Set::copy($dao->price_set_id);
CRM_Upgrade_Snapshot_V4p2_Price_BAO_Set::addTo('civicrm_event', $dao->entity_id, $copyPriceSet->id);
}
}
}
public function convertContribution() {
$minContributionId = CRM_Core_DAO::singleValueQuery('SELECT coalesce(min(id),0) FROM civicrm_contribution');
$maxContributionId = CRM_Core_DAO::singleValueQuery('SELECT coalesce(max(id),0) FROM civicrm_contribution');
for ($startId = $minContributionId; $startId <= $maxContributionId; $startId += self::BATCH_SIZE) {
$endId = $startId + self::BATCH_SIZE - 1;
$title = "Upgrade DB to 4.2.alpha1: Contributions ($startId => $endId)";
$this->addTask($title, 'task_4_2_alpha1_convertContributions', $startId, $endId);
}
$minParticipantId = CRM_Core_DAO::singleValueQuery('SELECT coalesce(min(id),0) FROM civicrm_participant');
$maxParticipantId = CRM_Core_DAO::singleValueQuery('SELECT coalesce(max(id),0) FROM civicrm_participant');
for ($startId = $minParticipantId; $startId <= $maxParticipantId; $startId += self::BATCH_SIZE) {
$endId = $startId + self::BATCH_SIZE - 1;
$title = "Upgrade DB to 4.2.alpha1: Participant ($startId => $endId)";
$this->addTask($title, 'task_4_2_alpha1_convertParticipants', $startId, $endId);
}
}
/**
* (Queue Task Callback)
*
* Upgrade code to create priceset for contribution pages and events
*
* @param \CRM_Queue_TaskContext $ctx
* @param string $rev
*
* @return bool
*/
public static function task_4_2_alpha1_createPriceSets(CRM_Queue_TaskContext $ctx, $rev) {
$upgrade = new CRM_Upgrade_Form();
$daoName = array(
'civicrm_contribution_page' => array(
'CRM_Contribute_BAO_ContributionPage',
CRM_Core_Component::getComponentID('CiviContribute'),
),
'civicrm_event' => array(
'CRM_Event_BAO_Event',
CRM_Core_Component::getComponentID('CiviEvent'),
),
);
// get all option group used for event and contribution page
$query = "
SELECT id, name
FROM civicrm_option_group
WHERE name LIKE '%.amount.%' ";
$dao = CRM_Core_DAO::executeQuery($query);
while ($dao->fetch()) {
$addTo = explode('.', $dao->name);
if (!empty($addTo[2])) {
$options = array('optionGroup' => $dao->name);
self::createPriceSet($daoName, $addTo, $options);
}
CRM_Core_OptionGroup::deleteAssoc($dao->name);
}
//create pricesets for contribution with only other amount
$query = "
SELECT ccp.id as contribution_page_id, ccp.is_allow_other_amount, cmb.id as membership_block_id
FROM civicrm_contribution_page ccp
LEFT JOIN civicrm_membership_block cmb ON cmb.entity_id = ccp.id AND cmb.entity_table = 'civicrm_contribution_page'
LEFT JOIN civicrm_price_set_entity cpse ON cpse.entity_id = ccp.id and cpse.entity_table = 'civicrm_contribution_page'
WHERE cpse.price_set_id IS NULL";
$dao = CRM_Core_DAO::executeQuery($query);
$addTo = array('civicrm_contribution_page');
while ($dao->fetch()) {
$addTo[2] = $dao->contribution_page_id;
$options = array(
'otherAmount' => $dao->is_allow_other_amount,
'membership' => $dao->membership_block_id,
);
self::createPriceSet($daoName, $addTo, $options);
}
return TRUE;
}
/**
* Create price sets.
*
* @param string $daoName
* @param string $addTo
* @param array $options
*/
public static function createPriceSet($daoName, $addTo, $options = array()) {
$query = "SELECT title FROM {$addTo[0]} where id =%1";
$setParams['title'] = CRM_Core_DAO::singleValueQuery($query,
array(1 => array($addTo[2], 'Integer'))
);
$pageTitle = strtolower(CRM_Utils_String::munge($setParams['title'], '_', 245));
// an event or contrib page has been deleted but left the option group behind - (this may be fixed in later versions?)
// we should probably delete the option group - but at least early exit here as the code following it does not fatal
// CRM-10298
if (empty($pageTitle)) {
return;
}
$optionValue = array();
if (!empty($options['optionGroup'])) {
CRM_Core_OptionGroup::getAssoc($options['optionGroup'], $optionValue);
if (empty($optionValue)) {
return;
}
}
elseif (empty($options['otherAmount']) && empty($options['membership'])) {
//CRM-12273
//if options group, otherAmount, membersip is empty then return, contribution should be default price set
return;
}
if (!CRM_Core_DAO::getFieldValue('CRM_Upgrade_Snapshot_V4p2_Price_BAO_Set', $pageTitle, 'id', 'name', TRUE)) {
$setParams['name'] = $pageTitle;
}
else {
$timeSec = explode(".", microtime(TRUE));
$setParams['name'] = $pageTitle . '_' . date('is', $timeSec[0]) . $timeSec[1];
}
$setParams['extends'] = $daoName[$addTo[0]][1];
$setParams['is_quick_config'] = 1;
$priceSet = CRM_Upgrade_Snapshot_V4p2_Price_BAO_Set::create($setParams);
CRM_Upgrade_Snapshot_V4p2_Price_BAO_Set::addTo($addTo[0], $addTo[2], $priceSet->id, 1);
$fieldParams['price_set_id'] = $priceSet->id;
if (!empty($options['optionGroup'])) {
$fieldParams['html_type'] = 'Radio';
$fieldParams['is_required'] = 1;
if ($addTo[0] == 'civicrm_event') {
$query = "SELECT fee_label FROM civicrm_event where id =%1";
$fieldParams['name'] = $fieldParams['label'] = CRM_Core_DAO::singleValueQuery($query,
array(1 => array($addTo[2], 'Integer'))
);
$defaultAmountColumn = 'default_fee_id';
}
else {
$options['membership'] = 1;
$fieldParams['name'] = strtolower(CRM_Utils_String::munge("Contribution Amount", '_', 245));
$fieldParams['label'] = "Contribution Amount";
$defaultAmountColumn = 'default_amount_id';
$options['otherAmount'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionPage', $addTo[2], 'is_allow_other_amount');
if (!empty($options['otherAmount'])) {
$fieldParams['is_required'] = 0;
}
}
$fieldParams['option_label'] = $optionValue['label'];
$fieldParams['option_amount'] = $optionValue['value'];
$fieldParams['option_weight'] = $optionValue['weight'];
$fieldParams['is_quick_config'] = $setParams['is_quick_config'];
if ($defaultAmount = CRM_Core_DAO::getFieldValue($daoName[$addTo[0]][0], $addTo[2], $defaultAmountColumn)) {
$fieldParams['default_option'] = array_search($defaultAmount, $optionValue['amount_id']);
}
$priceField = CRM_Upgrade_Snapshot_V4p2_Price_BAO_Field::create($fieldParams);
}
if (!empty($options['membership'])) {
$dao = new CRM_Member_DAO_MembershipBlock();
$dao->entity_table = 'civicrm_contribution_page';
$dao->entity_id = $addTo[2];
if ($dao->find(TRUE)) {
if ($dao->membership_types) {
$fieldParams = array(
'name' => strtolower(CRM_Utils_String::munge("Membership Amount", '_', 245)),
'label' => "Membership Amount",
'is_required' => $dao->is_required,
'is_display_amounts' => $dao->display_min_fee,
'is_active' => $dao->is_active,
'price_set_id' => $priceSet->id,
'html_type' => 'Radio',
'weight' => 1,
);
$membershipTypes = unserialize($dao->membership_types);
$rowcount = 0;
foreach ($membershipTypes as $membershipType => $autoRenew) {
$membershipTypeDetail = CRM_Member_BAO_MembershipType::getMembershipTypeDetails($membershipType);
$rowcount++;
$fieldParams['option_label'][$rowcount] = $membershipTypeDetail['name'];
$fieldParams['option_amount'][$rowcount] = $membershipTypeDetail['minimum_fee'];
$fieldParams['option_weight'][$rowcount] = $rowcount;
$fieldParams['membership_type_id'][$rowcount] = $membershipType;
if ($membershipType == $dao->membership_type_default) {
$fieldParams['default_option'] = $rowcount;
}
}
$priceField = CRM_Upgrade_Snapshot_V4p2_Price_BAO_Field::create($fieldParams);
$setParams = array(
'id' => $priceSet->id,
'extends' => CRM_Core_Component::getComponentID('CiviMember'),
'contribution_type_id' => CRM_Core_DAO::getFieldValue($daoName[$addTo[0]][0], $addTo[2], 'contribution_type_id'),
);
CRM_Upgrade_Snapshot_V4p2_Price_BAO_Set::create($setParams);
}
}
}
if (!empty($options['otherAmount'])) {
$fieldParams = array(
'name' => strtolower(CRM_Utils_String::munge("Other Amount", '_', 245)),
'label' => "Other Amount",
'is_required' => 0,
'is_display_amounts' => 0,
'is_active' => 1,
'price_set_id' => $priceSet->id,
'html_type' => 'Text',
'weight' => 3,
);
$fieldParams['option_label'][1] = "Other Amount";
$fieldParams['option_amount'][1] = 1;
$fieldParams['option_weight'][1] = 1;
$priceField = CRM_Upgrade_Snapshot_V4p2_Price_BAO_Field::create($fieldParams);
}
}
/**
* (Queue Task Callback)
*
* Find any contribution records and create corresponding line-item
* records.
*
* @param CRM_Queue_TaskContext $ctx
* @param int $startId
* the first/lowest contribution ID to convert.
* @param int $endId
* the last/highest contribution ID to convert.
*
* @return bool
*/
public static function task_4_2_alpha1_convertContributions(CRM_Queue_TaskContext $ctx, $startId, $endId) {
$upgrade = new CRM_Upgrade_Form();
$query = "
INSERT INTO civicrm_line_item(`entity_table` ,`entity_id` ,`price_field_id` ,`label` , `qty` ,`unit_price` ,`line_total` ,`participant_count` ,`price_field_value_id`)
SELECT 'civicrm_contribution',cc.id, cpf.id as price_field_id, cpfv.label, 1, cc.total_amount, cc.total_amount line_total, 0, cpfv.id as price_field_value
FROM civicrm_membership_payment cmp
LEFT JOIN `civicrm_contribution` cc ON cc.id = cmp.contribution_id
LEFT JOIN civicrm_line_item cli ON cc.id=cli.entity_id and cli.entity_table = 'civicrm_contribution'
LEFT JOIN civicrm_membership cm ON cm.id=cmp.membership_id
LEFT JOIN civicrm_membership_type cmt ON cmt.id = cm.membership_type_id
LEFT JOIN civicrm_price_field cpf ON BINARY cpf.name = cmt.member_of_contact_id
LEFT JOIN civicrm_price_field_value cpfv ON cpfv.membership_type_id = cm.membership_type_id AND cpf.id = cpfv.price_field_id
WHERE (cc.id BETWEEN %1 AND %2) AND cli.entity_id IS NULL ;
";
$sqlParams = array(
1 => array($startId, 'Integer'),
2 => array($endId, 'Integer'),
);
CRM_Core_DAO::executeQuery($query, $sqlParams);
// create lineitems for contribution done for membership
$sql = "
SELECT cc.id, cmp.membership_id, cpse.price_set_id, cc.total_amount
FROM civicrm_contribution cc
LEFT JOIN civicrm_line_item cli ON cc.id=cli.entity_id AND cli.entity_table = 'civicrm_contribution'
LEFT JOIN civicrm_membership_payment cmp ON cc.id = cmp.contribution_id
LEFT JOIN civicrm_participant_payment cpp ON cc.id = cpp.contribution_id
LEFT JOIN civicrm_price_set_entity cpse on cpse.entity_table = 'civicrm_contribution_page' AND cpse.entity_id = cc.contribution_page_id
WHERE (cc.id BETWEEN %1 AND %2)
AND cli.entity_id IS NULL AND cc.contribution_page_id IS NOT NULL AND cpp.contribution_id IS NULL
GROUP BY cc.id, cmp.membership_id
";
$result = CRM_Core_DAO::executeQuery($sql, $sqlParams);
while ($result->fetch()) {
$sql = "
SELECT cpf.id, cpfv.id as price_field_value_id, cpfv.label, cpfv.amount, cpfv.count
FROM civicrm_price_field cpf
LEFT JOIN civicrm_price_field_value cpfv ON cpf.id = cpfv.price_field_id
WHERE cpf.price_set_id = %1
";
$lineParams = array(
'entity_table' => 'civicrm_contribution',
'entity_id' => $result->id,
);
if ($result->membership_id) {
$sql .= " AND cpf.name = %2 AND cpfv.membership_type_id = %3 ";
$params = array(
'1' => array($result->price_set_id, 'Integer'),
'2' => array('membership_amount', 'String'),
'3' => array(
CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $result->membership_id, 'membership_type_id'),
'Integer',
),
);
$res = CRM_Core_DAO::executeQuery($sql, $params);
if ($res->fetch()) {
$lineParams += array(
'price_field_id' => $res->id,
'label' => $res->label,
'qty' => 1,
'unit_price' => $res->amount,
'line_total' => $res->amount,
'participant_count' => $res->count ? $res->count : 0,
'price_field_value_id' => $res->price_field_value_id,
);
}
else {
$lineParams['price_field_id'] = CRM_Core_DAO::getFieldValue('CRM_Upgrade_Snapshot_V4p2_Price_DAO_Field', $result->price_set_id, 'id', 'price_set_id');
$lineParams['label'] = 'Membership Amount';
$lineParams['qty'] = 1;
$lineParams['unit_price'] = $lineParams['line_total'] = $result->total_amount;
$lineParams['participant_count'] = 0;
}
}
else {
$sql .= "AND cpfv.amount = %2";
//CRM-12273
//check if price_set_id is exist, if not use the default contribution amount
if (isset($result->price_set_id)) {
$priceSetId = $result->price_set_id;
}
else {
$defaultPriceSets = CRM_Price_BAO_PriceSet::getDefaultPriceSet();
foreach ($defaultPriceSets as $key => $pSet) {
if ($pSet['name'] == 'contribution_amount') {
$priceSetId = $pSet['setID'];
}
}
}
$params = array(
'1' => array($priceSetId, 'Integer'),
'2' => array($result->total_amount, 'String'),
);
$res = CRM_Core_DAO::executeQuery($sql, $params);
if ($res->fetch()) {
$lineParams += array(
'price_field_id' => $res->id,
'label' => $res->label,
'qty' => 1,
'unit_price' => $res->amount,
'line_total' => $res->amount,
'participant_count' => $res->count ? $res->count : 0,
'price_field_value_id' => $res->price_field_value_id,
);
}
else {
$params = array(
'price_set_id' => $priceSetId,
'name' => 'other_amount',
);
$defaults = array();
CRM_Upgrade_Snapshot_V4p2_Price_BAO_Field::retrieve($params, $defaults);
if (!empty($defaults)) {
$lineParams['price_field_id'] = $defaults['id'];
$lineParams['label'] = $defaults['label'];
$lineParams['price_field_value_id']
= CRM_Core_DAO::getFieldValue('CRM_Upgrade_Snapshot_V4p2_Price_DAO_FieldValue', $defaults['id'], 'id', 'price_field_id');
}
else {
$lineParams['price_field_id']
= CRM_Core_DAO::getFieldValue('CRM_Upgrade_Snapshot_V4p2_Price_DAO_Field', $priceSetId, 'id', 'price_set_id');
$lineParams['label'] = 'Contribution Amount';
}
$lineParams['qty'] = 1;
$lineParams['participant_count'] = 0;
$lineParams['unit_price'] = $lineParams['line_total'] = $result->total_amount;
}
}
CRM_Upgrade_Snapshot_V4p2_Price_BAO_LineItem::create($lineParams);
}
return TRUE;
}
/**
* (Queue Task Callback)
*
* Find any participant records and create corresponding line-item
* records.
*
* @param CRM_Queue_TaskContext $ctx
* @param int $startId
* the first/lowest participant ID to convert.
* @param int $endId
* the last/highest participant ID to convert.
*
* @return bool
*/
public static function task_4_2_alpha1_convertParticipants(CRM_Queue_TaskContext $ctx, $startId, $endId) {
$upgrade = new CRM_Upgrade_Form();
//create lineitems for participant in edge cases using default price set for contribution.
$query = "
SELECT cp.id as participant_id, cp.fee_amount, cp.fee_level,ce.is_monetary,
cpse.price_set_id, cpf.id as price_field_id, cpfv.id as price_field_value_id
FROM civicrm_participant cp
LEFT JOIN civicrm_line_item cli ON cli.entity_id=cp.id and cli.entity_table = 'civicrm_participant'
LEFT JOIN civicrm_event ce ON ce.id=cp.event_id
LEFT JOIN civicrm_price_set_entity cpse ON cp.event_id = cpse.entity_id and cpse.entity_table = 'civicrm_event'
LEFT JOIN civicrm_price_field cpf ON cpf.price_set_id = cpse.price_set_id
LEFT JOIN civicrm_price_field_value cpfv ON cpfv.price_field_id = cpf.id AND cpfv.label = cp.fee_level
WHERE (cp.id BETWEEN %1 AND %2)
AND cli.entity_id IS NULL AND cp.fee_amount IS NOT NULL";
$sqlParams = array(
1 => array($startId, 'Integer'),
2 => array($endId, 'Integer'),
);
$dao = CRM_Core_DAO::executeQuery($query, $sqlParams);
if ($dao->N) {
$defaultPriceSetId = CRM_Core_DAO::getFieldValue('CRM_Upgrade_Snapshot_V4p2_Price_DAO_Set', 'default_contribution_amount', 'id', 'name');
$priceSets = current(CRM_Upgrade_Snapshot_V4p2_Price_BAO_Set::getSetDetail($defaultPriceSetId));
$fieldID = key($priceSets['fields']);
}
while ($dao->fetch()) {
$lineParams = array(
'entity_table' => 'civicrm_participant',
'entity_id' => $dao->participant_id,
'label' => $dao->fee_level ? $dao->fee_level : ts('Default'),
'qty' => 1,
'unit_price' => $dao->fee_amount,
'line_total' => $dao->fee_amount,
'participant_count' => 1,
);
if ($dao->is_monetary && $dao->price_field_id) {
$lineParams += array(
'price_field_id' => $dao->price_field_id,
'price_field_value_id' => $dao->price_field_value_id,
);
$priceSetId = $dao->price_set_id;
}
else {
$lineParams['price_field_id'] = $fieldID;
$priceSetId = $defaultPriceSetId;
}
CRM_Upgrade_Snapshot_V4p2_Price_BAO_LineItem::create($lineParams);
}
return TRUE;
}
/**
* (Queue Task Callback)
*
* Create an event registration profile with a single email field CRM-9587
*
* @param \CRM_Queue_TaskContext $ctx
*
* @return bool
*/
public static function task_4_2_alpha1_eventProfile(CRM_Queue_TaskContext $ctx) {
$upgrade = new CRM_Upgrade_Form();
$profileTitle = ts('Your Registration Info');
$sql = "
INSERT INTO civicrm_uf_group
(is_active, group_type, title, help_pre, help_post, limit_listings_group_id, post_URL, add_to_group_id, add_captcha, is_map, is_edit_link, is_uf_link, is_update_dupe, cancel_URL, is_cms_user, notify, is_reserved, name, created_id, created_date, is_proximity_search)
VALUES
(1, 'Individual, Contact', %1, NULL, NULL, NULL, NULL, NULL, 0, 0, 0, 0, 0, NULL, 0, NULL, 0, 'event_registration', NULL, NULL, 0);
";
$params = array(
1 => array($profileTitle, 'String'),
);
CRM_Core_DAO::executeQuery($sql, $params);
$eventRegistrationId = CRM_Core_DAO::singleValueQuery('SELECT LAST_INSERT_ID()');
$sql = "
INSERT INTO civicrm_uf_field
(uf_group_id, field_name, is_active, is_view, is_required, weight, help_post, help_pre, visibility, in_selector, is_searchable, location_type_id, phone_type_id, label, field_type, is_reserved)
VALUES
({$eventRegistrationId}, 'email', 1, 0, 1, 1, NULL, NULL, 'User and User Admin Only', 0, 0, NULL, NULL, 'Email Address', 'Contact', 0);
";
CRM_Core_DAO::executeQuery($sql);
$sql = "SELECT * FROM civicrm_event WHERE is_online_registration = 1;";
$events = CRM_Core_DAO::executeQuery($sql);
while ($events->fetch()) {
// Get next weights for the event registration profile
$nextMainWeight = $nextAdditionalWeight = 1;
$sql = "
SELECT weight
FROM civicrm_uf_join
WHERE entity_id = {$events->id} AND module = 'CiviEvent'
ORDER BY weight DESC LIMIT 1";
$weights = CRM_Core_DAO::executeQuery($sql);
$weights->fetch();
if (isset($weights->weight)) {
$nextMainWeight += $weights->weight;
}
$sql = "
SELECT weight
FROM civicrm_uf_join
WHERE entity_id = {$events->id} AND module = 'CiviEvent_Additional'
ORDER BY weight DESC LIMIT 1";
$weights = CRM_Core_DAO::executeQuery($sql);
$weights->fetch();
if (isset($weights->weight)) {
$nextAdditionalWeight += $weights->weight;
}
// Add an event registration profile to the event
$sql = "
INSERT INTO civicrm_uf_join
(is_active, module, entity_table, entity_id, weight, uf_group_id)
VALUES
(1, 'CiviEvent', 'civicrm_event', {$events->id}, {$nextMainWeight}, {$eventRegistrationId});
";
CRM_Core_DAO::executeQuery($sql);
$sql = "
INSERT INTO civicrm_uf_join
(is_active, module, entity_table, entity_id, weight, uf_group_id)
VALUES
(1, 'CiviEvent_Additional', 'civicrm_event', {$events->id}, {$nextAdditionalWeight}, {$eventRegistrationId});";
CRM_Core_DAO::executeQuery($sql);
}
return TRUE;
}
/**
* @return array
*/
public static function deleteInvalidPairs() {
require_once 'CRM/Member/PseudoConstant.php';
require_once 'CRM/Contribute/PseudoConstant.php';
$processedRecords = array();
$tempTableName1 = CRM_Core_DAO::createTempTableName();
// 1. collect all duplicates
$sql = "
CREATE TEMPORARY TABLE {$tempTableName1} SELECT mp.id as payment_id, mp.contribution_id, mp.membership_id, mem.membership_type_id, mem.start_date, mem.end_date, mem.status_id, mem.contact_id, con.contribution_status_id
FROM civicrm_membership_payment mp
INNER JOIN ( SELECT cmp.contribution_id
FROM civicrm_membership_payment cmp
LEFT JOIN civicrm_line_item cli ON cmp.contribution_id=cli.entity_id and cli.entity_table = 'civicrm_contribution'
WHERE cli.entity_id IS NULL
GROUP BY cmp.contribution_id
HAVING COUNT(cmp.membership_id) > 1) submp ON submp.contribution_id = mp.contribution_id
INNER JOIN civicrm_membership mem ON mem.id = mp.membership_id
INNER JOIN civicrm_contribution con ON con.id = mp.contribution_id
ORDER BY mp.contribution_id, mp.membership_id";
$dao = CRM_Core_DAO::executeQuery($sql);
$tempTableName2 = CRM_Core_DAO::createTempTableName();
// 2. collect all records that are going to be retained
$sql = "
CREATE TEMPORARY TABLE {$tempTableName2}
SELECT MAX(payment_id) as payment_id FROM {$tempTableName1} GROUP BY contribution_id HAVING COUNT(*) > 1";
CRM_Core_DAO::executeQuery($sql);
// 3. do the un-linking
$sql = "
DELETE cmp.*
FROM civicrm_membership_payment cmp
INNER JOIN $tempTableName1 temp1 ON temp1.payment_id = cmp.id
LEFT JOIN $tempTableName2 temp2 ON temp1.payment_id = temp2.payment_id
WHERE temp2.payment_id IS NULL";
CRM_Core_DAO::executeQuery($sql);
// 4. show all records that were Processed, i.e Retained vs Un-linked
$sql = "
SELECT temp1.contact_id, temp1.contribution_id, temp1.contribution_status_id, temp1.membership_id, temp1.membership_type_id, temp1.start_date, temp1.end_date, temp1.status_id, temp2.payment_id as retain_id
FROM $tempTableName1 temp1
LEFT JOIN $tempTableName2 temp2 ON temp1.payment_id = temp2.payment_id";
$dao = CRM_Core_DAO::executeQuery($sql);
if ($dao->N) {
$membershipType = CRM_Member_PseudoConstant::membershipType();
$membershipStatus = CRM_Member_PseudoConstant::membershipStatus();
$contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus();
while ($dao->fetch()) {
$status = $dao->retain_id ? 'Retained' : 'Un-linked';
$memType = CRM_Utils_Array::value($dao->membership_type_id, $membershipType);
$memStatus = CRM_Utils_Array::value($dao->status_id, $membershipStatus);
$contribStatus = CRM_Utils_Array::value($dao->contribution_status_id, $contributionStatus);
$processedRecords[] = array(
$dao->contact_id,
$dao->contribution_id,
$contribStatus,
$dao->membership_id,
$memType,
$dao->start_date,
$dao->end_date,
$memStatus,
$status,
);
}
}
if (!empty($processedRecords)) {
CRM_Core_Error::debug_log_message("deleteInvalidPairs() - The following records have been processed. Membership records with action:");
CRM_Core_Error::debug_log_message("Contact ID, ContributionID, Contribution Status, MembershipID, Membership Type, Start Date, End Date, Membership Status, Action");
foreach ($processedRecords as $record) {
CRM_Core_Error::debug_log_message(implode(', ', $record));
}
}
else {
CRM_Core_Error::debug_log_message("deleteInvalidPairs() - Could not find any records to process.");
}
return $processedRecords;
}
}