forked from mccrodp/message_private
-
Notifications
You must be signed in to change notification settings - Fork 0
/
message_private.module
executable file
·638 lines (561 loc) · 21.5 KB
/
message_private.module
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
<?php
/**
* Message Private with access permissions based on message fields.
*/
/**
* The string name for email notifications variable.
*/
define('MESSAGE_PRIVATE_EMAIL_NOTIFICATIONS', 'message_private_email_notifications');
/**
* The string name for message limit variable.
*/
define('MESSAGE_PRIVATE_MESSAGE_LIMIT', 'message_private_message_limit');
/**
* The assoc index to be used when fetching default limit variable.
*/
define('MESSAGE_PRIVATE_DEFAULT_LIMIT', 'message_private_default_limit');
/**
* The assoc index to be used when fetching default interval variable.
*/
define('MESSAGE_PRIVATE_DEFAULT_INTERVAL', 'message_private_default_interval');
/**
* The default index for settings such as role.
*/
define('MESSAGE_PRIVATE_DEFAULT_INDEX', 0);
/**
* The maximum message limit.
*/
define('MESSAGE_PRIVATE_MESSAGE_LIMIT_MAX', 1000);
/**
* The minimum message limit.
*/
define('MESSAGE_PRIVATE_MESSAGE_LIMIT_MIN', 1);
/**
* The maximum message interval in minutes.
*/
define('MESSAGE_PRIVATE_MESSAGE_INTERVAL_MAX', 1440);
/**
* The minimum message interval in minutes.
*/
define('MESSAGE_PRIVATE_MESSAGE_INTERVAL_MIN', 1);
/**
* Implements hook_help().
*/
function message_private_help($path, $arg) {
switch ($path) {
case 'admin/help#message_private':
$output = file_get_contents(drupal_get_path('module', 'message_private') . '/README.md');
return \Drupal::moduleHandler()->moduleExists('markdown') ? \Drupal\Component\Utility\Xss::filterAdmin(\Drupal::moduleHandler()->invoke('markdown', 'filter', ['process', 0, -1, $output])) : '<h3>Message Private README</h3><pre>' . \Drupal\Component\Utility\Html::escape($output) . '</pre>';
}
}
/**
* Implements hook_views_api().
*/
function message_private_views_api() {
list($module, $api) = func_get_args();
if ($module == 'views' && $api == 'views_default') {
return array('version' => '3.0');
}
return array();
}
/**
* Implements hook_permission().
*/
function message_private_permission() {
// Build the permissions.
$permissions = array();
$permissions['bypass private message access control'] = array(
'title' => t('Bypass message access control'),
'description' => t('Grant to the user the permission to apply CRUD option on any private messages.'),
'restrict access' => TRUE,
);
$permissions['administer message private'] = array(
'title' => t('Administer message private'),
'description' => t('Access the message private administration pages.'),
);
return $permissions;
}
/**
* Access callback for Messages tab.
*
* Checks for the private_message bundle and user permissions.
*
* @param object $message
* The message object.
*
* @return bool
* TRUE if the user is allowed perform the operation, FALSE otherwise.
*/
function message_private_access_callback($message) {
if ($message->type == 'private_message') {
return \Drupal::currentUser()->hasPermission('bypass private message access control') || \Drupal::currentUser()->hasPermission('view a private_message message instance');
}
return FALSE;
}
/**
* Implements hook_menu_alter().
*
* Override some of the menu paths set in message ui module.
*/
function message_private_menu_alter(&$items) {
// Override access callbacks.
$items['message/%message']['access callback'] = 'message_private_access_control';
$items['message/%message/view']['access callback'] = 'message_private_access_control';
$items['message/%message/edit']['access callback'] = 'message_private_access_control';
$items['message/%message/delete']['access callback'] = 'message_private_access_control';
// Override page created by message_ui to allow custom "Private Message" URI.
$items['admin/content/message/create']['page callback'] = 'message_private_create_new_message_instance_list';
// Unset menu item created by message_ui for private_message type.
unset($items['admin/content/message/create/private-message']);
return $items;
}
/**
* Message module access callback.
*
* @param string $operation
* The operation - create, view, update, delete.
* @param object|string $message
* The message object or message type.
* @param object|null $user_obj
* A user object. Optional.
*
* @return bool
* TRUE if user is allowed to perform the message operation, FALSE otherwise.
*/
function message_private_access_control($operation, $message, $user_obj = NULL) {
if (empty($user_obj)) {
$user = \Drupal::currentUser();
$account = \Drupal::entityManager()->getStorage('user')->load($user->uid);
}
else {
$user = $user_obj;
$account = \Drupal::entityManager()->getStorage('user')->load($user->uid);
}
// Get the message type from the function argument or from the message object.
$type = is_object($message) ? $message->type : $message;
// If this is not a private message then use the message callback provided by
// message_ui module.
if ($type != 'private_message') {
return message_ui_access_control($operation, $message);
}
else {
if ($account->hasPermission('bypass private message access control')) {
return TRUE;
}
// Verify that the user can apply the op.
if ($account->hasPermission($operation . ' any message instance')
|| $account->hasPermission($operation . ' a ' . $type . ' message instance')
) {
if ($type == 'private_message' && $operation != 'create') {
// Check if the user is message author.
if ($message->uid == $account->uid) {
return TRUE;
}
$users = field_get_items('message', $message, 'field_message_user_ref');
if ($users && is_array($users)) {
foreach ($users as $user_ref) {
if ($user_ref['target_id'] == $account->uid) {
return TRUE;
}
}
}
}
else {
return TRUE;
}
}
}
return FALSE;
}
/**
* Override instance list provided by Message UI.
*
* Create links to all message create forms by type, allowing for creation of
* link to custom Private Message create form URI.
*
* @return null|string
* @throws Exception
*/
function message_private_create_new_message_instance_list() {
$items = array();
$allowed_types = message_ui_user_can_create_message();
if ($types = message_ui_get_types()) {
foreach ($types as $type => $title) {
if ($allowed_types || (is_array($allowed_types) && $allowed_types[$type])) {
// Create links to message create forms.
if ($type != 'private_message') {
// @FIXME
// l() expects a Url object, created from a route name or external URI.
// $items[] = l($title, 'admin/content/message/create/' . str_replace('_', '-', $type));
}
else {
// Create link to customised menu item for private_message create.
// @FIXME
// l() expects a Url object, created from a route name or external URI.
// $items[] = l($title, 'message/create/' . str_replace('_', '-', $type));
}
}
}
}
else {
// @FIXME
// url() expects a route name or an external URI.
// return t("There are no messages types. You can create a new message type <a href='@url'>here</a>.", array('@url' => url('admin/structure/messages/add')));
}
// @FIXME
// theme() has been renamed to _theme() and should NEVER be called directly.
// Calling _theme() directly can alter the expected output and potentially
// introduce security issues (see https://www.drupal.org/node/2195739). You
// should use renderable arrays instead.
//
//
// @see https://www.drupal.org/node/2195739
// return theme('item_list', array('items' => $items));
}
/**
* Implements hook_form_FORM_ID_alter().
*
* This function is defined to override that provided by Message UI module. This
* allows override specific values of the form such as the cancel link. It hides
* the message_text on the edit and create form, and adds custom validation.
*/
function message_private_form_message_ui_instance_message_manage_alter(&$form, &$form_state, $form_id) {
if (!empty($form_state['#entity']) && $form_state['#entity']->type == 'private_message') {
$user = \Drupal::currentUser();
$referer = $_SERVER['HTTP_REFERER']; // Get the referrer uri from globals.
// Redirect back to referer uri is exists, otherwise to user message inbox.
// @FIXME
// l() expects a Url object, created from a route name or external URI.
// $form['actions']['cancel']['#markup'] =
l(t('Cancel'), (!empty($referer) ? $referer : 'user/'. $user->uid . '/messages'));
if (isset($form['text']['#type'])) {
$form['text']['#type'] = 'hidden';
}
$form['owner']['#access'] = \Drupal::currentUser()->hasPermission('bypass private message access control');
$form['#validate'][] = 'message_private_form_message_private_instance_message_manage_validate';
}
}
/**
* Implements hook_form_FORM_ID_alter().
*
* Override redirect for private messages.
*/
function message_private_form_message_ui_instance_delete_alter(&$form, &$form_state, $form_id) {
if (!empty($form_state['#entity']) && $form_state['#entity']->type == 'private_message') {
$user = \Drupal::currentUser();
$referer = $_SERVER['HTTP_REFERER']; // Get the referrer uri from globals.
// Redirect back to referer uri is exists, otherwise to user message inbox.
$form['actions']['cancel']['#href'] = !empty($referer) ? $referer : 'user/'. $user->uid . '/messages';
// Call custom submit callback for private messages.
$form['#submit'] = array('message_private_instance_delete_submit');
}
}
/**
* Custom submit callback for deleting private messages.
*/
function message_private_instance_delete_submit($form, &$form_state) {
if ($form_state['clicked_button']['#type']) {
$user = \Drupal::currentUser();
$form_state['#entity']->delete();
// Redirect back to user message inbox.
$form_state['redirect'] = 'user/' . $user->uid . '/messages';
drupal_set_message(t('The message instance @type deleted successfully', array(
'@type' => $form_state['#entity']->type,
)));
}
}
/**
* Implements hook_menu_local_tasks_alter().
*/
function message_private_menu_local_tasks_alter(&$data, $router_item, $root_path) {
$user = \Drupal::currentUser();
switch ($root_path) {
case 'user/%':
// Add a 'Create a new message for %user' action link.
if (is_array($router_item['page_arguments'])) {
// Get the user object from page arguments.
foreach ($router_item['page_arguments'] as $arg) {
if (is_object($arg) && !empty($arg->uid)) {
$to_user = $arg;
}
}
}
// Only display the local task on other users profile, not current user's.
if (!empty($to_user) && $user->uid != $to_user->uid) {
// @FIXME
// menu_get_item() has been removed. To retrieve route information, use the
// RouteMatch object, which you can retrieve by calling \Drupal::routeMatch().
//
//
// @see https://www.drupal.org/node/2203305
// $item = menu_get_item('message/create/private-message');
$item['title'] = t('Create a new message for') . ' ' . $to_user->name;
$item['localized_options']['query'] = array('field_message_user_ref' => $to_user->uid);
$data['actions']['output'][] = array(
'#theme' => 'menu_local_action',
'#link' => $item,
);
}
break;
case 'user/%/messages':
// Add a 'Create a new message' action link above message_private view.
// @FIXME
// menu_get_item() has been removed. To retrieve route information, use the
// RouteMatch object, which you can retrieve by calling \Drupal::routeMatch().
//
//
// @see https://www.drupal.org/node/2203305
// $item = menu_get_item('message/create/private-message');
$item['title'] = t('Create a new message');
$data['actions']['output'][] = array(
'#theme' => 'menu_local_action',
'#link' => $item,
);
break;
case 'message/%':
$message = \Drupal::routeMatch()->getParameter('message', 1, $router_item['href']);
if (isset($message->type) && $message->type == 'private_message') {
// Add a Messages tab to the private_message Message entities.
// @FIXME
// menu_get_item() has been removed. To retrieve route information, use the
// RouteMatch object, which you can retrieve by calling \Drupal::routeMatch().
//
//
// @see https://www.drupal.org/node/2203305
// $item = menu_get_item('user/' . $user->uid . '/messages');
$item['title'] = t('Messages');
$data['tabs'][0]['output'][] = array(
'#theme' => 'menu_local_task',
'#link' => $item,
);
// Get from user to Add a 'Create a new message for %user' action link.
$to_user = \Drupal::entityManager()->getStorage('user')->load($message->uid);
// Display the local task on other users profile, not current user's.
if (!empty($to_user) && $user->uid != $to_user->uid) {
// @FIXME
// menu_get_item() has been removed. To retrieve route information, use the
// RouteMatch object, which you can retrieve by calling \Drupal::routeMatch().
//
//
// @see https://www.drupal.org/node/2203305
// $item = menu_get_item('message/create/private-message');
$item['title'] = t('Create a new message for') . ' ' . $to_user->name;
$item['localized_options']['query'] = array('field_message_user_ref' => $to_user->uid);
$data['actions']['output'][] = array(
'#theme' => 'menu_local_action',
'#link' => $item,
);
}
}
break;
}
}
/**
* Validation for Private Message form.
*
* @param mixed $form
* The message form provided by message_ui.
* @param mixed $form_state
* The form state including values submitted.
*/
function message_private_form_message_private_instance_message_manage_validate($form, &$form_state) {
// If there is an imposed message limit set in the admin settings interface.
// @FIXME
// // @FIXME
// // The correct configuration object could not be determined. You'll need to
// // rewrite this call manually.
// if (variable_get(MESSAGE_PRIVATE_MESSAGE_LIMIT, FALSE)
// && !\Drupal::currentUser()->hasPermission('bypass private message access control')) {
// $user = \Drupal::currentUser();
//
// // Get the role belonging to user with max message limit.
// $rid = _message_private_max_message_limit_role($user->roles);
// $role = user_role_load($rid);
//
// // Get the message limitation settings for this role.
// $role_name = str_replace(' ', '_', $role->name);
// $limit_name = 'message_private_' . $role_name . '_limit';
// $interval_name = 'message_private_' . $role_name . '_interval';
// $interval = variable_get($interval_name);
// $limit = variable_get($limit_name);
//
// // Calculate timestamp of the last interval.
// $current_timestamp = time();
// $interval_timestamp = strtotime('-' . $interval . ' minutes', $current_timestamp);
//
// // Get total amount of this user's messages since last interval.
// $query = new EntityFieldQuery();
// $total = $query->entityCondition('entity_type', 'message')
// ->entityCondition('bundle', 'private_message')
// ->propertyCondition('timestamp', $interval_timestamp, '>')
// ->propertyCondition('uid', $user->uid)
// ->count()
// ->execute();
//
// // Display error preventing message create when total messages over limit.
// if ($total >= $limit) {
// form_error($form, t('Message create limit reached. Please try again later.'));
// }
// }
}
/**
* Implements hook_message_insert().
*
* Send an email if a private message has been created.
*
* Currently addslashes() or equivalent is not used on the email,
* this may be an issue with the message module itself as I don't
* think escaping strings for email should be done in this module.
*/
function message_private_message_insert($message) {
// Prepare message notifications for private messages if notifications are on.
// @FIXME
// // @FIXME
// // The correct configuration object could not be determined. You'll need to
// // rewrite this call manually.
// if ($message->type == 'private_message'
// && variable_get(MESSAGE_PRIVATE_EMAIL_NOTIFICATIONS, TRUE)) {
// // Use message load as the $message object has issue with mail function.
// // It causes duplicate entry, possibly as mid is missing and the mail
// // function message_notify_send_message tries to re-save as a new message.
// $message = message_load($message->mid);
// $wrapper = entity_metadata_wrapper('message', $message);
//
// $mail = array();
// $users = $wrapper->field_message_user_ref->value();
//
// if (is_array($users)) {
// foreach ($users as $user) {
// $notify = field_get_items('user', $user, 'field_private_message_notify');
// if (!empty($notify) && is_array($notify)) {
// // Get the 1st value of the array as there is only 1 possible item.
// $notify = array_shift($notify);
// }
// // If the user has set field for notifications, add their email.
// if (isset($notify['value']) && $notify['value']) {
// $mail[] = $user->mail;
// }
// }
// }
// if (!empty($mail)) {
// message_notify_send_message($message, array('mail' => implode(',', $mail)));
// }
// }
}
/**
* Implements hook_form_FORM_ID_alter().
*
* If email notifications are disabled, hide the per user setting on user
* profiles, unless the user is in role with bypass access control permission.
*/
function message_private_form_user_profile_form_alter(&$form, &$form_state, $form_id) {
// @FIXME
// // @FIXME
// // The correct configuration object could not be determined. You'll need to
// // rewrite this call manually.
// if (!\Drupal::currentUser()->hasPermission('bypass private message access control')
// && !variable_get(MESSAGE_PRIVATE_EMAIL_NOTIFICATIONS, TRUE)) {
// $form['field_private_message_notify']['#access'] = FALSE;
// }
}
/**
* Implements hook_theme().
*/
function message_private_theme() {
$info['message_private'] = array(
'render element' => 'elements',
'template' => 'message--private_message',
'base hook' => 'message_private',
);
return $info;
}
/**
* Implements hook_message_view_alter().
*/
function message_private_message_view_alter(&$build) {
// Use template_preprocess_message_private for private_message messages only.
if (!empty($build['#bundle']) && $build['#bundle'] == 'private_message') {
$build['#theme'] = 'message_private';
}
}
/**
* Process variables for message--private_message.tpl.php.
*/
function template_preprocess_message_private(&$variables) {
// Call the parent message template function defined in message module.
if (function_exists('template_preprocess_message')) {
template_preprocess_message($variables);
}
// Save the message entity for ease of access.
if (is_object($variables['elements']['#entity'])) {
$message = $variables['elements']['#entity'];
}
// Create submitted variable containing user who created the message and date.
if (!empty($message) && $uid = $message->uid) {
$variables['date'] = format_date($message->timestamp);
// @FIXME
// theme() has been renamed to _theme() and should NEVER be called directly.
// Calling _theme() directly can alter the expected output and potentially
// introduce security issues (see https://www.drupal.org/node/2195739). You
// should use renderable arrays instead.
//
//
// @see https://www.drupal.org/node/2195739
// $variables['name'] = theme('username', array('account' => user_load($uid)));
$variables['submitted'] = t('Submitted by !username on !datetime', array(
'!username' => $variables['name'],
'!datetime' => $variables['date'],
));
}
}
/**
* Get the role id with the maximum allowed message create limit.
*
* Using the values set for each role, calculate the the lowest time interval
* required per message: INTERVAL / LIMIT and return the role with this value.
*
* @param null|array $roles
* An assoc array of role names and ids.
*
* @return mixed
* Either a role id or null.
*/
function _message_private_max_message_limit_role($roles) {
$limits = array();
// @FIXME
// // @FIXME
// // The correct configuration object could not be determined. You'll need to
// // rewrite this call manually.
// $limit = variable_get(MESSAGE_PRIVATE_DEFAULT_LIMIT);
// @FIXME
// // @FIXME
// // The correct configuration object could not be determined. You'll need to
// // rewrite this call manually.
// $interval = variable_get(MESSAGE_PRIVATE_DEFAULT_INTERVAL);
// Ensure we have existing valid numerical values for both variables.
if (!empty($limit) && ctype_digit($limit) && !empty($interval) && ctype_digit($interval)) {
$limits[MESSAGE_PRIVATE_DEFAULT_INDEX] = $interval / $limit;
}
// Cycle through the roles and get each limit and interval.
foreach ($roles as $rid => $role) {
$role_name = str_replace(' ', '_', $role);
$limit_name = 'message_private_' . $role_name . '_limit';
$interval_name = 'message_private_' . $role_name . '_interval';
// @FIXME
// // @FIXME
// // The correct configuration object could not be determined. You'll need to
// // rewrite this call manually.
// $interval = variable_get($interval_name);
// @FIXME
// // @FIXME
// // The correct configuration object could not be determined. You'll need to
// // rewrite this call manually.
// $limit = variable_get($limit_name);
// Ensure we have existing valid numerical values for both variables.
if (!empty($limit) && ctype_digit($limit) && !empty($interval) && ctype_digit($interval)) {
$limits[$rid] = $interval / $limit;
}
}
// The min value corresponds to the lowest interval required per message.
return array_search(min($limits), $limits);
}