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

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

Data Hooks это новый специальный тип хуков, реализованный в 3.1.

 

В отличие от других типов хуков, переопределяющих произвольные классы и функции, Data Hooks работают только в заданных точках. Но зато эти точки заданы как раз там, где любой разработчик мечтал ранее их увидеть. А именно:

 

postAddReply (Add Reply)

This is called by classPost::addReply right before a record is inserted into the posts table. The data sent is what will be inserted.

 

postAddReplyPoll (Add Reply: Poll)

This is called by classPost::addReply right before a record is inserted into the polls table. The data sent is what will be inserted.

 

postAutoMerge (Add Reply: Auto merge with previous post)

When a user posts a second post within a certain timeframe after a previous post, the second post is added to the first. postAutoMerge is called by classPost::addReply right before this happens. The data sent is an array with three parameters, "new_post" containing what we will update the post with, "post_date" containing the current unix timestamp and "pid" indicating the post ID of the previous post. You can edit "new_post" and "post_date" which will be used in an update query.

 

postAddReplyTopicUpdate (Add Reply: Topic Data)

This is called by classPost::addReply after a post has been made, right before the topic data is updated with the latest poster information. The data sent is what will be updated in the posts table.

 

postAddTopic (New Topic: Topic Data)

This is called by classPost::addTopic right before a record is inserted into the topics table. The data sent is what will be inserted.

 

postFirstPost (New Topic: First Post)

This is called by classPost:: addTopic right before a record is inserted into the posts table. The data sent is what will be inserted.

 

postAddTopicPoll (New Topic: Poll)

This is called by classPost::addTopic right before a record is inserted into the polls table. The data sent is what will be inserted.

 

editPostAddPoll (Edit Post: Added Poll)

This is called by classPost::editPost right before a record is inserted into the polls table. The data sent is what will be inserted.

 

editPostUpdatePoll (Edit Post: Updated Poll)

This is called by classPost::editPost right before a record is updated in the polls table. The data sent is what will be used in the update query.

 

editPostUpdateTopicTitle (Edit Post: Update Topic Title)

This is called by classPost::editPost right before a record is updated in the topics table. The data sent is what will be used in the update query (contains "title" and "description" elements).

 

editPostData (Edit Post: Post Data)

This is called by classPost::editPost right before a record is updated in the posts table. The data sent is what will be used in the update query.

 

updateForumLastPostData (Forum last post update data)

This is called by classPost::editPost right before a record is updated in the forums table (i.e. last poster information). The data sent is what will be used in the update query.

 

messengerSendReplyData (Messenger: Reply data)

This is called by messengerFunctions::sendReply right before a record is inserted into the message_posts table. The data sent is what will be inserted.

 

messengerSendTopicData (Messenger: New conversation, topic data)

This is called by messengerFunctions::sendNewPersonalTopic right before a record is inserted into the message_topics table. The data sent is what will be inserted.

 

messengerSendTopicFirstPostData (Messenger: New conversation, first post)

This is called by messengerFunctions::sendNewPersonalTopic right before a record is inserted into the message_posts table. The data sent is what will be inserted.

 

profileCommentNew (Profile: New comment)

This is called by profileCommentsLib::addCommentToDB right before a record is inserted into the profile_comments table. The data sent is what will be inserted.

 

profileFriendsNew (Profile: New friend)

This is called by profileFriendsLib::addFriend right before a record is inserted into the profile_friends table. The data sent is what will be inserted.

 

boardIndexCategories (Board Index Output: Categories)

This is called by public_forums_forums_boards::doExecute before the categories list is sent to the skin_board::boardIndexTemplate template. The data sent is the return value of public_forums_forums_boards::processAllCategories and what will be sent to the output.

 

boardIndexOnlineUsers (Board Index Output: Active users)

This is called by public_forums_forums_boards::doExecute before the users online list is sent to the skin_board::boardIndexTemplate template. The data sent is the return value of public_forums_forums_boards::getActiveUserDetails and what will be sent to the output.

 

forumViewData (Forum View Output)

This is called by public_forums_forums_forums::doExecute before the forum data is sent to the skin_forum::forumIndexTemplate template. The data sent is the return value of public_forums_forums_boards::showForum and what will be sent to the output.

 

topicViewPostData (Topic View Output: Posts Data)

This is called by public_forums_forums_topics::doExecute before the posts data is sent to the skin_topic::topicViewTemplate template. The data sent is what will be sent to the output.

 

topicViewForumData (Topic View Output: Forum Data)

This is called by public_forums_forums_topics::doExecute before the forum data is sent to the skin_topic::topicViewTemplate template. The data sent is what will be sent to the output.

 

topicViewTopicData (Topic View Output: Topic Data)

This is called by public_forums_forums_topics::doExecute before the topic data is sent to the skin_topic::topicViewTemplate template. The data sent is what will be sent to the output.

 

