First commit

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

View file

@ -0,0 +1,710 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
class CRM_Campaign_BAO_Campaign extends CRM_Campaign_DAO_Campaign {
/**
* Takes an associative array and creates a campaign object.
*
* the function extract all the params it needs to initialize the create a
* contact object. the params array could contain additional unused name/value
* pairs
*
* @param array $params
* (reference ) an assoc array of name/value pairs.
*
* @return CRM_Campaign_DAO_Campaign
*/
public static function create(&$params) {
if (empty($params)) {
return NULL;
}
if (!(CRM_Utils_Array::value('id', $params))) {
if (!(CRM_Utils_Array::value('created_id', $params))) {
$session = CRM_Core_Session::singleton();
$params['created_id'] = $session->get('userID');
}
if (!(CRM_Utils_Array::value('created_date', $params))) {
$params['created_date'] = date('YmdHis');
}
if (!(CRM_Utils_Array::value('name', $params))) {
$params['name'] = CRM_Utils_String::titleToVar($params['title'], 64);
}
CRM_Utils_Hook::pre('create', 'Campaign', NULL, $params);
}
else {
CRM_Utils_Hook::pre('edit', 'Campaign', $params['id'], $params);
}
$campaign = new CRM_Campaign_DAO_Campaign();
$campaign->copyValues($params);
$campaign->save();
if (!empty($params['id'])) {
CRM_Utils_Hook::post('edit', 'Campaign', $campaign->id, $campaign);
}
else {
CRM_Utils_Hook::post('create', 'Campaign', $campaign->id, $campaign);
}
/* Create the campaign group record */
$groupTableName = CRM_Contact_BAO_Group::getTableName();
if (isset($params['groups']) && !empty($params['groups']['include']) && is_array($params['groups']['include'])) {
foreach ($params['groups']['include'] as $entityId) {
$dao = new CRM_Campaign_DAO_CampaignGroup();
$dao->campaign_id = $campaign->id;
$dao->entity_table = $groupTableName;
$dao->entity_id = $entityId;
$dao->group_type = 'Include';
$dao->save();
$dao->free();
}
}
//store custom data
if (!empty($params['custom']) &&
is_array($params['custom'])
) {
CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_campaign', $campaign->id);
}
return $campaign;
}
/**
* Delete the campaign.
*
* @param int $id
* Id of the campaign.
*
* @return bool|mixed
*/
public static function del($id) {
if (!$id) {
return FALSE;
}
CRM_Utils_Hook::pre('delete', 'Campaign', $id, CRM_Core_DAO::$_nullArray);
$dao = new CRM_Campaign_DAO_Campaign();
$dao->id = $id;
$result = $dao->delete();
CRM_Utils_Hook::post('delete', 'Campaign', $id, $dao);
return $result;
}
/**
* Retrieve DB object based on input parameters.
*
* It also stores all the retrieved values in the default array.
*
* @param array $params
* (reference ) an assoc array of name/value pairs.
* @param array $defaults
* (reference ) an assoc array to hold the flattened values.
*
* @return \CRM_Campaign_DAO_Campaign|null
*/
public static function retrieve(&$params, &$defaults) {
$campaign = new CRM_Campaign_DAO_Campaign();
$campaign->copyValues($params);
if ($campaign->find(TRUE)) {
CRM_Core_DAO::storeValues($campaign, $defaults);
return $campaign;
}
return NULL;
}
/**
* Return the all eligible campaigns w/ cache.
*
* @param int $includeId
* Lets inlcude this campaign by force.
* @param int $excludeId
* Do not include this campaign.
* @param bool $onlyActive
* Consider only active campaigns.
*
* @param bool $onlyCurrent
* @param bool $appendDatesToTitle
* @param bool $forceAll
*
* @return mixed
* $campaigns a set of campaigns.
*/
public static function getCampaigns(
$includeId = NULL,
$excludeId = NULL,
$onlyActive = TRUE,
$onlyCurrent = TRUE,
$appendDatesToTitle = FALSE,
$forceAll = FALSE
) {
static $campaigns;
$cacheKey = 0;
$cacheKeyParams = array(
'includeId',
'excludeId',
'onlyActive',
'onlyCurrent',
'appendDatesToTitle',
'forceAll',
);
foreach ($cacheKeyParams as $param) {
$cacheParam = $$param;
if (!$cacheParam) {
$cacheParam = 0;
}
$cacheKey .= '_' . $cacheParam;
}
if (!isset($campaigns[$cacheKey])) {
$where = array('( camp.title IS NOT NULL )');
if ($excludeId) {
$where[] = "( camp.id != $excludeId )";
}
if ($onlyActive) {
$where[] = '( camp.is_active = 1 )';
}
if ($onlyCurrent) {
$where[] = '( camp.end_date IS NULL OR camp.end_date >= NOW() )';
}
$whereClause = implode(' AND ', $where);
if ($includeId) {
$whereClause .= " OR ( camp.id = $includeId )";
}
//lets force all.
if ($forceAll) {
$whereClause = '( 1 )';
}
$query = "
SELECT camp.id,
camp.title,
camp.start_date,
camp.end_date
FROM civicrm_campaign camp
WHERE {$whereClause}
Order By camp.title";
$campaign = CRM_Core_DAO::executeQuery($query);
$campaigns[$cacheKey] = array();
$config = CRM_Core_Config::singleton();
while ($campaign->fetch()) {
$title = $campaign->title;
if ($appendDatesToTitle) {
$dates = array();
foreach (array('start_date', 'end_date') as $date) {
if ($campaign->$date) {
$dates[] = CRM_Utils_Date::customFormat($campaign->$date, $config->dateformatFull);
}
}
if (!empty($dates)) {
$title .= ' (' . implode('-', $dates) . ')';
}
}
$campaigns[$cacheKey][$campaign->id] = $title;
}
}
return $campaigns[$cacheKey];
}
/**
* Wrapper to self::getCampaigns( )
* w/ permissions and component check.
*
* @param int $includeId
* @param int $excludeId
* @param bool $onlyActive
* @param bool $onlyCurrent
* @param bool $appendDatesToTitle
* @param bool $forceAll
* @param bool $doCheckForComponent
* @param bool $doCheckForPermissions
*
* @return mixed
*/
public static function getPermissionedCampaigns(
$includeId = NULL,
$excludeId = NULL,
$onlyActive = TRUE,
$onlyCurrent = TRUE,
$appendDatesToTitle = FALSE,
$forceAll = FALSE,
$doCheckForComponent = TRUE,
$doCheckForPermissions = TRUE
) {
$cacheKey = 0;
$cachekeyParams = array(
'includeId',
'excludeId',
'onlyActive',
'onlyCurrent',
'appendDatesToTitle',
'doCheckForComponent',
'doCheckForPermissions',
'forceAll',
);
foreach ($cachekeyParams as $param) {
$cacheKeyParam = $$param;
if (!$cacheKeyParam) {
$cacheKeyParam = 0;
}
$cacheKey .= '_' . $cacheKeyParam;
}
static $validCampaigns;
if (!isset($validCampaigns[$cacheKey])) {
$isValid = TRUE;
$campaigns = array(
'campaigns' => array(),
'hasAccessCampaign' => FALSE,
'isCampaignEnabled' => FALSE,
);
//do check for component.
if ($doCheckForComponent) {
$campaigns['isCampaignEnabled'] = $isValid = self::isCampaignEnable();
}
//do check for permissions.
if ($doCheckForPermissions) {
$campaigns['hasAccessCampaign'] = $isValid = self::accessCampaign();
}
//finally retrieve campaigns from db.
if ($isValid) {
$campaigns['campaigns'] = self::getCampaigns($includeId,
$excludeId,
$onlyActive,
$onlyCurrent,
$appendDatesToTitle,
$forceAll
);
}
//store in cache.
$validCampaigns[$cacheKey] = $campaigns;
}
return $validCampaigns[$cacheKey];
}
/**
* Is CiviCampaign enabled.
* @return bool
*/
public static function isCampaignEnable() {
static $isEnable = NULL;
if (!isset($isEnable)) {
$isEnable = FALSE;
$config = CRM_Core_Config::singleton();
if (in_array('CiviCampaign', $config->enableComponents)) {
$isEnable = TRUE;
}
}
return $isEnable;
}
/**
* Retrieve campaigns for dashboard.
*
* @param array $params
* @param bool $onlyCount
*
* @return array|int
*/
public static function getCampaignSummary($params = array(), $onlyCount = FALSE) {
$campaigns = array();
//build the limit and order clause.
$limitClause = $orderByClause = $lookupTableJoins = NULL;
if (!$onlyCount) {
$sortParams = array(
'sort' => 'start_date',
'offset' => 0,
'rowCount' => 10,
'sortOrder' => 'desc',
);
foreach ($sortParams as $name => $default) {
if (!empty($params[$name])) {
$sortParams[$name] = $params[$name];
}
}
//need to lookup tables.
$orderOnCampaignTable = TRUE;
if ($sortParams['sort'] == 'status') {
$orderOnCampaignTable = FALSE;
$lookupTableJoins = "
LEFT JOIN civicrm_option_value status ON ( status.value = campaign.status_id OR campaign.status_id IS NULL )
INNER JOIN civicrm_option_group grp ON ( status.option_group_id = grp.id AND grp.name = 'campaign_status' )";
$orderByClause = "ORDER BY status.label {$sortParams['sortOrder']}";
}
elseif ($sortParams['sort'] == 'campaign_type') {
$orderOnCampaignTable = FALSE;
$lookupTableJoins = "
LEFT JOIN civicrm_option_value campaign_type ON ( campaign_type.value = campaign.campaign_type_id
OR campaign.campaign_type_id IS NULL )
INNER JOIN civicrm_option_group grp ON ( campaign_type.option_group_id = grp.id AND grp.name = 'campaign_type' )";
$orderByClause = "ORDER BY campaign_type.label {$sortParams['sortOrder']}";
}
elseif ($sortParams['sort'] == 'isActive') {
$sortParams['sort'] = 'is_active';
}
if ($orderOnCampaignTable) {
$orderByClause = "ORDER BY campaign.{$sortParams['sort']} {$sortParams['sortOrder']}";
}
$limitClause = "LIMIT {$sortParams['offset']}, {$sortParams['rowCount']}";
}
//build the where clause.
$queryParams = $where = array();
if (!empty($params['id'])) {
$where[] = "( campaign.id = %1 )";
$queryParams[1] = array($params['id'], 'Positive');
}
if (!empty($params['name'])) {
$where[] = "( campaign.name LIKE %2 )";
$queryParams[2] = array('%' . trim($params['name']) . '%', 'String');
}
if (!empty($params['title'])) {
$where[] = "( campaign.title LIKE %3 )";
$queryParams[3] = array('%' . trim($params['title']) . '%', 'String');
}
if (!empty($params['start_date'])) {
$startDate = CRM_Utils_Date::processDate($params['start_date']);
$where[] = "( campaign.start_date >= %4 OR campaign.start_date IS NULL )";
$queryParams[4] = array($startDate, 'String');
}
if (!empty($params['end_date'])) {
$endDate = CRM_Utils_Date::processDate($params['end_date'], '235959');
$where[] = "( campaign.end_date <= %5 OR campaign.end_date IS NULL )";
$queryParams[5] = array($endDate, 'String');
}
if (!empty($params['description'])) {
$where[] = "( campaign.description LIKE %6 )";
$queryParams[6] = array('%' . trim($params['description']) . '%', 'String');
}
if (!empty($params['campaign_type_id'])) {
$typeId = $params['campaign_type_id'];
if (is_array($params['campaign_type_id'])) {
$typeId = implode(' , ', $params['campaign_type_id']);
}
$where[] = "( campaign.campaign_type_id IN ( {$typeId} ) )";
}
if (!empty($params['status_id'])) {
$statusId = $params['status_id'];
if (is_array($params['status_id'])) {
$statusId = implode(' , ', $params['status_id']);
}
$where[] = "( campaign.status_id IN ( {$statusId} ) )";
}
if (array_key_exists('is_active', $params)) {
$active = "( campaign.is_active = 1 )";
if (!empty($params['is_active'])) {
$active = "( campaign.is_active = 0 OR campaign.is_active IS NULL )";
}
$where[] = $active;
}
$whereClause = NULL;
if (!empty($where)) {
$whereClause = ' WHERE ' . implode(" \nAND ", $where);
}
$properties = array(
'id',
'name',
'title',
'start_date',
'end_date',
'status_id',
'is_active',
'description',
'campaign_type_id',
);
$selectClause = '
SELECT campaign.id as id,
campaign.name as name,
campaign.title as title,
campaign.is_active as is_active,
campaign.status_id as status_id,
campaign.end_date as end_date,
campaign.start_date as start_date,
campaign.description as description,
campaign.campaign_type_id as campaign_type_id';
if ($onlyCount) {
$selectClause = 'SELECT COUNT(*)';
}
$fromClause = 'FROM civicrm_campaign campaign';
$query = "{$selectClause} {$fromClause} {$lookupTableJoins} {$whereClause} {$orderByClause} {$limitClause}";
//in case of only count.
if ($onlyCount) {
return (int) CRM_Core_DAO::singleValueQuery($query, $queryParams);
}
$campaign = CRM_Core_DAO::executeQuery($query, $queryParams);
while ($campaign->fetch()) {
foreach ($properties as $property) {
$campaigns[$campaign->id][$property] = $campaign->$property;
}
}
return $campaigns;
}
/**
* Get the campaign count.
*
*/
public static function getCampaignCount() {
return (int) CRM_Core_DAO::singleValueQuery('SELECT COUNT(*) FROM civicrm_campaign');
}
/**
* Get Campaigns groups.
*
* @param int $campaignId
* Campaign id.
*
* @return array
*/
public static function getCampaignGroups($campaignId) {
static $campaignGroups;
if (!$campaignId) {
return array();
}
if (!isset($campaignGroups[$campaignId])) {
$campaignGroups[$campaignId] = array();
$query = "
SELECT grp.title, grp.id
FROM civicrm_campaign_group campgrp
INNER JOIN civicrm_group grp ON ( grp.id = campgrp.entity_id )
WHERE campgrp.group_type = 'Include'
AND campgrp.entity_table = 'civicrm_group'
AND campgrp.campaign_id = %1";
$groups = CRM_Core_DAO::executeQuery($query, array(1 => array($campaignId, 'Positive')));
while ($groups->fetch()) {
$campaignGroups[$campaignId][$groups->id] = $groups->title;
}
}
return $campaignGroups[$campaignId];
}
/**
* Update the is_active flag in the db.
*
* @param int $id
* Id of the database record.
* @param bool $is_active
* Value we want to set the is_active field.
*
* @return CRM_Campaign_DAO_Campaign|null
* DAO object on success, null otherwise
*/
public static function setIsActive($id, $is_active) {
return CRM_Core_DAO::setFieldValue('CRM_Campaign_DAO_Campaign', $id, 'is_active', $is_active);
}
/**
* @return bool
*/
public static function accessCampaign() {
static $allow = NULL;
if (!isset($allow)) {
$allow = FALSE;
if (CRM_Core_Permission::check('manage campaign') ||
CRM_Core_Permission::check('administer CiviCampaign')
) {
$allow = TRUE;
}
}
return $allow;
}
/**
* Add select element for campaign
* and assign needful info to templates.
*
* @param CRM_Core_Form $form
* @param int $connectedCampaignId
*/
public static function addCampaign(&$form, $connectedCampaignId = NULL) {
//some forms do set default and freeze.
$appendDates = TRUE;
if ($form->get('action') & CRM_Core_Action::VIEW) {
$appendDates = FALSE;
}
$campaignDetails = self::getPermissionedCampaigns($connectedCampaignId, NULL, TRUE, TRUE, $appendDates);
$fields = array('campaigns', 'hasAccessCampaign', 'isCampaignEnabled');
foreach ($fields as $fld) {
$$fld = CRM_Utils_Array::value($fld, $campaignDetails);
}
//lets see do we have past campaigns.
$hasPastCampaigns = FALSE;
$allActiveCampaigns = CRM_Campaign_BAO_Campaign::getCampaigns(NULL, NULL, TRUE, FALSE);
if (count($allActiveCampaigns) > count($campaigns)) {
$hasPastCampaigns = TRUE;
}
$hasCampaigns = FALSE;
if (!empty($campaigns)) {
$hasCampaigns = TRUE;
}
if ($hasPastCampaigns) {
$hasCampaigns = TRUE;
$form->add('hidden', 'included_past_campaigns');
}
$showAddCampaign = FALSE;
$alreadyIncludedPastCampaigns = FALSE;
if ($connectedCampaignId || ($isCampaignEnabled && $hasAccessCampaign)) {
$showAddCampaign = TRUE;
//lets add past campaigns as options to quick-form element.
if ($hasPastCampaigns && $form->getElementValue('included_past_campaigns')) {
$campaigns = $allActiveCampaigns;
$alreadyIncludedPastCampaigns = TRUE;
}
$campaign = &$form->add('select',
'campaign_id',
ts('Campaign'),
array('' => ts('- select -')) + $campaigns,
FALSE,
array('class' => 'crm-select2')
);
//lets freeze when user does not has access or campaign is disabled.
if (!$isCampaignEnabled || !$hasAccessCampaign) {
$campaign->freeze();
}
}
$addCampaignURL = NULL;
if (empty($campaigns) && $hasAccessCampaign && $isCampaignEnabled) {
$addCampaignURL = CRM_Utils_System::url('civicrm/campaign/add', 'reset=1');
}
$includePastCampaignURL = NULL;
if ($hasPastCampaigns && $isCampaignEnabled && $hasAccessCampaign) {
$includePastCampaignURL = CRM_Utils_System::url('civicrm/ajax/rest',
'className=CRM_Campaign_Page_AJAX&fnName=allActiveCampaigns',
FALSE, NULL, FALSE
);
}
//carry this info to templates.
$infoFields = array(
'hasCampaigns',
'addCampaignURL',
'showAddCampaign',
'hasPastCampaigns',
'hasAccessCampaign',
'isCampaignEnabled',
'includePastCampaignURL',
'alreadyIncludedPastCampaigns',
);
foreach ($infoFields as $fld) {
$campaignInfo[$fld] = $$fld;
}
$form->assign('campaignInfo', $campaignInfo);
}
/**
* Add campaign in component search.
* and assign needful info to templates.
*
* @param CRM_Core_Form $form
* @param string $elementName
*/
public static function addCampaignInComponentSearch(&$form, $elementName = 'campaign_id') {
$campaignInfo = array();
$campaignDetails = self::getPermissionedCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
$fields = array('campaigns', 'hasAccessCampaign', 'isCampaignEnabled');
foreach ($fields as $fld) {
$$fld = CRM_Utils_Array::value($fld, $campaignDetails);
}
$showCampaignInSearch = FALSE;
if ($isCampaignEnabled && $hasAccessCampaign && !empty($campaigns)) {
//get the current campaign only.
$currentCampaigns = self::getCampaigns(NULL, NULL, FALSE);
$pastCampaigns = array_diff($campaigns, $currentCampaigns);
$allCampaigns = array();
if (!empty($currentCampaigns)) {
$allCampaigns = array('crm_optgroup_current_campaign' => ts('Current Campaigns')) + $currentCampaigns;
}
if (!empty($pastCampaigns)) {
$allCampaigns += array('crm_optgroup_past_campaign' => ts('Past Campaigns')) + $pastCampaigns;
}
$showCampaignInSearch = TRUE;
$form->add('select', $elementName, ts('Campaigns'), $allCampaigns, FALSE,
array('id' => 'campaigns', 'multiple' => 'multiple', 'class' => 'crm-select2')
);
}
$infoFields = array(
'elementName',
'hasAccessCampaign',
'isCampaignEnabled',
'showCampaignInSearch',
);
foreach ($infoFields as $fld) {
$campaignInfo[$fld] = $$fld;
}
$form->assign('campaignInfo', $campaignInfo);
}
}

