Attachments 2

Позволяет загрузить файлы, прикрепить их к какому-либо объекту Котонти, и выводить их как список для скачивания или галерею изображений.

М помощью этого плагина вы сможете загрузить файлы, прикрепить их к какому-либо объекту Котонти (странице или теме форума), которые затем, будут выводиться как список для скачивания или галерея изображений.

Автор: Vladimir Sibirov (Trustmaster)

Благодарности: Pavlo Tkachenko (Dayver), Kabak (Kabak)

GitHub: https://github.com/Cotonti-Extensions/attach2

 

#1. Особенности

  • Современный механизм загрузки основанный на jQuery File Upload.
  • Поддержка мультизагрузки.
  • Простая интергация через обратный вызов функций из шаблона.
  • Встроенная галерея Lightbox 2.
  • Загрузки подсчитываются и происходят с оригинальным именем файла.
  • Создание изображений для предпросмотра (thumbnail) и простая его настройка.
  • Специальные ББкоды для вставки изображений в текст страниц вне зависимости от выбранного парсера.

#2. Установка

  1. Загрузить архив и распаковать в папку сплагинами вашего сайта.
  2. В меню «Управление сайтом → Пасширения» произветси установку нажав «установить».
  3. В настройках плагина выберите подходящие вам установки.
  4. Создайте "Каталог для файлов" на вашем сервере (по умолчанию используется "datas/attach") и установите права на запись для PHP (например CHMOD 775 или CHMOD 777).

#3. Использование

Этот раздел рассказывает об основных моментах использования плагина на страницах (pages) c  минимальными изменениями сайта. Аналогично можно настроить его для применения с другими разделам сайта, как например темы форума или комментарии.

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

#3.1. Добавление диалога загрузки

Первое, что необходимо сделать это добавить  файлы на страницу. Возможно вы предполагаете сделать это во время редактирования страницы, однако данный плагин позволяет сделать это во время просмотра страницы. Для этого добавим ссылку "Прикрепить файлы" в меню администрирования страницы, в швблон "page.tpl":

Link to attachment management

Для этого надо добавить следующий код в "page.tpl":

<!-- IF {PHP|cot_auth('plug', 'attach2', 'W')} -->
<li>{PAGE_ID|att_widget('page',$this,'attach2.link')}</li>
<!-- ENDIF -->

Эта ссылка будет видна только тем пользователям, которые имеют на прикрепление файлов (которое определяется правом «записи» (Write access) в настойках прав этого плагина).

#3.2. Использование интерфейса загрузки

Если нажать на ссылку "Прикрепить файлы", откроется следующего вида окно:

Attachment dialog

Интерфейс диалогового окна достаточно стандартен и понятен. Он позволяет выбрать один или несколько файлов за 1 раз, загрузить их, позволяет удалять загруженные, заменять файлы и редактировать описания посредством. Для настройки необходимой последовательности файлов просто перетаците соответствующую строку (Drag & Drop). После того как вы загрузили необходиомое и написали описания нажмите «закрыть», после чего содержимое страницы обновиться и вы увидите результат.

#3.3. Просмотр прикрепленных файлов

Самый простой способ вывода прикрепленных к странице файлов это использовать виджет att_display() в шаблоне "page.tpl":

<!-- IF {PAGE_ID|att_count('page',$this)} > 0 -->
<div class="block">
	<h3>{PHP.L.att_attachments}</h3>
	{PAGE_ID|att_display('page',$this)}
</div>
<!-- ENDIF -->

Который отобразит примерно следующее:

Attachments display all example

#3.4. Добавление простой галереи

Одна из частых задач это размещение на страницах галереи фотографий. Вы можетет добавить простейшую галерею включив в шаблон "page.tpl" следующий код:

<!-- IF {PAGE_ID|att_count('page',$this,'images')} > 0 -->
<div class="block">
	<h3>{PHP.L.att_gallery}</h3>
	{PAGE_ID|att_gallery('page',$this)}
</div>
<!-- ENDIF -->

Он добавить Lightbox 2 галерею на страницу:

Attachments 2 gallery example

#3.5. Добавление списка файлов для скачивания

Еще одной растространненной задачей является добавление на страницу списка файлов для скачивания. Используйте функцию att_downloads() в своем шаблоне("page.tpl"):

<!-- IF {PAGE_ID|att_count('page',$this,'files')} > 0 -->
<div class="block">
	<h3>{PHP.L.att_downloads}</h3>
	{PAGE_ID|att_downloads('page',$this)}
</div>
<!-- ENDIF -->

Стандартный блок выглядит так:

Attachments 2 downloads block example

#4. Расширенные возможности

Вставка стандартных блоков в шаблон дело не хитрое. Но если вы хотите использовать всю мощь плагина или более глубоко разобраться как он работает, этот раздел вам поможет.

#4.1. Вызов функций из TPL шаблонов и их параметры

Прикрепление файлов не ограничивается только страницами и стандартными шаблонами. Вы можете настроить прикрепление файлов и к другим объектам системы и настроить соответствующие им шаблоны. Давайте разберемся какие функции плагин предоставляет для использования в шаблонах и какие параметры им нужно передавать.

att_widget()

/**
 * Создает виджет загрузки/редактирования файлов.
 * Используется как функцию для вызова из шаблонов.
 * @param  string  $area    Код целевого модуля или плагина.
 * @param  integer $item    ID конкретного элемента (например страницы).
 * @param  string  $tpl     Код шаблона
 * @return string           HTML код виджета
 */
function att_widget($area, $item, $tpl = 'attach2.widget', $width = '100%', $height = '200')

Этот вызов используется для создание виждета прикрепления файлов и интеграции его внутрь содержимого вашего объекта (например страницы). В предыдущей главев мы использовали его для добавления на страницы ссылки «Прикрепить файлы» и кода виджета, редактируя при этом шаблон page.tpl. На самом деле эта функция шире, давайте взглянем на параметры:

  • $area - определяет тип содержимого к которому прикрепляются файлы. Usually conains module or plugin code, such as 'page', 'forums', 'comments', etc.
  • $item - This parameter accepts an integer ID of the item the files are attached to. For example, it can be a page ID, forums post ID or comment ID. CoTemplate pipe operator and "$this" keyword are used to pass the appropriate tag to this parameter.
  • $tpl - Contains template code for the widget to be rendered. E.g. if you pass it 'attach2.my_widget', it will try to find the template in "themes/your_theme/plugins/attach2.my_widget.tpl". Default (fallback) templates can be found in "plugins/attach2/tpl", use them as reference. 'attach2.widget' inserts the dialog as an iframe, whereas 'attach2.link' (see previous chapter) adds a link + popup dialog.
  • $width - Width of the iframe, optional.
  • $height - Height of the iframe, optional. 

For example, here is how you can add "Attach files" link for forum posts in "forums.posts.tpl" inside the FORUMS_POSTS_ROW block:

<!-- IF {FORUMS_POSTS_ROW_USERID} == {PHP.usr.id} -->
{FORUMS_POSTS_ROW_ID|att_widget('forums',$this,'attach2.link')}
<!-- ENDIF -->

att_display()

/**
 * Renders attached items on page
 * @param  string  $area Target module/plugin code
 * @param  integer $item Target item id
 * @param  string  $tpl  Template code
 * @param  string  $type Attachment type filter: 'files', 'images'. By default includes all attachments.
 * @return string        Rendered output
 */
function att_display($area, $item, $tpl = 'attach2.display', $type = 'all')

This callback is used to display files already attached to an item. It can render them all within one stream or include a certain type of files only. The paramters are similar with other callbacks:

  • $area - Site area, same as for att_widget().
  • $item - Item ID, same as for att_widget().
  • $tpl - Template code, similar to att_widget(). The standard one for this widget is called 'attach2.display' and can be found in "plugins/attach2/tpl/attach2.display.tpl".
  • $type - Use this parameter to display images only or files only.

Here is how you can display all files attached to a forums post in "forums.posts.tpl" inside the FORUMS_POSTS_ROW block:

{FORUMS_POSTS_ROW_ID|att_display('forums',$this)}

att_count()

/**
 * Returns number of attachments for a specific item.
 * @param  string  $area Target module/plugin code
 * @param  integer $item Target item id
 * @param  string  $type Attachment type filter: 'files', 'images'. By default includes all attachments.
 * @return integer       Number of attachments
 */
function att_count($area, $item, $type = 'all')

This callback returns the number of files attached to an item but it is often used to check whether there are files attached or not. Parameters are common:

  • $area - Site area, same as for att_widget().
  • $item - Item ID, same as for att_widget().
  • $type - Use this parameter to count images only or files only.

Here is how you can use it to display attachments in "forums.posts.tpl" only if there are files attached:

<!-- IF {FORUMS_POSTS_ROW_ID|att_count('forums',$this)} > 0 -->
{FORUMS_POSTS_ROW_ID|att_display('forums',$this)}
<!-- ENDIF -->

att_gallery()

/**
 * Renders images only as a gallery.
 * @param  string  $area Target module/plugin code
 * @param  integer $item Target item id
 * @param  string  $tpl  Template code
 * @return string        Rendered output
 */
function att_gallery($area, $item, $tpl = 'attach2.gallery')

This is a shortcut to att_display() using 'attach2.gallery' as $tpl by default and $type set to 'images'. By default it shows you how to make a simple gallery using Lightbox 2, but you can make your own template and use any gallery script you wish. Parameters:

  • $area - Site area, same as for att_widget().
  • $item - Item ID, same as for att_widget().
  • $tpl - Template code, see att_widget() for description.

E.g. let's imagine we've made our own template located in "themes/your_theme/plugins/attach2.fancy-gallery.tpl". Here's how we attach it to LIST_ROW block in "page.list.tpl":

{LIST_ROW_ID|att_gallery('page',$this,'attach2.fancy-gallery')}

att_downloads()

/**
 * Renders files only as downloads block.
 * @param  string  $area Target module/plugin code
 * @param  integer $item Target item id
 * @param  string  $tpl  Template code
 * @return string        Rendered output
 */
function att_downloads($area, $item, $tpl = 'attach2.downloads')

Similarly to att_gallery(), this is a shortcut to att_display() using 'attach2.downloads' as $tpl by default and $type set to 'files'. It is normally used to provide downloadable files section. Parameters:

  • $area - Site area, same as for att_widget().
  • $item - Item ID, same as for att_widget().
  • $tpl - Template code, see att_widget() for description.

E.g. let's imagine we've made our own template located in "themes/your_theme/plugins/attach2.download-box.tpl". Here's how we attach it to a page in "page.tpl":

{PAGE_ID|att_downloads('page',$this,'attach2.download-box')}

att_thumb()

/**
 * Returns attachment thumbnail path. Generates the thumbnail first if
 * it does not exist.
 * @param  mixed   $id     Attachment ID or a row returned by att_get() function.
 * @param  integer $width  Thumbnail width in pixels
 * @param  integer $height Thumbnail height in pixels
 * @param  string  $frame  Framing mode: 'width', 'height', 'auto' or 'crop'
 * @return string          Thumbnail path on success or false on error
 */

function att_thumb($id, $width = 0, $height = 0, $frame = '')

This callback is mostly used in attach2 templates themselves. It generates a thumbnail for an image attachment and returns an URL to that thumbnail. The parameters are:

  • $id - Attachment ID.
  • $width - Max. thumbnail width in pixels.
  • $height - Max. thumbnail height in pixels.
  • $frame - Framing mode. 'width' fits to the width and saves image ratio, 'height' fits to the height and saves image ratio. 'auto' (default) keeps the original ratio and fits the image into the given rectangle, 'crop' crops the image into the exact width/height given.

Thumbnails are generated on the fly and cached for futher use. Here is an example call from attach2.gallery.tpl:

<img src="{ATTACH_ROW_ID|att_thumb($this,200,200,'crop')}" alt="{ATTACH_ROW_FILENAME}" />

att_get()

