예제 #1
0
 public function preProcess()
 {
     if (!CRM_Campaign_BAO_Campaign::accessCampaign()) {
         CRM_Utils_System::permissionDenied();
     }
     $this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'add', 'REQUEST');
     $this->_surveyId = CRM_Utils_Request::retrieve('id', 'Positive', $this, FALSE);
     if ($this->_surveyId) {
         $this->_single = TRUE;
         $params = array('id' => $this->_surveyId);
         CRM_Campaign_BAO_Survey::retrieve($params, $surveyInfo);
         $this->_surveyTitle = $surveyInfo['title'];
         $this->assign('surveyTitle', $this->_surveyTitle);
         CRM_Utils_System::setTitle(ts('Configure Survey - %1', array(1 => $this->_surveyTitle)));
     }
     $this->assign('action', $this->_action);
     $this->assign('surveyId', $this->_surveyId);
     // when custom data is included in this page
     if (!empty($_POST['hidden_custom'])) {
         $this->set('type', 'Event');
         $this->set('entityId', $this->_surveyId);
         CRM_Custom_Form_CustomData::preProcess($this, NULL, NULL, 1, 'Survey', $this->_surveyId);
         CRM_Custom_Form_CustomData::buildQuickForm($this);
         CRM_Custom_Form_CustomData::setDefaultValues($this);
     }
     // CRM-11480, CRM-11682
     // Preload libraries required by the "Questions" tab
     CRM_UF_Page_ProfileEditor::registerProfileScripts();
     CRM_UF_Page_ProfileEditor::registerSchemas(array('IndividualModel', 'ActivityModel'));
     CRM_Campaign_Form_Survey_TabHeader::build($this);
 }
예제 #2
0
 /**
  * Build the form object.
  */
 public function buildQuickForm()
 {
     if ($this->_search) {
         return;
     }
     $attributes = CRM_Core_DAO::getAttribute('CRM_Campaign_DAO_Survey');
     $this->add('text', 'survey_title', ts('Title'), $attributes['title']);
     //activity Type id
     $surveyTypes = CRM_Campaign_BAO_Survey::getSurveyActivityType();
     $this->add('select', 'activity_type_id', ts('Activity Type'), array('' => ts('- select -')) + $surveyTypes);
     $this->set('surveyTypes', $surveyTypes);
     $this->assign('surveyTypes', json_encode($surveyTypes));
     //campaigns
     $campaigns = CRM_Campaign_BAO_Campaign::getCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
     $this->add('select', 'survey_campaign_id', ts('Campaign'), array('' => ts('- select -')) + $campaigns);
     $this->set('surveyCampaigns', $campaigns);
     $this->assign('surveyCampaigns', json_encode($campaigns));
     //build the array of all search params.
     $this->_searchParams = array();
     foreach ($this->_elements as $element) {
         $name = $element->_attributes['name'];
         $label = $element->_label;
         if ($name == 'qfKey') {
             continue;
         }
         $this->_searchParams[$name] = $label ? $label : $name;
     }
     $this->set('searchParams', $this->_searchParams);
     $this->assign('searchParams', json_encode($this->_searchParams));
 }
예제 #3
0
 function browse()
 {
     require_once 'CRM/Core/Permission.php';
     $surveys = CRM_Campaign_BAO_Survey::getSurvey(true);
     if (!empty($surveys)) {
         require_once 'CRM/Campaign/BAO/Campaign.php';
         $surveyType = CRM_Campaign_BAO_Survey::getSurveyActivityType();
         $campaigns = CRM_Campaign_BAO_Campaign::getAllCampaign();
         $activityTypes = CRM_Core_OptionGroup::values('activity_type', false, false, false, false, 'name');
         foreach ($surveys as $sid => $survey) {
             $surveys[$sid]['campaign_id'] = $campaigns[$survey['campaign_id']];
             $surveys[$sid]['activity_type_id'] = $surveyType[$survey['activity_type_id']];
             $surveys[$sid]['release_frequency'] = $survey['release_frequency_interval'] . ' ' . $survey['release_frequency_unit'];
             $action = array_sum(array_keys($this->actionLinks()));
             if ($survey['is_active']) {
                 $action -= CRM_Core_Action::ENABLE;
             } else {
                 $action -= CRM_Core_Action::DISABLE;
             }
             $surveys[$sid]['action'] = CRM_Core_Action::formLink($this->actionLinks(), $action, array('id' => $sid));
         }
     }
     $this->assign('surveys', $surveys);
     $this->assign('addSurveyUrl', CRM_Utils_System::url('civicrm/survey/add', 'reset=1&action=add'));
 }
예제 #4
0
/**
 * Get the list of voters (respondents, yet to record survey response) for a survey
 *
 * @param  array   $params           (reference ) input parameters
 *
 * @return array (reference )        contact_id
 * @static void
 * @access public
 */
function &civicrm_api3_survey_voter_get($params)
{
    civicrm_api3_verify_one_mandatory($params, 'CRM_Campaign_BAO_Survey', array('survey_id', 'id'));
    if (array_key_exists('status_id', $params)) {
        $status_id = $params['status_id'];
    } else {
        $status_id = null;
    }
    $surveyID = empty($params['survey_id']) ? $params['id'] : $params['survey_id'];
    require_once 'CRM/Campaign/BAO/Survey.php';
    $survey = new CRM_Campaign_BAO_Survey();
    $voters = $survey->getSurveyVoterInfo($surveyID);
    require_once 'CRM/Contact/BAO/Contact.php';
    foreach ($voters as $key => $voterArray) {
        $voters[$key]['voter_name'] = CRM_Contact_BAO_Contact::displayName($voterArray['voter_id']);
    }
    return civicrm_api3_create_success($voters, $params);
}
예제 #5
0
 /**
  * Process the form when submitted.
  */
 public function postProcess()
 {
     if ($this->_surveyId) {
         CRM_Campaign_BAO_Survey::del($this->_surveyId);
         CRM_Core_Session::setStatus('', ts("'%1' survey has been deleted.", array(1 => $this->_surveyTitle)), 'success');
         CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/campaign', 'reset=1&subPage=survey'));
     } else {
         CRM_Core_Error::fatal(ts('Delete action is missing expected survey ID.'));
     }
 }
예제 #6
0
 function buildForm(&$form)
 {
     $form->add('text', 'sort_name', ts('Contact Name'), true);
     $form->add('text', 'street_number', ts('Street Number'), true);
     $form->add('text', 'street_address', ts('Street Address'), true);
     $form->add('text', 'city', ts('City'), true);
     $surveys = CRM_Campaign_BAO_Survey::getSurveyList();
     $form->add('select', 'survey_id', ts('Survey'), array('' => ts('- select -')) + $surveys);
     $form->add('checkbox', 'status_id', ts('Is Held'), null, false);
     $form->assign('elements', array('sort_name', 'street_number', 'street_address', 'city', 'status_id', 'survey_id'));
     $this->setTitle('Find Voters');
 }
    public function releaseRespondent()
    {
        require_once 'CRM/Core/PseudoConstant.php';
        require_once 'CRM/Campaign/BAO/Survey.php';
        $activityStatus = CRM_Core_PseudoConstant::activityStatus('name');
        $reserveStatusId = array_search('Scheduled', $activityStatus);
        $surveyActivityTypes = CRM_Campaign_BAO_Survey::getSurveyActivityType();
        $surveyActivityTypesIds = array_keys($surveyActivityTypes);
        //retrieve all survey activities related to reserve action.
        $releasedCount = 0;
        if ($reserveStatusId && !empty($surveyActivityTypesIds)) {
            $query = '
    SELECT  activity.id as id,
            activity.activity_date_time as activity_date_time,
            survey.id as surveyId,
            survey.release_frequency as release_frequency
      FROM  civicrm_activity activity
INNER JOIN  civicrm_survey survey ON ( survey.id = activity.source_record_id )
     WHERE  activity.is_deleted = 0
       AND  activity.status_id = %1
       AND  activity.activity_type_id IN ( ' . implode(', ', $surveyActivityTypesIds) . ' )';
            $activity = CRM_Core_DAO::executeQuery($query, array(1 => array($reserveStatusId, 'Positive')));
            $releasedIds = array();
            while ($activity->fetch()) {
                if (!$activity->release_frequency) {
                    continue;
                }
                $reservedSeconds = CRM_Utils_Date::unixTime($activity->activity_date_time);
                $releasedSeconds = $activity->release_frequency * 24 * 3600;
                $totalReservedSeconds = $reservedSeconds + $releasedSeconds;
                if ($totalReservedSeconds < time()) {
                    $releasedIds[$activity->id] = $activity->id;
                }
            }
            //released respondent.
            if (!empty($releasedIds)) {
                $query = '
UPDATE  civicrm_activity
   SET  is_deleted = 1
 WHERE  id IN ( ' . implode(', ', $releasedIds) . ' )';
                CRM_Core_DAO::executeQuery($query);
                $releasedCount = count($releasedIds);
            }
        }
        echo "<br /><br />Number of respondents released = {$releasedCount}";
    }
예제 #8
0
 /**
  * Function to actually build the form
  *
  * @param null
  *
  * @return void
  * @access public
  */
 public function buildQuickForm()
 {
     $subTypeId = CRM_Core_DAO::getFieldValue('CRM_Campaign_DAO_Survey', $this->_surveyId, 'activity_type_id');
     if (!CRM_Core_BAO_CustomGroup::autoCreateByActivityType($subTypeId)) {
         $activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, TRUE, FALSE, 'label', TRUE, FALSE);
         // everything
         // FIXME: Displays weird "/\ Array" message; doesn't work with tabs
         CRM_Core_Session::setStatus(ts('There are no custom data sets for activity type "%1". To create one, <a href="%2" target="%3">click here</a>.', array(1 => $activityTypes[$subTypeId], 2 => CRM_Utils_System::url('civicrm/admin/custom/group', 'action=add&reset=1'), 3 => '_blank')));
     }
     $allowCoreTypes = CRM_Campaign_BAO_Survey::surveyProfileTypes();
     $allowSubTypes = array('ActivityType' => array($subTypeId));
     $entities = array(array('entity_name' => 'contact_1', 'entity_type' => 'IndividualModel'), array('entity_name' => 'activity_1', 'entity_type' => 'ActivityModel', 'entity_sub_type' => $subTypeId));
     $this->addProfileSelector('contact_profile_id', ts('Contact Info'), $allowCoreTypes, $allowSubTypes, $entities);
     $this->addProfileSelector('activity_profile_id', ts('Questions'), $allowCoreTypes, $allowSubTypes, $entities);
     // Note: Because this is in a tab, we also preload the schema via CRM_Campaign_Form_Survey::preProcess
     parent::buildQuickForm();
 }
