function preProcess()
 {
     $cid = CRM_Utils_Request::retrieve('cid', 'Positive', $this, FALSE);
     $oid = CRM_Utils_Request::retrieve('oid', 'Positive', $this, FALSE);
     if ($oid) {
         $this->_id = CRM_Utils_Request::retrieve('oid', 'Positive', $this, FALSE);
     } else {
         $this->assign('hide_contact', TRUE);
         $this->_id = $cid;
     }
     if (!CRM_Utils_Rule::positiveInteger($this->_id)) {
         CRM_Core_Error::fatal('We need a valid discount ID for view');
     }
     $this->assign('id', $this->_id);
     $defaults = array();
     $params = array('id' => $this->_id);
     require_once 'CRM/CiviDiscount/BAO/Item.php';
     CRM_CiviDiscount_BAO_Item::retrieve($params, $defaults);
     require_once 'CRM/CiviDiscount/BAO/Track.php';
     if ($cid) {
         $rows = CRM_CiviDiscount_BAO_Track::getUsageByContact($this->_id);
     } else {
         $rows = CRM_CiviDiscount_BAO_Track::getUsageByOrg($this->_id);
     }
     $this->assign('rows', $rows);
     $this->assign('code_details', $defaults);
     $this->ajaxResponse['tabCount'] = count($rows);
     if (!empty($defaults['code'])) {
         CRM_Utils_System::setTitle($defaults['code']);
     }
 }
 /**
  * Checks wether a contact is a member of a group
  *
  * This function is a copy of CRM_Contact_BAO_GroupContact::isContactInGroup but with
  * a change so that the group contact cache won't be rebuild. Which somehow resulted
  * in a deadlock
  *
  * @param $contact_id
  * @param $group_id
  * @return bool
  */
 public static function isContactInGroup($contact_id, $group_id)
 {
     if (!CRM_Utils_Rule::positiveInteger($contact_id) || !CRM_Utils_Rule::positiveInteger($group_id)) {
         return FALSE;
     }
     $params = array(array('group', 'IN', array($group_id => 1), 0, 0), array('contact_id', '=', $contact_id, 0, 0));
     list($contacts, $_) = CRM_Contact_BAO_Query::apiQuery($params, array('contact_id'), null, null, 0, 1, false, false, true);
     if (!empty($contacts)) {
         return TRUE;
     }
     return FALSE;
 }
Ejemplo n.º 3
0
 /**
  * Retrieve assignee_id by activity_id
  *
  * @param int    $id  ID of the activity
  *
  * @return void
  *
  * @access public
  *
  */
 static function retrieveAssigneeIdsByActivityId($activity_id)
 {
     $assigneeArray = array();
     if (!CRM_Utils_Rule::positiveInteger($activity_id)) {
         return $assigneeArray;
     }
     $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
     $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
     $sql = "\nSELECT     contact_id\nFROM       civicrm_activity_contact\nINNER JOIN civicrm_contact ON contact_id = civicrm_contact.id\nWHERE      activity_id = %1\nAND        record_type_id = {$assigneeID}\nAND        civicrm_contact.is_deleted = 0\n";
     $assignment = CRM_Core_DAO::executeQuery($sql, array(1 => array($activity_id, 'Integer')));
     while ($assignment->fetch()) {
         $assigneeArray[] = $assignment->contact_id;
     }
     return $assigneeArray;
 }
Ejemplo n.º 4
0
 /**
  * function to retrieve id of target contact by activity_id
  *
  * @param int    $id  ID of the activity
  * 
  * @return mixed
  * 
  * @access public
  * 
  */
 static function retrieveTargetIdsByActivityId($activity_id)
 {
     $targetArray = array();
     require_once 'CRM/Utils/Rule.php';
     if (!CRM_Utils_Rule::positiveInteger($activity_id)) {
         return $targetArray;
     }
     $target =& new CRM_Activity_BAO_ActivityTarget();
     $target->activity_id = $activity_id;
     $target->find();
     $count = 1;
     while ($target->fetch()) {
         $targetArray[$count] = $target->target_contact_id;
         $count++;
     }
     return $targetArray;
 }
Ejemplo n.º 5
0
 /**
  * Retrieve assignee_id by activity_id
  *
  * @param int    $id  ID of the activity
  * 
  * @return void
  * 
  * @access public
  * 
  */
 static function retrieveAssigneeIdsByActivityId($activity_id)
 {
     $assigneeArray = array();
     require_once 'CRM/Utils/Rule.php';
     if (!CRM_Utils_Rule::positiveInteger($activity_id)) {
         return $assigneeArray;
     }
     $assignment =& new CRM_Activity_BAO_ActivityAssignment();
     $assignment->activity_id = $activity_id;
     $assignment->find();
     $count = 1;
     while ($assignment->fetch()) {
         $assigneeArray[$count] = $assignment->assignee_contact_id;
         $count++;
     }
     return $assigneeArray;
 }
 /**
  * Retrieve assignee_id by activity_id
  *
  * @param int    $id  ID of the activity
  *
  * @return void
  *
  * @access public
  *
  */
 static function retrieveAssigneeIdsByActivityId($activity_id)
 {
     $assigneeArray = array();
     if (!CRM_Utils_Rule::positiveInteger($activity_id)) {
         return $assigneeArray;
     }
     $sql = '
         SELECT assignee_contact_id
         FROM civicrm_activity_assignment
         JOIN civicrm_contact ON assignee_contact_id = civicrm_contact.id
         WHERE activity_id = %1 AND civicrm_contact.is_deleted = 0
     ';
     $assignment = CRM_Core_DAO::executeQuery($sql, array(1 => array($activity_id, 'Integer')));
     while ($assignment->fetch()) {
         $assigneeArray[] = $assignment->assignee_contact_id;
     }
     return $assigneeArray;
 }
 /**
  * function to retrieve id of target contact by activity_id
  *
  * @param int    $id  ID of the activity
  *
  * @return mixed
  *
  * @access public
  *
  */
 static function retrieveTargetIdsByActivityId($activity_id)
 {
     $targetArray = array();
     if (!CRM_Utils_Rule::positiveInteger($activity_id)) {
         return $targetArray;
     }
     $sql = '
         SELECT target_contact_id
         FROM civicrm_activity_target
         JOIN civicrm_contact ON target_contact_id = civicrm_contact.id
         WHERE activity_id = %1 AND civicrm_contact.is_deleted = 0
     ';
     $target = CRM_Core_DAO::executeQuery($sql, array(1 => array($activity_id, 'Integer')));
     while ($target->fetch()) {
         $targetArray[] = $target->target_contact_id;
     }
     return $targetArray;
 }
