1. PHP / Говнокод #27657

    +1

    1. 1
    $bIsExpressDelivery = !empty($arDeliveryTariff["UF_EXPRESS_DELIVERY"]) ? true : false;

    Чтобы наверняка true или наверняка false...

    alexxrin, 11 Сентября 2021

    Комментарии (5)
  2. PHP / Говнокод #27654

    0

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    25. 25
    26. 26
    27. 27
    28. 28
    29. 29
    30. 30
    31. 31
    32. 32
    33. 33
    34. 34
    35. 35
    36. 36
    37. 37
    38. 38
    39. 39
    40. 40
    41. 41
    42. 42
    43. 43
    /**
         * Возвращает сумму прописью
         * @param $num
         * @return string
         */
        public static function num2str($num) {
            $nul='ноль';
            $ten=[
                ['','один','два','три','четыре','пять','шесть','семь', 'восемь','девять'],
                ['','одна','две','три','четыре','пять','шесть','семь', 'восемь','девять'],
            ];
            $a20=['десять','одиннадцать','двенадцать','тринадцать','четырнадцать' ,'пятнадцать','шестнадцать','семнадцать','восемнадцать','девятнадцать'];
            $tens=[2=>'двадцать','тридцать','сорок','пятьдесят','шестьдесят','семьдесят' ,'восемьдесят','девяносто'];
            $hundred=['','сто','двести','триста','четыреста','пятьсот','шестьсот', 'семьсот','восемьсот','девятьсот'];
            $unit=[ // Units
                ['копейка' ,'копейки' ,'копеек',	 1],
                ['рубль'   ,'рубля'   ,'рублей'    ,0],
                ['тысяча'  ,'тысячи'  ,'тысяч'     ,1],
                ['миллион' ,'миллиона','миллионов' ,0],
                ['миллиард','милиарда','миллиардов',0],
            ];
            //
            list($rub,$kop) = explode('.',sprintf("%015.2f", floatval($num)));
            $out = [];
            if (intval($rub)>0) {
                foreach(str_split($rub,3) as $uk=>$v) { // by 3 symbols
                    if (!intval($v)) continue;
                    $uk = sizeof($unit)-$uk-1; // unit key
                    $gender = $unit[$uk][3];
                    list($i1,$i2,$i3) = array_map('intval',str_split($v,1));
                    // mega-logic
                    $out[] = $hundred[$i1]; # 1xx-9xx
                    if ($i2>1) $out[]= $tens[$i2].' '.$ten[$gender][$i3]; # 20-99
                    else $out[]= $i2>0 ? $a20[$i3] : $ten[$gender][$i3]; # 10-19 | 1-9
                    // units without rub & kop
                    if ($uk>1) $out[]= self::morph($v,$unit[$uk][0],$unit[$uk][1],$unit[$uk][2]);
                } //foreach
            }
            else $out[] = $nul;
            $out[] = self::morph(intval($rub), $unit[1][0],$unit[1][1],$unit[1][2]); // rub
            $out[] = $kop.' '.self::morph($kop,$unit[0][0],$unit[0][1],$unit[0][2]); // kop
            return trim(preg_replace('/ {2,}/', ' ', join(' ',$out)));
        }

    Один большой проект...

    TrueGameover, 10 Сентября 2021

    Комментарии (5)
  3. PHP / Говнокод #27634

    0

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    switch ($group) {
            case 'Root':
                break;
            case 'Admin':
                break;
            case 'Accountant':
                break;
            case 'Manager':
                break;
            }
    
    return $group;

    Вот так можно проверить что ничего не надо делать

    zoorg, 01 Сентября 2021

    Комментарии (10)
  4. PHP / Говнокод #27582

    +2

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    25. 25
    26. 26
    27. 27
    28. 28
    29. 29
    30. 30
    31. 31
    32. 32
    33. 33
    34. 34
    35. 35
    36. 36
    37. 37
    38. 38
    39. 39
    40. 40
    41. 41
    42. 42
    43. 43
    44. 44
    45. 45
    46. 46
    47. 47
    48. 48
    49. 49
    50. 50
    if($account['lvl']=="1"){ $exp=round($account['exp']*100/52);}
    if($account['lvl']=="2"){ $exp=round((($account['exp']-52)/(110))*100,2);}
    if($account['lvl']=="3"){ $exp=round((($account['exp']-135)/(832-135))*100,2);}
    if($account['lvl']=="4"){ $exp=round((($account['exp']-832)/(3547-832))*100,2);}
    if($account['lvl']=="5"){ $exp=round((($account['exp']-3547)/(9658-3547))*100,2);}
    if($account['lvl']=="6"){ $exp=round((($account['exp']-9658)/(15478-9658))*100,2);}
    if($account['lvl']=="7"){ $exp=round((($account['exp']-15478)/(18478-15478))*100,2);}
    if($account['lvl']=="8"){ $exp=round((($account['exp']-18478)/(30789-18478))*100,2);}
    if($account['lvl']=="9"){ $exp=round((($account['exp']-30789)/(72394-30789))*100,2);}
    if($account['lvl']=="10"){ $exp=round((($account['exp']-72394)/(138789-72394))*100,2);}
    if($account['lvl']=="11"){ $exp=round((($account['exp']-138789)/(214787-138789))*100,2);}
    if($account['lvl']=="12"){ $exp=round((($account['exp']-214787)/(398747-214787))*100,2);}
    if($account['lvl']=="13"){ $exp=round((($account['exp']-398747)/(587058-398747))*100,2);}
    if($account['lvl']=="14"){ $exp=round((($account['exp']-587058)/(824585-587058))*100,2);}
    if($account['lvl']=="15"){ $exp=round((($account['exp']-824585)/(1247858-824585))*100,2);}
    if($account['lvl']=="16"){ $exp=round((($account['exp']-1247858)/(1558789-1247858))*100,2);}
    if($account['lvl']=="17"){ $exp=round((($account['exp']-1558789)/(1985478-1558789))*100,2);}
    if($account['lvl']=="18"){ $exp=round((($account['exp']-1985478)/(2245857-1985478))*100,2);}
    if($account['lvl']=="19"){ $exp=round((($account['exp']-2245857)/(2785896-2245857))*100,2);}
    if($account['lvl']=="20"){ $exp=round((($account['exp']-2785896)/(3685478-2785896))*100,2);}
    if($account['lvl']=="21"){ $exp=round((($account['exp']-3685478)/(4169875-3685478))*100,2);}
    if($account['lvl']=="22"){ $exp=round((($account['exp']-4169875)/(5125478-4169875))*100,2);}
    if($account['lvl']=="23"){ $exp=round((($account['exp']-5125478)/(5999999-5125478))*100,2);}
    if($account['lvl']=="24"){ $exp=round((($account['exp']-5999999)/(7145877-5999999))*100,2);}
    if($account['lvl']=="25"){ $exp=round((($account['exp']-7145877)/(8791755-7145877))*100,2);}
    if($account['lvl']=="26"){ $exp=round((($account['exp']-8791755)/(10691755-8791755))*100,2);}
    if($account['lvl']=="27"){ $exp=round((($account['exp']-10691755)/(12791755-10691755))*100,2);}
    if($account['lvl']=="28"){ $exp=round((($account['exp']-12791755)/(15191755-12791755))*100,2);}
    if($account['lvl']=="29"){ $exp=round((($account['exp']-15191755)/(18091755-15191755))*100,2);}
    if($account['lvl']=="30"){ $exp=round((($account['exp']-18091755)/(21191755-18091755))*100,2);}
    if($account['lvl']=="31"){ $exp=round((($account['exp']-21191755)/(24491755-21191755))*100,2);}
    if($account['lvl']=="32"){ $exp=round((($account['exp']-24491755)/(27991755-24491755))*100,2);}
    if($account['lvl']=="33"){ $exp=round((($account['exp']-27991755)/(31691755-27991755))*100,2);}
    if($account['lvl']=="34"){ $exp=round((($account['exp']-31691755)/(35791755-31691755))*100,2);}
    if($account['lvl']=="35"){ $exp=round((($account['exp']-35791755)/(40391755-35791755))*100,2);}
    if($account['lvl']=="36"){ $exp=round((($account['exp']-40391755)/(45591755-40391755))*100,2);}
    if($account['lvl']=="37"){ $exp=round((($account['exp']-45591755)/(51491755-45591755))*100,2);}
    if($account['lvl']=="38"){ $exp=round((($account['exp']-51491755)/(58191755-51491755))*100,2);}
    if($account['lvl']=="39"){ $exp=round((($account['exp']-58191755)/(65791755-58191755))*100,2);}
    if($account['lvl']=="40"){ $exp=round((($account['exp']-65791755)/(74391755-65791755))*100,2);}
    if($account['lvl']=="41"){ $exp=round((($account['exp']-74391755)/(83991755-74391755))*100,2);}
    if($account['lvl']=="42"){ $exp=round((($account['exp']-83991755)/(94591755-83991755))*100,2);}
    if($account['lvl']=="43"){ $exp=round((($account['exp']-94591755)/(106191755-94591755))*100,2);}
    if($account['lvl']=="44"){ $exp=round((($account['exp']-106191755)/(118791755-106191755))*100,2);}
    if($account['lvl']=="45"){ $exp=round((($account['exp']-118791755)/(132391755-118791755))*100,2);}
    if($account['lvl']=="46"){ $exp=round((($account['exp']-132391755)/(146991755-132391755))*100,2);}
    if($account['lvl']=="47"){ $exp=round((($account['exp']-146991755)/(162591755-146991755))*100,2);}
    if($account['lvl']=="48"){ $exp=round((($account['exp']-162591755)/(179191755-162591755))*100,2);}
    if($account['lvl']=="49"){ $exp=round((($account['exp']-179191755)/(196791755-179191755))*100,2);}
    if($account['lvl']=="50"){ $exp=round((($account['exp']-196791755)/(215391755-196791755))*100,2);}

    Расчет % заполнения шкалы уровня в зависимости от опыта

    EndoCrinolog, 20 Августа 2021

    Комментарии (26)
  5. PHP / Говнокод #27531

    +3

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    25. 25
    26. 26
    27. 27
    28. 28
    29. 29
    30. 30
    31. 31
    32. 32
    33. 33
    34. 34
    35. 35
    36. 36
    37. 37
    do {           
                $entries = $xpath->query("//div[@class='identity']/img");
                if(isset($entries[0])) break;
                $entries = $xpath->query("//h1[@class='avatared']/a/img");
                if(isset($entries[0])) break;
                $entries = $xpath->query("//div[@class='avatared']/a/img");
                if(isset($entries[0])) break;
                $entries = $xpath->query("//div[@itemtype='http://schema.org/Person']/a/img");
            } while(false);
            if(!isset($entries[0])) continue;
    
            $src = $entries[0]->getAttribute('src');
            if(!preg_match('#[/=]([0-9a-f]{32})[\?&]#', $src, $matches)) continue;
            $hash = $matches[1];
    
    // спустя несколько строк
    
            do {           
                $entries = $xpath->query("//div[@class='email']/script");
                if(isset($entries[0])) break;
                $entries = $xpath->query("//dl/dd[@class='email']/script");
            } while(false);
            if(isset($entries[0])) {
                $rawcode = $entries[0]->textContent;
                if(!preg_match("#eval\(decodeURIComponent\('(.*)'\)\)#", $rawcode, $matches)) continue;
                $rawcode2 = urldecode($matches[1]);
                if(!preg_match('#href=\\\\?"mailto:([^"\\\\]*)\\\\?"#', $rawcode2, $matches)) continue;
                $email = $matches[1];
                unset($entries);
            } else do {
                $entries = $xpath->query("//div[@class='avatared']/div[@class='details']/dl/dd/a[@data-email]");
                if(isset($entries[0])) break;
                $entries = $xpath->query("//ul[@class='vcard-details']/li[@class='vcard-detail']/a[@data-email]");
            } while(false);
            if(isset($entries[0])) {
                $email = urldecode($entries[0]->getAttribute('data-email'));
            }

    Прототип программы, вытягивающей хэш аватарки и е-мейл из архивной копии профиля в «Гитхабе».

    Nyancat, 21 Июля 2021

    Комментарии (5)
  6. PHP / Говнокод #27506

    +3

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    $a != abs($a)
    $a+abs($a) == 0
    $a && !($a + abs($a))
    $n>>1 > $n
    substr_count($a,"-")
    is_nan(sqrt($number))
    is_nan(log($n))
    !array_shift(explode("-", $num))
    (int)$var === ~~(int)$var
    strlen(strval($num)) != strlen(strval(abs($num)))
    strlen(decbin($n)) == 32
    is_int(strpos(get_headers("http://habrahabr.ru/blogs/php/page$num/")[0], '404'));
    
    function lessThanZero ($num) {
        while (1) {
            if ($num++ == 0) {
                return true;
            }
        }
    }
    
    function is_value_between($value, $begin, $end) {
        return in_array($value, range($begin,$end));
    }

    "Как проверять отрицательное ли число ?
    В мануале в математических функциях не нашёл ."

    https://php.ru/forum/threads/kak-proverjat-otricatelnoe-li-chislo.8208/

    kezzyhko, 09 Июля 2021

    Комментарии (74)
  7. PHP / Говнокод #27502

    +1

    1. 1
    2. 2
    3. 3
    4. 4
    public function isBooted()
    {
        return true === $this->booted;
    }

    Дичь

    deenmluzsxbpg, 07 Июля 2021

    Комментарии (42)
  8. PHP / Говнокод #27492

    +1

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    25. 25
    26. 26
    27. 27
    <?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 ......

    crazzy501, 30 Июня 2021

    Комментарии (56)
  9. PHP / Говнокод #27422

    +2

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    25. 25
    26. 26
    27. 27
    28. 28
    29. 29
    30. 30
    31. 31
    32. 32
    33. 33
    34. 34
    35. 35
    36. 36
    37. 37
    38. 38
    39. 39
    <?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 не в конце функции?

    3_dar, 12 Мая 2021

    Комментарии (9)
  10. PHP / Говнокод #27390

    0

    1. 001
    2. 002
    3. 003
    4. 004
    5. 005
    6. 006
    7. 007
    8. 008
    9. 009
    10. 010
    11. 011
    12. 012
    13. 013
    14. 014
    15. 015
    16. 016
    17. 017
    18. 018
    19. 019
    20. 020
    21. 021
    22. 022
    23. 023
    24. 024
    25. 025
    26. 026
    27. 027
    28. 028
    29. 029
    30. 030
    31. 031
    32. 032
    33. 033
    34. 034
    35. 035
    36. 036
    37. 037
    38. 038
    39. 039
    40. 040
    41. 041
    42. 042
    43. 043
    44. 044
    45. 045
    46. 046
    47. 047
    48. 048
    49. 049
    50. 050
    51. 051
    52. 052
    53. 053
    54. 054
    55. 055
    56. 056
    57. 057
    58. 058
    59. 059
    60. 060
    61. 061
    62. 062
    63. 063
    64. 064
    65. 065
    66. 066
    67. 067
    68. 068
    69. 069
    70. 070
    71. 071
    72. 072
    73. 073
    74. 074
    75. 075
    76. 076
    77. 077
    78. 078
    79. 079
    80. 080
    81. 081
    82. 082
    83. 083
    84. 084
    85. 085
    86. 086
    87. 087
    88. 088
    89. 089
    90. 090
    91. 091
    92. 092
    93. 093
    94. 094
    95. 095
    96. 096
    97. 097
    98. 098
    99. 099
    100. 100
    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;
    	} // ...
    }

    Зачем в методах класса вообще использовать глобальные изменяемые состояния, если это нарушает принцип инкапсуляции (для обеспечения чего и была введена абстракция класса в языки)? И сидишь гадаешь, при вызове какого метода у какого объекта у тебя слетела верстка, контент и пр. Это усложняет написание безопасных расширений для системы.

    JaneBurt, 03 Мая 2021

    Комментарии (11)