/**
 * Get the list of signatories.
 *
 * @deprecated - api currently not supported
 *
 * @param array $params
 *   input parameters.
 *
 * @return array
 */
function civicrm_api3_survey_respondant_get(&$params)
{
    civicrm_api3_verify_one_mandatory($params, NULL, array('survey_id', 'id'));
    if (array_key_exists('survey_id', $params)) {
        $surveyID = $params['survey_id'];
    } else {
        $surveyID = $params['id'];
    }
    $interviewerID = NULL;
    if (array_key_exists('interviewer_id', $params)) {
        $interviewerID = $params['interviewer_id'];
    }
    $statusIds = array();
    if (array_key_exists('status_id', $params)) {
        $statusIds = explode(',', $params['status_id']);
    }
    $respondants = CRM_Campaign_BAO_Survey::getSurveyActivities($surveyID, $interviewerID, $statusIds);
    return civicrm_api3_create_success($respondants, $params, 'SurveyRespondant', 'get');
}
예제 #10
0
파일: Confirm.php 프로젝트: kidaa30/yes
 /**
  * @return string
  * @throws Exception
  */
 public function run()
 {
     CRM_Utils_System::addHTMLHead('<META NAME="ROBOTS" CONTENT="NOINDEX, NOFOLLOW">');
     $contact_id = CRM_Utils_Request::retrieve('cid', 'Integer', CRM_Core_DAO::$_nullObject);
     $subscribe_id = CRM_Utils_Request::retrieve('sid', 'Integer', CRM_Core_DAO::$_nullObject);
     $hash = CRM_Utils_Request::retrieve('h', 'String', CRM_Core_DAO::$_nullObject);
     $activity_id = CRM_Utils_Request::retrieve('a', 'String', CRM_Core_DAO::$_nullObject);
     $petition_id = CRM_Utils_Request::retrieve('pid', 'String', CRM_Core_DAO::$_nullObject);
     if (!$petition_id) {
         $petition_id = CRM_Utils_Request::retrieve('p', 'String', CRM_Core_DAO::$_nullObject);
     }
     if (!$contact_id || !$subscribe_id || !$hash) {
         CRM_Core_Error::fatal(ts("Missing input parameters"));
     }
     $result = $this->confirm($contact_id, $subscribe_id, $hash, $activity_id, $petition_id);
     if ($result === FALSE) {
         $this->assign('success', $result);
     } else {
         $this->assign('success', TRUE);
         // $this->assign( 'group'  , $result );
     }
     list($displayName, $email) = CRM_Contact_BAO_Contact_Location::getEmailDetails($contact_id);
     $this->assign('display_name', $displayName);
     $this->assign('email', $email);
     $this->assign('petition_id', $petition_id);
     $this->assign('survey_id', $petition_id);
     $pparams['id'] = $petition_id;
     $this->petition = array();
     CRM_Campaign_BAO_Survey::retrieve($pparams, $this->petition);
     $this->assign('is_share', CRM_Utils_Array::value('is_share', $this->petition));
     $this->assign('thankyou_title', CRM_Utils_Array::value('thankyou_title', $this->petition));
     $this->assign('thankyou_text', CRM_Utils_Array::value('thankyou_text', $this->petition));
     CRM_Utils_System::setTitle(CRM_Utils_Array::value('thankyou_title', $this->petition));
     // send thank you email
     $params['contactId'] = $contact_id;
     $params['email-Primary'] = $email;
     $params['sid'] = $petition_id;
     $params['activityId'] = $activity_id;
     CRM_Campaign_BAO_Petition::sendEmail($params, CRM_Campaign_Form_Petition_Signature::EMAIL_THANK);
     return parent::run();
 }
예제 #11
0
파일: Survey.php 프로젝트: hguru/224Civi
 public function preProcess()
 {
     if (!CRM_Campaign_BAO_Campaign::accessCampaign()) {
         CRM_Utils_System::permissionDenied();
     }
     $this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'add', 'REQUEST');
     $this->_surveyId = CRM_Utils_Request::retrieve('id', 'Positive', $this, FALSE);
     if ($this->_surveyId) {
         $this->_single = TRUE;
         $params = array('id' => $this->_surveyId);
         CRM_Campaign_BAO_Survey::retrieve($params, $surveyInfo);
         $this->_surveyTitle = $surveyInfo['title'];
         $this->assign('surveyTitle', $this->_surveyTitle);
         CRM_Utils_System::setTitle(ts('Configure Survey - %1', array(1 => $this->_surveyTitle)));
     }
     $this->assign('action', $this->_action);
     $this->assign('surveyId', $this->_surveyId);
     // CRM-11480, CRM-11682
     // Preload libraries required by the "Questions" tab
     CRM_UF_Page_ProfileEditor::registerProfileScripts();
     CRM_UF_Page_ProfileEditor::registerSchemas(array('IndividualModel', 'ActivityModel'));
     CRM_Campaign_Form_Survey_TabHeader::build($this);
 }
 function run()
 {
     $id = CRM_Utils_Request::retrieve('id', 'Positive', $this);
     $petition_id = CRM_Utils_Request::retrieve('pid', 'Positive', $this);
     $params['id'] = $petition_id;
     $this->petition = array();
     CRM_Campaign_BAO_Survey::retrieve($params, $this->petition);
     $this->assign('petitionTitle', $this->petition['title']);
     $this->assign('thankyou_title', CRM_Utils_Array::value('thankyou_title', $this->petition));
     $this->assign('thankyou_text', CRM_Utils_Array::value('thankyou_text', $this->petition));
     $this->assign('survey_id', $petition_id);
     $this->assign('status_id', $id);
     CRM_Utils_System::setTitle(CRM_Utils_Array::value('thankyou_title', $this->petition));
     // send thank you or email verification emails
     /* 
      * sendEmailMode
      * 1 = connected user via login/pwd - thank you
      * 	 	or dedupe contact matched who doesn't have a tag CIVICRM_TAG_UNCONFIRMED - thank you
      * 	 	login using fb connect - thank you + click to add msg to fb wall
      * 2 = send a confirmation request email     
      */
     return parent::run();
 }
예제 #13
0
파일: Survey.php 프로젝트: kidaa30/yes
 public function browse()
 {
     $surveys = CRM_Campaign_BAO_Survey::getSurveySummary();
     if (!empty($surveys)) {
         $surveyType = CRM_Campaign_BAO_Survey::getSurveyActivityType();
         $campaigns = CRM_Campaign_BAO_Campaign::getAllCampaign();
         $activityTypes = CRM_Core_OptionGroup::values('activity_type', FALSE, FALSE, FALSE, FALSE, 'name');
         foreach ($surveys as $sid => $survey) {
             $surveys[$sid]['campaign_id'] = $campaigns[$survey['campaign_id']];
             $surveys[$sid]['activity_type_id'] = $surveyType[$survey['activity_type_id']];
             $surveys[$sid]['release_frequency'] = $survey['release_frequency_interval'] . ' ' . $survey['release_frequency_unit'];
             $action = array_sum(array_keys($this->actionLinks()));
             if ($survey['is_active']) {
                 $action -= CRM_Core_Action::ENABLE;
             } else {
                 $action -= CRM_Core_Action::DISABLE;
             }
             $surveys[$sid]['action'] = CRM_Core_Action::formLink($this->actionLinks(), $action, array('id' => $sid), ts('more'), FALSE, 'survey.selector.row', 'Survey', $sid);
         }
     }
     $this->assign('surveys', $surveys);
     $this->assign('addSurveyUrl', CRM_Utils_System::url('civicrm/survey/add', 'reset=1&action=add'));
 }
