You are here

function _twitter_filter_embed_tweet in Twitter 7.6

Same name and namespace in other branches
  1. 6.5 twitter.module \_twitter_filter_embed_tweet()
  2. 7.5 twitter.module \_twitter_filter_embed_tweet()

Callback for Embedded Tweets.

1 string reference to '_twitter_filter_embed_tweet'
twitter_filter_info in ./twitter.module
Implements hook_filter_info()

File

./twitter.module, line 495
Provides API integration with the Twitter microblogging service.

Code

function _twitter_filter_embed_tweet($text, $filter) {
  module_load_include('inc', 'twitter');

  // Tags to skip and not recurse into.
  $ignore_tags = 'a|script|style|code|pre';

  // Split at all tags; ensures that no tags or attributes are processed.
  $chunks = preg_split('/(<.+?>)/is', $text, -1, PREG_SPLIT_DELIM_CAPTURE);

  // PHP ensures that the array consists of alternating delimiters and
  // literals, and begins and ends with a literal (inserting NULL as required).
  // Therefore, the first chunk is always text:
  $chunk_type = 'text';

  // If a tag of $ignore_tags is found, it is stored in $open_tag and only
  // removed when the closing tag is found. Until the closing tag is found, no
  // replacements are made.
  $open_tag = '';

  // Loop through all of the text chunks.
  foreach ($chunks as $i => $chunk) {
    if ($chunk_type == 'text') {

      // Only process this text if there are no unclosed $ignore_tags.
      if ($open_tag == '') {

        // Check for links to Tweets to replace with embed code.
        $tweets = array();
        preg_match_all('/https?:\\/\\/(www\\.)?twitter.com\\/.+?\\/status(es)?\\/(.*)/i', $chunks[$i], $tweets, PREG_SET_ORDER);
        foreach ($tweets as $tweet) {
          $url = $tweet[0];
          $id = $tweet[3];
          $embed = twitter_statuses_oembed($id);
          $chunks[$i] = str_replace($url, $embed['html'], $chunks[$i]);
        }
      }

      // Text chunk is done, so next chunk must be a tag.
      $chunk_type = 'tag';
    }
    else {

      // Only process this tag if there are no unclosed $ignore_tags.
      if ($open_tag == '') {

        // Check whether this tag is contained in $ignore_tags.
        if (preg_match("`<({$ignore_tags})(?:\\s|>)`i", $chunks[$i], $matches)) {
          $open_tag = $matches[1];
        }
      }
      else {
        if (preg_match("`<\\/{$open_tag}>`i", $chunks[$i], $matches)) {
          $open_tag = '';
        }
      }

      // Tag chunk is done, so next chunk must be text.
      $chunk_type = 'text';
    }
  }
  return implode($chunks);
}