Projet

Général

Profil

Paste
Télécharger (85,3 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / flag / flag.module @ 651307cd

1
<?php
2

    
3
/**
4
 * @file
5
 * The Flag module.
6
 */
7

    
8
define('FLAG_API_VERSION', 3);
9

    
10
define('FLAG_ADMIN_PATH', 'admin/structure/flags');
11
define('FLAG_ADMIN_PATH_START', 3);
12

    
13
/**
14
 * Implements hook_entity_info().
15
 */
16
function flag_entity_info() {
17
  $return = array(
18
    'flagging' => array(
19
      'label' => t('Flagging'),
20
      'controller class' => 'FlaggingController',
21
      'base table' => 'flagging',
22
      'fieldable' => TRUE,
23
      'entity keys' => array(
24
        'id' => 'flagging_id',
25
        'bundle' => 'flag_name',
26
      ),
27
      // The following tells Field UI how to extract the bundle name from a
28
      // $flag object when we're visiting ?q=admin/.../manage/%flag/fields.
29
      'bundle keys' => array(
30
        'bundle' => 'name',
31
      ),
32
      'bundles' => array(),
33
      // The following tells EntityAPI how to save flaggings, thus allowing use
34
      // of Entity metadata wrappers (if present).
35
      'save callback' => 'flagging_save',
36
      'creation callback' => 'flagging_create',
37
    ),
38
  );
39

    
40
  // Check for our table before we query it. This is a workaround for a core
41
  // bug: https://www.drupal.org/node/1311820
42
  // TODO: Remove this when that bug is fixed.
43
  if (db_table_exists('flag')) {
44
    // Add bundle info but bypass flag_get_flags() as we cannot use it here, as
45
    // it calls entity_get_info().
46
    $result = db_query("SELECT name, title FROM {flag}");
47
    $flag_names = $result->fetchAllKeyed();
48
    foreach ($flag_names as $flag_name => $flag_title) {
49
      $return['flagging']['bundles'][$flag_name] = array(
50
        'label' => $flag_title,
51
        'admin' => array(
52
          'path' => FLAG_ADMIN_PATH . '/manage/%flag',
53
          'real path' => FLAG_ADMIN_PATH . '/manage/' . $flag_name,
54
          'bundle argument' => FLAG_ADMIN_PATH_START + 1,
55
          'access arguments' => array('administer flags'),
56
        ),
57
      );
58
    }
59
  }
60

    
61
  return $return;
62
}
63

    
64
/**
65
 * Loads a flagging entity.
66
 *
67
 * @param int $flagging_id
68
 *   The 'flagging_id' database serial column.
69
 * @param bool $reset
70
 *   Whether to reset the DrupalDefaultEntityController cache.
71
 *
72
 * @return stdClass
73
 *   The entity object, or FALSE if it can't be found.
74
 */
75
function flagging_load($flagging_id, $reset = FALSE) {
76
  // The flag machine name is loaded in by FlaggingController::buildQuery().
77
  $result = entity_load('flagging', array($flagging_id), array(), $reset);
78
  return reset($result);
79
}
80

    
81
/**
82
 * Entity API creation callback.
83
 *
84
 * Creates an unsaved flagging object for use with $flag->flag().
85
 *
86
 * @param array $values
87
 *   An array of values as described by the entity's property info. Only
88
 *   'flag_name' or 'fid' must be specified, since $flag->flag() does the rest.
89
 *
90
 * @return
91
 *   An unsaved flagging object containing the property values.
92
 */
93
function flagging_create($values = array()) {
94
  $flagging = (object) array();
95

    
96
  if (!isset($values['flag_name'])) {
97
    if (isset($values['fid'])) {
98
      // Add flag_name, determined from fid.
99
      $flag = flag_get_flag(NULL, $values['fid']);
100
      $values['flag_name'] = $flag->name;
101
    }
102
  }
103

    
104
  // Apply the given values.
105
  foreach ($values as $key => $value) {
106
    $flagging->$key = $value;
107
  }
108

    
109
  return $flagging;
110
}
111

    
112
/**
113
 * Saves a flagging entity.
114
 *
115
 * For a new flagging, throws an exception is the flag action is not allowed for
116
 * the given combination of flag, entity, and user.
117
 *
118
 * @param $flagging
119
 *   The flagging entity. This may have either flag_name or the flag fid set,
120
 *   and may also omit the uid property to use the current user.
121
 *
122
 * @throws Exception
123
 */
124
function flagging_save($flagging) {
125
  // Get the flag, either way.
126
  if (isset($flagging->flag_name)) {
127
    $flag = flag_get_flag($flagging->flag_name);
128
  }
129
  else {
130
    $flag = flag_get_flag(NULL, $flagging->fid);
131
  }
132

    
133
  if (!$flag) {
134
    throw new Exception('Flag not found for flagging entity.');
135
  }
136

    
137
  // Fill in properties that may be omitted.
138
  $flagging->fid = $flag->fid;
139
  $flagging->flag_name = $flag->name;
140

    
141
  if (!empty($flagging->uid)) {
142
    $account = user_load($flagging->uid);
143
  }
144
  else {
145
    $account = NULL;
146
  }
147

    
148
  $result = $flag->flag('flag', $flagging->entity_id, $account, FALSE, $flagging);
149

    
150
  if (!$result) {
151
    throw new Exception('Flag action not allowed for given flagging entity properties.');
152
  }
153
}
154

    
155
// @todo: Implement flagging_view(). Not extremely useful. I already have it.
156

    
157
// @tood: Discuss: Should flag deleting call flag_reset_flag()? No.
158

    
159
// @todo: flag_reset_flag():
160
// - it should delete the flaggings.
161
// - (it has other issues; see http://drupal.org/node/894992.)
162
// - (is problematic: it might not be possible to delete all data in a single
163
//   page request.)
164

    
165
// @todo: Discuss: Note that almost all functions/identifiers dealing with
166
// flaggings *aren't* prefixed by "flag_". For example:
167
// - The menu argument is %flagging, not %flag_flagging.
168
// - The entity type is "flagging", not "flag_flagging".
169
// On the one hand this succinct version is readable and nice. On the other
170
// hand, it isn't very "correct".
171

    
172
/**
173
 * Implements hook_entity_query_alter().
174
 *
175
 * Replaces bundle condition in EntityFieldQuery on flagging entities
176
 * with query condition on [name] field in [flag] table.
177
 *
178
 * @see flag_query_flagging_flag_names_alter()
179
 */
180
function flag_entity_query_alter(EntityFieldQuery $query) {
181
  $conditions = &$query->entityConditions;
182

    
183
  // Alter only flagging queries with bundle conditions.
184
  if (isset($conditions['entity_type']) && $conditions['entity_type']['value'] == 'flagging' && isset($conditions['bundle'])) {
185
    // Add tag to alter query.
186
    $query->addTag('flagging_flag_names');
187
    // Make value and operator of the bundle condition accessible
188
    // in hook_query_TAG_alter.
189
    $query->addMetaData('flag_name_value', $conditions['bundle']['value']);
190
    $query->addMetaData('flag_name_operator', $conditions['bundle']['operator']);
191
    unset($conditions['bundle']);
192
  }
193
}
194

    
195
/**
196
 * Implements hook_query_TAG_alter() for flagging_flag_names tag.
197
 *
198
 * @see flag_entity_query_alter()
199
 */
200
function flag_query_flagging_flag_names_alter(QueryAlterableInterface $query) {
201
  // Queries with this tag need to have the {flag} table joined on so they can
202
  // have a condition on the flag name.
203
  // However, we need to ensure the {flagging} table is there to join from. Not
204
  // all instances of EntityFieldQuery will add it; for example, with only a
205
  // field condition the entity base table is not added to the SelectQuery.
206
  $tables =& $query->getTables();
207
  if (!isset($tables['flagging'])) {
208
    // All tables that are in the query will be field tables and are equivalent,
209
    // so just join on the first one.
210
    $field_table = reset($tables);
211
    $field_table_alias = $field_table['alias'];
212

    
213
    $query->join('flagging', 'flagging', "$field_table_alias.entity_id = flagging.fid");
214
  }
215

    
216
  // Get value and operator for bundle condition from meta data.
217
  $value = $query->getMetaData('flag_name_value');
218
  $operator = $query->getMetaData('flag_name_operator');
219
  // Join [flag] and [flagging] tables by [fid] and
220
  // apply bundle condition on [flag].[name] field.
221
  $query->join('flag', 'f', 'flagging.fid = f.fid');
222
  $query->condition('f.name', $value, $operator);
223
}
224

    
225
/**
226
 * Implements hook_menu().
227
 */
228
function flag_menu() {
229
  $items[FLAG_ADMIN_PATH] = array(
230
    'title' => 'Flags',
231
    'page callback' => 'flag_admin_page',
232
    'access callback' => 'user_access',
233
    'access arguments' => array('administer flags'),
234
    'description' => 'Configure flags for marking content with arbitrary information (such as <em>offensive</em> or <em>bookmarked</em>).',
235
    'file' => 'includes/flag.admin.inc',
236
  );
237
  $items[FLAG_ADMIN_PATH . '/list'] = array(
238
    'title' => 'List',
239
    'type' => MENU_DEFAULT_LOCAL_TASK,
240
    'weight' => -10,
241
  );
242
  $items[FLAG_ADMIN_PATH . '/add'] = array(
243
    'title' => 'Add flag',
244
    'page callback' => 'flag_add_page',
245
    'access callback' => 'user_access',
246
    'access arguments' => array('administer flags'),
247
    'file' => 'includes/flag.admin.inc',
248
    'type' => MENU_LOCAL_ACTION,
249
    'weight' => 1,
250
  );
251
  $items[FLAG_ADMIN_PATH . '/import'] = array(
252
    'title' => 'Import',
253
    'page callback' => 'drupal_get_form',
254
    'page arguments' => array('flag_import_form'),
255
    'access arguments' => array('use flag import'),
256
    'file' => 'includes/flag.export.inc',
257
    'type' => MENU_LOCAL_ACTION,
258
    'weight' => 2,
259
  );
260
  $items[FLAG_ADMIN_PATH . '/export'] = array(
261
    'title' => 'Export',
262
    'page callback' => 'drupal_get_form',
263
    'page arguments' => array('flag_export_form'),
264
    'access arguments' => array('administer flags'),
265
    'file' => 'includes/flag.export.inc',
266
    'type' => MENU_LOCAL_ACTION,
267
    'weight' => 3,
268
  );
269

    
270
  $items[FLAG_ADMIN_PATH . '/manage/%flag'] = array(
271
    // Allow for disabled flags.
272
    'load arguments' => array(TRUE),
273
    'page callback' => 'drupal_get_form',
274
    'page arguments' => array('flag_form', FLAG_ADMIN_PATH_START + 1),
275
    'access callback' => 'user_access',
276
    'access arguments' => array('administer flags'),
277
    'file' => 'includes/flag.admin.inc',
278
    // Make the flag title the default title for descendant menu items.
279
    'title callback' => '_flag_menu_title',
280
    'title arguments' => array(FLAG_ADMIN_PATH_START + 1),
281
  );
282
  $items[FLAG_ADMIN_PATH . '/manage/%flag/edit'] = array(
283
    // Allow for disabled flags.
284
    'load arguments' => array(TRUE),
285
    'title' => 'Edit flag',
286
    'type' => MENU_DEFAULT_LOCAL_TASK,
287
    'weight' => -10,
288
  );
289
  $items[FLAG_ADMIN_PATH . '/manage/%flag/export'] = array(
290
    'title' => 'Export',
291
    'page callback' => 'drupal_get_form',
292
    'page arguments' => array('flag_export_form', FLAG_ADMIN_PATH_START + 1),
293
    'access arguments' => array('administer flags'),
294
    'file' => 'includes/flag.export.inc',
295
    'type' => MENU_LOCAL_TASK,
296
    'weight' => 20,
297
  );
298
  $items[FLAG_ADMIN_PATH . '/manage/%flag/delete'] = array(
299
    'title' => 'Delete flag',
300
    'page callback' => 'drupal_get_form',
301
    'page arguments' => array('flag_delete_confirm', FLAG_ADMIN_PATH_START + 1),
302
    'access callback' => 'user_access',
303
    'access arguments' => array('administer flags'),
304
    'file' => 'includes/flag.admin.inc',
305
    'type' => MENU_CALLBACK,
306
  );
307
  $items[FLAG_ADMIN_PATH . '/manage/%flag/update'] = array(
308
    // Allow for disabled flags.
309
    'load arguments' => array(TRUE),
310
    'title' => 'Update',
311
    'page callback' => 'flag_update_page',
312
    'page arguments' => array(FLAG_ADMIN_PATH_START + 1),
313
    'access arguments' => array('administer flags'),
314
    'file' => 'includes/flag.export.inc',
315
    'type' => MENU_CALLBACK,
316
  );
317

    
318
  $items['flag/%/%flag/%'] = array(
319
    'title' => 'Flag',
320
    'page callback' => 'flag_page',
321
    'page arguments' => array(1, 2, 3),
322
    'access callback' => 'flag_page_access',
323
    'access arguments' => array(1, 2, 3),
324
    'file' => 'includes/flag.pages.inc',
325
    'type' => MENU_CALLBACK,
326
  );
327
  $items['flag/confirm/%/%flag/%'] = array(
328
    'title' => 'Flag confirm',
329
    'page callback' => 'drupal_get_form',
330
    'page arguments' => array('flag_confirm', 2, 3, 4),
331
    'access callback' => 'flag_page_access',
332
    'access arguments' => array(2, 3, 4),
333
    'file' => 'includes/flag.pages.inc',
334
    'type' => MENU_CALLBACK,
335
  );
336

    
337
  return $items;
338
}
339

    
340
/**
341
 * Menu access callback for flagging pages.
342
 *
343
 * Same parameters as flag_page().
344
 *
345
 * @see flag_page()
346
 * @see flag_confirm()
347
 */
348
function flag_page_access($action, $flag, $entity_id) {
349
  $access = $flag->access($entity_id, $action);
350
  return $access;
351
}
352

    
353
/**
354
 * Implements hook_admin_menu_map().
355
 */
356
function flag_admin_menu_map() {
357
  if (!user_access('administer flags')) {
358
    return;
359
  }
360

    
361
  $map = array();
362
  $map[FLAG_ADMIN_PATH . '/manage/%flag'] = array(
363
    'parent' => FLAG_ADMIN_PATH,
364
    'arguments' => array(
365
      array(
366
        '%flag' => array_keys(flag_get_flags()),
367
      ),
368
    ),
369
  );
370

    
371
  return $map;
372
}
373

    
374
/**
375
 * Menu loader for '%flag' arguments.
376
 *
377
 * @param string $flag_name
378
 *   The machine name of the flag.
379
 * @param bool $include_disabled
380
 *   (optional) Whether to return a disabled flag too. Normally only enabled
381
 *   flags are returned. Some menu items operate on disabled flags and in this
382
 *   case you need to turn on this switch by doing:
383
 *   @code
384
 *   'load arguments' => array(TRUE)
385
 *   @endcode
386
 *   in your hook_menu().
387
 *
388
 * @return
389
 *   Either the flag object, or FALSE if none was found.
390
 */
391
function flag_load($flag_name, $include_disabled = FALSE) {
392
  if (($flag = flag_get_flag($flag_name))) {
393
    return $flag;
394
  }
395
  else {
396
    // No enabled flag was found. Search among the disabled ones.
397
    if ($include_disabled) {
398
      $default_flags = flag_get_default_flags(TRUE);
399
      if (isset($default_flags[$flag_name])) {
400
        return $default_flags[$flag_name];
401
      }
402
    }
403
  }
404
  // A menu loader has to return FALSE (not NULL) when no object is found.
405
  return FALSE;
406
}
407

    
408
/**
409
 * Menu title callback.
410
 */
411
function _flag_menu_title($flag) {
412
  // The following conditional it to handle a D7 bug (@todo: link).
413
  return $flag ? $flag->get_title() : '';
414
}
415

    
416
/**
417
 * Implements hook_help().
418
 */
419
function flag_help($path, $arg) {
420
  switch ($path) {
421
    case FLAG_ADMIN_PATH:
422
      $output = '<p>' . t('This page lists all the <em>flags</em> that are currently defined on this system.') . '</p>';
423
      return $output;
424

    
425
    case FLAG_ADMIN_PATH . '/add':
426
      $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>';
427
      return $output;
428

    
429
    case FLAG_ADMIN_PATH . '/manage/%/fields':
430
      // Get the existing link types that provide a flagging form.
431
      $link_types = flag_get_link_types();
432
      $form_link_types = array();
433
      foreach (flag_get_link_types() as $link_type) {
434
        if ($link_type['provides form']) {
435
          $form_link_types[] = '<em>' . $link_type['title'] . '</em>';
436
        }
437
      }
438

    
439
      // Get the flag for which we're managing fields.
440
      $flag = menu_get_object('flag', FLAG_ADMIN_PATH_START + 1);
441

    
442
      // Common text.
443
      $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>';
444
      $output .= '<p>' . t('On this page you can add fields to flags, delete them, and otherwise manage them.') . '</p>';
445

    
446
      // Three cases:
447
      if ($flag->link_type == 'form') {
448
        // Case 1: the current link type is the flagging form. Don't tell the
449
        // user anything extra, all is fine.
450
      }
451
      elseif ($link_types[$flag->link_type]['provides form']) {
452
        // Case 2: the current link type shows the form for creation of the
453
        // flagging, but it not the flagging form. Tell the user they can't edit
454
        // existing flagging fields.
455
        $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(
456
          '!flagging-form-url' => 'http://drupal.org/project/flagging_form',
457
        ));
458
        if (!module_exists('flagging_form')) {
459
          $output .= ' <span class="warning">'
460
            . t("You do not currently have this module enabled.")
461
            . '</span>';
462
        }
463
        $output .= '</p>';
464
      }
465
      else {
466
        // Case 3: the current link type does not allow access to the flagging
467
        // form. Tell the user they should change it.
468
        $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(
469
          '!form-link-type-url' => url('admin/structure/flags/manage/' . $flag->name, array('fragment' => 'edit-link-type')),
470
          // The list of labels from link types. These are all defined in code
471
          // in hook_flag_link_type_info() and therefore safe to output raw.
472
          '!link-types-list' => implode(', ', $form_link_types),
473
        )) . '</p>';
474
        $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(
475
          '!flagging-form-url' => 'http://drupal.org/project/flagging_form',
476
        ));
477
        if (!module_exists('flagging_form')) {
478
          $output .= ' <span class="warning">'
479
            . t("You do not currently have this module enabled.")
480
            . '</span>';
481
        }
482
        $output .= '</p>';
483
      }