예제 #14
0
 /**
 * takes an associative array and sends a thank you or email verification email
 *
 * @param array $params (reference ) an assoc array of name/value pairs
 *
 * @param $sendEmailMode
 *
 * @throws Exception
 * @return void
   @access public
 * @static
 */
 public static function sendEmail($params, $sendEmailMode)
 {
     /* sendEmailMode
      * CRM_Campaign_Form_Petition_Signature::EMAIL_THANK
      *   connected user via login/pwd - thank you
      *    or dedupe contact matched who doesn't have a tag CIVICRM_TAG_UNCONFIRMED - thank you
      *   or login using fb connect - thank you + click to add msg to fb wall
      *
      * CRM_Campaign_Form_Petition_Signature::EMAIL_CONFIRM
      *  send a confirmation request email
      */
     // check if the group defined by CIVICRM_PETITION_CONTACTS exists, else create it
     $petitionGroupName = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'petition_contacts', NULL, 'Petition Contacts');
     $dao = new CRM_Contact_DAO_Group();
     $dao->title = $petitionGroupName;
     if (!$dao->find(TRUE)) {
         $dao->is_active = 1;
         $dao->visibility = 'User and User Admin Only';
         $dao->save();
     }
     $group_id = $dao->id;
     // get petition info
     $petitionParams['id'] = $params['sid'];
     $petitionInfo = array();
     CRM_Campaign_BAO_Survey::retrieve($petitionParams, $petitionInfo);
     if (empty($petitionInfo)) {
         CRM_Core_Error::fatal('Petition doesn\'t exist.');
     }
     //get the default domain email address.
     list($domainEmailName, $domainEmailAddress) = CRM_Core_BAO_Domain::getNameAndEmail();
     $emailDomain = CRM_Core_BAO_MailSettings::defaultDomain();
     $toName = CRM_Contact_BAO_Contact::displayName($params['contactId']);
     $replyTo = "do-not-reply@{$emailDomain}";
     // set additional general message template params (custom tokens to use in email msg templates)
     // tokens then available in msg template as {$petition.title}, etc
     $petitionTokens['title'] = $petitionInfo['title'];
     $petitionTokens['petitionId'] = $params['sid'];
     $tplParams['petition'] = $petitionTokens;
     switch ($sendEmailMode) {
         case CRM_Campaign_Form_Petition_Signature::EMAIL_THANK:
             // add this contact to the CIVICRM_PETITION_CONTACTS group
             // Cannot pass parameter 1 by reference
             $p = array($params['contactId']);
             CRM_Contact_BAO_GroupContact::addContactsToGroup($p, $group_id, 'API');
             if ($params['email-Primary']) {
                 CRM_Core_BAO_MessageTemplate::sendTemplate(array('groupName' => 'msg_tpl_workflow_petition', 'valueName' => 'petition_sign', 'contactId' => $params['contactId'], 'tplParams' => $tplParams, 'from' => "\"{$domainEmailName}\" <{$domainEmailAddress}>", 'toName' => $toName, 'toEmail' => $params['email-Primary'], 'replyTo' => $replyTo, 'petitionId' => $params['sid'], 'petitionTitle' => $petitionInfo['title']));
             }
             break;
         case CRM_Campaign_Form_Petition_Signature::EMAIL_CONFIRM:
             // create mailing event subscription record for this contact
             // this will allow using a hash key to confirm email address by sending a url link
             $se = CRM_Mailing_Event_BAO_Subscribe::subscribe($group_id, $params['email-Primary'], $params['contactId'], 'profile');
             //    require_once 'CRM/Core/BAO/Domain.php';
             //    $domain = CRM_Core_BAO_Domain::getDomain();
             $config = CRM_Core_Config::singleton();
             $localpart = CRM_Core_BAO_MailSettings::defaultLocalpart();
             $replyTo = implode($config->verpSeparator, array($localpart . 'c', $se->contact_id, $se->id, $se->hash)) . "@{$emailDomain}";
             $confirmUrl = CRM_Utils_System::url('civicrm/petition/confirm', "reset=1&cid={$se->contact_id}&sid={$se->id}&h={$se->hash}&a={$params['activityId']}&p={$params['sid']}", TRUE);
             $confirmUrlPlainText = CRM_Utils_System::url('civicrm/petition/confirm', "reset=1&cid={$se->contact_id}&sid={$se->id}&h={$se->hash}&a={$params['activityId']}&p={$params['sid']}", TRUE, NULL, FALSE);
             // set email specific message template params and assign to tplParams
             $petitionTokens['confirmUrl'] = $confirmUrl;
             $petitionTokens['confirmUrlPlainText'] = $confirmUrlPlainText;
             $tplParams['petition'] = $petitionTokens;
             if ($params['email-Primary']) {
                 CRM_Core_BAO_MessageTemplate::sendTemplate(array('groupName' => 'msg_tpl_workflow_petition', 'valueName' => 'petition_confirmation_needed', 'contactId' => $params['contactId'], 'tplParams' => $tplParams, 'from' => "\"{$domainEmailName}\" <{$domainEmailAddress}>", 'toName' => $toName, 'toEmail' => $params['email-Primary'], 'replyTo' => $replyTo, 'petitionId' => $params['sid'], 'petitionTitle' => $petitionInfo['title'], 'confirmUrl' => $confirmUrl));
             }
             break;
     }
 }
예제 #15
0
 /**
  * Build all the data structures needed to build the form.
  */
 public function preProcess()
 {
     $this->_interviewToRelease = $this->get('interviewToRelease');
     if ($this->_interviewToRelease) {
         //user came from interview form.
         foreach (array('surveyId', 'contactIds', 'interviewerId') as $fld) {
             $this->{"_{$fld}"} = $this->get($fld);
         }
         if (!empty($this->_contactIds)) {
             $this->assign('totalSelectedContacts', count($this->_contactIds));
         }
     } else {
         parent::preProcess();
         //get the survey id from user submitted values.
         $this->_surveyId = CRM_Utils_Array::value('campaign_survey_id', $this->get('formValues'));
         $this->_interviewerId = CRM_Utils_Array::value('survey_interviewer_id', $this->get('formValues'));
     }
     if (!$this->_surveyId) {
         CRM_Core_Error::statusBounce(ts("Please search with 'Survey', to apply this action."));
     }
     if (!$this->_interviewerId) {
         CRM_Core_Error::statusBounce(ts('Missing Interviewer contact.'));
     }
     if (!is_array($this->_contactIds) || empty($this->_contactIds)) {
         CRM_Core_Error::statusBounce(ts('Could not find respondents to release.'));
     }
     $surveyDetails = array();
     $params = array('id' => $this->_surveyId);
     $this->_surveyDetails = CRM_Campaign_BAO_Survey::retrieve($params, $surveyDetails);
     $activityStatus = CRM_Core_PseudoConstant::activityStatus('name');
     $statusIds = array();
     foreach (array('Scheduled') as $name) {
         if ($statusId = array_search($name, $activityStatus)) {
             $statusIds[] = $statusId;
         }
     }
     //fetch the target survey activities.
     $this->_surveyActivities = CRM_Campaign_BAO_Survey::voterActivityDetails($this->_surveyId, $this->_contactIds, $this->_interviewerId, $statusIds);
     if (count($this->_surveyActivities) < 1) {
         CRM_Core_Error::statusBounce(ts('We could not found respondent for this survey to release.'));
     }
     $this->assign('surveyTitle', $surveyDetails['title']);
     //append breadcrumb to survey dashboard.
     if (CRM_Campaign_BAO_Campaign::accessCampaign()) {
         $url = CRM_Utils_System::url('civicrm/campaign', 'reset=1&subPage=survey');
         CRM_Utils_System::appendBreadCrumb(array(array('title' => ts('Survey(s)'), 'url' => $url)));
     }
     //set the title.
     CRM_Utils_System::setTitle(ts('Release Respondents'));
 }