Ejemplo n.º 8
0
 /**
  * class constructor
  *
  * @param object  CRM_Event_Controller
  * @param int     $action
  *
  * @return object CRM_Event_StateMachine
  */
 function __construct($controller, $action = CRM_Core_Action::NONE)
 {
     parent::__construct($controller, $action);
     $id = CRM_Utils_Request::retrieve('id', 'Positive', $controller, true);
     $is_monetary = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $id, 'is_monetary');
     $pages = array('CRM_Event_Form_Registration_Register' => null);
     //handle additional participant scenario, where we need to insert participant pages on runtime
     $additionalParticipant = null;
     // check that the controller has some data, hence we dont send the form name
     // which results in an invalid argument error
     $values = $controller->exportValues();
     //first check POST value then QF
     if (isset($_POST['additional_participants']) && CRM_Utils_Rule::positiveInteger($_POST['additional_participants'])) {
         // we need to use $_POST since the QF framework has not yet been called
         // and the additional participants page is the next one, so need to set this up
         // now
         $additionalParticipant = $_POST['additional_participants'];
     } else {
         if (isset($values['additional_participants']) && CRM_Utils_Rule::positiveInteger($values['additional_participants'])) {
             $additionalParticipant = $values['additional_participants'];
         }
     }
     if ($additionalParticipant) {
         $additionalParticipant = CRM_Utils_Type::escape($additionalParticipant, 'Integer');
         $controller->set('addParticipant', $additionalParticipant);
     }
     //to add instances of Additional Participant page, only if user has entered any additional participants
     if ($additionalParticipant) {
         require_once "CRM/Event/Form/Registration/AdditionalParticipant.php";
         $extraPages =& CRM_Event_Form_Registration_AdditionalParticipant::getPages($additionalParticipant);
         $pages = array_merge($pages, $extraPages);
     }
     $additionalPages = array('CRM_Event_Form_Registration_Confirm' => null, 'CRM_Event_Form_Registration_ThankYou' => null);
     $pages = array_merge($pages, $additionalPages);
     if (!$is_monetary) {
         unset($pages['CRM_Event_Form_Registration_Confirm']);
     }
     $this->addSequentialPages($pages, $action);
 }
 function preProcess()
 {
     $this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this, FALSE, 0);
     $this->_cloneID = CRM_Utils_Request::retrieve('cloneID', 'Positive', $this, FALSE, 0);
     $this->set('BAOName', 'CRM_CiviDiscount_BAO_Item');
     parent::preProcess();
     $session = CRM_Core_Session::singleton();
     $url = CRM_Utils_System::url('civicrm/cividiscount/discount/list', 'reset=1');
     $session->pushUserContext($url);
     // check and ensure that update / delete have a valid id
     if ($this->_action & (CRM_Core_Action::UPDATE | CRM_Core_Action::DELETE)) {
         if (!CRM_Utils_Rule::positiveInteger($this->_id)) {
             CRM_Core_Error::fatal(ts('We need a valid discount ID for update and/or delete'));
         }
     }
     if ($this->_action & CRM_Core_Action::COPY) {
         if (!CRM_Utils_Rule::positiveInteger($this->_cloneID)) {
             CRM_Core_Error::fatal(ts('We need a valid discount ID for update and/or delete'));
         }
     }
     CRM_Utils_System::setTitle(ts('Discounts'));
     $this->_multiValued = array('memberships' => NULL, 'events' => NULL, 'pricesets' => NULL);
     $this->select2style = array('placeholder' => ts('- none -'), 'multiple' => TRUE, 'class' => 'crm-select2 huge');
 }
Ejemplo n.º 10
0
 /**
  * This function sets the default values for the form. Note that in edit/view mode
  * the default values are retrieved from the database
  *
  * @param null
  *
  * @return array    array of default values
  * @access public
  */
 function setDefaultValues()
 {
     $defaults = $this->_values;
     if ($this->_id) {
         $this->assign('id', $this->_id);
         $this->_gid = $defaults['custom_group_id'];
         //get the value for state or country
         if ($defaults['data_type'] == 'StateProvince' && ($stateId = CRM_Utils_Array::value('default_value', $defaults))) {
             $defaults['default_value'] = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_StateProvince', $stateId);
         } elseif ($defaults['data_type'] == 'Country' && ($countryId = CRM_Utils_Array::value('default_value', $defaults))) {
             $defaults['default_value'] = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Country', $countryId);
         }
         if ($defaults['data_type'] == 'ContactReference' && CRM_Utils_Array::value('filter', $defaults)) {
             $contactRefFilter = 'Advance';
             if (strpos($defaults['filter'], 'action=lookup') !== FALSE && strpos($defaults['filter'], 'group=') !== FALSE) {
                 $filterParts = explode('&', $defaults['filter']);
                 if (count($filterParts) == 2) {
                     $contactRefFilter = 'Group';
                     foreach ($filterParts as $part) {
                         if (strpos($part, 'group=') === FALSE) {
                             continue;
                         }
                         $groups = substr($part, strpos($part, '=') + 1);
                         foreach (explode(',', $groups) as $grp) {
                             if (CRM_Utils_Rule::positiveInteger($grp)) {
                                 $defaults['group_id'][] = $grp;
                             }
                         }
                     }
                 }
             }
             $defaults['filter_selected'] = $contactRefFilter;
         }
         if (CRM_Utils_Array::value('data_type', $defaults)) {
             $defaultDataType = array_search($defaults['data_type'], self::$_dataTypeKeys);
             $defaultHTMLType = array_search($defaults['html_type'], self::$_dataToHTML[$defaultDataType]);
             $defaults['data_type'] = array('0' => $defaultDataType, '1' => $defaultHTMLType);
             $this->_defaultDataType = $defaults['data_type'];
         }
         $defaults['option_type'] = 2;
         $this->assign('changeFieldType', CRM_Custom_Form_ChangeFieldType::fieldTypeTransitions($this->_values['data_type'], $this->_values['html_type']));
     } else {
         $defaults['is_active'] = 1;
         $defaults['option_type'] = 1;
     }
     // set defaults for weight.
     for ($i = 1; $i <= self::NUM_OPTION; $i++) {
         $defaults['option_status[' . $i . ']'] = 1;
         $defaults['option_weight[' . $i . ']'] = $i;
     }
     if ($this->_action & CRM_Core_Action::ADD) {
         $fieldValues = array('custom_group_id' => $this->_gid);
         $defaults['weight'] = CRM_Utils_Weight::getDefaultWeight('CRM_Core_DAO_CustomField', $fieldValues);
         $defaults['text_length'] = 255;
         $defaults['note_columns'] = 60;
         $defaults['note_rows'] = 4;
         $defaults['is_view'] = 0;
     }
     if (CRM_Utils_Array::value('html_type', $defaults)) {
         $dontShowLink = substr($defaults['html_type'], -14) == 'State/Province' || substr($defaults['html_type'], -7) == 'Country' ? 1 : 0;
     }
     if (isset($dontShowLink)) {
         $this->assign('dontShowLink', $dontShowLink);
     }
     return $defaults;
 }
Ejemplo n.º 11
0
 static function isContactInGroup($contactID, $groupID)
 {
     if (!CRM_Utils_Rule::positiveInteger($contactID) || !CRM_Utils_Rule::positiveInteger($groupID)) {
         return false;
     }
     $params = array('group' => array($groupID => 1), 'contact_id' => $contactID, 'return.contact_id' => 1);
     require_once 'api/v2/Contact.php';
     $contacts = civicrm_contact_search($params);
     if (!empty($contacts)) {
         return true;
     }
     return false;
 }
Ejemplo n.º 12
0
 /**
  * Delete all pledge payments.
  *
  * @param int $id
  *   Pledge id.
  *
  * @return bool
  */
 public static function deletePayments($id)
 {
     if (!CRM_Utils_Rule::positiveInteger($id)) {
         return FALSE;
     }
     $transaction = new CRM_Core_Transaction();
     $payment = new CRM_Pledge_DAO_PledgePayment();
     $payment->pledge_id = $id;
     if ($payment->find()) {
         while ($payment->fetch()) {
             //also delete associated contribution.
             if ($payment->contribution_id) {
                 CRM_Contribute_BAO_Contribution::deleteContribution($payment->contribution_id);
             }
             self::del($payment->id);
         }
     }
     $transaction->commit();
     return TRUE;
 }
Ejemplo n.º 13
0
 /**
  * @dataProvider positiveDataProvider
  */
 function testPositive($inputData, $expectedResult)
 {
     $this->assertEquals($expectedResult, CRM_Utils_Rule::positiveInteger($inputData));
 }