484

    
485
      return $output;
486
  }
487
}
488

    
489
/**
490
 * Implements hook_init().
491
 */
492
function flag_init() {
493
  module_load_include('inc', 'flag', 'includes/flag.actions');
494
}
495

    
496
/**
497
 * Implements hook_hook_info().
498
 */
499
function flag_hook_info() {
500
  $hooks['flag_type_info'] = array(
501
    'group' => 'flag',
502
  );
503
  $hooks['flag_type_info_alter'] = array(
504
    'group' => 'flag',
505
  );
506
  $hooks['flag_link_type_info'] = array(
507
    'group' => 'flag',
508
  );
509
  $hooks['flag_link_type_info_alter'] = array(
510
    'group' => 'flag',
511
  );
512
  return $hooks;
513
}
514

    
515
/**
516
 * Get a flag type definition.
517
 *
518
 * @param string $entity_type
519
 *   (optional) The entity type to get the definition for, or NULL to return
520
 *   all flag types.
521
 *
522
 * @return
523
 *   The flag type definition array.
524
 *
525
 * @see hook_flag_type_info()
526
 */
527
function flag_fetch_definition($entity_type = NULL) {
528
  $definitions = &drupal_static(__FUNCTION__);
529
  if (!isset($definitions)) {
530
    if ($cache = cache_get('flag_type_info')) {
531
      $definitions = $cache->data;
532
    }
533
    else {
534
      $definitions = module_invoke_all('flag_type_info');
535
      drupal_alter('flag_type_info', $definitions);
536

    
537
      cache_set('flag_type_info', $definitions);
538
    }
539
  }
540

    
541
  if (isset($entity_type)) {
542
    if (isset($definitions[$entity_type])) {
543
      return $definitions[$entity_type];
544
    }
545
  }
546
  else {
547
    return $definitions;
548
  }
549
}
550

    
551
/**
552
 * Returns all flag types defined on the system.
553
 *
554
 * @return
555
 *   An array of flag type names.
556
 */
557
function flag_get_types() {
558
  $types = &drupal_static(__FUNCTION__);
559
  if (!isset($types)) {
560
    $types = array_keys(flag_fetch_definition());
561
  }
562
  return $types;
563
}
564

    
565
/**
566
 * Instantiates a new flag handler.
567
 *
568
 * A flag handler is more commonly know as "a flag". A factory method usually
569
 * populates this empty flag with settings loaded from the database.
570
 *
571
 * @param $entity_type
572
 *  The entity type to create a flag handler for. This may be FALSE if the
573
 *  entity type property could not be found in the flag configuration data.
574
 *
575
 * @return
576
 *  A flag handler object. This may be the special class flag_broken is there is
577
 *  a problem with the flag.
578
 */
579
function flag_create_handler($entity_type) {
580
  $definition = flag_fetch_definition($entity_type);
581
  if (isset($definition) && class_exists($definition['handler'])) {
582
    $handler = new $definition['handler']();
583
  }
584
  else {
585
    $handler = new flag_broken();
586
  }
587
  $handler->entity_type = $entity_type;
588
  $handler->construct();
589
  return $handler;
590
}
591

    
592
/**
593
 * Implements hook_permission().
594
 */
595
function flag_permission() {
596
  $permissions = array(
597
    'administer flags' => array(
598
      'title' => t('Administer flags'),
599
      'description' => t('Create and edit site-wide flags.'),
600
    ),
601
    'use flag import' => array(
602
      'title' => t('Use flag importer'),
603
      'description' => t('Access the flag import functionality.'),
604
      'restrict access' => TRUE,
605
    ),
606
  );
607

    
608
  // Reset static cache to ensure all flag permissions are available.
609
  drupal_static_reset('flag_get_flags');
610
  $flags = flag_get_flags();
611
  // Provide flag and unflag permissions for each flag.
612
  foreach ($flags as $flag_name => $flag) {
613
    $permissions += $flag->get_permissions();
614
  }
615

    
616
  return $permissions;
617
}
618

    
619
/**
620
 * Implements hook_form_FORM_ID_alter(): user_admin_permissions.
621
 *
622
 * Disable permission on the permissions form that don't make sense for
623
 * anonymous users when Session API module is not enabled.
624
 */
625
function flag_form_user_admin_permissions_alter(&$form, &$form_state, $form_id) {
626
  if (!module_exists('session_api')) {
627
    $flags = flag_get_flags();
628
    // Disable flag and unflag permission checkboxes for anonymous users.
629
    foreach ($flags as $flag_name => $flag) {
630
      $form['checkboxes'][DRUPAL_ANONYMOUS_RID]["flag $flag_name"]['#disabled'] = TRUE;
631
      $form['checkboxes'][DRUPAL_ANONYMOUS_RID]["unflag $flag_name"]['#disabled'] = TRUE;
632
    }
633
  }
634
}
635

    
636
/**
637
 * Implements hook_flag_link().
638
 */
639
function flag_flag_link($flag, $action, $entity_id) {
640
  $token = flag_get_token($entity_id);
641
  return array(
642
    'href' => 'flag/' . ($flag->link_type == 'confirm' ? 'confirm/' : '') . "$action/$flag->name/$entity_id",
643
    'query' => drupal_get_destination() + ($flag->link_type == 'confirm' ? array() : array('token' => $token)),
644
  );
645
}
646

    
647
/**
648
 * Implements hook_field_extra_fields().
649
 */
650
function flag_field_extra_fields() {
651
  $extra = array();
652

    
653
  $flags = flag_get_flags();
654
  foreach ($flags as $name => $flag) {
655
    // Skip flags that aren't on entities.
656
    if (!($flag instanceof flag_entity)) {
657
      continue;
658
    }
659

    
660
    $applicable_bundles = $flag->types;
661
    // If the list of bundles is empty, it indicates all bundles apply.
662
    if (empty($applicable_bundles)) {
663
      $entity_info = entity_get_info($flag->entity_type);
664
      $applicable_bundles = array_keys($entity_info['bundles']);
665
    }
666

    
667
    foreach ($applicable_bundles as $bundle_name) {
668
      if ($flag->show_on_form) {
669
        $extra[$flag->entity_type][$bundle_name]['form']['flag'] = array(
670
          'label' => t('Flags'),
671
          'description' => t('Checkboxes for toggling flags'),
672
          'weight' => 10,
673
        );
674
      }
675

    
676
      if ($flag->show_as_field) {
677
        $extra[$flag->entity_type][$bundle_name]['display']['flag_' . $name] = array(
678
          // It would be nicer to use % as the placeholder, but the label is
679
          // run through check_plain() by field_ui_display_overview_form()
680
          // (arguably incorrectly; see http://drupal.org/node/1991292).
681
          'label' => t('Flag: @title', array(
682
            '@title' => $flag->title,
683
          )),
684
          'description' => t('Individual flag link'),
685
          'weight' => 10,
686
        );
687
      }
688
    }
689
  }
690

    
691
  return $extra;
692
}
693

    
694
/**
695
 * Implements hook_form_FORM_ID_alter(): node_type_form.
696
 */