예제 #16
0
 /**
  * Form submission of petition signature.
  */
 public function postProcess()
 {
     $tag_name = Civi::settings()->get('tag_unconfirmed');
     if ($tag_name) {
         // Check if contact 'email confirmed' tag exists, else create one
         // This should be in the petition module initialise code to create a default tag for this
         $tag_params['name'] = $tag_name;
         $tag_params['version'] = 3;
         $tag = civicrm_api('tag', 'get', $tag_params);
         if ($tag['count'] == 0) {
             //create tag
             $tag_params['description'] = $tag_name;
             $tag_params['is_reserved'] = 1;
             $tag_params['used_for'] = 'civicrm_contact';
             $tag = civicrm_api('tag', 'create', $tag_params);
         }
         $this->_tagId = $tag['id'];
     }
     // export the field values to be used for saving the profile form
     $params = $this->controller->exportValues($this->_name);
     $session = CRM_Core_Session::singleton();
     // format params
     $params['last_modified_id'] = $session->get('userID');
     $params['last_modified_date'] = date('YmdHis');
     if ($this->_action & CRM_Core_Action::ADD) {
         $params['created_id'] = $session->get('userID');
         $params['created_date'] = date('YmdHis');
     }
     if (isset($this->_surveyId)) {
         $params['sid'] = $this->_surveyId;
     }
     if (isset($this->_contactId)) {
         $params['contactId'] = $this->_contactId;
     }
     // if logged in user, skip dedupe
     if ($this->_loggedIn) {
         $ids[0] = $this->_contactId;
     } else {
         // dupeCheck - check if contact record already exists
         // code modified from api/v2/Contact.php-function civicrm_contact_check_params()
         $params['contact_type'] = $this->_ctype;
         //TODO - current dedupe finds soft deleted contacts - adding param is_deleted not working
         // ignore soft deleted contacts
         //$params['is_deleted'] = 0;
         $dedupeParams = CRM_Dedupe_Finder::formatParams($params, $params['contact_type']);
         $dedupeParams['check_permission'] = '';
         //dupesByParams($params, $ctype, $level = 'Unsupervised', $except = array())
         $ids = CRM_Dedupe_Finder::dupesByParams($dedupeParams, $params['contact_type']);
     }
     $petition_params['id'] = $this->_surveyId;
     $petition = array();
     CRM_Campaign_BAO_Survey::retrieve($petition_params, $petition);
     switch (count($ids)) {
         case 0:
             //no matching contacts - create a new contact
             // Add a source for this new contact
             $params['source'] = ts('Petition Signature') . ' ' . $this->petition['title'];
             if ($this->petition['bypass_confirm']) {
                 // send thank you email directly, bypassing confirmation
                 $this->_sendEmailMode = self::EMAIL_THANK;
                 // Set status for signature activity to completed
                 $params['statusId'] = 2;
             } else {
                 $this->_sendEmailMode = self::EMAIL_CONFIRM;
                 // Set status for signature activity to scheduled until email is verified
                 $params['statusId'] = 1;
             }
             break;
         case 1:
             $this->_contactId = $params['contactId'] = $ids[0];
             // check if user has already signed this petition - redirects to Thank You if true
             $this->redirectIfSigned($params);
             if ($this->petition['bypass_confirm']) {
                 // send thank you email directly, bypassing confirmation
                 $this->_sendEmailMode = self::EMAIL_THANK;
                 // Set status for signature activity to completed
                 $params['statusId'] = 2;
                 break;
             }
             // dedupe matched single contact, check for 'unconfirmed' tag
             if ($tag_name) {
                 $tag = new CRM_Core_DAO_EntityTag();
                 $tag->entity_id = $this->_contactId;
                 $tag->tag_id = $this->_tagId;
                 if (!$tag->find()) {
                     // send thank you email directly, the user is known and validated
                     $this->_sendEmailMode = self::EMAIL_THANK;
                     // Set status for signature activity to completed
                     $params['statusId'] = 2;
                 } else {
                     // send email verification email
                     $this->_sendEmailMode = self::EMAIL_CONFIRM;
                     // Set status for signature activity to scheduled until email is verified
                     $params['statusId'] = 1;
                 }
             }
             break;
         default:
             // more than 1 matching contact
             // for time being, take the first matching contact (not sure that's the best strategy, but better than creating another duplicate)
             $this->_contactId = $params['contactId'] = $ids[0];
             // check if user has already signed this petition - redirects to Thank You if true
             $this->redirectIfSigned($params);
             if ($this->petition['bypass_confirm']) {
                 // send thank you email directly, bypassing confirmation
                 $this->_sendEmailMode = self::EMAIL_THANK;
                 // Set status for signature activity to completed
                 $params['statusId'] = 2;
                 break;
             }
             if ($tag_name) {
                 $tag = new CRM_Core_DAO_EntityTag();
                 $tag->entity_id = $this->_contactId;
                 $tag->tag_id = $this->_tagId;
                 if (!$tag->find()) {
                     // send thank you email
                     $this->_sendEmailMode = self::EMAIL_THANK;
                     // Set status for signature activity to completed
                     $params['statusId'] = 2;
                 } else {
                     // send email verification email
                     $this->_sendEmailMode = self::EMAIL_CONFIRM;
                     // Set status for signature activity to scheduled until email is verified
                     $params['statusId'] = 1;
                 }
             }
             break;
     }
     $transaction = new CRM_Core_Transaction();
     // CRM-17029 - get the add_to_group_id from the _contactProfileFields array.
     // There's a much more elegant solution with
     // array_values($this->_contactProfileFields)[0] but it's PHP 5.4+ only.
     $slice = array_slice($this->_contactProfileFields, 0, 1);
     $firstField = array_shift($slice);
     $addToGroupID = isset($firstField['add_to_group_id']) ? $firstField['add_to_group_id'] : NULL;
     $this->_contactId = CRM_Contact_BAO_Contact::createProfileContact($params, $this->_contactProfileFields, $this->_contactId, $addToGroupID, $this->_contactProfileId, $this->_ctype, TRUE);
     // get additional custom activity profile field data
     // to save with new signature activity record
     $surveyInfo = $this->bao->getSurveyInfo($this->_surveyId);
     $customActivityFields = CRM_Core_BAO_CustomField::getFields('Activity', FALSE, FALSE, $surveyInfo['activity_type_id']);
     $customActivityFields = CRM_Utils_Array::crmArrayMerge($customActivityFields, CRM_Core_BAO_CustomField::getFields('Activity', FALSE, FALSE, NULL, NULL, TRUE));
     $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, NULL, 'Activity');
     // create the signature activity record
     $params['contactId'] = $this->_contactId;
     $params['activity_campaign_id'] = CRM_Utils_Array::value('campaign_id', $this->petition);
     $result = $this->bao->createSignature($params);
     // send thank you or email verification emails
     // if logged in using Facebook connect and email on form matches Fb email,
     // no need for email confirmation, send thank you email
     if ($this->forceEmailConfirmed['flag'] && $this->forceEmailConfirmed['email'] == $params['email-Primary']) {
         $this->_sendEmailMode = self::EMAIL_THANK;
     }
     switch ($this->_sendEmailMode) {
         case self::EMAIL_THANK:
             // mark the signature activity as completed and set confirmed cookie
             $this->bao->confirmSignature($result->id, $this->_contactId, $this->_surveyId);
             break;
         case self::EMAIL_CONFIRM:
             // set 'Unconfirmed' tag for this new contact
             if ($tag_name) {
                 unset($tag_params);
                 $tag_params['contact_id'] = $this->_contactId;
                 $tag_params['tag_id'] = $this->_tagId;
                 $tag_params['version'] = 3;
                 $tag_value = civicrm_api('entity_tag', 'create', $tag_params);
             }
             break;
     }
     //send email
     $params['activityId'] = $result->id;
     $params['tagId'] = $this->_tagId;
     $transaction->commit();
     $this->bao->sendEmail($params, $this->_sendEmailMode);
     if ($result) {
         // call the hook before we redirect
         $this->postProcessHook();
         // set the template to thank you
         $url = CRM_Utils_System::url('civicrm/petition/thankyou', 'pid=' . $this->_surveyId . '&id=' . $this->_sendEmailMode . '&reset=1');
         CRM_Utils_System::redirect($url);
     }
 }
예제 #17
0
 /**
  * Process the form.
  */
 public function postProcess()
 {
     // store the submitted values in an array
     $status = '';
     $params = $this->controller->exportValues($this->_name);
     $params['id'] = $this->_surveyId;
     $updateResultSet = FALSE;
     $resultSetOptGrpId = NULL;
     if (CRM_Utils_Array::value('option_type', $params) == 2 && !empty($params['option_group_id'])) {
         $updateResultSet = TRUE;
         $resultSetOptGrpId = $params['option_group_id'];
     }
     $recontactInterval = array();
     if ($updateResultSet) {
         $optionValue = new CRM_Core_DAO_OptionValue();
         $optionValue->option_group_id = $resultSetOptGrpId;
         $optionValue->delete();
         $params['result_id'] = $resultSetOptGrpId;
     } else {
         $opGroupName = 'civicrm_survey_' . rand(10, 1000) . '_' . date('YmdHis');
         $optionGroup = new CRM_Core_DAO_OptionGroup();
         $optionGroup->name = $opGroupName;
         $optionGroup->title = $this->_values['title'] . ' Result Set';
         $optionGroup->is_active = 1;
         $optionGroup->save();
         $params['result_id'] = $optionGroup->id;
     }
     foreach ($params['option_value'] as $k => $v) {
         if (strlen(trim($v))) {
             $optionValue = new CRM_Core_DAO_OptionValue();
             $optionValue->option_group_id = $params['result_id'];
             $optionValue->label = $params['option_label'][$k];
             $optionValue->name = CRM_Utils_String::titleToVar($params['option_label'][$k]);
             $optionValue->value = trim($v);
             $optionValue->weight = $params['option_weight'][$k];
             $optionValue->is_active = 1;
             if (!empty($params['default_option']) && $params['default_option'] == $k) {
                 $optionValue->is_default = 1;
             }
             $optionValue->save();
             // using is_numeric since 0 is a valid value for option_interval
             if (is_numeric($params['option_interval'][$k])) {
                 $recontactInterval[$optionValue->label] = $params['option_interval'][$k];
             }
         }
     }
     $params['recontact_interval'] = serialize($recontactInterval);
     $survey = CRM_Campaign_BAO_Survey::create($params);
     // create report if required.
     if (!$this->_reportId && $survey->id && !empty($params['create_report'])) {
         $activityStatus = CRM_Core_PseudoConstant::activityStatus('name');
         $activityStatus = array_flip($activityStatus);
         $this->_params = array('name' => "survey_{$survey->id}", 'title' => $params['report_title'] ? $params['report_title'] : $this->_values['title'], 'status_id_op' => 'eq', 'status_id_value' => $activityStatus['Scheduled'], 'survey_id_value' => array($survey->id), 'description' => ts('Detailed report for canvassing, phone-banking, walk lists or other surveys.'));
         //Default value of order by
         $this->_params['order_bys'] = array(1 => array('column' => 'sort_name', 'order' => 'ASC'));
         // for WalkList or default
         $displayFields = array('id', 'sort_name', 'result', 'street_number', 'street_name', 'street_unit', 'survey_response');
         if (CRM_Core_OptionGroup::getValue('activity_type', 'WalkList') == $this->_values['activity_type_id']) {
             $this->_params['order_bys'] = array(1 => array('column' => 'street_name', 'order' => 'ASC'), 2 => array('column' => 'street_number_odd_even', 'order' => 'ASC'), 3 => array('column' => 'street_number', 'order' => 'ASC'), 4 => array('column' => 'sort_name', 'order' => 'ASC'));
         } elseif (CRM_Core_OptionGroup::getValue('activity_type', 'PhoneBank') == $this->_values['activity_type_id']) {
             array_push($displayFields, 'phone');
         } elseif (CRM_Core_OptionGroup::getValue('activity_type', 'Survey') == $this->_values['activity_type_id'] || CRM_Core_OptionGroup::getValue('activity_type', 'Canvass') == $this->_values['activity_type_id']) {
             array_push($displayFields, 'phone', 'city', 'state_province_id', 'postal_code', 'email');
         }
         foreach ($displayFields as $key) {
             $this->_params['fields'][$key] = 1;
         }
         $this->_createNew = TRUE;
         $this->_id = CRM_Report_Utils_Report::getInstanceIDForValue('survey/detail');
         CRM_Report_Form_Instance::postProcess($this, FALSE);
         $query = "SELECT MAX(id) FROM civicrm_report_instance WHERE name = %1";
         $reportID = CRM_Core_DAO::singleValueQuery($query, array(1 => array("survey_{$survey->id}", 'String')));
         if ($reportID) {
             $url = CRM_Utils_System::url("civicrm/report/instance/{$reportID}", 'reset=1');
             $status = ts("A Survey Detail Report <a href='%1'>%2</a> has been created.", array(1 => $url, 2 => $this->_params['title']));
         }
     }
     if ($status) {
         // reset status as we don't want status set by Instance::postProcess
         $session = CRM_Core_Session::singleton();
         $session->getStatus(TRUE);
         // set new status
         CRM_Core_Session::setStatus($status, ts('Saved'), 'success');
     }
     parent::endPostProcess();
 }