Ejemplo n.º 14
0
 /**
  * global form rule
  *
  * @param array $fields  the input form values
  * @param array $files   the uploaded files if any
  * @param array $options additional user data
  *
  * @return true if no errors, else array of errors
  * @access public
  * @static
  */
 static function formRule($fields, $files, $self)
 {
     $errors = array();
     $amount = self::computeAmount($fields, $self);
     if (!empty($fields['selectMembership']) && $fields['selectMembership'] != 'no_thanks' || !empty($fields['priceSetId']) && $self->_useForMember) {
         $lifeMember = CRM_Member_BAO_Membership::getAllContactMembership($self->_userID, FALSE, TRUE);
         $membershipOrgDetails = CRM_Member_BAO_MembershipType::getMembershipTypeOrganization();
         $unallowedOrgs = array();
         foreach (array_keys($lifeMember) as $memTypeId) {
             $unallowedOrgs[] = $membershipOrgDetails[$memTypeId];
         }
     }
     //check for atleast one pricefields should be selected
     if (!empty($fields['priceSetId'])) {
         $priceField = new CRM_Price_DAO_PriceField();
         $priceField->price_set_id = $fields['priceSetId'];
         $priceField->orderBy('weight');
         $priceField->find();
         $check = array();
         $membershipIsActive = TRUE;
         $previousId = $otherAmount = FALSE;
         while ($priceField->fetch()) {
             if ($self->_quickConfig && ($priceField->name == 'contribution_amount' || $priceField->name == 'membership_amount')) {
                 $previousId = $priceField->id;
                 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}"])) {
                     $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);
                     if ($min && $otherAmountVal < $min) {
                         $errors["price_{$priceField->id}"] = ts('Contribution amount must be at least %1', array(1 => $min));
                     }
                     if ($max && $otherAmountVal > $max) {
                         $errors["price_{$priceField->id}"] = ts('Contribution amount cannot be more than %1.', array(1 => $max));
                     }
                 }
             }
             if (!empty($fields["price_{$priceField->id}"]) || $previousId == $priceField->id && isset($fields["price_{$previousId}"]) && empty($fields["price_{$previousId}"])) {
                 $check[] = $priceField->id;
             }
         }
         // CRM-12233
         if ($membershipIsActive && !$self->_membershipBlock['is_required'] && $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
                 if ($fieldValue['name'] == 'membership_amount' && CRM_Utils_Array::value('price_' . $fieldKey, $fields) == 0) {
                     $membershipFieldId = $fieldKey;
                 } elseif ($membershipFieldId) {
                     if ($fieldValue['name'] == 'other_amount') {
                         $otherFieldId = $fieldKey;
                     } elseif ($fieldValue['name'] == 'contribution_amount') {
                         $contributionFieldId = $fieldKey;
                     }
                     if (!$errorKey || CRM_Utils_Array::value('price_' . $contributionFieldId, $fields) == '0') {
                         $errorKey = $fieldKey;
                     }
                 }
             }
             // $membershipFieldId is set and additional amount is 'No thank you' or NULL then throw error
             if ($membershipFieldId && !(CRM_Utils_Array::value('price_' . $contributionFieldId, $fields, -1) > 0) && empty($fields['price_' . $otherFieldId])) {
                 $errors["price_{$errorKey}"] = ts('Additional Contribution is required.');
             }
         }
         if (empty($check)) {
             if ($self->_useForMember == 1 && $membershipIsActive) {
                 $errors['_qf_default'] = ts('Select at least one option from Membership Type(s).');
             } else {
                 $errors['_qf_default'] = ts('Select at least one option from Contribution(s).');
             }
         }
         if ($otherAmount && !empty($check)) {
             $errors["price_{$otherAmount}"] = ts('Amount is required field.');
         }
         if ($self->_useForMember == 1 && !empty($check) && $membershipIsActive) {
             $priceFieldIDS = array();
             $priceFieldMemTypes = array();
             foreach ($self->_priceSet['fields'] as $priceId => $value) {
                 if (!empty($fields['price_' . $priceId]) || $self->_quickConfig && $value['name'] == 'membership_amount' && empty($self->_membershipBlock['is_required'])) {
                     if (!empty($fields['price_' . $priceId]) && is_array($fields['price_' . $priceId])) {
                         foreach ($fields['price_' . $priceId] as $priceFldVal => $isSet) {
                             if ($isSet) {
                                 $priceFieldIDS[] = $priceFldVal;
                             }
                         }
                     } elseif (!$value['is_enter_qty'] && !empty($fields['price_' . $priceId])) {
                         // The check for {!$value['is_enter_qty']} is done since, quantity fields allow entering
                         // quantity. And the quantity can't be conisdered as civicrm_price_field_value.id, CRM-9577
                         $priceFieldIDS[] = $fields['price_' . $priceId];
                     }
                     if (!empty($value['options'])) {
                         foreach ($value['options'] as $val) {
                             if (!empty($val['membership_type_id'])) {
                                 $priceFieldMemTypes[] = $val['membership_type_id'];
                             }
                         }
                     }
                 }
             }
             if (!empty($lifeMember)) {
                 foreach ($priceFieldIDS as $priceFieldId) {
                     if (($id = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldId, 'membership_type_id')) && in_array($membershipOrgDetails[$id], $unallowedOrgs)) {
                         $errors['_qf_default'] = ts('You already have a lifetime membership and cannot select a membership with a shorter term.');
                         break;
                     }
                 }
             }
             if (!empty($priceFieldIDS)) {
                 $ids = implode(',', $priceFieldIDS);
                 $priceFieldIDS['id'] = $fields['priceSetId'];
                 $self->set('memberPriceFieldIDS', $priceFieldIDS);
                 $count = CRM_Price_BAO_PriceSet::getMembershipCount($ids);
                 foreach ($count as $id => $occurance) {
                     if ($occurance > 1) {
                         $errors['_qf_default'] = ts('You have selected multiple memberships for the same organization or entity. Please review your selections and choose only one membership per entity. Contact the site administrator if you need assistance.');
                     }
                 }
             }
             if (empty($priceFieldMemTypes)) {
                 $errors['_qf_default'] = ts('Please select at least one membership option.');
             }
         }
         CRM_Price_BAO_PriceSet::processAmount($self->_values['fee'], $fields, $lineItem);
         if ($fields['amount'] < 0) {
             $errors['_qf_default'] = ts('Contribution can not be less than zero. Please select the options accordingly');
         }
         $amount = $fields['amount'];
     }
     if (isset($fields['selectProduct']) && $fields['selectProduct'] != 'no_thanks') {
         $productDAO = new CRM_Contribute_DAO_Product();
         $productDAO->id = $fields['selectProduct'];
         $productDAO->find(TRUE);
         $min_amount = $productDAO->min_contribution;
         if ($amount < $min_amount) {
             $errors['selectProduct'] = ts('The premium you have selected requires a minimum contribution of %1', array(1 => CRM_Utils_Money::format($min_amount)));
             CRM_Core_Session::setStatus($errors['selectProduct']);
         }
     }
     if (!empty($fields['is_recur'])) {
         if ($fields['frequency_interval'] <= 0) {
             $errors['frequency_interval'] = ts('Please enter a number for how often you want to make this recurring contribution (EXAMPLE: Every 3 months).');
         }
         if ($fields['frequency_unit'] == '0') {
             $errors['frequency_unit'] = ts('Please select a period (e.g. months, years ...) for how often you want to make this recurring contribution (EXAMPLE: Every 3 MONTHS).');
         }
     }
     if (!empty($fields['is_recur']) && 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.');
     }
     if (!empty($fields['is_for_organization']) && !property_exists($self, 'organizationName')) {
         if (empty($fields['onbehalf']['organization_name'])) {
             if (!empty($fields['org_option']) && !$fields['onbehalfof_id']) {
                 $errors['organization_id'] = ts('Please select an organization or enter a new one.');
             } elseif (empty($fields['org_option'])) {
                 $errors['onbehalf']['organization_name'] = ts('Please enter the organization name.');
             }
         }
         foreach ($fields['onbehalf'] as $key => $value) {
             if (strstr($key, 'email')) {
                 $emailLocType = explode('-', $key);
             }
         }
         if (empty($fields['onbehalf']["email-{$emailLocType[1]}"])) {
             $errors['onbehalf']["email-{$emailLocType[1]}"] = ts('Organization email is required.');
         }
     }
     // validate PCP fields - if not anonymous, we need a nick name value
     if ($self->_pcpId && !empty($fields['pcp_display_in_roll']) && CRM_Utils_Array::value('pcp_is_anonymous', $fields) == 0 && CRM_Utils_Array::value('pcp_roll_nickname', $fields) == '') {
         $errors['pcp_roll_nickname'] = ts('Please enter a name to include in the Honor Roll, or select \'contribute anonymously\'.');
     }
     // return if this is express mode
     $config = CRM_Core_Config::singleton();
     if ($self->_paymentProcessor && $self->_paymentProcessor['billing_mode'] & CRM_Core_Payment::BILLING_MODE_BUTTON) {
         if (!empty($fields[$self->_expressButtonName . '_x']) || !empty($fields[$self->_expressButtonName . '_y']) || CRM_Utils_Array::value($self->_expressButtonName, $fields)) {
             return $errors;
         }
     }
     //validate the pledge fields.
     if (!empty($self->_values['pledge_block_id'])) {
         //validation for pledge payment.
         if (!empty($self->_values['pledge_id'])) {
             if (empty($fields['pledge_amount'])) {
                 $errors['pledge_amount'] = ts('At least one payment option needs to be checked.');
             }
         } elseif (!empty($fields['is_pledge'])) {
             if (CRM_Utils_Rule::positiveInteger(CRM_Utils_Array::value('pledge_installments', $fields)) == FALSE) {
                 $errors['pledge_installments'] = ts('Please enter a valid number of pledge installments.');
             } else {
                 if (CRM_Utils_Array::value('pledge_installments', $fields) == NULL) {
                     $errors['pledge_installments'] = ts('Pledge Installments is required field.');
                 } elseif (CRM_Utils_array::value('pledge_installments', $fields) == 1) {
                     $errors['pledge_installments'] = ts('Pledges consist of multiple scheduled payments. Select one-time contribution if you want to make your gift in a single payment.');
                 } elseif (CRM_Utils_array::value('pledge_installments', $fields) == 0) {
                     $errors['pledge_installments'] = ts('Pledge Installments field must be > 1.');
                 }
             }
             //validation for Pledge Frequency Interval.
             if (CRM_Utils_Rule::positiveInteger(CRM_Utils_Array::value('pledge_frequency_interval', $fields)) == FALSE) {
                 $errors['pledge_frequency_interval'] = ts('Please enter a valid Pledge Frequency Interval.');
             } else {
                 if (CRM_Utils_Array::value('pledge_frequency_interval', $fields) == NULL) {
                     $errors['pledge_frequency_interval'] = ts('Pledge Frequency Interval. is required field.');
                 } elseif (CRM_Utils_array::value('pledge_frequency_interval', $fields) == 0) {
                     $errors['pledge_frequency_interval'] = ts('Pledge frequency interval field must be > 0');
                 }
             }
         }
     }
     // also return if paylater mode
     if (CRM_Utils_Array::value('payment_processor', $fields) == 0) {
         return empty($errors) ? TRUE : $errors;
     }
     // if the user has chosen a free membership or the amount is less than zero
     // i.e. we skip calling the payment processor and hence dont need credit card
     // info
     if ((double) $amount <= 0.0) {
         return $errors;
     }
     if (!empty($self->_paymentFields)) {
         CRM_Core_Form::validateMandatoryFields($self->_paymentFields, $fields, $errors);
     }
     CRM_Core_Payment_Form::validateCreditCard($fields, $errors);
     foreach (CRM_Contact_BAO_Contact::$_greetingTypes as $greeting) {
         if ($greetingType = CRM_Utils_Array::value($greeting, $fields)) {
             $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))));
             }
         }
     }
     return empty($errors) ? TRUE : $errors;
 }