topicViewDisplayData (Topic View Output: Other Data)

This is called by public_forums_forums_topics::doExecute before the display data is sent to the skin_topic::topicViewTemplate template. The data sent is what will be sent to the output.

 

memberListData (Member List View Output)

This is called by public_members_list_view::doExecute before the member list is sent to the skin_mlist::member_list_show template. The data sent is what will be sent to the output.

 

onlineUsersListData (Online Users List Output)

This is called by public_members_online_online::_listAll before the list of members is sent to the skin_online::showOnlineList template. The data sent is what will be sent to the output.

 

Итого целых 26 сексуальных позиций, способных удовлетворить любого самого взыскательного кодера. Мало? Всегда можно запросить больше на форуме IPS.

 

Сделать хук просто. Выберите тип "Data Hook" ("Данные Модификации" на дынном языке IBR) при создании и выберите свою позицию. Принимающий файл хука должен иметь именованный вами класс с функцией handleData(), принимающей один параметр - данные перед их отправкой в БД:

 

<?php

class your_sexy_awesome_class
{
	public function handleData($sexy_data)
	{
                    return $sexy_data;
	}
}

 

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

 

Статья на IPS.

 

К чему я это? Как бы намекаю, что написать свой мод скрытого текста под тройку без модификации кода теперь сможет каждый школьник ;)

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

Сраные кретины. Ничего нормально сделать не могут.

 

Пока не выпустят патч, скрытого текста под 3.1 не будет.

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

О да! Я тоже нагеморроился с этим getPostContentPreFormatted.

Идея вроде хорошая, но в модификациях мешается адски.

 

По всей видимости, временно можно обходить эту проблему путем дропа кеша поста.

Костыли-костыли.

 

"Данные Модификации"

Бггггггг)))

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

Вы не поверите, "так и задумано". Сделали красивый хук просто для отвода глаз - то что практической пользы от такой реализации postAddReply нет разрабов не колышет.
Ссылка на комментарий
Поделиться на других сайтах

Покопался в коде. Вообще, их логику можно понять в данном случае.

Этот хук нужен прежде всего для того, чтобы добавлять простые дополнительные поля. Без радикального вмешательства в стандартные сущности.

 

Чтобы вмешаться в сам пост предполагается перегружать compilePostData. Там же можно сбросить preFormatted при необходимости.

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

Чтобы вмешаться в сам пост предполагается перегружать compilePostData.

Если бы это было так, данный метод не был бы protected. До появления Data Hook не было возможности (кроме переопределения $_POST) вмешаться в процесс. И с его внедрением ничего не изменилось :(

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

Да. Бета-тестеры уже тестируют, не жалуются :)