예제 #18
0
 /**
  * This function uses the deprecated v1 datatable api and needs updating. See CRM-16353.
  * @deprecated
  */
 public function surveyList()
 {
     //get the search criteria params.
     $searchCriteria = CRM_Utils_Request::retrieve('searchCriteria', 'String', CRM_Core_DAO::$_nullObject, FALSE, NULL, 'POST');
     $searchParams = explode(',', $searchCriteria);
     $params = $searchRows = array();
     foreach ($searchParams as $param) {
         if (!empty($_POST[$param])) {
             $params[$param] = $_POST[$param];
         }
     }
     //this is sequence columns on datatable.
     $selectorCols = array('id', 'title', 'campaign_id', 'campaign', 'activity_type_id', 'activity_type', 'release_frequency', 'default_number_of_contacts', 'max_number_of_contacts', 'is_default', 'is_active', 'isActive', 'result_id', 'action', 'voterLinks');
     // get the data table params.
     $dataTableParams = array('sEcho' => array('name' => 'sEcho', 'type' => 'Integer', 'default' => 0), 'offset' => array('name' => 'iDisplayStart', 'type' => 'Integer', 'default' => 0), 'rowCount' => array('name' => 'iDisplayLength', 'type' => 'Integer', 'default' => 25), 'sort' => array('name' => 'iSortCol_0', 'type' => 'Integer', 'default' => 'created_date'), 'sortOrder' => array('name' => 'sSortDir_0', 'type' => 'String', 'default' => 'desc'));
     foreach ($dataTableParams as $pName => $pValues) {
         ${$pName} = $pValues['default'];
         if (!empty($_POST[$pValues['name']])) {
             ${$pName} = CRM_Utils_Type::escape($_POST[$pValues['name']], $pValues['type']);
             if ($pName == 'sort') {
                 ${$pName} = $selectorCols[${$pName}];
             }
         }
     }
     foreach (array('sort', 'offset', 'rowCount', 'sortOrder') as $sortParam) {
         $params[$sortParam] = ${$sortParam};
     }
     $surveys = CRM_Campaign_Page_DashBoard::getSurveySummary($params);
     $searchCount = CRM_Campaign_BAO_Survey::getSurveySummary($params, TRUE);
     $iTotal = $searchCount;
     if ($searchCount > 0) {
         if ($searchCount < $offset) {
             $offset = 0;
         }
         foreach ($surveys as $surveyID => $values) {
             foreach ($selectorCols as $col) {
                 $searchRows[$surveyID][$col] = CRM_Utils_Array::value($col, $values);
             }
         }
     }
     $selectorElements = $selectorCols;
     $iFilteredTotal = $iTotal;
     CRM_Utils_System::setHttpHeader('Content-Type', 'application/json');
     echo CRM_Utils_JSON::encodeDataTableSelector($searchRows, $sEcho, $iTotal, $iFilteredTotal, $selectorElements);
     CRM_Utils_System::civiExit();
 }
예제 #19
0
 /**
  * add all the elements shared between case activity search  and advanaced search
  *
  * @access public 
  * @return void
  * @static
  */
 static function buildSearchForm(&$form)
 {
     $activityOptions = CRM_Core_PseudoConstant::activityType(true, true, false, 'label', true);
     asort($activityOptions);
     foreach ($activityOptions as $activityID => $activity) {
         $form->_activityElement =& $form->addElement('checkbox', "activity_type_id[{$activityID}]", null, $activity, array('onClick' => 'showCustomData( this.id );'));
     }
     $form->addDate('activity_date_low', ts('Activity Dates - From'), false, array('formatType' => 'searchDate'));
     $form->addDate('activity_date_high', ts('To'), false, array('formatType' => 'searchDate'));
     $activityRoles = array(1 => ts('Created by'), 2 => ts('Assigned to'));
     $form->addRadio('activity_role', null, $activityRoles, null, '<br />');
     $form->setDefaults(array('activity_role' => 1));
     $form->addElement('text', 'activity_contact_name', ts('Contact Name'), CRM_Core_DAO::getAttribute('CRM_Contact_DAO_Contact', 'sort_name'));
     $activityStatus = CRM_Core_PseudoConstant::activityStatus();
     foreach ($activityStatus as $activityStatusID => $activityStatusName) {
         $activity_status[] = HTML_QuickForm::createElement('checkbox', $activityStatusID, null, $activityStatusName);
     }
     $form->addGroup($activity_status, 'activity_status', ts('Activity Status'));
     $form->setDefaults(array('activity_status[1]' => 1, 'activity_status[2]' => 1));
     $form->addElement('text', 'activity_subject', ts('Subject'), CRM_Core_DAO::getAttribute('CRM_Contact_DAO_Contact', 'sort_name'));
     $form->addElement('checkbox', 'activity_test', ts('Find Test Activities?'));
     require_once 'CRM/Core/BAO/Tag.php';
     $activity_tags = CRM_Core_BAO_Tag::getTags('civicrm_activity');
     if ($activity_tags) {
         foreach ($activity_tags as $tagID => $tagName) {
             $form->_tagElement =& $form->addElement('checkbox', "activity_tags[{$tagID}]", null, $tagName);
         }
     }
     require_once 'CRM/Campaign/BAO/Survey.php';
     $surveys = array('' => ts('- none -')) + CRM_Campaign_BAO_Survey::getSurveyList();
     $form->add('select', 'activity_survey_id', ts('Survey'), $surveys, false);
     require_once 'CRM/Core/BAO/CustomGroup.php';
     $extends = array('Activity');
     $groupDetails = CRM_Core_BAO_CustomGroup::getGroupDetail(null, true, $extends);
     if ($groupDetails) {
         require_once 'CRM/Core/BAO/CustomField.php';
         $form->assign('activityGroupTree', $groupDetails);
         foreach ($groupDetails as $group) {
             foreach ($group['fields'] as $field) {
                 $fieldId = $field['id'];
                 $elementName = 'custom_' . $fieldId;
                 CRM_Core_BAO_CustomField::addQuickFormElement($form, $elementName, $fieldId, false, false, true);
             }
         }
     }
 }
예제 #20
0
 public function validateIds()
 {
     $errorMessages = array();
     //check for required permissions.
     if (!CRM_Core_Permission::check('manage campaign') && !CRM_Core_Permission::check('administer CiviCampaign') && !CRM_Core_Permission::check("{$this->_searchVoterFor} campaign contacts")) {
         $errorMessages[] = ts('You are not authorized to access this page.');
     }
     $surveys = CRM_Campaign_BAO_Survey::getSurveys();
     if (empty($surveys)) {
         $errorMessages[] = ts("Oops. It looks like no surveys have been created. <a href='%1'>Click here to create a new survey.</a>", array(1 => CRM_Utils_System::url('civicrm/survey/add', 'reset=1&action=add')));
     }
     if ($this->_force && !$this->_surveyId) {
         $errorMessages[] = ts('Could not find Survey.');
     }
     $this->assign('errorMessages', empty($errorMessages) ? FALSE : $errorMessages);
 }
예제 #21
0
/**
 * This api checks and updates the status of all survey respondents.
 *
 * @param array $params
 *   (reference ) input parameters.
 *
 * @return bool
 *   true if success, else false
 */
function civicrm_api3_job_process_respondent($params)
{
    $result = CRM_Campaign_BAO_Survey::releaseRespondent($params);
    if ($result['is_error'] == 0) {
        return civicrm_api3_create_success();
    } else {
        return civicrm_api3_create_error($result['messages']);
    }
}
예제 #22
0
 /**
  * @param array $params
  *
  * @return array
  */
 public static function getPetitionSummary($params = array())
 {
     $config = CRM_Core_Config::singleton();
     $petitionsData = array();
     //get the petitions.
     $petitions = CRM_Campaign_BAO_Petition::getPetitionSummary($params);
     if (!empty($petitions)) {
         $campaigns = CRM_Campaign_BAO_Campaign::getCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
         $petitionType = CRM_Campaign_BAO_Survey::getSurveyActivityType('label', TRUE);
         foreach ($petitions as $pid => $petition) {
             $petitionsData[$pid] = $petition;
             $camapignId = CRM_Utils_Array::value('campaign_id', $petition);
             $petitionsData[$pid]['campaign'] = CRM_Utils_Array::value($camapignId, $campaigns);
             $petitionsData[$pid]['activity_type'] = $petitionType[$petition['activity_type_id']];
             $action = array_sum(array_keys(self::petitionActionLinks()));
             if ($petition['is_active']) {
                 $action -= CRM_Core_Action::ENABLE;
             } else {
                 $action -= CRM_Core_Action::DISABLE;
             }
             $isActive = ts('No');
             if ($petitionsData[$pid]['is_active']) {
                 $isActive = ts('Yes');
             }
             $petitionsData[$pid]['isActive'] = $isActive;
             $isDefault = NULL;
             if ($petitionsData[$pid]['is_default']) {
                 $isDefault = '<img src="' . $config->resourceBase . 'i/check.gif" alt="' . ts('Default') . '" />';
             }
             $petitionsData[$pid]['is_default'] = $isDefault;
             $petitionsData[$pid]['action'] = CRM_Core_Action::formLink(self::petitionActionLinks(), $action, array('id' => $pid), ts('more'), FALSE, 'petition.dashboard.row', 'Petition', $pid);
         }
     }
     return $petitionsData;
 }