Ejemplo n.º 15
0
 /**
  * Global form rule.
  *
  * @param array $fields
  *   The input form values.
  * @param array $files
  *   The uploaded files if any.
  * @param CRM_Core_Form $self
  *
  * @return bool|array
  *   true if no errors, else array of errors
  */
 public static function formRule($fields, $files, $self)
 {
     $errors = array();
     $amount = self::computeAmount($fields, $self->_values);
     if (CRM_Utils_Array::value('auto_renew', $fields) && CRM_Utils_Array::value('payment_processor_id', $fields) == 0) {
         $errors['auto_renew'] = ts('You cannot have auto-renewal on if you are paying later.');
     }
     if (!empty($fields['selectMembership']) && $fields['selectMembership'] != 'no_thanks' || !empty($fields['priceSetId']) && $self->_useForMember) {
         $isTest = $self->_action & CRM_Core_Action::PREVIEW ? TRUE : FALSE;
         $lifeMember = CRM_Member_BAO_Membership::getAllContactMembership($self->_membershipContactID, $isTest, TRUE);
         $membershipOrgDetails = CRM_Member_BAO_MembershipType::getMembershipTypeOrganization();
         $unallowedOrgs = array();
         foreach (array_keys($lifeMember) as $memTypeId) {
             $unallowedOrgs[] = $membershipOrgDetails[$memTypeId];
         }
     }
     //check for atleast one pricefields should be selected
     if (!empty($fields['priceSetId']) && empty($self->_ccid)) {
         $priceField = new CRM_Price_DAO_PriceField();
         $priceField->price_set_id = $fields['priceSetId'];
         $priceField->orderBy('weight');
         $priceField->find();
         $check = array();
         $membershipIsActive = TRUE;
         $previousId = $otherAmount = FALSE;
         while ($priceField->fetch()) {
             if ($self->_quickConfig && ($priceField->name == 'contribution_amount' || $priceField->name == 'membership_amount')) {
                 $previousId = $priceField->id;
                 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}"])) {
                     $otherAmount = $priceField->id;
                 } elseif (!empty($fields["price_{$priceField->id}"])) {
                     $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));
                     }
                     if ($max && $otherAmountVal > $max) {
                         $errors["price_{$priceField->id}"] = ts('Contribution amount cannot be more than %1.', array(1 => $max));
                     }
                 }
             }
             if (!empty($fields["price_{$priceField->id}"]) || $previousId == $priceField->id && isset($fields["price_{$previousId}"]) && empty($fields["price_{$previousId}"])) {
                 $check[] = $priceField->id;
             }
         }
         $currentMemberships = NULL;
         if ($membershipIsActive) {
             $is_test = $self->_mode != 'live' ? 1 : 0;
             $memContactID = $self->_membershipContactID;
             // For anonymous user check using dedupe rule
             // if user has Cancelled Membership
             if (!$memContactID) {
                 $dedupeParams = CRM_Dedupe_Finder::formatParams($fields, 'Individual');
                 $dedupeParams['check_permission'] = FALSE;
                 $ids = CRM_Dedupe_Finder::dupesByParams($dedupeParams, 'Individual');
                 // if we find more than one contact, use the first one
                 $memContactID = CRM_Utils_Array::value(0, $ids);
             }
             $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]) && isset($fieldValue['options'][$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)) {
                             $errors['price_' . $fieldKey] = ts($errorText, array(1 => CRM_Member_PseudoConstant::membershipType($fieldValue['options'][$fields['price_' . $fieldKey]]['membership_type_id'])));
                         }
                     } else {
                         if (is_array($fields['price_' . $fieldKey])) {
                             foreach (array_keys($fields['price_' . $fieldKey]) as $key) {
                                 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']) {
             $membershipFieldId = $contributionFieldId = $errorKey = $otherFieldId = NULL;
             foreach ($self->_values['fee'] as $fieldKey => $fieldValue) {
                 // if 'No thank you' membership is selected then set $membershipFieldId
                 if ($fieldValue['name'] == 'membership_amount' && CRM_Utils_Array::value('price_' . $fieldKey, $fields) == 0) {
                     $membershipFieldId = $fieldKey;
                 } elseif ($membershipFieldId) {
                     if ($fieldValue['name'] == 'other_amount') {
                         $otherFieldId = $fieldKey;
                     } elseif ($fieldValue['name'] == 'contribution_amount') {
                         $contributionFieldId = $fieldKey;
                     }
                     if (!$errorKey || CRM_Utils_Array::value('price_' . $contributionFieldId, $fields) == '0') {
                         $errorKey = $fieldKey;
                     }
                 }
             }
             // $membershipFieldId is set and additional amount is 'No thank you' or NULL then throw error
             if ($membershipFieldId && !(CRM_Utils_Array::value('price_' . $contributionFieldId, $fields, -1) > 0) && empty($fields['price_' . $otherFieldId])) {
                 $errors["price_{$errorKey}"] = ts('Additional Contribution is required.');
             }
         }
         if (empty($check) && empty($self->_ccid)) {
             if ($self->_useForMember == 1 && $membershipIsActive) {
                 $errors['_qf_default'] = ts('Select at least one option from Membership Type(s).');
             } else {
                 $errors['_qf_default'] = ts('Select at least one option from Contribution(s).');
             }
         }
         if ($otherAmount && !empty($check)) {
             $errors["price_{$otherAmount}"] = ts('Amount is required field.');
         }
         if ($self->_useForMember == 1 && !empty($check) && $membershipIsActive) {
             $priceFieldIDS = array();
             $priceFieldMemTypes = array();
             foreach ($self->_priceSet['fields'] as $priceId => $value) {
                 if (!empty($fields['price_' . $priceId]) || $self->_quickConfig && $value['name'] == 'membership_amount' && empty($self->_membershipBlock['is_required'])) {
                     if (!empty($fields['price_' . $priceId]) && is_array($fields['price_' . $priceId])) {
                         foreach ($fields['price_' . $priceId] as $priceFldVal => $isSet) {
                             if ($isSet) {
                                 $priceFieldIDS[] = $priceFldVal;
                             }
                         }
                     } elseif (!$value['is_enter_qty'] && !empty($fields['price_' . $priceId])) {
                         // The check for {!$value['is_enter_qty']} is done since, quantity fields allow entering
                         // quantity. And the quantity can't be conisdered as civicrm_price_field_value.id, CRM-9577
                         $priceFieldIDS[] = $fields['price_' . $priceId];
                     }
                     if (!empty($value['options'])) {
                         foreach ($value['options'] as $val) {
                             if (!empty($val['membership_type_id']) && ($fields['price_' . $priceId] == $val['id'] || isset($fields['price_' . $priceId]) && !empty($fields['price_' . $priceId][$val['id']]))) {
                                 $priceFieldMemTypes[] = $val['membership_type_id'];
                             }
                         }
                     }
                 }
             }
             if (!empty($lifeMember)) {
                 foreach ($priceFieldIDS as $priceFieldId) {
                     if (($id = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldId, 'membership_type_id')) && in_array($membershipOrgDetails[$id], $unallowedOrgs)) {
                         $errors['_qf_default'] = ts('You already have a lifetime membership and cannot select a membership with a shorter term.');
                         break;
                     }
                 }
             }
             if (!empty($priceFieldIDS)) {
                 $ids = implode(',', $priceFieldIDS);
                 $priceFieldIDS['id'] = $fields['priceSetId'];
                 $self->set('memberPriceFieldIDS', $priceFieldIDS);
                 $count = CRM_Price_BAO_PriceSet::getMembershipCount($ids);
                 foreach ($count as $id => $occurrence) {
                     if ($occurrence > 1) {
                         $errors['_qf_default'] = ts('You have selected multiple memberships for the same organization or entity. Please review your selections and choose only one membership per entity. Contact the site administrator if you need assistance.');
                     }
                 }
             }
             if (empty($priceFieldMemTypes) && $self->_membershipBlock['is_required'] == 1) {
                 $errors['_qf_default'] = ts('Please select at least one membership option.');
             }
         }
         CRM_Price_BAO_PriceSet::processAmount($self->_values['fee'], $fields, $lineItem);
         if ($fields['amount'] < 0) {
             $errors['_qf_default'] = ts('Contribution can not be less than zero. Please select the options accordingly');
         }
         $amount = $fields['amount'];
     }
     if (isset($fields['selectProduct']) && $fields['selectProduct'] != 'no_thanks') {
         $productDAO = new CRM_Contribute_DAO_Product();
         $productDAO->id = $fields['selectProduct'];
         $productDAO->find(TRUE);
         $min_amount = $productDAO->min_contribution;
         if ($amount < $min_amount) {
             $errors['selectProduct'] = ts('The premium you have selected requires a minimum contribution of %1', array(1 => CRM_Utils_Money::format($min_amount)));
             CRM_Core_Session::setStatus($errors['selectProduct']);
         }
     }
     //CRM-16285 - Function to handle validation errors on form, for recurring contribution field.
     CRM_Contribute_BAO_ContributionRecur::validateRecurContribution($fields, $files, $self, $errors);
     if (!empty($fields['is_recur']) && CRM_Utils_Array::value('payment_processor_id', $fields) == 0) {
         $errors['_qf_default'] = ts('You cannot set up a recurring contribution if you are not paying online by credit card.');
     }
     // validate PCP fields - if not anonymous, we need a nick name value
     if ($self->_pcpId && !empty($fields['pcp_display_in_roll']) && CRM_Utils_Array::value('pcp_is_anonymous', $fields) == 0 && CRM_Utils_Array::value('pcp_roll_nickname', $fields) == '') {
         $errors['pcp_roll_nickname'] = ts('Please enter a name to include in the Honor Roll, or select \'contribute anonymously\'.');
     }
     // return if this is express mode
     $config = CRM_Core_Config::singleton();
     if ($self->_paymentProcessor && $self->_paymentProcessor['billing_mode'] & CRM_Core_Payment::BILLING_MODE_BUTTON) {
         if (!empty($fields[$self->_expressButtonName . '_x']) || !empty($fields[$self->_expressButtonName . '_y']) || CRM_Utils_Array::value($self->_expressButtonName, $fields)) {
             return $errors;
         }
     }
     //validate the pledge fields.
     if (!empty($self->_values['pledge_block_id'])) {
         //validation for pledge payment.
         if (!empty($self->_values['pledge_id'])) {
             if (empty($fields['pledge_amount'])) {
                 $errors['pledge_amount'] = ts('At least one payment option needs to be checked.');
             }
         } elseif (!empty($fields['is_pledge'])) {
             if (CRM_Utils_Rule::positiveInteger(CRM_Utils_Array::value('pledge_installments', $fields)) == FALSE) {
                 $errors['pledge_installments'] = ts('Please enter a valid number of pledge installments.');
             } else {
                 if (CRM_Utils_Array::value('pledge_installments', $fields) == NULL) {
                     $errors['pledge_installments'] = ts('Pledge Installments is required field.');
                 } elseif (CRM_Utils_Array::value('pledge_installments', $fields) == 1) {
                     $errors['pledge_installments'] = ts('Pledges consist of multiple scheduled payments. Select one-time contribution if you want to make your gift in a single payment.');
                 } elseif (CRM_Utils_Array::value('pledge_installments', $fields) == 0) {
                     $errors['pledge_installments'] = ts('Pledge Installments field must be > 1.');
                 }
             }
             //validation for Pledge Frequency Interval.
             if (CRM_Utils_Rule::positiveInteger(CRM_Utils_Array::value('pledge_frequency_interval', $fields)) == FALSE) {
                 $errors['pledge_frequency_interval'] = ts('Please enter a valid Pledge Frequency Interval.');
             } else {
                 if (CRM_Utils_Array::value('pledge_frequency_interval', $fields) == NULL) {
                     $errors['pledge_frequency_interval'] = ts('Pledge Frequency Interval. is required field.');
                 } elseif (CRM_Utils_Array::value('pledge_frequency_interval', $fields) == 0) {
                     $errors['pledge_frequency_interval'] = ts('Pledge frequency interval field must be > 0');
                 }
             }
         }
     }
     // if the user has chosen a free membership or the amount is less than zero
     // i.e. we don't need to validate payment related fields or profiles.
     if ((double) $amount <= 0.0) {
         return $errors;
     }
     if (CRM_Utils_Array::value('payment_processor_id', $fields) == NULL) {
         $errors['payment_processor_id'] = ts('Payment Method is a required field.');
     } else {
         CRM_Core_Payment_Form::validatePaymentInstrument($fields['payment_processor_id'], $fields, $errors, !$self->_isBillingAddressRequiredForPayLater ? NULL : 'billing');
     }
     foreach (CRM_Contact_BAO_Contact::$_greetingTypes as $greeting) {
         if ($greetingType = CRM_Utils_Array::value($greeting, $fields)) {
             $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))));
             }
         }
     }
     return empty($errors) ? TRUE : $errors;
 }
 /**
  * Function to delete discount codes track
  *
  * @param  int $trackID ID of the discount code track to be deleted.
  *
  * @access public
  * @static
  * @return true on success else false
  */
 static function del($trackID)
 {
     if (!CRM_Utils_Rule::positiveInteger($trackID)) {
         return FALSE;
     }
     $item = new CRM_CiviDiscount_DAO_Track();
     $item->id = $trackID;
     $item->delete();
     return TRUE;
 }
