[RC] Attachments in subfolders [Вложения в подпапках]

Здесь авторы могут постить бета-версии своих модификаций для phpBB 3.0.x. Внимание! Не устанавливайте бета-версии модов на работающие форумы!
Правила форума
Местная Конституция | Шаблон запроса | Документация (phpBB3) | Переход на 3.0.6 и выше | FAQ-3 (phpbb3) | Как задавать вопросы | Как устанавливать моды

Ваш вопрос может быть удален без объяснения причин, если на него есть ответы по приведённым ссылкам (а вы рискуете получить предупреждение ;) ).
Аватара пользователя
Татьяна5
Поддержка
Поддержка
Сообщения: 13159
Стаж: 15 лет 1 месяц
Благодарил (а): 236 раз
Поблагодарили: 3750 раз

Re: [RC] Attachments in subfolders (вложения в подпапках)

Сообщение Татьяна5 »

Пчелкин писал(а):Последний вариант моих правок -
Судя по инструкции при установленном "img to attach" после строки

Код: Выделить всё

$filedata['post_attach'] = false;
код из мода "Вложения в подпапках" добавлять дважды (строки всего 2, после обеих),

и после строки

Код: Выделить всё

$this->filename_data['filecomment'] = '';
тоже дважды (строка встречается 4 раза, после 2-х последних)
Аватара пользователя
Пчелкин
phpBB 3.3.0
Сообщения: 11361
Стаж: 16 лет 8 месяцев
Благодарил (а): 1832 раза
Поблагодарили: 1358 раз

Re: [RC] Attachments in subfolders (вложения в подпапках)

Сообщение Пчелкин »

Хм....делал... Мож не внимательно... повторюсь...
NIKON-D90, AF-S 18-105, AF-S 14-24, AF-S 24-70
Аватара пользователя
Пчелкин
phpBB 3.3.0
Сообщения: 11361
Стаж: 16 лет 8 месяцев
Благодарил (а): 1832 раза
Поблагодарили: 1358 раз

Re: [RC] Attachments in subfolders (вложения в подпапках)

Сообщение Пчелкин »

Татьяна5 По ходу выходит что так?

