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

    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
    <?php
    /* -= Developed by [email protected] =- */
    // -= О П Ц И И =-
    require("config.php");
    // Технические настройки скрипта
    header('Content-Type: text/html; charset=utf-8');
    ini_set('memory_limit', '-1');
    // -=-=-=-=-=-=-=-
    
    // -= Функции инкапсуляции технических аспектов =-
    // Функция печати логов, добавляет "date n time now" и перенос строки
    function printLog($text) { echo sprintf("[%s] %s", date("Y-m-d H:i:s"), $text) . "\n"; }
    // Функция преобразования текста в ключ индекса, убирает пробелы, переводит в верхний регистр и добавляет префикс "_"
    function str2idx($str) { return "_" . strtoupper( str_replace(' ', '', (string)$str) ); }
    // Функция генерации ассоциативного массива индексов, использует str2idx
    function genIdxs($array, $val_key, $idx_keys, $filter_func=NULL) {
        $idxs = [];
        foreach ($array as $item) {
        	if ($filter_func && !$filter_func($item)) { continue; } 
        	if (is_string($idx_keys)){
        		foreach (preg_split("/\s?;\s?/", $item[$idx_keys]) as $idx) {
        			if ($idx) { $idxs[str2idx($idx)] = str2idx((string)$item[$val_key]); }
        		} unset($idx);
        	} else {
        		foreach ($idx_keys as $idx_key) {
        			foreach (preg_split("/\s?;\s?/", $item[$idx_key]) as $idx) {
        				if ($idx) { $idxs[str2idx($idx)] = str2idx((string)$item[$val_key]); }
        			}
        		} unset($idx_key);
        	}
        } unset($item);
        return $idxs;
    }
    // Функция сравнения изображений
    function compareImages($image1, $image2) {
        $compare_result = $image1->compareImages($image2, IMAGICK_METRIC);
        return (int)$compare_result[1] > THRESHOLD_SIMILARITY_VALUE;
    }
    // Функция исполнения SQL-запросов в БД, инкапсулирующая все ужасы взаимодействия с БД MySQL на PHP
    function execSQL($sql, $mode="fetch_assoc") {
        // Проверяем коннект к БД, в случае проблем - пытаемся переподключ
        if (!$GLOBALS["mysqli"] || $GLOBALS["mysqli"]->connect_errno) { 
        	$GLOBALS["mysqli"] = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME); 
        	if ($GLOBALS["mysqli"]->connect_errno) {
        		throw new Exception("Can't connect to DB: (".$GLOBALS["mysqli"]->connect_errno.") ".$GLOBALS["mysqli"]->connect_error);
        	}
        	printf("default charset: %s\n", $GLOBALS["mysqli"]->character_set_name());
        	/* изменение набора символов на utf8 */
        	if (!$GLOBALS["mysqli"]->set_charset("utf8")) {
        		throw new Exception("set charset utf8 error: %s\n", $GLOBALS["mysqli"]->error);
        	} else { printf("current charset: %s\n", $GLOBALS["mysqli"]->character_set_name()); }
        }
        $_result = $GLOBALS["mysqli"]->query($sql);
        if (!$_result) { printLog("SQL ERROR: ". $GLOBALS["mysqli"]->error . "\n executable SQL: " . $sql . "\n\n"); }
        if (is_bool($_result)) { return $_result; }
        elseif ($mode==="num_rows") { return $_result->num_rows; }
        elseif ($mode==="fetch_assoc") {
        	$result = [];
        	while($row = $_result->fetch_assoc()) {
        		reset($row);
        		$key = str2idx($row[key($row)]);
        		$result[$key] = $row;
            } unset($row);
            return $result;
        }
        throw new Exception("Recieved unexpected mode (".$mode.") or query result by execute SQL: ".$sql );
    }
    // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
    
    // -= Старт работы скрипта =-
    $start = microtime(true);
    printLog("Updater script started");
    // Инициализация глобальных переменных, счетчиков
    $GLOBALS["mysqli"] = NULL;
    $kingsilk_offers_count = 0;
    // Проверка хранилища фотографий
    if (!is_dir(IMAGES_PATH)) throw new Exception("ERROR: images path not found!");
    $IMAGES_FULL_PATH = IMAGES_PATH . IMAGE_PATH_PREFIX;
    if (!is_dir($IMAGES_FULL_PATH)) mkdir($IMAGES_FULL_PATH);
    // -=-=-=-=-=-=-=-=-=-=-=-=-=-
    
    // -= Получение YML-данных от поставщика Кингсилк, формирование индексов =-
    $yml_catalog = new SimpleXMLElement(
        file_get_contents(YML_URL_KINGSILK)
    );
    // Формирование индекса импортируемых категорий по id'шнику категории поставщика
    $GLOBALS['cats_outer_idxs'] = [];
    foreach ($yml_catalog->categories->category as $cat){
        $GLOBALS['cats_outer_idxs'][str2idx((string)$cat["id"])] = $cat;
    } unset($cat);
    // Группировка предложений поставщика по схожести картинок,
    // формирование древовидного индекса по md5 хэшу картинок
    $offers_groups_idxs = [];
    foreach ($yml_catalog->offers->offer as $offer) {
        // Отсеиваем не опубликованные товары
        if ((string)$offer["available"] != "true"){
        	continue;
        }
        $kingsilk_offers_count++;
        $hash = NULL;

    - = А ЧО ТУТ НЕЛЬЯ ПОСТИТЬ ПОЛНЫЙ КОД = - ???
    ===~ ТАМ ДОХРЕНА ЕЩЁ ~==

    P.S - вот как кодят питонисты на php
    продолжение: <a href="https://raw.githubusercontent.com/Siyet/goods-updater-oc3-php7/master/updater.php">Перейти</a>

    vasily2808, 10 Августа 2020

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

    +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
    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
    51. 51
    52. 52
    53. 53
    54. 54
    55. 55
    56. 56
    57. 57
    58. 58
    59. 59
    60. 60
    61. 61
    62. 62
    63. 63
    64. 64
    65. 65
    66. 66
    67. 67
    68. 68
    69. 69
    70. 70
    71. 71
    72. 72
    73. 73
    74. 74
    75. 75
    76. 76
    77. 77
    78. 78
    79. 79
    80. 80
    81. 81
    82. 82
    83. 83
    84. 84
    85. 85
    $data = [];
            $firstGenreId = Genre::where('homepage_filter_band', 1)->first()->id;
            $bandSearch = [
                'limit' => request('limit') ?? 6,
                'genre' => $firstGenreId,
                'category' => BandCategory::where('homepage_filter', 1)->first()->id,
                'status' => 1
            ];
    
            $subGenres = Genre::getGenresByCategory($bandSearch['genre']);
            $bandSearch['genre'] = [$bandSearch['genre']];
            foreach ($subGenres as $subGenre){
                array_push($bandSearch['genre'], $subGenre->id);
            }
    
            $data['bandsGenre']['bands'] = Band::getBandsLimitListByGenre($bandSearch);
            $data['bandsGenre']['filters'] = Genre::isExistGenreByBandFilter();
            $data['bandsGenre']['active_filter'] = $firstGenreId;
            $data['bandsGenre']['type'] = 'genre';
    
            $data['bandsCategories']['bands'] = Band::getBandsLimitListByCategory($bandSearch);
            $data['bandsCategories']['filters'] = BandCategory::isExistCategoryByBandFilter();
            $data['bandsCategories']['active_filter'] = $bandSearch['category'];
            $data['bandsCategories']['type'] = 'category';
    
            $data['bandsStatus']['bands'] = Band::getBandsLimitListByStatus($bandSearch);
            $data['bandsStatus']['active_filter'] = 1;
            $data['bandsStatus']['filters'] = (object)[
                0 => [
                    'id' => 1,
                    'name' => trans('validation-custom.newest')
                ],
                1 => [
                    'id' => 2,
                    'name' => trans('validation-custom.lastUpdated')
                ]
            ];
            $data['bandsStatus']['type'] = 'status';
    
            $firstGenreId = Genre::where('homepage_filter_musician', 1)->first()->id;
            $firstInstrumentId = Instrument::where('homepage_filter', 1)->first()->id;
            $musicianSearch = [
                'limit' => request('limit') ?? 6,
                'genre' => $firstGenreId,
                'instrument' => $firstInstrumentId,
                'status' => 1
            ];
    
            $subGenres = Genre::getGenresByCategory($musicianSearch['genre']);
            $musicianSearch['genre'] = [$musicianSearch['genre']];
            foreach ($subGenres as $subGenre){
                array_push($musicianSearch['genre'], $subGenre->id);
            }
    
            $subInstruments = Instrument::getInstrumentsByCategory($musicianSearch['instrument']);
            $musicianSearch['instrument'] = [$musicianSearch['instrument']];
            foreach ($subInstruments as $subInstrument){
                array_push($musicianSearch['instrument'], $subInstrument->id);
            }
    
            $data['musiciansGenre']['musicians'] = User::getMusiciansLimitListByGenre($musicianSearch);
            $data['musiciansGenre']['filters'] = Genre::isExistGenreByFilter();
            $data['musiciansGenre']['active_filter'] = $firstGenreId;
            $data['musiciansGenre']['type'] = 'genre';
    
            $data['musiciansInstrument']['musicians'] = User::getMusiciansLimitListByInstrument($musicianSearch);
            $data['musiciansInstrument']['filters'] = Instrument::isExistInstrumentByFilter();
            $data['musiciansInstrument']['active_filter'] = $firstInstrumentId;
            $data['musiciansInstrument']['type'] = 'instrument';
    
            $data['musiciansStatus']['musicians'] = User::getMusiciansLimitListByStatus($musicianSearch);
            $data['musiciansStatus']['active_filter'] = 1;
            $data['musiciansStatus']['filters'] = (object)[
                0 => [
                    'id' => 1,
                    'name' => trans('validation-custom.newest')
                ],
                1 => [
                    'id' => 2,
                    'name' => trans('validation-custom.lastUpdated')
                ]
            ];
            $data['musiciansStatus']['type'] = 'status';
    
            return response()->json($data, 200);

    Кажуть - шота сторінка довго грузиться :)

    silverreve23, 07 Августа 2020

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

    +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
    28. 28
    29. 29
    30. 30
    31. 31
    class MyEvents extends \Event\EventsHandler {
     static $key = 1;
     public function BeforeQuery() {
     Timer::start(self::$key);
     }
     public function AfterQuery() {
     Timer::step(self::$key++);
     if(Timer::$last['different'] > 1) {
     $debug_backtrace = debug_backtrace();
     foreach($debug_backtrace as $k=>$v) {
     if($v['function'] == 'q') {
     $error = "QUERY: ".$v['args'][0]."\n".
     "file: ".$v['file']."\n".				 
     "line: ".$v['line']."\n".
     "date: ".date("Y-m-d H:i:s")."\n".
     "===================================";		
     
     file_put_contents('./logs/slowquery.log',$error."\r\n",FILE_APPEND);
     break;
     }
     }
     }
     }
     public function ShutDownSystem() {
     echo microtime(true) - $_SERVER["REQUEST_TIME_FLOAT"];
     }
    }
    Event::setEventHandler('MyEvents');
    q("SELECT * FROM `table` ORDER BY RAND()");
    q("SELECT NOW()");
    echo Timer::result();

    Измеряем время запросов и время загрузки страницы
    https://school-php.com/tricks/23/dokumentatsiya-po-fw

    6a6yuH, 07 Августа 2020

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

    +1

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    while (true) {
      if ($current === $requested) {
         break;
      }
      if (! in_array($requested, $available)) {
         break;
      }
      session()->put('locale', $requested);
      break;
    }

    Edd, 05 Августа 2020

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

    0

    1. 1
    2. 2
    3. 3
    Именно поэтому я за «PHP» #3
    #1: https://govnokod.ru/26462 https://govnokod.xyz/_26462
    #2: https://govnokod.ru/26827 https://govnokod.xyz/_26827

    gostinho, 31 Июля 2020

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

    +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
    // Both set_time_limit(...) and  ini_set('max_execution_time',...); won't count the time cost of sleep,
    // file_get_contents,shell_exec,mysql_query etc, so i build this function my_background_exec(),
    // to run static method/function in background/detached process and time is out kill it:
    
    // my_exec.php:
    <?php
    function my_background_exec($function_name, $params, $str_requires, $timeout=600)
             {$map=array('"'=>'\"', '$'=>'\$', '`'=>'\`', '\\'=>'\\\\', '!'=>'\!');
              $str_requires=strtr($str_requires, $map);
              $path_run=dirname($_SERVER['SCRIPT_FILENAME']);
              $my_target_exec="/usr/bin/php -r \"chdir('{$path_run}');{$str_requires} \\\$params=json_decode(file_get_contents('php://stdin'),true);call_user_func_array('{$function_name}', \\\$params);\"";
              $my_target_exec=strtr(strtr($my_target_exec, $map), $map);
              $my_background_exec="(/usr/bin/php -r \"chdir('{$path_run}');{$str_requires} my_timeout_exec(\\\"{$my_target_exec}\\\", file_get_contents('php://stdin'), {$timeout});\" <&3 &) 3<&0";//php by default use "sh", and "sh" don't support "<&0"
              my_timeout_exec($my_background_exec, json_encode($params), 2);
             }
    // ...

    Шедевр (заплюсованный) из https://www.php.net/manual/ru/function.set-time-limit.php.

    gost, 30 Июля 2020

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

    0

    1. 1
    Именно поэтому я за «PHP».

    gostinho, 29 Июля 2020

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

    0

    1. 1
    2. 2
    3. 3
    https://github.com/moscow-technologies/blockchain-voting/tree/voting2020/elec2020/ballot
    https://github.com/moscow-technologies/blockchain-voting/blob/voting2020/elec2020/ballot/public/js/forms/mgik/LeavingPageCheckerInit.js
    https://github.com/moscow-technologies/blockchain-voting/blob/voting2020/elec2020/frontend-library-source/crypto-lib/src/util/numberFromLeBytes.js

    Как и всё в этой стране, обнуление написано на PHP, jQuery и (да-да) местами Rust, а управляется supervisord, ибо для редактирования юнитов systemd нужно sudo, который не дали.

    Какой блокчейн )))

    Fike, 30 Июня 2020

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

    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
    /**
         * @param int $filterType
         * @return int
         */
        public static function performanceFarmerStatFilterTranslator(int $filterType): int
        {
            switch (true) {
                case 1 === $filterType:
                    return Task::TYPE_PREPARE_ACCOUNTS_BY_REQUEST;
                case 2 === $filterType:
                    return Task::TYPE_PREPARE_GOOGLE_ACCOUNTS_BY_REQUEST;
                case 3 === $filterType:
                    return Task::TYPE_PREPARE_TWITTER_ACCOUNTS_BY_REQUEST;
                case 4 === $filterType:
                    return Task::TYPE_PASSWORD_MATCHING;
                case 6 === $filterType:
                    return Task::TYPE_ACCOUNT_MARKUP;
                case 7 === $filterType:
                    return Task::TYPE_REPLACE_ACCOUNTS;
            }
    
            return 0;
        }

    FireDemonru, 15 Июня 2020

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

    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
    <?php 
    	$bool1 = false;
    	$bool2 = true;
    	
    	$info = '';
    	
    	if ($bool1 || function () {
    		if ($bool2)
    		{
    			$info = 'Привет мир!';
    		}
    	})
    	{
    		echo 'Код выполнен';
    	}
    	
    	echo $info . "\n";
    
    ?>

    Еще бы работало:D

    A1mDev, 12 Июня 2020

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