- 1
- 2
- 3
- 4
public function isBooted()
{
return true === $this->booted;
}
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
+1
public function isBooted()
{
return true === $this->booted;
}
Дичь
+1
<?php
// bitrix/modules/main/classes/mysql/database.php:: 176
if(!$result)
{
.......
if(!$bIgnoreErrors)
{
.......
if(file_exists($_SERVER["DOCUMENT_ROOT"].BX_PERSONAL_ROOT."/php_interface/dbquery_error.php"))
include($_SERVER["DOCUMENT_ROOT"].BX_PERSONAL_ROOT."/php_interface/dbquery_error.php");
elseif(file_exists($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/dbquery_error.php"))
include($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/dbquery_error.php");
else
die("MySQL Query Error!");
die();
}
return false;
}
// bitrix/modules/main/include/dbquery_error.php
<br>
<table>
//верстка html страницы со вставками переменных через <?= ?>
</table>
Исключения? Не, не слышали. Пусть конечный разработчик голову ломает, почему он не может отловить MySQL Query Error [1062] Duplicate entry ......
+2
<?php
function syoma_verify_spam($comment_post_ID) {
// NOTE: На telegram этот метод не вызывается
$content = trim($_POST['comment']);
if (preg_match('#<a href=#', $content) && !preg_match('#\[code#', $content)) {
die('Ня, пока.');
}
$content = strip_tags(apply_filters('gk_content', $content));
$content = strtr($content, array(
'A' => 'А',
'a' => 'а',
'B' => 'В',
'E' => 'Е',
'e' => 'е',
'3' => 'З',
'K' => 'К',
'k' => 'к',
'M' => 'М',
'H' => 'Н',
'O' => 'О',
'o' => 'о',
'P' => 'Р',
'p' => 'р',
'C' => 'С',
'c' => 'с',
'T' => 'Т',
'Y' => 'У',
'y' => 'у',
'X' => 'Х',
'x' => 'х',
'b' => 'ь',
));
$content = mb_strtolower($content);
if (preg_match('#русня|хуйло|ватник|ватный|пидораш|пидорах#', $content)) {
die('Рус-ня, пока.');
}
}
Угадайте, почему фильтрация <a href не в конце функции?
0
class MediaWiki {
// Поля, другие методы
private function performRequest() {
global $wgTitle;
$request = $this->context->getRequest();
$requestTitle = $title = $this->context->getTitle();
$output = $this->context->getOutput();
$user = $this->context->getUser();
if ( $request->getVal( 'printable' ) === 'yes' ) {
$output->setPrintable();
}
$this->getHookRunner()->onBeforeInitialize( $title, null, $output, $user, $request, $this );
// Invalid titles. T23776: The interwikis must redirect even if the page name is empty.
if ( $title === null || ( $title->getDBkey() == '' && !$title->isExternal() )
|| $title->isSpecial( 'Badtitle' )
) {
$this->context->setTitle( SpecialPage::getTitleFor( 'Badtitle' ) );
try {
$this->parseTitle();
} catch ( MalformedTitleException $ex ) {
throw new BadTitleError( $ex );
}
throw new BadTitleError();
}
// Check user's permissions to read this page.
// We have to check here to catch special pages etc.
// We will check again in Article::view().
$permissionStatus = PermissionStatus::newEmpty();
if ( !$this->context->getAuthority()->authorizeRead( 'read', $title, $permissionStatus ) ) {
// T34276: allowing the skin to generate output with $wgTitle or
// $this->context->title set to the input title would allow anonymous users to
// determine whether a page exists, potentially leaking private data. In fact, the
// curid and oldid request parameters would allow page titles to be enumerated even
// when they are not guessable. So we reset the title to Special:Badtitle before the
// permissions error is displayed.
// The skin mostly uses $this->context->getTitle() these days, but some extensions
// still use $wgTitle.
$badTitle = SpecialPage::getTitleFor( 'Badtitle' );
$this->context->setTitle( $badTitle );
$wgTitle = $badTitle;
throw new PermissionsError( 'read', $permissionStatus );
}
// Еще какая-то логика для хандлинга редиректов по заголовкам страниц
}
// ...
}
// ...
class MessageCache implements LoggerAwareInterface {
// ...
public function parse( $text, $title = null, $linestart = true,
$interface = false, $language = null
) {
global $wgTitle;
if ( $this->mInParser ) {
return htmlspecialchars( $text );
}
$parser = $this->getParser();
$popts = $this->getParserOptions();
$popts->setInterfaceMessage( $interface );
if ( is_string( $language ) ) {
$language = $this->langFactory->getLanguage( $language );
}
$popts->setTargetLanguage( $language );
if ( !$title || !$title instanceof Title ) {
$logger = LoggerFactory::getInstance( 'GlobalTitleFail' );
$logger->info(
__METHOD__ . ' called with no title set.',
[ 'exception' => new Exception ]
);
$title = $wgTitle;
}
// Sometimes $wgTitle isn't set either...
if ( !$title ) {
# It's not uncommon having a null $wgTitle in scripts. See r80898
# Create a ghost title in such case
$title = Title::makeTitle( NS_SPECIAL, 'Badtitle/title not set in ' . __METHOD__ );
}
$this->mInParser = true;
$res = $parser->parse( $text, $title, $popts, $linestart );
$this->mInParser = false;
return $res;
} // ...
}
Зачем в методах класса вообще использовать глобальные изменяемые состояния, если это нарушает принцип инкапсуляции (для обеспечения чего и была введена абстракция класса в языки)? И сидишь гадаешь, при вызове какого метода у какого объекта у тебя слетела верстка, контент и пр. Это усложняет написание безопасных расширений для системы.
−1
https://thestreetjournal.org/2021/04/chinese-authorities-seize-7221-human-penises-on-cargo-ship-from-nigeria/
7221 камерунских шоколадных зайцев пострадало.
0
public function addMoney($name, $amount, $type)
{
$checkExist = $this->checkUserMoney($name);
$checkExist = ($checkExist != '<b>(Ico)</b> <h11 style=\"color: red\">Произошла ошибка!</h11> <br/>') ? true : false;
$name_uuid = $this->genUUID($name);
if ($this->version == '1.12.2' AND $this->plugin != 'iconomy')
{
if ($checkExist)
{
if ($type == 'add')
{
$queryText = ($this->plugin == 'economylite') ? "UPDATE `economyliteplayers` SET `balance` = `balance` + '$amount' WHERE `uuid` = '$name_uuid' AND `currency` = 'economylite:coin'"
: "UPDATE `{$this->table}` SET `money` = `money` + '$amount' WHERE `player_name` = '$name'";
} else
{
$queryText = ($this->plugin == 'economylite') ? "UPDATE `economyliteplayers` SET `balance` = '$amount' WHERE `uuid` = '$name_uuid' AND `currency` = 'economylite:coin'"
: "UPDATE `{$this->table}` SET `money` = '$amount' WHERE `player_name` = '$name'";
}
} else
{
$queryText = ($this->plugin == 'economylite') ? "INSERT INTO `economyliteplayers` (`uuid`, `balance`, `currency`) VALUES ('$name_uuid', '$amount', 'economylite:coin')"
: "INSERT INTO `{$this->table}` (`player_uuid`, `player_name`, `money`, `sync_complete`, `last_seen`) VALUES ('$name_uuid', '$name', '$amount', 'true', '0')";
}
} else
{
if ($checkExist)
{
$queryText = ($type == 'add') ? "UPDATE `{$this->table}` SET `balance` = `balance` + $amount WHERE `username` = '$name'"
: "UPDATE `{$this->table}` SET `balance` = $amount WHERE `username` = '$name'";
} else
{
$queryText = "INSERT INTO `{$this->table}` (`username`, `balance`) VALUES ('$name', $amount)";
}
}
echo $queryText;
$data = siteQuery($queryText, 'query', $this->mysqli);
$text = ($data != NULL) ? "<b>(Ico)</b> <h11 style=\"color: green\">Игроку $name успешно начисленно: $amount эмеральдов!</h11> <br/>"
: '<b>(Ico)</b> <h11 style="color: red">Произошла ошибка!</h11> <br/>';
return $text;
}
public function checkUserMoney($name)
{
$name_uuid = $this->genUUID($name);
if ($this->version == '1.12.2' AND $this->plugin != 'iconomy')
{
$queryText = ($this->plugin == 'economylite') ? "SELECT `balance` FROM `economyliteplayers` WHERE `uuid` = '{$name_uuid}' AND `currency` = 'economylite:coin'"
: "SELECT `money` as 'balance' FROM `{$this->table}` WHERE `player_name` = '{$name}'";
} else
{
$queryText = "SELECT `balance` FROM `{$this->table}` WHERE `username` = '{$name}'";
}
$data = siteQuery($queryText, 'assoc', $this->mysqli);
$text = ($data != NULL) ? "<b>(Ico)</b> <h11 style=\"color: green\">Балланс игрока $name: {$data['balance']} эмеральдов!</h11> <br/>"
: '<b>(Ico)</b> <h11 style=\"color: red\">Произошла ошибка!</h11> <br/>';
return $text;
}
Этот говнокод кодил наш сотрудник https://vk.com/valiev_off, здесь вы можете наблюдать мастерские SQL запросы под тернарным соусом
+1
// если пользователь авторизован
if($user->get('id')) {
$_SESSION['city-select'] = '';
// если пользователь авторизован - определяем город
$profile = $user->getOne('Profile');
if ($profile) {
$city = $profile->get('city');
}
// проходим все города и ищем подходящий
$cities = $modx->runSnippet('pdoResources', array(
'parents' => 205,
'limit' => 0,
'includeTVs' => 'setCityForHome',
'where' => '{ "template" : "25" }',
'tpl' => '@CODE:{"id":"[[+id]]","city":"[[+tv.setCityForHome]]"}',
'outputSeparator' => ','
));
$redirectTo = 0;
if($cities) {
$cities = $modx->fromJson('['.$cities.']');
foreach( $cities as $c ) {
if($c['city'] == $city) {
$redirectTo = $c['id'];
break;
}
}
}
} else {
// если не авторизован - проверяем сессию
$session = $_SESSION['city-select'];
// если сессия пустая - проверяем, на какой странице находимся
// если страница города и пустая сессия - записываем в сессию
if($modx->resource->get('template') == 25) {
$_SESSION['city-select'] = $modx->resource->get('pagetitle');
$city = $modx->resource->get('pagetitle');
} else {
$city = (!empty($_SESSION['city-select']))? $_SESSION['city-select'] : $city;
}
}
Сумрачный гений, сука. Строки 11-28 особенно примечательны.
0
function isRegEx($test)
{
$notThisLine = error_get_last();
$notThisLine = isset($notThisLine['line']) ? $notThisLine['line'] + 0 : 0;
while (($lines = rand(1, 100)) == $notThisLine);
eval(
str_repeat("\n", $lines) .
'@preg_match(\'' . addslashes($test) . '\', \'\');'
);
$check = error_get_last();
$check = isset($check['line']) ? $check['line'] + 0 : 0;
return $check == $notThisLine;
}
"Test if a regular expression is a valid one in PHP"
https://stackoverflow.com/a/15143479/6702274
+1
$query = "
SELECT
`version`, `mods`, `plugins`, `keywords`
WHERE
`version` = {$version}";
foreach (explode(",", $mods) as $mod)
{
$query += "AND `mods` LIKE '{$mod}' OR `mods` LIKE '{$mod},%' OR `mods` LIKE '%,{$mod},%' OR `mods` LIKE '%,{$mod}'";
}
foreach (explode(",", $plugins) as $plugin)
{
$query += "AND `plugins` LIKE '{$plugin}' OR `plugins` LIKE '{$plugin},%' OR `plugins` LIKE '%,{$plugin},%' OR `plugins` LIKE '%,{$plugin}'";
}
Говнокод чтобы прогнать массив с id записей внутри varchar по массиву с id записей из переменной (id,id,id)
−1
https://www.kp.ru/online/news/4203427/
Ко-ко-кой багор)