Ejemplo n.º 17
0
 /**
  * @param $fields
  * @param $files
  * @param $self
  *
  * @return array
  */
 public static function formRule($fields, $files, $self)
 {
     $errors = array();
     $op = CRM_Utils_Array::value('total_range_op', $fields);
     $val = CRM_Utils_Array::value('total_range_value', $fields);
     if (!in_array($op, array('eq', 'lte'))) {
         $errors['total_range_op'] = ts("Please select 'Is equal to' OR 'Is Less than or equal to' operator");
     }
     if ($val && !CRM_Utils_Rule::positiveInteger($val)) {
         $errors['total_range_value'] = ts("Please enter positive number");
     }
     return $errors;
 }
Ejemplo n.º 18
0
 /**
  * @param $value
  * @param null $actualElementValue
  *
  * @return bool
  */
 public static function validContact($value, $actualElementValue = NULL)
 {
     if ($actualElementValue) {
         $value = $actualElementValue;
     }
     return CRM_Utils_Rule::positiveInteger($value);
 }
Ejemplo n.º 19
0
 /**
  * Delete Relationship Types.
  *
  * @param int $relationshipTypeId
  *
  * @throws CRM_Core_Exception
  * @return mixed
  */
 public static function del($relationshipTypeId)
 {
     // make sure relationshipTypeId is an integer
     // @todo review this as most delete functions rely on the api & form layer for this
     // or do a find first & throw error if no find
     if (!CRM_Utils_Rule::positiveInteger($relationshipTypeId)) {
         throw new CRM_Core_Exception(ts('Invalid relationship type'));
     }
     //check dependencies
     // delete all relationships
     $relationship = new CRM_Contact_DAO_Relationship();
     $relationship->relationship_type_id = $relationshipTypeId;
     $relationship->delete();
     // remove this relationship type from membership types
     $mems = civicrm_api3('MembershipType', 'get', array('relationship_type_id' => array('LIKE' => "%{$relationshipTypeId}%"), 'return' => array('id', 'relationship_type_id', 'relationship_direction')));
     foreach ($mems['values'] as $membershipTypeId => $membershipType) {
         $pos = array_search($relationshipTypeId, $membershipType['relationship_type_id']);
         // Api call may have returned false positives but currently the relationship_type_id uses
         // nonstandard serialization which makes anything more accurate impossible.
         if ($pos !== FALSE) {
             unset($membershipType['relationship_type_id'][$pos], $membershipType['relationship_direction'][$pos]);
             civicrm_api3('MembershipType', 'create', $membershipType);
         }
     }
     //fixed for CRM-3323
     $mappingField = new CRM_Core_DAO_MappingField();
     $mappingField->relationship_type_id = $relationshipTypeId;
     $mappingField->find();
     while ($mappingField->fetch()) {
         $mappingField->delete();
     }
     $relationshipType = new CRM_Contact_DAO_RelationshipType();
     $relationshipType->id = $relationshipTypeId;
     return $relationshipType->delete();
 }