Код: Выделить всё

	*/
	function parse_attachments($form_name, $mode, $forum_id, $submit, $preview, $refresh, $is_message = false)
	{
		global $config, $auth, $user, $phpbb_root_path, $phpEx, $db;

		$error = array();

		$num_attachments = sizeof($this->attachment_data);
		$this->filename_data['filecomment'] = utf8_normalize_nfc(request_var('filecomment', '', true));
		$img_to_attach = (isset($_FILES['img_to_attach']) && sizeof($_FILES['img_to_attach'])) ? sizeof($_FILES['img_to_attach']) : 0;
		$num_attachments += $img_to_attach;
		$upload_file = (isset($_FILES[$form_name]) && $_FILES[$form_name]['name'] != 'none' && trim($_FILES[$form_name]['name']) || $img_to_attach) ? true : false;

		$add_file		= (isset($_POST['add_file']) || $img_to_attach) ? true : false;
		$delete_file	= (isset($_POST['delete_file'])) ? true : false;

		// First of all adjust comments if changed
		$actual_comment_list = utf8_normalize_nfc(request_var('comment_list', array(''), true));

		foreach ($actual_comment_list as $comment_key => $comment)
		{
			if (!isset($this->attachment_data[$comment_key]))
			{
				continue;
			}

			if ($this->attachment_data[$comment_key]['attach_comment'] != $actual_comment_list[$comment_key])
			{
				$this->attachment_data[$comment_key]['attach_comment'] = $actual_comment_list[$comment_key];
			}
		}

		$cfg = array();
		$cfg['max_attachments'] = ($is_message) ? $config['max_attachments_pm'] : $config['max_attachments'];
		$forum_id = ($is_message) ? 0 : $forum_id;

		$max_length = 5;
		if ($submit && in_array($mode, array('post', 'reply', 'quote', 'edit')) && $upload_file)
		{
			if ($num_attachments < $cfg['max_attachments'] || $auth->acl_get('a_') || $auth->acl_get('m_', $forum_id))
			{
				if($img_to_attach)
				{
					foreach($_FILES['img_to_attach'] as $img_url)
					{
						$filedata = upload_attachment($form_name, $forum_id, false, '', $is_message, false, $img_url);
						$error = $filedata['error'];

						if ($filedata['post_attach'] && !sizeof($error))
						{
								$max_length=10;
								$real_filename = $filedata['real_filename'];
								$filedata['real_filename'] = str_replace('.' . $filedata['extension'],'',$filedata['real_filename']);
								if($max_length < strlen($filedata['real_filename']))
								{
									$filedata['real_filename'] = truncate_string($filedata['real_filename'],$max_length,$max_length, false,'',-$max_length) . '.' . $filedata['extension'];
								}
								else
								{
									$filedata['real_filename'] = $real_filename;
								}
						
							$sql_ary = array(
								'physical_filename'	=> $filedata['physical_filename'],
								'attach_comment'	=> $this->filename_data['filecomment'],
								'real_filename'		=> $filedata['real_filename'],
								'extension'			=> $filedata['extension'],
								'mimetype'			=> $filedata['mimetype'],
								'filesize'			=> $filedata['filesize'],
								'filetime'			=> $filedata['filetime'],
								'thumbnail'			=> $filedata['thumbnail'],
								'is_orphan'			=> 1,
								'in_message'		=> ($is_message) ? 1 : 0,
								'poster_id'			=> $user->data['user_id'],
							);

							$db->sql_query('INSERT INTO ' . ATTACHMENTS_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary));

					////////////////// Attachments in subfolders /////////////////////

					$new_attachment_id = $db->sql_nextid();
					$new_entry = array(
						'attach_id'		=> $new_attachment_id,
						'is_orphan'		=> 1,
								'mimetype'		=> $filedata['mimetype'],						
						'real_filename'	=> $filedata['real_filename'],
						'attach_comment'=> $this->filename_data['filecomment'],
					);
					////////////////// Attachments in subfolders /////////////////////

							$this->attachment_data = array_merge(array(0 => $new_entry), $this->attachment_data);
							$this->message = preg_replace('#\[attachment=([0-9]+)\](.*?)\[\/attachment\]#e', "'[attachment='.(\\1 + 1).']\\2[/attachment]'", $this->message);
							$this->message = utf8_normalize_nfc(preg_replace('#\[(img|hsimg):' . $this->bbcode_uid . '\].*' . $real_filename . '\[\/(img|hsimg):' . $this->bbcode_uid . '\]#iu', '[attachment=0]' . $filedata['real_filename'] . '[/attachment]', utf8_decode_ncr($this->message)));
							$this->filename_data['filecomment'] = '';

							// This Variable is set to false here, because Attachments are entered into the
							// Database in two modes, one if the id_list is 0 and the second one if post_attach is true
							// Since post_attach is automatically switched to true if an Attachment got added to the filesystem,
							// but we are assigning an id of 0 here, we have to reset the post_attach variable to false.
							//
							// This is very relevant, because it could happen that the post got not submitted, but we do not
							// know this circumstance here. We could be at the posting page or we could be redirected to the entered
							// post. :)
							$filedata['post_attach'] = false;
					////////////////// Attachments in subfolders /////////////////////
					$ais_folder_1 = substr(substr($new_attachment_id + 1000000, -6), 0, 2);
					$ais_folder_2 = substr(substr($new_attachment_id + 1000000, -4), 0, 2);
					$ais_path_to_add = '/' . $ais_folder_1 . '/' . $ais_folder_2;
					
					if (!file_exists($phpbb_root_path . $config['upload_path'] . '/' . $ais_folder_1))
					{
						mkdir($phpbb_root_path . $config['upload_path'] . '/' . $ais_folder_1);
						copy($phpbb_root_path . $config['upload_path'] . '/index.htm', $phpbb_root_path . $config['upload_path'] . '/' . $ais_folder_1 . '/index.htm');
					}
					
					if (!file_exists($phpbb_root_path . $config['upload_path'] . $ais_path_to_add))
					{
						mkdir($phpbb_root_path . $config['upload_path'] . $ais_path_to_add);
						copy($phpbb_root_path . $config['upload_path'] . '/index.htm', $phpbb_root_path . $config['upload_path'] . $ais_path_to_add . '/index.htm');
					}

					if (file_exists($phpbb_root_path . $config['upload_path'] . '/' . $filedata['physical_filename']))
					{
						rename($phpbb_root_path . $config['upload_path'] . '/' . $filedata['physical_filename'], $phpbb_root_path . $config['upload_path'] . $ais_path_to_add . '/' . $filedata['physical_filename']);
					}

					if (file_exists($phpbb_root_path . $config['upload_path'] . '/thumb_' . $filedata['physical_filename']))
					{
						rename($phpbb_root_path . $config['upload_path'] . '/thumb_' . $filedata['physical_filename'], $phpbb_root_path . $config['upload_path'] . $ais_path_to_add . '/thumb_' . $filedata['physical_filename']);
					}
					////////////////// Attachments in subfolders /////////////////////							
						}
					}	
				}
				else
				{
				$filedata = upload_attachment($form_name, $forum_id, false, '', $is_message);
				$error = $filedata['error'];

				if ($filedata['post_attach'] && !sizeof($error))
				{
					$sql_ary = array(
						'physical_filename'	=> $filedata['physical_filename'],
						'attach_comment'	=> $this->filename_data['filecomment'],
						'real_filename'		=> $filedata['real_filename'],
						'extension'			=> $filedata['extension'],
						'mimetype'			=> $filedata['mimetype'],
						'filesize'			=> $filedata['filesize'],
						'filetime'			=> $filedata['filetime'],
						'thumbnail'			=> $filedata['thumbnail'],
						'is_orphan'			=> 1,
						'in_message'		=> ($is_message) ? 1 : 0,
						'poster_id'			=> $user->data['user_id'],
					);

					$db->sql_query('INSERT INTO ' . ATTACHMENTS_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary));

						////////////////// Attachments in subfolders /////////////////////
						$new_attachment_id = $db->sql_nextid();
						$new_entry = array(
							'attach_id'		=> $new_attachment_id,
							'is_orphan'		=> 1,
						'mimetype'   	=> $filedata['mimetype'],								
							'real_filename'	=> $filedata['real_filename'],
							'attach_comment'=> $this->filename_data['filecomment'],
						);
						////////////////// Attachments in subfolders /////////////////////

					$this->attachment_data = array_merge(array(0 => $new_entry), $this->attachment_data);
					$this->message = preg_replace('#\[attachment=([0-9]+)\](.*?)\[\/attachment\]#e', "'[attachment='.(\\1 + 1).']\\2[/attachment]'", $this->message);

					$this->filename_data['filecomment'] = '';

					// This Variable is set to false here, because Attachments are entered into the
					// Database in two modes, one if the id_list is 0 and the second one if post_attach is true
					// Since post_attach is automatically switched to true if an Attachment got added to the filesystem,
					// but we are assigning an id of 0 here, we have to reset the post_attach variable to false.
					//
					// This is very relevant, because it could happen that the post got not submitted, but we do not
					// know this circumstance here. We could be at the posting page or we could be redirected to the entered
					// post. :)
					$filedata['post_attach'] = false;
					////////////////// Attachments in subfolders /////////////////////
					$ais_folder_1 = substr(substr($new_attachment_id + 1000000, -6), 0, 2);
					$ais_folder_2 = substr(substr($new_attachment_id + 1000000, -4), 0, 2);
					$ais_path_to_add = '/' . $ais_folder_1 . '/' . $ais_folder_2;
					
					if (!file_exists($phpbb_root_path . $config['upload_path'] . '/' . $ais_folder_1))
					{
						mkdir($phpbb_root_path . $config['upload_path'] . '/' . $ais_folder_1);
						copy($phpbb_root_path . $config['upload_path'] . '/index.htm', $phpbb_root_path . $config['upload_path'] . '/' . $ais_folder_1 . '/index.htm');
					}
					
					if (!file_exists($phpbb_root_path . $config['upload_path'] . $ais_path_to_add))
					{
						mkdir($phpbb_root_path . $config['upload_path'] . $ais_path_to_add);
						copy($phpbb_root_path . $config['upload_path'] . '/index.htm', $phpbb_root_path . $config['upload_path'] . $ais_path_to_add . '/index.htm');
					}

					if (file_exists($phpbb_root_path . $config['upload_path'] . '/' . $filedata['physical_filename']))
					{
						rename($phpbb_root_path . $config['upload_path'] . '/' . $filedata['physical_filename'], $phpbb_root_path . $config['upload_path'] . $ais_path_to_add . '/' . $filedata['physical_filename']);
					}

					if (file_exists($phpbb_root_path . $config['upload_path'] . '/thumb_' . $filedata['physical_filename']))
					{
						rename($phpbb_root_path . $config['upload_path'] . '/thumb_' . $filedata['physical_filename'], $phpbb_root_path . $config['upload_path'] . $ais_path_to_add . '/thumb_' . $filedata['physical_filename']);
					}
					////////////////// Attachments in subfolders /////////////////////						
				}
			}
			}
			else
			{
				$error[] = sprintf($user->lang['TOO_MANY_ATTACHMENTS'], $cfg['max_attachments']);
			}
		}

		if ($preview || $refresh || sizeof($error))
		{
			// Perform actions on temporary attachments
			if ($delete_file)
			{
				include_once($phpbb_root_path . 'includes/functions_admin.' . $phpEx);

				$index = array_keys(request_var('delete_file', array(0 => 0)));
				$index = (!empty($index)) ? $index[0] : false;

				if ($index !== false && !empty($this->attachment_data[$index]))
				{
					// delete selected attachment
					if ($this->attachment_data[$index]['is_orphan'])
					{
						$sql = 'SELECT attach_id, physical_filename, thumbnail
							FROM ' . ATTACHMENTS_TABLE . '
							WHERE attach_id = ' . (int) $this->attachment_data[$index]['attach_id'] . '
								AND is_orphan = 1
								AND poster_id = ' . $user->data['user_id'];
						$result = $db->sql_query($sql);
						$row = $db->sql_fetchrow($result);
						$db->sql_freeresult($result);

						if ($row)
						{
							phpbb_unlink($row['physical_filename'], 'file');

							if ($row['thumbnail'])
							{
								phpbb_unlink($row['physical_filename'], 'thumbnail');
							}

							$db->sql_query('DELETE FROM ' . ATTACHMENTS_TABLE . ' WHERE attach_id = ' . (int) $this->attachment_data[$index]['attach_id']);
						}
					}
					else
					{
						delete_attachments('attach', array(intval($this->attachment_data[$index]['attach_id'])));
					}

					unset($this->attachment_data[$index]);
					$this->message = preg_replace('#\[attachment=([0-9]+)\](.*?)\[\/attachment\]#e', "(\\1 == \$index) ? '' : ((\\1 > \$index) ? '[attachment=' . (\\1 - 1) . ']\\2[/attachment]' : '\\0')", $this->message);

					// Reindex Array
					$this->attachment_data = array_values($this->attachment_data);
				}
			}
			else if (($add_file || $preview) && $upload_file)
			{
				if ($num_attachments < $cfg['max_attachments'] || $auth->acl_gets('m_', 'a_', $forum_id))
				{
					if($img_to_attach)
					{
						foreach($_FILES['img_to_attach'] as $img_url)
						{
							$filedata = upload_attachment($form_name, $forum_id, false, '', $is_message, false, $img_url);
							$error = array_merge($error, $filedata['error']);

							if (!sizeof($error))
							{
                                $max_length=10;
								$real_filename = $filedata['real_filename'];
								$filedata['real_filename'] = str_replace('.' . $filedata['extension'],'',$filedata['real_filename']);
								if($max_length < strlen($filedata['real_filename']))
								{
									$filedata['real_filename'] = truncate_string($filedata['real_filename'],$max_length,$max_length, false,'',-$max_length) . '.' . $filedata['extension'];
								}
								else
								{
									$filedata['real_filename'] = $real_filename;
								}							
								$sql_ary = array(
									'physical_filename'	=> $filedata['physical_filename'],
									'attach_comment'	=> $this->filename_data['filecomment'],
									'real_filename'		=> $filedata['real_filename'],
									'extension'			=> $filedata['extension'],
									'mimetype'			=> $filedata['mimetype'],
									'filesize'			=> $filedata['filesize'],
									'filetime'			=> $filedata['filetime'],
									'thumbnail'			=> $filedata['thumbnail'],
									'is_orphan'			=> 1,
									'in_message'		=> ($is_message) ? 1 : 0,
									'poster_id'			=> $user->data['user_id'],
								);

								$db->sql_query('INSERT INTO ' . ATTACHMENTS_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary));

						////////////////// Attachments in subfolders /////////////////////
						$new_attachment_id = $db->sql_nextid();
						$new_entry = array(
							'attach_id'		=> $new_attachment_id,
							'is_orphan'		=> 1,
									'mimetype'		=> $filedata['mimetype'],							
							'real_filename'	=> $filedata['real_filename'],
							'attach_comment'=> $this->filename_data['filecomment'],
						);
						////////////////// Attachments in subfolders /////////////////////

								$this->attachment_data = array_merge(array(0 => $new_entry), $this->attachment_data);
								$this->message = preg_replace('#\[attachment=([0-9]+)\](.*?)\[\/attachment\]#e', "'[attachment='.(\\1 + 1).']\\2[/attachment]'", $this->message);
								$this->message = utf8_normalize_nfc(preg_replace('#\[(img|hsimg):' . $this->bbcode_uid . '\].*' . $real_filename . '\[\/(img|hsimg):' . $this->bbcode_uid . '\]#iu', '[attachment=0]' . $filedata['real_filename'] . '[/attachment]', utf8_decode_ncr($this->message)));
								$this->filename_data['filecomment'] = '';
						////////////////// Attachments in subfolders /////////////////////
						$ais_folder_1 = substr(substr($new_attachment_id + 1000000, -6), 0, 2);
						$ais_folder_2 = substr(substr($new_attachment_id + 1000000, -4), 0, 2);
						$ais_path_to_add = '/' . $ais_folder_1 . '/' . $ais_folder_2;
						
						if (!file_exists($phpbb_root_path . $config['upload_path'] . '/' . $ais_folder_1))
						{
								mkdir($phpbb_root_path . $config['upload_path'] . '/' . $ais_folder_1);
								copy($phpbb_root_path . $config['upload_path'] . '/index.htm', $phpbb_root_path . $config['upload_path'] . '/' . $ais_folder_1 . '/index.htm');
						}
						
						if (!file_exists($phpbb_root_path . $config['upload_path'] . $ais_path_to_add))
						{
								mkdir($phpbb_root_path . $config['upload_path'] . $ais_path_to_add);
								copy($phpbb_root_path . $config['upload_path'] . '/index.htm', $phpbb_root_path . $config['upload_path'] . $ais_path_to_add . '/index.htm');
						}

						if (file_exists($phpbb_root_path . $config['upload_path'] . '/' . $filedata['physical_filename']))
						{
							rename($phpbb_root_path . $config['upload_path'] . '/' . $filedata['physical_filename'], $phpbb_root_path . $config['upload_path'] . $ais_path_to_add . '/' . $filedata['physical_filename']);
						}

						if (file_exists($phpbb_root_path . $config['upload_path'] . '/thumb_' . $filedata['physical_filename']))
						{
							rename($phpbb_root_path . $config['upload_path'] . '/thumb_' . $filedata['physical_filename'], $phpbb_root_path . $config['upload_path'] . $ais_path_to_add . '/thumb_' . $filedata['physical_filename']);
						}
						////////////////// Attachments in subfolders /////////////////////								
							}
						}	
					}
					else
					{

					$filedata = upload_attachment($form_name, $forum_id, false, '', $is_message);
					$error = array_merge($error, $filedata['error']);

					if (!sizeof($error))
					{
						$sql_ary = array(
							'physical_filename'	=> $filedata['physical_filename'],
							'attach_comment'	=> $this->filename_data['filecomment'],
							'real_filename'		=> $filedata['real_filename'],
							'extension'			=> $filedata['extension'],
							'mimetype'			=> $filedata['mimetype'],
							'filesize'			=> $filedata['filesize'],
							'filetime'			=> $filedata['filetime'],
							'thumbnail'			=> $filedata['thumbnail'],
							'is_orphan'			=> 1,
							'in_message'		=> ($is_message) ? 1 : 0,
							'poster_id'			=> $user->data['user_id'],
						);

						$db->sql_query('INSERT INTO ' . ATTACHMENTS_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary));

						////////////////// Attachments in subfolders /////////////////////
						$new_attachment_id = $db->sql_nextid();
						$new_entry = array(
							'attach_id'		=> $new_attachment_id,
							'is_orphan'		=> 1,
									'mimetype'		=> $filedata['mimetype'],							
							'real_filename'	=> $filedata['real_filename'],
							'attach_comment'=> $this->filename_data['filecomment'],
						);
						////////////////// Attachments in subfolders /////////////////////

						$this->attachment_data = array_merge(array(0 => $new_entry), $this->attachment_data);
						$this->message = preg_replace('#\[attachment=([0-9]+)\](.*?)\[\/attachment\]#e', "'[attachment='.(\\1 + 1).']\\2[/attachment]'", $this->message);
						$this->filename_data['filecomment'] = '';
						////////////////// Attachments in subfolders /////////////////////
						$ais_folder_1 = substr(substr($new_attachment_id + 1000000, -6), 0, 2);
						$ais_folder_2 = substr(substr($new_attachment_id + 1000000, -4), 0, 2);
						$ais_path_to_add = '/' . $ais_folder_1 . '/' . $ais_folder_2;
						
						if (!file_exists($phpbb_root_path . $config['upload_path'] . '/' . $ais_folder_1))
						{
								mkdir($phpbb_root_path . $config['upload_path'] . '/' . $ais_folder_1);
								copy($phpbb_root_path . $config['upload_path'] . '/index.htm', $phpbb_root_path . $config['upload_path'] . '/' . $ais_folder_1 . '/index.htm');
						}
						
						if (!file_exists($phpbb_root_path . $config['upload_path'] . $ais_path_to_add))
						{
								mkdir($phpbb_root_path . $config['upload_path'] . $ais_path_to_add);
								copy($phpbb_root_path . $config['upload_path'] . '/index.htm', $phpbb_root_path . $config['upload_path'] . $ais_path_to_add . '/index.htm');
						}

						if (file_exists($phpbb_root_path . $config['upload_path'] . '/' . $filedata['physical_filename']))
						{
							rename($phpbb_root_path . $config['upload_path'] . '/' . $filedata['physical_filename'], $phpbb_root_path . $config['upload_path'] . $ais_path_to_add . '/' . $filedata['physical_filename']);
						}

						if (file_exists($phpbb_root_path . $config['upload_path'] . '/thumb_' . $filedata['physical_filename']))
						{
							rename($phpbb_root_path . $config['upload_path'] . '/thumb_' . $filedata['physical_filename'], $phpbb_root_path . $config['upload_path'] . $ais_path_to_add . '/thumb_' . $filedata['physical_filename']);
						}
						////////////////// Attachments in subfolders /////////////////////						
					}
				}
				}
				else
				{
					$error[] = sprintf($user->lang['TOO_MANY_ATTACHMENTS'], $cfg['max_attachments']);
				}
			}
		}

		foreach ($error as $error_msg)
		{
			$this->warn_msg[] = $error_msg;
		}
	}

	/**
	* Get Attachment Data
	*/
	function get_submitted_attachment_data($check_user_id = false)
	{
		global $user, $db, $phpbb_root_path, $phpEx, $config;

		$this->filename_data['filecomment'] = utf8_normalize_nfc(request_var('filecomment', '', true));
		$attachment_data = (isset($_POST['attachment_data'])) ? $_POST['attachment_data'] : array();
		$this->attachment_data = array();

		$check_user_id = ($check_user_id === false) ? $user->data['user_id'] : $check_user_id;

		if (!sizeof($attachment_data))
		{
			return;
		}

		$not_orphan = $orphan = array();

		foreach ($attachment_data as $pos => $var_ary)
		{
			if ($var_ary['is_orphan'])
			{
				$orphan[(int) $var_ary['attach_id']] = $pos;
			}
			else
			{
				$not_orphan[(int) $var_ary['attach_id']] = $pos;
			}
		}

		// Regenerate already posted attachments
		if (sizeof($not_orphan))
		{
			// Get the attachment data, based on the poster id...
			$sql = 'SELECT attach_id, is_orphan, real_filename, attach_comment
				FROM ' . ATTACHMENTS_TABLE . '
				WHERE ' . $db->sql_in_set('attach_id', array_keys($not_orphan)) . '
					AND poster_id = ' . $check_user_id;
			$result = $db->sql_query($sql);

			while ($row = $db->sql_fetchrow($result))
			{
				$pos = $not_orphan[$row['attach_id']];
				$this->attachment_data[$pos] = $row;
				set_var($this->attachment_data[$pos]['attach_comment'], $_POST['attachment_data'][$pos]['attach_comment'], 'string', true);

				unset($not_orphan[$row['attach_id']]);
			}
			$db->sql_freeresult($result);
		}

		if (sizeof($not_orphan))
		{
			trigger_error('NO_ACCESS_ATTACHMENT', E_USER_ERROR);
		}

		// Regenerate newly uploaded attachments
		if (sizeof($orphan))
		{
			$sql = 'SELECT attach_id, is_orphan, real_filename, attach_comment
				FROM ' . ATTACHMENTS_TABLE . '
				WHERE ' . $db->sql_in_set('attach_id', array_keys($orphan)) . '
					AND poster_id = ' . $user->data['user_id'] . '
					AND is_orphan = 1';
			$result = $db->sql_query($sql);

			while ($row = $db->sql_fetchrow($result))
			{
				$pos = $orphan[$row['attach_id']];
				$this->attachment_data[$pos] = $row;
				set_var($this->attachment_data[$pos]['attach_comment'], $_POST['attachment_data'][$pos]['attach_comment'], 'string', true);

				unset($orphan[$row['attach_id']]);
			}
			$db->sql_freeresult($result);
		}

		if (sizeof($orphan))
		{
			trigger_error('NO_ACCESS_ATTACHMENT', E_USER_ERROR);
		}

		ksort($this->attachment_data);
	}

	/**
Пошла четвертая попытка... млин...
NIKON-D90, AF-S 18-105, AF-S 14-24, AF-S 24-70
Аватара пользователя
Татьяна5
Поддержка
Поддержка
Сообщения: 13159
Стаж: 15 лет 1 месяц
Благодарил (а): 236 раз
Поблагодарили: 3750 раз

Re: [RC] Attachments in subfolders (вложения в подпапках)

Сообщение Татьяна5 »

Пчелкин, в этом файле так
Аватара пользователя
Пчелкин
phpBB 3.3.0
Сообщения: 11361
Стаж: 16 лет 8 месяцев
Благодарил (а): 1832 раза
Поблагодарили: 1358 раз

Re: [RC] Attachments in subfolders (вложения в подпапках)

Сообщение Пчелкин »

Поехали значит на живом пробовать... кошмар... да хранит меня...

Добавлено спустя 6 минут 43 секунды:
Ни фига... те же ошибки лезут после запуска скрипта...

Код: Выделить всё

 
Язык: ru	Страница: move_attachments_in_subfolders.php?current_id=9465
Файл: [ROOT]/move_attachments_in_subfolders.php
Строка: 103	[PHP Warning]

mkdir(): Permission denied	
Язык: ru	Страница: move_attachments_in_subfolders.php?current_id=9465
Файл: [ROOT]/move_attachments_in_subfolders.php
Строка: 104	[PHP Warning]

copy(files_new/index.htm): failed to open stream: No such file or directory	
Язык: ru	Страница: move_attachments_in_subfolders.php?current_id=9465
Файл: [ROOT]/move_attachments_in_subfolders.php
Строка: 109	[PHP Warning]

mkdir(): No such file or directory	
Язык: ru	Страница: move_attachments_in_subfolders.php?current_id=9465
Файл: [ROOT]/move_attachments_in_subfolders.php
Строка: 110	[PHP Warning]

copy(files_new/00/index.htm): failed to open stream: No such file or directory	
Язык: ru	Страница: move_attachments_in_subfolders.php?current_id=9465
Файл: [ROOT]/move_attachments_in_subfolders.php
Строка: 115	[PHP Warning]

mkdir(): No such file or directory	
Язык: ru	Страница: move_attachments_in_subfolders.php?current_id=9465
Файл: [ROOT]/move_attachments_in_subfolders.php
Строка: 116	[PHP Warning]

copy(files_new/00/95/index.htm): failed to open stream: No such file or directory	
Язык: ru	Страница: move_attachments_in_subfolders.php?current_id=9465
Файл: [ROOT]/move_attachments_in_subfolders.php
Строка: 124	[PHP Warning]

copy(files_new/00/95/55_185501ef004bd6edc5748bbdfc48052c): failed to open stream: No such file or directory	
Язык: ru	Страница: move_attachments_in_subfolders.php?current_id=9465
Файл: [ROOT]/move_attachments_in_subfolders.php
Строка: 136	[PHP Warning]

copy(files_new/00/95/thumb_55_185501ef004bd6edc5748bbdfc48052c): failed to open stream: No such file or directory
Вот зачем, зачем у меня такой сложный форум? Зачем он такой получился? Зачем? Зачем? Зачем? :roll: :oops:

Добавлено спустя 13 минут 14 секунд:
Создал папки с ЧМОД 755
В конце выдал

Код: Выделить всё

[phpBB Debug] PHP Notice: в файле [ROOT]/move_attachments_in_subfolders.php в строке 150: Undefined variable: ais_attachment_id
Выделить текст ошибки
[phpBB Debug] PHP Notice: в файле [ROOT]/move_attachments_in_subfolders.php в строке 151: Undefined variable: ais_attachment_id
Выделить текст ошибки
[phpBB Debug] PHP Warning: в файле [ROOT]/move_attachments_in_subfolders.php в строке 161: rename(files,files_old): Permission denied
Выделить текст ошибки
[phpBB Debug] PHP Warning: в файле [ROOT]/move_attachments_in_subfolders.php в строке 162: rename(files_new,files): No such file or directory
И все...ни ОЛД ни перемещений файлов...млин...

Добавлено спустя 5 минут 32 секунды:
Опаньки...в ISP Manager прям на сервере смотреть - выставлены права на новые папки - apache
1911.jpg
У вас нет необходимых прав для просмотра вложений в этом сообщении.
NIKON-D90, AF-S 18-105, AF-S 14-24, AF-S 24-70
sweetah
phpBB 2.0.6
Сообщения: 506
Стаж: 16 лет 7 месяцев
Благодарил (а): 108 раз
Поблагодарили: 26 раз

Re: [RC] Attachments in subfolders (вложения в подпапках)

Сообщение sweetah »

Pazh писал(а):2. потерянные вложения через админку не удаляются
В смысле они удаляются, но на деле не удаляются (физически)? Или ошибку получаешь о невозможности удалить?
Аватара пользователя
Пчелкин
phpBB 3.3.0
Сообщения: 11361
Стаж: 16 лет 8 месяцев
Благодарил (а): 1832 раза
Поблагодарили: 1358 раз

Re: [RC] Attachments in subfolders (вложения в подпапках)

Сообщение Пчелкин »

Просто не удаляются и все...
Pazh писал(а):потому что в функционале мода нет явного вызова phpbb_chmod
Исправление - [RC] Attachments in subfolders (вложения в подпапках)
NIKON-D90, AF-S 18-105, AF-S 14-24, AF-S 24-70
Аватара пользователя
Пчелкин
phpBB 3.3.0
Сообщения: 11361
Стаж: 16 лет 8 месяцев
Благодарил (а): 1832 раза
Поблагодарили: 1358 раз

Re: [RC] Attachments in subfolders (вложения в подпапках)

Сообщение Пчелкин »

Pazh писал(а):КОД НЕ ПРОВЕРЯЛСЯ!!!!
ЭТО ПРАВКА ДЛЯ ИЗМЕНЕННОГО ФАЙЛА ПО ИНСТРУКЦИИ К САБЖУ ИЛИ ДЛЯ ЕЩЕ НЕ ИЗМЕНЕННОГО ПО ИНСТРУКЦИИ? ЕСЛИ ДЛЯ ЕЩЕ НЕИЗМЕНЕННОГО - НЕ ПОКАЗЫВАЮТСЯ И АДМИНКА ПОТЕРЯННЫЕ не видит ВСЕ РАВНО... Если уже для измененного - не состыковочка...

Добавлено спустя 3 минуты 19 секунд:
2. В STK проверка записей в БД о вложениях тоже ничего не находит....Потери создавал искусственно - результат от STK не получил...
NIKON-D90, AF-S 18-105, AF-S 14-24, AF-S 24-70
Аватара пользователя
Pazh
Former team member
Сообщения: 2317
Стаж: 16 лет 10 месяцев
Благодарил (а): 42 раза
Поблагодарили: 506 раз

Re: [RC] Attachments in subfolders (вложения в подпапках)

Сообщение Pazh »

Пчелкин после установки мода и переноса файлов. Показывать потерянные вложения админка показывает исходя из данных БД, а не наличия файлов, а вот при удалении потерянных вложений штатный движок проверяет наличие физического файла и удаляет запись из phpbb_attachments в любом случае, а вот сами файлы оставались, т.к. они искались по старому пути
Помощь в ЛС/email только за WM или ЮMoney
Аватара пользователя
Пчелкин
phpBB 3.3.0
Сообщения: 11361
Стаж: 16 лет 8 месяцев
Благодарил (а): 1832 раза
Поблагодарили: 1358 раз

Re: [RC] Attachments in subfolders (вложения в подпапках)

Сообщение Пчелкин »

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

Код: Выделить всё

/**
* Delete attached file
*/
function phpbb_unlink($filename, $mode = 'file', $entry_removed = false)
{
	global $db, $phpbb_root_path, $config;

////////////////// Attachments in subfolders /////////////////////
// Because of copying topics or modifications a physical filename could be assigned more than once. If so, do not remove the file itself.
	$sql = 'SELECT attach_id
		FROM ' . ATTACHMENTS_TABLE . "
		WHERE physical_filename = '" . $db->sql_escape(utf8_basename($filename)) . "'";
	$result = $db->sql_query($sql);
	$entries = array();
	while($row = $db->sql_fetchrow($result))
	{
		$entries[] = $row['attach_id'];
	}	
	$db->sql_freeresult($result);

	// Do not remove file if at least one additional entry with the same name exist.
	if (($entry_removed && sizeof($entries) > 0) || (!$entry_removed && sizeof($entries) > 1))
	{
		unset($entries);
		return false;
	}

	$filename = ($mode == 'thumbnail') ? 'thumb_' . utf8_basename($filename) : utf8_basename($filename);
	foreach($entries as $attach_id)
	{
		$ais_folder_1 = substr(substr($attach_id + 1000000, -6), 0, 2);
		$ais_folder_2 = substr(substr($attach_id + 1000000, -4), 0, 2);
		$ais_path_to_add = '/' . $ais_folder_1 . '/' . $ais_folder_2;

		@unlink($phpbb_root_path . $config['upload_path'] . $ais_path_to_add . '/' . $filename);
	}
return true;
////////////////// Attachments in subfolders /////////////////////
}

