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