Ejemplo n.º 20
0
 /**
  * Delete the Message Templates.
  *
  * @param int $messageTemplatesID
  */
 public static function del($messageTemplatesID)
 {
     // make sure messageTemplatesID is an integer
     if (!CRM_Utils_Rule::positiveInteger($messageTemplatesID)) {
         CRM_Core_Error::fatal(ts('Invalid Message template'));
     }
     // Set mailing msg template col to NULL
     $query = "UPDATE civicrm_mailing\n                  SET msg_template_id = NULL\n                  WHERE msg_template_id = %1";
     $params = array(1 => array($messageTemplatesID, 'Integer'));
     CRM_Core_DAO::executeQuery($query, $params);
     $messageTemplates = new CRM_Core_DAO_MessageTemplate();
     $messageTemplates->id = $messageTemplatesID;
     $messageTemplates->delete();
     CRM_Core_Session::setStatus(ts('Selected message template has been deleted.'), ts('Deleted'), 'success');
 }
 /**
  * Function to delete Relationship Types
  *
  * @param int $relationshipTypeId
  * @static
  */
 static function del($relationshipTypeId)
 {
     // make sure relationshipTypeId is an integer
     // @todo review this as most delete functions rely on the api & form layer for this
     // or do a find first & throw error if no find
     if (!CRM_Utils_Rule::positiveInteger($relationshipTypeId)) {
         throw new CRM_Core_Exception(ts('Invalid relationship type'));
     }
     //check dependencies
     // delete all relationships
     $relationship = new CRM_Contact_DAO_Relationship();
     $relationship->relationship_type_id = $relationshipTypeId;
     $relationship->delete();
     // set all membership_type to null
     $query = "\nUPDATE civicrm_membership_type\n  SET  relationship_type_id = NULL\n WHERE relationship_type_id = %1\n";
     $params = array(1 => array(CRM_Core_DAO::VALUE_SEPARATOR . $relationshipTypeId . CRM_Core_DAO::VALUE_SEPARATOR, 'String'));
     CRM_Core_DAO::executeQuery($query, $params);
     //fixed for CRM-3323
     $mappingField = new CRM_Core_DAO_MappingField();
     $mappingField->relationship_type_id = $relationshipTypeId;
     $mappingField->find();
     while ($mappingField->fetch()) {
         $mappingField->delete();
     }
     $relationshipType = new CRM_Contact_DAO_RelationshipType();
     $relationshipType->id = $relationshipTypeId;
     return $relationshipType->delete();
 }