697
function flag_form_node_type_form_alter(&$form, &$form_state, $form_id) {
698
  global $user;
699
  $flags = flag_get_flags('node', $form['#node_type']->type, $user);
700
  foreach ($flags as $flag) {
701
    if ($flag->show_on_form) {
702
      // To be able to process node tokens in flag labels, we create a fake
703
      // node and store it in the flag's cache for replace_tokens() to find,
704
      // with a fake ID.
705
      $flag->remember_entity('fake', (object) array(
706
        'nid' => NULL,
707
        'type' => $form['#node_type']->type,
708
        'title' => '',
709
      ));
710
      $var = 'flag_' . $flag->name . '_default';
711
      $form['workflow']['flag'][$var] = array(
712
        '#type' => 'checkbox',
713
        '#title' => $flag->get_label('flag_short', 'fake'),
714
        '#default_value' => variable_get($var . '_' . $form['#node_type']->type, 0),
715
        '#return_value' => 1,
716
      );
717
    }
718
  }
719

    
720
  if (isset($form['workflow']['flag'])) {
721
    $form['workflow']['flag'] += array(
722
      '#type' => 'item',
723
      '#title' => t('Default flags'),
724
      '#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))),
725
      // Make the spacing a bit more compact:
726
      '#prefix' => '<div class="form-checkboxes">',
727
      '#suffix' => '</div>',
728
    );
729
  }
730
}
731

    
732
/**
733
 * Implements hook_field_attach_form().
734
 *
735
 * Handles the 'show_on_form' flag option.
736
 *
737
 * Warning: will not work on entity types that are not fieldable, as this relies
738
 * on a field module hook.
739
 *
740
 * @see flag_field_attach_submit()
741
 */
742
function flag_field_attach_form($entity_type, $entity, &$form, &$form_state, $langcode) {
743
  list($id) = entity_extract_ids($entity_type, $entity);
744
  // Some modules are being stupid here. Commerce!
745
  if (empty($id)) {
746
    $id = NULL;
747
  }
748

    
749
  // Keep track of whether the entity is new or not, as we're about to fiddle
750
  // with the entity id for the flag's entity cache.
751
  $is_existing_entity = !empty($id);
752

    
753
  // Get all possible flags for this entity type.
754
  $flags = flag_get_flags($entity_type);
755

    
756
  // Filter out flags which need to be included on the node form.
757
  $flags_in_form = 0;
758
  $flags_visible = 0;
759
  foreach ($flags as $flag) {
760
    if (!$flag->show_on_form) {
761
      continue;
762
    }
763

    
764
    // Get the flag status.
765
    if ($is_existing_entity) {
766
      $flag_status = $flag->is_flagged($id);
767
    }
768
    else {
769
      // We don't have per-bundle defaults on general entities yet: default
770
      // status is just unflagged.
771
      $flag_status = FALSE;
772
      // Apply the per-bundle defaults for nodes.
773
      if ($entity_type == 'node') {
774
        $node_type = $entity->type;
775
        $flag_status = variable_get('flag_' . $flag->name . '_default_' . $node_type, 0);
776
      }
777

    
778
      // For a new, unsaved entity, make a dummy entity ID so that the flag
779
      // handler can remember the entity. This allows access to the flag to be
780
      // correctly handled in node and comment preview.
781
      $id = 'new';
782
      $flag->remember_entity($id, $entity);
783
    }
784

    
785
    // If the flag is not global and the user doesn't have access, skip it.
786
    // Global flags have their value set even if the user doesn't have access
787
    // to it, similar to the way "published" and "promote" keep the default
788
    // values even if the user doesn't have "administer nodes" permission.
789
    // Furthermore, a global flag is set to its default value on new nodes
790
    // even if the user creating the node doesn't have access to the flag.
791
    global $user;
792
    $access = $flag->access($id, $flag_status ? 'unflag' : 'flag');
793
    if (!$access && !$flag->global) {
794
      continue;
795
    }
796

    
797
    $form['flag'][$flag->name] = array(
798
      '#type' => 'checkbox',
799
      '#title' => $flag->get_label('flag_short', $id),
800
      '#description' => $flag->get_label('flag_long', $id),
801
      '#default_value' => $flag_status,
802
      '#return_value' => 1,
803
      // Used by our drupalSetSummary() on vertical tabs.
804
      '#attributes' => array('title' => $flag->get_title()),
805
    );
806

    
807
    // If the user does not have access to the flag, set as a value.
808
    if (!$access) {
809
      $form['flag'][$flag->name]['#type'] = 'value';
810
      $form['flag'][$flag->name]['#value'] = $flag_status;
811
    }
812
    else {
813
      $flags_visible++;
814
    }
815
    $flags_in_form++;
816
  }
817

    
818
  if ($flags_in_form) {
819
    $form['flag'] += array(
820
      '#weight' => 1,
821
      '#tree' => TRUE,
822
    );
823
  }
824
  if ($flags_visible) {
825
    $form['flag'] += array(
826
      '#type' => 'fieldset',
827
      '#title' => t('Flags'),
828
      '#collapsible' => TRUE,
829
    );
830

    
831
    if ($entity_type == 'node') {
832
      // Turn the fieldset into a vertical tab.
833
      $form['flag'] += array(
834
        '#group' => 'additional_settings',
835
        '#attributes' => array('class' => array('flag-fieldset')),
836
        '#attached' => array(
837
          'js' => array(
838
            'vertical-tabs' => drupal_get_path('module', 'flag') . '/theme/flag-admin.js',
839
          ),
840
        ),
841
      );
842
    }
843
  }
844
}
845

    
846
/**
847
 * Implements hook_field_attach_submit().
848
 *
849
 * @see flag_field_attach_form()
850
 */
851
function flag_field_attach_submit($entity_type, $entity, $form, &$form_state) {
852
  // This is invoked for each flag_field_attach_form(), but possibly more than
853
  // once for a particular form in the case that a form is showing multiple
854
  // entities (field collection, inline entity form). Hence we can't simply
855
  // assume our submitted form values are in $form_state['values']['flag'].
856
  if (isset($form['flag'])) {
857
    $parents = $form['flag']['#parents'];
858
    $flag_values = drupal_array_get_nested_value($form_state['values'], $parents);
859

    
860
    // Put the form values in the entity so flag_field_attach_save() can find
861
    // them. We can't call flag() here as new entities have no id yet.
862
    $entity->flag = $flag_values;
863
  }
864
}
865

    
866
/**
867
 * Implements hook_field_attach_insert().
868
 */
869
function flag_field_attach_insert($entity_type, $entity) {
870
  if (isset($entity->flag)) {
871
    flag_field_attach_save($entity_type, $entity);
872
  }
873
}
874

    
875
/**
876
 * Implements hook_field_attach_update().
877
 */
878
function flag_field_attach_update($entity_type, $entity) {
879
  if (isset($entity->flag)) {
880
    flag_field_attach_save($entity_type, $entity);
881
  }
882
}
883

    
884
/**
885
 * Shared saving routine between flag_field_attach_insert/update().
886
 *
887
 * @see flag_field_attach_form()
888
 */
889
function flag_field_attach_save($entity_type, $entity) {
890
  list($id) = entity_extract_ids($entity_type, $entity);
891
  // Get the flag values we stashed in the entity in flag_field_attach_submit().
892
  foreach ($entity->flag as $flag_name => $state) {
893
    flag($state ? 'flag' : 'unflag', $flag_name, $id);
894
  }
895
}
896

    
897
/*
898
 * Implements hook_contextual_links_view_alter().
899
 */
900
function flag_contextual_links_view_alter(&$element, $items) {
901
  if (isset($element['#element']['#entity_type'])) {
902
    $entity_type = $element['#element']['#entity_type'];
903

    
904
    // Get the entity out of the element. This requires a bit of legwork.
905
    if (isset($element['#element']['#entity'])) {
906
      // EntityAPI entities will all have the entity in the same place.
907
      $entity = $element['#element']['#entity'];
908
    }
909
    elseif (isset($element['#element']['#' . $entity_type])) {
910
      // Node module at least puts it here.
911
      $entity = $element['#element']['#' . $entity_type];
912
    }
913
    else {
914
      // Give up.
915
      return;
916
    }
917

    
918
    // Get all possible flags for this entity type.
919
    $flags = flag_get_flags($entity_type);
920

    
921
    foreach ($flags as $name => $flag) {
922
      if (!$flag->show_contextual_link) {
923
        continue;
924
      }
925

    
926
      list($entity_id) = entity_extract_ids($entity_type, $entity);
927
      if (!$flag->access($entity_id) && (!$flag->is_flagged($entity_id) || !$flag->access($entity_id, 'flag'))) {
928
        // User has no permission to use this flag or flag does not apply to
929
        // this object. The link is not skipped if the user has "flag" access
930
        // but not "unflag" access (this way the unflag denied message is
931
        // shown).
932
        continue;
933
      }
934

    
935
      $element['#links']['flag-' . $name] = array(
936
        'title' => $flag->theme($flag->is_flagged($entity_id) ? 'unflag' : 'flag', $entity_id),
937
        'html' => TRUE,
938
      );
939
    }
940
  }
941
}
942

    
943
/**
944
 * Implements hook_entity_view().
945
 *
946
 * Handles the 'show_in_links' and 'show_as_field' flag options.
947
 *
948
 * Note this is broken for taxonomy terms for version of Drupal core < 7.17.
949
 */
950
function flag_entity_view($entity, $type, $view_mode, $langcode) {
951
  // Get all possible flags for this entity type.
952
  $flags = flag_get_flags($type);
953
  foreach ($flags as $flag) {
954
    // Check if the flag outputs on entity view.
955
    if (!($flag->show_as_field || $flag->shows_in_entity_links($view_mode))) {
956
      // Flag is not configured to output on entity view, so skip it to save on
957
      // calls to access checks.
958
      continue;
959
    }
960

    
961
    $entity_id = $flag->get_entity_id($entity);
962
    // For a new, unsaved entity, make a dummy entity ID so that the flag
963
    // handler can remember the entity. This allows access to the flag to be
964
    // correctly handled in node and comment preview.
965
    if (is_null($entity_id)) {
966
      $entity_id = 'new';
967
    }
968
    $flag->remember_entity($entity_id, $entity);
969

    
970
    if (!$flag->access($entity_id) && (!$flag->is_flagged($entity_id) || !$flag->access($entity_id, 'flag'))) {
971
      // User has no permission to use this flag or flag does not apply to this
972
      // entity. The link is not skipped if the user has "flag" access but
973
      // not "unflag" access (this way the unflag denied message is shown).
974
      continue;
975
    }
976

    
977
    // We're good to go. Output the flag in the appropriate manner(s).
978

    
979
    // The old-style entity links output.
980
    if ($flag->shows_in_entity_links($view_mode)) {
981
      // The flag links are actually fully rendered theme functions.
982
      // The HTML attribute is set to TRUE to allow whatever the themer desires.
983
      $links['flag-' . $flag->name] = array(
984
        'title' => $flag->theme($flag->is_flagged($entity_id) ? 'unflag' : 'flag', $entity_id),
985
        'html' => TRUE,
986
      );
987
    }
988

    
989
    // The pseudofield output.
990
    if ($flag->show_as_field) {
991
      $entity->content['flag_' . $flag->name] = array(
992
        '#markup' => $flag->theme($flag->is_flagged($entity_id) ? 'unflag' : 'flag', $entity_id, array('needs_wrapping_element' => TRUE)),
993
      );
994
    }
995
  }
996

    
997
  // If any links were made, add them to the entity's links array.
998
  if (isset($links)) {
999
    $entity->content['links']['flag'] = array(
1000
      '#theme' => 'links',
1001
      '#links' => $links,
1002
      '#attributes' => array('class' => array('links', 'inline')),
1003
    );
1004
  }
1005
}
1006

    
1007
/**
1008
 * Implements hook_node_insert().
1009
 */
1010
function flag_node_insert($node) {
1011
  flag_node_save($node);
1012
}
1013

    
1014
/**
1015
 * Implements hook_node_update().
1016
 */
1017
function flag_node_update($node) {
1018
  flag_node_save($node);
1019
}
1020

    
1021
/**
1022
 * Shared saving routine between flag_node_insert() and flag_node_update().
1023
 */
1024
function flag_node_save($node) {
1025
  // Response to the flag checkboxes added to the form in flag_form_alter().
1026
  $remembered = FALSE;
1027
  if (isset($node->flag)) {
1028
    foreach ($node->flag as $name => $state) {
1029
      $flag = flag_get_flag($name);
1030
      // Flagging may trigger actions. We want actions to get the current
1031
      // node, not a stale database-loaded one:
1032
      if (!$remembered) {
1033
        $flag->remember_entity($node->nid, $node);
1034
        // Actions may modify a node, and we don't want to overwrite this
1035
        // modification:
1036
        $remembered = TRUE;
1037
      }
1038

    
1039
      $action = $state ? 'flag' : 'unflag';
1040
      // Pass TRUE for $skip_permission_check so that flags that have been
1041
      // passed through as hidden form values are saved.
1042
      $flag->flag($action, $node->nid, NULL, TRUE);
1043
    }
1044
  }
1045
}
1046

    
1047
/**
1048
 * Implements hook_entity_delete().
1049
 */