/**
* All-encompasing sync function
ИБО-
Pazh писал(а):КОД НЕ ПРОВЕРЯЛСЯ!!!!
Добавлено спустя 49 секунд:
Упс.. сам ступил... появились...
NIKON-D90, AF-S 18-105, AF-S 14-24, AF-S 24-70
Аватара пользователя
Пчелкин
phpBB 3.3.0
Сообщения: 11361
Стаж: 16 лет 8 месяцев
Благодарил (а): 1832 раза
Поблагодарили: 1358 раз

Re: [RC] Attachments in subfolders (вложения в подпапках)

Сообщение Пчелкин »

Крайне сложный и вредный мод.. Требуется дописка ко всем модам, работающим с вложениями...
Устал биться с ним и скинул... СТК помогла восстановить обращения во всем вложениям после их переноса в одну папку...

Вопрос снят.. Не ставьте... Одни проблемы...

И еще ... Для первого запуска работы мода по раскидке вложений по попкам срипту необходимы ТРИ величины на диске хоста от веса занимаемого вложениями... То есть, если вложений 10 гег, то чтоб скрипт по раскидке доработал до конца, надо чтоб было свободно еще 20 гег... увы... :lol:
NIKON-D90, AF-S 18-105, AF-S 14-24, AF-S 24-70
sweetah
phpBB 2.0.6
Сообщения: 506
Стаж: 16 лет 7 месяцев
Благодарил (а): 108 раз
Поблагодарили: 26 раз

Re: [RC] Attachments in subfolders (вложения в подпапках)

Сообщение sweetah »

Просто нужно было заранее о подпапках подумать и не переносить ничего, тогда проблем не будет.
Аватара пользователя
Пчелкин
phpBB 3.3.0
Сообщения: 11361
Стаж: 16 лет 8 месяцев
Благодарил (а): 1832 раза
Поблагодарили: 1358 раз

Re: [RC] Attachments in subfolders (вложения в подпапках)

Сообщение Пчелкин »

Ты хоть сам понял что написал? И второе - а чего курил?
NIKON-D90, AF-S 18-105, AF-S 14-24, AF-S 24-70
sweetah
phpBB 2.0.6
Сообщения: 506
Стаж: 16 лет 7 месяцев
Благодарил (а): 108 раз
Поблагодарили: 26 раз

Re: [RC] Attachments in subfolders (вложения в подпапках)

Сообщение sweetah »

Зачем призывать не ставить этот мод? Если запускается новый форум, то сразу поставить и не будет проблем. Все пути до файлов прописываются в базе и проблем с модами, которые работают с аттачами не должно быть.
Аватара пользователя
Пчелкин
phpBB 3.3.0
Сообщения: 11361
Стаж: 16 лет 8 месяцев
Благодарил (а): 1832 раза
Поблагодарили: 1358 раз

Re: [RC] Attachments in subfolders (вложения в подпапках)

Сообщение Пчелкин »

sweetah писал(а):Все пути до файлов прописываются в базе
Да ты что? Вот это новость!!! А я посчитал что в самом скрипте...
Тогда как про это -
Пчелкин писал(а):Требуется дописка ко всем модам, работающим с вложениями...
???
И где ты здесь запись в БД нашел, умник?

Код: Выделить всё

<?php
/**
*
* @author I-FR70 (Dreddone) fabio@rambaudi.net - http://www.rambaudi.net
*
* @package phpBB3
* @version 1.0.0
* @copyright (c) 2011 by Dreddone
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
*
*/