Ejemplo n.º 22
0
 /**
  * global form rule
  *
  * @param array $fields  the input form values
  * @param array $files   the uploaded files if any
  * @param array $options additional user data
  *
  * @return true if no errors, else array of errors
  * @access public
  * @static
  */
 static function formRule($fields, $files, $self)
 {
     $errors = array();
     //check that either an email or firstname+lastname is included in the form(CRM-9587)
     self::checkProfileComplete($fields, $errors, $self->_eventId);
     //To check if the user is already registered for the event(CRM-2426)
     if (!$self->_skipDupeRegistrationCheck) {
         self::checkRegistration($fields, $self);
     }
     //check for availability of registrations.
     if (!$self->_allowConfirmation && !CRM_Utils_Array::value('bypass_payment', $fields) && is_numeric($self->_availableRegistrations) && CRM_Utils_Array::value('additional_participants', $fields) >= $self->_availableRegistrations) {
         $errors['additional_participants'] = ts("There is only enough space left on this event for %1 participant(s).", array(1 => $self->_availableRegistrations));
     }
     // during confirmation don't allow to increase additional participants, CRM-4320
     if ($self->_allowConfirmation && CRM_Utils_Array::value('additional_participants', $fields) && is_array($self->_additionalParticipantIds) && $fields['additional_participants'] > count($self->_additionalParticipantIds)) {
         $errors['additional_participants'] = ts("Oops. It looks like you are trying to increase the number of additional people you are registering for. You can confirm registration for a maximum of %1 additional people.", array(1 => count($self->_additionalParticipantIds)));
     }
     //don't allow to register w/ waiting if enough spaces available.
     if (CRM_Utils_Array::value('bypass_payment', $fields)) {
         if (!is_numeric($self->_availableRegistrations) || !CRM_Utils_Array::value('priceSetId', $fields) && CRM_Utils_Array::value('additional_participants', $fields) < $self->_availableRegistrations) {
             $errors['bypass_payment'] = ts("Oops. There are enough available spaces in this event. You can not add yourself to the waiting list.");
         }
     }
     if (CRM_Utils_Array::value('additional_participants', $fields) && !CRM_Utils_Rule::positiveInteger($fields['additional_participants'])) {
         $errors['additional_participants'] = ts('Please enter a whole number for Number of additional people.');
     }
     // priceset validations
     if (CRM_Utils_Array::value('priceSetId', $fields)) {
         //format params.
         $formatted = self::formatPriceSetParams($self, $fields);
         $ppParams = array($formatted);
         $priceSetErrors = self::validatePriceSet($self, $ppParams);
         $primaryParticipantCount = self::getParticipantCount($self, $ppParams);
         //get price set fields errors in.
         $errors = array_merge($errors, CRM_Utils_Array::value(0, $priceSetErrors, array()));
         $totalParticipants = $primaryParticipantCount;
         if (CRM_Utils_Array::value('additional_participants', $fields)) {
             $totalParticipants += $fields['additional_participants'];
         }
         if (!CRM_Utils_Array::value('bypass_payment', $fields) && !$self->_allowConfirmation && is_numeric($self->_availableRegistrations) && $self->_availableRegistrations < $totalParticipants) {
             $errors['_qf_default'] = ts("Only %1 Registrations available.", array(1 => $self->_availableRegistrations));
         }
         $lineItem = array();
         CRM_Price_BAO_PriceSet::processAmount($self->_values['fee'], $fields, $lineItem);
         if ($fields['amount'] < 0) {
             $errors['_qf_default'] = ts('Event Fee(s) can not be less than zero. Please select the options accordingly');
         }
     }
     if ($self->_values['event']['is_monetary']) {
         if (empty($self->_requireApproval) && !empty($fields['amount']) && $fields['amount'] > 0 && !isset($fields['payment_processor'])) {
             $errors['payment_processor'] = ts('Please select a Payment Method');
         }
         if (is_array($self->_paymentProcessor)) {
             $payment = CRM_Core_Payment::singleton($self->_mode, $self->_paymentProcessor, $this);
             $error = $payment->checkConfig($self->_mode);
             if ($error) {
                 $errors['_qf_default'] = $error;
             }
         }
         // return if this is express mode
         if ($self->_paymentProcessor && $self->_paymentProcessor['billing_mode'] & CRM_Core_Payment::BILLING_MODE_BUTTON) {
             if (CRM_Utils_Array::value($self->_expressButtonName . '_x', $fields) || CRM_Utils_Array::value($self->_expressButtonName . '_y', $fields) || CRM_Utils_Array::value($self->_expressButtonName, $fields)) {
                 return empty($errors) ? TRUE : $errors;
             }
         }
         $isZeroAmount = $skipPaymentValidation = FALSE;
         if (CRM_Utils_Array::value('priceSetId', $fields)) {
             if (CRM_Utils_Array::value('amount', $fields) == 0) {
                 $isZeroAmount = TRUE;
             }
         } elseif (CRM_Utils_Array::value('amount', $fields) && (isset($self->_values['discount'][$fields['amount']]) && CRM_Utils_Array::value('value', $self->_values['discount'][$fields['amount']]) == 0)) {
             $isZeroAmount = TRUE;
         } elseif (CRM_Utils_Array::value('amount', $fields) && (isset($self->_values['fee'][$fields['amount']]) && CRM_Utils_Array::value('value', $self->_values['fee'][$fields['amount']]) == 0)) {
             $isZeroAmount = TRUE;
         }
         if ($isZeroAmount && !($self->_forcePayement && CRM_Utils_Array::value('additional_participants', $fields))) {
             $skipPaymentValidation = TRUE;
         }
         // also return if paylater mode or zero fees for valid members
         if (CRM_Utils_Array::value('is_pay_later', $fields) || CRM_Utils_Array::value('bypass_payment', $fields) || $skipPaymentValidation || !$self->_allowConfirmation && ($self->_requireApproval || $self->_allowWaitlist)) {
             return empty($errors) ? TRUE : $errors;
         }
         if (!empty($self->_paymentFields)) {
             CRM_Core_Form::validateMandatoryFields($self->_paymentFields, $fields, $errors);
         }
         CRM_Core_Payment_Form::validateCreditCard($fields, $errors);
     }
     foreach (CRM_Contact_BAO_Contact::$_greetingTypes as $greeting) {
         if ($greetingType = CRM_Utils_Array::value($greeting, $fields)) {
             $customizedValue = CRM_Core_OptionGroup::getValue($greeting, 'Customized', 'name');
             if ($customizedValue == $greetingType && empty($fields[$greeting . '_custom'])) {
                 $errors[$customizedGreeting] = ts('Custom %1 is a required field if %1 is of type Customized.', array(1 => ucwords(str_replace('_', ' ', $greeting))));
             }
         }
     }
     return empty($errors) ? TRUE : $errors;
 }
Ejemplo n.º 23
0
 /**
  * Delete all the block associated with the location
  *
  * @param  int  $contactId      contact id
  * @param  int  $locationTypeId id of the location to delete
  *
  * @return void
  * @access public
  * @static
  */
 static function deleteLocationBlocks($contactId, $locationTypeId)
 {
     // ensure that contactId has a value
     if (empty($contactId) || !CRM_Utils_Rule::positiveInteger($contactId)) {
         CRM_Core_Error::fatal();
     }
     if (empty($locationTypeId) || !CRM_Utils_Rule::positiveInteger($locationTypeId)) {
         // so we only delete the blocks which DO NOT have a location type Id
         // CRM-3581
         $locationTypeId = 'null';
     }
     static $blocks = array('Address', 'Phone', 'IM', 'OpenID', 'Email');
     $params = array('contact_id' => $contactId, 'location_type_id' => $locationTypeId);
     foreach ($blocks as $name) {
         CRM_Core_BAO_Block::blockDelete($name, $params);
     }
 }
Ejemplo n.º 24
0
 /**
  * Verify that a variable is of a given type.
  *
  * @param mixed $data
  *   The value to validate.
  * @param string $type
  *   The type to validate against.
  * @param bool $abort
  *   If TRUE, the operation will CRM_Core_Error::fatal() on invalid data.
  * @name string $name
  *   The name of the attribute
  *
  * @return mixed
  *   The data, escaped if necessary
  */
 public static function validate($data, $type, $abort = TRUE, $name = 'One of parameters ')
 {
     switch ($type) {
         case 'Integer':
         case 'Int':
             if (CRM_Utils_Rule::integer($data)) {
                 return (int) $data;
             }
             break;
         case 'Positive':
             if (CRM_Utils_Rule::positiveInteger($data)) {
                 return $data;
             }
             break;
         case 'Boolean':
             if (CRM_Utils_Rule::boolean($data)) {
                 return $data;
             }
             break;
         case 'Float':
         case 'Money':
             if (CRM_Utils_Rule::numeric($data)) {
                 return $data;
             }
             break;
         case 'Text':
         case 'String':
         case 'Link':
         case 'Memo':
             return $data;
         case 'Date':
             // a null date is valid
             if (strlen(trim($data)) == 0) {
                 return trim($data);
             }
             if (preg_match('/^\\d{8}$/', $data) && CRM_Utils_Rule::mysqlDate($data)) {
                 return $data;
             }
             break;
         case 'Timestamp':
             // a null timestamp is valid
             if (strlen(trim($data)) == 0) {
                 return trim($data);
             }
             if ((preg_match('/^\\d{14}$/', $data) || preg_match('/^\\d{8}$/', $data)) && CRM_Utils_Rule::mysqlDate($data)) {
                 return $data;
             }
             break;
         case 'ContactReference':
             // null is valid
             if (strlen(trim($data)) == 0) {
                 return trim($data);
             }
             if (CRM_Utils_Rule::validContact($data)) {
                 return $data;
             }
             break;
         default:
             CRM_Core_Error::fatal("Cannot recognize {$type} for {$data}");
             break;
     }
     if ($abort) {
         $data = htmlentities($data);
         CRM_Core_Error::fatal("{$name} (value: {$data}) is not of the type {$type}");
     }
     return NULL;
 }
Ejemplo n.º 25
0
 /**
  * Set severity level
  *
  * @param string|int $level
  * @throws \CRM_Core_Exception
  */
 public function setLevel($level)
 {
     // Convert level to integer
     if (!CRM_Utils_Rule::positiveInteger($level)) {
         $level = CRM_Utils_Check::severityMap($level);
     } else {
         // Validate numeric input - this will throw an exception if invalid
         CRM_Utils_Check::severityMap($level, TRUE);
     }
     $this->level = $level;
     // Clear internal caches
     unset($this->isVisible, $this->hiddenUntil);
 }
