forked from socketwench/flag-drupal8
-
Notifications
You must be signed in to change notification settings - Fork 0
/
flag.module
620 lines (551 loc) · 20.6 KB
/
flag.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
<?php
/**
* @file
* The Flag module.
*/
define('FLAG_API_VERSION', 3);
define('FLAG_ADMIN_PATH', 'admin/structure/flags');
define('FLAG_ADMIN_PATH_START', 3);
use Drupal\Component\Utility\String;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Entity\Entity\EntityViewDisplay;
use Drupal\flag\Entity\Flag;
use Drupal\node\NodeInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\user\UserInterface;
use Drupal\Core\Form\FormStateInterface;
/**
* Implements hook_help().
*/
function flag_help($route_name, RouteMatchInterface $route_match) {
switch ($route_name) {
case 'flag.list':
$output = '<p>' . t('This page lists all the <em>flags</em> that are currently defined on this system.') . '</p>';
return $output;
case 'flag.add_page':
$output = '<p>' . t('Select the type of flag to create. An individual flag can only affect one type of object. This cannot be changed once the flag is created.') . '</p>';
return $output;
case 'field_ui.overview_flagging':
// @todo: Doesn't make sense at the moment, implement when form
// functionality is available.
/*
// Get the existing link types that provide a flagging form.
$link_types = flag_get_link_types();
$form_link_types = array();
foreach (flag_get_link_types() as $link_type) {
if ($link_type['provides form']) {
$form_link_types[] = '<em>' . $link_type['title'] . '</em>';
}
}
// Get the flag for which we're managing fields.
$flag = menu_get_object('flag', FLAG_ADMIN_PATH_START + 1);
// Common text.
$output = '<p>' . t('Flags can have fields added to them. For example, a "Spam" flag could have a <em>Reason</em> field where a user could type in why he believes the item flagged is spam. A "Bookmarks" flag could have a <em>Folder</em> field into which a user could arrange her bookmarks.') . '</p>';
$output .= '<p>' . t('On this page you can add fields to flags, delete them, and otherwise manage them.') . '</p>';
// Three cases:
if ($flag->link_type == 'form') {
// Case 1: the current link type is the flagging form. Don't tell the
// user anything extra, all is fine.
}
elseif ($link_types[$flag->link_type]['provides form']) {
// Case 2: the current link type shows the form for creation of the
// flagging, but it not the flagging form. Tell the user they can't edit
// existing flagging fields.
$output .= t("Field values may be edited when flaggings are created because this flag's link type shows a form for the flagging. However, to edit field values on existing flaggings, you will need to set your flag to use the <em>Flagging form</em> link type. This is provided by the <em><a href='!flagging-form-url'>Flagging Form</a></em> module.", array(
'!flagging-form-url' => 'http://drupal.org/project/flagging_form',
));
if (!\Drupal::moduleHandler()->moduleExists('flagging_form')) {
$output .= ' <span class="warning">'
. t("You do not currently have this module enabled.")
. '</span>';
}
$output .= '</p>';
}
else {
// Case 3: the current link type does not allow access to the flagging
// form. Tell the user they should change it.
$output .= '<p class="warning">' . t("To allow users to enter values for fields you will need to <a href='!form-link-type-url'>set your flag</a> to use one of the following link types which allow users to access the flagging form: !link-types-list. (In case a form isn't used, the fields are assigned their default values.)", array(
'!form-link-type-url' => url('admin/structure/flags/manage/' . $flag->name, array('fragment' => 'edit-link-type')),
// The list of labels from link types. These are all defined in code
// in hook_flag_link_type_info() and therefore safe to output raw.
'!link-types-list' => implode(', ', $form_link_types),
)) . '</p>';
$output .= '<p>' . t("Additionally, to edit field values on existing flaggings, you will need to set your flag to use the Flagging form link type. This is provided by the <em><a href='!flagging-form-url'>Flagging Form</a></em> module.", array(
'!flagging-form-url' => 'http://drupal.org/project/flagging_form',
));
if (!\Drupal::moduleHandler()->moduleExists('flagging_form')) {
$output .= ' <span class="warning">'
. t("You do not currently have this module enabled.")
. '</span>';
}
$output .= '</p>';
}
return $output;
*/
}
}
/**
* Implements hook_form_FORM_ID_alter(): user_admin_permissions().
*
* Disable permission on the permissions form that don't make sense for
* anonymous users when Session API module is not enabled.
*/
function flag_form_user_admin_permissions_alter(&$form, FormStateInterface $form_state, $form_id) {
if (!\Drupal::moduleHandler()->moduleExists('session_api')) {
$flags = \Drupal::service('flag')->getFlags();
// Disable flag and unflag permission checkboxes for anonymous users.
foreach ($flags as $flag_name => $flag) {
$form['checkboxes'][DRUPAL_ANONYMOUS_RID]["flag $flag_name"]['#disabled'] = TRUE;
$form['checkboxes'][DRUPAL_ANONYMOUS_RID]["unflag $flag_name"]['#disabled'] = TRUE;
}
}
}
/**
* Implements hook_entity_extra_field_info().
*/
function flag_entity_extra_field_info() {
$extra = [];
$flag_service = \Drupal::service('flag');
$flags = $flag_service->getFlags();
foreach ($flags as $flag) {
// Skip flags that aren't on entities.
$flag_type_plugin = $flag->getFlagTypePlugin();
if (!($flag_type_plugin instanceof \Drupal\flag\Plugin\Flag\EntityFlagType)) {
continue;
}
foreach ($flag->types as $bundle_name) {
if ($flag_type_plugin->showOnForm()) {
$extra[$flag->entity_type][$bundle_name]['form']['flag'] = [
'label' => t('Flags'),
'description' => t('Checkboxes for toggling flags'),
'weight' => 10,
];
}
if ($flag_type_plugin->showAsField()) {
$extra[$flag->entity_type][$bundle_name]['display']['flag_' . $flag->id()] = [
// It would be nicer to use % as the placeholder, but the label is
// run through check_plain() by field_ui_display_overview_form()
// (arguably incorrectly; see http://drupal.org/node/1991292).
'label' => t('Flag: @title', [
'@title' => $flag->label,
]),
'description' => t('Individual flag link'),
'weight' => 10,
];
}
}
}
return $extra;
}
function flag_node_links_alter(array &$links, NodeInterface $entity, array &$context) {
//@todo: Define this for handling the showOnLinks() flag mode.
}
/**
* Implements hook_entity_view().
*
* Handles the 'show_in_links' and 'show_as_field' flag options.
*/
function flag_entity_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode, $langcode) {
// Don't show on previews.
if ($entity->isNew()) {
return;
}
// @todo: Add caching here PLZ.
// Get all possible flags for this entity type.
$flag_service = \Drupal::service('flag');
$flags = $flag_service->getFlags($entity->getEntityTypeID(), $entity->bundle());
foreach ($flags as $flag) {
// Do not display the flag if disabled.
if(!$flag->isEnabled()){
continue;
}
$link_type_plugin = $flag->getLinkTypePlugin();
$flag_type_plugin = $flag->getFlagTypePlugin();
// Only add cache key if flag link is displayed.
if ($flag_type_plugin->showAsField() && !$display->getComponent('flag_' . $flag->id())) {
continue;
}
$action = 'flag';
if ($flag->isFlagged($entity)) {
$action = 'unflag';
}
// If the user does not have permission, go to the next foreach loop and
// don't display this flag.
if(!$flag->hasActionAccess($action)){
continue;
}
$link = $link_type_plugin->renderLink($action, $flag, $entity);
$build['flag_' . $flag->id()] = $link;
}
}
/**
* Implements hook_entity_build_defaults_alter().
*/
function flag_entity_build_defaults_alter(array &$build, EntityInterface $entity, $view_mode = 'full', $langcode = NULL) {
// Add the flag ID combined with the action to the cache key if render
// caching is enabled.
if (isset($build['#cache']) && isset($build['#cache']['keys'])) {
// Get all possible flags for this entity type.
$flag_service = \Drupal::service('flag');
$flags = $flag_service->getFlags($entity->getEntityTypeID(),
$entity->bundle());
// Get the corresponding display settings.
$display = EntityViewDisplay::collectRenderDisplay($entity, $view_mode);
foreach ($flags as $flag) {
$flag_type_plugin = $flag->getFlagTypePlugin();
// Only add cache key if flag link is displayed.
if ($flag_type_plugin->showAsField() && !$display->getComponent('flag_' . $flag->id())) {
continue;
}
$action = 'flag';
if ($flag->isFlagged($entity)) {
$action = 'unflag';
}
$build['#cache']['keys'][] = $flag->id . '-' . $action;
}
}
return $build;
}
/**
* Implements hook_entity_delete().
*/
function flag_entity_delete(EntityInterface $entity) {
// Node and user flags handle things through the entity type delete hooks.
// @todo: make this configurable in the flag type definition?
if ($entity->getEntityTypeId() == 'node' || $entity->getEntityTypeId() == 'user') {
return;
}
// @todo Actually delete the flaggings and clear associated flag counts.
}
/**
* Implements hook_user_cancel().
*/
function flag_user_cancel($edit, $account, $method) {
flag_user_account_removal($account);
}
/**
* Implements hook_user_delete().
*/
function flag_user_delete(UserInterface $account) {
flag_user_account_removal($account);
}
/**
* Shared helper for user account cancellation or deletion.
*/
function flag_user_account_removal(UserInterface $account) {
// Remove flags by this user.
$query = db_select('flagging', 'fc');
$query->leftJoin('flag_counts', 'c', 'fc.entity_id = c.entity_id AND fc.entity_type = c.entity_type');
$result = $query
->fields('fc', ['fid', 'entity_id'])
->fields('c', ['count'])
->condition('fc.uid', $account->id())
->execute();
foreach ($result as $flag_data) {
// Only decrement the flag count table if it's greater than 1.
if ($flag_data->count > 0) {
$flag_data->count--;
db_update('flag_counts')
->fields([
'count' => $flag_data->count,
])
->condition('fid', $flag_data->fid)
->condition('entity_id', $flag_data->entity_id)
->execute();
}
elseif ($flag_data->count == 0) {
db_delete('flag_counts')
->condition('fid', $flag_data->fid)
->condition('entity_id', $flag_data->entity_id)
->execute();
}
}
db_delete('flagging')
->condition('uid', $account->id())
->execute();
// Remove flags that have been done to this user.
//_flag_entity_delete('user', $account->id());
}
/**
* Implements hook_flag_access().
*/
function flag_flag_access($flag, $entity_id, $action, $account) {
// Do nothing if there is no restriction by authorship.
if (empty($flag->access_author)) {
return;
}
// Restrict access by authorship. It's important that TRUE is never returned
// here, otherwise we'd grant permission even if other modules denied access.
if ($flag->entity_type == 'node') {
// For non-existent nodes (such as on the node add form), assume that the
// current user is creating the content.
if (empty($entity_id) || !($node = $flag->fetch_entity($entity_id))) {
return AccessResult::allowedIf($flag->access_author == 'others')->cacheUntilEntityChanges($flag);
}
if ($flag->access_author == 'own' && $node->uid != $account->uid) {
return AccessResult::forbidden()->cacheUntilEntityChanges($flag);
}
elseif ($flag->access_author == 'others' && $node->uid == $account->uid) {
return AccessResult::forbidden()->cacheUntilEntityChanges($flag);
}
}
// Restrict access by comment authorship.
if ($flag->entity_type == 'comment') {
// For non-existent comments (such as on the comment add form), assume that
// the current user is creating the content.
if (empty($entity_id) || !($comment = $flag->fetch_entity($entity_id))) {
return $flag->access_author == 'comment_others' ? AccessResult::forbidden()->cacheUntilEntityChanges($flag) : NULL;
}
$node = \Drupal::entityManager()->getStorage('node')->load($comment->nid);
if ($flag->access_author == 'node_own' && $node->uid != $account->uid) {
return AccessResult::forbidden()->cacheUntilEntityChanges($flag);
}
elseif ($flag->access_author == 'node_others' && $node->uid == $account->uid) {
return AccessResult::forbidden()->cacheUntilEntityChanges($flag);
}
elseif ($flag->access_author == 'comment_own' && $comment->uid != $account->uid) {
return AccessResult::forbidden()->cacheUntilEntityChanges($flag);
}
elseif ($flag->access_author == 'comment_others' && $comment->uid == $account->uid) {
return AccessResult::forbidden()->cacheUntilEntityChanges($flag);
}
}
}
/**
* Implements hook_flag_access_multiple().
*/
function flag_flag_access_multiple($flag, $entity_ids, $account) {
$access = array();
// Do nothing if there is no restriction by authorship.
if (empty($flag->access_author)) {
return $access;
}
if ($flag->entity_type == 'node') {
// Restrict access by authorship. This is similar to flag_flag_access()
// above, but returns an array of 'nid' => $access values. Similarly, we
// should never return TRUE in any of these access values, only FALSE if we
// want to deny access, or use the current access value provided by Flag.
$result = db_select('node', 'n')
->fields('n', array('nid', 'uid'))
->condition('nid', array_keys($entity_ids), 'IN')
->condition('type', $flag->types, 'IN')
->execute();
foreach ($result as $row) {
if ($flag->access_author == 'own') {
$access[$row->nid] = $row->uid != $account->uid ? FALSE : NULL;
}
elseif ($flag->access_author == 'others') {
$access[$row->nid] = $row->uid == $account->uid ? FALSE : NULL;
}
}
}
if ($flag->entity_type == 'comment') {
// Restrict access by comment ownership.
$query = db_select('comment', 'c');
$query->leftJoin('node', 'n', 'c.nid = n.nid');
$query
->fields('c', array('cid', 'nid', 'uid'))
->condition('c.cid', $entity_ids, 'IN');
$query->addField('c', 'uid', 'comment_uid');
$result = $query->execute();
foreach ($result as $row) {
if ($flag->access_author == 'node_own') {
$access[$row->cid] = $row->node_uid != $account->uid ? FALSE : NULL;
}
elseif ($flag->access_author == 'node_others') {
$access[$row->cid] = $row->node_uid == $account->uid ? FALSE : NULL;
}
elseif ($flag->access_author == 'comment_own') {
$access[$row->cid] = $row->comment_uid != $account->uid ? FALSE : NULL;
}
elseif ($flag->access_author == 'comment_others') {
$access[$row->cid] = $row->comment_uid == $account->uid ? FALSE : NULL;
}
}
}
// Always return an array (even if empty) of accesses.
return $access;
}
// ---------------------------------------------------------------------------
// Non-Views public API
/**
* Get the count of flags for a certain entity.
*
* @param $flag
* The flag.
* @param $entity_type
* The entity type (usually 'node').
*
* @return
* The flag count with the flag name and entity type as the array key.
*
* @deprecated In Drupal 8.
* @todo Move flag_get_entity_flag_counts() into FlagCountService.
*/
function flag_get_entity_flag_counts($flag, $entity_type) {
$counts = &drupal_static(__FUNCTION__);
// We check to see if the flag count is already in the cache,
// if it's not, run the query.
if (!isset($counts[$flag->name][$entity_type])) {
$counts[$flag->name][$entity_type] = [];
$result = db_select('flagging', 'f')
->fields('f', ['fid'])
->condition('fid', $flag->fid)
->condition('entity_type', $entity_type)
->countQuery()
->execute()
->fetchField();
$counts[$flag->name][$entity_type] = $result;
}
return $counts[$flag->name][$entity_type];
}
/**
* Get the user's flag count.
*
* @param $flag
* The flag.
* @param $user
* The user object.
*
* @return
* The flag count with the flag name and the uid as the array key.
*
* @deprecated In Drupal 8.
* @todo Move flag_get_user_flag_counts() to FlagCountsService.
*/
function flag_get_user_flag_counts($flag, $user) {
$counts = &drupal_static(__FUNCTION__);
// We check to see if the flag count is already in the cache,
// if it's not, run the query.
if (!isset($counts[$flag->name][$user->uid])) {
$counts[$flag->name][$user->uid] = [];
$result = db_select('flagging', 'f')
->fields('f', ['fid'])
->condition('fid', $flag->fid)
->condition('uid', $user->uid)
->countQuery()
->execute()
->fetchField();
$counts[$flag->name][$user->uid] = $result;
}
return $counts[$flag->name][$user->uid];
}
/**
* Get flag counts for all flags on a node.
*
* @param $entity_type
* The entity type (usually 'node').
* @param $entity_id
* The entity ID (usually the node ID).
*
* @return
* The flag count with the entity type and id as array keys.
*
* @deprecated In Drupal 8
* @todo Move flag_get_counts() to FlagCountService.
*/
function flag_get_counts($entity_type, $entity_id) {
$counts = &drupal_static(__FUNCTION__);
if (!isset($counts[$entity_type][$entity_id])) {
$counts[$entity_type][$entity_id] = [];
$query = db_select('flag', 'f');
$query->leftJoin('flag_counts', 'fc', 'f.fid = fc.fid');
$result = $query
->fields('f', ['name'])
->fields('fc', ['count'])
->condition('fc.entity_type', $entity_type)
->condition('fc.entity_id', $entity_id)
->execute();
foreach ($result as $row) {
$counts[$entity_type][$entity_id][$row->name] = $row->count;
}
}
return $counts[$entity_type][$entity_id];
}
/**
* Get the total count of items flagged within a flag.
*
* @param $flag_name
* The flag name for which to retrieve a flag count.
* @param $reset
* (optional) Reset the internal cache and execute the SQL query another time.
*
* @deprecated In Drupal 8.
* @todo Move flag_get_flag_counts() into FlagCountService.
*/
function flag_get_flag_counts($flag_name, $reset = FALSE) {
$counts = &drupal_static(__FUNCTION__);
if ($reset) {
$counts = array();
}
if (!isset($counts[$flag_name])) {
$flag = flag_get_flag($flag_name);
$counts[$flag_name] = db_select('flag_counts', 'fc')
->fields('fc', array('flagging_id'))
->condition('fid', $flag->fid)
->countQuery()
->execute()
->fetchField();
}
return $counts[$flag_name];
}
/**
* Remove all flagged entities from a flag.
*
* @param $flag
* The flag object.
* @param $entity_id
* (optional) The entity ID on which all flaggings will be removed. If left
* empty, this will remove all of this flag's entities.
*
* @deprecated In Drupal 8.
* @todo Move to Flag::reset().
*/
function flag_reset_flag($flag, $entity_id = NULL) {
$query = db_select('flagging', 'fc')
->fields('fc')
->condition('fid', $flag->fid);
if ($entity_id) {
$query->condition('entity_id', $entity_id);
}
$result = $query->execute()->fetchAllAssoc('flagging_id', PDO::FETCH_ASSOC);
$rows = array();
foreach ($result as $row) {
$rows[] = $row;
}
\Drupal::moduleHandler()->invokeAll('flag_reset', array($flag, $entity_id, $rows));
$query = db_delete('flagging')->condition('fid' , $flag->fid);
// Update the flag_counts table.
$count_query = db_delete('flag_counts')->condition('fid', $flag->fid);
if ($entity_id) {
$query->condition('entity_id', $entity_id);
$count_query->condition('entity_id', $entity_id);
}
$count_query->execute();
return $query->execute();
}
/**
* Implements hook_entity_operation().
*/
function flag_entity_operation(\Drupal\Core\Entity\EntityInterface $entity) {
$operations = [];
if ($entity instanceof \Drupal\flag\FlagInterface) {
if (!$entity->isEnabled()) {
$operations['enable'] = [
'title' => t('Enable'),
'url' => $entity->urlInfo('enable'),
'weight' => 50,
];
}
else {
$operations['disable'] = [
'title' => t('Disable'),
'url' => $entity->urlInfo('disable'),
'weight' => 50,
];
}
}
return $operations;
}