1050
function flag_entity_delete($entity, $type) {
1051
  // Node and user flags handle things through the entity type delete hooks.
1052
  // @todo: make this configurable in the flag type definition?
1053
  if ($type == 'node' || $type == 'user') {
1054
    return;
1055
  }
1056

    
1057
  list($id) = entity_extract_ids($type, $entity);
1058
  _flag_entity_delete($type, $id);
1059
}
1060

    
1061
/**
1062
 * Implements hook_node_delete().
1063
 */
1064
function flag_node_delete($node) {
1065
  foreach (flag_get_flags('node') as $flag) {
1066
    // If the flag is being tracked by translation set and the node is part
1067
    // of a translation set, don't delete the flagging record.
1068
    // Instead, data will be updated in hook_node_translation_change(), below.
1069
    if (!$flag->i18n || empty($node->tnid)) {
1070
      _flag_entity_delete('node', $node->nid, $flag->fid);
1071
    }
1072
  }
1073
}
1074

    
1075
/**
1076
 * Implements hook_node_translation_change().
1077
 *
1078
 * (Hook provided by translation_helpers module.)
1079
 */
1080
function flag_node_translation_change($node) {
1081
  if (isset($node->translation_change)) {
1082
    // If there is only one node remaining, track by nid rather than tnid.
1083
    // Otherwise, use the new tnid.
1084
    $entity_id = $node->translation_change['new_tnid'] == 0 ? $node->translation_change['remaining_nid'] : $node->translation_change['new_tnid'];
1085
    foreach (flag_get_flags('node') as $flag) {
1086
      if ($flag->i18n) {
1087
        db_update('flagging')->fields(array('entity_id' => $entity_id))
1088
          ->condition('fid', $flag->fid)
1089
          ->condition('entity_id', $node->translation_change['old_tnid'])
1090
          ->execute();
1091
        db_update('flag_counts')->fields(array('entity_id' => $entity_id))
1092
          ->condition('fid', $flag->fid)
1093
          ->condition('entity_id', $node->translation_change['old_tnid'])
1094
          ->execute();
1095
      }
1096
    }
1097
  }
1098
}
1099

    
1100
/**
1101
 * Deletes flagging records for the entity.
1102
 *
1103
 * @param $entity_type
1104
 *   The type of the entity being deleted; e.g. 'node' or 'comment'.
1105
 * @param $entity_id
1106
 *   The ID of the entity being deleted.
1107
 * @param $fid
1108
 *   The flag id
1109
 */
1110
function _flag_entity_delete($entity_type, $entity_id, $fid = NULL) {
1111
  $query_content = db_delete('flagging')
1112
    ->condition('entity_type', $entity_type)
1113
    ->condition('entity_id', $entity_id);
1114
  $query_counts = db_delete('flag_counts')
1115
    ->condition('entity_type', $entity_type)
1116
    ->condition('entity_id', $entity_id);
1117
  if (isset($fid)) {
1118
    $query_content->condition('fid', $fid);
1119
    $query_counts->condition('fid', $fid);
1120
  }
1121
  $query_content->execute();
1122
  $query_counts->execute();
1123
}
1124

    
1125
/**
1126
 * Implements hook_user_login().
1127
 */
1128
function flag_user_login(&$edit, &$account) {
1129
  // Migrate anonymous flags to this user's account.
1130
  if (module_exists('session_api') && ($sid = flag_get_sid(0))) {
1131
    // Get a list of flagging IDs that will be moved over.
1132
    $duplicate_flaggings = array();
1133
    $flaggings = db_select('flagging', 'fc')
1134
      ->fields('fc', array('flagging_id', 'fid', 'entity_id'))
1135
      ->condition('uid', 0)
1136
      ->condition('sid', $sid)
1137
      ->execute()
1138
      ->fetchAllAssoc('flagging_id', PDO::FETCH_ASSOC);
1139

    
1140
    // Convert anonymous flaggings to their authenticated account.
1141
    foreach ($flaggings as $flagging_id => $flagging) {
1142
      // Each update is wrapped in a try block to prevent unique key errors.
1143
      // Any duplicate object that was flagged as anonoymous is deleted in the
1144
      // subsequent db_delete() call.
1145
      try {
1146
        db_update('flagging')
1147
          ->fields(array(
1148
            'uid' => $account->uid,
1149
            'sid' => 0,
1150
          ))
1151
          ->condition('flagging_id', $flagging_id)
1152
          ->execute();
1153
      }
1154
      catch (Exception $e) {
1155
        $duplicate_flaggings[$flagging_id] = $flagging;
1156
      }
1157
    }
1158

    
1159
    // Delete any remaining flags this user had as an anonymous user. We use the
1160
    // proper unflag action here to make sure the count gets decremented again
1161
    // and so that other modules can clean up their tables if needed.
1162
    $anonymous_user = drupal_anonymous_user();
1163
    foreach ($duplicate_flaggings as $flagging_id => $flagging) {
1164
      $flag = flag_get_flag(NULL, $flagging['fid']);
1165
      $flag->flag('unflag', $flagging['entity_id'], $anonymous_user, TRUE);
1166
    }
1167

    
1168
    // Clean up anonymous cookies.
1169
    FlagCookieStorage::drop();
1170
  }
1171
}
1172

    
1173
/**
1174
 * Implements hook_user_cancel().
1175
 */
1176
function flag_user_cancel($edit, $account, $method) {
1177
  flag_user_account_removal($account);
1178
}
1179

    
1180
/**
1181
 * Implements hook_user_delete().
1182
 */
1183
function flag_user_delete($account) {
1184
  flag_user_account_removal($account);
1185
}
1186

    
1187
/**
1188
 * Shared helper for user account cancellation or deletion.
1189
 */
1190
function flag_user_account_removal($account) {
1191
  // Remove flags by this user.
1192
  $query = db_select('flagging', 'fc');
1193
  $query->leftJoin('flag_counts', 'c', 'fc.entity_id = c.entity_id AND fc.entity_type = c.entity_type AND fc.fid = c.fid');
1194
  $result = $query
1195
    ->fields('fc', array('fid', 'entity_id'))
1196
    ->fields('c', array('count'))
1197
    ->condition('fc.uid', $account->uid)
1198
    ->execute();
1199

    
1200
  foreach ($result as $flag_data) {
1201
    // Only decrement the flag count table if it's greater than 1.
1202
    if ($flag_data->count > 0) {
1203
      $flag_data->count--;
1204
      db_update('flag_counts')
1205
        ->fields(array(
1206
          'count' => $flag_data->count,
1207
        ))
1208
        ->condition('fid', $flag_data->fid)
1209
        ->condition('entity_id', $flag_data->entity_id)
1210
        ->execute();
1211
    }
1212
    elseif ($flag_data->count == 0) {
1213
      db_delete('flag_counts')
1214
        ->condition('fid', $flag_data->fid)
1215
        ->condition('entity_id', $flag_data->entity_id)
1216
        ->execute();
1217
    }
1218
  }
1219
  db_delete('flagging')
1220
    ->condition('uid', $account->uid)
1221
    ->execute();
1222

    
1223
  // Remove flags that have been done to this user.
1224
  _flag_entity_delete('user', $account->uid);
1225
}
1226

    
1227
/**
1228
 * Implements hook_user_view().
1229
 */
1230
function flag_user_view($account, $view_mode) {
1231
  $flags = flag_get_flags('user');
1232
  $flag_items = array();
1233
  foreach ($flags as $flag) {
1234
    if (!$flag->access($account->uid)) {
1235
      // User has no permission to use this flag.
1236
      continue;
1237
    }
1238
    if (!$flag->show_on_profile) {
1239
      // Flag not set to appear on profile.
1240
      continue;
1241
    }
1242
    $flag_items[$flag->name] = array(
1243
      '#type' => 'user_profile_item',
1244
      '#title' => $flag->get_title($account->uid),
1245
      '#markup' => $flag->theme($flag->is_flagged($account->uid) ? 'unflag' : 'flag', $account->uid),
1246
      '#attributes' => array('class' => array('flag-profile-' . $flag->name)),
1247
    );
1248
  }
1249
  if (!empty($flag_items)) {
1250
    $account->content['flags'] = $flag_items;
1251
    $account->content['flags'] += array(
1252
      '#type' => 'user_profile_category',
1253
      '#title' => t('Actions'),
1254
      '#attributes' => array('class' => array('flag-profile')),
1255
    );
1256
  }
1257
}
1258

    
1259
/**
1260
 * Implements hook_session_api_cleanup().
1261
 *
1262
 * Clear out anonymous user flaggings during Session API cleanup.
1263
 */
1264
function flag_session_api_cleanup($arg = 'run') {
1265
  // Session API 1.1 version:
1266
  if ($arg == 'run') {
1267
    $query = db_select('flagging', 'fc');
1268
    $query->leftJoin('session_api', 's', 'fc.sid = s.sid');
1269
    $result = $query
1270
      ->fields('fc', array('sid'))
1271
      ->condition('fc.sid', 0, '<>')
1272
      ->isNull('s.sid')
1273
      ->execute();
1274
    foreach ($result as $row) {
1275
      db_delete('flagging')
1276
        ->condition('sid', $row->sid)
1277
        ->execute();
1278
    }
1279
  }
1280
  // Session API 1.2+ version.
1281
  elseif (is_array($arg)) {
1282
    $outdated_sids = $arg;
1283
    db_delete('flagging')->condition('sid', $outdated_sids, 'IN')->execute();
1284
  }
1285
}
1286

    
1287
/**
1288
 * Implements hook_field_attach_delete_bundle().
1289
 *
1290
 * Delete any flags' applicability to the deleted bundle.
1291
 */
1292
function flag_field_attach_delete_bundle($entity_type, $bundle, $instances) {
1293
  // This query can't use db_delete() because that doesn't support a
1294
  // subquery: see http://drupal.org/node/1267508.
1295
  db_query("DELETE FROM {flag_types} WHERE type = :bundle AND fid IN (SELECT fid FROM {flag} WHERE entity_type = :entity_type)", array(
1296
    ':bundle' => $bundle,
1297
    ':entity_type' => $entity_type,
1298
  ));
1299
}
1300

    
1301
/**
1302
 * Flags or unflags an item.
1303
 *
1304
 * @param $action
1305
 *   Either 'flag' or 'unflag'.
1306
 * @param $flag_name
1307
 *   The name of the flag to use.
1308
 * @param $entity_id
1309
 *   The ID of the item to flag or unflag.
1310
 * @param $account
1311
 *   (optional) The user on whose behalf to flag. Omit for the current user.
1312
 * @param permissions_check
1313
 *   (optional) A boolean indicating whether to skip permissions.
1314
 *
1315
 * @return
1316
 *   FALSE if some error occured (e.g., user has no permission, flag isn't
1317
 *   applicable to the item, etc.), TRUE otherwise.
1318
 */
1319
function flag($action, $flag_name, $entity_id, $account = NULL, $permissions_check = FALSE) {
1320
  if (!($flag = flag_get_flag($flag_name))) {
1321
    // Flag does not exist.
1322
    return FALSE;
1323
  }
1324
  return $flag->flag($action, $entity_id, $account, $permissions_check);
1325
}
1326

    
1327
/**
1328
 * Implements hook_flag_flag().
1329
 */
1330
function flag_flag_flag($flag, $entity_id, $account, $flagging) {
1331
  if (module_exists('trigger')) {
1332
    flag_flag_trigger('flag', $flag, $entity_id, $account, $flagging);
1333
  }
1334
}
1335

    
1336
/**
1337
 * Implements hook_flag_unflag().
1338
 */
1339
function flag_flag_unflag($flag, $entity_id, $account, $flagging) {
1340
  if (module_exists('trigger')) {
1341
    flag_flag_trigger('unflag', $flag, $entity_id, $account, $flagging);
1342
  }
1343
}
1344

    
1345
/**
1346
 * Trigger actions if any are available. Helper for hook_flag_(un)flag().
1347
 *
1348
 * @param $op
1349
 *  The operation being performed: one of 'flag' or 'unflag'.
1350
 * @param $flag
1351
 *  The flag object.
1352
 * @param $entity_id
1353
 *  The id of the entity the flag is on.
1354
 * @param $account
1355
 *  The user account performing the action.
1356
 * @param $flagging_id
1357
 *  The flagging entity.
1358
 */
1359
function flag_flag_trigger($action, $flag, $entity_id, $account, $flagging) {
1360
  $context['hook'] = 'flag';
1361
  $context['account'] = $account;
1362
  $context['flag'] = $flag;
1363
  $context['op'] = $action;
1364
  // We add to the $context all the objects we know about:
1365
  $context = array_merge($flag->get_relevant_action_objects($entity_id), $context);
1366
  // The primary object the actions work on.
1367
  $object = $flag->fetch_entity($entity_id);
1368

    
1369
  // Generic "all flags" actions.
1370
  foreach (trigger_get_assigned_actions('flag_' . $action) as $aid => $action_info) {
1371
    // The 'if ($aid)' is a safeguard against
1372
    // http://drupal.org/node/271460#comment-886564
1373
    if ($aid) {
1374
      actions_do($aid, $object, $context);
1375
    }
1376
  }
1377
  // Actions specifically for this flag.
1378
  foreach (trigger_get_assigned_actions('flag_' . $action . '_' . $flag->name) as $aid => $action_info) {
1379
    if ($aid) {
1380
      actions_do($aid, $object, $context);
1381
    }
1382
  }
1383
}
1384

    
1385
/**
1386
 * Implements hook_flag_access().
1387
 */
