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

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

    +152

    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
    function code_generator(){
            $chars="ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
    	$code_name='';
    	for ($i=0;$i<5;$i++){
    
    		$code_name.=substr($chars, rand(1, strlen($chars))-1,1);
    
    	}
    	return $code_name;
    }
    
    function generate (){
    	$code_name=code_generator().'-'.code_generator().'-'.code_generator().'-'.code_generator().'-'.code_generator();
            return $code_name;
    }

    Шедевральное решение задачи по генерированию ключа:)

    PHPed, 09 Мая 2014

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

    +152

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    7. 7
    /** 
     * Yesterday,
     * All my troubles seemed so far away
     * Now it looks as though they're here to stay
     * Oh, I believe in yesterday
     */
    $yesterday = date('Y-m-d', strtotime($_REQUEST['dateFrom']) - 86400);

    DIX315, 25 Апреля 2014

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

    +152

    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
    function locate($info) {
        $name = sprintf("%s_%02d_%02d.jpg", $info['prefix'], $info['vol'], $info['page']);
        if (file_exists($name))
            return $name;
        $name = sprintf("%s_%02d_%03d.jpg", $info['prefix'], $info['vol'], $info['page']);
        if (file_exists($name))
            return $name;
        $name = sprintf("%s%d_%03d.jpg", $info['prefix'], $info['vol'], $info['page']);
        if (file_exists($name))
            return $name;
        $name = sprintf("%s%d_%03d-%03d.jpg", $info['prefix'], $info['vol'], $info['page'], $info['page']+1);
        if (file_exists($name))
            return $name;
        $name = sprintf("%s%d_%03dcover.jpg", $info['prefix'], $info['vol'], $info['page']);
        if (file_exists($name))
            return $name;
        return false;
    }

    Онлайн читалка манги. Эта функция ищет картинку по номеру тома/страницы.

    Как считаете, я сильно наговнокодила? ^_^

    kitty, 19 Апреля 2014

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

    +152

    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
    $db = Db::getInstance();
    $result = $db->ExecuteS('SELECT * FROM `'._DB_PREFIX_.'payment_module_settings`;');
    $text = "";
    for($i=2;$i<sizeof($result[0]);$i++)
    {
        if($i == 2)
        {
            $text .= "[general]"."\n";
            $text .= "url = '".$result[0][url]."'"."\n";
        }
        if($i == 3)
        {
            $text .= "[payment]"."\n";
            $text .= "sequritySender = '".$result[0][security_sender]."'"."\n";
        }
        if($i == 4)
        {
            $text .= "transactionChannel = '".$result[0][transaction_Channel]."'"."\n";
        }
        if($i == 5)
        {
            $text .= "transactionMode = '".$result[0][transaction_Mode]."'"."\n";
        }
        if($i == 6)
        {
            $text .= "userLogin = '".$result[0][user_Login]."'"."\n";
        }
        if($i == 7)
        {
            $text .= "userPwd = '".$result[0][user_Pwd]."'"."\n";
        }
        if($i == 8)
        {
            $text .= "paymentType = '".$result[0][payment_Type]."'"."\n";
        }
        if($i == 9)
        {
            $text .= "presentationCurrency = '".$result[0][presentation_Currency]."'"."\n";
        }
        if($i == 10)
        {
            $text .= "[view]"."\n";
            $text .= "src = '".$result[0][src]."'"."\n";
        }
        if($i == 11)
        {
            $text .= "language = '".$result[0][language]."'"."\n";
        }
        if($i == 12)
        {
            $text .= "style = '".$result[0][style]."'"."\n";
        }
       
    }
    
    if($_GET['paymentType'] == 'CC')
    {
      $text .= "brands[] = 'VISA'"."\n";
      $text .= "brands[] = 'MASTER'"."\n";
     
    }
    if($_GET['paymentType'] == 'VA')
    {
      $text .= "brands[] = 'PAYPAL'"."\n";
    }
    
    $text .= "[soap]"."\n";
    $text .= "url = 'http://debugservices.fine-trade.org/PayOnOrderHandling.svc?WSDL'"."\n";
    $text .= "username  = 'extensions'"."\n";
    $text .= "password = 'testExtensions'"."\n";
    $text .= "options[] = false"."\n";
    $text .= "importIfPending = false"."\n";
    
    if (file_exists('LoviitLib/config.ini')) {
        unlink('LoviitLib/config.ini');
    } 
    $myFile = "LoviitLib/testFile.txt";
    $fh = fopen($myFile, 'w') or die("can't open file");
    fwrite($fh, $text);
    fclose($fh);
    rename("LoviitLib/testFile.txt","LoviitLib/config.ini");

    Преамбула: для конфигурации библиотеки передаётся ассоциативный массив в конструктор. Если передаётся null, то для конфигурации используется файл config.ini с дефолтными настройками, который находится в корне библиотеки.
    Этот код исполняется при каждой инициализации библиотеки (при каждом чекауте).
    Ремарка: после запроса к db результатом является ассоциативный массив.
    И да, это код из модуля для prestashop cms.

    aronsky, 15 Апреля 2014

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

    +152

    1. 1
    2. 2
    3. 3
    4. 4
    if (ctype_space($text[$pos] && $pos < $len)) {
        while (ctype_space($text[$pos++]) && $pos < $len);
        $pos--;
    }

    Написал я когда-то такое и подумал: а какой смысл в $pos++ в последней итерации, если потом сразу $pos--?
    И тут до меня дошло, что
    while (ctype_space($text[$pos++]) && $pos < $len);
    это не то же самое, что
    while (ctype_space($text[$pos]) && $pos < $len) $pos++;
    ибо в первом случае $pos++ выполнится в последней итерации, даже если ctype_space возвратит false.
    И в итоге заоптимизировал до while (ctype_space($text[$pos]) && $pos < $len) $pos++; (уже без ифа и декремента).

    Мораль: нефиг выпендриваться (ставить инкременты и декременты в условия), если можно написать по-простому.

    arzeth, 14 Апреля 2014

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

    +152

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    // Will we have a result object instantiated? If not - we'll simply return TRUE
    if ($return_object !== TRUE) {
    	if ($this->cache_on === TRUE && $this->cache_autodel === TRUE && $this->_cache_init()) {
    		$this->CACHE->delete();
    	}
    	return TRUE;
    }
    
    // Return TRUE if we don't need to create a result object
    if ($return_object !== TRUE) {
    	return TRUE;
    }

    Codeigniter / классика
    https://github.com/EllisLab/CodeIgniter/blob/develop/system/database/DB_driver.php#L668

    Fike, 09 Апреля 2014

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

    +152

    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
    86. 86
    87. 87
    88. 88
    $manufacturer_id = JRequest::getInt('manufacturer_id');
                $label_id = JRequest::getInt('label_id');
                $vendor_id = JRequest::getInt('vendor_id');
               
                $view_name = "cart";
                $view_config = array("template_path"=>JPATH_COMPONENT."/templates/".$jshopConfig->template."/".$view_name);
                $view = $this->getView($view_name, getDocumentType(), '', $view_config);
                        if ($category->category_template=="") $category->category_template="default";
                $view->setLayout("category_".$category->category_template);        
         
                $jshopConfig->count_products_to_page = $category->products_page;
         
                $context = "jshoping.list.front.product";
                $contextfilter = "jshoping.list.front.product.cat.".$category_id;
                $orderby = $mainframe->getUserStateFromRequest( $context.'orderby', 'orderby', $jshopConfig->product_sorting_direction, 'int');
                $order = $mainframe->getUserStateFromRequest( $context.'order', 'order', $jshopConfig->product_sorting, 'int');
                $limit = $mainframe->getUserStateFromRequest( $context.'limit', 'limit', $category->products_page, 'int');
                if (!$limit) $limit = $category->products_page;
                $limitstart = JRequest::getInt('limitstart');
         
                $orderbyq = getQuerySortDirection($order, $orderby);
                $image_sort_dir = getImgSortDirection($order, $orderby);
                $field_order = $jshopConfig->sorting_products_field_select[$order];
                $filters = getBuildFilterListProduct($contextfilter, array("categorys"));
                $orderfield = $jshopConfig->category_sorting==1 ? "ordering" : "name";
                $sub_categories = $category->getChildCategories($orderfield, 'asc', $publish = 1);
                $dispatcher->trigger( 'onBeforeDisplayCategory', array(&$category, &$sub_categories) );
         
                if ($category->meta_title=="") $category->meta_title = $category->name;
                setMetaData($category->meta_title, $category->meta_keyword, $category->meta_description);
               
                $total = $category->getCountProducts($filters);
                $action = xhtmlUrl($_SERVER['REQUEST_URI']);
                       
                        $dispatcher->trigger('onBeforeFixLimitstartDisplayProductList', array(&$limitstart, &$total, 'category'));
                if ($limitstart>=$total) $limitstart = 0;
         
                $products = $category->getProducts($filters, $field_order, $orderbyq, $limitstart, $limit);
                        addLinkToProducts($products, $category_id);
         
                jimport('joomla.html.pagination');
                $pagination = new JPagination($total, $limitstart, $limit);
                $pagenav = $pagination->getPagesLinks();
               
                foreach($jshopConfig->sorting_products_name_select as $key=>$value){
                    $sorts[] = JHTML::_('select.option', $key, $value, 'sort_id', 'sort_value' );
                }
         
                insertValueInArray($category->products_page, $jshopConfig->count_product_select); //insert category count
                foreach ($jshopConfig->count_product_select as $key => $value){
                    $product_count[] = JHTML::_('select.option',$key, $value, 'count_id', 'count_value' );
                }
                $sorting_sel = JHTML::_('select.genericlist', $sorts, 'order', 'class = "inputbox" size = "1" onchange = "submitListProductFilters()"','sort_id', 'sort_value', $order );
                $product_count_sel = JHTML::_('select.genericlist', $product_count, 'limit', 'class = "inputbox" size = "1" onchange = "submitListProductFilters()"','count_id', 'count_value', $limit );
               
                $_review = JTable::getInstance('review', 'jshop');
                $allow_review = $_review->getAllowReview();
               
                if (!$category->category_ordertype) $category->category_ordertype = 1;
               
                $manufacuturers_sel = '';
                if ($jshopConfig->show_product_list_filters){
                    $filter_manufactures = $category->getManufacturers();
                    $first_manufacturer = array();
                    $first_manufacturer[] = JHTML::_('select.option', 0, _JSHOP_ALL, 'id', 'name');
                    if (isset($filters['manufacturers'][0])){
                        $active_manufacturer = $filters['manufacturers'][0];            
                    }else{
                        $active_manufacturer = 0;
                    }
                    $manufacuturers_sel = JHTML::_('select.genericlist', array_merge($first_manufacturer, $filter_manufactures), 'manufacturers[]', 'class = "inputbox" onchange = "submitListProductFilters()"','id', 'name', $active_manufacturer);
                }
                $display_list_products = (count($products)>0 || willBeUseFilter($filters));
         
                $dispatcher->trigger('onBeforeDisplayProductList', array(&$products));
                $view->assign('config', $jshopConfig);
                $view->assign('template_block_list_product', "cart/list_products.php");
                $view->assign('template_block_form_filter', "cart/form_filters.php");
                $view->assign('template_block_pagination', "cart/block_pagination.php");
                $view->assign('path_image_sorting_dir', $jshopConfig->live_path.'images/'.$image_sort_dir);
                $view->assign('filter_show_category', 0);
                $view->assign('display_pagination', $pagenav!="");
                $view->assign('rows', $products);
                $view->assign('count_product_to_row', $category->products_row);
                $view->assign('filters', $filters);
                $view->assign('display_list_products', $display_list_products);
                $view->assign('shippinginfo', SEFLink($jshopConfig->shippinginfourl,1));
                $view->display();

    Все это (пришлось еще отрезать строк 30) нужно таскать за собой для вывода списка товаров в нестандартном месте. При этом оно лежит в контроллере.
    Полный код: http://pastebin.com/jTj83ZpE
    (joomshopping)

    attn, 03 Апреля 2014

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

    +152

    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
    public function validateItem() {
      $orderPricesSum = null;
      if($orderPricesSum == null) {
    	$orderPricesSum = $this->getPricesSum();
      }
    
     if($this->minimal && $orderPricesSum < $this->minimal) {
    	return false;
      }
    
      if($this->maximum && $orderPricesSum > $this->maximum) {
    	return false;
      }
    
      return true;
    }

    $orderPricesSum другой ведь какой-то может быть...

    farit_slv, 28 Марта 2014

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

    +152

    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
    if(isset($_GET['do'])){
    	$page = $checkObj->pageCheck($_GET['dopage']);
    	$incModules = 'staticpage';
    	if($link_set['on_news_post_html'] == 1){
    		$nameLinkPost = $checkObj->pageCheck($_GET['dopage']);
    		if($nameLinkPost != ''){
    			$tmp_id_post = explode('_',$_GET['dopage']);
    			$id_post = $checkObj->idCheck($tmp_id_post[0]);
    			$nameLinkPost = $checkObj->pageCheck($tmp_id_post[1]);
    			if(($id_post) and (!empty($tmp_id_post[1]))){
    				$incModules = 'post';
    				$page = '';
    			}
    		}
    	}
    }

    Так нормально?

    straga_coda, 17 Марта 2014

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

    +152

    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
    // Калькулятор умеющий умножать, делить, складывать и вычитать.
    
    
    <?php
    
    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    	if (isset($_POST['num1'])) { 
    		if(is_numeric($_POST['num1'])) {
    			$num1 = strip_tags($_POST['num1']*1); 
    			}
    		} 
    		elseif (isset($_POST['num1'])) {
    			echo "Неверное значение Число 1";
    		}
    	if (isset($_POST['num2'])) { 
    		if(is_numeric($_POST['num2'])) {
    			$num2 = strip_tags($_POST['num2']*1); 
    			}
    		} 
    		elseif (isset($_POST['num2'])) {
    			echo "Неверное значение Число 2";
    		}
    	if (isset($_POST['operator'])) { 
    			$operator = $_POST['operator']; 
    		} 
    		elseif (isset($_POST['operator'])) {
    			echo "Неверное значение Оператор";
    		}
    		
    
    		switch ($operator) {
    		case '-':
    		$output .= $num1-$num2;break;
    		case '+':
    		$output .= $num1+$num2;break;
    		case '*':
    		$output .= $num1*$num2;break;
    		case '/':
    			if ($num2 == 0) {echo "На 0 делить нельзя";}else{$output .= $num1/$num2;break;}
    			default:
    				$output = "Неизвестный оператор ".$operator;
    	}
    }
    	
    ?>
    <h1>Калькулятор</h1>
    
    <?php
    
    if (isset($output)){
    	echo "Результат $output";
    }
    	
    ?>
    
    <form action="<?php echo $_SERVER['REQUEST_URI']; ?>" method="post">
    
    Число 1:<br />
    <input type="text" name="num1" /><br /><br />
    
    Оператор:<br />
    <input type="text" name="operator" /><br /><br />
    
    Число 2:<br />
    <input type="text" name="num2" /><br /><br />
    
    <input type="submit" value="Считать!" />
    
    </form>

    // Калькулятор умеющий умножать, делить, складывать и вычитать.

    Arthur, 14 Марта 2014

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