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