/**
* @ignore
*/

/***************************
**                        **
** Parameter              **
**                        **
***************************/

// Set 1 to copy attachments, 0 to move attachments.
$ais_move_or_copy = 1;

/***************************
**                        **
**       End              **
**                        **
***************************/

//
//
// Please don't modify anything under this line.
//
//
//

define('IN_PHPBB', true);

// Specify the path to you phpBB3 installation directory.
$phpbb_root_path = (defined('PHPBB_ROOT_PATH')) ? PHPBB_ROOT_PATH : './';
$phpEx = substr(strrchr(__FILE__, '.'), 1);

// The common.php file is required.
include($phpbb_root_path . 'common.' . $phpEx);

// since we are grabbing the user avatar, the function is inside the functions_display.php file since RC7
include($phpbb_root_path . 'includes/functions_display.' . $phpEx);

// Start session management
$user->session_begin();
$auth->acl($user->data);

// specify styles and/or localisation
$user->setup('mods/move_attachments_in_subfolders_lang');

// Variables assignment.
$ais_source_dir = $config['upload_path'];
$ais_target_dir = $ais_source_dir . '_new';
$ais_old_dir = $ais_source_dir . '_old';
$url_root_phpbb = substr($phpbb_root_path, 0, -1);
$current_page = generate_board_url(false) . '/move_attachments_in_subfolders.php';
$ais_first_id = request_var('current_id', 0);