1388
function flag_flag_access($flag, $entity_id, $action, $account) {
1389
  // Do nothing if there is no restriction by authorship.
1390
  if (empty($flag->access_author)) {
1391
    return;
1392
  }
1393

    
1394
  // Restrict access by authorship. It's important that TRUE is never returned
1395
  // here, otherwise we'd grant permission even if other modules denied access.
1396
  if ($flag->entity_type == 'node') {
1397
    // For non-existent nodes (such as on the node add form), assume that the
1398
    // current user is creating the content.
1399
    if (empty($entity_id) || !($node = $flag->fetch_entity($entity_id))) {
1400
      return $flag->access_author == 'others' ? FALSE : NULL;
1401
    }
1402

    
1403
    if ($flag->access_author == 'own' && $node->uid != $account->uid) {
1404
      return FALSE;
1405
    }
1406
    elseif ($flag->access_author == 'others' && $node->uid == $account->uid) {
1407
      return FALSE;
1408
    }
1409
  }
1410

    
1411
  // Restrict access by comment authorship.
1412
  if ($flag->entity_type == 'comment') {
1413
    // For non-existent comments (such as on the comment add form), assume that
1414
    // the current user is creating the content.
1415
    if (empty($entity_id) || !($comment = $flag->fetch_entity($entity_id)) || $entity_id == 'new') {
1416
      return $flag->access_author == 'comment_others' ? FALSE : NULL;
1417
    }
1418

    
1419
    $node = node_load($comment->nid);
1420
    if ($flag->access_author == 'node_own' && $node->uid != $account->uid) {
1421
      return FALSE;
1422
    }
1423
    elseif ($flag->access_author == 'node_others' && $node->uid == $account->uid) {
1424
      return FALSE;
1425
    }
1426
    elseif ($flag->access_author == 'comment_own' && $comment->uid != $account->uid) {
1427
      return FALSE;
1428
    }
1429
    elseif ($flag->access_author == 'comment_others' && $comment->uid == $account->uid) {
1430
      return FALSE;
1431
    }
1432
  }
1433
}
1434

    
1435
/**
1436
 * Implements hook_flag_access_multiple().
1437
 */
1438
function flag_flag_access_multiple($flag, $entity_ids, $account) {
1439
  $access = array();
1440

    
1441
  // Do nothing if there is no restriction by authorship.
1442
  if (empty($flag->access_author)) {
1443
    return $access;
1444
  }
1445

    
1446
  if ($flag->entity_type == 'node') {
1447
    // Restrict access by authorship. This is similar to flag_flag_access()
1448
    // above, but returns an array of 'nid' => $access values. Similarly, we
1449
    // should never return TRUE in any of these access values, only FALSE if we
1450
    // want to deny access, or use the current access value provided by Flag.
1451
    $result = db_select('node', 'n')
1452
      ->fields('n', array('nid', 'uid'))
1453
      ->condition('nid', array_keys($entity_ids), 'IN')
1454
      ->condition('type', $flag->types, 'IN')
1455
      ->execute();
1456
    foreach ($result as $row) {
1457
      if ($flag->access_author == 'own') {
1458
        $access[$row->nid] = $row->uid != $account->uid ? FALSE : NULL;
1459
      }
1460
      elseif ($flag->access_author == 'others') {
1461
        $access[$row->nid] = $row->uid == $account->uid ? FALSE : NULL;
1462
      }
1463
    }
1464
  }
1465

    
1466
  if ($flag->entity_type == 'comment') {
1467
    // Restrict access by comment ownership.
1468
    $query = db_select('comment', 'c');
1469
    $query->leftJoin('node', 'n', 'c.nid = n.nid');
1470
    $query
1471
      ->fields('c', array('cid', 'nid', 'uid'))
1472
      ->condition('c.cid', $entity_ids, 'IN');
1473
    $query->addField('c', 'uid', 'comment_uid');
1474
    $result = $query->execute();
1475

    
1476
    foreach ($result as $row) {
1477
      if ($flag->access_author == 'node_own') {
1478
        $access[$row->cid] = $row->node_uid != $account->uid ? FALSE : NULL;
1479
      }
1480
      elseif ($flag->access_author == 'node_others') {
1481
        $access[$row->cid] = $row->node_uid == $account->uid ? FALSE : NULL;
1482
      }
1483
      elseif ($flag->access_author == 'comment_own') {
1484
        $access[$row->cid] = $row->comment_uid != $account->uid ? FALSE : NULL;
1485
      }
1486
      elseif ($flag->access_author == 'comment_others') {
1487
        $access[$row->cid] = $row->comment_uid == $account->uid ? FALSE : NULL;
1488
      }
1489
    }
1490
  }
1491

    
1492
  // Always return an array (even if empty) of accesses.
1493
  return $access;
1494
}
1495

    
1496
/**
1497
 * Implements hook_theme().
1498
 */
1499
function flag_theme() {
1500
  $path = drupal_get_path('module', 'flag') . '/theme';
1501

    
1502
  return array(
1503
    'flag' => array(
1504
      'variables' => array(
1505
        'flag' => NULL,
1506
        'action' => NULL,
1507
        'entity_id' => NULL,
1508
        'after_flagging' => FALSE,
1509
        'needs_wrapping_element' => FALSE,
1510
        'errors' => array(),
1511
      ),
1512
      'template' => 'flag',
1513
      'pattern' => 'flag__',
1514
      'path' => $path,
1515
    ),
1516
    'flag_tokens_browser' => array(
1517
      'variables' => array(
1518
        'types' => array('all'),
1519
        'global_types' => TRUE,
1520
      ),
1521
      'file' => 'flag.tokens.inc',
1522
    ),
1523
    'flag_admin_listing' => array(
1524
      'render element' => 'form',
1525
      'file' => 'includes/flag.admin.inc',
1526
    ),
1527
    'flag_admin_listing_disabled' => array(
1528
      'variables' => array(
1529
        'flags' => NULL,
1530
        'default_flags' => NULL,
1531
      ),
1532
      'file' => 'includes/flag.admin.inc',
1533
    ),
1534
    'flag_admin_page' => array(
1535
      'variables' => array(
1536
        'flags' => NULL,
1537
        'default_flags' => NULL,
1538
        'flag_admin_listing' => NULL,
1539
      ),
1540
      'file' => 'includes/flag.admin.inc',
1541
    ),
1542
    'flag_form_roles' => array(
1543
      'render element' => 'element',
1544
      'file' => 'includes/flag.admin.inc',
1545
    ),
1546
  );
1547
}
1548

    
1549
/**
1550
 * A preprocess function for our theme('flag'). It generates the
1551
 * variables needed there.
1552
 *
1553
 * The $variables array initially contains the following arguments:
1554
 * - $flag
1555
 * - $action
1556
 * - $entity_id
1557
 * - $after_flagging
1558
 * - $errors
1559
 * - $needs_wrapping_element
1560
 *
1561
 * See 'flag.tpl.php' for their documentation.
1562
 */
1563
function template_preprocess_flag(&$variables) {
1564
  global $user;
1565
  $initialized = &drupal_static(__FUNCTION__, array());
1566

    
1567
  // Some typing shotcuts:
1568
  $flag =& $variables['flag'];
1569
  $action = $variables['action'];
1570
  $entity_id = $variables['entity_id'];
1571
  $errors = implode('<br />', $variables['errors']);
1572
  $flag_name_css = str_replace('_', '-', $flag->name);
1573

    
1574
  // Generate the link URL.
1575
  $link_type = $flag->get_link_type();
1576
  $link = module_invoke($link_type['module'], 'flag_link', $flag, $action, $entity_id);
1577
  if (isset($link['title']) && empty($link['html'])) {
1578
    $link['title'] = check_plain($link['title']);
1579
  }
1580

    
1581
  // Replace the link with the access denied text if unable to flag.
1582
  if ($action == 'unflag' && !$flag->access($entity_id, 'unflag')) {
1583
    $link['title'] = $flag->get_label('unflag_denied_text', $entity_id);
1584
    unset($link['href']);
1585
  }
1586

    
1587
  // Anonymous users always need the JavaScript to maintain their flag state.
1588
  if ($user->uid == 0) {
1589
    $link_type['uses standard js'] = TRUE;
1590
  }
1591

    
1592
  // Load the JavaScript/CSS, if the link type requires it.
1593
  if (!isset($initialized[$link_type['name']])) {
1594
    if ($link_type['uses standard css']) {
1595
      drupal_add_css(drupal_get_path('module', 'flag') . '/theme/flag.css');
1596
    }
1597
    if ($link_type['uses standard js']) {
1598
      drupal_add_js(drupal_get_path('module', 'flag') . '/theme/flag.js');
1599
    }
1600
    $initialized[$link_type['name']] = TRUE;
1601
  }
1602

    
1603
  $variables['link'] = $link;
1604
  $variables['link_href'] = isset($link['href']) ? check_url(url($link['href'], $link)) : FALSE;
1605
  $variables['link_text'] = isset($link['title']) ? $link['title'] : $flag->get_label($action . '_short', $entity_id);
1606
  $variables['link_title'] = isset($link['attributes']['title']) ? check_plain($link['attributes']['title']) : check_plain(strip_tags($flag->get_label($action . '_long', $entity_id)));
1607
  $variables['status'] = ($action == 'flag' ? 'unflagged' : 'flagged');
1608
  $variables['flag_name_css'] = $flag_name_css;
1609

    
1610
  $variables['flag_wrapper_classes_array'] = array();
1611
  $variables['flag_wrapper_classes_array'][] = 'flag-wrapper';
1612
  $variables['flag_wrapper_classes_array'][] = 'flag-' . $flag_name_css;
1613
  $variables['flag_wrapper_classes_array'][] = 'flag-' . $flag_name_css . '-' . $entity_id;
1614

    
1615
  $variables['flag_classes_array'] = array();
1616
  $variables['flag_classes_array'][] = 'flag';
1617
  if (isset($link['href'])) {
1618
    $variables['flag_classes_array'][] = $variables['action'] . '-action';
1619
    $variables['flag_classes_array'][] = 'flag-link-' . $flag->link_type;
1620
  }
1621
  else {
1622
    $variables['flag_classes_array'][] = $variables['action'] . '-disabled';
1623
  }
1624
  if (isset($link['attributes']['class'])) {
1625
    $link['attributes']['class'] = is_string($link['attributes']['class']) ? array_filter(explode(' ', $link['attributes']['class'])) : $link['attributes']['class'];
1626
    $variables['flag_classes_array'] = array_merge($variables['flag_classes_array'], $link['attributes']['class']);
1627
  }
1628
  $variables['message_classes_array'] = array();
1629
  if ($variables['after_flagging']) {
1630
    $variables['message_classes_array'][] = 'flag-message';
1631
    if ($errors) {
1632
      $variables['message_classes_array'][] = 'flag-failure-message';
1633
      $variables['message_text'] = $errors;
1634
    }
1635
    else {
1636
      $inverse_action = ($action == 'flag' ? 'unflag' : 'flag');
1637
      $variables['message_classes_array'][] = 'flag-success-message';
1638
      $variables['message_classes_array'][] = 'flag-' . $variables['status'] . '-message';
1639
      $variables['message_text'] = $flag->get_label($inverse_action . '_message', $entity_id);
1640
      $variables['flag_classes_array'][] = $variables['status'];
1641
      // By default we make our JS code remove, after a few seconds, only
1642
      // success messages.
1643
      $variables['message_classes_array'][] = 'flag-auto-remove';
1644
    }
1645
  }
1646
  else {
1647
    $variables['message_text'] = '';
1648
  }
1649
}
1650

    
1651
/**
1652
 * Theme processor for flag.tpl.php.
1653
 *
1654
 * @param array &$variables
1655
 *  An array of variables for the template. See 'flag.tpl.php' for their
1656
 *  documentation.
1657
 */
1658
function template_process_flag(&$variables) {
1659
  // Convert class arrays to strings.
1660
  $variables['flag_wrapper_classes'] = implode(' ', $variables['flag_wrapper_classes_array']);
1661
  $variables['flag_classes'] = implode(' ', $variables['flag_classes_array']);
1662
  $variables['message_classes'] = implode(' ', $variables['message_classes_array']);
1663
}
1664

    
1665
/**
1666
 * Return an array of flag names keyed by fid.
1667
 */
1668
function _flag_get_flag_names() {
1669
  $flags = flag_get_flags();
1670
  $flag_names = array();
1671
  foreach ($flags as $flag) {
1672
    $flag_names[$flag->fid] = $flag->name;
1673
  }
1674
  return $flag_names;
1675
}
1676

    
1677
/**
1678
 * Return an array of flag link types suitable for a select list or radios.
1679
 */
