Merge pull request #1834 from monishdeb/CRM-13614
[civicrm-core.git] / CRM / Member / Form / MembershipView.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
232624b1 4 | CiviCRM version 4.4 |
6a488035
TO
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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-2013
32 * $Id$
33 *
34 */
35
36/**
37 * This class generates form components for Payment-Instrument
38 *
39 */
40class CRM_Member_Form_MembershipView extends CRM_Core_Form {
41
42 /**
43 * The action links that we need to display for the browse screen
44 *
45 * @var array
46 * @static
47 */
48 static $_links = NULL;
49
50 /**
51 * Add context information at the end of a link
52 *
53 * @return text extra query parameters
54 */
55 function addContext() {
56 $extra = '';
57 foreach (array('context', 'selectedChild') as $arg) {
58 if ($value = CRM_Utils_Request::retrieve($arg, 'String', $this)) {
59 $extra .= "&{$arg}={$value}";
60 }
61 }
62 return $extra;
63 }
64
65 /**
66 * Get action Links
67 *
68 * @return array (reference) of action links
69 */
70 function &links() {
71 if (!(self::$_links)) {
72 self::$_links = array(
73 CRM_Core_Action::DELETE => array(
74 'name' => ts('Delete'),
75 'url' => 'civicrm/contact/view/membership',
76 'qs' => 'action=view&id=%%id%%&cid=%%cid%%&relAction=delete&mid=%%mid%%&reset=1' . $this->addContext(),
77 'title' => ts('Cancel Related Membership'),
78 ),
79 CRM_Core_Action::ADD => array(
80 'name' => ts('Create'),
81 'url' => 'civicrm/contact/view/membership',
82 'qs' => 'action=view&id=%%id%%&cid=%%cid%%&relAction=create&rid=%%rid%%&reset=1' . $this->addContext(),
83 'title' => ts('Create Related Membership'),
84 ),
85 );
86 }
87 return self::$_links;
88 }
89
90 /**
91 * Perform create or delete action on related memberships
92 *
93 * @param string $action create or delete
94 * @param array $owner primary membership info (membership_id, contact_id, membership_type ...)
95 *
96 */
97 function relAction($action, $owner) {
98 switch ($action) {
99 case 'delete':
100 $id = CRM_Utils_Request::retrieve('mid', 'Positive', $this);
101 $relatedContactId = CRM_Utils_Request::retrieve('cid', 'Positive', $this);
102 $relatedDisplayName = CRM_Contact_BAO_Contact::displayName($relatedContactId);
3506b6cd 103 CRM_Member_BAO_Membership::del($id);
8d8bd076 104 CRM_Core_Session::setStatus(ts('Related membership for %1 has been deleted.', array(1 => $relatedDisplayName)),
105 ts('Membership Deleted'), 'success');
6a488035
TO
106 break;
107 case 'create':
108 $ids = array();
109 $params = array(
8d8bd076 110 'contact_id' => CRM_Utils_Request::retrieve('rid', 'Positive', $this),
111 'membership_type_id' => $owner['membership_type_id'],
112 'owner_membership_id' => $owner['id'],
113 'join_date' => CRM_Utils_Date::processDate($owner['join_date'], NULL, TRUE, 'Ymd'),
114 'start_date' => CRM_Utils_Date::processDate($owner['start_date'], NULL, TRUE, 'Ymd'),
115 'end_date' => CRM_Utils_Date::processDate($owner['end_date'], NULL, TRUE, 'Ymd'),
116 'source' => ts('Manual Assignment of Related Membership'),
117 'is_test' => $owner['is_test'],
118 'campaign_id' => CRM_Utils_Array::value('campaign_id', $owner),
119 'status_id' => $owner['status_id'],
120 'skipStatusCal' => TRUE,
121 'createActivity' => TRUE,
6a488035
TO
122 );
123 CRM_Member_BAO_Membership::create($params, $ids);
124 $relatedDisplayName = CRM_Contact_BAO_Contact::displayName($params['contact_id']);
8d8bd076 125 CRM_Core_Session::setStatus(ts('Related membership for %1 has been created.', array(1 => $relatedDisplayName)),
126 ts('Membership Added'), 'success');
6a488035
TO
127 break;
128 default:
129 CRM_Core_Error::fatal(ts("Invalid action specified in URL"));
130 }
131
132 // Redirect back to membership view page for the owner, without the relAction parameters
133 CRM_Utils_System::redirect(
134 CRM_Utils_System::url(
135 'civicrm/contact/view/membership',
136 "action=view&reset=1&id={$owner['membership_id']}&cid={$owner['contact_id']}" . $this->addContext()
137 )
138 );
139 }
140
141 /**
142 * Function to set variables up before form is built
143 *
144 * @return void
145 * @access public
146 */
147 public function preProcess() {
148
149 $values = array();
150 $id = CRM_Utils_Request::retrieve('id', 'Positive', $this);
151
152 // Make sure context is assigned to template for condition where we come here view civicrm/membership/view
153 $context = CRM_Utils_Request::retrieve('context', 'String', $this);
154 $this->assign('context', $context);
155
156 if ($id) {
157 $params = array('id' => $id);
158
159 CRM_Member_BAO_Membership::retrieve($params, $values);
160 $membershipType = CRM_Member_BAO_MembershipType::getMembershipTypeDetails($values['membership_type_id']);
161
162 // Do the action on related Membership if needed
163 $relAction = CRM_Utils_Request::retrieve('relAction', 'String', $this);
164 if ($relAction) {
165 $this->relAction($relAction, $values);
166 }
167
168 // build associated contributions
8d8bd076 169 $this->assign('accessContribution', FALSE);
170 if (CRM_Core_Permission::access('CiviContribute')) {
171 $this->assign('accessContribution', TRUE);
172 CRM_Member_Page_Tab::associatedContribution($values['contact_id'], $id);
173 }
6a488035
TO
174
175 //Provide information about membership source when it is the result of a relationship (CRM-1901)
176 $values['owner_membership_id'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership',
177 $id,
178 'owner_membership_id'
179 );
180
181 if (isset($values['owner_membership_id'])) {
182 $values['owner_contact_id'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership',
183 $values['owner_membership_id'],
184 'contact_id',
185 'id'
186 );
187
188 $values['owner_display_name'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
189 $values['owner_contact_id'],
190 'display_name',
191 'id'
192 );
193
194 $direction = strrev($membershipType['relationship_direction']);
195 // To display relationship type in view membership page
196 $relTypeIds = str_replace(CRM_Core_DAO::VALUE_SEPARATOR, ",", $membershipType['relationship_type_id']);
197 $sql = "
198SELECT relationship_type_id,
03e04002 199 CASE
6a488035
TO
200 WHEN contact_id_a = {$values['owner_contact_id']} AND contact_id_b = {$values['contact_id']} THEN 'b_a'
201 WHEN contact_id_b = {$values['owner_contact_id']} AND contact_id_a = {$values['contact_id']} THEN 'a_b'
202END AS 'relType'
03e04002 203 FROM civicrm_relationship
6a488035
TO
204 WHERE relationship_type_id IN ($relTypeIds)";
205 $dao = CRM_Core_DAO::executeQuery($sql);
206 $values['relationship'] = NULL;
207 while ($dao->fetch()) {
208 $typeId = $dao->relationship_type_id;
209 $direction = $dao->relType;
210 if ($direction && $typeId) {
211 if ($values['relationship']) {
212 $values['relationship'] .= ',';
213 }
214 $values['relationship'] .= CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_RelationshipType',
215 $typeId,
216 "name_$direction",
217 'id'
218 );
219 }
220 }
221 }
222
223 $this->assign('has_related', FALSE);
224 // if membership can be granted, and we are the owner of the membership
225 if (CRM_Utils_Array::value('relationship_type_id', $membershipType)
8d8bd076 226 && !CRM_Utils_Array::value('owner_membership_id', $values)
227 ) {
6a488035
TO
228 // display related contacts/membership block
229 $this->assign('has_related', TRUE);
230 $this->assign('max_related', CRM_Utils_Array::value('max_related', $values, ts('Unlimited')));
231 // split the relations in 2 arrays based on direction
232 $relTypeId = explode(CRM_Core_DAO::VALUE_SEPARATOR, $membershipType['relationship_type_id']);
233 $relDirection = explode(CRM_Core_DAO::VALUE_SEPARATOR, $membershipType['relationship_direction']);
234 foreach ($relTypeId as $rid) {
235 $dir = each($relDirection);
236 $relTypeDir[substr($dir['value'], 0, 1)][] = $rid;
237 }
238 // build query in 2 parts with a UNION if necessary
239 // _x and _y are replaced with _a and _b first, then vice-versa
240 // comment is a qualifier for the relationship - now just job_title
241 $select = "
242SELECT r.id, c.id as cid, c.display_name as name, c.job_title as comment,
243 rt.name_x_y as relation, r.start_date, r.end_date,
244 m.id as mid, ms.is_current_member, ms.label as status
245 FROM civicrm_relationship r
246 LEFT JOIN civicrm_relationship_type rt ON rt.id = r.relationship_type_id
247 LEFT JOIN civicrm_contact c ON c.id = r.contact_id_x
8d8bd076 248 LEFT JOIN civicrm_membership m ON (m.owner_membership_id = {$values['id']}
249 AND m.contact_id = r.contact_id_x AND m.is_test = 0)
6a488035
TO
250 LEFT JOIN civicrm_membership_status ms ON ms.id = m.status_id
251 WHERE r.contact_id_y = {$values['contact_id']} AND r.is_active = 1 AND c.is_deleted = 0";
252 $query = '';
8d8bd076 253 foreach (array('a', 'b') as $dir) {
2eef47ee 254 if (isset($relTypeDir[$dir])) {
6a488035 255 $query .= ($query ? ' UNION ' : '')
8d8bd076 256 . str_replace('_y', '_' . $dir, str_replace('_x', '_' . ($dir == 'a' ? 'b' : 'a'), $select))
257 . ' AND r.relationship_type_id IN (' . implode(',', $relTypeDir[$dir]) . ')';
6a488035
TO
258 }
259 }
260 $query .= " ORDER BY is_current_member DESC";
261 $dao = CRM_Core_DAO::executeQuery($query);
262 $related = array();
263 $relatedRemaining = CRM_Utils_Array::value('max_related', $values, PHP_INT_MAX);
8d8bd076 264 $rowElememts = array(
265 'id',
266 'cid',
267 'name',
268 'comment',
269 'relation',
270 'mid',
271 'start_date',
272 'end_date',
273 'is_current_member',
274 'status'
275 );
276
6a488035
TO
277 while ($dao->fetch()) {
278 $row = array();
8d8bd076 279 foreach ($rowElememts as $field) {
6a488035
TO
280 $row[$field] = $dao->$field;
281 }
282 if ($row['mid'] && ($row['is_current_member'] == 1)) {
283 $relatedRemaining--;
284 $row['action'] = CRM_Core_Action::formLink(self::links(), CRM_Core_Action::DELETE,
285 array(
286 'id' => CRM_Utils_Request::retrieve('id', 'Positive', $this),
287 'cid' => $row['cid'],
288 'mid' => $row['mid'],
289 )
290 );
8d8bd076 291 }
292 else {
293 if ($relatedRemaining > 0) {
6a488035
TO
294 $row['action'] = CRM_Core_Action::formLink(self::links(), CRM_Core_Action::ADD,
295 array(
296 'id' => CRM_Utils_Request::retrieve('id', 'Positive', $this),
297 'cid' => $row['cid'],
298 'rid' => $row['cid'],
299 )
300 );
8d8bd076 301 }
6a488035
TO
302 }
303 $related[] = $row;
304 }
305 $this->assign('related', $related);
306 if ($relatedRemaining <= 0) {
307 $this->assign('related_text', ts('None available'));
8d8bd076 308 }
309 else {
310 if ($relatedRemaining < 100000) {
311 $this->assign('related_text', ts('%1 available', array(1 => $relatedRemaining)));
312 }
313 else {
314 $this->assign('related_text', ts('Unlimited', array(1 => $relatedRemaining)));
315 }
6a488035
TO
316 }
317 }
318
319 $displayName = CRM_Contact_BAO_Contact::displayName($values['contact_id']);
320 $this->assign('displayName', $displayName);
03e04002 321
6a488035
TO
322 // Check if this is default domain contact CRM-10482
323 if (CRM_Contact_BAO_Contact::checkDomainContact($values['contact_id'])) {
324 $displayName .= ' (' . ts('default organization') . ')';
325 }
326
8d8bd076 327 // omitting contactImage from title for now since the summary overlay css doesn't work outside crm-container
328 CRM_Utils_System::setTitle(ts('View Membership for') . ' ' . $displayName);
03e04002 329
6a488035
TO
330 // add viewed membership to recent items list
331 $recentTitle = $displayName . ' - ' . ts('Membership Type:') . ' ' . $values['membership_type'];
332 $url = CRM_Utils_System::url('civicrm/contact/view/membership',
333 "action=view&reset=1&id={$values['id']}&cid={$values['contact_id']}&context=home"
334 );
335
336 $recentOther = array();
337 if (CRM_Core_Permission::checkActionPermission('CiviMember', CRM_Core_Action::UPDATE)) {
338 $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/membership',
339 "action=update&reset=1&id={$values['id']}&cid={$values['contact_id']}&context=home"
340 );
341 }
342 if (CRM_Core_Permission::checkActionPermission('CiviMember', CRM_Core_Action::DELETE)) {
343 $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/contact/view/membership',
344 "action=delete&reset=1&id={$values['id']}&cid={$values['contact_id']}&context=home"
345 );
346 }
347 CRM_Utils_Recent::add($recentTitle,
348 $url,
349 $values['id'],
350 'Membership',
351 $values['contact_id'],
352 NULL,
353 $recentOther
354 );
355
8d8bd076 356 CRM_Member_Page_Tab::setContext($this, $values['contact_id']);
6a488035
TO
357
358 $memType = CRM_Core_DAO::getFieldValue("CRM_Member_DAO_Membership", $id, "membership_type_id");
359
360 $groupTree = CRM_Core_BAO_CustomGroup::getTree('Membership', $this, $id, 0, $memType);
361 CRM_Core_BAO_CustomGroup::buildCustomDataView($this, $groupTree);
362
363 $isRecur = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $id, 'contribution_recur_id');
364
365 $autoRenew = $isRecur ? TRUE : FALSE;
366 }
367
368 if (CRM_Utils_Array::value('is_test', $values)) {
369 $values['membership_type'] .= ' (test) ';
370 }
371
372 $subscriptionCancelled = CRM_Member_BAO_Membership::isSubscriptionCancelled($id);
373 $values['auto_renew'] = ($autoRenew && !$subscriptionCancelled) ? 'Yes' : 'No';
374
375 //do check for campaigns
376 if ($campaignId = CRM_Utils_Array::value('campaign_id', $values)) {
377 $campaigns = CRM_Campaign_BAO_Campaign::getCampaigns($campaignId);
378 $values['campaign'] = $campaigns[$campaignId];
379 }
380
381 $this->assign($values);
382 }
383
384 /**
385 * Function to build the form
386 *
387 * @return None
388 * @access public
389 */
390 public function buildQuickForm() {
391 $this->addButtons(array(
392 array(
393 'type' => 'cancel',
394 'name' => ts('Done'),
395 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
396 'isDefault' => TRUE,
397 ),
398 )
399 );
400 }
401}
402