예제 #23
0
 /**
  * Process the form
  * 
  * @param null
  * 
  * @return void
  * @access public
  */
 public function postProcess()
 {
     // store the submitted values in an array
     $params = $this->controller->exportValues($this->_name);
     $session = CRM_Core_Session::singleton();
     $params['last_modified_id'] = $session->get('userID');
     $params['last_modified_date'] = date('YmdHis');
     require_once 'CRM/Core/BAO/OptionValue.php';
     require_once 'CRM/Core/BAO/OptionGroup.php';
     $updateResultSet = false;
     if (CRM_Utils_Array::value('option_type', $params) == 2 && CRM_Utils_Array::value('option_group_id', $params)) {
         if ($params['option_group_id'] == CRM_Utils_Array::value('result_id', $this->_values)) {
             $updateResultSet = true;
         }
     }
     if ($this->_surveyId) {
         if ($this->_action & CRM_Core_Action::DELETE) {
             CRM_Campaign_BAO_Survey::del($this->_surveyId);
             CRM_Core_Session::setStatus(ts(' Survey has been deleted.'));
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/campaign', 'reset=1&subPage=survey'));
             return;
         }
         $params['id'] = $this->_surveyId;
     } else {
         $params['created_id'] = $session->get('userID');
         $params['created_date'] = date('YmdHis');
     }
     $params['is_active'] = CRM_Utils_Array::value('is_active', $params, 0);
     $params['is_default'] = CRM_Utils_Array::value('is_default', $params, 0);
     $recontactInterval = array();
     if ($updateResultSet) {
         $optionValue = new CRM_Core_DAO_OptionValue();
         $optionValue->option_group_id = $this->_values['result_id'];
         $optionValue->delete();
         $params['result_id'] = $this->_values['result_id'];
     } else {
         $opGroupName = 'civicrm_survey_' . rand(10, 1000) . '_' . date('YmdHis');
         $optionGroup = new CRM_Core_DAO_OptionGroup();
         $optionGroup->name = $opGroupName;
         $optionGroup->label = $params['title'] . ' Response Set';
         $optionGroup->is_active = 1;
         $optionGroup->save();
         $params['result_id'] = $optionGroup->id;
     }
     foreach ($params['option_value'] as $k => $v) {
         if (strlen(trim($v))) {
             $optionValue = new CRM_Core_DAO_OptionValue();
             $optionValue->option_group_id = $params['result_id'];
             $optionValue->label = $params['option_label'][$k];
             $optionValue->name = CRM_Utils_String::titleToVar($params['option_label'][$k]);
             $optionValue->value = trim($v);
             $optionValue->weight = $params['option_weight'][$k];
             $optionValue->is_active = 1;
             if (CRM_Utils_Array::value('default_option', $params) && $params['default_option'] == $k) {
                 $optionValue->is_default = 1;
             }
             $optionValue->save();
             if (CRM_Utils_Array::value($k, $params['option_interval'])) {
                 $recontactInterval[$optionValue->label] = $params['option_interval'][$k];
             }
         }
     }
     $params['recontact_interval'] = serialize($recontactInterval);
     $surveyId = CRM_Campaign_BAO_Survey::create($params);
     if (CRM_Utils_Array::value('result_id', $this->_values) && !$updateResultSet) {
         $query = "SELECT COUNT(*) FROM civicrm_survey WHERE result_id = %1";
         $countSurvey = CRM_Core_DAO::singleValueQuery($query, array(1 => array($this->_values['result_id'], 'Integer')));
         // delete option group if no any survey is using it.
         if (!($countSurvey >= 1)) {
             CRM_Core_BAO_OptionGroup::del($this->_values['result_id']);
         }
     }
     require_once 'CRM/Core/BAO/UFJoin.php';
     // also update the ProfileModule tables
     $ufJoinParams = array('is_active' => 1, 'module' => 'CiviCampaign', 'entity_table' => 'civicrm_survey', 'entity_id' => $surveyId->id);
     // first delete all past entries
     if ($this->_surveyId) {
         CRM_Core_BAO_UFJoin::deleteAll($ufJoinParams);
     }
     if (CRM_Utils_Array::value('profile_id', $params)) {
         $ufJoinParams['weight'] = 1;
         $ufJoinParams['uf_group_id'] = $params['profile_id'];
         CRM_Core_BAO_UFJoin::create($ufJoinParams);
     }
     if (!is_a($surveyId, 'CRM_Core_Error')) {
         CRM_Core_Session::setStatus(ts('Survey %1 has been saved.', array(1 => $params['title'])));
     }
     if ($this->_context == 'dialog') {
         $returnArray = array('returnSuccess' => true);
         echo json_encode($returnArray);
         CRM_Utils_System::civiExit();
     }
     $buttonName = $this->controller->getButtonName();
     if ($buttonName == $this->getButtonName('next', 'new')) {
         CRM_Core_Session::setStatus(ts(' You can add another Survey.'));
         $session->replaceUserContext(CRM_Utils_System::url('civicrm/survey/add', 'reset=1&action=add'));
     } else {
         $session->replaceUserContext(CRM_Utils_System::url('civicrm/campaign', 'reset=1&subPage=survey'));
     }
 }
예제 #24
0
 /**
  * Add all the elements shared between case activity search and advanced search.
  *
  *
  * @param CRM_Core_Form $form
  * @return void
  */
 public static function buildSearchForm(&$form)
 {
     $activityOptions = CRM_Core_PseudoConstant::activityType(TRUE, TRUE, FALSE, 'label', TRUE);
     $form->addSelect('activity_type_id', array('entity' => 'activity', 'label' => 'Activity Type(s)', 'multiple' => 'multiple', 'option_url' => NULL, 'placeholder' => ts('- any -')));
     CRM_Core_Form_Date::buildDateRange($form, 'activity_date', 1, '_low', '_high', ts('From'), FALSE, FALSE);
     $followUpActivity = array(1 => ts('Yes'), 2 => ts('No'));
     $form->addRadio('parent_id', NULL, $followUpActivity, array('allowClear' => TRUE));
     $form->addRadio('followup_parent_id', NULL, $followUpActivity, array('allowClear' => TRUE));
     $activityRoles = array(3 => ts('With'), 2 => ts('Assigned to'), 1 => ts('Added by'));
     $form->addRadio('activity_role', NULL, $activityRoles, array('allowClear' => TRUE));
     $form->setDefaults(array('activity_role' => 3));
     $activityStatus = CRM_Core_PseudoConstant::get('CRM_Activity_DAO_Activity', 'status_id', array('flip' => 1, 'labelColumn' => 'name'));
     $form->addSelect('status_id', array('entity' => 'activity', 'multiple' => 'multiple', 'option_url' => NULL, 'placeholder' => ts('- any -')));
     $form->setDefaults(array('status_id' => array($activityStatus['Completed'], $activityStatus['Scheduled'])));
     $form->addElement('text', 'activity_subject', ts('Subject'), CRM_Core_DAO::getAttribute('CRM_Contact_DAO_Contact', 'sort_name'));
     $form->addYesNo('activity_test', ts('Activity is a Test?'));
     $activity_tags = CRM_Core_BAO_Tag::getTags('civicrm_activity');
     if ($activity_tags) {
         foreach ($activity_tags as $tagID => $tagName) {
             $form->_tagElement =& $form->addElement('checkbox', "activity_tags[{$tagID}]", NULL, $tagName);
         }
     }
     $parentNames = CRM_Core_BAO_Tag::getTagSet('civicrm_activity');
     CRM_Core_Form_Tag::buildQuickForm($form, $parentNames, 'civicrm_activity', NULL, TRUE, TRUE);
     $surveys = CRM_Campaign_BAO_Survey::getSurveys(TRUE, FALSE, FALSE, TRUE);
     if ($surveys) {
         $form->add('select', 'activity_survey_id', ts('Survey / Petition'), array('' => ts('- none -')) + $surveys, FALSE, array('class' => 'crm-select2'));
     }
     $extends = array('Activity');
     $groupDetails = CRM_Core_BAO_CustomGroup::getGroupDetail(NULL, TRUE, $extends);
     if ($groupDetails) {
         $form->assign('activityGroupTree', $groupDetails);
         foreach ($groupDetails as $group) {
             foreach ($group['fields'] as $field) {
                 $fieldId = $field['id'];
                 $elementName = 'custom_' . $fieldId;
                 CRM_Core_BAO_CustomField::addQuickFormElement($form, $elementName, $fieldId, FALSE, FALSE, TRUE);
             }
         }
     }
     CRM_Campaign_BAO_Campaign::addCampaignInComponentSearch($form, 'activity_campaign_id');
     //add engagement level CRM-7775
     $buildEngagementLevel = FALSE;
     $buildSurveyResult = FALSE;
     if (CRM_Campaign_BAO_Campaign::isCampaignEnable() && CRM_Campaign_BAO_Campaign::accessCampaign()) {
         $buildEngagementLevel = TRUE;
         $form->addSelect('activity_engagement_level', array('entity' => 'activity', 'context' => 'search'));
         // Add survey result field.
         $optionGroups = CRM_Campaign_BAO_Survey::getResultSets('name');
         $resultOptions = array();
         foreach ($optionGroups as $gid => $name) {
             if ($name) {
                 $value = array();
                 $value = CRM_Core_OptionGroup::values($name);
                 if (!empty($value)) {
                     while (list($k, $v) = each($value)) {
                         $resultOptions[$v] = $v;
                     }
                 }
             }
         }
         // If no survey result options have been created, don't build
         // the field to avoid clutter.
         if (count($resultOptions) > 0) {
             $buildSurveyResult = TRUE;
             asort($resultOptions);
             $form->add('select', 'activity_result', ts("Survey Result"), $resultOptions, FALSE, array('id' => 'activity_result', 'multiple' => 'multiple', 'class' => 'crm-select2'));
         }
     }
     $form->assign('buildEngagementLevel', $buildEngagementLevel);
     $form->assign('buildSurveyResult', $buildSurveyResult);
     $form->setDefaults(array('activity_test' => 0));
 }