if (!is_numeric($ais_first_id))
{
	$ais_first_id = 0;
}

$ais_reload_page = 0;

if (!file_exists($ais_source_dir . '/index.htm'))
{
	trigger_error($user->lang['AIS_NO_INDEX_HTML']);
	exit_handler();
}

$sql = 'SELECT attach_id, 
		physical_filename 
	FROM ' . ATTACHMENTS_TABLE . ' 
	WHERE attach_id >= ' . $ais_first_id.' ORDER BY attach_id ASC LIMIT 100';
		
$ais_result = $db->sql_query($sql);
$ais_affected_rows = $db->sql_affectedrows();

if ($ais_affected_rows > 0)
{
	$ais_reload_page = 1;
	
	while ($ais_current_row = $db->sql_fetchrow($ais_result))
	{	
		$ais_attachment_id = $ais_current_row['attach_id'];
		$ais_physical_filename = $ais_current_row['physical_filename'];
		$ais_thumb_filename = 'thumb_' . $ais_physical_filename;
		$ais_folder_1 = substr(substr($ais_attachment_id + 1000000, -6), 0, 2);
		$ais_folder_2 = substr(substr($ais_attachment_id + 1000000, -4), 0, 2);
		$ais_path_to_add = $ais_folder_1 . '/' . $ais_folder_2;
		
		// Creates subfolder, if not exists
		if (!file_exists($ais_target_dir))
		{
			mkdir($ais_target_dir);
			copy($ais_source_dir . '/index.htm', $ais_target_dir . '/index.htm');
		}
		
		if (!file_exists($ais_target_dir . '/' . $ais_folder_1))
		{
			mkdir($ais_target_dir . '/' . $ais_folder_1);
			copy($ais_source_dir . '/index.htm', $ais_target_dir . '/' . $ais_folder_1 . '/index.htm');
		}
		
		if (!file_exists($ais_target_dir . '/' . $ais_path_to_add))
		{
			mkdir($ais_target_dir . '/' . $ais_path_to_add);
			copy($ais_source_dir . '/index.htm', $ais_target_dir . '/' . $ais_path_to_add . '/index.htm');
		}
		
		// Copy or move the attachments on the right subfolder
		if (file_exists($ais_source_dir . '/' . $ais_physical_filename))
		{
			if($ais_move_or_copy == 1)
			{
				copy($ais_source_dir . '/' . $ais_physical_filename, $ais_target_dir . '/' . $ais_path_to_add . '/' . $ais_physical_filename);
			}
			else 
			{
				rename($ais_source_dir . '/' . $ais_physical_filename, $ais_target_dir . '/' . $ais_path_to_add . '/' . $ais_physical_filename);
			}
		}
			
		if (file_exists($ais_source_dir . '/' . $ais_thumb_filename))
		{
			if($ais_move_or_copy == 1)
			{
				copy($ais_source_dir . '/' . $ais_thumb_filename, $ais_target_dir . '/' . $ais_path_to_add . '/' . $ais_thumb_filename);
			}
			else
			{
				rename($ais_source_dir . '/' . $ais_thumb_filename, $ais_target_dir . '/' . $ais_path_to_add . '/' . $ais_thumb_filename);
			}
		}
	}
		
	$db->sql_freeresult($ais_result);
	
}

