You are here

function ad_embed_replace in Advertisement 7

Same name and namespace in other branches
  1. 5.2 embed/ad_embed.module \ad_embed_replace()
  2. 5 embed/ad_embed.module \ad_embed_replace()
  3. 6.3 embed/ad_embed.module \ad_embed_replace()
  4. 6 embed/ad_embed.module \ad_embed_replace()
  5. 6.2 embed/ad_embed.module \ad_embed_replace()

Replaces [[ad]] and <!--ad--> style tags with JavaScript for displaying ads.

1 call to ad_embed_replace()
ad_embed_nodeapi in embed/ad_embed.module
Implementation of hook_nodeapi().

File

embed/ad_embed.module, line 223
Embed ads in content.

Code

function ad_embed_replace($text) {
  $tags = array(
    '[[ad' => ']]',
    '<!--ad' => '-->',
  );
  if (!$text) {
    return;
  }
  foreach ($tags as $open => $close) {
    if ($open == '[[ad' && !variable_get('ad_embed_replace_brackets', 1)) {
      continue;
    }
    if ($open == '<!--ad' && !variable_get('ad_embed_replace_comments', 1)) {
      continue;
    }
    if (strlen($open) > strlen($text)) {
      continue;
    }
    $pos = 0;
    while ($pos !== FALSE) {

      // Locate the first open embed tag.
      $pos = strpos($text, $open, $pos);
      if ($pos !== FALSE) {
        $start = $pos + strlen($open);

        // Locate the matching close embed tag.
        $pos = strpos($text, $close, $start);
        if ($pos) {

          // Extract the contents within the tags.
          $contents = substr($text, $start, $pos - $start);

          // Parse the options within the contents.
          $options = implode('&', explode('|', $contents));
          parse_str($options, $args);

          // Set defaults
          $quantity = 1;
          $options = array();
          $group = '';
          foreach ($args as $key => $value) {
            switch ($key) {
              case 'quantity':

                // Must be at least 1
                $quantity = (int) $value ? (int) $value : 1;
                break;
              case 'group':
                $group = $value;
                break;
              case 'hostid':
                $options['hostid'] = $value;
                break;
              case 'nids':
                $options['nids'] = $value;
                break;
            }
          }
          $replace = $open . $contents . $close;
          $ad = ad($group, $quantity, $options);
          $text = str_replace($replace, $ad, $text);

          // Adjust position to compensate for difference in length of what
          // we are replacing and length of what we are replacing it with.
          if (strlen($replace) > strlen($ad)) {
            $pos -= strlen($replace) - strlen($ad) - 1;
          }
          else {
            if (strlen($replace) < strlen($ad)) {
              $pos += strlen($ad) - strlen($replace) + 1;
            }
          }
        }
      }
    }
  }
  return $text;
}