예제 #25
0
 static function formRule($params, $rules, &$form)
 {
     $errors = array();
     $surveyDetails = array();
     if (CRM_Utils_Array::value('survey_id', $params)) {
         $form->_surveyId = $params['survey_id'];
         $params = array('id' => $form->_surveyId);
         $form->_surveyDetails = CRM_Campaign_BAO_Survey::retrieve($params, $surveyDetails);
         $numVoters = CRM_Core_DAO::singleValueQuery("SELECT COUNT(*) FROM " . self::ACTIVITY_SURVEY_DETAIL_TABLE . " WHERE status_id = 'H' AND survey_id = %1 ", array(1 => array($form->_surveyId, 'Integer')));
         $form->_numVoters = isset($numVoters) ? $numVoters : 0;
         if (CRM_Utils_Array::value('max_number_of_contacts', $surveyDetails) && $form->_numVoters && $surveyDetails['max_number_of_contacts'] <= $form->_numVoters) {
             $errors['survey_id'] = ts("Voter Reservation is full for this survey.");
         } else {
             if (CRM_Utils_Array::value('default_number_of_contacts', $surveyDetails)) {
                 if (count($form->_contactIds) > $surveyDetails['default_number_of_contacts']) {
                     $errors['survey_id'] = ts("You can select maximum %1 contact(s) at a time for voter reservation of this survey.", array(1 => $surveyDetails['default_number_of_contacts']));
                 }
             }
         }
     }
     return $errors;
 }
예제 #26
0
 /**
  * @param array $params
  *
  * @return array
  */
 public static function voterClause($params)
 {
     $voterClause = array();
     $fromClause = $whereClause = NULL;
     if (!is_array($params) || empty($params)) {
         return $voterClause;
     }
     $surveyId = CRM_Utils_Array::value('campaign_survey_id', $params);
     $searchVoterFor = CRM_Utils_Array::value('campaign_search_voter_for', $params);
     //get the survey activities.
     $activityStatus = CRM_Core_PseudoConstant::activityStatus('name');
     $status = array('Scheduled');
     if ($searchVoterFor == 'reserve') {
         $status[] = 'Completed';
     }
     $completedStatusId = NULL;
     foreach ($status as $name) {
         if ($statusId = array_search($name, $activityStatus)) {
             $statusIds[] = $statusId;
             if ($name == 'Completed') {
                 $completedStatusId = $statusId;
             }
         }
     }
     $voterActValues = CRM_Campaign_BAO_Survey::getSurveyVoterInfo($surveyId, NULL, $statusIds);
     if (!empty($voterActValues)) {
         $operator = 'IN';
         $voterIds = array_keys($voterActValues);
         if ($searchVoterFor == 'reserve') {
             $operator = 'NOT IN';
             //filter out recontact survey contacts.
             $recontactInterval = CRM_Core_DAO::getFieldValue('CRM_Campaign_DAO_Survey', $surveyId, 'recontact_interval');
             $recontactInterval = unserialize($recontactInterval);
             if ($surveyId && is_array($recontactInterval) && !empty($recontactInterval)) {
                 $voterIds = array();
                 foreach ($voterActValues as $values) {
                     $numOfDays = CRM_Utils_Array::value($values['result'], $recontactInterval);
                     if ($numOfDays && $values['status_id'] == $completedStatusId) {
                         $recontactIntSeconds = $numOfDays * 24 * 3600;
                         $actDateTimeSeconds = CRM_Utils_Date::unixTime($values['activity_date_time']);
                         $totalSeconds = $recontactIntSeconds + $actDateTimeSeconds;
                         //don't consider completed survey activity
                         //unless it fulfill recontact interval criteria.
                         if ($totalSeconds <= time()) {
                             continue;
                         }
                     }
                     $voterIds[$values['voter_id']] = $values['voter_id'];
                 }
             }
         }
         //lets dump these ids in tmp table and
         //use appropriate join depend on operator.
         if (!empty($voterIds)) {
             $voterIdCount = count($voterIds);
             //create temporary table to store voter ids.
             $tempTableName = CRM_Core_DAO::createTempTableName('civicrm_survey_respondent');
             CRM_Core_DAO::executeQuery("DROP TEMPORARY TABLE IF EXISTS {$tempTableName}");
             $query = "\n     CREATE TEMPORARY TABLE {$tempTableName} (\n            id int unsigned NOT NULL AUTO_INCREMENT,\n            survey_contact_id int unsigned NOT NULL,\n  PRIMARY KEY ( id )\n);\n";
             CRM_Core_DAO::executeQuery($query);
             $batch = 100;
             $insertedCount = 0;
             do {
                 $processIds = $voterIds;
                 $insertIds = array_splice($processIds, $insertedCount, $batch);
                 if (!empty($insertIds)) {
                     $insertSQL = "INSERT IGNORE INTO {$tempTableName}( survey_contact_id )\n                     VALUES (" . implode('),(', $insertIds) . ');';
                     CRM_Core_DAO::executeQuery($insertSQL);
                 }
                 $insertedCount += $batch;
             } while ($insertedCount < $voterIdCount);
             if ($operator == 'IN') {
                 $fromClause = " INNER JOIN {$tempTableName} ON ( {$tempTableName}.survey_contact_id = contact_a.id )";
             } else {
                 $fromClause = " LEFT JOIN {$tempTableName} ON ( {$tempTableName}.survey_contact_id = contact_a.id )";
                 $whereClause = "( {$tempTableName}.survey_contact_id IS NULL )";
             }
         }
     }
     $voterClause = array('fromClause' => $fromClause, 'whereClause' => $whereClause);
     return $voterClause;
 }
