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