Merge pull request #3810 from colemanw/dynPath
[civicrm-core.git] / CRM / Campaign / BAO / Survey.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
06b69b18 4 | CiviCRM version 4.5 |
6a488035 5 +--------------------------------------------------------------------+
06b69b18 6 | Copyright CiviCRM LLC (c) 2004-2014 |
6a488035
TO
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26*/
27
28/**
29 *
30 * @package CRM
06b69b18 31 * @copyright CiviCRM LLC (c) 2004-2014
6a488035
TO
32 * $Id$
33 *
34 */
35require_once 'CRM/Campaign/DAO/Survey.php';
4c6ce474
EM
36
37/**
38 * Class CRM_Campaign_BAO_Survey
39 */
6a488035
TO
40class CRM_Campaign_BAO_Survey extends CRM_Campaign_DAO_Survey {
41
42 /**
43 * Takes a bunch of params that are needed to match certain criteria and
44 * retrieves the relevant objects. Typically the valid params are only
45 * campaign_id.
46 *
47 * @param array $params (reference ) an assoc array of name/value pairs
48 * @param array $defaults (reference ) an assoc array to hold the flattened values
49 *
50 * @access public
51 */
52
53 /**
54 * The action links that we need to display for the browse screen
55 *
77b97be7
EM
56 * @param $params
57 * @param $defaults
58 *
59 * @return \CRM_Campaign_DAO_Survey|null
60 * @internal param array $
6a488035
TO
61 */
62 static function retrieve(&$params, &$defaults) {
63 $dao = new CRM_Campaign_DAO_Survey();
64
65 $dao->copyValues($params);
66
67 if ($dao->find(TRUE)) {
68 CRM_Core_DAO::storeValues($dao, $defaults);
69 return $dao;
70 }
71 return NULL;
72 }
73
74 /**
75 * takes an associative array and creates a Survey object
76 *
77 * the function extract all the params it needs to initialize the create a
78 * survey object.
79 *
80 *
77b97be7
EM
81 * @param $params
82 *
6a488035
TO
83 * @return object CRM_Survey_DAO_Survey object
84 * @access public
85 * @static
86 */
87 static function create(&$params) {
88 if (empty($params)) {
89 return false;
90 }
91
a7488080 92 if (!empty($params['is_default'])) {
6a488035
TO
93 $query = "UPDATE civicrm_survey SET is_default = 0";
94 CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
95 }
96
97 if (!(CRM_Utils_Array::value('id', $params))) {
98
99 if (!(CRM_Utils_Array::value('created_id', $params))) {
100 $session = CRM_Core_Session::singleton();
101 $params['created_id'] = $session->get('userID');
102 }
103 if (!(CRM_Utils_Array::value('created_date', $params))) {
104 $params['created_date'] = date('YmdHis');
105 }
106 }
107
108 $dao = new CRM_Campaign_DAO_Survey();
109 $dao->copyValues($params);
110 $dao->save();
111
a7488080 112 if (!empty($params['custom']) &&
6a488035
TO
113 is_array($params['custom'])
114 ) {
115 CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_survey', $dao->id);
116 }
117 return $dao;
118 }
119
120 /**
121 * Function to retrieve surveys for dashboard.
122 *
123 * @static
124 */
125 static function getSurveySummary($params = array(
126 ), $onlyCount = FALSE) {
127 //build the limit and order clause.
128 $limitClause = $orderByClause = $lookupTableJoins = NULL;
129 if (!$onlyCount) {
130 $sortParams = array(
131 'sort' => 'created_date',
132 'offset' => 0,
133 'rowCount' => 10,
134 'sortOrder' => 'desc',
135 );
136 foreach ($sortParams as $name => $default) {
a7488080 137 if (!empty($params[$name])) {
6a488035
TO
138 $sortParams[$name] = $params[$name];
139 }
140 }
141
142 //need to lookup tables.
143 $orderOnSurveyTable = TRUE;
144 if ($sortParams['sort'] == 'campaign') {
145 $orderOnSurveyTable = FALSE;
146 $lookupTableJoins = '
147 LEFT JOIN civicrm_campaign campaign ON ( campaign.id = survey.campaign_id )';
148 $orderByClause = "ORDER BY campaign.title {$sortParams['sortOrder']}";
149 }
150 elseif ($sortParams['sort'] == 'activity_type') {
151 $orderOnSurveyTable = FALSE;
152 $lookupTableJoins = "
91da6cd5 153 LEFT JOIN civicrm_option_value activity_type ON ( activity_type.value = survey.activity_type_id
6a488035
TO
154 OR survey.activity_type_id IS NULL )
155INNER JOIN civicrm_option_group grp ON ( activity_type.option_group_id = grp.id AND grp.name = 'activity_type' )";
156 $orderByClause = "ORDER BY activity_type.label {$sortParams['sortOrder']}";
157 }
158 elseif ($sortParams['sort'] == 'isActive') {
159 $sortParams['sort'] = 'is_active';
160 }
161 if ($orderOnSurveyTable) {
162 $orderByClause = "ORDER BY survey.{$sortParams['sort']} {$sortParams['sortOrder']}";
163 }
164 $limitClause = "LIMIT {$sortParams['offset']}, {$sortParams['rowCount']}";
165 }
166
167 //build the where clause.
168 $queryParams = $where = array();
169
170 //we only have activity type as a
171 //difference between survey and petition.
172 $petitionTypeID = CRM_Core_OptionGroup::getValue('activity_type', 'petition', 'name');
173 if ($petitionTypeID) {
174 $where[] = "( survey.activity_type_id != %1 )";
175 $queryParams[1] = array($petitionTypeID, 'Positive');
176 }
177
a7488080 178 if (!empty($params['title'])) {
6a488035
TO
179 $where[] = "( survey.title LIKE %2 )";
180 $queryParams[2] = array('%' . trim($params['title']) . '%', 'String');
181 }
a7488080 182 if (!empty($params['campaign_id'])) {
6a488035
TO
183 $where[] = '( survey.campaign_id = %3 )';
184 $queryParams[3] = array($params['campaign_id'], 'Positive');
185 }
a7488080 186 if (!empty($params['activity_type_id'])) {
6a488035
TO
187 $typeId = $params['activity_type_id'];
188 if (is_array($params['activity_type_id'])) {
189 $typeId = implode(' , ', $params['activity_type_id']);
190 }
191 $where[] = "( survey.activity_type_id IN ( {$typeId} ) )";
192 }
193 $whereClause = NULL;
194 if (!empty($where)) {
195 $whereClause = ' WHERE ' . implode(" \nAND ", $where);
196 }
197
198 $selectClause = '
199SELECT survey.id as id,
200 survey.title as title,
201 survey.is_active as is_active,
202 survey.result_id as result_id,
203 survey.is_default as is_default,
204 survey.campaign_id as campaign_id,
205 survey.activity_type_id as activity_type_id,
206 survey.release_frequency as release_frequency,
207 survey.max_number_of_contacts as max_number_of_contacts,
208 survey.default_number_of_contacts as default_number_of_contacts';
209 if ($onlyCount) {
210 $selectClause = 'SELECT COUNT(*)';
211 }
212 $fromClause = 'FROM civicrm_survey survey';
213
214 $query = "{$selectClause} {$fromClause} {$lookupTableJoins} {$whereClause} {$orderByClause} {$limitClause}";
215
216 //return only count.
217 if ($onlyCount) {
218 return (int)CRM_Core_DAO::singleValueQuery($query, $queryParams);
219 }
220
221 $surveys = array();
222 $properties = array(
223 'id', 'title', 'campaign_id', 'is_active', 'is_default', 'result_id', 'activity_type_id',
224 'release_frequency', 'max_number_of_contacts', 'default_number_of_contacts',
225 );
226
227 $survey = CRM_Core_DAO::executeQuery($query, $queryParams);
228 while ($survey->fetch()) {
229 foreach ($properties as $property) {
230 $surveys[$survey->id][$property] = $survey->$property;
231 }
232 }
233
234 return $surveys;
235 }
236
237 /**
238 * Get the survey count.
239 *
240 * @static
241 */
242 static function getSurveyCount() {
243 return (int)CRM_Core_DAO::singleValueQuery('SELECT COUNT(*) FROM civicrm_survey');
244 }
245
246 /**
247 * Function to get Surveys
248 *
249 * @param boolean $onlyActive retrieve only active surveys.
250 * @param boolean $onlyDefault retrieve only default survey.
251 * @param boolean $forceAll retrieve all surveys.
9231464f 252 * @param boolean $includePetition include or exclude petitions
6a488035
TO
253 *
254 * @static
255 */
9231464f 256 static function getSurveys($onlyActive = TRUE, $onlyDefault = FALSE, $forceAll = FALSE, $includePetition = FALSE ) {
6a488035 257 $cacheKey = 0;
9231464f 258 $cacheKeyParams = array('onlyActive', 'onlyDefault', 'forceAll', 'includePetition');
6a488035
TO
259 foreach ($cacheKeyParams as $param) {
260 $cacheParam = $$param;
261 if (!$cacheParam) {
262 $cacheParam = 0;
263 }
264 $cacheKey .= '_' . $cacheParam;
265 }
266
267 static $surveys;
268
269 if (!isset($surveys[$cacheKey])) {
9231464f
KJ
270 if (!$includePetition) {
271 //we only have activity type as a
272 //difference between survey and petition.
273 $petitionTypeID = CRM_Core_OptionGroup::getValue('activity_type', 'petition', 'name');
6a488035 274
9231464f
KJ
275 $where = array();
276 if ($petitionTypeID) {
277 $where[] = "( survey.activity_type_id != {$petitionTypeID} )";
278 }
6a488035
TO
279 }
280 if (!$forceAll && $onlyActive) {
281 $where[] = '( survey.is_active = 1 )';
282 }
283 if (!$forceAll && $onlyDefault) {
284 $where[] = '( survey.is_default = 1 )';
285 }
286 $whereClause = implode(' AND ', $where);
287
288 $query = "
289SELECT survey.id as id,
290 survey.title as title
291 FROM civicrm_survey as survey
292 WHERE {$whereClause}";
293 $surveys[$cacheKey] = array();
294 $survey = CRM_Core_DAO::executeQuery($query);
295 while ($survey->fetch()) {
296 $surveys[$cacheKey][$survey->id] = $survey->title;
297 }
298 }
299
300 return $surveys[$cacheKey];
301 }
302
303 /**
304 * Function to get Surveys activity types
305 *
306 *
307 * @static
308 */
309 static function getSurveyActivityType($returnColumn = 'label',
310 $includePetitionActivityType = FALSE
311 ) {
312 static $activityTypes;
313 $cacheKey = "{$returnColumn}_{$includePetitionActivityType}";
314
315 if (!isset($activityTypes[$cacheKey])) {
316 $activityTypes = array();
317 $campaignCompId = CRM_Core_Component::getComponentID('CiviCampaign');
318 if ($campaignCompId) {
319 $condition = " AND v.component_id={$campaignCompId}";
320 if (!$includePetitionActivityType) {
321 $condition .= " AND v.name != 'Petition'";
322 }
323 $activityTypes[$cacheKey] = CRM_Core_OptionGroup::values('activity_type',
324 FALSE, FALSE, FALSE,
325 $condition,
326 $returnColumn
327 );
328 }
329 }
330
331 return $activityTypes[$cacheKey];
332 }
333
334 /**
335 * Function to get Surveys custom groups
336 *
337 * @param $surveyTypes array an array of survey type id.
338 *
77b97be7 339 * @return array
6a488035
TO
340 * @static
341 */
342 static function getSurveyCustomGroups($surveyTypes = array(
343 )) {
344 $customGroups = array();
345 if (!is_array($surveyTypes)) {
346 $surveyTypes = array($surveyTypes);
347 }
348
349 if (!empty($surveyTypes)) {
350 $activityTypes = array_flip($surveyTypes);
351 }
352 else {
353 $activityTypes = self::getSurveyActivityType();
354 }
355
356 if (!empty($activityTypes)) {
357 $extendSubType = implode('[[:>:]]|[[:<:]]', array_keys($activityTypes));
358
359 $query = "SELECT cg.id, cg.name, cg.title, cg.extends_entity_column_value
360 FROM civicrm_custom_group cg
361 WHERE cg.is_active = 1 AND cg.extends_entity_column_value REGEXP '[[:<:]]{$extendSubType}[[:>:]]'";
362
363 $dao = CRM_Core_DAO::executeQuery($query);
364 while ($dao->fetch()) {
365 $customGroups[$dao->id]['id'] = $dao->id;
366 $customGroups[$dao->id]['name'] = $dao->name;
367 $customGroups[$dao->id]['title'] = $dao->title;
368 $customGroups[$dao->id]['extends'] = $dao->extends_entity_column_value;
369 }
370 }
371
372 return $customGroups;
373 }
374
375 /**
376 * update the is_active flag in the db
377 *
378 * @param int $id id of the database record
379 * @param boolean $is_active value we want to set the is_active field
380 *
381 * @return Object DAO object on sucess, null otherwise
382 * @static
383 */
384 static function setIsActive($id, $is_active) {
385 return CRM_Core_DAO::setFieldValue('CRM_Campaign_DAO_Survey', $id, 'is_active', $is_active);
386 }
387
388 /**
389 * Function to delete the survey
390 *
391 * @param int $id survey id
392 *
77b97be7 393 * @return mixed|null
6a488035
TO
394 * @access public
395 * @static
396 *
397 */
398 static function del($id) {
399 if (!$id) {
400 return NULL;
401 }
402 $reportId = CRM_Campaign_BAO_Survey::getReportID($id);
403 if($reportId){
0b25329b 404 CRM_Report_BAO_ReportInstance::del($reportId);
6a488035
TO
405 }
406 $dao = new CRM_Campaign_DAO_Survey();
407 $dao->id = $id;
408 return $dao->delete();
409 }
410
411 /**
412 * This function retrieve contact information.
413 *
2a6da8d7
EM
414 * @param $voterIds
415 * @param array $returnProperties an array of return elements.
6a488035 416 *
2a6da8d7
EM
417 * @internal param array $voter an array of contact Ids.
418 * @return array $voterDetails array of contact info.@static
6a488035
TO
419 */
420 static function voterDetails($voterIds, $returnProperties = array(
421 )) {
422 $voterDetails = array();
423 if (!is_array($voterIds) || empty($voterIds)) {
424 return $voterDetails;
425 }
426
427 if (empty($returnProperties)) {
428 $autocompleteContactSearch = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
429 'contact_autocomplete_options'
430 );
431 $returnProperties = array_fill_keys(array_merge(array(
432 'contact_type',
433 'contact_sub_type',
434 'sort_name',
435 ),
436 array_keys($autocompleteContactSearch)
437 ), 1);
438 }
439
440 $select = $from = array();
441 foreach ($returnProperties as $property => $ignore) {
442 $value = (in_array($property, array(
443 'city', 'street_address'))) ? 'address' : $property;
444 switch ($property) {
445 case 'sort_name':
446 case 'contact_type':
447 case 'contact_sub_type':
448 $select[] = "$property as $property";
449 $from['contact'] = 'civicrm_contact contact';
450 break;
451
452 case 'email':
453 case 'phone':
454 case 'city':
455 case 'street_address':
456 $select[] = "$property as $property";
457 $from[$value] = "LEFT JOIN civicrm_{$value} {$value} ON ( contact.id = {$value}.contact_id AND {$value}.is_primary = 1 ) ";
458 break;
459
460 case 'country':
461 case 'state_province':
462 $select[] = "{$property}.name as $property";
463 if (!in_array('address', $from)) {
464 $from['address'] = 'LEFT JOIN civicrm_address address ON ( contact.id = address.contact_id AND address.is_primary = 1) ';
465 }
466 $from[$value] = " LEFT JOIN civicrm_{$value} {$value} ON ( address.{$value}_id = {$value}.id ) ";
467 break;
468 }
469 }
470
471 //finally retrieve contact details.
472 if (!empty($select) && !empty($from)) {
473 $fromClause = implode(' ', $from);
474 $selectClause = implode(', ', $select);
475 $whereClause = "contact.id IN (" . implode(',', $voterIds) . ')';
476
477 $query = "
91da6cd5 478 SELECT contact.id as contactId, $selectClause
6a488035
TO
479 FROM $fromClause
480 WHERE $whereClause
481Group By contact.id";
482
483 $contact = CRM_Core_DAO::executeQuery($query);
484 while ($contact->fetch()) {
485 $voterDetails[$contact->contactId]['contact_id'] = $contact->contactId;
486 foreach ($returnProperties as $property => $ignore) {
487 $voterDetails[$contact->contactId][$property] = $contact->$property;
488 }
489 $image = CRM_Contact_BAO_Contact_Utils::getImage($contact->contact_sub_type ?
490 $contact->contact_sub_type : $contact->contact_type,
491 FALSE,
492 $contact->contactId
493 );
494 $voterDetails[$contact->contactId]['contact_type'] = $image;
495 }
496 $contact->free();
497 }
498
499 return $voterDetails;
500 }
501
502 /**
503 * This function retrieve survey related activities w/ for give voter ids.
504 *
2a6da8d7
EM
505 * @param int $surveyId survey id.
506 * @param array $voterIds voterIds.
6a488035 507 *
2a6da8d7
EM
508 * @param null $interviewerId
509 * @param array $statusIds
510 *
511 * @return array $activityDetails array of survey activity.@static
6a488035
TO
512 */
513 static function voterActivityDetails($surveyId, $voterIds, $interviewerId = NULL,
514 $statusIds = array()) {
515 $activityDetails = array();
516 if (!$surveyId ||
517 !is_array($voterIds) || empty($voterIds)
518 ) {
519 return $activityDetails;
520 }
521
522 $whereClause = NULL;
523 if (is_array($statusIds) && !empty($statusIds)) {
524 $whereClause = ' AND ( activity.status_id IN ( ' . implode(',', array_values($statusIds)) . ' ) )';
525 }
526
6a488035 527 $targetContactIds = ' ( ' . implode(',', $voterIds) . ' ) ';
e7e657f0 528 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
9e74e3ce 529 $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
530 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
8ef12e64 531
64e716d7 532 $params[1] = array($surveyId, 'Integer');
91da6cd5
DL
533 $query = "
534 SELECT activity.id, activity.status_id,
baf8a079 535 activityTarget.contact_id as voter_id,
536 activityAssignment.contact_id as interviewer_id
6a488035 537 FROM civicrm_activity activity
91da6cd5 538INNER JOIN civicrm_activity_contact activityTarget
9e74e3ce 539 ON ( activityTarget.activity_id = activity.id AND activityTarget.record_type_id = $targetID )
91da6cd5 540INNER JOIN civicrm_activity_contact activityAssignment
9e74e3ce 541 ON ( activityAssignment.activity_id = activity.id AND activityAssignment.record_type_id = $assigneeID )
6a488035 542 WHERE activity.source_record_id = %1
64e716d7
JM
543 AND ( activity.is_deleted IS NULL OR activity.is_deleted = 0 ) ";
544 if(!empty($interviewerId)) {
545 $query .= "AND activityAssignment.contact_id = %2 ";
546 $params[2] = array($interviewerId, 'Integer');
547 }
548 $query .= "AND activityTarget.contact_id IN {$targetContactIds}
6a488035 549 $whereClause";
77b97be7 550 $activity = CRM_Core_DAO::executeQuery($query, $params);
6a488035
TO
551 while ($activity->fetch()) {
552 $activityDetails[$activity->voter_id] = array(
553 'voter_id' => $activity->voter_id,
554 'status_id' => $activity->status_id,
555 'activity_id' => $activity->id,
556 'interviewer_id' => $activity->interviewer_id,
557 );
558 }
559
560 return $activityDetails;
561 }
562
563 /**
564 * This function retrieve survey related activities.
565 *
2a6da8d7 566 * @param int $surveyId survey id.
6a488035 567 *
2a6da8d7
EM
568 * @param null $interviewerId
569 * @param null $statusIds
570 * @param null $voterIds
571 * @param bool $onlyCount
572 * @return array $activities an array of survey activity.@static
6a488035
TO
573 */
574 static function getSurveyActivities($surveyId,
575 $interviewerId = NULL,
576 $statusIds = NULL,
577 $voterIds = NULL,
578 $onlyCount = FALSE
579 ) {
580 $activities = array();
581 $surveyActivityCount = 0;
582 if (!$surveyId) {
583 return ($onlyCount) ? 0 : $activities;
584 }
585
586 $where = array();
587 if (!empty($statusIds)) {
588 $where[] = '( activity.status_id IN ( ' . implode(',', array_values($statusIds)) . ' ) )';
589 }
590
591 if ($interviewerId) {
5161d8be 592 $where[] = "( activityAssignment.contact_id = $interviewerId )";
6a488035
TO
593 }
594
595 if (!empty($voterIds)) {
5161d8be 596 $where[] = "( activityTarget.contact_id IN ( " . implode(',', $voterIds) . " ) )";
6a488035
TO
597 }
598
599 $whereClause = NULL;
600 if (!empty($where)) {
601 $whereClause = ' AND ( ' . implode(' AND ', $where) . ' )';
602 }
603
604 $actTypeId = CRM_Core_DAO::getFieldValue('CRM_Campaign_DAO_Survey', $surveyId, 'activity_type_id');
605 if (!$actTypeId) {
606 return $activities;
607 }
608
609 if ($onlyCount) {
610 $select = "SELECT count(activity.id)";
611 }
612 else {
613 $select = "
91da6cd5 614 SELECT activity.id, activity.status_id,
5161d8be 615 activityTarget.contact_id as voter_id,
616 activityAssignment.contact_id as interviewer_id,
6a488035
TO
617 activity.result as result,
618 activity.activity_date_time as activity_date_time,
619 contact_a.display_name as voter_name";
620 }
621
e7e657f0 622 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
9e74e3ce 623 $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
624 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
625
6a488035
TO
626 $query = "
627 $select
628 FROM civicrm_activity activity
91da6cd5 629INNER JOIN civicrm_activity_contact activityTarget
9e74e3ce 630 ON ( activityTarget.activity_id = activity.id AND activityTarget.record_type_id = $targetID )
91da6cd5 631INNER JOIN civicrm_activity_contact activityAssignment
9e74e3ce 632 ON ( activityAssignment.activity_id = activity.id AND activityAssignment.record_type_id = $assigneeID )
91da6cd5 633INNER JOIN civicrm_contact contact_a ON ( activityTarget.contact_id = contact_a.id )
6a488035
TO
634 WHERE activity.source_record_id = %1
635 AND activity.activity_type_id = %2
636 AND ( activity.is_deleted IS NULL OR activity.is_deleted = 0 )
637 $whereClause";
638
639 $params = array(1 => array($surveyId, 'Integer'),
640 2 => array($actTypeId, 'Integer'),
641 );
642
643 if ($onlyCount) {
644 $dbCount = CRM_Core_DAO::singleValueQuery($query, $params);
645 return ($dbCount) ? $dbCount : 0;
646 }
647
648 $activity = CRM_Core_DAO::executeQuery($query, $params);
649
650 while ($activity->fetch()) {
651 $activities[$activity->id] = array(
652 'id' => $activity->id,
653 'voter_id' => $activity->voter_id,
654 'voter_name' => $activity->voter_name,
655 'status_id' => $activity->status_id,
656 'interviewer_id' => $activity->interviewer_id,
657 'result' => $activity->result,
658 'activity_date_time' => $activity->activity_date_time
659 );
660 }
661
662 return $activities;
663 }
664
665 /**
666 * This function retrieve survey voter information.
667 *
668 * @param int $surveyId survey id.
669 * @param int $interviewerId interviewer id.
670 * @param array $statusIds survey status ids.
671 *
672 * @return array $$contactIds survey related contact ids.
673 * @static
674 */
675 static function getSurveyVoterInfo($surveyId, $interviewerId = NULL, $statusIds = array( )) {
676 $voterIds = array();
677 if (!$surveyId) {
678 return $voterIds;
679 }
680
681 $cacheKey = $surveyId;
682 if ($interviewerId) {
683 $cacheKey .= "_{$interviewerId}";
684 }
685 if (is_array($statusIds) && !empty($statusIds)) {
686 $cacheKey = "{$cacheKey}_" . implode('_', $statusIds);
687 }
688
689 static $contactIds = array();
690 if (!isset($contactIds[$cacheKey])) {
691 $activities = self::getSurveyActivities($surveyId, $interviewerId, $statusIds);
692 foreach ($activities as $values) {
693 $voterIds[$values['voter_id']] = $values;
694 }
695 $contactIds[$cacheKey] = $voterIds;
696 }
697
698 return $contactIds[$cacheKey];
699 }
700
701 /**
91da6cd5 702 * This function retrieve all option groups which are created as a result set
6a488035 703 *
2a6da8d7
EM
704 * @param string $valueColumnName
705 * @return array $resultSets an array of option groups.@static
6a488035
TO
706 */
707 static function getResultSets( $valueColumnName = 'title' ) {
708 $resultSets = array();
709 $valueColumnName = CRM_Utils_Type::escape($valueColumnName, 'String');
710
711 $query = "SELECT id, {$valueColumnName} FROM civicrm_option_group WHERE name LIKE 'civicrm_survey_%' AND is_active=1";
712 $dao = CRM_Core_DAO::executeQuery($query);
713 while ($dao->fetch()) {
714 $resultSets[$dao->id] = $dao->$valueColumnName;
715 }
716
717 return $resultSets;
718 }
719
720 /**
91da6cd5 721 * This function is to check survey activity.
6a488035
TO
722 *
723 * @param int $activityId activity id.
2a6da8d7 724 * @internal param int $activityTypeId activity type id.
6a488035
TO
725 * @return boolean $isSurveyActivity true/false boolean.
726 * @static
727 */
728 static function isSurveyActivity($activityId) {
729 $isSurveyActivity = FALSE;
730 if (!$activityId) {
731 return $isSurveyActivity;
732 }
733
734 $activity = new CRM_Activity_DAO_Activity();
735 $activity->id = $activityId;
736 $activity->selectAdd('source_record_id, activity_type_id');
737 if ($activity->find(TRUE) &&
738 $activity->source_record_id
739 ) {
740 $surveyActTypes = self::getSurveyActivityType();
741 if (array_key_exists($activity->activity_type_id, $surveyActTypes)) {
742 $isSurveyActivity = TRUE;
743 }
744 }
745
746 return $isSurveyActivity;
747 }
748
749 /**
750 * This function retrive all response options of survey
751 *
752 * @param int $surveyId survey id.
2a6da8d7 753 * @return array $responseOptions an array of option values@static
6a488035
TO
754 */
755 static function getResponsesOptions($surveyId) {
756 $responseOptions = array();
757 if (!$surveyId) {
758 return $responseOptions;
759 }
760
761 $resultId = CRM_Core_DAO::getFieldValue('CRM_Campaign_DAO_Survey', $surveyId, 'result_id');
762 if ($resultId) {
763 $responseOptions = CRM_Core_OptionGroup::valuesByID($resultId);
764 }
765
766 return $responseOptions;
767 }
768
769 /**
770 * This function return all voter links with respecting permissions
771 *
2a6da8d7
EM
772 * @param $surveyId
773 * @param bool $enclosedInUL
774 * @param string $extraULName
775 * @return array|string $url array of permissioned links@static
6a488035
TO
776 */
777 static function buildPermissionLinks($surveyId, $enclosedInUL = FALSE, $extraULName = 'more') {
778 $menuLinks = array();
779 if (!$surveyId) {
780 return $menuLinks;
781 }
782
783 static $voterLinks = array();
784 if (empty($voterLinks)) {
785 $permissioned = FALSE;
786 if (CRM_Core_Permission::check('manage campaign') ||
787 CRM_Core_Permission::check('administer CiviCampaign')
788 ) {
789 $permissioned = TRUE;
790 }
791
792 if ($permissioned || CRM_Core_Permission::check("reserve campaign contacts")) {
793 $voterLinks['reserve'] = array(
794 'name' => 'reserve',
795 'url' => 'civicrm/survey/search',
2db64250 796 'qs' => 'sid=%%id%%&reset=1&op=reserve',
6a488035
TO
797 'title' => ts('Reserve Respondents'),
798 );
799 }
800 if ($permissioned || CRM_Core_Permission::check("interview campaign contacts")) {
801 $voterLinks['release'] = array(
802 'name' => 'interview',
803 'url' => 'civicrm/survey/search',
804 'qs' => 'sid=%%id%%&reset=1&op=interview&force=1',
805 'title' => ts('Interview Respondents'),
806 );
807 }
808 if ($permissioned || CRM_Core_Permission::check("release campaign contacts")) {
809 $voterLinks['interview'] = array(
810 'name' => 'release',
811 'url' => 'civicrm/survey/search',
812 'qs' => 'sid=%%id%%&reset=1&op=release&force=1',
813 'title' => ts('Release Respondents'),
814 );
815 }
816 }
817
818 if (CRM_Core_Permission::check('access CiviReport')) {
819 $reportID = self::getReportID($surveyId);
820 if ($reportID) {
91da6cd5 821 $voterLinks['report'] =
6a488035
TO
822 array(
823 'name' => 'report',
824 'url' => "civicrm/report/instance/{$reportID}",
825 'qs' => 'reset=1',
826 'title' => ts('View Survey Report'),
827 );
828 }
829 }
830
831 $ids = array('id' => $surveyId);
832 foreach ($voterLinks as $link) {
a7488080 833 if (!empty($link['qs']) &&
6a488035
TO
834 !CRM_Utils_System::isNull($link['qs'])
835 ) {
836 $urlPath = CRM_Utils_System::url(CRM_Core_Action::replace($link['url'], $ids),
837 CRM_Core_Action::replace($link['qs'], $ids)
838 );
a1c7d42f 839 $menuLinks[] = sprintf('<a href="%s" class="action-item crm-hover-button" title="%s">%s</a>',
6a488035
TO
840 $urlPath,
841 CRM_Utils_Array::value('title', $link),
842 $link['title']
843 );
844 }
845 }
846 if ($enclosedInUL) {
847 $extraLinksName = strtolower($extraULName);
848 $allLinks = '';
849 CRM_Utils_String::append($allLinks, '</li><li>', $menuLinks);
850 $allLinks = "$extraULName <ul id='panel_{$extraLinksName}_xx' class='panel'><li>{$allLinks}</li></ul>";
a1c7d42f 851 $menuLinks = "<span class='btn-slide crm-hover-button' id={$extraLinksName}_xx>{$allLinks}</span>";
6a488035
TO
852 }
853
854 return $menuLinks;
855 }
856
857 /**
858 * Function to retrieve survey associated profile id.
859 *
860 */
861 public static function getSurveyProfileId($surveyId) {
862 if (!$surveyId) {
863 return NULL;
864 }
865
866 static $ufIds = array();
867 if (!array_key_exists($surveyId, $ufIds)) {
868 //get the profile id.
869 $ufJoinParams = array(
870 'entity_id' => $surveyId,
871 'entity_table' => 'civicrm_survey',
872 'module' => 'CiviCampaign',
873 );
91da6cd5 874
6a488035
TO
875 list($first, $second) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams);
876
877 if ($first) {
91da6cd5 878 $ufIds[$surveyId] = array($first);
6a488035
TO
879 }
880 if ($second) {
91da6cd5 881 $ufIds[$surveyId][] = array_shift($second);
6a488035
TO
882 }
883 }
884
47dd4836 885 return CRM_Utils_Array::value($surveyId, $ufIds);
6a488035
TO
886 }
887
30c4e065
EM
888 /**
889 * @param $surveyId
890 *
891 * @return mixed
892 */
6a488035
TO
893 public Static function getReportID($surveyId) {
894 static $reportIds = array();
895
896 if (!array_key_exists($surveyId, $reportIds)) {
897 $query = "SELECT MAX(id) as id FROM civicrm_report_instance WHERE name = %1";
898 $reportID = CRM_Core_DAO::singleValueQuery($query, array(1 => array("survey_{$surveyId}",'String')));
899 $reportIds[$surveyId] = $reportID;
900 }
901 return $reportIds[$surveyId];
902 }
903
904 /**
905 * Function to decides the contact type for given survey.
906 *
907 */
908 public static function getSurveyContactType($surveyId) {
909 $contactType = NULL;
910
911 //apply filter of profile type on search.
912 $profileId = self::getSurveyProfileId($surveyId);
913 if ($profileId) {
914 $profileType = CRM_Core_BAO_UFField::getProfileType($profileId);
915 if (in_array($profileType, CRM_Contact_BAO_ContactType::basicTypes())) {
916 $contactType = $profileType;
917 }
918 }
919
920 return $contactType;
921 }
922
923 /**
924 * Function to get survey supportable profile types
925 *
926 */
927 public static function surveyProfileTypes() {
928 static $profileTypes;
929
930 if (!isset($profileTypes)) {
931 $profileTypes = array_merge(array('Activity', 'Contact'), CRM_Contact_BAO_ContactType::basicTypes());
932 $profileTypes = array_diff($profileTypes, array('Organization','Household'));
933 }
934
935 return $profileTypes;
936 }
937
938 /**
939 * Get the valid survey response fields those
940 * are configured with profile and custom fields.
941 *
942 * @param int $surveyId survey id.
943 * @param int $surveyTypeId survey activity type id.
944 *
945 * @return array an array of valid survey response fields.
946 */
947 public static function getSurveyResponseFields($surveyId, $surveyTypeId = NULL) {
948 if (empty($surveyId)) {
949 return array();
950 }
951
952 static $responseFields;
953 $cacheKey = "{$surveyId}_{$surveyTypeId}";
954
955 if (isset($responseFields[$cacheKey])) {
956 return $responseFields[$cacheKey];
957 }
958
959 $responseFields[$cacheKey] = array();
960
961 $profileId = self::getSurveyProfileId($surveyId);
962
963 if (!$profileId) {
964 return $responseFields;
965 }
966
967 if (!$surveyTypeId) {
968 $surveyTypeId = CRM_Core_DAO::getFieldValue('CRM_Campaign_DAO_Survey', $surveyId, 'activity_type_id');
969 }
970
971 $profileFields = CRM_Core_BAO_UFGroup::getFields($profileId,
5e5141ea 972 FALSE, CRM_Core_Action::VIEW, NULL, NULL, FALSE, NULL, FALSE, NULL, CRM_Core_Permission::CREATE, 'field_name', TRUE
6a488035
TO
973 );
974
975 //don't load these fields in grid.
976 $removeFields = array('File', 'RichTextEditor');
977
978 $supportableFieldTypes = self::surveyProfileTypes();
979
980 // get custom fields of type survey
981 $customFields = CRM_Core_BAO_CustomField::getFields('Activity', FALSE, FALSE, $surveyTypeId);
982
983 foreach ($profileFields as $name => $field) {
984 //get only contact and activity fields.
985 //later stage we might going to consider contact type also.
4e9ab75a
RN
986 if (in_array($field['field_type'], $supportableFieldTypes)) {
987 // we should allow all supported custom data for survey
988 // In case of activity, allow normal activity and with subtype survey,
989 // suppress custom data of other activity types
990 if (CRM_Core_BAO_CustomField::getKeyID($name)) {
991 if (!in_array($field['html_type'], $removeFields)) {
992 if ($field['field_type'] != 'Activity') {
993 $responseFields[$cacheKey][$name] = $field;
994 }
995 elseif (array_key_exists(CRM_Core_BAO_CustomField::getKeyID($name), $customFields)) {
996 $responseFields[$cacheKey][$name] = $field;
997 }
998 }
6a488035 999 }
4e9ab75a 1000 else {
6a488035
TO
1001 $responseFields[$cacheKey][$name] = $field;
1002 }
1003 }
6a488035
TO
1004 }
1005
1006 return $responseFields[$cacheKey];
1007 }
1008
1009 /**
1010 * Get all interviewers of surveys.
1011 *
1012 * @return array an array of valid survey response fields.
1013 */
1014 public static function getInterviewers() {
1015 static $interviewers;
1016
1017 if (isset($interviewers)) {
1018 return $interviewers;
1019 }
1020
1021 $whereClause = NULL;
1022 $activityTypes = self::getSurveyActivityType();
1023 if (!empty($activityTypes)) {
1024 $whereClause = ' WHERE survey.activity_type_id IN ( ' . implode(' , ', array_keys($activityTypes)) . ' )';
1025 }
1026
1027 $interviewers = array();
e7e657f0 1028 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
9e74e3ce 1029 $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
6a488035
TO
1030
1031 $query = "
91da6cd5 1032 SELECT contact.id as id,
6a488035 1033 contact.sort_name as sort_name
91da6cd5 1034 FROM civicrm_contact contact
9e74e3ce 1035INNER JOIN civicrm_activity_contact assignment ON ( assignment.contact_id = contact.id AND record_type_id = $assigneeID )
6a488035
TO
1036INNER JOIN civicrm_activity activity ON ( activity.id = assignment.activity_id )
1037INNER JOIN civicrm_survey survey ON ( activity.source_record_id = survey.id )
1038 {$whereClause}";
1039
1040 $interviewer = CRM_Core_DAO::executeQuery($query);
1041 while ($interviewer->fetch()) {
1042 $interviewers[$interviewer->id] = $interviewer->sort_name;
1043 }
1044
1045 return $interviewers;
1046 }
1047
1048 /**
1049 * Check and update the survey respondents.
1050 *
dd244018
EM
1051 * @param $params
1052 *
6a488035
TO
1053 * @return array success message
1054 */
1055 public function releaseRespondent($params) {
1056 $activityStatus = CRM_Core_PseudoConstant::activityStatus('name');
1057 $reserveStatusId = array_search('Scheduled', $activityStatus);
1058 $surveyActivityTypes = CRM_Campaign_BAO_Survey::getSurveyActivityType();
1059 $surveyActivityTypesIds = array_keys($surveyActivityTypes);
1060
1061 //retrieve all survey activities related to reserve action.
1062 $releasedCount = 0;
1063 if ($reserveStatusId && !empty($surveyActivityTypesIds)) {
1064 $query = '
91da6cd5 1065 SELECT activity.id as id,
6a488035
TO
1066 activity.activity_date_time as activity_date_time,
1067 survey.id as surveyId,
1068 survey.release_frequency as release_frequency
1069 FROM civicrm_activity activity
91da6cd5
DL
1070INNER JOIN civicrm_survey survey ON ( survey.id = activity.source_record_id )
1071 WHERE activity.is_deleted = 0
1072 AND activity.status_id = %1
6a488035
TO
1073 AND activity.activity_type_id IN ( ' . implode(', ', $surveyActivityTypesIds) . ' )';
1074 $activity = CRM_Core_DAO::executeQuery($query, array(1 => array($reserveStatusId, 'Positive')));
1075 $releasedIds = array();
1076 while ($activity->fetch()) {
1077 if (!$activity->release_frequency) {
1078 continue;
1079 }
1080 $reservedSeconds = CRM_Utils_Date::unixTime($activity->activity_date_time);
1081 $releasedSeconds = $activity->release_frequency * 24 * 3600;
1082 $totalReservedSeconds = $reservedSeconds + $releasedSeconds;
1083 if ($totalReservedSeconds < time()) {
1084 $releasedIds[$activity->id] = $activity->id;
1085 }
1086 }
1087
1088 //released respondent.
1089 if (!empty($releasedIds)) {
1090 $query = '
1091UPDATE civicrm_activity
1092 SET is_deleted = 1
1093 WHERE id IN ( ' . implode(', ', $releasedIds) . ' )';
1094 CRM_Core_DAO::executeQuery($query);
1095 $releasedCount = count($releasedIds);
1096 }
1097 }
1098
1099 $rtnMsg = array(
1100 'is_error' => 0,
1101 'messages' => "Number of respondents released = {$releasedCount}",
1102 );
1103
1104 return $rtnMsg;
1105 }
a2015e41
CW
1106
1107 /**
1108 * Get options for a given field.
1109 * @see CRM_Core_DAO::buildOptions
1110 *
1111 * @param String $fieldName
1112 * @param String $context: @see CRM_Core_DAO::buildOptionsContext
1113 * @param Array $props: whatever is known about this dao object
1114 *
1115 * @return array|bool
1116 */
1117 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
1118 $params = array();
1119 // Special logic for fields whose options depend on context or properties
1120 switch ($fieldName) {
1121 case 'activity_type_id':
1122 $campaignCompId = CRM_Core_Component::getComponentID('CiviCampaign');
1123 if ($campaignCompId) {
1124 $params['condition'] = array("component_id={$campaignCompId}", "v.name != 'Petition'");
1125 }
1126 break;
1127 }
1128 return CRM_Core_PseudoConstant::get(__CLASS__, $fieldName, $params, $context);
1129 }
6a488035
TO
1130}
1131