You are here

function flag_user_login in Flag 7.3

Same name and namespace in other branches
  1. 7.2 flag.module \flag_user_login()

Implements hook_user_login().

File

./flag.module, line 1128
The Flag module.

Code

function flag_user_login(&$edit, &$account) {

  // Migrate anonymous flags to this user's account.
  if (module_exists('session_api') && ($sid = flag_get_sid(0))) {

    // Get a list of flagging IDs that will be moved over.
    $duplicate_flaggings = array();
    $flaggings = db_select('flagging', 'fc')
      ->fields('fc', array(
      'flagging_id',
      'fid',
      'entity_id',
    ))
      ->condition('uid', 0)
      ->condition('sid', $sid)
      ->execute()
      ->fetchAllAssoc('flagging_id', PDO::FETCH_ASSOC);

    // Convert anonymous flaggings to their authenticated account.
    foreach ($flaggings as $flagging_id => $flagging) {

      // Each update is wrapped in a try block to prevent unique key errors.
      // Any duplicate object that was flagged as anonoymous is deleted in the
      // subsequent db_delete() call.
      try {
        db_update('flagging')
          ->fields(array(
          'uid' => $account->uid,
          'sid' => 0,
        ))
          ->condition('flagging_id', $flagging_id)
          ->execute();
      } catch (Exception $e) {
        $duplicate_flaggings[$flagging_id] = $flagging;
      }
    }

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

    // Clean up anonymous cookies.
    FlagCookieStorage::drop();
  }
}