From 7b9e7b6ec9c22fdd64ac9b9a02fb356b38528968 Mon Sep 17 00:00:00 2001
From: Kevin Cristiano <kcristiano@tadpole.cc>
Date: Fri, 4 May 2018 09:11:24 -0400
Subject: [PATCH] civicrm: v5.1.0 release

Signed-off-by: Kevin Cristiano <kcristiano@tadpole.cc>
---
 .github/CONTRIBUTING.md                       |  20 +
 .github/PULL_REQUEST_TEMPLATE.md              |  19 +
 civicrm.php                                   |   2 +-
 civicrm/CONTRIBUTORS.txt                      |  14 +-
 civicrm/CRM/Activity/Form/Activity.php        |  11 +
 civicrm/CRM/Activity/Form/ActivityView.php    |   9 +
 civicrm/CRM/Admin/Form/ScheduleReminders.php  |   3 +-
 civicrm/CRM/Campaign/Form/Task/Interview.php  |  23 +-
 .../CRM/Contact/BAO/Contact/Permission.php    |  15 +-
 civicrm/CRM/Contact/Form/Edit/Address.php     |   9 +-
 civicrm/CRM/Contact/Form/Merge.php            |   2 +-
 civicrm/CRM/Contact/Form/Search.php           | 190 ++++---
 civicrm/CRM/Contact/Form/Search/Criteria.php  |   1 +
 civicrm/CRM/Contact/Import/Parser/Contact.php |  10 +
 civicrm/CRM/Contact/Page/DedupeFind.php       |   7 +-
 .../CRM/Contribute/BAO/ContributionRecur.php  |   3 +-
 civicrm/CRM/Contribute/Form/Contribution.php  |   1 +
 .../Contribute/Form/Contribution/Confirm.php  |  30 +-
 .../CRM/Contribute/Form/ContributionView.php  |  24 +
 civicrm/CRM/Contribute/Form/Search.php        |   2 +-
 .../Contribute/Form/Task/PDFLetterCommon.php  |  14 +-
 .../Contribute/Form/UpdateSubscription.php    |  17 +-
 .../Contribute/Import/Parser/Contribution.php |  10 +-
 .../CRM/Contribute/Page/ContributionRecur.php |  61 +-
 civicrm/CRM/Contribute/Page/Tab.php           | 107 ++--
 civicrm/CRM/Core/BAO/CustomField.php          |  37 +-
 civicrm/CRM/Core/BAO/CustomGroup.php          |  15 +-
 civicrm/CRM/Core/BAO/CustomOption.php         |   2 +-
 civicrm/CRM/Core/BAO/Email.php                |  17 +-
 civicrm/CRM/Core/BAO/FinancialTrxn.php        |   3 +-
 civicrm/CRM/Core/BAO/PrevNextCache.php        |  11 +-
 civicrm/CRM/Core/BAO/Setting.php              |  15 -
 civicrm/CRM/Core/Form.php                     |  32 +-
 civicrm/CRM/Core/Form/Renderer.php            |   5 +-
 .../CRM/Core/I18n/SchemaStructure_2_2_0.php   |  69 ---
 .../Core/I18n/SchemaStructure_3_0_alpha1.php  | 251 ---------
 .../Core/I18n/SchemaStructure_3_0_beta1.php   | 267 ---------
 .../Core/I18n/SchemaStructure_3_0_beta4.php   | 280 ---------
 .../Core/I18n/SchemaStructure_3_1_alpha1.php  | 284 ----------
 .../Core/I18n/SchemaStructure_3_1_beta2.php   | 287 ----------
 .../Core/I18n/SchemaStructure_3_2_beta4.php   | 288 ----------
 .../Core/I18n/SchemaStructure_3_3_beta1.php   | 296 ----------
 .../CRM/Core/I18n/SchemaStructure_3_4_0.php   | 223 --------
 .../Core/I18n/SchemaStructure_3_4_beta2.php   | 296 ----------
 .../Core/I18n/SchemaStructure_3_4_beta3.php   | 223 --------
 .../CRM/Core/I18n/SchemaStructure_4_1_0.php   | 229 --------
 .../Core/I18n/SchemaStructure_4_1_alpha1.php  | 226 --------
 civicrm/CRM/Core/OptionGroup.php              |   4 +-
 civicrm/CRM/Custom/Form/Option.php            |   2 +
 civicrm/CRM/Custom/Page/AJAX.php              |   1 +
 civicrm/CRM/Dedupe/Merger.php                 |   3 +-
 civicrm/CRM/Event/BAO/Participant.php         |  27 +-
 civicrm/CRM/Export/BAO/Export.php             | 230 ++++----
 .../CRM/Financial/BAO/PaymentProcessor.php    |  20 +
 civicrm/CRM/Financial/Form/FinancialBatch.php |  25 +-
 civicrm/CRM/Group/Form/Edit.php               |   7 +-
 civicrm/CRM/Logging/Schema.php                |  60 +-
 civicrm/CRM/Mailing/BAO/Mailing.php           |   2 +-
 civicrm/CRM/Mailing/BAO/MailingJob.php        |   5 +-
 civicrm/CRM/Member/BAO/Membership.php         | 132 ++++-
 civicrm/CRM/Member/BAO/MembershipType.php     |   2 +
 civicrm/CRM/Member/Form/MembershipType.php    |  11 +-
 civicrm/CRM/Price/BAO/LineItem.php            |   9 +-
 .../Page/MultipleRecordFieldsListing.php      |   2 +-
 civicrm/CRM/Profile/Selector/Listings.php     |   2 +-
 civicrm/CRM/Report/Form.php                   | 108 +++-
 civicrm/CRM/Report/Form/Activity.php          |   2 +-
 civicrm/CRM/Report/Form/ActivitySummary.php   |  14 +-
 .../Report/Form/Campaign/SurveyDetails.php    |  16 +-
 civicrm/CRM/Report/Form/Case/Demographics.php |  14 +-
 civicrm/CRM/Report/Form/Case/Detail.php       |  50 +-
 .../Report/Form/Contact/CurrentEmployer.php   |  16 +-
 civicrm/CRM/Report/Form/Contact/Detail.php    |  33 +-
 civicrm/CRM/Report/Form/Contact/Summary.php   |  33 +-
 .../Report/Form/Contribute/Bookkeeping.php    |   3 -
 civicrm/CRM/Report/Form/Contribute/Detail.php |  25 +-
 .../CRM/Report/Form/Contribute/History.php    |  31 +-
 .../Form/Contribute/HouseholdSummary.php      |  33 +-
 civicrm/CRM/Report/Form/Contribute/Lybunt.php |  17 +-
 .../Form/Contribute/OrganizationSummary.php   |  25 +-
 civicrm/CRM/Report/Form/Contribute/Recur.php  |  11 +-
 .../Report/Form/Contribute/RecurSummary.php   |   7 +-
 .../CRM/Report/Form/Contribute/Summary.php    |  18 +-
 civicrm/CRM/Report/Form/Contribute/Sybunt.php |  17 +-
 .../CRM/Report/Form/Contribute/TopDonor.php   |  11 +-
 .../Form/Event/ParticipantListCount.php       |  13 +-
 .../Report/Form/Event/ParticipantListing.php  |  14 +-
 civicrm/CRM/Report/Form/Grant/Detail.php      |  16 +-
 civicrm/CRM/Report/Form/Grant/Statistics.php  |  37 +-
 civicrm/CRM/Report/Form/Mailing/Bounce.php    |   8 +-
 civicrm/CRM/Report/Form/Mailing/Clicks.php    |   9 +-
 civicrm/CRM/Report/Form/Mailing/Detail.php    |   7 +-
 civicrm/CRM/Report/Form/Mailing/Opened.php    |   9 +-
 .../Report/Form/Member/ContributionDetail.php |  34 +-
 civicrm/CRM/Report/Form/Member/Detail.php     |  30 +-
 civicrm/CRM/Report/Form/Member/Lapse.php      |  39 +-
 .../CRM/Report/Form/Membership/Summary.php    |  20 +-
 civicrm/CRM/Report/Form/Pledge/Detail.php     |  13 +-
 civicrm/CRM/Report/Form/Pledge/Pbnp.php       |  26 +-
 civicrm/CRM/Report/Form/Pledge/Summary.php    |  21 +-
 civicrm/CRM/Report/Form/Walklist/Walklist.php |  28 +-
 civicrm/CRM/Report/Utils/Get.php              |   1 +
 .../civicrm_msg_template.tpl                  |  16 -
 .../contribution_online_receipt_html.tpl      | 391 -------------
 .../event_online_receipt_html.tpl             | 469 ----------------
 .../event_online_receipt_text.tpl             | 296 ----------
 civicrm/CRM/Upgrade/Form.php                  |  14 +-
 .../CRM/Upgrade/Incremental/php/FiveOne.php   |  87 +++
 .../CRM/Upgrade/Incremental/php/FourOne.php   | 430 --------------
 .../Upgrade/Incremental/sql/4.1.0.mysql.tpl   |   8 -
 .../Upgrade/Incremental/sql/4.1.1.mysql.tpl   |  20 -
 .../Upgrade/Incremental/sql/4.1.2.mysql.tpl   |  22 -
 .../Upgrade/Incremental/sql/4.1.3.mysql.tpl   |   5 -
 .../Incremental/sql/4.1.alpha1.mysql.tpl      | 529 ------------------
 .../Incremental/sql/4.1.alpha2.mysql.tpl      |  12 -
 .../Incremental/sql/4.1.beta1.mysql.tpl       |  11 -
 .../Incremental/sql/4.1.beta2.mysql.tpl       | 119 ----
 .../Incremental/sql/4.1.beta3.mysql.tpl       |  33 --
 .../Upgrade/Incremental/sql/5.0.0.mysql.tpl   |   1 -
 .../Upgrade/Incremental/sql/5.0.1.mysql.tpl   |   1 -
 .../Upgrade/Incremental/sql/5.0.2.mysql.tpl   |   1 -
 .../Upgrade/Incremental/sql/5.1.0.mysql.tpl   |   1 +
 .../Incremental/sql/5.1.alpha1.mysql.tpl      |   1 +
 .../Incremental/sql/5.1.beta1.mysql.tpl       |   1 +
 civicrm/CRM/Utils/Check/Component/Env.php     |  26 +-
 civicrm/CRM/Utils/Money.php                   |  13 +
 civicrm/CRM/Utils/Rule.php                    |  41 +-
 civicrm/CRM/Utils/System/Joomla.php           |  17 +-
 civicrm/CRM/Utils/System/WordPress.php        |   2 +-
 civicrm/CRM/Utils/Type.php                    |   9 +-
 civicrm/CRM/Utils/VersionCheck.php            |   9 +
 civicrm/Civi/Angular/AngularLoader.php        |  85 +++
 civicrm/Civi/Angular/Page/Main.php            |  21 +-
 civicrm/Civi/Core/SettingsBag.php             |   5 -
 civicrm/Civi/Test/Api3DocTrait.php            | 209 +++++++
 civicrm/Civi/Test/Api3TestTrait.php           | 262 +++++++++
 civicrm/api/v3/Campaign.php                   |   1 +
 .../bower_components/crossfilter2/.bower.json |   8 +-
 .../crossfilter2/crossfilter.js               |  40 +-
 .../crossfilter2/crossfilter.min.js           |   2 +-
 .../bower_components/crossfilter2/index.d.ts  |  58 +-
 civicrm/civicrm-version.php                   |   2 +-
 civicrm/js/Common.js                          |   3 +-
 civicrm/js/crm.optionEdit.js                  | 162 +++++-
 civicrm/packages/DB/DataObject.php            |  34 +-
 civicrm/release-notes.md                      |  30 +
 civicrm/release-notes/5.0.1.md                |  55 +-
 civicrm/release-notes/5.0.2.md                |  45 +-
 civicrm/release-notes/5.1.0.md                | 442 +++++++++++++++
 civicrm/sql/civicrm_data.mysql                |   2 +-
 civicrm/sql/civicrm_generated.mysql           |   2 +-
 .../CRM/Activity/Form/Search/Common.tpl       |   2 +-
 .../CRM/Activity/Selector/Selector.tpl        |   4 +-
 .../CRM/Admin/Form/MessageTemplates.tpl       |   3 +-
 .../templates/CRM/Admin/Form/Setting/Mail.tpl |   4 +-
 .../templates/CRM/Admin/Page/MailSettings.tpl |   5 +-
 civicrm/templates/CRM/Batch/Form/Entry.tpl    |   8 +-
 .../templates/CRM/Campaign/Form/Search.tpl    |   1 -
 .../templates/CRM/Contact/Form/Contact.hlp    |   2 +-
 .../Contact/Form/Edit/Address/CustomData.tpl  |  11 +-
 .../Contact/Form/Edit/Address/CustomField.tpl | 107 ----
 .../CRM/Contact/Form/Edit/CustomData.tpl      |  14 -
 .../templates/CRM/Contact/Form/Edit/Email.tpl |  61 +-
 .../templates/CRM/Contact/Form/Edit/Phone.tpl |   3 +-
 .../CRM/Contact/Form/Edit/TagsAndGroups.tpl   |   2 +-
 .../CRM/Contact/Form/Inline/Email.tpl         |  76 +--
 .../CRM/Contact/Form/Inline/Phone.tpl         |   2 +-
 .../templates/CRM/Contact/Form/OnBehalfOf.tpl |   2 +-
 .../Contact/Form/Search/AdvancedCriteria.tpl  |  11 +-
 .../CRM/Contribute/Form/Contribution.tpl      |  16 +-
 .../CRM/Contribute/Form/Contribution/Main.tpl |   2 +-
 .../Form/ContributionPage/Amount.tpl          |   5 +-
 .../Form/ContributionPage/Settings.tpl        |   3 +-
 .../CRM/Contribute/Form/ContributionView.tpl  |  11 +-
 .../CRM/Contribute/Form/Selector.tpl          |  11 +-
 .../CRM/Contribute/Form/SoftCredit.tpl        |   7 +-
 .../Contribute/Form/UpdateSubscription.tpl    |  13 +
 .../CRM/Contribute/Page/ContributionRecur.tpl |   8 +-
 .../Contribute/Page/ContributionTotals.tpl    |   2 +-
 .../CRM/Contribute/Page/PaymentInfo.tpl       |   2 +-
 civicrm/templates/CRM/Contribute/Page/Tab.tpl |  21 +-
 .../templates/CRM/Custom/Form/CustomData.tpl  |  75 +--
 .../templates/CRM/Custom/Form/CustomField.tpl |  73 +--
 .../CRM/Custom/Form/Edit/CustomData.tpl       |  45 ++
 .../CRM/Custom/Form/Edit/CustomField.tpl      |  99 ++++
 civicrm/templates/CRM/Custom/Form/Group.tpl   |   2 +-
 civicrm/templates/CRM/Custom/Form/Option.tpl  |   3 +
 civicrm/templates/CRM/Custom/Page/Option.tpl  |   2 +
 .../CRM/Event/Form/ManageEvent/Location.tpl   |   5 +-
 .../templates/CRM/Event/Form/Task/Batch.tpl   |  12 +-
 .../CRM/Event/Form/Task/PickProfile.tpl       |   7 +-
 .../CRM/Event/Form/Task/SaveSearch.tpl        |  12 +-
 civicrm/templates/CRM/Friend/Form/Friend.tpl  |   3 -
 civicrm/templates/CRM/Group/Form/Edit.tpl     |   2 +-
 .../CRM/Member/Form/MembershipCommon.tpl      |   2 +-
 .../templates/CRM/Pledge/Form/Selector.tpl    |   4 +-
 civicrm/templates/CRM/Price/Form/PriceSet.tpl |   2 +-
 .../Page/MultipleRecordFieldsListing.tpl      |   2 +-
 .../CRM/common/civicrm.settings.php.template  |   7 +
 civicrm/vendor/autoload.php                   |   2 +-
 civicrm/vendor/composer/autoload_real.php     |  14 +-
 civicrm/vendor/composer/autoload_static.php   |  10 +-
 civicrm/xml/version.xml                       |   2 +-
 203 files changed, 2985 insertions(+), 7185 deletions(-)
 create mode 100644 .github/CONTRIBUTING.md
 create mode 100644 .github/PULL_REQUEST_TEMPLATE.md
 delete mode 100644 civicrm/CRM/Core/I18n/SchemaStructure_2_2_0.php
 delete mode 100644 civicrm/CRM/Core/I18n/SchemaStructure_3_0_alpha1.php
 delete mode 100644 civicrm/CRM/Core/I18n/SchemaStructure_3_0_beta1.php
 delete mode 100644 civicrm/CRM/Core/I18n/SchemaStructure_3_0_beta4.php
 delete mode 100644 civicrm/CRM/Core/I18n/SchemaStructure_3_1_alpha1.php
 delete mode 100644 civicrm/CRM/Core/I18n/SchemaStructure_3_1_beta2.php
 delete mode 100644 civicrm/CRM/Core/I18n/SchemaStructure_3_2_beta4.php
 delete mode 100644 civicrm/CRM/Core/I18n/SchemaStructure_3_3_beta1.php
 delete mode 100644 civicrm/CRM/Core/I18n/SchemaStructure_3_4_0.php
 delete mode 100644 civicrm/CRM/Core/I18n/SchemaStructure_3_4_beta2.php
 delete mode 100644 civicrm/CRM/Core/I18n/SchemaStructure_3_4_beta3.php
 delete mode 100644 civicrm/CRM/Core/I18n/SchemaStructure_4_1_0.php
 delete mode 100644 civicrm/CRM/Core/I18n/SchemaStructure_4_1_alpha1.php
 delete mode 100644 civicrm/CRM/Upgrade/4.1.alpha1.msg_template/civicrm_msg_template.tpl
 delete mode 100644 civicrm/CRM/Upgrade/4.1.alpha1.msg_template/message_templates/contribution_online_receipt_html.tpl
 delete mode 100644 civicrm/CRM/Upgrade/4.1.alpha1.msg_template/message_templates/event_online_receipt_html.tpl
 delete mode 100644 civicrm/CRM/Upgrade/4.1.alpha1.msg_template/message_templates/event_online_receipt_text.tpl
 create mode 100644 civicrm/CRM/Upgrade/Incremental/php/FiveOne.php
 delete mode 100644 civicrm/CRM/Upgrade/Incremental/php/FourOne.php
 delete mode 100644 civicrm/CRM/Upgrade/Incremental/sql/4.1.0.mysql.tpl
 delete mode 100644 civicrm/CRM/Upgrade/Incremental/sql/4.1.1.mysql.tpl
 delete mode 100644 civicrm/CRM/Upgrade/Incremental/sql/4.1.2.mysql.tpl
 delete mode 100644 civicrm/CRM/Upgrade/Incremental/sql/4.1.3.mysql.tpl
 delete mode 100644 civicrm/CRM/Upgrade/Incremental/sql/4.1.alpha1.mysql.tpl
 delete mode 100644 civicrm/CRM/Upgrade/Incremental/sql/4.1.alpha2.mysql.tpl
 delete mode 100644 civicrm/CRM/Upgrade/Incremental/sql/4.1.beta1.mysql.tpl
 delete mode 100644 civicrm/CRM/Upgrade/Incremental/sql/4.1.beta2.mysql.tpl
 delete mode 100644 civicrm/CRM/Upgrade/Incremental/sql/4.1.beta3.mysql.tpl
 delete mode 100644 civicrm/CRM/Upgrade/Incremental/sql/5.0.0.mysql.tpl
 delete mode 100644 civicrm/CRM/Upgrade/Incremental/sql/5.0.1.mysql.tpl
 delete mode 100644 civicrm/CRM/Upgrade/Incremental/sql/5.0.2.mysql.tpl
 create mode 100644 civicrm/CRM/Upgrade/Incremental/sql/5.1.0.mysql.tpl
 create mode 100644 civicrm/CRM/Upgrade/Incremental/sql/5.1.alpha1.mysql.tpl
 create mode 100644 civicrm/CRM/Upgrade/Incremental/sql/5.1.beta1.mysql.tpl
 create mode 100644 civicrm/Civi/Test/Api3DocTrait.php
 create mode 100644 civicrm/Civi/Test/Api3TestTrait.php
 create mode 100644 civicrm/release-notes/5.1.0.md
 delete mode 100644 civicrm/templates/CRM/Contact/Form/Edit/Address/CustomField.tpl
 create mode 100644 civicrm/templates/CRM/Custom/Form/Edit/CustomData.tpl
 create mode 100644 civicrm/templates/CRM/Custom/Form/Edit/CustomField.tpl

diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md
new file mode 100644
index 0000000000..0e1ed32e17
--- /dev/null
+++ b/.github/CONTRIBUTING.md
@@ -0,0 +1,20 @@
+CiviCRM is a community-driven open-source project. It has a small, full-time 
+[core team](https://civicrm.org/core-team)
+which facilitates development and works on critical issues. 
+Additionally, a large community of active contributors and 
+[partner organizations](https://civicrm.org/partners-contributors)
+drive much of the development work. 
+
+For developers, CiviCRM maintains a comprehensive
+[Developer Guide](https://docs.civicrm.org/dev/en/latest).
+Topics of particular importance while submitting pull requests include:
+
+* [Contributing to CiviCRM core](https://docs.civicrm.org/dev/en/latest/core/contributing/)
+* [Pull requests](https://docs.civicrm.org/dev/en/latest/tools/git/#pr)
+* [Git workflow overview](https://docs.civicrm.org/dev/en/latest/tools/git/#contributing)
+* [Writing automated tests](https://docs.civicrm.org/dev/en/latest/testing/setup/)
+* [Jenkins continuous integration](https://docs.civicrm.org/dev/en/latest/tools/jenkins/)
+* [Release Process](https://docs.civicrm.org/dev/en/latest/core/release-process/)
+* [Developer Community](https://docs.civicrm.org/dev/en/latest/basics/community/)
+
+CiviCRM thanks you for your contributions and invites you to [log your time spent](https://civicrm.org/contributor-log) so that you (or your organization) may receive public recognition and promotion for your efforts.
diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md
new file mode 100644
index 0000000000..85e7f8f59d
--- /dev/null
+++ b/.github/PULL_REQUEST_TEMPLATE.md
@@ -0,0 +1,19 @@
+Overview
+----------------------------------------
+_A brief description of the pull request. Try to keep it non-technical._
+
+Before
+----------------------------------------
+_The current status. Please provide screenshots or gifs ([LICEcap](http://www.cockos.com/licecap/), [SilentCast](https://github.com/colinkeenan/silentcast)) where appropriate._
+
+After
+----------------------------------------
+_What has been changed. Please provide screenshots or gifs ([LICEcap](http://www.cockos.com/licecap/), [SilentCast](https://github.com/colinkeenan/silentcast)) where appropriate._
+
+Technical Details
+----------------------------------------
+_If the PR introduces noteworthy technical changes, please describe them here. Provide code snippets if necessary_
+
+Comments
+----------------------------------------
+_Anything else you would like the reviewer to note_
diff --git a/civicrm.php b/civicrm.php
index 6c6db6312d..156a12780d 100644
--- a/civicrm.php
+++ b/civicrm.php
@@ -2,7 +2,7 @@
 /*
 Plugin Name: CiviCRM
 Description: CiviCRM - Growing and Sustaining Relationships
-Version: 5.0.2
+Version: 5.1.0
 Author: CiviCRM LLC
 Author URI: https://civicrm.org/
 Plugin URI: https://wiki.civicrm.org/confluence/display/CRMDOC/Installing+CiviCRM+for+WordPress
diff --git a/civicrm/CONTRIBUTORS.txt b/civicrm/CONTRIBUTORS.txt
index aa39577eff..60a8f1ac4e 100644
--- a/civicrm/CONTRIBUTORS.txt
+++ b/civicrm/CONTRIBUTORS.txt
@@ -6,11 +6,13 @@ Key Contributors and Sponsors for 5.x
 
 CiviCRM - Coleman Watts, Tim Otten
 
-AGH Strategies - Andrew Hunt
-Agileware - Alok Patel
+AGH Strategies - Alice Frumin, Andrew Hunt, Eli Lisseck
+Agileware - Alok Patel, Francis Whittle, Justin Freeman
+Andrew Thompson
 Australian Greens - Seamus Lee
 CiviDesk - Yashodha Chaku
-CompuCorp - Mukesh Ram, Omar Abu Hussein, René Olivo, Vinu Varshith Sekar
+CompuCorp - Michael Devery, Mukesh Ram, Omar Abu Hussein, René Olivo, Vinu
+    Varshith Sekar
 Coop SymbioTIC - Samuel Vanhove
 Davis Media Access - Darrick Servis
 Fuzion - Jitendra Purohit
@@ -18,12 +20,16 @@ Ginkgo Street Labs - Frank Gómez
 JMA Consulting - Monish Deb
 John Kingsnorth
 Joinery - Allen Shaw
+Kompetenzzentrum Technik-Diversity-Chancengleichheit - Niels Heinemann
 Left Join Labs - Sean Madsen
 Lighthouse Design and Consulting - Brian Shaughnessy
 Łukasz Krutul
+Megaphone Technology Consulting - Jon Goldberg
 MJW Consulting - Matthew Wire
 myDropWizard - David Snopek
-Oxfam Germany - Thomas Schüttler
+Naomi Rosenberg
+Olivier Tétard
+Oxfam Germany - Thomas Schüttler, Yuliyana Liyana
 Progressive Technology Project - Jamie McClelland
 Systopia - Björn Endres
 Tadpole Collective - Kevin Cristiano
diff --git a/civicrm/CRM/Activity/Form/Activity.php b/civicrm/CRM/Activity/Form/Activity.php
index 113247adfe..5b8fe0b676 100644
--- a/civicrm/CRM/Activity/Form/Activity.php
+++ b/civicrm/CRM/Activity/Form/Activity.php
@@ -522,6 +522,17 @@ class CRM_Activity_Form_Activity extends CRM_Contact_Form_Task {
     if ($this->_action & CRM_Core_Action::UPDATE) {
       CRM_Core_Form_RecurringEntity::preProcess('civicrm_activity');
     }
+
+    if ($this->_action & CRM_Core_Action::VIEW) {
+      $url = CRM_Utils_System::url(implode("/", $this->urlPath), "reset=1&id={$this->_activityId}&action=view&cid={$this->_values['source_contact_id']}");
+      CRM_Utils_Recent::add($this->_values['subject'],
+        $url,
+        $this->_values['id'],
+        'Activity',
+        $this->_values['source_contact_id'],
+        $this->_values['source_contact']
+      );
+    }
   }
 
   /**
diff --git a/civicrm/CRM/Activity/Form/ActivityView.php b/civicrm/CRM/Activity/Form/ActivityView.php
index 98e9872669..a1dac67084 100644
--- a/civicrm/CRM/Activity/Form/ActivityView.php
+++ b/civicrm/CRM/Activity/Form/ActivityView.php
@@ -108,6 +108,15 @@ class CRM_Activity_Form_ActivityView extends CRM_Core_Form {
 
     $values['attachment'] = CRM_Core_BAO_File::attachmentInfo('civicrm_activity', $activityId);
     $this->assign('values', $values);
+
+    $url = CRM_Utils_System::url(implode("/", $this->urlPath), "reset=1&id={$activityId}&action=view&cid={$values['source_contact_id']}");
+    CRM_Utils_Recent::add($this->_values['subject'],
+      $url,
+      $values['id'],
+      'Activity',
+      $values['source_contact_id'],
+      $values['source_contact']
+    );
   }
 
   /**
diff --git a/civicrm/CRM/Admin/Form/ScheduleReminders.php b/civicrm/CRM/Admin/Form/ScheduleReminders.php
index 6e56a4dfc0..beec68bb85 100644
--- a/civicrm/CRM/Admin/Form/ScheduleReminders.php
+++ b/civicrm/CRM/Admin/Form/ScheduleReminders.php
@@ -168,11 +168,10 @@ class CRM_Admin_Form_ScheduleReminders extends CRM_Admin_Form {
     $this->add('number', 'start_action_offset', ts('When'), array('class' => 'six', 'min' => 0));
     $this->addRule('start_action_offset', ts('Value should be a positive number'), 'positiveInteger');
 
-    $isActive = ts('Send email');
+    $isActive = ts('Scheduled Reminder Active');
     $recordActivity = ts('Record activity for automated email');
     if ($providersCount) {
       $this->assign('sms', $providersCount);
-      $isActive = ts('Send email or SMS');
       $recordActivity = ts('Record activity for automated email or SMS');
       $options = CRM_Core_OptionGroup::values('msg_mode');
       $this->add('select', 'mode', ts('Send as'), $options);
diff --git a/civicrm/CRM/Campaign/Form/Task/Interview.php b/civicrm/CRM/Campaign/Form/Task/Interview.php
index 191e39b810..046da10cdd 100644
--- a/civicrm/CRM/Campaign/Form/Task/Interview.php
+++ b/civicrm/CRM/Campaign/Form/Task/Interview.php
@@ -100,10 +100,11 @@ class CRM_Campaign_Form_Task_Interview extends CRM_Campaign_Form_Task {
 
     $orderClause = FALSE;
     $buttonName = $this->controller->getButtonName();
+    $walkListActivityId = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'WalkList');
     if ($buttonName == '_qf_Interview_submit_orderBy' && !empty($_POST['order_bys'])) {
       $orderByParams = CRM_Utils_Array::value('order_bys', $_POST);
     }
-    elseif (CRM_Core_OptionGroup::getValue('activity_type', 'WalkList') == $this->_surveyDetails['activity_type_id']) {
+    elseif ($walkListActivityId == $this->_surveyDetails['activity_type_id']) {
       $orderByParams
         = array(
           1 => array(
@@ -170,8 +171,7 @@ WHERE {$clause}
       $this->_contactIds,
       $this->_interviewerId
     );
-    $activityStatus = CRM_Core_PseudoConstant::activityStatus('name');
-    $scheduledStatusId = array_search('Scheduled', $activityStatus);
+    $scheduledStatusId = CRM_Core_PseudoConstant::getKey('CRM_Activity_DAO_Activity', 'activity_status_id', 'Scheduled');
 
     $activityIds = array();
     foreach ($this->_contactIds as $key => $voterId) {
@@ -248,9 +248,9 @@ WHERE {$clause}
     }
 
     //set the title.
-    $activityTypes = CRM_Core_PseudoConstant::activityType(FALSE, TRUE, FALSE, 'label', TRUE);
     $this->_surveyTypeId = CRM_Utils_Array::value('activity_type_id', $this->_surveyValues);
-    CRM_Utils_System::setTitle(ts('Record %1 Responses', array(1 => $activityTypes[$this->_surveyTypeId])));
+    $surveyTypeLabel = CRM_Core_PseudoConstant::getLabel('CRM_Activity_BAO_Activity', 'activity_type_id', $this->_surveyTypeId);
+    CRM_Utils_System::setTitle(ts('Record %1 Responses', array(1 => $surveyTypeLabel)));
   }
 
   public function validateIds() {
@@ -387,7 +387,7 @@ WHERE {$clause}
     foreach ($this->_surveyFields as $name => $field) {
       $acceptable_types = CRM_Contact_BAO_ContactType::basicTypes();
       $acceptable_types[] = 'Contact';
-      if (in_array($field['field_type'], $acceptable_types)) {
+      if (isset($field['field_type']) && (in_array($field['field_type'], $acceptable_types))) {
         $contactFields[$name] = $field;
       }
     }
@@ -397,7 +397,8 @@ WHERE {$clause}
       }
     }
 
-    if (CRM_Core_OptionGroup::getValue('activity_type', 'WalkList') == $this->_surveyDetails['activity_type_id']) {
+    $walkListActivityId = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'WalkList');
+    if ($walkListActivityId == $this->_surveyDetails['activity_type_id']) {
       $defaults['order_bys']
         = array(
           1 => array(
@@ -480,7 +481,7 @@ WHERE {$clause}
 
     static $statusId;
     if (!$statusId) {
-      $statusId = array_search('Completed', CRM_Core_PseudoConstant::activityStatus('name'));
+      $statusId = CRM_Core_PseudoConstant::getKey('CRM_Activity_DAO_Activity', 'activity_status_id', 'Completed');
     }
 
     //format custom fields.
@@ -580,11 +581,7 @@ WHERE {$clause}
     $this->_contactIds = $this->get('contactIds');
     if (!is_array($this->_contactIds)) {
       //get the survey activities.
-      $activityStatus = CRM_Core_PseudoConstant::activityStatus('name');
-      $statusIds = array();
-      if ($statusId = array_search('Scheduled', $activityStatus)) {
-        $statusIds[] = $statusId;
-      }
+      $statusIds[] = CRM_Core_PseudoConstant::getKey('CRM_Activity_DAO_Activity', 'activity_status_id', 'Scheduled');
       $surveyActivities = CRM_Campaign_BAO_Survey::getSurveyVoterInfo($this->_surveyId,
         $this->_interviewerId,
         $statusIds
diff --git a/civicrm/CRM/Contact/BAO/Contact/Permission.php b/civicrm/CRM/Contact/BAO/Contact/Permission.php
index 7c56b49b65..3333dfb1d5 100644
--- a/civicrm/CRM/Contact/BAO/Contact/Permission.php
+++ b/civicrm/CRM/Contact/BAO/Contact/Permission.php
@@ -199,9 +199,12 @@ WHERE contact_a.id = %1 AND $permission
     //   that somebody might flush the cache away from under our feet,
     //   but the alternative would be a SQL call every time this is called,
     //   and a complete rebuild if the result was an empty set...
-    static $_processed = array(
-      CRM_Core_Permission::VIEW => array(),
-      CRM_Core_Permission::EDIT => array());
+    if (!isset(Civi::$statics[__CLASS__]['processed'])) {
+      Civi::$statics[__CLASS__]['processed'] = [
+        CRM_Core_Permission::VIEW => [],
+        CRM_Core_Permission::EDIT => [],
+      ];
+    }
 
     if ($type == CRM_Core_Permission::VIEW) {
       $operationClause = " operation IN ( 'Edit', 'View' ) ";
@@ -215,7 +218,7 @@ WHERE contact_a.id = %1 AND $permission
 
     if (!$force) {
       // skip if already calculated
-      if (!empty($_processed[$type][$userID])) {
+      if (!empty(Civi::$statics[__CLASS__]['processed'][$type][$userID])) {
         return;
       }
 
@@ -228,7 +231,7 @@ AND    $operationClause
 ";
       $count = CRM_Core_DAO::singleValueQuery($sql, $queryParams);
       if ($count > 0) {
-        $_processed[$type][$userID] = 1;
+        Civi::$statics[__CLASS__]['processed'][$type][$userID] = 1;
         return;
       }
     }
@@ -257,7 +260,7 @@ AND ac.user_id IS NULL
         CRM_Core_DAO::executeQuery("INSERT INTO civicrm_acl_contact_cache ( user_id, contact_id, operation ) VALUES(%1, %1, '{$operation}')", $queryParams);
       }
     }
-    $_processed[$type][$userID] = 1;
+    Civi::$statics[__CLASS__]['processed'][$type][$userID] = 1;
   }
 
   /**
diff --git a/civicrm/CRM/Contact/Form/Edit/Address.php b/civicrm/CRM/Contact/Form/Edit/Address.php
index b6df73e0ec..366d02ba44 100644
--- a/civicrm/CRM/Contact/Form/Edit/Address.php
+++ b/civicrm/CRM/Contact/Form/Edit/Address.php
@@ -56,9 +56,6 @@ class CRM_Contact_Form_Edit_Address {
       $blockId = $addressBlockCount;
     }
 
-    $config = CRM_Core_Config::singleton();
-    $countryDefault = $config->defaultContactCountry;
-
     $form->applyFilter('__ALL__', 'trim');
 
     $js = array();
@@ -93,7 +90,6 @@ class CRM_Contact_Form_Edit_Address {
     $addressOptions = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
       'address_options', TRUE, NULL, TRUE
     );
-    $attributes = CRM_Core_DAO::getAttribute('CRM_Core_DAO_Address');
 
     $elements = array(
       'address_name',
@@ -115,7 +111,7 @@ class CRM_Contact_Form_Edit_Address {
     );
 
     foreach ($elements as $name) {
-      //Remove id from name, to allow comparison against enabled addressOtions.
+      //Remove id from name, to allow comparison against enabled addressOptions.
       $nameWithoutID = strpos($name, '_id') !== FALSE ? substr($name, 0, -3) : $name;
       // Skip fields which are not enabled in the address options.
       if (empty($addressOptions[$nameWithoutID])) {
@@ -204,8 +200,7 @@ class CRM_Contact_Form_Edit_Address {
       // more handling done in formRule func
       CRM_Contact_Form_Edit_Address::storeRequiredCustomDataInfo($form, $groupTree);
 
-      $template = CRM_Core_Smarty::singleton();
-      $tplGroupTree = $template->get_template_vars('address_groupTree');
+      $tplGroupTree = CRM_Core_Smarty::singleton()->get_template_vars('address_groupTree');
       $tplGroupTree = empty($tplGroupTree) ? array() : $tplGroupTree;
 
       $form->assign('address_groupTree', $tplGroupTree + array($blockId => $groupTree));
diff --git a/civicrm/CRM/Contact/Form/Merge.php b/civicrm/CRM/Contact/Form/Merge.php
index 2c6a299186..53045ac971 100644
--- a/civicrm/CRM/Contact/Form/Merge.php
+++ b/civicrm/CRM/Contact/Form/Merge.php
@@ -244,7 +244,7 @@ class CRM_Contact_Form_Merge extends CRM_Core_Form {
       'type' => 'next',
       'name' => $this->next ? ts('Merge and go to Next Pair') : ts('Merge'),
       'isDefault' => TRUE,
-      'icon' => $this->next ? 'circle-triangle-e' : 'check',
+      'icon' => $this->next ? 'fa-play-circle' : 'check',
     );
 
     if ($this->next || $this->prev) {
diff --git a/civicrm/CRM/Contact/Form/Search.php b/civicrm/CRM/Contact/Form/Search.php
index 2df8b362cf..8316b85260 100644
--- a/civicrm/CRM/Contact/Form/Search.php
+++ b/civicrm/CRM/Contact/Form/Search.php
@@ -199,92 +199,105 @@ class CRM_Contact_Form_Search extends CRM_Core_Form_Search {
   }
 
   public static function setModeValues() {
-    if (!self::$_modeValues) {
-      self::$_modeValues = array(
-        CRM_Contact_BAO_Query::MODE_CONTACTS => array(
-          'selectorName' => self::$_selectorName,
-          'selectorLabel' => ts('Contacts'),
-          'taskFile' => 'CRM/Contact/Form/Search/ResultTasks.tpl',
-          'taskContext' => NULL,
-          'resultFile' => 'CRM/Contact/Form/Selector.tpl',
-          'resultContext' => NULL,
-          'taskClassName' => 'CRM_Contact_Task',
-        ),
-        CRM_Contact_BAO_Query::MODE_CONTRIBUTE => array(
-          'selectorName' => 'CRM_Contribute_Selector_Search',
-          'selectorLabel' => ts('Contributions'),
-          'taskFile' => 'CRM/common/searchResultTasks.tpl',
-          'taskContext' => 'Contribution',
-          'resultFile' => 'CRM/Contribute/Form/Selector.tpl',
-          'resultContext' => 'Search',
-          'taskClassName' => 'CRM_Contribute_Task',
-        ),
-        CRM_Contact_BAO_Query::MODE_EVENT => array(
-          'selectorName' => 'CRM_Event_Selector_Search',
-          'selectorLabel' => ts('Event Participants'),
-          'taskFile' => 'CRM/common/searchResultTasks.tpl',
-          'taskContext' => NULL,
-          'resultFile' => 'CRM/Event/Form/Selector.tpl',
-          'resultContext' => 'Search',
-          'taskClassName' => 'CRM_Event_Task',
-        ),
-        CRM_Contact_BAO_Query::MODE_ACTIVITY => array(
-          'selectorName' => 'CRM_Activity_Selector_Search',
-          'selectorLabel' => ts('Activities'),
-          'taskFile' => 'CRM/common/searchResultTasks.tpl',
-          'taskContext' => NULL,
-          'resultFile' => 'CRM/Activity/Form/Selector.tpl',
-          'resultContext' => 'Search',
-          'taskClassName' => 'CRM_Activity_Task',
-        ),
-        CRM_Contact_BAO_Query::MODE_MEMBER => array(
-          'selectorName' => 'CRM_Member_Selector_Search',
-          'selectorLabel' => ts('Memberships'),
-          'taskFile' => "CRM/common/searchResultTasks.tpl",
-          'taskContext' => NULL,
-          'resultFile' => 'CRM/Member/Form/Selector.tpl',
-          'resultContext' => 'Search',
-          'taskClassName' => 'CRM_Member_Task',
-        ),
-        CRM_Contact_BAO_Query::MODE_CASE => array(
-          'selectorName' => 'CRM_Case_Selector_Search',
-          'selectorLabel' => ts('Cases'),
-          'taskFile' => "CRM/common/searchResultTasks.tpl",
-          'taskContext' => NULL,
-          'resultFile' => 'CRM/Case/Form/Selector.tpl',
-          'resultContext' => 'Search',
-          'taskClassName' => 'CRM_Case_Task',
-        ),
-        CRM_Contact_BAO_Query::MODE_CONTACTSRELATED => array(
-          'selectorName' => self::$_selectorName,
-          'selectorLabel' => ts('Related Contacts'),
-          'taskFile' => 'CRM/Contact/Form/Search/ResultTasks.tpl',
-          'taskContext' => NULL,
-          'resultFile' => 'CRM/Contact/Form/Selector.tpl',
-          'resultContext' => NULL,
-          'taskClassName' => 'CRM_Contact_Task',
-        ),
-        CRM_Contact_BAO_Query::MODE_MAILING => array(
-          'selectorName' => 'CRM_Mailing_Selector_Search',
-          'selectorLabel' => ts('Mailings'),
-          'taskFile' => "CRM/common/searchResultTasks.tpl",
-          'taskContext' => NULL,
-          'resultFile' => 'CRM/Mailing/Form/Selector.tpl',
-          'resultContext' => 'Search',
-          'taskClassName' => 'CRM_Mailing_Task',
-        ),
-      );
-    }
+    self::$_modeValues = array(
+      CRM_Contact_BAO_Query::MODE_CONTACTS => array(
+        'selectorName' => self::$_selectorName,
+        'selectorLabel' => ts('Contacts'),
+        'taskFile' => 'CRM/Contact/Form/Search/ResultTasks.tpl',
+        'taskContext' => NULL,
+        'resultFile' => 'CRM/Contact/Form/Selector.tpl',
+        'resultContext' => NULL,
+        'taskClassName' => 'CRM_Contact_Task',
+        'component' => '',
+      ),
+      CRM_Contact_BAO_Query::MODE_CONTRIBUTE => array(
+        'selectorName' => 'CRM_Contribute_Selector_Search',
+        'selectorLabel' => ts('Contributions'),
+        'taskFile' => 'CRM/common/searchResultTasks.tpl',
+        'taskContext' => 'Contribution',
+        'resultFile' => 'CRM/Contribute/Form/Selector.tpl',
+        'resultContext' => 'Search',
+        'taskClassName' => 'CRM_Contribute_Task',
+        'component' => 'CiviContribute',
+      ),
+      CRM_Contact_BAO_Query::MODE_EVENT => array(
+        'selectorName' => 'CRM_Event_Selector_Search',
+        'selectorLabel' => ts('Event Participants'),
+        'taskFile' => 'CRM/common/searchResultTasks.tpl',
+        'taskContext' => NULL,
+        'resultFile' => 'CRM/Event/Form/Selector.tpl',
+        'resultContext' => 'Search',
+        'taskClassName' => 'CRM_Event_Task',
+        'component' => 'CiviEvent',
+      ),
+      CRM_Contact_BAO_Query::MODE_ACTIVITY => array(
+        'selectorName' => 'CRM_Activity_Selector_Search',
+        'selectorLabel' => ts('Activities'),
+        'taskFile' => 'CRM/common/searchResultTasks.tpl',
+        'taskContext' => NULL,
+        'resultFile' => 'CRM/Activity/Form/Selector.tpl',
+        'resultContext' => 'Search',
+        'taskClassName' => 'CRM_Activity_Task',
+        'component' => 'activity',
+      ),
+      CRM_Contact_BAO_Query::MODE_MEMBER => array(
+        'selectorName' => 'CRM_Member_Selector_Search',
+        'selectorLabel' => ts('Memberships'),
+        'taskFile' => "CRM/common/searchResultTasks.tpl",
+        'taskContext' => NULL,
+        'resultFile' => 'CRM/Member/Form/Selector.tpl',
+        'resultContext' => 'Search',
+        'taskClassName' => 'CRM_Member_Task',
+        'component' => 'CiviMember',
+      ),
+      CRM_Contact_BAO_Query::MODE_CASE => array(
+        'selectorName' => 'CRM_Case_Selector_Search',
+        'selectorLabel' => ts('Cases'),
+        'taskFile' => "CRM/common/searchResultTasks.tpl",
+        'taskContext' => NULL,
+        'resultFile' => 'CRM/Case/Form/Selector.tpl',
+        'resultContext' => 'Search',
+        'taskClassName' => 'CRM_Case_Task',
+        'component' => 'CiviCase',
+      ),
+      CRM_Contact_BAO_Query::MODE_CONTACTSRELATED => array(
+        'selectorName' => self::$_selectorName,
+        'selectorLabel' => ts('Related Contacts'),
+        'taskFile' => 'CRM/Contact/Form/Search/ResultTasks.tpl',
+        'taskContext' => NULL,
+        'resultFile' => 'CRM/Contact/Form/Selector.tpl',
+        'resultContext' => NULL,
+        'taskClassName' => 'CRM_Contact_Task',
+        'component' => 'related_contact',
+      ),
+      CRM_Contact_BAO_Query::MODE_MAILING => array(
+        'selectorName' => 'CRM_Mailing_Selector_Search',
+        'selectorLabel' => ts('Mailings'),
+        'taskFile' => "CRM/common/searchResultTasks.tpl",
+        'taskContext' => NULL,
+        'resultFile' => 'CRM/Mailing/Form/Selector.tpl',
+        'resultContext' => 'Search',
+        'taskClassName' => 'CRM_Mailing_Task',
+        'component' => 'CiviMail',
+      ),
+    );
   }
 
   /**
+   * Get the metadata for the query mode (this includes task class names)
+   *
    * @param int $mode
    *
-   * @return mixed
+   * @return array
+   * @throws \CRM_Core_Exception
    */
   public static function getModeValue($mode = CRM_Contact_BAO_Query::MODE_CONTACTS) {
-    self::setModeValues();
+    $searchPane = CRM_Utils_Request::retrieve('searchPane', 'String');
+    if (!empty($searchPane)) {
+      $mode = array_search($searchPane, self::getModeToComponentMapping());
+    }
 
+    self::setModeValues();
     if (!array_key_exists($mode, self::$_modeValues)) {
       $mode = CRM_Contact_BAO_Query::MODE_CONTACTS;
     }
@@ -292,6 +305,24 @@ class CRM_Contact_Form_Search extends CRM_Core_Form_Search {
     return self::$_modeValues[$mode];
   }
 
+  /**
+   * Get a mapping of modes to components.
+   *
+   * This will map the integers to the components. Contact has an empty component
+   * an pseudo-components exist for activity & related_contact.
+   *
+   * @return array
+   */
+  public static function getModeToComponentMapping() {
+    $mapping = [];
+    self::setModeValues();
+
+    foreach (self::$_modeValues as $id => $metadata) {
+      $mapping[$id] = $metadata['component'];
+    }
+    return $mapping;
+  }
+
   /**
    * @return array
    */
@@ -657,9 +688,8 @@ class CRM_Contact_Form_Search extends CRM_Core_Form_Search {
     if (!isset($this->_componentMode)) {
       $this->_componentMode = CRM_Contact_BAO_Query::MODE_CONTACTS;
     }
-    self::setModeValues();
-
     self::$_selectorName = $this->_modeValue['selectorName'];
+    self::setModeValues();
 
     $setDynamic = FALSE;
     if (strpos(self::$_selectorName, 'CRM_Contact_Selector') !== FALSE) {
diff --git a/civicrm/CRM/Contact/Form/Search/Criteria.php b/civicrm/CRM/Contact/Form/Search/Criteria.php
index 87159ac23b..d47739a364 100644
--- a/civicrm/CRM/Contact/Form/Search/Criteria.php
+++ b/civicrm/CRM/Contact/Form/Search/Criteria.php
@@ -158,6 +158,7 @@ class CRM_Contact_Form_Search_Criteria {
     );
 
     $componentModes = CRM_Contact_Form_Search::getModeSelect();
+    $form->assign('component_mappings', json_encode(CRM_Contact_Form_Search::getModeToComponentMapping()));
     if (count($componentModes) > 1) {
       $form->add('select',
         'component_mode',
diff --git a/civicrm/CRM/Contact/Import/Parser/Contact.php b/civicrm/CRM/Contact/Import/Parser/Contact.php
index ad97146add..b5043a135c 100644
--- a/civicrm/CRM/Contact/Import/Parser/Contact.php
+++ b/civicrm/CRM/Contact/Import/Parser/Contact.php
@@ -456,6 +456,16 @@ class CRM_Contact_Import_Parser_Contact extends CRM_Contact_Import_Parser {
     return CRM_Import_Parser::VALID;
   }
 
+  /**
+   * Get Array of all the fields that could potentially be part
+   * import process
+   *
+   * @return array
+   */
+  public function getAllFields() {
+    return $this->_fields;
+  }
+
   /**
    * Handle the values in import mode.
    *
diff --git a/civicrm/CRM/Contact/Page/DedupeFind.php b/civicrm/CRM/Contact/Page/DedupeFind.php
index 65f2833851..90beae0b95 100644
--- a/civicrm/CRM/Contact/Page/DedupeFind.php
+++ b/civicrm/CRM/Contact/Page/DedupeFind.php
@@ -63,8 +63,9 @@ class CRM_Contact_Page_DedupeFind extends CRM_Core_Page_Basic {
     $limit = CRM_Utils_Request::retrieve('limit', 'Integer', $this);
     $rgid = CRM_Utils_Request::retrieve('rgid', 'Positive', $this);
     $cid = CRM_Utils_Request::retrieve('cid', 'Positive', $this, FALSE, 0);
-    // Using a placeholder for criteria as it is intended to be able to pass this later.
-    $criteria = array();
+    $criteria = CRM_Utils_Request::retrieve('criteria', 'Json', $this, FALSE);
+    $this->assign('criteria', $criteria);
+
     $isConflictMode = ($context == 'conflicts');
     if ($cid) {
       $this->_cid = $cid;
@@ -79,8 +80,10 @@ class CRM_Contact_Page_DedupeFind extends CRM_Core_Page_Basic {
       'rgid' => $rgid,
       'gid' => $gid,
       'limit' => $limit,
+      'criteria' => $criteria,
     );
     $this->assign('urlQuery', CRM_Utils_System::makeQueryString($urlQry));
+    $criteria = json_decode($criteria, TRUE);
 
     if ($context == 'search') {
       $context = 'search';
diff --git a/civicrm/CRM/Contribute/BAO/ContributionRecur.php b/civicrm/CRM/Contribute/BAO/ContributionRecur.php
index ec23ddb44b..3049402ea5 100644
--- a/civicrm/CRM/Contribute/BAO/ContributionRecur.php
+++ b/civicrm/CRM/Contribute/BAO/ContributionRecur.php
@@ -323,7 +323,7 @@ SELECT r.payment_processor_id
   }
 
   /**
-   * Get list of recurring contribution of contact Ids.
+   * @deprecated Get list of recurring contribution of contact Ids.
    *
    * @param int $contactId
    *   Contact ID.
@@ -333,6 +333,7 @@ SELECT r.payment_processor_id
    *
    */
   public static function getRecurContributions($contactId) {
+    Civi::log()->warning('Deprecated function, use ContributionRecur.get API instead', array('civi.tag' => 'deprecated'));
     $params = array();
     $recurDAO = new CRM_Contribute_DAO_ContributionRecur();
     $recurDAO->contact_id = $contactId;
diff --git a/civicrm/CRM/Contribute/Form/Contribution.php b/civicrm/CRM/Contribute/Form/Contribution.php
index 8bc4c44c07..07daaa7368 100644
--- a/civicrm/CRM/Contribute/Form/Contribution.php
+++ b/civicrm/CRM/Contribute/Form/Contribution.php
@@ -239,6 +239,7 @@ class CRM_Contribute_Form_Contribution extends CRM_Contribute_Form_AbstractEditP
     if (!empty($this->_id)) {
       $this->assignPaymentInfoBlock();
       $this->assign('contribID', $this->_id);
+      $this->assign('isUsePaymentBlock', TRUE);
     }
 
     $this->_context = CRM_Utils_Request::retrieve('context', 'String', $this);
diff --git a/civicrm/CRM/Contribute/Form/Contribution/Confirm.php b/civicrm/CRM/Contribute/Form/Contribution/Confirm.php
index f91d894784..a47603f86f 100644
--- a/civicrm/CRM/Contribute/Form/Contribution/Confirm.php
+++ b/civicrm/CRM/Contribute/Form/Contribution/Confirm.php
@@ -334,7 +334,9 @@ class CRM_Contribute_Form_Contribution_Confirm extends CRM_Contribute_Form_Contr
     }
     // if onbehalf-of-organization
     if (!empty($this->_values['onbehalf_profile_id']) && !empty($this->_params['onbehalf']['organization_name'])) {
-      $this->_params['organization_id'] = CRM_Utils_Array::value('onbehalfof_id', $this->_params);
+      if (empty($this->_params['org_option']) && empty($this->_params['organization_id'])) {
+        $this->_params['organization_id'] = CRM_Utils_Array::value('onbehalfof_id', $this->_params);
+      }
       $this->_params['organization_name'] = $this->_params['onbehalf']['organization_name'];
       $addressBlocks = array(
         'street_address',
@@ -1530,6 +1532,7 @@ class CRM_Contribute_Form_Contribution_Confirm extends CRM_Contribute_Form_Contr
       }
 
       $i = 1;
+      $form->_params['createdMembershipIDs'] = array();
       foreach ($membershipTypeIDs as $memType) {
         $membershipLineItems = array();
         if ($i < count($membershipTypeIDs)) {
@@ -1590,6 +1593,15 @@ class CRM_Contribute_Form_Contribution_Confirm extends CRM_Contribute_Form_Contr
           // Next line is probably redundant. Checksprevent it happening twice.
           CRM_Member_BAO_Membership::linkMembershipPayment($membership, $membershipContribution);
         }
+        if ($membership) {
+          CRM_Core_BAO_CustomValueTable::postProcess($form->_params, 'civicrm_membership', $membership->id, 'Membership');
+          $form->_params['createdMembershipIDs'][] = $membership->id;
+          $form->_params['membershipID'] = $membership->id;
+
+          //CRM-15232: Check if membership is created and on the basis of it use
+          //membership receipt template to send payment receipt
+          $form->_values['isMembership'] = TRUE;
+        }
       }
       if ($form->_priceSetId && !empty($form->_useForMember) && !empty($form->_lineItem)) {
         foreach ($form->_lineItem[$form->_priceSetId] as & $priceFieldOp) {
@@ -1611,23 +1623,7 @@ class CRM_Contribute_Form_Contribution_Confirm extends CRM_Contribute_Form_Contr
       $message = $this->compileErrorMessage($errors);
       throw new CRM_Core_Exception($message);
     }
-    $form->_params['createdMembershipIDs'] = array();
-
-    // CRM-7851 - Moved after processing Payment Errors
-    //@todo - the reasoning for this being here seems a little outdated
-    CRM_Core_BAO_CustomValueTable::postProcess($form->_params, 'civicrm_membership', $membership->id, 'Membership');
-    $form->_params['createdMembershipIDs'][] = $membership->id;
-
-    if ($membership) {
-      //presumably this is only relevant for exactly 1 membership
-      $form->_params['membershipID'] = $membership->id;
-    }
 
-    //CRM-15232: Check if membership is created and on the basis of it use
-    //membership receipt template to send payment receipt
-    if ($membership) {
-      $form->_values['isMembership'] = TRUE;
-    }
     if (isset($membershipContributionID)) {
       $form->_values['contribution_id'] = $membershipContributionID;
     }
diff --git a/civicrm/CRM/Contribute/Form/ContributionView.php b/civicrm/CRM/Contribute/Form/ContributionView.php
index feb6f0c8e5..50752ca048 100644
--- a/civicrm/CRM/Contribute/Form/ContributionView.php
+++ b/civicrm/CRM/Contribute/Form/ContributionView.php
@@ -249,6 +249,7 @@ class CRM_Contribute_Form_ContributionView extends CRM_Core_Form {
       $this->assign('componentId', $id);
       $this->assign('component', 'contribution');
     }
+    $this->assignPaymentInfoBlock($id);
   }
 
   /**
@@ -266,4 +267,27 @@ class CRM_Contribute_Form_ContributionView extends CRM_Core_Form {
     ));
   }
 
+  /**
+   * Assign the values to build the payment info block.
+   *
+   * @todo - this is a bit too much copy & paste from AbstractEditPayment
+   * (justifying on the basis it's 'pretty short' and in a different inheritance
+   * tree. I feel like traits are probably the longer term answer).
+   *
+   * @param int $id
+   *
+   * @return string $title
+   *   Block title.
+   */
+  protected function assignPaymentInfoBlock($id) {
+    // component is used in getPaymentInfo primarily to retrieve the contribution id, we
+    // already have that.
+    $paymentInfo = CRM_Contribute_BAO_Contribution::getPaymentInfo($id, 'contribution', TRUE);
+    $title = ts('View Payment');
+    $this->assign('transaction', TRUE);
+    $this->assign('payments', $paymentInfo['transaction']);
+    $this->assign('paymentLinks', $paymentInfo['payment_links']);
+    return $title;
+  }
+
 }
diff --git a/civicrm/CRM/Contribute/Form/Search.php b/civicrm/CRM/Contribute/Form/Search.php
index b0345ee9b8..c3100a2e53 100644
--- a/civicrm/CRM/Contribute/Form/Search.php
+++ b/civicrm/CRM/Contribute/Form/Search.php
@@ -260,7 +260,7 @@ class CRM_Contribute_Form_Search extends CRM_Core_Form_Search {
 
     $this->_done = TRUE;
 
-    if (!empty($_POST)) {
+    if (!empty($_POST) && !$this->_force) {
       $this->_formValues = $this->controller->exportValues($this->_name);
     }
 
diff --git a/civicrm/CRM/Contribute/Form/Task/PDFLetterCommon.php b/civicrm/CRM/Contribute/Form/Task/PDFLetterCommon.php
index 98cba059ed..f5fdb968c9 100644
--- a/civicrm/CRM/Contribute/Form/Task/PDFLetterCommon.php
+++ b/civicrm/CRM/Contribute/Form/Task/PDFLetterCommon.php
@@ -188,17 +188,17 @@ class CRM_Contribute_Form_Task_PDFLetterCommon extends CRM_Contact_Form_Task_PDF
    * Check that the token only appears in a table cell. The '</td><td>' separator cannot otherwise work
    * Calculate the number of times it appears IN the cell & the number of times it appears - should be the same!
    *
-   * @param $token
-   * @param $entity
-   * @param $textToSearch
+   * @param string $token
+   * @param string $entity
+   * @param string $textToSearch
    *
    * @return bool
    */
   public static function isHtmlTokenInTableCell($token, $entity, $textToSearch) {
-    $tokenToMatch = $entity . '.' . $token;
-    $dontCare = array();
-    $within = preg_match_all("|<td.+?{" . $tokenToMatch . "}.+?</td|si", $textToSearch, $dontCare);
-    $total = preg_match_all("|{" . $tokenToMatch . "}|", $textToSearch, $dontCare);
+    $tokenToMatch = $entity . '\.' . $token;
+    $pattern = '|<td(?![\w-])((?!</td>).)*\{' . $tokenToMatch . '\}.*?</td>|si';
+    $within = preg_match_all($pattern, $textToSearch);
+    $total = preg_match_all("|{" . $tokenToMatch . "}|", $textToSearch);
     return ($within == $total);
   }
 
diff --git a/civicrm/CRM/Contribute/Form/UpdateSubscription.php b/civicrm/CRM/Contribute/Form/UpdateSubscription.php
index 826b7cb3af..a1c90737b4 100644
--- a/civicrm/CRM/Contribute/Form/UpdateSubscription.php
+++ b/civicrm/CRM/Contribute/Form/UpdateSubscription.php
@@ -146,6 +146,13 @@ class CRM_Contribute_Form_UpdateSubscription extends CRM_Core_Form {
       }
     }
 
+    // when custom data is included in this page
+    if (!empty($_POST['hidden_custom'])) {
+      CRM_Custom_Form_CustomData::preProcess($this, NULL, NULL, 1, 'ContributionRecur', $this->contributionRecurID);
+      CRM_Custom_Form_CustomData::buildQuickForm($this);
+      CRM_Custom_Form_CustomData::setDefaultValues($this);
+    }
+
     $this->assign('editableScheduleFields', array_diff($this->editableScheduleFields, $alreadyHardCodedFields));
 
     if ($this->_subscriptionDetails->contact_id) {
@@ -171,7 +178,7 @@ class CRM_Contribute_Form_UpdateSubscription extends CRM_Core_Form {
     $this->_defaults['financial_type_id'] = $this->_subscriptionDetails->financial_type_id;
     $this->_defaults['is_notify'] = 1;
     foreach ($this->editableScheduleFields as $field) {
-      $this->_defaults[$field] = $this->_subscriptionDetails->$field;
+      $this->_defaults[$field] = isset($this->_subscriptionDetails->$field) ? $this->_subscriptionDetails->$field : NULL;
     }
 
     return $this->_defaults;
@@ -205,6 +212,10 @@ class CRM_Contribute_Form_UpdateSubscription extends CRM_Core_Form {
       $this->addEntityRef('financial_type_id', ts('Financial Type'), array('entity' => 'FinancialType'), !$this->_selfService);
     }
 
+    // Add custom data
+    $this->assign('customDataType', 'ContributionRecur');
+    $this->assign('entityID', $this->contributionRecurID);
+
     $type = 'next';
     if ($this->_selfService) {
       $type = 'submit';
@@ -253,8 +264,10 @@ class CRM_Contribute_Form_UpdateSubscription extends CRM_Core_Form {
       $msgType = 'error';
     }
     elseif ($updateSubscription) {
+      // Handle custom data
+      $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, $this->contributionRecurID, 'ContributionRecur');
       // save the changes
-      $result = CRM_Contribute_BAO_ContributionRecur::add($params);
+      CRM_Contribute_BAO_ContributionRecur::add($params);
       $status = ts('Recurring contribution has been updated to: %1, every %2 %3(s) for %4 installments.',
         array(
           1 => CRM_Utils_Money::format($params['amount'], $this->_subscriptionDetails->currency),
diff --git a/civicrm/CRM/Contribute/Import/Parser/Contribution.php b/civicrm/CRM/Contribute/Import/Parser/Contribution.php
index 993e977dec..0e22418d61 100644
--- a/civicrm/CRM/Contribute/Import/Parser/Contribution.php
+++ b/civicrm/CRM/Contribute/Import/Parser/Contribution.php
@@ -256,14 +256,8 @@ class CRM_Contribute_Import_Parser_Contribution extends CRM_Contribute_Import_Pa
     }
 
     $params = &$this->getActiveFieldParams();
-    $formatted = array('version' => 3);
-
-    // don't add to recent items, CRM-4399
-    $formatted['skipRecentView'] = TRUE;
-
-    //for date-Formats
-    $session = CRM_Core_Session::singleton();
-    $dateType = $session->get('dateTypes');
+    $formatted = ['version' => 3, 'skipRecentView' => TRUE, 'skipCleanMoney' => FALSE];
+    $dateType = CRM_Core_Session::singleton()->get('dateTypes');
 
     $customDataType = !empty($params['contact_type']) ? $params['contact_type'] : 'Contribution';
     $customFields = CRM_Core_BAO_CustomField::getFields($customDataType);
diff --git a/civicrm/CRM/Contribute/Page/ContributionRecur.php b/civicrm/CRM/Contribute/Page/ContributionRecur.php
index baec9f45dd..a2c746a828 100644
--- a/civicrm/CRM/Contribute/Page/ContributionRecur.php
+++ b/civicrm/CRM/Contribute/Page/ContributionRecur.php
@@ -44,45 +44,44 @@ class CRM_Contribute_Page_ContributionRecur extends CRM_Core_Page {
    * View details of a recurring contribution.
    */
   public function view() {
-    $recur = new CRM_Contribute_DAO_ContributionRecur();
-    $recur->id = $this->_id;
-    if ($recur->find(TRUE)) {
-      $values = array();
-      CRM_Core_DAO::storeValues($recur, $values);
-      // if there is a payment processor ID, get the name of the payment processor
-      if (!empty($values['payment_processor_id'])) {
-        $values['payment_processor'] = CRM_Core_DAO::getFieldValue(
-          'CRM_Financial_DAO_PaymentProcessor',
-          $values['payment_processor_id'],
-          'name'
-        );
-      }
-      $idFields = array('contribution_status_id', 'campaign_id');
-      if (CRM_Contribute_BAO_ContributionRecur::supportsFinancialTypeChange($values['id'])) {
-        $idFields[] = 'financial_type_id';
-      }
-      foreach ($idFields as $idField) {
-        if (!empty($values[$idField])) {
-          $values[substr($idField, 0, -3)] = CRM_Core_PseudoConstant::getLabel('CRM_Contribute_BAO_ContributionRecur', $idField, $values[$idField]);
-        }
-      }
+    if (empty($this->_id)) {
+      CRM_Core_Error::statusBounce('Recurring contribution not found');
+    }
 
-      // Add linked membership
-      $membership = civicrm_api3('Membership', 'get', array(
-        'contribution_recur_id' => $recur->id,
+    try {
+      $contributionRecur = civicrm_api3('ContributionRecur', 'getsingle', array(
+        'id' => $this->_id,
       ));
-      if (!empty($membership['count'])) {
-        $membershipDetails = reset($membership['values']);
-        $values['membership_id'] = $membershipDetails['id'];
-        $values['membership_name'] = $membershipDetails['membership_name'];
+    }
+    catch (Exception $e) {
+      CRM_Core_Error::statusBounce('Recurring contribution not found (ID: ' . $this->_id);
+    }
+
+    $contributionRecur['payment_processor'] = CRM_Financial_BAO_PaymentProcessor::getPaymentProcessorName($contributionRecur['payment_processor_id']);
+    $idFields = array('contribution_status_id', 'campaign_id', 'financial_type_id');
+    foreach ($idFields as $idField) {
+      if (!empty($contributionRecur[$idField])) {
+        $contributionRecur[substr($idField, 0, -3)] = CRM_Core_PseudoConstant::getLabel('CRM_Contribute_BAO_ContributionRecur', $idField, $contributionRecur[$idField]);
       }
+    }
 
-      $this->assign('recur', $values);
+    // Add linked membership
+    $membership = civicrm_api3('Membership', 'get', array(
+      'contribution_recur_id' => $contributionRecur['id'],
+    ));
+    if (!empty($membership['count'])) {
+      $membershipDetails = reset($membership['values']);
+      $contributionRecur['membership_id'] = $membershipDetails['id'];
+      $contributionRecur['membership_name'] = $membershipDetails['membership_name'];
     }
+
+    $groupTree = CRM_Core_BAO_CustomGroup::getTree('ContributionRecur', NULL, $contributionRecur['id']);
+    CRM_Core_BAO_CustomGroup::buildCustomDataView($this, $groupTree, FALSE, NULL, NULL, NULL, $contributionRecur['id']);
+
+    $this->assign('recur', $contributionRecur);
   }
 
   public function preProcess() {
-    $context = CRM_Utils_Request::retrieve('context', 'String', $this);
     $this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'view');
     $this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this);
     $this->_contactId = CRM_Utils_Request::retrieve('cid', 'Positive', $this, TRUE);
diff --git a/civicrm/CRM/Contribute/Page/Tab.php b/civicrm/CRM/Contribute/Page/Tab.php
index d236e2a26c..52026bf133 100644
--- a/civicrm/CRM/Contribute/Page/Tab.php
+++ b/civicrm/CRM/Contribute/Page/Tab.php
@@ -100,7 +100,6 @@ class CRM_Contribute_Page_Tab extends CRM_Core_Page {
 
     return self::$_links;
   }
-  // end function
 
   /**
    * called when action is browse.
@@ -131,44 +130,9 @@ class CRM_Contribute_Page_Tab extends CRM_Core_Page {
     $controller->run();
 
     // add recurring block
-    $action = array_sum(array_keys($this->recurLinks()));
-    $params = CRM_Contribute_BAO_ContributionRecur::getRecurContributions($this->_contactId);
+    $this->addRecurringContributionsBlock();
 
-    if (!empty($params)) {
-      foreach ($params as $ids => $recur) {
-        $action = array_sum(array_keys($this->recurLinks($ids)));
-        // no action allowed if it's not active
-        $params[$ids]['is_active'] = ($recur['contribution_status_id'] != 3);
-
-        if ($params[$ids]['is_active']) {
-          $details = CRM_Contribute_BAO_ContributionRecur::getSubscriptionDetails($params[$ids]['id'], 'recur');
-          $hideUpdate = $details->membership_id & $details->auto_renew;
-
-          if ($hideUpdate) {
-            $action -= CRM_Core_Action::UPDATE;
-          }
-
-          $params[$ids]['action'] = CRM_Core_Action::formLink(self::recurLinks($ids), $action,
-            array(
-              'cid' => $this->_contactId,
-              'crid' => $ids,
-              'cxt' => 'contribution',
-            ),
-            ts('more'),
-            FALSE,
-            'contribution.selector.recurring',
-            'Contribution',
-            $ids
-          );
-        }
-      }
-      // assign vars to templates
-      $this->assign('action', $this->_action);
-      $this->assign('recurRows', $params);
-      $this->assign('recur', TRUE);
-    }
-
-    //enable/disable soft credit records for test contribution
+    // enable/disable soft credit records for test contribution
     $isTest = 0;
     if (CRM_Utils_Request::retrieve('isTest', 'Positive', $this)) {
       $isTest = 1;
@@ -183,7 +147,7 @@ class CRM_Contribute_Page_Tab extends CRM_Core_Page {
       list($softCreditTotals['amount'],
         $softCreditTotals['avg'],
         $softCreditTotals['currency'],
-        $softCreditTotals['cancelAmount'] //to get cancel amount
+        $softCreditTotals['cancelAmount'] // to get cancel amount
         ) = CRM_Contribute_BAO_ContributionSoft::getSoftContributionTotals($this->_contactId, $isTest);
 
       $this->assign('softCredit', TRUE);
@@ -198,10 +162,69 @@ class CRM_Contribute_Page_Tab extends CRM_Core_Page {
     }
   }
 
+  /**
+   * Get all the recurring contribution information and assign to the template
+   */
+  private function addRecurringContributionsBlock() {
+    try {
+      $contributionRecurResult = civicrm_api3('ContributionRecur', 'get', array(
+        'contact_id' => $this->_contactId,
+        'options' => array('limit' => 0, 'sort' => 'start_date ASC'),
+      ));
+      $recurContributions = CRM_Utils_Array::value('values', $contributionRecurResult);
+    }
+    catch (Exception $e) {
+      $recurContributions = NULL;
+    }
+
+    if (!empty($recurContributions)) {
+      foreach ($recurContributions as $recurId => $recurDetail) {
+        $action = array_sum(array_keys($this->recurLinks($recurId)));
+        // no action allowed if it's not active
+        $recurContributions[$recurId]['is_active'] = (!CRM_Contribute_BAO_Contribution::isContributionStatusNegative($recurDetail['contribution_status_id']));
+
+        // Get the name of the payment processor
+        if (!empty($recurDetail['payment_processor_id'])) {
+          $recurContributions[$recurId]['payment_processor'] = CRM_Financial_BAO_PaymentProcessor::getPaymentProcessorName($recurDetail['payment_processor_id']);
+        }
+        // Get the label for the contribution status
+        if (!empty($recurDetail['contribution_status_id'])) {
+          $recurContributions[$recurId]['contribution_status'] = CRM_Core_PseudoConstant::getLabel('CRM_Contribute_BAO_ContributionRecur', 'contribution_status_id', $recurDetail['contribution_status_id']);
+        }
+
+        if ($recurContributions[$recurId]['is_active']) {
+          $details = CRM_Contribute_BAO_ContributionRecur::getSubscriptionDetails($recurContributions[$recurId]['id'], 'recur');
+          $hideUpdate = $details->membership_id & $details->auto_renew;
+
+          if ($hideUpdate) {
+            $action -= CRM_Core_Action::UPDATE;
+          }
+
+          $recurContributions[$recurId]['action'] = CRM_Core_Action::formLink(self::recurLinks($recurId), $action,
+            array(
+              'cid' => $this->_contactId,
+              'crid' => $recurId,
+              'cxt' => 'contribution',
+            ),
+            ts('more'),
+            FALSE,
+            'contribution.selector.recurring',
+            'Contribution',
+            $recurId
+          );
+        }
+      }
+      // assign vars to templates
+      $this->assign('action', $this->_action);
+      $this->assign('recurRows', $recurContributions);
+      $this->assign('recur', TRUE);
+    }
+  }
+
   /**
    * called when action is view.
    *
-   * @return null
+   * @return mixed
    */
   public function view() {
     $controller = new CRM_Core_Controller_Simple(
@@ -219,7 +242,9 @@ class CRM_Contribute_Page_Tab extends CRM_Core_Page {
   /**
    * called when action is update or new.
    *
-   * @return null
+   * @return mixed
+   * @throws \CRM_Core_Exception
+   * @throws \Exception
    */
   public function edit() {
     // set https for offline cc transaction
diff --git a/civicrm/CRM/Core/BAO/CustomField.php b/civicrm/CRM/Core/BAO/CustomField.php
index a656f5048c..02a6ca4d88 100644
--- a/civicrm/CRM/Core/BAO/CustomField.php
+++ b/civicrm/CRM/Core/BAO/CustomField.php
@@ -803,6 +803,7 @@ class CRM_Core_BAO_CustomField extends CRM_Core_DAO_CustomField {
     $field = self::getFieldObject($fieldId);
     $widget = $field->html_type;
     $element = NULL;
+    $customFieldAttributes = array();
 
     // Custom field HTML should indicate group+field name
     $groupName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $field->custom_group_id);
@@ -837,23 +838,27 @@ class CRM_Core_BAO_CustomField extends CRM_Core_DAO_CustomField {
       if ($search || ($widget !== 'AdvMulti-Select' && strpos($widget, 'Select') !== FALSE)) {
         $widget = 'Select';
       }
-      $selectAttributes = array(
-        'data-crm-custom' => $dataCrmCustomVal,
-        'class' => 'crm-select2',
-      );
+
+      $customFieldAttributes['data-crm-custom'] = $dataCrmCustomVal;
+      $selectAttributes = array('class' => 'crm-select2');
+
       // Search field is always multi-select
       if ($search || strpos($field->html_type, 'Multi') !== FALSE) {
         $selectAttributes['class'] .= ' huge';
         $selectAttributes['multiple'] = 'multiple';
         $selectAttributes['placeholder'] = $placeholder;
       }
+
       // Add data for popup link. Normally this is handled by CRM_Core_Form->addSelect
-      if ($field->option_group_id && !$search && $widget == 'Select' && CRM_Core_Permission::check('administer CiviCRM')) {
-        $selectAttributes += array(
+      $isSupportedWidget = in_array($widget, ['Select', 'Radio']);
+      $canEditOptions = CRM_Core_Permission::check('administer CiviCRM');
+      if ($field->option_group_id && !$search && $isSelect && $canEditOptions) {
+        $customFieldAttributes += array(
           'data-api-entity' => $field->getEntity(),
           'data-api-field' => 'custom_' . $field->id,
           'data-option-edit-path' => 'civicrm/admin/options/' . CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup', $field->option_group_id),
         );
+        $selectAttributes += $customFieldAttributes;
       }
     }
 
@@ -933,10 +938,18 @@ class CRM_Core_BAO_CustomField extends CRM_Core_DAO_CustomField {
 
       case 'Radio':
         $choice = array();
+        parse_str($field->attributes, $radioAttributes);
+        $radioAttributes = array_merge($radioAttributes, $customFieldAttributes);
+
         foreach ($options as $v => $l) {
-          $choice[] = $qf->createElement('radio', NULL, '', $l, (string) $v, $field->attributes);
+          $choice[] = $qf->createElement('radio', NULL, '', $l, (string) $v, $radioAttributes);
         }
         $element = $qf->addGroup($choice, $elementName, $label);
+        $optionEditKey = 'data-option-edit-path';
+        if (isset($selectAttributes[$optionEditKey])) {
+          $element->setAttribute($optionEditKey, $selectAttributes[$optionEditKey]);
+        }
+
         if ($useRequired && !$search) {
           $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
         }
@@ -988,9 +1001,15 @@ class CRM_Core_BAO_CustomField extends CRM_Core_DAO_CustomField {
       case 'CheckBox':
         $check = array();
         foreach ($options as $v => $l) {
-          $check[] = &$qf->addElement('advcheckbox', $v, NULL, $l, array('data-crm-custom' => $dataCrmCustomVal));
+          $check[] = &$qf->addElement('advcheckbox', $v, NULL, $l, $customFieldAttributes);
         }
-        $element = $qf->addGroup($check, $elementName, $label);
+
+        $group = $element = $qf->addGroup($check, $elementName, $label);
+        $optionEditKey = 'data-option-edit-path';
+        if (isset($customFieldAttributes[$optionEditKey])) {
+          $group->setAttribute($optionEditKey, $customFieldAttributes[$optionEditKey]);
+        }
+
         if ($useRequired && !$search) {
           $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
         }
diff --git a/civicrm/CRM/Core/BAO/CustomGroup.php b/civicrm/CRM/Core/BAO/CustomGroup.php
index 2e88e08014..6653d6b4f7 100644
--- a/civicrm/CRM/Core/BAO/CustomGroup.php
+++ b/civicrm/CRM/Core/BAO/CustomGroup.php
@@ -1259,6 +1259,10 @@ ORDER BY civicrm_custom_group.weight,
    */
   private static function _addWhereAdd(&$customGroupDAO, $entityType, $entityID = NULL, $allSubtypes = FALSE) {
     $addSubtypeClause = FALSE;
+    // This function isn't really accessible with user data but since the string
+    // is not passed as a param to the query CRM_Core_DAO::escapeString seems like a harmless
+    // precaution.
+    $entityType = CRM_Core_DAO::escapeString($entityType);
 
     switch ($entityType) {
       case 'Contact':
@@ -1281,13 +1285,7 @@ ORDER BY civicrm_custom_group.weight,
         }
         break;
 
-      case 'Case':
-      case 'Location':
-      case 'Address':
-      case 'Activity':
-      case 'Contribution':
-      case 'Membership':
-      case 'Participant':
+      default:
         $customGroupDAO->whereAdd("extends IN ('$entityType')");
         break;
     }
@@ -1961,7 +1959,7 @@ SELECT IF( EXISTS(SELECT name FROM civicrm_contact_type WHERE name like %1), 1,
   /**
    * Build custom data view.
    *
-   * @param CRM_Core_Form $form
+   * @param CRM_Core_Form|CRM_Core_Page $form
    *   Page object.
    * @param array $groupTree
    * @param bool $returnCount
@@ -1972,6 +1970,7 @@ SELECT IF( EXISTS(SELECT name FROM civicrm_contact_type WHERE name like %1), 1,
    * @param int $entityId
    *
    * @return array|int
+   * @throws \Exception
    */
   public static function buildCustomDataView(&$form, &$groupTree, $returnCount = FALSE, $gID = NULL, $prefix = NULL, $customValueId = NULL, $entityId = NULL) {
     $details = array();
diff --git a/civicrm/CRM/Core/BAO/CustomOption.php b/civicrm/CRM/Core/BAO/CustomOption.php
index 6b7f0f8d75..6cee5cf2eb 100644
--- a/civicrm/CRM/Core/BAO/CustomOption.php
+++ b/civicrm/CRM/Core/BAO/CustomOption.php
@@ -159,7 +159,7 @@ class CRM_Core_BAO_CustomOption {
           $options[$dao->id]['is_default'] = '';
         }
       }
-
+      $options[$dao->id]['description'] = $dao->description;
       $options[$dao->id]['class'] = $dao->id . ',' . $class;
       $options[$dao->id]['is_active'] = empty($dao->is_active) ? ts('No') : ts('Yes');
       $options[$dao->id]['links'] = CRM_Core_Action::formLink($links,
diff --git a/civicrm/CRM/Core/BAO/Email.php b/civicrm/CRM/Core/BAO/Email.php
index 3cb40c5916..9e08e3460c 100644
--- a/civicrm/CRM/Core/BAO/Email.php
+++ b/civicrm/CRM/Core/BAO/Email.php
@@ -237,10 +237,20 @@ ORDER BY e.is_primary DESC, email_id ASC ";
    *   Email object.
    */
   public static function holdEmail(&$email) {
+    if ($email->id && $email->on_hold === NULL) {
+      // email is being updated but no change to on_hold.
+      return;
+    }
+    if ($email->on_hold === 'null' || $email->on_hold === NULL) {
+      // legacy handling, deprecated.
+      $email->on_hold = 0;
+    }
+    $email->on_hold = (int) $email->on_hold;
+
     //check for update mode
     if ($email->id) {
       $params = array(1 => array($email->id, 'Integer'));
-      if ($email->on_hold && $email->on_hold != 'null') {
+      if ($email->on_hold) {
         $sql = "
 SELECT id
 FROM   civicrm_email
@@ -252,7 +262,8 @@ AND    hold_date IS NULL
           $email->reset_date = 'null';
         }
       }
-      elseif ($email->on_hold == 'null') {
+      elseif ($email->on_hold === 0) {
+        // we do this lookup to see if reset_date should be changed.
         $sql = "
 SELECT id
 FROM   civicrm_email
@@ -269,7 +280,7 @@ AND    reset_date IS NULL
       }
     }
     else {
-      if (($email->on_hold != 'null') && $email->on_hold) {
+      if ($email->on_hold) {
         $email->hold_date = date('YmdHis');
       }
     }
diff --git a/civicrm/CRM/Core/BAO/FinancialTrxn.php b/civicrm/CRM/Core/BAO/FinancialTrxn.php
index 922e8ee24b..f61af4f391 100644
--- a/civicrm/CRM/Core/BAO/FinancialTrxn.php
+++ b/civicrm/CRM/Core/BAO/FinancialTrxn.php
@@ -486,7 +486,8 @@ WHERE ft.is_payment = 1
       if (!$ftTotalAmt) {
         $ftTotalAmt = 0;
       }
-      $value = $paymentVal = $lineItemTotal - $ftTotalAmt;
+      $currency = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'currency');
+      $value = $paymentVal = CRM_Utils_Money::subtractCurrencies($lineItemTotal, $ftTotalAmt, $currency);
       if ($returnType) {
         $value = array();
         if ($paymentVal < 0) {
diff --git a/civicrm/CRM/Core/BAO/PrevNextCache.php b/civicrm/CRM/Core/BAO/PrevNextCache.php
index 0112a921b8..157783dddd 100644
--- a/civicrm/CRM/Core/BAO/PrevNextCache.php
+++ b/civicrm/CRM/Core/BAO/PrevNextCache.php
@@ -398,8 +398,17 @@ WHERE (pn.cacheKey $op %1 OR pn.cacheKey $op %2)
     }
     elseif ($rgid) {
       $contactIDs = array();
+      // The thing we really need to filter out is any chaining that would 'DO SOMETHING' to the DB.
+      // criteria could be passed in via url so we want to ensure nothing could be in that url that
+      // would chain to a delete. Limiting to getfields for 'get' limits us to declared fields,
+      // although we might wish to revisit later to allow joins.
+      $validFieldsForRetrieval = civicrm_api3('Contact', 'getfields', ['action' => 'get'])['values'];
       if (!empty($criteria)) {
-        $contacts = civicrm_api3('Contact', 'get', array_merge(array('options' => array('limit' => 0), 'return' => 'id'), $criteria['contact']));
+        $contacts = civicrm_api3('Contact', 'get', array_merge([
+          'options' => ['limit' => 0],
+          'return' => 'id',
+          'check_permissions' => TRUE,
+        ], array_intersect_key($criteria['contact'], $validFieldsForRetrieval)));
         $contactIDs = array_keys($contacts['values']);
       }
       $foundDupes = CRM_Dedupe_Finder::dupes($rgid, $contactIDs, $checkPermissions, $searchLimit);
diff --git a/civicrm/CRM/Core/BAO/Setting.php b/civicrm/CRM/Core/BAO/Setting.php
index 13e066d461..dc2dd9d523 100644
--- a/civicrm/CRM/Core/BAO/Setting.php
+++ b/civicrm/CRM/Core/BAO/Setting.php
@@ -475,21 +475,6 @@ class CRM_Core_BAO_Setting extends CRM_Core_DAO_Setting {
     self::setItem($optionValue, $group, $name);
   }
 
-  /**
-   * Civicrm_setting didn't exist before 4.1.alpha1 and this function helps taking decisions during upgrade
-   *
-   * @return bool
-   */
-  public static function isUpgradeFromPreFourOneAlpha1() {
-    if (CRM_Core_Config::isUpgradeMode()) {
-      $currentVer = CRM_Core_BAO_Domain::version();
-      if (version_compare($currentVer, '4.1.alpha1') < 0) {
-        return TRUE;
-      }
-    }
-    return FALSE;
-  }
-
   /**
    * Check if environment is explicitly set.
    *
diff --git a/civicrm/CRM/Core/Form.php b/civicrm/CRM/Core/Form.php
index 3d52eb9b7b..015b8390a7 100644
--- a/civicrm/CRM/Core/Form.php
+++ b/civicrm/CRM/Core/Form.php
@@ -1091,6 +1091,12 @@ class CRM_Core_Form extends HTML_QuickForm_Page {
       $options[] = $this->createElement('radio', NULL, NULL, $var, $key, $attributes);
     }
     $group = $this->addGroup($options, $name, $title, $separator);
+
+    $optionEditKey = 'data-option-edit-path';
+    if (!empty($attributes[$optionEditKey])) {
+      $group->setAttribute($optionEditKey, $attributes[$optionEditKey]);
+    }
+
     if ($required) {
       $this->addRule($name, ts('%1 is a required field.', array(1 => $title)), 'required');
     }
@@ -1144,25 +1150,29 @@ class CRM_Core_Form extends HTML_QuickForm_Page {
     if ($javascriptMethod) {
       foreach ($values as $key => $var) {
         if (!$flipValues) {
-          $options[] = $this->createElement('checkbox', $var, NULL, $key, $javascriptMethod);
+          $options[] = $this->createElement('checkbox', $var, NULL, $key, $javascriptMethod, $attributes);
         }
         else {
-          $options[] = $this->createElement('checkbox', $key, NULL, $var, $javascriptMethod);
+          $options[] = $this->createElement('checkbox', $key, NULL, $var, $javascriptMethod, $attributes);
         }
       }
     }
     else {
       foreach ($values as $key => $var) {
         if (!$flipValues) {
-          $options[] = $this->createElement('checkbox', $var, NULL, $key);
+          $options[] = $this->createElement('checkbox', $var, NULL, $key, $attributes);
         }
         else {
-          $options[] = $this->createElement('checkbox', $key, NULL, $var);
+          $options[] = $this->createElement('checkbox', $key, NULL, $var, $attributes);
         }
       }
     }
 
-    $this->addGroup($options, $id, $title, $separator);
+    $group = $this->addGroup($options, $id, $title, $separator);
+    $optionEditKey = 'data-option-edit-path';
+    if (!empty($attributes[$optionEditKey])) {
+      $group->setAttribute($optionEditKey, $attributes[$optionEditKey]);
+    }
 
     if ($other) {
       $this->addElement('text', $id . '_other', ts('Other'), $attributes[$id . '_other']);
@@ -1425,8 +1435,16 @@ class CRM_Core_Form extends HTML_QuickForm_Page {
       }
 
       // Add data for popup link.
-      if ((!empty($props['option_url']) || !array_key_exists('option_url', $props)) && ($context != 'search' && $widget == 'Select' && CRM_Core_Permission::check('administer CiviCRM'))) {
-        $props['data-option-edit-path'] = !empty($props['option_url']) ? $props['option_url'] : CRM_Core_PseudoConstant::getOptionEditUrl($fieldSpec);
+      $canEditOptions = CRM_Core_Permission::check('administer CiviCRM');
+      $hasOptionUrl = !empty($props['option_url']);
+      $optionUrlKeyIsSet = array_key_exists('option_url', $props);
+      $shouldAdd = $context !== 'search' && $isSelect && $canEditOptions;
+
+      // Only add if key is not set, or if non-empty option url is provided
+      if (($hasOptionUrl || !$optionUrlKeyIsSet) && $shouldAdd) {
+        $optionUrl = $hasOptionUrl ? $props['option_url'] :
+          CRM_Core_PseudoConstant::getOptionEditUrl($fieldSpec);
+        $props['data-option-edit-path'] = $optionUrl;
         $props['data-api-entity'] = $props['entity'];
         $props['data-api-field'] = $props['name'];
       }
diff --git a/civicrm/CRM/Core/Form/Renderer.php b/civicrm/CRM/Core/Form/Renderer.php
index 293935923d..17bf8d0308 100644
--- a/civicrm/CRM/Core/Form/Renderer.php
+++ b/civicrm/CRM/Core/Form/Renderer.php
@@ -138,7 +138,10 @@ class CRM_Core_Form_Renderer extends HTML_QuickForm_Renderer_ArraySmarty {
     }
     // Active form elements
     else {
-      if ($element->getType() == 'select' && $element->getAttribute('data-option-edit-path')) {
+      $typesToShowEditLink = array('select', 'group');
+      $hasEditPath = NULL !== $element->getAttribute('data-option-edit-path');
+
+      if (in_array($element->getType(), $typesToShowEditLink) && $hasEditPath) {
         $this->addOptionsEditLink($el, $element);
       }
 
diff --git a/civicrm/CRM/Core/I18n/SchemaStructure_2_2_0.php b/civicrm/CRM/Core/I18n/SchemaStructure_2_2_0.php
deleted file mode 100644
index 9652264a83..0000000000
--- a/civicrm/CRM/Core/I18n/SchemaStructure_2_2_0.php
+++ /dev/null
@@ -1,69 +0,0 @@
-<?php
-/*
- +--------------------------------------------------------------------+
- | CiviCRM version 4.7                                                |
- +--------------------------------------------------------------------+
- | Copyright CiviCRM LLC (c) 2004-2018                                |
- +--------------------------------------------------------------------+
- | 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-2018
- * $Id$
- *
- */
-class CRM_Core_I18n_SchemaStructure_2_2_0 {
-  /**
-   * @return mixed
-   */
-  public static function &columns() {
-    static $result = NULL;
-    if (!$result) {
-      $result = unserialize('a:17:{s:20:"civicrm_custom_group";a:3:{s:5:"title";s:11:"varchar(64)";s:8:"help_pre";s:4:"text";s:9:"help_post";s:4:"text";}s:20:"civicrm_custom_field";a:3:{s:5:"label";s:12:"varchar(255)";s:8:"help_pre";s:4:"text";s:9:"help_post";s:4:"text";}s:20:"civicrm_option_group";a:2:{s:5:"label";s:12:"varchar(255)";s:11:"description";s:12:"varchar(255)";}s:17:"civicrm_price_set";a:3:{s:5:"title";s:12:"varchar(255)";s:8:"help_pre";s:4:"text";s:9:"help_post";s:4:"text";}s:15:"civicrm_contact";a:7:{s:9:"sort_name";s:12:"varchar(128)";s:12:"display_name";s:12:"varchar(128)";s:10:"first_name";s:11:"varchar(64)";s:11:"middle_name";s:11:"varchar(64)";s:9:"last_name";s:11:"varchar(64)";s:14:"household_name";s:12:"varchar(128)";s:17:"organization_name";s:12:"varchar(128)";}s:16:"civicrm_premiums";a:2:{s:20:"premiums_intro_title";s:12:"varchar(255)";s:19:"premiums_intro_text";s:4:"text";}s:15:"civicrm_product";a:3:{s:4:"name";s:12:"varchar(255)";s:11:"description";s:4:"text";s:7:"options";s:4:"text";}s:23:"civicrm_membership_type";a:2:{s:4:"name";s:12:"varchar(128)";s:11:"description";s:12:"varchar(255)";}s:25:"civicrm_membership_status";a:1:{s:4:"name";s:12:"varchar(128)";}s:19:"civicrm_tell_friend";a:5:{s:5:"title";s:12:"varchar(255)";s:5:"intro";s:4:"text";s:17:"suggested_message";s:4:"text";s:14:"thankyou_title";s:12:"varchar(255)";s:13:"thankyou_text";s:4:"text";}s:20:"civicrm_option_value";a:2:{s:5:"label";s:12:"varchar(255)";s:11:"description";s:12:"varchar(255)";}s:19:"civicrm_price_field";a:3:{s:5:"label";s:12:"varchar(255)";s:8:"help_pre";s:4:"text";s:9:"help_post";s:4:"text";}s:25:"civicrm_contribution_page";a:13:{s:5:"title";s:12:"varchar(255)";s:10:"intro_text";s:4:"text";s:14:"pay_later_text";s:4:"text";s:17:"pay_later_receipt";s:4:"text";s:14:"thankyou_title";s:12:"varchar(255)";s:13:"thankyou_text";s:4:"text";s:15:"thankyou_footer";s:4:"text";s:16:"for_organization";s:4:"text";s:17:"receipt_from_name";s:12:"varchar(255)";s:12:"receipt_text";s:4:"text";s:11:"footer_text";s:4:"text";s:17:"honor_block_title";s:12:"varchar(255)";s:16:"honor_block_text";s:4:"text";}s:24:"civicrm_membership_block";a:4:{s:9:"new_title";s:12:"varchar(255)";s:8:"new_text";s:4:"text";s:13:"renewal_title";s:12:"varchar(255)";s:12:"renewal_text";s:4:"text";}s:16:"civicrm_uf_group";a:3:{s:5:"title";s:11:"varchar(64)";s:8:"help_pre";s:4:"text";s:9:"help_post";s:4:"text";}s:16:"civicrm_uf_field";a:2:{s:9:"help_post";s:4:"text";s:5:"label";s:12:"varchar(255)";}s:13:"civicrm_event";a:18:{s:5:"title";s:12:"varchar(255)";s:7:"summary";s:4:"text";s:11:"description";s:4:"text";s:22:"registration_link_text";s:12:"varchar(255)";s:15:"event_full_text";s:4:"text";s:9:"fee_label";s:12:"varchar(255)";s:10:"intro_text";s:4:"text";s:11:"footer_text";s:4:"text";s:13:"confirm_title";s:12:"varchar(255)";s:12:"confirm_text";s:4:"text";s:19:"confirm_footer_text";s:4:"text";s:18:"confirm_email_text";s:4:"text";s:17:"confirm_from_name";s:12:"varchar(255)";s:14:"thankyou_title";s:12:"varchar(255)";s:13:"thankyou_text";s:4:"text";s:20:"thankyou_footer_text";s:4:"text";s:14:"pay_later_text";s:4:"text";s:17:"pay_later_receipt";s:4:"text";}}');
-    }
-    return $result;
-  }
-
-  /**
-   * @return mixed
-   */
-  public static function &indices() {
-    static $result = NULL;
-    if (!$result) {
-      $result = unserialize('a:4:{s:20:"civicrm_custom_group";a:1:{s:16:"UI_title_extends";a:4:{s:4:"name";s:16:"UI_title_extends";s:5:"field";a:2:{i:0;s:5:"title";i:1;s:7:"extends";}s:11:"localizable";b:1;s:6:"unique";b:1;}}s:20:"civicrm_custom_field";a:1:{s:24:"UI_label_custom_group_id";a:4:{s:4:"name";s:24:"UI_label_custom_group_id";s:5:"field";a:2:{i:0;s:5:"label";i:1;s:15:"custom_group_id";}s:11:"localizable";b:1;s:6:"unique";b:1;}}s:17:"civicrm_price_set";a:1:{s:8:"UI_title";a:4:{s:4:"name";s:8:"UI_title";s:5:"field";a:1:{i:0;s:5:"title";}s:11:"localizable";b:1;s:6:"unique";b:1;}}s:15:"civicrm_contact";a:5:{s:15:"index_sort_name";a:3:{s:4:"name";s:15:"index_sort_name";s:5:"field";a:1:{i:0;s:9:"sort_name";}s:11:"localizable";b:1;}s:16:"index_first_name";a:3:{s:4:"name";s:16:"index_first_name";s:5:"field";a:1:{i:0;s:10:"first_name";}s:11:"localizable";b:1;}s:15:"index_last_name";a:3:{s:4:"name";s:15:"index_last_name";s:5:"field";a:1:{i:0;s:9:"last_name";}s:11:"localizable";b:1;}s:20:"index_household_name";a:3:{s:4:"name";s:20:"index_household_name";s:5:"field";a:1:{i:0;s:14:"household_name";}s:11:"localizable";b:1;}s:23:"index_organization_name";a:3:{s:4:"name";s:23:"index_organization_name";s:5:"field";a:1:{i:0;s:17:"organization_name";}s:11:"localizable";b:1;}}}');
-    }
-    return $result;
-  }
-
-  /**
-   * @return array
-   */
-  public static function &tables() {
-    static $result = NULL;
-    if (!$result) {
-      $result = array_keys(self::columns());
-    }
-    return $result;
-  }
-
-}
diff --git a/civicrm/CRM/Core/I18n/SchemaStructure_3_0_alpha1.php b/civicrm/CRM/Core/I18n/SchemaStructure_3_0_alpha1.php
deleted file mode 100644
index 4a8a6485ce..0000000000
--- a/civicrm/CRM/Core/I18n/SchemaStructure_3_0_alpha1.php
+++ /dev/null
@@ -1,251 +0,0 @@
-<?php
-/*
- +--------------------------------------------------------------------+
- | CiviCRM version 4.7                                                |
- +--------------------------------------------------------------------+
- | Copyright CiviCRM LLC (c) 2004-2018                                |
- +--------------------------------------------------------------------+
- | 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-2018
- * $Id$
- *
- */
-class CRM_Core_I18n_SchemaStructure_3_0_alpha1 {
-  /**
-   * @return array
-   */
-  public static function &columns() {
-    static $result = NULL;
-    if (!$result) {
-      $result = array(
-        'civicrm_option_group' => array(
-          'label' => 'varchar(255)',
-          'description' => 'varchar(255)',
-        ),
-        'civicrm_price_set' => array(
-          'title' => 'varchar(255)',
-          'help_pre' => 'text',
-          'help_post' => 'text',
-        ),
-        'civicrm_contact' => array(
-          'sort_name' => 'varchar(128)',
-          'display_name' => 'varchar(128)',
-          'first_name' => 'varchar(64)',
-          'middle_name' => 'varchar(64)',
-          'last_name' => 'varchar(64)',
-          'email_greeting_display' => 'varchar(255)',
-          'postal_greeting_display' => 'varchar(255)',
-          'addressee_display' => 'varchar(255)',
-          'household_name' => 'varchar(128)',
-          'organization_name' => 'varchar(128)',
-        ),
-        'civicrm_premiums' => array(
-          'premiums_intro_title' => 'varchar(255)',
-          'premiums_intro_text' => 'text',
-        ),
-        'civicrm_product' => array(
-          'name' => 'varchar(255)',
-          'description' => 'text',
-          'options' => 'text',
-        ),
-        'civicrm_membership_type' => array(
-          'name' => 'varchar(128)',
-          'description' => 'varchar(255)',
-        ),
-        'civicrm_membership_status' => array(
-          'name' => 'varchar(128)',
-        ),
-        'civicrm_participant_status_type' => array(
-          'label' => 'varchar(255)',
-        ),
-        'civicrm_tell_friend' => array(
-          'title' => 'varchar(255)',
-          'intro' => 'text',
-          'suggested_message' => 'text',
-          'thankyou_title' => 'varchar(255)',
-          'thankyou_text' => 'text',
-        ),
-        'civicrm_custom_group' => array(
-          'title' => 'varchar(64)',
-          'help_pre' => 'text',
-          'help_post' => 'text',
-        ),
-        'civicrm_custom_field' => array(
-          'label' => 'varchar(255)',
-          'help_pre' => 'text',
-          'help_post' => 'text',
-        ),
-        'civicrm_option_value' => array(
-          'label' => 'varchar(255)',
-          'description' => 'varchar(255)',
-        ),
-        'civicrm_price_field' => array(
-          'label' => 'varchar(255)',
-          'help_pre' => 'text',
-          'help_post' => 'text',
-        ),
-        'civicrm_contribution_page' => array(
-          'title' => 'varchar(255)',
-          'intro_text' => 'text',
-          'pay_later_text' => 'text',
-          'pay_later_receipt' => 'text',
-          'thankyou_title' => 'varchar(255)',
-          'thankyou_text' => 'text',
-          'thankyou_footer' => 'text',
-          'for_organization' => 'text',
-          'receipt_from_name' => 'varchar(255)',
-          'receipt_text' => 'text',
-          'footer_text' => 'text',
-          'honor_block_title' => 'varchar(255)',
-          'honor_block_text' => 'text',
-        ),
-        'civicrm_membership_block' => array(
-          'new_title' => 'varchar(255)',
-          'new_text' => 'text',
-          'renewal_title' => 'varchar(255)',
-          'renewal_text' => 'text',
-        ),
-        'civicrm_uf_group' => array(
-          'title' => 'varchar(64)',
-          'help_pre' => 'text',
-          'help_post' => 'text',
-        ),
-        'civicrm_uf_field' => array(
-          'help_post' => 'text',
-          'label' => 'varchar(255)',
-        ),
-        'civicrm_event' => array(
-          'title' => 'varchar(255)',
-          'summary' => 'text',
-          'description' => 'text',
-          'registration_link_text' => 'varchar(255)',
-          'event_full_text' => 'text',
-          'fee_label' => 'varchar(255)',
-          'intro_text' => 'text',
-          'footer_text' => 'text',
-          'confirm_title' => 'varchar(255)',
-          'confirm_text' => 'text',
-          'confirm_footer_text' => 'text',
-          'confirm_email_text' => 'text',
-          'confirm_from_name' => 'varchar(255)',
-          'thankyou_title' => 'varchar(255)',
-          'thankyou_text' => 'text',
-          'thankyou_footer_text' => 'text',
-          'pay_later_text' => 'text',
-          'pay_later_receipt' => 'text',
-          'waitlist_text' => 'text',
-          'approval_req_text' => 'text',
-          'template_title' => 'varchar(255)',
-        ),
-      );
-    }
-    return $result;
-  }
-
-  /**
-   * @return array
-   */
-  public static function &indices() {
-    static $result = NULL;
-    if (!$result) {
-      $result = array(
-        'civicrm_price_set' => array(
-          'UI_title' => array(
-            'name' => 'UI_title',
-            'field' => array(
-              'title',
-            ),
-            'unique' => 1,
-          ),
-        ),
-        'civicrm_contact' => array(
-          'index_sort_name' => array(
-            'name' => 'index_sort_name',
-            'field' => array(
-              'sort_name',
-            ),
-          ),
-          'index_first_name' => array(
-            'name' => 'index_first_name',
-            'field' => array(
-              'first_name',
-            ),
-          ),
-          'index_last_name' => array(
-            'name' => 'index_last_name',
-            'field' => array(
-              'last_name',
-            ),
-          ),
-          'index_household_name' => array(
-            'name' => 'index_household_name',
-            'field' => array(
-              'household_name',
-            ),
-          ),
-          'index_organization_name' => array(
-            'name' => 'index_organization_name',
-            'field' => array(
-              'organization_name',
-            ),
-          ),
-        ),
-        'civicrm_custom_group' => array(
-          'UI_title_extends' => array(
-            'name' => 'UI_title_extends',
-            'field' => array(
-              'title',
-              'extends',
-            ),
-            'unique' => 1,
-          ),
-        ),
-        'civicrm_custom_field' => array(
-          'UI_label_custom_group_id' => array(
-            'name' => 'UI_label_custom_group_id',
-            'field' => array(
-              'label',
-              'custom_group_id',
-            ),
-            'unique' => 1,
-          ),
-        ),
-      );
-    }
-    return $result;
-  }
-
-  /**
-   * @return array $result
-   */
-  public static function &tables() {
-    static $result = NULL;
-    if (!$result) {
-      $result = array_keys(self::columns());
-    }
-    return $result;
-  }
-
-}
diff --git a/civicrm/CRM/Core/I18n/SchemaStructure_3_0_beta1.php b/civicrm/CRM/Core/I18n/SchemaStructure_3_0_beta1.php
deleted file mode 100644
index 7a3d298a30..0000000000
--- a/civicrm/CRM/Core/I18n/SchemaStructure_3_0_beta1.php
+++ /dev/null
@@ -1,267 +0,0 @@
-<?php
-/*
- +--------------------------------------------------------------------+
- | CiviCRM version 4.7                                                |
- +--------------------------------------------------------------------+
- | Copyright CiviCRM LLC (c) 2004-2018                                |
- +--------------------------------------------------------------------+
- | 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-2018
- * $Id$
- *
- */
-class CRM_Core_I18n_SchemaStructure_3_0_beta1 {
-  /**
-   * @return array
-   */
-  public static function &columns() {
-    static $result = NULL;
-    if (!$result) {
-      $result = array(
-        'civicrm_option_group' => array(
-          'label' => 'varchar(255)',
-          'description' => 'varchar(255)',
-        ),
-        'civicrm_price_set' => array(
-          'title' => 'varchar(255)',
-          'help_pre' => 'text',
-          'help_post' => 'text',
-        ),
-        'civicrm_contact' => array(
-          'sort_name' => 'varchar(128)',
-          'display_name' => 'varchar(128)',
-          'first_name' => 'varchar(64)',
-          'middle_name' => 'varchar(64)',
-          'last_name' => 'varchar(64)',
-          'email_greeting_display' => 'varchar(255)',
-          'postal_greeting_display' => 'varchar(255)',
-          'addressee_display' => 'varchar(255)',
-          'household_name' => 'varchar(128)',
-          'organization_name' => 'varchar(128)',
-        ),
-        'civicrm_premiums' => array(
-          'premiums_intro_title' => 'varchar(255)',
-          'premiums_intro_text' => 'text',
-        ),
-        'civicrm_product' => array(
-          'name' => 'varchar(255)',
-          'description' => 'text',
-          'options' => 'text',
-        ),
-        'civicrm_membership_type' => array(
-          'name' => 'varchar(128)',
-          'description' => 'varchar(255)',
-        ),
-        'civicrm_membership_status' => array(
-          'name' => 'varchar(128)',
-        ),
-        'civicrm_participant_status_type' => array(
-          'label' => 'varchar(255)',
-        ),
-        'civicrm_tell_friend' => array(
-          'title' => 'varchar(255)',
-          'intro' => 'text',
-          'suggested_message' => 'text',
-          'thankyou_title' => 'varchar(255)',
-          'thankyou_text' => 'text',
-        ),
-        'civicrm_custom_group' => array(
-          'title' => 'varchar(64)',
-          'help_pre' => 'text',
-          'help_post' => 'text',
-        ),
-        'civicrm_custom_field' => array(
-          'label' => 'varchar(255)',
-          'help_pre' => 'text',
-          'help_post' => 'text',
-        ),
-        'civicrm_option_value' => array(
-          'label' => 'varchar(255)',
-          'description' => 'varchar(255)',
-        ),
-        'civicrm_price_field' => array(
-          'label' => 'varchar(255)',
-          'help_pre' => 'text',
-          'help_post' => 'text',
-        ),
-        'civicrm_contribution_page' => array(
-          'title' => 'varchar(255)',
-          'intro_text' => 'text',
-          'pay_later_text' => 'text',
-          'pay_later_receipt' => 'text',
-          'thankyou_title' => 'varchar(255)',
-          'thankyou_text' => 'text',
-          'thankyou_footer' => 'text',
-          'for_organization' => 'text',
-          'receipt_from_name' => 'varchar(255)',
-          'receipt_text' => 'text',
-          'footer_text' => 'text',
-          'honor_block_title' => 'varchar(255)',
-          'honor_block_text' => 'text',
-        ),
-        'civicrm_membership_block' => array(
-          'new_title' => 'varchar(255)',
-          'new_text' => 'text',
-          'renewal_title' => 'varchar(255)',
-          'renewal_text' => 'text',
-        ),
-        'civicrm_uf_group' => array(
-          'title' => 'varchar(64)',
-          'help_pre' => 'text',
-          'help_post' => 'text',
-        ),
-        'civicrm_uf_field' => array(
-          'help_post' => 'text',
-          'label' => 'varchar(255)',
-        ),
-        'civicrm_address' => array(
-          'street_address' => 'varchar(96)',
-          'supplemental_address_1' => 'varchar(96)',
-          'supplemental_address_2' => 'varchar(96)',
-          'supplemental_address_3' => 'varchar(96)',
-          'city' => 'varchar(64)',
-          'name' => 'varchar(255)',
-        ),
-        'civicrm_event' => array(
-          'title' => 'varchar(255)',
-          'summary' => 'text',
-          'description' => 'text',
-          'registration_link_text' => 'varchar(255)',
-          'event_full_text' => 'text',
-          'fee_label' => 'varchar(255)',
-          'intro_text' => 'text',
-          'footer_text' => 'text',
-          'confirm_title' => 'varchar(255)',
-          'confirm_text' => 'text',
-          'confirm_footer_text' => 'text',
-          'confirm_email_text' => 'text',
-          'confirm_from_name' => 'varchar(255)',
-          'thankyou_title' => 'varchar(255)',
-          'thankyou_text' => 'text',
-          'thankyou_footer_text' => 'text',
-          'pay_later_text' => 'text',
-          'pay_later_receipt' => 'text',
-          'waitlist_text' => 'text',
-          'approval_req_text' => 'text',
-          'template_title' => 'varchar(255)',
-        ),
-      );
-    }
-    return $result;
-  }
-
-  /**
-   * @return array
-   */
-  public static function &indices() {
-    static $result = NULL;
-    if (!$result) {
-      $result = array(
-        'civicrm_price_set' => array(
-          'UI_title' => array(
-            'name' => 'UI_title',
-            'field' => array(
-              'title',
-            ),
-            'unique' => 1,
-          ),
-        ),
-        'civicrm_contact' => array(
-          'index_sort_name' => array(
-            'name' => 'index_sort_name',
-            'field' => array(
-              'sort_name',
-            ),
-          ),
-          'index_first_name' => array(
-            'name' => 'index_first_name',
-            'field' => array(
-              'first_name',
-            ),
-          ),
-          'index_last_name' => array(
-            'name' => 'index_last_name',
-            'field' => array(
-              'last_name',
-            ),
-          ),
-          'index_household_name' => array(
-            'name' => 'index_household_name',
-            'field' => array(
-              'household_name',
-            ),
-          ),
-          'index_organization_name' => array(
-            'name' => 'index_organization_name',
-            'field' => array(
-              'organization_name',
-            ),
-          ),
-        ),
-        'civicrm_custom_group' => array(
-          'UI_title_extends' => array(
-            'name' => 'UI_title_extends',
-            'field' => array(
-              'title',
-              'extends',
-            ),
-            'unique' => 1,
-          ),
-        ),
-        'civicrm_custom_field' => array(
-          'UI_label_custom_group_id' => array(
-            'name' => 'UI_label_custom_group_id',
-            'field' => array(
-              'label',
-              'custom_group_id',
-            ),
-            'unique' => 1,
-          ),
-        ),
-        'civicrm_address' => array(
-          'index_city' => array(
-            'name' => 'index_city',
-            'field' => array(
-              'city',
-            ),
-          ),
-        ),
-      );
-    }
-    return $result;
-  }
-
-  /**
-   * @return array
-   */
-  public static function &tables() {
-    static $result = NULL;
-    if (!$result) {
-      $result = array_keys(self::columns());
-    }
-    return $result;
-  }
-
-}
diff --git a/civicrm/CRM/Core/I18n/SchemaStructure_3_0_beta4.php b/civicrm/CRM/Core/I18n/SchemaStructure_3_0_beta4.php
deleted file mode 100644
index 458d029461..0000000000
--- a/civicrm/CRM/Core/I18n/SchemaStructure_3_0_beta4.php
+++ /dev/null
@@ -1,280 +0,0 @@
-<?php
-/*
- +--------------------------------------------------------------------+
- | CiviCRM version 4.7                                                |
- +--------------------------------------------------------------------+
- | Copyright CiviCRM LLC (c) 2004-2018                                |
- +--------------------------------------------------------------------+
- | 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-2018
- * $Id$
- *
- */
-class CRM_Core_I18n_SchemaStructure_3_0_beta4 {
-  /**
-   * @return array
-   */
-  public static function &columns() {
-    static $result = NULL;
-    if (!$result) {
-      $result = array(
-        'civicrm_option_group' => array(
-          'label' => 'varchar(255)',
-          'description' => 'varchar(255)',
-        ),
-        'civicrm_price_set' => array(
-          'title' => 'varchar(255)',
-          'help_pre' => 'text',
-          'help_post' => 'text',
-        ),
-        'civicrm_contact' => array(
-          'sort_name' => 'varchar(128)',
-          'display_name' => 'varchar(128)',
-          'first_name' => 'varchar(64)',
-          'middle_name' => 'varchar(64)',
-          'last_name' => 'varchar(64)',
-          'email_greeting_display' => 'varchar(255)',
-          'postal_greeting_display' => 'varchar(255)',
-          'addressee_display' => 'varchar(255)',
-          'household_name' => 'varchar(128)',
-          'organization_name' => 'varchar(128)',
-        ),
-        'civicrm_mailing_component' => array(
-          'name' => 'varchar(64)',
-          'subject' => 'varchar(255)',
-          'body_html' => 'text',
-          'body_text' => 'text',
-        ),
-        'civicrm_mailing' => array(
-          'name' => 'varchar(128)',
-          'from_name' => 'varchar(128)',
-          'subject' => 'varchar(128)',
-          'body_text' => 'longtext',
-          'body_html' => 'longtext',
-        ),
-        'civicrm_premiums' => array(
-          'premiums_intro_title' => 'varchar(255)',
-          'premiums_intro_text' => 'text',
-        ),
-        'civicrm_product' => array(
-          'name' => 'varchar(255)',
-          'description' => 'text',
-          'options' => 'text',
-        ),
-        'civicrm_membership_type' => array(
-          'name' => 'varchar(128)',
-          'description' => 'varchar(255)',
-        ),
-        'civicrm_membership_status' => array(
-          'name' => 'varchar(128)',
-        ),
-        'civicrm_participant_status_type' => array(
-          'label' => 'varchar(255)',
-        ),
-        'civicrm_tell_friend' => array(
-          'title' => 'varchar(255)',
-          'intro' => 'text',
-          'suggested_message' => 'text',
-          'thankyou_title' => 'varchar(255)',
-          'thankyou_text' => 'text',
-        ),
-        'civicrm_custom_group' => array(
-          'title' => 'varchar(64)',
-          'help_pre' => 'text',
-          'help_post' => 'text',
-        ),
-        'civicrm_custom_field' => array(
-          'label' => 'varchar(255)',
-          'help_pre' => 'text',
-          'help_post' => 'text',
-        ),
-        'civicrm_option_value' => array(
-          'label' => 'varchar(255)',
-          'description' => 'varchar(255)',
-        ),
-        'civicrm_price_field' => array(
-          'label' => 'varchar(255)',
-          'help_pre' => 'text',
-          'help_post' => 'text',
-        ),
-        'civicrm_contribution_page' => array(
-          'title' => 'varchar(255)',
-          'intro_text' => 'text',
-          'pay_later_text' => 'text',
-          'pay_later_receipt' => 'text',
-          'thankyou_title' => 'varchar(255)',
-          'thankyou_text' => 'text',
-          'thankyou_footer' => 'text',
-          'for_organization' => 'text',
-          'receipt_from_name' => 'varchar(255)',
-          'receipt_text' => 'text',
-          'footer_text' => 'text',
-          'honor_block_title' => 'varchar(255)',
-          'honor_block_text' => 'text',
-        ),
-        'civicrm_membership_block' => array(
-          'new_title' => 'varchar(255)',
-          'new_text' => 'text',
-          'renewal_title' => 'varchar(255)',
-          'renewal_text' => 'text',
-        ),
-        'civicrm_uf_group' => array(
-          'title' => 'varchar(64)',
-          'help_pre' => 'text',
-          'help_post' => 'text',
-        ),
-        'civicrm_uf_field' => array(
-          'help_post' => 'text',
-          'label' => 'varchar(255)',
-        ),
-        'civicrm_address' => array(
-          'street_address' => 'varchar(96)',
-          'supplemental_address_1' => 'varchar(96)',
-          'supplemental_address_2' => 'varchar(96)',
-          'supplemental_address_3' => 'varchar(96)',
-          'city' => 'varchar(64)',
-          'name' => 'varchar(255)',
-        ),
-        'civicrm_event' => array(
-          'title' => 'varchar(255)',
-          'summary' => 'text',
-          'description' => 'text',
-          'registration_link_text' => 'varchar(255)',
-          'event_full_text' => 'text',
-          'fee_label' => 'varchar(255)',
-          'intro_text' => 'text',
-          'footer_text' => 'text',
-          'confirm_title' => 'varchar(255)',
-          'confirm_text' => 'text',
-          'confirm_footer_text' => 'text',
-          'confirm_email_text' => 'text',
-          'confirm_from_name' => 'varchar(255)',
-          'thankyou_title' => 'varchar(255)',
-          'thankyou_text' => 'text',
-          'thankyou_footer_text' => 'text',
-          'pay_later_text' => 'text',
-          'pay_later_receipt' => 'text',
-          'waitlist_text' => 'text',
-          'approval_req_text' => 'text',
-          'template_title' => 'varchar(255)',
-        ),
-      );
-    }
-    return $result;
-  }
-
-  /**
-   * @return array
-   */
-  public static function &indices() {
-    static $result = NULL;
-    if (!$result) {
-      $result = array(
-        'civicrm_price_set' => array(
-          'UI_title' => array(
-            'name' => 'UI_title',
-            'field' => array(
-              'title',
-            ),
-            'unique' => 1,
-          ),
-        ),
-        'civicrm_contact' => array(
-          'index_sort_name' => array(
-            'name' => 'index_sort_name',
-            'field' => array(
-              'sort_name',
-            ),
-          ),
-          'index_first_name' => array(
-            'name' => 'index_first_name',
-            'field' => array(
-              'first_name',
-            ),
-          ),
-          'index_last_name' => array(
-            'name' => 'index_last_name',
-            'field' => array(
-              'last_name',
-            ),
-          ),
-          'index_household_name' => array(
-            'name' => 'index_household_name',
-            'field' => array(
-              'household_name',
-            ),
-          ),
-          'index_organization_name' => array(
-            'name' => 'index_organization_name',
-            'field' => array(
-              'organization_name',
-            ),
-          ),
-        ),
-        'civicrm_custom_group' => array(
-          'UI_title_extends' => array(
-            'name' => 'UI_title_extends',
-            'field' => array(
-              'title',
-              'extends',
-            ),
-            'unique' => 1,
-          ),
-        ),
-        'civicrm_custom_field' => array(
-          'UI_label_custom_group_id' => array(
-            'name' => 'UI_label_custom_group_id',
-            'field' => array(
-              'label',
-              'custom_group_id',
-            ),
-            'unique' => 1,
-          ),
-        ),
-        'civicrm_address' => array(
-          'index_city' => array(
-            'name' => 'index_city',
-            'field' => array(
-              'city',
-            ),
-          ),
-        ),
-      );
-    }
-    return $result;
-  }
-
-  /**
-   * @return array
-   */
-  public static function &tables() {
-    static $result = NULL;
-    if (!$result) {
-      $result = array_keys(self::columns());
-    }
-    return $result;
-  }
-
-}
diff --git a/civicrm/CRM/Core/I18n/SchemaStructure_3_1_alpha1.php b/civicrm/CRM/Core/I18n/SchemaStructure_3_1_alpha1.php
deleted file mode 100644
index 95582b8a1e..0000000000
--- a/civicrm/CRM/Core/I18n/SchemaStructure_3_1_alpha1.php
+++ /dev/null
@@ -1,284 +0,0 @@
-<?php
-/*
- +--------------------------------------------------------------------+
- | CiviCRM version 4.7                                                |
- +--------------------------------------------------------------------+
- | Copyright CiviCRM LLC (c) 2004-2018                                |
- +--------------------------------------------------------------------+
- | 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-2018
- * $Id$
- *
- */
-class CRM_Core_I18n_SchemaStructure_3_1_alpha1 {
-  /**
-   * @return array
-   */
-  public static function &columns() {
-    static $result = NULL;
-    if (!$result) {
-      $result = array(
-        'civicrm_option_group' => array(
-          'label' => 'varchar(255)',
-          'description' => 'varchar(255)',
-        ),
-        'civicrm_contact' => array(
-          'sort_name' => 'varchar(128)',
-          'display_name' => 'varchar(128)',
-          'first_name' => 'varchar(64)',
-          'middle_name' => 'varchar(64)',
-          'last_name' => 'varchar(64)',
-          'email_greeting_display' => 'varchar(255)',
-          'postal_greeting_display' => 'varchar(255)',
-          'addressee_display' => 'varchar(255)',
-          'household_name' => 'varchar(128)',
-          'organization_name' => 'varchar(128)',
-        ),
-        'civicrm_contact_type' => array(
-          'label' => 'varchar(64)',
-          'description' => 'text',
-        ),
-        'civicrm_mailing_component' => array(
-          'name' => 'varchar(64)',
-          'subject' => 'varchar(255)',
-          'body_html' => 'text',
-          'body_text' => 'text',
-        ),
-        'civicrm_mailing' => array(
-          'name' => 'varchar(128)',
-          'from_name' => 'varchar(128)',
-          'subject' => 'varchar(128)',
-          'body_text' => 'longtext',
-          'body_html' => 'longtext',
-        ),
-        'civicrm_premiums' => array(
-          'premiums_intro_title' => 'varchar(255)',
-          'premiums_intro_text' => 'text',
-        ),
-        'civicrm_product' => array(
-          'name' => 'varchar(255)',
-          'description' => 'text',
-          'options' => 'text',
-        ),
-        'civicrm_membership_type' => array(
-          'name' => 'varchar(128)',
-          'description' => 'varchar(255)',
-        ),
-        'civicrm_membership_status' => array(
-          'name' => 'varchar(128)',
-        ),
-        'civicrm_participant_status_type' => array(
-          'label' => 'varchar(255)',
-        ),
-        'civicrm_tell_friend' => array(
-          'title' => 'varchar(255)',
-          'intro' => 'text',
-          'suggested_message' => 'text',
-          'thankyou_title' => 'varchar(255)',
-          'thankyou_text' => 'text',
-        ),
-        'civicrm_price_set' => array(
-          'title' => 'varchar(255)',
-          'help_pre' => 'text',
-          'help_post' => 'text',
-        ),
-        'civicrm_custom_group' => array(
-          'title' => 'varchar(64)',
-          'help_pre' => 'text',
-          'help_post' => 'text',
-        ),
-        'civicrm_custom_field' => array(
-          'label' => 'varchar(255)',
-          'help_pre' => 'text',
-          'help_post' => 'text',
-        ),
-        'civicrm_option_value' => array(
-          'label' => 'varchar(255)',
-          'description' => 'varchar(255)',
-        ),
-        'civicrm_contribution_page' => array(
-          'title' => 'varchar(255)',
-          'intro_text' => 'text',
-          'pay_later_text' => 'text',
-          'pay_later_receipt' => 'text',
-          'thankyou_title' => 'varchar(255)',
-          'thankyou_text' => 'text',
-          'thankyou_footer' => 'text',
-          'for_organization' => 'text',
-          'receipt_from_name' => 'varchar(255)',
-          'receipt_text' => 'text',
-          'footer_text' => 'text',
-          'honor_block_title' => 'varchar(255)',
-          'honor_block_text' => 'text',
-        ),
-        'civicrm_membership_block' => array(
-          'new_title' => 'varchar(255)',
-          'new_text' => 'text',
-          'renewal_title' => 'varchar(255)',
-          'renewal_text' => 'text',
-        ),
-        'civicrm_price_field' => array(
-          'label' => 'varchar(255)',
-          'help_pre' => 'text',
-          'help_post' => 'text',
-        ),
-        'civicrm_uf_group' => array(
-          'title' => 'varchar(64)',
-          'help_pre' => 'text',
-          'help_post' => 'text',
-        ),
-        'civicrm_uf_field' => array(
-          'help_post' => 'text',
-          'label' => 'varchar(255)',
-        ),
-        'civicrm_address' => array(
-          'street_address' => 'varchar(96)',
-          'supplemental_address_1' => 'varchar(96)',
-          'supplemental_address_2' => 'varchar(96)',
-          'supplemental_address_3' => 'varchar(96)',
-          'city' => 'varchar(64)',
-          'name' => 'varchar(255)',
-        ),
-        'civicrm_event' => array(
-          'title' => 'varchar(255)',
-          'summary' => 'text',
-          'description' => 'text',
-          'registration_link_text' => 'varchar(255)',
-          'event_full_text' => 'text',
-          'fee_label' => 'varchar(255)',
-          'intro_text' => 'text',
-          'footer_text' => 'text',
-          'confirm_title' => 'varchar(255)',
-          'confirm_text' => 'text',
-          'confirm_footer_text' => 'text',
-          'confirm_email_text' => 'text',
-          'confirm_from_name' => 'varchar(255)',
-          'thankyou_title' => 'varchar(255)',
-          'thankyou_text' => 'text',
-          'thankyou_footer_text' => 'text',
-          'pay_later_text' => 'text',
-          'pay_later_receipt' => 'text',
-          'waitlist_text' => 'text',
-          'approval_req_text' => 'text',
-          'template_title' => 'varchar(255)',
-        ),
-      );
-    }
-    return $result;
-  }
-
-  /**
-   * @return array
-   */
-  public static function &indices() {
-    static $result = NULL;
-    if (!$result) {
-      $result = array(
-        'civicrm_contact' => array(
-          'index_sort_name' => array(
-            'name' => 'index_sort_name',
-            'field' => array(
-              'sort_name',
-            ),
-          ),
-          'index_first_name' => array(
-            'name' => 'index_first_name',
-            'field' => array(
-              'first_name',
-            ),
-          ),
-          'index_last_name' => array(
-            'name' => 'index_last_name',
-            'field' => array(
-              'last_name',
-            ),
-          ),
-          'index_household_name' => array(
-            'name' => 'index_household_name',
-            'field' => array(
-              'household_name',
-            ),
-          ),
-          'index_organization_name' => array(
-            'name' => 'index_organization_name',
-            'field' => array(
-              'organization_name',
-            ),
-          ),
-        ),
-        'civicrm_price_set' => array(
-          'UI_title' => array(
-            'name' => 'UI_title',
-            'field' => array(
-              'title',
-            ),
-            'unique' => 1,
-          ),
-        ),
-        'civicrm_custom_group' => array(
-          'UI_title_extends' => array(
-            'name' => 'UI_title_extends',
-            'field' => array(
-              'title',
-              'extends',
-            ),
-            'unique' => 1,
-          ),
-        ),
-        'civicrm_custom_field' => array(
-          'UI_label_custom_group_id' => array(
-            'name' => 'UI_label_custom_group_id',
-            'field' => array(
-              'label',
-              'custom_group_id',
-            ),
-            'unique' => 1,
-          ),
-        ),
-        'civicrm_address' => array(
-          'index_city' => array(
-            'name' => 'index_city',
-            'field' => array(
-              'city',
-            ),
-          ),
-        ),
-      );
-    }
-    return $result;
-  }
-
-  /**
-   * @return array
-   */
-  public static function &tables() {
-    static $result = NULL;
-    if (!$result) {
-      $result = array_keys(self::columns());
-    }
-    return $result;
-  }
-
-}
diff --git a/civicrm/CRM/Core/I18n/SchemaStructure_3_1_beta2.php b/civicrm/CRM/Core/I18n/SchemaStructure_3_1_beta2.php
deleted file mode 100644
index 1d3acb2aa2..0000000000
--- a/civicrm/CRM/Core/I18n/SchemaStructure_3_1_beta2.php
+++ /dev/null
@@ -1,287 +0,0 @@
-<?php
-/*
- +--------------------------------------------------------------------+
- | CiviCRM version 4.7                                                |
- +--------------------------------------------------------------------+
- | Copyright CiviCRM LLC (c) 2004-2018                                |
- +--------------------------------------------------------------------+
- | 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-2018
- * $Id$
- *
- */
-class CRM_Core_I18n_SchemaStructure_3_1_beta2 {
-  /**
-   * @return array
-   */
-  public static function &columns() {
-    static $result = NULL;
-    if (!$result) {
-      $result = array(
-        'civicrm_option_group' => array(
-          'label' => 'varchar(255)',
-          'description' => 'varchar(255)',
-        ),
-        'civicrm_contact' => array(
-          'sort_name' => 'varchar(128)',
-          'display_name' => 'varchar(128)',
-          'first_name' => 'varchar(64)',
-          'middle_name' => 'varchar(64)',
-          'last_name' => 'varchar(64)',
-          'email_greeting_display' => 'varchar(255)',
-          'postal_greeting_display' => 'varchar(255)',
-          'addressee_display' => 'varchar(255)',
-          'household_name' => 'varchar(128)',
-          'organization_name' => 'varchar(128)',
-        ),
-        'civicrm_contact_type' => array(
-          'label' => 'varchar(64)',
-          'description' => 'text',
-        ),
-        'civicrm_mailing_component' => array(
-          'name' => 'varchar(64)',
-          'subject' => 'varchar(255)',
-          'body_html' => 'text',
-          'body_text' => 'text',
-        ),
-        'civicrm_mailing' => array(
-          'name' => 'varchar(128)',
-          'from_name' => 'varchar(128)',
-          'subject' => 'varchar(128)',
-          'body_text' => 'longtext',
-          'body_html' => 'longtext',
-        ),
-        'civicrm_premiums' => array(
-          'premiums_intro_title' => 'varchar(255)',
-          'premiums_intro_text' => 'text',
-        ),
-        'civicrm_product' => array(
-          'name' => 'varchar(255)',
-          'description' => 'text',
-          'options' => 'text',
-        ),
-        'civicrm_membership_type' => array(
-          'name' => 'varchar(128)',
-          'description' => 'varchar(255)',
-        ),
-        'civicrm_membership_status' => array(
-          'name' => 'varchar(128)',
-        ),
-        'civicrm_participant_status_type' => array(
-          'label' => 'varchar(255)',
-        ),
-        'civicrm_tell_friend' => array(
-          'title' => 'varchar(255)',
-          'intro' => 'text',
-          'suggested_message' => 'text',
-          'thankyou_title' => 'varchar(255)',
-          'thankyou_text' => 'text',
-        ),
-        'civicrm_price_set' => array(
-          'title' => 'varchar(255)',
-          'help_pre' => 'text',
-          'help_post' => 'text',
-        ),
-        'civicrm_custom_group' => array(
-          'title' => 'varchar(64)',
-          'help_pre' => 'text',
-          'help_post' => 'text',
-        ),
-        'civicrm_custom_field' => array(
-          'label' => 'varchar(255)',
-          'help_pre' => 'text',
-          'help_post' => 'text',
-        ),
-        'civicrm_dashboard' => array(
-          'label' => 'varchar(255)',
-        ),
-        'civicrm_option_value' => array(
-          'label' => 'varchar(255)',
-          'description' => 'varchar(255)',
-        ),
-        'civicrm_contribution_page' => array(
-          'title' => 'varchar(255)',
-          'intro_text' => 'text',
-          'pay_later_text' => 'text',
-          'pay_later_receipt' => 'text',
-          'thankyou_title' => 'varchar(255)',
-          'thankyou_text' => 'text',
-          'thankyou_footer' => 'text',
-          'for_organization' => 'text',
-          'receipt_from_name' => 'varchar(255)',
-          'receipt_text' => 'text',
-          'footer_text' => 'text',
-          'honor_block_title' => 'varchar(255)',
-          'honor_block_text' => 'text',
-        ),
-        'civicrm_membership_block' => array(
-          'new_title' => 'varchar(255)',
-          'new_text' => 'text',
-          'renewal_title' => 'varchar(255)',
-          'renewal_text' => 'text',
-        ),
-        'civicrm_price_field' => array(
-          'label' => 'varchar(255)',
-          'help_pre' => 'text',
-          'help_post' => 'text',
-        ),
-        'civicrm_uf_group' => array(
-          'title' => 'varchar(64)',
-          'help_pre' => 'text',
-          'help_post' => 'text',
-        ),
-        'civicrm_uf_field' => array(
-          'help_post' => 'text',
-          'label' => 'varchar(255)',
-        ),
-        'civicrm_address' => array(
-          'street_address' => 'varchar(96)',
-          'supplemental_address_1' => 'varchar(96)',
-          'supplemental_address_2' => 'varchar(96)',
-          'supplemental_address_3' => 'varchar(96)',
-          'city' => 'varchar(64)',
-          'name' => 'varchar(255)',
-        ),
-        'civicrm_event' => array(
-          'title' => 'varchar(255)',
-          'summary' => 'text',
-          'description' => 'text',
-          'registration_link_text' => 'varchar(255)',
-          'event_full_text' => 'text',
-          'fee_label' => 'varchar(255)',
-          'intro_text' => 'text',
-          'footer_text' => 'text',
-          'confirm_title' => 'varchar(255)',
-          'confirm_text' => 'text',
-          'confirm_footer_text' => 'text',
-          'confirm_email_text' => 'text',
-          'confirm_from_name' => 'varchar(255)',
-          'thankyou_title' => 'varchar(255)',
-          'thankyou_text' => 'text',
-          'thankyou_footer_text' => 'text',
-          'pay_later_text' => 'text',
-          'pay_later_receipt' => 'text',
-          'waitlist_text' => 'text',
-          'approval_req_text' => 'text',
-          'template_title' => 'varchar(255)',
-        ),
-      );
-    }
-    return $result;
-  }
-
-  /**
-   * @return array
-   */
-  public static function &indices() {
-    static $result = NULL;
-    if (!$result) {
-      $result = array(
-        'civicrm_contact' => array(
-          'index_sort_name' => array(
-            'name' => 'index_sort_name',
-            'field' => array(
-              'sort_name',
-            ),
-          ),
-          'index_first_name' => array(
-            'name' => 'index_first_name',
-            'field' => array(
-              'first_name',
-            ),
-          ),
-          'index_last_name' => array(
-            'name' => 'index_last_name',
-            'field' => array(
-              'last_name',
-            ),
-          ),
-          'index_household_name' => array(
-            'name' => 'index_household_name',
-            'field' => array(
-              'household_name',
-            ),
-          ),
-          'index_organization_name' => array(
-            'name' => 'index_organization_name',
-            'field' => array(
-              'organization_name',
-            ),
-          ),
-        ),
-        'civicrm_price_set' => array(
-          'UI_title' => array(
-            'name' => 'UI_title',
-            'field' => array(
-              'title',
-            ),
-            'unique' => 1,
-          ),
-        ),
-        'civicrm_custom_group' => array(
-          'UI_title_extends' => array(
-            'name' => 'UI_title_extends',
-            'field' => array(
-              'title',
-              'extends',
-            ),
-            'unique' => 1,
-          ),
-        ),
-        'civicrm_custom_field' => array(
-          'UI_label_custom_group_id' => array(
-            'name' => 'UI_label_custom_group_id',
-            'field' => array(
-              'label',
-              'custom_group_id',
-            ),
-            'unique' => 1,
-          ),
-        ),
-        'civicrm_address' => array(
-          'index_city' => array(
-            'name' => 'index_city',
-            'field' => array(
-              'city',
-            ),
-          ),
-        ),
-      );
-    }
-    return $result;
-  }
-
-  /**
-   * @return array
-   */
-  public static function &tables() {
-    static $result = NULL;
-    if (!$result) {
-      $result = array_keys(self::columns());
-    }
-    return $result;
-  }
-
-}
diff --git a/civicrm/CRM/Core/I18n/SchemaStructure_3_2_beta4.php b/civicrm/CRM/Core/I18n/SchemaStructure_3_2_beta4.php
deleted file mode 100644
index 16ee40660c..0000000000
--- a/civicrm/CRM/Core/I18n/SchemaStructure_3_2_beta4.php
+++ /dev/null
@@ -1,288 +0,0 @@
-<?php
-/*
-+--------------------------------------------------------------------+
-| CiviCRM version 4.7                                                |
-+--------------------------------------------------------------------+
-| Copyright CiviCRM LLC (c) 2004-2018                                |
-+--------------------------------------------------------------------+
-| 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-2018
- * $Id$
- *
- */
-class CRM_Core_I18n_SchemaStructure_3_2_beta4 {
-  /**
-   * @return array
-   */
-  public static function &columns() {
-    static $result = NULL;
-    if (!$result) {
-      $result = array(
-        'civicrm_option_group' => array(
-          'label' => 'varchar(255)',
-          'description' => 'varchar(255)',
-        ),
-        'civicrm_contact' => array(
-          'sort_name' => 'varchar(128)',
-          'display_name' => 'varchar(128)',
-          'first_name' => 'varchar(64)',
-          'middle_name' => 'varchar(64)',
-          'last_name' => 'varchar(64)',
-          'email_greeting_display' => 'varchar(255)',
-          'postal_greeting_display' => 'varchar(255)',
-          'addressee_display' => 'varchar(255)',
-          'household_name' => 'varchar(128)',
-          'organization_name' => 'varchar(128)',
-        ),
-        'civicrm_contact_type' => array(
-          'label' => 'varchar(64)',
-          'description' => 'text',
-        ),
-        'civicrm_mailing_component' => array(
-          'name' => 'varchar(64)',
-          'subject' => 'varchar(255)',
-          'body_html' => 'text',
-          'body_text' => 'text',
-        ),
-        'civicrm_mailing' => array(
-          'name' => 'varchar(128)',
-          'from_name' => 'varchar(128)',
-          'subject' => 'varchar(128)',
-          'body_text' => 'longtext',
-          'body_html' => 'longtext',
-        ),
-        'civicrm_premiums' => array(
-          'premiums_intro_title' => 'varchar(255)',
-          'premiums_intro_text' => 'text',
-        ),
-        'civicrm_product' => array(
-          'name' => 'varchar(255)',
-          'description' => 'text',
-          'options' => 'text',
-        ),
-        'civicrm_membership_type' => array(
-          'name' => 'varchar(128)',
-          'description' => 'varchar(255)',
-        ),
-        'civicrm_membership_status' => array(
-          'label' => 'varchar(128)',
-        ),
-        'civicrm_participant_status_type' => array(
-          'label' => 'varchar(255)',
-        ),
-        'civicrm_tell_friend' => array(
-          'title' => 'varchar(255)',
-          'intro' => 'text',
-          'suggested_message' => 'text',
-          'thankyou_title' => 'varchar(255)',
-          'thankyou_text' => 'text',
-        ),
-        'civicrm_price_set' => array(
-          'title' => 'varchar(255)',
-          'help_pre' => 'text',
-          'help_post' => 'text',
-        ),
-        'civicrm_custom_group' => array(
-          'title' => 'varchar(64)',
-          'help_pre' => 'text',
-          'help_post' => 'text',
-        ),
-        'civicrm_custom_field' => array(
-          'label' => 'varchar(255)',
-          'help_pre' => 'text',
-          'help_post' => 'text',
-        ),
-        'civicrm_dashboard' => array(
-          'label' => 'varchar(255)',
-        ),
-        'civicrm_option_value' => array(
-          'label' => 'varchar(255)',
-          'description' => 'varchar(255)',
-        ),
-        'civicrm_contribution_page' => array(
-          'title' => 'varchar(255)',
-          'intro_text' => 'text',
-          'pay_later_text' => 'text',
-          'pay_later_receipt' => 'text',
-          'thankyou_title' => 'varchar(255)',
-          'thankyou_text' => 'text',
-          'thankyou_footer' => 'text',
-          'for_organization' => 'text',
-          'receipt_from_name' => 'varchar(255)',
-          'receipt_text' => 'text',
-          'footer_text' => 'text',
-          'honor_block_title' => 'varchar(255)',
-          'honor_block_text' => 'text',
-        ),
-        'civicrm_membership_block' => array(
-          'new_title' => 'varchar(255)',
-          'new_text' => 'text',
-          'renewal_title' => 'varchar(255)',
-          'renewal_text' => 'text',
-        ),
-        'civicrm_price_field' => array(
-          'label' => 'varchar(255)',
-          'help_pre' => 'text',
-          'help_post' => 'text',
-        ),
-        'civicrm_uf_group' => array(
-          'title' => 'varchar(64)',
-          'help_pre' => 'text',
-          'help_post' => 'text',
-        ),
-        'civicrm_uf_field' => array(
-          'help_post' => 'text',
-          'help_pre' => 'text',
-          'label' => 'varchar(255)',
-        ),
-        'civicrm_address' => array(
-          'street_address' => 'varchar(96)',
-          'supplemental_address_1' => 'varchar(96)',
-          'supplemental_address_2' => 'varchar(96)',
-          'supplemental_address_3' => 'varchar(96)',
-          'city' => 'varchar(64)',
-          'name' => 'varchar(255)',
-        ),
-        'civicrm_event' => array(
-          'title' => 'varchar(255)',
-          'summary' => 'text',
-          'description' => 'text',
-          'registration_link_text' => 'varchar(255)',
-          'event_full_text' => 'text',
-          'fee_label' => 'varchar(255)',
-          'intro_text' => 'text',
-          'footer_text' => 'text',
-          'confirm_title' => 'varchar(255)',
-          'confirm_text' => 'text',
-          'confirm_footer_text' => 'text',
-          'confirm_email_text' => 'text',
-          'confirm_from_name' => 'varchar(255)',
-          'thankyou_title' => 'varchar(255)',
-          'thankyou_text' => 'text',
-          'thankyou_footer_text' => 'text',
-          'pay_later_text' => 'text',
-          'pay_later_receipt' => 'text',
-          'waitlist_text' => 'text',
-          'approval_req_text' => 'text',
-          'template_title' => 'varchar(255)',
-        ),
-      );
-    }
-    return $result;
-  }
-
-  /**
-   * @return array
-   */
-  public static function &indices() {
-    static $result = NULL;
-    if (!$result) {
-      $result = array(
-        'civicrm_contact' => array(
-          'index_sort_name' => array(
-            'name' => 'index_sort_name',
-            'field' => array(
-              'sort_name',
-            ),
-          ),
-          'index_first_name' => array(
-            'name' => 'index_first_name',
-            'field' => array(
-              'first_name',
-            ),
-          ),
-          'index_last_name' => array(
-            'name' => 'index_last_name',
-            'field' => array(
-              'last_name',
-            ),
-          ),
-          'index_household_name' => array(
-            'name' => 'index_household_name',
-            'field' => array(
-              'household_name',
-            ),
-          ),
-          'index_organization_name' => array(
-            'name' => 'index_organization_name',
-            'field' => array(
-              'organization_name',
-            ),
-          ),
-        ),
-        'civicrm_price_set' => array(
-          'UI_title' => array(
-            'name' => 'UI_title',
-            'field' => array(
-              'title',
-            ),
-            'unique' => 1,
-          ),
-        ),
-        'civicrm_custom_group' => array(
-          'UI_title_extends' => array(
-            'name' => 'UI_title_extends',
-            'field' => array(
-              'title',
-              'extends',
-            ),
-            'unique' => 1,
-          ),
-        ),
-        'civicrm_custom_field' => array(
-          'UI_label_custom_group_id' => array(
-            'name' => 'UI_label_custom_group_id',
-            'field' => array(
-              'label',
-              'custom_group_id',
-            ),
-            'unique' => 1,
-          ),
-        ),
-        'civicrm_address' => array(
-          'index_city' => array(
-            'name' => 'index_city',
-            'field' => array(
-              'city',
-            ),
-          ),
-        ),
-      );
-    }
-    return $result;
-  }
-
-  /**
-   * @return array
-   */
-  public static function &tables() {
-    static $result = NULL;
-    if (!$result) {
-      $result = array_keys(self::columns());
-    }
-    return $result;
-  }
-
-}
diff --git a/civicrm/CRM/Core/I18n/SchemaStructure_3_3_beta1.php b/civicrm/CRM/Core/I18n/SchemaStructure_3_3_beta1.php
deleted file mode 100644
index 5eced3dd9d..0000000000
--- a/civicrm/CRM/Core/I18n/SchemaStructure_3_3_beta1.php
+++ /dev/null
@@ -1,296 +0,0 @@
-<?php
-/*
-+--------------------------------------------------------------------+
-| CiviCRM version 4.7                                                |
-+--------------------------------------------------------------------+
-| Copyright CiviCRM LLC (c) 2004-2018                                |
-+--------------------------------------------------------------------+
-| 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-2018
- * $Id$
- *
- */
-class CRM_Core_I18n_SchemaStructure_3_3_beta1 {
-  /**
-   * @return array
-   */
-  static public function &columns() {
-    static $result = NULL;
-    if (!$result) {
-      $result = array(
-        'civicrm_option_group' => array(
-          'label' => 'varchar(255)',
-          'description' => 'varchar(255)',
-        ),
-        'civicrm_contact' => array(
-          'sort_name' => 'varchar(128)',
-          'display_name' => 'varchar(128)',
-          'first_name' => 'varchar(64)',
-          'middle_name' => 'varchar(64)',
-          'last_name' => 'varchar(64)',
-          'email_greeting_display' => 'varchar(255)',
-          'postal_greeting_display' => 'varchar(255)',
-          'addressee_display' => 'varchar(255)',
-          'household_name' => 'varchar(128)',
-          'organization_name' => 'varchar(128)',
-        ),
-        'civicrm_contact_type' => array(
-          'label' => 'varchar(64)',
-          'description' => 'text',
-        ),
-        'civicrm_mailing_component' => array(
-          'name' => 'varchar(64)',
-          'subject' => 'varchar(255)',
-          'body_html' => 'text',
-          'body_text' => 'text',
-        ),
-        'civicrm_mailing' => array(
-          'name' => 'varchar(128)',
-          'from_name' => 'varchar(128)',
-          'subject' => 'varchar(128)',
-          'body_text' => 'longtext',
-          'body_html' => 'longtext',
-        ),
-        'civicrm_premiums' => array(
-          'premiums_intro_title' => 'varchar(255)',
-          'premiums_intro_text' => 'text',
-        ),
-        'civicrm_product' => array(
-          'name' => 'varchar(255)',
-          'description' => 'text',
-          'options' => 'text',
-        ),
-        'civicrm_membership_type' => array(
-          'name' => 'varchar(128)',
-          'description' => 'varchar(255)',
-        ),
-        'civicrm_membership_status' => array(
-          'label' => 'varchar(128)',
-        ),
-        'civicrm_participant_status_type' => array(
-          'label' => 'varchar(255)',
-        ),
-        'civicrm_tell_friend' => array(
-          'title' => 'varchar(255)',
-          'intro' => 'text',
-          'suggested_message' => 'text',
-          'thankyou_title' => 'varchar(255)',
-          'thankyou_text' => 'text',
-        ),
-        'civicrm_price_set' => array(
-          'title' => 'varchar(255)',
-          'help_pre' => 'text',
-          'help_post' => 'text',
-        ),
-        'civicrm_batch' => array(
-          'label' => 'varchar(64)',
-          'description' => 'text',
-        ),
-        'civicrm_custom_group' => array(
-          'title' => 'varchar(64)',
-          'help_pre' => 'text',
-          'help_post' => 'text',
-        ),
-        'civicrm_custom_field' => array(
-          'label' => 'varchar(255)',
-          'help_pre' => 'text',
-          'help_post' => 'text',
-        ),
-        'civicrm_dashboard' => array(
-          'label' => 'varchar(255)',
-        ),
-        'civicrm_option_value' => array(
-          'label' => 'varchar(255)',
-          'description' => 'varchar(255)',
-        ),
-        'civicrm_contribution_page' => array(
-          'title' => 'varchar(255)',
-          'intro_text' => 'text',
-          'pay_later_text' => 'text',
-          'pay_later_receipt' => 'text',
-          'thankyou_title' => 'varchar(255)',
-          'thankyou_text' => 'text',
-          'thankyou_footer' => 'text',
-          'for_organization' => 'text',
-          'receipt_from_name' => 'varchar(255)',
-          'receipt_text' => 'text',
-          'footer_text' => 'text',
-          'honor_block_title' => 'varchar(255)',
-          'honor_block_text' => 'text',
-        ),
-        'civicrm_membership_block' => array(
-          'new_title' => 'varchar(255)',
-          'new_text' => 'text',
-          'renewal_title' => 'varchar(255)',
-          'renewal_text' => 'text',
-        ),
-        'civicrm_price_field' => array(
-          'label' => 'varchar(255)',
-          'help_pre' => 'text',
-          'help_post' => 'text',
-        ),
-        'civicrm_uf_group' => array(
-          'title' => 'varchar(64)',
-          'help_pre' => 'text',
-          'help_post' => 'text',
-        ),
-        'civicrm_uf_field' => array(
-          'help_post' => 'text',
-          'help_pre' => 'text',
-          'label' => 'varchar(255)',
-        ),
-        'civicrm_address' => array(
-          'street_address' => 'varchar(96)',
-          'supplemental_address_1' => 'varchar(96)',
-          'supplemental_address_2' => 'varchar(96)',
-          'supplemental_address_3' => 'varchar(96)',
-          'city' => 'varchar(64)',
-          'name' => 'varchar(255)',
-        ),
-        'civicrm_event' => array(
-          'title' => 'varchar(255)',
-          'summary' => 'text',
-          'description' => 'text',
-          'registration_link_text' => 'varchar(255)',
-          'event_full_text' => 'text',
-          'fee_label' => 'varchar(255)',
-          'intro_text' => 'text',
-          'footer_text' => 'text',
-          'confirm_title' => 'varchar(255)',
-          'confirm_text' => 'text',
-          'confirm_footer_text' => 'text',
-          'confirm_email_text' => 'text',
-          'confirm_from_name' => 'varchar(255)',
-          'thankyou_title' => 'varchar(255)',
-          'thankyou_text' => 'text',
-          'thankyou_footer_text' => 'text',
-          'pay_later_text' => 'text',
-          'pay_later_receipt' => 'text',
-          'waitlist_text' => 'text',
-          'approval_req_text' => 'text',
-          'template_title' => 'varchar(255)',
-        ),
-        'civicrm_price_field_value' => array(
-          'label' => 'varchar(255)',
-          'description' => 'text',
-        ),
-      );
-    }
-    return $result;
-  }
-
-  /**
-   * @return array
-   */
-  static public function &indices() {
-    static $result = NULL;
-    if (!$result) {
-      $result = array(
-        'civicrm_contact' => array(
-          'index_sort_name' => array(
-            'name' => 'index_sort_name',
-            'field' => array(
-              'sort_name',
-            ),
-          ),
-          'index_first_name' => array(
-            'name' => 'index_first_name',
-            'field' => array(
-              'first_name',
-            ),
-          ),
-          'index_last_name' => array(
-            'name' => 'index_last_name',
-            'field' => array(
-              'last_name',
-            ),
-          ),
-          'index_household_name' => array(
-            'name' => 'index_household_name',
-            'field' => array(
-              'household_name',
-            ),
-          ),
-          'index_organization_name' => array(
-            'name' => 'index_organization_name',
-            'field' => array(
-              'organization_name',
-            ),
-          ),
-        ),
-        'civicrm_price_set' => array(
-          'UI_title' => array(
-            'name' => 'UI_title',
-            'field' => array(
-              'title',
-            ),
-            'unique' => 1,
-          ),
-        ),
-        'civicrm_custom_group' => array(
-          'UI_title_extends' => array(
-            'name' => 'UI_title_extends',
-            'field' => array(
-              'title',
-              'extends',
-            ),
-            'unique' => 1,
-          ),
-        ),
-        'civicrm_custom_field' => array(
-          'UI_label_custom_group_id' => array(
-            'name' => 'UI_label_custom_group_id',
-            'field' => array(
-              'label',
-              'custom_group_id',
-            ),
-            'unique' => 1,
-          ),
-        ),
-        'civicrm_address' => array(
-          'index_city' => array(
-            'name' => 'index_city',
-            'field' => array(
-              'city',
-            ),
-          ),
-        ),
-      );
-    }
-    return $result;
-  }
-
-  /**
-   * @return array
-   */
-  static public function &tables() {
-    static $result = NULL;
-    if (!$result) {
-      $result = array_keys(self::columns());
-    }
-    return $result;
-  }
-
-}
diff --git a/civicrm/CRM/Core/I18n/SchemaStructure_3_4_0.php b/civicrm/CRM/Core/I18n/SchemaStructure_3_4_0.php
deleted file mode 100644
index 7a601c0d62..0000000000
--- a/civicrm/CRM/Core/I18n/SchemaStructure_3_4_0.php
+++ /dev/null
@@ -1,223 +0,0 @@
-<?php
-/*
-+--------------------------------------------------------------------+
-| CiviCRM version 4.7                                                |
-+--------------------------------------------------------------------+
-| Copyright CiviCRM LLC (c) 2004-2018                                |
-+--------------------------------------------------------------------+
-| 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-2018
- * $Id$
- *
- */
-class CRM_Core_I18n_SchemaStructure_3_4_0 {
-  /**
-   * @return array
-   */
-  public static function &columns() {
-    static $result = NULL;
-    if (!$result) {
-      $result = array(
-        'civicrm_option_group' => array(
-          'label' => "varchar(255)",
-          'description' => "varchar(255)",
-        ),
-        'civicrm_contact_type' => array(
-          'label' => "varchar(64)",
-          'description' => "text",
-        ),
-        'civicrm_premiums' => array(
-          'premiums_intro_title' => "varchar(255)",
-          'premiums_intro_text' => "text",
-        ),
-        'civicrm_product' => array(
-          'name' => "varchar(255)",
-          'description' => "text",
-          'options' => "text",
-        ),
-        'civicrm_membership_type' => array(
-          'name' => "varchar(128)",
-          'description' => "varchar(255)",
-        ),
-        'civicrm_membership_status' => array(
-          'label' => "varchar(128)",
-        ),
-        'civicrm_participant_status_type' => array(
-          'label' => "varchar(255)",
-        ),
-        'civicrm_tell_friend' => array(
-          'title' => "varchar(255)",
-          'intro' => "text",
-          'suggested_message' => "text",
-          'thankyou_title' => "varchar(255)",
-          'thankyou_text' => "text",
-        ),
-        'civicrm_price_set' => array(
-          'title' => "varchar(255)",
-          'help_pre' => "text",
-          'help_post' => "text",
-        ),
-        'civicrm_batch' => array(
-          'label' => "varchar(64)",
-          'description' => "text",
-        ),
-        'civicrm_custom_group' => array(
-          'title' => "varchar(64)",
-          'help_pre' => "text",
-          'help_post' => "text",
-        ),
-        'civicrm_custom_field' => array(
-          'label' => "varchar(255)",
-          'help_pre' => "text",
-          'help_post' => "text",
-        ),
-        'civicrm_dashboard' => array(
-          'label' => "varchar(255)",
-        ),
-        'civicrm_option_value' => array(
-          'label' => "varchar(255)",
-          'description' => "text",
-        ),
-        'civicrm_contribution_page' => array(
-          'title' => "varchar(255)",
-          'intro_text' => "text",
-          'pay_later_text' => "text",
-          'pay_later_receipt' => "text",
-          'thankyou_title' => "varchar(255)",
-          'thankyou_text' => "text",
-          'thankyou_footer' => "text",
-          'for_organization' => "text",
-          'receipt_from_name' => "varchar(255)",
-          'receipt_text' => "text",
-          'footer_text' => "text",
-          'honor_block_title' => "varchar(255)",
-          'honor_block_text' => "text",
-        ),
-        'civicrm_membership_block' => array(
-          'new_title' => "varchar(255)",
-          'new_text' => "text",
-          'renewal_title' => "varchar(255)",
-          'renewal_text' => "text",
-        ),
-        'civicrm_price_field' => array(
-          'label' => "varchar(255)",
-          'help_pre' => "text",
-          'help_post' => "text",
-        ),
-        'civicrm_price_field_value' => array(
-          'label' => "varchar(255)",
-          'description' => "text",
-        ),
-        'civicrm_uf_group' => array(
-          'title' => "varchar(64)",
-          'help_pre' => "text",
-          'help_post' => "text",
-        ),
-        'civicrm_uf_field' => array(
-          'help_post' => "text",
-          'help_pre' => "text",
-          'label' => "varchar(255)",
-        ),
-        'civicrm_event' => array(
-          'title' => "varchar(255)",
-          'summary' => "text",
-          'description' => "text",
-          'registration_link_text' => "varchar(255)",
-          'event_full_text' => "text",
-          'fee_label' => "varchar(255)",
-          'intro_text' => "text",
-          'footer_text' => "text",
-          'confirm_title' => "varchar(255)",
-          'confirm_text' => "text",
-          'confirm_footer_text' => "text",
-          'confirm_email_text' => "text",
-          'confirm_from_name' => "varchar(255)",
-          'thankyou_title' => "varchar(255)",
-          'thankyou_text' => "text",
-          'thankyou_footer_text' => "text",
-          'pay_later_text' => "text",
-          'pay_later_receipt' => "text",
-          'waitlist_text' => "text",
-          'approval_req_text' => "text",
-          'template_title' => "varchar(255)",
-        ),
-      );
-    }
-    return $result;
-  }
-
-  /**
-   * @return array
-   */
-  public static function &indices() {
-    static $result = NULL;
-    if (!$result) {
-      $result = array(
-        'civicrm_price_set' => array(
-          'UI_title' => array(
-            'name' => 'UI_title',
-            'field' => array(
-              'title',
-            ),
-            'unique' => 1,
-          ),
-        ),
-        'civicrm_custom_group' => array(
-          'UI_title_extends' => array(
-            'name' => 'UI_title_extends',
-            'field' => array(
-              'title',
-              'extends',
-            ),
-            'unique' => 1,
-          ),
-        ),
-        'civicrm_custom_field' => array(
-          'UI_label_custom_group_id' => array(
-            'name' => 'UI_label_custom_group_id',
-            'field' => array(
-              'label',
-              'custom_group_id',
-            ),
-            'unique' => 1,
-          ),
-        ),
-      );
-    }
-    return $result;
-  }
-
-  /**
-   * @return array
-   */
-  public static function &tables() {
-    static $result = NULL;
-    if (!$result) {
-      $result = array_keys(self::columns());
-    }
-    return $result;
-  }
-
-}
diff --git a/civicrm/CRM/Core/I18n/SchemaStructure_3_4_beta2.php b/civicrm/CRM/Core/I18n/SchemaStructure_3_4_beta2.php
deleted file mode 100644
index 1ae3955613..0000000000
--- a/civicrm/CRM/Core/I18n/SchemaStructure_3_4_beta2.php
+++ /dev/null
@@ -1,296 +0,0 @@
-<?php
-/*
-+--------------------------------------------------------------------+
-| CiviCRM version 4.7                                                |
-+--------------------------------------------------------------------+
-| Copyright CiviCRM LLC (c) 2004-2018                                |
-+--------------------------------------------------------------------+
-| 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-2018
- * $Id$
- *
- */
-class CRM_Core_I18n_SchemaStructure_3_4_beta2 {
-  /**
-   * @return array
-   */
-  public static function &columns() {
-    static $result = NULL;
-    if (!$result) {
-      $result = array(
-        'civicrm_option_group' => array(
-          'label' => "varchar(255)",
-          'description' => "varchar(255)",
-        ),
-        'civicrm_contact' => array(
-          'sort_name' => "varchar(128)",
-          'display_name' => "varchar(128)",
-          'first_name' => "varchar(64)",
-          'middle_name' => "varchar(64)",
-          'last_name' => "varchar(64)",
-          'email_greeting_display' => "varchar(255)",
-          'postal_greeting_display' => "varchar(255)",
-          'addressee_display' => "varchar(255)",
-          'household_name' => "varchar(128)",
-          'organization_name' => "varchar(128)",
-        ),
-        'civicrm_contact_type' => array(
-          'label' => "varchar(64)",
-          'description' => "text",
-        ),
-        'civicrm_mailing_component' => array(
-          'name' => "varchar(64)",
-          'subject' => "varchar(255)",
-          'body_html' => "text",
-          'body_text' => "text",
-        ),
-        'civicrm_premiums' => array(
-          'premiums_intro_title' => "varchar(255)",
-          'premiums_intro_text' => "text",
-        ),
-        'civicrm_product' => array(
-          'name' => "varchar(255)",
-          'description' => "text",
-          'options' => "text",
-        ),
-        'civicrm_membership_type' => array(
-          'name' => "varchar(128)",
-          'description' => "varchar(255)",
-        ),
-        'civicrm_membership_status' => array(
-          'label' => "varchar(128)",
-        ),
-        'civicrm_participant_status_type' => array(
-          'label' => "varchar(255)",
-        ),
-        'civicrm_tell_friend' => array(
-          'title' => "varchar(255)",
-          'intro' => "text",
-          'suggested_message' => "text",
-          'thankyou_title' => "varchar(255)",
-          'thankyou_text' => "text",
-        ),
-        'civicrm_price_set' => array(
-          'title' => "varchar(255)",
-          'help_pre' => "text",
-          'help_post' => "text",
-        ),
-        'civicrm_batch' => array(
-          'label' => "varchar(64)",
-          'description' => "text",
-        ),
-        'civicrm_custom_group' => array(
-          'title' => "varchar(64)",
-          'help_pre' => "text",
-          'help_post' => "text",
-        ),
-        'civicrm_custom_field' => array(
-          'label' => "varchar(255)",
-          'help_pre' => "text",
-          'help_post' => "text",
-        ),
-        'civicrm_dashboard' => array(
-          'label' => "varchar(255)",
-        ),
-        'civicrm_option_value' => array(
-          'label' => "varchar(255)",
-          'description' => "text",
-        ),
-        'civicrm_mailing' => array(
-          'name' => "varchar(128)",
-          'from_name' => "varchar(128)",
-          'subject' => "varchar(128)",
-          'body_text' => "longtext",
-          'body_html' => "longtext",
-        ),
-        'civicrm_contribution_page' => array(
-          'title' => "varchar(255)",
-          'intro_text' => "text",
-          'pay_later_text' => "text",
-          'pay_later_receipt' => "text",
-          'thankyou_title' => "varchar(255)",
-          'thankyou_text' => "text",
-          'thankyou_footer' => "text",
-          'for_organization' => "text",
-          'receipt_from_name' => "varchar(255)",
-          'receipt_text' => "text",
-          'footer_text' => "text",
-          'honor_block_title' => "varchar(255)",
-          'honor_block_text' => "text",
-        ),
-        'civicrm_membership_block' => array(
-          'new_title' => "varchar(255)",
-          'new_text' => "text",
-          'renewal_title' => "varchar(255)",
-          'renewal_text' => "text",
-        ),
-        'civicrm_price_field' => array(
-          'label' => "varchar(255)",
-          'help_pre' => "text",
-          'help_post' => "text",
-        ),
-        'civicrm_price_field_value' => array(
-          'label' => "varchar(255)",
-          'description' => "text",
-        ),
-        'civicrm_uf_group' => array(
-          'title' => "varchar(64)",
-          'help_pre' => "text",
-          'help_post' => "text",
-        ),
-        'civicrm_uf_field' => array(
-          'help_post' => "text",
-          'help_pre' => "text",
-          'label' => "varchar(255)",
-        ),
-        'civicrm_address' => array(
-          'street_address' => "varchar(96)",
-          'supplemental_address_1' => "varchar(96)",
-          'supplemental_address_2' => "varchar(96)",
-          'supplemental_address_3' => "varchar(96)",
-          'city' => "varchar(64)",
-          'name' => "varchar(255)",
-        ),
-        'civicrm_event' => array(
-          'title' => "varchar(255)",
-          'summary' => "text",
-          'description' => "text",
-          'registration_link_text' => "varchar(255)",
-          'event_full_text' => "text",
-          'fee_label' => "varchar(255)",
-          'intro_text' => "text",
-          'footer_text' => "text",
-          'confirm_title' => "varchar(255)",
-          'confirm_text' => "text",
-          'confirm_footer_text' => "text",
-          'confirm_email_text' => "text",
-          'confirm_from_name' => "varchar(255)",
-          'thankyou_title' => "varchar(255)",
-          'thankyou_text' => "text",
-          'thankyou_footer_text' => "text",
-          'pay_later_text' => "text",
-          'pay_later_receipt' => "text",
-          'waitlist_text' => "text",
-          'approval_req_text' => "text",
-          'template_title' => "varchar(255)",
-        ),
-      );
-    }
-    return $result;
-  }
-
-  /**
-   * @return array
-   */
-  public static function &indices() {
-    static $result = NULL;
-    if (!$result) {
-      $result = array(
-        'civicrm_contact' => array(
-          'index_sort_name' => array(
-            'name' => 'index_sort_name',
-            'field' => array(
-              'sort_name',
-            ),
-          ),
-          'index_first_name' => array(
-            'name' => 'index_first_name',
-            'field' => array(
-              'first_name',
-            ),
-          ),
-          'index_last_name' => array(
-            'name' => 'index_last_name',
-            'field' => array(
-              'last_name',
-            ),
-          ),
-          'index_household_name' => array(
-            'name' => 'index_household_name',
-            'field' => array(
-              'household_name',
-            ),
-          ),
-          'index_organization_name' => array(
-            'name' => 'index_organization_name',
-            'field' => array(
-              'organization_name',
-            ),
-          ),
-        ),
-        'civicrm_price_set' => array(
-          'UI_title' => array(
-            'name' => 'UI_title',
-            'field' => array(
-              'title',
-            ),
-            'unique' => 1,
-          ),
-        ),
-        'civicrm_custom_group' => array(
-          'UI_title_extends' => array(
-            'name' => 'UI_title_extends',
-            'field' => array(
-              'title',
-              'extends',
-            ),
-            'unique' => 1,
-          ),
-        ),
-        'civicrm_custom_field' => array(
-          'UI_label_custom_group_id' => array(
-            'name' => 'UI_label_custom_group_id',
-            'field' => array(
-              'label',
-              'custom_group_id',
-            ),
-            'unique' => 1,
-          ),
-        ),
-        'civicrm_address' => array(
-          'index_city' => array(
-            'name' => 'index_city',
-            'field' => array(
-              'city',
-            ),
-          ),
-        ),
-      );
-    }
-    return $result;
-  }
-
-  /**
-   * @return array
-   */
-  public static function &tables() {
-    static $result = NULL;
-    if (!$result) {
-      $result = array_keys(self::columns());
-    }
-    return $result;
-  }
-
-}
diff --git a/civicrm/CRM/Core/I18n/SchemaStructure_3_4_beta3.php b/civicrm/CRM/Core/I18n/SchemaStructure_3_4_beta3.php
deleted file mode 100644
index 289ddcc721..0000000000
--- a/civicrm/CRM/Core/I18n/SchemaStructure_3_4_beta3.php
+++ /dev/null
@@ -1,223 +0,0 @@
-<?php
-/*
-+--------------------------------------------------------------------+
-| CiviCRM version 4.7                                                |
-+--------------------------------------------------------------------+
-| Copyright CiviCRM LLC (c) 2004-2018                                |
-+--------------------------------------------------------------------+
-| 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-2018
- * $Id$
- *
- */
-class CRM_Core_I18n_SchemaStructure_3_4_beta3 {
-  /**
-   * @return array
-   */
-  public static function &columns() {
-    static $result = NULL;
-    if (!$result) {
-      $result = array(
-        'civicrm_option_group' => array(
-          'label' => "varchar(255)",
-          'description' => "varchar(255)",
-        ),
-        'civicrm_contact_type' => array(
-          'label' => "varchar(64)",
-          'description' => "text",
-        ),
-        'civicrm_premiums' => array(
-          'premiums_intro_title' => "varchar(255)",
-          'premiums_intro_text' => "text",
-        ),
-        'civicrm_product' => array(
-          'name' => "varchar(255)",
-          'description' => "text",
-          'options' => "text",
-        ),
-        'civicrm_membership_type' => array(
-          'name' => "varchar(128)",
-          'description' => "varchar(255)",
-        ),
-        'civicrm_membership_status' => array(
-          'label' => "varchar(128)",
-        ),
-        'civicrm_participant_status_type' => array(
-          'label' => "varchar(255)",
-        ),
-        'civicrm_tell_friend' => array(
-          'title' => "varchar(255)",
-          'intro' => "text",
-          'suggested_message' => "text",
-          'thankyou_title' => "varchar(255)",
-          'thankyou_text' => "text",
-        ),
-        'civicrm_price_set' => array(
-          'title' => "varchar(255)",
-          'help_pre' => "text",
-          'help_post' => "text",
-        ),
-        'civicrm_batch' => array(
-          'label' => "varchar(64)",
-          'description' => "text",
-        ),
-        'civicrm_custom_group' => array(
-          'title' => "varchar(64)",
-          'help_pre' => "text",
-          'help_post' => "text",
-        ),
-        'civicrm_custom_field' => array(
-          'label' => "varchar(255)",
-          'help_pre' => "text",
-          'help_post' => "text",
-        ),
-        'civicrm_dashboard' => array(
-          'label' => "varchar(255)",
-        ),
-        'civicrm_option_value' => array(
-          'label' => "varchar(255)",
-          'description' => "text",
-        ),
-        'civicrm_contribution_page' => array(
-          'title' => "varchar(255)",
-          'intro_text' => "text",
-          'pay_later_text' => "text",
-          'pay_later_receipt' => "text",
-          'thankyou_title' => "varchar(255)",
-          'thankyou_text' => "text",
-          'thankyou_footer' => "text",
-          'for_organization' => "text",
-          'receipt_from_name' => "varchar(255)",
-          'receipt_text' => "text",
-          'footer_text' => "text",
-          'honor_block_title' => "varchar(255)",
-          'honor_block_text' => "text",
-        ),
-        'civicrm_membership_block' => array(
-          'new_title' => "varchar(255)",
-          'new_text' => "text",
-          'renewal_title' => "varchar(255)",
-          'renewal_text' => "text",
-        ),
-        'civicrm_price_field' => array(
-          'label' => "varchar(255)",
-          'help_pre' => "text",
-          'help_post' => "text",
-        ),
-        'civicrm_price_field_value' => array(
-          'label' => "varchar(255)",
-          'description' => "text",
-        ),
-        'civicrm_uf_group' => array(
-          'title' => "varchar(64)",
-          'help_pre' => "text",
-          'help_post' => "text",
-        ),
-        'civicrm_uf_field' => array(
-          'help_post' => "text",
-          'help_pre' => "text",
-          'label' => "varchar(255)",
-        ),
-        'civicrm_event' => array(
-          'title' => "varchar(255)",
-          'summary' => "text",
-          'description' => "text",
-          'registration_link_text' => "varchar(255)",
-          'event_full_text' => "text",
-          'fee_label' => "varchar(255)",
-          'intro_text' => "text",
-          'footer_text' => "text",
-          'confirm_title' => "varchar(255)",
-          'confirm_text' => "text",
-          'confirm_footer_text' => "text",
-          'confirm_email_text' => "text",
-          'confirm_from_name' => "varchar(255)",
-          'thankyou_title' => "varchar(255)",
-          'thankyou_text' => "text",
-          'thankyou_footer_text' => "text",
-          'pay_later_text' => "text",
-          'pay_later_receipt' => "text",
-          'waitlist_text' => "text",
-          'approval_req_text' => "text",
-          'template_title' => "varchar(255)",
-        ),
-      );
-    }
-    return $result;
-  }
-
-  /**
-   * @return array
-   */
-  public static function &indices() {
-    static $result = NULL;
-    if (!$result) {
-      $result = array(
-        'civicrm_price_set' => array(
-          'UI_title' => array(
-            'name' => 'UI_title',
-            'field' => array(
-              'title',
-            ),
-            'unique' => 1,
-          ),
-        ),
-        'civicrm_custom_group' => array(
-          'UI_title_extends' => array(
-            'name' => 'UI_title_extends',
-            'field' => array(
-              'title',
-              'extends',
-            ),
-            'unique' => 1,
-          ),
-        ),
-        'civicrm_custom_field' => array(
-          'UI_label_custom_group_id' => array(
-            'name' => 'UI_label_custom_group_id',
-            'field' => array(
-              'label',
-              'custom_group_id',
-            ),
-            'unique' => 1,
-          ),
-        ),
-      );
-    }
-    return $result;
-  }
-
-  /**
-   * @return array
-   */
-  public static function &tables() {
-    static $result = NULL;
-    if (!$result) {
-      $result = array_keys(self::columns());
-    }
-    return $result;
-  }
-
-}
diff --git a/civicrm/CRM/Core/I18n/SchemaStructure_4_1_0.php b/civicrm/CRM/Core/I18n/SchemaStructure_4_1_0.php
deleted file mode 100644
index dfc3172280..0000000000
--- a/civicrm/CRM/Core/I18n/SchemaStructure_4_1_0.php
+++ /dev/null
@@ -1,229 +0,0 @@
-<?php
-/*
-+--------------------------------------------------------------------+
-| CiviCRM version 4.7                                                |
-+--------------------------------------------------------------------+
-| Copyright CiviCRM LLC (c) 2004-2018                                |
-+--------------------------------------------------------------------+
-| 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-2018
- * $Id$
- *
- */
-class CRM_Core_I18n_SchemaStructure_4_1_0 {
-  /**
-   * @return array
-   */
-  public static function &columns() {
-    static $result = NULL;
-    if (!$result) {
-      $result = array(
-        'civicrm_location_type' => array(
-          'display_name' => "varchar(64)",
-        ),
-        'civicrm_option_group' => array(
-          'title' => "varchar(255)",
-          'description' => "varchar(255)",
-        ),
-        'civicrm_contact_type' => array(
-          'label' => "varchar(64)",
-          'description' => "text",
-        ),
-        'civicrm_premiums' => array(
-          'premiums_intro_title' => "varchar(255)",
-          'premiums_intro_text' => "text",
-        ),
-        'civicrm_product' => array(
-          'name' => "varchar(255)",
-          'description' => "text",
-          'options' => "text",
-        ),
-        'civicrm_membership_status' => array(
-          'label' => "varchar(128)",
-        ),
-        'civicrm_participant_status_type' => array(
-          'label' => "varchar(255)",
-        ),
-        'civicrm_tell_friend' => array(
-          'title' => "varchar(255)",
-          'intro' => "text",
-          'suggested_message' => "text",
-          'thankyou_title' => "varchar(255)",
-          'thankyou_text' => "text",
-        ),
-        'civicrm_price_set' => array(
-          'title' => "varchar(255)",
-          'help_pre' => "text",
-          'help_post' => "text",
-        ),
-        'civicrm_batch' => array(
-          'label' => "varchar(64)",
-          'description' => "text",
-        ),
-        'civicrm_custom_group' => array(
-          'title' => "varchar(64)",
-          'help_pre' => "text",
-          'help_post' => "text",
-        ),
-        'civicrm_custom_field' => array(
-          'label' => "varchar(255)",
-          'help_pre' => "text",
-          'help_post' => "text",
-        ),
-        'civicrm_dashboard' => array(
-          'label' => "varchar(255)",
-        ),
-        'civicrm_option_value' => array(
-          'label' => "varchar(255)",
-          'description' => "text",
-        ),
-        'civicrm_contribution_page' => array(
-          'title' => "varchar(255)",
-          'intro_text' => "text",
-          'pay_later_text' => "text",
-          'pay_later_receipt' => "text",
-          'thankyou_title' => "varchar(255)",
-          'thankyou_text' => "text",
-          'thankyou_footer' => "text",
-          'for_organization' => "text",
-          'receipt_from_name' => "varchar(255)",
-          'receipt_text' => "text",
-          'footer_text' => "text",
-          'honor_block_title' => "varchar(255)",
-          'honor_block_text' => "text",
-        ),
-        'civicrm_price_field' => array(
-          'label' => "varchar(255)",
-          'help_pre' => "text",
-          'help_post' => "text",
-        ),
-        'civicrm_uf_group' => array(
-          'title' => "varchar(64)",
-          'help_pre' => "text",
-          'help_post' => "text",
-        ),
-        'civicrm_uf_field' => array(
-          'help_post' => "text",
-          'help_pre' => "text",
-          'label' => "varchar(255)",
-        ),
-        'civicrm_membership_type' => array(
-          'name' => "varchar(128)",
-          'description' => "varchar(255)",
-        ),
-        'civicrm_membership_block' => array(
-          'new_title' => "varchar(255)",
-          'new_text' => "text",
-          'renewal_title' => "varchar(255)",
-          'renewal_text' => "text",
-        ),
-        'civicrm_price_field_value' => array(
-          'label' => "varchar(255)",
-          'description' => "text",
-        ),
-        'civicrm_pcp_block' => array(
-          'link_text' => "varchar(255)",
-        ),
-        'civicrm_event' => array(
-          'title' => "varchar(255)",
-          'summary' => "text",
-          'description' => "text",
-          'registration_link_text' => "varchar(255)",
-          'event_full_text' => "text",
-          'fee_label' => "varchar(255)",
-          'intro_text' => "text",
-          'footer_text' => "text",
-          'confirm_title' => "varchar(255)",
-          'confirm_text' => "text",
-          'confirm_footer_text' => "text",
-          'confirm_email_text' => "text",
-          'confirm_from_name' => "varchar(255)",
-          'thankyou_title' => "varchar(255)",
-          'thankyou_text' => "text",
-          'thankyou_footer_text' => "text",
-          'pay_later_text' => "text",
-          'pay_later_receipt' => "text",
-          'waitlist_text' => "text",
-          'approval_req_text' => "text",
-          'template_title' => "varchar(255)",
-        ),
-      );
-    }
-    return $result;
-  }
-
-  /**
-   * @return array
-   */
-  public static function &indices() {
-    static $result = NULL;
-    if (!$result) {
-      $result = array(
-        'civicrm_price_set' => array(
-          'UI_title' => array(
-            'name' => 'UI_title',
-            'field' => array(
-              'title',
-            ),
-            'unique' => 1,
-          ),
-        ),
-        'civicrm_custom_group' => array(
-          'UI_title_extends' => array(
-            'name' => 'UI_title_extends',
-            'field' => array(
-              'title',
-              'extends',
-            ),
-            'unique' => 1,
-          ),
-        ),
-        'civicrm_custom_field' => array(
-          'UI_label_custom_group_id' => array(
-            'name' => 'UI_label_custom_group_id',
-            'field' => array(
-              'label',
-              'custom_group_id',
-            ),
-            'unique' => 1,
-          ),
-        ),
-      );
-    }
-    return $result;
-  }
-
-  /**
-   * @return array
-   */
-  public static function &tables() {
-    static $result = NULL;
-    if (!$result) {
-      $result = array_keys(self::columns());
-    }
-    return $result;
-  }
-
-}
diff --git a/civicrm/CRM/Core/I18n/SchemaStructure_4_1_alpha1.php b/civicrm/CRM/Core/I18n/SchemaStructure_4_1_alpha1.php
deleted file mode 100644
index 1545d5de32..0000000000
--- a/civicrm/CRM/Core/I18n/SchemaStructure_4_1_alpha1.php
+++ /dev/null
@@ -1,226 +0,0 @@
-<?php
-/*
-+--------------------------------------------------------------------+
-| CiviCRM version 4.7                                                |
-+--------------------------------------------------------------------+
-| Copyright CiviCRM LLC (c) 2004-2018                                |
-+--------------------------------------------------------------------+
-| 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-2018
- * $Id$
- *
- */
-class CRM_Core_I18n_SchemaStructure_4_1_alpha1 {
-  /**
-   * @return array
-   */
-  public static function &columns() {
-    static $result = NULL;
-    if (!$result) {
-      $result = array(
-        'civicrm_location_type' => array(
-          'display_name' => "varchar(64)",
-        ),
-        'civicrm_option_group' => array(
-          'title' => "varchar(255)",
-          'description' => "varchar(255)",
-        ),
-        'civicrm_contact_type' => array(
-          'label' => "varchar(64)",
-          'description' => "text",
-        ),
-        'civicrm_premiums' => array(
-          'premiums_intro_title' => "varchar(255)",
-          'premiums_intro_text' => "text",
-        ),
-        'civicrm_product' => array(
-          'name' => "varchar(255)",
-          'description' => "text",
-          'options' => "text",
-        ),
-        'civicrm_membership_status' => array(
-          'label' => "varchar(128)",
-        ),
-        'civicrm_participant_status_type' => array(
-          'label' => "varchar(255)",
-        ),
-        'civicrm_tell_friend' => array(
-          'title' => "varchar(255)",
-          'intro' => "text",
-          'suggested_message' => "text",
-          'thankyou_title' => "varchar(255)",
-          'thankyou_text' => "text",
-        ),
-        'civicrm_price_set' => array(
-          'title' => "varchar(255)",
-          'help_pre' => "text",
-          'help_post' => "text",
-        ),
-        'civicrm_batch' => array(
-          'label' => "varchar(64)",
-          'description' => "text",
-        ),
-        'civicrm_custom_group' => array(
-          'title' => "varchar(64)",
-          'help_pre' => "text",
-          'help_post' => "text",
-        ),
-        'civicrm_custom_field' => array(
-          'label' => "varchar(255)",
-          'help_pre' => "text",
-          'help_post' => "text",
-        ),
-        'civicrm_dashboard' => array(
-          'label' => "varchar(255)",
-        ),
-        'civicrm_option_value' => array(
-          'label' => "varchar(255)",
-          'description' => "text",
-        ),
-        'civicrm_contribution_page' => array(
-          'title' => "varchar(255)",
-          'intro_text' => "text",
-          'pay_later_text' => "text",
-          'pay_later_receipt' => "text",
-          'thankyou_title' => "varchar(255)",
-          'thankyou_text' => "text",
-          'thankyou_footer' => "text",
-          'for_organization' => "text",
-          'receipt_from_name' => "varchar(255)",
-          'receipt_text' => "text",
-          'footer_text' => "text",
-          'honor_block_title' => "varchar(255)",
-          'honor_block_text' => "text",
-        ),
-        'civicrm_price_field' => array(
-          'label' => "varchar(255)",
-          'help_pre' => "text",
-          'help_post' => "text",
-        ),
-        'civicrm_uf_group' => array(
-          'title' => "varchar(64)",
-          'help_pre' => "text",
-          'help_post' => "text",
-        ),
-        'civicrm_uf_field' => array(
-          'help_post' => "text",
-          'help_pre' => "text",
-          'label' => "varchar(255)",
-        ),
-        'civicrm_membership_type' => array(
-          'name' => "varchar(128)",
-          'description' => "varchar(255)",
-        ),
-        'civicrm_membership_block' => array(
-          'new_title' => "varchar(255)",
-          'new_text' => "text",
-          'renewal_title' => "varchar(255)",
-          'renewal_text' => "text",
-        ),
-        'civicrm_price_field_value' => array(
-          'label' => "varchar(255)",
-          'description' => "text",
-        ),
-        'civicrm_event' => array(
-          'title' => "varchar(255)",
-          'summary' => "text",
-          'description' => "text",
-          'registration_link_text' => "varchar(255)",
-          'event_full_text' => "text",
-          'fee_label' => "varchar(255)",
-          'intro_text' => "text",
-          'footer_text' => "text",
-          'confirm_title' => "varchar(255)",
-          'confirm_text' => "text",
-          'confirm_footer_text' => "text",
-          'confirm_email_text' => "text",
-          'confirm_from_name' => "varchar(255)",
-          'thankyou_title' => "varchar(255)",
-          'thankyou_text' => "text",
-          'thankyou_footer_text' => "text",
-          'pay_later_text' => "text",
-          'pay_later_receipt' => "text",
-          'waitlist_text' => "text",
-          'approval_req_text' => "text",
-          'template_title' => "varchar(255)",
-        ),
-      );
-    }
-    return $result;
-  }
-
-  /**
-   * @return array
-   */
-  public static function &indices() {
-    static $result = NULL;
-    if (!$result) {
-      $result = array(
-        'civicrm_price_set' => array(
-          'UI_title' => array(
-            'name' => 'UI_title',
-            'field' => array(
-              'title',
-            ),
-            'unique' => 1,
-          ),
-        ),
-        'civicrm_custom_group' => array(
-          'UI_title_extends' => array(
-            'name' => 'UI_title_extends',
-            'field' => array(
-              'title',
-              'extends',
-            ),
-            'unique' => 1,
-          ),
-        ),
-        'civicrm_custom_field' => array(
-          'UI_label_custom_group_id' => array(
-            'name' => 'UI_label_custom_group_id',
-            'field' => array(
-              'label',
-              'custom_group_id',
-            ),
-            'unique' => 1,
-          ),
-        ),
-      );
-    }
-    return $result;
-  }
-
-  /**
-   * @return array
-   */
-  public static function &tables() {
-    static $result = NULL;
-    if (!$result) {
-      $result = array_keys(self::columns());
-    }
-    return $result;
-  }
-
-}
diff --git a/civicrm/CRM/Core/OptionGroup.php b/civicrm/CRM/Core/OptionGroup.php
index a6fdb677f8..c9a95591b8 100644
--- a/civicrm/CRM/Core/OptionGroup.php
+++ b/civicrm/CRM/Core/OptionGroup.php
@@ -342,7 +342,7 @@ WHERE  v.option_group_id = g.id
    * @return null
    */
   public static function getLabel($groupName, $value, $onlyActiveValue = TRUE) {
-    Civi::log()->warning('Deprecated function, use CRM_Core_PseudoConstant::getLabel', array('civi.tag' => 'deprecated'));
+    Civi::log()->warning('Deprecated function CRM_Core_OptionGroup::getLabel, use CRM_Core_PseudoConstant::getLabel', array('civi.tag' => 'deprecated'));
     if (empty($groupName) ||
       empty($value)
     ) {
@@ -396,7 +396,7 @@ WHERE  v.option_group_id = g.id
       return NULL;
     }
 
-    Civi::log()->warning('Deprecated function, use CRM_Core_PseudoConstant::getKey', array('civi.tag' => 'deprecated'));
+    Civi::log()->warning('Deprecated function CRM_Core_OptionGroup::getValue, use CRM_Core_PseudoConstant::getKey', array('civi.tag' => 'deprecated'));
 
     $query = "
 SELECT  v.label as label ,v.{$valueField} as value
diff --git a/civicrm/CRM/Custom/Form/Option.php b/civicrm/CRM/Custom/Form/Option.php
index 7426b98b31..7d81cb6069 100644
--- a/civicrm/CRM/Custom/Form/Option.php
+++ b/civicrm/CRM/Custom/Form/Option.php
@@ -181,6 +181,7 @@ class CRM_Custom_Form_Option extends CRM_Core_Form {
 
       $this->add('text', 'value', ts('Option Value'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_OptionValue', 'value'), TRUE);
 
+      $this->add('textarea', 'description', ts('Description'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_OptionValue', 'description'));
       // weight
       $this->add('text', 'weight', ts('Order'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_OptionValue', 'weight'), TRUE);
       $this->addRule('weight', ts('is a numeric field'), 'numeric');
@@ -406,6 +407,7 @@ SELECT count(*)
     $customOption->label = $params['label'];
     $customOption->name = CRM_Utils_String::titleToVar($params['label']);
     $customOption->weight = $params['weight'];
+    $customOption->description = $params['description'];
     $customOption->value = $params['value'];
     $customOption->is_active = CRM_Utils_Array::value('is_active', $params, FALSE);
 
diff --git a/civicrm/CRM/Custom/Page/AJAX.php b/civicrm/CRM/Custom/Page/AJAX.php
index fba5e2b108..653971cde5 100644
--- a/civicrm/CRM/Custom/Page/AJAX.php
+++ b/civicrm/CRM/Custom/Page/AJAX.php
@@ -57,6 +57,7 @@ class CRM_Custom_Page_AJAX {
     $selectorElements = array(
       'label',
       'value',
+      'description',
       'is_default',
       'is_active',
       'links',
diff --git a/civicrm/CRM/Dedupe/Merger.php b/civicrm/CRM/Dedupe/Merger.php
index 3a6eba7f6d..a2b25399dd 100644
--- a/civicrm/CRM/Dedupe/Merger.php
+++ b/civicrm/CRM/Dedupe/Merger.php
@@ -322,6 +322,7 @@ class CRM_Dedupe_Merger {
         // Empty array == do nothing - this table is handled by mergeGroupContact
         'civicrm_subscription_history' => array(),
         'civicrm_relationship' => array('CRM_Contact_BAO_Relationship' => 'mergeRelationships'),
+        'civicrm_membership' => array('CRM_Member_BAO_Membership' => 'mergeMemberships'),
       );
     }
     return $tables;
@@ -518,7 +519,7 @@ INNER JOIN  civicrm_membership membership2 ON membership1.membership_type_id = m
       // Call custom processing function for objects that require it
       if (isset($cpTables[$table])) {
         foreach ($cpTables[$table] as $className => $fnName) {
-          $className::$fnName($mainId, $otherId, $sqls);
+          $className::$fnName($mainId, $otherId, $sqls, $tables, $tableOperations);
         }
         // Skip normal processing
         continue;
diff --git a/civicrm/CRM/Event/BAO/Participant.php b/civicrm/CRM/Event/BAO/Participant.php
index 1a8edcc2a9..7d6bd6c992 100644
--- a/civicrm/CRM/Event/BAO/Participant.php
+++ b/civicrm/CRM/Event/BAO/Participant.php
@@ -1432,24 +1432,24 @@ UPDATE  civicrm_participant
 
       //check is it primary and has additional.
       if (array_key_exists($participantId, $primaryANDAdditonalIds)) {
-        foreach ($primaryANDAdditonalIds[$participantId] as $additonalId) {
+        foreach ($primaryANDAdditonalIds[$participantId] as $additionalId) {
 
           if ($emailType) {
-            $mail = self::sendTransitionParticipantMail($additonalId,
-              $participantDetails[$additonalId],
-              $eventDetails[$participantDetails[$additonalId]['event_id']],
-              $contactDetails[$participantDetails[$additonalId]['contact_id']],
+            $mail = self::sendTransitionParticipantMail($additionalId,
+              $participantDetails[$additionalId],
+              $eventDetails[$participantDetails[$additionalId]['event_id']],
+              $contactDetails[$participantDetails[$additionalId]['contact_id']],
               $domainValues,
               $emailType
             );
 
             //get the mail participant ids
             if ($mail) {
-              $mailedParticipants[$additonalId] = $contactDetails[$participantDetails[$additonalId]['contact_id']]['display_name'];
+              $mailedParticipants[$additionalId] = $contactDetails[$participantDetails[$additionalId]['contact_id']]['display_name'];
             }
           }
-          $updateParticipantIds[] = $additonalId;
-          $processedParticipantIds[] = $additonalId;
+          $updateParticipantIds[] = $additionalId;
+          $processedParticipantIds[] = $additionalId;
         }
       }
 
@@ -1898,13 +1898,11 @@ WHERE    civicrm_participant.contact_id = {$contactID} AND
     $date = CRM_Utils_Date::currentDBDate();
     $event = CRM_Event_BAO_Event::getEvents(0, $eventId);
     $subject = sprintf("Registration selections changed for %s", CRM_Utils_Array::value($eventId, $event));
-    $targetCid = $contactId;
-    $srcRecId = $participantId;
 
     // activity params
     $activityParams = array(
-      'source_contact_id' => $targetCid,
-      'source_record_id' => $srcRecId,
+      'source_contact_id' => $contactId,
+      'source_record_id' => $participantId,
       'activity_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', $activityType),
       'subject' => $subject,
       'activity_date_time' => $date,
@@ -1913,11 +1911,10 @@ WHERE    civicrm_participant.contact_id = {$contactID} AND
     );
 
     // create activity with target contacts
-    $session = CRM_Core_Session::singleton();
-    $id = $session->get('userID');
+    $id = CRM_Core_Session::singleton()->getLoggedInContactID();;
     if ($id) {
       $activityParams['source_contact_id'] = $id;
-      $activityParams['target_contact_id'][] = $targetCid;
+      $activityParams['target_contact_id'][] = $contactId;
     }
     // @todo use api & also look at duplication of similar methods.
     CRM_Activity_BAO_Activity::create($activityParams);
diff --git a/civicrm/CRM/Export/BAO/Export.php b/civicrm/CRM/Export/BAO/Export.php
index 132e9318c1..70a1a14e73 100644
--- a/civicrm/CRM/Export/BAO/Export.php
+++ b/civicrm/CRM/Export/BAO/Export.php
@@ -770,27 +770,15 @@ INSERT INTO {$componentTable} SELECT distinct gc.contact_id FROM civicrm_group_c
     $limitReached = FALSE;
     while (!$limitReached) {
       $limitQuery = "{$queryString} LIMIT {$offset}, {$rowCount}";
-      $dao = CRM_Core_DAO::executeQuery($limitQuery);
+      $iterationDAO = CRM_Core_DAO::executeQuery($limitQuery);
       // If this is less than our limit by the end of the iteration we do not need to run the query again to
       // check if some remain.
       $rowsThisIteration = 0;
 
-      while ($dao->fetch()) {
+      while ($iterationDAO->fetch()) {
         $count++;
         $rowsThisIteration++;
         $row = array();
-
-        //convert the pseudo constants
-        // CRM-14398 there is problem in this architecture that is not easily solved. For now we are using the cloned
-        // temporary iterationDAO object to get around it.
-        // the issue is that the convertToPseudoNames function is adding additional properties (e.g for campaign) to the DAO object
-        // these additional properties are NOT reset when the $dao cycles through the while loop
-        // nor are they overwritten as they are not in the loop
-        // the convertToPseudoNames will not adequately over-write them either as it doesn't 'kick-in' unless the
-        // relevant property is set.
-        // It may be that a long-term fix could be introduced there - however, it's probably necessary to figure out how to test the
-        // export class before tackling a better architectural fix
-        $iterationDAO = clone $dao;
         $query->convertToPseudoNames($iterationDAO);
 
         //first loop through output columns so that we return what is required, and in same order.
@@ -839,105 +827,7 @@ INSERT INTO {$componentTable} SELECT distinct gc.contact_id FROM civicrm_group_c
           elseif (array_key_exists($field, $contactRelationshipTypes)) {
             $relDAO = CRM_Utils_Array::value($iterationDAO->contact_id, $allRelContactArray[$field]);
             $relationQuery[$field]->convertToPseudoNames($relDAO);
-            foreach ($value as $relationField => $relationValue) {
-              if (is_object($relDAO) && property_exists($relDAO, $relationField)) {
-                $fieldValue = $relDAO->$relationField;
-                if ($relationField == 'phone_type_id') {
-                  $fieldValue = $phoneTypes[$relationValue];
-                }
-                elseif ($relationField == 'provider_id') {
-                  $fieldValue = CRM_Utils_Array::value($relationValue, $imProviders);
-                }
-                // CRM-13995
-                elseif (is_object($relDAO) && in_array($relationField, array(
-                    'email_greeting',
-                    'postal_greeting',
-                    'addressee',
-                  ))
-                ) {
-                  //special case for greeting replacement
-                  $fldValue = "{$relationField}_display";
-                  $fieldValue = $relDAO->$fldValue;
-                }
-              }
-              elseif (is_object($relDAO) && $relationField == 'state_province') {
-                $fieldValue = CRM_Core_PseudoConstant::stateProvince($relDAO->state_province_id);
-              }
-              elseif (is_object($relDAO) && $relationField == 'country') {
-                $fieldValue = CRM_Core_PseudoConstant::country($relDAO->country_id);
-              }
-              else {
-                $fieldValue = '';
-              }
-              $field = $field . '_';
-
-              if (is_object($relDAO) && $relationField == 'id') {
-                $row[$field . $relationField] = $relDAO->contact_id;
-              }
-              elseif (is_array($relationValue) && $relationField == 'location') {
-                foreach ($relationValue as $ltype => $val) {
-                  foreach (array_keys($val) as $fld) {
-                    $type = explode('-', $fld);
-                    $fldValue = "{$ltype}-" . $type[0];
-                    if (!empty($type[1])) {
-                      $fldValue .= "-" . $type[1];
-                    }
-                    // CRM-3157: localise country, region (both have ‘country’ context)
-                    // and state_province (‘province’ context)
-                    switch (TRUE) {
-                      case (!is_object($relDAO)):
-                        $row[$field . '_' . $fldValue] = '';
-                        break;
-
-                      case in_array('country', $type):
-                      case in_array('world_region', $type):
-                        $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
-                          array('context' => 'country')
-                        );
-                        break;
-
-                      case in_array('state_province', $type):
-                        $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
-                          array('context' => 'province')
-                        );
-                        break;
-
-                      default:
-                        $row[$field . '_' . $fldValue] = $relDAO->$fldValue;
-                        break;
-                    }
-                  }
-                }
-              }
-              elseif (isset($fieldValue) && $fieldValue != '') {
-                //check for custom data
-                if ($cfID = CRM_Core_BAO_CustomField::getKeyID($relationField)) {
-                  $row[$field . $relationField] = CRM_Core_BAO_CustomField::displayValue($fieldValue, $cfID);
-                }
-                else {
-                  //normal relationship fields
-                  // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context)
-                  switch ($relationField) {
-                    case 'country':
-                    case 'world_region':
-                      $row[$field . $relationField] = $i18n->crm_translate($fieldValue, array('context' => 'country'));
-                      break;
-
-                    case 'state_province':
-                      $row[$field . $relationField] = $i18n->crm_translate($fieldValue, array('context' => 'province'));
-                      break;
-
-                    default:
-                      $row[$field . $relationField] = $fieldValue;
-                      break;
-                  }
-                }
-              }
-              else {
-                // if relation field is empty or null
-                $row[$field . $relationField] = '';
-              }
-            }
+            self::fetchRelationshipDetails($relDAO, $value, $field, $row);
           }
           elseif (isset($fieldValue) &&
             $fieldValue != ''
@@ -1070,7 +960,6 @@ INSERT INTO {$componentTable} SELECT distinct gc.contact_id FROM civicrm_group_c
           $componentDetails = array();
         }
       }
-      $dao->free();
       if ($rowsThisIteration < self::EXPORT_ROW_COUNT) {
         $limitReached = TRUE;
       }
@@ -2175,4 +2064,117 @@ WHERE  {$whereClause}";
     return array($outputColumns, $headerRows, $sqlColumns, $metadata);
   }
 
+  /**
+   * Get the values of linked household contact.
+   *
+   * @param CRM_Core_DAO $relDAO
+   * @param array $value
+   * @param string $field
+   * @param array $row
+   */
+  private static function fetchRelationshipDetails($relDAO, $value, $field, &$row) {
+    $phoneTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id');
+    $imProviders = CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id');
+    $i18n = CRM_Core_I18n::singleton();
+    foreach ($value as $relationField => $relationValue) {
+      if (is_object($relDAO) && property_exists($relDAO, $relationField)) {
+        $fieldValue = $relDAO->$relationField;
+        if ($relationField == 'phone_type_id') {
+          $fieldValue = $phoneTypes[$relationValue];
+        }
+        elseif ($relationField == 'provider_id') {
+          $fieldValue = CRM_Utils_Array::value($relationValue, $imProviders);
+        }
+        // CRM-13995
+        elseif (is_object($relDAO) && in_array($relationField, array(
+            'email_greeting',
+            'postal_greeting',
+            'addressee',
+          ))
+        ) {
+          //special case for greeting replacement
+          $fldValue = "{$relationField}_display";
+          $fieldValue = $relDAO->$fldValue;
+        }
+      }
+      elseif (is_object($relDAO) && $relationField == 'state_province') {
+        $fieldValue = CRM_Core_PseudoConstant::stateProvince($relDAO->state_province_id);
+      }
+      elseif (is_object($relDAO) && $relationField == 'country') {
+        $fieldValue = CRM_Core_PseudoConstant::country($relDAO->country_id);
+      }
+      else {
+        $fieldValue = '';
+      }
+      $field = $field . '_';
+
+      if (is_object($relDAO) && $relationField == 'id') {
+        $row[$field . $relationField] = $relDAO->contact_id;
+      }
+      elseif (is_array($relationValue) && $relationField == 'location') {
+        foreach ($relationValue as $ltype => $val) {
+          foreach (array_keys($val) as $fld) {
+            $type = explode('-', $fld);
+            $fldValue = "{$ltype}-" . $type[0];
+            if (!empty($type[1])) {
+              $fldValue .= "-" . $type[1];
+            }
+            // CRM-3157: localise country, region (both have ‘country’ context)
+            // and state_province (‘province’ context)
+            switch (TRUE) {
+              case (!is_object($relDAO)):
+                $row[$field . '_' . $fldValue] = '';
+                break;
+
+              case in_array('country', $type):
+              case in_array('world_region', $type):
+                $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
+                  array('context' => 'country')
+                );
+                break;
+
+              case in_array('state_province', $type):
+                $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
+                  array('context' => 'province')
+                );
+                break;
+
+              default:
+                $row[$field . '_' . $fldValue] = $relDAO->$fldValue;
+                break;
+            }
+          }
+        }
+      }
+      elseif (isset($fieldValue) && $fieldValue != '') {
+        //check for custom data
+        if ($cfID = CRM_Core_BAO_CustomField::getKeyID($relationField)) {
+          $row[$field . $relationField] = CRM_Core_BAO_CustomField::displayValue($fieldValue, $cfID);
+        }
+        else {
+          //normal relationship fields
+          // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context)
+          switch ($relationField) {
+            case 'country':
+            case 'world_region':
+              $row[$field . $relationField] = $i18n->crm_translate($fieldValue, array('context' => 'country'));
+              break;
+
+            case 'state_province':
+              $row[$field . $relationField] = $i18n->crm_translate($fieldValue, array('context' => 'province'));
+              break;
+
+            default:
+              $row[$field . $relationField] = $fieldValue;
+              break;
+          }
+        }
+      }
+      else {
+        // if relation field is empty or null
+        $row[$field . $relationField] = '';
+      }
+    }
+  }
+
 }
diff --git a/civicrm/CRM/Financial/BAO/PaymentProcessor.php b/civicrm/CRM/Financial/BAO/PaymentProcessor.php
index ad04284ad1..ba90e5ebf8 100644
--- a/civicrm/CRM/Financial/BAO/PaymentProcessor.php
+++ b/civicrm/CRM/Financial/BAO/PaymentProcessor.php
@@ -569,6 +569,26 @@ INNER JOIN civicrm_contribution       con ON ( mp.contribution_id = con.id )
     return Civi\Payment\System::singleton()->getById($paymentProcessorId);
   }
 
+  /**
+   * Get the name of the payment processor
+   *
+   * @param $paymentProcessorId
+   *
+   * @return null|string
+   */
+  public static function getPaymentProcessorName($paymentProcessorId) {
+    try {
+      $paymentProcessor = civicrm_api3('PaymentProcessor', 'getsingle', array(
+        'return' => array('name'),
+        'id' => $paymentProcessorId,
+      ));
+      return $paymentProcessor['name'];
+    }
+    catch (Exception $e) {
+      return ts('Unknown') . ' (' . $paymentProcessorId . ')';
+    }
+  }
+
   /**
    * Generate and assign an arbitrary value to a field of a test object.
    *
diff --git a/civicrm/CRM/Financial/Form/FinancialBatch.php b/civicrm/CRM/Financial/Form/FinancialBatch.php
index b8e336ab4e..59b6cc4d36 100644
--- a/civicrm/CRM/Financial/Form/FinancialBatch.php
+++ b/civicrm/CRM/Financial/Form/FinancialBatch.php
@@ -114,10 +114,10 @@ class CRM_Financial_Form_FinancialBatch extends CRM_Contribute_Form {
     );
 
     if ($this->_action & CRM_Core_Action::UPDATE && $this->_id) {
-      $batchStatus = CRM_Core_PseudoConstant::get('CRM_Batch_DAO_Batch', 'status_id');
+      $batchStatus = CRM_Core_PseudoConstant::get('CRM_Batch_BAO_Batch', 'status_id');
 
       // unset exported status
-      $exportedStatusId = CRM_Utils_Array::key('Exported', $batchStatus);
+      $exportedStatusId = CRM_Core_PseudoConstant::getKey('CRM_Batch_BAO_Batch', 'status_id', 'Exported');
       unset($batchStatus[$exportedStatusId]);
       $this->add('select', 'status_id', ts('Batch Status'), array('' => ts('- select -')) + $batchStatus, TRUE);
       $this->freeze(array('status_id'));
@@ -196,7 +196,7 @@ class CRM_Financial_Form_FinancialBatch extends CRM_Contribute_Form {
   public function postProcess() {
     $session = CRM_Core_Session::singleton();
     $params = $this->exportValues();
-    $batchStatus = CRM_Core_PseudoConstant::get('CRM_Batch_DAO_Batch', 'status_id');
+    $closedStatusId = CRM_Core_PseudoConstant::getKey('CRM_Batch_BAO_Batch', 'status_id', 'Closed');
     if ($this->_id) {
       $params['id'] = $this->_id;
     }
@@ -209,9 +209,8 @@ class CRM_Financial_Form_FinancialBatch extends CRM_Contribute_Form {
     }
 
     if ($this->_action & CRM_Core_Action::ADD) {
-      $batchMode = CRM_Core_PseudoConstant::get('CRM_Batch_DAO_Batch', 'mode_id', array('labelColumn' => 'name'));
-      $params['mode_id'] = CRM_Utils_Array::key('Manual Batch', $batchMode);
-      $params['status_id'] = CRM_Utils_Array::key('Open', $batchStatus);
+      $params['mode_id'] = CRM_Core_PseudoConstant::getKey('CRM_Batch_BAO_Batch', 'mode_id', 'Manual Batch');
+      $params['status_id'] = CRM_Core_PseudoConstant::getKey('CRM_Batch_BAO_Batch', 'status_id', 'Open');
       $params['created_date'] = date('YmdHis');
       if (empty($params['created_id'])) {
         $params['created_id'] = $session->get('userID');
@@ -221,25 +220,25 @@ class CRM_Financial_Form_FinancialBatch extends CRM_Contribute_Form {
     }
     elseif ($this->_action & CRM_Core_Action::UPDATE && $this->_id) {
       $details = "{$params['title']} batch has been edited by this contact.";
-      if (CRM_Utils_Array::value($params['status_id'], $batchStatus) == 'Closed') {
+      if ($params['status_id'] === $closedStatusId) {
         $details = "{$params['title']} batch has been closed by this contact.";
       }
       $activityTypeName = 'Edit Batch';
     }
 
+    // FIXME: What happens if we get to here and no activityType is defined?
+
     $batch = CRM_Batch_BAO_Batch::create($params);
 
     //set batch id
     $this->_id = $batch->id;
 
-    $activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, FALSE, FALSE, 'name');
-
     // create activity.
     $activityParams = array(
-      'activity_type_id' => array_search($activityTypeName, $activityTypes),
+      'activity_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_DAO_Activity', 'activity_type_id', $activityTypeName),
       'subject' => $batch->title . "- Batch",
-      'status_id' => 2,
-      'priority_id' => 2,
+      'status_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_DAO_Activity', 'activity_status_id', 'Completed'),
+      'priority_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_DAO_Activity', 'priority_id', 'Normal'),
       'activity_date_time' => date('YmdHis'),
       'source_contact_id' => $session->get('userID'),
       'source_contact_qid' => $session->get('userID'),
@@ -262,7 +261,7 @@ class CRM_Financial_Form_FinancialBatch extends CRM_Contribute_Form {
       $session->replaceUserContext(CRM_Utils_System::url('civicrm/financial/batch',
         "reset=1&action=add"));
     }
-    elseif (CRM_Utils_Array::value($batch->status_id, $batchStatus) == 'Closed') {
+    elseif ($batch->status_id === $closedStatusId) {
       $session->replaceUserContext(CRM_Utils_System::url('civicrm', 'reset=1'));
     }
     elseif (($buttonName == $this->getButtonName('next') & $this->_action == CRM_Core_Action::UPDATE) ||
diff --git a/civicrm/CRM/Group/Form/Edit.php b/civicrm/CRM/Group/Form/Edit.php
index 0ef2b90b1f..8c286116e9 100644
--- a/civicrm/CRM/Group/Form/Edit.php
+++ b/civicrm/CRM/Group/Form/Edit.php
@@ -106,7 +106,12 @@ class CRM_Group_Form_Edit extends CRM_Core_Form {
     if ($this->_action == CRM_Core_Action::DELETE) {
       if (isset($this->_id)) {
         $this->assign('title', $this->_title);
-        $this->assign('count', CRM_Contact_BAO_Group::memberCount($this->_id));
+        try {
+          $this->assign('count', CRM_Contact_BAO_Group::memberCount($this->_id));
+        }
+        catch (CRM_Core_Exception $e) {
+          // If the group is borked the query might fail but delete should be possible.
+        }
         CRM_Utils_System::setTitle(ts('Confirm Group Delete'));
       }
       if ($this->_groupValues['is_reserved'] == 1 && !CRM_Core_Permission::check('administer reserved groups')) {
diff --git a/civicrm/CRM/Logging/Schema.php b/civicrm/CRM/Logging/Schema.php
index de3f13bccc..e9ec1b44ba 100644
--- a/civicrm/CRM/Logging/Schema.php
+++ b/civicrm/CRM/Logging/Schema.php
@@ -572,7 +572,7 @@ AND    (TABLE_NAME LIKE 'log_civicrm_%' $nonStandardTableNameString )
       // NOTE: W.r.t Performance using one query to find all details and storing in static array is much faster
       // than firing query for every given table.
       $query = "
-SELECT TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME, DATA_TYPE, IS_NULLABLE, COLUMN_DEFAULT, COLUMN_TYPE
+SELECT TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME, DATA_TYPE, IS_NULLABLE, COLUMN_DEFAULT, COLUMN_TYPE, EXTRA
 FROM   INFORMATION_SCHEMA.COLUMNS
 WHERE  table_schema IN ('{$this->db}', '{$civiDB}')";
       $dao = CRM_Core_DAO::executeQuery($query);
@@ -588,6 +588,7 @@ WHERE  table_schema IN ('{$this->db}', '{$civiDB}')";
           'DATA_TYPE' => $dao->DATA_TYPE,
           'IS_NULLABLE' => $dao->IS_NULLABLE,
           'COLUMN_DEFAULT' => $dao->COLUMN_DEFAULT,
+          'EXTRA' => $dao->EXTRA,
         );
         if (($first = strpos($dao->COLUMN_TYPE, '(')) != 0) {
           \Civi::$statics[__CLASS__]['columnSpecs'][$dao->TABLE_NAME][$dao->COLUMN_NAME]['LENGTH'] = substr(
@@ -612,10 +613,8 @@ WHERE  table_schema IN ('{$this->db}', '{$civiDB}')";
     $logTableSpecs = $this->columnSpecsOf($logTable);
 
     $diff = array('ADD' => array(), 'MODIFY' => array(), 'OBSOLETE' => array());
-
     // columns to be added
     $diff['ADD'] = array_diff(array_keys($civiTableSpecs), array_keys($logTableSpecs));
-
     // columns to be modified
     // NOTE: we consider only those columns for modifications where there is a spec change, and that the column definition
     // wasn't deliberately modified by fixTimeStampAndNotNullSQL() method.
@@ -623,28 +622,29 @@ WHERE  table_schema IN ('{$this->db}', '{$civiDB}')";
       if (!isset($logTableSpecs[$col]) || !is_array($logTableSpecs[$col])) {
         $logTableSpecs[$col] = array();
       }
-
       $specDiff = array_diff($civiTableSpecs[$col], $logTableSpecs[$col]);
-      if (!empty($specDiff) && $col != 'id' && !array_key_exists($col, $diff['ADD'])) {
-        // ignore 'id' column for any spec changes, to avoid any auto-increment mysql errors
-        if ($civiTableSpecs[$col]['DATA_TYPE'] != CRM_Utils_Array::value('DATA_TYPE', $logTableSpecs[$col])
-        // We won't alter the log if the length is decreased in case some of the existing data won't fit.
-        || CRM_Utils_Array::value('LENGTH', $civiTableSpecs[$col]) > CRM_Utils_Array::value('LENGTH', $logTableSpecs[$col])
-        ) {
-          // if data-type is different, surely consider the column
-          $diff['MODIFY'][] = $col;
-        }
-        elseif ($civiTableSpecs[$col]['IS_NULLABLE'] != CRM_Utils_Array::value('IS_NULLABLE', $logTableSpecs[$col]) &&
-          $logTableSpecs[$col]['IS_NULLABLE'] == 'NO'
-        ) {
-          // if is-null property is different, and log table's column is NOT-NULL, surely consider the column
-          $diff['MODIFY'][] = $col;
-        }
-        elseif ($civiTableSpecs[$col]['COLUMN_DEFAULT'] != CRM_Utils_Array::value('COLUMN_DEFAULT', $logTableSpecs[$col]) &&
-          !strstr($civiTableSpecs[$col]['COLUMN_DEFAULT'], 'TIMESTAMP')
-        ) {
-          // if default property is different, and its not about a timestamp column, consider it
-          $diff['MODIFY'][] = $col;
+      if (!empty($specDiff) && $col != 'id' && !in_array($col, $diff['ADD'])) {
+        if (empty($colSpecs['EXTRA']) || (!empty($colSpecs['EXTRA']) && $colSpecs['EXTRA'] !== 'auto_increment')) {
+          // ignore 'id' column for any spec changes, to avoid any auto-increment mysql errors
+          if ($civiTableSpecs[$col]['DATA_TYPE'] != CRM_Utils_Array::value('DATA_TYPE', $logTableSpecs[$col])
+          // We won't alter the log if the length is decreased in case some of the existing data won't fit.
+          || CRM_Utils_Array::value('LENGTH', $civiTableSpecs[$col]) > CRM_Utils_Array::value('LENGTH', $logTableSpecs[$col])
+          ) {
+            // if data-type is different, surely consider the column
+            $diff['MODIFY'][] = $col;
+          }
+          elseif ($civiTableSpecs[$col]['IS_NULLABLE'] != CRM_Utils_Array::value('IS_NULLABLE', $logTableSpecs[$col]) &&
+            $logTableSpecs[$col]['IS_NULLABLE'] == 'NO'
+          ) {
+            // if is-null property is different, and log table's column is NOT-NULL, surely consider the column
+            $diff['MODIFY'][] = $col;
+          }
+          elseif ($civiTableSpecs[$col]['COLUMN_DEFAULT'] != CRM_Utils_Array::value('COLUMN_DEFAULT', $logTableSpecs[$col]) &&
+            !strstr($civiTableSpecs[$col]['COLUMN_DEFAULT'], 'TIMESTAMP')
+          ) {
+            // if default property is different, and its not about a timestamp column, consider it
+            $diff['MODIFY'][] = $col;
+          }
         }
       }
     }
@@ -703,12 +703,20 @@ COLS;
     // - prepend the name with log_
     // - drop AUTO_INCREMENT columns
     // - drop non-column rows of the query (keys, constraints, etc.)
-    // - set the ENGINE to the specified engine (default is archive)
+    // - set the ENGINE to the specified engine (default is archive or if archive is disabled or nor installed INNODB)
     // - add log-specific columns (at the end of the table)
+    $mysqlEngines = [];
+    $engines = CRM_Core_DAO::executeQuery("SHOW ENGINES");
+    while ($engines->fetch()) {
+      if ($engines->Support == 'YES' || $engines->Support == 'DEFAULT') {
+        $mysqlEngines[] = $engines->Engine;
+      }
+    }
+    $logEngine = in_array('ARCHIVE', $mysqlEngines) ? 'ARCHIVE' : 'INNODB';
     $query = preg_replace("/^CREATE TABLE `$table`/i", "CREATE TABLE `{$this->db}`.log_$table", $query);
     $query = preg_replace("/ AUTO_INCREMENT/i", '', $query);
     $query = preg_replace("/^  [^`].*$/m", '', $query);
-    $engine = strtoupper(CRM_Utils_Array::value('engine', $this->logTableSpec[$table], 'ARCHIVE'));
+    $engine = strtoupper(CRM_Utils_Array::value('engine', $this->logTableSpec[$table], $logEngine));
     $engine .= " " . CRM_Utils_Array::value('engine_config', $this->logTableSpec[$table]);
     $query = preg_replace("/^\) ENGINE=[^ ]+ /im", ') ENGINE=' . $engine . ' ', $query);
 
diff --git a/civicrm/CRM/Mailing/BAO/Mailing.php b/civicrm/CRM/Mailing/BAO/Mailing.php
index 3a0f08048c..3790cd540f 100644
--- a/civicrm/CRM/Mailing/BAO/Mailing.php
+++ b/civicrm/CRM/Mailing/BAO/Mailing.php
@@ -335,7 +335,7 @@ class CRM_Mailing_BAO_Mailing extends CRM_Mailing_DAO_Mailing {
 
     $query = $query->select($selectClause)->orderBy($orderBy);
     if (!CRM_Utils_System::isNull($aclFrom)) {
-      $query = $query->from('acl', $aclFrom);
+      $query = $query->join('acl', $aclFrom);
     }
     if (!CRM_Utils_System::isNull($aclWhere)) {
       $query = $query->where($aclWhere);
diff --git a/civicrm/CRM/Mailing/BAO/MailingJob.php b/civicrm/CRM/Mailing/BAO/MailingJob.php
index 0d49819d64..d86815a7a4 100644
--- a/civicrm/CRM/Mailing/BAO/MailingJob.php
+++ b/civicrm/CRM/Mailing/BAO/MailingJob.php
@@ -375,11 +375,11 @@ class CRM_Mailing_BAO_MailingJob extends CRM_Mailing_DAO_MailingJob {
         continue;
       }
 
+      $transaction = new CRM_Core_Transaction();
+
       $job->split_job($offset);
 
       // update the status of the parent job
-      $transaction = new CRM_Core_Transaction();
-
       $saveJob = new CRM_Mailing_DAO_MailingJob();
       $saveJob->id = $job->id;
       $saveJob->start_date = date('YmdHis');
@@ -437,6 +437,7 @@ VALUES (%1, %2, %3, %4, %5, %6, %7)
         CRM_Core_DAO::executeQuery($sql, $params);
       }
     }
+
   }
 
   /**
diff --git a/civicrm/CRM/Member/BAO/Membership.php b/civicrm/CRM/Member/BAO/Membership.php
index c7dc326293..8c12469015 100644
--- a/civicrm/CRM/Member/BAO/Membership.php
+++ b/civicrm/CRM/Member/BAO/Membership.php
@@ -2125,9 +2125,12 @@ INNER JOIN  civicrm_contact contact ON ( contact.id = membership.contact_id AND
    */
   protected static function updateDeceasedMembersStatuses() {
     $count = 0;
+
+    $deceasedStatusId = CRM_Core_PseudoConstant::getKey('CRM_Member_BAO_Membership', 'status_id', 'Deceased');
+
     // 'create' context for buildOptions returns only if enabled.
     $allStatus = self::buildOptions('status_id', 'create');
-    if (($deceasedStatusId = array_search('Deceased', $allStatus)) === FALSE) {
+    if (array_key_exists($deceasedStatusId, $allStatus) === FALSE) {
       // Deceased status is an admin status & is required. We want to fail early if
       // it is not present or active.
       // We could make the case 'some databases just don't use deceased so we will check
@@ -2570,4 +2573,131 @@ WHERE      civicrm_membership.is_test = 0";
     return $cancelledMembershipIds;
   }
 
+  /**
+   * Merges the memberships from otherContactID to mainContactID.
+   *
+   * General idea is to merge memberships in regards to their type. We
+   * move the other contact’s contributions to the main contact’s
+   * membership which has the same type (if any) and then we update
+   * membership to avoid loosing `join_date`, `end_date`, and
+   * `status_id`. In this function, we don’t touch the contributions
+   * directly (CRM_Dedupe_Merger::moveContactBelongings() takes care
+   * of it).
+   *
+   * This function adds new SQL queries to the $sqlQueries parameter.
+   *
+   * @param int $mainContactID
+   *   Contact id of main contact record.
+   * @param int $otherContactID
+   *   Contact id of record which is going to merge.
+   * @param array $sqlQueries
+   *   (reference) array of SQL queries to be executed.
+   * @param array $tables
+   *   List of tables that have to be merged.
+   * @param array $tableOperations
+   *   Special options/params for some tables to be merged.
+   *
+   * @see CRM_Dedupe_Merger::cpTables()
+   */
+  public static function mergeMemberships($mainContactID, $otherContactID, &$sqlQueries, $tables, $tableOperations) {
+    /*
+     * If the user requests not to merge memberships but to add them,
+     * just attribute the `civicrm_membership` to the
+     * `$mainContactID`. We have to do this here since the general
+     * merge process is bypassed by this function.
+     */
+    if (array_key_exists("civicrm_membership", $tableOperations) && $tableOperations['civicrm_membership']['add']) {
+      $sqlQueries[] = "UPDATE IGNORE civicrm_membership SET contact_id = $mainContactID WHERE contact_id = $otherContactID";
+      return;
+    }
+
+    /*
+     * Retrieve all memberships that belongs to each contacts and
+     * keep track of each membership type.
+     */
+    $mainContactMemberships = array();
+    $otherContactMemberships = array();
+
+    $sql = "SELECT id, membership_type_id FROM civicrm_membership membership WHERE contact_id = %1";
+    $dao = CRM_Core_DAO::executeQuery($sql, array(1 => array($mainContactID, "Integer")));
+    while ($dao->fetch()) {
+      $mainContactMemberships[$dao->id] = $dao->membership_type_id;
+    }
+
+    $dao = CRM_Core_DAO::executeQuery($sql, array(1 => array($otherContactID, "Integer")));
+    while ($dao->fetch()) {
+      $otherContactMemberships[$dao->id] = $dao->membership_type_id;
+    }
+
+    /*
+     * For each membership, move related contributions to the main
+     * contact’s membership (by updating `membership_payments`). Then,
+     * update membership’s `join_date` (if the other membership’s
+     * join_date is older) and `end_date` (if the other membership’s
+     * `end_date` is newer) and `status_id` (if the newly calculated
+     * status is different).
+     *
+     * FIXME: what should we do if we have multiple memberships with
+     * the same type (currently we only take the first one)?
+     */
+    $newSql = array();
+    foreach ($otherContactMemberships as $otherMembershipId => $otherMembershipTypeId) {
+      if ($newMembershipId = array_search($otherMembershipTypeId, $mainContactMemberships)) {
+
+        /*
+         * Move other membership’s contributions to the main one only
+         * if user requested to merge contributions.
+         */
+        if (!empty($tables) && in_array('civicrm_contribution', $tables)) {
+          $newSql[] = "UPDATE civicrm_membership_payment SET membership_id=$newMembershipId WHERE membership_id=$otherMembershipId";
+        }
+
+        $sql = "SELECT * FROM civicrm_membership membership WHERE id = %1";
+
+        $newMembership = CRM_Member_DAO_Membership::findById($newMembershipId);
+        $otherMembership = CRM_Member_DAO_Membership::findById($otherMembershipId);
+
+        $updates = array();
+        if (new DateTime($otherMembership->join_date) < new DateTime($newMembership->join_date)) {
+          $updates["join_date"] = $otherMembership->join_date;
+        }
+
+        if (new DateTime($otherMembership->end_date) > new DateTime($newMembership->end_date)) {
+          $updates["end_date"] = $otherMembership->end_date;
+        }
+
+        if (count($updates)) {
+
+          /*
+           * Update status
+           */
+          $status = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate(
+            isset($updates["start_date"]) ? $updates["start_date"] : $newMembership->start_date,
+            isset($updates["end_date"]) ? $updates["end_date"] : $newMembership->end_date,
+            isset($updates["join_date"]) ? $updates["join_date"] : $newMembership->join_date,
+            'today',
+            FALSE,
+            $newMembershipId,
+            $newMembership
+          );
+
+          if (!empty($status['id']) and $status['id'] != $newMembership->status_id) {
+            $updates['status_id'] = $status['id'];
+          }
+
+          $updates_sql = [];
+          foreach ($updates as $k => $v) {
+            $updates_sql[] = "$k = '{$v}'";
+          }
+
+          $newSql[] = sprintf("UPDATE civicrm_membership SET %s WHERE id=%s", implode(", ", $updates_sql), $newMembershipId);
+          $newSql[] = sprintf("DELETE FROM civicrm_membership WHERE id=%s", $otherMembershipId);
+        }
+
+      }
+    }
+
+    $sqlQueries = array_merge($sqlQueries, $newSql);
+  }
+
 }
diff --git a/civicrm/CRM/Member/BAO/MembershipType.php b/civicrm/CRM/Member/BAO/MembershipType.php
index 0b141d8ac9..f6fb3d8c7d 100644
--- a/civicrm/CRM/Member/BAO/MembershipType.php
+++ b/civicrm/CRM/Member/BAO/MembershipType.php
@@ -536,6 +536,8 @@ class CRM_Member_BAO_MembershipType extends CRM_Member_DAO_MembershipType {
         $date = $membershipDetails->end_date;
       }
       $date = explode('-', $date);
+      // We have to add 1 day first in case it's the end of the month, then subtract afterwards
+      // eg. 2018-02-28 should renew to 2018-03-31, if we just added 1 month we'd get 2018-03-28
       $logStartDate = date('Y-m-d', mktime(0, 0, 0,
         (double) $date[1],
         (double) ($date[2] + 1),
diff --git a/civicrm/CRM/Member/Form/MembershipType.php b/civicrm/CRM/Member/Form/MembershipType.php
index 1a22b0cd8e..20f91d6788 100644
--- a/civicrm/CRM/Member/Form/MembershipType.php
+++ b/civicrm/CRM/Member/Form/MembershipType.php
@@ -109,6 +109,9 @@ class CRM_Member_Form_MembershipType extends CRM_Member_Form_MembershipConfig {
    * Build the form object.
    *
    * @return void
+   * @throws \CRM_Core_Exception
+   * @throws \CiviCRM_API3_Exception
+   * @throws \HTML_QuickForm_Error
    */
   public function buildQuickForm() {
     parent::buildQuickForm();
@@ -133,7 +136,7 @@ class CRM_Member_Form_MembershipType extends CRM_Member_Form_MembershipConfig {
 
     $this->addSelect('duration_unit', array(), TRUE);
 
-    //period type
+    // period type
     $this->addSelect('period_type', array(), TRUE);
 
     $this->add('text', 'duration_interval', ts('Duration Interval'),
@@ -148,7 +151,7 @@ class CRM_Member_Form_MembershipType extends CRM_Member_Form_MembershipConfig {
       CRM_Core_SelectValues::date(NULL, 'M d'), FALSE
     );
 
-    //Auto-renew Option
+    // Auto-renew Option
     $paymentProcessor = CRM_Core_PseudoConstant::paymentProcessor(FALSE, FALSE, 'is_recur = 1');
     $isAuthorize = FALSE;
     $options = array();
@@ -160,7 +163,7 @@ class CRM_Member_Form_MembershipType extends CRM_Member_Form_MembershipConfig {
     $this->addRadio('auto_renew', ts('Auto-renew Option'), $options);
     $this->assign('authorize', $isAuthorize);
 
-    //rollover day
+    // rollover day
     $this->add('date', 'fixed_period_rollover_day', ts('Fixed Period Rollover Day'),
       CRM_Core_SelectValues::date(NULL, 'M d'), FALSE
     );
@@ -292,7 +295,6 @@ class CRM_Member_Form_MembershipType extends CRM_Member_Form_MembershipConfig {
   /**
    * Process the form submission.
    *
-   *
    * @return void
    */
   public function postProcess() {
@@ -333,7 +335,6 @@ class CRM_Member_Form_MembershipType extends CRM_Member_Form_MembershipConfig {
         $params[$fld] = CRM_Utils_Array::value($fld, $submitted, 'NULL');
       }
 
-      //clean money.
       if ($params['minimum_fee']) {
         $params['minimum_fee'] = CRM_Utils_Rule::cleanMoney($params['minimum_fee']);
       }
diff --git a/civicrm/CRM/Price/BAO/LineItem.php b/civicrm/CRM/Price/BAO/LineItem.php
index e85866fd61..303e384d44 100644
--- a/civicrm/CRM/Price/BAO/LineItem.php
+++ b/civicrm/CRM/Price/BAO/LineItem.php
@@ -455,8 +455,11 @@ WHERE li.contribution_id = %1";
           // CRM-19094: entity_table is set to civicrm_membership then ensure
           // the entityId is set to membership ID not contribution by default
           elseif ($line['entity_table'] == 'civicrm_membership' && !empty($line['entity_id']) && $line['entity_id'] == $contributionDetails->id) {
-            $membershipId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipPayment', 'contribution_id', $line['entity_id'], 'membership_id');
-            $line['entity_id'] = $membershipId ? $membershipId : $line['entity_id'];
+            $membershipId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipPayment', $contributionDetails->id, 'membership_id', 'contribution_id');
+            if ($membershipId && (int) $membershipId !== (int) $line['entity_id']) {
+              $line['entity_id'] = $membershipId;
+              Civi::log()->warning('Per https://lab.civicrm.org/dev/core/issues/15 this data fix should not be required. Please log a ticket at https://lab.civicrm.org/dev/core with steps to get this.', array('civi.tag' => 'deprecated'));
+            }
           }
         }
 
@@ -766,7 +769,7 @@ WHERE li.contribution_id = %1";
           ));
           unset($updateFinancialItemInfoValues['financialTrxn']);
         }
-        elseif (!empty($updateFinancialItemInfoValues['link-financial-trxn'])) {
+        elseif (!empty($updateFinancialItemInfoValues['link-financial-trxn']) && $newFinancialItem->amount != 0) {
           civicrm_api3('EntityFinancialTrxn', 'create', array(
             'entity_id' => $newFinancialItem->id,
             'entity_table' => 'civicrm_financial_item',
diff --git a/civicrm/CRM/Profile/Page/MultipleRecordFieldsListing.php b/civicrm/CRM/Profile/Page/MultipleRecordFieldsListing.php
index 4db419686f..d50543595c 100644
--- a/civicrm/CRM/Profile/Page/MultipleRecordFieldsListing.php
+++ b/civicrm/CRM/Profile/Page/MultipleRecordFieldsListing.php
@@ -199,10 +199,10 @@ class CRM_Profile_Page_MultipleRecordFieldsListing extends CRM_Core_Page_Basic {
     elseif ($this->_pageViewType == 'customDataView') {
       // require custom group id for _pageViewType of customDataView
       $customGroupId = $this->_customGroupId;
+      $this->assign('customGroupId', $customGroupId);
       $reached = CRM_Core_BAO_CustomGroup::hasReachedMaxLimit($customGroupId, $this->_contactId);
       if (!$reached) {
         $this->assign('contactId', $this->_contactId);
-        $this->assign('customGroupId', $customGroupId);
         $this->assign('ctype', $this->_contactType);
       }
       $this->assign('reachedMax', $reached);
diff --git a/civicrm/CRM/Profile/Selector/Listings.php b/civicrm/CRM/Profile/Selector/Listings.php
index ea1a00df57..3be2a7801d 100644
--- a/civicrm/CRM/Profile/Selector/Listings.php
+++ b/civicrm/CRM/Profile/Selector/Listings.php
@@ -506,7 +506,7 @@ class CRM_Profile_Selector_Listings extends CRM_Core_Selector_Base implements CR
     if ($editLink && ($mask & CRM_Core_Permission::EDIT)) {
       // do not allow edit for anon users in joomla frontend, CRM-4668
       $config = CRM_Core_Config::singleton();
-      if (!$config->userFrameworkFrontend) {
+      if (!$config->userFrameworkFrontend || CRM_Core_Session::singleton()->getLoggedInContactID()) {
         $this->_editLink = TRUE;
       }
     }
diff --git a/civicrm/CRM/Report/Form.php b/civicrm/CRM/Report/Form.php
index c95b5dffd2..c8795f4407 100644
--- a/civicrm/CRM/Report/Form.php
+++ b/civicrm/CRM/Report/Form.php
@@ -3996,10 +3996,11 @@ LEFT JOIN civicrm_contact {$field['alias']} ON {$field['alias']}.id = {$this->_a
         }
         if (array_key_exists('filters', $table)) {
           foreach ($table['filters'] as $filterName => $filter) {
-            if (!empty($this->_params["{$filterName}_value"]) ||
-              CRM_Utils_Array::value("{$filterName}_op", $this->_params) ==
-              'nll' ||
-              CRM_Utils_Array::value("{$filterName}_op", $this->_params) ==
+            if (!empty($this->_params["{$filterName}_value"])
+              || !empty($this->_params["{$filterName}_relative"])
+              || CRM_Utils_Array::value("{$filterName}_op", $this->_params) ==
+              'nll'
+              || CRM_Utils_Array::value("{$filterName}_op", $this->_params) ==
               'nnll'
             ) {
               $this->_selectedTables[] = $tableName;
@@ -4304,8 +4305,12 @@ LEFT JOIN civicrm_contact {$field['alias']} ON {$field['alias']}.id = {$this->_a
 
   /**
    * Add Address into From Table if required.
+   *
+   * @deprecated use joinAddressFromContact
+   * (left here in case extensions use it).
    */
   public function addAddressFromClause() {
+    Civi::log()->warning('Deprecated function addAddressFromClause. Use joinAddressFromContact.', array('civi.tag' => 'deprecated'));
     // include address field if address column is to be included
     if ((isset($this->_addressField) &&
         $this->_addressField
@@ -4322,8 +4327,13 @@ LEFT JOIN civicrm_contact {$field['alias']} ON {$field['alias']}.id = {$this->_a
 
   /**
    * Add Phone into From Table if required.
+   *
+   * @deprecated use joinPhoneFromContact
+   *  (left here in case extensions use it).
    */
   public function addPhoneFromClause() {
+
+    Civi::log()->warning('Deprecated function addPhoneFromClause. Use joinPhoneFromContact.', array('civi.tag' => 'deprecated'));
     // include address field if address column is to be included
     if ($this->isTableSelected('civicrm_phone')) {
       $this->_from .= "
@@ -4334,6 +4344,96 @@ LEFT JOIN civicrm_contact {$field['alias']} ON {$field['alias']}.id = {$this->_a
     }
   }
 
+  /**
+   * Add Address into From Table if required.
+   *
+   * Prefix will be added to both tables as
+   * it is assumed you are using it to get address of a secondary contact.
+   *
+   * @param string $prefix
+   * @param array $extra Additional options.
+   *      Not currently used in core but may be used in override extensions.
+   */
+  protected function joinAddressFromContact($prefix = '', $extra = array()) {
+    $addressTables = ['civicrm_address', 'civicrm_country', 'civicrm_worldregion', 'civicrm_state_province'];
+    $isJoinRequired = $this->_addressField;
+    foreach ($addressTables as $addressTable) {
+      if ($this->isTableSelected($prefix . $addressTable)) {
+        $isJoinRequired = TRUE;
+      }
+    }
+    if ($isJoinRequired) {
+      $this->_from .= "
+                 LEFT JOIN civicrm_address {$this->_aliases[$prefix . 'civicrm_address']}
+                           ON ({$this->_aliases[$prefix . 'civicrm_contact']}.id =
+                               {$this->_aliases[$prefix . 'civicrm_address']}.contact_id) AND
+                               {$this->_aliases[$prefix . 'civicrm_address']}.is_primary = 1\n";
+    }
+  }
+
+  /**
+   * Add Country into From Table if required.
+   *
+   * Prefix will be added to both tables as
+   * it is assumed you are using it to get address of a secondary contact.
+   *
+   * @param string $prefix
+   * @param array $extra Additional options.
+   *      Not currently used in core but may be used in override extensions.
+   */
+  protected function joinCountryFromAddress($prefix = '', $extra = array()) {
+    // include country field if country column is to be included
+    if ($this->isTableSelected($prefix . 'civicrm_country') || $this->isTableSelected($prefix . 'civicrm_worldregion')) {
+      if (empty($this->_aliases[$prefix . 'civicrm_country'])) {
+        $this->_aliases[$prefix . 'civicrm_country'] = $prefix . '_report_country';
+      }
+      $this->_from .= "
+            LEFT JOIN civicrm_country {$this->_aliases[$prefix . 'civicrm_country']}
+                   ON {$this->_aliases[$prefix . 'civicrm_address']}.country_id = {$this->_aliases[$prefix . 'civicrm_country']}.id AND
+                      {$this->_aliases[$prefix . 'civicrm_address']}.is_primary = 1 ";
+    }
+  }
+
+  /**
+   * Add Phone into From Table if required.
+   *
+   * Prefix will be added to both tables as
+   * it is assumed you are using it to get address of a secondary contact.
+   *
+   * @param string $prefix
+   * @param array $extra Additional options.
+   *      Not currently used in core but may be used in override extensions.
+   */
+  protected function joinPhoneFromContact($prefix = '', $extra = array()) {
+    // include phone field if phone column is to be included
+    if ($this->isTableSelected($prefix . 'civicrm_phone')) {
+      $this->_from .= "
+      LEFT JOIN civicrm_phone {$this->_aliases[$prefix . 'civicrm_phone']}
+             ON {$this->_aliases[$prefix . 'civicrm_contact']}.id = {$this->_aliases[$prefix . 'civicrm_phone']}.contact_id AND
+                {$this->_aliases[$prefix . 'civicrm_phone']}.is_primary = 1\n";
+    }
+  }
+
+  /**
+   * Add Email into From Table if required.
+   *
+   * Prefix will be added to both tables as
+   * it is assumed you are using it to get address of a secondary contact.
+   *
+   * @param string $prefix
+   * @param array $extra Additional options.
+   *      Not currently used in core but may be used in override extensions.
+   */
+  protected function joinEmailFromContact($prefix = '', $extra = array()) {
+    // include email field if email column is to be included
+    if ($this->isTableSelected($prefix . 'civicrm_email')) {
+      $this->_from .= "
+            LEFT JOIN  civicrm_email {$this->_aliases[$prefix . 'civicrm_email']}
+                   ON ({$this->_aliases[$prefix . 'civicrm_contact']}.id = {$this->_aliases[$prefix . 'civicrm_email']}.contact_id AND
+                       {$this->_aliases[$prefix . 'civicrm_email']}.is_primary = 1) ";
+    }
+  }
+
   /**
    * Add Financial Transaction into From Table if required.
    */
diff --git a/civicrm/CRM/Report/Form/Activity.php b/civicrm/CRM/Report/Form/Activity.php
index dd52e784aa..8532ae9717 100644
--- a/civicrm/CRM/Report/Form/Activity.php
+++ b/civicrm/CRM/Report/Form/Activity.php
@@ -582,7 +582,7 @@ class CRM_Report_Form_Activity extends CRM_Report_Form {
       $this->_aliases['civicrm_contact'] = 'civicrm_contact_source';
     }
 
-    $this->addAddressFromClause();
+    $this->joinAddressFromContact();
   }
 
   /**
diff --git a/civicrm/CRM/Report/Form/ActivitySummary.php b/civicrm/CRM/Report/Form/ActivitySummary.php
index 9ce524b30f..29960096af 100644
--- a/civicrm/CRM/Report/Form/ActivitySummary.php
+++ b/civicrm/CRM/Report/Form/ActivitySummary.php
@@ -337,12 +337,7 @@ class CRM_Report_Form_ActivitySummary extends CRM_Report_Form {
                LEFT JOIN civicrm_case_contact
                       ON civicrm_case_contact.case_id = civicrm_case.id ";
 
-      if ($this->_phoneField) {
-        $this->_from .= "
-              LEFT JOIN civicrm_phone  {$this->_aliases['civicrm_phone']}
-                     ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id AND
-                       {$this->_aliases['civicrm_phone']}.is_primary = 1 ";
-      }
+      $this->joinPhoneFromContact();
     }
     else {
       $this->_from = "
@@ -355,12 +350,7 @@ class CRM_Report_Form_ActivitySummary extends CRM_Report_Form {
               {$this->_aclFrom}";
     }
 
-    if ($this->_emailField) {
-      $this->_from .= "
-            LEFT JOIN civicrm_email  {$this->_aliases['civicrm_email']}
-                   ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id AND
-                     {$this->_aliases['civicrm_email']}.is_primary = 1 ";
-    }
+    $this->joinEmailFromContact();
   }
 
   /**
diff --git a/civicrm/CRM/Report/Form/Campaign/SurveyDetails.php b/civicrm/CRM/Report/Form/Campaign/SurveyDetails.php
index 42a70c3906..1f43b85dd3 100644
--- a/civicrm/CRM/Report/Form/Campaign/SurveyDetails.php
+++ b/civicrm/CRM/Report/Form/Campaign/SurveyDetails.php
@@ -291,19 +291,9 @@ class CRM_Report_Form_Campaign_SurveyDetails extends CRM_Report_Form {
     $this->_from .= " INNER JOIN civicrm_activity_contact activity_contact_civireport ON
                       ( {$this->_aliases['civicrm_activity']}.id = activity_contact_civireport.activity_id  AND activity_contact_civireport.record_type_id = {$assigneeID} )\n";
 
-    //get the address table.
-    $this->_from .= " LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']} ON
-                      {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_address']}.contact_id AND {$this->_aliases['civicrm_address']}.is_primary = 1\n";
-
-    if ($this->_emailField) {
-      $this->_from .= "LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']} ON
-                       {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id AND {$this->_aliases['civicrm_email']}.is_primary = 1\n";
-    }
-
-    if ($this->_phoneField) {
-      $this->_from .= "LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']} ON
-                       {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id AND {$this->_aliases['civicrm_phone']}.is_primary = 1\n";
-    }
+    $this->joinAddressFromContact();
+    $this->joinPhoneFromContact();
+    $this->joinEmailFromContact();
 
     if ($this->_locationBasedPhoneField) {
       foreach ($this->_surveyResponseFields as $key => $value) {
diff --git a/civicrm/CRM/Report/Form/Case/Demographics.php b/civicrm/CRM/Report/Form/Case/Demographics.php
index e4c838f0c7..b015af1e13 100644
--- a/civicrm/CRM/Report/Form/Case/Demographics.php
+++ b/civicrm/CRM/Report/Form/Case/Demographics.php
@@ -313,19 +313,9 @@ where (cg.extends='Contact' OR cg.extends='Individual' OR cg.extends_entity_colu
       }
     }
 
-    if ($this->_emailField) {
-      $this->_from .= "
-            LEFT JOIN  civicrm_email {$this->_aliases['civicrm_email']}
-                   ON ({$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id AND
-                      {$this->_aliases['civicrm_email']}.is_primary = 1) ";
-    }
+    $this->joinPhoneFromContact();
+    $this->joinEmailFromContact();
 
-    if ($this->_phoneField) {
-      $this->_from .= "
-            LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
-                   ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id AND
-                      {$this->_aliases['civicrm_phone']}.is_primary = 1 ";
-    }
   }
 
   public function where() {
diff --git a/civicrm/CRM/Report/Form/Case/Detail.php b/civicrm/CRM/Report/Form/Case/Detail.php
index 50d3f72c07..8b84613163 100644
--- a/civicrm/CRM/Report/Form/Case/Detail.php
+++ b/civicrm/CRM/Report/Form/Case/Detail.php
@@ -36,13 +36,7 @@ class CRM_Report_Form_Case_Detail extends CRM_Report_Form {
 
   protected $_relField = FALSE;
 
-  protected $_addressField = FALSE;
-
-  protected $_emailField = FALSE;
-
-  protected $_phoneField = FALSE;
-
-  protected $_worldRegionField = FALSE;
+  protected $_addressField = TRUE;
 
   protected $_activityLast = FALSE;
 
@@ -344,19 +338,10 @@ class CRM_Report_Form_Case_Detail extends CRM_Report_Form {
     foreach ($this->_columns as $tableName => $table) {
       if (array_key_exists('fields', $table)) {
         foreach ($table['fields'] as $fieldName => $field) {
-          if ($tableName == 'civicrm_address') {
-            $this->_addressField = TRUE;
-          }
           if (!empty($field['required']) ||
             !empty($this->_params['fields'][$fieldName])
           ) {
-            if ($tableName == 'civicrm_email') {
-              $this->_emailField = TRUE;
-            }
-            elseif ($tableName == 'civicrm_phone') {
-              $this->_phoneField = TRUE;
-            }
-            elseif ($tableName == 'civicrm_relationship') {
+            if ($tableName == 'civicrm_relationship') {
               $this->_relField = TRUE;
             }
             if ($fieldName == 'sort_name') {
@@ -414,25 +399,11 @@ class CRM_Report_Form_Case_Detail extends CRM_Report_Form {
 ";
     }
 
-    if ($this->_addressField) {
-      $this->_from .= "
-             LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
-                    ON {$conact}.id = {$this->_aliases['civicrm_address']}.contact_id AND
-                       {$this->_aliases['civicrm_address']}.is_primary = 1 ";
-    }
-    if ($this->_emailField) {
-      $this->_from .= "
-             LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']}
-                   ON {$conact}.id = {$this->_aliases['civicrm_email']}.contact_id AND
-                       {$this->_aliases['civicrm_email']}.is_primary = 1 ";
-    }
-    if ($this->_phoneField) {
-      $this->_from .= "
-             LEFT JOIN  civicrm_phone {$this->_aliases['civicrm_phone']}
-                       ON ( {$conact}.id = {$this->_aliases['civicrm_phone']}.contact_id AND
-                          {$this->_aliases['civicrm_phone']}.is_primary = 1) ";
-    }
-    if ($this->_worldRegionField) {
+    $this->joinAddressFromContact();
+    $this->joinPhoneFromContact();
+    $this->joinEmailFromContact();
+
+    if ($this->isTableSelected('civicrm_worldregion')) {
       $this->_from .= "
              LEFT JOIN civicrm_country {$this->_aliases['civicrm_country']}
                    ON {$this->_aliases['civicrm_country']}.id ={$this->_aliases['civicrm_address']}.country_id
@@ -601,13 +572,6 @@ class CRM_Report_Form_Case_Detail extends CRM_Report_Form {
   }
 
   public function checkEnabledFields() {
-    if (isset($this->_params['worldregion_id_value']) &&
-      !empty($this->_params['worldregion_id_value'])
-    ) {
-      $this->_addressField = TRUE;
-      $this->_worldRegionField = TRUE;
-    }
-
     if (isset($this->_params['case_role_value'])
       && !empty($this->_params['case_role_value'])
     ) {
diff --git a/civicrm/CRM/Report/Form/Contact/CurrentEmployer.php b/civicrm/CRM/Report/Form/Contact/CurrentEmployer.php
index 050745a50e..ab75475c3d 100644
--- a/civicrm/CRM/Report/Form/Contact/CurrentEmployer.php
+++ b/civicrm/CRM/Report/Form/Contact/CurrentEmployer.php
@@ -252,17 +252,11 @@ FROM civicrm_contact {$this->_aliases['civicrm_contact']}
      LEFT JOIN civicrm_relationship {$this->_aliases['civicrm_relationship']}
           ON ( {$this->_aliases['civicrm_relationship']}.contact_id_a={$this->_aliases['civicrm_contact']}.id
               AND {$this->_aliases['civicrm_relationship']}.contact_id_b={$this->_aliases['civicrm_contact']}.employer_id
-              AND {$this->_aliases['civicrm_relationship']}.relationship_type_id={$relType})
-     LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
-          ON ({$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_address']}.contact_id
-             AND {$this->_aliases['civicrm_address']}.is_primary = 1 )
-
-     LEFT JOIN  civicrm_phone {$this->_aliases['civicrm_phone']}
-          ON ({$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id
-             AND {$this->_aliases['civicrm_phone']}.is_primary = 1)
-     LEFT JOIN  civicrm_email {$this->_aliases['civicrm_email']}
-          ON ({$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id
-             AND {$this->_aliases['civicrm_email']}.is_primary = 1) ";
+              AND {$this->_aliases['civicrm_relationship']}.relationship_type_id={$relType})  ";
+
+    $this->joinAddressFromContact();
+    $this->joinPhoneFromContact();
+    $this->joinEmailFromContact();
   }
 
   public function where() {
diff --git a/civicrm/CRM/Report/Form/Contact/Detail.php b/civicrm/CRM/Report/Form/Contact/Detail.php
index 8ddef41d96..c16977d5c7 100644
--- a/civicrm/CRM/Report/Form/Contact/Detail.php
+++ b/civicrm/CRM/Report/Form/Contact/Detail.php
@@ -457,35 +457,10 @@ class CRM_Report_Form_Contact_Detail extends CRM_Report_Form {
     $this->_from = "
         FROM civicrm_contact {$this->_aliases['civicrm_contact']} {$this->_aclFrom}";
 
-    if ($this->isTableSelected('civicrm_country') ||
-      $this->isTableSelected('civicrm_address')
-    ) {
-      $this->_from .= "
-            LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
-                   ON ({$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_address']}.contact_id AND
-                      {$this->_aliases['civicrm_address']}.is_primary = 1 ) ";
-    }
-
-    if ($this->isTableSelected('civicrm_email')) {
-      $this->_from .= "
-            LEFT JOIN  civicrm_email {$this->_aliases['civicrm_email']}
-                   ON ({$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id AND
-                      {$this->_aliases['civicrm_email']}.is_primary = 1) ";
-    }
-
-    if ($this->isTableSelected('civicrm_phone')) {
-      $this->_from .= "
-            LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
-                   ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id AND
-                      {$this->_aliases['civicrm_phone']}.is_primary = 1 ";
-    }
-
-    if ($this->isTableSelected('civicrm_country')) {
-      $this->_from .= "
-            LEFT JOIN civicrm_country {$this->_aliases['civicrm_country']}
-                   ON {$this->_aliases['civicrm_address']}.country_id = {$this->_aliases['civicrm_country']}.id AND
-                      {$this->_aliases['civicrm_address']}.is_primary = 1 ";
-    }
+    $this->joinAddressFromContact();
+    $this->joinCountryFromAddress();
+    $this->joinPhoneFromContact();
+    $this->joinEmailFromContact();
 
     $this->_from .= "{$group}";
 
diff --git a/civicrm/CRM/Report/Form/Contact/Summary.php b/civicrm/CRM/Report/Form/Contact/Summary.php
index a37ce608d5..706d992981 100644
--- a/civicrm/CRM/Report/Form/Contact/Summary.php
+++ b/civicrm/CRM/Report/Form/Contact/Summary.php
@@ -151,15 +151,6 @@ class CRM_Report_Form_Contact_Summary extends CRM_Report_Form {
           if (!empty($field['required']) ||
             !empty($this->_params['fields'][$fieldName])
           ) {
-            if ($tableName == 'civicrm_email') {
-              $this->_emailField = TRUE;
-            }
-            elseif ($tableName == 'civicrm_phone') {
-              $this->_phoneField = TRUE;
-            }
-            elseif ($tableName == 'civicrm_country') {
-              $this->_countryField = TRUE;
-            }
 
             $alias = "{$tableName}_{$fieldName}";
             $select[] = "{$field['dbAlias']} as {$alias}";
@@ -192,27 +183,9 @@ class CRM_Report_Form_Contact_Summary extends CRM_Report_Form {
             LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
                    ON ({$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_address']}.contact_id AND
                       {$this->_aliases['civicrm_address']}.is_primary = 1 ) ";
-
-    if ($this->isTableSelected('civicrm_email')) {
-      $this->_from .= "
-            LEFT JOIN  civicrm_email {$this->_aliases['civicrm_email']}
-                   ON ({$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id AND
-                      {$this->_aliases['civicrm_email']}.is_primary = 1) ";
-    }
-
-    if ($this->_phoneField) {
-      $this->_from .= "
-            LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
-                   ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id AND
-                      {$this->_aliases['civicrm_phone']}.is_primary = 1 ";
-    }
-
-    if ($this->isTableSelected('civicrm_country')) {
-      $this->_from .= "
-            LEFT JOIN civicrm_country {$this->_aliases['civicrm_country']}
-                   ON {$this->_aliases['civicrm_address']}.country_id = {$this->_aliases['civicrm_country']}.id AND
-                      {$this->_aliases['civicrm_address']}.is_primary = 1 ";
-    }
+    $this->joinPhoneFromContact();
+    $this->joinEmailFromContact();
+    $this->joinCountryFromAddress();
   }
 
   public function postProcess() {
diff --git a/civicrm/CRM/Report/Form/Contribute/Bookkeeping.php b/civicrm/CRM/Report/Form/Contribute/Bookkeeping.php
index 05da2d5908..0280a6ee0c 100644
--- a/civicrm/CRM/Report/Form/Contribute/Bookkeeping.php
+++ b/civicrm/CRM/Report/Form/Contribute/Bookkeeping.php
@@ -31,9 +31,6 @@
  * @copyright CiviCRM LLC (c) 2004-2018
  */
 class CRM_Report_Form_Contribute_Bookkeeping extends CRM_Report_Form {
-  protected $_addressField = FALSE;
-
-  protected $_emailField = FALSE;
 
   protected $_summary = NULL;
 
diff --git a/civicrm/CRM/Report/Form/Contribute/Detail.php b/civicrm/CRM/Report/Form/Contribute/Detail.php
index 6359238334..b64e45f58a 100644
--- a/civicrm/CRM/Report/Form/Contribute/Detail.php
+++ b/civicrm/CRM/Report/Form/Contribute/Detail.php
@@ -31,9 +31,6 @@
  * @copyright CiviCRM LLC (c) 2004-2018
  */
 class CRM_Report_Form_Contribute_Detail extends CRM_Report_Form {
-  protected $_addressField = FALSE;
-
-  protected $_emailField = FALSE;
 
   protected $_summary = NULL;
 
@@ -75,7 +72,7 @@ class CRM_Report_Form_Contribute_Detail extends CRM_Report_Form {
       'fields_defaults' => array('sort_name'),
       'fields_excluded' => array('id'),
       'fields_required' => array('id'),
-      'filters_defaults' => array('is_deleted' => FALSE),
+      'filters_defaults' => array('is_deleted' => 0),
       'no_field_disambiguation' => TRUE,
     )), array(
       'civicrm_email' => array(
@@ -411,6 +408,7 @@ class CRM_Report_Form_Contribute_Detail extends CRM_Report_Form {
     $group = "\nGROUP BY {$this->_aliases['civicrm_contribution']}.currency";
     $sql = "{$select} {$this->_from} {$this->_where} {$group}";
     $dao = CRM_Core_DAO::executeQuery($sql);
+    $this->addToDeveloperTab($sql);
 
     while ($dao->fetch()) {
       $totalAmount[] = CRM_Utils_Money::format($dao->amount, $dao->currency) . " (" . $dao->count . ")";
@@ -461,6 +459,7 @@ SELECT COUNT(contribution_soft_civireport.amount ) as count,
 {$this->_softFrom}
 GROUP BY {$this->_aliases['civicrm_contribution']}.currency";
       $dao = CRM_Core_DAO::executeQuery($sql);
+      $this->addToDeveloperTab($sql);
       while ($dao->fetch()) {
         $totalAmount[] = CRM_Utils_Money::format($dao->amount, $dao->currency) . " (" .
           $dao->count . ")";
@@ -524,6 +523,7 @@ GROUP BY {$this->_aliases['civicrm_contribution']}.currency";
     // 1. use main contribution query to build temp table 1
     $sql = $this->buildQuery();
     $tempQuery = "CREATE TEMPORARY TABLE civireport_contribution_detail_temp1 {$this->_databaseAttributes} AS {$sql}";
+    $this->addToDeveloperTab($tempQuery);
     CRM_Core_DAO::executeQuery($tempQuery);
     $this->setPager();
 
@@ -542,6 +542,7 @@ GROUP BY {$this->_aliases['civicrm_contribution']}.currency";
     // we inner join with temp1 to restrict soft contributions to those in temp1 table
     $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy}";
     $tempQuery = "CREATE TEMPORARY TABLE civireport_contribution_detail_temp2 {$this->_databaseAttributes} AS {$sql}";
+    $this->addToDeveloperTab($tempQuery);
     CRM_Core_DAO::executeQuery($tempQuery);
     if (CRM_Utils_Array::value('contribution_or_soft_value', $this->_params) ==
       'soft_credits_only'
@@ -580,6 +581,7 @@ UNION ALL
 
     // 4. build temp table 3
     $sql = "CREATE TEMPORARY TABLE civireport_contribution_detail_temp3 {$this->_databaseAttributes} AS {$tempQuery}";
+    $this->addToDeveloperTab($sql);
     CRM_Core_DAO::executeQuery($sql);
 
     // 5. Re-construct order-by to make sense for final query on temp3 table
@@ -751,6 +753,7 @@ UNION ALL
 SELECT civicrm_contact_id, civicrm_contact_sort_name, civicrm_contribution_total_amount, civicrm_contribution_currency
 FROM   civireport_contribution_detail_temp2
 WHERE  civicrm_contribution_contribution_id={$row['civicrm_contribution_contribution_id']}";
+        $this->addToDeveloperTab($query);
         $dao = CRM_Core_DAO::executeQuery($query);
         $string = '';
         $separator = ($this->_outputMode !== 'csv') ? "<br/>" : ' ';
@@ -773,6 +776,7 @@ WHERE  civicrm_contribution_contribution_id={$row['civicrm_contribution_contribu
 SELECT civicrm_contact_id, civicrm_contact_sort_name
 FROM   civireport_contribution_detail_temp1
 WHERE  civicrm_contribution_contribution_id={$row['civicrm_contribution_contribution_id']}";
+        $this->addToDeveloperTab($query);
         $dao = CRM_Core_DAO::executeQuery($query);
         $string = '';
         while ($dao->fetch()) {
@@ -852,6 +856,7 @@ WHERE  civicrm_contribution_contribution_id={$row['civicrm_contribution_contribu
       // initialize array of total counts
       $sumcontribs = $totals = array();
       $dao = CRM_Core_DAO::executeQuery($query);
+      $this->addToDeveloperTab($query);
       while ($dao->fetch()) {
 
         // let $this->_alterDisplay translate any integer ids to human-readable values.
@@ -939,16 +944,10 @@ WHERE  civicrm_contribution_contribution_id={$row['civicrm_contribution_contribu
               INNER JOIN (SELECT c.id, IF(COUNT(oc.id) = 0, 0, 1) AS ordinality FROM civicrm_contribution c LEFT JOIN civicrm_contribution oc ON c.contact_id = oc.contact_id AND oc.receive_date < c.receive_date GROUP BY c.id) {$this->_aliases['civicrm_contribution_ordinality']}
                       ON {$this->_aliases['civicrm_contribution_ordinality']}.id = {$this->_aliases['civicrm_contribution']}.id";
     }
-    $this->addPhoneFromClause();
-
-    $this->addAddressFromClause();
+    $this->joinPhoneFromContact();
+    $this->joinAddressFromContact();
+    $this->joinEmailFromContact();
 
-    if ($this->_emailField) {
-      $this->_from .= "
-            LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']}
-                   ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id AND
-                      {$this->_aliases['civicrm_email']}.is_primary = 1\n";
-    }
     // include contribution note
     if (!empty($this->_params['fields']['contribution_note']) ||
       !empty($this->_params['note_value'])
diff --git a/civicrm/CRM/Report/Form/Contribute/History.php b/civicrm/CRM/Report/Form/Contribute/History.php
index f9fbf895d3..9764c84bd0 100644
--- a/civicrm/CRM/Report/Form/Contribute/History.php
+++ b/civicrm/CRM/Report/Form/Contribute/History.php
@@ -29,15 +29,10 @@
  *
  * @package CRM
  * @copyright CiviCRM LLC (c) 2004-2018
- * $Id$
- *
  */
 class CRM_Report_Form_Contribute_History extends CRM_Report_Form {
   // Primary Contacts count limitCONSTROW_COUNT_LIMIT = 10;
 
-  protected $_addressField = FALSE;
-  protected $_emailField = FALSE;
-  protected $_phoneField = FALSE;
   protected $_relationshipColumns = array();
 
   protected $_customGroupExtends = array(
@@ -327,6 +322,7 @@ class CRM_Report_Form_Contribute_History extends CRM_Report_Form {
 
   public function select() {
     $select = array();
+    // @todo remove this & use parent (with maybe some override in this or better yet selectWhere fn)
     $this->_columnHeaders = array();
 
     foreach ($this->_columns as $tableName => $table) {
@@ -336,15 +332,6 @@ class CRM_Report_Form_Contribute_History extends CRM_Report_Form {
           if (!empty($field['required']) ||
             !empty($this->_params['fields'][$fieldName])
           ) {
-            if ($tableName == 'civicrm_address') {
-              $this->_addressField = TRUE;
-            }
-            if ($tableName == 'civicrm_email') {
-              $this->_emailField = TRUE;
-            }
-            if ($tableName == 'civicrm_phone') {
-              $this->_phoneField = TRUE;
-            }
             if ($tableName == 'civicrm_relationship') {
               $this->_relationshipColumns["{$tableName}_{$fieldName}"] = "{$field['dbAlias']} as {$tableName}_{$fieldName}";
               $this->_columnHeaders["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array::value('type', $field);
@@ -398,23 +385,13 @@ class CRM_Report_Form_Contribute_History extends CRM_Report_Form {
                      ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_contribution']}.contact_id AND
                         {$this->_aliases['civicrm_contribution']}.is_test = 0 ";
 
-    if ($this->_emailField) {
-      $this->_from .= " LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']}
-                     ON ({$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id AND
-                        {$this->_aliases['civicrm_email']}.is_primary = 1) ";
-    }
-
-    if ($this->_phoneField) {
-      $this->_from .= " LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
-                     ON ({$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id AND
-                        {$this->_aliases['civicrm_phone']}.is_primary = 1) ";
-    }
-
     $relContacAlias = 'contact_relationship';
     $this->_relationshipFrom = " INNER JOIN civicrm_relationship {$this->_aliases['civicrm_relationship']}
                      ON (({$this->_aliases['civicrm_relationship']}.contact_id_a = {$relContacAlias}.id OR {$this->_aliases['civicrm_relationship']}.contact_id_b = {$relContacAlias}.id ) AND {$this->_aliases['civicrm_relationship']}.is_active = 1) ";
 
-    $this->addAddressFromClause();
+    $this->joinAddressFromContact();
+    $this->joinPhoneFromContact();
+    $this->joinEmailFromContact();
 
     // for credit card type
     $this->addFinancialTrxnFromClause();
diff --git a/civicrm/CRM/Report/Form/Contribute/HouseholdSummary.php b/civicrm/CRM/Report/Form/Contribute/HouseholdSummary.php
index b6f8afac55..cb0225bf5d 100644
--- a/civicrm/CRM/Report/Form/Contribute/HouseholdSummary.php
+++ b/civicrm/CRM/Report/Form/Contribute/HouseholdSummary.php
@@ -29,15 +29,9 @@
  *
  * @package CRM
  * @copyright CiviCRM LLC (c) 2004-2018
- * $Id$
- *
  */
 class CRM_Report_Form_Contribute_HouseholdSummary extends CRM_Report_Form {
 
-  protected $_addressField = FALSE;
-
-  protected $_emailField = FALSE;
-
   public $_drilldownReport = array('contribute/detail' => 'Link to Detail Report');
 
   protected $_summary = NULL;
@@ -232,11 +226,8 @@ class CRM_Report_Form_Contribute_HouseholdSummary extends CRM_Report_Form {
     parent::__construct();
   }
 
-  public function preProcess() {
-    parent::preProcess();
-  }
-
   public function select() {
+    // @todo remove this & use parent select.
     $this->_columnHeaders = $select = array();
     foreach ($this->_columns as $tableName => $table) {
       if (array_key_exists('fields', $table)) {
@@ -244,12 +235,6 @@ class CRM_Report_Form_Contribute_HouseholdSummary extends CRM_Report_Form {
           if (!empty($field['required']) ||
             !empty($this->_params['fields'][$fieldName])
           ) {
-            if ($tableName == 'civicrm_address') {
-              $this->_addressField = TRUE;
-            }
-            elseif ($tableName == 'civicrm_email') {
-              $this->_emailField = TRUE;
-            }
 
             if (!empty($field['statistics'])) {
               foreach ($field['statistics'] as $stat => $label) {
@@ -274,8 +259,6 @@ class CRM_Report_Form_Contribute_HouseholdSummary extends CRM_Report_Form {
   }
 
   public function from() {
-
-    $this->_from = NULL;
     $this->_from = "
         FROM  civicrm_relationship {$this->_aliases['civicrm_relationship']}
             LEFT  JOIN civicrm_contact {$this->_aliases['civicrm_contact_household']} ON
@@ -286,18 +269,8 @@ class CRM_Report_Form_Contribute_HouseholdSummary extends CRM_Report_Form {
             INNER JOIN civicrm_contribution {$this->_aliases['civicrm_contribution']} ON
                       ({$this->_aliases['civicrm_contribution']}.contact_id = {$this->_aliases['civicrm_relationship']}.$this->otherContact ) AND {$this->_aliases['civicrm_contribution']}.is_test = 0 ";
 
-    if ($this->_addressField) {
-      $this->_from .= "
-            LEFT JOIN civicrm_address  {$this->_aliases['civicrm_address']} ON
-                      {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_address']}.contact_id AND
-                      {$this->_aliases['civicrm_address']}.is_primary = 1\n ";
-    }
-    if ($this->_emailField) {
-      $this->_from .= "
-            LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']} ON
-                      {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id AND
-                      {$this->_aliases['civicrm_email']}.is_primary = 1\n ";
-    }
+    $this->joinAddressFromContact();
+    $this->joinEmailFromContact();
 
     // for credit card type
     $this->addFinancialTrxnFromClause();
diff --git a/civicrm/CRM/Report/Form/Contribute/Lybunt.php b/civicrm/CRM/Report/Form/Contribute/Lybunt.php
index d0ac75a6ae..9b040c3b50 100644
--- a/civicrm/CRM/Report/Form/Contribute/Lybunt.php
+++ b/civicrm/CRM/Report/Form/Contribute/Lybunt.php
@@ -345,19 +345,10 @@ class CRM_Report_Form_Contribute_Lybunt extends CRM_Report_Form {
           AND {$this->_aliases['civicrm_contribution']}.is_test = 0
         INNER JOIN civicrm_contact {$this->_aliases['civicrm_contact']}
           ON restricted_contacts.cid = {$this->_aliases['civicrm_contact']}.id";
-      if ($this->isTableSelected('civicrm_email')) {
-        $this->_from .= "
-          LEFT  JOIN civicrm_email  {$this->_aliases['civicrm_email']}
-            ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id
-            AND {$this->_aliases['civicrm_email']}.is_primary = 1";
-      }
-      if ($this->isTableSelected('civicrm_phone')) {
-        $this->_from .= "
-          LEFT  JOIN civicrm_phone  {$this->_aliases['civicrm_phone']}
-            ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id
-            AND {$this->_aliases['civicrm_phone']}.is_primary = 1";
-      }
-      $this->addAddressFromClause();
+
+      $this->joinAddressFromContact();
+      $this->joinPhoneFromContact();
+      $this->joinEmailFromContact();
     }
     else {
       $this->setFromBase('civicrm_contact');
diff --git a/civicrm/CRM/Report/Form/Contribute/OrganizationSummary.php b/civicrm/CRM/Report/Form/Contribute/OrganizationSummary.php
index a44d5e63df..e3565a80cb 100644
--- a/civicrm/CRM/Report/Form/Contribute/OrganizationSummary.php
+++ b/civicrm/CRM/Report/Form/Contribute/OrganizationSummary.php
@@ -32,10 +32,6 @@
  */
 class CRM_Report_Form_Contribute_OrganizationSummary extends CRM_Report_Form {
 
-  protected $_addressField = FALSE;
-
-  protected $_emailField = FALSE;
-
   public $_drilldownReport = array('contribute/detail' => 'Link to Detail Report');
 
   protected $_summary = NULL;
@@ -238,17 +234,12 @@ class CRM_Report_Form_Contribute_OrganizationSummary extends CRM_Report_Form {
   }
 
   public function select() {
+    // @todo remove this in favour of using parent function
     $this->_columnHeaders = $select = array();
     foreach ($this->_columns as $tableName => $table) {
       if (array_key_exists('fields', $table)) {
         foreach ($table['fields'] as $fieldName => $field) {
           if (!empty($field['required']) || !empty($this->_params['fields'][$fieldName])) {
-            if ($tableName == 'civicrm_address') {
-              $this->_addressField = TRUE;
-            }
-            elseif ($tableName == 'civicrm_email') {
-              $this->_emailField = TRUE;
-            }
 
             if (!empty($field['statistics'])) {
               foreach ($field['statistics'] as $stat => $label) {
@@ -285,18 +276,8 @@ class CRM_Report_Form_Contribute_OrganizationSummary extends CRM_Report_Form {
             INNER JOIN civicrm_contribution {$this->_aliases['civicrm_contribution']} ON
                       ({$this->_aliases['civicrm_contribution']}.contact_id = {$this->_aliases['civicrm_relationship']}.$this->otherContact ) AND {$this->_aliases['civicrm_contribution']}.is_test = 0  ";
 
-    if ($this->_addressField) {
-      $this->_from .= "
-            LEFT JOIN civicrm_address  {$this->_aliases['civicrm_address']} ON
-                      {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_address']}.contact_id AND
-                      {$this->_aliases['civicrm_address']}.is_primary = 1\n ";
-    }
-    if ($this->_emailField) {
-      $this->_from .= "
-            LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']} ON
-                      {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id AND
-                      {$this->_aliases['civicrm_email']}.is_primary = 1\n ";
-    }
+    $this->joinAddressFromContact();
+    $this->joinEmailFromContact();
 
     // for credit card type
     $this->addFinancialTrxnFromClause();
diff --git a/civicrm/CRM/Report/Form/Contribute/Recur.php b/civicrm/CRM/Report/Form/Contribute/Recur.php
index d2cf531ef6..fd44c88bb8 100644
--- a/civicrm/CRM/Report/Form/Contribute/Recur.php
+++ b/civicrm/CRM/Report/Form/Contribute/Recur.php
@@ -273,14 +273,9 @@ class CRM_Report_Form_Contribute_Recur extends CRM_Report_Form {
     $this->_from .= "
       LEFT JOIN civicrm_contribution  {$this->_aliases['civicrm_contribution']}
         ON {$this->_aliases['civicrm_contribution_recur']}.id = {$this->_aliases['civicrm_contribution']}.contribution_recur_id";
-    $this->_from .= "
-      LEFT JOIN civicrm_email  {$this->_aliases['civicrm_email']}
-        ON ({$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id AND
-        {$this->_aliases['civicrm_email']}.is_primary = 1)";
-    $this->_from .= "
-      LEFT  JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
-        ON ({$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id AND
-        {$this->_aliases['civicrm_phone']}.is_primary = 1)";
+
+    $this->joinPhoneFromContact();
+    $this->joinEmailFromContact();
 
     // for credit card type
     $this->addFinancialTrxnFromClause();
diff --git a/civicrm/CRM/Report/Form/Contribute/RecurSummary.php b/civicrm/CRM/Report/Form/Contribute/RecurSummary.php
index 4e31df8d8a..d6641be7cb 100644
--- a/civicrm/CRM/Report/Form/Contribute/RecurSummary.php
+++ b/civicrm/CRM/Report/Form/Contribute/RecurSummary.php
@@ -94,14 +94,12 @@ class CRM_Report_Form_Contribute_RecurSummary extends CRM_Report_Form {
   }
 
   public function select() {
+    // @todo remove & only adjust parent with selectWhere fn (if needed)
     $select = array();
     $this->_columnHeaders = array();
     foreach ($this->_columns as $tableName => $table) {
       if (array_key_exists('group_bys', $table)) {
         foreach ($table['group_bys'] as $fieldName => $field) {
-          if ($tableName == 'civicrm_address') {
-            $this->_addressField = TRUE;
-          }
           if (!empty($this->_params['group_bys'][$fieldName])) {
             switch (CRM_Utils_Array::value($fieldName, $this->_params['group_bys_freq'])) {
               case 'YEARWEEK':
@@ -150,9 +148,6 @@ class CRM_Report_Form_Contribute_RecurSummary extends CRM_Report_Form {
 
       if (array_key_exists('fields', $table)) {
         foreach ($table['fields'] as $fieldName => $field) {
-          if ($tableName == 'civicrm_address') {
-            $this->_addressField = TRUE;
-          }
           if (!empty($field['required']) ||
             !empty($this->_params['fields'][$fieldName])
           ) {
diff --git a/civicrm/CRM/Report/Form/Contribute/Summary.php b/civicrm/CRM/Report/Form/Contribute/Summary.php
index 1f95dc45da..4cc74ef432 100644
--- a/civicrm/CRM/Report/Form/Contribute/Summary.php
+++ b/civicrm/CRM/Report/Form/Contribute/Summary.php
@@ -31,7 +31,6 @@
  * @copyright CiviCRM LLC (c) 2004-2018
  */
 class CRM_Report_Form_Contribute_Summary extends CRM_Report_Form {
-  protected $_addressField = FALSE;
 
   protected $_charts = array(
     '' => 'Tabular',
@@ -344,9 +343,6 @@ class CRM_Report_Form_Contribute_Summary extends CRM_Report_Form {
     foreach ($this->_columns as $tableName => $table) {
       if (array_key_exists('group_bys', $table)) {
         foreach ($table['group_bys'] as $fieldName => $field) {
-          if ($tableName == 'civicrm_address') {
-            $this->_addressField = TRUE;
-          }
           if (!empty($this->_params['group_bys'][$fieldName])) {
             switch (CRM_Utils_Array::value($fieldName, $this->_params['group_bys_freq'])) {
               case 'YEARWEEK':
@@ -411,9 +407,6 @@ class CRM_Report_Form_Contribute_Summary extends CRM_Report_Form {
 
       if (array_key_exists('fields', $table)) {
         foreach ($table['fields'] as $fieldName => $field) {
-          if ($tableName == 'civicrm_address') {
-            $this->_addressField = TRUE;
-          }
           if (!empty($field['required']) ||
             !empty($this->_params['fields'][$fieldName])
           ) {
@@ -515,15 +508,12 @@ class CRM_Report_Form_Contribute_Summary extends CRM_Report_Form {
              {$softCreditJoin}
              LEFT  JOIN civicrm_financial_type  {$this->_aliases['civicrm_financial_type']}
                      ON {$this->_aliases['civicrm_contribution']}.financial_type_id ={$this->_aliases['civicrm_financial_type']}.id
-             LEFT  JOIN civicrm_email {$this->_aliases['civicrm_email']}
-                     ON ({$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id AND
-                        {$this->_aliases['civicrm_email']}.is_primary = 1)
+             ";
 
-             LEFT  JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
-                     ON ({$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id AND
-                        {$this->_aliases['civicrm_phone']}.is_primary = 1)";
+    $this->joinAddressFromContact();
+    $this->joinPhoneFromContact();
+    $this->joinEmailFromContact();
 
-    $this->addAddressFromClause();
     //for contribution batches
     if ($this->isTableSelected('civicrm_batch')) {
       $this->_from .= "
diff --git a/civicrm/CRM/Report/Form/Contribute/Sybunt.php b/civicrm/CRM/Report/Form/Contribute/Sybunt.php
index 918965a81d..f5c3073464 100644
--- a/civicrm/CRM/Report/Form/Contribute/Sybunt.php
+++ b/civicrm/CRM/Report/Form/Contribute/Sybunt.php
@@ -352,22 +352,13 @@ class CRM_Report_Form_Contribute_Sybunt extends CRM_Report_Form {
                       ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_contribution']}.contact_id
              {$this->_aclFrom}";
 
-    if ($this->isTableSelected('civicrm_email')) {
-      $this->_from .= "
-              LEFT  JOIN civicrm_email  {$this->_aliases['civicrm_email']}
-                      ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id
-                     AND {$this->_aliases['civicrm_email']}.is_primary = 1";
-    }
-    if ($this->isTableSelected('civicrm_phone')) {
-      $this->_from .= "
-              LEFT  JOIN civicrm_phone  {$this->_aliases['civicrm_phone']}
-                      ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id AND
-                         {$this->_aliases['civicrm_phone']}.is_primary = 1";
-    }
+    $this->joinPhoneFromContact();
+    $this->joinEmailFromContact();
+
     // for credit card type
     $this->addFinancialTrxnFromClause();
 
-    $this->addAddressFromClause();
+    $this->joinAddressFromContact();
   }
 
   public function where() {
diff --git a/civicrm/CRM/Report/Form/Contribute/TopDonor.php b/civicrm/CRM/Report/Form/Contribute/TopDonor.php
index 4be5c28e8b..36a97fe448 100644
--- a/civicrm/CRM/Report/Form/Contribute/TopDonor.php
+++ b/civicrm/CRM/Report/Form/Contribute/TopDonor.php
@@ -242,17 +242,14 @@ class CRM_Report_Form_Contribute_TopDonor extends CRM_Report_Form {
         FROM civicrm_contact {$this->_aliases['civicrm_contact']} {$this->_aclFrom}
             INNER JOIN civicrm_contribution {$this->_aliases['civicrm_contribution']}
                 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_contribution']}.contact_id AND {$this->_aliases['civicrm_contribution']}.is_test = 0
-             LEFT  JOIN civicrm_email  {$this->_aliases['civicrm_email']}
-                         ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id
-                         AND {$this->_aliases['civicrm_email']}.is_primary = 1
-             LEFT  JOIN civicrm_phone  {$this->_aliases['civicrm_phone']}
-                         ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id AND
-                            {$this->_aliases['civicrm_phone']}.is_primary = 1";
+       ";
 
     // for credit card type
     $this->addFinancialTrxnFromClause();
 
-    $this->addAddressFromClause();
+    $this->joinAddressFromContact();
+    $this->joinPhoneFromContact();
+    $this->joinEmailFromContact();
   }
 
   public function where() {
diff --git a/civicrm/CRM/Report/Form/Event/ParticipantListCount.php b/civicrm/CRM/Report/Form/Event/ParticipantListCount.php
index 07fcb817f0..bc15afc499 100644
--- a/civicrm/CRM/Report/Form/Event/ParticipantListCount.php
+++ b/civicrm/CRM/Report/Form/Event/ParticipantListCount.php
@@ -462,17 +462,12 @@ class CRM_Report_Form_Event_ParticipantListCount extends CRM_Report_Form_Event {
          {$this->_aclFrom}
          LEFT JOIN civicrm_contact {$this->_aliases['civicrm_employer']}
               ON ({$this->_aliases['civicrm_employer']}.id  = {$this->_aliases['civicrm_contact']}.employer_id  )
-         LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
-              ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_address']}.contact_id AND
-                {$this->_aliases['civicrm_address']}.is_primary = 1
-         LEFT JOIN  civicrm_email {$this->_aliases['civicrm_email']}
-              ON ({$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id AND
-                {$this->_aliases['civicrm_email']}.is_primary = 1)
-         LEFT  JOIN civicrm_phone  {$this->_aliases['civicrm_phone']}
-              ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id AND
-                {$this->_aliases['civicrm_phone']}.is_primary = 1
          LEFT JOIN civicrm_line_item {$this->_aliases['civicrm_line_item']}
               ON {$this->_aliases['civicrm_line_item']}.entity_table = 'civicrm_participant' AND {$this->_aliases['civicrm_participant']}.id ={$this->_aliases['civicrm_line_item']}.entity_id";
+
+    $this->joinAddressFromContact();
+    $this->joinPhoneFromContact();
+    $this->joinEmailFromContact();
   }
 
   public function storeWhereHavingClauseArray() {
diff --git a/civicrm/CRM/Report/Form/Event/ParticipantListing.php b/civicrm/CRM/Report/Form/Event/ParticipantListing.php
index 11e07bdf50..a5269d8807 100644
--- a/civicrm/CRM/Report/Form/Event/ParticipantListing.php
+++ b/civicrm/CRM/Report/Form/Event/ParticipantListing.php
@@ -513,16 +513,12 @@ ORDER BY  cv.label
              LEFT JOIN civicrm_contact {$this->_aliases['civicrm_contact']}
                     ON ({$this->_aliases['civicrm_participant']}.contact_id  = {$this->_aliases['civicrm_contact']}.id  )
              {$this->_aclFrom}
-             LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
-                    ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_address']}.contact_id AND
-                       {$this->_aliases['civicrm_address']}.is_primary = 1
-             LEFT JOIN  civicrm_email {$this->_aliases['civicrm_email']}
-                    ON ({$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id AND
-                       {$this->_aliases['civicrm_email']}.is_primary = 1)
-             LEFT  JOIN civicrm_phone  {$this->_aliases['civicrm_phone']}
-                     ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id AND
-                         {$this->_aliases['civicrm_phone']}.is_primary = 1
       ";
+
+    $this->joinAddressFromContact();
+    $this->joinPhoneFromContact();
+    $this->joinEmailFromContact();
+
     if ($this->_contribField) {
       $this->_from .= "
              LEFT JOIN civicrm_participant_payment pp
diff --git a/civicrm/CRM/Report/Form/Grant/Detail.php b/civicrm/CRM/Report/Form/Grant/Detail.php
index 4078bb33fc..cf1563bef6 100644
--- a/civicrm/CRM/Report/Form/Grant/Detail.php
+++ b/civicrm/CRM/Report/Form/Grant/Detail.php
@@ -32,8 +32,6 @@
  */
 class CRM_Report_Form_Grant_Detail extends CRM_Report_Form {
 
-  protected $_addressField = FALSE;
-
   protected $_customGroupExtends = array(
     'Grant',
   );
@@ -212,13 +210,11 @@ class CRM_Report_Form_Grant_Detail extends CRM_Report_Form {
   }
 
   public function select() {
+    // @todo remove this override - seems to do nothing parent doesn't.
     $select = array();
 
     $this->_columnHeaders = array();
     foreach ($this->_columns as $tableName => $table) {
-      if ($tableName == 'civicrm_address') {
-        $this->_addressField = TRUE;
-      }
       if (array_key_exists('fields', $table)) {
         foreach ($table['fields'] as $fieldName => $field) {
           if (!empty($field['required']) ||
@@ -242,16 +238,11 @@ class CRM_Report_Form_Grant_Detail extends CRM_Report_Form {
         FROM civicrm_grant {$this->_aliases['civicrm_grant']}
                         LEFT JOIN civicrm_contact {$this->_aliases['civicrm_contact']}
                     ON ({$this->_aliases['civicrm_grant']}.contact_id  = {$this->_aliases['civicrm_contact']}.id  ) ";
-    if ($this->_addressField) {
-      $this->_from .= "
-                  LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
-                         ON {$this->_aliases['civicrm_contact']}.id =
-                            {$this->_aliases['civicrm_address']}.contact_id AND
-                            {$this->_aliases['civicrm_address']}.is_primary = 1\n";
-    }
+    $this->joinAddressFromContact();
   }
 
   public function where() {
+    // @todo this function appears to do nothing more than parent, test & remove
     $clauses = array();
     $this->_where = '';
     foreach ($this->_columns as $tableName => $table) {
@@ -291,6 +282,7 @@ class CRM_Report_Form_Grant_Detail extends CRM_Report_Form {
   }
 
   public function groupBy() {
+    // @todo this function appears to do nothing more than parent, test & remove
     $this->_groupBy = "";
     if (!empty($this->_params['group_bys']) &&
       is_array($this->_params['group_bys']) &&
diff --git a/civicrm/CRM/Report/Form/Grant/Statistics.php b/civicrm/CRM/Report/Form/Grant/Statistics.php
index 47d03c5f22..b44f3b5648 100644
--- a/civicrm/CRM/Report/Form/Grant/Statistics.php
+++ b/civicrm/CRM/Report/Form/Grant/Statistics.php
@@ -32,8 +32,6 @@
  */
 class CRM_Report_Form_Grant_Statistics extends CRM_Report_Form {
 
-  protected $_addressField = FALSE;
-
   protected $_customGroupExtends = array('Grant');
 
   protected $_add2groupSupported = FALSE;
@@ -163,7 +161,7 @@ class CRM_Report_Form_Grant_Statistics extends CRM_Report_Form {
         ),
         'grouping' => 'contact-fields',
       ),
-      'civicrm_world_region' => array(
+      'civicrm_worldregion' => array(
         'dao' => 'CRM_Core_DAO_Worldregion',
         'fields' => array(
           'id' => array(
@@ -210,13 +208,6 @@ class CRM_Report_Form_Grant_Statistics extends CRM_Report_Form {
 
     $this->_columnHeaders = array();
     foreach ($this->_columns as $tableName => $table) {
-      if (in_array($tableName, array(
-        'civicrm_address',
-        'civicrm_world_region',
-      ))) {
-        $this->_addressField = TRUE;
-      }
-
       if (array_key_exists('fields', $table)) {
         foreach ($table['fields'] as $fieldName => $field) {
           if (!empty($field['required']) ||
@@ -241,18 +232,14 @@ class CRM_Report_Form_Grant_Statistics extends CRM_Report_Form {
         FROM civicrm_grant {$this->_aliases['civicrm_grant']}
                         LEFT JOIN civicrm_contact {$this->_aliases['civicrm_contact']}
                     ON ({$this->_aliases['civicrm_grant']}.contact_id  = {$this->_aliases['civicrm_contact']}.id  ) ";
-    if ($this->_addressField) {
+
+    $this->joinAddressFromContact();
+    $this->joinCountryFromAddress();
+    if ($this->isTableSelected('civicrm_worldregion')) {
       $this->_from .= "
-                  LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
-                         ON {$this->_aliases['civicrm_contact']}.id =
-                            {$this->_aliases['civicrm_address']}.contact_id AND
-                            {$this->_aliases['civicrm_address']}.is_primary = 1\n
-                  LEFT JOIN civicrm_country country
-                         ON {$this->_aliases['civicrm_address']}.country_id =
-                            country.id
-                  LEFT JOIN civicrm_worldregion {$this->_aliases['civicrm_world_region']}
-                         ON country.region_id =
-                            {$this->_aliases['civicrm_world_region']}.id";
+                  LEFT JOIN civicrm_worldregion {$this->_aliases['civicrm_worldregion']}
+                         ON {$this->_aliases['civicrm_country']}.region_id =
+                            {$this->_aliases['civicrm_worldregion']}.id";
     }
   }
 
@@ -416,11 +403,11 @@ SELECT COUNT({$this->_aliases['civicrm_grant']}.id) as count ,
         );
       }
 
-      if (array_key_exists('civicrm_world_region_name', $values)) {
-        $region = CRM_Utils_Array::value('civicrm_world_region_name', $values);
+      if (array_key_exists('civicrm_worldregion_name', $values)) {
+        $region = CRM_Utils_Array::value('civicrm_worldregion_name', $values);
         $region = ($region) ? $region : 'Unassigned';
-        $grantStatistics['civicrm_world_region_name']['title'] = ts('By Region');
-        self::getStatistics($grantStatistics['civicrm_world_region_name'], $region, $values,
+        $grantStatistics['civicrm_worldregion_name']['title'] = ts('By Region');
+        self::getStatistics($grantStatistics['civicrm_worldregion_name'], $region, $values,
           $awardedGrants, $awardedGrantsAmount
         );
       }
diff --git a/civicrm/CRM/Report/Form/Mailing/Bounce.php b/civicrm/CRM/Report/Form/Mailing/Bounce.php
index 574d1659f9..9d438b72a2 100644
--- a/civicrm/CRM/Report/Form/Mailing/Bounce.php
+++ b/civicrm/CRM/Report/Form/Mailing/Bounce.php
@@ -337,13 +337,7 @@ class CRM_Report_Form_Mailing_Bounce extends CRM_Report_Form {
         INNER JOIN civicrm_mailing {$this->_aliases['civicrm_mailing']}
           ON civicrm_mailing_job.mailing_id = {$this->_aliases['civicrm_mailing']}.id
       ";
-
-    if ($this->_phoneField) {
-      $this->_from .= "
-            LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
-                   ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id AND
-                      {$this->_aliases['civicrm_phone']}.is_primary = 1 ";
-    }
+    $this->joinPhoneFromContact();
   }
 
   public function where() {
diff --git a/civicrm/CRM/Report/Form/Mailing/Clicks.php b/civicrm/CRM/Report/Form/Mailing/Clicks.php
index 31e6429226..4bfa795ac8 100644
--- a/civicrm/CRM/Report/Form/Mailing/Clicks.php
+++ b/civicrm/CRM/Report/Form/Mailing/Clicks.php
@@ -293,14 +293,7 @@ class CRM_Report_Form_Mailing_Clicks extends CRM_Report_Form {
         ON civicrm_mailing_job.mailing_id = {$this->_aliases['civicrm_mailing']}.id
         AND civicrm_mailing_job.is_test = 0
     ";
-
-    if ($this->_phoneField) {
-      $this->_from .= "
-        LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
-          ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id
-          AND {$this->_aliases['civicrm_phone']}.is_primary = 1
-      ";
-    }
+    $this->joinPhoneFromContact();
   }
 
   public function where() {
diff --git a/civicrm/CRM/Report/Form/Mailing/Detail.php b/civicrm/CRM/Report/Form/Mailing/Detail.php
index f028d236ba..7a55a5c034 100644
--- a/civicrm/CRM/Report/Form/Mailing/Detail.php
+++ b/civicrm/CRM/Report/Form/Mailing/Detail.php
@@ -443,12 +443,7 @@ class CRM_Report_Form_Mailing_Detail extends CRM_Report_Form {
           ON civicrm_mailing_job.mailing_id = {$this->_aliases['civicrm_mailing']}.id
           AND civicrm_mailing_job.is_test = 0";
 
-    if ($this->_phoneField) {
-      $this->_from .= "
-            LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
-                   ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id AND
-                      {$this->_aliases['civicrm_phone']}.is_primary = 1 ";
-    }
+    $this->joinPhoneFromContact();
   }
 
   public function where() {
diff --git a/civicrm/CRM/Report/Form/Mailing/Opened.php b/civicrm/CRM/Report/Form/Mailing/Opened.php
index 08ced58dbc..5a48f9e56f 100644
--- a/civicrm/CRM/Report/Form/Mailing/Opened.php
+++ b/civicrm/CRM/Report/Form/Mailing/Opened.php
@@ -279,14 +279,7 @@ class CRM_Report_Form_Mailing_Opened extends CRM_Report_Form {
         ON civicrm_mailing_job.mailing_id = {$this->_aliases['civicrm_mailing']}.id
         AND civicrm_mailing_job.is_test = 0
     ";
-
-    if ($this->_phoneField) {
-      $this->_from .= "
-        LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
-          ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id
-          AND {$this->_aliases['civicrm_phone']}.is_primary = 1
-      ";
-    }
+    $this->joinPhoneFromContact();
   }
 
   public function where() {
diff --git a/civicrm/CRM/Report/Form/Member/ContributionDetail.php b/civicrm/CRM/Report/Form/Member/ContributionDetail.php
index 3bb37c78aa..0f8a0c01b9 100644
--- a/civicrm/CRM/Report/Form/Member/ContributionDetail.php
+++ b/civicrm/CRM/Report/Form/Member/ContributionDetail.php
@@ -31,9 +31,6 @@
  * @copyright CiviCRM LLC (c) 2004-2018
  */
 class CRM_Report_Form_Member_ContributionDetail extends CRM_Report_Form {
-  protected $_addressField = FALSE;
-
-  protected $_emailField = FALSE;
 
   protected $_summary = NULL;
 
@@ -411,12 +408,6 @@ class CRM_Report_Form_Member_ContributionDetail extends CRM_Report_Form {
           if (!empty($field['required']) ||
             !empty($this->_params['fields'][$fieldName])
           ) {
-            if ($tableName == 'civicrm_address') {
-              $this->_addressField = TRUE;
-            }
-            if ($tableName == 'civicrm_email') {
-              $this->_emailField = TRUE;
-            }
 
             // only include statistics columns if set
             if (!empty($field['statistics'])) {
@@ -509,12 +500,6 @@ class CRM_Report_Form_Member_ContributionDetail extends CRM_Report_Form {
 
     }
 
-    if (!empty($this->_params['fields']['phone'])) {
-      $this->_from .= "
-               LEFT JOIN  civicrm_phone {$this->_aliases['civicrm_phone']}
-                      ON ({$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id AND
-                         {$this->_aliases['civicrm_phone']}.is_primary = 1)";
-    }
     //for contribution batches
     if (!empty($this->_params['fields']['batch_id']) ||
         !empty($this->_params['bid_value'])
@@ -528,22 +513,9 @@ class CRM_Report_Form_Member_ContributionDetail extends CRM_Report_Form {
           AND {$this->_aliases['civicrm_batch']}.entity_table = 'civicrm_financial_trxn')";
     }
 
-    if ($this->_addressField OR
-      (!empty($this->_params['state_province_id_value']) OR
-        !empty($this->_params['country_id_value']))
-    ) {
-      $this->_from .= "
-            LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
-                   ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_address']}.contact_id AND
-                      {$this->_aliases['civicrm_address']}.is_primary = 1\n";
-    }
-
-    if ($this->_emailField) {
-      $this->_from .= "
-            LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']}
-                   ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id AND
-                      {$this->_aliases['civicrm_email']}.is_primary = 1\n";
-    }
+    $this->joinAddressFromContact();
+    $this->joinPhoneFromContact();
+    $this->joinEmailFromContact();
   }
 
   /**
diff --git a/civicrm/CRM/Report/Form/Member/Detail.php b/civicrm/CRM/Report/Form/Member/Detail.php
index 344af45dda..8b3f75660f 100644
--- a/civicrm/CRM/Report/Form/Member/Detail.php
+++ b/civicrm/CRM/Report/Form/Member/Detail.php
@@ -81,6 +81,11 @@ class CRM_Report_Form_Member_Detail extends CRM_Report_Form {
             'title' => ts('Contact Name'),
             'operator' => 'like',
           ),
+          'is_deleted' => array(
+            'title' => ts('Is Deleted'),
+            'default' => 0,
+            'type' => CRM_Utils_Type::T_BOOLEAN,
+          ),
           'id' => array('no_display' => TRUE),
         ),
         'order_bys' => array(
@@ -284,29 +289,10 @@ class CRM_Report_Form_Member_Detail extends CRM_Report_Form {
                           ON {$this->_aliases['civicrm_membership_status']}.id =
                              {$this->_aliases['civicrm_membership']}.status_id ";
 
-    if ($this->isTableSelected('civicrm_address')) {
-      $this->_from .= "
-             LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
-                       ON {$this->_aliases['civicrm_contact']}.id =
-                          {$this->_aliases['civicrm_address']}.contact_id AND
-                          {$this->_aliases['civicrm_address']}.is_primary = 1\n";
-    }
+    $this->joinAddressFromContact();
+    $this->joinPhoneFromContact();
+    $this->joinEmailFromContact();
 
-    if ($this->isTableSelected('civicrm_email')) {
-      $this->_from .= "
-              LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']}
-                        ON {$this->_aliases['civicrm_contact']}.id =
-                           {$this->_aliases['civicrm_email']}.contact_id AND
-                           {$this->_aliases['civicrm_email']}.is_primary = 1\n";
-    }
-    //used when phone field is selected
-    if ($this->isTableSelected('civicrm_phone')) {
-      $this->_from .= "
-              LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
-                        ON {$this->_aliases['civicrm_contact']}.id =
-                           {$this->_aliases['civicrm_phone']}.contact_id AND
-                           {$this->_aliases['civicrm_phone']}.is_primary = 1\n";
-    }
     //used when contribution field is selected.
     if ($this->isTableSelected('civicrm_contribution')) {
       $this->_from .= "
diff --git a/civicrm/CRM/Report/Form/Member/Lapse.php b/civicrm/CRM/Report/Form/Member/Lapse.php
index 13782579ac..f354302a01 100644
--- a/civicrm/CRM/Report/Form/Member/Lapse.php
+++ b/civicrm/CRM/Report/Form/Member/Lapse.php
@@ -35,9 +35,6 @@
 class CRM_Report_Form_Member_Lapse extends CRM_Report_Form {
 
   protected $_summary = NULL;
-  protected $_addressField = FALSE;
-  protected $_emailField = FALSE;
-  protected $_phoneField = FALSE;
   protected $_charts = array('' => 'Tabular');
   protected $_customGroupExtends = array(
     'Membership',
@@ -212,16 +209,6 @@ class CRM_Report_Form_Member_Lapse extends CRM_Report_Form {
           if (!empty($field['required']) ||
             !empty($this->_params['fields'][$fieldName])
           ) {
-            // to include optional columns address ,email and phone only if checked
-            if ($tableName == 'civicrm_address') {
-              $this->_addressField = TRUE;
-            }
-            elseif ($tableName == 'civicrm_email') {
-              $this->_emailField = TRUE;
-            }
-            elseif ($tableName == 'civicrm_phone') {
-              $this->_phoneField = TRUE;
-            }
             $select[] = "{$field['dbAlias']} as {$tableName}_{$fieldName}";
             $this->_columnHeaders["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array::value('type', $field);
             $this->_columnHeaders["{$tableName}_{$fieldName}"]['title'] = $field['title'];
@@ -248,8 +235,6 @@ class CRM_Report_Form_Member_Lapse extends CRM_Report_Form {
   }
 
   public function from() {
-    $this->_from = NULL;
-
     $this->_from = "
         FROM  civicrm_contact {$this->_aliases['civicrm_contact']} {$this->_aclFrom}
               INNER JOIN civicrm_membership {$this->_aliases['civicrm_membership']}
@@ -262,27 +247,9 @@ class CRM_Report_Form_Member_Lapse extends CRM_Report_Form {
                          ON {$this->_aliases['civicrm_membership']}.membership_type_id =
                             {$this->_aliases['civicrm_membership_type']}.id";
 
-    //  include address field if address column is to be included
-    if ($this->_addressField) {
-      $this->_from .= "
-            LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
-                      ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_address']}.contact_id AND {$this->_aliases['civicrm_address']}.is_primary = 1\n";
-    }
-
-    // include email field if email column is to be included
-    if ($this->_emailField) {
-      $this->_from .= "
-            LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']}
-                      ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id AND {$this->_aliases['civicrm_email']}.is_primary = 1\n";
-    }
-
-    // include phone field if phone column is to be included
-    if ($this->_phoneField) {
-      $this->_from .= "
-            LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
-                      ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id
-                     AND {$this->_aliases['civicrm_phone']}.is_primary = 1\n";
-    }
+    $this->joinAddressFromContact();
+    $this->joinPhoneFromContact();
+    $this->joinEmailFromContact();
   }
 
   public function where() {
diff --git a/civicrm/CRM/Report/Form/Membership/Summary.php b/civicrm/CRM/Report/Form/Membership/Summary.php
index 5e8df23c90..ba497f4ff7 100644
--- a/civicrm/CRM/Report/Form/Membership/Summary.php
+++ b/civicrm/CRM/Report/Form/Membership/Summary.php
@@ -148,6 +148,7 @@ class CRM_Report_Form_Membership_Summary extends CRM_Report_Form {
    * Generate select clause.
    */
   public function select() {
+    // @todo remove this in favour of just using parent.
     $select = array();
     $this->_columnHeaders = array();
     foreach ($this->_columns as $tableName => $table) {
@@ -156,14 +157,6 @@ class CRM_Report_Form_Membership_Summary extends CRM_Report_Form {
           if (!empty($field['required']) ||
             !empty($this->_params['fields'][$fieldName])
           ) {
-            // to include optional columns address and email, only if checked
-            if ($tableName == 'civicrm_address') {
-              $this->_addressField = TRUE;
-              $this->_emailField = TRUE;
-            }
-            elseif ($tableName == 'civicrm_email') {
-              $this->_emailField = TRUE;
-            }
             $select[] = "{$field['dbAlias']} as {$tableName}_{$fieldName}";
             $this->_columnHeaders["{$tableName}_{$fieldName}"]['type'] = $field['type'];
             $this->_columnHeaders["{$tableName}_{$fieldName}"]['title'] = $field['title'];
@@ -189,15 +182,8 @@ LEFT  JOIN civicrm_membership_type  {$this->_aliases['civicrm_membership_type']}
 LEFT  JOIN civicrm_contribution  {$this->_aliases['civicrm_contribution']}
        ON {$this->_aliases['civicrm_membership']}.contact_id = {$this->_aliases['civicrm_contribution']}.contact_id
 ";
-    // Include address table if address column is to be included.
-    if ($this->_addressField) {
-      $this->_from .= "LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']} ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_address']}.contact_id AND {$this->_aliases['civicrm_address']}.is_primary = 1\n";
-    }
-
-    // Include email table if email column is to be included.
-    if ($this->_emailField) {
-      $this->_from .= "LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']} ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id AND {$this->_aliases['civicrm_email']}.is_primary = 1\n";
-    }
+    $this->joinAddressFromContact();
+    $this->joinEmailFromContact();
   }
 
   /**
diff --git a/civicrm/CRM/Report/Form/Pledge/Detail.php b/civicrm/CRM/Report/Form/Pledge/Detail.php
index 85a485caa5..7c2c1da2a5 100644
--- a/civicrm/CRM/Report/Form/Pledge/Detail.php
+++ b/civicrm/CRM/Report/Form/Pledge/Detail.php
@@ -286,16 +286,9 @@ class CRM_Report_Form_Pledge_Detail extends CRM_Report_Form {
       ";
     }
 
-    $this->addPhoneFromClause();
-    $this->addAddressFromClause();
-    // include email field if email column is to be included
-    if ($this->_emailField) {
-      $this->_from .= "
-                 LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']}
-                           ON ({$this->_aliases['civicrm_contact']}.id =
-                               {$this->_aliases['civicrm_email']}.contact_id) AND
-                               {$this->_aliases['civicrm_email']}.is_primary = 1\n";
-    }
+    $this->joinPhoneFromContact();
+    $this->joinAddressFromContact();
+    $this->joinEmailFromContact();
   }
 
   /**
diff --git a/civicrm/CRM/Report/Form/Pledge/Pbnp.php b/civicrm/CRM/Report/Form/Pledge/Pbnp.php
index 596d91dd1b..01294d59c6 100644
--- a/civicrm/CRM/Report/Form/Pledge/Pbnp.php
+++ b/civicrm/CRM/Report/Form/Pledge/Pbnp.php
@@ -230,14 +230,6 @@ class CRM_Report_Form_Pledge_Pbnp extends CRM_Report_Form {
           if (!empty($field['required']) ||
             !empty($this->_params['fields'][$fieldName])
           ) {
-            // to include optional columns address and email, only if checked
-            if ($tableName == 'civicrm_address') {
-              $this->_addressField = TRUE;
-              $this->_emailField = TRUE;
-            }
-            elseif ($tableName == 'civicrm_email') {
-              $this->_emailField = TRUE;
-            }
             $select[] = "{$field['dbAlias']} as {$tableName}_{$fieldName}";
             $this->_columnHeaders["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array::value('type', $field);
             $this->_columnHeaders["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array::value('title', $field);
@@ -279,23 +271,9 @@ class CRM_Report_Form_Pledge_Pbnp extends CRM_Report_Form {
                         ON ({$this->_aliases['civicrm_pledge']}.id =
                             {$this->_aliases['civicrm_pledge_payment']}.pledge_id AND  {$this->_aliases['civicrm_pledge_payment']}.status_id = {$pendingStatus} ) ";
 
-    // include address field if address column is to be included
-    if ($this->_addressField) {
-      $this->_from .= "
-             LEFT  JOIN civicrm_address {$this->_aliases['civicrm_address']}
-                        ON ({$this->_aliases['civicrm_contact']}.id =
-                            {$this->_aliases['civicrm_address']}.contact_id) AND
-                            {$this->_aliases['civicrm_address']}.is_primary = 1\n";
-    }
+    $this->joinAddressFromContact();
+    $this->joinEmailFromContact();
 
-    // include email field if email column is to be included
-    if ($this->_emailField) {
-      $this->_from .= "
-            LEFT  JOIN civicrm_email {$this->_aliases['civicrm_email']}
-                       ON ({$this->_aliases['civicrm_contact']}.id =
-                           {$this->_aliases['civicrm_email']}.contact_id) AND
-                           {$this->_aliases['civicrm_email']}.is_primary = 1\n";
-    }
   }
 
   public function groupBy() {
diff --git a/civicrm/CRM/Report/Form/Pledge/Summary.php b/civicrm/CRM/Report/Form/Pledge/Summary.php
index 39749ef804..b5905c5c8d 100644
--- a/civicrm/CRM/Report/Form/Pledge/Summary.php
+++ b/civicrm/CRM/Report/Form/Pledge/Summary.php
@@ -38,8 +38,6 @@ class CRM_Report_Form_Pledge_Summary extends CRM_Report_Form {
   protected $_totalPaid = FALSE;
   protected $_customGroupExtends = array('Pledge', 'Individual');
   protected $_customGroupGroupBy = TRUE;
-  protected $_addressField = FALSE;
-  protected $_emailField = FALSE;
 
   /**
    * This report has not been optimised for group filtering.
@@ -216,23 +214,8 @@ class CRM_Report_Form_Pledge_Summary extends CRM_Report_Form {
                           {$this->_aliases['civicrm_pledge']}.contact_id )
                  {$this->_aclFrom} ";
 
-    // include address field if address column is to be included
-    if ($this->_addressField) {
-      $this->_from .= "
-                 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
-                           ON ({$this->_aliases['civicrm_contact']}.id =
-                               {$this->_aliases['civicrm_address']}.contact_id) AND
-                               {$this->_aliases['civicrm_address']}.is_primary = 1\n";
-    }
-
-    // include email field if email column is to be included
-    if ($this->_emailField) {
-      $this->_from .= "
-                 LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']}
-                           ON ({$this->_aliases['civicrm_contact']}.id =
-                               {$this->_aliases['civicrm_email']}.contact_id) AND
-                               {$this->_aliases['civicrm_email']}.is_primary = 1\n";
-    }
+    $this->joinAddressFromContact();
+    $this->joinEmailFromContact();
 
     if (!empty($this->_params['fields']['total_paid'])) {
       $this->_from .= "
diff --git a/civicrm/CRM/Report/Form/Walklist/Walklist.php b/civicrm/CRM/Report/Form/Walklist/Walklist.php
index 98e51413fe..25e92d7027 100644
--- a/civicrm/CRM/Report/Form/Walklist/Walklist.php
+++ b/civicrm/CRM/Report/Form/Walklist/Walklist.php
@@ -31,11 +31,6 @@
  * @copyright CiviCRM LLC (c) 2004-2018
  */
 class CRM_Report_Form_Walklist_Walklist extends CRM_Report_Form {
-  protected $_addressField = FALSE;
-
-  protected $_emailField = FALSE;
-
-  protected $_phoneField = FALSE;
 
   protected $_summary = NULL;
 
@@ -149,6 +144,7 @@ class CRM_Report_Form_Walklist_Walklist extends CRM_Report_Form {
   }
 
   public function select() {
+    // @todo remove this function & use parent.
     $select = array();
 
     $this->_columnHeaders = array();
@@ -157,15 +153,6 @@ class CRM_Report_Form_Walklist_Walklist extends CRM_Report_Form {
         if (!empty($field['required']) ||
           !empty($this->_params['fields'][$fieldName])
         ) {
-          if ($tableName == 'civicrm_address') {
-            $this->_addressField = TRUE;
-          }
-          elseif ($tableName == 'civicrm_email') {
-            $this->_emailField = TRUE;
-          }
-          elseif ($tableName == 'civicrm_phone') {
-            $this->_phoneField = TRUE;
-          }
 
           $select[] = "{$field['dbAlias']} as {$tableName}_{$fieldName}";
           $this->_columnHeaders["{$tableName}_{$fieldName}"]['title'] = $field['title'];
@@ -183,17 +170,10 @@ class CRM_Report_Form_Walklist_Walklist extends CRM_Report_Form {
     $this->_from = "
 FROM       civicrm_contact {$this->_aliases['civicrm_contact']} {$this->_aclFrom}
 ";
-    if ($this->_addressField) {
-      $this->_from .= "LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']} ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_address']}.contact_id AND {$this->_aliases['civicrm_address']}.is_primary = 1\n";
-    }
-
-    if ($this->_emailField) {
-      $this->_from .= "LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']} ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id AND {$this->_aliases['civicrm_email']}.is_primary = 1\n";
-    }
 
-    if ($this->_phoneField) {
-      $this->_from .= "LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']} ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id AND {$this->_aliases['civicrm_phone']}.is_primary = 1\n";
-    }
+    $this->joinAddressFromContact();
+    $this->joinPhoneFromContact();
+    $this->joinEmailFromContact();
   }
 
   public function where() {
diff --git a/civicrm/CRM/Report/Utils/Get.php b/civicrm/CRM/Report/Utils/Get.php
index b7f4b01dde..146bb5266b 100644
--- a/civicrm/CRM/Report/Utils/Get.php
+++ b/civicrm/CRM/Report/Utils/Get.php
@@ -113,6 +113,7 @@ class CRM_Report_Utils_Get {
       case 'ew':
       case 'nhas':
       case 'like':
+      case 'eq':
       case 'neq':
         $value = self::getTypedValue("{$fieldName}_value", CRM_Utils_Array::value('type', $field));
         if ($value !== NULL) {
diff --git a/civicrm/CRM/Upgrade/4.1.alpha1.msg_template/civicrm_msg_template.tpl b/civicrm/CRM/Upgrade/4.1.alpha1.msg_template/civicrm_msg_template.tpl
deleted file mode 100644
index 11a9a5c862..0000000000
--- a/civicrm/CRM/Upgrade/4.1.alpha1.msg_template/civicrm_msg_template.tpl
+++ /dev/null
@@ -1,16 +0,0 @@
-{php}
-  $dir = SMARTY_DIR . '/../../CRM/Upgrade/4.1.alpha1.msg_template/message_templates';
-  $templates = array();
-  foreach (preg_grep('/\.tpl$/', scandir($dir)) as $filename) {
-    $parts = explode('_', basename($filename, '.tpl'));
-    $templates[] = array('type' => array_pop($parts), 'name' => implode('_', $parts), 'filename' => "$dir/$filename");
-  }
-  $this->assign('templates', $templates);
-{/php}
-
-{foreach from=$templates item=tpl}
-  {fetch assign=content file=$tpl.filename}
-  SELECT @workflow_id := MAX(id) FROM civicrm_option_value WHERE name = '{$tpl.name}';
-  SELECT @content := msg_{$tpl.type} FROM civicrm_msg_template WHERE workflow_id = @workflow_id AND is_reserved = 1 LIMIT 1;
-  UPDATE civicrm_msg_template SET msg_{$tpl.type} = '{$content|escape:"quotes"}' WHERE workflow_id = @workflow_id AND (is_reserved = 1 OR (is_default = 1 AND msg_{$tpl.type} = @content));
-{/foreach}
diff --git a/civicrm/CRM/Upgrade/4.1.alpha1.msg_template/message_templates/contribution_online_receipt_html.tpl b/civicrm/CRM/Upgrade/4.1.alpha1.msg_template/message_templates/contribution_online_receipt_html.tpl
deleted file mode 100644
index f22d675522..0000000000
--- a/civicrm/CRM/Upgrade/4.1.alpha1.msg_template/message_templates/contribution_online_receipt_html.tpl
+++ /dev/null
@@ -1,391 +0,0 @@
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
-<html xmlns="http://www.w3.org/1999/xhtml">
-<head>
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
- <title></title>
-</head>
-<body>
-
-{capture assign=headerStyle}colspan="2" style="text-align: left; padding: 4px; border-bottom: 1px solid #999; background-color: #eee;"{/capture}
-{capture assign=labelStyle }style="padding: 4px; border-bottom: 1px solid #999; background-color: #f7f7f7;"{/capture}
-{capture assign=valueStyle }style="padding: 4px; border-bottom: 1px solid #999;"{/capture}
-
-<center>
- <table width="500" border="0" cellpadding="0" cellspacing="0" id="crm-event_receipt" style="font-family: Arial, Verdana, sans-serif; text-align: left;">
-
-  <!-- BEGIN HEADER -->
-  <!-- You can add table row(s) here with logo or other header elements -->
-  <!-- END HEADER -->
-
-  <!-- BEGIN CONTENT -->
-
-  <tr>
-   <td>
-
-    {if $receipt_text}
-     <p>{$receipt_text|htmlize}</p>
-    {/if}
-
-    {if $is_pay_later}
-     <p>{$pay_later_receipt}</p> {* FIXME: this might be text rather than HTML *}
-    {else}
-     <p>{ts}Please print this confirmation for your records.{/ts}</p>
-    {/if}
-
-   </td>
-  </tr>
-  </table>
-  <table width="500" style="border: 1px solid #999; margin: 1em 0em 1em; border-collapse: collapse;">
-
-     {if $amount}
-
-
-      <tr>
-       <th {$headerStyle}>
-        {ts}Contribution Information{/ts}
-       </th>
-      </tr>
-
-      {if $lineItem and $priceSetID}
-
-       {foreach from=$lineItem item=value key=priceset}
-        <tr>
-         <td colspan="2" {$valueStyle}>
-          <table> {* FIXME: style this table so that it looks like the text version (justification, etc.) *}
-           <tr>
-            <th>{ts}Item{/ts}</th>
-            <th>{ts}Qty{/ts}</th>
-            <th>{ts}Each{/ts}</th>
-            <th>{ts}Total{/ts}</th>
-           </tr>
-           {foreach from=$value item=line}
-            <tr>
-             <td>
-             {if $line.html_type eq 'Text'}{$line.label}{else}{$line.field_title} - {$line.label}{/if} {if $line.description}<div>{$line.description|truncate:30:"..."}</div>{/if}
-             </td>
-             <td>
-              {$line.qty}
-             </td>
-             <td>
-              {$line.unit_price|crmMoney:$currency}
-             </td>
-             <td>
-              {$line.line_total|crmMoney:$currency}
-             </td>
-            </tr>
-           {/foreach}
-          </table>
-         </td>
-        </tr>
-       {/foreach}
-       <tr>
-        <td {$labelStyle}>
-         {ts}Total Amount{/ts}
-        </td>
-        <td {$valueStyle}>
-         {$amount|crmMoney:$currency}
-        </td>
-       </tr>
-
-      {else}
-
-       <tr>
-        <td {$labelStyle}>
-         {ts}Amount{/ts}
-        </td>
-        <td {$valueStyle}>
-         {$amount|crmMoney:$currency} {if $amount_level} - {$amount_level}{/if}
-        </td>
-       </tr>
-
-      {/if}
-
-
-     {/if}
-
-
-     {if $receive_date}
-      <tr>
-       <td {$labelStyle}>
-        {ts}Date{/ts}
-       </td>
-       <td {$valueStyle}>
-        {$receive_date|crmDate}
-       </td>
-      </tr>
-     {/if}
-
-     {if $is_monetary and $trxn_id}
-      <tr>
-       <td {$labelStyle}>
-        {ts}Transaction #{/ts}
-       </td>
-       <td {$valueStyle}>
-        {$trxn_id}
-       </td>
-      </tr>
-     {/if}
-
-     {if $is_recur}
-      {if $contributeMode eq 'notify'}
-       <tr>
-        <td {$labelStyle}>
-         {ts 1=$cancelSubscriptionUrl}This is a recurring contribution. You can modify or cancel future contributions by <a href="%1">logging in to your account</a>.{/ts}
-        </td>
-       </tr>
-      {elseif $contributeMode eq 'directIPN' and $receiptFromEmail}
-       <tr>
-        <td {$labelStyle}>
-         {ts 1=$receiptFromEmail}This is a recurring contribution. To modify or cancel future contributions please contact us at %1.{/ts}
-        </td>
-       </tr>
-      {/if}
-     {/if}
-
-     {if $honor_block_is_active}
-      <tr>
-       <th {$headerStyle}>
-        {$honor_type}
-       </th>
-      </tr>
-      <tr>
-       <td colspan="2" {$labelStyle}>
-        {$honor_prefix} {$honor_first_name} {$honor_last_name}
-       </td>
-      </tr>
-      {if $honor_email}
-       <tr>
-        <td {$labelStyle}>
-         {ts}Honoree Email{/ts}
-        </td>
-        <td {$valueStyle}>
-         {$honor_email}
-        </td>
-       </tr>
-      {/if}
-     {/if}
-
-     {if $pcpBlock}
-      <tr>
-       <th {$headerStyle}>
-        {ts}Personal Campaign Page{/ts}
-       </th>
-      </tr>
-      <tr>
-       <td {$labelStyle}>
-        {ts}Display In Honor Roll{/ts}
-       </td>
-       <td {$valueStyle}>
-        {if $pcp_display_in_roll}{ts}Yes{/ts}{else}{ts}No{/ts}{/if}
-       </td>
-      </tr>
-      {if $pcp_roll_nickname}
-       <tr>
-        <td {$labelStyle}>
-         {ts}Nickname{/ts}
-        </td>
-        <td {$valueStyle}>
-         {$pcp_roll_nickname}
-        </td>
-       </tr>
-      {/if}
-      {if $pcp_personal_note}
-       <tr>
-        <td {$labelStyle}>
-         {ts}Personal Note{/ts}
-        </td>
-        <td {$valueStyle}>
-         {$pcp_personal_note}
-        </td>
-       </tr>
-      {/if}
-     {/if}
-
-     {if $onBehalfProfile}
-      <tr>
-       <th {$headerStyle}>
-        {$onBehalfProfile_grouptitle}
-       </th>
-      </tr>
-      {foreach from=$onBehalfProfile item=onBehalfValue key=onBehalfName}
-        <tr>
-         <td {$labelStyle}>
-          {$onBehalfName}
-         </td>
-         <td {$valueStyle}>
-          {$onBehalfValue}
-         </td>
-        </tr>
-      {/foreach}
-     {/if}
-
-     {if $isShare}
-      <tr>
-        <td colspan="2" {$valueStyle}>
-            {capture assign=contributionUrl}{crmURL p='civicrm/contribute/transact' q="reset=1&id=`$contributionPageId`" a=true fe=1 h=1}{/capture}
-            {include file="CRM/common/SocialNetwork.tpl" emailMode=true url=$contributionUrl title=$title pageURL=$contributionUrl}
-        </td>
-      </tr>
-     {/if}
-
-     {if ! ($contributeMode eq 'notify' OR $contributeMode eq 'directIPN') and $is_monetary}
-      {if $is_pay_later}
-       <tr>
-        <th {$headerStyle}>
-         {ts}Registered Email{/ts}
-        </th>
-       </tr>
-       <tr>
-        <td colspan="2" {$valueStyle}>
-         {$email}
-        </td>
-       </tr>
-      {elseif $amount GT 0}
-       <tr>
-        <th {$headerStyle}>
-         {ts}Billing Name and Address{/ts}
-        </th>
-       </tr>
-       <tr>
-        <td colspan="2" {$valueStyle}>
-         {$billingName}<br />
-         {$address|nl2br}<br />
-         {$email}
-        </td>
-       </tr>
-      {/if}
-     {/if}
-
-     {if $contributeMode eq 'direct' AND !$is_pay_later AND $amount GT 0}
-      <tr>
-       <th {$headerStyle}>
-        {ts}Credit Card Information{/ts}
-       </th>
-      </tr>
-      <tr>
-       <td colspan="2" {$valueStyle}>
-        {$credit_card_type}<br />
-        {$credit_card_number}<br />
-        {ts}Expires{/ts}: {$credit_card_exp_date|truncate:7:''|crmDate}<br />
-       </td>
-      </tr>
-     {/if}
-
-     {if $selectPremium}
-      <tr>
-       <th {$headerStyle}>
-        {ts}Premium Information{/ts}
-       </th>
-      </tr>
-      <tr>
-       <td colspan="2" {$labelStyle}>
-        {$product_name}
-       </td>
-      </tr>
-      {if $option}
-       <tr>
-        <td {$labelStyle}>
-         {ts}Option{/ts}
-        </td>
-        <td {$valueStyle}>
-         {$option}
-        </td>
-       </tr>
-      {/if}
-      {if $sku}
-       <tr>
-        <td {$labelStyle}>
-         {ts}SKU{/ts}
-        </td>
-        <td {$valueStyle}>
-         {$sku}
-        </td>
-       </tr>
-      {/if}
-      {if $start_date}
-       <tr>
-        <td {$labelStyle}>
-         {ts}Start Date{/ts}
-        </td>
-        <td {$valueStyle}>
-         {$start_date|crmDate}
-        </td>
-       </tr>
-      {/if}
-      {if $end_date}
-       <tr>
-        <td {$labelStyle}>
-         {ts}End Date{/ts}
-        </td>
-        <td {$valueStyle}>
-         {$end_date|crmDate}
-        </td>
-       </tr>
-      {/if}
-      {if $contact_email OR $contact_phone}
-       <tr>
-        <td colspan="2" {$valueStyle}>
-         <p>{ts}For information about this premium, contact:{/ts}</p>
-         {if $contact_email}
-          <p>{$contact_email}</p>
-         {/if}
-         {if $contact_phone}
-          <p>{$contact_phone}</p>
-         {/if}
-        </td>
-       </tr>
-      {/if}
-      {if $is_deductible AND $price}
-        <tr>
-         <td colspan="2" {$valueStyle}>
-          <p>{ts 1=$price|crmMoney:$currency}The value of this premium is %1. This may affect the amount of the tax deduction you can claim. Consult your tax advisor for more information.{/ts}</p>
-         </td>
-        </tr>
-      {/if}
-     {/if}
-
-     {if $customPre}
-      <tr>
-       <th {$headerStyle}>
-        {$customPre_grouptitle}
-       </th>
-      </tr>
-      {foreach from=$customPre item=customValue key=customName}
-       {if ($trackingFields and ! in_array($customName, $trackingFields)) or ! $trackingFields}
-        <tr>
-         <td {$labelStyle}>
-          {$customName}
-         </td>
-         <td {$valueStyle}>
-          {$customValue}
-         </td>
-        </tr>
-       {/if}
-      {/foreach}
-     {/if}
-
-     {if $customPost}
-      <tr>
-       <th {$headerStyle}>
-        {$customPost_grouptitle}
-       </th>
-      </tr>
-      {foreach from=$customPost item=customValue key=customName}
-       {if ($trackingFields and ! in_array($customName, $trackingFields)) or ! $trackingFields}
-        <tr>
-         <td {$labelStyle}>
-          {$customName}
-         </td>
-         <td {$valueStyle}>
-          {$customValue}
-         </td>
-        </tr>
-       {/if}
-      {/foreach}
-     {/if}
-
-  </table>
-</center>
-
-</body>
-</html>
diff --git a/civicrm/CRM/Upgrade/4.1.alpha1.msg_template/message_templates/event_online_receipt_html.tpl b/civicrm/CRM/Upgrade/4.1.alpha1.msg_template/message_templates/event_online_receipt_html.tpl
deleted file mode 100644
index 98a9422078..0000000000
--- a/civicrm/CRM/Upgrade/4.1.alpha1.msg_template/message_templates/event_online_receipt_html.tpl
+++ /dev/null
@@ -1,469 +0,0 @@
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
-<html xmlns="http://www.w3.org/1999/xhtml">
-<head>
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
- <title></title>
-</head>
-<body>
-
-{capture assign=headerStyle}colspan="2" style="text-align: left; padding: 4px; border-bottom: 1px solid #999; background-color: #eee;"{/capture}
-{capture assign=labelStyle }style="padding: 4px; border-bottom: 1px solid #999; background-color: #f7f7f7;"{/capture}
-{capture assign=valueStyle }style="padding: 4px; border-bottom: 1px solid #999;"{/capture}
-
-<center>
- <table width="500" border="0" cellpadding="0" cellspacing="0" id="crm-event_receipt" style="font-family: Arial, Verdana, sans-serif; text-align: left;">
-
-  <!-- BEGIN HEADER -->
-  <!-- You can add table row(s) here with logo or other header elements -->
-  <!-- END HEADER -->
-
-  <!-- BEGIN CONTENT -->
-
-  <tr>
-   <td>
-  <p>Dear {contact.display_name},</p>
-
-    {if $event.confirm_email_text AND (not $isOnWaitlist AND not $isRequireApproval)}
-     <p>{$event.confirm_email_text|htmlize}</p>
-
-    {else}
-  <p>Thank you for your participation.  This letter is a confirmation that your registration has been received and your status has been updated to <strong>{if $isOnWaitlist}waitlisted{else}registered{/if}</strong> for the following:</p>
-
-    {/if}
-
-    <p>
-    {if $isOnWaitlist}
-     <p>{ts}You have been added to the WAIT LIST for this event.{/ts}</p>
-     {if $isPrimary}
-       <p>{ts}If space becomes available you will receive an email with a link to a web page where you can complete your registration.{/ts}</p>
-     {/if}
-    {elseif $isRequireApproval}
-     <p>{ts}Your registration has been submitted.{/ts}</p>
-     {if $isPrimary}
-      <p>{ts}Once your registration has been reviewed, you will receive an email with a link to a web page where you can complete the registration process.{/ts}</p>
-     {/if}
-    {elseif $is_pay_later && !$isAmountzero}
-     <p>{$pay_later_receipt}</p> {* FIXME: this might be text rather than HTML *}
-    {else}
-     <p>{ts}Please print this confirmation for your records.{/ts}</p>
-    {/if}
-
-   </td>
-  </tr>
-  <tr>
-   <td>
-    <table width="500" style="border: 1px solid #999; margin: 1em 0em 1em; border-collapse: collapse;">
-     <tr>
-      <th {$headerStyle}>
-       {ts}Event Information and Location{/ts}
-      </th>
-     </tr>
-     <tr>
-      <td colspan="2" {$valueStyle}>
-       {$event.event_title}<br />
-       {$event.event_start_date|date_format:"%A"} {$event.event_start_date|crmDate}{if $event.event_end_date}-{if $event.event_end_date|date_format:"%Y%m%d" == $event.event_start_date|date_format:"%Y%m%d"}{$event.event_end_date|crmDate:0:1}{else}{$event.event_end_date|date_format:"%A"} {$event.event_end_date|crmDate}{/if}{/if}
-      </td>
-     </tr>
-
-
-     {if $conference_sessions}
-      <tr>
-       <td colspan="2" {$labelStyle}>
-  {ts}Your schedule:{/ts}
-       </td>
-      </tr>
-      <tr>
-       <td colspan="2" {$valueStyle}>
-  {assign var='group_by_day' value='NA'}
-  {foreach from=$conference_sessions item=session}
-   {if $session.start_date|date_format:"%Y/%m/%d" != $group_by_day|date_format:"%Y/%m/%d"}
-    {assign var='group_by_day' value=$session.start_date}
-          <em>{$group_by_day|date_format:"%m/%d/%Y"}</em><br />
-   {/if}
-   {$session.start_date|crmDate:0:1}{if $session.end_date}-{$session.end_date|crmDate:0:1}{/if} {$session.title}<br />
-   {if $session.location}&nbsp;&nbsp;&nbsp;&nbsp;{$session.location}<br />{/if}
-  {/foreach}
-       </td>
-      </tr>
-     {/if}
-
-     {if $event.participant_role neq 'Attendee' and $defaultRole}
-      <tr>
-       <td {$labelStyle}>
-        {ts}Participant Role{/ts}
-       </td>
-       <td {$valueStyle}>
-        {$event.participant_role}
-       </td>
-      </tr>
-     {/if}
-
-     {if $isShowLocation}
-      <tr>
-       <td colspan="2" {$valueStyle}>
-        {if $location.address.1.name}
-         {$location.address.1.name}<br />
-        {/if}
-        {if $location.address.1.street_address}
-         {$location.address.1.street_address}<br />
-        {/if}
-        {if $location.address.1.supplemental_address_1}
-         {$location.address.1.supplemental_address_1}<br />
-        {/if}
-        {if $location.address.1.supplemental_address_2}
-         {$location.address.1.supplemental_address_2}<br />
-        {/if}
-        {if $location.address.1.city}
-         {$location.address.1.city}, {$location.address.1.state_province} {$location.address.1.postal_code}{if $location.address.1.postal_code_suffix} - {$location.address.1.postal_code_suffix}{/if}<br />
-        {/if}
-       </td>
-      </tr>
-     {/if}
-
-     {if $location.phone.1.phone || $location.email.1.email}
-      <tr>
-       <td colspan="2" {$labelStyle}>
-        {ts}Event Contacts:{/ts}
-       </td>
-      </tr>
-      {foreach from=$location.phone item=phone}
-       {if $phone.phone}
-        <tr>
-         <td {$labelStyle}>
-          {if $phone.phone_type}
-           {$phone.phone_type_display}
-          {else}
-           {ts}Phone{/ts}
-          {/if}
-         </td>
-         <td {$valueStyle}>
-          {$phone.phone}
-         </td>
-        </tr>
-       {/if}
-      {/foreach}
-      {foreach from=$location.email item=eventEmail}
-       {if $eventEmail.email}
-        <tr>
-         <td {$labelStyle}>
-          {ts}Email{/ts}
-         </td>
-         <td {$valueStyle}>
-          {$eventEmail.email}
-         </td>
-        </tr>
-       {/if}
-      {/foreach}
-     {/if}
-     <tr>
-      <td colspan="2" {$valueStyle}>
-       {capture assign=icalFeed}{crmURL p='civicrm/event/ical' q="reset=1&id=`$event.id`" h=0 a=1 fe=1}{/capture}
-       <a href="{$icalFeed}">{ts}Download iCalendar File{/ts}</a>
-      </td>
-     </tr>
-     {if $event.is_share}
-        <tr>
-            <td colspan="2" {$valueStyle}>
-                {capture assign=eventUrl}{crmURL p='civicrm/event/info' q="id=`$event.id`&reset=1" a=true fe=1 h=1}{/capture}
-                {include file="CRM/common/SocialNetwork.tpl" emailMode=true url=$eventUrl title=$event.title pageURL=$eventUrl}
-            </td>
-        </tr>
-     {/if}
-     {if $email}
-      <tr>
-       <th {$headerStyle}>
-        {ts}Registered Email{/ts}
-       </th>
-      </tr>
-      <tr>
-       <td colspan="2" {$valueStyle}>
-        {$email}
-       </td>
-      </tr>
-     {/if}
-    {if $payer.name}
-     <tr>
-       <th {$headerStyle}>
-         {ts}You were registered by:{/ts}
-       </th>
-     </tr>
-     <tr>
-       <td colspan="2" {$valueStyle}>
-   {$payer.name}
-       </td>
-     </tr>
-     {/if}
-     {if $event.is_monetary}
-
-      <tr>
-       <th {$headerStyle}>
-        {$event.fee_label}
-       </th>
-      </tr>
-
-      {if $lineItem}
-       {foreach from=$lineItem item=value key=priceset}
-        {if $value neq 'skip'}
-         {if $isPrimary}
-          {if $lineItem|@count GT 1} {* Header for multi participant registration cases. *}
-           <tr>
-            <td colspan="2" {$labelStyle}>
-             {ts 1=$priceset+1}Participant %1{/ts} {$part.$priceset.info}
-            </td>
-           </tr>
-          {/if}
-         {/if}
-         <tr>
-          <td colspan="2" {$valueStyle}>
-           <table> {* FIXME: style this table so that it looks like the text version (justification, etc.) *}
-            <tr>
-             <th>{ts}Item{/ts}</th>
-             <th>{ts}Qty{/ts}</th>
-             <th>{ts}Each{/ts}</th>
-             <th>{ts}Total{/ts}</th>
-       {if  $pricesetFieldsCount }<th>{ts}Total Participants{/ts}</th>{/if}
-            </tr>
-            {foreach from=$value item=line}
-             <tr>
-              <td>
-              {if $line.html_type eq 'Text'}{$line.label}{else}{$line.field_title} - {$line.label}{/if} {if $line.description}<div>{$line.description|truncate:30:"..."}</div>{/if}
-              </td>
-              <td>
-               {$line.qty}
-              </td>
-              <td>
-               {$line.unit_price|crmMoney}
-              </td>
-              <td>
-               {$line.line_total|crmMoney}
-              </td>
-        {if $pricesetFieldsCount }<td>{$line.participant_count}</td> {/if}
-             </tr>
-            {/foreach}
-           </table>
-          </td>
-         </tr>
-        {/if}
-       {/foreach}
-      {/if}
-
-      {if $amount && !$lineItem}
-       {foreach from=$amount item=amnt key=level}
-        <tr>
-         <td colspan="2" {$valueStyle}>
-          {$amnt.amount|crmMoney} {$amnt.label}
-         </td>
-        </tr>
-       {/foreach}
-      {/if}
-
-      {if $isPrimary}
-       <tr>
-        <td {$labelStyle}>
-         {ts}Total Amount{/ts}
-        </td>
-        <td {$valueStyle}>
-         {$totalAmount|crmMoney} {if $hookDiscount.message}({$hookDiscount.message}){/if}
-        </td>
-       </tr>
-       {if $pricesetFieldsCount }
-     <tr>
-       <td {$labelStyle}>
-      {ts}Total Participants{/ts}</td>
-      <td {$valueStyle}>
-      {assign var="count" value= 0}
-      {foreach from=$lineItem item=pcount}
-      {assign var="lineItemCount" value=0}
-      {if $pcount neq 'skip'}
-        {foreach from=$pcount item=p_count}
-        {assign var="lineItemCount" value=$lineItemCount+$p_count.participant_count}
-        {/foreach}
-      {if $lineItemCount < 1 }
-        {assign var="lineItemCount" value=1}
-      {/if}
-      {assign var="count" value=$count+$lineItemCount}
-      {/if}
-      {/foreach}
-     {$count}
-     </td> </tr>
-      {/if}
-       {if $is_pay_later}
-        <tr>
-         <td colspan="2" {$labelStyle}>
-          {$pay_later_receipt}
-         </td>
-        </tr>
-       {/if}
-
-       {if $register_date}
-        <tr>
-         <td {$labelStyle}>
-          {ts}Registration Date{/ts}
-         </td>
-         <td {$valueStyle}>
-          {$register_date|crmDate}
-         </td>
-        </tr>
-       {/if}
-
-       {if $receive_date}
-        <tr>
-         <td {$labelStyle}>
-          {ts}Transaction Date{/ts}
-         </td>
-         <td {$valueStyle}>
-          {$receive_date|crmDate}
-         </td>
-        </tr>
-       {/if}
-
-       {if $contributionTypeName}
-        <tr>
-         <td {$labelStyle}>
-          {ts}Contribution Type{/ts}
-         </td>
-         <td {$valueStyle}>
-          {$contributionTypeName}
-         </td>
-        </tr>
-       {/if}
-
-       {if $trxn_id}
-        <tr>
-         <td {$labelStyle}>
-          {ts}Transaction #{/ts}
-         </td>
-         <td {$valueStyle}>
-          {$trxn_id}
-         </td>
-        </tr>
-       {/if}
-
-       {if $paidBy}
-        <tr>
-         <td {$labelStyle}>
-          {ts}Paid By{/ts}
-         </td>
-         <td {$valueStyle}>
-         {$paidBy}
-         </td>
-        </tr>
-       {/if}
-
-       {if $checkNumber}
-        <tr>
-         <td {$labelStyle}>
-          {ts}Check Number{/ts}
-         </td>
-         <td {$valueStyle}>
-          {$checkNumber}
-         </td>
-        </tr>
-       {/if}
-
-       {if $contributeMode ne 'notify' and !$isAmountzero and !$is_pay_later and !$isOnWaitlist and !$isRequireApproval}
-        <tr>
-         <th {$headerStyle}>
-          {ts}Billing Name and Address{/ts}
-         </th>
-        </tr>
-        <tr>
-         <td colspan="2" {$valueStyle}>
-          {$billingName}<br />
-          {$address|nl2br}
-         </td>
-        </tr>
-       {/if}
-
-       {if $contributeMode eq 'direct' and !$isAmountzero and !$is_pay_later and !$isOnWaitlist and !$isRequireApproval}
-        <tr>
-         <th {$headerStyle}>
-          {ts}Credit Card Information{/ts}
-         </th>
-        </tr>
-        <tr>
-         <td colspan="2" {$valueStyle}>
-          {$credit_card_type}<br />
-          {$credit_card_number}<br />
-          {ts}Expires{/ts}: {$credit_card_exp_date|truncate:7:''|crmDate}
-         </td>
-        </tr>
-       {/if}
-
-      {/if}
-
-     {/if} {* End of conditional section for Paid events *}
-
-
-{if $customPre}
-{foreach from=$customPre item=customPr key=i}
-   <tr> <th {$headerStyle}>{$customPre_grouptitle.$i}</th></tr>
-   {foreach from=$customPr item=customValue key=customName}
-   {if ( $trackingFields and ! in_array( $customName, $trackingFields ) ) or ! $trackingFields}
-     <tr>
-         <td {$labelStyle}>{$customName}</td>
-         <td {$valueStyle}>{$customValue}</td>
-     </tr>
-   {/if}
-   {/foreach}
-{/foreach}
-{/if}
-
-{if $customPost}
-{foreach from=$customPost item=customPos key=j}
-   <tr> <th {$headerStyle}>{$customPost_grouptitle.$j}</th></tr>
-   {foreach from=$customPos item=customValue key=customName}
-   {if ( $trackingFields and ! in_array( $customName, $trackingFields ) ) or ! $trackingFields}
-     <tr>
-         <td {$labelStyle}>{$customName}</td>
-         <td {$valueStyle}>{$customValue}</td>
-     </tr>
-{/if}
-{/foreach}
-{/foreach}
-{/if}
-
-{if $customProfile}
-{foreach from=$customProfile.profile item=eachParticipant key=participantID}
-     <tr><th {$headerStyle}>{ts 1=$participantID+2}Participant Information - Participant %1{/ts} </th></tr>
-     {foreach from=$eachParticipant item=eachProfile key=pid}
-     <tr><th {$headerStyle}>{$customProfile.title.$pid}</th></tr>
-     {foreach from=$eachProfile item=val key=field}
-     <tr>{foreach from=$val item=v key=f}
-         <td {$labelStyle}>{$field}</td>
-         <td {$valueStyle}>{$v}</td>
-         {/foreach}
-     </tr>
-     {/foreach}
-{/foreach}
-{/foreach}
-{/if}
-
-    {if $customGroup}
-      {foreach from=$customGroup item=value key=customName}
-       <tr>
-        <th {$headerStyle}>
-         {$customName}
-        </th>
-       </tr>
-       {foreach from=$value item=v key=n}
-        <tr>
-         <td {$labelStyle}>
-          {$n}
-         </td>
-         <td {$valueStyle}>
-          {$v}
-         </td>
-        </tr>
-       {/foreach}
-      {/foreach}
-     {/if}
-
-    </table>
-   </td>
-  </tr>
- </table>
-</center>
-
-</body>
-</html>
diff --git a/civicrm/CRM/Upgrade/4.1.alpha1.msg_template/message_templates/event_online_receipt_text.tpl b/civicrm/CRM/Upgrade/4.1.alpha1.msg_template/message_templates/event_online_receipt_text.tpl
deleted file mode 100644
index e2f6777899..0000000000
--- a/civicrm/CRM/Upgrade/4.1.alpha1.msg_template/message_templates/event_online_receipt_text.tpl
+++ /dev/null
@@ -1,296 +0,0 @@
-Dear {contact.display_name},
-
-{if $event.confirm_email_text AND (not $isOnWaitlist AND not $isRequireApproval)}
-{$event.confirm_email_text}
-
-{else}
-Thank you for your participation.  This letter is a confirmation that your registration has been received and your status has been updated to {if $isOnWaitlist}waitlisted{else}registered{/if} for the following:
-
-{/if}
-
-{if $isOnWaitlist}
-==========================================================={if $pricesetFieldsCount }===================={/if}
-
-{ts}You have been added to the WAIT LIST for this event.{/ts}
-
-{if $isPrimary}
-{ts}If space becomes available you will receive an email with a link to a web page where you can complete your registration.{/ts}
-{/if}
-==========================================================={if $pricesetFieldsCount }===================={/if}
-
-{elseif $isRequireApproval}
-==========================================================={if $pricesetFieldsCount }===================={/if}
-
-{ts}Your registration has been submitted.{/ts}
-
-{if $isPrimary}
-{ts}Once your registration has been reviewed, you will receive an email with a link to a web page where you can complete the registration process.{/ts}
-
-{/if}
-==========================================================={if $pricesetFieldsCount }===================={/if}
-
-{elseif $is_pay_later && !$isAmountzero}
-
-==========================================================={if $pricesetFieldsCount }===================={/if}
-
-{$pay_later_receipt}
-==========================================================={if $pricesetFieldsCount }===================={/if}
-
-{else}
-
-{ts}Please print this confirmation for your records.{/ts}
-{/if}
-
-
-==========================================================={if $pricesetFieldsCount }===================={/if}
-
-{ts}Event Information and Location{/ts}
-
-==========================================================={if $pricesetFieldsCount }===================={/if}
-
-{$event.event_title}
-{$event.event_start_date|date_format:"%A"} {$event.event_start_date|crmDate}{if $event.event_end_date}-{if $event.event_end_date|date_format:"%Y%m%d" == $event.event_start_date|date_format:"%Y%m%d"}{$event.event_end_date|crmDate:0:1}{else}{$event.event_end_date|date_format:"%A"} {$event.event_end_date|crmDate}{/if}{/if}
-{if $conference_sessions}
-
-
-{ts}Your schedule:{/ts}
-{assign var='group_by_day' value='NA'}
-{foreach from=$conference_sessions item=session}
-{if $session.start_date|date_format:"%Y/%m/%d" != $group_by_day|date_format:"%Y/%m/%d"}
-{assign var='group_by_day' value=$session.start_date}
-
-{$group_by_day|date_format:"%m/%d/%Y"}
-
-
-{/if}
-{$session.start_date|crmDate:0:1}{if $session.end_date}-{$session.end_date|crmDate:0:1}{/if} {$session.title}
-{if $session.location}    {$session.location}{/if}
-{/foreach}
-{/if}
-
-{if $event.participant_role neq 'Attendee' and $defaultRole}
-{ts}Participant Role{/ts}: {$event.participant_role}
-{/if}
-
-{if $isShowLocation}
-{if $location.address.1.name}
-
-{$location.address.1.name}
-{/if}
-{if $location.address.1.street_address}{$location.address.1.street_address}
-{/if}
-{if $location.address.1.supplemental_address_1}{$location.address.1.supplemental_address_1}
-{/if}
-{if $location.address.1.supplemental_address_2}{$location.address.1.supplemental_address_2}
-{/if}
-{if $location.address.1.city}{$location.address.1.city}, {$location.address.1.state_province} {$location.address.1.postal_code}{if $location.address.1.postal_code_suffix} - {$location.address.1.postal_code_suffix}{/if}
-{/if}
-
-{/if}{*End of isShowLocation condition*}
-
-{if $location.phone.1.phone || $location.email.1.email}
-
-{ts}Event Contacts:{/ts}
-{foreach from=$location.phone item=phone}
-{if $phone.phone}
-
-{if $phone.phone_type}{$phone.phone_type_display}{else}{ts}Phone{/ts}{/if}: {$phone.phone}{/if}
-{/foreach}
-{foreach from=$location.email item=eventEmail}
-{if $eventEmail.email}
-
-{ts}Email{/ts}: {$eventEmail.email}{/if}{/foreach}
-{/if}
-
-{capture assign=icalFeed}{crmURL p='civicrm/event/ical' q="reset=1&id=`$event.id`" h=0 a=1 fe=1}{/capture}
-{ts}Download iCalendar File:{/ts} {$icalFeed}
-{if $email}
-
-==========================================================={if $pricesetFieldsCount }===================={/if}
-
-{ts}Registered Email{/ts}
-
-==========================================================={if $pricesetFieldsCount }===================={/if}
-
-{$email}
-{/if}
-
-{if $payer.name}
-You were registered by: {$payer.name}
-{/if}
-{if $event.is_monetary} {* This section for Paid events only.*}
-
-==========================================================={if $pricesetFieldsCount }===================={/if}
-
-{$event.fee_label}
-==========================================================={if $pricesetFieldsCount }===================={/if}
-
-{if $lineItem}{foreach from=$lineItem item=value key=priceset}
-
-{if $value neq 'skip'}
-{if $isPrimary}
-{if $lineItem|@count GT 1} {* Header for multi participant registration cases. *}
-{ts 1=$priceset+1}Participant %1{/ts} {$part.$priceset.info}
-
-{/if}
-{/if}
------------------------------------------------------------{if $pricesetFieldsCount }--------------------{/if}
-
-{capture assign=ts_item}{ts}Item{/ts}{/capture}
-{capture assign=ts_qty}{ts}Qty{/ts}{/capture}
-{capture assign=ts_each}{ts}Each{/ts}{/capture}
-{capture assign=ts_total}{ts}Total{/ts}{/capture}
-{if $pricesetFieldsCount }{capture assign=ts_participant_total}{ts}Total Participants{/ts}{/capture}{/if}
-{$ts_item|string_format:"%-30s"} {$ts_qty|string_format:"%5s"} {$ts_each|string_format:"%10s"} {$ts_total|string_format:"%10s"} {$ts_participant_total|string_format:"%10s"}
------------------------------------------------------------{if $pricesetFieldsCount }--------------------{/if}
-
-{foreach from=$value item=line}
-{if $pricesetFieldsCount }{capture assign=ts_participant_count}{$line.participant_count}{/capture}{/if}
-{capture assign=ts_item}{if $line.html_type eq 'Text'}{$line.label}{else}{$line.field_title} - {$line.label}{/if} {if $line.description} {$line.description}{/if}{/capture}{$ts_item|truncate:30:"..."|string_format:"%-30s"} {$line.qty|string_format:"%5s"} {$line.unit_price|crmMoney|string_format:"%10s"} {$line.line_total|crmMoney|string_format:"%10s"}{$ts_participant_count|string_format:"%10s"}
-{/foreach}
-{/if}
-{/foreach}
-{/if}
-{if $amount && !$lineItem}
-{foreach from=$amount item=amnt key=level}{$amnt.amount|crmMoney} {$amnt.label}
-{/foreach}
-{/if}
-{if $isPrimary }
-
-{ts}Total Amount{/ts}: {$totalAmount|crmMoney} {if $hookDiscount.message}({$hookDiscount.message}){/if}
-
-{if $pricesetFieldsCount }
-      {assign var="count" value= 0}
-      {foreach from=$lineItem item=pcount}
-      {assign var="lineItemCount" value=0}
-      {if $pcount neq 'skip'}
-        {foreach from=$pcount item=p_count}
-        {assign var="lineItemCount" value=$lineItemCount+$p_count.participant_count}
-        {/foreach}
-      {if $lineItemCount < 1 }
-        {assign var="lineItemCount" value=1}
-      {/if}
-      {assign var="count" value=$count+$lineItemCount}
-      {/if}
-      {/foreach}
-
-{ts}Total Participants{/ts}: {$count}
-{/if}
-
-{if $is_pay_later}
-
-==========================================================={if $pricesetFieldsCount }===================={/if}
-
-{$pay_later_receipt}
-==========================================================={if $pricesetFieldsCount }===================={/if}
-
-{/if}
-
-{if $register_date}
-{ts}Registration Date{/ts}: {$register_date|crmDate}
-{/if}
-{if $receive_date}
-{ts}Transaction Date{/ts}: {$receive_date|crmDate}
-{/if}
-{if $contributionTypeName}
-{ts}Contribution Type{/ts}: {$contributionTypeName}
-{/if}
-{if $trxn_id}
-{ts}Transaction #{/ts}: {$trxn_id}
-{/if}
-{if $paidBy}
-{ts}Paid By{/ts}: {$paidBy}
-{/if}
-{if $checkNumber}
-{ts}Check Number{/ts}: {$checkNumber}
-{/if}
-{if $contributeMode ne 'notify' and !$isAmountzero and !$is_pay_later and !$isOnWaitlist and !$isRequireApproval}
-
-==========================================================={if $pricesetFieldsCount }===================={/if}
-
-{ts}Billing Name and Address{/ts}
-
-==========================================================={if $pricesetFieldsCount }===================={/if}
-
-{$billingName}
-{$address}
-{/if}
-
-{if $contributeMode eq 'direct' and !$isAmountzero and !$is_pay_later and !$isOnWaitlist and !$isRequireApproval}
-==========================================================={if $pricesetFieldsCount }===================={/if}
-
-{ts}Credit Card Information{/ts}
-
-==========================================================={if $pricesetFieldsCount }===================={/if}
-
-{$credit_card_type}
-{$credit_card_number}
-{ts}Expires{/ts}: {$credit_card_exp_date|truncate:7:''|crmDate}
-{/if}
-{/if}
-{/if} {* End of conditional section for Paid events *}
-
-{if $customPre}
-{foreach from=$customPre item=customPr key=i}
-==========================================================={if $pricesetFieldsCount }===================={/if}
-
-{$customPre_grouptitle.$i}
-==========================================================={if $pricesetFieldsCount }===================={/if}
-
-{foreach from=$customPr item=customValue key=customName}
-{if ( $trackingFields and ! in_array( $customName, $trackingFields ) ) or ! $trackingFields}
- {$customName}: {$customValue}
-{/if}
-{/foreach}
-{/foreach}
-{/if}
-
-{if $customPost}
-{foreach from=$customPost item=customPos key=j}
-==========================================================={if $pricesetFieldsCount }===================={/if}
-
-{$customPost_grouptitle.$j}
-==========================================================={if $pricesetFieldsCount }===================={/if}
-
-{foreach from=$customPos item=customValue key=customName}
-{if ( $trackingFields and ! in_array( $customName, $trackingFields ) ) or ! $trackingFields}
- {$customName}: {$customValue}
-{/if}
-{/foreach}
-{/foreach}
-{/if}
-{if $customProfile}
-
-{foreach from=$customProfile.profile item=eachParticipant key=participantID}
-==========================================================={if $pricesetFieldsCount }===================={/if}
-
-{ts 1=$participantID+2}Participant Information - Participant %1{/ts}
-
-==========================================================={if $pricesetFieldsCount }===================={/if}
-
-{foreach from=$eachParticipant item=eachProfile key=pid}
-----------------------------------------------------------{if $pricesetFieldsCount }--------------------{/if}
-
-{$customProfile.title.$pid}
-----------------------------------------------------------{if $pricesetFieldsCount }--------------------{/if}
-
-{foreach from=$eachProfile item=val key=field}
-{foreach from=$val item=v key=f}
-{$field}: {$v}
-{/foreach}
-{/foreach}
-{/foreach}
-{/foreach}
-{/if}
-{if $customGroup}
-{foreach from=$customGroup item=value key=customName}
-=========================================================={if $pricesetFieldsCount }===================={/if}
-
-{$customName}
-=========================================================={if $pricesetFieldsCount }===================={/if}
-
-{foreach from=$value item=v key=n}
-{$n}: {$v}
-{/foreach}
-{/foreach}
-{/if}
diff --git a/civicrm/CRM/Upgrade/Form.php b/civicrm/CRM/Upgrade/Form.php
index e2246c0e04..c6a3cca9a9 100644
--- a/civicrm/CRM/Upgrade/Form.php
+++ b/civicrm/CRM/Upgrade/Form.php
@@ -45,7 +45,7 @@ class CRM_Upgrade_Form extends CRM_Core_Form {
   /**
    * Minimum previous CiviCRM version we can directly upgrade from
    */
-  const MINIMUM_UPGRADABLE_VERSION = '4.0.8';
+  const MINIMUM_UPGRADABLE_VERSION = '4.1.3';
 
   /**
    * Minimum php version required to run (equal to or lower than the minimum install version)
@@ -336,9 +336,6 @@ SET    version = '$version'
     $sqlFilePattern = '/^((\d{1,2}\.\d{1,2})\.(\d{1,2}\.)?(\d{1,2}|\w{4,7}))\.(my)?sql(\.tpl)?$/i';
     foreach ($sqlFiles as $file) {
       if (preg_match($sqlFilePattern, $file, $matches)) {
-        if ($matches[2] == '4.0') {
-          CRM_Core_Error::fatal("4.0.x upgrade files shouldn't exist. Contact Lobo to discuss this. This is related to the issue CRM-7731.");
-        }
         if (!in_array($matches[1], $revList)) {
           $revList[] = $matches[1];
         }
@@ -533,12 +530,6 @@ SET    version = '$version'
   public static function buildQueue($currentVer, $latestVer, $postUpgradeMessageFile) {
     $upgrade = new CRM_Upgrade_Form();
 
-    // hack to make 4.0.x (D7,J1.6) codebase go through 3.4.x (d6, J1.5) upgrade files,
-    // since schema wise they are same
-    if (CRM_Upgrade_Form::getRevisionPart($currentVer) == '4.0') {
-      $currentVer = str_replace('4.0.', '3.4.', $currentVer);
-    }
-
     // Ensure that queue can be created
     if (!CRM_Queue_BAO_QueueItem::findCreateTable()) {
       CRM_Core_Error::fatal(ts('Failed to find or create queueing table'));
@@ -747,6 +738,9 @@ SET    version = '$version'
     $config = CRM_Core_Config::singleton();
     $config->cleanupCaches(1);
 
+    $versionCheck = new CRM_Utils_VersionCheck();
+    $versionCheck->flushCache();
+
     // Rebuild all triggers and re-enable logging if needed
     $logging = new CRM_Logging_Schema();
     $logging->fixSchemaDifferences();
diff --git a/civicrm/CRM/Upgrade/Incremental/php/FiveOne.php b/civicrm/CRM/Upgrade/Incremental/php/FiveOne.php
new file mode 100644
index 0000000000..cb3d6f92d8
--- /dev/null
+++ b/civicrm/CRM/Upgrade/Incremental/php/FiveOne.php
@@ -0,0 +1,87 @@
+<?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.                                       |
+ |                                                                    |
+ | 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 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 FiveOne */
+class CRM_Upgrade_Incremental_php_FiveOne extends CRM_Upgrade_Incremental_Base {
+
+  /**
+   * 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.4.alpha1', '4.4.beta3', '4.4.0'.
+   * @param null $currentVer
+   */
+  public function setPreUpgradeMessage(&$preUpgradeMessage, $rev, $currentVer = NULL) {
+    // Example: Generate a pre-upgrade message.
+    // if ($rev == '5.12.34') {
+    //   $preUpgradeMessage .= '<p>' . ts('A new permission has been added called %1 This Permission is now used to control access to the Manage Tags screen', array(1 => 'manage tags')) . '</p>';
+    // }
+  }
+
+  /**
+   * 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) {
+    // Example: Generate a post-upgrade message.
+    // if ($rev == '5.12.34') {
+    //   $postUpgradeMessage .= '<br /><br />' . ts("By default, CiviCRM now disables the ability to import directly from SQL. To use this feature, you must explicitly grant permission 'import SQL datasource'.");
+    // }
+  }
+
+  /*
+   * Important! All upgrade functions MUST add a 'runSql' task.
+   * Uncomment and use the following template for a new upgrade version
+   * (change the x in the function name):
+   */
+
+  //  /**
+  //   * Upgrade function.
+  //   *
+  //   * @param string $rev
+  //   */
+  //  public function upgrade_5_0_x($rev) {
+  //    $this->addTask(ts('Upgrade DB to %1: SQL', array(1 => $rev)), 'runSql', $rev);
+  //    $this->addTask('Do the foo change', 'taskFoo', ...);
+  //    // Additional tasks here...
+  //    // Note: do not use ts() in the addTask description because it adds unnecessary strings to transifex.
+  //    // The above is an exception because 'Upgrade DB to %1: SQL' is generic & reusable.
+  //  }
+
+  // public static function taskFoo(CRM_Queue_TaskContext $ctx, ...) {
+  //   return TRUE;
+  // }
+
+}
diff --git a/civicrm/CRM/Upgrade/Incremental/php/FourOne.php b/civicrm/CRM/Upgrade/Incremental/php/FourOne.php
deleted file mode 100644
index 2fe81eedf2..0000000000
--- a/civicrm/CRM/Upgrade/Incremental/php/FourOne.php
+++ /dev/null
@@ -1,430 +0,0 @@
-<?php
-/*
- +--------------------------------------------------------------------+
- | CiviCRM version 4.7                                                |
- +--------------------------------------------------------------------+
- | Copyright CiviCRM LLC (c) 2004-2018                                |
- +--------------------------------------------------------------------+
- | 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-2018
- * $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";
-  }
-
-}
diff --git a/civicrm/CRM/Upgrade/Incremental/sql/4.1.0.mysql.tpl b/civicrm/CRM/Upgrade/Incremental/sql/4.1.0.mysql.tpl
deleted file mode 100644
index 1210bad37b..0000000000
--- a/civicrm/CRM/Upgrade/Incremental/sql/4.1.0.mysql.tpl
+++ /dev/null
@@ -1,8 +0,0 @@
-
-{if $multilingual}
-  {foreach from=$locales item=locale}
-      ALTER TABLE civicrm_pcp_block ADD link_text_{$locale} varchar(255);
-      UPDATE civicrm_pcp_block SET link_text_{$locale} = link_text;
-  {/foreach}
-  ALTER TABLE civicrm_pcp_block DROP link_text;
-{/if}
\ No newline at end of file
diff --git a/civicrm/CRM/Upgrade/Incremental/sql/4.1.1.mysql.tpl b/civicrm/CRM/Upgrade/Incremental/sql/4.1.1.mysql.tpl
deleted file mode 100644
index 50af4a5df0..0000000000
--- a/civicrm/CRM/Upgrade/Incremental/sql/4.1.1.mysql.tpl
+++ /dev/null
@@ -1,20 +0,0 @@
--- CRM-9699
-
-{if $addDedupeEmail}
-    ALTER TABLE `civicrm_mailing` ADD `dedupe_email` TINYINT( 4 ) NULL DEFAULT '0' COMMENT 'Remove duplicate emails?';
-{/if}
-
-{if $worldRegionEmpty}
-    INSERT INTO `civicrm_worldregion` (`id`, `name`) VALUES
-    (1, 'Europe and Central Asia'),
-    (2, 'America South, Central, North and Caribbean'),
-    (3, 'Middle East and North Africa'),
-    (4, 'Asia-Pacific'),
-    (5, 'Africa West, East, Central and Southern'),
-    (99, 'unassigned');
-{/if}
-
-SELECT @region_id   := max(id) from civicrm_worldregion where name = "Africa West, East, Central and Southern";
-
-INSERT INTO `civicrm_country` (`name`, `iso_code`, `country_code`, `idd_prefix`, `ndd_prefix`, `region_id`, `is_province_abbreviated`, `address_format_id`) VALUES ('South Sudan', 'SS', NULL, NULL, NULL, @region_id, 0, NULL) ON DUPLICATE KEY UPDATE iso_code='SS';
-
diff --git a/civicrm/CRM/Upgrade/Incremental/sql/4.1.2.mysql.tpl b/civicrm/CRM/Upgrade/Incremental/sql/4.1.2.mysql.tpl
deleted file mode 100644
index 1a2923e247..0000000000
--- a/civicrm/CRM/Upgrade/Incremental/sql/4.1.2.mysql.tpl
+++ /dev/null
@@ -1,22 +0,0 @@
--- CRM-9795 (fix duplicate option values)
-
-SELECT @option_group_id_act := max(id) from civicrm_option_group where name = 'activity_type';
-SELECT @maxValue            := MAX(ROUND(value)) FROM civicrm_option_value WHERE option_group_id = @option_group_id_act;
-SELECT @clientCaseValue     := value FROM civicrm_option_value WHERE name = 'Add Client To Case' AND option_group_id = @option_group_id_act;
-
-UPDATE civicrm_option_value SET value = @maxValue + 1 WHERE name = 'Add Client To Case' AND option_group_id = @option_group_id_act;
-
-UPDATE civicrm_activity
-INNER JOIN civicrm_case_activity ON civicrm_activity.id = civicrm_case_activity.activity_id
-SET   civicrm_activity.activity_type_id = @maxValue + 1
-WHERE civicrm_activity.activity_type_id = @clientCaseValue;
-
--- CRM-9868 Force disable jobs that should only be run manually
-UPDATE  civicrm_job
-SET     is_active = 0
-WHERE   api_action IN ('process_membership_reminder_date','update_greeting');
-
-UPDATE  civicrm_job
-SET     description = '{ts escape="sql"}Sets membership renewal reminder dates for current membership records where reminder date is null. This job should never be run automatically as it will cause members to get renewal reminders repeatedly.{/ts}'
-WHERE   api_action = 'process_membership_reminder_date';
-
diff --git a/civicrm/CRM/Upgrade/Incremental/sql/4.1.3.mysql.tpl b/civicrm/CRM/Upgrade/Incremental/sql/4.1.3.mysql.tpl
deleted file mode 100644
index ff5c018be5..0000000000
--- a/civicrm/CRM/Upgrade/Incremental/sql/4.1.3.mysql.tpl
+++ /dev/null
@@ -1,5 +0,0 @@
--- CRM-10264
-INSERT INTO `civicrm_job`
-    ( domain_id, run_frequency, last_run, name, description, api_prefix, api_entity, api_action, parameters, is_active )
-VALUES
-    ( {$domainID}, 'Hourly', NULL, '{ts escape="sql" skip="true"}Clean-up Temporary Data and Files{/ts}','{ts escape="sql" skip="true"}Removes temporary data and files, and clears old data from cache tables. Recommend running this job every hour to help prevent database and file system bloat.{/ts}','civicrm_api3', 'job', 'cleanup', NULL, 0);
diff --git a/civicrm/CRM/Upgrade/Incremental/sql/4.1.alpha1.mysql.tpl b/civicrm/CRM/Upgrade/Incremental/sql/4.1.alpha1.mysql.tpl
deleted file mode 100644
index 377e551362..0000000000
--- a/civicrm/CRM/Upgrade/Incremental/sql/4.1.alpha1.mysql.tpl
+++ /dev/null
@@ -1,529 +0,0 @@
-{include file='../CRM/Upgrade/4.1.alpha1.msg_template/civicrm_msg_template.tpl'}
-
--- get domain id
-SELECT  @domainID := min(id) FROM civicrm_domain;
-
--- CRM-8356
--- Add filter column 'filter' for 'civicrm_custom_field'
-ALTER TABLE `civicrm_custom_field` ADD `filter` VARCHAR(255) NULL COMMENT 'Stores Contact Get API params contact reference custom fields. May be used for other filters in the future.';
-
--- CRM-8062
-ALTER TABLE `civicrm_subscription_history` CHANGE `status` `status` ENUM( 'Added', 'Removed', 'Pending', 'Deleted' ) CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT NULL COMMENT 'The state of the contact within the group';
-
--- CRM-8510
-ALTER TABLE civicrm_currency
-ADD UNIQUE INDEX UI_name ( name );
-
--- CRM-8616
-DELETE FROM civicrm_currency WHERE name = 'EEK';
-
--- CRM-8769
-INSERT IGNORE INTO civicrm_state_province
-  (`name`, `abbreviation`, `country_id`)
-VALUES
-  ('Metropolitan Manila' , 'MNL', '1170');
-
--- CRM-8902
-    UPDATE civicrm_navigation SET permission ='add cases,access all cases and activities', permission_operator = 'OR'
-    WHERE civicrm_navigation.name= 'New Case';
-
--- CRM-8780
-
--- add the settings table
- CREATE TABLE `civicrm_setting` (
-  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
-  `group_name` varchar(64) COLLATE utf8_unicode_ci NOT NULL COMMENT 'group name for setting element, useful in caching setting elements',
-  `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'Unique name for setting',
-  `value` text COLLATE utf8_unicode_ci COMMENT 'data associated with this group / name combo',
-  `domain_id` int(10) unsigned NOT NULL COMMENT 'Which Domain is this menu item for',
-  `contact_id` int(10) unsigned DEFAULT NULL COMMENT 'FK to Contact ID if the setting is localized to a contact',
-  `is_domain` tinyint(4) DEFAULT NULL COMMENT 'Is this setting a contact specific or site wide setting?',
-  `component_id` int(10) unsigned DEFAULT NULL COMMENT 'Component that this menu item belongs to',
-  `created_date` datetime DEFAULT NULL COMMENT 'When was the setting created',
-  `created_id` int(10) unsigned DEFAULT NULL COMMENT 'FK to civicrm_contact, who created this setting',
-  PRIMARY KEY (`id`),
-  KEY `index_group_name` (`group_name`,`name`),
-  KEY `FK_civicrm_setting_domain_id` (`domain_id`),
-  KEY `FK_civicrm_setting_contact_id` (`contact_id`),
-  KEY `FK_civicrm_setting_component_id` (`component_id`),
-  KEY `FK_civicrm_setting_created_id` (`created_id`),
-  CONSTRAINT `FK_civicrm_setting_domain_id` FOREIGN KEY (`domain_id`) REFERENCES `civicrm_domain` (`id`) ON DELETE CASCADE,
-  CONSTRAINT `FK_civicrm_setting_contact_id` FOREIGN KEY (`contact_id`) REFERENCES `civicrm_contact` (`id`) ON DELETE CASCADE,
-  CONSTRAINT `FK_civicrm_setting_component_id` FOREIGN KEY (`component_id`) REFERENCES `civicrm_component` (`id`),
-  CONSTRAINT `FK_civicrm_setting_created_id` FOREIGN KEY (`created_id`) REFERENCES `civicrm_contact` (`id`) ON DELETE SET NULL
-) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;
-
--- CRM-8508
-    SELECT @caseCompId := id FROM `civicrm_component` where `name` like 'CiviCase';
-
-    SELECT @option_group_id_activity_type := max(id) from civicrm_option_group where name = 'activity_type';
-    SELECT @max_val    := MAX(ROUND(op.value)) FROM civicrm_option_value op WHERE op.option_group_id  = @option_group_id_activity_type;
-    SELECT @max_wt     := max(weight) from civicrm_option_value where option_group_id=@option_group_id_activity_type;
-
-    INSERT INTO civicrm_option_value
-      (option_group_id,                {localize field='label'}label{/localize}, {localize field='description'}description{/localize}, value,                           name,               weight,                        filter, component_id)
-    VALUES
-        (@option_group_id_activity_type, {localize}'Change Custom Data'{/localize},{localize}''{/localize},                              (SELECT @max_val := @max_val+1), 'Change Custom Data', (SELECT @max_wt := @max_wt+1), 0, @caseCompId);
-
--- CRM-8739
-    Update civicrm_menu set title = 'Cleanup Caches and Update Paths' where path = 'civicrm/admin/setting/updateConfigBackend';
-
--- CRM-8855
-    SELECT @option_group_id_udOpt := max(id) from civicrm_option_group where name = 'user_dashboard_options';
-    SELECT @max_val    := MAX(ROUND(op.value)) FROM civicrm_option_value op WHERE op.option_group_id  = @option_group_id_udOpt;
-    SELECT @max_wt     := max(weight) from civicrm_option_value where option_group_id=@option_group_id_udOpt;
-
-    INSERT INTO civicrm_option_value
-      (option_group_id,                {localize field='label'}label{/localize}, value, name, weight, filter, is_default, component_id)
-    VALUES
-        (@option_group_id_udOpt, {localize}'Assigned Activities'{/localize},  (SELECT @max_val := @max_val+1), 'Assigned Activities', (SELECT @max_wt := @max_wt+1), 0, NULL, NULL);
-
--- CRM-8737
-   ALTER TABLE `civicrm_event` ADD `is_share` TINYINT( 4 ) NULL DEFAULT '1' COMMENT 'Can people share the event through social media?';
-   ALTER TABLE `civicrm_contribution_page` ADD `is_share` TINYINT(4) NULL DEFAULT '1' COMMENT 'Can people share the contribution page through social media?';
-
--- CRM-8357
-ALTER TABLE `civicrm_contact` CHANGE `contact_sub_type` `contact_sub_type` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT NULL COMMENT 'May be used to over-ride contact view and edit templates.';
-
-UPDATE civicrm_contact SET contact_sub_type = CONCAT('', contact_sub_type, '');
-
--- CRM-6811
-INSERT INTO `civicrm_dashboard`
-    ( `domain_id`, {localize field='label'}`label`{/localize}, `url`, `permission`, `permission_operator`, `column_no`, `is_minimized`, `is_active`, `weight`, `fullscreen_url`, `is_fullscreen`, `is_reserved`)
-    VALUES
-    ( @domainID, {localize}'Case Dashboard Dashlet'{/localize}, 'civicrm/dashlet/casedashboard&reset=1&snippet=4', 'access CiviCase', NULL , 0, 0, 1, 4, 'civicrm/dashlet/casedashboard&reset=1&snippet=4&context=dashletFullscreen', 1, 1);
-
--- CRM-9059 Admin menu rebuild
-SELECT @domainID := min(id) FROM civicrm_domain;
-SELECT @adminlastID := id   FROM civicrm_navigation where name = 'Administer' AND domain_id = @domainID;
-SELECT @customizeOld := id  FROM civicrm_navigation where name = 'Customize' AND domain_id = @domainID;
-SELECT @configureOld := id  FROM civicrm_navigation where name = 'Configure' AND domain_id = @domainID;
-SELECT @globalOld := id     FROM civicrm_navigation where name = 'Global Settings' AND domain_id = @domainID;
-SELECT @manageOld := id     FROM civicrm_navigation where name = 'Manage' AND domain_id = @domainID;
-SELECT @optionsOld := id    FROM civicrm_navigation where name = 'Option Lists' AND domain_id = @domainID;
-SELECT @customizeOld := id  FROM civicrm_navigation where name = 'Customize' AND domain_id = @domainID;
-
-DELETE from civicrm_navigation WHERE parent_id = @globalOld;
-DELETE from civicrm_navigation WHERE parent_id IN (@customizeOld, @configureOld, @manageOld, @optionsOld);
-DELETE from civicrm_navigation WHERE id IN (@customizeOld, @configureOld, @manageOld, @optionsOld);
-UPDATE civicrm_navigation SET weight = 9 WHERE name = 'CiviCampaign' AND parent_id = @adminlastID;
-UPDATE civicrm_navigation SET weight = 10 WHERE name = 'CiviCase' AND parent_id = @adminlastID;
-UPDATE civicrm_navigation SET weight = 11 WHERE name = 'CiviContribute' AND parent_id = @adminlastID;
-UPDATE civicrm_navigation SET weight = 12 WHERE name = 'CiviEvent' AND parent_id = @adminlastID;
-UPDATE civicrm_navigation SET weight = 13 WHERE name = 'CiviGrant' AND parent_id = @adminlastID;
-UPDATE civicrm_navigation SET weight = 14 WHERE name = 'CiviMail' AND parent_id = @adminlastID;
-UPDATE civicrm_navigation SET weight = 15 WHERE name = 'CiviMember' AND parent_id = @adminlastID;
-UPDATE civicrm_navigation SET weight = 16 WHERE name = 'CiviReport' AND parent_id = @adminlastID;
-
-DELETE FROM civicrm_navigation WHERE name = 'Administration Console';
-
-INSERT INTO civicrm_navigation
-    ( domain_id, url, label, name, permission, permission_operator, parent_id, is_active, has_separator, weight )
-VALUES
-    ( @domainID, 'civicrm/admin&reset=1', '{ts escape="sql" skip="true"}Administration Console{/ts}', 'Administration Console', 'administer CiviCRM', '', @adminlastID, '1', NULL, 1 );
-
-SET @adminConsolelastID:=LAST_INSERT_ID();
-INSERT INTO civicrm_navigation
-    ( domain_id, url, label, name, permission, permission_operator, parent_id, is_active, has_separator, weight )
-VALUES
-    ( @domainID, 'civicrm/admin/configtask&reset=1', '{ts escape="sql" skip="true"}Configuration Checklist{/ts}', 'Configuration Checklist', 'administer CiviCRM', '', @adminConsolelastID, '1', NULL, 1 );
-
-INSERT INTO civicrm_navigation
-    ( domain_id, url, label, name, permission, permission_operator, parent_id, is_active, has_separator, weight )
-VALUES
-    ( @domainID, NULL, '{ts escape="sql" skip="true"}Customize Data and Screens{/ts}', 'Customize Data and Screens', 'administer CiviCRM', '', @adminlastID, '1', NULL, 3 );
-
-SET @CustomizelastID:=LAST_INSERT_ID();
-INSERT INTO civicrm_navigation
-    ( domain_id, url, label, name, permission, permission_operator, parent_id, is_active, has_separator, weight )
-VALUES
-    ( @domainID, 'civicrm/admin/custom/group&reset=1',      '{ts escape="sql" skip="true"}Custom Fields{/ts}', 'Custom Fields',                             'administer CiviCRM', '',   @CustomizelastID, '1', NULL, 1 ),
-    ( @domainID, 'civicrm/admin/uf/group&reset=1',          '{ts escape="sql" skip="true"}Profiles{/ts}', 'Profiles',                                       'administer CiviCRM', '',   @CustomizelastID, '1', NULL, 2 ),
-    ( @domainID, 'civicrm/admin/tag&reset=1',               '{ts escape="sql" skip="true"}Tags (Categories){/ts}', 'Tags (Categories)',                     'administer CiviCRM', '',   @CustomizelastID, '1', NULL, 3 ),
-    ( @domainID, 'civicrm/admin/options/activity_type&reset=1&group=activity_type', '{ts escape="sql" skip="true"}Activity Types{/ts}', 'Activity Types',   'administer CiviCRM', '',   @CustomizelastID, '1', NULL, 4 ),
-    ( @domainID, 'civicrm/admin/reltype&reset=1',           '{ts escape="sql" skip="true"}Relationship Types{/ts}', 'Relationship Types',                   'administer CiviCRM', '',   @CustomizelastID, '1', NULL, 5 ),
-    ( @domainID, 'civicrm/admin/options/subtype&reset=1',   '{ts escape="sql" skip="true"}Contact Types{/ts}','Contact Types',                              'administer CiviCRM', '',   @CustomizelastID, '1', NULL, 6 ),
-    ( @domainID, 'civicrm/admin/setting/preferences/display&reset=1',   '{ts escape="sql" skip="true"}Display Preferences{/ts}', 'Display Preferences',     'administer CiviCRM', '',   @CustomizelastID, '1', NULL, 9 ),
-    ( @domainID, 'civicrm/admin/setting/search&reset=1',    '{ts escape="sql" skip="true"}Search Preferences{/ts}',    'Search Preferences',                'administer CiviCRM', '',   @CustomizelastID, '1', NULL, 10 ),
-    ( @domainID, 'civicrm/admin/menu&reset=1',              '{ts escape="sql" skip="true"}Navigation Menu{/ts}', 'Navigation Menu',                         'administer CiviCRM', '',   @CustomizelastID, '1', NULL, 11 ),
-    ( @domainID, 'civicrm/admin/options/wordreplacements&reset=1','{ts escape="sql" skip="true"}Word Replacements{/ts}','Word Replacements',                'administer CiviCRM', '',   @CustomizelastID, '1', NULL, 12 ),
-    ( @domainID, 'civicrm/admin/options/custom_search&reset=1&group=custom_search', '{ts escape="sql" skip="true"}Manage Custom Searches{/ts}', 'Manage Custom Searches', 'administer CiviCRM', '', @CustomizelastID, '1', NULL, 13 ),
-    ( @domainID, 'civicrm/admin/extensions&reset=1',        '{ts escape="sql" skip="true"}Manage Extensions{/ts}', 'Manage Extensions', 'administer CiviCRM', '', @CustomizelastID, '1', NULL, 14 );
-
-INSERT INTO civicrm_navigation
-    ( domain_id, url, label, name, permission, permission_operator, parent_id, is_active, has_separator, weight )
-VALUES
-    ( @domainID, NULL, '{ts escape="sql" skip="true"}Dropdown Options{/ts}', 'Dropdown Options', 'administer CiviCRM', '', @CustomizelastID, '1', NULL, 8 );
-
-SET @optionListlastID:=LAST_INSERT_ID();
-INSERT INTO civicrm_navigation
-    ( domain_id, url, label, name, permission, permission_operator, parent_id, is_active, has_separator, weight )
-VALUES
-    ( @domainID, 'civicrm/admin/options/gender&reset=1&group=gender',                                                  '{ts escape="sql" skip="true"}Gender Options{/ts}',         'Gender Options',                           'administer CiviCRM', '',   @optionListlastID, '1', NULL,  1 ),
-    ( @domainID, 'civicrm/admin/options/individual_prefix&group=individual_prefix&reset=1',                            '{ts escape="sql" skip="true"}Individual Prefixes (Ms, Mr...){/ts}', 'Individual Prefixes (Ms, Mr...)', 'administer CiviCRM', '',   @optionListlastID, '1', NULL,  2 ),
-    ( @domainID, 'civicrm/admin/options/individual_suffix&group=individual_suffix&reset=1',                            '{ts escape="sql" skip="true"}Individual Suffixes (Jr, Sr...){/ts}', 'Individual Suffixes (Jr, Sr...)', 'administer CiviCRM', '',   @optionListlastID, '1', NULL,  3 ),
-    ( @domainID, 'civicrm/admin/options/instant_messenger_service&group=instant_messenger_service&reset=1',            '{ts escape="sql" skip="true"}Instant Messenger Services{/ts}',     'Instant Messenger Services',       'administer CiviCRM', '',   @optionListlastID, '1', NULL,  4 ),
-    ( @domainID, 'civicrm/admin/locationType&reset=1',                                                                 '{ts escape="sql" skip="true"}Location Types (Home, Work...){/ts}', 'Location Types (Home, Work...)',   'administer CiviCRM', '',   @optionListlastID, '1', NULL,  5 ),
-    ( @domainID, 'civicrm/admin/options/mobile_provider&group=mobile_provider&reset=1',                                '{ts escape="sql" skip="true"}Mobile Phone Providers{/ts}', 'Mobile Phone Providers',                   'administer CiviCRM', '',   @optionListlastID, '1', NULL,  6 ),
-    ( @domainID, 'civicrm/admin/options/phone_type&group=phone_type&reset=1',                                          '{ts escape="sql" skip="true"}Phone Types{/ts}',            'Phone Types',                              'administer CiviCRM', '',   @optionListlastID, '1', NULL,  7 ),
-    ( @domainID, 'civicrm/admin/options/website_type&group=website_type&reset=1',                                      '{ts escape="sql" skip="true"}Website Types{/ts}',          'Website Types',                            'administer CiviCRM', '',   @optionListlastID, '1', NULL,  8 );
-
-INSERT INTO civicrm_navigation
-    ( domain_id, url, label, name, permission, permission_operator, parent_id, is_active, has_separator, weight )
-VALUES
-    ( @domainID, NULL, '{ts escape="sql" skip="true"}Communications{/ts}', 'Communications', 'administer CiviCRM', '', @adminlastID, '1', NULL, 4 );
-
-SET @communicationslastID:=LAST_INSERT_ID();
-INSERT INTO civicrm_navigation
-    ( domain_id, url, label, name, permission, permission_operator, parent_id, is_active, has_separator, weight )
-VALUES
-    ( @domainID, 'civicrm/admin/domain&action=update&reset=1',         '{ts escape="sql" skip="true"}Organization Address and Contact Info{/ts}', 'Organization Address and Contact Info',                                      'administer CiviCRM', '', @communicationslastID, '1', NULL, 1 ),
-    ( @domainID, 'civicrm/admin/options/from_email_address&group=from_email_address&reset=1', '{ts escape="sql" skip="true"}FROM Email Addresses{/ts}', 'FROM Email Addresses',                                                 'administer CiviCRM', '', @communicationslastID, '1', NULL, 2 ),
-    ( @domainID, 'civicrm/admin/messageTemplates&reset=1',             '{ts escape="sql" skip="true"}Message Templates{/ts}',      'Message Templates',                                                                         'administer CiviCRM', '', @communicationslastID, '1', NULL, 3 ),
-    ( @domainID, 'civicrm/admin/scheduleReminders&reset=1',              '{ts escape="sql" skip="true"}Schedule Reminders{/ts}',    'Schedule Reminders',                                                                       'administer CiviCRM', '', @communicationslastID, '1', NULL, 4 ),
-    ( @domainID, 'civicrm/admin/options/preferred_communication_method&group=preferred_communication_method&reset=1',  '{ts escape="sql" skip="true"}Preferred Communication Methods{/ts}', 'Preferred Communication Methods',  'administer CiviCRM', '', @communicationslastID, '1', NULL, 5 ),
-    ( @domainID, 'civicrm/admin/labelFormats&reset=1',                                  '{ts escape="sql" skip="true"}Label Formats{/ts}',                 'Label Formats',                                                     'administer CiviCRM', '', @communicationslastID, '1', NULL, 6 ),
-    ( @domainID, 'civicrm/admin/pdfFormats&reset=1',                                    '{ts escape="sql" skip="true"}Print Page (PDF) Formats{/ts}',      'Print Page (PDF) Formats',                                          'administer CiviCRM', '', @communicationslastID, '1', NULL, 7 ),
-    ( @domainID, 'civicrm/admin/options/email_greeting&group=email_greeting&reset=1',   '{ts escape="sql" skip="true"}Email Greeting Formats{/ts}',        'Email Greeting Formats',                                            'administer CiviCRM', '', @communicationslastID, '1', NULL, 8 ),
-    ( @domainID, 'civicrm/admin/options/postal_greeting&group=postal_greeting&reset=1', '{ts escape="sql" skip="true"}Postal Greeting Formats{/ts}',       'Postal Greeting Formats',                                           'administer CiviCRM', '', @communicationslastID, '1', NULL, 9 ),
-    ( @domainID, 'civicrm/admin/options/addressee&group=addressee&reset=1',             '{ts escape="sql" skip="true"}Addressee Formats{/ts}',             'Addressee Formats',                                                 'administer CiviCRM', '', @communicationslastID, '1', NULL, 10 );
-
-INSERT INTO civicrm_navigation
-    ( domain_id, url, label, name, permission, permission_operator, parent_id, is_active, has_separator, weight )
-VALUES
-    ( @domainID, NULL, '{ts escape="sql" skip="true"}Localization{/ts}', 'Localization', 'administer CiviCRM', '', @adminlastID, '1', NULL, 6 );
-
-SET @locallastID:=LAST_INSERT_ID();
-INSERT INTO civicrm_navigation
-    ( domain_id, url, label, name, permission, permission_operator, parent_id, is_active, has_separator, weight )
-VALUES
-    ( @domainID, 'civicrm/admin/setting/localization&reset=1',          '{ts escape="sql" skip="true"}Languages, Currency, Locations{/ts}', 'Languages, Currency, Locations',   'administer CiviCRM', '', @locallastID, '1', NULL, 1 ),
-    ( @domainID, 'civicrm/admin/setting/preferences/address&reset=1',   '{ts escape="sql" skip="true"}Address Settings{/ts}',               'Address Settings',                 'administer CiviCRM', '', @locallastID, '1', NULL, 2 ),
-    ( @domainID, 'civicrm/admin/setting/date&reset=1',                  '{ts escape="sql" skip="true"}Date Format{/ts}',                    'Date Formats',                     'administer CiviCRM', '', @locallastID, '1', NULL, 3 ),
-    ( @domainID, 'civicrm/admin/options/languages&group=languages&reset=1', '{ts escape="sql" skip="true"}Preferred Language Options{/ts}', 'Preferred Language Options',       'administer CiviCRM', '', @locallastID, '1', NULL, 4 );
-
-INSERT INTO civicrm_navigation
-    ( domain_id, url, label, name, permission, permission_operator, parent_id, is_active, has_separator, weight )
-VALUES
-    ( @domainID, NULL,                                                  '{ts escape="sql" skip="true"}Users and Permissions{/ts}',          'Users and Permissions',            'administer CiviCRM', '', @adminlastID, '1', NULL, 7 );
-
-SET @usersPermslastID:=LAST_INSERT_ID();
-INSERT INTO civicrm_navigation
-    ( domain_id, url, label, name, permission, permission_operator, parent_id, is_active, has_separator, weight )
-VALUES
-    ( @domainID, 'civicrm/admin/access&reset=1',       '{ts escape="sql" skip="true"}Permissions (Access Control){/ts}',    'Permissions (Access Control)',     'administer CiviCRM', '', @usersPermslastID, '1', NULL, 1 ),
-    ( @domainID, 'civicrm/admin/synchUser&reset=1',    '{ts escape="sql" skip="true"}Synchronize Users to Contacts{/ts}',   'Synchronize Users to Contacts',    'administer CiviCRM', '', @usersPermslastID, '1', NULL, 2 );
-
-INSERT INTO civicrm_navigation
-    ( domain_id, url, label, name, permission, permission_operator, parent_id, is_active, has_separator, weight )
-VALUES
-    ( @domainID, NULL,                                 '{ts escape="sql" skip="true"}System Settings{/ts}',                 'System Settings',                      'administer CiviCRM', '', @adminlastID, '1', NULL, 8 );
-
-SET @systemSettingslastID:=LAST_INSERT_ID();
-INSERT INTO civicrm_navigation
-    ( domain_id, url, label, name, permission, permission_operator, parent_id, is_active, has_separator, weight )
-VALUES
-    ( @domainID, 'civicrm/admin/setting/component&reset=1',             '{ts escape="sql" skip="true"}Enable CiviCRM Components{/ts}', 'Enable Components',                     'administer CiviCRM', '', @systemSettingslastID, '1', NULL, 1 ),
-    ( @domainID, 'civicrm/admin/setting/smtp&reset=1',                  '{ts escape="sql" skip="true"}Outbound Email (SMTP/Sendmail){/ts}', 'Outbound Email',                   'administer CiviCRM', '', @systemSettingslastID, '1', NULL, 2 ),
-    ( @domainID, 'civicrm/admin/paymentProcessor&reset=1',              '{ts escape="sql" skip="true"}Payment Processors{/ts}', 'Payment Processors',                           'administer CiviCRM', '', @systemSettingslastID, '1', NULL, 3 ),
-    ( @domainID, 'civicrm/admin/setting/mapping&reset=1',               '{ts escape="sql" skip="true"}Mapping and Geocoding{/ts}', 'Mapping and Geocoding',                     'administer CiviCRM', '', @systemSettingslastID, '1', NULL, 4 ),
-    ( @domainID, 'civicrm/admin/setting/misc&reset=1',                  '{ts escape="sql" skip="true"}Undelete, Logging and ReCAPTCHA{/ts}', 'Undelete, Logging and ReCAPTCHA', 'administer CiviCRM', '', @systemSettingslastID, '1', NULL, 5 ),
-    ( @domainID, 'civicrm/admin/setting/path&reset=1',                  '{ts escape="sql" skip="true"}Directories{/ts}',        'Directories',                                  'administer CiviCRM', '', @systemSettingslastID, '1', NULL, 6 ),
-    ( @domainID, 'civicrm/admin/setting/url&reset=1',                   '{ts escape="sql" skip="true"}Resource URLs{/ts}',      'Resource URLs',                                'administer CiviCRM', '', @systemSettingslastID, '1', NULL, 7 ),
-    ( @domainID, 'civicrm/admin/setting/updateConfigBackend&reset=1',   '{ts escape="sql" skip="true"}Cleanup Caches and Update Paths{/ts}', 'Cleanup Caches and Update Paths', 'administer CiviCRM', '', @systemSettingslastID, '1', NULL, 8 ),
-    ( @domainID, 'civicrm/admin/setting/uf&reset=1',                    '{ts escape="sql" skip="true"}CMS Database Integration{/ts}',    'CMS Integration',                     'administer CiviCRM', '', @systemSettingslastID, '1', NULL, 9 ),
-    ( @domainID, 'civicrm/admin/options/safe_file_extension&group=safe_file_extension&reset=1', '{ts escape="sql" skip="true"}Safe File Extensions{/ts}', 'Safe File Extensions','administer CiviCRM', '',@systemSettingslastID, '1', NULL, 10 ),
-    ( @domainID, 'civicrm/admin/options?reset=1',                       '{ts escape="sql" skip="true"}Option Groups{/ts}', 'Option Groups',                                     'administer CiviCRM', '', @systemSettingslastID, '1', NULL, 11 ),
-    ( @domainID, 'civicrm/admin/mapping&reset=1',                       '{ts escape="sql" skip="true"}Import/Export Mappings{/ts}', 'Import/Export Mappings',                   'administer CiviCRM', '', @systemSettingslastID, '1', NULL, 12 ),
-    ( @domainID, 'civicrm/admin/setting/debug&reset=1',                 '{ts escape="sql" skip="true"}Debugging and Error Handling{/ts}','Debugging and Error Handling',        'administer CiviCRM', '', @systemSettingslastID, '1', NULL, 13 ),
-    ( @domainID, 'civicrm/admin/setting/preferences/multisite&reset=1', '{ts escape="sql" skip="true"}Multi Site Settings{/ts}', 'Multi Site Settings',                         'administer CiviCRM', '', @systemSettingslastID, '1', NULL, 14 );
-
-SELECT @campaignAdminID := id   FROM civicrm_navigation where name = 'CiviCampaign' AND parent_id = @adminlastID;
-SELECT @eventAdminID := id      FROM civicrm_navigation where name = 'CiviEvent'    AND parent_id = @adminlastID;
-SELECT @mailAdminID := id       FROM civicrm_navigation where name = 'CiviMail'      AND parent_id = @adminlastID;
-SELECT @memberAdminID := id     FROM civicrm_navigation where name = 'CiviMember' AND parent_id = @adminlastID;
-
-INSERT INTO civicrm_navigation
-    ( domain_id, url, label, name, permission, permission_operator, parent_id, is_active, has_separator, weight )
-VALUES
-    ( @domainID, 'civicrm/admin/setting/preferences/campaign&reset=1',  '{ts escape="sql" skip="true"}CiviCampaign Component Settings{/ts}', 'CiviCampaign Component Settings','administer CiviCampaign', '', @campaignAdminID, '1', NULL, 5 ),
-    ( @domainID, 'civicrm/admin/setting/preferences/event&reset=1',     '{ts escape="sql" skip="true"}CiviEvent Component Settings{/ts}', 'CiviEvent Component Settings','access CiviEvent,administer CiviCRM', 'AND', @eventAdminID, '1', NULL, 13 ),
-    ( @domainID, 'civicrm/admin/setting/preferences/mailing&reset=1',   '{ts escape="sql" skip="true"}CiviMail Component Settings{/ts}', 'CiviMail Component Settings','access CiviMail,administer CiviCRM', 'AND', @mailAdminID, '1', NULL, 6 ),
-    ( @domainID, 'civicrm/admin/setting/preferences/member&reset=1',    '{ts escape="sql" skip="true"}CiviMember Component Settings{/ts}', 'CiviMember Component Settings','access CiviMember,administer CiviCRM', 'AND', @memberAdminID, '1', NULL, 5 ),
-    ( @domainID, 'civicrm/admin/options/event_badge&group=event_badge&reset=1', '{ts escape="sql" skip="true"}Event Badge Formats{/ts}', 'Event Badge Formats', 'access CiviEvent,administer CiviCRM', 'AND', @eventAdminID, '1', NULL, 11 );
-
--- CRM-9113
-ALTER TABLE `civicrm_report_instance` ADD `grouprole` VARCHAR( 1024 ) NULL AFTER `permission`;
-
--- CRM-8762 Fix option_group table
-ALTER TABLE civicrm_option_group CHANGE `is_reserved` `is_reserved` TINYINT DEFAULT 1;
-UPDATE civicrm_option_group SET `is_reserved` = 1;
-{if $multilingual}
-  {foreach from=$locales item=locale}
-    UPDATE civicrm_option_group SET label_{$locale} = description_{$locale} WHERE label_{$locale} IS NULL;
-  {/foreach}
-{else}
-  UPDATE civicrm_option_group SET `label` = `description` WHERE `label` IS NULL;
-{/if}
-
--- CRM-9112
-  ALTER TABLE `civicrm_dedupe_rule_group` ADD `title` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT NULL COMMENT 'Label of the rule group';
-
-ALTER TABLE `civicrm_dedupe_rule_group` ADD `is_reserved` TINYINT( 4 ) NULL DEFAULT NULL COMMENT 'Is this a reserved rule - a rule group that has been optimized and cannot be changed by the admin';
-
-UPDATE `civicrm_dedupe_rule_group` SET `name` = CONCAT( REPLACE( `name`, '-', '' ), '-', id );
-
--- the fuzzy default dedupe rules
-INSERT INTO civicrm_dedupe_rule_group (contact_type, threshold, level, is_default, name, title, is_reserved)
-VALUES ('Individual', 20, 'Fuzzy', 1, 'IndividualFuzzy', 'Individual Fuzzy In-built', 1);
-
-SELECT @drgid := MAX(id) FROM civicrm_dedupe_rule_group;
-INSERT INTO civicrm_dedupe_rule (dedupe_rule_group_id, rule_table, rule_field, rule_weight)
-VALUES (@drgid, 'civicrm_contact', 'first_name', 5),
-       (@drgid, 'civicrm_contact', 'last_name',  7),
-       (@drgid, 'civicrm_email'  , 'email',     10);
-
--- the strict dedupe rules
-INSERT INTO civicrm_dedupe_rule_group (contact_type, threshold, level, is_default, name, title, is_reserved)
-VALUES ('Individual', 10, 'Strict', 1, 'IndividualStrict', 'Individual Strict In-built', 1);
-
-SELECT @drgid := MAX(id) FROM civicrm_dedupe_rule_group;
-INSERT INTO civicrm_dedupe_rule (dedupe_rule_group_id, rule_table, rule_field, rule_weight)
-VALUES (@drgid, 'civicrm_email', 'email', 10);
-
-INSERT INTO civicrm_dedupe_rule_group (contact_type, threshold, level, is_default, name, title, is_reserved)
-VALUES ('Individual', 15, 'Strict', 0, 'IndividualComplete', 'Individual Complete Inbuilt', 1);
-
-SELECT @drgid := MAX(id) FROM civicrm_dedupe_rule_group;
-INSERT INTO civicrm_dedupe_rule (dedupe_rule_group_id, rule_table, rule_field, rule_weight)
-VALUES (@drgid, 'civicrm_contact', 'first_name',     '5'),
-       (@drgid, 'civicrm_contact', 'last_name',      '5'),
-       (@drgid, 'civicrm_address', 'street_address', '5'),
-       (@drgid, 'civicrm_contact', 'middle_name',    '1'),
-       (@drgid, 'civicrm_contact', 'suffix_id',      '1');
-
--- CRM-9120
-{if $multilingual}
-  {foreach from=$locales item=locale}
-    ALTER TABLE `civicrm_location_type` ADD display_name_{$locale} VARCHAR( 64 ) DEFAULT NULL  COMMENT 'Location Type Display Name.' AFTER `name`;
-    UPDATE `civicrm_location_type` SET display_name_{$locale} = `name`;
-  {/foreach}
-{else}
-  ALTER TABLE `civicrm_location_type` ADD `display_name` VARCHAR( 64 ) DEFAULT NULL  COMMENT 'Location Type Display Name.' AFTER `name`;
-  UPDATE `civicrm_location_type` SET `display_name` = `name`;
-{/if}
-
-
--- CRM-9125
-ALTER TABLE `civicrm_contribution_recur` ADD `contribution_type_id` int(10) unsigned NULL COMMENT 'FK to Contribution Type';
-ALTER TABLE `civicrm_contribution_recur` ADD CONSTRAINT `FK_civicrm_contribution_recur_contribution_type_id` FOREIGN KEY (`contribution_type_id`) REFERENCES `civicrm_contribution_type` (`id`) ON DELETE SET NULL;
-
-ALTER TABLE `civicrm_contribution_recur` ADD `payment_instrument_id` int(10) unsigned NULL COMMENT 'FK to Payment Instrument';
-ALTER TABLE `civicrm_contribution_recur` ADD INDEX UI_contribution_recur_payment_instrument_id ( payment_instrument_id );
-
-ALTER TABLE `civicrm_contribution_recur` ADD `campaign_id` int(10) unsigned NULL COMMENT 'The campaign for which this contribution has been triggered.';
-ALTER TABLE `civicrm_contribution_recur` ADD CONSTRAINT `FK_civicrm_contribution_recur_campaign_id` FOREIGN KEY (`campaign_id`) REFERENCES `civicrm_campaign` (`id`) ON DELETE SET NULL;
-
-UPDATE `civicrm_contribution_recur` ccr INNER JOIN `civicrm_contribution` cc ON ccr.id = cc.contribution_recur_id SET ccr.campaign_id = cc.campaign_id, ccr.payment_instrument_id = cc.payment_instrument_id, ccr.contribution_type_id = cc.contribution_type_id;
-
--- CRM-8962
-INSERT INTO civicrm_action_mapping ( entity, entity_value, entity_value_label, entity_status, entity_status_label, entity_date_start, entity_date_end, entity_recipient )
-VALUES
-('civicrm_participant', 'event_type', 'Event Type', 'civicrm_participant_status_type', 'Participant Status', 'event_start_date', 'event_end_date', 'event_contacts'),
-('civicrm_participant', 'civicrm_event', 'Event Name', 'civicrm_participant_status_type', 'Participant Status', 'event_start_date', 'event_end_date', 'event_contacts');
-
-INSERT INTO civicrm_option_group
-      (name, {localize field='label'}label{/localize}, {localize field='description'}description{/localize}, is_reserved, is_active)
-VALUES
-      ('event_contacts', {localize}'{ts escape="sql"}Event Recipients{/ts}'{/localize}, {localize}'{ts escape="sql"}Event Recipients{/ts}'{/localize}, 1, 1),
-      ('contact_reference_options', {localize}'{ts escape="sql"}Contact Reference Autocomplete Options{/ts}'{/localize}, {localize}'{ts escape="sql"}Contact Reference Autocomplete Options{/ts}'{/localize}, 1, 1);
-
-SELECT @option_group_id_ere := max(id) from civicrm_option_group where name = 'event_contacts';
-
-INSERT INTO civicrm_option_value
-   (option_group_id, {localize field='label'}label{/localize}, value, name,  filter,  weight, is_active )
-VALUES
-   (@option_group_id_ere, {localize}'{ts escape="sql"}Participant Role{/ts}'{/localize}, 1, 'participant_role', 0,  1, 1 );
-
-ALTER TABLE civicrm_action_schedule ADD `absolute_date` date DEFAULT NULL COMMENT 'Date on which the reminder be sent.';
-ALTER TABLE civicrm_action_schedule ADD `recipient_listing` varchar(128) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'listing based on recipient field.';
-
-
--- CRM-8534
-ALTER TABLE civicrm_pcp_block
-      DROP FOREIGN KEY FK_civicrm_pcp_block_entity_id,
-      DROP INDEX FK_civicrm_pcp_block_entity_id;
-
-ALTER TABLE civicrm_pcp
-      DROP FOREIGN KEY FK_civicrm_pcp_contribution_page_id,
-      DROP INDEX FK_civicrm_pcp_contribution_page_id;
-
-ALTER TABLE `civicrm_pcp`
-  ADD `page_type` VARCHAR( 64 ) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL DEFAULT 'contribute' AFTER `contribution_page_id`;
-ALTER TABLE `civicrm_pcp`
-  CHANGE `contribution_page_id` `page_id` INT( 10 ) UNSIGNED NOT NULL COMMENT 'The Page which triggered this pcp';
-ALTER TABLE `civicrm_pcp`
-  ADD `pcp_block_id` int(10) unsigned NOT NULL COMMENT 'The pcp block that this pcp page was created from' AFTER `page_type`;
-
-UPDATE `civicrm_pcp`
-  SET `page_type` = 'contribute' WHERE `page_type` = '' OR `page_type` IS NULL;
-UPDATE `civicrm_pcp` `pcp`
-  SET `pcp_block_id` = (SELECT `id` FROM `civicrm_pcp_block` `pb` WHERE `pb`.`entity_id` = `pcp`.`page_id`);
-
-ALTER TABLE `civicrm_pcp_block`
-  ADD `target_entity_type` VARCHAR( 64 ) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL DEFAULT 'contribute' AFTER `entity_id`;
-ALTER TABLE `civicrm_pcp_block`
-  ADD `target_entity_id` int(10) unsigned NOT NULL COMMENT 'The entity that this pcp targets' AFTER `target_entity_type`;
-UPDATE `civicrm_pcp_block`
-  SET `target_entity_id` = `entity_id` WHERE `target_entity_id` = '' OR `target_entity_id` IS NULL;
-
-ALTER TABLE `civicrm_pcp` DROP COLUMN `referer`;
-
-UPDATE civicrm_navigation SET url = 'civicrm/admin/pcp?reset=1&page_type=contribute' WHERE url = 'civicrm/admin/pcp&reset=1';
-
-SELECT @lastEventId        := MAX(id) FROM civicrm_navigation where name = 'Events' AND domain_id = @domainID;
-SELECT @adminEventId       := MAX(id) FROM civicrm_navigation where name = 'CiviEvent' AND domain_id = @domainID;
-SELECT @lastEventIdWeight  := MAX(weight)+1 FROM civicrm_navigation where parent_id = @lastEventId;
-SELECT @adminEventIdWeight := MAX(weight)+1 FROM civicrm_navigation where parent_id = @adminEventId;
-
-INSERT INTO civicrm_navigation
-    ( domain_id, url, label, name, permission, permission_operator, parent_id, is_active, has_separator, weight )
-VALUES
-    ( @domainID, 'civicrm/admin/pcp?reset=1&page_type=event',            '{ts escape="sql" skip="true"}Personal Campaign Pages{/ts}',   'Personal Campaign Pages',   'access CiviEvent,administer CiviCRM', 'AND', @lastEventId, '1', 1, @lastEventIdWeight ),
-    ( @domainID, 'civicrm/admin/pcp?reset=1&page_type=event',            '{ts escape="sql" skip="true"}Personal Campaign Pages{/ts}',   'Personal Campaign Pages',   'access CiviEvent,administer CiviCRM', 'AND', @adminEventId, '1', 1, @adminEventIdWeight );
-
--- CRM-8358 - consolidated cron jobs
-
-CREATE TABLE `civicrm_job` (
-  `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'Job Id',
-  `domain_id` int(10) unsigned NOT NULL COMMENT 'Which Domain is this scheduled job for',
-  `run_frequency` enum('Hourly','Daily','Always') COLLATE utf8_unicode_ci DEFAULT 'Daily' COMMENT 'Scheduled job run frequency.',
-  `last_run` datetime DEFAULT NULL COMMENT 'When was this cron entry last run',
-  `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'Title of the job',
-  `description` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'Description of the job',
-  `api_prefix` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'Prefix of the job api call',
-  `api_entity` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'Entity of the job api call',
-  `api_action` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'Action of the job api call',
-  `parameters` text COLLATE utf8_unicode_ci COMMENT 'List of parameters to the command.',
-  `is_active` tinyint(4) DEFAULT NULL COMMENT 'Is this job active?',
-  PRIMARY KEY (`id`),
-  KEY `FK_civicrm_job_domain_id` (`domain_id`),
-  CONSTRAINT `FK_civicrm_job_domain_id` FOREIGN KEY (`domain_id`) REFERENCES `civicrm_domain` (`id`)
-) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
-
-CREATE TABLE `civicrm_job_log` (
-  `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'Job log entry Id',
-  `domain_id` int(10) unsigned NOT NULL COMMENT 'Which Domain is this scheduled job for',
-  `run_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'Log entry date',
-  `job_id` int(10) unsigned DEFAULT NULL COMMENT 'Pointer to job id - not a FK though, just for logging purposes',
-  `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'Title of the job',
-  `command` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'Full path to file containing job script',
-  `description` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'Title line of log entry',
-  `data` text COLLATE utf8_unicode_ci COMMENT 'Potential extended data for specific job run (e.g. tracebacks).',
-  PRIMARY KEY (`id`),
-  KEY `FK_civicrm_job_log_domain_id` (`domain_id`),
-  CONSTRAINT `FK_civicrm_job_log_domain_id` FOREIGN KEY (`domain_id`) REFERENCES `civicrm_domain` (`id`)
-) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
-
-INSERT INTO `civicrm_job`
-    ( domain_id, run_frequency, last_run, name, description, api_prefix, api_entity, api_action, parameters, is_active )
-VALUES
-    ( @domainID, 'Hourly' , NULL, '{ts escape="sql" skip="true"}Mailings scheduler{/ts}',          '{ts escape="sql" skip="true"}Sends out scheduled mailings{/ts}',                                         'civicrm_api3', 'job', 'process_mailing',         'user=USERNAME\r\npassword=PASSWORD\r\nkey=SITE_KEY', 0),
-    ( @domainID, 'Hourly' , NULL, '{ts escape="sql" skip="true"}Bounces fetcher{/ts}',             '{ts escape="sql" skip="true"}Fetches bounces from mailings and writes them to mailing statistics{/ts}',  'civicrm_api3', 'job', 'fetch_bounces',           'user=USERNAME\r\npassword=PASSWORD\r\nkey=SITE_KEY', 0),
-    ( @domainID, 'Hourly' , NULL, '{ts escape="sql" skip="true"}Activity processor{/ts}',          '{ts escape="sql" skip="true"}{/ts}',                                                                     'civicrm_api3', 'job', 'fetch_activities',        'user=USERNAME\r\npassword=PASSWORD\r\nkey=SITE_KEY', 0),
-    ( @domainID, 'Daily' ,  NULL, '{ts escape="sql" skip="true"}Pledge record processor{/ts}',     '{ts escape="sql" skip="true"}Updates pledge records and sends out reminders{/ts}',                       'civicrm_api3', 'job', 'process_pledge',          'version=3\r\n', 0),
-    ( @domainID, 'Daily' ,  NULL, '{ts escape="sql" skip="true"}Address geocoder{/ts}',            '{ts escape="sql" skip="true"}Goes through addresses and geocodes them (requires Geocoding API on){/ts}', 'civicrm_api3', 'job', 'geocode',                 'version=3\r\n', 0),
-    ( @domainID, 'Daily' ,  NULL, '{ts escape="sql" skip="true"}Greeting updater{/ts}',            '{ts escape="sql" skip="true"}Goes through contact records and updates greeting settings{/ts}',           'civicrm_api3', 'job', 'update_greeting',         'version=3\r\n', 0),
-    ( @domainID, 'Daily' ,  NULL, '{ts escape="sql" skip="true"}Report sender{/ts}',               '{ts escape="sql" skip="true"}Generates and sends out reports via email{/ts}',                            'civicrm_api3', 'job', 'mail_reports',            'version=3\r\n', 0),
-    ( @domainID, 'Daily' ,  NULL, '{ts escape="sql" skip="true"}Scheduled reminders sender{/ts}',  '{ts escape="sql" skip="true"}Sends out scheduled reminders via email.{/ts}',                             'civicrm_api3', 'job', 'send_reminder',           'version=3\r\n', 0),
-    ( @domainID, 'Always' , NULL, '{ts escape="sql" skip="true"}Participant status processor{/ts}','{ts escape="sql" skip="true"}Adjusts event participant statuses based on time{/ts}',                     'civicrm_api3', 'job', 'process_participant',     'version=3\r\n', 0),
-    ( @domainID, 'Always' , NULL, '{ts escape="sql" skip="true"}Membership status processor{/ts}', '{ts escape="sql" skip="true"}Adjusts event membership statuses based on time{/ts}',                      'civicrm_api3', 'job', 'process_membership',      'version=3\r\n', 0),
-    ( @domainID, 'Always' , NULL, '{ts escape="sql" skip="true"}Membership reminder date processor{/ts}','{ts escape="sql" skip="true"}Adjusts membership reminder dates based on time{/ts}',                     'civicrm_api3', 'job', 'process_process_membership_reminder_date',     'version=3\r\n', 0);
-
---CRM 9135
-ALTER TABLE civicrm_contribution_recur
- ADD is_email_receipt TINYINT (4) COMMENT 'if true, receipt is automatically emailed to contact on each successful payment' AFTER payment_processor_id;
-
--- /*****   Civicrm Multi-Event Registration   ***********/
-
-CREATE TABLE civicrm_event_carts (
-     id int unsigned NOT NULL AUTO_INCREMENT  COMMENT 'Cart Id',
-     user_id int unsigned    COMMENT 'FK to civicrm_contact who created this cart',
-     coupon_code varchar(255) DEFAULT NULL,
-     completed tinyint   DEFAULT 0,
-     PRIMARY KEY ( id ),
-     CONSTRAINT FK_civicrm_event_carts_user_id FOREIGN KEY (user_id)
-REFERENCES civicrm_contact(id) ON DELETE SET NULL
-)  ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci  ;
-
-CREATE TABLE civicrm_events_in_carts (
-     id int unsigned NOT NULL AUTO_INCREMENT  COMMENT 'Event In Cart Id',
-     event_id int unsigned    COMMENT 'FK to Event ID',
-     event_cart_id int unsigned    COMMENT 'FK to Event Cart ID',
-    PRIMARY KEY ( id ),
-     CONSTRAINT FK_civicrm_events_in_carts_event_id FOREIGN KEY (event_id)
-REFERENCES civicrm_event(id) ON DELETE CASCADE,
-     CONSTRAINT FK_civicrm_events_in_carts_event_cart_id FOREIGN KEY
-(event_cart_id) REFERENCES civicrm_event_carts(id) ON DELETE CASCADE
-)  ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci  ;
-
-
-ALTER TABLE civicrm_participant
-    ADD discount_amount int unsigned DEFAULT 0 COMMENT 'Discount Amount';
-ALTER TABLE civicrm_participant
-    ADD cart_id int unsigned DEFAULT NULL COMMENT 'FK to civicrm_event_carts';
-ALTER TABLE civicrm_participant
-    ADD CONSTRAINT FK_civicrm_participant_cart_id FOREIGN KEY (cart_id)
-        REFERENCES civicrm_event_carts(id) ON DELETE SET NULL;
-
--- XXX a hint to the payment form.  Can someone make this go away?
-ALTER TABLE civicrm_participant
-    ADD must_wait TINYINT   DEFAULT 0 COMMENT 'On Waiting List';
-
-
-SELECT @pending_id                 := MAX(id) + 1 FROM civicrm_participant_status_type;
-INSERT INTO civicrm_participant_status_type
-  (id,          name,                         {localize field='label'}label{/localize},                                                       class,      is_reserved, is_active, is_counted, weight,      visibility_id)
-VALUES
-  (@pending_id, 'Pending in cart',            {localize}'{ts escape="sql"}Pending in cart{/ts}'{/localize},                     'Pending',  1,           1,         0,          @pending_id, 2            );
-
-
-ALTER TABLE civicrm_event
-    ADD parent_event_id int unsigned DEFAULT NULL COMMENT 'Implicit FK to civicrm_event: parent event';
-ALTER TABLE civicrm_event
-    ADD slot_label_id int unsigned DEFAULT NULL COMMENT 'Subevent slot label. Implicit FK to civicrm_option_value where option_group = conference_slot.';
-
-INSERT INTO
-   `civicrm_option_group` (`name`, {localize field='label'}`label`{/localize}, {localize field='description'}`description`{/localize}, `is_reserved`, `is_active`)
-VALUES
-   ('conference_slot'               , {localize}'{ts escape="sql"}Conference Slot{/ts}'{/localize}, {localize}'{ts escape="sql"}Conference Slot{/ts}'{/localize}                    , 1, 1);
-
-SELECT @option_group_id_conference_slot := max(id) from civicrm_option_group where name = 'conference_slot';
-
-INSERT INTO
-   `civicrm_option_value` (`option_group_id`, {localize field='label'}`label`{/localize}, `value`, `name`, `grouping`, `filter`, `is_default`, `weight`, {localize field='description'}`description`{/localize}, `is_optgroup`, `is_reserved`, `is_active`, `component_id`, `visibility_id`)
-VALUES
-   (@option_group_id_conference_slot, {localize}'{ts escape="sql"}Morning Sessions{/ts}'{/localize}, 1, '{ts escape="sql"}Morning Sessions{/ts}', NULL, 0, NULL, 1, {localize}'{ts escape="sql"}NULL{/ts}'{/localize}, 0, 0, 1, NULL, NULL),
-   (@option_group_id_conference_slot, {localize}'{ts escape="sql"}Evening Sessions{/ts}'{/localize}, 2, '{ts escape="sql"}Evening Sessions{/ts}', NULL, 0, NULL, 2, {localize}'{ts escape="sql"}NULL{/ts}'{/localize}, 0, 0, 1, NULL, NULL);
-
-SELECT @msg_tpl_workflow_event := MAX(id)     FROM civicrm_option_group WHERE name = 'msg_tpl_workflow_event';
-SELECT @weight                 := MAX(weight) + 1 FROM civicrm_option_value WHERE option_group_id = @msg_tpl_workflow_event;
-
-INSERT INTO civicrm_option_value
-  (option_group_id,         name,                         {localize field='label'}label{/localize},                                         value,   weight)
-VALUES
-  (@msg_tpl_workflow_event, 'event_registration_receipt', {localize}'{ts escape="sql"}Events - Receipt only{/ts}'{/localize}, @weight, @weight);
-
-{* SELECT @tpl_ovid_$vName := MAX(id) FROM civicrm_option_value WHERE option_group_id = @tpl_ogid_$gName AND name = '$vName'; *}
-{* INSERT INTO civicrm_msg_template *}
-
--- CRM-8532
-UPDATE `civicrm_dashboard` SET url = REPLACE( url, 'snippet=4', 'snippet=5' ), fullscreen_url = REPLACE( fullscreen_url, 'snippet=4', 'snippet=5' );
-
-{if $multilingual}
-  {foreach from=$locales item=locale}
-    ALTER TABLE civicrm_option_group CHANGE label_{$locale} title_{$locale} varchar(255);
-  {/foreach}
-{else}
-  ALTER TABLE civicrm_option_group CHANGE label title varchar(255);
-{/if}
diff --git a/civicrm/CRM/Upgrade/Incremental/sql/4.1.alpha2.mysql.tpl b/civicrm/CRM/Upgrade/Incremental/sql/4.1.alpha2.mysql.tpl
deleted file mode 100644
index e840272121..0000000000
--- a/civicrm/CRM/Upgrade/Incremental/sql/4.1.alpha2.mysql.tpl
+++ /dev/null
@@ -1,12 +0,0 @@
--- CRM-8356 added missing option values
-SELECT @option_group_id_acConRef := max(id) from civicrm_option_group where name = 'contact_reference_options';
-
-INSERT INTO civicrm_option_value
-   (option_group_id, {localize field='label'}label{/localize}, value, name,  filter,  weight, is_active )
-VALUES
-  (@option_group_id_acConRef, {localize}'{ts escape="sql"}Email Address{/ts}'{/localize}   , 2, 'email'         , 0, 2,  1 ),
-  (@option_group_id_acConRef, {localize}'{ts escape="sql"}Phone{/ts}'{/localize}           , 3, 'phone'         , 0, 3,  1 ),
-  (@option_group_id_acConRef, {localize}'{ts escape="sql"}Street Address{/ts}'{/localize}  , 4, 'street_address', 0, 4,  1 ),
-  (@option_group_id_acConRef, {localize}'{ts escape="sql"}City{/ts}'{/localize}            , 5, 'city'          , 0, 5,  1 ),
-  (@option_group_id_acConRef, {localize}'{ts escape="sql"}State/Province{/ts}'{/localize}  , 6, 'state_province', 0, 6,  1 ),
-  (@option_group_id_acConRef, {localize}'{ts escape="sql"}Country{/ts}'{/localize}         , 7, 'country'       , 0, 7,  1 );
diff --git a/civicrm/CRM/Upgrade/Incremental/sql/4.1.beta1.mysql.tpl b/civicrm/CRM/Upgrade/Incremental/sql/4.1.beta1.mysql.tpl
deleted file mode 100644
index adfd46fe6c..0000000000
--- a/civicrm/CRM/Upgrade/Incremental/sql/4.1.beta1.mysql.tpl
+++ /dev/null
@@ -1,11 +0,0 @@
-{if $addWightForActivity}
-  ALTER TABLE `civicrm_activity` ADD weight INT( 11 ) NULL DEFAULT NULL;
-{/if}
-
--- CRM-8508
-SELECT @option_group_id_cgeo := max(id) from civicrm_option_group where name = 'cg_extend_objects';
-
-INSERT INTO civicrm_option_value
-   (option_group_id, {localize field='label'}label{/localize}, value, name, grouping, filter, is_default, weight, {localize field='description'}description{/localize}, is_optgroup, is_reserved, is_active, component_id, visibility_id)
-VALUES
-   (@option_group_id_cgeo, {localize}'{ts escape="sql"}Cases{/ts}'{/localize},  'Case',   'civicrm_case',   NULL, 0, NULL, 2, {localize}'CRM_Case_PseudoConstant::caseType;'{/localize}, 0, 0, 1, NULL, NULL);
diff --git a/civicrm/CRM/Upgrade/Incremental/sql/4.1.beta2.mysql.tpl b/civicrm/CRM/Upgrade/Incremental/sql/4.1.beta2.mysql.tpl
deleted file mode 100644
index 375b4443e2..0000000000
--- a/civicrm/CRM/Upgrade/Incremental/sql/4.1.beta2.mysql.tpl
+++ /dev/null
@@ -1,119 +0,0 @@
--- CRM-9384 Add sample CiviMail Newsletter Message Template
-INSERT INTO civicrm_msg_template
-  (msg_title,      msg_subject,                  msg_text,                  msg_html,                  workflow_id,        is_default, is_reserved)
-  VALUES
-  ('Sample CiviMail Newsletter Template', 'Sample CiviMail Newsletter', '', '<table width=612 cellpadding=0 cellspacing=0 bgcolor="#f4fff4">
-  <tr>
-    <td colspan="2" bgcolor="#ffffff" valign="middle" >
-      <table border="0" cellpadding="0" cellspacing="0" >
-        <tr>
-          <td>
-          <a href="http://www.YOUR-SITE.org"><img src="http://drupal.demo.civicrm.org/files/garland_logo.png" border=0 alt="Replace this logo with the URL to your own"></a>
-          </td>
-          <td>&nbsp; &nbsp;</td>
-          <td>
-          <a href="http://www.YOUR-SITE.org" style="text-decoration: none;"><font size=5 face="Arial, Verdana, sans-serif" color="#8bc539">Your Newsletter Title</font></a>
-          </td>
-        </tr>
-      </table>
-    </td>
-  </tr>
-  <tr>
-    <td valign="top">
-      <!-- left column -->
-      <table cellpadding="10" cellspacing="0" border="0">
-      <tr>
-        <td style="font-family: Arial, Verdana, sans-serif; font-size: 12px;" >
-        <font face="Arial, Verdana, sans-serif" size="2" >
-        Greetings {literal}{contact.display_name}{/literal},
-        <br /><br />
-        This is a sample template designed to help you get started creating and sending your own CiviMail messages. This template uses an HTML layout that is generally compatible with the wide variety of email clients that your recipients might be using (e.g. Gmail, Outlook, Yahoo, etc.).
-        <br /><br />You can select this "Sample CiviMail Newsletter Template" from the "Use Template" drop-down in Step 3 of creating a mailing, and customize it to your needs. Then check the "Save as New Template" box on the bottom the page to save your customized version for use in future mailings.
-        <br /><br />The logo you use must be uploaded to your server.  Copy and paste the URL path to the logo into the &lt;img src= tag in the HTML at the top.  Click "Source" or the Image button if you are using the text editor.
-        <br /><br />
-        Edit the color of the links and headers using the color button or by editing the HTML.
-        <br /><br />
-        Your newsletter message and donation appeal can go here.  Click the link button to <a href="#">create links</a> - remember to use a fully qualified URL starting with http:// in all your links!
-        <br /><br />
-        To use CiviMail:
-        <ul>
-          <li><a href="http://book.civicrm.org/user/initial-set-up/email-system-configuration">Configure your Email System</a>.</li>
-          <li>Make sure your web hosting provider allows outgoing bulk mail, and see if they have a restriction on quantity.  If they don\'t allow bulk mail, consider <a href="http://wiki.civicrm.org/confluence/display/CRM/Hosting+provider+information">finding a new host</a>.</li>
-        </ul>
-        Sincerely,
-        <br /><br />
-        Your Team
-        </font>
-        </td>
-      </tr>
-      </table>
-    </td>
-
-    <td valign="top" bgcolor="#f3f3ff" >
-      <!-- right column -->
-      <table width=180 cellpadding=10 cellspacing=0 border=0>
-      <tr>
-        <td style="color: #000; font-family: Arial, Verdana, sans-serif; font-size: 12px;" >
-        <font face="Arial, Verdana, sans-serif" size="2" >
-        <font color="#003399"><strong>Featured Events</strong> </font><br />
-        Fundraising Dinner<br />
-        Training Meeting<br />
-        Board of Directors Annual Meeting<br />
-
-        <br /><br />
-        <font color="#003399"><strong>Community Events</strong></font><br />
-        Bake Sale<br />
-        Charity Auction<br />
-        Art Exhibit<br />
-
-        <br /><br />
-        <font color="#003399"><strong>Important Dates</strong></font><br />
-        Tuesday August 27<br />
-        Wednesday September 8<br />
-        Thursday September 29<br />
-        Saturday October 1<br />
-        Sunday October 20<br />
-        </font>
-        </td>
-      </tr>
-      </table>
-    </td>
-  </tr>
-
-  <tr>
-    <td colspan="2">
-      <table cellpadding="10" cellspacing="0" border="0">
-      <tr>
-        <td>
-        <font face="Arial, Verdana, sans-serif" size="2" >
-        <font color="#8bc539"><strong>Helpful Tips</strong></font>
-        <br /><br />
-        <font color="#3b5187">Tokens</font><br />
-        Click "Insert Tokens" to dynamically insert names, addresses, and other contact data of your recipients.
-        <br /><br />
-        <font color="#3b5187">Plain Text Version</font><br />
-        Some people refuse HTML emails altogether.  We recommend sending a plain-text version of your important communications to accommodate them.  Luckily, CiviCRM accommodates for this!  Just click "Plain Text" and copy and paste in some text.  Line breaks (carriage returns) and fully qualified URLs like http://www.example.com are all you get, no HTML here!
-        <br /><br />
-        <font color="#3b5187">Play by the Rules</font><br />
-        The address of the sender is required by the Can Spam Act law.  This is an available token called domain.address.  An unsubscribe or opt-out link is also required.  There are several available tokens for this. <em>{literal}{action.optOutUrl}{/literal}</em> creates a link for recipients to click if they want to opt out of receiving  emails from your organization. <em>{literal}{action.unsubscribeUrl}{/literal}</em> creates a link to unsubscribe from the specific mailing list used to send this message. Click on "Insert Tokens" to find these and look for tokens named "Domain" or "Unsubscribe".  This sample template includes both required tokens at the bottom of the message. You can also configure a default Mailing Footer containing these tokens.
-        <br /><br />
-        <font color="#3b5187">Composing Offline</font><br />
-        If you prefer to compose an HTML email offline in your own text editor, you can upload this HTML content into CiviMail or simply click "Source" and then copy and paste the HTML in.
-        <br /><br />
-        <font color="#3b5187">Images</font><br />
-        Most email clients these days (Outlook, Gmail, etc) block image loading by default.  This is to protect their users from annoying or harmful email.  Not much we can do about this, so encourage recipients to add you to their contacts or "whitelist".  Also use images sparingly, do not rely on images to convey vital information, and always use HTML "alt" tags which describe the image content.
-        </td>
-      </tr>
-      </table>
-    </td>
-  </tr>
-  <tr>
-    <td colspan="2" style="color: #000; font-family: Arial, Verdana, sans-serif; font-size: 10px;">
-      <font face="Arial, Verdana, sans-serif" size="2" >
-      <hr>
-      <a href="{literal}{action.unsubscribeUrl}{/literal}" title="click to unsubscribe">Click here</a> to unsubscribe from this mailing list.<br /><br />
-      Our mailing address is:<br />
-      {literal}{domain.address}{/literal}
-    </td>
-  </tr>
-  </table>', NULL, 1, 0);
diff --git a/civicrm/CRM/Upgrade/Incremental/sql/4.1.beta3.mysql.tpl b/civicrm/CRM/Upgrade/Incremental/sql/4.1.beta3.mysql.tpl
deleted file mode 100644
index fd8414b295..0000000000
--- a/civicrm/CRM/Upgrade/Incremental/sql/4.1.beta3.mysql.tpl
+++ /dev/null
@@ -1,33 +0,0 @@
--- Fix invalid api actions in Job table and insert missing job
-UPDATE `civicrm_job`
-SET api_action = 'process_membership_reminder_date' WHERE api_action = 'process_process_membership_reminder_date';
-UPDATE `civicrm_job`
-SET api_action = 'mail_report' WHERE api_action = 'mail_reports';
-
-SELECT @domainID := min(id) FROM civicrm_domain;
-INSERT INTO `civicrm_job`
-    ( domain_id, run_frequency, last_run, name, description, api_prefix, api_entity, api_action, parameters, is_active )
-VALUES
-    ( @domainID, 'Always' , NULL, '{ts escape="sql" skip="true"}Process Survey Respondents{/ts}',   '{ts escape="sql" skip="true"}Releases reserved survey respondents when they have been reserved for longer than the Release Frequency days specified for that survey.{/ts}','civicrm_api3', 'job', 'process_respondent','version=3\r\n', 0);
-
--- Job table was initially delivered with invalid and not-used parameters. Clearing them out. Most jobs do not need any parameters.
-UPDATE `civicrm_job`
-SET parameters = NULL;
-
--- Insert Schedule Jobs admin menu item
-SELECT @systemSettingsID := id     FROM civicrm_navigation where name = 'System Settings' AND domain_id = @domainID;
-
-INSERT INTO civicrm_navigation
-    ( domain_id, url, label, name, permission, permission_operator, parent_id, is_active, has_separator, weight )
-VALUES
-    ( @domainID, 'civicrm/admin/job&reset=1', '{ts escape="sql" skip="true"}Scheduled Jobs{/ts}', 'Scheduled Jobs', 'administer CiviCRM', '', @systemSettingsID, '1', NULL, 15 );
-
--- CRM-9468
--- update Serbia/Montenegro provinces
-UPDATE civicrm_state_province SET country_id = 1243 WHERE id = 5112;
-UPDATE civicrm_state_province SET country_id = 1242 WHERE id = 5113;
-UPDATE civicrm_state_province SET country_id = 1242 WHERE id = 5114;
-UPDATE civicrm_state_province SET country_id = 1242 WHERE id = 5115;
-
--- CRM-9523
-ALTER TABLE `civicrm_note` MODIFY `privacy` VARCHAR(255) COMMENT 'Foreign Key to Note Privacy Level (which is an option value pair and hence an implicit FK)';
diff --git a/civicrm/CRM/Upgrade/Incremental/sql/5.0.0.mysql.tpl b/civicrm/CRM/Upgrade/Incremental/sql/5.0.0.mysql.tpl
deleted file mode 100644
index c6bdb5103b..0000000000
--- a/civicrm/CRM/Upgrade/Incremental/sql/5.0.0.mysql.tpl
+++ /dev/null
@@ -1 +0,0 @@
-{* file to handle db changes in 5.0.0 during upgrade *}
diff --git a/civicrm/CRM/Upgrade/Incremental/sql/5.0.1.mysql.tpl b/civicrm/CRM/Upgrade/Incremental/sql/5.0.1.mysql.tpl
deleted file mode 100644
index b21ae983cf..0000000000
--- a/civicrm/CRM/Upgrade/Incremental/sql/5.0.1.mysql.tpl
+++ /dev/null
@@ -1 +0,0 @@
-{* file to handle db changes in 5.0.1 during upgrade *}
diff --git a/civicrm/CRM/Upgrade/Incremental/sql/5.0.2.mysql.tpl b/civicrm/CRM/Upgrade/Incremental/sql/5.0.2.mysql.tpl
deleted file mode 100644
index d33cec936b..0000000000
--- a/civicrm/CRM/Upgrade/Incremental/sql/5.0.2.mysql.tpl
+++ /dev/null
@@ -1 +0,0 @@
-{* file to handle db changes in 5.0.2 during upgrade *}
diff --git a/civicrm/CRM/Upgrade/Incremental/sql/5.1.0.mysql.tpl b/civicrm/CRM/Upgrade/Incremental/sql/5.1.0.mysql.tpl
new file mode 100644
index 0000000000..698102eb71
--- /dev/null
+++ b/civicrm/CRM/Upgrade/Incremental/sql/5.1.0.mysql.tpl
@@ -0,0 +1 @@
+{* file to handle db changes in 5.1.0 during upgrade *}
diff --git a/civicrm/CRM/Upgrade/Incremental/sql/5.1.alpha1.mysql.tpl b/civicrm/CRM/Upgrade/Incremental/sql/5.1.alpha1.mysql.tpl
new file mode 100644
index 0000000000..38caa89e40
--- /dev/null
+++ b/civicrm/CRM/Upgrade/Incremental/sql/5.1.alpha1.mysql.tpl
@@ -0,0 +1 @@
+{* file to handle db changes in 5.1.alpha1 during upgrade *}
diff --git a/civicrm/CRM/Upgrade/Incremental/sql/5.1.beta1.mysql.tpl b/civicrm/CRM/Upgrade/Incremental/sql/5.1.beta1.mysql.tpl
new file mode 100644
index 0000000000..ad3b7a584d
--- /dev/null
+++ b/civicrm/CRM/Upgrade/Incremental/sql/5.1.beta1.mysql.tpl
@@ -0,0 +1 @@
+{* file to handle db changes in 5.1.beta1 during upgrade *}
diff --git a/civicrm/CRM/Utils/Check/Component/Env.php b/civicrm/CRM/Utils/Check/Component/Env.php
index f48cd035ba..31b92afa3d 100644
--- a/civicrm/CRM/Utils/Check/Component/Env.php
+++ b/civicrm/CRM/Utils/Check/Component/Env.php
@@ -413,7 +413,6 @@ class CRM_Utils_Check_Component_Env extends CRM_Utils_Check_Component {
       'uploadDir' => ts('Temporary Files Directory'),
       'imageUploadDir' => ts('Images Directory'),
       'customFileUploadDir' => ts('Custom Files Directory'),
-      'extensionsDir' => ts('CiviCRM Extensions Directory'),
     );
 
     foreach ($directories as $directory => $label) {
@@ -541,10 +540,10 @@ class CRM_Utils_Check_Component_Env extends CRM_Utils_Check_Component {
     elseif (!is_writable($basedir)) {
       $messages[] = new CRM_Utils_Check_Message(
         __FUNCTION__,
-        ts('Directory %1 is not writable.  Please change your file permissions.',
+        ts('Your extensions directory (%1) is read-only. If you would like to perform downloads or upgrades, then change the file permissions.',
           array(1 => $basedir)),
-        ts('Directory not writable'),
-        \Psr\Log\LogLevel::ERROR,
+        ts('Read-Only Extensions'),
+        \Psr\Log\LogLevel::WARNING,
         'fa-plug'
       );
       return $messages;
@@ -813,6 +812,25 @@ class CRM_Utils_Check_Component_Env extends CRM_Utils_Check_Component {
     return $messages;
   }
 
+  /**
+   * ensure reply id is set to any default value
+   * @return array
+   */
+  public function checkReplyIdForMailing() {
+    $messages = array();
+
+    if (!CRM_Mailing_PseudoConstant::defaultComponent('Reply', '')) {
+      $messages[] = new CRM_Utils_Check_Message(
+        __FUNCTION__,
+        ts('Reply Auto Responder is not set to any default value in <a %1>Headers, Footers, and Automated Messages</a>. This will disable the submit operation on any mailing created from CiviMail.', array(1 => 'href="' . CRM_Utils_System::url('civicrm/admin/component', 'reset=1') . '"')),
+        ts('No Default value for Auto Responder.'),
+        \Psr\Log\LogLevel::WARNING,
+        'fa-reply'
+      );
+    }
+    return $messages;
+  }
+
   /**
    * Check for required mbstring extension
    * @return array
diff --git a/civicrm/CRM/Utils/Money.php b/civicrm/CRM/Utils/Money.php
index 555e7db6e4..b0771a46f0 100644
--- a/civicrm/CRM/Utils/Money.php
+++ b/civicrm/CRM/Utils/Money.php
@@ -141,4 +141,17 @@ class CRM_Utils_Money {
     return 2;
   }
 
+  /**
+   * Subtract currencies using integers instead of floats, to preserve precision
+   *
+   * @return float
+   *   Result of subtracting $rightOp from $leftOp to the precision of $currency
+   */
+  public static function subtractCurrencies($leftOp, $rightOp, $currency) {
+    if (is_numeric($leftOp) && is_numeric($rightOp)) {
+      $precision = pow(10, self::getCurrencyPrecision($currency));
+      return (($leftOp * $precision) - ($rightOp * $precision)) / $precision;
+    }
+  }
+
 }
diff --git a/civicrm/CRM/Utils/Rule.php b/civicrm/CRM/Utils/Rule.php
index ada29634f1..d22e19c461 100644
--- a/civicrm/CRM/Utils/Rule.php
+++ b/civicrm/CRM/Utils/Rule.php
@@ -813,6 +813,25 @@ class CRM_Utils_Rule {
     }
   }
 
+  /**
+   * Validate json string for xss
+   *
+   * @param string $value
+   *
+   * @return bool
+   *   False if invalid, true if valid / safe.
+   */
+  public static function json($value) {
+    if (!self::xssString($value)) {
+      return FALSE;
+    }
+    $array = json_decode($value, TRUE);
+    if (!$array || !is_array($array)) {
+      return FALSE;
+    }
+    return self::arrayValue($array);
+  }
+
   /**
    * @param $path
    *
@@ -935,11 +954,31 @@ class CRM_Utils_Rule {
    * @param string $key Extension Key to check
    * @return bool
    */
-  public static function checkExtesnionKeyIsValid($key = NULL) {
+  public static function checkExtensionKeyIsValid($key = NULL) {
     if (!empty($key) && !preg_match('/^[0-9a-zA-Z._-]+$/', $key)) {
       return FALSE;
     }
     return TRUE;
   }
 
+  /**
+   * Validate array recursively checking keys and  values.
+   *
+   * @param array $array
+   * @return bool
+   */
+  protected static function arrayValue($array) {
+    foreach ($array as $key => $item) {
+      if (is_array($item)) {
+        if (!self::xssString($key) || !self::arrayValue($item)) {
+          return FALSE;
+        }
+      }
+      if (!self::xssString($key) || !self::xssString($item)) {
+        return FALSE;
+      }
+    }
+    return TRUE;
+  }
+
 }
diff --git a/civicrm/CRM/Utils/System/Joomla.php b/civicrm/CRM/Utils/System/Joomla.php
index 4b89202525..5def803e23 100644
--- a/civicrm/CRM/Utils/System/Joomla.php
+++ b/civicrm/CRM/Utils/System/Joomla.php
@@ -557,7 +557,6 @@ class CRM_Utils_System_Joomla extends CRM_Utils_System_Base {
       define('DS', DIRECTORY_SEPARATOR);
       define('JPATH_BASE', $joomlaBase . '/administrator');
       require $joomlaBase . '/administrator/includes/defines.php';
-      require $joomlaBase . '/administrator/includes/framework.php';
     }
 
     // Get the framework.
@@ -565,20 +564,26 @@ class CRM_Utils_System_Joomla extends CRM_Utils_System_Base {
       require $joomlaBase . '/libraries/import.legacy.php';
     }
     require $joomlaBase . '/libraries/cms.php';
-    require $joomlaBase . '/libraries/import.php';
-    require $joomlaBase . '/libraries/joomla/event/dispatcher.php';
-    require_once $joomlaBase . '/configuration.php';
     self::getJVersion($joomlaBase);
 
+    if (version_compare(JVERSION, '3.8', 'lt')) {
+      require $joomlaBase . '/libraries/import.php';
+      require $joomlaBase . '/libraries/joomla/event/dispatcher.php';
+    }
+
+    require_once $joomlaBase . '/configuration.php';
+
     if (version_compare(JVERSION, '3.0', 'lt')) {
       require $joomlaBase . '/libraries/joomla/environment/uri.php';
       require $joomlaBase . '/libraries/joomla/application/component/helper.php';
     }
-    else {
+    elseif (version_compare(JVERSION, '3.8', 'lt')) {
       jimport('joomla.environment.uri');
     }
 
-    jimport('joomla.application.cli');
+    if (version_compare(JVERSION, '3.8', 'lt')) {
+      jimport('joomla.application.cli');
+    }
 
     if (!defined('JDEBUG')) {
       define('JDEBUG', FALSE);
diff --git a/civicrm/CRM/Utils/System/WordPress.php b/civicrm/CRM/Utils/System/WordPress.php
index 7ee488bed5..1db0a2e401 100644
--- a/civicrm/CRM/Utils/System/WordPress.php
+++ b/civicrm/CRM/Utils/System/WordPress.php
@@ -482,7 +482,7 @@ class CRM_Utils_System_WordPress extends CRM_Utils_System_Base {
    */
   public function validInstallDir($dir) {
     $includePath = "$dir/wp-includes";
-    if (file_exists("$includePath/version.php")) {
+    if (@file_exists("$includePath/version.php")) {
       return TRUE;
     }
     return FALSE;
diff --git a/civicrm/CRM/Utils/Type.php b/civicrm/CRM/Utils/Type.php
index d96a0c4a13..3380fde9fb 100644
--- a/civicrm/CRM/Utils/Type.php
+++ b/civicrm/CRM/Utils/Type.php
@@ -422,6 +422,7 @@ class CRM_Utils_Type {
       'MysqlOrderByDirection',
       'MysqlOrderBy',
       'ExtensionKey',
+      'Json',
     );
     if (!in_array($type, $possibleTypes)) {
       if ($isThrowException) {
@@ -526,7 +527,13 @@ class CRM_Utils_Type {
         break;
 
       case 'ExtensionKey':
-        if (CRM_Utils_Rule::checkExtesnionKeyIsValid($data)) {
+        if (CRM_Utils_Rule::checkExtensionKeyIsValid($data)) {
+          return $data;
+        }
+        break;
+
+      case 'Json':
+        if (CRM_Utils_Rule::json($data)) {
           return $data;
         }
         break;
diff --git a/civicrm/CRM/Utils/VersionCheck.php b/civicrm/CRM/Utils/VersionCheck.php
index 740dd2f04e..5c9ba7cd11 100644
--- a/civicrm/CRM/Utils/VersionCheck.php
+++ b/civicrm/CRM/Utils/VersionCheck.php
@@ -336,6 +336,15 @@ class CRM_Utils_VersionCheck {
     }
   }
 
+  /**
+   * Removes cached version info.
+   */
+  public function flushCache() {
+    if (file_exists($this->cacheFile)) {
+      unlink($this->cacheFile);
+    }
+  }
+
   /**
    * Lookup version_check scheduled job
    */
diff --git a/civicrm/Civi/Angular/AngularLoader.php b/civicrm/Civi/Angular/AngularLoader.php
index 5c5bb9a51f..e16cab3419 100644
--- a/civicrm/Civi/Angular/AngularLoader.php
+++ b/civicrm/Civi/Angular/AngularLoader.php
@@ -61,6 +61,11 @@ class AngularLoader {
    */
   protected $modules;
 
+  /**
+   * @var array|NULL
+   */
+  protected $crmApp = NULL;
+
   /**
    * AngularLoader constructor.
    */
@@ -74,11 +79,32 @@ class AngularLoader {
 
   /**
    * Register resources required by Angular.
+   *
+   * @return AngularLoader
    */
   public function load() {
     $angular = $this->getAngular();
     $res = $this->getRes();
 
+    if ($this->crmApp !== NULL) {
+      $this->addModules($this->crmApp['modules']);
+      $region = \CRM_Core_Region::instance($this->crmApp['region']);
+      $region->update('default', array('disabled' => TRUE));
+      $region->add(array('template' => $this->crmApp['file'], 'weight' => 0));
+      $this->res->addSetting(array(
+        'crmApp' => array(
+          'defaultRoute' => $this->crmApp['defaultRoute'],
+        ),
+      ));
+
+      // If trying to load an Angular page via AJAX, the route must be passed as a
+      // URL parameter, since the server doesn't receive information about
+      // URL fragments (i.e, what comes after the #).
+      $this->res->addSetting(array(
+        'angularRoute' => $this->crmApp['activeRoute'],
+      ));
+    }
+
     $moduleNames = $this->findActiveModules();
     if (!$this->isAllModules($moduleNames)) {
       $assetParams = array('modules' => implode(',', $moduleNames));
@@ -135,6 +161,45 @@ class AngularLoader {
         $res->addStyleUrl($url, self::DEFAULT_MODULE_WEIGHT + (++$headOffset), $this->getRegion());
       }
     }
+
+    return $this;
+  }
+
+  /**
+   * Use Civi's generic "application" module.
+   *
+   * This is suitable for use on a basic, standalone Angular page
+   * like `civicrm/a`. (If you need to integrate Angular with pre-existing,
+   * non-Angular pages... then this probably won't help.)
+   *
+   * The Angular bootstrap process requires an HTML directive like
+   * `<div ng-app="foo">`.
+   *
+   * Calling useApp() will replace the page's main body with the
+   * `<div ng-app="crmApp">...</div>` and apply some configuration options
+   * for the `crmApp` module.
+   *
+   * @param array $settings
+   *   A list of settings. Accepted values:
+   *    - activeRoute: string, the route to open up immediately
+   *      Ex: '/case/list'
+   *    - defaultRoute: string, use this to redirect the default route (`/`) to another page
+   *      Ex: '/case/list'
+   *    - region: string, the place on the page where we should insert the angular app
+   *      Ex: 'page-body'
+   * @return AngularLoader
+   * @link https://code.angularjs.org/1.5.11/docs/guide/bootstrap
+   */
+  public function useApp($settings = array()) {
+    $defaults = array(
+      'modules' => array('crmApp'),
+      'activeRoute' => NULL,
+      'defaultRoute' => NULL,
+      'region' => 'page-body',
+      'file' => 'Civi/Angular/Page/Main.tpl',
+    );
+    $this->crmApp = array_merge($defaults, $settings);
+    return $this;
   }
 
   /**
@@ -170,9 +235,11 @@ class AngularLoader {
 
   /**
    * @param \CRM_Core_Resources $res
+   * @return AngularLoader
    */
   public function setRes($res) {
     $this->res = $res;
+    return $this;
   }
 
   /**
@@ -184,9 +251,11 @@ class AngularLoader {
 
   /**
    * @param \Civi\Angular\Manager $angular
+   * @return AngularLoader
    */
   public function setAngular($angular) {
     $this->angular = $angular;
+    return $this;
   }
 
   /**
@@ -198,9 +267,11 @@ class AngularLoader {
 
   /**
    * @param string $region
+   * @return AngularLoader
    */
   public function setRegion($region) {
     $this->region = $region;
+    return $this;
   }
 
   /**
@@ -214,9 +285,21 @@ class AngularLoader {
   /**
    * @param string $pageName
    *   Ex: 'civicrm/a'.
+   * @return AngularLoader
    */
   public function setPageName($pageName) {
     $this->pageName = $pageName;
+    return $this;
+  }
+
+  /**
+   * @param array|string $modules
+   * @return AngularLoader
+   */
+  public function addModules($modules) {
+    $modules = (array) $modules;
+    $this->modules = array_unique(array_merge($this->modules, $modules));
+    return $this;
   }
 
   /**
@@ -228,9 +311,11 @@ class AngularLoader {
 
   /**
    * @param array $modules
+   * @return AngularLoader
    */
   public function setModules($modules) {
     $this->modules = $modules;
+    return $this;
   }
 
 }
diff --git a/civicrm/Civi/Angular/Page/Main.php b/civicrm/Civi/Angular/Page/Main.php
index a13a18c068..aa31fef711 100644
--- a/civicrm/Civi/Angular/Page/Main.php
+++ b/civicrm/Civi/Angular/Page/Main.php
@@ -76,25 +76,12 @@ class Main extends \CRM_Core_Page {
   public function registerResources() {
     $loader = new \Civi\Angular\AngularLoader();
     $loader->setPageName('civicrm/a');
-    $loader->setModules(array('crmApp'));
-    $loader->load();
-
-    // If trying to load an Angular page via AJAX, the route must be passed as a
-    // URL parameter, since the server doesn't receive information about
-    // URL fragments (i.e, what comes after the #).
-    \CRM_Core_Resources::singleton()->addSetting(array(
-      'crmApp' => array(
-        'defaultRoute' => NULL,
-      ),
-      'angularRoute' => \CRM_Utils_Request::retrieve('route', 'String'),
+    $loader->useApp(array(
+      'activeRoute' => \CRM_Utils_Request::retrieve('route', 'String'),
+      'defaultRoute' => NULL,
     ));
-  }
+    $loader->load();
 
-  /**
-   * @inheritdoc
-   */
-  public function getTemplateFileName() {
-    return 'Civi/Angular/Page/Main.tpl';
   }
 
 }
diff --git a/civicrm/Civi/Core/SettingsBag.php b/civicrm/Civi/Core/SettingsBag.php
index 595ce92a9d..f56ac97634 100644
--- a/civicrm/Civi/Core/SettingsBag.php
+++ b/civicrm/Civi/Core/SettingsBag.php
@@ -326,11 +326,6 @@ class SettingsBag {
    *   The new value of the setting.
    */
   protected function setDb($name, $value) {
-    if (\CRM_Core_BAO_Setting::isUpgradeFromPreFourOneAlpha1()) {
-      // civicrm_setting table is not going to be present.
-      return;
-    }
-
     $fields = array();
     $fieldsToSet = \CRM_Core_BAO_Setting::validateSettingsInput(array($name => $value), $fields);
     //We haven't traditionally validated inputs to setItem, so this breaks things.
diff --git a/civicrm/Civi/Test/Api3DocTrait.php b/civicrm/Civi/Test/Api3DocTrait.php
new file mode 100644
index 0000000000..5f4c7ce8bb
--- /dev/null
+++ b/civicrm/Civi/Test/Api3DocTrait.php
@@ -0,0 +1,209 @@
+<?php
+
+namespace Civi\Test;
+
+/**
+ * Class Api3DocTrait
+ * @package Civi\Test
+ *
+ * This trait defines helper functions for testing and documenting APIv3. In
+ * particular, it supports a workflow that links a unit-test file to an
+ * example data file:
+ *
+ * - When defining a new API, write a unit test for it.
+ * - As part of the unit test, use `callAPIAndDocument($entity, $action, ...)`.
+ * - When the test executes, the inputs and outputs are logged to an example file.
+ * - You can commit this file to git.
+ * - Whenever the inputs/output change, they'll be visible in SCM/git because
+ *   the example file also changes.
+ *
+ * This trait is intended for use with PHPUnit-based test cases.
+ */
+trait Api3DocTrait {
+  use Api3TestTrait;
+
+  /**
+   * This function exists to wrap api functions.
+   * so we can ensure they succeed, generate and example & throw exceptions without litterering the test with checks
+   *
+   * @param string $entity
+   * @param string $action
+   * @param array $params
+   * @param string $function
+   *   Pass this in to create a generated example.
+   * @param string $file
+   *   Pass this in to create a generated example.
+   * @param string $description
+   * @param string|null $exampleName
+   *
+   * @return array|int
+   */
+  public function callAPIAndDocument($entity, $action, $params, $function, $file, $description = "", $exampleName = NULL) {
+    $params['version'] = $this->_apiversion;
+    $result = $this->callAPISuccess($entity, $action, $params);
+    $this->documentMe($entity, $action, $params, $result, $function, $file, $description, $exampleName);
+    return $result;
+  }
+
+  /**
+   * Create test generated example in api/v3/examples.
+   *
+   * To turn this off (e.g. on the server) set
+   * define(DONT_DOCUMENT_TEST_CONFIG ,1);
+   * in your settings file
+   *
+   * @param string $entity
+   * @param string $action
+   * @param array $params
+   *   Array as passed to civicrm_api function.
+   * @param array $result
+   *   Array as received from the civicrm_api function.
+   * @param string $testFunction
+   *   Calling function - generally __FUNCTION__.
+   * @param string $testFile
+   *   Called from file - generally __FILE__.
+   * @param string $description
+   *   Descriptive text for the example file.
+   * @param string $exampleName
+   *   Name for this example file (CamelCase) - if omitted the action name will be substituted.
+   */
+  private function documentMe($entity, $action, $params, $result, $testFunction, $testFile, $description = "", $exampleName = NULL) {
+    if (defined('DONT_DOCUMENT_TEST_CONFIG') && DONT_DOCUMENT_TEST_CONFIG) {
+      return;
+    }
+    $entity = _civicrm_api_get_camel_name($entity);
+    $action = strtolower($action);
+
+    if (empty($exampleName)) {
+      // Attempt to convert lowercase action name to CamelCase.
+      // This is clunky/imperfect due to the convention of all lowercase actions.
+      $exampleName = CRM_Utils_String::convertStringToCamel($action);
+      $knownPrefixes = array(
+        'Get',
+        'Set',
+        'Create',
+        'Update',
+        'Send',
+      );
+      foreach ($knownPrefixes as $prefix) {
+        if (strpos($exampleName, $prefix) === 0 && $prefix != $exampleName) {
+          $exampleName[strlen($prefix)] = strtoupper($exampleName[strlen($prefix)]);
+        }
+      }
+    }
+
+    $this->tidyExampleResult($result);
+    if (isset($params['version'])) {
+      unset($params['version']);
+    }
+    // Format multiline description as array
+    $desc = array();
+    if (is_string($description) && strlen($description)) {
+      foreach (explode("\n", $description) as $line) {
+        $desc[] = trim($line);
+      }
+    }
+    $smarty = CRM_Core_Smarty::singleton();
+    $smarty->assign('testFunction', $testFunction);
+    $smarty->assign('function', _civicrm_api_get_entity_name_from_camel($entity) . "_$action");
+    foreach ($params as $index => $param) {
+      if (is_string($param)) {
+        $params[$index] = addslashes($param);
+      }
+    }
+    $smarty->assign('params', $params);
+    $smarty->assign('entity', $entity);
+    $smarty->assign('testFile', basename($testFile));
+    $smarty->assign('description', $desc);
+    $smarty->assign('result', $result);
+    $smarty->assign('action', $action);
+
+    global $civicrm_root;
+    if (file_exists($civicrm_root . '/tests/templates/documentFunction.tpl')) {
+      if (!is_dir($civicrm_root . "/api/v3/examples/$entity")) {
+        mkdir($civicrm_root . "/api/v3/examples/$entity");
+      }
+      $f = fopen($civicrm_root . "/api/v3/examples/$entity/$exampleName.php", "w+b");
+      fwrite($f, $smarty->fetch($civicrm_root . '/tests/templates/documentFunction.tpl'));
+      fclose($f);
+    }
+  }
+
+  /**
+   * Tidy up examples array so that fields that change often ..don't
+   * and debug related fields are unset
+   *
+   * @param array $result
+   */
+  public function tidyExampleResult(&$result) {
+    if (!is_array($result)) {
+      return;
+    }
+    $fieldsToChange = array(
+      'hash' => '67eac7789eaee00',
+      'modified_date' => '2012-11-14 16:02:35',
+      'created_date' => '2013-07-28 08:49:19',
+      'create_date' => '20120130621222105',
+      'application_received_date' => '20130728084957',
+      'in_date' => '2013-07-28 08:50:19',
+      'scheduled_date' => '20130728085413',
+      'approval_date' => '20130728085413',
+      'pledge_start_date_high' => '20130726090416',
+      'start_date' => '2013-07-29 00:00:00',
+      'event_start_date' => '2013-07-29 00:00:00',
+      'end_date' => '2013-08-04 00:00:00',
+      'event_end_date' => '2013-08-04 00:00:00',
+      'decision_date' => '20130805000000',
+    );
+
+    $keysToUnset = array('xdebug', 'undefined_fields');
+    foreach ($keysToUnset as $unwantedKey) {
+      if (isset($result[$unwantedKey])) {
+        unset($result[$unwantedKey]);
+      }
+    }
+    if (isset($result['values'])) {
+      if (!is_array($result['values'])) {
+        return;
+      }
+      $resultArray = &$result['values'];
+    }
+    elseif (is_array($result)) {
+      $resultArray = &$result;
+    }
+    else {
+      return;
+    }
+
+    foreach ($resultArray as $index => &$values) {
+      if (!is_array($values)) {
+        continue;
+      }
+      foreach ($values as $key => &$value) {
+        if (substr($key, 0, 3) == 'api' && is_array($value)) {
+          if (isset($value['is_error'])) {
+            // we have a std nested result format
+            $this->tidyExampleResult($value);
+          }
+          else {
+            foreach ($value as &$nestedResult) {
+              // this is an alternative syntax for nested results a keyed array of results
+              $this->tidyExampleResult($nestedResult);
+            }
+          }
+        }
+        if (in_array($key, $keysToUnset)) {
+          unset($values[$key]);
+          break;
+        }
+        if (array_key_exists($key, $fieldsToChange) && !empty($value)) {
+          $value = $fieldsToChange[$key];
+        }
+        if (is_string($value)) {
+          $value = addslashes($value);
+        }
+      }
+    }
+  }
+
+}
diff --git a/civicrm/Civi/Test/Api3TestTrait.php b/civicrm/Civi/Test/Api3TestTrait.php
new file mode 100644
index 0000000000..767c723390
--- /dev/null
+++ b/civicrm/Civi/Test/Api3TestTrait.php
@@ -0,0 +1,262 @@
+<?php
+
+namespace Civi\Test;
+
+/**
+ * Class Api3TestTrait
+ * @package Civi\Test
+ *
+ * This trait defines a number of helper functions for testing APIv3. Commonly
+ * used helpers include `callAPISuccess()`, `callAPIFailure()`,
+ * `assertAPISuccess()`, and `assertAPIFailure()`.
+ *
+ * This trait is intended for use with PHPUnit-based test cases.
+ */
+trait Api3TestTrait {
+
+  /**
+   * Api version - easier to override than just a define
+   */
+  protected $_apiversion = 3;
+
+  /**
+   * Check that api returned 'is_error' => 1
+   * else provide full message
+   * @param array $result
+   * @param $expected
+   * @param array $valuesToExclude
+   * @param string $prefix
+   *   Extra test to add to message.
+   */
+  public function assertAPIArrayComparison($result, $expected, $valuesToExclude = array(), $prefix = '') {
+    $valuesToExclude = array_merge($valuesToExclude, array('debug', 'xdebug', 'sequential'));
+    foreach ($valuesToExclude as $value) {
+      if (isset($result[$value])) {
+        unset($result[$value]);
+      }
+      if (isset($expected[$value])) {
+        unset($expected[$value]);
+      }
+    }
+    $this->assertEquals($result, $expected, "api result array comparison failed " . $prefix . print_r($result, TRUE) . ' was compared to ' . print_r($expected, TRUE));
+  }
+
+  /**
+   * Check that a deleted item has been deleted.
+   *
+   * @param $entity
+   * @param $id
+   */
+  public function assertAPIDeleted($entity, $id) {
+    $this->callAPISuccess($entity, 'getcount', array('id' => $id), 0);
+  }
+
+  /**
+   * Check that api returned 'is_error' => 1.
+   *
+   * @param array $apiResult
+   *   Api result.
+   * @param string $prefix
+   *   Extra test to add to message.
+   * @param null $expectedError
+   */
+  public function assertAPIFailure($apiResult, $prefix = '', $expectedError = NULL) {
+    if (!empty($prefix)) {
+      $prefix .= ': ';
+    }
+    if ($expectedError && !empty($apiResult['is_error'])) {
+      $this->assertEquals($expectedError, $apiResult['error_message'], 'api error message not as expected' . $prefix);
+    }
+    $this->assertEquals(1, $apiResult['is_error'], "api call should have failed but it succeeded " . $prefix . (print_r($apiResult, TRUE)));
+    $this->assertNotEmpty($apiResult['error_message']);
+  }
+
+  /**
+   * Check that api returned 'is_error' => 0.
+   *
+   * @param array $apiResult
+   *   Api result.
+   * @param string $prefix
+   *   Extra test to add to message.
+   */
+  public function assertAPISuccess($apiResult, $prefix = '') {
+    if (!empty($prefix)) {
+      $prefix .= ': ';
+    }
+    $errorMessage = empty($apiResult['error_message']) ? '' : " " . $apiResult['error_message'];
+
+    if (!empty($apiResult['debug_information'])) {
+      $errorMessage .= "\n " . print_r($apiResult['debug_information'], TRUE);
+    }
+    if (!empty($apiResult['trace'])) {
+      $errorMessage .= "\n" . print_r($apiResult['trace'], TRUE);
+    }
+    $this->assertEquals(0, $apiResult['is_error'], $prefix . $errorMessage);
+  }
+
+  /**
+   * This function exists to wrap api functions.
+   * so we can ensure they fail where expected & throw exceptions without litterering the test with checks
+   * @param string $entity
+   * @param string $action
+   * @param array $params
+   * @param string $expectedErrorMessage
+   *   Error.
+   * @param null $extraOutput
+   * @return array|int
+   */
+  public function callAPIFailure($entity, $action, $params, $expectedErrorMessage = NULL, $extraOutput = NULL) {
+    if (is_array($params)) {
+      $params += array(
+        'version' => $this->_apiversion,
+      );
+    }
+    $result = $this->civicrm_api($entity, $action, $params);
+    $this->assertAPIFailure($result, "We expected a failure for $entity $action but got a success", $expectedErrorMessage);
+    return $result;
+  }
+
+  /**
+   * wrap api functions.
+   * so we can ensure they succeed & throw exceptions without litterering the test with checks
+   *
+   * @param string $entity
+   * @param string $action
+   * @param array $params
+   * @param mixed $checkAgainst
+   *   Optional value to check result against, implemented for getvalue,.
+   *   getcount, getsingle. Note that for getvalue the type is checked rather than the value
+   *   for getsingle the array is compared against an array passed in - the id is not compared (for
+   *   better or worse )
+   *
+   * @return array|int
+   */
+  public function callAPISuccess($entity, $action, $params, $checkAgainst = NULL) {
+    $params = array_merge(array(
+      'version' => $this->_apiversion,
+      'debug' => 1,
+    ),
+      $params
+    );
+    switch (strtolower($action)) {
+      case 'getvalue':
+        return $this->callAPISuccessGetValue($entity, $params, $checkAgainst);
+
+      case 'getsingle':
+        return $this->callAPISuccessGetSingle($entity, $params, $checkAgainst);
+
+      case 'getcount':
+        return $this->callAPISuccessGetCount($entity, $params, $checkAgainst);
+    }
+    $result = $this->civicrm_api($entity, $action, $params);
+    $this->assertAPISuccess($result, "Failure in api call for $entity $action");
+    return $result;
+  }
+
+  /**
+   * This function exists to wrap api getValue function & check the result
+   * so we can ensure they succeed & throw exceptions without litterering the test with checks
+   * There is a type check in this
+   * @param string $entity
+   * @param array $params
+   * @param null $count
+   * @throws Exception
+   * @return array|int
+   */
+  public function callAPISuccessGetCount($entity, $params, $count = NULL) {
+    $params += array(
+      'version' => $this->_apiversion,
+      'debug' => 1,
+    );
+    $result = $this->civicrm_api($entity, 'getcount', $params);
+    if (!is_int($result) || !empty($result['is_error']) || isset($result['values'])) {
+      throw new Exception('Invalid getcount result : ' . print_r($result, TRUE) . " type :" . gettype($result));
+    }
+    if (is_int($count)) {
+      $this->assertEquals($count, $result, "incorrect count returned from $entity getcount");
+    }
+    return $result;
+  }
+
+  /**
+   * This function exists to wrap api getsingle function & check the result
+   * so we can ensure they succeed & throw exceptions without litterering the test with checks
+   *
+   * @param string $entity
+   * @param array $params
+   * @param array $checkAgainst
+   *   Array to compare result against.
+   *   - boolean
+   *   - integer
+   *   - double
+   *   - string
+   *   - array
+   *   - object
+   *
+   * @throws Exception
+   * @return array|int
+   */
+  public function callAPISuccessGetSingle($entity, $params, $checkAgainst = NULL) {
+    $params += array(
+      'version' => $this->_apiversion,
+    );
+    $result = $this->civicrm_api($entity, 'getsingle', $params);
+    if (!is_array($result) || !empty($result['is_error']) || isset($result['values'])) {
+      throw new Exception('Invalid getsingle result' . print_r($result, TRUE));
+    }
+    if ($checkAgainst) {
+      // @todo - have gone with the fn that unsets id? should we check id?
+      $this->checkArrayEquals($result, $checkAgainst);
+    }
+    return $result;
+  }
+
+  /**
+   * This function exists to wrap api getValue function & check the result
+   * so we can ensure they succeed & throw exceptions without litterering the test with checks
+   * There is a type check in this
+   *
+   * @param string $entity
+   * @param array $params
+   * @param string $type
+   *   Per http://php.net/manual/en/function.gettype.php possible types.
+   *   - boolean
+   *   - integer
+   *   - double
+   *   - string
+   *   - array
+   *   - object
+   *
+   * @return array|int
+   */
+  public function callAPISuccessGetValue($entity, $params, $type = NULL) {
+    $params += array(
+      'version' => $this->_apiversion,
+      'debug' => 1,
+    );
+    $result = $this->civicrm_api($entity, 'getvalue', $params);
+    if ($type) {
+      if ($type == 'integer') {
+        // api seems to return integers as strings
+        $this->assertTrue(is_numeric($result), "expected a numeric value but got " . print_r($result, 1));
+      }
+      else {
+        $this->assertType($type, $result, "returned result should have been of type $type but was ");
+      }
+    }
+    return $result;
+  }
+
+  /**
+   * A stub for the API interface. This can be overriden by subclasses to change how the API is called.
+   *
+   * @param $entity
+   * @param $action
+   * @param array $params
+   * @return array|int
+   */
+  public function civicrm_api($entity, $action, $params) {
+    return civicrm_api($entity, $action, $params);
+  }
+
+}
diff --git a/civicrm/api/v3/Campaign.php b/civicrm/api/v3/Campaign.php
index c730030eb4..2156404511 100644
--- a/civicrm/api/v3/Campaign.php
+++ b/civicrm/api/v3/Campaign.php
@@ -58,6 +58,7 @@ function civicrm_api3_campaign_create($params) {
  */
 function _civicrm_api3_campaign_create_spec(&$params) {
   $params['title']['api.required'] = 1;
+  $params['is_active']['api.default'] = 1;
 }
 
 /**
diff --git a/civicrm/bower_components/crossfilter2/.bower.json b/civicrm/bower_components/crossfilter2/.bower.json
index d7363b6302..5b7d75c17f 100644
--- a/civicrm/bower_components/crossfilter2/.bower.json
+++ b/civicrm/bower_components/crossfilter2/.bower.json
@@ -25,12 +25,12 @@
     "test",
     "tests"
   ],
-  "version": "1.4.5",
-  "_release": "1.4.5",
+  "version": "1.4.6",
+  "_release": "1.4.6",
   "_resolution": {
     "type": "version",
-    "tag": "1.4.5",
-    "commit": "1ab783060946492b38a902e6ec4816c68ec79127"
+    "tag": "1.4.6",
+    "commit": "f53ac958a21902e98a59fc230bf87699619bef34"
   },
   "_source": "https://github.com/crossfilter/crossfilter.git",
   "_target": "~1.4",
diff --git a/civicrm/bower_components/crossfilter2/crossfilter.js b/civicrm/bower_components/crossfilter2/crossfilter.js
index 49b664e715..f017a69779 100644
--- a/civicrm/bower_components/crossfilter2/crossfilter.js
+++ b/civicrm/bower_components/crossfilter2/crossfilter.js
@@ -1,4 +1,4 @@
-(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.crossfilter = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
+(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.crossfilter = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
 module.exports = require("./src/crossfilter").crossfilter;
 
 },{"./src/crossfilter":6}],2:[function(require,module,exports){
@@ -938,7 +938,7 @@ module.exports = result;
 
 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
 },{}],3:[function(require,module,exports){
-module.exports={"version":"1.4.5"}
+module.exports={"version":"1.4.6"}
 },{}],4:[function(require,module,exports){
 if (typeof Uint8Array !== "undefined") {
   var crossfilter_array8 = function(n) { return new Uint8Array(n); };
@@ -1288,23 +1288,26 @@ function crossfilter() {
     triggerOnChange('dataRemoved');
   }
 
-  // Return true if the data element at index i is filtered IN.
-  // Optionally, ignore the filters of any dimensions in the ignore_dimensions list.
-  function isElementFiltered(i, ignore_dimensions) {
+  function maskForDimensions(dimensions) {
     var n,
         d,
-        id,
         len,
+        id,
         mask = Array(filters.subarrays);
     for (n = 0; n < filters.subarrays; n++) { mask[n] = ~0; }
-    if (ignore_dimensions) {
-      for (d = 0, len = ignore_dimensions.length; d < len; d++) {
-        // The top bits of the ID are the subarray offset and the lower bits are the bit
-        // offset of the "one" mask.
-        id = ignore_dimensions[d].id();
-        mask[id >> 7] &= ~(0x1 << (id & 0x3f));
-      }
+    for (d = 0, len = dimensions.length; d < len; d++) {
+      // The top bits of the ID are the subarray offset and the lower bits are the bit
+      // offset of the "one" mask.
+      id = dimensions[d].id();
+      mask[id >> 7] &= ~(0x1 << (id & 0x3f));
     }
+    return mask;
+  }
+
+  // Return true if the data element at index i is filtered IN.
+  // Optionally, ignore the filters of any dimensions in the ignore_dimensions list.
+  function isElementFiltered(i, ignore_dimensions) {
+    var mask = maskForDimensions(ignore_dimensions || []);
     return filters.zeroExceptMask(i,mask);
   }
 
@@ -2594,13 +2597,14 @@ function crossfilter() {
     return data;
   }
 
-  // Returns row data with all dimension filters applied
-  function allFiltered() {
+  // Returns row data with all dimension filters applied, except for filters in ignore_dimensions
+  function allFiltered(ignore_dimensions) {
     var array = [],
-        i = 0;
+        i = 0,
+        mask = maskForDimensions(ignore_dimensions || []);
 
       for (i = 0; i < n; i++) {
-        if (filters.zero(i)) {
+        if (filters.zeroExceptMask(i, mask)) {
           array.push(data[i]);
         }
       }
@@ -3160,4 +3164,4 @@ function crossfilter_zero() {
 module.exports = crossfilter_zero;
 
 },{}]},{},[1])(1)
-});
\ No newline at end of file
+});
diff --git a/civicrm/bower_components/crossfilter2/crossfilter.min.js b/civicrm/bower_components/crossfilter2/crossfilter.min.js
index 46114a21e3..506eed85ea 100644
--- a/civicrm/bower_components/crossfilter2/crossfilter.min.js
+++ b/civicrm/bower_components/crossfilter2/crossfilter.min.js
@@ -1 +1 @@
-!function(r){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=r();else if("function"==typeof define&&define.amd)define([],r);else{var t;t="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,t.crossfilter=r()}}(function(){return function r(t,e,n){function o(u,f){if(!e[u]){if(!t[u]){var a="function"==typeof require&&require;if(!f&&a)return a(u,!0);if(i)return i(u,!0);var s=new Error("Cannot find module '"+u+"'");throw s.code="MODULE_NOT_FOUND",s}var c=e[u]={exports:{}};t[u][0].call(c.exports,function(r){var e=t[u][1][r];return o(e?e:r)},c,c.exports,r,t,e,n)}return e[u].exports}for(var i="function"==typeof require&&require,u=0;u<n.length;u++)o(n[u]);return o}({1:[function(r,t){t.exports=r("./src/crossfilter").crossfilter},{"./src/crossfilter":6}],2:[function(r,t){(function(r){function e(r,t){return null==r?void 0:r[t]}function n(r){var t=!1;if(null!=r&&"function"!=typeof r.toString)try{t=!!(r+"")}catch(e){}return t}function o(r){var t=-1,e=r?r.length:0;for(this.clear();++t<e;){var n=r[t];this.set(n[0],n[1])}}function i(){this.__data__=dt?dt(null):{}}function u(r){return this.has(r)&&delete this.__data__[r]}function f(r){var t=this.__data__;if(dt){var e=t[r];return e===T?void 0:e}return st.call(t,r)?t[r]:void 0}function a(r){var t=this.__data__;return dt?void 0!==t[r]:st.call(t,r)}function s(r,t){var e=this.__data__;return e[r]=dt&&void 0===t?T:t,this}function c(r){var t=-1,e=r?r.length:0;for(this.clear();++t<e;){var n=r[t];this.set(n[0],n[1])}}function l(){this.__data__=[]}function h(r){var t=this.__data__,e=w(t,r);if(0>e)return!1;var n=t.length-1;return e==n?t.pop():pt.call(t,e,1),!0}function p(r){var t=this.__data__,e=w(t,r);return 0>e?void 0:t[e][1]}function v(r){return w(this.__data__,r)>-1}function d(r,t){var e=this.__data__,n=w(e,r);return 0>n?e.push([r,t]):e[n][1]=t,this}function y(r){var t=-1,e=r?r.length:0;for(this.clear();++t<e;){var n=r[t];this.set(n[0],n[1])}}function g(){this.__data__={hash:new o,map:new(vt||c),string:new o}}function b(r){return k(this,r).delete(r)}function _(r){return k(this,r).get(r)}function x(r){return k(this,r).has(r)}function m(r,t){return k(this,r).set(r,t),this}function w(r,t){for(var e=r.length;e--;)if(q(r[e][0],t))return e;return-1}function E(r){if(!R(r)||M(r))return!1;var t=N(r)||n(r)?lt:Z;return t.test(C(r))}function O(r){if("string"==typeof r)return r;if(D(r))return gt?gt.call(r):"";var t=r+"";return"0"==t&&1/r==-W?"-0":t}function A(r){return _t(r)?r:bt(r)}function k(r,t){var e=r.__data__;return S(t)?e["string"==typeof t?"string":"hash"]:e.map}function z(r,t){var n=e(r,t);return E(n)?n:void 0}function j(r,t){if(_t(r))return!1;var e=typeof r;return"number"==e||"symbol"==e||"boolean"==e||null==r||D(r)?!0:K.test(r)||!H.test(r)||null!=t&&r in Object(t)}function S(r){var t=typeof r;return"string"==t||"number"==t||"symbol"==t||"boolean"==t?"__proto__"!==r:null===r}function M(r){return!!ft&&ft in r}function F(r){if("string"==typeof r||D(r))return r;var t=r+"";return"0"==t&&1/r==-W?"-0":t}function C(r){if(null!=r){try{return at.call(r)}catch(t){}try{return r+""}catch(t){}}return""}function $(r,t){if("function"!=typeof r||t&&"function"!=typeof t)throw new TypeError(P);var e=function(){var n=arguments,o=t?t.apply(this,n):n[0],i=e.cache;if(i.has(o))return i.get(o);var u=r.apply(this,n);return e.cache=i.set(o,u),u};return e.cache=new($.Cache||y),e}function q(r,t){return r===t||r!==r&&t!==t}function N(r){var t=R(r)?ct.call(r):"";return t==J||t==G}function R(r){var t=typeof r;return!!r&&("object"==t||"function"==t)}function U(r){return!!r&&"object"==typeof r}function D(r){return"symbol"==typeof r||U(r)&&ct.call(r)==B}function I(r){return null==r?"":O(r)}function L(r,t,e){t=j(t,r)?[t]:A(t);var n=-1,o=t.length;for(o||(r=void 0,o=1);++n<o;){var i=null==r?void 0:r[F(t[n])];void 0===i&&(n=o,i=e),r=N(i)?i.call(r):i}return r}var P="Expected a function",T="__lodash_hash_undefined__",W=1/0,J="[object Function]",G="[object GeneratorFunction]",B="[object Symbol]",H=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,K=/^\w*$/,Q=/^\./,V=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,X=/[\\^$.*+?()[\]{}|]/g,Y=/\\(\\)?/g,Z=/^\[object .+?Constructor\]$/,rt="object"==typeof r&&r&&r.Object===Object&&r,tt="object"==typeof self&&self&&self.Object===Object&&self,et=rt||tt||Function("return this")(),nt=Array.prototype,ot=Function.prototype,it=Object.prototype,ut=et["__core-js_shared__"],ft=function(){var r=/[^.]+$/.exec(ut&&ut.keys&&ut.keys.IE_PROTO||"");return r?"Symbol(src)_1."+r:""}(),at=ot.toString,st=it.hasOwnProperty,ct=it.toString,lt=RegExp("^"+at.call(st).replace(X,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),ht=et.Symbol,pt=nt.splice,vt=z(et,"Map"),dt=z(Object,"create"),yt=ht?ht.prototype:void 0,gt=yt?yt.toString:void 0;o.prototype.clear=i,o.prototype.delete=u,o.prototype.get=f,o.prototype.has=a,o.prototype.set=s,c.prototype.clear=l,c.prototype.delete=h,c.prototype.get=p,c.prototype.has=v,c.prototype.set=d,y.prototype.clear=g,y.prototype.delete=b,y.prototype.get=_,y.prototype.has=x,y.prototype.set=m;var bt=$(function(r){r=I(r);var t=[];return Q.test(r)&&t.push(""),r.replace(V,function(r,e,n,o){t.push(n?o.replace(Y,"$1"):e||r)}),t});$.Cache=y;var _t=Array.isArray;t.exports=L}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],3:[function(r,t){t.exports={version:"1.4.5"}},{}],4:[function(r,t){function e(r){for(var t=new Array(r),e=-1;++e<r;)t[e]=0;return t}function n(r,t){for(var e=r.length;t>e;)r[e++]=0;return r}function o(r,t){if(t>32)throw new Error("invalid array width!");return r}function i(r){this.length=r,this.subarrays=1,this.width=8,this.masks={0:0},this[0]=u(r)}if("undefined"!=typeof Uint8Array)var u=function(r){return new Uint8Array(r)},f=function(r){return new Uint16Array(r)},a=function(r){return new Uint32Array(r)},s=function(r,t){if(r.length>=t)return r;var e=new r.constructor(t);return e.set(r),e},c=function(r,t){var e;switch(t){case 16:e=f(r.length);break;case 32:e=a(r.length);break;default:throw new Error("invalid array width!")}return e.set(r),e};i.prototype.lengthen=function(r){var t,e;for(t=0,e=this.subarrays;e>t;++t)this[t]=s(this[t],r);this.length=r},i.prototype.add=function(){var r,t,e,n,o;for(n=0,o=this.subarrays;o>n;++n)if(r=this.masks[n],t=this.width-32*n,e=~r&-~r,!(t>=32)||e)return 32>t&&e&1<<t&&(this[n]=c(this[n],t<<=1),this.width=32*n+t),this.masks[n]|=e,{offset:n,one:e};return this[this.subarrays]=u(this.length),this.masks[this.subarrays]=1,this.width+=8,{offset:this.subarrays++,one:1}},i.prototype.copy=function(r,t){var e,n;for(e=0,n=this.subarrays;n>e;++e)this[e][r]=this[e][t]},i.prototype.truncate=function(r){var t,e;for(t=0,e=this.subarrays;e>t;++t){for(var n=this.length-1;n>=r;n--)this[t][n]=0;this[t].length=r}this.length=r},i.prototype.zero=function(r){var t,e;for(t=0,e=this.subarrays;e>t;++t)if(this[t][r])return!1;return!0},i.prototype.zeroExcept=function(r,t,e){var n,o;for(n=0,o=this.subarrays;o>n;++n)if(n===t?this[n][r]&e:this[n][r])return!1;return!0},i.prototype.zeroExceptMask=function(r,t){var e,n;for(e=0,n=this.subarrays;n>e;++e)if(this[e][r]&t[e])return!1;return!0},i.prototype.only=function(r,t,e){var n,o;for(n=0,o=this.subarrays;o>n;++n)if(this[n][r]!=(n===t?e:0))return!1;return!0},i.prototype.onlyExcept=function(r,t,e,n,o){var i,u,f;for(u=0,f=this.subarrays;f>u;++u)if(i=this[u][r],u===t&&(i&=e),i!=(u===n?o:0))return!1;return!0},t.exports={array8:e,array16:e,array32:e,arrayLengthen:n,arrayWiden:o,bitarray:i}},{}],5:[function(r,t){"use strict";function e(r){function t(t,e,n,o){for(;o>n;){var i=n+o>>>1;r(t[i])<e?n=i+1:o=i}return n}function e(t,e,n,o){for(;o>n;){var i=n+o>>>1;e<r(t[i])?o=i:n=i+1}return n}return e.right=e,e.left=t,e}var n=r("./identity");t.exports=e(n),t.exports.by=e},{"./identity":10}],6:[function(r,t,e){"use strict";function n(){function r(r){var t=S,e=r.length;return e&&(j=j.concat(r),k.lengthen(S+=e),F.forEach(function(n){n(r,t,e)}),A("dataAdded")),z}function t(r){for(var t=o(S,S),e=[],n="function"==typeof r,i=function(t){return n?r(j[t],t):k.zero(t)},u=0,f=0;S>u;++u)i(u)?(e.push(u),t[u]=m):t[u]=f++;M.forEach(function(r){r(-1,-1,[],e,!0)}),C.forEach(function(r){r(t)});for(var a=0,s=0;S>a;++a)t[a]!==m&&(a!==s&&(k.copy(s,a),j[s]=j[a]),++s);j.length=S=s,k.truncate(s),A("dataRemoved")}function e(r,t){var e,n,o,i,u=Array(k.subarrays);for(e=0;e<k.subarrays;e++)u[e]=-1;if(t)for(n=0,i=t.length;i>n;n++)o=t[n].id(),u[o>>7]&=~(1<<(63&o));return k.zeroExceptMask(r,u)}function n(r,t){function e(e,n,u){if(t){pt=0,z=0,ot=[];for(var a=0;a<e.length;a++)for(z=0,ot=r(e[a]);z<ot.length;z++)pt++;Q=[],Y=i(e.length),rt=o(pt,1);for(var s=i(pt),c=0,l=0;l<e.length;l++)if(ot=r(e[l]),ot.length)for(Y[l]=ot.length,z=0;z<ot.length;z++)Q.push(ot[z]),s[c]=l,c++;else Y[l]=0,ut.push(l+n);var h=ft(i(pt),0,pt);Q=y(Q,h),V=y(s,h)}else Q=e.map(r),V=ft(i(u),0,u),Q=y(Q,V);t&&(u=pt);var p=at(Q),v=p[0],d=p[1];if(tt)for(var g=0;u>g;++g)tt(Q[g],g)||(k[G][V[g]+n]|=W,t&&(rt[g]=1));else{for(var b=0;v>b;++b)k[G][V[b]+n]|=W,t&&(rt[b]=1);for(var _=d;u>_;++_)k[G][V[_]+n]|=W,t&&(rt[_]=1)}if(!n)return H=Q,K=V,X=Y,Z=rt,lt=v,ht=d,void 0;var x,m=H,w=K,E=Z,O=0;if(a=0,t&&(x=n,n=m.length,u=pt),H=t?new Array(n+u):new Array(S),K=t?new Array(n+u):o(S,S),t&&(Z=o(n+u,1)),t){var A=X.length;X=f.arrayLengthen(X,S);for(var z=0;S>z+A;z++)X[z+A]=Y[z]}for(var j=0;n>a&&u>O;++j)m[a]<Q[O]?(H[j]=m[a],t&&(Z[j]=E[a]),K[j]=w[a++]):(H[j]=Q[O],t&&(Z[j]=rt[O]),K[j]=V[O++]+(t?x:n));for(;n>a;++a,++j)H[j]=m[a],t&&(Z[j]=E[a]),K[j]=w[a];for(;u>O;++O,++j)H[j]=Q[O],t&&(Z[j]=rt[O]),K[j]=V[O]+(t?x:n);p=at(H),lt=p[0],ht=p[1]}function n(r,t,e){st.forEach(function(r){r(Q,V,t,e)}),Q=V=null}function d(r){if(t){for(var e=0,n=0;e<ut.length;e++)r[ut[e]]!==m&&(ut[n]=r[ut[e]],n++);for(ut.length=n,e=0,n=0;S>e;e++)r[e]!==m&&(n!==e&&(X[n]=X[e]),n++);X.length=n}for(var o,i=H.length,u=0,f=0;i>u;++u)o=K[u],r[o]!==m&&(u!==f&&(H[f]=H[u]),K[f]=r[o],t&&(Z[f]=Z[u]),++f);for(H.length=f,t&&(Z.length=f);i>f;)K[f++]=0;var a=at(H);lt=a[0],ht=a[1]}function _(r){var e=r[0],n=r[1];if(tt)return tt=null,q(function(r,t){return t>=e&&n>t},0===r[0]&&r[1]===H.length),lt=e,ht=n,it;var o,i,u,f=[],a=[],s=[],c=[];if(lt>e)for(o=e,i=Math.min(lt,n);i>o;++o)f.push(K[o]),s.push(o);else if(e>lt)for(o=lt,i=Math.min(e,ht);i>o;++o)a.push(K[o]),c.push(o);if(n>ht)for(o=Math.max(e,ht),i=n;i>o;++o)f.push(K[o]),s.push(o);else if(ht>n)for(o=Math.max(lt,n),i=ht;i>o;++o)a.push(K[o]),c.push(o);if(t){var l=[],h=[];for(o=0;o<f.length;o++)X[f[o]]++,Z[s[o]]=0,1===X[f[o]]&&(k[G][f[o]]^=W,l.push(f[o]));for(o=0;o<a.length;o++)X[a[o]]--,Z[c[o]]=1,0===X[a[o]]&&(k[G][a[o]]^=W,h.push(a[o]));if(f=l,a=h,0===r[0]&&r[1]===H.length)for(o=0;o<ut.length;o++)k[G][u=ut[o]]&W&&(k[G][u]^=W,f.push(u));else for(o=0;o<ut.length;o++)k[G][u=ut[o]]&W||(k[G][u]^=W,a.push(u))}else{for(o=0;o<f.length;o++)k[G][f[o]]^=W;for(o=0;o<a.length;o++)k[G][a[o]]^=W}return lt=e,ht=n,M.forEach(function(r){r(W,G,f,a)}),A("filtered"),it}function w(r){return null==r?z():Array.isArray(r)?O(r):"function"==typeof r?$(r):E(r)}function E(r){return et=r,nt=!0,_((at=a.filterExact(v,r))(H))}function O(r){return et=r,nt=!0,_((at=a.filterRange(v,r))(H))}function z(){return et=void 0,nt=!1,_((at=a.filterAll)(H))}function $(r){et=r,nt=!0,tt=r,at=a.filterAll,q(r,!1);var t=at(H);return lt=t[0],ht=t[1],it}function q(r,e){var n,o,i,u=[],f=[],a=[],s=[],c=H.length;if(!t)for(n=0;c>n;++n)!(k[G][o=K[n]]&W)^!!(i=r(H[n],n))&&(i?u.push(o):f.push(o));if(t)for(n=0;c>n;++n)r(H[n],n)?(u.push(K[n]),a.push(n)):(f.push(K[n]),s.push(n));if(t){var l=[],h=[];for(n=0;n<u.length;n++)1===Z[a[n]]&&(X[u[n]]++,Z[a[n]]=0,1===X[u[n]]&&(k[G][u[n]]^=W,l.push(u[n])));for(n=0;n<f.length;n++)0===Z[s[n]]&&(X[f[n]]--,Z[s[n]]=1,0===X[f[n]]&&(k[G][f[n]]^=W,h.push(f[n])));if(u=l,f=h,e)for(n=0;n<ut.length;n++)k[G][o=ut[n]]&W&&(k[G][o]^=W,u.push(o));else for(n=0;n<ut.length;n++)k[G][o=ut[n]]&W||(k[G][o]^=W,f.push(o))}else{for(n=0;n<u.length;n++)k[G][u[n]]&W&&(k[G][u[n]]&=J);for(n=0;n<f.length;n++)k[G][f[n]]&W||(k[G][f[n]]|=W)}M.forEach(function(r){r(W,G,u,f)}),A("filtered")}function N(){return et}function R(){return nt}function U(r,e){var n,o=[],i=ht,u=0;for(e&&e>0&&(u=e);--i>=lt&&r>0;)k.zero(n=K[i])&&(u>0?--u:(o.push(j[n]),--r));if(t)for(i=0;i<ut.length&&r>0;i++)k.zero(n=ut[i])&&(u>0?--u:(o.push(j[n]),--r));return o}function D(r,e){var n,o,i=[],u=0;if(e&&e>0&&(u=e),t)for(n=0;n<ut.length&&r>0;n++)k.zero(o=ut[n])&&(u>0?--u:(i.push(j[o]),--r));for(n=lt;ht>n&&r>0;)k.zero(o=K[n])&&(u>0?--u:(i.push(j[o]),--r)),n++;return i}function I(r){function e(e,n,s,l){function h(){return t?(B++,void 0):(++B===T&&(w=f.arrayWiden(w,P<<=1),q=f.arrayWiden(q,P),T=u(P)),void 0)}t&&(L=s,s=H.length-e.length,l=e.length);var p,y,g,b,_,x,m=$,w=t?[]:o(B,T),E=U,O=D,A=I,z=B,F=0,C=0;for(X&&(E=A=c),X&&(O=A=c),$=new Array(B),B=0,q=t?z?q:[]:z>1?f.arrayLengthen(q,S):o(S,T),z&&(g=(y=m[0]).key);l>C&&!((b=r(e[C]))>=b);)++C;for(;l>C;){for(y&&b>=g?(_=y,x=g,w[F]=B,y=m[++F],y&&(g=y.key)):(_={key:b,value:A()},x=b),$[B]=_;x>=b&&(p=n[C]+(t?L:s),t?q[p]?q[p].push(B):q[p]=[B]:q[p]=B,_.value=E(_.value,j[p],!0),k.zeroExcept(p,G,J)||(_.value=O(_.value,j[p],!1)),!(++C>=l));)b=r(e[C]);h()}for(;z>F;)$[w[F]=B]=m[F++],h();if(t)for(var N=0;S>N;N++)q[N]||(q[N]=[]);if(B>F)if(t)for(F=0;L>F;++F)for(N=0;N<q[F].length;N++)q[F][N]=w[q[F][N]];else for(F=0;s>F;++F)q[F]=w[q[F]];p=M.indexOf(Q),B>1||t?(Q=i,V=v):(!B&&Y&&(B=1,$=[{key:null,value:A()}]),1===B?(Q=a,V=d):(Q=c,V=c),q=null),M[p]=Q}function n(r){if(B>1||t){var e,n,u,f=B,s=$,l=o(f,f);if(t){for(e=0,u=0;S>e;++e)if(r[e]!==m){for(q[u]=q[e],n=0;n<q[u].length;n++)l[q[u][n]]=1;++u}}else for(e=0,u=0;S>e;++e)r[e]!==m&&(l[q[u]=q[e]]=1,++u);for($=[],B=0,e=0;f>e;++e)l[e]&&(l[e]=B++,$.push(s[e]));if(B>1||t)if(t)for(e=0;u>e;++e)for(n=0;n<q[e].length;++n)q[e][n]=l[q[e][n]];else for(e=0;u>e;++e)q[e]=l[q[e]];else q=null;M[M.indexOf(Q)]=B>1||t?(V=v,Q=i):1===B?(V=d,Q=a):V=Q=c}else if(1===B){if(Y)return;for(var h=0;S>h;++h)if(r[h]!==m)return;$=[],B=0,M[M.indexOf(Q)]=Q=V=c}}function i(r,e,n,o,i){if(!(r===W&&e===G||X)){var u,f,a,s,c;if(t){for(u=0,s=n.length;s>u;++u)if(k.zeroExcept(a=n[u],G,J))for(f=0;f<q[a].length;f++)c=$[q[a][f]],c.value=U(c.value,j[a],!1,f);for(u=0,s=o.length;s>u;++u)if(k.onlyExcept(a=o[u],G,J,e,r))for(f=0;f<q[a].length;f++)c=$[q[a][f]],c.value=D(c.value,j[a],i,f)}else{for(u=0,s=n.length;s>u;++u)k.zeroExcept(a=n[u],G,J)&&(c=$[q[a]],c.value=U(c.value,j[a],!1));for(u=0,s=o.length;s>u;++u)k.onlyExcept(a=o[u],G,J,e,r)&&(c=$[q[a]],c.value=D(c.value,j[a],i))}}}function a(r,t,e,n,o){if(!(r===W&&t===G||X)){var i,u,f,a=$[0];for(i=0,f=e.length;f>i;++i)k.zeroExcept(u=e[i],G,J)&&(a.value=U(a.value,j[u],!1));for(i=0,f=n.length;f>i;++i)k.onlyExcept(u=n[i],G,J,t,r)&&(a.value=D(a.value,j[u],o))}}function v(){var r,e,n;for(r=0;B>r;++r)$[r].value=I();if(t){for(r=0;S>r;++r)for(e=0;e<q[r].length;e++)n=$[q[r][e]],n.value=U(n.value,j[r],!0,e);for(r=0;S>r;++r)if(!k.zeroExcept(r,G,J))for(e=0;e<q[r].length;e++)n=$[q[r][e]],n.value=D(n.value,j[r],!1,e)}else{for(r=0;S>r;++r)n=$[q[r]],n.value=U(n.value,j[r],!0);for(r=0;S>r;++r)k.zeroExcept(r,G,J)||(n=$[q[r]],n.value=D(n.value,j[r],!1))}}function d(){var r,t=$[0];for(t.value=I(),r=0;S>r;++r)t.value=U(t.value,j[r],!0);for(r=0;S>r;++r)k.zeroExcept(r,G,J)||(t.value=D(t.value,j[r],!1))}function y(){return X&&(V(),X=!1),$}function g(r){var t=N(y(),0,$.length,r);return R.sort(t,0,t.length)}function _(r,t,e){return U=r,D=t,I=e,X=!0,F}function x(){return _(b.reduceIncrement,b.reduceDecrement,l)}function w(r){return _(b.reduceAdd(r),b.reduceSubtract(r),l)}function E(r){function t(t){return r(t.value)}return N=h.by(t),R=p.by(t),F}function O(){return E(s)}function A(){return B}function z(){var r=M.indexOf(Q);return r>=0&&M.splice(r,1),r=st.indexOf(e),r>=0&&st.splice(r,1),r=C.indexOf(n),r>=0&&C.splice(r,1),r=ct.indexOf(F),r>=0&&ct.splice(r,1),F}var F={top:g,all:y,reduce:_,reduceCount:x,reduceSum:w,order:E,orderNatural:O,size:A,dispose:z,remove:z};ct.push(F);var $,q,N,R,U,D,I,L,P=8,T=u(P),B=0,Q=c,V=c,X=!0,Y=r===c;return arguments.length<1&&(r=s),M.push(Q),st.push(e),C.push(n),e(H,K,0,S),x().orderNatural()}function L(){var r=I(c),t=r.all;return delete r.all,delete r.top,delete r.order,delete r.orderNatural,delete r.size,r.value=function(){return t()[0].value},r}function P(){ct.forEach(function(r){r.dispose()});var r=F.indexOf(e);return r>=0&&F.splice(r,1),r=F.indexOf(n),r>=0&&F.splice(r,1),r=C.indexOf(d),r>=0&&C.splice(r,1),k.masks[G]&=J,z()}if("string"==typeof r){var T=r;r=function(r){return x(r,T)}}var W,J,G,B,H,K,Q,V,X,Y,Z,rt,tt,et,nt,ot,it={filter:w,filterExact:E,filterRange:O,filterFunction:$,filterAll:z,currentFilter:N,hasCurrentFilter:R,top:U,bottom:D,group:I,groupAll:L,dispose:P,remove:P,accessor:r,id:function(){return B}},ut=[],ft=g.by(function(r){return Q[r]}),at=a.filterAll,st=[],ct=[],lt=0,ht=0,pt=0;F.unshift(e),F.push(n),C.push(d);var vt=k.add();return G=vt.offset,W=vt.one,J=~W,B=G<<7|Math.log(W)/Math.log(2),e(j,0,S),n(j,0,S),it}function d(){function r(r,t){var e;if(!v)for(e=t;S>e;++e)a=s(a,j[e],!0),k.zero(e)||(a=c(a,j[e],!1))}function t(r,t,e,n,o){var i,u,f;if(!v){for(i=0,f=e.length;f>i;++i)k.zero(u=e[i])&&(a=s(a,j[u],o));for(i=0,f=n.length;f>i;++i)k.only(u=n[i],t,r)&&(a=c(a,j[u],o))}}function e(){var r;for(a=h(),r=0;S>r;++r)a=s(a,j[r],!0),k.zero(r)||(a=c(a,j[r],!1))}function n(r,t,e){return s=r,c=t,h=e,v=!0,p}function o(){return n(b.reduceIncrement,b.reduceDecrement,l)}function i(r){return n(b.reduceAdd(r),b.reduceSubtract(r),l)}function u(){return v&&(e(),v=!1),a}function f(){var e=M.indexOf(t);return e>=0&&M.splice(e,1),e=F.indexOf(r),e>=0&&F.splice(e,1),p}var a,s,c,h,p={reduce:n,reduceCount:o,reduceSum:i,value:u,dispose:f,remove:f},v=!0;return M.push(t),F.push(r),r(j,0,S),o()}function _(){return S}function w(){return j}function E(){var r=[],t=0;for(t=0;S>t;t++)k.zero(t)&&r.push(j[t]);return r}function O(r){return"function"!=typeof r?(console.warn("onChange callback parameter must be a function!"),void 0):($.push(r),function(){$.splice($.indexOf(r),1)})}function A(r){for(var t=0;t<$.length;t++)$[t](r)}var k,z={add:r,remove:t,dimension:n,groupAll:d,size:_,all:w,allFiltered:E,onChange:O,isElementFiltered:e},j=[],S=0,M=[],F=[],C=[],$=[];return k=new f.bitarray(0),arguments.length?r(arguments[0]):z}function o(r,t){return(257>t?f.array8:65537>t?f.array16:f.array32)(r)}function i(r){for(var t=o(r,r),e=-1;++e<r;)t[e]=e;return t}function u(r){return 8===r?256:16===r?65536:4294967296}var f=r("./array"),a=r("./filter"),s=r("./identity"),c=r("./null"),l=r("./zero"),h=r("./heapselect"),p=r("./heap"),v=r("./bisect"),d=r("./insertionsort"),y=r("./permute"),g=r("./quicksort"),b=r("./reduce"),_=r("./../package.json"),x=r("lodash.result"),m=-1;e.crossfilter=n,e.crossfilter.heap=p,e.crossfilter.heapselect=h,e.crossfilter.bisect=v,e.crossfilter.insertionsort=d,e.crossfilter.permute=y,e.crossfilter.quicksort=g,e.crossfilter.version=_.version},{"./../package.json":3,"./array":4,"./bisect":5,"./filter":7,"./heap":8,"./heapselect":9,"./identity":10,"./insertionsort":11,"./null":12,"./permute":13,"./quicksort":14,"./reduce":15,"./zero":16,"lodash.result":2}],7:[function(r,t){"use strict";function e(r,t){return function(e){var n=e.length;return[r.left(e,t,0,n),r.right(e,t,0,n)]}}function n(r,t){var e=t[0],n=t[1];return function(t){var o=t.length;return[r.left(t,e,0,o),r.left(t,n,0,o)]}}function o(r){return[0,r.length]}t.exports={filterExact:e,filterRange:n,filterAll:o}},{}],8:[function(r,t){"use strict";function e(r){function t(r,t,e){for(var o=e-t,i=(o>>>1)+1;--i>0;)n(r,i,o,t);return r}function e(r,t,e){for(var o,i=e-t;--i>0;)o=r[t],r[t]=r[t+i],r[t+i]=o,n(r,1,i,t);return r}function n(t,e,n,o){for(var i,u=t[--o+e],f=r(u);(i=e<<1)<=n&&(n>i&&r(t[o+i])>r(t[o+i+1])&&i++,!(f<=r(t[o+i])));)t[o+e]=t[o+i],e=i;t[o+e]=u}return t.sort=e,t}var n=r("./identity");t.exports=e(n),t.exports.by=e},{"./identity":10}],9:[function(r,t){"use strict";function e(r){function t(t,n,o,i){var u,f,a,s=new Array(i=Math.min(o-n,i));for(f=0;i>f;++f)s[f]=t[n++];if(e(s,0,i),o>n){u=r(s[0]);do r(a=t[n])>u&&(s[0]=a,u=r(e(s,0,i)[0]));while(++n<o)}return s}var e=o.by(r);return t}var n=r("./identity"),o=r("./heap");t.exports=e(n),t.exports.by=e},{"./heap":8,"./identity":10}],10:[function(r,t){"use strict";function e(r){return r}t.exports=e},{}],11:[function(r,t){"use strict";function e(r){function t(t,e,n){for(var o=e+1;n>o;++o){for(var i=o,u=t[o],f=r(u);i>e&&r(t[i-1])>f;--i)t[i]=t[i-1];t[i]=u}return t}return t}var n=r("./identity");t.exports=e(n),t.exports.by=e},{"./identity":10}],12:[function(r,t){"use strict";function e(){return null}t.exports=e},{}],13:[function(r,t){"use strict";function e(r,t,e){for(var n=0,o=t.length,i=e?JSON.parse(JSON.stringify(r)):new Array(o);o>n;++n)i[n]=r[t[n]];return i}t.exports=e},{}],14:[function(r,t){function e(r){function t(r,t,o){return(i>o-t?n:e)(r,t,o)}function e(e,n,o){var i,u=0|(o-n)/6,f=n+u,a=o-1-u,s=n+o-1>>1,c=s-u,l=s+u,h=e[f],p=r(h),v=e[c],d=r(v),y=e[s],g=r(y),b=e[l],_=r(b),x=e[a],m=r(x);p>d&&(i=h,h=v,v=i,i=p,p=d,d=i),_>m&&(i=b,b=x,x=i,i=_,_=m,m=i),p>g&&(i=h,h=y,y=i,i=p,p=g,g=i),d>g&&(i=v,v=y,y=i,i=d,d=g,g=i),p>_&&(i=h,h=b,b=i,i=p,p=_,_=i),g>_&&(i=y,y=b,b=i,i=g,g=_,_=i),d>m&&(i=v,v=x,x=i,i=d,d=m,m=i),d>g&&(i=v,v=y,y=i,i=d,d=g,g=i),_>m&&(i=b,b=x,x=i,i=_,_=m,m=i);var w=v,E=d,O=b,A=_;e[f]=h,e[c]=e[n],e[s]=y,e[l]=e[o-1],e[a]=x;var k=n+1,z=o-2,j=A>=E&&E>=A;if(j)for(var S=k;z>=S;++S){var M=e[S],F=r(M);if(E>F)S!==k&&(e[S]=e[k],e[k]=M),++k;else if(F>E)for(;;){var C=r(e[z]);{if(!(C>E)){if(E>C){e[S]=e[k],e[k++]=e[z],e[z--]=M;break}e[S]=e[z],e[z--]=M;break}z--}}}else!function(){for(var t=k;z>=t;t++){var n=e[t],o=r(n);if(E>o)t!==k&&(e[t]=e[k],e[k]=n),++k;else if(o>A)for(;;){var i=r(e[z]);{if(!(i>A)){E>i?(e[t]=e[k],e[k++]=e[z],e[z--]=n):(e[t]=e[z],e[z--]=n);break}if(z--,t>z)break}}}}();return e[n]=e[k-1],e[k-1]=w,e[o-1]=e[z+1],e[z+1]=O,t(e,n,k-1),t(e,z+2,o),j?e:(f>k&&z>a&&!function(){for(var t,n;(t=r(e[k]))<=E&&t>=E;)++k;for(;(n=r(e[z]))<=A&&n>=A;)--z;for(var o=k;z>=o;o++){var i=e[o],u=r(i);if(E>=u&&u>=E)o!==k&&(e[o]=e[k],e[k]=i),k++;else if(A>=u&&u>=A)for(;;){n=r(e[z]);{if(!(A>=n&&n>=A)){E>n?(e[o]=e[k],e[k++]=e[z],e[z--]=i):(e[o]=e[z],e[z--]=i);break}if(z--,o>z)break}}}}(),t(e,k,z+1))}var n=o.by(r);return t}var n=r("./identity"),o=r("./insertionsort"),i=32;t.exports=e(n),t.exports.by=e},{"./identity":10,"./insertionsort":11}],15:[function(r,t){"use strict";function e(r){return r+1}function n(r){return r-1}function o(r){return function(t,e){return t+ +r(e)}}function i(r){return function(t,e){return t-r(e)}}t.exports={reduceIncrement:e,reduceDecrement:n,reduceAdd:o,reduceSubtract:i}},{}],16:[function(r,t){"use strict";function e(){return 0}t.exports=e},{}]},{},[1])(1)});
\ No newline at end of file
+!function(r){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=r();else if("function"==typeof define&&define.amd)define([],r);else{var t;t="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,t.crossfilter=r()}}(function(){return function(){function r(t,e,n){function o(u,f){if(!e[u]){if(!t[u]){var a="function"==typeof require&&require;if(!f&&a)return a(u,!0);if(i)return i(u,!0);var c=new Error("Cannot find module '"+u+"'");throw c.code="MODULE_NOT_FOUND",c}var s=e[u]={exports:{}};t[u][0].call(s.exports,function(r){var e=t[u][1][r];return o(e||r)},s,s.exports,r,t,e,n)}return e[u].exports}for(var i="function"==typeof require&&require,u=0;u<n.length;u++)o(n[u]);return o}return r}()({1:[function(r,t){t.exports=r("./src/crossfilter").crossfilter},{"./src/crossfilter":6}],2:[function(r,t){(function(r){function e(r,t){return null==r?void 0:r[t]}function n(r){var t=!1;if(null!=r&&"function"!=typeof r.toString)try{t=!!(r+"")}catch(e){}return t}function o(r){var t=-1,e=r?r.length:0;for(this.clear();++t<e;){var n=r[t];this.set(n[0],n[1])}}function i(){this.__data__=dt?dt(null):{}}function u(r){return this.has(r)&&delete this.__data__[r]}function f(r){var t=this.__data__;if(dt){var e=t[r];return e===T?void 0:e}return ct.call(t,r)?t[r]:void 0}function a(r){var t=this.__data__;return dt?void 0!==t[r]:ct.call(t,r)}function c(r,t){var e=this.__data__;return e[r]=dt&&void 0===t?T:t,this}function s(r){var t=-1,e=r?r.length:0;for(this.clear();++t<e;){var n=r[t];this.set(n[0],n[1])}}function l(){this.__data__=[]}function h(r){var t=this.__data__,e=w(t,r);if(0>e)return!1;var n=t.length-1;return e==n?t.pop():pt.call(t,e,1),!0}function p(r){var t=this.__data__,e=w(t,r);return 0>e?void 0:t[e][1]}function v(r){return w(this.__data__,r)>-1}function d(r,t){var e=this.__data__,n=w(e,r);return 0>n?e.push([r,t]):e[n][1]=t,this}function y(r){var t=-1,e=r?r.length:0;for(this.clear();++t<e;){var n=r[t];this.set(n[0],n[1])}}function g(){this.__data__={hash:new o,map:new(vt||s),string:new o}}function b(r){return A(this,r).delete(r)}function _(r){return A(this,r).get(r)}function x(r){return A(this,r).has(r)}function m(r,t){return A(this,r).set(r,t),this}function w(r,t){for(var e=r.length;e--;)if(q(r[e][0],t))return e;return-1}function E(r){if(!R(r)||M(r))return!1;var t=N(r)||n(r)?lt:Z;return t.test(C(r))}function O(r){if("string"==typeof r)return r;if(D(r))return gt?gt.call(r):"";var t=r+"";return"0"==t&&1/r==-W?"-0":t}function k(r){return _t(r)?r:bt(r)}function A(r,t){var e=r.__data__;return S(t)?e["string"==typeof t?"string":"hash"]:e.map}function z(r,t){var n=e(r,t);return E(n)?n:void 0}function j(r,t){if(_t(r))return!1;var e=typeof r;return"number"==e||"symbol"==e||"boolean"==e||null==r||D(r)?!0:K.test(r)||!H.test(r)||null!=t&&r in Object(t)}function S(r){var t=typeof r;return"string"==t||"number"==t||"symbol"==t||"boolean"==t?"__proto__"!==r:null===r}function M(r){return!!ft&&ft in r}function F(r){if("string"==typeof r||D(r))return r;var t=r+"";return"0"==t&&1/r==-W?"-0":t}function C(r){if(null!=r){try{return at.call(r)}catch(t){}try{return r+""}catch(t){}}return""}function $(r,t){if("function"!=typeof r||t&&"function"!=typeof t)throw new TypeError(P);var e=function(){var n=arguments,o=t?t.apply(this,n):n[0],i=e.cache;if(i.has(o))return i.get(o);var u=r.apply(this,n);return e.cache=i.set(o,u),u};return e.cache=new($.Cache||y),e}function q(r,t){return r===t||r!==r&&t!==t}function N(r){var t=R(r)?st.call(r):"";return t==J||t==G}function R(r){var t=typeof r;return!!r&&("object"==t||"function"==t)}function U(r){return!!r&&"object"==typeof r}function D(r){return"symbol"==typeof r||U(r)&&st.call(r)==B}function I(r){return null==r?"":O(r)}function L(r,t,e){t=j(t,r)?[t]:k(t);var n=-1,o=t.length;for(o||(r=void 0,o=1);++n<o;){var i=null==r?void 0:r[F(t[n])];void 0===i&&(n=o,i=e),r=N(i)?i.call(r):i}return r}var P="Expected a function",T="__lodash_hash_undefined__",W=1/0,J="[object Function]",G="[object GeneratorFunction]",B="[object Symbol]",H=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,K=/^\w*$/,Q=/^\./,V=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,X=/[\\^$.*+?()[\]{}|]/g,Y=/\\(\\)?/g,Z=/^\[object .+?Constructor\]$/,rt="object"==typeof r&&r&&r.Object===Object&&r,tt="object"==typeof self&&self&&self.Object===Object&&self,et=rt||tt||Function("return this")(),nt=Array.prototype,ot=Function.prototype,it=Object.prototype,ut=et["__core-js_shared__"],ft=function(){var r=/[^.]+$/.exec(ut&&ut.keys&&ut.keys.IE_PROTO||"");return r?"Symbol(src)_1."+r:""}(),at=ot.toString,ct=it.hasOwnProperty,st=it.toString,lt=RegExp("^"+at.call(ct).replace(X,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),ht=et.Symbol,pt=nt.splice,vt=z(et,"Map"),dt=z(Object,"create"),yt=ht?ht.prototype:void 0,gt=yt?yt.toString:void 0;o.prototype.clear=i,o.prototype.delete=u,o.prototype.get=f,o.prototype.has=a,o.prototype.set=c,s.prototype.clear=l,s.prototype.delete=h,s.prototype.get=p,s.prototype.has=v,s.prototype.set=d,y.prototype.clear=g,y.prototype.delete=b,y.prototype.get=_,y.prototype.has=x,y.prototype.set=m;var bt=$(function(r){r=I(r);var t=[];return Q.test(r)&&t.push(""),r.replace(V,function(r,e,n,o){t.push(n?o.replace(Y,"$1"):e||r)}),t});$.Cache=y;var _t=Array.isArray;t.exports=L}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],3:[function(r,t){t.exports={version:"1.4.6"}},{}],4:[function(r,t){function e(r){for(var t=new Array(r),e=-1;++e<r;)t[e]=0;return t}function n(r,t){for(var e=r.length;t>e;)r[e++]=0;return r}function o(r,t){if(t>32)throw new Error("invalid array width!");return r}function i(r){this.length=r,this.subarrays=1,this.width=8,this.masks={0:0},this[0]=u(r)}if("undefined"!=typeof Uint8Array)var u=function(r){return new Uint8Array(r)},f=function(r){return new Uint16Array(r)},a=function(r){return new Uint32Array(r)},c=function(r,t){if(r.length>=t)return r;var e=new r.constructor(t);return e.set(r),e},s=function(r,t){var e;switch(t){case 16:e=f(r.length);break;case 32:e=a(r.length);break;default:throw new Error("invalid array width!")}return e.set(r),e};i.prototype.lengthen=function(r){var t,e;for(t=0,e=this.subarrays;e>t;++t)this[t]=c(this[t],r);this.length=r},i.prototype.add=function(){var r,t,e,n,o;for(n=0,o=this.subarrays;o>n;++n)if(r=this.masks[n],t=this.width-32*n,e=~r&-~r,!(t>=32)||e)return 32>t&&e&1<<t&&(this[n]=s(this[n],t<<=1),this.width=32*n+t),this.masks[n]|=e,{offset:n,one:e};return this[this.subarrays]=u(this.length),this.masks[this.subarrays]=1,this.width+=8,{offset:this.subarrays++,one:1}},i.prototype.copy=function(r,t){var e,n;for(e=0,n=this.subarrays;n>e;++e)this[e][r]=this[e][t]},i.prototype.truncate=function(r){var t,e;for(t=0,e=this.subarrays;e>t;++t){for(var n=this.length-1;n>=r;n--)this[t][n]=0;this[t].length=r}this.length=r},i.prototype.zero=function(r){var t,e;for(t=0,e=this.subarrays;e>t;++t)if(this[t][r])return!1;return!0},i.prototype.zeroExcept=function(r,t,e){var n,o;for(n=0,o=this.subarrays;o>n;++n)if(n===t?this[n][r]&e:this[n][r])return!1;return!0},i.prototype.zeroExceptMask=function(r,t){var e,n;for(e=0,n=this.subarrays;n>e;++e)if(this[e][r]&t[e])return!1;return!0},i.prototype.only=function(r,t,e){var n,o;for(n=0,o=this.subarrays;o>n;++n)if(this[n][r]!=(n===t?e:0))return!1;return!0},i.prototype.onlyExcept=function(r,t,e,n,o){var i,u,f;for(u=0,f=this.subarrays;f>u;++u)if(i=this[u][r],u===t&&(i&=e),i!=(u===n?o:0))return!1;return!0},t.exports={array8:e,array16:e,array32:e,arrayLengthen:n,arrayWiden:o,bitarray:i}},{}],5:[function(r,t){"use strict";function e(r){function t(t,e,n,o){for(;o>n;){var i=n+o>>>1;r(t[i])<e?n=i+1:o=i}return n}function e(t,e,n,o){for(;o>n;){var i=n+o>>>1;e<r(t[i])?o=i:n=i+1}return n}return e.right=e,e.left=t,e}var n=r("./identity");t.exports=e(n),t.exports.by=e},{"./identity":10}],6:[function(r,t,e){"use strict";function n(){function r(r){var t=M,e=r.length;return e&&(S=S.concat(r),z.lengthen(M+=e),C.forEach(function(n){n(r,t,e)}),A("dataAdded")),j}function t(r){for(var t=o(M,M),e=[],n="function"==typeof r,i=function(t){return n?r(S[t],t):z.zero(t)},u=0,f=0;M>u;++u)i(u)?(e.push(u),t[u]=m):t[u]=f++;F.forEach(function(r){r(-1,-1,[],e,!0)}),$.forEach(function(r){r(t)});for(var a=0,c=0;M>a;++a)t[a]!==m&&(a!==c&&(z.copy(c,a),S[c]=S[a]),++c);S.length=M=c,z.truncate(c),A("dataRemoved")}function e(r){var t,e,n,o,i=Array(z.subarrays);for(t=0;t<z.subarrays;t++)i[t]=-1;for(e=0,n=r.length;n>e;e++)o=r[e].id(),i[o>>7]&=~(1<<(63&o));return i}function n(r,t){var n=e(t||[]);return z.zeroExceptMask(r,n)}function d(r,t){function e(e,n,u){if(t){pt=0,A=0,ot=[];for(var a=0;a<e.length;a++)for(A=0,ot=r(e[a]);A<ot.length;A++)pt++;Q=[],Y=i(e.length),rt=o(pt,1);for(var c=i(pt),s=0,l=0;l<e.length;l++)if(ot=r(e[l]),ot.length)for(Y[l]=ot.length,A=0;A<ot.length;A++)Q.push(ot[A]),c[s]=l,s++;else Y[l]=0,ut.push(l+n);var h=ft(i(pt),0,pt);Q=y(Q,h),V=y(c,h)}else Q=e.map(r),V=ft(i(u),0,u),Q=y(Q,V);t&&(u=pt);var p=at(Q),v=p[0],d=p[1];if(tt)for(var g=0;u>g;++g)tt(Q[g],g)||(z[G][V[g]+n]|=W,t&&(rt[g]=1));else{for(var b=0;v>b;++b)z[G][V[b]+n]|=W,t&&(rt[b]=1);for(var _=d;u>_;++_)z[G][V[_]+n]|=W,t&&(rt[_]=1)}if(!n)return H=Q,K=V,X=Y,Z=rt,lt=v,ht=d,void 0;var x,m=H,w=K,E=Z,O=0;if(a=0,t&&(x=n,n=m.length,u=pt),H=t?new Array(n+u):new Array(M),K=t?new Array(n+u):o(M,M),t&&(Z=o(n+u,1)),t){var k=X.length;X=f.arrayLengthen(X,M);for(var A=0;M>A+k;A++)X[A+k]=Y[A]}for(var j=0;n>a&&u>O;++j)m[a]<Q[O]?(H[j]=m[a],t&&(Z[j]=E[a]),K[j]=w[a++]):(H[j]=Q[O],t&&(Z[j]=rt[O]),K[j]=V[O++]+(t?x:n));for(;n>a;++a,++j)H[j]=m[a],t&&(Z[j]=E[a]),K[j]=w[a];for(;u>O;++O,++j)H[j]=Q[O],t&&(Z[j]=rt[O]),K[j]=V[O]+(t?x:n);p=at(H),lt=p[0],ht=p[1]}function n(r,t,e){ct.forEach(function(r){r(Q,V,t,e)}),Q=V=null}function d(r){if(t){for(var e=0,n=0;e<ut.length;e++)r[ut[e]]!==m&&(ut[n]=r[ut[e]],n++);for(ut.length=n,e=0,n=0;M>e;e++)r[e]!==m&&(n!==e&&(X[n]=X[e]),n++);X.length=n}for(var o,i=H.length,u=0,f=0;i>u;++u)o=K[u],r[o]!==m&&(u!==f&&(H[f]=H[u]),K[f]=r[o],t&&(Z[f]=Z[u]),++f);for(H.length=f,t&&(Z.length=f);i>f;)K[f++]=0;var a=at(H);lt=a[0],ht=a[1]}function _(r){var e=r[0],n=r[1];if(tt)return tt=null,q(function(r,t){return t>=e&&n>t},0===r[0]&&r[1]===H.length),lt=e,ht=n,it;var o,i,u,f=[],a=[],c=[],s=[];if(lt>e)for(o=e,i=Math.min(lt,n);i>o;++o)f.push(K[o]),c.push(o);else if(e>lt)for(o=lt,i=Math.min(e,ht);i>o;++o)a.push(K[o]),s.push(o);if(n>ht)for(o=Math.max(e,ht),i=n;i>o;++o)f.push(K[o]),c.push(o);else if(ht>n)for(o=Math.max(lt,n),i=ht;i>o;++o)a.push(K[o]),s.push(o);if(t){var l=[],h=[];for(o=0;o<f.length;o++)X[f[o]]++,Z[c[o]]=0,1===X[f[o]]&&(z[G][f[o]]^=W,l.push(f[o]));for(o=0;o<a.length;o++)X[a[o]]--,Z[s[o]]=1,0===X[a[o]]&&(z[G][a[o]]^=W,h.push(a[o]));if(f=l,a=h,0===r[0]&&r[1]===H.length)for(o=0;o<ut.length;o++)z[G][u=ut[o]]&W&&(z[G][u]^=W,f.push(u));else for(o=0;o<ut.length;o++)z[G][u=ut[o]]&W||(z[G][u]^=W,a.push(u))}else{for(o=0;o<f.length;o++)z[G][f[o]]^=W;for(o=0;o<a.length;o++)z[G][a[o]]^=W}return lt=e,ht=n,F.forEach(function(r){r(W,G,f,a)}),A("filtered"),it}function w(r){return null==r?k():Array.isArray(r)?O(r):"function"==typeof r?j(r):E(r)}function E(r){return et=r,nt=!0,_((at=a.filterExact(v,r))(H))}function O(r){return et=r,nt=!0,_((at=a.filterRange(v,r))(H))}function k(){return et=void 0,nt=!1,_((at=a.filterAll)(H))}function j(r){et=r,nt=!0,tt=r,at=a.filterAll,q(r,!1);var t=at(H);return lt=t[0],ht=t[1],it}function q(r,e){var n,o,i,u=[],f=[],a=[],c=[],s=H.length;if(!t)for(n=0;s>n;++n)!(z[G][o=K[n]]&W)^!!(i=r(H[n],n))&&(i?u.push(o):f.push(o));if(t)for(n=0;s>n;++n)r(H[n],n)?(u.push(K[n]),a.push(n)):(f.push(K[n]),c.push(n));if(t){var l=[],h=[];for(n=0;n<u.length;n++)1===Z[a[n]]&&(X[u[n]]++,Z[a[n]]=0,1===X[u[n]]&&(z[G][u[n]]^=W,l.push(u[n])));for(n=0;n<f.length;n++)0===Z[c[n]]&&(X[f[n]]--,Z[c[n]]=1,0===X[f[n]]&&(z[G][f[n]]^=W,h.push(f[n])));if(u=l,f=h,e)for(n=0;n<ut.length;n++)z[G][o=ut[n]]&W&&(z[G][o]^=W,u.push(o));else for(n=0;n<ut.length;n++)z[G][o=ut[n]]&W||(z[G][o]^=W,f.push(o))}else{for(n=0;n<u.length;n++)z[G][u[n]]&W&&(z[G][u[n]]&=J);for(n=0;n<f.length;n++)z[G][f[n]]&W||(z[G][f[n]]|=W)}F.forEach(function(r){r(W,G,u,f)}),A("filtered")}function N(){return et}function R(){return nt}function U(r,e){var n,o=[],i=ht,u=0;for(e&&e>0&&(u=e);--i>=lt&&r>0;)z.zero(n=K[i])&&(u>0?--u:(o.push(S[n]),--r));if(t)for(i=0;i<ut.length&&r>0;i++)z.zero(n=ut[i])&&(u>0?--u:(o.push(S[n]),--r));return o}function D(r,e){var n,o,i=[],u=0;if(e&&e>0&&(u=e),t)for(n=0;n<ut.length&&r>0;n++)z.zero(o=ut[n])&&(u>0?--u:(i.push(S[o]),--r));for(n=lt;ht>n&&r>0;)z.zero(o=K[n])&&(u>0?--u:(i.push(S[o]),--r)),n++;return i}function I(r){function e(e,n,c,l){function h(){return t?(B++,void 0):(++B===T&&(w=f.arrayWiden(w,P<<=1),q=f.arrayWiden(q,P),T=u(P)),void 0)}t&&(L=c,c=H.length-e.length,l=e.length);var p,y,g,b,_,x,m=C,w=t?[]:o(B,T),E=U,O=D,k=I,A=B,j=0,$=0;for(X&&(E=k=s),X&&(O=k=s),C=new Array(B),B=0,q=t?A?q:[]:A>1?f.arrayLengthen(q,M):o(M,T),A&&(g=(y=m[0]).key);l>$&&!((b=r(e[$]))>=b);)++$;for(;l>$;){for(y&&b>=g?(_=y,x=g,w[j]=B,y=m[++j],y&&(g=y.key)):(_={key:b,value:k()},x=b),C[B]=_;x>=b&&(p=n[$]+(t?L:c),t?q[p]?q[p].push(B):q[p]=[B]:q[p]=B,_.value=E(_.value,S[p],!0),z.zeroExcept(p,G,J)||(_.value=O(_.value,S[p],!1)),!(++$>=l));)b=r(e[$]);h()}for(;A>j;)C[w[j]=B]=m[j++],h();if(t)for(var N=0;M>N;N++)q[N]||(q[N]=[]);if(B>j)if(t)for(j=0;L>j;++j)for(N=0;N<q[j].length;N++)q[j][N]=w[q[j][N]];else for(j=0;c>j;++j)q[j]=w[q[j]];p=F.indexOf(Q),B>1||t?(Q=i,V=v):(!B&&Y&&(B=1,C=[{key:null,value:k()}]),1===B?(Q=a,V=d):(Q=s,V=s),q=null),F[p]=Q}function n(r){if(B>1||t){var e,n,u,f=B,c=C,l=o(f,f);if(t){for(e=0,u=0;M>e;++e)if(r[e]!==m){for(q[u]=q[e],n=0;n<q[u].length;n++)l[q[u][n]]=1;++u}}else for(e=0,u=0;M>e;++e)r[e]!==m&&(l[q[u]=q[e]]=1,++u);for(C=[],B=0,e=0;f>e;++e)l[e]&&(l[e]=B++,C.push(c[e]));if(B>1||t)if(t)for(e=0;u>e;++e)for(n=0;n<q[e].length;++n)q[e][n]=l[q[e][n]];else for(e=0;u>e;++e)q[e]=l[q[e]];else q=null;F[F.indexOf(Q)]=B>1||t?(V=v,Q=i):1===B?(V=d,Q=a):V=Q=s}else if(1===B){if(Y)return;for(var h=0;M>h;++h)if(r[h]!==m)return;C=[],B=0,F[F.indexOf(Q)]=Q=V=s}}function i(r,e,n,o,i){if(!(r===W&&e===G||X)){var u,f,a,c,s;if(t){for(u=0,c=n.length;c>u;++u)if(z.zeroExcept(a=n[u],G,J))for(f=0;f<q[a].length;f++)s=C[q[a][f]],s.value=U(s.value,S[a],!1,f);for(u=0,c=o.length;c>u;++u)if(z.onlyExcept(a=o[u],G,J,e,r))for(f=0;f<q[a].length;f++)s=C[q[a][f]],s.value=D(s.value,S[a],i,f)}else{for(u=0,c=n.length;c>u;++u)z.zeroExcept(a=n[u],G,J)&&(s=C[q[a]],s.value=U(s.value,S[a],!1));for(u=0,c=o.length;c>u;++u)z.onlyExcept(a=o[u],G,J,e,r)&&(s=C[q[a]],s.value=D(s.value,S[a],i))}}}function a(r,t,e,n,o){if(!(r===W&&t===G||X)){var i,u,f,a=C[0];for(i=0,f=e.length;f>i;++i)z.zeroExcept(u=e[i],G,J)&&(a.value=U(a.value,S[u],!1));for(i=0,f=n.length;f>i;++i)z.onlyExcept(u=n[i],G,J,t,r)&&(a.value=D(a.value,S[u],o))}}function v(){var r,e,n;for(r=0;B>r;++r)C[r].value=I();if(t){for(r=0;M>r;++r)for(e=0;e<q[r].length;e++)n=C[q[r][e]],n.value=U(n.value,S[r],!0,e);for(r=0;M>r;++r)if(!z.zeroExcept(r,G,J))for(e=0;e<q[r].length;e++)n=C[q[r][e]],n.value=D(n.value,S[r],!1,e)}else{for(r=0;M>r;++r)n=C[q[r]],n.value=U(n.value,S[r],!0);for(r=0;M>r;++r)z.zeroExcept(r,G,J)||(n=C[q[r]],n.value=D(n.value,S[r],!1))}}function d(){var r,t=C[0];for(t.value=I(),r=0;M>r;++r)t.value=U(t.value,S[r],!0);for(r=0;M>r;++r)z.zeroExcept(r,G,J)||(t.value=D(t.value,S[r],!1))}function y(){return X&&(V(),X=!1),C}function g(r){var t=N(y(),0,C.length,r);return R.sort(t,0,t.length)}function _(r,t,e){return U=r,D=t,I=e,X=!0,j}function x(){return _(b.reduceIncrement,b.reduceDecrement,l)}function w(r){return _(b.reduceAdd(r),b.reduceSubtract(r),l)}function E(r){function t(t){return r(t.value)}return N=h.by(t),R=p.by(t),j}function O(){return E(c)}function k(){return B}function A(){var r=F.indexOf(Q);return r>=0&&F.splice(r,1),r=ct.indexOf(e),r>=0&&ct.splice(r,1),r=$.indexOf(n),r>=0&&$.splice(r,1),r=st.indexOf(j),r>=0&&st.splice(r,1),j}var j={top:g,all:y,reduce:_,reduceCount:x,reduceSum:w,order:E,orderNatural:O,size:k,dispose:A,remove:A};st.push(j);var C,q,N,R,U,D,I,L,P=8,T=u(P),B=0,Q=s,V=s,X=!0,Y=r===s;return arguments.length<1&&(r=c),F.push(Q),ct.push(e),$.push(n),e(H,K,0,M),x().orderNatural()}function L(){var r=I(s),t=r.all;return delete r.all,delete r.top,delete r.order,delete r.orderNatural,delete r.size,r.value=function(){return t()[0].value},r}function P(){st.forEach(function(r){r.dispose()});var r=C.indexOf(e);return r>=0&&C.splice(r,1),r=C.indexOf(n),r>=0&&C.splice(r,1),r=$.indexOf(d),r>=0&&$.splice(r,1),z.masks[G]&=J,k()}if("string"==typeof r){var T=r;r=function(r){return x(r,T)}}var W,J,G,B,H,K,Q,V,X,Y,Z,rt,tt,et,nt,ot,it={filter:w,filterExact:E,filterRange:O,filterFunction:j,filterAll:k,currentFilter:N,hasCurrentFilter:R,top:U,bottom:D,group:I,groupAll:L,dispose:P,remove:P,accessor:r,id:function(){return B}},ut=[],ft=g.by(function(r){return Q[r]}),at=a.filterAll,ct=[],st=[],lt=0,ht=0,pt=0;C.unshift(e),C.push(n),$.push(d);var vt=z.add();return G=vt.offset,W=vt.one,J=~W,B=G<<7|Math.log(W)/Math.log(2),e(S,0,M),n(S,0,M),it}function _(){function r(r,t){var e;if(!v)for(e=t;M>e;++e)a=c(a,S[e],!0),z.zero(e)||(a=s(a,S[e],!1))}function t(r,t,e,n,o){var i,u,f;if(!v){for(i=0,f=e.length;f>i;++i)z.zero(u=e[i])&&(a=c(a,S[u],o));for(i=0,f=n.length;f>i;++i)z.only(u=n[i],t,r)&&(a=s(a,S[u],o))}}function e(){var r;for(a=h(),r=0;M>r;++r)a=c(a,S[r],!0),z.zero(r)||(a=s(a,S[r],!1))}function n(r,t,e){return c=r,s=t,h=e,v=!0,p}function o(){return n(b.reduceIncrement,b.reduceDecrement,l)}function i(r){return n(b.reduceAdd(r),b.reduceSubtract(r),l)}function u(){return v&&(e(),v=!1),a}function f(){var e=F.indexOf(t);return e>=0&&F.splice(e,1),e=C.indexOf(r),e>=0&&C.splice(e,1),p}var a,c,s,h,p={reduce:n,reduceCount:o,reduceSum:i,value:u,dispose:f,remove:f},v=!0;return F.push(t),C.push(r),r(S,0,M),o()}function w(){return M}function E(){return S}function O(r){var t=[],n=0,o=e(r||[]);for(n=0;M>n;n++)z.zeroExceptMask(n,o)&&t.push(S[n]);return t}function k(r){return"function"!=typeof r?(console.warn("onChange callback parameter must be a function!"),void 0):(q.push(r),function(){q.splice(q.indexOf(r),1)})}function A(r){for(var t=0;t<q.length;t++)q[t](r)}var z,j={add:r,remove:t,dimension:d,groupAll:_,size:w,all:E,allFiltered:O,onChange:k,isElementFiltered:n},S=[],M=0,F=[],C=[],$=[],q=[];return z=new f.bitarray(0),arguments.length?r(arguments[0]):j}function o(r,t){return(257>t?f.array8:65537>t?f.array16:f.array32)(r)}function i(r){for(var t=o(r,r),e=-1;++e<r;)t[e]=e;return t}function u(r){return 8===r?256:16===r?65536:4294967296}var f=r("./array"),a=r("./filter"),c=r("./identity"),s=r("./null"),l=r("./zero"),h=r("./heapselect"),p=r("./heap"),v=r("./bisect"),d=r("./insertionsort"),y=r("./permute"),g=r("./quicksort"),b=r("./reduce"),_=r("./../package.json"),x=r("lodash.result"),m=-1;e.crossfilter=n,e.crossfilter.heap=p,e.crossfilter.heapselect=h,e.crossfilter.bisect=v,e.crossfilter.insertionsort=d,e.crossfilter.permute=y,e.crossfilter.quicksort=g,e.crossfilter.version=_.version},{"./../package.json":3,"./array":4,"./bisect":5,"./filter":7,"./heap":8,"./heapselect":9,"./identity":10,"./insertionsort":11,"./null":12,"./permute":13,"./quicksort":14,"./reduce":15,"./zero":16,"lodash.result":2}],7:[function(r,t){"use strict";function e(r,t){return function(e){var n=e.length;return[r.left(e,t,0,n),r.right(e,t,0,n)]}}function n(r,t){var e=t[0],n=t[1];return function(t){var o=t.length;return[r.left(t,e,0,o),r.left(t,n,0,o)]}}function o(r){return[0,r.length]}t.exports={filterExact:e,filterRange:n,filterAll:o}},{}],8:[function(r,t){"use strict";function e(r){function t(r,t,e){for(var o=e-t,i=(o>>>1)+1;--i>0;)n(r,i,o,t);return r}function e(r,t,e){for(var o,i=e-t;--i>0;)o=r[t],r[t]=r[t+i],r[t+i]=o,n(r,1,i,t);return r}function n(t,e,n,o){for(var i,u=t[--o+e],f=r(u);(i=e<<1)<=n&&(n>i&&r(t[o+i])>r(t[o+i+1])&&i++,!(f<=r(t[o+i])));)t[o+e]=t[o+i],e=i;t[o+e]=u}return t.sort=e,t}var n=r("./identity");t.exports=e(n),t.exports.by=e},{"./identity":10}],9:[function(r,t){"use strict";function e(r){function t(t,n,o,i){var u,f,a,c=new Array(i=Math.min(o-n,i));for(f=0;i>f;++f)c[f]=t[n++];if(e(c,0,i),o>n){u=r(c[0]);do r(a=t[n])>u&&(c[0]=a,u=r(e(c,0,i)[0]));while(++n<o)}return c}var e=o.by(r);return t}var n=r("./identity"),o=r("./heap");t.exports=e(n),t.exports.by=e},{"./heap":8,"./identity":10}],10:[function(r,t){"use strict";function e(r){return r}t.exports=e},{}],11:[function(r,t){"use strict";function e(r){function t(t,e,n){for(var o=e+1;n>o;++o){for(var i=o,u=t[o],f=r(u);i>e&&r(t[i-1])>f;--i)t[i]=t[i-1];t[i]=u}return t}return t}var n=r("./identity");t.exports=e(n),t.exports.by=e},{"./identity":10}],12:[function(r,t){"use strict";function e(){return null}t.exports=e},{}],13:[function(r,t){"use strict";function e(r,t,e){for(var n=0,o=t.length,i=e?JSON.parse(JSON.stringify(r)):new Array(o);o>n;++n)i[n]=r[t[n]];return i}t.exports=e},{}],14:[function(r,t){function e(r){function t(r,t,o){return(i>o-t?n:e)(r,t,o)}function e(e,n,o){var i,u=0|(o-n)/6,f=n+u,a=o-1-u,c=n+o-1>>1,s=c-u,l=c+u,h=e[f],p=r(h),v=e[s],d=r(v),y=e[c],g=r(y),b=e[l],_=r(b),x=e[a],m=r(x);p>d&&(i=h,h=v,v=i,i=p,p=d,d=i),_>m&&(i=b,b=x,x=i,i=_,_=m,m=i),p>g&&(i=h,h=y,y=i,i=p,p=g,g=i),d>g&&(i=v,v=y,y=i,i=d,d=g,g=i),p>_&&(i=h,h=b,b=i,i=p,p=_,_=i),g>_&&(i=y,y=b,b=i,i=g,g=_,_=i),d>m&&(i=v,v=x,x=i,i=d,d=m,m=i),d>g&&(i=v,v=y,y=i,i=d,d=g,g=i),_>m&&(i=b,b=x,x=i,i=_,_=m,m=i);var w=v,E=d,O=b,k=_;e[f]=h,e[s]=e[n],e[c]=y,e[l]=e[o-1],e[a]=x;var A=n+1,z=o-2,j=k>=E&&E>=k;if(j)for(var S=A;z>=S;++S){var M=e[S],F=r(M);if(E>F)S!==A&&(e[S]=e[A],e[A]=M),++A;else if(F>E)for(;;){var C=r(e[z]);{if(!(C>E)){if(E>C){e[S]=e[A],e[A++]=e[z],e[z--]=M;break}e[S]=e[z],e[z--]=M;break}z--}}}else!function(){for(var t=A;z>=t;t++){var n=e[t],o=r(n);if(E>o)t!==A&&(e[t]=e[A],e[A]=n),++A;else if(o>k)for(;;){var i=r(e[z]);{if(!(i>k)){E>i?(e[t]=e[A],e[A++]=e[z],e[z--]=n):(e[t]=e[z],e[z--]=n);break}if(z--,t>z)break}}}}();return e[n]=e[A-1],e[A-1]=w,e[o-1]=e[z+1],e[z+1]=O,t(e,n,A-1),t(e,z+2,o),j?e:(f>A&&z>a&&!function(){for(var t,n;(t=r(e[A]))<=E&&t>=E;)++A;for(;(n=r(e[z]))<=k&&n>=k;)--z;for(var o=A;z>=o;o++){var i=e[o],u=r(i);if(E>=u&&u>=E)o!==A&&(e[o]=e[A],e[A]=i),A++;else if(k>=u&&u>=k)for(;;){n=r(e[z]);{if(!(k>=n&&n>=k)){E>n?(e[o]=e[A],e[A++]=e[z],e[z--]=i):(e[o]=e[z],e[z--]=i);break}if(z--,o>z)break}}}}(),t(e,A,z+1))}var n=o.by(r);return t}var n=r("./identity"),o=r("./insertionsort"),i=32;t.exports=e(n),t.exports.by=e},{"./identity":10,"./insertionsort":11}],15:[function(r,t){"use strict";function e(r){return r+1}function n(r){return r-1}function o(r){return function(t,e){return t+ +r(e)}}function i(r){return function(t,e){return t-r(e)}}t.exports={reduceIncrement:e,reduceDecrement:n,reduceAdd:o,reduceSubtract:i}},{}],16:[function(r,t){"use strict";function e(){return 0}t.exports=e},{}]},{},[1])(1)});
\ No newline at end of file
diff --git a/civicrm/bower_components/crossfilter2/index.d.ts b/civicrm/bower_components/crossfilter2/index.d.ts
index 91c54bfd0c..b2e11e1a22 100644
--- a/civicrm/bower_components/crossfilter2/index.d.ts
+++ b/civicrm/bower_components/crossfilter2/index.d.ts
@@ -22,37 +22,37 @@ declare namespace crossfilter {
     | [NaturallyOrderedValue, NaturallyOrderedValue]
     | Predicate<NaturallyOrderedValue>;
 
-  export interface Grouping<TKey extends NaturallyOrderedValue> {
+  export interface Grouping<TKey extends NaturallyOrderedValue, TValue> {
     key: TKey;
-    value: number;
+    value: TValue;
   }
 
-  export interface Group<T, TKey extends NaturallyOrderedValue, TReduce extends NaturallyOrderedValue> {
-    top(k: number): Array<Grouping<TKey>>;
-    all(): Array<Grouping<TKey>>;
+  export interface Group<TRecord, TKey extends NaturallyOrderedValue, TValue> {
+    top(k: number): Array<Grouping<TKey, TValue>>;
+    all(): Array<Grouping<TKey, TValue>>;
     reduce(
-      add: (p: T, v: TReduce, nf: boolean) => TReduce,
-      remove: (p: T, v: TReduce, nf: boolean) => TReduce,
-      initial: () => TReduce,
-    ): Group<T, TKey, TReduce>;
-    reduceCount(): Group<T, TKey, TReduce>;
-    reduceSum(selector: (record: T) => number): Group<T, TKey, TReduce>;
-    order(selector: (value: TReduce) => NaturallyOrderedValue): Group<T, TKey, TReduce>;
-    orderNatural(): Group<T, TKey, TReduce>;
+      add: (p: TValue, v: TRecord, nf: boolean) => TValue,
+      remove: (p: TValue, v: TRecord, nf: boolean) => TValue,
+      initial: () => TValue,
+    ): Group<TRecord, TKey, TValue>;
+    reduceCount(): Group<TRecord, TKey, TValue>;
+    reduceSum(selector: (record: TRecord) => number): Group<TRecord, TKey, TValue>;
+    order(selector: (value: TValue) => NaturallyOrderedValue): Group<TRecord, TKey, TValue>;
+    orderNatural(): Group<TRecord, TKey, TValue>;
     size(): number;
-    dispose(): Group<T, TKey, TReduce>;
+    dispose(): Group<TRecord, TKey, TValue>;
   }
 
-  export interface GroupAll<T, TReduce extends NaturallyOrderedValue> {
+  export interface GroupAll<TRecord, TValue> {
     reduce(
-      add: (p: T, v: TReduce, nf: boolean) => TReduce,
-      remove: (p: T, v: TReduce, nf: boolean) => TReduce,
-      initial: () => TReduce,
-    ): GroupAll<T, TReduce>;
-    reduceCount(): GroupAll<T, TReduce>;
-    reduceSum(selector: (record: T) => number): GroupAll<T, TReduce>;
-    dispose(): GroupAll<T, TReduce>;
-    value(): number;
+      add: (p: TValue, v: TRecord, nf: boolean) => TValue,
+      remove: (p: TValue, v: TRecord, nf: boolean) => TValue,
+      initial: () => TValue,
+    ): GroupAll<TRecord, TValue>;
+    reduceCount(): GroupAll<TRecord, TValue>;
+    reduceSum(selector: (record: TRecord) => number): GroupAll<TRecord, TValue>;
+    dispose(): GroupAll<TRecord, TValue>;
+    value(): TValue;
   }
 
   export interface Dimension<TRecord, TValue extends NaturallyOrderedValue> {
@@ -61,12 +61,14 @@ declare namespace crossfilter {
     filterRange(range: [TValue, TValue]): Dimension<TRecord, TValue>;
     filterFunction(predicate: Predicate<TValue>): Dimension<TRecord, TValue>;
     filterAll(): Dimension<TRecord, TValue>;
+    currentFilter(): FilterValue | undefined;
+    hasCurrentFilter(): boolean;
     top(k: number, offset?: number): TRecord[];
     bottom(k: number, offset?: number): TRecord[];
-    group<TReduce extends NaturallyOrderedValue>(
-      groupValue?: (value: TValue) => NaturallyOrderedValue,
-    ): Group<TRecord, TValue, TReduce>;
-    groupAll<TReduce extends NaturallyOrderedValue>(): GroupAll<TRecord, TReduce>;
+    group<TKey extends NaturallyOrderedValue, TGroupValue extends NaturallyOrderedValue>(
+      groupValue?: (value: TValue) => TKey,
+    ): Group<TRecord, TKey, TGroupValue>;
+    groupAll<TGroupValue>(): GroupAll<TRecord, TGroupValue>;
     dispose(): Dimension<TRecord, TValue>;
     accessor(record: TRecord): NaturallyOrderedValue;
     id(): number;
@@ -85,7 +87,7 @@ declare namespace crossfilter {
       selector: OrderedValueSelector<T, TValue>,
       isArray?: boolean,
     ): Dimension<T, TValue>;
-    groupAll<TReduce extends NaturallyOrderedValue>(): GroupAll<T, TReduce>;
+    groupAll<TGroupValue>(): GroupAll<T, TGroupValue>;
     size(): number;
     all(): T[];
     allFiltered(): T[];
diff --git a/civicrm/civicrm-version.php b/civicrm/civicrm-version.php
index e8daba5a19..ff3f0498ad 100644
--- a/civicrm/civicrm-version.php
+++ b/civicrm/civicrm-version.php
@@ -1,6 +1,6 @@
 <?php
 function civicrmVersion( ) {
-  return array( 'version'  => '5.0.2',
+  return array( 'version'  => '5.1.0',
                 'cms'      => 'Wordpress',
                 'revision' => '' );
 }
diff --git a/civicrm/js/Common.js b/civicrm/js/Common.js
index 15f3528b2d..43cc526b72 100644
--- a/civicrm/js/Common.js
+++ b/civicrm/js/Common.js
@@ -1260,7 +1260,8 @@ if (!CRM.vars) CRM.vars = {};
       if (title.length) {
         text = title + "\n" + text;
       }
-      alert(text);
+      // strip html tags as they are not parsed in standard alerts
+      alert($("<div/>").html(text).text());
       return null;
     }
   };
diff --git a/civicrm/js/crm.optionEdit.js b/civicrm/js/crm.optionEdit.js
index 5f8c483428..1b1338ce00 100644
--- a/civicrm/js/crm.optionEdit.js
+++ b/civicrm/js/crm.optionEdit.js
@@ -5,12 +5,162 @@ jQuery(function($) {
     .on('click', 'a.crm-option-edit-link', CRM.popup)
     .on('crmPopupFormSuccess', 'a.crm-option-edit-link', function() {
       $(this).trigger('crmOptionsEdited');
-      var $elects = $('select[data-option-edit-path="' + $(this).data('option-edit-path') + '"]');
-      if ($elects.data('api-entity') && $elects.data('api-field')) {
-        CRM.api3($elects.data('api-entity'), 'getoptions', {sequential: 1, field: $elects.data('api-field')})
-          .done(function (data) {
-            CRM.utils.setOptions($elects, data.values);
-          });
+      var optionEditPath = $(this).data('option-edit-path');
+      var $selects = $('select[data-option-edit-path="' + optionEditPath + '"]');
+      var $inputs = $('input[data-option-edit-path="' + optionEditPath + '"]');
+      var $radios = $inputs.filter('[type=radio]');
+      var $checkboxes = $inputs.filter('[type=checkbox]');
+
+      if ($selects.length > 0) {
+        rebuildOptions($selects, CRM.utils.setOptions);
       }
+      else if ($radios.length > 0) {
+        rebuildOptions($radios, rebuildRadioOptions);
+      }
+      else if ($checkboxes.length > 0) {
+        rebuildOptions($checkboxes, rebuildCheckboxOptions);
+      }
+    });
+
+  /**
+   * Fetches options using metadata from the existing ones and calls the
+   * function to rebuild them
+   * @param $existing {object} The existing options, used as metadata store
+   * @param rebuilder {function} Function to be called to rebuild the options
+   */
+  function rebuildOptions($existing, rebuilder) {
+    if ($existing.data('api-entity') && $existing.data('api-field')) {
+      CRM.api3($existing.data('api-entity'), 'getoptions', {
+        sequential: 1,
+        field: $existing.data('api-field')
+      })
+      .done(function(data) {
+        rebuilder($existing, data.values);
+      });
+    }
+  }
+
+  /**
+   * Rebuild checkbox input options, overwriting the existing options
+   *
+   * @param $existing {object} the existing checkbox options
+   * @param newOptions {array} in format returned by api.getoptions
+   */
+  function rebuildCheckboxOptions($existing, newOptions) {
+    var $parent = $existing.first().parent(),
+      $firstExisting = $existing.first(),
+      optionName = $firstExisting.attr('name'),
+      optionAttributes =
+        'data-option-edit-path =' + $firstExisting.data('option-edit-path') +
+        ' data-api-entity = ' + $firstExisting.data('api-entity') +
+        ' data-api-field = ' + $firstExisting.data('api-field');
+
+    var prefix = optionName.substr(0, optionName.lastIndexOf("["));
+
+    var checkedBoxes = [];
+    $parent.find('input:checked').each(function() {
+      checkedBoxes.push($(this).attr('id'));
+    });
+
+    // remove existing checkboxes
+    $parent.find('input[type=checkbox]').remove();
+
+    // find existing labels for the checkboxes
+    var $checkboxLabels = $parent.find('label').filter(function() {
+      var forAttr = $(this).attr('for') || '';
+
+      return forAttr.indexOf(prefix) !== -1;
+    });
+
+    // find what is used to separate the elements; spaces or linebreaks
+    var $elementAfterLabel = $checkboxLabels.first().next();
+    var separator = $elementAfterLabel.is('br') ? '<br/>' : '&nbsp;';
+
+    // remove existing labels
+    $checkboxLabels.remove();
+
+    // remove linebreaks in container
+    $parent.find('br').remove();
+
+    // remove separator whitespace in container
+    $parent.html(function (i, html) {
+      return html.replace(/&nbsp;/g, '');
+    });
+
+    var renderedOptions = '';
+    // replace missing br at start of element
+    if (separator === '<br/>') {
+      $parent.prepend(separator);
+      renderedOptions = separator;
+    }
+
+    newOptions.forEach(function(option) {
+      var optionId = prefix + '_' + option.key,
+        checked = '';
+
+      if ($.inArray(optionId, checkedBoxes) !== -1) {
+        checked = ' checked="checked"';
+      }
+
+      renderedOptions += '<input type="checkbox" ' +
+        ' value="1"' +
+        ' id="' + optionId + '"' +
+        ' name="' + prefix + '[' + option.key +']' + '"' +
+        checked +
+        ' class="crm-form-checkbox"' +
+        optionAttributes +
+        '><label for="' + optionId + '">' + option.value + '</label>' +
+        separator;
+    });
+
+    // remove final separator
+    renderedOptions = renderedOptions.substring(0, renderedOptions.lastIndexOf(separator));
+
+    var $editLink = $parent.find('.crm-option-edit-link');
+
+    // try to insert before the edit link to maintain structure
+    if ($editLink.length > 0) {
+      $(renderedOptions).insertBefore($editLink);
+    }
+    else {
+      $parent.append(renderedOptions);
+    }
+  }
+
+  /**
+   * Rebuild radio input options, overwriting the existing options
+   *
+   * @param $existing {object} the existing input options
+   * @param newOptions {array} in format returned by api.getoptions
+   */
+  function rebuildRadioOptions($existing, newOptions) {
+    var $parent = $existing.first().parent(),
+      $firstExisting = $existing.first(),
+      optionName = $firstExisting.attr('name'),
+      renderedOptions = '',
+      checkedValue = parseInt($parent.find('input:checked').attr('value')),
+      optionAttributes =
+        'data-option-edit-path =' + $firstExisting.attr('data-option-edit-path') +
+        ' data-api-entity = ' + $firstExisting.attr('data-api-entity') +
+        ' data-api-field = ' + $firstExisting.attr('data-api-field');
+
+    // remove existing radio inputs and labels
+    $parent.find('input, label').remove();
+
+    newOptions.forEach(function(option) {
+      var optionId = 'CIVICRM_QFID_' + option.key + '_' + optionName,
+        checked = (option.key === checkedValue) ? ' checked="checked"' : '';
+
+      renderedOptions += '<input type="radio" ' +
+        ' value=' + option.key +
+        ' id="' + optionId +'"' +
+        ' name="' + optionName + '"' +
+        checked +
+        ' class="crm-form-radio"' +
+        optionAttributes +
+        '><label for="' + optionId + '">' + option.value + '</label> ';
     });
+
+    $parent.prepend(renderedOptions);
+  }
 });
diff --git a/civicrm/packages/DB/DataObject.php b/civicrm/packages/DB/DataObject.php
index 0d74ece76d..895db94254 100644
--- a/civicrm/packages/DB/DataObject.php
+++ b/civicrm/packages/DB/DataObject.php
@@ -2436,16 +2436,29 @@ class DB_DataObject extends DB_DataObject_Overload
         $t= explode(' ',microtime());
         $_DB_DATAOBJECT['QUERYENDTIME'] = $time = $t[0]+$t[1];
 
+      $maxTries = defined('CIVICRM_DEADLOCK_RETRIES') ? CIVICRM_DEADLOCK_RETRIES : 3;
+      for ($tries = 0;$tries < $maxTries;$tries++) {
+        if ($_DB_driver == 'DB') {
+          try {
+            $result = $DB->query($string);
+          }
+          catch (PEAR_Exception $e) {
+            // CRM-21489 If we have caught a DB lock - let it go around the loop until our tries limit is hit.
+            // else rethrow the exception. The 2 locks we are looking at are mysql code 1205 (lock) and
+            // 1213 (deadlock).
+            $dbErrorMessage = $e->getCause()->getUserInfo();
+            if (!stristr($dbErrorMessage, 'nativecode=1205') && !stristr($dbErrorMessage, 'nativecode=1213')) {
+              throw $e;
+            }
+            $message = (stristr($dbErrorMessage, 'nativecode=1213') ? 'Database deadlock encountered' : 'Database lock encountered');
+            if (($tries + 1) === $maxTries) {
+              throw new CRM_Core_Exception($message, 0, array('sql' => $string, 'trace' => $e->getTrace()));
+            }
+            CRM_Core_Error::debug_log_message("Retrying after $message hit on attempt " . ($tries + 1) . ' at query : ' . $string);
+            continue;
+          }
 
-        for ($tries = 0;$tries < 3;$tries++) {
-
-            if ($_DB_driver == 'DB') {
-                if ($tries) {
-                  CRM_Core_Error::debug_log_message('Attempt: ' . $tries + 1 . ' at query : ' . $string);
-                }
-                $result = $DB->query($string);
-
-            } else {
+        } else {
                 switch (strtolower(substr(trim($string),0,6))) {
 
                     case 'insert':
@@ -2460,7 +2473,7 @@ class DB_DataObject extends DB_DataObject_Overload
                 }
             }
 
-            // see if we got a failure.. - try again a few times..
+            // See CRM-21489 for why I believe this is never hit.
             if (!is_a($result,'PEAR_Error')) {
                 break;
             }
@@ -2471,7 +2484,6 @@ class DB_DataObject extends DB_DataObject_Overload
             $DB->connect($DB->dsn);
         }
 
-
         if (is_a($result,'PEAR_Error')) {
             if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
                 $this->debug($result->toString(), "Query Error",1 );
diff --git a/civicrm/release-notes.md b/civicrm/release-notes.md
index b91fe66a32..4010e2e495 100644
--- a/civicrm/release-notes.md
+++ b/civicrm/release-notes.md
@@ -14,6 +14,36 @@ Other resources for identifying changes are:
     * https://github.com/civicrm/civicrm-joomla
     * https://github.com/civicrm/civicrm-wordpress
 
+## CiviCRM 5.1.0
+
+Released May 2, 2018
+
+- **[Synopsis](release-notes/5.1.0.md#synopsis)**
+- **[Features](release-notes/5.1.0.md#features)**
+- **[Bugs resolved](release-notes/5.1.0.md#bugs)**
+- **[Miscellany](release-notes/5.1.0.md#misc)**
+- **[Credits](release-notes/5.1.0.md#credits)**
+- **[Feedback](release-notes/5.1.0.md#feedback)**
+
+## CiviCRM 5.0.2
+
+Released Apr 25, 2018
+
+- **[Synopsis](release-notes/5.0.2.md#synopsis)**
+- **[Bugs resolved](release-notes/5.0.2.md#bugs)**
+- **[Credits](release-notes/5.0.2.md#credits)**
+- **[Feedback](release-notes/5.0.2.md#feedback)**
+
+## CiviCRM 5.0.1
+
+Released April 19, 2018
+
+- **[Synopsis](release-notes/5.0.1.md#synopsis)**
+- **[Features](release-notes/5.0.1.md#features)**
+- **[Bugs resolved](release-notes/5.0.1.md#bugs)**
+- **[Credits](release-notes/5.0.1.md#credits)**
+- **[Feedback](release-notes/5.0.1.md#feedback)**
+
 ## CiviCRM 5.0.0
 
 Released April 4, 2018
diff --git a/civicrm/release-notes/5.0.1.md b/civicrm/release-notes/5.0.1.md
index 6658c20851..863e4ce04b 100644
--- a/civicrm/release-notes/5.0.1.md
+++ b/civicrm/release-notes/5.0.1.md
@@ -1,6 +1,55 @@
 # CiviCRM 5.0.1
 
-Released Apr 18, 2018
+Released April 19, 2018
 
-- **Backport: Dedupe - Fix for recent regression causing dedupe screen to fail on WordPress. ([11975](https://github.com/civicrm/civicrm-core/pull/11975))**
-- **Backport: VersionCheck - Get more nuanced messages from latest.civicrm.org. ([11991](https://github.com/civicrm/civicrm-core/pull/11991))**
+- **[Synopsis](#synopsis)**
+- **[Features](#features)**
+- **[Bugs resolved](#bugs)**
+- **[Credits](#credits)**
+- **[Feedback](#feedback)**
+
+## <a name="synopsis"></a>Synopsis
+
+| *Does this version...?*                                         |         |
+|:--------------------------------------------------------------- |:-------:|
+| Fix security vulnerabilities?                                   |   no    |
+| Change the database schema?                                     |   no    |
+| Alter the API?                                                  |   no    |
+| Require attention to configuration options?                     |   no    |
+| Fix problems installing or upgrading to a previous version?     |   no    |
+| **Introduce features?**                                         | **yes** |
+| **Fix bugs?**                                                   | **yes** |
+
+## <a name="features"></a>Features
+
+### Core CiviCRM
+
+- **VersionCheck - Get more nuanced messages from latest.civicrm.org
+  ([11991](https://github.com/civicrm/civicrm-core/pull/11991))**
+
+  Upgrade messages are now supplied by the CiviCRM version server rather than
+  being calculated by each site.
+
+## <a name="bugs"></a>Bugs resolved
+
+### Core CiviCRM
+
+- **Fix failure to render dedupe page
+  ([11976](https://github.com/civicrm/civicrm-core/pull/11976))**
+
+## <a name="credits"></a>Credits
+
+This release was developed by the following code authors:
+
+CiviCRM - Tim Otten; Wikimedia Foundation - Eileen McNaughton
+
+Most authors also reviewed code for this release; in addition, the following
+reviewers contributed their comments:
+
+Australian Greens - Seamus Lee; JMA Consulting - Monish Deb
+
+## <a name="feedback"></a>Feedback
+
+These release notes are edited by Tim Otten and Andrew Hunt.  If you'd like to
+provide feedback on them, please login to https://chat.civicrm.org/civicrm and
+contact `@agh1`
diff --git a/civicrm/release-notes/5.0.2.md b/civicrm/release-notes/5.0.2.md
index 59b4f95ea2..b9371ef391 100644
--- a/civicrm/release-notes/5.0.2.md
+++ b/civicrm/release-notes/5.0.2.md
@@ -2,5 +2,46 @@
 
 Released Apr 25, 2018
 
-- **Backport: Use current formula for hyperlinking release notes ([12008](https://github.com/civicrm/civicrm-core/pull/12008))**
-- **Add missing release notes for 5.0.1**
+- **[Synopsis](#synopsis)**
+- **[Bugs resolved](#bugs)**
+- **[Credits](#credits)**
+- **[Feedback](#feedback)**
+
+## <a name="synopsis"></a>Synopsis
+
+| *Does this version...?*                                         |         |
+|:--------------------------------------------------------------- |:-------:|
+| Fix security vulnerabilities?                                   |   no    |
+| Change the database schema?                                     |   no    |
+| Alter the API?                                                  |   no    |
+| Require attention to configuration options?                     |   no    |
+| Fix problems installing or upgrading to a previous version?     |   no    |
+| Introduce features?                                             |   no    |
+| **Fix bugs?**                                                   | **yes** |
+
+## <a name="bugs"></a>Bugs resolved
+
+### Core CiviCRM
+
+- **footer.tpl - Change the URL formula pointing to the release notes
+  ([12008](https://github.com/civicrm/civicrm-core/pull/12008))**
+
+  The link to release notes is now standardized at
+  `https://download.civicrm.org/about/{$version}` rather than hard-coding to
+  GitHub.
+
+## <a name="credits"></a>Credits
+
+This release was developed by the following code author:
+
+CiviCRM - Tim Otten
+
+The following reviewer contributed her comments:
+
+Wikimedia Foundation - Eileen McNaughton
+
+## <a name="feedback"></a>Feedback
+
+These release notes are edited by Tim Otten and Andrew Hunt.  If you'd like to
+provide feedback on them, please login to https://chat.civicrm.org/civicrm and
+contact `@agh1`.
diff --git a/civicrm/release-notes/5.1.0.md b/civicrm/release-notes/5.1.0.md
new file mode 100644
index 0000000000..22261be72a
--- /dev/null
+++ b/civicrm/release-notes/5.1.0.md
@@ -0,0 +1,442 @@
+# CiviCRM 5.1.0
+
+Released May 2, 2018
+
+- **[Synopsis](#synopsis)**
+- **[Features](#features)**
+- **[Bugs resolved](#bugs)**
+- **[Miscellany](#misc)**
+- **[Credits](#credits)**
+- **[Feedback](#feedback)**
+
+## <a name="synopsis"></a>Synopsis
+
+| *Does this version...?*                                         |         |
+|:--------------------------------------------------------------- |:-------:|
+| Fix security vulnerabilities?                                   |         |
+| Change the database schema?                                     |         |
+| Alter the API?                                                  |         |
+| Require attention to configuration options?                     |         |
+| Fix problems installing or upgrading to a previous version?     |         |
+| Introduce features?                                             |         |
+| Fix bugs?                                                       |         |
+
+## <a name="features"></a>Features
+
+### Core CiviCRM
+
+- **[CRM-21677](https://issues.civicrm.org/jira/browse/CRM-21677) Report
+  improvements ([11814](https://github.com/civicrm/civicrm-core/pull/11814),
+  [11898](https://github.com/civicrm/civicrm-core/pull/11898),
+  [11889](https://github.com/civicrm/civicrm-core/pull/11889),
+  [11880](https://github.com/civicrm/civicrm-core/pull/11880),
+  [11876](https://github.com/civicrm/civicrm-core/pull/11876),
+  [11875](https://github.com/civicrm/civicrm-core/pull/11875),
+  [11867](https://github.com/civicrm/civicrm-core/pull/11867), and
+  [11855](https://github.com/civicrm/civicrm-core/pull/11855))**
+
+  Reports that don't have detailed information about contacts now no longer join
+  to the address, phone, and email tables.
+
+- **[CRM-21434](https://issues.civicrm.org/jira/browse/CRM-21434) Add activities
+  to recent items on view and edit
+  ([11891](https://github.com/civicrm/civicrm-core/pull/11891))**
+
+  A recently viewed or edited activity will now appear on the list of recent
+  items in Backdrop, Drupal, and Joomla.
+
+- **[CRM-21489](https://issues.civicrm.org/jira/browse/CRM-21489) Deadlock
+  retries have been accidentally blocked
+  ([11336](https://github.com/civicrm/civicrm-core/pull/11336) and
+  [197](https://github.com/civicrm/civicrm-packages/pull/197))**
+
+  This restores functionality that retries transactions if they face a deadlock
+  in the database.  The number of times is now a constant that can be set in
+  `civicrm.settings.php`.
+
+- **[CRM-21840](https://issues.civicrm.org/jira/browse/CRM-21840) Show Tool Icon
+  For Radio Button Groups
+  ([11819](https://github.com/civicrm/civicrm-core/pull/11819))**
+
+  A group of radio buttons will now display a wrench icon if the user has the
+  permission to edit the options.  This now matches the feature for select
+  boxes.
+
+- **[CRM-20981](https://issues.civicrm.org/jira/browse/CRM-20981) Allow custom
+  base-pages with less `crmApp` boilerplate
+  ([10783](https://github.com/civicrm/civicrm-core/pull/10783))**
+
+  Extensions that use AngularJS can now define a base path more easily.
+
+- **[CRM-20624](https://issues.civicrm.org/jira/browse/CRM-20624) Expose
+  description field for option values in UI
+  ([10403](https://github.com/civicrm/civicrm-core/pull/10403))**
+
+  Custom field options have a `description` field (that has been in the database
+  for a while); now it can be set from the user interface and viewed when
+  managing option values.
+
+- **[CRM-21835](https://issues.civicrm.org/jira/browse/CRM-21835) Detailed
+  Logging - Use INNODB if Archive is not available
+  ([11786](https://github.com/civicrm/civicrm-core/pull/11786))**
+
+  The Archive storage engine is not always available in MariaDB, even though it
+  is the default for log tables when detailed logging is enabled.  Now, CiviCRM
+  will fall back to InnoDB if Archive is not available.
+
+- **[CRM-21753](https://issues.civicrm.org/jira/browse/CRM-21753) Support
+  'criteria' in url on batch merge form
+  ([11666](https://github.com/civicrm/civicrm-core/pull/11666)) (completes prior
+  work)**
+
+  This improves handling of criteria set in the URL for batch merges.
+
+- **[CRM-20811](https://issues.civicrm.org/jira/browse/CRM-20811) Schedule
+  Reminders uses mixed terminology for Active state: Active? versus Send Email
+  ([10602](https://github.com/civicrm/civicrm-core/pull/10602))**
+
+  The option for whether a scheduled reminder is active is now displayed as a
+  checkbox with "Scheduled Reminder Active" rather than "Send Email" or "Send
+  email or SMS".
+
+- **CRM_Utils_Check - Soften messages for read-only extensionsDir
+  ([11895](https://github.com/civicrm/civicrm-core/pull/11895))**
+
+  When a site's extensions directory is not writable by the web server, the
+  system check message now has a lower severity and explains the consequences
+  rather than indicating that this is definitely a problem.
+
+- **Meld Address custom field display template with main custom field template
+  ([11844](https://github.com/civicrm/civicrm-core/pull/11844))**
+
+  The display for address custom fields now uses the main custom field template.
+
+- **[CRM-21784](https://issues.civicrm.org/jira/browse/CRM-21784) View custom
+  data for recurring contributions
+  ([11697](https://github.com/civicrm/civicrm-core/pull/11697))**
+
+  This resolves a problem where custom data could be set for recurring
+  contributions but could not be viewed outside of the API.
+
+### CiviContribute
+
+- **[CRM-20610](https://issues.civicrm.org/jira/browse/CRM-20610) Replace
+  payment details block with editable payment list on 'Edit Contribution' form
+  ([10776](https://github.com/civicrm/civicrm-core/pull/10776))**
+
+  The backend contribution edit form is now based on the same payment editing
+  interface as events with multiple payments.
+
+- **Tweak layout on contribution view screen to make payments clearer
+  ([11863](https://github.com/civicrm/civicrm-core/pull/11863))**
+
+  When viewing a contribution on the back end, a table of payments now displays
+  immediately below the total amount.
+
+### CiviMail
+
+- **[CRM-20719](https://issues.civicrm.org/jira/browse/CRM-20719) Show warning
+  on system status page if reply_id for mailing is not set to any default.
+  ([10496](https://github.com/civicrm/civicrm-core/pull/10496))**
+
+  This warns users if no auto-reply message is selected as default, as this will
+  prevent CiviMail messages from being submitted.
+
+### Drupal Integration
+
+- **Add activity created_date, modified_date and original_id fields to views
+  ([525](https://github.com/civicrm/civicrm-drupal/pull/525))**
+
+## <a name="bugs"></a>Bugs resolved
+
+### Core CiviCRM
+
+- **[dev/core#83](https://lab.civicrm.org/dev/core/issues/83) Fix regression
+  whereby relationship types option no longer in adv search
+  ([12045](https://github.com/civicrm/civicrm-core/pull/12045))**
+
+- **Flush versionCheck cache when upgrading
+  ([12034](https://github.com/civicrm/civicrm-core/pull/12034))**
+
+  A recently-upgraded site will no longer potentially have a cached message
+  indicating that an upgrade is needed.
+
+- **[dev/core#64](https://lab.civicrm.org/dev/core/issues/64) - In custom
+  searches, column headings are being ignored
+  ([12005](https://github.com/civicrm/civicrm-core/pull/12005))**
+
+  This resolves a regression that displayed standard column headings on results
+  of custom searches.
+
+- **Fix trigger generation for modified_date on custom data
+  ([11984](https://github.com/civicrm/civicrm-core/pull/11984))**
+
+- **Phone: standardize appearance and translation of extension label
+  ([11930](https://github.com/civicrm/civicrm-core/pull/11930))**
+
+- **[dev/core#16](https://lab.civicrm.org/dev/core/issues/16) Select "Enable
+  multiple bulk email address for a contact", "hold_date" can not be updated
+  ([11807](https://github.com/civicrm/civicrm-core/pull/11807) and
+  [11884](https://github.com/civicrm/civicrm-core/pull/11884))**
+
+- **Handle eq (equals) operator in the report url
+  ([11885](https://github.com/civicrm/civicrm-core/pull/11885))**
+
+  When setting report filters via the URL, the `eq` operator now works like the
+  others.  It didn't work in past versions.
+
+- **Fix report form isTableSelected to treat relative date filters as filters
+  ([11882](https://github.com/civicrm/civicrm-core/pull/11882))**
+
+- **[CRM-21842](https://issues.civicrm.org/jira/browse/CRM-21842) broken link
+  ([11879](https://github.com/civicrm/civicrm-core/pull/11879))**
+
+  Links to the "Installation and basic set-up" documentation page had errors.
+
+- **[dev/core#22](https://lab.civicrm.org/dev/core/issues/22) Unable to delete
+  Smart Group ([11826](https://github.com/civicrm/civicrm-core/pull/11826))**
+
+  This resolves a fatal error that would appear when attempting to delete a
+  broken smart group.
+
+- **Fix template structures
+  ([11818](https://github.com/civicrm/civicrm-core/pull/11818),
+  [11839](https://github.com/civicrm/civicrm-core/pull/11839),
+  [11851](https://github.com/civicrm/civicrm-core/pull/11851),
+  [11862](https://github.com/civicrm/civicrm-core/pull/11862), and
+  [11869](https://github.com/civicrm/civicrm-core/pull/11869))**
+
+  This standardizes a number of page templates that didn't match the typical
+  structure.
+
+- **Fix ajax error on rendering multi custom data tab when field limit reached
+  ([11856](https://github.com/civicrm/civicrm-core/pull/11856))**
+
+- **Escape custom group title.
+  ([11854](https://github.com/civicrm/civicrm-core/pull/11854))**
+
+  This fixes a bug causing the display of multi-entry custom data sets when the
+  set's title has an apostrophe in it.
+
+- **[CRM-20790](https://issues.civicrm.org/jira/browse/CRM-20790) Import
+  Contacts, Current Employer (Employee of field) is not being imported at all
+  ([11843](https://github.com/civicrm/civicrm-core/pull/11843)) (completes prior
+  work)**
+
+  Unit tests now ensure relationships are added on import.
+
+- **[dev/core#17](https://lab.civicrm.org/dev/core/issues/17) Convert Campaign
+  Interview Task to use Pseudoconstant and remove PHP notices
+  ([11809](https://github.com/civicrm/civicrm-core/pull/11809))**
+
+  This replaces use of the deprecated `CRM_Core_OptionGroup::getValue()` with
+  `CRM_Core_PseudoConstant::getKey()` and fixes PHP notices.
+
+- **[CRM-21838](https://issues.civicrm.org/jira/browse/CRM-21838) When CRM.alert
+  falls back to standard JS alert it should strip html
+  ([11797](https://github.com/civicrm/civicrm-core/pull/11797))**
+
+### CiviContribute
+
+- **[CRM-21763](https://issues.civicrm.org/jira/browse/CRM-21763) Cannot record
+  payment for only cents owed
+  ([11668](https://github.com/civicrm/civicrm-core/pull/11668))**
+
+  This resolves a bug where the sum of payments would be fractions of a cent off
+  from the total amount due.  A new utility subtracts currency amounts using the
+  correct number of decimals for that currency.
+
+- **[CRM-21791](https://issues.civicrm.org/jira/browse/CRM-21791) Accounting
+  batch closed by default when created in localized civicrm
+  ([11878](https://github.com/civicrm/civicrm-core/pull/11878))**
+
+  If an accounting batch is created in a site with a language other than US
+  English, a bug caused the batch to start out closed.
+
+- **[dev/core#26](https://lab.civicrm.org/dev/core/issues/26) On behalf form
+  fails to create new organisation
+  ([11841](https://github.com/civicrm/civicrm-core/pull/11841))**
+
+- **[CRM-21807](https://issues.civicrm.org/jira/browse/CRM-21807) Deleted
+  contacts included by default in Membership and contribution detail report.
+  ([11727](https://github.com/civicrm/civicrm-core/pull/11727))**
+
+- **[CRM-21264](https://issues.civicrm.org/jira/browse/CRM-21264) print
+  contribution in tabular format with group by contact not working
+  ([11820](https://github.com/civicrm/civicrm-core/pull/11820))**
+
+### CiviEvent
+
+- **Fix fatal error when selecting a $0 price option in change fee selection
+  ([11934](https://github.com/civicrm/civicrm-core/pull/11934))**
+
+### CiviMail
+
+- **[dev/mail#8](https://lab.civicrm.org/dev/mail/issues/8) Using ACL to
+  restrict mailing recipients leads to fatal error
+  ([11963](https://github.com/civicrm/civicrm-core/pull/11963))**
+
+- **[dev/core#25](https://lab.civicrm.org/dev/core/issues/25) Wrap split_jobs in
+  a transaction ([11836](https://github.com/civicrm/civicrm-core/pull/11836))**
+
+  The process of splitting mail jobs is now a database transaction, preventing
+  other processes from potentially processing child jobs before it is finished.
+
+### CiviMember
+
+- **[CRM-21711](https://issues.civicrm.org/jira/browse/CRM-21711) When updating
+  multiple memberships thru a contribution page custom fields are only updated
+  on one ([11586](https://github.com/civicrm/civicrm-core/pull/11586))**
+
+- **[CRM-19151](https://issues.civicrm.org/jira/browse/CRM-19151) Add / fix the
+  Ability to merge memberships
+  ([11298](https://github.com/civicrm/civicrm-core/pull/11298)) (initial work)**
+
+  When merging contacts that each have memberships, one membership and all its
+  data will be deleted unless you check the Add New box.  Now, the surviving
+  membership is updated to have the earliest Join Date and latest End Date of
+  the two, and the Membership Status is recalculated.
+
+- **[CRM-19850](https://issues.civicrm.org/jira/browse/CRM-19850) Add a offline
+  membership without 'record payment' option, later edit the membership and
+  saving with 'record payment' option
+  ([11087](https://github.com/civicrm/civicrm-core/pull/11087))**
+
+  This resolves an error that failed to show the payment information when
+  editing an unpaid membership and checking the "Record Payment" box.
+
+- **[dev/core#15](https://lab.civicrm.org/dev/core/issues/15) Wrong parameter
+  passing in LineItem.php
+  ([11816](https://github.com/civicrm/civicrm-core/pull/11816))**
+
+  This addresses an intermittent bug where membership line items would refer to
+  the wrong contribution.
+
+- **[CRM-21682](https://issues.civicrm.org/jira/browse/CRM-21682) Automatic
+  membership renewal fixes
+  ([11824](https://github.com/civicrm/civicrm-core/pull/11824) and
+  [11825](https://github.com/civicrm/civicrm-core/pull/11825))**
+
+- **“Deceased” status could be translated
+  ([11890](https://github.com/civicrm/civicrm-core/pull/11890))**
+
+  The membership status update job would look for the status labeled "Deceased",
+  which may be translated.
+
+### Drupal Integration
+
+- **[dev/core#83](https://lab.civicrm.org/dev/core/issues/18) Log tables for
+  CiviCRM Drupal Modules can cause WSODs after running upgrades when
+  re-calculating ([11865](https://github.com/civicrm/civicrm-core/pull/11865))**
+
+### Joomla Integration
+
+- **[CRM-21348](https://issues.civicrm.org/jira/browse/CRM-21348) Don't hide the
+  "edit" link from logged-in users in profile listings in joomla front-end.
+  ([11199](https://github.com/civicrm/civicrm-core/pull/11199))**
+
+- **[CRM-21203](https://issues.civicrm.org/jira/browse/CRM-21203) cli.php PHP
+  error prevents cron jobs from running
+  ([11609](https://github.com/civicrm/civicrm-core/pull/11609)) (completes prior
+  work)**
+
+### WordPress Integration
+
+- **[CRM-21277](https://issues.civicrm.org/jira/browse/CRM-21277)
+  CRM_Utils_System_WordPress::validInstallDir spams log with warnings when
+  open_basedir restriction is in effect
+  ([11086](https://github.com/civicrm/civicrm-core/pull/11086))**
+
+## <a name="misc"></a>Miscellany
+
+- **Increment minimum upgradable version
+  ([11864](https://github.com/civicrm/civicrm-core/pull/11864))**
+
+  New versions of CiviCRM no longer contain code facilitating a direct upgrade
+  from versions before 4.1.3.  Older sites attempting to upgrade should upgrade
+  to one or more intermediate versions before upgrading to 5.1.0.
+
+- **(NFC) make (includes taxes) translation work
+  ([11927](https://github.com/civicrm/civicrm-core/pull/11927))**
+
+- **Extract fetchRelationshipDetails function
+  ([11918](https://github.com/civicrm/civicrm-core/pull/11918))**
+
+- **NFC Minor comments cleanup on MembershipType
+  ([11909](https://github.com/civicrm/civicrm-core/pull/11909))**
+
+- **Remove cloning hack from export and add unit tests
+  ([11703](https://github.com/civicrm/civicrm-core/pull/11703))**
+
+- **NFC Fix function name typo
+  ([11888](https://github.com/civicrm/civicrm-core/pull/11888))**
+
+- **[NFC] Fix mispelled variable and simplify a couple of other vars
+  ([11886](https://github.com/civicrm/civicrm-core/pull/11886))**
+
+- **[NFC] remove unused vars
+  ([11874](https://github.com/civicrm/civicrm-core/pull/11874))**
+
+- **CiviUnitTestCase - Extract Api3TestTrait and Api3DocTrait
+  ([11872](https://github.com/civicrm/civicrm-core/pull/11872))**
+
+- **Consolidate CustomData code into shared tpl
+  ([11857](https://github.com/civicrm/civicrm-core/pull/11857))**
+
+- **[nfc] Add test for thousand separators on import
+  ([11859](https://github.com/civicrm/civicrm-core/pull/11859))**
+
+- **[nfc] Minor test tidy ups
+  ([11860](https://github.com/civicrm/civicrm-core/pull/11860))**
+
+- **[NFC] fix line endings, using windows line endings, change to 'unix
+  ([11858](https://github.com/civicrm/civicrm-core/pull/11858))**
+
+- **NFC reformat whitespace in Email.tpl files
+  ([11842](https://github.com/civicrm/civicrm-core/pull/11842))**
+
+- **Version check test: in alphas don't test for site stats not provided for
+  alphas ([11831](https://github.com/civicrm/civicrm-core/pull/11831))**
+
+- **Fix style warnings
+  ([526](https://github.com/civicrm/civicrm-drupal/pull/526))**
+
+- **add GitHub PR template and Contributing templates to WP repo
+  ([127](https://github.com/civicrm/civicrm-wordpress/pull/127))**
+
+## <a name="credits"></a>Credits
+
+This release was developed by the following code authors:
+
+AGH Strategies - Alice Frumin, Andrew Hunt, Eli Lisseck; Agileware - Agileware
+Team, Alok Patel, Francis Whittle, Justin Freeman; Andrew Thompson; Australian
+Greens - Seamus Lee; CiviCRM - Coleman Watts, Tim Otten; CiviDesk - Yashodha
+Chaku; CompuCorp - Michael Devery, Mukesh Ram; Coop SymbioTIC - Samuel Vanhove;
+Davis Media Access - Darrick Servis; Fuzion - Jitendra Purohit; JMA Consulting -
+Monish Deb; Joinery - Allen Shaw; Kompetenzzentrum
+Technik-Diversity-Chancengleichheit - Niels Heinemann; Left Join Labs - Sean
+Madsen; Megaphone Technology Consulting - Jon Goldberg; MJW Consulting - Matthew
+Wire; Naomi Rosenberg; Olivier Tétard; Oxfam Germany - Yuliyana Liyana; Tadpole
+Collective - Kevin Cristiano; Wikimedia Foundation - Eileen McNaughton
+
+Most authors also reviewed code for this release; in addition, the following
+reviewers contributed their comments:
+
+Ben Jarlett; British Humanist Association - Andrew West; Chris Burgess;
+Christian Wach; CiviDesk - Sunil Pawar; Community Builders - Andrew Perry;
+CompuCorp - Jamie Novick; Coop SymbioTIC - Mathieu Lutfy; David Hepper; DevApp -
+Adam Kwiatkowski; Donald Hirst; Francesc Bassas i Bullich; Fuzion - Peter Davis;
+Ginkgo Street Labs - Frank Gómez; JMA Consulting - Monish Deb; Johan Vervloet;
+John Kingsnorth; Korlon - Stuart Gaston; Lemniscus - Noah Miller; Lighthouse
+Design and Consulting - Brian Shaughnessy; Lorenzo Ardizzone; Lyons Digital
+Media - Barbara Forbes-Lyons; Marcello Gribaudo; National Democratic Institute -
+Evan Summers; Neil Zampella; Nicol Wistreich; Pratik Joshi; Progressive
+Technology Project - Jamie McClelland; Responsive Development Technologies -
+Thomas Nilefalk; Richard Edgar; SEN Magazine - Jeremy Nicholls; Skvare - Mark
+Hanna; small biz
+
+## <a name="feedback"></a>Feedback
+
+These release notes are edited by Andrew Hunt.  If you'd like to provide
+feedback on them, please login to https://chat.civicrm.org/civicrm and contact
+`@agh1`.
diff --git a/civicrm/sql/civicrm_data.mysql b/civicrm/sql/civicrm_data.mysql
index c78c583d77..0152831191 100644
--- a/civicrm/sql/civicrm_data.mysql
+++ b/civicrm/sql/civicrm_data.mysql
@@ -23961,4 +23961,4 @@ INSERT INTO `civicrm_report_instance`
     ( `domain_id`, `title`, `report_id`, `description`, `permission`, `form_values`)
 VALUES
     (  @domainID, 'Survey Details', 'survey/detail', 'Detailed report for canvassing, phone-banking, walk lists or other surveys.', 'access CiviReport', 'a:39:{s:6:"fields";a:2:{s:9:"sort_name";s:1:"1";s:6:"result";s:1:"1";}s:22:"assignee_contact_id_op";s:2:"eq";s:25:"assignee_contact_id_value";s:0:"";s:12:"sort_name_op";s:3:"has";s:15:"sort_name_value";s:0:"";s:17:"street_number_min";s:0:"";s:17:"street_number_max";s:0:"";s:16:"street_number_op";s:3:"lte";s:19:"street_number_value";s:0:"";s:14:"street_name_op";s:3:"has";s:17:"street_name_value";s:0:"";s:15:"postal_code_min";s:0:"";s:15:"postal_code_max";s:0:"";s:14:"postal_code_op";s:3:"lte";s:17:"postal_code_value";s:0:"";s:7:"city_op";s:3:"has";s:10:"city_value";s:0:"";s:20:"state_province_id_op";s:2:"in";s:23:"state_province_id_value";a:0:{}s:13:"country_id_op";s:2:"in";s:16:"country_id_value";a:0:{}s:12:"survey_id_op";s:2:"in";s:15:"survey_id_value";a:0:{}s:12:"status_id_op";s:2:"eq";s:15:"status_id_value";s:1:"1";s:11:"custom_1_op";s:2:"in";s:14:"custom_1_value";a:0:{}s:11:"custom_2_op";s:2:"in";s:14:"custom_2_value";a:0:{}s:17:"custom_3_relative";s:1:"0";s:13:"custom_3_from";s:0:"";s:11:"custom_3_to";s:0:"";s:11:"description";s:75:"Detailed report for canvassing, phone-banking, walk lists or other surveys.";s:13:"email_subject";s:0:"";s:8:"email_to";s:0:"";s:8:"email_cc";s:0:"";s:10:"permission";s:17:"access CiviReport";s:6:"groups";s:0:"";s:9:"domain_id";i:1;}');
-UPDATE civicrm_domain SET version = '5.0.2';
+UPDATE civicrm_domain SET version = '5.1.0';
diff --git a/civicrm/sql/civicrm_generated.mysql b/civicrm/sql/civicrm_generated.mysql
index 136b4951d6..4acee7c4d1 100644
--- a/civicrm/sql/civicrm_generated.mysql
+++ b/civicrm/sql/civicrm_generated.mysql
@@ -398,7 +398,7 @@ UNLOCK TABLES;
 
 LOCK TABLES `civicrm_domain` WRITE;
 /*!40000 ALTER TABLE `civicrm_domain` DISABLE KEYS */;
-INSERT INTO `civicrm_domain` (`id`, `name`, `description`, `config_backend`, `version`, `contact_id`, `locales`, `locale_custom_strings`) VALUES (1,'Default Domain Name',NULL,NULL,'5.0.2',1,NULL,'a:1:{s:5:\"en_US\";a:0:{}}');
+INSERT INTO `civicrm_domain` (`id`, `name`, `description`, `config_backend`, `version`, `contact_id`, `locales`, `locale_custom_strings`) VALUES (1,'Default Domain Name',NULL,NULL,'5.1.0',1,NULL,'a:1:{s:5:\"en_US\";a:0:{}}');
 /*!40000 ALTER TABLE `civicrm_domain` ENABLE KEYS */;
 UNLOCK TABLES;
 
diff --git a/civicrm/templates/CRM/Activity/Form/Search/Common.tpl b/civicrm/templates/CRM/Activity/Form/Search/Common.tpl
index e4b83eca7a..a78e20d621 100644
--- a/civicrm/templates/CRM/Activity/Form/Search/Common.tpl
+++ b/civicrm/templates/CRM/Activity/Form/Search/Common.tpl
@@ -135,7 +135,7 @@ campaignContext="componentSearch" campaignTrClass='' campaignTdClass=''}
 
 {if $activityGroupTree}
   <tr id="activityCustom">
-    <td id="activityCustomData" colspan="2">
+    <td id="activityCustomData" colspan="4">
       {include file="CRM/Custom/Form/Search.tpl" groupTree=$activityGroupTree showHideLinks=false}
     </td>
   </tr>
diff --git a/civicrm/templates/CRM/Activity/Selector/Selector.tpl b/civicrm/templates/CRM/Activity/Selector/Selector.tpl
index a9a7c88399..6cc3b32be3 100644
--- a/civicrm/templates/CRM/Activity/Selector/Selector.tpl
+++ b/civicrm/templates/CRM/Activity/Selector/Selector.tpl
@@ -37,9 +37,9 @@
           <td class="crm-contact-form-block-activity_type_exclude_filter_id crm-inline-edit-field">
             {$form.activity_type_exclude_filter_id.label}<br /> {$form.activity_type_exclude_filter_id.html|crmAddClass:medium}
           </td>
-          {include file="CRM/Core/DateRange.tpl" fieldName="activity_date" from='_low' to='_high' label='Date'}
+          {include file="CRM/Core/DateRange.tpl" fieldName="activity_date" from='_low' to='_high' label='<label>Date</label>'}
           <td class="crm-contact-form-block-activity_status_filter_id crm-inline-edit-field">
-            {ts}Status{/ts}<br /> {$form.status_id.html|crmAddClass:medium}
+            <label>{ts}Status{/ts}</label><br /> {$form.status_id.html|crmAddClass:medium}
           </td>
         </tr>
       </table>
diff --git a/civicrm/templates/CRM/Admin/Form/MessageTemplates.tpl b/civicrm/templates/CRM/Admin/Form/MessageTemplates.tpl
index 9ef2c6c860..b2818d87f0 100644
--- a/civicrm/templates/CRM/Admin/Form/MessageTemplates.tpl
+++ b/civicrm/templates/CRM/Admin/Form/MessageTemplates.tpl
@@ -26,13 +26,14 @@
 {* this template is used for adding/editing/deleting Message Templates *}
 {capture assign=tokenDocsRepeated}{docURL page="user/common-workflows/tokens-and-mail-merge" text="token documentation"}{/capture}
 
-<h3>{if $action eq 1}{ts}New Message Template{/ts}{elseif $action eq 2}{ts}Edit Message Template{/ts}{else}{ts}Delete Message Template{/ts}{/if}</h3>
 {if $action neq 8}
 <div class="help">
     {ts}Use this form to add or edit re-usable message templates.{/ts} {help id="id-intro" file="CRM/Admin/Page/MessageTemplates.hlp"}
 </div>
 {/if}
 
+<h3>{if $action eq 1}{ts}New Message Template{/ts}{elseif $action eq 2}{ts}Edit Message Template{/ts}{else}{ts}Delete Message Template{/ts}{/if}</h3>
+
 <div class="crm-block crm-form-block">
 <div class="form-item" id="message_templates">
 {if $action eq 8}
diff --git a/civicrm/templates/CRM/Admin/Form/Setting/Mail.tpl b/civicrm/templates/CRM/Admin/Form/Setting/Mail.tpl
index 3235e35dfe..8c9ae9c0b0 100644
--- a/civicrm/templates/CRM/Admin/Form/Setting/Mail.tpl
+++ b/civicrm/templates/CRM/Admin/Form/Setting/Mail.tpl
@@ -24,9 +24,9 @@
  +--------------------------------------------------------------------+
 *}
 {capture assign=docLink}{docURL page="CiviMail Mailer Settings" text="CiviMail Mailer Settings and Optimization" resource="wiki"}{/capture}
-<div class="crm-block crm-form-block crm-mail-form-block">
-  <div class="help">
+<div class="help">
     {ts 1=$docLink}These settings are used to configure mailer properties for the optional CiviMail component and may allow you to significantly optimize performance. Please read the %1 documentation, and make sure you understand it before modifying default values. (These settings are NOT used for the built-in 'Email - send now' feature).{/ts}
   </div>
+<div class="crm-block crm-form-block crm-mail-form-block">
   {include file='CRM/Admin/Form/Setting/SettingForm.tpl'}
 </div>
diff --git a/civicrm/templates/CRM/Admin/Page/MailSettings.tpl b/civicrm/templates/CRM/Admin/Page/MailSettings.tpl
index a5f543cc85..19dcfee283 100644
--- a/civicrm/templates/CRM/Admin/Page/MailSettings.tpl
+++ b/civicrm/templates/CRM/Admin/Page/MailSettings.tpl
@@ -27,12 +27,12 @@
    {include file="CRM/Admin/Form/MailSettings.tpl"}
 {else}
 
+<div class="crm-block crm-content-block">
 {if $rows}
 <div id="mSettings">
-  <p></p>
   <div class="form-item">
     {strip}
-      <table cellpadding="0" cellspacing="0" border="0">
+      <table cellpadding="0" cellspacing="0" border="0" class="row-highlight">
         <thead class="sticky">
             <th>{ts}Name{/ts}</th>
             <th>{ts}Server{/ts}</th>
@@ -79,3 +79,4 @@
     {crmButton p="civicrm/admin" q="reset=1" class="cancel" icon="times"}{ts}Done{/ts}{/crmButton}
   </div>
 {/if}
+</div>
diff --git a/civicrm/templates/CRM/Batch/Form/Entry.tpl b/civicrm/templates/CRM/Batch/Form/Entry.tpl
index 60340e1fa9..1f97a2b21b 100644
--- a/civicrm/templates/CRM/Batch/Form/Entry.tpl
+++ b/civicrm/templates/CRM/Batch/Form/Entry.tpl
@@ -45,11 +45,15 @@
   {/if}
   <table class="form-layout-compressed batch-totals">
     <tr>
-      <td class="label">{ts}Total amount expected{/ts}</td>
+      <td class="label">
+        <label>{ts}Total amount expected{/ts}</label>
+      </td>
       <td class="right"><span class="batch-expected-total">{$batchTotal|crmMoney}</span></td>
     </tr>
     <tr>
-      <td class="label">{ts}Total amount entered{/ts}</td>
+      <td class="label">
+        <label>{ts}Total amount entered{/ts}</label>
+      </td>
       <td class="right">{$config->defaultCurrencySymbol} <span class="batch-actual-total"></span></td>
     </tr>
   </table>
diff --git a/civicrm/templates/CRM/Campaign/Form/Search.tpl b/civicrm/templates/CRM/Campaign/Form/Search.tpl
index 5d6e53c854..3799799538 100644
--- a/civicrm/templates/CRM/Campaign/Form/Search.tpl
+++ b/civicrm/templates/CRM/Campaign/Form/Search.tpl
@@ -51,7 +51,6 @@
       </div>
       <div class="crm-search-results">
        {* This section displays the rows along and includes the paging controls *}
-       <p></p>
        {include file="CRM/Campaign/Form/Selector.tpl" context="Search"}
       </div>
     </fieldset>
diff --git a/civicrm/templates/CRM/Contact/Form/Contact.hlp b/civicrm/templates/CRM/Contact/Form/Contact.hlp
index 2fe6220c6a..584e7336ae 100644
--- a/civicrm/templates/CRM/Contact/Form/Contact.hlp
+++ b/civicrm/templates/CRM/Contact/Form/Contact.hlp
@@ -160,7 +160,7 @@
   {ts}Geocoding{/ts}
 {/htxt}
 {htxt id="id-geo-code"}
-{capture assign=docLink}{docURL page="user/initial-set-up/installation-and-basic-setup" text="(Refer to the Mapping and Geocoding section in the Installation and Basic Setup Chapter)"}{/capture}
+{capture assign=docLink}{docURL page="user/initial-set-up/installation-and-basic-set-up" text="(Refer to the Mapping and Geocoding section in the Installation and Basic Setup Chapter)"}{/capture}
 <p>{ts}Latitude and longitude may be automatically populated by enabling a Mapping Provider.{/ts} {$docLink}</p>
 {/htxt}
 
diff --git a/civicrm/templates/CRM/Contact/Form/Edit/Address/CustomData.tpl b/civicrm/templates/CRM/Contact/Form/Edit/Address/CustomData.tpl
index 5f2b6a2f3d..feaa7c0988 100644
--- a/civicrm/templates/CRM/Contact/Form/Edit/Address/CustomData.tpl
+++ b/civicrm/templates/CRM/Contact/Form/Edit/Address/CustomData.tpl
@@ -31,16 +31,7 @@
             {$cd_edit.title}
         </div>
         <div>
-            {if $cd_edit.help_pre}
-                <div class="messages help">{$cd_edit.help_pre}</div>
-            {/if}
-            <table class="form-layout-compressed">
-                {foreach from=$cd_edit.fields item=element key=field_id}
-                    {include file="CRM/Contact/Form/Edit/Address/CustomField.tpl"}
-                {/foreach}
-            </table>
-            <div class="spacer"></div>
-            {if $cd_edit.help_post}<div class="messages help">{$cd_edit.help_post}</div>{/if}
+        {include file="CRM/Custom/Form/Edit/CustomData.tpl" customDataEntity='address'}
         </div>
     </div>
 
diff --git a/civicrm/templates/CRM/Contact/Form/Edit/Address/CustomField.tpl b/civicrm/templates/CRM/Contact/Form/Edit/Address/CustomField.tpl
deleted file mode 100644
index 3ce814cc99..0000000000
--- a/civicrm/templates/CRM/Contact/Form/Edit/Address/CustomField.tpl
+++ /dev/null
@@ -1,107 +0,0 @@
-{*
- +--------------------------------------------------------------------+
- | CiviCRM version 4.7                                                |
- +--------------------------------------------------------------------+
- | Copyright CiviCRM LLC (c) 2004-2018                                |
- +--------------------------------------------------------------------+
- | 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        |
- +--------------------------------------------------------------------+
-*}
-{assign var="element_name" value=$element.element_custom_name}
-{if $element.is_view eq 0}{* fix for CRM-3510 *}
-    {if $element.help_pre}
-        <tr>
-            <td>&nbsp;</td>
-            <td class="html-adjust description">{$element.help_pre}</td>
-        </tr>
-    {/if}
-     {if $element.options_per_line != 0 }
-        <tr>
-            <td class="label">{$form.address.$blockId.$element_name.label}</td>
-            <td class="html-adjust">
-                {assign var="count" value="1"}
-                <table class="form-layout-compressed" style="margin-top: -0.5em;">
-                    <tr>
-                        {* sort by fails for option per line. Added a variable to iterate through the element array*}
-                        {assign var="index" value="1"}
-                        {foreach name=outer key=key item=item from=$form.address.$blockId.$element_name}
-                            {if $index < 10}
-                                {assign var="index" value=`$index+1`}
-                            {else}
-                                <td class="labels font-light">{$form.address.$blockId.$element_name.$key.html}</td>
-                                {if $count == $element.options_per_line}
-                                    </tr>
-                                    <tr>
-                                    {assign var="count" value="1"}
-                                {else}
-                                    {assign var="count" value=`$count+1`}
-                                {/if}
-                            {/if}
-                        {/foreach}
-                    </tr>
-                </table>
-            </td>
-        </tr>
-
-        {if $element.help_post}
-            <tr>
-                <td>&nbsp;</td>
-                <td class="description">{$element.help_post}<br />&nbsp;</td>
-            </tr>
-             {/if}
-    {else}
-        <tr>
-            <td class="label">{$form.address.$blockId.$element_name.label}</td>
-            <td class="html-adjust">
-                {$form.address.$blockId.$element_name.html}&nbsp;
-
-                {if $element.data_type eq 'File'}
-                    {if $element.element_value.data}
-                        <span class="html-adjust"><br />
-                            &nbsp;{ts}Attached File{/ts}: &nbsp;
-                            {if $element.element_value.displayURL }
-                                <a href="{$element.element_value.displayURL}" class='crm-image-popup'>
-                                  <img src="{$element.element_value.displayURL}" height = "100" width="100">
-                                </a>
-                            {else}
-                                <a href="{$element.element_value.fileURL}">{$element.element_value.fileName}</a>
-                            {/if}
-                            {if $element.element_value.deleteURL }
-                                <br />
-                            {$element.element_value.deleteURL}
-                            {/if}
-                        </span>
-                    {/if}
-                {elseif $element.html_type eq 'Autocomplete-Select'}
-        {assign var="element_name" value="address[$blockId][$element_name]" }
-                    {if $element.data_type eq 'ContactReference'}
-                      {include file="CRM/Custom/Form/ContactReference.tpl"}
-                    {/if}
-                {/if}
-            </td>
-        </tr>
-
-        {if $element.help_post}
-
-<td>&nbsp;</td>
-<td class="description">{$element.help_post}<br />&nbsp;</td>
-</tr>
-        {/if}
-    {/if}
-{/if}
diff --git a/civicrm/templates/CRM/Contact/Form/Edit/CustomData.tpl b/civicrm/templates/CRM/Contact/Form/Edit/CustomData.tpl
index 73d994396b..8b5606a8ab 100644
--- a/civicrm/templates/CRM/Contact/Form/Edit/CustomData.tpl
+++ b/civicrm/templates/CRM/Contact/Form/Edit/CustomData.tpl
@@ -38,21 +38,7 @@
     <div class="crm-accordion-header">
       {$cd_edit.title}
     </div>
-
     <div id="customData{$group_id}" class="crm-accordion-body">
-      {if $cd_edit.is_multiple eq 1}
-        {if $cd_edit.table_id}
-          <table class="no-border">
-            <tr>
-              <a href="#" class="crm-hover-button crm-custom-value-del" title="{ts 1=$cd_edit.title}Delete %1{/ts}"
-               data-post='{ldelim}"valueID": "{$tableID}", "groupID": "{$group_id}", "contactId": "{$contactId}", "key": "{crmKey name='civicrm/ajax/customvalue'}"{rdelim}'>
-                <span class="icon delete-icon"></span> {ts}Delete{/ts}
-              </a>
-              <!-- crm-submit-buttons -->
-            </tr>
-          </table>
-        {/if}
-      {/if}
       {include file="CRM/Custom/Form/CustomData.tpl" formEdit=true}
     </div>
     <!-- crm-accordion-body-->
diff --git a/civicrm/templates/CRM/Contact/Form/Edit/Email.tpl b/civicrm/templates/CRM/Contact/Form/Edit/Email.tpl
index 94323e8daf..c0a9021f2a 100644
--- a/civicrm/templates/CRM/Contact/Form/Edit/Email.tpl
+++ b/civicrm/templates/CRM/Contact/Form/Edit/Email.tpl
@@ -28,42 +28,45 @@
 {* @var $blockId Contains the current email block id in evaluation, and assigned in the CRM/Contact/Form/Location.php file *}
 
 {if !$addBlock}
-    <tr>
-  <td>{ts}Email{/ts}
+  <tr>
+    <td>{ts}Email{/ts}
       &nbsp;&nbsp;<a id='addEmail' href="#" title={ts}Add{/ts} onClick="buildAdditionalBlocks( 'Email', '{$className}');return false;">{ts}add{/ts}</a>
-  </td>
-  {if $className eq 'CRM_Contact_Form_Contact'}
+    </td>
+    {if $className eq 'CRM_Contact_Form_Contact'}
       <td>{ts}On Hold?{/ts} {help id="id-onhold" file="CRM/Contact/Form/Contact.hlp"}</td>
       <td>{ts}Bulk Mailings?{/ts} {help id="id-bulkmail" file="CRM/Contact/Form/Contact.hlp"}</td>
       <td id="Email-Primary" class="hiddenElement">{ts}Primary?{/ts}</td>
-  {/if}
-    </tr>
+    {/if}
+  </tr>
 {/if}
 
 <tr id="Email_Block_{$blockId}">
-    <td>{$form.email.$blockId.email.html|crmAddClass:email}&nbsp;{$form.email.$blockId.location_type_id.html}
+  <td>{$form.email.$blockId.email.html|crmAddClass:email}&nbsp;{$form.email.$blockId.location_type_id.html}
     <div class="clear"></div>
-{if $className eq 'CRM_Contact_Form_Contact'}
-<div class="email-signature crm-collapsible collapsed">
-  <div class="collapsible-title">
-    {ts}Signature{/ts}
-  </div>
-  <div id="signatureBlock{$blockId}">
-    {$form.email.$blockId.signature_html.label}<br />{$form.email.$blockId.signature_html.html}<br />
-    {$form.email.$blockId.signature_text.label}<br />{$form.email.$blockId.signature_text.html}
-  </div>
-</div>
-
-{/if}
-    </td>
-    <td align="center">{$form.email.$blockId.on_hold.html}</td>
-    {if $multipleBulk}
-      <td align="center" id="Email-Bulkmail-html">{$form.email.$blockId.is_bulkmail.html}</td>
-    {else}
-      <td align="center" id="Email-Bulkmail-html">{$form.email.$blockId.is_bulkmail.1.html}</td>
-    {/if}
-    <td align="center" id="Email-Primary-html" {if $blockId eq 1}class="hiddenElement"{/if}>{$form.email.$blockId.is_primary.1.html}</td>
-    {if $blockId gt 1}
-  <td><a href="#" title="{ts}Delete Email Block{/ts}" onClick="removeBlock( 'Email', '{$blockId}' ); return false;">{ts}delete{/ts}</a></td>
+    {if $className eq 'CRM_Contact_Form_Contact'}
+      <div class="email-signature crm-collapsible collapsed">
+        <div class="collapsible-title">
+          {ts}Signature{/ts}
+        </div>
+        <div id="signatureBlock{$blockId}">
+          {$form.email.$blockId.signature_html.label}<br/>{$form.email.$blockId.signature_html.html}<br/>
+          {$form.email.$blockId.signature_text.label}<br/>{$form.email.$blockId.signature_text.html}
+        </div>
+      </div>
     {/if}
+  </td>
+  <td align="center">{$form.email.$blockId.on_hold.html}</td>
+  {if $multipleBulk}
+    <td align="center" id="Email-Bulkmail-html">{$form.email.$blockId.is_bulkmail.html}</td>
+  {else}
+    <td align="center" id="Email-Bulkmail-html">{$form.email.$blockId.is_bulkmail.1.html}</td>
+  {/if}
+  <td align="center" id="Email-Primary-html" {if $blockId eq 1}class="hiddenElement"{/if}>
+    {$form.email.$blockId.is_primary.1.html}
+  </td>
+  {if $blockId gt 1}
+    <td>
+      <a href="#" title="{ts}Delete Email Block{/ts}" onClick="removeBlock( 'Email', '{$blockId}' ); return false;">{ts}delete{/ts}</a>
+    </td>
+  {/if}
 </tr>
diff --git a/civicrm/templates/CRM/Contact/Form/Edit/Phone.tpl b/civicrm/templates/CRM/Contact/Form/Edit/Phone.tpl
index 184c0a4608..91b4923fab 100644
--- a/civicrm/templates/CRM/Contact/Form/Edit/Phone.tpl
+++ b/civicrm/templates/CRM/Contact/Form/Edit/Phone.tpl
@@ -40,7 +40,7 @@
   </tr>
 {/if}
 <tr id="Phone_Block_{$blockId}">
-  <td>{$form.phone.$blockId.phone.html}&nbsp;&nbsp;{ts}ext.{/ts}&nbsp;{$form.phone.$blockId.phone_ext.html|crmAddClass:four}&nbsp;</td>
+  <td>{$form.phone.$blockId.phone.html} {ts context="phone_ext"}ext.{/ts}&nbsp;{$form.phone.$blockId.phone_ext.html|crmAddClass:four}&nbsp;</td>
   {if $className eq 'CRM_Contact_Form_Contact'}
   <td>{$form.phone.$blockId.location_type_id.html}</td>
   {/if}
@@ -60,4 +60,3 @@
   </td>
 </tr>
 {/if}
-
diff --git a/civicrm/templates/CRM/Contact/Form/Edit/TagsAndGroups.tpl b/civicrm/templates/CRM/Contact/Form/Edit/TagsAndGroups.tpl
index dd726fc421..134528e776 100644
--- a/civicrm/templates/CRM/Contact/Form/Edit/TagsAndGroups.tpl
+++ b/civicrm/templates/CRM/Contact/Form/Edit/TagsAndGroups.tpl
@@ -45,7 +45,7 @@
           <td>
             {if $groupElementType eq 'select'}
               <div class="crm-section group-section">
-              {if $title}{$form.group.label}{/if}
+              {if $title}{$form.group.label}<br>{/if}
               {$form.group.html}
             </div>
             {else}
diff --git a/civicrm/templates/CRM/Contact/Form/Inline/Email.tpl b/civicrm/templates/CRM/Contact/Form/Inline/Email.tpl
index be0767213e..ccbfd1d54a 100644
--- a/civicrm/templates/CRM/Contact/Form/Inline/Email.tpl
+++ b/civicrm/templates/CRM/Contact/Form/Inline/Email.tpl
@@ -26,50 +26,52 @@
 {* This file provides the template for inline editing of emails *}
 {$form.oplock_ts.html}
 <table class="crm-inline-edit-form">
-    <tr>
-      <td colspan="5">
-        <div class="crm-submit-buttons">
-          {include file="CRM/common/formButtons.tpl"}
-        </div>
-      </td>
-    </tr>
-    <tr>
-      <td>{ts}Email{/ts}&nbsp;
+  <tr>
+    <td colspan="5">
+      <div class="crm-submit-buttons">
+        {include file="CRM/common/formButtons.tpl"}
+      </div>
+    </td>
+  </tr>
+  <tr>
+    <td>{ts}Email{/ts}&nbsp;
       {if $actualBlockCount lt 5 }
-        <span id="add-more-email" title="{ts}click to add more{/ts}"><a class="crm-hover-button action-item add-more-inline" href="#">{ts}add{/ts}</a></span>
+        <span id="add-more-email" title="{ts}click to add more{/ts}">
+          <a class="crm-hover-button action-item add-more-inline" href="#">{ts}add{/ts}</a>
+        </span>
       {/if}
+    </td>
+    <td>{ts}On Hold?{/ts}</td>
+    <td>{ts}Bulk Mailings?{/ts}</td>
+    <td>{ts}Primary?{/ts}</td>
+    <td>&nbsp;</td>
+  </tr>
+  {section name='i' start=1 loop=$totalBlocks}
+    {assign var='blockId' value=$smarty.section.i.index}
+    <tr id="Email_Block_{$blockId}" {if $blockId gt $actualBlockCount}class="hiddenElement"{/if}>
+      <td>{$form.email.$blockId.email.html|crmAddClass:email}&nbsp;{$form.email.$blockId.location_type_id.html}</td>
+      <td align="center">{$form.email.$blockId.on_hold.html}</td>
+      {if $multipleBulk}
+        <td align="center">{$form.email.$blockId.is_bulkmail.html}</td>
+      {else}
+        <td align="center" class="crm-email-bulkmail">{$form.email.$blockId.is_bulkmail.1.html}</td>
+      {/if}
+      <td align="center" class="crm-email-is_primary">{$form.email.$blockId.is_primary.1.html}</td>
+      <td>
+        {if $blockId gt 1}
+          <a title="{ts}Delete Email{/ts}" class="crm-delete-inline crm-hover-button" href="#"><span
+              class="icon delete-icon"></span></a>
+        {/if}
       </td>
-      <td>{ts}On Hold?{/ts}</td>
-      <td>{ts}Bulk Mailings?{/ts}</td>
-      <td>{ts}Primary?{/ts}</td>
-      <td>&nbsp;</td>
     </tr>
-    {section name='i' start=1 loop=$totalBlocks}
-    {assign var='blockId' value=$smarty.section.i.index}
-        <tr id="Email_Block_{$blockId}" {if $blockId gt $actualBlockCount}class="hiddenElement"{/if}>
-            <td>{$form.email.$blockId.email.html|crmAddClass:email}&nbsp;{$form.email.$blockId.location_type_id.html}
-            </td>
-            <td align="center">{$form.email.$blockId.on_hold.html}</td>
-            {if $multipleBulk}
-              <td align="center">{$form.email.$blockId.is_bulkmail.html}</td>
-            {else}
-              <td align="center" class="crm-email-bulkmail">{$form.email.$blockId.is_bulkmail.1.html}</td>
-            {/if}
-            <td align="center" class="crm-email-is_primary">{$form.email.$blockId.is_primary.1.html}</td>
-            <td>
-              {if $blockId gt 1}
-                <a title="{ts}Delete Email{/ts}" class="crm-delete-inline crm-hover-button" href="#"><span class="icon delete-icon"></span></a>
-              {/if}
-            </td>
-        </tr>
-    {/section}
+  {/section}
 </table>
 
 {literal}
-<script type="text/javascript">
-    CRM.$(function($) {
+  <script type="text/javascript">
+    CRM.$(function ($) {
       // check first primary radio
-      $('#Email_1_IsPrimary').prop('checked', true );
+      $('#Email_1_IsPrimary').prop('checked', true);
     });
-</script>
+  </script>
 {/literal}
diff --git a/civicrm/templates/CRM/Contact/Form/Inline/Phone.tpl b/civicrm/templates/CRM/Contact/Form/Inline/Phone.tpl
index 074c9afee7..16cec53a76 100644
--- a/civicrm/templates/CRM/Contact/Form/Inline/Phone.tpl
+++ b/civicrm/templates/CRM/Contact/Form/Inline/Phone.tpl
@@ -47,7 +47,7 @@
     {section name='i' start=1 loop=$totalBlocks}
     {assign var='blockId' value=$smarty.section.i.index}
     <tr id="Phone_Block_{$blockId}" {if $blockId gt $actualBlockCount}class="hiddenElement"{/if}>
-        <td>{$form.phone.$blockId.phone.html}&nbsp;&nbsp;{ts}ext.{/ts}&nbsp;{$form.phone.$blockId.phone_ext.html|crmAddClass:four}&nbsp;</td>
+        <td>{$form.phone.$blockId.phone.html} {ts context="phone_ext"}ext.{/ts}&nbsp;{$form.phone.$blockId.phone_ext.html|crmAddClass:four}&nbsp;</td>
         <td>{$form.phone.$blockId.location_type_id.html}</td>
         <td>{$form.phone.$blockId.phone_type_id.html}</td>
         <td align="center" class="crm-phone-is_primary">{$form.phone.$blockId.is_primary.1.html}</td>
diff --git a/civicrm/templates/CRM/Contact/Form/OnBehalfOf.tpl b/civicrm/templates/CRM/Contact/Form/OnBehalfOf.tpl
index 207e9c0654..84f107ad20 100644
--- a/civicrm/templates/CRM/Contact/Form/OnBehalfOf.tpl
+++ b/civicrm/templates/CRM/Contact/Form/OnBehalfOf.tpl
@@ -187,7 +187,7 @@
             <div class="content">{$form.address.$index.geo_code_1.html}, {$form.address.$index.geo_code_2.html}
                 <br class="spacer"/>
                 <span class="description">
-                    {ts}Latitude and longitude may be automatically populated by enabling a Mapping Provider.{/ts} {docURL page="user/initial-set-up/installation-and-basic-setup" text="(Refer to the Mapping and Geocoding section in the Installation and Basic Setup Chapter)"}</span>
+                    {ts}Latitude and longitude may be automatically populated by enabling a Mapping Provider.{/ts} {docURL page="user/initial-set-up/installation-and-basic-set-up" text="(Refer to the Mapping and Geocoding section in the Installation and Basic Setup Chapter)"}</span>
             </div>
             <div class="clear"></div>
         </div>
diff --git a/civicrm/templates/CRM/Contact/Form/Search/AdvancedCriteria.tpl b/civicrm/templates/CRM/Contact/Form/Search/AdvancedCriteria.tpl
index 8f2f0acb8c..47e8915dd7 100644
--- a/civicrm/templates/CRM/Contact/Form/Search/AdvancedCriteria.tpl
+++ b/civicrm/templates/CRM/Contact/Form/Search/AdvancedCriteria.tpl
@@ -56,14 +56,7 @@ CRM.$(function($) {
     return false;
   });
   // TODO: Why are the modes numeric? If they used the string there would be no need for this map
-  var modes = {
-    '2': 'CiviContribute',
-    '3': 'CiviEvent',
-    '4': 'activity',
-    '5': 'CiviMember',
-    '6': 'CiviCase',
-    '8': 'CiviMail'
-  };
+  var modes = {/literal}{$component_mappings}{literal};
   // Handle change of results mode
   $('#component_mode').change(function() {
     // Reset task dropdown
@@ -73,7 +66,7 @@ CRM.$(function($) {
       $('.crm-' + mode + '-accordion.collapsed').crmAccordionToggle();
       loadPanes(mode);
     }
-    if ($('#component_mode').val() == '7') {
+    if ('related_contact' === modes[$('#component_mode').val()]) {
       $('#crm-display_relationship_type').show();
     }
     else {
diff --git a/civicrm/templates/CRM/Contribute/Form/Contribution.tpl b/civicrm/templates/CRM/Contribute/Form/Contribution.tpl
index da7bb1bb8f..9b12de3e0b 100644
--- a/civicrm/templates/CRM/Contribute/Form/Contribution.tpl
+++ b/civicrm/templates/CRM/Contribute/Form/Contribution.tpl
@@ -31,13 +31,6 @@
   {include file="CRM/Contribute/Form/AdditionalInfo/$formType.tpl"}
 {else}
   {include file="CRM/Contribute/Form/AdditionalInfo/Payment.tpl"}
-  <div class="crm-block crm-form-block crm-contribution-form-block">
-
-  {if !$email and $action neq 8 and $context neq 'standalone'}
-  <div class="messages status no-popup">
-    <div class="icon inform-icon"></div>&nbsp;{ts}You will not be able to send an automatic email receipt for this contribution because there is no email address recorded for this contact. If you want a receipt to be sent when this contribution is recorded, click Cancel and then click Edit from the Summary tab to add an email address before recording the contribution.{/ts}
-  </div>
-  {/if}
   {if $contributionMode}
   <div class="help">
     {if $contactId && $payNow}
@@ -51,6 +44,15 @@
     {/if}
   </div>
   {/if}
+  
+  <div class="crm-block crm-form-block crm-contribution-form-block">
+
+  {if !$email and $action neq 8 and $context neq 'standalone'}
+  <div class="messages status no-popup">
+    <div class="icon inform-icon"></div>&nbsp;{ts}You will not be able to send an automatic email receipt for this contribution because there is no email address recorded for this contact. If you want a receipt to be sent when this contribution is recorded, click Cancel and then click Edit from the Summary tab to add an email address before recording the contribution.{/ts}
+  </div>
+  {/if}
+  
   {if $action eq 8}
   <div class="messages status no-popup">
     <div class="icon inform-icon"></div>
diff --git a/civicrm/templates/CRM/Contribute/Form/Contribution/Main.tpl b/civicrm/templates/CRM/Contribute/Form/Contribution/Main.tpl
index 4a270e537b..3e65035b7b 100644
--- a/civicrm/templates/CRM/Contribute/Form/Contribution/Main.tpl
+++ b/civicrm/templates/CRM/Contribute/Form/Contribution/Main.tpl
@@ -98,7 +98,7 @@
     {else}
       <div class="display-block">
         <td class="label">{$form.total_amount.label}</td>
-        <td><span>{$form.total_amount.html|crmMoney}&nbsp;&nbsp;{if $taxAmount}(includes {$taxTerm} of {$taxAmount|crmMoney}){/if}</span></td>
+        <td><span>{$form.total_amount.html|crmMoney}&nbsp;&nbsp;{if $taxAmount}{ts 1=$taxTerm 2=$taxAmount|crmMoney}(includes %1 of %2){/ts}{/if}</span></td>
       </div>
     {/if}
   {else}
diff --git a/civicrm/templates/CRM/Contribute/Form/ContributionPage/Amount.tpl b/civicrm/templates/CRM/Contribute/Form/ContributionPage/Amount.tpl
index 78eb734c50..ffdf1f82b9 100644
--- a/civicrm/templates/CRM/Contribute/Form/ContributionPage/Amount.tpl
+++ b/civicrm/templates/CRM/Contribute/Form/ContributionPage/Amount.tpl
@@ -202,7 +202,10 @@
 
             <tr><td colspan="2">
                 <fieldset><legend>{ts}Fixed Contribution Options{/ts}</legend>
-                    {ts}Use the table below to enter up to ten fixed contribution amounts. These will be presented as a list of radio button options. Both the label and dollar amount will be displayed.{/ts}{if $isQuick}{ts} Click <a id='quickconfig' href='#'>here</a> if you want to configure the Fixed Contribution Options below as part of a Price Set, with the added flexibility and complexity that entails.{/ts}{/if}<br />
+                  <div class="description">
+                    {ts}Use the table below to enter up to ten fixed contribution amounts. These will be presented as a list of radio button options. Both the label and dollar amount will be displayed.{/ts}{if $isQuick}{ts} Click <a id='quickconfig' href='#'>here</a> if you want to configure the Fixed Contribution Options below as part of a Price Set, with the added flexibility and complexity that entails.{/ts}{/if}
+                  </div>
+                    <br />
                     <table id="map-field-table">
                         <tr class="columnheader" ><th scope="column">{ts}Contribution Label{/ts}</th><th scope="column">{ts}Amount{/ts}</th><th scope="column">{ts}Default?{/ts}<br />{$form.default.0.html}</th></tr>
                         {section name=loop start=1 loop=11}
diff --git a/civicrm/templates/CRM/Contribute/Form/ContributionPage/Settings.tpl b/civicrm/templates/CRM/Contribute/Form/ContributionPage/Settings.tpl
index c046f62931..eb85deaa44 100644
--- a/civicrm/templates/CRM/Contribute/Form/ContributionPage/Settings.tpl
+++ b/civicrm/templates/CRM/Contribute/Form/ContributionPage/Settings.tpl
@@ -25,7 +25,6 @@
  +--------------------------------------------------------------------+
 *}
 {crmRegion name="contribute-form-contributionpage-settings-main"}
-<div class="crm-block crm-form-block crm-contribution-contributionpage-settings-form-block">
 <div class="help">
     {if $action eq 0}
         <p>{ts}This is the first step in creating a new online Contribution Page. You can create one or more different Contribution Pages for different purposes, audiences, campaigns, etc. Each page can have it's own introductory message, pre-configured contribution amounts, custom data collection fields, etc.{/ts}</p>
@@ -34,6 +33,8 @@
         {ts}Use this form to edit the page title, financial type (e.g. donation, campaign contribution, etc.), goal amount, introduction, and status (active/inactive) for this online contribution page.{/ts}
     {/if}
 </div>
+<div class="crm-block crm-form-block crm-contribution-contributionpage-settings-form-block">
+
     <div class="crm-submit-buttons">{include file="CRM/common/formButtons.tpl" location="top"}</div>
   <table class="form-layout-compressed">
   <tr class="crm-contribution-contributionpage-settings-form-block-title"><td class="label">{$form.title.label} {if $action == 2}{include file='CRM/Core/I18n/Dialog.tpl' table='civicrm_contribution_page' field='title' id=$contributionPageID}{/if}</td><td>{$form.title.html}<br/>
diff --git a/civicrm/templates/CRM/Contribute/Form/ContributionView.tpl b/civicrm/templates/CRM/Contribute/Form/ContributionView.tpl
index 305cbeaff8..d3b4b42f18 100644
--- a/civicrm/templates/CRM/Contribute/Form/ContributionView.tpl
+++ b/civicrm/templates/CRM/Contribute/Form/ContributionView.tpl
@@ -90,10 +90,7 @@
   {else}
     <tr>
       <td class="label">{ts}Total Amount{/ts}</td>
-      <td><strong><a class="nowrap bold crm-expand-row" title="{ts}view payments{/ts}"
-        href="{crmURL p='civicrm/payment' q="view=transaction&component=contribution&action=browse&cid=`$contact_id`&id=`$contribution_id`&selector=1"}">
-               &nbsp; {$total_amount|crmMoney:$currency}
-            </strong></a>&nbsp;
+      <td><strong>{$total_amount|crmMoney:$currency}</strong>
         {if $contribution_recur_id}
           <a class="crm-hover-button" href='{crmURL p="civicrm/contact/view/contributionrecur" q="reset=1&id=`$contribution_recur_id`&cid=`$contact_id`&context=contribution"}'>
             <strong>{ts}Recurring Contribution{/ts}</strong>
@@ -239,9 +236,13 @@
       <td>{$thankyou_date|crmDate}</td>
     </tr>
   {/if}
+  <tr>
+    <td class="label">{ts}Payment Details{/ts}</td>
+    <td>{include file="CRM/Contribute/Form/PaymentInfoBlock.tpl"}</td>
+  </tr>
   {if $addRecordPayment}
     <tr>
-      <td class='label'>{ts}Fees{/ts}</td>
+      <td class='label'>{ts}Payment Summary{/ts}</td>
       <td id='payment-info'></td>
     </tr>
   {/if}
diff --git a/civicrm/templates/CRM/Contribute/Form/Selector.tpl b/civicrm/templates/CRM/Contribute/Form/Selector.tpl
index 57b961e702..cc88a89e9b 100644
--- a/civicrm/templates/CRM/Contribute/Form/Selector.tpl
+++ b/civicrm/templates/CRM/Contribute/Form/Selector.tpl
@@ -26,12 +26,16 @@
 {include file="CRM/common/pager.tpl" location="top"}
 
 {strip}
+  <div class="crm-contact-contribute-contributions">
   <table class="selector row-highlight">
     <thead class="sticky">
     <tr>
       {if !$single and $context eq 'Search' }
         <th scope="col" title="Select Rows">{$form.toggleSelect.html}</th>
       {/if}
+      {if !$single}
+      <th scope="col"></th>
+      {/if}
       {foreach from=$columnHeaders item=header}
         <th scope="col">
           {if $header.sort}
@@ -45,9 +49,6 @@
     </tr>
     </thead>
 
-    <p class="description">
-      {ts}Click arrow to view payment details.{/ts}
-    </p>
     {counter start=0 skip=1 print=false}
     {foreach from=$rows item=row}
       <tr id="rowid{$row.contribution_id}" class="{cycle values="odd-row,even-row"} {if $row.cancel_date} cancelled{/if} crm-contribution_{$row.contribution_id}">
@@ -56,7 +57,8 @@
             {assign var=cbName value=$row.checkbox}
             <td>{$form.$cbName.html}</td>
           {/if}
-          <td>{$row.contact_type} &nbsp; <a href="{crmURL p='civicrm/contact/view' q="reset=1&cid=`$row.contact_id`"}">{$row.sort_name}</a></td>
+          <td>{$row.contact_type}</td>
+          <td><a href="{crmURL p='civicrm/contact/view' q="reset=1&cid=`$row.contact_id`"}">{$row.sort_name}</a></td>
         {/if}
         <td class="crm-contribution-amount">
           {if !$row.contribution_soft_credit_amount}
@@ -107,6 +109,7 @@
     {/foreach}
 
   </table>
+  </div>
 {/strip}
 
 {include file="CRM/common/pager.tpl" location="bottom"}
diff --git a/civicrm/templates/CRM/Contribute/Form/SoftCredit.tpl b/civicrm/templates/CRM/Contribute/Form/SoftCredit.tpl
index 69fad09a61..a5db4a6a1f 100644
--- a/civicrm/templates/CRM/Contribute/Form/SoftCredit.tpl
+++ b/civicrm/templates/CRM/Contribute/Form/SoftCredit.tpl
@@ -30,13 +30,14 @@
     <tr id="soft-credit-row-{$rowNumber}"
         class="crm-contribution-form-block-soft_credit_to {if $rowNumber gte $showSoftCreditRow}hiddenElement{/if}">
       <td>
-        {$form.soft_credit_contact_id.$rowNumber.label}&nbsp;{$form.soft_credit_contact_id.$rowNumber.html|crmAddClass:twenty}
+        {$form.soft_credit_contact_id.$rowNumber.label}<br>{$form.soft_credit_contact_id.$rowNumber.html|crmAddClass:twenty}
       </td>
       <td>
-        {$form.soft_credit_amount.$rowNumber.label}&nbsp;{$form.soft_credit_amount.$rowNumber.html|crmAddClass:eight}
+        {$form.soft_credit_amount.$rowNumber.label}<br>{$form.soft_credit_amount.$rowNumber.html|crmAddClass:eight}
       </td>
       <td>
-        {$form.soft_credit_type.$rowNumber.label}&nbsp;{$form.soft_credit_type.$rowNumber.html}
+        {$form.soft_credit_type.$rowNumber.label}<br>
+        {$form.soft_credit_type.$rowNumber.html}
         &nbsp;<a class="crm-hover-button soft-credit-delete-link" href="#"><span class="icon delete-icon"></span></a>
       </td>
     </tr>
diff --git a/civicrm/templates/CRM/Contribute/Form/UpdateSubscription.tpl b/civicrm/templates/CRM/Contribute/Form/UpdateSubscription.tpl
index a06f23cae1..e5961bad12 100644
--- a/civicrm/templates/CRM/Contribute/Form/UpdateSubscription.tpl
+++ b/civicrm/templates/CRM/Contribute/Form/UpdateSubscription.tpl
@@ -52,5 +52,18 @@
     {/if}
   </table>
 
+  <div id="customData"></div>
+  {*include custom data js file*}
+  {include file="CRM/common/customData.tpl"}
+  {literal}
+    <script type="text/javascript">
+      CRM.$(function($) {
+        {/literal}
+        CRM.buildCustomData( '{$customDataType}' );
+        {literal}
+      });
+    </script>
+  {/literal}
+
   <div class="crm-submit-buttons">{include file="CRM/common/formButtons.tpl" location="bottom"}</div>
 </div>
diff --git a/civicrm/templates/CRM/Contribute/Page/ContributionRecur.tpl b/civicrm/templates/CRM/Contribute/Page/ContributionRecur.tpl
index d825557da9..6821532484 100644
--- a/civicrm/templates/CRM/Contribute/Page/ContributionRecur.tpl
+++ b/civicrm/templates/CRM/Contribute/Page/ContributionRecur.tpl
@@ -56,6 +56,8 @@
               <td><a class="crm-hover-button" href='{crmURL p="civicrm/contact/view/membership" q="action=view&reset=1&cid=`$contactId`&id=`$recur.membership_id`&context=membership&selectedChild=member"}'>{$recur.membership_name}</a></td>
               </tr>
             {/if}
+            {include file="CRM/Custom/Page/CustomDataView.tpl"}
+
           </table>
           <div class="crm-submit-buttons"><a class="button cancel crm-form-submit" href="{crmURL p='civicrm/contact/view' q='action=browse&selectedChild=contribute'}">{ts}Done{/ts}</a></div>
         </div>
@@ -70,7 +72,7 @@
             <th scope="col">{ts}Start Date{/ts}</th>
             <th scope="col">{ts}Installments{/ts}</th>
             <th scope="col">{ts}Status{/ts}</th>
-            <th scope="col">&nbsp;</th>
+            <th scope="col"></th>
         </tr>
 
         {foreach from=$recurRows item=row}
@@ -81,9 +83,7 @@
                 <td>{$row.start_date|crmDate}</td>
                 <td>{$row.installments}</td>
                 <td>{$row.contribution_status}</td>
-                <td>
-                    {$row.action|replace:'xx':$row.recurId}
-                </td>
+                <td>{$row.action|replace:'xx':$row.recurId}</td>
             </tr>
         {/foreach}
     </table>
diff --git a/civicrm/templates/CRM/Contribute/Page/ContributionTotals.tpl b/civicrm/templates/CRM/Contribute/Page/ContributionTotals.tpl
index 20936373ec..888d06c025 100644
--- a/civicrm/templates/CRM/Contribute/Page/ContributionTotals.tpl
+++ b/civicrm/templates/CRM/Contribute/Page/ContributionTotals.tpl
@@ -24,7 +24,7 @@
  +--------------------------------------------------------------------+
 *}
 {*Table displays contribution totals for a contact or search result-set *}
-{if $annual.count OR $contributionSummary}
+{if $annual.count OR $contributionSummary.total.count OR $contributionSummary.cancel.count OR $contributionSummary.soft_credit.count}
     <table class="form-layout-compressed">
 
     {if $annual.count}
diff --git a/civicrm/templates/CRM/Contribute/Page/PaymentInfo.tpl b/civicrm/templates/CRM/Contribute/Page/PaymentInfo.tpl
index b27cad046c..039eacaa9d 100644
--- a/civicrm/templates/CRM/Contribute/Page/PaymentInfo.tpl
+++ b/civicrm/templates/CRM/Contribute/Page/PaymentInfo.tpl
@@ -55,7 +55,7 @@ CRM.$(function($) {
     {if $component eq "event"}
       <th>{ts}Total Fee(s){/ts}</th>
     {else}
-      <th>{ts}Contribution Amount(s){/ts}</th>
+      <th>{ts}Contribution Total{/ts}</th>
     {/if}
     <th class="right">{ts}Total Paid{/ts}</th>
     <th class="right">{ts}Balance{/ts}</th>
diff --git a/civicrm/templates/CRM/Contribute/Page/Tab.tpl b/civicrm/templates/CRM/Contribute/Page/Tab.tpl
index 68690af559..cd38ffa634 100644
--- a/civicrm/templates/CRM/Contribute/Page/Tab.tpl
+++ b/civicrm/templates/CRM/Contribute/Page/Tab.tpl
@@ -28,7 +28,7 @@
 {elseif $action eq 4}
     {include file="CRM/Contribute/Form/ContributionView.tpl"}
 {else}
-    <div class="view-content">
+    <div class="contact-summary-contribute-tab view-content">
         <div class="help">
             {if $permission EQ 'edit'}
               {capture assign=newContribURL}{crmURL p="civicrm/contact/view/contribution" q="reset=1&action=add&cid=`$contactId`&context=contribution"}{/capture}
@@ -52,13 +52,12 @@
                 {/if}
                 <br /><br />
             </div>
-      <div class='clear'> </div>
+          <div class='clear'></div>
         {/if}
 
-
         {if $rows}
             {include file="CRM/Contribute/Page/ContributionTotals.tpl" mode="view"}
-            <p> </p>
+          <div class='clear'></div>
             {include file="CRM/Contribute/Form/Selector.tpl"}
         {else}
             <div class="messages status no-popup">
@@ -68,19 +67,17 @@
         {/if}
 
         {if $recur}
-            <div class="solid-border-top">
-                <br /><label>{ts 1=$displayName}Recurring Contributions{/ts}</label>
-            </div>
+          <div class="crm-block crm-contact-contribute-recur">
+            <h3>{ts}Recurring Contributions{/ts}</h3>
             {include file="CRM/Contribute/Page/ContributionRecur.tpl"}
+          </div>
         {/if}
 
         {if $softCredit}
-            <div class="solid-border-top">
-                <br />
-                <div class="label">{ts}Soft credits{/ts} {help id="id-soft_credit"}</div>
-                <div class="spacer"></div>
-            </div>
+          <div class="crm-block crm-contact-contribute-softcredit">
+            <h3>{ts}Soft credits{/ts} {help id="id-soft_credit"}</h3>
             {include file="CRM/Contribute/Page/ContributionSoft.tpl"}
+          </div>
         {/if}
     </div>
 {/if}
diff --git a/civicrm/templates/CRM/Custom/Form/CustomData.tpl b/civicrm/templates/CRM/Custom/Form/CustomData.tpl
index d06e35c438..c0de8e0b75 100644
--- a/civicrm/templates/CRM/Custom/Form/CustomData.tpl
+++ b/civicrm/templates/CRM/Custom/Form/CustomData.tpl
@@ -25,42 +25,18 @@
 *}
 {* Custom Data form*}
 {if $formEdit}
-  {if $cd_edit.help_pre}
-    <div class="messages help">{$cd_edit.help_pre}</div>
-  {/if}
-  <table class="form-layout-compressed">
-    {foreach from=$cd_edit.fields item=element key=field_id}
-      {include file="CRM/Custom/Form/CustomField.tpl"}
-    {/foreach}
-  </table>
-  <div class="spacer"></div>
-  {if $cd_edit.help_post}
-    <div class="messages help">{$cd_edit.help_post}</div>
-  {/if}
-  {if $cd_edit.is_multiple and ( ( $cd_edit.max_multiple eq '' )  or ( $cd_edit.max_multiple > 0 and $cd_edit.max_multiple > $cgCount ) ) }
-    <div id="add-more-link-{$cgCount}" class="add-more-link-{$group_id} add-more-link-{$group_id}-{$cgCount}">
-      <a href="#" class="crm-hover-button" onclick="CRM.buildCustomData('{$cd_edit.extends}',{if $cd_edit.subtype}'{$cd_edit.subtype}'{else}'{$cd_edit.extends_entity_column_id}'{/if}, '', {$cgCount}, {$group_id}, true ); return false;">
-        <i class="crm-i fa-plus-circle"></i>
-        {ts 1=$cd_edit.title}Another %1 record{/ts}
-      </a>
-    </div>
-  {/if}
+  {include file="CRM/Custom/Form/Edit/CustomData.tpl" customDataEntity=''}
 {else}
   {foreach from=$groupTree item=cd_edit key=group_id name=custom_sets}
     {if $cd_edit.is_multiple and $multiRecordDisplay eq 'single'}
+      {assign var="isSingleRecordEdit" value=TRUE}
+    {else}
+      {* always assign to prevent leakage*}
+      {assign var="isSingleRecordEdit" value=''}
+    {/if}
+    {if $isSingleRecordEdit}
       <div class="custom-group custom-group-{$cd_edit.name}">
-        {if $cd_edit.help_pre}
-          <div class="messages help">{$cd_edit.help_pre}</div>
-        {/if}
-        <table>
-          {foreach from=$cd_edit.fields item=element key=field_id}
-            {include file="CRM/Custom/Form/CustomField.tpl"}
-          {/foreach}
-        </table>
-        <div class="spacer"></div>
-        {if $cd_edit.help_post}
-          <div class="messages help">{$cd_edit.help_post}</div>
-        {/if}
+        {include file="CRM/Custom/Form/Edit/CustomData.tpl" customDataEntity=''}
       </div>
     {else}
      <div class="custom-group custom-group-{$cd_edit.name} crm-accordion-wrapper crm-custom-accordion {if $cd_edit.collapse_display and !$skipTitle}collapsed{/if}">
@@ -70,42 +46,9 @@
        </div><!-- /.crm-accordion-header -->
       {/if}
       <div class="crm-accordion-body">
-        {if $cd_edit.is_multiple eq 1 and $cd_edit.table_id and $contactId and !$skipTitle and $cd_edit.style eq 'Inline'}
-          {assign var=tableID value=$cd_edit.table_id}
-          <a href="#" class="crm-hover-button crm-custom-value-del" title="{ts 1=$cd_edit.title}Delete %1{/ts}"
-           data-post='{ldelim}"valueID": "{$tableID}", "groupID": "{$group_id}", "contactId": "{$contactId}", "key": "{crmKey name='civicrm/ajax/customvalue'}"{rdelim}'>
-            <span class="icon delete-icon"></span> {ts}Delete{/ts}
-          </a>
-        {/if}
-        {if $cd_edit.help_pre}
-          <div class="messages help">{$cd_edit.help_pre}</div>
-        {/if}
-        <table class="form-layout-compressed">
-          {foreach from=$cd_edit.fields item=element key=field_id}
-            {include file="CRM/Custom/Form/CustomField.tpl"}
-          {/foreach}
-        </table>
-        <div class="spacer"></div>
-        {if $cd_edit.help_post}
-          <div class="messages help">{$cd_edit.help_post}</div>
-        {/if}
+        {include file="CRM/Custom/Form/Edit/CustomData.tpl" customDataEntity=''}
       </div>
      </div>
-     {if $cd_edit.is_multiple and ( ( $cd_edit.max_multiple eq '' )  or ( $cd_edit.max_multiple > 0 and $cd_edit.max_multiple > $cgCount ) ) }
-      {if $skipTitle}
-        {* We don't yet support adding new records in inline-edit forms *}
-        <div class="messages help">
-          <em>{ts 1=$cd_edit.title}Click "Edit Contact" to add more %1 records{/ts}</em>
-        </div>
-      {else}
-        <div id="add-more-link-{$cgCount}" class="add-more-link-{$group_id} add-more-link-{$group_id}-{$cgCount}">
-          <a href="#" class="crm-hover-button" onclick="CRM.buildCustomData('{$cd_edit.extends}',{if $cd_edit.subtype}'{$cd_edit.subtype}'{else}'{$cd_edit.extends_entity_column_id}'{/if}, '', {$cgCount}, {$group_id}, true ); return false;">
-            <i class="crm-i fa-plus-circle"></i>
-            {ts 1=$cd_edit.title}Another %1 record{/ts}
-          </a>
-        </div>
-      {/if}
-    {/if}
     {/if}
     <div id="custom_group_{$group_id}_{$cgCount}"></div>
   {/foreach}
diff --git a/civicrm/templates/CRM/Custom/Form/CustomField.tpl b/civicrm/templates/CRM/Custom/Form/CustomField.tpl
index 7dc3cd2938..0ef7da5dd7 100644
--- a/civicrm/templates/CRM/Custom/Form/CustomField.tpl
+++ b/civicrm/templates/CRM/Custom/Form/CustomField.tpl
@@ -23,73 +23,8 @@
  | see the CiviCRM license FAQ at http://civicrm.org/licensing        |
  +--------------------------------------------------------------------+
 *}
-{assign var="element_name" value=$element.element_name}
-
-    {if $element.help_pre}
-        <tr class="custom_field-help-pre-row {$element.element_name}-row-help-pre">
-            <td>&nbsp;</td>
-            <td class="html-adjust description">{$element.help_pre}</td>
-        </tr>
-    {/if}
-     {if $element.options_per_line != 0 }
-        <tr class="custom_field-row {$element.element_name}-row">
-            <td class="label">{$form.$element_name.label}{if $element.help_post}{help id=$element.id file="CRM/Custom/Form/CustomField.hlp" title=$element.label}{/if}</td>
-            <td class="html-adjust">
-                {assign var="count" value="1"}
-                <table class="form-layout-compressed" style="margin-top: -0.5em;">
-                    <tr>
-                        {* sort by fails for option per line. Added a variable to iterate through the element array*}
-                        {assign var="index" value="1"}
-                        {foreach name=outer key=key item=item from=$form.$element_name}
-                            {if $index < 10}
-                                {assign var="index" value=`$index+1`}
-                            {else}
-                                <td class="labels font-light">{$form.$element_name.$key.html}</td>
-                                {if $count == $element.options_per_line}
-                                    </tr>
-                                    <tr>
-                                    {assign var="count" value="1"}
-                                {else}
-                                    {assign var="count" value=`$count+1`}
-                                {/if}
-                            {/if}
-                        {/foreach}
-                    </tr>
-                </table>
-            </td>
-        </tr>
+{* this file is deprecated & it's recommended to define formElement in the calling function. As of 5.1
+ it is no longer used by core & is only retained in case it is used by extensions *}
 
-    {else}
-        <tr class="custom_field-row {$element.element_name}-row">
-            <td class="label">{$form.$element_name.label}{if $element.help_post}{help id=$element.id file="CRM/Custom/Form/CustomField.hlp" title=$element.label}{/if}</td>
-            <td class="html-adjust">
-                {$form.$element_name.html}&nbsp;
-                {if $element.data_type eq 'File'}
-                    {if $element.element_value.data}
-                      <div class="crm-attachment-wrapper crm-entity" id="file_{$element_name}">
-                        <span class="html-adjust"><br />
-                            &nbsp;{ts}Attached File{/ts}: &nbsp;
-                            {if $element.element_value.displayURL}
-                                <a href="{$element.element_value.displayURL}" class='crm-image-popup crm-attachment'>
-                                  <img src="{$element.element_value.displayURL}"
-                                       height = "{$element.element_value.imageThumbHeight}"
-                                       width="{$element.element_value.imageThumbWidth}">
-                                </a>
-                            {else}
-                                <a class="crm-attachment" href="{$element.element_value.fileURL}">{$element.element_value.fileName}</a>
-                            {/if}
-                            {if $element.element_value.deleteURL}
-                                   <a href="#" class="crm-hover-button delete-attachment" data-filename="{$element.element_value.fileName}" data-args="{$element.element_value.deleteURLArgs}" title="{ts}Delete File{/ts}"><span class="icon delete-icon"></span></a>
-                            {/if}
-                        </span>
-                      </div>
-                    {/if}
-                {elseif $element.html_type eq 'Autocomplete-Select'}
-                  {if $element.data_type eq 'ContactReference'}
-                    {include file="CRM/Custom/Form/ContactReference.tpl"}
-                  {/if}
-                {/if}
-            </td>
-        </tr>
-
-    {/if}
+{assign var="element_name" value=$element.element_name}
+{include file="CRM/Custom/Form/Edit/CustomField.tpl" formElement=$form.$element_name}
diff --git a/civicrm/templates/CRM/Custom/Form/Edit/CustomData.tpl b/civicrm/templates/CRM/Custom/Form/Edit/CustomData.tpl
new file mode 100644
index 0000000000..4af5020783
--- /dev/null
+++ b/civicrm/templates/CRM/Custom/Form/Edit/CustomData.tpl
@@ -0,0 +1,45 @@
+{if !$isSingleRecordEdit && $cd_edit.is_multiple eq 1 and $cd_edit.table_id and $contactId and !$skipTitle and $cd_edit.style eq 'Inline'}
+  {assign var=tableID value=$cd_edit.table_id}
+  <a href="#" class="crm-hover-button crm-custom-value-del" title="{ts 1=$cd_edit.title}Delete %1{/ts}"
+     data-post='{ldelim}"valueID": "{$tableID}", "groupID": "{$group_id}", "contactId": "{$contactId}", "key": "{crmKey name='civicrm/ajax/customvalue'}"{rdelim}'>
+    <span class="icon delete-icon"></span> {ts}Delete{/ts}
+  </a>
+{/if}
+
+{if $cd_edit.help_pre}
+  <div class="messages help">{$cd_edit.help_pre}</div>
+{/if}
+<table {if !$isSingleRecordEdit}class="form-layout-compressed"{/if}>
+  {foreach from=$cd_edit.fields item=element key=field_id}
+    {if $customDataEntity && $blockId}
+      {* custom data entity combined with blockId tells us we have an entity with mutliple blocks
+      such as address. Some risk of leakage on blockId so only set customDataEntity when using blocks*}
+      {assign var="element_name" value=$element.element_custom_name}
+      {assign var="formElement" value=$form.$customDataEntity.$blockId.$element_name}
+    {else}
+      {assign var="element_name" value=$element.element_name}
+      {assign var="formElement" value=$form.$element_name}
+    {/if}
+    {include file="CRM/Custom/Form/Edit/CustomField.tpl"}
+  {/foreach}
+</table>
+<div class="spacer"></div>
+{if $cd_edit.help_post}<div class="messages help">{$cd_edit.help_post}</div>{/if}
+{if !$isSingleRecordEdit && $cd_edit.is_multiple and ( ( $cd_edit.max_multiple eq '' )  or ( $cd_edit.max_multiple > 0 and $cd_edit.max_multiple > $cgCount ) ) }
+  {if $skipTitle}
+    {* We don't yet support adding new records in inline-edit forms *}
+    <div class="messages help">
+      <em>{ts 1=$cd_edit.title}Click "Edit Contact" to add more %1 records{/ts}</em>
+    </div>
+  {else}
+    <div id="add-more-link-{$cgCount}" class="add-more-link-{$group_id} add-more-link-{$group_id}-{$cgCount}">
+      <a href="#" class="crm-hover-button" onclick="CRM.buildCustomData('{$cd_edit.extends}',{if $cd_edit.subtype}'{$cd_edit.subtype}'{else}'{$cd_edit.extends_entity_column_id}'{/if}, '', {$cgCount}, {$group_id}, true ); return false;">
+        <i class="crm-i fa-plus-circle"></i>
+        {ts 1=$cd_edit.title}Another %1 record{/ts}
+      </a>
+    </div>
+  {/if}
+{/if}
+
+{*set customDataEntity to null to prevent leakage if this is called more than once*}
+{assign var='customDataEntity' value=''}
diff --git a/civicrm/templates/CRM/Custom/Form/Edit/CustomField.tpl b/civicrm/templates/CRM/Custom/Form/Edit/CustomField.tpl
new file mode 100644
index 0000000000..9b345a10a4
--- /dev/null
+++ b/civicrm/templates/CRM/Custom/Form/Edit/CustomField.tpl
@@ -0,0 +1,99 @@
+{*
++--------------------------------------------------------------------+
+| CiviCRM version 4.7                                                |
++--------------------------------------------------------------------+
+| Copyright CiviCRM LLC (c) 2004-2018                                |
++--------------------------------------------------------------------+
+| 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        |
++--------------------------------------------------------------------+
+*}
+
+{if $element.help_pre}
+  <tr class="custom_field-help-pre-row {$element.element_name}-row-help-pre">
+    <td>&nbsp;</td>
+    <td class="html-adjust description">{$element.help_pre}</td>
+  </tr>
+{/if}
+{if $element.options_per_line != 0 }
+  <tr class="custom_field-row {$element.element_name}-row">
+    <td
+      class="label">{$formElement.label}{if $element.help_post}{help id=$element.id file="CRM/Custom/Form/CustomField.hlp" title=$element.label}{/if}</td>
+    <td class="html-adjust">
+      {assign var="count" value="1"}
+      <table class="form-layout-compressed" style="margin-top: -0.5em;">
+        <tr>
+          {* sort by fails for option per line. Added a variable to iterate through the element array*}
+          {assign var="index" value="1"}
+          {foreach name=outer key=key item=item from=$formElement}
+          {if $index < 10}
+          {assign var="index" value=`$index+1`}
+          {else}
+          <td class="labels font-light">{$formElement.$key.html}</td>
+          {if $count == $element.options_per_line}
+        </tr>
+        <tr>
+          {assign var="count" value="1"}
+          {else}
+          {assign var="count" value=`$count+1`}
+          {/if}
+          {/if}
+          {/foreach}
+        </tr>
+      </table>
+    </td>
+  </tr>
+{else}
+  <tr class="custom_field-row {$element.element_name}-row">
+    <td class="label">{$formElement.label}
+      {if $element.help_post}{help id=$element.id file="CRM/Custom/Form/CustomField.hlp" title=$element.label}{/if}
+    </td>
+    <td class="html-adjust">
+      {$formElement.html}&nbsp;
+      {if $element.data_type eq 'File'}
+        {if $element.element_value.data}
+          <div class="crm-attachment-wrapper crm-entity" id="file_{$element.element_name}">
+            <span class="html-adjust"><br/>&nbsp;{ts}Attached File{/ts}: &nbsp;
+              {if $element.element_value.displayURL}
+                <a href="{$element.element_value.displayURL}" class='crm-image-popup crm-attachment'>
+                  <img src="{$element.element_value.displayURL}"
+                       height="{$element.element_value.imageThumbHeight}"
+                       width="{$element.element_value.imageThumbWidth}">
+                </a>
+              {else}
+                <a class="crm-attachment" href="{$element.element_value.fileURL}">{$element.element_value.fileName}</a>
+              {/if}
+              {if $element.element_value.deleteURL}
+                <a href="#" class="crm-hover-button delete-attachment"
+                   data-filename="{$element.element_value.fileName}"
+                   data-args="{$element.element_value.deleteURLArgs}" title="{ts}Delete File{/ts}">
+                  <span class="icon delete-icon"></span>
+                </a>
+              {/if}
+            </span>
+          </div>
+        {/if}
+      {elseif $element.html_type eq 'Autocomplete-Select'}
+        {if $element.data_type eq 'ContactReference'}
+          {assign var="element_name" value=$element.element_name}
+          {include file="CRM/Custom/Form/ContactReference.tpl"}
+        {/if}
+      {/if}
+    </td>
+  </tr>
+{/if}
diff --git a/civicrm/templates/CRM/Custom/Form/Group.tpl b/civicrm/templates/CRM/Custom/Form/Group.tpl
index 467063de5a..9381bd39bf 100644
--- a/civicrm/templates/CRM/Custom/Form/Group.tpl
+++ b/civicrm/templates/CRM/Custom/Form/Group.tpl
@@ -24,8 +24,8 @@
  +--------------------------------------------------------------------+
 *}
 {* add/update/view custom data group *}
+<div class="help">{ts}Use Custom Field Sets to add logically related fields for a specific type of CiviCRM record (e.g. contact records, contribution records, etc.).{/ts} {help id="id-group_intro"}</div>
 <div class="crm-block crm-form-block">
-    <div class="help">{ts}Use Custom Field Sets to add logically related fields for a specific type of CiviCRM record (e.g. contact records, contribution records, etc.).{/ts} {help id="id-group_intro"}</div>
     <div class="crm-submit-buttons">{include file="CRM/common/formButtons.tpl" location="top"}</div>
     <table class="form-layout">
     <tr>
diff --git a/civicrm/templates/CRM/Custom/Form/Option.tpl b/civicrm/templates/CRM/Custom/Form/Option.tpl
index 67da170999..2f869d7114 100644
--- a/civicrm/templates/CRM/Custom/Form/Option.tpl
+++ b/civicrm/templates/CRM/Custom/Form/Option.tpl
@@ -42,6 +42,9 @@
         <tr class="crm-custom_option-form-block-value">
             <td class="label">{$form.value.label}</td>
             <td>{$form.value.html}</td>
+        <tr class="crm-custom_option-form-block-desc">
+            <td class="label">{$form.description.label}</td>
+            <td>{$form.description.html}</td>
         <tr class="crm-custom_option-form-block-weight">
             <td class="label">{$form.weight.label}</td>
             <td>{$form.weight.html}</td>
diff --git a/civicrm/templates/CRM/Custom/Page/Option.tpl b/civicrm/templates/CRM/Custom/Page/Option.tpl
index f388d80ff5..2322e6a3d8 100644
--- a/civicrm/templates/CRM/Custom/Page/Option.tpl
+++ b/civicrm/templates/CRM/Custom/Page/Option.tpl
@@ -42,6 +42,7 @@
           <tr class="columnheader">
             <th class='crm-custom_option-label'>{ts}Label{/ts}</th>
             <th class='crm-custom_option-value'>{ts}Value{/ts}</th>
+	          <th class='crm-custom_option-description'>{ts}Description{/ts}</th>
             <th class='crm-custom_option-default_value'>{ts}Default{/ts}</th>
             <th class='crm-custom_option-is_active'>{ts}Enabled?{/ts}</th>
             <th class='crm-custom_option-links'>&nbsp;</th>
@@ -70,6 +71,7 @@
                               {sClass:'crm-custom_option-label'},
                               {sClass:'crm-custom_option-value'},
                               {sClass:'crm-custom_option-default_value'},
+                              {sClass:'crm-custom_option-default_description'},
                               {sClass:'crm-custom_option-is_active'},
                               {sClass:'crm-custom_option-links'},
                               {sClass:'hiddenElement'}
diff --git a/civicrm/templates/CRM/Event/Form/ManageEvent/Location.tpl b/civicrm/templates/CRM/Event/Form/ManageEvent/Location.tpl
index 23833b625a..628c6f92a7 100644
--- a/civicrm/templates/CRM/Event/Form/ManageEvent/Location.tpl
+++ b/civicrm/templates/CRM/Event/Form/ManageEvent/Location.tpl
@@ -71,11 +71,11 @@
     </tr>
     <tr>
       <td><label>{ts}Phone 1:{/ts}</label></td>
-      <td>{$form.phone.1.phone.html|crmAddClass:phone}&nbsp;x&nbsp;{$form.phone.1.phone_ext.html|crmAddClass:four}&nbsp;{$form.phone.1.phone_type_id.html}</td>
+      <td>{$form.phone.1.phone.html|crmAddClass:phone} {ts context="phone_ext"}ext.{/ts}&nbsp;{$form.phone.1.phone_ext.html|crmAddClass:four}&nbsp;{$form.phone.1.phone_type_id.html}</td>
     </tr>
     <tr>
       <td><label>{ts}Phone 2:{/ts}</label></td>
-      <td>{$form.phone.2.phone.html|crmAddClass:phone}&nbsp;x&nbsp;{$form.phone.2.phone_ext.html|crmAddClass:four}&nbsp;{$form.phone.2.phone_type_id.html}</td>
+      <td>{$form.phone.2.phone.html|crmAddClass:phone} {ts context="phone_ext"}ext.{/ts}&nbsp;{$form.phone.2.phone_ext.html|crmAddClass:four}&nbsp;{$form.phone.2.phone_type_id.html}</td>
     </tr>
   </table>
 
@@ -166,4 +166,3 @@
       {/literal}
     </script>
   {/if}
-
diff --git a/civicrm/templates/CRM/Event/Form/Task/Batch.tpl b/civicrm/templates/CRM/Event/Form/Task/Batch.tpl
index 8821f9342c..f70eec3fae 100644
--- a/civicrm/templates/CRM/Event/Form/Task/Batch.tpl
+++ b/civicrm/templates/CRM/Event/Form/Task/Batch.tpl
@@ -24,7 +24,6 @@
  +--------------------------------------------------------------------+
 *}
 <div class="batch-update crm-block crm-form-block crm-event-batch-form-block">
-<fieldset>
   <div class="help">
     {if $context EQ 'statusChange'} {* Update Participant Status task *}
       {ts}Update the status for each participant individually below, or change all statuses to:{/ts}
@@ -108,15 +107,10 @@
              </tr>
             {/foreach}
            </tr>
-           <tr>
-              <td>&nbsp;</td>
-              <td>&nbsp;</td>
-              <td> {if $fields}{$form._qf_Batch_refresh.html}{/if}{include file="CRM/common/formButtons.tpl"}
-              </td>
-           </tr>
          </table>
-
-</fieldset>
+<div class="crm-submit-buttons">
+{if $fields}{$form._qf_Batch_refresh.html}{/if}{include file="CRM/common/formButtons.tpl"}
+</div>
 </div>
 
 {if $context EQ 'statusChange'} {* Update Participant Status task *}
diff --git a/civicrm/templates/CRM/Event/Form/Task/PickProfile.tpl b/civicrm/templates/CRM/Event/Form/Task/PickProfile.tpl
index c7d221f973..2264fd06cf 100644
--- a/civicrm/templates/CRM/Event/Form/Task/PickProfile.tpl
+++ b/civicrm/templates/CRM/Event/Form/Task/PickProfile.tpl
@@ -33,10 +33,9 @@
            <td>&nbsp;</td>
            <td>{include file="CRM/Event/Form/Task.tpl"}</td>
         </tr>
-        <tr>
-           <td>&nbsp;</td>
-           <td>{include file="CRM/common/formButtons.tpl" location="bottom"}</td>
-        </tr>
     </table>
+    <div class="crm-submit-buttons">
+      {include file="CRM/common/formButtons.tpl" location="bottom"}
+    </div>
 </div>
 
diff --git a/civicrm/templates/CRM/Event/Form/Task/SaveSearch.tpl b/civicrm/templates/CRM/Event/Form/Task/SaveSearch.tpl
index 81887a6bbd..d05ef2468f 100644
--- a/civicrm/templates/CRM/Event/Form/Task/SaveSearch.tpl
+++ b/civicrm/templates/CRM/Event/Form/Task/SaveSearch.tpl
@@ -24,8 +24,8 @@
  +--------------------------------------------------------------------+
 *}
 <div class="crm-block crm-form-block crm-event-savesearch-form-block">
-<fieldset>
-    <legend>{ts}Smart Group{/ts}</legend>
+
+  <h3>{ts}Smart Group{/ts}</h3>
 
   <div class="help">
     <p>{ts}This smart group will stay up-to-date with all contacts who meet the search criteria.{/ts}</p>
@@ -56,11 +56,9 @@
    <tr>
       <td colspan="2" class="label">{include file="CRM/Event/Form/Task.tpl"}</td>
    </tr>
-   <tr>
-      <td colspan="2">{include file="CRM/common/formButtons.tpl" location="bottom"}</td>
-   </tr>
 </table>
-
-</fieldset>
+<div class="crm-submit-buttons">
+{include file="CRM/common/formButtons.tpl" location="bottom"}
+</div>
 </div>
 
diff --git a/civicrm/templates/CRM/Friend/Form/Friend.tpl b/civicrm/templates/CRM/Friend/Form/Friend.tpl
index 20c8363862..9165352a3e 100644
--- a/civicrm/templates/CRM/Friend/Form/Friend.tpl
+++ b/civicrm/templates/CRM/Friend/Form/Friend.tpl
@@ -42,9 +42,6 @@
 </div>
    <div class="crm-submit-buttons">{include file="CRM/common/formButtons.tpl" location="top"}</div>
     <table class="form-layout">
-        <tr>
-           <td></td>
-        </tr>
         <tr class="crm-friend-manage-form-block-tf_is_active">
            <td class="label"">{$form.tf_is_active.html}</td>
            <td>{$form.tf_is_active.label}</td>
diff --git a/civicrm/templates/CRM/Group/Form/Edit.tpl b/civicrm/templates/CRM/Group/Form/Edit.tpl
index e515ef3f0f..00041fb9ef 100644
--- a/civicrm/templates/CRM/Group/Form/Edit.tpl
+++ b/civicrm/templates/CRM/Group/Form/Edit.tpl
@@ -76,7 +76,7 @@
   </tr>
 
   <tr class="crm-group-form-block-isReserved">
-    <td class="report-label">{$form.is_reserved.label}</td>
+    <td class="label">{$form.is_reserved.label}</td>
     <td>{$form.is_reserved.html}
       <span class="description">{ts}If reserved, only users with 'administer reserved groups' permission can disable, delete, or change settings for this group. The reserved flag does NOT affect users ability to add or remove contacts from a group.{/ts}</span>
     </td>
diff --git a/civicrm/templates/CRM/Member/Form/MembershipCommon.tpl b/civicrm/templates/CRM/Member/Form/MembershipCommon.tpl
index 37517e2dda..bb4bd07021 100644
--- a/civicrm/templates/CRM/Member/Form/MembershipCommon.tpl
+++ b/civicrm/templates/CRM/Member/Form/MembershipCommon.tpl
@@ -1,5 +1,5 @@
 {if !$membershipMode}
-  {if $accessContribution && $action != 2}
+  {if $accessContribution && ($action != 2 or (!$rows.0.contribution_id AND !$softCredit) or $onlinePendingContributionId)}
     <table>
       <tr class="crm-{$formClass}-form-block-contribution-contact">
         <td class="label">{$form.is_different_contribution_contact.label}</td>
diff --git a/civicrm/templates/CRM/Pledge/Form/Selector.tpl b/civicrm/templates/CRM/Pledge/Form/Selector.tpl
index 4099d60729..b6c03b1f09 100644
--- a/civicrm/templates/CRM/Pledge/Form/Selector.tpl
+++ b/civicrm/templates/CRM/Pledge/Form/Selector.tpl
@@ -34,9 +34,7 @@
         {if ! $single and $context eq 'Search' }
             <th scope="col" title="Select Rows">{$form.toggleSelect.html}</th>
         {/if}
-        {if $single}
             <th></th>
-        {/if}
         {foreach from=$columnHeaders item=header}
             <th scope="col">
                 {if $header.sort}
@@ -60,8 +58,8 @@
                 <a class="crm-expand-row" title="{ts}view payments{/ts}" href="{crmURL p='civicrm/pledge/payment' q="action=browse&context=`$context`&pledgeId=`$row.pledge_id`&cid=`$row.contact_id`"}"></a>
             </td>
             {if ! $single }
+                <td>{$row.contact_type}</td>
                 <td>
-                    {$row.contact_type} &nbsp;
                     <a href="{crmURL p='civicrm/contact/view' q="reset=1&cid=`$row.contact_id`"}">{$row.sort_name}</a>
                 </td>
             {/if}
diff --git a/civicrm/templates/CRM/Price/Form/PriceSet.tpl b/civicrm/templates/CRM/Price/Form/PriceSet.tpl
index eacf241ae7..e6876900ee 100644
--- a/civicrm/templates/CRM/Price/Form/PriceSet.tpl
+++ b/civicrm/templates/CRM/Price/Form/PriceSet.tpl
@@ -82,7 +82,7 @@
                           {$amount|crmMoney}
                         {elseif $displayOpt == 'Inclusive'}
                           {$amount|crmMoney}
-                          <span class='crm-price-amount-label'> (includes {$taxTerm} of {$option.tax_amount|crmMoney})</span>
+                          <span class='crm-price-amount-label'> {ts 1=$taxTerm 2=$option.tax_amount|crmMoney}(includes %1 of %2){/ts}</span>
                         {else}
                           {$option.amount|crmMoney}
                           <span class='crm-price-amount-label'> + {$option.tax_amount|crmMoney} {$taxTerm}</span>
diff --git a/civicrm/templates/CRM/Profile/Page/MultipleRecordFieldsListing.tpl b/civicrm/templates/CRM/Profile/Page/MultipleRecordFieldsListing.tpl
index fa46b57d3f..03206d0b89 100644
--- a/civicrm/templates/CRM/Profile/Page/MultipleRecordFieldsListing.tpl
+++ b/civicrm/templates/CRM/Profile/Page/MultipleRecordFieldsListing.tpl
@@ -49,7 +49,7 @@
               {literal}
               <script type="text/javascript">
                 (function($) {
-                  var ZeroRecordText = {/literal}'{ts 1=$customGroupTitle}No records of type \'%1\' found.{/ts}'{literal};
+                  var ZeroRecordText = {/literal}'{ts 1=$customGroupTitle|escape}No records of type \'%1\' found.{/ts}'{literal};
                   var $table = $('#records-' + {/literal}'{$customGroupId}'{literal});
                   $('table.crm-multifield-selector').data({
                     "ajax": {
diff --git a/civicrm/templates/CRM/common/civicrm.settings.php.template b/civicrm/templates/CRM/common/civicrm.settings.php.template
index e2993b81bd..bb575170a4 100644
--- a/civicrm/templates/CRM/common/civicrm.settings.php.template
+++ b/civicrm/templates/CRM/common/civicrm.settings.php.template
@@ -420,6 +420,13 @@ if (!defined('CIVICRM_DB_CACHE_PREFIX')) {
 // define('CIVICRM_GETTEXT_NATIVE', 1);
 // }
 
+/**
+ * Define how many times to retry a transaction when the DB hits a deadlock
+ * (ie. the database is locked by another transaction). This is an
+ * advanced setting intended for high-traffic databases & experienced developers/ admins.
+ */
+define('CIVICRM_DEADLOCK_RETRIES', 3);
+
 /**
  * Configure MySQL to throw more errors when encountering unusual SQL expressions.
  *
diff --git a/civicrm/vendor/autoload.php b/civicrm/vendor/autoload.php
index fba7079725..5f96e3447d 100644
--- a/civicrm/vendor/autoload.php
+++ b/civicrm/vendor/autoload.php
@@ -4,4 +4,4 @@
 
 require_once __DIR__ . '/composer/autoload_real.php';
 
-return ComposerAutoloaderInitb241e108718908c2e104fc6a22d5523d::getLoader();
+return ComposerAutoloaderInit96ff39fb6e058d2b7f42d3e422a177a8::getLoader();
diff --git a/civicrm/vendor/composer/autoload_real.php b/civicrm/vendor/composer/autoload_real.php
index dfb80a93f3..e020c6c8cc 100644
--- a/civicrm/vendor/composer/autoload_real.php
+++ b/civicrm/vendor/composer/autoload_real.php
@@ -2,7 +2,7 @@
 
 // autoload_real.php @generated by Composer
 
-class ComposerAutoloaderInitb241e108718908c2e104fc6a22d5523d
+class ComposerAutoloaderInit96ff39fb6e058d2b7f42d3e422a177a8
 {
     private static $loader;
 
@@ -19,9 +19,9 @@ class ComposerAutoloaderInitb241e108718908c2e104fc6a22d5523d
             return self::$loader;
         }
 
-        spl_autoload_register(array('ComposerAutoloaderInitb241e108718908c2e104fc6a22d5523d', 'loadClassLoader'), true, true);
+        spl_autoload_register(array('ComposerAutoloaderInit96ff39fb6e058d2b7f42d3e422a177a8', 'loadClassLoader'), true, true);
         self::$loader = $loader = new \Composer\Autoload\ClassLoader();
-        spl_autoload_unregister(array('ComposerAutoloaderInitb241e108718908c2e104fc6a22d5523d', 'loadClassLoader'));
+        spl_autoload_unregister(array('ComposerAutoloaderInit96ff39fb6e058d2b7f42d3e422a177a8', 'loadClassLoader'));
 
         $includePaths = require __DIR__ . '/include_paths.php';
         $includePaths[] = get_include_path();
@@ -31,7 +31,7 @@ class ComposerAutoloaderInitb241e108718908c2e104fc6a22d5523d
         if ($useStaticLoader) {
             require_once __DIR__ . '/autoload_static.php';
 
-            call_user_func(\Composer\Autoload\ComposerStaticInitb241e108718908c2e104fc6a22d5523d::getInitializer($loader));
+            call_user_func(\Composer\Autoload\ComposerStaticInit96ff39fb6e058d2b7f42d3e422a177a8::getInitializer($loader));
         } else {
             $map = require __DIR__ . '/autoload_namespaces.php';
             foreach ($map as $namespace => $path) {
@@ -52,19 +52,19 @@ class ComposerAutoloaderInitb241e108718908c2e104fc6a22d5523d
         $loader->register(true);
 
         if ($useStaticLoader) {
-            $includeFiles = Composer\Autoload\ComposerStaticInitb241e108718908c2e104fc6a22d5523d::$files;
+            $includeFiles = Composer\Autoload\ComposerStaticInit96ff39fb6e058d2b7f42d3e422a177a8::$files;
         } else {
             $includeFiles = require __DIR__ . '/autoload_files.php';
         }
         foreach ($includeFiles as $fileIdentifier => $file) {
-            composerRequireb241e108718908c2e104fc6a22d5523d($fileIdentifier, $file);
+            composerRequire96ff39fb6e058d2b7f42d3e422a177a8($fileIdentifier, $file);
         }
 
         return $loader;
     }
 }
 
-function composerRequireb241e108718908c2e104fc6a22d5523d($fileIdentifier, $file)
+function composerRequire96ff39fb6e058d2b7f42d3e422a177a8($fileIdentifier, $file)
 {
     if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) {
         require $file;
diff --git a/civicrm/vendor/composer/autoload_static.php b/civicrm/vendor/composer/autoload_static.php
index 9d7737e30b..3059544393 100644
--- a/civicrm/vendor/composer/autoload_static.php
+++ b/civicrm/vendor/composer/autoload_static.php
@@ -4,7 +4,7 @@
 
 namespace Composer\Autoload;
 
-class ComposerStaticInitb241e108718908c2e104fc6a22d5523d
+class ComposerStaticInit96ff39fb6e058d2b7f42d3e422a177a8
 {
     public static $files = array (
         'decc78cc4436b1292c6c0d151b19445c' => __DIR__ . '/..' . '/phpseclib/phpseclib/phpseclib/bootstrap.php',
@@ -371,10 +371,10 @@ class ComposerStaticInitb241e108718908c2e104fc6a22d5523d
     public static function getInitializer(ClassLoader $loader)
     {
         return \Closure::bind(function () use ($loader) {
-            $loader->prefixLengthsPsr4 = ComposerStaticInitb241e108718908c2e104fc6a22d5523d::$prefixLengthsPsr4;
-            $loader->prefixDirsPsr4 = ComposerStaticInitb241e108718908c2e104fc6a22d5523d::$prefixDirsPsr4;
-            $loader->prefixesPsr0 = ComposerStaticInitb241e108718908c2e104fc6a22d5523d::$prefixesPsr0;
-            $loader->classMap = ComposerStaticInitb241e108718908c2e104fc6a22d5523d::$classMap;
+            $loader->prefixLengthsPsr4 = ComposerStaticInit96ff39fb6e058d2b7f42d3e422a177a8::$prefixLengthsPsr4;
+            $loader->prefixDirsPsr4 = ComposerStaticInit96ff39fb6e058d2b7f42d3e422a177a8::$prefixDirsPsr4;
+            $loader->prefixesPsr0 = ComposerStaticInit96ff39fb6e058d2b7f42d3e422a177a8::$prefixesPsr0;
+            $loader->classMap = ComposerStaticInit96ff39fb6e058d2b7f42d3e422a177a8::$classMap;
 
         }, null, ClassLoader::class);
     }
diff --git a/civicrm/xml/version.xml b/civicrm/xml/version.xml
index 23fc4ebb50..5530db5ddd 100644
--- a/civicrm/xml/version.xml
+++ b/civicrm/xml/version.xml
@@ -1,4 +1,4 @@
 <?xml version="1.0" encoding="iso-8859-1" ?>
 <version>
-  <version_no>5.0.2</version_no>
+  <version_no>5.1.0</version_no>
 </version>
-- 
GitLab