View file

@ -0,0 +1,683 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
class CRM_Campaign_BAO_Petition extends CRM_Campaign_BAO_Survey {
/**
* Class constructor.
*/
public function __construct() {
parent::__construct();
// expire cookie in one day
$this->cookieExpire = (1 * 60 * 60 * 24);
}
/**
* Get Petition Details for dashboard.
*
* @param array $params
* @param bool $onlyCount
*
* @return array|int
*/
public static function getPetitionSummary($params = array(), $onlyCount = FALSE) {
//build the limit and order clause.
$limitClause = $orderByClause = $lookupTableJoins = NULL;
if (!$onlyCount) {
$sortParams = array(
'sort' => 'created_date',
'offset' => 0,
'rowCount' => 10,
'sortOrder' => 'desc',
);
foreach ($sortParams as $name => $default) {
if (!empty($params[$name])) {
$sortParams[$name] = $params[$name];
}
}
//need to lookup tables.
$orderOnPetitionTable = TRUE;
if ($sortParams['sort'] == 'campaign') {
$orderOnPetitionTable = FALSE;
$lookupTableJoins = '
LEFT JOIN civicrm_campaign campaign ON ( campaign.id = petition.campaign_id )';
$orderByClause = "ORDER BY campaign.title {$sortParams['sortOrder']}";
}
elseif ($sortParams['sort'] == 'activity_type') {
$orderOnPetitionTable = FALSE;
$lookupTableJoins = "
LEFT JOIN civicrm_option_value activity_type ON ( activity_type.value = petition.activity_type_id
OR petition.activity_type_id IS NULL )
INNER JOIN civicrm_option_group grp ON ( activity_type.option_group_id = grp.id AND grp.name = 'activity_type' )";
$orderByClause = "ORDER BY activity_type.label {$sortParams['sortOrder']}";
}
elseif ($sortParams['sort'] == 'isActive') {
$sortParams['sort'] = 'is_active';
}
if ($orderOnPetitionTable) {
$orderByClause = "ORDER BY petition.{$sortParams['sort']} {$sortParams['sortOrder']}";
}
$limitClause = "LIMIT {$sortParams['offset']}, {$sortParams['rowCount']}";
}
//build the where clause.
$queryParams = $where = array();
//we only have activity type as a
//difference between survey and petition.
$petitionTypeID = CRM_Core_OptionGroup::getValue('activity_type', 'petition', 'name');
if ($petitionTypeID) {
$where[] = "( petition.activity_type_id = %1 )";
$queryParams[1] = array($petitionTypeID, 'Positive');
}
if (!empty($params['title'])) {
$where[] = "( petition.title LIKE %2 )";
$queryParams[2] = array('%' . trim($params['title']) . '%', 'String');
}
if (!empty($params['campaign_id'])) {
$where[] = '( petition.campaign_id = %3 )';
$queryParams[3] = array($params['campaign_id'], 'Positive');
}
$whereClause = NULL;
if (!empty($where)) {
$whereClause = ' WHERE ' . implode(" \nAND ", $where);
}
$selectClause = '
SELECT petition.id as id,
petition.title as title,
petition.is_active as is_active,
petition.result_id as result_id,
petition.is_default as is_default,
petition.campaign_id as campaign_id,
petition.activity_type_id as activity_type_id';
if ($onlyCount) {
$selectClause = 'SELECT COUNT(*)';
}
$fromClause = 'FROM civicrm_survey petition';
$query = "{$selectClause} {$fromClause} {$whereClause} {$orderByClause} {$limitClause}";
if ($onlyCount) {
return (int) CRM_Core_DAO::singleValueQuery($query, $queryParams);
}
$petitions = array();
$properties = array(
'id',
'title',
'campaign_id',
'is_active',
'is_default',
'result_id',
'activity_type_id',
);
$petition = CRM_Core_DAO::executeQuery($query, $queryParams);
while ($petition->fetch()) {
foreach ($properties as $property) {
$petitions[$petition->id][$property] = $petition->$property;
}
}
return $petitions;
}
/**
* Get the petition count.
*
*/
public static function getPetitionCount() {
$whereClause = 'WHERE ( 1 )';
$queryParams = array();
$petitionTypeID = CRM_Core_OptionGroup::getValue('activity_type', 'petition', 'name');
if ($petitionTypeID) {
$whereClause = "WHERE ( petition.activity_type_id = %1 )";
$queryParams[1] = array($petitionTypeID, 'Positive');
}
$query = "SELECT COUNT(*) FROM civicrm_survey petition {$whereClause}";
return (int) CRM_Core_DAO::singleValueQuery($query, $queryParams);
}
/**
* Takes an associative array and creates a petition signature activity.
*
* @param array $params
* (reference ) an assoc array of name/value pairs.
*
* @return CRM_Campaign_BAO_Petition
*/
public function createSignature(&$params) {
if (empty($params)) {
return NULL;
}
if (!isset($params['sid'])) {
$statusMsg = ts('No survey sid parameter. Cannot process signature.');
CRM_Core_Session::setStatus($statusMsg, ts('Sorry'), 'error');
return;
}
if (isset($params['contactId'])) {
// add signature as activity with survey id as source id
// get the activity type id associated with this survey
$surveyInfo = CRM_Campaign_BAO_Petition::getSurveyInfo($params['sid']);
// create activity
// 1-Schedule, 2-Completed
$activityParams = array(
'source_contact_id' => $params['contactId'],
'target_contact_id' => $params['contactId'],
'source_record_id' => $params['sid'],
'subject' => $surveyInfo['title'],
'activity_type_id' => $surveyInfo['activity_type_id'],
'activity_date_time' => date("YmdHis"),
'status_id' => $params['statusId'],
'activity_campaign_id' => $params['activity_campaign_id'],
);
//activity creation
// *** check for activity using source id - if already signed
$activity = CRM_Activity_BAO_Activity::create($activityParams);
// save activity custom data
if (!empty($params['custom']) &&
is_array($params['custom'])
) {
CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_activity', $activity->id);
}
// Set browser cookie to indicate this petition was already signed.
$config = CRM_Core_Config::singleton();
$url_parts = parse_url($config->userFrameworkBaseURL);
setcookie('signed_' . $params['sid'], $activity->id, time() + $this->cookieExpire, $url_parts['path'], $url_parts['host'], CRM_Utils_System::isSSL());
}
return $activity;
}
/**
* @param int $activity_id
* @param int $contact_id
* @param int $petition_id
*
* @return bool
*/
public function confirmSignature($activity_id, $contact_id, $petition_id) {
// change activity status to completed (status_id = 2)
// I wonder why do we need contact_id when we have activity_id anyway? [chastell]
$sql = 'UPDATE civicrm_activity SET status_id = 2 WHERE id = %1';
$activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
$sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
$params = array(
1 => array($activity_id, 'Integer'),
2 => array($contact_id, 'Integer'),
3 => array($sourceID, 'Integer'),
);
CRM_Core_DAO::executeQuery($sql, $params);
$sql = 'UPDATE civicrm_activity_contact SET contact_id = %2 WHERE activity_id = %1 AND record_type_id = %3';
CRM_Core_DAO::executeQuery($sql, $params);
// remove 'Unconfirmed' tag for this contact
$tag_name = Civi::settings()->get('tag_unconfirmed');
$sql = "
DELETE FROM civicrm_entity_tag
WHERE entity_table = 'civicrm_contact'
AND entity_id = %1
AND tag_id = ( SELECT id FROM civicrm_tag WHERE name = %2 )";
$params = array(
1 => array($contact_id, 'Integer'),
2 => array($tag_name, 'String'),
);
CRM_Core_DAO::executeQuery($sql, $params);
// validate arguments to setcookie are numeric to prevent header manipulation
if (isset($petition_id) && is_numeric($petition_id)
&& isset($activity_id) && is_numeric($activity_id)) {
// set permanent cookie to indicate this users email address now confirmed
$config = CRM_Core_Config::singleton();
$url_parts = parse_url($config->userFrameworkBaseURL);
setcookie("confirmed_{$petition_id}",
$activity_id,
time() + $this->cookieExpire,
$url_parts['path'],
$url_parts['host'],
CRM_Utils_System::isSSL()
);
return TRUE;
}
else {
CRM_Core_Error::fatal(ts('Petition Id and/or Activity Id is not of the type Positive.'));
return FALSE;
}
}
/**
* Get Petition Signature Total.
*
* @param int $surveyId
*
* @return array
*/
public static function getPetitionSignatureTotalbyCountry($surveyId) {
$countries = array();
$sql = "
SELECT count(civicrm_address.country_id) as total,
IFNULL(country_id,'') as country_id,IFNULL(iso_code,'') as country_iso, IFNULL(civicrm_country.name,'') as country
FROM ( civicrm_activity a, civicrm_survey, civicrm_contact )
LEFT JOIN civicrm_address ON civicrm_address.contact_id = civicrm_contact.id AND civicrm_address.is_primary = 1
LEFT JOIN civicrm_country ON civicrm_address.country_id = civicrm_country.id
LEFT JOIN civicrm_activity_contact ac ON ( ac.activity_id = a.id AND ac.record_type_id = %2 )
WHERE
ac.contact_id = civicrm_contact.id AND
a.activity_type_id = civicrm_survey.activity_type_id AND
civicrm_survey.id = %1 AND
a.source_record_id = %1 ";
$activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
$sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
$params = array(
1 => array($surveyId, 'Integer'),
2 => array($sourceID, 'Integer'),
);
$sql .= " GROUP BY civicrm_address.country_id";
$fields = array('total', 'country_id', 'country_iso', 'country');
$dao = CRM_Core_DAO::executeQuery($sql, $params);
while ($dao->fetch()) {
$row = array();
foreach ($fields as $field) {
$row[$field] = $dao->$field;
}
$countries[] = $row;
}
return $countries;
}
/**
* Get Petition Signature Total.
*
* @param int $surveyId
*
* @return array
*/
public static function getPetitionSignatureTotal($surveyId) {
$surveyInfo = CRM_Campaign_BAO_Petition::getSurveyInfo((int) $surveyId);
//$activityTypeID = $surveyInfo['activity_type_id'];
$sql = "
SELECT
status_id,count(id) as total
FROM civicrm_activity
WHERE
source_record_id = " . (int) $surveyId . " AND activity_type_id = " . (int) $surveyInfo['activity_type_id'] . " GROUP BY status_id";
$statusTotal = array();
$total = 0;
$dao = CRM_Core_DAO::executeQuery($sql);
while ($dao->fetch()) {
$total += $dao->total;
$statusTotal['status'][$dao->status_id] = $dao->total;
}
$statusTotal['count'] = $total;
return $statusTotal;
}
/**
* @param int $surveyId
*
* @return array
*/
public static function getSurveyInfo($surveyId = NULL) {
$surveyInfo = array();
$sql = "
SELECT activity_type_id,
campaign_id,
s.title,
ov.label AS activity_type
FROM civicrm_survey s, civicrm_option_value ov, civicrm_option_group og
WHERE s.id = " . (int) $surveyId . "
AND s.activity_type_id = ov.value
AND ov.option_group_id = og.id
AND og.name = 'activity_type'";
$dao = CRM_Core_DAO::executeQuery($sql);
while ($dao->fetch()) {
//$survey['campaign_id'] = $dao->campaign_id;
//$survey['campaign_name'] = $dao->campaign_name;
$surveyInfo['activity_type'] = $dao->activity_type;
$surveyInfo['activity_type_id'] = $dao->activity_type_id;
$surveyInfo['title'] = $dao->title;
}
return $surveyInfo;
}
/**
* Get Petition Signature Details.
*
* @param int $surveyId
* @param int $status_id
*
* @return array
*/
public static function getPetitionSignature($surveyId, $status_id = NULL) {
// sql injection protection
$surveyId = (int) $surveyId;
$signature = array();
$sql = "
SELECT a.id,
a.source_record_id as survey_id,
a.activity_date_time,
a.status_id,
civicrm_contact.id as contact_id,
civicrm_contact.contact_type,civicrm_contact.contact_sub_type,image_URL,
first_name,last_name,sort_name,
employer_id,organization_name,
household_name,
IFNULL(gender_id,'') AS gender_id,
IFNULL(state_province_id,'') AS state_province_id,
IFNULL(country_id,'') as country_id,IFNULL(iso_code,'') as country_iso, IFNULL(civicrm_country.name,'') as country
FROM (civicrm_activity a, civicrm_survey, civicrm_contact )
LEFT JOIN civicrm_activity_contact ac ON ( ac.activity_id = a.id AND ac.record_type_id = %3 )
LEFT JOIN civicrm_address ON civicrm_address.contact_id = civicrm_contact.id AND civicrm_address.is_primary = 1
LEFT JOIN civicrm_country ON civicrm_address.country_id = civicrm_country.id
WHERE
ac.contact_id = civicrm_contact.id AND
a.activity_type_id = civicrm_survey.activity_type_id AND
civicrm_survey.id = %1 AND
a.source_record_id = %1 ";
$params = array(1 => array($surveyId, 'Integer'));
if ($status_id) {
$sql .= " AND status_id = %2";
$params[2] = array($status_id, 'Integer');
}
$sql .= " ORDER BY a.activity_date_time";
$activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
$sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
$params[3] = array($sourceID, 'Integer');
$fields = array(
'id',
'survey_id',
'contact_id',
'activity_date_time',
'activity_type_id',
'status_id',
'first_name',
'last_name',
'sort_name',
'gender_id',
'country_id',
'state_province_id',
'country_iso',
'country',
);
$dao = CRM_Core_DAO::executeQuery($sql, $params);
while ($dao->fetch()) {
$row = array();
foreach ($fields as $field) {
$row[$field] = $dao->$field;
}
$signature[] = $row;
}
return $signature;
}
/**
* This function returns all entities assigned to a specific tag.
*
* @param object $tag
* An object of a tag.
*
* @return array
* array of contact ids
*/
public function getEntitiesByTag($tag) {
$contactIds = array();
$entityTagDAO = new CRM_Core_DAO_EntityTag();
$entityTagDAO->tag_id = $tag['id'];
$entityTagDAO->find();
while ($entityTagDAO->fetch()) {
$contactIds[] = $entityTagDAO->entity_id;
}
return $contactIds;
}
/**
* Check if contact has signed this petition.
*
* @param int $surveyId
* @param int $contactId
*
* @return array
*/
public static function checkSignature($surveyId, $contactId) {
$surveyInfo = CRM_Campaign_BAO_Petition::getSurveyInfo($surveyId);
$signature = array();
$activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
$sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
$sql = "
SELECT a.id AS id,
a.source_record_id AS source_record_id,
ac.contact_id AS source_contact_id,
a.activity_date_time AS activity_date_time,
a.activity_type_id AS activity_type_id,
a.status_id AS status_id,
%1 AS survey_title
FROM civicrm_activity a
INNER JOIN civicrm_activity_contact ac ON (ac.activity_id = a.id AND ac.record_type_id = %5)
WHERE a.source_record_id = %2
AND a.activity_type_id = %3
AND ac.contact_id = %4
";
$params = array(
1 => array($surveyInfo['title'], 'String'),
2 => array($surveyId, 'Integer'),
3 => array($surveyInfo['activity_type_id'], 'Integer'),
4 => array($contactId, 'Integer'),
5 => array($sourceID, 'Integer'),
);
$dao = CRM_Core_DAO::executeQuery($sql, $params);
while ($dao->fetch()) {
$signature[$dao->id]['id'] = $dao->id;
$signature[$dao->id]['source_record_id'] = $dao->source_record_id;
$signature[$dao->id]['source_contact_id'] = CRM_Contact_BAO_Contact::displayName($dao->source_contact_id);
$signature[$dao->id]['activity_date_time'] = $dao->activity_date_time;
$signature[$dao->id]['activity_type_id'] = $dao->activity_type_id;
$signature[$dao->id]['status_id'] = $dao->status_id;
$signature[$dao->id]['survey_title'] = $dao->survey_title;
$signature[$dao->id]['contactId'] = $dao->source_contact_id;
}
return $signature;
}
/**
* 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 int $sendEmailMode
*
* @throws Exception
*/
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 = Civi::settings()->get('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']}&pid={$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']}&pid={$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;
}
}
}

