<?xml version="1.0" encoding="ISO-8859-1"?>

<product productid="vb_accelerator" active="1">
	<title>vB Accelerator</title>
	<description>Optimise attachments processing</description>
	<version>0.9</version>
	<url><![CDATA[http://www.vbulletin.org/forum/misc.php?do=producthelp&pid=vb_accelerator]]></url>
	<versioncheckurl><![CDATA[http://www.vbulletin.org/forum/misc.php?do=productcheck&pid=vb_accelerator]]></versioncheckurl>
	<apm_releasedate>0</apm_releasedate>
	<apm_author />
	<apm_relatedurl />
	<apm_extrainfo />
	<apm_extraedit />
	<dependencies>
	</dependencies>
	<codes>
		<code version="0.7">
			<installcode><![CDATA[$db->hide_errors();
 $db->query_write("ALTER TABLE " . TABLE_PREFIX . "attachment ADD INDEX `vba_coverage` ( `attachmentid` , `filedataid` , `userid` ) ");
$db->show_errors();]]></installcode>
			<uninstallcode><![CDATA[$db->hide_errors();
$db->query_write("ALTER TABLE " . TABLE_PREFIX . "attachment DROP INDEX vba_coverage");
$db->show_errors();]]></uninstallcode>
		</code>
	</codes>
	<templates>
	</templates>
	<stylevardfns>
	</stylevardfns>
	<stylevars>
	</stylevars>
	<plugins>
		<plugin active="1" executionorder="5">
			<title>Accelerate fullsize attachments downloads</title>
			<hookname>attachment_display</hookname>
			<phpcode><![CDATA[if (    $vbulletin->options['vb_acc_nginx'])
{
  @fclose($fp);

  require_once(DIR . '/includes/functions_file.php');

  $attachuri = fetch_attachment_path(
        $attachmentinfo['uploader'],
        $attachmentinfo['filedataid'],
        (bool)$vbulletin->GPC['thumb'],
        $vbulletin->options['vb_acc_www_path_posts']
      );

  header('X-Accel-Redirect: ' . $attachuri);

  // update views counter
  if (    !$vbulletin->GPC['thumb']
      AND connection_status() == 0
      AND $lastbyte == ($attachmentinfo['filesize'] - 1))
  {
    if ($vbulletin->options['attachmentviewslive'])
    {
      // doing it as they happen; not using a DM to avoid overhead
      $db->query_write("
          UPDATE " . TABLE_PREFIX . "attachment SET
            counter = counter + 1
          WHERE attachmentid = $attachmentinfo[attachmentid]
        ");
    }
    else
    {
      // or doing it once an hour
      $db->query_write("
          INSERT INTO " . TABLE_PREFIX . "attachmentviews (attachmentid)
          VALUES ($attachmentinfo[attachmentid])
        ");
    }
  }

  exit;
}]]></phpcode>
		</plugin>
		<plugin active="1" executionorder="2">
			<title>Replace Thumbnails Links for HTML</title>
			<hookname>global_complete</hookname>
			<phpcode><![CDATA[// this hook must eval before VBSeo

if (!isset($cdn_list))
{
    $vbulletin->options['vb_acc_cdn_list'] = trim($vbulletin->options['vb_acc_cdn_list']);
    if (!empty($vbulletin->options['vb_acc_cdn_list']))
    {
        $cdn_list = explode("\n", $vbulletin->options['vb_acc_cdn_list']);
        $cdn_list = array_map('trim', $cdn_list);
        foreach ($cdn_list as $key=>$cdn)
        {
            if ('/' == $cdn[strlen($cdn)-1])
            {
                $cdn_list[$key] = substr($cdn, 0, -1);
            }
        }
    }
    else
    {
        $cdn_list[] = $vbulletin->options['bburl'];
    }
}


// Only procees if "attachment.php" exists in output html
if (strpos($output, 'attachment.php'))
{
    // get thumbnails list
    $pattern = '#src=\"((?:' . preg_quote($vbulletin->options['bburl'] . '/') . ')?' . 'attachment.php\?' . preg_quote("{$vbulletin->session->vars['sessionurl']}") . 'attachmentid=(\d+)[\w:\d&=;]*thumb=1[\w:\d&=;]*)\"#';
    preg_match_all($pattern, $output, $matches, PREG_SET_ORDER);

    $attachment_ids = array();
    $attachments = array();
    $transformed_attachments = array();
    foreach ($matches as $val) {
        list( , $url,$attachment_id) = $val;
        $attachment_ids[] = $attachment_id;
        $attachments[$attachment_id] = $url;
        $transformed_attachments[$attachment_id] = $url;
    }

    if (!empty($attachment_ids))
    {
        require_once(DIR . '/includes/functions_file.php');

        // todo maybe add index to "attachment" table?
        $sql = 'SELECT
                    a.attachmentid, a.filedataid, fd.userid as uploader
                FROM ' . TABLE_PREFIX . 'attachment AS a
                INNER JOIN ' . TABLE_PREFIX . 'filedata AS fd USING (filedataid)
                WHERE
                    a.attachmentid IN (' . implode(', ', $attachment_ids) . ')';

        $result = $vbulletin->db->query_read($sql);
        $position = 0;
        while ($row = $vbulletin->db->fetch_array($result))
        {
            $path = $cdn_list[$position] . $vbulletin->options['vb_acc_www_path_posts'];
            // extract timestamp 
            preg_match('#&amp;d=(\d+)#', $transformed_attachments[$row['attachmentid']], $timestamp);
            $transformed_attachments[$row['attachmentid']]= fetch_attachment_path(
                $row['uploader'],
                $row['filedataid'],
                true,
                $path
            ) . '?d='. $timestamp[1];
            $position = ++$position % count($cdn_list);
        }
    }
    // replace old thumb attachements links
    if (!empty($attachments))
    {
        $output = str_replace($attachments, $transformed_attachments, $output);
    }
}

// Only procees if "asset.php" exists in output html
if (strpos($output, 'asset.php'))
{
    require_once(DIR . '/includes/functions_file.php');

    // get thumbnails list
    $pattern = '#src=\"(asset.php\?' . preg_quote("{$vbulletin->session->vars['sessionurl']}") . 'fid=(\d+)&amp;uid=(\d+)&amp;d=(\d+))\"#';
    preg_match_all($pattern, $output, $matches, PREG_SET_ORDER);

    $attachment_ids = array();
    $attachments = array();
    $transformed_attachments = array();
    $position = 0;
    
    foreach ($matches as $val) {
        list( , $url,$attachment_fid,$attachment_uid,$attachment_timestamp) = $val;
        $attachments[$attachment_fid] = $url;
        $path = $cdn_list[$position] . $vbulletin->options['vb_acc_www_path_posts'];
        $transformed_attachments[$attachment_fid]= fetch_attachment_path(
                $attachment_uid,
                $attachment_fid,
                true,
                $path
        ) . '?d=' . $attachment_timestamp;
        $position = ++$position % count($cdn_list);
    }

    // replace thumb links
    if (!empty($attachments))
    {
        $output = str_replace($attachments, $transformed_attachments, $output);
    }
}]]></phpcode>
		</plugin>
		<plugin active="1" executionorder="2">
			<title>Replace Thumbnails Links for XML</title>
			<hookname>xml_print_output</hookname>
			<phpcode><![CDATA[// this hook must eval before VBSeo
global $vbulletin;

if (!isset($cdn_list))
{
    $vbulletin->options['vb_acc_cdn_list'] = trim($vbulletin->options['vb_acc_cdn_list']);
    if (!empty($vbulletin->options['vb_acc_cdn_list']))
    {
        $cdn_list = explode("\n", $vbulletin->options['vb_acc_cdn_list']);
        $cdn_list = array_map('trim', $cdn_list);
        foreach ($cdn_list as $key=>$cdn)
        {
            if ('/' == $cdn[strlen($cdn)-1])
            {
                $cdn_list[$key] = substr($cdn, 0, -1);
            }
        }
    }
    else
    {
        $cdn_list[] = $vbulletin->options['bburl'];
    }
}


// Only procees if "attachment.php" exists in output html
if (strpos($this->doc, 'attachment.php'))
{
    // get thumbnails list
    $pattern = '#src=\"((?:' . preg_quote($vbulletin->options['bburl'] . '/') . ')?' . 'attachment.php\?' . preg_quote("{$vbulletin->session->vars['sessionurl']}") . 'attachmentid=(\d+)[\w:\d&=;]*thumb=1[\w:\d&=;]*)\"#';
    preg_match_all($pattern, $this->doc, $matches, PREG_SET_ORDER);

    $attachment_ids = array();
    $attachments = array();
    $transformed_attachments = array();
    foreach ($matches as $val) {
        list( , $url,$attachment_id) = $val;
        $attachment_ids[] = $attachment_id;
        $attachments[$attachment_id] = $url;
        $transformed_attachments[$attachment_id] = $url;
    }

    if (!empty($attachment_ids))
    {
        require_once(DIR . '/includes/functions_file.php');

        // todo maybe add index to "attachment" table?
        $sql = 'SELECT
                    a.attachmentid, a.filedataid, fd.userid as uploader
                FROM ' . TABLE_PREFIX . 'attachment AS a
                INNER JOIN ' . TABLE_PREFIX . 'filedata AS fd USING (filedataid)
                WHERE
                    a.attachmentid IN (' . implode(', ', $attachment_ids) . ')';

        $result = $vbulletin->db->query_read($sql);
        $position = 0;
        while ($row = $vbulletin->db->fetch_array($result))
        {
            $path = $cdn_list[$position] . $vbulletin->options['vb_acc_www_path_posts'];
            // extract timestamp 
            preg_match('#&amp;d=(\d+)#', $transformed_attachments[$row['attachmentid']], $timestamp);
            $transformed_attachments[$row['attachmentid']]= fetch_attachment_path(
                $row['uploader'],
                $row['filedataid'],
                true,
                $path
            ) . '?d='. $timestamp[1];
            $position = ++$position % count($cdn_list);
        }
    }
    // replace old thumb attachements links
    if (!empty($attachments))
    {
        $this->doc = str_replace($attachments, $transformed_attachments, $this->doc);
    }
}

// Only procees if "asset.php" exists in output html
if (strpos($this->doc, 'asset.php'))
{
    require_once(DIR . '/includes/functions_file.php');

    // get thumbnails list
    $pattern = '#src=\"(asset.php\?' . preg_quote("{$vbulletin->session->vars['sessionurl']}") . 'fid=(\d+)&amp;uid=(\d+)&amp;d=(\d+))\"#';
    preg_match_all($pattern, $this->doc, $matches, PREG_SET_ORDER);

    $attachment_ids = array();
    $attachments = array();
    $transformed_attachments = array();
    $position = 0;
    
    foreach ($matches as $val) {
        list( , $url,$attachment_fid,$attachment_uid,$attachment_timestamp) = $val;
        $attachments[$attachment_fid] = $url;
        $path = $cdn_list[$position] . $vbulletin->options['vb_acc_www_path_posts'];
        $transformed_attachments[$attachment_fid]= fetch_attachment_path(
                $attachment_uid,
                $attachment_fid,
                true,
                $path
        ) . '?d=' . $attachment_timestamp;
        $position = ++$position % count($cdn_list);
    }

    // replace thumb links
    if (!empty($attachments))
    {
        $this->doc = str_replace($attachments, $transformed_attachments, $this->doc);
    }
}]]></phpcode>
		</plugin>
	</plugins>
	<phrases>
		<phrasetype name="vBulletin Settings" fieldname="vbsettings">
			<phrase name="setting_vb_acc_cdn_list_desc" date="1276075558" username="Vitaly" version="0.6"><![CDATA[Enter up to 4 mirror domains, to load local images faster. For example:<br>
<br>
http://img1.myforum.com<br>
http://img2.myforum.com<br>
http://img3.myforum.com<br>
http://img4.myforum.com<br>
<br>
If don't use mirrors - leave this field blank or set to forum domain.]]></phrase>
			<phrase name="setting_vb_acc_cdn_list_title" date="1276075558" username="Vitaly" version="0.6"><![CDATA[CDN list]]></phrase>
			<phrase name="setting_vb_acc_nginx_desc" date="1236190598" username="Vitaly" version="0.2"><![CDATA[ONLY set yes, if you have NGINX websever!!!<br /> <br /> Other webservers don't catch X-Accel-Redirect headers!!!]]></phrase>
			<phrase name="setting_vb_acc_nginx_title" date="1236190598" username="Vitaly" version="0.2"><![CDATA[Enable large downloads acceleration]]></phrase>
			<phrase name="setting_vb_acc_www_path_posts_desc" date="1275476288" username="varnak" version="0.4"><![CDATA[Relative web-server URI to attachments directory. No trailing slash allowed.]]></phrase>
			<phrase name="setting_vb_acc_www_path_posts_title" date="1275476288" username="varnak" version="0.4"><![CDATA[Path to attachments]]></phrase>
			<phrase name="settinggroup_vb_accelerator" date="1236189322" username="Dimit" version="0.2"><![CDATA[vB Accelerator]]></phrase>
		</phrasetype>
	</phrases>
	<options>
		<settinggroup name="vb_accelerator" displayorder="65535">
			<setting varname="vb_acc_www_path_posts" displayorder="10">
				<datatype>free</datatype>
				<defaultvalue>/uploads</defaultvalue>
			</setting>
			<setting varname="vb_acc_cdn_list" displayorder="20">
				<datatype>free</datatype>
				<optioncode>textarea</optioncode>
			</setting>
			<setting varname="vb_acc_nginx" displayorder="30">
				<datatype>boolean</datatype>
				<optioncode>yesno</optioncode>
				<defaultvalue>0</defaultvalue>
			</setting>
		</settinggroup>
	</options>
	<helptopics>
	</helptopics>
	<cronentries>
	</cronentries>
	<faqentries>
	</faqentries>
	<templateedits>
	</templateedits>
</product>