/**
 * Fetches a single attachment object for a given item.
 * @param  string  $area   Target module/plugin code.
 * @param  integer $item   Target item id.
 * @param  string  $column Empty string to return full row, one of the following to return a single value: 'id', 'user', 'path', 'filename', 'ext', 'img', 'size', 'title', 'count'
 * @param  string  $mode   One of these values: 'first', 'rand' or 'last'. Defines which image is selected.
 * @return mixed           Scalar column value, entire row as array or NULL if no attachments found.
 */
function att_get($area, $item, $column = '', $mode = 'first')

This function is used to get data for a single attachment per item. Its main purpose is to create page covers in category lists. Parameters are:

  • $area - Site area, same as for att_widget().
  • $item - Item ID, same as for att_widget().
  • $column - Name of the column to be returned by the function. If empty, the function returns an array with a row from the database. If one of the specified values is passed, the scalar column value is returned.
  • $mode - Affects the ordering. By default the first attachment is returned. You can change it to last with 'last' or to a random one with 'random'. Note: if you call att_get() several times in the same template, $mode matters only for the first call with the same $area and $item.

Here is an example of how this function can be used to turn a first attachment per page into clickable page cover thumbnails in "page.list.tpl":

<a href="{LIST_ROW_ID|att_get('page',$this,'path')}" title="{LIST_ROW_ID|att_get('page',$this,'title')}">
    <img src="{LIST_ROW_ID|att_get('page',$this)|att_thumb($this,240,160)}" alt="Foobar" />
</a>

As you see, this function can be used in conjunction with att_thumb() to generate thumbnails on the fly. The minimal Cotonti version for this feature to work is 0.9.12.

#4.2. BBcodes for embedding into content

Images and thumbnails of the attachments can be pasted directly into content such as page_text, com_text, etc. However, you need to get the Attachment ID somehow first in order to paste it. The syntax of bbcode parameters is similar to URL query string. Available bbcodes are:

  • [att_thumb] - inserts only a thumbnail <img/> tag.
  • [att_image] - inserts a clickable image conisting of an <img/> thumbnail and a hyperlink to a full image.

Usage example:

[att_thumb?id=15]
[att_image?id=11&width=320&height=240&alt=Picture description&class=foo]

These bbcodes work regardless of the parser being used, including HTML and Markdown. If you want to disable them, just Pause the attach2.parser part of this plugin in Administration / Extensions / Attachments.

#4.3. Cleanup tool

There's a tool in Administration / Other / Attachments. It is used to purge files attached to items which don't exist anymore. Sometimes items are removed but the code removing linked attachmehts is missing, so this tool may help.

#5. Контакты

Тема на форуме для обсуждения и GitHub tracker сообщений об ошибках.

#6. Credits


1. elfrenazo  28.10.2012 13:01

I will try it, thanks!

2. Alex300  29.10.2012 06:28

Good plugin, thanks.
Already using it. )))

3. diablo  03.02.2013 22:58

for some reason thumbnail page cover doesnt work for me

4. Chiaroscuro  02.07.2013 14:59

В плагине предусметрена возможность установки максимального размера (px) картинки?

5. Twiebie  28.09.2013 21:28
6. pieter  19.02.2015 10:23

Love the plugin so far.

Is there a way to limit the attachments per page.
I only see "Attachments per post (max.), 0 - unlimited:" and this does not effect on pages.

7. kushelbek  06.05.2015 11:25
8. kaossik  10.01.2016 22:50

Something wrong goes with the plugin on my pages. Instead of opening a new vindown this opens in page windows: http://s2.postimg.org/gfzje3jqx/Screenshot_from_2016_01_10_23_50_05.png

Then when i clikc image and upload it this appear: http://s2.postimg.org/k0vexboaf/Screenshot_from_2016_01_10_23_50_24.png

 

9. Macik  13.01.2016 14:25

kaossik, please open separate forum post to get any detailed help.

10. Hantr  07.02.2018 08:07

Подскажите пожалуста как вывести миниатюрки с заданным размером в news.tpl ?

Добавление комментариев доступно только зарегистрированным пользователям