The Flag API (PHP)

Last modified: November 16, 2009 - 01:46

[This page contains some random notes. When more material is gathered, it will be revised.]

Contents:

First and foremost

Flag provides some API functions. At some point we switched to use object oriented programming (OOP). Some functions don't have equivalent methods (yet?).

To work with a flag you first need to get your hands on a "flag handler":

$flag = flag_get_flag('bookmarks');

The parameter to flag_get_flag() is the machine-name of the flag. If no such flag exists, NULL will be returned.

Discovering whether a piece of content is flagged

Use the is_flagged() method to find out if an item is flagged.

This can be very useful in 'node.tpl.php', when you want to theme flagged nodes differently than non-flagged ones.

Examples:

$flag = flag_get_flag('bookmarks') or die('no "bookmarks" flag defined');

if ($flag->is_flagged($node->nid)) {
  print "This node is bookmarked!";
}


$flag = flag_get_flag('idiots') or die('no "idiots" flag defined');

if ($flag->is_flagged($node->uid)) {
  print "The author of this node isn't very smart!";
}


$flag = flag_get_flag('idols') or die('no "idols" flag defined');

if ($flag->is_flagged($GLOBAL['user']->uid, $node->uid)) {
  print "This author venerates you!";
}

// flag::is_flagged() uses a caching mechanism so it's efficient.

The examples above makes PHP die() if the flag doesn't exist. A different style is to add $flag && to the conditional:

$flag = flag_get_flag('bookmarks');

if ($flag && $flag->is_flagged($node->nid)) {
  print "This node is bookmarked!";
}

You use flag_create_link() for this. See the separate page, Placing a flag link on a page.

Getting the number of times an item is flagged

Whenever an item is flagged, or unflagged, a counter field is updated. To read this counter, use the get_count() method:

$flag = flag_get_flag('votes') or die('no "votes" flag');

print "The number of people who voted for this proposal:";
print $flag->get_count($node->nid);

A different approach is to use tokens. This module provides a count token for each flag, and you can use it in email messages, for example, and in every place that accepts tokens:

Hello, [node-author].
Your post has been bookmarked [flag-bookmarks-count] times.

A different method, get_user_count(), is used for counting the items a user has flagged. This method is less efficient than get_count() because an SQL COUNT query is issued.

$flag = flag_get_flag('votes') or die('no "votes" flag');

// We assume an $account variable exists in this template.

print format_plural($flag->get_user_count($account->uid),
    'This user has participated in 1 voting.',
    'This user has participated in @count votings.');

Flagging, or unflagging, an item

You use the $flag->flag() method to either flag or unflag an item. Example:

$flag = flag_get_flag('bookmarks') or die('no "bookmarks" flag defined');

// Flag node #456:
$flag->flag('flag', 456);

// Unflag node #456:
$flag->flag('unflag', 456);

The signature of this $this->flag() method is:

function flag($action, $content_id, $account = NULL, $skip_permission_check = FALSE)

A complete and up-to-date documentation of it is in the Doxygen (link missing/unavailable?). But, in short: $action is the action you want to carry out; either 'flag' or 'unflag'. $content_id is the identifier of the item. $account is the user on whose behalf you want to carry out the action (This parameter is only meaningful when using a non-global flag).

This method returns FALSE if some error occured (e.g., the user has no permission to use this flag; flag isn't applicable to the item; etc.). Note that it isn't an error to flag an item that is already flagged (in this case the method will do nothing, but it will not return FALSE).

Responding to a flagging

Any module may react to a piece of content being flagged by implementing hook_flag().

<?php
mymodule_flag
($action, $flag, $content_id, $account) {
  if (
$action == 'flag') { // Or $action == 'unflag'.
    // Do something in response to the flagging.
 
}
}
?>

Flag module actually implements it's own hook in the flag_flag() function in flag.module. You might use it for reference when creating your own version.

Creating a Flag in the Database

To create a node flag in the database, create a flag from the flag_flag class, modify the defaults, then save with the $flag->save() method. Note that you can also create

  $flag = flag_flag::factory_by_content_type('node');

  // Absolutely required, will break your site if not added properties.
  $flag->name = 'my_flag_name';
  $flag->title = 'My Title';

  // Properties required by the UI.
  $flag->roles = array(2); // An array of role IDs. 2 is for "authenticated users".
  $flag->types = array('story', 'page'); // An array of node types.
  $flag->flag_short = 'Flag this';
  $flag->unflag_short = 'Unflag this';

  // Optional properties, defaults are defined for these (and more).
  // Use a print_r() or dsm() to see all the available flag properties.
  $flag->global = TRUE;
  $flag->flag_long = '';
  $flag->flag_message = '';
  $flag->show_on_form = TRUE;
  $flag->show_on_node = TRUE;
  $flag->show_on_teaser = TRUE;
  $flag->link_type = 'toggle'; // For JS link. Other options: 'normal' and 'confirm'.

  // Save the flag.
  $flag->save();

Creating a Module-Based Default Flag

Flags can be included in modules by implementing hook_flag_default_flags(). By defining a flag in code, the developer can "lock" certain properties of a flag and ensure that a flag is available for the module to use. Any "locked" properties will not be shown on the flag configuration form.

<?php
function mymodule_flag_default_flags() {
 
$flags = array();
 
$flags[] = array(
   
'content_type' => 'node',
   
'name' => 'starred',
   
'title' => 'Starred',
   
'roles' => array('2'),
   
'global' => FALSE,
   
'types' => array('story', 'blog'),
   
'flag_short' => 'Star',
   
'flag_long' => 'Add this your starred list',
   
'flag_message' => 'Added to your starred list.',
   
'unflag_short' => 'Unstar',
   
'unflag_long' => 'Remove this issue from your starred list',
   
'unflag_message' => 'Removed from your starred list.',
   
'show_on_page' => TRUE,
   
'show_on_teaser' => TRUE,
   
'show_on_form' => FALSE,
   
'status' => FALSE,
   
'locked' => array('show_on_teaser', 'name', 'types', 'roles', 'global'),
  );
  return
$flags;
}
?>

Im trying to make this code

vertazzar - October 28, 2009 - 13:49

Im trying to make this code work...

<?php
function popups_admin_flag($action, $flag, $content_id, $account) {
 
//Example values.
 
$points = 10;
 
$my_flag_name = 'aplauz';

 
//Pseudo-code.
 
if (module_exists('userpoints')) {
    if (
$flag->name == $my_flag_name) {
     
//If unflagging, remove userpoints.
     
if ($flag_status == 'unflag') {
       
$points = -$points;
      }
        if (
$flag_status == 'flag') {
       
$points = $points;
      }
      if (
$flag_type == 'comment') {
       
$comment = comment_load(array('cid' => $flagged_item_id));
       
$uid = $comment->uid;
       
$account = user_load(array('uid' => $uid));
      }
      else if (
$flag_type == 'user') {
       
$account = user_load(array('uid' => $flagged_item_id));
       
$uid = $node->uid;
      }
      else {
        return;
      }
     
userpoints_userpointsapi('points', $points, $uid, 'flag-'. $flag->name) ;
     
drupal_set_message(check_plain($account->name) .' was awarded '. $points .' points thanks to your '. $my_flag_name .'.');
    }
  }
}

?>

what im doing wrong ?

edit:
nvm issue fixed.

 
 

Drupal is a registered trademark of Dries Buytaert.