И я хочууууу...)))...А то 90 процентов хайда теперь просто не отображается..(((

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

И с его внедрением ничего не изменилось

У меня все работает через Library hook, или как там его.

Отлично перегружаются любые методы внутри classPost\classPostForms.

 

Ближе к вечеру выложу.

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

Это песня вообще.) Library hook реально работает дай бог в половине мест. В остальных банально забыли заменить require_once на функцию-обертку.

 

Also, IPB жиреет прямо на глазах. По сравнению с 3.0, во все основные места дописали еще по 20-40 строчек. Какое-то мягкое удаление и т.п. фигня. Что же дальше-то будет?)

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

Вот еще меня один вопрос все мучает.

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

 

Но, в общем, согласно профайлеру, это не так. На "сложном" посте размером в 10Кб с кучей тегов парсер проигрывает версии 2.3 в несколько раз. Очень много объектов и вызовов "дешевых" функций. Плюс известные проблемы со вложенностью (хардкод условия $iteration > 50).

 

Кто-нибудь может объяснить, откуда в принципе взялись такие сложности с бб-кодами? Единственный тег, которому реально нужна вложенность - quote.

Так в чем проблема собирать вообще все бб-коды одной регуляркой через preg_replace_callback, отдавая содержимое в общую функцию, которая выполнит проверки и передаст данные в функцию специализированную?

 

И не нужны никакие сотни объектов. И бедный strpos крутить не надо по сто раз.

 

Да, конечно, нельзя будет писать всякий бред, типа:

[b]Тест [b] мурк [/b] няя! [/b]

- но есть ли в этом практическая необходимость? Quote можно отдельно покрутить.

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

Парсер - это отдельная песня. Об этом мы уже общались с LastDragon в теме про эксплоиты. Помимо низкой скорости работы и требовательности к ресурсам такой подход еще и дыряв как дуршлаг. Трижды pwn'ил официальную доску именно благодаря новому парсеру :D
Ссылка на комментарий
Поделиться на других сайтах

Дайте линку на тему про эксплойты. ^__^

 

Темы про безопасность меня тоже поражают постоянно. 90% дыр появляются от того, что либо нет централизованной фильтрации, либо она НЕ танцует от правила "запрещено всё, что не разрешено".

 

В чем проблема сделать один убогий вызов htmlspecialchars с ENT_QUOTES, а затем, если тебе очень нужные какие-то из спец-символов в сильно хитром бб-коде, вручную и очень аккуратно вернуть их обратно?

 

Неееет. Вместо этого надо накрутить что-нибудь в таком роде:

 

		//-----------------------------------------
	// Here we can do some generic checking for XSS
	// This should not be considered fool proof, though can provide
	//	a centralized point for maintenance and checking
	//-----------------------------------------

	$txt = preg_replace( "/(j)avascript/i" , "\\1avascript", $txt );
	//$txt = str_ireplace( "alert"      , "alert"          , $txt );
	$txt = str_ireplace( "behavior"   , "behavior"    	  , $txt );
	$txt = preg_replace( "/(e)((\/\*.*?\*\/)*)x((\/\*.*?\*\/)*)p((\/\*.*?\*\/)*)r((\/\*.*?\*\/)*)e((\/\*.*?\*\/)*)s((\/\*.*?\*\/)*)s((\/\*.*?\*\/)*)i((\/\*.*?\*\/)*)o((\/\*.*?\*\/)*)n/is" , "\\1xp<b></b>ression"     , $txt );
	$txt = preg_replace( "/(e)((\\\|\)*)x((\\\|\)*)p((\\\|\)*)r((\\\|\)*)e((\\\|\)*)s((\\\|\)*)s((\\\|\)*)i((\\\|\)*)o((\\\|\)*)n/is" 	  , "\\1xp<b></b>ression"     	  , $txt );
	$txt = preg_replace( "/m((\\\|\)*)o((\\\|\)*)z((\\\|\)*)\-((\\\|\)*)b((\\\|\)*)i((\\\|\)*)n((\\\|\)*)d((\\\|\)*)i((\\\|\)*)n((\\\|\)*)g/is" 	  , "moz-<b></b>binding"     	  , $txt );
	$txt = str_ireplace( "about:"     , "about:"         , $txt );
	$txt = str_ireplace( "<body"      , "<body"            , $txt );
	$txt = str_ireplace( "<html"      , "<html"            , $txt );
	$txt = str_ireplace( "document." , "document."      , $txt );
	$txt = str_ireplace( "window."   , "window."      , $txt );

	$event_handlers	= array( 'mouseover', 'mouseout', 'mouseup', 'mousemove', 'mousedown', 'mouseenter', 'mouseleave', 'mousewheel',
							 'contextmenu', 'click', 'dblclick', 'load', 'unload', 'submit', 'blur', 'focus', 'resize', 'scroll',
							 'change', 'reset', 'select', 'selectionchange', 'selectstart', 'start', 'stop', 'keydown', 'keyup',
							 'keypress', 'abort', 'error', 'dragdrop', 'move', 'moveend', 'movestart', 'activate', 'afterprint',
							 'afterupdate', 'beforeactivate', 'beforecopy', 'beforecut', 'beforedeactivate', 'beforeeditfocus',
							 'beforepaste', 'beforeprint', 'beforeunload', 'begin', 'bounce', 'cellchange', 'controlselect',
							 'copy', 'cut', 'paste', 'dataavailable', 'datasetchanged', 'datasetcomplete', 'deactivate', 'drag',
							 'dragend', 'dragleave', 'dragenter', 'dragover', 'drop', 'end', 'errorupdate', 'filterchange', 'finish',
							 'focusin', 'focusout', 'help', 'layoutcomplete', 'losecapture', 'mediacomplete', 'mediaerror', 'outofsync',
							 'pause', 'propertychange', 'progress', 'readystatechange', 'repeat', 'resizeend', 'resizestart', 'resume',
							 'reverse', 'rowsenter', 'rowexit', 'rowdelete', 'rowinserted', 'seek', 'syncrestored', 'timeerror',
							 'trackchange', 'urlflip',
							);

	foreach( $event_handlers as $handler )
	{
		$txt = str_ireplace( 'on' . $handler, 'on' . $handler, $txt );
	}

 

Кстати, лол. Вгляделся в скопированный код. Тут половина строк ничего не делает.

Ну максимум - заменяет большие буквы на маленькие. :crazy:

 

И 4 preg_replace крутятся на каждый option каждого тега.

 

Йесс.

 

Или вот в чем сакральный смысл этого действия?

$txt = preg_replace( "/(j)avascript/i" , "\\1avascript", $txt );

 

Насколько я понимаю, это регистронезависимая замена строки 'javascript' на 'javascript'?)) Почему не strtolower или str_ireplace?

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

Аххах) Я - дерево. :lol:

Кстати, баг! Внутри code все должно сохраняться. :P Иначе нафиг он нужен?

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

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

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

Гость
Ответить в этой теме...

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

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

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

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

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

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

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

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