forked from backdrop-contrib/flag
-
Notifications
You must be signed in to change notification settings - Fork 0
/
flag.module
2658 lines (2426 loc) · 85.1 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
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* @file
* The Flag module.
*/
define('FLAG_API_VERSION', 3);
define('FLAG_ADMIN_PATH', 'admin/structure/flags');
define('FLAG_ADMIN_PATH_START', 3);
/**
* Implements hook_config_info().
*/
function flag_config_info() {
$prefixes['flag.settings'] = array(
'label' => t('Flag settings'),
'group' => t('Configuration'),
);
return $prefixes;
}
/**
* Implements hook_autoload_info().
*/
function flag_autoload_info() {
return array(
'flag_user' => 'includes/flag/flag_user.inc',
'flag_entity' => 'includes/flag/flag_entity.inc',
'flag_flag' => 'includes/flag/flag_flag.inc',
'flag_broken' => 'includes/flag/flag_flag.inc',
'flagging' => 'includes/flag/flag.entity.inc',
'flag_node' => 'includes/flag/flag_node.inc',
'flag_comment' => 'includes/flag/flag_comment.inc',
'FlaggingController' => 'includes/flag.entity.inc',
'FlagCookieStorage' => 'includes/flag.cookie_storage.inc',
'FlagGlobalCookieStorage' => 'includes/flag.cookie_storage.inc',
'FlagNonGlobalCookieStorage' => 'includes/flag.cookie_storage.inc',
'FlagUpdate_2' => 'includes/flag.export.inc',
'FlagUpdate_3' => 'includes/flag.export.inc',
'FlagRulesDataWrapper' => 'flag.rules.inc',
'FlagRulesUIClass' => 'flag.rules.inc',
// views
'flag_handler_sort_flagged' => 'views/flag_handler_sort_flagged.inc',
'flag_handler_relationship_content' => 'views/flag_handler_relationships.inc',
'flag_handler_relationship_counts' => 'views/flag_handler_relationships.inc',
'flag_handler_relationship_user_content' => 'views/flag_handler_relationships.inc',
'flag_handler_field_ops' => 'views/flag_handler_field_ops.inc',
'flag_plugin_argument_validate_flaggability' => 'views/flag_plugin_argument_validate_flaggability.inc',
'flag_handler_argument_entity_id' => 'views/flag_handler_argument_entity_id.inc',
'flag_handler_field_flagged' => 'views/flag_handler_field_flagged.inc',
'flag_handler_filter_flagged' => 'views/flag_handler_filter_flagged.inc',
);
}
/**
* Implements hook_entity_info().
*/
function flag_entity_info() {
$return = array(
'flagging' => array(
'label' => t('Flagging'),
'controller class' => 'FlaggingController',
'base table' => 'flagging',
'entity class' => 'Flagging',
'fieldable' => TRUE,
'entity keys' => array(
'id' => 'flagging_id',
'bundle' => 'flag_name',
),
// The following tells Field UI how to extract the bundle name from a
// $flag object when we're visiting ?q=admin/.../manage/%flag/fields.
'bundle keys' => array(
'bundle' => 'name',
),
'bundles' => array(),
// The following tells EntityAPI how to save flaggings, thus allowing use
// of Entity metadata wrappers (if present).
'save callback' => 'flagging_save',
'creation callback' => 'flagging_create',
),
);
// Add bundle info but bypass flag_get_flags() as we cannot use it here, as
// it calls entity_get_info().
$result = db_query("SELECT name, title FROM {flag}");
$flag_names = $result->fetchAllKeyed();
foreach ($flag_names as $flag_name => $flag_title) {
$return['flagging']['bundles'][$flag_name] = array(
'label' => $flag_title,
'admin' => array(
'path' => FLAG_ADMIN_PATH . '/manage/%flag',
'real path' => FLAG_ADMIN_PATH . '/manage/' . $flag_name,
'bundle argument' => FLAG_ADMIN_PATH_START + 1,
'access arguments' => array('administer flags'),
),
);
}
return $return;
}
/**
* Loads a flagging entity.
*
* @param $flagging_id
* The 'flagging_id' database serial column.
* @param $reset
* Whether to reset the DefaultEntityController cache.
*
* @return
* The entity object, or FALSE if it can't be found.
*/
function flagging_load($flagging_id, $reset = FALSE) {
// The flag machine name is loaded in by FlaggingController::buildQuery().
$result = entity_load('flagging', array($flagging_id), array(), $reset);
return reset($result);
}
/**
* Entity API creation callback.
*
* Creates an unsaved flagging object for use with $flag->flag().
*
* @param $values
* An array of values as described by the entity's property info. Only
* 'flag_name' or 'fid' must be specified, since $flag->flag() does the rest.
*
* @return
* An unsaved flagging object containing the property values.
*/
function flagging_create($values = array()) {
if (!isset($values['flag_name'])) {
if (isset($values['fid'])) {
// Add flag_name, determined from fid.
$flag = flag_get_flag(NULL, $values['fid']);
$values['flag_name'] = $flag->name;
}
}
$flagging = entity_create('flagging', $values);
// Apply the given values.
foreach ($values as $key => $value) {
$flagging->$key = $value;
}
return $flagging;
}
/**
* Saves a flagging entity.
*
* For a new flagging, throws an exception is the flag action is not allowed for
* the given combination of flag, entity, and user.
*
* @param $flagging
* The flagging entity. This may have either flag_name or the flag fid set,
* and may also omit the uid property to use the current user.
*
* @throws Exception
*/
function flagging_save($flagging) {
// Get the flag, either way.
if (isset($flagging->flag_name)) {
$flag = flag_get_flag($flagging->flag_name);
}
else {
$flag = flag_get_flag(NULL, $flagging->fid);
}
if (!$flag) {
throw new Exception('Flag not found for flagging entity.');
}
// Fill in properties that may be omitted.
$flagging->fid = $flag->fid;
$flagging->flag_name = $flag->name;
if (!empty($flagging->uid)) {
$account = user_load($flagging->uid);
}
else {
$account = NULL;
}
$result = $flag->flag('flag', $flagging->entity_id, $account, FALSE, $flagging);
if (!$result) {
throw new Exception('Flag action not allowed for given flagging entity properties.');
}
}
// @todo: Implement flagging_view(). Not extremely useful. I already have it.
// @todo: When renaming a flag: Call field_attach_rename_bundle().
// @todo: When creating a flag: Call field_attach_create_bundle().
// @todo: When deleting a flag: Call field_attach_delete_bundle().
// @todo: Discuss: Should flag deleting call flag_reset_flag()? No.
// @todo: flag_reset_flag():
// - it should delete the flaggings.
// - (it has other issues; see http://drupal.org/node/894992.)
// - (is problematic: it might not be possible to delete all data in a single
// page request.)
// @todo: Discuss: Note that almost all functions/identifiers dealing with
// flaggings *aren't* prefixed by "flag_". For example:
// - The menu argument is %flagging, not %flag_flagging.
// - The entity type is "flagging", not "flag_flagging".
// On the one hand this succinct version is readable and nice. On the other
// hand, it isn't very "correct".
/**
* Implements hook_entity_query_alter().
*
* Replaces bundle condition in EntityFieldQuery on flagging entities
* with query condition on [name] field in [flag] table.
*
* @see flag_query_flagging_flag_names_alter()
*/
function flag_entity_query_alter(EntityFieldQuery $query) {
$conditions = &$query->entityConditions;
// Alter only flagging queries with bundle conditions.
if (isset($conditions['entity_type']) && $conditions['entity_type']['value'] == 'flagging' && isset($conditions['bundle'])) {
// Add tag to alter query.
$query->addTag('flagging_flag_names');
// Make value and operator of the bundle condition accessible
// in hook_query_TAG_alter.
$query->addMetaData('flag_name_value', $conditions['bundle']['value']);
$query->addMetaData('flag_name_operator', $conditions['bundle']['operator']);
unset($conditions['bundle']);
}
}
/**
* Implements hook_query_TAG_alter() for flagging_flag_names tag.
*
* @see flag_entity_query_alter()
*/
function flag_query_flagging_flag_names_alter(QueryAlterableInterface $query) {
// Get value and operator for bundle condition from meta data.
$value = $query->getMetaData('flag_name_value');
$operator = $query->getMetaData('flag_name_operator');
// Join [flag] and [flagging] tables by [fid] and
// apply bundle condition on [flag].[name] field.
$query->join('flag', 'f', 'flagging.fid = f.fid');
$query->condition('f.name', $value, $operator);
}
/**
* Implements hook_menu().
*/
function flag_menu() {
$items[FLAG_ADMIN_PATH] = array(
'title' => 'Flags',
'page callback' => 'flag_admin_page',
'access callback' => 'user_access',
'access arguments' => array('administer flags'),
'description' => 'Configure flags for marking content with arbitrary information (such as <em>offensive</em> or <em>bookmarked</em>).',
'file' => 'flag.admin.inc',
);
$items[FLAG_ADMIN_PATH . '/list'] = array(
'title' => 'List',
'type' => MENU_DEFAULT_LOCAL_TASK,
'weight' => -10,
);
$items[FLAG_ADMIN_PATH . '/add'] = array(
'title' => 'Add flag',
'page callback' => 'flag_add_page',
'access callback' => 'user_access',
'access arguments' => array('administer flags'),
'file' => 'flag.admin.inc',
'type' => MENU_LOCAL_ACTION,
'weight' => 1,
);
$items[FLAG_ADMIN_PATH . '/import'] = array(
'title' => 'Import',
'page callback' => 'backdrop_get_form',
'page arguments' => array('flag_import_form'),
'access arguments' => array('use flag import'),
'file' => 'includes/flag.export.inc',
'type' => MENU_LOCAL_ACTION,
'weight' => 2,
);
$items[FLAG_ADMIN_PATH . '/export'] = array(
'title' => 'Export',
'page callback' => 'backdrop_get_form',
'page arguments' => array('flag_export_form'),
'access arguments' => array('administer flags'),
'file' => 'includes/flag.export.inc',
'type' => MENU_LOCAL_ACTION,
'weight' => 3,
);
$items[FLAG_ADMIN_PATH . '/manage/%flag'] = array(
// Allow for disabled flags.
'load arguments' => array(TRUE),
'page callback' => 'backdrop_get_form',
'page arguments' => array('flag_form', FLAG_ADMIN_PATH_START + 1),
'access callback' => 'user_access',
'access arguments' => array('administer flags'),
'file' => 'flag.admin.inc',
'type' => MENU_LOCAL_TASK,
// Make the flag title the default title for descendant menu items.
'title callback' => '_flag_menu_title',
'title arguments' => array(FLAG_ADMIN_PATH_START + 1),
);
$items[FLAG_ADMIN_PATH . '/manage/%flag/edit'] = array(
// Allow for disabled flags.
'load arguments' => array(TRUE),
'title' => 'Edit flag',
'type' => MENU_DEFAULT_LOCAL_TASK,
'weight' => -10,
);
$items[FLAG_ADMIN_PATH . '/manage/%flag/export'] = array(
'title' => 'Export',
'page callback' => 'backdrop_get_form',
'page arguments' => array('flag_export_form', FLAG_ADMIN_PATH_START + 1),
'access arguments' => array('administer flags'),
'file' => 'includes/flag.export.inc',
'type' => MENU_LOCAL_TASK,
'weight' => 20,
);
$items[FLAG_ADMIN_PATH . '/manage/%flag/delete'] = array(
'title' => 'Delete flag',
'page callback' => 'backdrop_get_form',
'page arguments' => array('flag_delete_confirm', FLAG_ADMIN_PATH_START + 1),
'access callback' => 'user_access',
'access arguments' => array('administer flags'),
'file' => 'flag.admin.inc',
'type' => MENU_CALLBACK,
);
$items[FLAG_ADMIN_PATH . '/manage/%flag/update'] = array(
// Allow for disabled flags.
'load arguments' => array(TRUE),
'title' => 'Update',
'page callback' => 'flag_update_page',
'page arguments' => array(FLAG_ADMIN_PATH_START + 1),
'access arguments' => array('administer flags'),
'file' => 'includes/flag.export.inc',
'type' => MENU_CALLBACK,
);
$items['flag/%/%flag/%'] = array(
'title' => 'Flag',
'page callback' => 'flag_page',
'page arguments' => array(1, 2, 3),
'access callback' => 'user_access',
'access arguments' => array('access content'),
'file' => 'flag.pages.inc',
'type' => MENU_CALLBACK,
);
$items['flag/confirm/%/%flag/%'] = array(
'title' => 'Flag confirm',
'page callback' => 'backdrop_get_form',
'page arguments' => array('flag_confirm', 2, 3, 4),
'access callback' => 'user_access',
'access arguments' => array('access content'),
'file' => 'flag.pages.inc',
'type' => MENU_CALLBACK,
);
return $items;
}
/**
* Implements hook_admin_menu_map().
*/
function flag_admin_menu_map() {
if (!user_access('administer flags')) {
return;
}
$map = array();
$map[FLAG_ADMIN_PATH . '/manage/%flag'] = array(
'parent' => FLAG_ADMIN_PATH,
'arguments' => array(
array(
'%flag' => array_keys(flag_get_flags()),
),
),
);
return $map;
}
/**
* Menu loader for '%flag' arguments.
*
* @param $flag_name
* The machine name of the flag.
* @param $include_disabled
* (optional) Whether to return a disabled flag too. Normally only enabled
* flags are returned. Some menu items operate on disabled flags and in this
* case you need to turn on this switch by doing:
* @code
* 'load arguments' => array(TRUE)
* @endcode
* in your hook_menu().
*
* @return
* Either the flag object, or FALSE if none was found.
*/
function flag_load($flag_name, $include_disabled = FALSE) {
if (($flag = flag_get_flag($flag_name))) {
return $flag;
}
else {
// No enabled flag was found. Search among the disabled ones.
if ($include_disabled) {
$default_flags = flag_get_default_flags(TRUE);
if (isset($default_flags[$flag_name])) {
return $default_flags[$flag_name];
}
}
}
// A menu loader has to return FALSE (not NULL) when no object is found.
return FALSE;
}
/**
* Menu title callback.
*/
function _flag_menu_title($flag) {
// The following conditional it to handle a D7 bug (@todo: link).
return $flag ? $flag->get_title() : '';
}
/**
* Implements hook_help().
*
* @todo move to admin page or remove.
*/
function flag_help($path, $arg) {
switch ($path) {
case FLAG_ADMIN_PATH:
$output = '<p>' . t('This page lists all the <em>flags</em> that are currently defined on this system.') . '</p>';
return $output;
case FLAG_ADMIN_PATH . '/add':
$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 FLAG_ADMIN_PATH . '/manage/%/fields':
// 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 (!module_exists('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 (!module_exists('flagging_form')) {
$output .= ' <span class="warning">'
. t("You do not currently have this module enabled.")
. '</span>';
}
$output .= '</p>';
}
return $output;
}
}
/**
* Implements hook_init().
*/
function flag_init() {
module_load_include('inc', 'flag', 'includes/flag.actions');
}
/**
* Implements hook_hook_info().
*/
function flag_hook_info() {
$hooks['flag_type_info'] = array(
'group' => 'flag',
);
$hooks['flag_type_info_alter'] = array(
'group' => 'flag',
);
$hooks['flag_link_type_info'] = array(
'group' => 'flag',
);
$hooks['flag_link_type_info_alter'] = array(
'group' => 'flag',
);
return $hooks;
}
/**
* Get a flag type definition.
*
* @param $entity_type
* (optional) The entity type to get the definition for, or NULL to return
* all flag types.
*
* @return
* The flag type definition array.
*
* @see hook_flag_type_info()
*/
function flag_fetch_definition($entity_type = NULL) {
$definitions = &backdrop_static(__FUNCTION__);
if (!isset($definitions)) {
if ($cache = cache_get('flag_type_info')) {
$definitions = $cache->data;
}
else {
$definitions = module_invoke_all('flag_type_info');
backdrop_alter('flag_type_info', $definitions);
cache_set('flag_type_info', $definitions);
}
}
if (isset($entity_type)) {
if (isset($definitions[$entity_type])) {
return $definitions[$entity_type];
}
}
else {
return $definitions;
}
}
/**
* Returns all flag types defined on the system.
*
* @return
* An array of flag type names.
*/
function flag_get_types() {
$types = &backdrop_static(__FUNCTION__);
if (!isset($types)) {
$types = array_keys(flag_fetch_definition());
}
return $types;
}
/**
* Instantiates a new flag handler.
*
* A flag handler is more commonly know as "a flag". A factory method usually
* populates this empty flag with settings loaded from the database.
*
* @param $entity_type
* The entity type to create a flag handler for. This may be FALSE if the
* entity type property could not be found in the flag configuration data.
*
* @return
* A flag handler object. This may be the special class flag_broken is there is
* a problem with the flag.
*/
function flag_create_handler($entity_type) {
$definition = flag_fetch_definition($entity_type);
if (isset($definition) && class_exists($definition['handler'])) {
$handler = new $definition['handler']();
}
else {
$handler = new flag_broken();
}
$handler->entity_type = $entity_type;
$handler->construct();
return $handler;
}
/**
* Implements hook_permission().
*/
function flag_permission() {
$permissions = array(
'administer flags' => array(
'title' => t('Administer flags'),
'description' => t('Create and edit site-wide flags.'),
),
'use flag import' => array(
'title' => t('Use flag importer'),
'description' => t('Access the flag import functionality.'),
'restrict access' => TRUE,
),
);
// NOTE: on uninstall, user_modules_uninstalled() calls hook_permission()
// after flag module has been uninstalled. Once the module schema and
// config are removed, we can't know what permissions flag module may have
// been provided, so we'll just return the gloabl permissions only for now.
// One possible fix would be a new pre-uninstall hook to give user module
// a chance to do its cleanup before Backdrop uninstalls the module.
if (!module_exists('flag')) {
return $permissions;
}
// Reset static cache to ensure all flag permissions are available.
backdrop_static_reset('flag_get_flags');
$flags = flag_get_flags();
// Provide flag and unflag permissions for each flag.
foreach ($flags as $flag_name => $flag) {
$permissions += $flag->get_permissions();
}
return $permissions;
}
/**
* 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, &$form_state, $form_id) {
if (!module_exists('session_api')) {
$flags = flag_get_flags();
// Disable flag and unflag permission checkboxes for anonymous users.
foreach ($flags as $flag_name => $flag) {
$form['checkboxes'][BACKDROP_ANONYMOUS_ROLE]["flag $flag_name"]['#disabled'] = TRUE;
$form['checkboxes'][BACKDROP_ANONYMOUS_ROLE]["unflag $flag_name"]['#disabled'] = TRUE;
}
}
}
/**
* Implements hook_flag_link().
*/
function flag_flag_link($flag, $action, $entity_id) {
$token = flag_get_token($entity_id);
return array(
'href' => 'flag/' . ($flag->link_type == 'confirm' ? 'confirm/' : '') . "$action/$flag->name/$entity_id",
'query' => backdrop_get_destination() + ($flag->link_type == 'confirm' ? array() : array('token' => $token)),
);
}
/**
* Implements hook_field_extra_fields().
*/
function flag_field_extra_fields() {
$extra = array();
$flags = flag_get_flags();
foreach ($flags as $name => $flag) {
// Skip flags that aren't on entities.
if (!($flag instanceof flag_entity)) {
continue;
}
$applicable_bundles = $flag->types;
// If the list of bundles is empty, it indicates all bundles apply.
if (empty($applicable_bundles)) {
$entity_info = entity_get_info($flag->entity_type);
$applicable_bundles = array_keys($entity_info['bundles']);
}
foreach ($applicable_bundles as $bundle_name) {
if ($flag->show_on_form) {
$extra[$flag->entity_type][$bundle_name]['form']['flag'] = array(
'label' => t('Flags'),
'description' => t('Checkboxes for toggling flags'),
'weight' => 10,
);
}
if ($flag->show_as_field) {
$extra[$flag->entity_type][$bundle_name]['display']['flag_' . $name] = array(
// 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', array(
'@title' => $flag->title,
)),
'description' => t('Individual flag link'),
'weight' => 10,
);
}
}
}
return $extra;
}
/**
* Implements hook_form_FORM_ID_alter(): node_type_form.
*/
function flag_form_node_type_form_alter(&$form, &$form_state, $form_id) {
global $user;
$flags = flag_get_flags('node', $form['#node_type']->type, $user);
foreach ($flags as $flag) {
if ($flag->show_on_form) {
// To be able to process node tokens in flag labels, we create a fake
// node and store it in the flag's cache for replace_tokens() to find,
// with a fake ID.
$flag->remember_entity('fake', (object) array(
'nid' => NULL,
'type' => $form['#node_type']->type,
'title' => '',
));
$var = 'flag_' . $flag->name . '_default';
$form['workflow']['flag'][$var] = array(
'#type' => 'checkbox',
'#title' => $flag->get_label('flag_short', 'fake'),
'#default_value' => config_get('flag.settings', $var . '_' . $form['#node_type']->type),
'#return_value' => 1,
);
}
}
if (isset($form['workflow']['flag'])) {
$form['workflow']['flag'] += array(
'#type' => 'item',
'#title' => t('Default flags'),
'#description' => t('Above are the <a href="@flag-url">flags</a> you elected to show on the node editing form. You may specify their initial state here.', array('@flag-url' => url(FLAG_ADMIN_PATH))),
// Make the spacing a bit more compact:
'#prefix' => '<div class="form-checkboxes">',
'#suffix' => '</div>',
);
}
}
/**
* Implements hook_field_attach_form().
*
* Handles the 'show_on_form' flag option.
*
* Warning: will not work on entity types that are not fieldable, as this relies
* on a field module hook.
*
* @see flag_field_attach_submit()
*/
function flag_field_attach_form($entity_type, $entity, &$form, &$form_state, $langcode) {
list($id) = entity_extract_ids($entity_type, $entity);
// Some modules are being stupid here. Commerce!
if (empty($id)) {
$id = NULL;
}
// Keep track of whether the entity is new or not, as we're about to fiddle
// with the entity id for the flag's entity cache.
$is_existing_entity = !empty($id);
// Get all possible flags for this entity type.
$flags = flag_get_flags($entity_type);
// Filter out flags which need to be included on the node form.
$flags_in_form = 0;
$flags_visible = 0;
foreach ($flags as $flag) {
if (!$flag->show_on_form) {
continue;
}
// Get the flag status.
if ($is_existing_entity) {
$flag_status = $flag->is_flagged($id);
}
else {
// We don't have per-bundle defaults on general entities yet: default
// status is just unflagged.
$flag_status = FALSE;
// Apply the per-bundle defaults for nodes.
if ($entity_type == 'node') {
$node_type = $entity->type;
$flag_status = config_get('flag.settings', 'flag_' . $flag->name . '_default_' . $node_type);
}
// For a new, unsaved entity, make a dummy entity ID so that the flag
// handler can remember the entity. This allows access to the flag to be
// correctly handled in node and comment preview.
$id = 'new';
$flag->remember_entity($id, $entity);
}
// If the flag is not global and the user doesn't have access, skip it.
// Global flags have their value set even if the user doesn't have access
// to it, similar to the way "published" and "promote" keep the default
// values even if the user doesn't have "administer nodes" permission.
// Furthermore, a global flag is set to its default value on new nodes
// even if the user creating the node doesn't have access to the flag.
global $user;
$access = $flag->access($id, $flag_status ? 'unflag' : 'flag');
if (!$access && !$flag->global) {
continue;
}
$form['flag'][$flag->name] = array(
'#type' => 'checkbox',
'#title' => $flag->get_label('flag_short', $id),
'#description' => $flag->get_label('flag_long', $id),
'#default_value' => $flag_status,
'#return_value' => 1,
// Used by our backdropSetSummary() on vertical tabs.
'#attributes' => array('title' => $flag->get_title()),
);
// If the user does not have access to the flag, set as a value.
if (!$access) {
$form['flag'][$flag->name]['#type'] = 'value';
$form['flag'][$flag->name]['#value'] = $flag_status;
}
else {
$flags_visible++;
}
$flags_in_form++;
}
if ($flags_in_form) {
$form['flag'] += array(
'#weight' => 1,
'#tree' => TRUE,
);
}
if ($flags_visible) {
$form['flag'] += array(
'#type' => 'fieldset',
'#title' => t('Flags'),
'#collapsible' => TRUE,
);
if ($entity_type == 'node') {
// Turn the fieldset into a vertical tab.
$form['flag'] += array(
'#group' => 'additional_settings',
'#attributes' => array('class' => array('flag-fieldset')),
'#attached' => array(
'js' => array(
'vertical-tabs' => backdrop_get_path('module', 'flag') . '/js/flag-admin.js',
),
),
);
}
}
}
/**
* Implements hook_field_attach_submit().
*
* @see flag_field_attach_form()
*/
function flag_field_attach_submit($entity_type, $entity, $form, &$form_state) {
// This is invoked for each flag_field_attach_form(), but possibly more than
// once for a particular form in the case that a form is showing multiple
// entities (field collection, inline entity form). Hence we can't simply
// assume our submitted form values are in $form_state['values']['flag'].
if (isset($form['flag'])) {
$parents = $form['flag']['#parents'];
$flag_values = backdrop_array_get_nested_value($form_state['values'], $parents);
// Put the form values in the entity so flag_field_attach_save() can find
// them. We can't call flag() here as new entities have no id yet.
$entity->flag = $flag_values;
}
}
/**
* Implements hook_field_attach_insert().
*/
function flag_field_attach_insert($entity_type, $entity) {
if (isset($entity->flag)) {
flag_field_attach_save($entity_type, $entity);
}
}
/**
* Implements hook_field_attach_update().
*/
function flag_field_attach_update($entity_type, $entity) {
if (isset($entity->flag)) {
flag_field_attach_save($entity_type, $entity);
}
}
/**
* Shared saving routine between flag_field_attach_insert/update().
*
* @see flag_field_attach_form()
*/
function flag_field_attach_save($entity_type, $entity) {
list($id) = entity_extract_ids($entity_type, $entity);
// Get the flag values we stashed in the entity in flag_field_attach_submit().
foreach ($entity->flag as $flag_name => $state) {
flag($state ? 'flag' : 'unflag', $flag_name, $id);
}
}
/*
* Implements hook_contextual_links_view_alter().
*/
function flag_contextual_links_view_alter(&$element, $items) {
if (isset($element['#element']['#entity_type'])) {
$entity_type = $element['#element']['#entity_type'];
// Get the entity out of the element. This requires a bit of legwork.
if (isset($element['#element']['#entity'])) {
// EntityAPI entities will all have the entity in the same place.
$entity = $element['#element']['#entity'];
}
elseif (isset($element['#element']['#' . $entity_type])) {
// Node module at least puts it here.
$entity = $element['#element']['#' . $entity_type];
}
else {
// Give up.
return;
}
// Get all possible flags for this entity type.
$flags = flag_get_flags($entity_type);
foreach ($flags as $name => $flag) {
if (!$flag->show_contextual_link) {
continue;
}
list($entity_id) = entity_extract_ids($entity_type, $entity);
if (!$flag->access($entity_id) && (!$flag->is_flagged($entity_id) || !$flag->access($entity_id, 'flag'))) {
// User has no permission to use this flag or flag does not apply to
// this object. The link is not skipped if the user has "flag" access
// but not "unflag" access (this way the unflag denied message is
// shown).
continue;
}
$element['#links']['flag-' . $name] = array(
'title' => $flag->theme($flag->is_flagged($entity_id) ? 'unflag' : 'flag', $entity_id),
'html' => TRUE,
);
}
}
}
/**
* Implements hook_entity_view().
*
* Handles the 'show_in_links' and 'show_as_field' flag options.
*/
function flag_entity_view($entity, $type, $view_mode, $langcode) {
// Get all possible flags for this entity type.
$flags = flag_get_flags($type);
foreach ($flags as $flag) {
// Check if the flag outputs on entity view.
if (!($flag->show_as_field || $flag->shows_in_entity_links($view_mode))) {
// Flag is not configured to output on entity view, so skip it to save on
// calls to access checks.
continue;
}
$entity_id = $flag->get_entity_id($entity);
// For a new, unsaved entity, make a dummy entity ID so that the flag
// handler can remember the entity. This allows access to the flag to be
// correctly handled in node and comment preview.
if (is_null($entity_id)) {
$entity_id = 'new';
}
$flag->remember_entity($entity_id, $entity);