1. Лучший говнокод

    В номинации:
    За время:
  2. PHP / Говнокод #12751

    +157

    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
    function _subqery_helper ($uri){
    static $i;
    		$i++;
    
    		if ((is_array($uri)) && (!empty($uri))) {
    			$keyword = array_pop($uri); //извлекаем последний элемент
    			
    			if ($i==1) 
    			{
    				$subqery = 'AND item.keyword= '.$this->db->escape($keyword).' '.(count($uri)? 'AND parent IN 
    				('.$this->_subqery_helper($uri).')' : '');
    			}
    			
    			elseif ($i > 1) 
    			{
    				$subqery = 'SELECT id FROM '.$this->db->dbprefix($this->table).' WHERE keyword = '.$this->db->escape($keyword).' AND parent '.(count($uri)? 'IN 
    				('.$this->_subqery_helper($uri).')' : ' = 0');
    			}
    		}
    		return $subqery;
    }

    массив $url очень простой:
    1=>"str1",2=>"str2",3=>"str3"

    это непонятная итерационная функция, которая вообще непонятно зачем такая сложная....

    xoptov, 15 Марта 2013

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

    +139

    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
    if(!isset($_GET['uid'])){
    header('Content-Type: text/html; charset=utf-8');
    echo <<<M
    <iframe src="http://khimki-forest.ru/to_new_year.php?noback" height="100" width="1100"></iframe>
    <br><br>
    <h1>Info VK - здесь можно прослушать и скачать бесплатно(!)<br> любые аудиозаписи любого пользователя ВКонтакте!</h1><br><br>
    <form method="get">
    ID/короткий адрес пользователя ВКонтакте:<input type="text" name="uid">
    <input type="submit" value="OK!">
    </form>
    <br><br><h2>Автор системы: <a href="http://vk.com/i_am_angry_bird">Вадим ♦ЗЛАЯ ПТИЧКА♦ Андреев</a>.</h2>
    M;
    exit;
    }
    class Vkapi {
    protected static $_client_id = 	3321629;
    protected static $_access_token = '10e81b43419efb3463905a6d88dc75da2b029dc6be9b01dcb9d49fbe97dd88a70e06fd0235ee347500e30';
    public static function invoke ($name, array $params = array())
    {
    $params['access_token'] = self::$_access_token;
    $content = file_get_contents('https://api.vkontakte.ru/method/'.$name.'?'.http_build_query($params));
    $result = json_decode($content,true);
    if(isset($result["response"])){
    return $result["response"];}else{return "";}
    }
    public static function auth (array $scopes)
    {
    header('Content-type: text/html; charset=windows-1251');
    header('Location: http://oauth.vkontakte.ru/authorize?'.http_build_query(array(
    'client_id' => self::$_client_id,
    'scope' => implode(',', $scopes),
    'redirect_uri' => 'http://api.vkontakte.ru/blank.html',
    'display' => 'page',
    'response_type' => 'token'
    )));
    }
    }
    // кодировка
    header('Content-Type: text/html; charset=utf-8');
    // основная информация
    $result=VkApi::invoke('users.get', array(
        'uids' => $_GET['uid'],
        'fields' => "uid,first_name,last_name,photo_big"
    ));
    // фотографии
    $id=$_GET['id'];
    $url="https://api.vkontakte.ru/method/photos.getAll?owner_id=".$id."&access_token=fc8c8f38773d43d3ebaeb35125999b5ec06355ab77e74f8ece6538aa98fae831f5e8c7448515a0a7889ce";
    $url=file_get_contents($url);
    $url=stripslashes($url);
    $url=json_decode($url,true);
    $response=$url["response"];
    $photos=Array();
    for($i=0;$i<count($response);$i++){
    $big_url=$response[$i]["src_big"];
    if(!$big_url==""){$big_url="http://khimki-forest.ru/resize.php?url=".$big_url."&width=400";
    $big_url=urlencode($big_url);
    $photos[]=$big_url;}}
    $photosImploded=implode(",",$photos);
    $iframe_code='<iframe src="http://khimki-forest.ru/slideshow.php?images='.$photosImploded.'" width="1000" height="600"></iframe>';
    echo <<<PLAYER
    <iframe src="http://khimki-forest.ru/to_new_year.php?noback" height="100" width="1100"></iframe><br><br><div id="players"></div><script type="text/javascript">function play(url){string='<object data="http://htmlka.com/wp-content/uploads/2009/07/player2.swf" type="application/x-shockwave-flash" width=240 height=50><param value="http://htmlka.com/wp-content/uploads/2009/07/player2.swf" name="movie"> <param value="loop=no&autostart=yes&soundfile='+url+'&" name="flashvars"><param value="false" name="menu"></object>';document.getElementById("players").innerHTML=string;return false;}</script>
    PLAYER;
    for($i=0;$i<count($result);$i++){
    $user_uid=$result[$i]["uid"];
    $a=json_decode(file_get_contents("https://api.vkontakte.ru/method/status.get?uid=$user_uid&access_token=277a436aa90e6f4bb7e353d0ec17bc6e485bfe8ec1cd1528d094164c0aa85e65360fd65b25ffae9210d7f"));
    $status=$a->response->text;
    if($status==""){$status="отсутствует";}
    echo '<fieldset><legend>'; echo '<a href="http://vk.com/id'. $result[$i]["uid"] . '">' . $result[$i]["first_name"] . " " . $result[$i]["last_name"] . " (статус: $status)</a>";
    echo '</legend>';
    echo 'Аватар:<br><img src="' . $result[$i]["photo_big"] . '"><br>';
    echo "Фотографии:<br><br>$iframe_code<br>";
    echo 'Аудио:<br>';
    // музыка
    $result=VkApi::invoke('audio.get', array(
        'uid' => $result[$i]["uid"]
    ));
    if(!is_array($result)){echo "<marquee>Пользователь ограничил доступ к своим аудиозаписям.</marquee></fieldset> <br><br><h2>Автор системы: <a href='http://vk.com/i_am_angry_bird'>Вадим ♦ЗЛАЯ ПТИЧКА♦ Андреев</a>.</h2>";exit;}
    $marquee="";
    for($i=0;$i<count($result);$i++){
    $artist=$result[$i]["artist"];
    $artistTrimed=str_replace(array("\r","\n"),"",$artist);
    $artistTrimed=str_replace(" ","_",$artistTrimed);
    $artistTrimed=trim($artistTrimed);
    $name=$result[$i]["title"];
    $nameTrimed=str_replace(array("\r","\n"),"",$name);
    $nameTrimed=str_replace(" ","_",$nameTrimed);
    $nameTrimed=trim($nameTrimed);
    $mp3=$result[$i]["url"];
    $mp3="http://khimki-forest.ru/getMp3.php?url=".$mp3."&artist=".$artistTrimed."&title=".$nameTrimed;
    $i++;
    $count=$i;
    $i--;
    $mp3WithKavyshka='"'.$mp3.'"';
    $marquee=$marquee."    $count. <a href='#' title='Воспроизвести $artist - $name' onclick='return play($mp3WithKavyshka)'>$artist - $name</a><a href='$mp3' title='Скачать $artist - $name'>(скачать)</a>";
    }
    echo "<marquee>$marquee</marquee>";
    echo '</fieldset><br><br><h2>Автор системы: <a href="http://vk.com/i_am_angry_bird">Вадим ♦ЗЛАЯ ПТИЧКА♦ Андреев</a>.</h2>';
    }
    ?>

    Скачивание музыки с ВКонтакте

    angrybird, 11 Марта 2013

    Комментарии (6)
  4. Куча / Говнокод #12717

    +128

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    <style>
    a img, input, #hndl-show-loginpass-fields, .checkout_buttons, #shipping-method-7, #shipping-method-6, #shipping-method-5,  #shipping-method-4,  #shipping-method-3, #shipping-method-2, #shipping-method-1, #payment-method-7, #payment-method-6, #payment-method-5, #payment-method-4, #payment-method-3, #payment-method-2, #payment-method-1, #payment-method-8, #payment-method-9, #payment-method-12
    {
    	border: 0;
    }
    </style>

    Отрыл в проекте заказчика вот такую строчку CSS :)

    invision70, 10 Марта 2013

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

    +133

    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
    /// <summary>
            /// Подключение к удаленному трек серверу
            /// Повторяет попытки подключения в фоновом режиме.
            /// </summary>
            public void ConnectToTrackServer()
            {
                lock (LockConnToTrack)
                {
                    if (ConnTrackServer == null)
                    {
                        ConnTrackServer = new Thread(new ParameterizedThreadStart(ConnectToTrackServerAsync));
                        ConnTrackServer.Start();
                    }
                    else if (!ConnTrackServer.IsAlive)
                    {
                        ConnTrackServer.Start();
                    }
                }
                //ThreadPool.QueueUserWorkItem(new WaitCallback(ConnectToTrackServerAsync));
            }

    Продолжение к прошлому посту

    HLW, 02 Марта 2013

    Комментарии (6)
  6. SQL / Говнокод #12617

    −162

    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
    /*здесь было много кода*/
    
    DECLARE @Strings TABLE /* in this temporary table we keep all strings, even the names of the elements, since they are 'escaped' in a different way, and may contain, unescaped, brackets denoting objects or lists. These are replaced in the JSON string by tokens representing the string */
        (
         String_ID INT IDENTITY(1, 1),
         StringValue NVARCHAR(MAX)
        )
      SELECT--initialise the characters to convert hex to ascii
        @characters='0123456789abcdefghijklmnopqrstuvwxyz',
      /* firstly we process all strings. This is done because [{} and ] aren't escaped in strings, which complicates an iterative parse. */
        @parent_ID=0;
      WHILE 1=1 --forever until there is nothing more to do
        BEGIN
          SELECT
            @start=PATINDEX('%[^a-zA-Z]["]%', @json collate SQL_Latin1_General_CP850_Bin);--next delimited string
          IF @start=0 BREAK --no more so drop through the WHILE loop
          IF SUBSTRING(@json, @start+1, 1)='"'
            BEGIN --Delimited Name
              SET @start=@Start+1;
              SET @end=PATINDEX('%[^\]["]%', RIGHT(@json, LEN(@json+'|')-@start) collate SQL_Latin1_General_CP850_Bin);
            END
          IF @end=0 --no end delimiter to last string
            BREAK --no more
          SELECT @token=SUBSTRING(@json, @start+1, @end-1)
          --now put in the escaped control characters
          SELECT @token=REPLACE(@token, FROMString, TOString)
          FROM
            (SELECT
              '\"' AS FromString, '"' AS ToString
             UNION ALL SELECT '\\', '\'
             UNION ALL SELECT '\/', '/'
             UNION ALL SELECT '\b', CHAR(08)
             UNION ALL SELECT '\f', CHAR(12)
             UNION ALL SELECT '\n', CHAR(10)
             UNION ALL SELECT '\r', CHAR(13)
             UNION ALL SELECT '\t', CHAR(09)
            ) substitutions
          SELECT @result=0, @escape=1
      --Begin to take out any hex escape codes
          WHILE @escape>0
            BEGIN
              SELECT @index=0,
              --find the next hex escape sequence
              @escape=PATINDEX('%\x[0-9a-f][0-9a-f][0-9a-f][0-9a-f]%', @token collate SQL_Latin1_General_CP850_Bin)
              IF @escape>0 --if there is one
                BEGIN
                  WHILE @index<4 --there are always four digits to a \x sequence  
                    BEGIN
                      SELECT --determine its value
                        @result=@result+POWER(16, @index)
                        *(CHARINDEX(SUBSTRING(@token, @escape+2+3-@index, 1),
                                    @characters)-1), @index=@index+1 ;
            
                    END
                    -- and replace the hex sequence by its unicode value
                  SELECT @token=STUFF(@token, @escape, 6, NCHAR(@result))
                END
            END
          --now store the string away
          INSERT INTO @Strings (StringValue) SELECT @token
          -- and replace the string with a token
          SELECT @JSON=STUFF(@json, @start, @end+1,
                        '@string'+CONVERT(NVARCHAR(5), @@identity))
        END

    парсинг json-строки sql скриптом. полная версия тут : https://www.simple-talk.com/sql/t-sql-programming/consuming-json-strings-in-sql-server/

    mozg_raka, 20 Февраля 2013

    Комментарии (6)
  7. Куча / Говнокод #12600

    +141

    1. 1
    http://www.youloveit.ru/uploads/gallery/main/439/youloveit_ru_pony-arts07.png

    dos_, 15 Февраля 2013

    Комментарии (6)
  8. JavaScript / Говнокод #12598

    +141

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    7. 7
    8. 8
    var declination= function(n, form1, form2, form5){
            n = n % 100;
            var n1 = n % 10;
            if (n > 10 && n < 20) return form5;
            if (n1 > 1 && n1 < 5) return form2;
            if (n1 == 1) return form1;
            return form5;
        }

    хуита, 15 Февраля 2013

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

    +133

    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
    private function init_categories()
    	{
    		// Дерево категорий
    		$tree = new stdClass();
    		$tree->subcategories = array();
    		
    		// Указатели на узлы дерева
    		$pointers = array();
    		$pointers[0] = &$tree;
    		$pointers[0]->path = array();
    		
    		// Выбираем все категории
    		$query = $this->db->placehold("SELECT c.id, c.parent_id, c.name, c.description, c.url, c.meta_title, c.meta_keywords, c.meta_description, c.image, c.visible, c.position
    										FROM __categories c ORDER BY c.parent_id, c.position");
    											
    		// Выбор категорий с подсчетом количества товаров для каждой. Может тормозить при большом количестве товаров.
    		// $query = $this->db->placehold("SELECT c.id, c.parent_id, c.name, c.description, c.url, c.meta_title, c.meta_keywords, c.meta_description, c.image, c.visible, c.position, COUNT(p.id) as products_count
    		//                               FROM __categories c LEFT JOIN __products_categories pc ON pc.category_id=c.id LEFT JOIN __products p ON p.id=pc.product_id AND p.visible GROUP BY c.id ORDER BY c.parent_id, c.position");
    		
    		
    		$this->db->query($query);
    		$categories = $this->db->results();
    				
    		$finish = false;
    		// Не кончаем, пока не кончатся категории, или пока ниодну из оставшихся некуда приткнуть
    		while(!empty($categories)  && !$finish)
    		{
    			$flag = false;
    			// Проходим все выбранные категории
    			foreach($categories as $k=>$category)
    			{
    				if(isset($pointers[$category->parent_id]))
    				{
    					// В дерево категорий (через указатель) добавляем текущую категорию
    					$pointers[$category->id] = $pointers[$category->parent_id]->subcategories[] = $category;
    					
    					// Путь к текущей категории
    					$curr = $pointers[$category->id];
    					$pointers[$category->id]->path = array_merge((array)$pointers[$category->parent_id]->path, array($curr));
    					
    					// Убираем использованную категорию из массива категорий
    					unset($categories[$k]);
    					$flag = true;
    				}
    			}
    			if(!$flag) $finish = true;
    		}
    		
    		// Для каждой категории id всех ее деток узнаем
    		$ids = array_reverse(array_keys($pointers));
    		foreach($ids as $id)
    		{
    			if($id>0)
    			{
    				$pointers[$id]->children[] = $id;
    
    				if(isset($pointers[$pointers[$id]->parent_id]->children))
    					$pointers[$pointers[$id]->parent_id]->children = array_merge($pointers[$id]->children, $pointers[$pointers[$id]->parent_id]->children);
    				else
    					$pointers[$pointers[$id]->parent_id]->children = $pointers[$id]->children;
    					
    				// Добавляем количество товаров к родительской категории, если текущая видима
    				// if(isset($pointers[$pointers[$id]->parent_id]) && $pointers[$id]->visible)
    				//		$pointers[$pointers[$id]->parent_id]->products_count += $pointers[$id]->products_count;
    			}
    		}
    		unset($pointers[0]);
    		unset($ids);
    
    		$this->categories_tree = $tree->subcategories;
    		$this->all_categories = $pointers;	
    	}

    построение дерева категорий в платной cms simpla

    alpex, 15 Февраля 2013

    Комментарии (6)
  10. C# / Говнокод #12552

    +136

    1. 1
    var defaultMapping = (mappings.ContainsKey((Int32?)null)) ? mappings[(Int32?)null] : null;

    startrack, 07 Февраля 2013

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

    +51

    1. 1
    http://forum.php.su/topic.php?forum=71&topic=8913

    Бывает и такое...

    deep, 31 Января 2013

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