예제 #27
0
 public function buildQuickForm()
 {
     if ($this->_action & (CRM_Core_Action::DELETE | CRM_Core_Action::RENEW)) {
         //enable form element (ActivityLinks sets this true)
         $this->assign('suppressForm', FALSE);
         $button = ts('Delete');
         if ($this->_action & CRM_Core_Action::RENEW) {
             $button = ts('Restore');
         }
         $this->addButtons(array(array('type' => 'next', 'name' => $button, 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;', 'isDefault' => TRUE), array('type' => 'cancel', 'name' => ts('Cancel'))));
         return;
     }
     // Build other activity links.
     CRM_Activity_Form_ActivityLinks::commonBuildQuickForm($this);
     // Enable form element (ActivityLinks sets this true).
     $this->assign('suppressForm', FALSE);
     $element =& $this->add('select', 'activity_type_id', ts('Activity Type'), array('' => '- ' . ts('select') . ' -') + $this->_fields['followup_activity_type_id']['attributes'], FALSE, array('onchange' => "CRM.buildCustomData( 'Activity', this.value );", 'class' => 'crm-select2 required'));
     // Freeze for update mode.
     if ($this->_action & CRM_Core_Action::UPDATE) {
         $element->freeze();
     }
     // Call to RecurringEntity buildQuickForm for add/update mode.
     if ($this->_action & (CRM_Core_Action::UPDATE | CRM_Core_Action::ADD)) {
         CRM_Core_Form_RecurringEntity::buildQuickForm($this);
     }
     foreach ($this->_fields as $field => $values) {
         if (!empty($this->_fields[$field])) {
             $attribute = CRM_Utils_Array::value('attributes', $values);
             $required = !empty($values['required']);
             if ($values['type'] == 'select' && empty($attribute)) {
                 $this->addSelect($field, array('entity' => 'activity'), $required);
             } elseif ($values['type'] == 'entityRef') {
                 $this->addEntityRef($field, $values['label'], $attribute, $required);
             } else {
                 $this->add($values['type'], $field, $values['label'], $attribute, $required, CRM_Utils_Array::value('extra', $values));
             }
         }
     }
     // CRM-7362 --add campaigns.
     CRM_Campaign_BAO_Campaign::addCampaign($this, CRM_Utils_Array::value('campaign_id', $this->_values));
     // Add engagement level CRM-7775
     $buildEngagementLevel = FALSE;
     if (CRM_Campaign_BAO_Campaign::isCampaignEnable() && CRM_Campaign_BAO_Campaign::accessCampaign()) {
         $buildEngagementLevel = TRUE;
         $this->addSelect('engagement_level', array('entity' => 'activity'));
         $this->addRule('engagement_level', ts('Please enter the engagement index as a number (integers only).'), 'positiveInteger');
     }
     $this->assign('buildEngagementLevel', $buildEngagementLevel);
     // check for survey activity
     $this->_isSurveyActivity = FALSE;
     if ($this->_activityId && CRM_Campaign_BAO_Campaign::isCampaignEnable() && CRM_Campaign_BAO_Campaign::accessCampaign()) {
         $this->_isSurveyActivity = CRM_Campaign_BAO_Survey::isSurveyActivity($this->_activityId);
         if ($this->_isSurveyActivity) {
             $surveyId = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity', $this->_activityId, 'source_record_id');
             $responseOptions = CRM_Campaign_BAO_Survey::getResponsesOptions($surveyId);
             if ($responseOptions) {
                 $this->add('select', 'result', ts('Result'), array('' => ts('- select -')) + array_combine($responseOptions, $responseOptions));
             }
             $surveyTitle = NULL;
             if ($surveyId) {
                 $surveyTitle = CRM_Core_DAO::getFieldValue('CRM_Campaign_DAO_Survey', $surveyId, 'title');
             }
             $this->assign('surveyTitle', $surveyTitle);
         }
     }
     $this->assign('surveyActivity', $this->_isSurveyActivity);
     // this option should be available only during add mode
     if ($this->_action != CRM_Core_Action::UPDATE) {
         $this->add('advcheckbox', 'is_multi_activity', ts('Create a separate activity for each contact.'));
     }
     $this->addRule('duration', ts('Please enter the duration as number of minutes (integers only).'), 'positiveInteger');
     $this->addDateTime('activity_date_time', ts('Date'), TRUE, array('formatType' => 'activityDateTime'));
     // Add followup date.
     $this->addDateTime('followup_date', ts('in'), FALSE, array('formatType' => 'activityDateTime'));
     // Only admins and case-workers can change the activity source
     if (!CRM_Core_Permission::check('administer CiviCRM') && $this->_context != 'caseActivity') {
         $this->getElement('source_contact_id')->freeze();
     }
     //need to assign custom data type and subtype to the template
     $this->assign('customDataType', 'Activity');
     $this->assign('customDataSubType', $this->_activityTypeId);
     $this->assign('entityID', $this->_activityId);
     CRM_Core_BAO_Tag::getTags('civicrm_activity', $tags, NULL, '&nbsp;&nbsp;', TRUE);
     if (!empty($tags)) {
         $this->add('select', 'tag', ts('Tags'), $tags, FALSE, array('id' => 'tags', 'multiple' => 'multiple', 'class' => 'crm-select2 huge'));
     }
     // we need to hide activity tagset for special activities
     $specialActivities = array('Open Case');
     if (!in_array($this->_activityTypeName, $specialActivities)) {
         // build tag widget
         $parentNames = CRM_Core_BAO_Tag::getTagSet('civicrm_activity');
         CRM_Core_Form_Tag::buildQuickForm($this, $parentNames, 'civicrm_activity', $this->_activityId);
     }
     // if we're viewing, we're assigning different buttons than for adding/editing
     if ($this->_action & CRM_Core_Action::VIEW) {
         if (isset($this->_groupTree)) {
             CRM_Core_BAO_CustomGroup::buildCustomDataView($this, $this->_groupTree);
         }
         // form should be frozen for view mode
         $this->freeze();
         $buttons = array();
         $buttons[] = array('type' => 'cancel', 'name' => ts('Done'));
         $this->addButtons($buttons);
     } else {
         $message = array('completed' => ts('Are you sure? This is a COMPLETED activity with the DATE in the FUTURE. Click Cancel to change the date / status. Otherwise, click OK to save.'), 'scheduled' => ts('Are you sure? This is a SCHEDULED activity with the DATE in the PAST. Click Cancel to change the date / status. Otherwise, click OK to save.'));
         $js = array('onclick' => "return activityStatus(" . json_encode($message) . ");");
         $this->addButtons(array(array('type' => 'upload', 'name' => ts('Save'), 'js' => $js, 'isDefault' => TRUE), array('type' => 'cancel', 'name' => ts('Cancel'))));
     }
     if ($this->_activityTypeFile) {
         $className = "CRM_{$this->_crmDir}_Form_Activity_{$this->_activityTypeFile}";
         $className::buildQuickForm($this);
         $this->addFormRule(array($className, 'formRule'), $this);
     }
     $this->addFormRule(array('CRM_Activity_Form_Activity', 'formRule'), $this);
     if (Civi::settings()->get('activity_assignee_notification')) {
         $this->assign('activityAssigneeNotification', TRUE);
     } else {
         $this->assign('activityAssigneeNotification', FALSE);
     }
 }
예제 #28
0
    private function _addSurveyResponseColumns()
    {
        $surveyIds = CRM_Utils_Array::value('survey_id_value', $this->_params);
        if (CRM_Utils_System::isNull($surveyIds) || empty($this->_params['fields']['survey_response'])) {
            return;
        }
        $responseFields = array();
        foreach ($surveyIds as $surveyId) {
            $responseFields += CRM_Campaign_BAO_Survey::getSurveyResponseFields($surveyId);
            $this->_surveyResponseFields = $responseFields;
        }
        foreach ($responseFields as $key => $value) {
            if (substr($key, 0, 5) == 'phone' && !empty($value['location_type_id'])) {
                $fName = str_replace('-', '_', $key);
                $this->_columns["civicrm_{$fName}"] = array('dao' => 'CRM_Core_DAO_Phone', 'alias' => "phone_civireport_{$fName}", 'fields' => array($fName => array_merge($value, array('is_required' => '1', 'alias' => "phone_civireport_{$fName}", 'dbAlias' => "phone_civireport_{$fName}.phone", 'no_display' => TRUE))));
                $this->_aliases["civicrm_phone_{$fName}"] = $this->_columns["civicrm_{$fName}"]['alias'];
                $this->_locationBasedPhoneField = TRUE;
            }
        }
        $responseFieldIds = array();
        foreach (array_keys($responseFields) as $key) {
            $cfId = CRM_Core_BAO_CustomField::getKeyID($key);
            if ($cfId) {
                $responseFieldIds[$cfId] = $cfId;
            }
        }
        if (empty($responseFieldIds)) {
            return;
        }
        $query = '
     SELECT  cg.extends,
             cf.data_type,
             cf.html_type,
             cg.table_name,
             cf.column_name,
             cf.time_format,
             cf.id as cfId,
             cf.option_group_id
       FROM  civicrm_custom_group cg
INNER  JOIN  civicrm_custom_field cf ON ( cg.id = cf.custom_group_id )
      WHERE  cf.id IN ( ' . implode(' , ', $responseFieldIds) . ' )  ORDER BY cf.weight';
        $response = CRM_Core_DAO::executeQuery($query);
        $fildCnt = 1;
        while ($response->fetch()) {
            $resTable = $response->table_name;
            $fieldName = "custom_{$response->cfId}";
            //need to check does these custom data already included.
            if (!array_key_exists($resTable, $this->_columns)) {
                $this->_columns[$resTable]['dao'] = 'CRM_Contact_DAO_Contact';
                $this->_columns[$resTable]['extends'] = $response->extends;
            }
            if (empty($this->_columns[$resTable]['alias'])) {
                $this->_columns[$resTable]['alias'] = "{$resTable}_survey_response";
            }
            if (!is_array(CRM_Utils_Array::value('fields', $this->_columns[$resTable]))) {
                $this->_columns[$resTable]['fields'] = array();
            }
            if (array_key_exists($fieldName, $this->_columns[$resTable]['fields'])) {
                $this->_columns[$resTable]['fields'][$fieldName]['required'] = TRUE;
                $this->_columns[$resTable]['fields'][$fieldName]['isSurveyResponseField'] = TRUE;
                continue;
            }
            $title = $responseFields[$fieldName]['title'];
            if (in_array($this->_outputMode, array('print', 'pdf'))) {
                $title = 'Q' . $fildCnt++;
            }
            $fldType = 'CRM_Utils_Type::T_STRING';
            if ($response->time_format) {
                $fldType = CRM_Utils_Type::T_TIMESTAMP;
            }
            $field = array('name' => $response->column_name, 'type' => $fldType, 'title' => $title, 'label' => $responseFields[$fieldName]['title'], 'dataType' => $response->data_type, 'htmlType' => $response->html_type, 'required' => TRUE, 'alias' => $response->data_type == 'ContactReference' ? $this->_columns[$resTable]['alias'] . '_contact' : $this->_columns[$resTable]['alias'], 'dbAlias' => $this->_columns[$resTable]['alias'] . '.' . $response->column_name, 'no_display' => TRUE, 'isSurveyResponseField' => TRUE);
            $this->_columns[$resTable]['fields'][$fieldName] = $field;
            $this->_aliases[$resTable] = $this->_columns[$resTable]['alias'];
        }
    }
예제 #29
0
 /**
  * Process the form
  *
  * @param null
  *
  * @return void
  * @access public
  */
 public function postProcess()
 {
     // store the submitted values in an array
     $params = $this->controller->exportValues($this->_name);
     $session = CRM_Core_Session::singleton();
     $params['last_modified_id'] = $session->get('userID');
     $params['last_modified_date'] = date('YmdHis');
     if ($this->_surveyId) {
         $params['id'] = $this->_surveyId;
     } else {
         $params['created_id'] = $session->get('userID');
         $params['created_date'] = date('YmdHis');
     }
     $params['is_active'] = CRM_Utils_Array::value('is_active', $params, 0);
     $params['is_default'] = CRM_Utils_Array::value('is_default', $params, 0);
     $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, $customFields, $this->_surveyId, 'Survey');
     $survey = CRM_Campaign_BAO_Survey::create($params);
     $this->_surveyId = $survey->id;
     if (!empty($this->_values['result_id'])) {
         $query = "SELECT COUNT(*) FROM civicrm_survey WHERE result_id = %1";
         $countSurvey = (int) CRM_Core_DAO::singleValueQuery($query, array(1 => array($this->_values['result_id'], 'Positive')));
         // delete option group if no any survey is using it.
         if (!$countSurvey) {
             CRM_Core_BAO_OptionGroup::del($this->_values['result_id']);
         }
     }
     parent::endPostProcess();
 }
예제 #30
0
 /**
  * Build all the data structures needed to build the form.
  */
 public function preProcess()
 {
     parent::preProcess();
     //get the survey id from user submitted values.
     $this->_surveyId = $this->get('surveyId');
     $this->_interviewerId = $this->get('interviewerId');
     if (!$this->_surveyId) {
         CRM_Core_Error::statusBounce(ts("Could not find Survey Id."));
     }
     if (!$this->_interviewerId) {
         CRM_Core_Error::statusBounce(ts("Missing Interviewer contact."));
     }
     if (!is_array($this->_contactIds) || empty($this->_contactIds)) {
         CRM_Core_Error::statusBounce(ts("Could not find contacts for reservation."));
     }
     $params = array('id' => $this->_surveyId);
     CRM_Campaign_BAO_Survey::retrieve($params, $this->_surveyDetails);
     //get the survey activities.
     $activityStatus = CRM_Core_PseudoConstant::activityStatus('name');
     $statusIds = array();
     foreach (array('Scheduled') as $name) {
         if ($statusId = array_search($name, $activityStatus)) {
             $statusIds[] = $statusId;
         }
     }
     // these are the activities count that are linked to the current
     // interviewer and current survey and not the list of ALL survey activities
     $this->_numVoters = CRM_Campaign_BAO_Survey::getSurveyActivities($this->_surveyId, $this->_interviewerId, $statusIds, NULL, TRUE);
     //validate the selected survey.
     $this->validateSurvey();
     $this->assign('surveyTitle', $this->_surveyDetails['title']);
     $this->assign('activityType', $this->_surveyDetails['activity_type_id']);
     $this->assign('surveyId', $this->_surveyId);
     //append breadcrumb to survey dashboard.
     if (CRM_Campaign_BAO_Campaign::accessCampaign()) {
         $url = CRM_Utils_System::url('civicrm/campaign', 'reset=1&subPage=survey');
         CRM_Utils_System::appendBreadCrumb(array(array('title' => ts('Survey(s)'), 'url' => $url)));
     }
     //set the title.
     CRM_Utils_System::setTitle(ts('Reserve Respondents'));
 }