//Prepares the output
$ais_message = $user->lang['AIS_MESSAGE'] . ' : ' . $ais_attachment_id;
$ais_first_id = $ais_attachment_id + 1;

if ($ais_reload_page == 1)
{
	$ais_header = '<META HTTP-EQUIV="REFRESH" CONTENT="1; URL=' . $current_page . '?current_id=' . $ais_first_id . '">'; 
}
else
{
	$ais_header = '';
	$ais_message = $ais_message . '<br /><br />' . $user->lang['AIS_ENDMESSAGE'] . '!!!';
	rename($ais_source_dir, $ais_old_dir);
	rename($ais_target_dir, $ais_source_dir);		
}

// Send variables to template.
$template->assign_vars(array(
    'AIS_MESSAGE'		=> $ais_message,
    'AIS_HEADER'		=> $ais_header
    ));
    
// Page title, this language variable should be defined in the language file you setup at the top of this page.
page_header($user->lang['AIS_TITLE']);

// The filename of the template.
$template->set_filenames(array(
    'body' => 'move_attachments_in_subfolders.html'
));

// Completing the script and displaying the page.
page_footer();

?>
NIKON-D90, AF-S 18-105, AF-S 14-24, AF-S 24-70

Вернуться в «Бета-версии модов для phpBB 3.0.x»