You are here

function twitter_post_nodeapi in Twitter 6.5

Implementation of hook_nodeapi().

Intercepts newly published nodes and posts noticed to Twitter.

File

twitter_post/twitter_post.module, line 122
Hook implementations for twitter_post module.

Code

function twitter_post_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  switch ($op) {
    case 'insert':
    case 'update':
      if (!empty($node->status) && !empty($node->twitter) && !empty($node->twitter['post'])) {
        module_load_include('inc', 'twitter');
        $twitter_account = twitter_account_load($node->twitter['account']);
        global $user;
        $account = user_load($user->uid);
        $access_global = user_access('post to twitter with global account', $account);

        // Only allow the tweet to be posted if the Twitter account is either
        // a global account and the user has access to global accounts, or it
        // is tied to the current user.
        if (!($twitter_account->is_global && $access_global || $twitter_account->uid == $account->uid)) {
          return;
        }

        // Prepare the string replacements for the status message.
        $replacements = array(
          // 117 characters is the maximum that can be added to a tweet and
          // still have a URL, so don't allow the title to be longer than that.
          '!title' => truncate_utf8($node->title, 117, FALSE, TRUE),
          '!url' => url('node/' . $node->nid, array(
            'absolute' => TRUE,
            'alias' => TRUE,
          )),
          '!url-alias' => url('node/' . $node->nid, array(
            'absolute' => TRUE,
          )),
          '!user' => $node->name,
        );

        // Only generate the shortened URL if it's going to be used. No sense
        // burning through TinyURLs without a good reason.
        if (strstr($node->twitter['status'], '!tinyurl') !== FALSE) {
          $replacements['!tinyurl'] = twitter_shorten_url(url('node/' . $node->nid, array(
            'absolute' => TRUE,
          )));
        }
        $status = strtr($node->twitter['status'], $replacements);

        // If token module is available, process status to do the token replacement
        if (module_exists('token')) {
          $status = token_replace($status, 'node', $node);
        }
        if (twitter_set_status($twitter_account, $status)) {
          drupal_set_message(t('Successfully posted "%node" to Twitter: <a href="@status" target="_blank">@status</a>', array(
            '@status' => _twitter_status_url($status),
            '%node' => $node->title,
          )));
        }
        else {
          drupal_set_message(t('Could not post to Twitter. Please check the site reports.'));
        }

        // Return something useful for module_invoke().
        return $status;
      }
      break;
  }
}