Merge remote-tracking branch 'upstream/4.5' into 4.5-master-2015-01-12-16-09-32
authorkurund <kurund@civicrm.org>
Mon, 12 Jan 2015 10:51:26 +0000 (16:21 +0530)
committerkurund <kurund@civicrm.org>
Mon, 12 Jan 2015 10:51:26 +0000 (16:21 +0530)
Conflicts:
CRM/Contact/Page/AJAX.php
CRM/Contribute/Form/ContributionPage/Settings.php

1  2 
CRM/Contact/Page/AJAX.php
CRM/Contribute/Form/Contribution/Main.php
CRM/Contribute/Form/ContributionPage/Settings.php

index 9d1580f5c823c3e6c1de81fd9025366e794bd578,11a3202147deddf92f5311c60ef3e1028a6c42f1..5018815665a5896141f86af6a2e1ca378078dff5
@@@ -1,7 -1,7 +1,7 @@@
  <?php
  /*
   +--------------------------------------------------------------------+
 - | CiviCRM version 4.5                                                |
 + | CiviCRM version 4.6                                                |
   +--------------------------------------------------------------------+
   | Copyright CiviCRM LLC (c) 2004-2014                                |
   +--------------------------------------------------------------------+
@@@ -48,7 -48,7 +48,7 @@@ class CRM_Contact_Page_AJAX 
    /**
     * @deprecated
     */
 -  static function getContactList() {
 +  public static function getContactList() {
      // if context is 'customfield'
      if (CRM_Utils_Array::value('context', $_GET) == 'customfield') {
        return self::contactReference();
@@@ -65,7 -65,7 +65,7 @@@
        'context' => 'context',
        'rel' => 'rel',
        'contact_sub_type' => 'contact_sub_type',
 -      'contact_type' => 'contact_type'
 +      'contact_type' => 'contact_type',
      );
      foreach ($whitelist as $key => $param) {
        if (!empty($_GET[$key])) {
     *
     * Todo: Migrate contact reference fields to use EntityRef
     */
 -  static function contactReference() {
 +  public static function contactReference() {
      $name = CRM_Utils_Array::value('term', $_GET);
      $name = CRM_Utils_Type::escape($name, 'String');
      $cfID = CRM_Utils_Type::escape($_GET['id'], 'Positive');
      }
  
      $list = array_keys(CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
 -        'contact_reference_options'
 -      ), '1');
 +      'contact_reference_options'
 +    ), '1');
  
      $return = array_unique(array_merge(array('sort_name'), $list));
  
      }
  
      if (!empty($action)) {
 -      $excludeGet = array('reset', 'key', 'className', 'fnName', 'json', 'reset', 'context', 'timestamp', 'limit', 'id', 's', 'q', 'action');
 +      $excludeGet = array(
 +        'reset',
 +        'key',
 +        'className',
 +        'fnName',
 +        'json',
 +        'reset',
 +        'context',
 +        'timestamp',
 +        'limit',
 +        'id',
 +        's',
 +        'q',
 +        'action'
 +      );
        foreach ($_GET as $param => $val) {
          if (empty($val) ||
            in_array($param, $excludeGet) ||
    }
  
    /**
 -   * Function to fetch PCP ID by PCP Supporter sort_name, also displays PCP title and associated Contribution Page title
 +   * Fetch PCP ID by PCP Supporter sort_name, also displays PCP title and associated Contribution Page title
     */
 -  static function getPCPList() {
 -    $name  = CRM_Utils_Array::value('term', $_GET);
 -    $name  = CRM_Utils_Type::escape($name, 'String');
 +  public static function getPCPList() {
-     $name = CRM_Utils_Array::value('s', $_GET);
++    $name = CRM_Utils_Array::value('term', $_GET);
 +    $name = CRM_Utils_Type::escape($name, 'String');
      $limit = '10';
  
      $where = ' AND pcp.page_id = cp.id AND pcp.contact_id = cc.id';
      CRM_Utils_JSON::output($results);
    }
  
 -  static function relationship() {
 +  public static function relationship() {
      $relType = CRM_Utils_Request::retrieve('rel_type', 'Positive', CRM_Core_DAO::$_nullObject, TRUE);
      $relContactID = CRM_Utils_Request::retrieve('rel_contact', 'Positive', CRM_Core_DAO::$_nullObject, TRUE);
      $relationshipID = CRM_Utils_Array::value('rel_id', $_REQUEST); // this used only to determine add or update mode
  
      $ret = array('is_error' => 0);
  
 -    foreach($clientList as $sourceContactID) {
 +    foreach ($clientList as $sourceContactID) {
        $relationParams = array(
          'relationship_type_id' => $relType . '_a_b',
          'contact_check' => array($relContactID => 1),
          $caseRelationships->contact_id_a = $sourceContactID;
          $caseRelationships->find();
  
 -        while($caseRelationships->fetch()) {
 +        while ($caseRelationships->fetch()) {
            $relationIds['relationship'] = $caseRelationships->id;
            $relationIds['contactTarget'] = $relContactID;
          }
        }
  
        // create new or update existing relationship
 -      $return = CRM_Contact_BAO_Relationship::create($relationParams, $relationIds);
 +      $return = CRM_Contact_BAO_Relationship::createMultiple($relationParams, $relationIds);
  
        if (!empty($return[4][0])) {
          $relationshipID = $return[4][0];
          $ret = array(
            'is_error' => 1,
            'error_message' => ts('The relationship type definition for the case role is not valid for the client and / or staff contact types. You can review and edit relationship types at <a href="%1">Administer >> Option Lists >> Relationship Types</a>.',
 -            array(1 => CRM_Utils_System::url('civicrm/admin/reltype', 'reset=1')))
 +            array(1 => CRM_Utils_System::url('civicrm/admin/reltype', 'reset=1'))),
          );
        }
      }
    }
  
    /**
 -   * Function to fetch the custom field help
 +   * Fetch the custom field help
     */
 -  static function customField() {
 -    $fieldId          = CRM_Utils_Type::escape($_REQUEST['id'], 'Integer');
 -    $params           = array('id' => $fieldId);
 +  public static function customField() {
 +    $fieldId = CRM_Utils_Type::escape($_REQUEST['id'], 'Integer');
 +    $params = array('id' => $fieldId);
      $returnProperties = array('help_pre', 'help_post');
 -    $values           = array();
 +    $values = array();
  
      CRM_Core_DAO::commonRetrieve('CRM_Core_DAO_CustomField', $params, $values, $returnProperties);
      CRM_Utils_JSON::output($values);
    }
  
 -  static function groupTree() {
 +  public static function groupTree() {
      $gids = CRM_Utils_Type::escape($_GET['gids'], 'String');
      echo CRM_Contact_BAO_GroupNestingCache::json($gids);
      CRM_Utils_System::civiExit();
     * Old quicksearch function. No longer used in core.
     * @todo: Remove this function and associated menu entry in CiviCRM 5
     */
 -  static function search() {
 +  public static function search() {
      $json = TRUE;
      $name = CRM_Utils_Array::value('name', $_GET, '');
      if (!array_key_exists('name', $_GET)) {
        $relType = NULL;
        if (isset($_GET['rel'])) {
          $relation = explode('_', $_GET['rel']);
 -        $relType  = CRM_Utils_Type::escape($relation[0], 'Integer');
 -        $rel      = CRM_Utils_Type::escape($relation[2], 'String');
 +        $relType = CRM_Utils_Type::escape($relation[0], 'Integer');
 +        $rel = CRM_Utils_Type::escape($relation[2], 'String');
        }
  
        //shared household info
          $splitName = explode(' :: ', $name);
          if ($splitName) {
            $contactName = trim(CRM_Utils_Array::value('0', $splitName));
 -          $street      = trim(CRM_Utils_Array::value('1', $splitName));
 -          $city        = trim(CRM_Utils_Array::value('2', $splitName));
 +          $street = trim(CRM_Utils_Array::value('1', $splitName));
 +          $city = trim(CRM_Utils_Array::value('2', $splitName));
          }
          else {
            $contactName = $name;
@@@ -497,8 -483,7 +497,8 @@@ ORDER BY sort_name "
        else {
          while ($dao->fetch()) {
            if ($json) {
 -            $elements[] = array('name' => addslashes($dao->sort_name),
 +            $elements[] = array(
 +              'name' => addslashes($dao->sort_name),
                'id' => $dao->id,
              );
            }
    }
  
    /**
 -   * Function to delete custom value
 -   *
 +   * Delete custom value
     */
 -  static function deleteCustomValue() {
 +  public static function deleteCustomValue() {
      $customValueID = CRM_Utils_Type::escape($_REQUEST['valueID'], 'Positive');
      $customGroupID = CRM_Utils_Type::escape($_REQUEST['groupID'], 'Positive');
  
    }
  
    /**
 -   * Function to perform enable / disable actions on record.
 -   *
 +   * Perform enable / disable actions on record.
     */
 -  static function enableDisable() {
 -    $op        = CRM_Utils_Type::escape($_REQUEST['op'], 'String');
 -    $recordID  = CRM_Utils_Type::escape($_REQUEST['recordID'], 'Positive');
 +  public static function enableDisable() {
 +    $op = CRM_Utils_Type::escape($_REQUEST['op'], 'String');
 +    $recordID = CRM_Utils_Type::escape($_REQUEST['recordID'], 'Positive');
      $recordBAO = CRM_Utils_Type::escape($_REQUEST['recordBAO'], 'String');
  
      $isActive = NULL;
        // make sure recordClass is namespaced (we cant check CRM since extensions can also use this)
        // but it should be at least 3 levels deep
        if (count($recordClass) >= 3) {
 -        require_once (str_replace('_', DIRECTORY_SEPARATOR, $recordBAO) . ".php");
 +        require_once str_replace('_', DIRECTORY_SEPARATOR, $recordBAO) . ".php";
          $method = 'setIsActive';
  
          if (method_exists($recordBAO, $method)) {
    }
  
    /**
 -     *Function to check the CMS username
 -     *
 -    */
 +   *  check the CMS username
 +   */
    static public function checkUserName() {
      $signer = new CRM_Utils_Signer(CRM_Core_Key::privateKey(), array('for', 'ts'));
      if (
    /**
     *  Function to get email address of a contact
     */
 -  static function getContactEmail() {
 +  public static function getContactEmail() {
      if (!empty($_REQUEST['contact_id'])) {
        $contactID = CRM_Utils_Type::escape($_REQUEST['contact_id'], 'Positive');
        if (!CRM_Contact_BAO_Contact_Permission::allow($contactID, CRM_Core_Permission::EDIT)) {
        }
        list($displayName,
          $userEmail
 -      ) = CRM_Contact_BAO_Contact_Location::getEmailDetails($contactID);
 +        ) = CRM_Contact_BAO_Contact_Location::getEmailDetails($contactID);
        if ($userEmail) {
          echo $userEmail;
        }
          }
        }
        else {
 -              $cid = CRM_Utils_Array::value('cid', $_GET);
 -              if ($cid) {
 +        $cid = CRM_Utils_Array::value('cid', $_GET);
 +        if ($cid) {
            //check cid for interger
            $contIDS = explode(',', $cid);
            foreach ($contIDS as $contID) {
              CRM_Utils_Type::escape($contID, 'Integer');
            }
            $queryString = " cc.id IN ( $cid )";
 -              }
 +        }
        }
  
        if ($queryString) {
@@@ -723,10 -711,11 +723,10 @@@ LIMIT {$offset}, {$rowCount
              CRM_Utils_Array::value('cid', $_GET)
            );
  
 -
            $dao = CRM_Core_DAO::executeQuery($query);
  
            while ($dao->fetch()) {
 -              //working here
 +            //working here
              $result[] = array(
                'text' => '"' . $dao->name . '" <' . $dao->email . '>',
                'id' => (CRM_Utils_Array::value('id', $_GET)) ? "{$dao->id}::{$dao->email}" : '"' . $dao->name . '" <' . $dao->email . '>',
      CRM_Utils_System::civiExit();
    }
  
 -  static function getContactPhone() {
 +  public static function getContactPhone() {
  
      $queryString = NULL;
      //check for mobile type
        $queryString = " ( cc.sort_name LIKE '%$name%' OR cp.phone LIKE '%$name%' ) ";
      }
      else {
 -      $cid = CRM_Utils_Array::value('cid', $_GET);
 -      if ($cid) {
 +      $cid = CRM_Utils_Array::value('cid', $_GET);
 +      if ($cid) {
          //check cid for interger
          $contIDS = explode(',', $cid);
          foreach ($contIDS as $contID) {
@@@ -811,7 -800,7 +811,7 @@@ LIMIT {$offset}, {$rowCount
    }
  
  
 -  static function buildSubTypes() {
 +  public static function buildSubTypes() {
      $parent = CRM_Utils_Array::value('parentId', $_REQUEST);
  
      switch ($parent) {
      CRM_Utils_JSON::output($subTypes);
    }
  
 -  static function buildDedupeRules() {
 +  public static function buildDedupeRules() {
      $parent = CRM_Utils_Array::value('parentId', $_REQUEST);
  
      switch ($parent) {
    /**
     * Function used for CiviCRM dashboard operations
     */
 -  static function dashboard() {
 +  public static function dashboard() {
      $operation = CRM_Utils_Type::escape($_REQUEST['op'], 'String');
  
      switch ($operation) {
    }
  
    /**
 -   * Function to retrieve signature based on email id
 +   * Retrieve signature based on email id
     */
 -  static function getSignature() {
 +  public static function getSignature() {
      $emailID = CRM_Utils_Type::escape($_REQUEST['emailID'], 'Positive');
 -    $query   = "SELECT signature_text, signature_html FROM civicrm_email WHERE id = {$emailID}";
 -    $dao     = CRM_Core_DAO::executeQuery($query);
 +    $query = "SELECT signature_text, signature_html FROM civicrm_email WHERE id = {$emailID}";
 +    $dao = CRM_Core_DAO::executeQuery($query);
  
      $signatures = array();
      while ($dao->fetch()) {
    }
  
    /**
 -   * Function to process dupes.
 -   *
 +   * Process dupes.
     */
 -  static function processDupes() {
 +  public static function processDupes() {
      $oper = CRM_Utils_Type::escape($_REQUEST['op'], 'String');
 -    $cid  = CRM_Utils_Type::escape($_REQUEST['cid'], 'Positive');
 -    $oid  = CRM_Utils_Type::escape($_REQUEST['oid'], 'Positive');
 +    $cid = CRM_Utils_Type::escape($_REQUEST['cid'], 'Positive');
 +    $oid = CRM_Utils_Type::escape($_REQUEST['oid'], 'Positive');
  
      if (!$oper || !$cid || !$oid) {
        return;
      CRM_Utils_JSON::output(array('status' => ($status) ? $oper : $status));
    }
  
 -  static function getDedupes() {
 +  public static function getDedupes() {
  
 -    $sEcho     = CRM_Utils_Type::escape($_REQUEST['sEcho'], 'Integer');
 -    $offset    = isset($_REQUEST['iDisplayStart']) ? CRM_Utils_Type::escape($_REQUEST['iDisplayStart'], 'Integer') : 0;
 -    $rowCount  = isset($_REQUEST['iDisplayLength']) ? CRM_Utils_Type::escape($_REQUEST['iDisplayLength'], 'Integer') : 25;
 -    $sort      = 'sort_name';
 +    $sEcho = CRM_Utils_Type::escape($_REQUEST['sEcho'], 'Integer');
 +    $offset = isset($_REQUEST['iDisplayStart']) ? CRM_Utils_Type::escape($_REQUEST['iDisplayStart'], 'Integer') : 0;
 +    $rowCount = isset($_REQUEST['iDisplayLength']) ? CRM_Utils_Type::escape($_REQUEST['iDisplayLength'], 'Integer') : 25;
 +    $sort = 'sort_name';
      $sortOrder = isset($_REQUEST['sSortDir_0']) ? CRM_Utils_Type::escape($_REQUEST['sSortDir_0'], 'String') : 'asc';
  
 -    $gid         = isset($_REQUEST['gid']) ? CRM_Utils_Type::escape($_REQUEST['gid'], 'Integer') : 0;
 -    $rgid        = isset($_REQUEST['rgid']) ? CRM_Utils_Type::escape($_REQUEST['rgid'], 'Integer') : 0;
 +    $gid = isset($_REQUEST['gid']) ? CRM_Utils_Type::escape($_REQUEST['gid'], 'Integer') : 0;
 +    $rgid = isset($_REQUEST['rgid']) ? CRM_Utils_Type::escape($_REQUEST['rgid'], 'Integer') : 0;
      $contactType = '';
      if ($rgid) {
        $contactType = CRM_Core_DAO::getFieldValue('CRM_Dedupe_DAO_RuleGroup', $rgid, 'contact_type');
      }
  
 -    $cacheKeyString   = "merge {$contactType}_{$rgid}_{$gid}";
 -    $searchRows       = array();
 +    $cacheKeyString = "merge {$contactType}_{$rgid}_{$gid}";
 +    $searchRows = array();
      $selectorElements = array('src', 'dst', 'weight', 'actions');
  
 -
      $join = "LEFT JOIN civicrm_dedupe_exception de ON ( pn.entity_id1 = de.contact_id1 AND
                                                               pn.entity_id2 = de.contact_id2 )";
      $where = "de.id IS NULL";
    }
  
    /**
 -   * Function to retrieve a PDF Page Format for the PDF Letter form
 +   * Retrieve a PDF Page Format for the PDF Letter form
     */
 -  function pdfFormat() {
 +  public function pdfFormat() {
      $formatId = CRM_Utils_Type::escape($_REQUEST['formatId'], 'Integer');
  
      $pdfFormat = CRM_Core_BAO_PdfFormat::getById($formatId);
    }
  
    /**
 -   * Function to retrieve Paper Size dimensions
 +   * Retrieve Paper Size dimensions
     */
 -  static function paperSize() {
 +  public static function paperSize() {
      $paperSizeName = CRM_Utils_Type::escape($_REQUEST['paperSizeName'], 'String');
  
      $paperSize = CRM_Core_BAO_PaperSize::getByName($paperSizeName);
      CRM_Utils_JSON::output($paperSize);
    }
  
 -  static function selectUnselectContacts() {
 -    $name         = CRM_Utils_Array::value('name', $_REQUEST);
 -    $cacheKey     = CRM_Utils_Array::value('qfKey', $_REQUEST);
 -    $state        = CRM_Utils_Array::value('state', $_REQUEST, 'checked');
 +  public static function selectUnselectContacts() {
 +    $name = CRM_Utils_Array::value('name', $_REQUEST);
 +    $cacheKey = CRM_Utils_Array::value('qfKey', $_REQUEST);
 +    $state = CRM_Utils_Array::value('state', $_REQUEST, 'checked');
      $variableType = CRM_Utils_Array::value('variableType', $_REQUEST, 'single');
  
      $actionToPerform = CRM_Utils_Array::value('action', $_REQUEST, 'select');
    }
  
    /**
 -   * @param $name
 +   * @param string $name
     *
     * @return string
     */
 -  static function _convertToId($name) {
 +  public static function _convertToId($name) {
      if (substr($name, 0, CRM_Core_Form::CB_PREFIX_LEN) == CRM_Core_Form::CB_PREFIX) {
        $cId = substr($name, CRM_Core_Form::CB_PREFIX_LEN);
      }
      return $cId;
    }
  
 -  static function getAddressDisplay() {
 +  public static function getAddressDisplay() {
      $contactId = CRM_Utils_Array::value('contact_id', $_REQUEST);
      if (!$contactId) {
        $addressVal["error_message"] = "no contact id found";
    }
  
    /**
 -   * Function to retrieve contact relationships
 +   * Retrieve contact relationships
     */
    public static function getContactRelationships() {
      $contactID = CRM_Utils_Type::escape($_GET['cid'], 'Integer');
        10 => '',
      );
  
 -    $sEcho     = CRM_Utils_Type::escape($_REQUEST['sEcho'], 'Integer');
 -    $offset    = isset($_REQUEST['iDisplayStart']) ? CRM_Utils_Type::escape($_REQUEST['iDisplayStart'], 'Integer') : 0;
 -    $rowCount  = isset($_REQUEST['iDisplayLength']) ? CRM_Utils_Type::escape($_REQUEST['iDisplayLength'], 'Integer') : 25;
 -    $sort      = isset($_REQUEST['iSortCol_0']) ? CRM_Utils_Array::value(CRM_Utils_Type::escape($_REQUEST['iSortCol_0'], 'Integer'), $sortMapper) : NULL;
 +    $sEcho = CRM_Utils_Type::escape($_REQUEST['sEcho'], 'Integer');
 +    $offset = isset($_REQUEST['iDisplayStart']) ? CRM_Utils_Type::escape($_REQUEST['iDisplayStart'], 'Integer') : 0;
 +    $rowCount = isset($_REQUEST['iDisplayLength']) ? CRM_Utils_Type::escape($_REQUEST['iDisplayLength'], 'Integer') : 25;
 +    $sort = isset($_REQUEST['iSortCol_0']) ? CRM_Utils_Array::value(CRM_Utils_Type::escape($_REQUEST['iSortCol_0'], 'Integer'), $sortMapper) : NULL;
      $sortOrder = isset($_REQUEST['sSortDir_0']) ? CRM_Utils_Type::escape($_REQUEST['sSortDir_0'], 'String') : 'asc';
  
      $params = $_POST;
index 26c79c0637533970b2be2ce6d8dfa45ac04aad91,2dada275a7fdbc5f9c333c7ba032f80b08f1f5e2..41cd1980203c3f3e9e4d6074c35a9b6f756e467c
@@@ -1,7 -1,7 +1,7 @@@
  <?php
  /*
    +--------------------------------------------------------------------+
 -  | CiviCRM version 4.5                                                |
 +  | CiviCRM version 4.6                                                |
    +--------------------------------------------------------------------+
    | Copyright CiviCRM LLC (c) 2004-2014                                |
    +--------------------------------------------------------------------+
@@@ -40,7 -40,8 +40,7 @@@
  class CRM_Contribute_Form_Contribution_Main extends CRM_Contribute_Form_ContributionBase {
  
    /**
 -   *Define default MembershipType Id
 -   *
 +   * Define default MembershipType Id
     */
    public $_defaultMemTypeId;
  
  
    public $_useForMember;
  
 -  protected $_ppType;
 +  /**
 +   * Array of payment related fields to potentially display on this form (generally credit card or debit card fields). This is rendered via billingBlock.tpl
 +   * @var array
 +   */
 +  public $_paymentFields = array();
 +
 +  protected $_paymentProcessorID;
    protected $_snippet;
  
    /**
 -   * Function to set variables up before form is built
 +   * Set variables up before form is built
     *
     * @return void
 -   * @access public
     */
    public function preProcess() {
      parent::preProcess();
@@@ -81,7 -77,7 +81,7 @@@
  
      // make sure we have right permission to edit this user
      $csContactID = $this->getContactID();
 -    $reset       = CRM_Utils_Request::retrieve('reset', 'Boolean', CRM_Core_DAO::$_nullObject);
 +    $reset = CRM_Utils_Request::retrieve('reset', 'Boolean', CRM_Core_DAO::$_nullObject);
      $mainDisplay = CRM_Utils_Request::retrieve('_qf_Main_display', 'Boolean', CRM_Core_DAO::$_nullObject);
  
      if ($reset) {
      }
  
      //CRM-5001
-     if (!empty($this->_values['is_for_organization'])) {
+     //CRM-15787
+     $member = CRM_Member_BAO_Membership::getMembershipBlock($this->_id);
+     if (!empty($this->_values['is_for_organization']) && empty($member['is_active'])) {
        $msg = ts('Mixed profile not allowed for on behalf of registration/sign up.');
        $ufJoinParams = array(
          'module' => 'onBehalf',
        if ($onBehalfProfileID) {
          $onBehalfProfile = CRM_Core_BAO_UFGroup::profileGroups($onBehalfProfileID);
          foreach (array(
 -            'Individual', 'Organization', 'Household') as $contactType) {
 +                   'Individual',
 +                   'Organization',
 +                   'Household'
 +                 ) as $contactType) {
            if (in_array($contactType, $onBehalfProfile) &&
              (in_array('Membership', $onBehalfProfile) ||
                in_array('Contribution', $onBehalfProfile)
        if ($postID = CRM_Utils_Array::value('custom_post_id', $this->_values)) {
          $postProfile = CRM_Core_BAO_UFGroup::profileGroups($postID);
          foreach (array(
 -            'Individual', 'Organization', 'Household') as $contactType) {
 +                   'Individual',
 +                   'Organization',
 +                   'Household'
 +                 ) as $contactType) {
            if (in_array($contactType, $postProfile) &&
              (in_array('Membership', $postProfile) ||
                in_array('Contribution', $postProfile)
    }
  
    /**
 -   * set the default values
 +   * Set the default values
     *
     * @return void
 -   * @access public
     */
    /**
 -   *
     */
 -  function setDefaultValues() {
 +  public function setDefaultValues() {
      // check if the user is registered and we have a contact ID
      $contactID = $this->getContactID();
  
  
      // to process Custom data that are appended to URL
      $getDefaults = CRM_Core_BAO_CustomGroup::extractGetParams($this, "'Contact', 'Individual', 'Contribution'");
 -    if (!empty($getDefaults)) {
 -      $this->_defaults = array_merge($this->_defaults, $getDefaults);
 -    }
 +    $this->_defaults = array_merge($this->_defaults, $getDefaults);
  
      $config = CRM_Core_Config::singleton();
      // set default country from config if no country set
    }
  
    /**
 -   * Function to build the form
 +   * Build the form object
     *
     * @return void
 -   * @access public
     */
    public function buildQuickForm() {
      // build profiles first so that we can determine address fields etc
      }
  
      // Build payment processor form
 -    if ($this->_ppType && empty($_GET['onbehalf'])) {
 +    if (empty($_GET['onbehalf'])) {
        CRM_Core_Payment_ProcessorForm::buildQuickForm($this);
        // Return if we are in an ajax callback
        if ($this->_snippet) {
      );
      $this->addRule("email-{$this->_bltID}", ts('Email is not valid.'), 'email');
      $pps = array();
 +    //@todo - this should be replaced by a check as to whether billing fields are set
      $onlinePaymentProcessorEnabled = FALSE;
      if (!empty($this->_paymentProcessors)) {
        foreach ($this->_paymentProcessors as $key => $name) {
 -        if($name['billing_mode'] == 1) {
 +        if ($name['billing_mode'] == 1) {
            $onlinePaymentProcessorEnabled = TRUE;
          }
          $pps[$key] = $name['name'];
      }
  
      $contactID = $this->getContactID();
 -    if($this->getContactID() === '0') {
 +    if ($this->getContactID() === '0') {
        $this->addCidZeroOptions($onlinePaymentProcessorEnabled);
      }
      //build pledge block.
        $this->set('priceSetId', $this->_priceSetId);
        CRM_Price_BAO_PriceSet::buildPriceSet($this);
        if ($this->_values['is_monetary'] &&
 -        $this->_values['is_recur'] && empty($this->_values['pledge_id'])) {
 +        $this->_values['is_recur'] && empty($this->_values['pledge_id'])
 +      ) {
          self::buildRecur($this);
        }
      }
        CRM_Contact_Form_ProfileContact::buildQuickForm($this);
      }
  
 -
      //don't build pledge block when mid is passed
      if (!$this->_mid) {
        $config = CRM_Core_Config::singleton();
      }
  
      //to create an cms user
 -    if (!$this->_userID) {
 +    if (!$this->_contactID) {
        $createCMSUser = FALSE;
  
        if ($this->_values['custom_pre_id']) {
          $pcp_supporter_text = ts('This contribution is being made thanks to the effort of <strong>%1</strong>, who supports our campaign.', array(1 => $pcpSupporter));
          // Only tell people that can also create a PCP if the contribution page has a non-empty value in the "Create Personal Campaign Page link" field.
          $text = CRM_PCP_BAO_PCP::getPcpBlockStatus($this->_id, 'contribute');
 -        if(!empty($text)) {
 +        if (!empty($text)) {
            $pcp_supporter_text .= ts("You can support it as well - once you complete the donation, you will be able to create your own Personal Campaign Page!");
          }
          $this->assign('pcpSupporterText', $pcp_supporter_text);
            array('onclick' => "showHideByValue('pcp_display_in_roll','','nameID|nickID|personalNoteID','block','radio',false); pcpAnonymous( );")
          );
          $extraOption = array('onclick' => "return pcpAnonymous( );");
 -        $elements    = array();
 -        $elements[]  = &$this->createElement('radio', NULL, '', ts('Include my name and message'), 0, $extraOption);
 -        $elements[]  = &$this->createElement('radio', NULL, '', ts('List my contribution anonymously'), 1, $extraOption);
 +        $elements = array();
 +        $elements[] = &$this->createElement('radio', NULL, '', ts('Include my name and message'), 0, $extraOption);
 +        $elements[] = &$this->createElement('radio', NULL, '', ts('List my contribution anonymously'), 1, $extraOption);
          $this->addGroup($elements, 'pcp_is_anonymous', NULL, '&nbsp;&nbsp;&nbsp;');
          $this->setDefaults(array('pcp_display_in_roll' => 1));
          $this->setDefaults(array('pcp_is_anonymous' => 1));
      //when multiple payment processor as the user
      //can toggle with payment processor selection
      $billingModePaymentProcessors = 0;
 -    if ( !empty( $this->_paymentProcessors ) ) {
 +    if (!empty($this->_paymentProcessors)) {
        foreach ($this->_paymentProcessors as $key => $values) {
          if ($values['billing_mode'] == CRM_Core_Payment::BILLING_MODE_BUTTON) {
            $billingModePaymentProcessors++;
  
      if ($billingModePaymentProcessors && count($this->_paymentProcessors) == $billingModePaymentProcessors) {
        $allAreBillingModeProcessors = TRUE;
 -    } else {
 +    }
 +    else {
        $allAreBillingModeProcessors = FALSE;
      }
  
    }
  
    /**
 -   * build elements to enable pay on behalf of an organization.
 -   *
 -   * @access public
 +   * Build elements to enable pay on behalf of an organization.
     */
 -  function buildOnBehalfOrganization() {
 +  public function buildOnBehalfOrganization() {
      if ($this->_membershipContactID) {
        $entityBlock = array('contact_id' => $this->_membershipContactID);
        CRM_Core_BAO_Location::getValues($entityBlock, $this->_defaults);
    }
  
    /**
 -   * build elements to collect information for recurring contributions
 +   * Build elements to collect information for recurring contributions
 +   *
     *
 -   * @access public
 +   * @param CRM_Core_Form $form
     */
    public static function buildRecur(&$form) {
      $attributes = CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_ContributionRecur');
      $unitVals = explode(CRM_Core_DAO::VALUE_SEPARATOR, $frUnits);
  
      // CRM 10860, display text instead of a dropdown if there's only 1 frequency unit
 -    if(sizeof($unitVals) == 1) {
 -      $form->assign('one_frequency_unit', true);
 +    if (sizeof($unitVals) == 1) {
 +      $form->assign('one_frequency_unit', TRUE);
        $unit = $unitVals[0];
        $form->add('hidden', 'frequency_unit', $unit);
        if (!empty($form->_values['is_recur_interval']) || $className == 'CRM_Contribute_Form_Contribution') {
          $unit .= "(s)";
        }
        $form->assign('frequency_unit', $unit);
 -    } else {
 -      $form->assign('one_frequency_unit', false);
 +    }
 +    else {
 +      $form->assign('one_frequency_unit', FALSE);
        $units = array();
        $frequencyUnits = CRM_Core_OptionGroup::values('recur_frequency_units');
        foreach ($unitVals as $key => $val) {
        $frequencyUnit = &$form->add('select', 'frequency_unit', NULL, $units);
      }
  
 -
      // FIXME: Ideally we should freeze select box if there is only
      // one option but looks there is some problem /w QF freeze.
      //if ( count( $units ) == 1 ) {
    }
  
    /**
 -   * global form rule
 +   * Global form rule
     *
 -   * @param array $fields the input form values
 -   * @param array $files the uploaded files if any
 +   * @param array $fields
 +   *   The input form values.
 +   * @param array $files
 +   *   The uploaded files if any.
     * @param $self
     *
 -   * @internal param array $options additional user data
     *
 -   * @return true if no errors, else array of errors
 -   * @access public
 +   * @return bool|array
 +   *   true if no errors, else array of errors
     * @static
     */
 -  static function formRule($fields, $files, $self) {
 +  public static function formRule($fields, $files, $self) {
      $errors = array();
      $amount = self::computeAmount($fields, $self);
  
          $self->_useForMember
        )
      ) {
 -      $lifeMember = CRM_Member_BAO_Membership::getAllContactMembership($self->_userID, FALSE, TRUE);
 +      $lifeMember = CRM_Member_BAO_Membership::getAllContactMembership($self->_membershipContactID, FALSE, TRUE);
  
        $membershipOrgDetails = CRM_Member_BAO_MembershipType::getMembershipTypeOrganization();
  
  
          if ($self->_quickConfig && ($priceField->name == 'contribution_amount' || $priceField->name == 'membership_amount')) {
            $previousId = $priceField->id;
 -          if ($priceField->name == 'membership_amount' && !$priceField->is_active ) {
 +          if ($priceField->name == 'membership_amount' && !$priceField->is_active) {
              $membershipIsActive = FALSE;
            }
          }
          if ($priceField->name == 'other_amount') {
            if ($self->_quickConfig && empty($fields["price_{$priceField->id}"]) &&
 -            array_key_exists("price_{$previousId}", $fields) && isset($fields["price_{$previousId}"]) && $self->_values['fee'][$previousId]['name'] == 'contribution_amount' && empty($fields["price_{$previousId}"])) {
 +            array_key_exists("price_{$previousId}", $fields) && isset($fields["price_{$previousId}"]) && $self->_values['fee'][$previousId]['name'] == 'contribution_amount' && empty($fields["price_{$previousId}"])
 +          ) {
              $otherAmount = $priceField->id;
            }
            elseif (!empty($fields["price_{$priceField->id}"])) {
 -            $otherAmountVal = $fields["price_{$priceField->id}"];
 -            $min            = CRM_Utils_Array::value('min_amount', $self->_values);
 -            $max            = CRM_Utils_Array::value('max_amount', $self->_values);
 +            $otherAmountVal = CRM_Utils_Rule::cleanMoney($fields["price_{$priceField->id}"]);
 +            $min = CRM_Utils_Array::value('min_amount', $self->_values);
 +            $max = CRM_Utils_Array::value('max_amount', $self->_values);
              if ($min && $otherAmountVal < $min) {
                $errors["price_{$priceField->id}"] = ts('Contribution amount must be at least %1',
 -                                                   array(1 => $min)
 +                array(1 => $min)
                );
              }
              if ($max && $otherAmountVal > $max) {
                $errors["price_{$priceField->id}"] = ts('Contribution amount cannot be more than %1.',
 -                                                   array(1 => $max)
 +                array(1 => $max)
                );
              }
            }
          }
          if (!empty($fields["price_{$priceField->id}"]) || ($previousId == $priceField->id && isset($fields["price_{$previousId}"])
 -            && empty($fields["price_{$previousId}"]))) {
 +            && empty($fields["price_{$previousId}"]))
 +        ) {
            $check[] = $priceField->id;
          }
        }
        if ($membershipIsActive) {
          $is_test = $self->_mode != 'live' ? 1 : 0;
          $memContactID = $self->_membershipContactID;
 -       
 -        // For anonymous user check using dedupe rule 
 +
 +        // For anonymous user check using dedupe rule
          // if user has Cancelled Membership
          if (!$memContactID) {
            $dedupeParams = CRM_Dedupe_Finder::formatParams($fields, 'Individual');
          $currentMemberships = CRM_Member_BAO_Membership::getContactsCancelledMembership($memContactID,
            $is_test
          );
 -        
 +
          $errorText = 'Your %1 membership was previously cancelled and can not be renewed online. Please contact the site administrator for assistance.';
          foreach ($self->_values['fee'] as $fieldKey => $fieldValue) {
            if ($fieldValue['html_type'] != 'Text' && CRM_Utils_Array::value('price_' . $fieldKey, $fields)) {
              if (!is_array($fields['price_' . $fieldKey])) {
 -              if (array_key_exists('membership_type_id', $fieldValue['options'][$fields['price_' . $fieldKey]]) 
 -                && in_array($fieldValue['options'][$fields['price_' . $fieldKey]]['membership_type_id'], $currentMemberships)) {
 +              if (array_key_exists('membership_type_id', $fieldValue['options'][$fields['price_' . $fieldKey]])
 +                && in_array($fieldValue['options'][$fields['price_' . $fieldKey]]['membership_type_id'], $currentMemberships)
 +              ) {
                  $errors['price_' . $fieldKey] = ts($errorText, array(1 => CRM_Member_PseudoConstant::membershipType($fieldValue['options'][$fields['price_' . $fieldKey]]['membership_type_id'])));
                }
              }
              else {
                foreach ($fields['price_' . $fieldKey] as $key => $ignore) {
 -                if (array_key_exists('membership_type_id', $fieldValue['options'][$key]) 
 -                  && in_array($fieldValue['options'][$key]['membership_type_id'], $currentMemberships)) {
 +                if (array_key_exists('membership_type_id', $fieldValue['options'][$key])
 +                  && in_array($fieldValue['options'][$key]['membership_type_id'], $currentMemberships)
 +                ) {
                    $errors['price_' . $fieldKey] = ts($errorText, array(1 => CRM_Member_PseudoConstant::membershipType($fieldValue['options'][$key]['membership_type_id'])));
                  }
                }
            }
          }
        }
 - 
 +
        // CRM-12233
        if ($membershipIsActive && !$self->_membershipBlock['is_required']
 -        && $self->_values['amount_block_is_active']) {
 +        && $self->_values['amount_block_is_active']
 +      ) {
          $membershipFieldId = $contributionFieldId = $errorKey = $otherFieldId = NULL;
          foreach ($self->_values['fee'] as $fieldKey => $fieldValue) {
            // if 'No thank you' membership is selected then set $membershipFieldId
            $errors['_qf_default'] = ts('Select at least one option from Contribution(s).');
          }
        }
 -      if($otherAmount && !empty($check)) {
 +      if ($otherAmount && !empty($check)) {
          $errors["price_{$otherAmount}"] = ts('Amount is required field.');
        }
  
      }
  
      if (isset($fields['selectProduct']) &&
 -      $fields['selectProduct'] != 'no_thanks') {
 +      $fields['selectProduct'] != 'no_thanks'
 +    ) {
        $productDAO = new CRM_Contribute_DAO_Product();
        $productDAO->id = $fields['selectProduct'];
        $productDAO->find(TRUE);
      }
  
      if (!empty($fields['is_recur']) &&
 -      CRM_Utils_Array::value('payment_processor', $fields) == 0) {
 +      CRM_Utils_Array::value('payment_processor', $fields) == 0
 +    ) {
        $errors['_qf_default'] = ts('You cannot set up a recurring contribution if you are not paying online by credit card.');
      }
  
      }
  
      // also return if paylater mode
 -    if (CRM_Utils_Array::value('payment_processor', $fields) == 0) {
 +    if (CRM_Utils_Array::value('payment_processor', $fields) == 0 && $self->_isBillingAddressRequiredForPayLater == 0) {
        return empty($errors) ? TRUE : $errors;
      }
  
          $customizedValue = CRM_Core_OptionGroup::getValue($greeting, 'Customized', 'name');
          if ($customizedValue == $greetingType && empty($fielse[$greeting . '_custom'])) {
            $errors[$greeting . '_custom'] = ts('Custom %1 is a required field if %1 is of type Customized.',
 -                                           array(1 => ucwords(str_replace('_', " ", $greeting)))
 +            array(1 => ucwords(str_replace('_', " ", $greeting)))
            );
          }
        }
    }
  
    /**
 -   * @param $params
 -   * @param $form
 +   * @param array $params
 +   * @param CRM_Core_Form $form
     *
     * @return int|mixed|null|string
     */
    }
  
    /**
 -   * Function to process the form
 +   * Process the form submission
     *
 -   * @access public
     *
     * @return void
     */
      if (($this->_values['is_pay_later'] &&
          empty($this->_paymentProcessor) &&
          !array_key_exists('hidden_processor', $params)) ||
 -      (!empty($params['payment_processor']) && $params['payment_processor'] == 0)) {
 +      (!empty($params['payment_processor']) && $params['payment_processor'] == 0)
 +    ) {
        $params['is_pay_later'] = 1;
      }
      else {
          $params['amount'] = $memFee ? $memFee : 0;
        }
      }
 -
      //If the membership & contribution is used in contribution page & not separate payment
      $fieldId = $memPresent = $membershipLabel = $fieldOption = $is_quick_config = NULL;
      $proceFieldAmount = 0;
        $is_quick_config = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config');
        if ($is_quick_config) {
          foreach ($this->_priceSet['fields'] as $fieldKey => $fieldVal) {
 -          if ($fieldVal['name'] == 'membership_amount' && !empty($params['price_' . $fieldKey ])) {
 -            $fieldId     = $fieldVal['id'];
 +          if ($fieldVal['name'] == 'membership_amount' && !empty($params['price_' . $fieldKey])) {
 +            $fieldId = $fieldVal['id'];
              $fieldOption = $params['price_' . $fieldId];
              $proceFieldAmount += $fieldVal['options'][$this->_submitValues['price_' . $fieldId]]['amount'];
 -            $memPresent  = TRUE;
 +            $memPresent = TRUE;
            }
            else {
              if (!empty($params['price_' . $fieldKey]) && $memPresent && ($fieldVal['name'] == 'other_amount' || $fieldVal['name'] == 'contribution_amount')) {
  
      if ($priceSetId = CRM_Utils_Array::value('priceSetId', $params)) {
        $lineItem = array();
 -      $is_quick_config = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config' );
 -      if ( $is_quick_config ) {
 -        foreach ( $this->_values['fee'] as $key => & $val ) {
 -          if ( $val['name'] == 'other_amount' && $val['html_type'] == 'Text' && array_key_exists( 'price_'.$key, $params ) && $params['price_'.$key] != 0 ) {
 -            foreach ( $val['options'] as $optionKey => & $options ) {
 -              $options['amount'] = CRM_Utils_Array::value( 'price_'.$key, $params );
 -              break;
 +      $is_quick_config = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
 +      if ($is_quick_config) {
 +        foreach ($this->_values['fee'] as $key => & $val) {
 +          if ($val['name'] == 'other_amount' && $val['html_type'] == 'Text' && array_key_exists('price_' . $key, $params)) {
 +            $params['price_' . $key] = CRM_Utils_Rule::cleanMoney($params['price_' . $key]); //Clean out any currency symbols
 +            if ($params['price_' . $key] != 0) {
 +              foreach ($val['options'] as $optionKey => & $options) {
 +                $options['amount'] = CRM_Utils_Array::value('price_' . $key, $params);
 +                break;
 +              }
              }
 -            $params['price_'.$key] = 1;
 +            $params['price_' . $key] = 1;
              break;
            }
          }
        }
 -
        $component = '';
        if ($this->_membershipBlock) {
          $component = 'membership';
        }
 +
        CRM_Price_BAO_PriceSet::processAmount($this->_values['fee'], $params, $lineItem[$priceSetId], $component);
 +      if ($params['tax_amount']) {
 +        $this->set('tax_amount', $params['tax_amount']);
 +      }
  
        if ($proceFieldAmount) {
 -        $lineItem[$params['priceSetId']][$fieldOption]['line_total'] = $proceFieldAmount;
          $lineItem[$params['priceSetId']][$fieldOption]['unit_price'] = $proceFieldAmount;
 +        $lineItem[$params['priceSetId']][$fieldOption]['line_total'] = $proceFieldAmount;
 +        if (isset($lineItem[$params['priceSetId']][$fieldOption]['tax_amount'])) {
 +          $proceFieldAmount += $lineItem[$params['priceSetId']][$fieldOption]['tax_amount'];
 +        }
          if (!$this->_membershipBlock['is_separate_payment']) {
            $params['amount'] = $proceFieldAmount; //require when separate membership not used
          }
  
      if ($this->_membershipBlock['is_separate_payment'] && !empty($params['separate_amount'])) {
        $this->set('amount', $params['separate_amount']);
 -    } else {
 +    }
 +    else {
        $this->set('amount', $params['amount']);
      }
  
          $buttonName = $this->controller->getButtonName();
          if (in_array($buttonName,
              array($this->_expressButtonName, $this->_expressButtonName . '_x', $this->_expressButtonName . '_y')
 -          ) && empty($params['is_pay_later'])) {
 +          ) && empty($params['is_pay_later'])
 +        ) {
            $this->set('contributeMode', 'express');
  
 -          $donateURL           = CRM_Utils_System::url('civicrm/contribute', '_qf_Contribute_display=1');
 +          $donateURL = CRM_Utils_System::url('civicrm/contribute', '_qf_Contribute_display=1');
            $params['cancelURL'] = CRM_Utils_System::url('civicrm/contribute/transact', "_qf_Main_display=1&qfKey={$params['qfKey']}", TRUE, NULL, FALSE);
            $params['returnURL'] = CRM_Utils_System::url('civicrm/contribute/transact', "_qf_Confirm_display=1&rfp=1&qfKey={$params['qfKey']}", TRUE, NULL, FALSE);
            $params['invoiceID'] = $invoiceID;
        // redirect to thank you page
        CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contribute/transact', "_qf_ThankYou_display=1&qfKey=$qfKey", TRUE, NULL, FALSE));
      }
 +
    }
  
    /**
     * Handle Payment Processor switching
     * For contribution and event registration forms
 +   * @param CRM_Contribute_Form_Contribution_Main|CRM_Event_Form_Registration_Register $form
 +   * @param bool $noFees
     */
 -  static function preProcessPaymentOptions(&$form, $noFees = FALSE) {
 +  public static function preProcessPaymentOptions(&$form, $noFees = FALSE) {
      $form->_snippet = CRM_Utils_Array::value('snippet', $_GET);
  
      $form->_paymentProcessors = $noFees ? array() : $form->get('paymentProcessors');
 -    $form->_ppType = NULL;
 +    $form->_paymentProcessorID = NULL;
      if ($form->_paymentProcessors) {
        // Fetch type during ajax request
        if (isset($_GET['type']) && $form->_snippet) {
 -        $form->_ppType = $_GET['type'];
 +        $form->_paymentProcessorID = CRM_Utils_Request::retrieve('type', 'Integer', CRM_Core_DAO::$_nullObject, FALSE, 0);
        }
        // Remember type during form post
        elseif (!empty($form->_submitValues)) {
 -        $form->_ppType = CRM_Utils_Array::value('payment_processor', $form->_submitValues);
 -        $form->_paymentProcessor = CRM_Utils_Array::value($form->_ppType, $form->_paymentProcessors);
 -        $form->set('type', $form->_ppType);
 +        $form->_paymentProcessorID = CRM_Utils_Array::value('payment_processor', $form->_submitValues);
 +        $form->_paymentProcessor = CRM_Utils_Array::value($form->_paymentProcessorID, $form->_paymentProcessors);
 +        $form->set('type', $form->_paymentProcessorID);
          $form->set('mode', $form->_mode);
          $form->set('paymentProcessor', $form->_paymentProcessor);
        }
        else {
          foreach ($form->_paymentProcessors as $values) {
            if (!empty($values['is_default']) || count($form->_paymentProcessors) == 1) {
 -            $form->_ppType = $values['id'];
 +            $form->_paymentProcessorID = $values['id'];
              break;
            }
          }
        }
 -      if ($form->_ppType) {
 +      if ($form->_paymentProcessorID) {
          CRM_Core_Payment_ProcessorForm::preProcess($form);
        }
 +      else {
 +        $form->_paymentProcessor = array();
 +      }
  
        //get payPal express id and make it available to template
        foreach ($form->_paymentProcessors as $ppId => $values) {
            ->addScript('CRM.config.creditCardTypes = ' . json_encode($creditCardTypes) . ';');
        }
      }
 -    $form->assign('ppType', $form->_ppType);
 +    $form->assign('paymentProcessorID', $form->_paymentProcessorID);
    }
  }
 -
index 60a074e41b43473dadf36aeb8f8baee7cc6d090b,b20f5f2f5f5103808bef2a03b2cadf959271e8eb..d62d54edda1ee8c76290b5f2da222737d6fda194
@@@ -1,7 -1,7 +1,7 @@@
  <?php
  /*
   +--------------------------------------------------------------------+
 - | CiviCRM version 4.5                                                |
 + | CiviCRM version 4.6                                                |
   +--------------------------------------------------------------------+
   | Copyright CiviCRM LLC (c) 2004-2014                                |
   +--------------------------------------------------------------------+
  class CRM_Contribute_Form_ContributionPage_Settings extends CRM_Contribute_Form_ContributionPage {
  
    /**
 -   * Function to set variables up before form is built
 +   * Set variables up before form is built
     *
     * @return void
 -   * @access public
     */
    public function preProcess() {
      parent::preProcess();
    }
  
    /**
 -   * This function sets the default values for the form. Note that in edit/view mode
 +   * Set default values for the form. Note that in edit/view mode
     * the default values are retrieved from the database
     *
 -   * @access public
     *
     * @return void
     */
 -  function setDefaultValues() {
 +  public function setDefaultValues() {
      $defaults = parent::setDefaultValues();
      $soft_credit_types = CRM_Core_OptionGroup::values('soft_credit_type', TRUE, FALSE, FALSE, NULL, 'name');
  
@@@ -59,7 -61,9 +59,7 @@@
          $this->_id,
          'title'
        );
 -      CRM_Utils_System::setTitle(ts('Title and Settings (%1)',
 -          array(1 => $title)
 -        ));
 +      CRM_Utils_System::setTitle(ts('Title and Settings') . " ($title)");
  
        $ufJoinParams = array(
          'module' => 'OnBehalf',
@@@ -89,7 -93,7 +89,7 @@@
          }
          $defaults['soft_credit_types'] = array(
            CRM_Utils_Array::value('in_honor_of', $soft_credit_types),
 -          CRM_Utils_Array::value('in_memory_of', $soft_credit_types)
 +          CRM_Utils_Array::value('in_memory_of', $soft_credit_types),
          );
        }
      }
        }
        $defaults['soft_credit_types'] = array(
          CRM_Utils_Array::value('in_honor_of', $soft_credit_types),
 -        CRM_Utils_Array::value('in_memory_of', $soft_credit_types)
 +        CRM_Utils_Array::value('in_memory_of', $soft_credit_types),
        );
      }
  
    }
  
    /**
 -   * Function to actually build the form
 +   * Build the form object
     *
     * @return void
 -   * @access public
     */
    public function buildQuickForm() {
  
      // is on behalf of an organization ?
      $this->addElement('checkbox', 'is_organization', ts('Allow individuals to contribute and / or signup for membership on behalf of an organization?'), NULL, array('onclick' => "showHideByValue('is_organization',true,'for_org_text','table-row','radio',false);showHideByValue('is_organization',true,'for_org_option','table-row','radio',false);"));
  
-     $allowCoreTypes = array_merge(array(
-         'Contact',
-         'Organization'
-       ), CRM_Contact_BAO_ContactType::subTypes('Organization'));
-     $allowSubTypes = array();
-     $entities = array(
-       array(
-         'entity_name' => 'contact_1',
-         'entity_type' => 'OrganizationModel',
-       ),
+     //CRM-15787 - If applicable, register 'membership_1'
+     $member = CRM_Member_BAO_Membership::getMembershipBlock($this->_id);
+     $coreTypes = array('Contact', 'Organization');
+     $entities[] = array(
+       'entity_name' => array ('contact_1'),
+       'entity_type' => 'OrganizationModel',
      );
  
 -    $allowCoreTypes = array_merge($coreTypes, CRM_Contact_BAO_ContactType::subTypes('Organization'));
+     if ($member && $member['is_active']) {
+       $coreTypes[] = 'Membership';
+       $entities[] = array(
+         'entity_name' => array ('membership_1'),
+         'entity_type' => 'MembershipModel',
+       );
+     }
++    
++    $allowCoreTypes = array_merge($coreTypes, 
++      CRM_Contact_BAO_ContactType::subTypes('Organization'));
+     $allowSubTypes = array();
      $this->addProfileSelector('onbehalf_profile_id', ts('Organization Profile'), $allowCoreTypes, $allowSubTypes, $entities);
  
 -    $options   = array();
 +    $options = array();
      $options[] = $this->createElement('radio', NULL, NULL, ts('Optional'), 1);
      $options[] = $this->createElement('radio', NULL, NULL, ts('Required'), 2);
      $this->addGroup($options, 'is_for_organization', ts(''));
        'entity' => 'ContributionSoft',
        'field' => 'soft_credit_type_id',
        'multiple' => TRUE,
 -      'class' => 'huge'
 +      'class' => 'huge',
      ));
  
      $entities = array(
        ),
      );
  
 -    $allowCoreTypes = array_merge(array('Contact', 'Individual', 'Organization', 'Household'), CRM_Contact_BAO_ContactType::subTypes('Individual'));
 +    $allowCoreTypes = array_merge(array(
 +        'Contact',
 +        'Individual',
 +        'Organization',
 +        'Household'
 +      ), CRM_Contact_BAO_ContactType::subTypes('Individual'));
      $allowSubTypes = array();
  
      $this->addProfileSelector('honoree_profile', ts('Honoree Profile'), $allowCoreTypes, $allowSubTypes, $entities);
    }
  
    /**
 -   * global validation rules for the form
 +   * Global validation rules for the form
     *
 -   * @param array $values posted values of the form
 +   * @param array $values
 +   *   Posted values of the form.
     *
     * @param $files
     * @param $self
     *
 -   * @return array list of errors to be posted back to the form
 +   * @return array
 +   *   list of errors to be posted back to the form
     * @static
 -   * @access public
     */
 -  static function formRule($values, $files, $self) {
 +  public static function formRule($values, $files, $self) {
      $errors = array();
      $contributionPageId = $self->_id;
      //CRM-4286
  
      // ensure on-behalf-of profile meets minimum requirements
      if (!empty($values['is_organization'])) {
 -      if (empty($values['onbehalf_profile_id']) ) {
 +      if (empty($values['onbehalf_profile_id'])) {
          $errors['onbehalf_profile_id'] = ts('Please select a profile to collect organization information on this contribution page.');
        }
        else {
  
        list($contributionProfiles['custom_pre_id'],
          $contributionProfiles['custom_post_id']
 -      ) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams);
 +        ) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams);
  
        $conProfileType = NULL;
        if ($contributionProfiles['custom_pre_id']) {
        if ($contributionProfiles['custom_post_id']) {
          $postProfileType = CRM_Core_BAO_UFField::getProfileType($contributionProfiles['custom_post_id']);
          if ($postProfileType == 'Membership') {
 -          $conProfileType  = empty($conProfileType) ? "'Includes Profile (bottom of page)'" : "{$conProfileType} and 'Includes Profile (bottom of page)'";
 +          $conProfileType = empty($conProfileType) ? "'Includes Profile (bottom of page)'" : "{$conProfileType} and 'Includes Profile (bottom of page)'";
          }
        }
        if (!empty($conProfileType)) {
     * Process the form
     *
     * @return void
 -   * @access public
     */
    public function postProcess() {
      // get the submitted form values.
            'module' => 'soft_credit',
            'entity_table' => 'civicrm_contribution_page',
            'entity_id' => $dao->id,
 -        )
 +        ),
      );
  
 -
      foreach ($ufJoinParams as $index => $ufJoinParam) {
        if (!empty($params[$index])) {
 -          $ufJoinParam['weight'] = 1;
 -          if ($index == 'honor_block_is_active') {
 -            $ufJoinParam['is_active'] = 1;
 -            $ufJoinParam['module'] = 'soft_credit';
 -            $ufJoinParam['uf_group_id'] = $params['honoree_profile'];
 -            $ufJoinParam['module_data'] = $sctJSON;
 -          }
 -          else {
 -            // first delete all past entries
 -            CRM_Core_BAO_UFJoin::deleteAll($ufJoinParam);
 -            $ufJoinParam['uf_group_id'] = $params[$index];
 -          }
 -            CRM_Core_BAO_UFJoin::create($ufJoinParam);
 +        $ufJoinParam['weight'] = 1;
 +        if ($index == 'honor_block_is_active') {
 +          $ufJoinParam['is_active'] = 1;
 +          $ufJoinParam['module'] = 'soft_credit';
 +          $ufJoinParam['uf_group_id'] = $params['honoree_profile'];
 +          $ufJoinParam['module_data'] = $sctJSON;
 +        }
 +        else {
 +          // first delete all past entries
 +          CRM_Core_BAO_UFJoin::deleteAll($ufJoinParam);
 +          $ufJoinParam['uf_group_id'] = $params[$index];
          }
 +        CRM_Core_BAO_UFJoin::create($ufJoinParam);
 +      }
        elseif ($index == 'honor_block_is_active') {
          //On subsequent honor_block_is_active uncheck, disable(don't delete)
          //that particular honoree profile entry in UFjoin table, CRM-13981
          $url = 'civicrm/admin/contribute';
          $urlParams = 'reset=1';
          CRM_Core_Session::setStatus(ts("'%1' information has been saved.",
 -            array(1 => $this->getTitle())
 -          ), ts('Saved'), 'success');
 +          array(1 => $this->getTitle())
 +        ), ts('Saved'), 'success');
        }
  
        CRM_Utils_System::redirect(CRM_Utils_System::url($url, $urlParams));
     * Return a descriptive name for the page, used in wizard header
     *
     * @return string
 -   * @access public
     */
    public function getTitle() {
      return ts('Title and Settings');
    }
  }
 -