View file

@ -0,0 +1,565 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
class CRM_Campaign_BAO_Query {
//since normal activity clause clause get collides.
const
CIVICRM_ACTIVITY = 'civicrm_survey_activity',
CIVICRM_ACTIVITY_TARGET = 'civicrm_survey_activity_target',
CIVICRM_ACTIVITY_ASSIGNMENT = 'civicrm_survey_activity_assignment';
/**
* Static field for all the campaign fields.
*
* @var array
*/
static $_campaignFields = NULL;
static $_applySurveyClause = FALSE;
/**
* Function get the fields for campaign.
*
* @return array
* self::$_campaignFields an associative array of campaign fields
*/
public static function &getFields() {
if (!isset(self::$_campaignFields)) {
self::$_campaignFields = array();
}
return self::$_campaignFields;
}
/**
* If survey, campaign are involved, add the specific fields.
*
* @param CRM_Contact_BAO_Contact $query
*/
public static function select(&$query) {
self::$_applySurveyClause = FALSE;
if (is_array($query->_params)) {
foreach ($query->_params as $values) {
if (!is_array($values) || count($values) != 5) {
continue;
}
list($name, $op, $value, $grouping, $wildcard) = $values;
if ($name == 'campaign_survey_id') {
self::$_applySurveyClause = TRUE;
break;
}
}
}
// CRM-13810 Translate campaign_id to label for search builder
// CRM-14238 Only translate when we are in contact mode
// Other modes need the untranslated data for export and other functions
if (is_array($query->_select) && $query->_mode == CRM_Contact_BAO_Query::MODE_CONTACTS) {
foreach ($query->_select as $field => $queryString) {
if (substr($field, -11) == 'campaign_id') {
$query->_pseudoConstantsSelect[$field] = array(
'pseudoField' => 'campaign_id',
'idCol' => $field,
'bao' => 'CRM_Activity_BAO_Activity',
);
}
}
}
//get survey clause in force,
//only when we have survey id.
if (!self::$_applySurveyClause) {
return;
}
//all below tables are require to fetch result.
//1. get survey activity target table in.
$query->_select['survey_activity_target_contact_id'] = 'civicrm_activity_target.contact_id as survey_activity_target_contact_id';
$query->_select['survey_activity_target_id'] = 'civicrm_activity_target.id as survey_activity_target_id';
$query->_element['survey_activity_target_id'] = 1;
$query->_element['survey_activity_target_contact_id'] = 1;
$query->_tables[self::CIVICRM_ACTIVITY_TARGET] = 1;
$query->_whereTables[self::CIVICRM_ACTIVITY_TARGET] = 1;
//2. get survey activity table in.
$query->_select['survey_activity_id'] = 'civicrm_activity.id as survey_activity_id';
$query->_element['survey_activity_id'] = 1;
$query->_tables[self::CIVICRM_ACTIVITY] = 1;
$query->_whereTables[self::CIVICRM_ACTIVITY] = 1;
//3. get the assignee table in.
$query->_select['survey_interviewer_id'] = 'civicrm_activity_assignment.id as survey_interviewer_id';
$query->_element['survey_interviewer_id'] = 1;
$query->_tables[self::CIVICRM_ACTIVITY_ASSIGNMENT] = 1;
$query->_whereTables[self::CIVICRM_ACTIVITY_ASSIGNMENT] = 1;
//4. get survey table.
$query->_select['campaign_survey_id'] = 'civicrm_survey.id as campaign_survey_id';
$query->_element['campaign_survey_id'] = 1;
$query->_tables['civicrm_survey'] = 1;
$query->_whereTables['civicrm_survey'] = 1;
//5. get campaign table.
$query->_select['campaign_id'] = 'civicrm_campaign.id as campaign_id';
$query->_element['campaign_id'] = 1;
$query->_tables['civicrm_campaign'] = 1;
$query->_whereTables['civicrm_campaign'] = 1;
}
/**
* @param $query
*/
public static function where(&$query) {
//get survey clause in force,
//only when we have survey id.
if (!self::$_applySurveyClause) {
return;
}
$grouping = NULL;
foreach (array_keys($query->_params) as $id) {
if ($query->_mode == CRM_Contact_BAO_Query::MODE_CONTACTS) {
$query->_useDistinct = TRUE;
}
self::whereClauseSingle($query->_params[$id], $query);
}
}
/**
* @param $values
* @param $query
*/
public static function whereClauseSingle(&$values, &$query) {
//get survey clause in force,
//only when we have survey id.
if (!self::$_applySurveyClause) {
return;
}
list($name, $op, $value, $grouping, $wildcard) = $values;
switch ($name) {
case 'campaign_survey_id':
$query->_qill[$grouping][] = ts('Survey - %1', array(1 => CRM_Core_DAO::getFieldValue('CRM_Campaign_DAO_Survey', $value, 'title')));
$query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause('civicrm_activity.source_record_id',
$op, $value, 'Integer'
);
$query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause('civicrm_survey.id',
$op, $value, 'Integer'
);
return;
case 'survey_status_id':
$activityStatus = CRM_Core_PseudoConstant::activityStatus();
$query->_qill[$grouping][] = ts('Survey Status - %1', array(1 => $activityStatus[$value]));
$query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause('civicrm_activity.status_id',
$op, $value, 'Integer'
);
return;
case 'campaign_search_voter_for':
if (in_array($value, array('release', 'interview'))) {
$query->_where[$grouping][] = '(civicrm_activity.is_deleted = 0 OR civicrm_activity.is_deleted IS NULL)';
}
return;
case 'survey_interviewer_id':
$surveyInterviewerName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $value, 'sort_name');
$query->_qill[$grouping][] = ts('Survey Interviewer - %1', array(1 => $surveyInterviewerName));
$query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause('civicrm_activity_assignment.contact_id',
$op, $value, 'Integer'
);
return;
}
}
/**
* @param string $name
* @param $mode
* @param $side
*
* @return null|string
*/
public static function from($name, $mode, $side) {
$from = NULL;
//get survey clause in force,
//only when we have survey id.
if (!self::$_applySurveyClause) {
return $from;
}
$activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
$sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
$assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
$targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
switch ($name) {
case self::CIVICRM_ACTIVITY_TARGET:
$from = " INNER JOIN civicrm_activity_contact civicrm_activity_target
ON ( civicrm_activity_target.contact_id = contact_a.id AND civicrm_activity_target.record_type_id = $targetID) ";
break;
case self::CIVICRM_ACTIVITY:
$surveyActivityTypes = CRM_Campaign_PseudoConstant::activityType();
$surveyKeys = "(" . implode(',', array_keys($surveyActivityTypes)) . ")";
$from = " INNER JOIN civicrm_activity ON ( civicrm_activity.id = civicrm_activity_target.activity_id
AND civicrm_activity.activity_type_id IN $surveyKeys ) ";
break;
case self::CIVICRM_ACTIVITY_ASSIGNMENT:
$from = "
INNER JOIN civicrm_activity_contact civicrm_activity_assignment ON ( civicrm_activity.id = civicrm_activity_assignment.activity_id AND
civicrm_activity_assignment.record_type_id = $assigneeID ) ";
break;
case 'civicrm_survey':
$from = " INNER JOIN civicrm_survey ON ( civicrm_survey.id = civicrm_activity.source_record_id ) ";
break;
case 'civicrm_campaign':
$from = " $side JOIN civicrm_campaign ON ( civicrm_campaign.id = civicrm_survey.campaign_id ) ";
break;
}
return $from;
}
/**
* @param $mode
* @param bool $includeCustomFields
*
* @return array|null
*/
public static function defaultReturnProperties(
$mode,
$includeCustomFields = TRUE
) {
$properties = NULL;
if ($mode & CRM_Contact_BAO_Query::MODE_CAMPAIGN) {
$properties = array(
'contact_id' => 1,
'contact_type' => 1,
'contact_sub_type' => 1,
'sort_name' => 1,
'display_name' => 1,
'street_unit' => 1,
'street_name' => 1,
'street_number' => 1,
'street_address' => 1,
'city' => 1,
'postal_code' => 1,
'state_province' => 1,
'country' => 1,
'email' => 1,
'phone' => 1,
'survey_activity_target_id' => 1,
'survey_activity_id' => 1,
'survey_status_id' => 1,
'campaign_survey_id' => 1,
'campaign_id' => 1,
'survey_interviewer_id' => 1,
'survey_activity_target_contact_id' => 1,
);
}
return $properties;
}
/**
* @param $tables
*/
public static function tableNames(&$tables) {
}
/**
* @param $row
* @param int $id
*/
public static function searchAction(&$row, $id) {
}
/**
* @param $tables
*/
public static function info(&$tables) {
//get survey clause in force,
//only when we have survey id.
if (!self::$_applySurveyClause) {
return;
}
$weight = end($tables);
$tables[self::CIVICRM_ACTIVITY_TARGET] = ++$weight;
$tables[self::CIVICRM_ACTIVITY] = ++$weight;
$tables[self::CIVICRM_ACTIVITY_ASSIGNMENT] = ++$weight;
$tables['civicrm_survey'] = ++$weight;
$tables['civicrm_campaign'] = ++$weight;
}
/**
* Add all the elements shared between,
* normal voter search and voter listing (GOTV form)
*
* @param CRM_Core_Form $form
*/
public static function buildSearchForm(&$form) {
$attributes = CRM_Core_DAO::getAttribute('CRM_Core_DAO_Address');
$className = CRM_Utils_System::getClassName($form);
$form->add('text', 'sort_name', ts('Contact Name'),
CRM_Core_DAO::getAttribute('CRM_Contact_DAO_Contact', 'sort_name')
);
$form->add('text', 'street_name', ts('Street Name'), $attributes['street_name']);
$form->add('text', 'street_number', ts('Street Number'), $attributes['street_number']);
$form->add('text', 'street_unit', ts('Street Unit'), $attributes['street_unit']);
$form->add('text', 'street_address', ts('Street Address'), $attributes['street_address']);
$form->add('text', 'city', ts('City'), $attributes['city']);
$form->add('text', 'postal_code', ts('Postal Code'), $attributes['postal_code']);
//@todo FIXME - using the CRM_Core_DAO::VALUE_SEPARATOR creates invalid html - if you can find the form
// this is loaded onto then replace with something like '__' & test
$separator = CRM_Core_DAO::VALUE_SEPARATOR;
$contactTypes = CRM_Contact_BAO_ContactType::getSelectElements(FALSE, TRUE, $separator);
$form->add('select', 'contact_type', ts('Contact Type(s)'), $contactTypes, FALSE,
array('id' => 'contact_type', 'multiple' => 'multiple', 'class' => 'crm-select2')
);
$groups = CRM_Core_PseudoConstant::nestedGroup();
$form->add('select', 'group', ts('Groups'), $groups, FALSE,
array('multiple' => 'multiple', 'class' => 'crm-select2')
);
$showInterviewer = FALSE;
if (CRM_Core_Permission::check('administer CiviCampaign')) {
$showInterviewer = TRUE;
}
$form->assign('showInterviewer', $showInterviewer);
if ($showInterviewer ||
$className == 'CRM_Campaign_Form_Gotv'
) {
$form->addEntityRef('survey_interviewer_id', ts('Interviewer'), array('class' => 'big'));
$userId = NULL;
if (isset($form->_interviewerId) && $form->_interviewerId) {
$userId = $form->_interviewerId;
}
if (!$userId) {
$session = CRM_Core_Session::singleton();
$userId = $session->get('userID');
}
if ($userId) {
$defaults = array();
$defaults['survey_interviewer_id'] = $userId;
$form->setDefaults($defaults);
}
}
//build ward and precinct custom fields.
$query = '
SELECT fld.id, fld.label
FROM civicrm_custom_field fld
INNER JOIN civicrm_custom_group grp on fld.custom_group_id = grp.id
WHERE grp.name = %1';
$dao = CRM_Core_DAO::executeQuery($query, array(1 => array('Voter_Info', 'String')));
$customSearchFields = array();
while ($dao->fetch()) {
foreach (array(
'ward',
'precinct',
) as $name) {
if (stripos($name, $dao->label) !== FALSE) {
$fieldId = $dao->id;
$fieldName = 'custom_' . $dao->id;
$customSearchFields[$name] = $fieldName;
CRM_Core_BAO_CustomField::addQuickFormElement($form, $fieldName, $fieldId, FALSE);
break;
}
}
}
$form->assign('customSearchFields', $customSearchFields);
$surveys = CRM_Campaign_BAO_Survey::getSurveys();
if (empty($surveys) &&
($className == 'CRM_Campaign_Form_Search')
) {
CRM_Core_Error::statusBounce(ts('Could not find survey for %1 respondents.',
array(1 => $form->get('op'))
),
CRM_Utils_System::url('civicrm/survey/add',
'reset=1&action=add'
)
);
}
//CRM-7406 --
//If survey had associated campaign and
//campaign has some contact groups, don't
//allow to search the contacts those are not
//in given campaign groups ( ie not in constituents )
$props = array('class' => 'crm-select2');
if ($form->get('searchVoterFor') == 'reserve') {
$props['onChange'] = "buildCampaignGroups( );return false;";
}
$form->add('select', 'campaign_survey_id', ts('Survey'), $surveys, TRUE, $props);
}
/*
* Retrieve all valid voter ids,
* and build respective clause to restrict search.
*
* @param array $criteria
* An array.
* @return $voterClause as a string
*/
/**
* @param array $params
*
* @return array
*/
static public 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 = "
CREATE TEMPORARY TABLE {$tempTableName} (
id int unsigned NOT NULL AUTO_INCREMENT,
survey_contact_id int unsigned NOT NULL,
PRIMARY KEY ( id )
);
";
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 )
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;
}
}

File diff suppressed because it is too large Load diff