1680
function _flag_link_type_options() {
1681
  $options = array();
1682
  $types = flag_get_link_types();
1683
  foreach ($types as $type_name => $type) {
1684
    $options[$type_name] = $type['title'];
1685
  }
1686
  return $options;
1687
}
1688

    
1689
/**
1690
 * Return an array of flag link type descriptions.
1691
 */
1692
function _flag_link_type_descriptions() {
1693
  $options = array();
1694
  $types = flag_get_link_types();
1695
  foreach ($types as $type_name => $type) {
1696
    $options[$type_name] = $type['description'];
1697
  }
1698
  return $options;
1699
}
1700

    
1701
// ---------------------------------------------------------------------------
1702
// Non-Views public API
1703

    
1704
/**
1705
 * Gets the count of flaggings for the given flag.
1706
 *
1707
 * For example, if you have an 'endorse' flag, this method will tell you how
1708
 * many endorsements have been made, rather than how many things have been
1709
 * endorsed.
1710
 *
1711
 * When called during a flagging or unflagging (such as from a hook
1712
 * implementation or from Rules), the flagging or unflagging that is in the
1713
 * process of being performed:
1714
 *  - will be included during a flagging operation
1715
 *  - will STILL be included during an unflagging operation. That is, the count
1716
 *    will not yet have been decreased.
1717
 * This is because this queries the {flagging} table, which only has its record
1718
 * deleted at the very end of the unflagging process.
1719
 *
1720
 * @param $flag
1721
 *   The flag.
1722
 * @param $entity_type
1723
 *   The entity type. For example, 'node'.
1724
 *
1725
 * @return int
1726
 *   The number of flaggings for the flag.
1727
 */
1728
function flag_get_entity_flag_counts($flag, $entity_type) {
1729
  $counts = &drupal_static(__FUNCTION__);
1730

    
1731
  // We check to see if the flag count is already in the cache,
1732
  // if it's not, run the query.
1733
  if (!isset($counts[$flag->name][$entity_type])) {
1734
    $counts[$flag->name][$entity_type] = array();
1735
    $result = db_select('flagging', 'f')
1736
      ->fields('f', array('fid'))
1737
      ->condition('fid', $flag->fid)
1738
      ->condition('entity_type', $entity_type)
1739
      ->countQuery()
1740
      ->execute()
1741
      ->fetchField();
1742
    $counts[$flag->name][$entity_type] = $result;
1743
  }
1744

    
1745
  return $counts[$flag->name][$entity_type];
1746
}
1747

    
1748
/**
1749
 * Gets the count of the flaggings made by a user with a flag.
1750
 *
1751
 * For example, with a 'bookmarks' flag, this returns the number of bookmarks
1752
 * a user has created.
1753
 *
1754
 * When called during a flagging or unflagging (such as from a hook
1755
 * implementation or from Rules), the flagging or unflagging that is in the
1756
 * process of being performed:
1757
 *  - will be included during a flagging operation
1758
 *  - will STILL be included during an unflagging operation. That is, the count
1759
 *    will not yet have been decreased.
1760
 * This is because this queries the {flagging} table, which only has its record
1761
 * deleted at the very end of the unflagging process.
1762
 *
1763
 * However, it should be noted that this method does not serves global flags.
1764
 *
1765
 * @param $flag
1766
 *   The flag.
1767
 * @param $user
1768
 *   The user object.
1769
 *
1770
 * @return int
1771
 *   The number of flaggings for the given flag and user.
1772
 */
1773
function flag_get_user_flag_counts($flag, $user) {
1774
  $counts = &drupal_static(__FUNCTION__);
1775

    
1776
  // We check to see if the flag count is already in the cache,
1777
  // if it's not, run the query.
1778
  if (!isset($counts[$flag->name][$user->uid])) {
1779
    $counts[$flag->name][$user->uid] = array();
1780
    $result = db_select('flagging', 'f')
1781
      ->fields('f', array('fid'))
1782
      ->condition('fid', $flag->fid)
1783
      ->condition('uid', $user->uid)
1784
      ->countQuery()
1785
      ->execute()
1786
      ->fetchField();
1787
    $counts[$flag->name][$user->uid] = $result;
1788
  }
1789

    
1790
  return $counts[$flag->name][$user->uid];
1791
}
1792

    
1793
/**
1794
 * Gets flag counts for all flags on an entity.
1795
 *
1796
 * Provides a count of all the flaggings for a single entity. Instead
1797
 * of a single response, this method returns an array of counts keyed by
1798
 * the flag ID:
1799
 *
1800
 * @code
1801
 * array(
1802
 *   my_flag => 42
1803
 *   another_flag => 57
1804
 * );
1805
 * @endcode
1806
 *
1807
 * When called during a flagging or unflagging (such as from a hook
1808
 * implementation or from Rules), the count this returns takes into account the
1809
 * the flagging or unflagging that is in the process of being performed.
1810
 *
1811
 * @param $entity_type
1812
 *   The entity type (usually 'node').
1813
 * @param $entity_id
1814
 *   The entity ID (usually the node ID).
1815
 *
1816
 * @return array
1817
 *   An array giving the counts of all flaggings on the entity. The flag IDs
1818
 *   are the keys and the counts for each flag the values. Note that flags
1819
 *   that have no flaggings are not included in the array.
1820
 */
1821
function flag_get_counts($entity_type, $entity_id) {
1822
  $counts = &drupal_static(__FUNCTION__);
1823

    
1824
  if (!isset($counts[$entity_type][$entity_id])) {
1825
    $counts[$entity_type][$entity_id] = array();
1826
    $query = db_select('flag', 'f');
1827
    $query->leftJoin('flag_counts', 'fc', 'f.fid = fc.fid');
1828
    $result = $query
1829
      ->fields('f', array('name'))
1830
      ->fields('fc', array('count'))
1831
      ->condition('fc.entity_type', $entity_type)
1832
      ->condition('fc.entity_id', $entity_id)
1833
      ->execute();
1834
    foreach ($result as $row) {
1835
      $counts[$entity_type][$entity_id][$row->name] = $row->count;
1836
    }
1837
  }
1838

    
1839
  return $counts[$entity_type][$entity_id];
1840
}
1841

    
1842
/**
1843
 * Gets the count of entities flagged by the given flag.
1844
 *
1845
 * For example, with a 'report abuse' flag, this returns the number of
1846
 * entities that have been reported, not the total number of reports. In other
1847
 * words, an entity that has been reported multiple times will only be counted
1848
 * once.
1849
 *
1850
 * When called during a flagging or unflagging (such as from a hook
1851
 * implementation or from Rules), the count this returns takes into account the
1852
 * the flagging or unflagging that is in the process of being performed.
1853
 *
1854
 * @param $flag_name
1855
 *   The flag name for which to retrieve a flag count.
1856
 * @param $reset
1857
 *   (optional) Reset the internal cache and execute the SQL query another time.
1858
 *
1859
 * @return int
1860
 *   The number of entities that are flagged with the flag.
1861
 */
1862
function flag_get_flag_counts($flag_name, $reset = FALSE) {
1863
  $counts = &drupal_static(__FUNCTION__);
1864

    
1865
  if ($reset) {
1866
    $counts = array();
1867
  }
1868
  if (!isset($counts[$flag_name])) {
1869
    $flag = flag_get_flag($flag_name);
1870
    $counts[$flag_name] = db_select('flag_counts', 'fc')
1871
      ->fields('fc', array('fid'))
1872
      ->condition('fid', $flag->fid)
1873
      ->countQuery()
1874
      ->execute()
1875
      ->fetchField();
1876
  }
1877

    
1878
  return $counts[$flag_name];
1879
}
1880

    
1881
/**
1882
 * Load a single flag either by name or by flag ID.
1883
 *
1884
 * @param $name
1885
 *  (optional) The flag name.
1886
 * @param $fid
1887
 *  (optional) The the flag id.
1888
 *
1889
 * @return
1890
 *  The flag object, or FALSE if no matching flag was found.
1891
 */
1892
function flag_get_flag($name = NULL, $fid = NULL) {
1893
  $flags = flag_get_flags();
1894
  if (isset($name)) {
1895
    if (isset($flags[$name])) {
1896
      return $flags[$name];
1897
    }
1898
  }
1899
  elseif (isset($fid)) {
1900
    foreach ($flags as $flag) {
1901
      if ($flag->fid == $fid) {
1902
        return $flag;
1903
      }
1904
    }
1905
  }
1906
  return FALSE;
1907
}
1908

    
1909
/**
1910
 * List all flags available.
1911
 *
1912
 * If all the parameters are omitted, a list of all flags will be returned.
1913
 *
1914
 * @param $entity_type
1915
 *   (optional) The type of entity for which to load the flags. Usually 'node'.
1916
 * @param $content_subtype
1917
 *   (optional) The node type for which to load the flags.
1918
 * @param $account
1919
 *   (optional) The user accont to filter available flags. If not set, all
1920
 *   flags for will this node will be returned.
1921
 *
1922
 * @return
1923
 *   An array of flag objects, keyed by the flag names.
1924
 */
1925
function flag_get_flags($entity_type = NULL, $content_subtype = NULL, $account = NULL) {
1926
  $flags = &drupal_static(__FUNCTION__);
1927

    
1928
  // Retrieve a list of all flags, regardless of the parameters.
1929
  if (!isset($flags)) {
1930
    $flags = array();
1931

    
1932
    // Database flags.
1933
    $query = db_select('flag', 'f');
1934
    $query->leftJoin('flag_types', 'fn', 'fn.fid = f.fid');
1935
    $result = $query
1936
      ->fields('f', array(
1937
        'fid',
1938
        'entity_type',
1939
        'name',
1940
        'title',
1941
        'global',
1942
        'options',
1943
      ))
1944
      ->fields('fn', array('type'))
1945
      ->execute();
1946
    foreach ($result as $row) {
1947
      if (!isset($flags[$row->name])) {
1948
        $flags[$row->name] = flag_flag::factory_by_row($row);
1949
      }
1950
      else {
1951
        $flags[$row->name]->types[] = $row->type;
1952
      }
1953
    }
1954

    
1955
    // Add code-based flags provided by modules.
1956
    $default_flags = flag_get_default_flags();
1957
    foreach ($default_flags as $name => $default_flag) {
1958
      // Insert new enabled flags into the database to give them an FID.
1959
      if ($default_flag->status && !isset($flags[$name])) {
1960
        $default_flag->save();
1961
        $flags[$name] = $default_flag;
1962
      }
1963

    
1964
      if (isset($flags[$name])) {
1965
        // Ensure overridden flags are associated with their parent module.
1966
        $flags[$name]->module = $default_flag->module;
1967

    
1968
        // Update the flag with any properties that are "locked" by the code
1969
        // version.
1970
        if (isset($default_flag->locked)) {
1971
          $flags[$name]->locked = $default_flag->locked;
1972
          foreach ($default_flag->locked as $property) {
1973
            $flags[$name]->$property = $default_flag->$property;
1974
          }
1975
        }
1976
      }
1977
    }
1978

    
1979
    // Sort the list of flags by weight.
1980
    uasort($flags, '_flag_compare_weight');
1981

    
1982
    foreach ($flags as $flag) {
1983
      // Allow modules implementing hook_flag_alter(&$flag) to modify each flag.
1984
      drupal_alter('flag', $flag);
1985
    }
1986
  }
1987

    
1988
  // Make a variable copy to filter types and account.
1989
  $filtered_flags = $flags;
1990

    
1991
  // Filter out flags based on type and subtype.
1992
  if (isset($entity_type) || isset($content_subtype)) {
1993
    foreach ($filtered_flags as $name => $flag) {
1994
      if (!$flag->access_entity_enabled($entity_type, $content_subtype)) {
1995
        unset($filtered_flags[$name]);
1996
      }
1997
    }
1998
  }
1999

    
2000
  // Filter out flags based on account permissions.
2001
  if (isset($account) && $account->uid != 1) {
2002
    foreach ($filtered_flags as $name => $flag) {
2003
      // We test against the 'flag' action, which is the minimum permission to
2004
      // use a flag.
2005
      if (!$flag->user_access('flag', $account)) {
2006
        unset($filtered_flags[$name]);
2007
      }
2008
    }
2009
  }
2010

    
2011
  return $filtered_flags;
2012
}
2013

    
2014
/**
2015
 * Comparison function for uasort().
2016
 */
2017
function _flag_compare_weight($flag1, $flag2) {
2018
  if ($flag1->weight == $flag2->weight) {
2019
    return 0;
2020
  }
2021
  return $flag1->weight < $flag2->weight ? -1 : 1;
2022
}
2023

    
2024
/**
2025
 * Retrieve a list of flags defined by modules.
2026
 *
2027
 * @param $include_disabled
2028
 *   (optional) Unless specified, only enabled flags will be returned.
2029
 *
2030
 * @return
2031
 *   An array of flag prototypes, not usable for flagging. Use flag_get_flags()
2032
 *   if needing to perform a flagging with any enabled flag.
2033
 */
