Перейти к контенту

Кто скачивал вложения (D-View who downloaded attachments) мод


dimitry

Рекомендуемые сообщения

На ранее существовавшем сайте invisionize.com был такой мод, как D-View who downloaded attachments версии 1.0, который
позволял в посте, к которому был прикреплен файл видеть статистику того, кто и когда скачивал вложения из поста.
С наступлением страших версий PHP 5.x работа мода начала хандрить: при просмотре popup окна статистики выдавало белый экран. Пришлось делать правки в файл attach.php.
Оригинальный файл дистрибутива IPB 1.3 выглядел так:
attach orig.php
В архиве с модом шел уже правленный файл attach.php, которым предлагалось заменить оригинальный. Правленный выглядел так:
attach_from_mod.php
И тот и другой с PHP 5.6 имеют конфликты:
1)
участок:

@header( "Content-Type: ".$post['attach_type']."\nContent-Disposition: inline; filename=\"".$post['attach_file']."\"\nContent-Length: ".(string)(filesize( $file ) ) );

нужно переделывать, как:

@header("Content-Type: ".$post['attach_type']);
@header("Content-Disposition: inline; filename=\"".$post['attach_file']."\"");
@header("Content-Length: ".(string)(filesize($file) ) ); 

(Song)
2)
это

$DB->query("SELECT pid, attach_id, attach_type, attach_file FROM ibf_posts WHERE pid='".$ibforums->input['id']."'");
            
            if ( !$DB->get_num_rows() )
            {
                $std->Error( array( 'LEVEL' => 1, 'MSG' => 'missing_files' ) );
            }
            
            $post = $DB->fetch_row();
            
            if ( $post['attach_id'] == "" )
            {
                $std->Error( array( 'LEVEL' => 1, 'MSG' => 'missing_files' ) );
            }
            
            $file = $ibforums->vars['upload_dir']."/".$post['attach_id'];
            
            if ( file_exists( $file ) and ( $post['attach_type'] != "" ) )
            {
                // Update the "hits"..
                
                $DB->query("UPDATE ibf_posts SET attach_hits=attach_hits+1 WHERE pid='".$post['pid']."'");
                
                $ga = $DB->query("SELECT * FROM ibf_attachmentdls WHERE aid='{$post['pid']}' AND mid='{$ibforums->input['mid']}'");
            if ($DB->get_num_rows($ga) <= 0)
            {
                $DB->query("INSERT INTO ibf_attachmentdls (aid, mid) VALUES ('{$post['pid']}', '{$ibforums->input['mid']}')");
            }


заменено на это:

$DB->simple_construct( array( 'select' => '*', 'from' => 'attachments', 'where' => "attach_id=".$ibforums->input['id'] ) );
            $DB->simple_exec();
            
            if ( !$DB->get_num_rows() )
            {
                $std->Error( array( 'LEVEL' => 1, 'MSG' => 'missing_files' ) );
            }
            
            $post = $DB->fetch_row();
            
            if ( $post['attach_id'] == "" )
            {
                $std->Error( array( 'LEVEL' => 1, 'MSG' => 'missing_files' ) );
            }
            
                                    $file = $ibforums->vars['upload_dir']."/".$post['attach_location'];
            
            if ( file_exists( $file ) and ( $ibforums->cache['attachtypes'][ $post['attach_ext'] ]['atype_mimetype'] != "" ) )

            {
                // Update the "hits"..
                
                            $DB->simple_construct( array( 'update' => 'attachments', 'set' =>"attach_hits=attach_hits+1", 'where' => "attach_id=".$ibforums->input['id'] ) );
            $DB->simple_exec();
                $ga = $DB->query("SELECT * FROM ibf_attachmentdls WHERE aid='{$post['pid']}' AND mid='{$ibforums->input['mid']}'");
            if ($DB->get_num_rows($ga) <= 0)
            {
                $DB->query("INSERT INTO ibf_attachmentdls (aid, mid) VALUES ('{$post['pid']}', '{$ibforums->input['mid']}')");
            }


иначе, если этого не сделать, то при клике мышью на скачиваемый файл будет выдаваться ошибка IPB, что ссылка битая и пр., в результате код attach.php выглядит так:
attach_my.php
skin_topic.php у меня выглядит так:
см. вложение skin_topic.php

Ошибка, которую мне никак не удается исправить:

При скачивании файлов файл нормально, небито скачивается окном сохранения в браузере, счетчик скачиваний нормально считает количество скачиваний, НО при открытии popup окна статистики, кто скачивал все время пишет:

нет пользователей, скачавших это вложение

Посмотрел БД:

CREATE TABLE `ibf_attachmentdls` (
aid int( 11 ) NOT NULL default '0',
mid int( 11 ) NOT NULL default '0'
);

все есть с правильными установками.
Такое ощущение, что в файле attach.php
вот в этом верхнем месте:

$idx = new attach;

class attach {

    
    function attach()
    {
        global $ibforums, $DB, $std, $print, $skin_universal;

	$ibforums->lang = $std->load_words($ibforums->lang, 'lang_topic', $ibforums->lang_id);
	$this->html = $std->load_template('skin_topic');

	$ibforums->input['id'] = preg_replace( "/^(\d+)$/", "\\1", $ibforums->input['id'] );

	if ($ibforums->input['id'] == "")
	{
		$std->Error( array( 'LEVEL' => 1, 'MSG' => 'missing_files' ) );
	}

	if ($ibforums->input['type'] == 'view')
        {
        	$a = $DB->query("SELECT a.*, m.*, g.*
				 FROM ibf_attachmentdls a
				 LEFT JOIN ibf_members m ON (a.mid=m.id)
				 LEFT JOIN ibf_groups g ON (m.mgroup=g.g_id)
				 WHERE a.aid='{$ibforums->input['id']}'");
        	
        	if ($DB->get_num_rows($a) <= 0)
        	{
        		$adls = "{$ibforums->lang['no_atc_dls']}";
        	}
        	else
		{
			while ($attach = $DB->fetch_row($a))
			{
				$adls .= "<a href='javascript:' onclick=\"opener.window.location='index.php?showuser={$attach['mid']}'\">{$attach['prefix']}{$attach['name']}{$attach['suffix']}</a><br>\n";
			}
		}

		$print->pop_up_window("{$ibforums->lang['attach_dls']}", $this->html->attachment_downloaders($adls));
	}

есть что-то в коде, что не дает данные в БД и статистика скачавших все время нулевая...
Еще, что мне не нравится, так это то, что в attach.php указано:

$adls

, а в skin_topic.php в функции attachment_downloaders это уже идет, как:

function attachment_downloaders($dls) {
global $ibforums;
return <<<EOF
<div align='center' class='tableborder'>
<table align='center' width="100%" cellpadding="3" cellspacing="0">
  <tr>
    <td width="100%">
      {$dls}
    </td>
  </tr>
</table>
</div>
EOF;
}

D-View who downloaded attachments 1.0.zip

Изменено пользователем dimitry
Ссылка на комментарий
Поделиться на других сайтах

Решил проблему:
 
Решение:

skin_topic.php

В функции function Show_attachments должно быть:
 
 

function Show_attachments($data="") {
global $ibforums;
$IPBHTML = "";
//--starthtml--//


$IPBHTML .= <<<EOF
<a href="{$ibforums->base_url}act=Attach&type={$data['method']}&id={$data['id']}&mid={$ibforums->member['id']}" title="{$ibforums->lang['attach_dl']}" target="_blank"><img src="{$ibforums->vars['mime_img']}/{$data['image']}" alt="{$ibforums->lang['attached_file']}" /></a>
 <a href="{$ibforums->base_url}act=Attach&type={$data['method']}&id={$data['id']}&mid={$ibforums->member['id']}" title="{$ibforums->lang['attach_dl']}" target="_blank">{$data['name']}</a> ( {$data['size']} )
<span class="desc">{$ibforums->lang['attach_hits']}: {$data['hits']}</span> (<a href='javascript:' onclick="window.open('index.php?act=Attach&type=view&id={$data['id']}', 'Downloaders', 'width=150,height=200,resizable=no,location=no,directories=no,status=no,menubar=no,toolbar=no')">{$ibforums->lang['view_who_dled']}</a>)</span>
EOF;

//--endhtml--//
return $IPBHTML;
}

 

Т.е.
 
 

<a href="{$ibforums->base_url}act=Attach&type={$data['method']}&id={$data['id']}"

 


дважды заменить на:
 
 

<a href="{$ibforums->base_url}act=Attach&type={$data['method']}&id={$data['id']}&mid={$ibforums->member['id']}"

 


в
 
 

</span> (<a href='javascript:' onclick="window.open('index.php?act=Attach&type=view&id={$data['pid']}', 'Downloaders', 'width=150,height=200,resizable=no,location=no,directories=no,status=no,menubar=no,toolbar=no')">{$ibforums->lang['view_who_dled']}</a>)</span>

 
 
 

{$data['pid']}

 
 заменить на
 

{$data['id']}

 


attach.php

Найти:
 
 

// Update the "hits"..
                
                            $DB->simple_construct( array( 'update' => 'attachments', 'set' =>"attach_hits=attach_hits+1", 'where' => "attach_id=".$ibforums->input['id'] ) );
            $DB->simple_exec();
                $ga = $DB->query("SELECT * FROM ibf_attachmentdls WHERE aid='{$post['pid']}' AND mid='{$ibforums->input['mid']}'");
            if ($DB->get_num_rows($ga) <= 0)
            {
                $DB->query("INSERT INTO ibf_attachmentdls (aid, mid) VALUES ('{$post['pid']}', '{$ibforums->input['mid']}')");
            }

 

Заменить на:
 
 

// Update the "hits"..
                
                            $DB->simple_construct( array( 'update' => 'attachments', 'set' =>"attach_hits=attach_hits+1", 'where' => "attach_id=".$ibforums->input['id'] ) );
            $DB->simple_exec();
                $ga = $DB->query("SELECT * FROM ibf_attachmentdls WHERE aid='{$post['attach_id']}' AND mid='{$ibforums->input['mid']}'");
            if ($DB->get_num_rows($ga) <= 0)
            {
                $DB->query("INSERT INTO ibf_attachmentdls (aid, mid) VALUES ('{$post['attach_id']}', '{$ibforums->input['mid']}')");
            }

 


т.е.
 
 

{$post['pid']}

 
 заменено на
 

{$post['attach_id']}
Изменено пользователем dimitry
Ссылка на комментарий
Поделиться на других сайтах

Присоединиться к обсуждению

Вы можете ответить сейчас, а зарегистрироваться позже. Если у вас уже есть аккаунт, войдите, чтобы ответить от своего имени.

Гость
Unfortunately, your content contains terms that we do not allow. Please edit your content to remove the highlighted words below.
Ответить в этой теме...

×   Вы вставили отформатированный текст.   Удалить форматирование

  Допустимо не более 75 смайлов.

×   Ваша ссылка была автоматически заменена на медиа-контент.   Отображать как ссылку

×   Ваши публикации восстановлены.   Очистить редактор

×   Вы не можете вставить изображения напрямую. Загрузите или вставьте изображения по ссылке.

Зарузка...
×
×
  • Создать...

Важная информация

Находясь на нашем сайте, вы соглашаетесь на использование файлов cookie, а также с нашим положением о конфиденциальности Политика конфиденциальности и пользовательским соглашением Условия использования.