Ejemplo n.º 26
0
 static function getInstanceID()
 {
     $config = CRM_Core_Config::singleton();
     $arg = explode('/', $_GET[$config->userFrameworkURLVar]);
     if ($arg[1] == 'report' && CRM_Utils_Array::value(2, $arg) == 'instance') {
         if (CRM_Utils_Rule::positiveInteger($arg[3])) {
             return $arg[3];
         }
     }
 }
Ejemplo n.º 27
0
 /**
  * Retrieve id of target contact by activity_id.
  *
  * @param int $activityID
  * @param int $recordTypeID
  *
  * @return mixed
  */
 public static function retrieveContactIdsByActivityId($activityID, $recordTypeID)
 {
     $activityContact = array();
     if (!CRM_Utils_Rule::positiveInteger($activityID) || !CRM_Utils_Rule::positiveInteger($recordTypeID)) {
         return $activityContact;
     }
     $sql = "                                                                                                                                                                                             SELECT     contact_id\nFROM       civicrm_activity_contact\nINNER JOIN civicrm_contact ON contact_id = civicrm_contact.id\nWHERE      activity_id = %1\nAND        record_type_id = %2\nAND        civicrm_contact.is_deleted = 0\n";
     $params = array(1 => array($activityID, 'Integer'), 2 => array($recordTypeID, 'Integer'));
     $dao = CRM_Core_DAO::executeQuery($sql, $params);
     while ($dao->fetch()) {
         $activityContact[] = $dao->contact_id;
     }
     return $activityContact;
 }
Ejemplo n.º 28
0
/**
 * Get details of a particular case, or search for cases, depending on params.
 *
 * Please provide one (and only one) of the four get/search parameters:
 *
 * @param array $params
 *   'id' => if set, will get all available info about a case, including contacts and activities
 *
 *   // if no case_id provided, this function will use one of the following search parameters:
 *   'client_id' => finds all cases with a specific client
 *   'activity_id' => returns the case containing a specific activity
 *   'contact_id' => finds all cases associated with a contact (in any role, not just client)
 *
 * @throws API_Exception
 * @return array
 *   (get mode, case_id provided): Array with case details, case roles, case activity ids, (search mode, case_id not provided): Array of cases found
 */
function civicrm_api3_case_get($params)
{
    $options = _civicrm_api3_get_options_from_params($params);
    $sql = CRM_Utils_SQL_Select::fragment();
    // Add clause to search by client
    if (!empty($params['contact_id'])) {
        $contacts = array();
        foreach ((array) $params['contact_id'] as $c) {
            if (!CRM_Utils_Rule::positiveInteger($c)) {
                throw new API_Exception('Invalid parameter: contact_id. Must provide numeric value(s).');
            }
            $contacts[] = $c;
        }
        $sql->join('civicrm_case_contact', 'INNER JOIN civicrm_case_contact ON civicrm_case_contact.case_id = a.id')->where('civicrm_case_contact.contact_id IN (' . implode(',', $contacts) . ')');
    }
    // Add clause to search by activity
    if (!empty($params['activity_id'])) {
        if (!CRM_Utils_Rule::positiveInteger($params['activity_id'])) {
            throw new API_Exception('Invalid parameter: activity_id. Must provide a numeric value.');
        }
        $activityId = $params['activity_id'];
        $originalId = CRM_Core_DAO::getFieldValue('CRM_Activity_BAO_Activity', $activityId, 'original_id');
        if ($originalId) {
            $activityId .= ',' . $originalId;
        }
        $sql->join('civicrm_case_activity', 'INNER JOIN civicrm_case_activity ON civicrm_case_activity.case_id = a.id')->where("civicrm_case_activity.activity_id IN ({$activityId})");
    }
    $foundcases = _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params, TRUE, 'Case', $sql);
    if (empty($options['is_count'])) {
        // For historic reasons we return these by default only when fetching a case by id
        if (!empty($params['id']) && empty($options['return'])) {
            $options['return'] = array('contacts' => 1, 'activities' => 1, 'contact_id' => 1);
        }
        foreach ($foundcases['values'] as &$case) {
            _civicrm_api3_case_read($case, $options);
        }
    }
    return $foundcases;
}
Ejemplo n.º 29
0
 /**
  * handle the values in summary mode
  *
  * @param array $values the array of values belonging to this line
  *
  * @return boolean      the result of this processing
  * @access public
  */
 function summary(&$values)
 {
     $erroneousField = NULL;
     $response = $this->setActiveFieldValues($values, $erroneousField);
     $index = -1;
     $errorRequired = FALSE;
     if ($this->_activityTypeIndex > -1 && $this->_activityLabelIndex > -1) {
         array_unshift($values, ts('Please select either Activity Type ID OR Activity Type Label.'));
         return CRM_Import_Parser::ERROR;
     } elseif ($this->_activityLabelIndex > -1) {
         $index = $this->_activityLabelIndex;
     } elseif ($this->_activityTypeIndex > -1) {
         $index = $this->_activityTypeIndex;
     }
     if ($index < 0 or $this->_activityDateIndex < 0) {
         $errorRequired = TRUE;
     } else {
         $errorRequired = !CRM_Utils_Array::value($index, $values) || !CRM_Utils_Array::value($this->_activityDateIndex, $values);
     }
     if ($errorRequired) {
         array_unshift($values, ts('Missing required fields'));
         return CRM_Import_Parser::ERROR;
     }
     $params =& $this->getActiveFieldParams();
     $errorMessage = NULL;
     //for date-Formats
     $session = CRM_Core_Session::singleton();
     $dateType = $session->get('dateTypes');
     if (!isset($params['source_contact_id'])) {
         $params['source_contact_id'] = $session->get('userID');
     }
     foreach ($params as $key => $val) {
         if ($key == 'activity_date_time') {
             if ($val) {
                 $dateValue = CRM_Utils_Date::formatDate($val, $dateType);
                 if ($dateValue) {
                     $params[$key] = $dateValue;
                 } else {
                     CRM_Contact_Import_Parser_Contact::addToErrorMsg('Activity date', $errorMessage);
                 }
             }
         } elseif ($key == 'activity_engagement_level' && $val && !CRM_Utils_Rule::positiveInteger($val)) {
             CRM_Contact_Import_Parser_Contact::addToErrorMsg('Activity Engagement Index', $errorMessage);
         }
     }
     //date-Format part ends
     //checking error in custom data
     $params['contact_type'] = isset($this->_contactType) ? $this->_contactType : 'Activity';
     CRM_Contact_Import_Parser_Contact::isErrorInCustomData($params, $errorMessage);
     if ($errorMessage) {
         $tempMsg = "Invalid value for field(s) : {$errorMessage}";
         array_unshift($values, $tempMsg);
         $errorMessage = NULL;
         return CRM_Import_Parser::ERROR;
     }
     return CRM_Import_Parser::VALID;
 }
Ejemplo n.º 30
0
 /**
  * function to delete the Message Templates
  *
  * @access public
  * @static 
  * @return object
  */
 static function del($messageTemplatesID)
 {
     // make sure messageTemplatesID is an integer
     if (!CRM_Utils_Rule::positiveInteger($messageTemplatesID)) {
         CRM_Core_Error::fatal(ts('Invalid Message template'));
     }
     // set membership_type to null
     $query = "UPDATE civicrm_membership_type\n                  SET renewal_msg_id = NULL\n                  WHERE renewal_msg_id = %1";
     $params = array(1 => array($messageTemplatesID, 'Integer'));
     CRM_Core_DAO::executeQuery($query, $params);
     $query = "UPDATE civicrm_mailing\n                  SET msg_template_id = NULL\n                  WHERE msg_template_id = %1";
     CRM_Core_DAO::executeQuery($query, $params);
     $messageTemplates =& new CRM_Core_DAO_MessageTemplates();
     $messageTemplates->id = $messageTemplatesID;
     $messageTemplates->delete();
     CRM_Core_Session::setStatus(ts('Selected message templates has been deleted.'));
 }