2034
function flag_get_default_flags($include_disabled = FALSE) {
2035
  $default_flags = array();
2036
  $flag_status = variable_get('flag_default_flag_status', array());
2037

    
2038
  $default_flags_info = array();
2039
  foreach (module_implements('flag_default_flags') as $module) {
2040
    $function = $module . '_flag_default_flags';
2041
    foreach ($function() as $flag_name => $flag_info) {
2042
      // Backward compatibility: old exported default flags have their names
2043
      // in $flag_info instead, so we use the + operator to not overwrite it.
2044
      $default_flags_info[$flag_name] = $flag_info + array(
2045
        'name' => $flag_name,
2046
        'module' => $module,
2047
      );
2048
    }
2049
  }
2050

    
2051
  // Allow modules to alter definitions using hook_flag_default_flags_alter().
2052
  drupal_alter('flag_default_flags', $default_flags_info);
2053

    
2054
  foreach ($default_flags_info as $flag_info) {
2055
    $flag = flag_flag::factory_by_array($flag_info);
2056

    
2057
    // Disable flags that are not at the current API version.
2058
    if (!$flag->is_compatible()) {
2059
      $flag->status = FALSE;
2060
    }
2061

    
2062
    // Add flags that have been enabled.
2063
    if ((!isset($flag_status[$flag->name]) && (!isset($flag->status) || $flag->status)) || !empty($flag_status[$flag->name])) {
2064
      $flag->status = TRUE;
2065
      $default_flags[$flag->name] = $flag;
2066
    }
2067
    // Add flags that have been disabled.
2068
    elseif ($include_disabled) {
2069
      $flag->status = FALSE;
2070
      $default_flags[$flag->name] = $flag;
2071
    }
2072
  }
2073

    
2074
  return $default_flags;
2075
}
2076

    
2077
/**
2078
 * Get all flagged entities in a flag.
2079
 *
2080
 * @param $flag_name
2081
 *   The flag name for which to retrieve flagged entites.
2082
 *
2083
 * @return
2084
 *   An array of flagging data, keyed by the flagging ID.
2085
 */
2086
function flag_get_flag_flagging_data($flag_name) {
2087
  $flag = flag_get_flag($flag_name);
2088
  $result = db_select('flagging', 'fc')
2089
    ->fields('fc')
2090
    ->condition('fid', $flag->fid)
2091
    ->execute();
2092
  return $result->fetchAllAssoc('flagging_id');
2093
}
2094

    
2095
/**
2096
 * Find what a user has flagged, either a single entity or on the entire site.
2097
 *
2098
 * When called during a flagging or unflagging (such as from a hook
2099
 * implementation or from Rules), the flagging or unflagging that is in the
2100
 * process of being performed:
2101
 *  - will be included during a flagging operation
2102
 *  - will STILL be included during an unflagging operation. That is, the count
2103
 *    will not yet have been decreased.
2104
 * This is because this queries the {flagging} table, which only has its record
2105
 * deleted at the very end of the unflagging process.
2106
 *
2107
 * @param $entity_type
2108
 *   The type of entity that will be retrieved. Usually 'node'.
2109
 * @param $entity_id
2110
 *   (optional) The entity ID to check for flagging. If none given, all
2111
 *   entities flagged by this user will be returned.
2112
 * @param $uid
2113
 *   (optional) The user ID whose flags we're checking. If none given, the
2114
 *   current user will be used.
2115
 * @param $sid
2116
 *   (optional) The user SID (provided by Session API) whose flags we're
2117
 *   checking. If none given, the current user will be used. The SID is 0 for
2118
 *   logged in users.
2119
 *
2120
 * @return
2121
 *   If returning a single item's flags (that is, when $entity_id isn't NULL),
2122
 *   an array of the structure
2123
 *   [flag_name] => (
2124
 *     flagging_id => [flagging_id],
2125
 *     uid => [uid],
2126
 *     entity_id => [entity_id],
2127
 *     timestamp => [timestamp],
2128
 *     ...)
2129
 *
2130
 *   If returning all items' flags, an array of arrays for each flag:
2131
 *   [flag_name] => [entity_id] => Object from above.
2132
 */
2133
function flag_get_user_flags($entity_type, $entity_id = NULL, $uid = NULL, $sid = NULL) {
2134
  $flagged_content = &drupal_static(__FUNCTION__);
2135

    
2136
  $uid = !isset($uid) ? $GLOBALS['user']->uid : $uid;
2137
  $sid = !isset($sid) ? flag_get_sid($uid) : $sid;
2138

    
2139
  if (isset($entity_id)) {
2140
    if (!isset($flagged_content[$uid][$sid][$entity_type][$entity_id])) {
2141
      $flag_names = _flag_get_flag_names();
2142
      $flagged_content[$uid][$sid][$entity_type][$entity_id] = array();
2143
      $result = db_select('flagging', 'fc')
2144
        ->fields('fc')
2145
        ->condition('entity_type', $entity_type)
2146
        ->condition('entity_id', $entity_id)
2147
        ->condition(db_or()
2148
          ->condition('uid', $uid)
2149
          ->condition('uid', 0)
2150
        )
2151
        ->condition('sid', $sid)
2152
        ->execute();
2153

    
2154
      foreach ($result as $flagging_data) {
2155
        $flagged_content[$uid][$sid][$entity_type][$entity_id][$flag_names[$flagging_data->fid]] = $flagging_data;
2156
      }
2157
    }
2158
    return $flagged_content[$uid][$sid][$entity_type][$entity_id];
2159
  }
2160

    
2161
  else {
2162
    if (!isset($flagged_content[$uid][$sid][$entity_type]['all'])) {
2163
      $flag_names = _flag_get_flag_names();
2164
      $flagged_content[$uid][$sid][$entity_type]['all'] = array();
2165
      $result = db_select('flagging', 'fc')
2166
        ->fields('fc')
2167
        ->condition('entity_type', $entity_type)
2168
        ->condition(db_or()
2169
          ->condition('uid', $uid)
2170
          ->condition('uid', 0)
2171
        )
2172
        ->condition('sid', $sid)
2173
        ->execute();
2174
      foreach ($result as $flagging_data) {
2175
        $flagged_content[$uid][$sid][$entity_type]['all'][$flag_names[$flagging_data->fid]][$flagging_data->entity_id] = $flagging_data;
2176
      }
2177
    }
2178
    return $flagged_content[$uid][$sid][$entity_type]['all'];
2179
  }
2180

    
2181
}
2182

    
2183
/**
2184
 * Return a list of users who have flagged an entity.
2185
 *
2186
 * When called during a flagging or unflagging (such as from a hook
2187
 * implementation or from Rules), the flagging or unflagging that is in the
2188
 * process of being performed:
2189
 *  - will be included during a flagging operation
2190
 *  - will STILL be included during an unflagging operation. That is, the count
2191
 *    will not yet have been decreased.
2192
 * This is because this queries the {flagging} table, which only has its record
2193
 * deleted at the very end of the unflagging process.
2194
 *
2195
 * @param $entity_type
2196
 *   The type of entity that will be retrieved. Usually 'node'.
2197
 * @param $entity_id
2198
 *   The entity ID to check for flagging.
2199
 * @param $flag_name
2200
 *   (optional) The name of a flag if wanting a list specific to a single flag.
2201
 *
2202
 * @return
2203
 *   A nested array of flagging records (i.e. rows from the {flagging} table,
2204
 *   rather than complete Flagging entities). The structure depends on the
2205
 *   presence of the $flag_name parameter:
2206
 *    - if $flag_name is omitted, the array is keyed first by the user ID of
2207
 *      the users that flagged the entity, then by flag name. Each value is
2208
 *      then the flagging record.
2209
 *    - if $flag_name is given, the array is keyed only by user ID. Each value
2210
 *      is the flagging record.
2211
 *   If no flags were found an empty array is returned.
2212
 */
2213
function flag_get_entity_flags($entity_type, $entity_id, $flag_name = NULL) {
2214
  $entity_flags = &drupal_static(__FUNCTION__, array());
2215

    
2216
  if (!isset($entity_flags[$entity_type][$entity_id])) {
2217
    $flag_names = _flag_get_flag_names();
2218
    $result = db_select('flagging', 'fc')
2219
      ->fields('fc')
2220
      ->condition('entity_type', $entity_type)
2221
      ->condition('entity_id', $entity_id)
2222
      ->orderBy('timestamp', 'DESC')
2223
      ->execute();
2224
    $entity_flags[$entity_type][$entity_id] = array();
2225
    foreach ($result as $flagging_data) {
2226
      // Build a list of flaggings for all flags by user.
2227
      $entity_flags[$entity_type][$entity_id]['users'][$flagging_data->uid][$flag_names[$flagging_data->fid]] = $flagging_data;
2228
      // Build a list of flaggings for each individual flag.
2229
      $entity_flags[$entity_type][$entity_id]['flags'][$flag_names[$flagging_data->fid]][$flagging_data->uid] = $flagging_data;
2230
    }
2231
  }
2232
  if (empty($entity_flags[$entity_type][$entity_id])) {
2233
    return array();
2234
  }
2235
  if (isset($flag_name)) {
2236
    if (isset($entity_flags[$entity_type][$entity_id]['flags'][$flag_name])) {
2237
      return $entity_flags[$entity_type][$entity_id]['flags'][$flag_name];
2238
    }
2239
    return array();
2240
  }
2241
  return $entity_flags[$entity_type][$entity_id]['users'];
2242
}
2243

    
2244
/**
2245
 * A utility function for outputting a flag link.
2246
 *
2247
 * You should call this function from your template when you want to put the
2248
 * link on the page yourself. For example, you could call this function from
2249
 * your theme preprocessor for node.tpl.php:
2250
 * @code
2251
 * $variables['my_flag_link'] = flag_create_link('bookmarks', $node->nid);
2252
 * @endcode
2253
 *
2254
 * @param $flag_name
2255
 *   The "machine readable" name of the flag; e.g. 'bookmarks'.
2256
 * @param $entity_id
2257
 *   The entity ID to check for flagging, for example a node ID.
2258
 * @param $variables
2259
 *  An array of further variables to pass to theme('flag'). For the full list
2260
 *  of parameters, see flag.tpl.php. Of particular interest:
2261
 *  - after_flagging: Set to TRUE if this flag link is being displayed as the
2262
 *    result of a flagging action.
2263
 *  - errors: An array of error messages.
2264
 *
2265
 * @return
2266
 *   The HTML for the themed flag link.
2267
 */
2268
function flag_create_link($flag_name, $entity_id, $variables = array()) {
2269
  $flag = flag_get_flag($flag_name);
2270
  if (!$flag) {
2271
    // Flag does not exist.
2272
    return;
2273
  }
2274
  if (!$flag->access($entity_id) && (!$flag->is_flagged($entity_id) || !$flag->access($entity_id, 'flag'))) {
2275
    // User has no permission to use this flag.
2276
    return;
2277
  }
2278
  return $flag->theme($flag->is_flagged($entity_id) ? 'unflag' : 'flag', $entity_id, $variables);
2279
}
2280

    
2281
/**
2282
 * Trim a flag to a certain size.
2283
 *
2284
 * @param $fid
2285
 *   The flag object.
2286
 * @param $account
2287
 *   The user object on behalf the trimming will occur.
2288
 * @param $cutoff_size
2289
 *   The number of flaggings allowed. Any flaggings beyond that will be trimmed.
2290
 * @param $trim_newest
2291
 *   An optional boolean indicating whether to trim the newest flags.
2292
 * @param $permissions_check
2293
 *   (optional) A boolean indicating whether to skip permissions.
2294
 *   This will trim the flag if $permissions_check is TRUE even if the user
2295
 *   doesn't have the permission to flag/unflag.
2296
 */
2297
function flag_trim_flag($flag, $account, $cutoff_size, $trim_newest, $permissions_check = FALSE) {
2298
  $query = db_select('flagging', 'fc')
2299
    ->fields('fc')
2300
    ->condition('fid', $flag->fid)
2301
    ->condition(db_or()->condition('uid', $account->uid)->condition('uid', 0))
2302
    // Account for session ID (in the case of anonymous users).
2303
    ->condition('sid', flag_get_sid($account->uid));
2304
  // If $trim_newest is TRUE, then, we should order by 'ASC' as we should trim
2305
  // the newest flags.
2306
  if ($trim_newest) {
2307
    $query->orderBy('timestamp', 'ASC');
2308
  }
2309
  else {
2310
    $query->orderBy('timestamp', 'DESC');
2311
  }
2312

    
2313
  // Execute the query.
2314
  $result = $query->execute();
2315

    
2316
  $i = 1;
2317
  foreach ($result as $row) {
2318
    if ($i++ > $cutoff_size) {
2319
      flag('unflag', $flag->name, $row->entity_id, $account, $permissions_check);
2320
    }
2321
  }
2322
}
2323

    
2324
/**
2325
 * Remove all flagged entities from a flag.
2326
 *
2327
 * @param $flag
2328
 *   The flag object.
2329
 * @param $entity_id
2330
 *   (optional) The entity ID on which all flaggings will be removed. If left
2331
 *   empty, this will remove all of this flag's entities.
2332
 */
