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