2333
function flag_reset_flag($flag, $entity_id = NULL) {
2334
  $query = db_select('flagging', 'fc')
2335
    ->fields('fc')
2336
    ->condition('fid', $flag->fid);
2337

    
2338
  if ($entity_id) {
2339
    $query->condition('entity_id', $entity_id);
2340
  }
2341

    
2342
  $result = $query->execute()->fetchAllAssoc('flagging_id', PDO::FETCH_ASSOC);
2343
  $rows = array();
2344
  foreach ($result as $row) {
2345
    $rows[] = $row;
2346
  }
2347
  module_invoke_all('flag_reset', $flag, $entity_id, $rows);
2348

    
2349
  $query = db_delete('flagging')->condition('fid', $flag->fid);
2350
  // Update the flag_counts table.
2351
  $count_query = db_delete('flag_counts')->condition('fid', $flag->fid);
2352
  if ($entity_id) {
2353
    $query->condition('entity_id', $entity_id);
2354
    $count_query->condition('entity_id', $entity_id);
2355
  }
2356
  $count_query->execute();
2357
  return $query->execute();
2358
}
2359

    
2360
/**
2361
 * Return an array of link types provided by modules.
2362
 *
2363
 * @return
2364
 *  An array of link types as defined by hook_flag_link_type_info(). These are
2365
 *  keyed by the type name, and each value is an array of properties. In
2366
 *  addition to those defined in hook_flag_link_type_info(), the following
2367
 *  properties are set:
2368
 *  - 'module': The providing module.
2369
 *  - 'name': The machine name of the type.
2370
 *
2371
 * @see hook_flag_link_type_info()
2372
 * @see hook_flag_link_type_info_alter()
2373
 */
2374
function flag_get_link_types() {
2375
  $link_types = &drupal_static(__FUNCTION__);
2376

    
2377
  if (!isset($link_types)) {
2378
    if ($cache = cache_get('flag_link_type_info')) {
2379
      $link_types = $cache->data;
2380
    }
2381
    // In some rare edge cases cache_get() can return an empty result. If it
2382
    // does, we make sure to fetch the link types again.
2383
    if (empty($link_types)) {
2384
      $link_types = array();
2385
      foreach (module_implements('flag_link_type_info') as $module) {
2386
        $module_types = module_invoke($module, 'flag_link_type_info');
2387
        foreach ($module_types as $type_name => $info) {
2388
          $link_types[$type_name] = $info + array(
2389
            'module' => $module,
2390
            'name' => $type_name,
2391
            'title' => '',
2392
            'description' => '',
2393
            'options' => array(),
2394
            'uses standard js' => TRUE,
2395
            'uses standard css' => TRUE,
2396
            'provides form' => FALSE,
2397
          );
2398
        }
2399
      }
2400
      drupal_alter('flag_link_type_info', $link_types);
2401

    
2402
      cache_set('flag_link_type_info', $link_types);
2403
    }
2404
  }
2405

    
2406
  return $link_types;
2407
}
2408

    
2409
/**
2410
 * Get a private token used to protect links from spoofing - CSRF.
2411
 */
2412
function flag_get_token($entity_id) {
2413
  // Anonymous users get a less secure token, since it must be the same for all
2414
  // anonymous users on the entire site to work with page caching.
2415
  return ($GLOBALS['user']->uid) ? drupal_get_token($entity_id) : md5(drupal_get_private_key() . $entity_id);
2416
}
2417

    
2418
/**
2419
 * Check to see if a token value matches the specified node.
2420
 */
2421
function flag_check_token($token, $entity_id) {
2422
  return flag_get_token($entity_id) == $token;
2423
}
2424

    
2425
/**
2426
 * Set the Session ID for a user. Utilizes the Session API module.
2427
 *
2428
 * Creates a Session ID for an anonymous user and returns it. It will always
2429
 * return 0 for registered users.
2430
 *
2431
 * @param int $uid
2432
 *   (optional) The user ID to create a session ID for. Defaults to the
2433
 *   current user.
2434
 * @param bool $create
2435
 *   (optional) Determines whether a session should be created if it doesn't
2436
 *   exist yet. Defaults to TRUE.
2437
 *
2438
 * @return
2439
 *   The session ID, if a session was created. If not, the return value is 0.
2440
 *
2441
 * @see flag_get_sid()
2442
 */
2443
function flag_set_sid($uid = NULL, $create = TRUE) {
2444
  $sids = &drupal_static(__FUNCTION__, array());
2445

    
2446
  if (!isset($uid)) {
2447
    $uid = $GLOBALS['user']->uid;
2448
  }
2449

    
2450
  // Set the sid if none has been set yet. If the caller specified to create an
2451
  // sid and we have an invalid one (-1), create it.
2452
  if (!isset($sids[$uid]) || ($sids[$uid] == -1 && $create)) {
2453
    if (module_exists('session_api') && session_api_available() && $uid == 0) {
2454
      // This returns one of the following:
2455
      // - -1. This indicates that no session exists and none was created.
2456
      // - A positive integer with the Session ID when it does exist.
2457
      $sids[$uid] = session_api_get_sid($create);
2458
    }
2459
    else {
2460
      $sids[$uid] = 0;
2461
    }
2462
  }
2463

    
2464
  // Keep the -1 case internal and let the outside world only distinguish two
2465
  // cases: (1) there is an SID; (2) there is no SID (-> 0).
2466
  return $sids[$uid] == -1 ? 0 : $sids[$uid];
2467
}
2468

    
2469
/**
2470
 * Get the Session ID for a user. Utilizes the Session API module.
2471
 *
2472
 * Gets the Session ID for an anonymous user. It will always return 0 for
2473
 * registered users.
2474
 *
2475
 * @param int $uid
2476
 *   (optional) The user ID to return the session ID for. Defaults to the
2477
 *   current user.
2478
 * @param bool $create
2479
 *   (optional) Determines whether a session should be created if it doesn't
2480
 *   exist yet. Defaults to FALSE.
2481
 *
2482
 * @return
2483
 *   The session ID, if the session exists. If not, the return value is 0.
2484
 *
2485
 * @see flag_set_sid()
2486
 */
2487
function flag_get_sid($uid = NULL, $create = FALSE) {
2488
  return flag_set_sid($uid, $create);
2489
}
2490

    
2491
// ---------------------------------------------------------------------------
2492
// Drupal Core operations
2493

    
2494
/**
2495
 * Implements hook_node_operations().
2496
 *
2497
 * Add additional options on the admin/build/node page.
2498
 */
2499
function flag_node_operations() {
2500
  global $user;
2501

    
2502
  $flags = flag_get_flags('node', NULL, $user);
2503
  $operations = array();
2504

    
2505
  foreach ($flags as $flag) {
2506
    $operations['flag_' . $flag->name] = array(
2507
      'label' => $flag->get_label('flag_short'),
2508
      'callback' => 'flag_nodes',
2509
      'callback arguments' => array('flag', $flag->name),
2510
      'behavior' => array(),
2511
    );
2512
    $operations['unflag_' . $flag->name] = array(
2513
      'label' => $flag->get_label('unflag_short'),
2514
      'callback' => 'flag_nodes',
2515
      'callback arguments' => array('unflag', $flag->name),
2516
      'behavior' => array(),
2517
    );
2518
  }
2519
  return $operations;
2520
}
2521

    
2522
/**
2523
 * Callback function for hook_node_operations().
2524
 */
2525
function flag_nodes($nodes, $action, $flag_name) {
2526
  $performed = FALSE;
2527
  foreach ($nodes as $nid) {
2528
    $performed |= flag($action, $flag_name, $nid);
2529
  }
2530
  if ($performed) {
2531
    drupal_set_message(t('The update has been performed.'));
2532
  }
2533
}
2534

    
2535
/**
2536
 * Implements hook_user_operations().
2537
 */
2538
function flag_user_operations() {
2539
  global $user;
2540

    
2541
  $flags = flag_get_flags('user', NULL, $user);
2542
  $operations = array();
2543

    
2544
  foreach ($flags as $flag) {
2545
    $operations['flag_' . $flag->name] = array(
2546
      'label' => $flag->get_label('flag_short'),
2547
      'callback' => 'flag_users',
2548
      'callback arguments' => array('flag', $flag->name),
2549
    );
2550
    $operations['unflag_' . $flag->name] = array(
2551
      'label' => $flag->get_label('unflag_short'),
2552
      'callback' => 'flag_users',
2553
      'callback arguments' => array('unflag', $flag->name),
2554
    );
2555
  }
2556
  return $operations;
2557
}
2558
/**
2559
 * Callback function for hook_user_operations().
2560
 */
2561
function flag_users($users, $action, $flag_name) {
2562
  foreach ($users as $uid) {
2563
    flag($action, $flag_name, $uid);
2564
  }
2565
}
2566

    
2567
// ---------------------------------------------------------------------------
2568
// Contrib integration hooks
2569

    
2570
/**
2571
 * Implements hook_views_api().
2572
 */
2573
function flag_views_api() {
2574
  return array(
2575
    'api' => 3.0,
2576
    'path' => drupal_get_path('module', 'flag') . '/includes/views',
2577
  );
2578
}
2579

    
2580
/**
2581
 * Implements hook_features_api().
2582
 */
2583
function flag_features_api() {
2584
  return array(
2585
    'flag' => array(
2586
      'name' => t('Flag'),
2587
      'feature_source' => TRUE,
2588
      'default_hook' => 'flag_default_flags',
2589
      'file' => drupal_get_path('module', 'flag') . '/includes/flag.features.inc',
2590
    ),
2591
  );
2592
}
2593

    
2594
/**
2595
 * Implements hook_ctools_plugin_directory().
2596
 */
2597
function flag_ctools_plugin_directory($module, $plugin) {
2598
  if ($module == 'ctools' && !empty($plugin)) {
2599
    return "plugins/$plugin";
2600
  }
2601
}
2602

    
2603
/**
2604
 * Implements hook_field_attach_rename_bundle().
2605
 */
2606
function flag_field_attach_rename_bundle($entity_type, $bundle_old, $bundle_new) {
2607
  $flags = flag_get_flags($entity_type);
2608
  foreach ($flags as $flag) {
2609
    foreach ($flag->types as $key => $type) {
2610
      if ($type == $bundle_old) {
2611
        $flag->types[$key] = $bundle_new;
2612
      }
2613
    }
2614
    $flag->save();
2615
  }
2616
}
2617

    
2618
// ---------------------------------------------------------------------------
2619
// Entity Metadata callbacks
2620

    
2621
/**
2622
 * Getter callback that returns whether the given entity is flagged.
2623
 */
2624
function flag_properties_get_flagging_boolean($entity, array $options, $name, $entity_type, $property_info) {
2625
  list($entity_id,) = entity_extract_ids($entity_type, $entity);
2626

    
2627
  $flagging_data = flag_get_user_flags($entity_type, $entity_id);
2628
  return isset($flagging_data[$property_info['flag_name']]);
2629
}
2630

    
2631
/**
2632
 * Getter callback that returns entities the given user flagged.
2633
 */
2634
function flag_properties_get_flagged_entities($entity, array $options, $name, $entity_type, $property_info) {
2635
  // Need the entity type the flag applies to.
2636
  $flag_entity_type = $property_info['flag_entity_type'];
2637

    
2638
  $flagging_data = flag_get_user_flags($flag_entity_type, NULL, $entity->uid);
2639

    
2640
  $flag_name = $property_info['flag_name'];
2641
  if (isset($flagging_data[$flag_name])) {
2642
    return array_keys($flagging_data[$flag_name]);
2643
  }
2644
  return array();
2645
}
2646

    
2647
/**
2648
 * Getter callback that returns users who flagged the given entity.
2649
 */
2650
function flag_properties_get_flagging_users($entity, array $options, $name, $entity_type, $property_info) {
2651
  list($entity_id,) = entity_extract_ids($entity_type, $entity);
2652

    
2653
  $flagging_data = flag_get_entity_flags($entity_type, $entity_id, $property_info['flag_name']);
2654

    
2655
  return array_keys($flagging_data);
2656
}
2657

    
2658
/**
2659
 * Getter callback that returns the SID of the user that is being retrieved.
2660
 *
2661
 * Callback for hook_entity_property_info_alter().
2662
 *
2663
 * @param stdobj $entity
2664
 *  The entity object representing a user for which we are getting inforamtion for.
2665
 *
2666
 * @param array $options
2667
 *  Options reguarding the nature of the entity. Language, etc.
2668
 *
2669
 * @param string $name
2670
 *  The name of the property we are running this callback for.
2671
 *
2672
 * @param string $entity_type
2673
 *  The type that the stdobj $entity is supposed to be.
2674
 *
2675
 * @param $property_info
2676
 *  The ifnromatin that represents the property we are providing a result for.
2677
 *
2678
 * @return an integer representing the user's sid field from the session_api table
2679
 *
2680
 * @ingroup callbacks
2681
 */
2682
function flag_properties_get_user_sid($entity, array $options, $name, $entity_type, $property_info) {
2683
  $sid = flag_get_sid($entity->uid, FALSE);
2684
  return $sid;
2685
}