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

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

    +154

    1. 1
    $data_move = date("d.m.Y", mktime(0, 0, 0, (int)date("m",time()), (int)date("d",time()), (int)date("Y",time())));

    Вишенка даже не в том, что афтар - кармический индус, а в том, что теоретически возможна ситуация, при которой date("m",time()) выполняется в последнюю миллисекунду предыдущего месяца, а date("d",time()) - в первую следующего.

    catgav, 03 Июня 2014

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

    +154

    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
    if ($_SERVER["REQUEST_METHOD"] == "POST" && strlen($_REQUEST["backButton"]) > 0 && ($arParams["DELIVERY_NO_SESSION"] == "N" || check_bitrix_sessid()))
    {
    	if($arResult["POST"]["CurrentStep"] == 6 && $arResult["SKIP_FORTH_STEP"] == "Y")
    		$arResult["CurrentStepTmp"] = 3;
    
    	if($arResult["POST"]["CurrentStepTmp"] <= 5 && $arResult["SKIP_THIRD_STEP"] == "Y")
    		$arResult["CurrentStepTmp"] = 2;
    
    	if($arResult["POST"]["CurrentStepTmp"] <= 3 && $arResult["SKIP_SECOND_STEP"] == "Y")
    		$arResult["CurrentStepTmp"] = 1;
    
    	if(IntVal($arResult["CurrentStepTmp"])>0)
    		$arResult["CurrentStep"] = $arResult["CurrentStepTmp"];
    	else
    		$arResult["CurrentStep"] = $arResult["CurrentStep"] - 2;
    	$arResult["BACK"] = "Y";
    }
    if ($arResult["CurrentStep"] <= 0)
    	$arResult["CurrentStep"] = 1;
    $arResult["ERROR_MESSAGE"] = "";

    Компонент страницы заказа в магазине Битрикса, 14я версия.
    Тут вам и отсутствие констант для осмысленных шагов, и отсутствие конфигурирования этих шагов, как они i18n-ятся, вообще не представляю.
    КАК ЭТО ВСЁ РАБОТАЕТ??!!!

    ЗЫ мало того, тут же в компонент вкопипащен (или переговнокоден заново, не сравнивал) процесс залогинивания/регистрации нового юзера, елси он не залогинен. Не смог перекопипастить эту копипасту лишь потому, что она содержит 310 строк. Неслабый DRY.

    velosipedistorg, 30 Мая 2014

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

    +154

    1. 1
    2. 2
    foreach($arr as $val)
      $data[uniqid()] = $val;

    Ну для ооочень медленных серверов =)

    lisiy50, 27 Мая 2014

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

    +154

    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
    function box_navigation($gc, $num, $id, $function, $act){
    	global $tpl, $page;
    	$gcount = $gc;
    	$cnt = $num;
    	$items_count = $cnt;
    	$items_per_page = $gcount;
    	$page_refers_per_page = 5;
    	$pages = '';		
    	$pages_count = ( ( $items_count % $items_per_page != 0 ) ) ? floor( $items_count / $items_per_page ) + 1 : floor( $items_count / $items_per_page );
    	$start_page = ( $page - $page_refers_per_page <= 0  ) ? 1 : $page - $page_refers_per_page + 1;
    	$page_refers_per_page_count = ( ( $page - $page_refers_per_page < 0 ) ? $page : $page_refers_per_page ) + ( ( $page + $page_refers_per_page > $pages_count ) ? ( $pages_count - $page )  :  $page_refers_per_page - 1 );
    	
    	if(!$act)
    		$act = "''";
    	else
    		$act = "'{$act}'";
    			
    	if($page > 1)
    		$pages .= '<a href="" onClick="'.$function.'('.$id.', '.($page-1).', '.$act.'); return false">«</a>';
    	else
    		$pages .= '';
    				
    	if ( $start_page > 1 ) {
    		$pages .= '<a href="" onClick="'.$function.'('.$id.', 1, '.$act.'); return false">1</a>';
    		$pages .= '<a href="" onClick="'.$function.'('.$id.', '.($start_page-1).', '.$act.'); return false">...</a>';
    			
    	}
    					
    	for ( $index = -1; ++$index <= $page_refers_per_page_count-1; ) {
    		if ( $index + $start_page == $page )
    			$pages .= '<span>' . ( $start_page + $index ) . '</span>';
    		else 
    			$pages .= '<a href="" onClick="'.$function.'('.$id.', '.($start_page+$index).', '.$act.'); return false">'.($start_page+$index).'</a>';
    	} 
    			
    	if ( $page + $page_refers_per_page <= $pages_count ) { 
    		$pages .= '<a href="" onClick="'.$function.'('.$id.', '.($start_page + $page_refers_per_page_count).', '.$act.'); return false">...</a>';
    		$pages .= '<a href="" onClick="'.$function.'('.$id.', '.$pages_count.', '.$act.'); return false">'.$pages_count.'</a>';	
    	} 
    				
    	$resif = $cnt/$gcount;
    	if(ceil($resif) == $page)
    		$pages .= '';
    	else
    		$pages .= '<a href="/" onClick="'.$function.'('.$id.', '.($page+1).', '.$act.'); return false">»</a>';
    
    	if ( $pages_count <= 1 )
    		$pages = '';
    
    	$tpl_2 = new mozg_template();
    	$tpl_2->dir = TEMPLATE_DIR;
    	$tpl_2->load_template('nav.tpl');
    	$tpl_2->set('{pages}', $pages);
    	$tpl_2->compile('content');
    	$tpl_2->clear();
    	$tpl->result['content'] .= $tpl_2->result['content'];
    }

    дали проект чтобы разобрался)

    progsmile, 21 Мая 2014

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

    +154

    1. 1
    2. 2
    3. 3
    function deleteCookie(name, path, domain) {
    	if (getCookie(name)) document.cookie = name + '=' + ((path) ? '; path=' + path : '') + ((domain) ? '; domain=' + domain : '') + '; expires=Thu, 01-Jan-1970 00:00:00 GMT';
    }

    ...

    gost, 21 Мая 2014

    Комментарии (69)
  7. JavaScript / Говнокод #16031

    +154

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    var turn = 0;
    		function turn_over() {
    			var text = document.getElementById('turn-over-in').value;
    			var first_letter = text.charAt(0).toLowerCase();
    			var last_letter = text.charAt(text.length-1).toUpperCase();
    			var new_text = first_letter + text.substr(1,text.length-2) + last_letter;
    			var text_array = new_text.split('');
    			var inside_out = text_array.reverse();
    			var turn_over_text = inside_out.join('');
    			document.getElementById('turn-over-out').value = turn_over_text;
    <...>

    Задача: развернуть строку текста (Абв->Вба).

    gost, 21 Мая 2014

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

    +154

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    function chksremail(t) {
    	if (t.value!='' && (t.value.indexOf('@')<1 || t.value.indexOf('.')<1 || t.value.length<4 || t.value.indexOf(' ')!=-1)) {
    		if (t.value.indexOf('@')<1) alert('Вы ввели неправильный адрес электронной почты! Адрес электронной почты должен обязательно содержать символ "@".');
    		else if (t.value.indexOf('.')<1) alert('Вы ввели неправильный адрес электронной почты! Адрес электронной почты должен обязательно содержать точку (".").');
    		else if (t.value.length<4) alert('Вы ввели неправильный адрес электронной почты! Адрес электронной почты должен обязательно содержать минимум 4 символа.');
    		else if (t.value.indexOf(' ')!=-1) alert('Вы ввели неправильный адрес электронной почты! Адрес электронной почты не может содержать пробелы.');
    		t.focus();
    		return false;
    	}
    	return true;
    }

    $%&$@^@#$^@rlu.ru/rlu.js

    gost, 21 Мая 2014

    Комментарии (1)
  9. JavaScript / Говнокод #16018

    +154

    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
    (function () {
    
        if (location.pathname === "/") {
            document.body.id = 'front-page';
        }
        else {
            var path = window.location.pathname.replace('/index.php/', ''),
                splittedPath = path.split('/') || ['', ''],
                category = splittedPath[0],
                subcategory = '';
    
            for (var i = 1; i < splittedPath.length; i++) {
                subcategory += ('-' + splittedPath[i]);
            }
    
            if (category && (typeof category === 'string')) {
                document.body.classList.add('page-' + category);
            }
    
            if (subcategory && (typeof subcategory === 'string')) {
                document.body.classList.add('page-' + subcategory.replace(/^[-]/, ''));
            }
        }
    
    })();

    Сей замысловатый код призван добавить уникальный класс в body для каждой страницы прямо из урла. Предназначалось в качестве костыля для джумлы, так как через пых не работало, а разбираться никто не стал :)

    DrDre, 19 Мая 2014

    Комментарии (26)
  10. JavaScript / Говнокод #15988

    +154

    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
    if($('.article-775-gallery')){
            $('.article-775-gallery').each(function(){
                get_images_by_building_gallery_id($(this).attr('id').replace(/gallery-/g,''));
            });
        }
    
        /* ************************************************************************************************************** */
    
        function get_building_details_by_property_id(id, size){
            $.get(urlprefix + "/ajax/nanar/" + id, function(data){
                var desc = jQuery.parseJSON(data);
                console.log(desc);
                if(desc.street && desc.zip && desc.town){
                    $('div[id="new-property-entry-id-' + id + '"] .house-item-head').html(desc.street + " <strong>" + desc.zip + " " + desc.town + " </strong>");
                    $('div[id="new-property-entry-id-' + id + '"] .house__item-descr').text(desc.description);
                    $('div[id="new-property-entry-id-' + id + '"] img').attr('src', desc.preview + size);
                    $('div[id="new-property-entry-id-' + id + '"] .verd').text(desc.verd);
                    $('div[id="new-property-entry-id-' + id + '"] .stard').text(desc.stard);
                    $('div[id="new-property-entry-id-' + id + '"] .tegund').text(desc.tegund);
                    $('div[id="new-property-entry-id-' + id + '"] .rooms').text(desc.rooms);
                    $('div[id="new-property-entry-id-' + id + '"]').slideDown();
                }
            });
        }
    
        if($('div[id^="new-property-entry-id-"]')){
            setTimeout(function(){
                $($('div[id^="new-property-entry-id-"]')).each(function(){
                    var size;
                    if($('div[id^="new-property-entry-id-"] div').hasClass('big-image')){
                        size = "180x140";
                        $('.new-property-entry-description').css('width','476px');
                        $('.time').css('display','block');
                    }else{size = "322x157";}
                    get_building_details_by_property_id($(this).attr('id').replace(/new-property-entry-id-/g,''), size);
                });
            },500);
        }

    код творит чудеса :), я его побоялся трогать.... знаю что функция на 9 строчке, это некое подобие шаблонизатора

    expert, 15 Мая 2014

    Комментарии (5)
  11. JavaScript / Говнокод #15987

    +154

    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
    $('.order-form-popup form').on('submit', function (e) {
    			e.preventDefault();
    			var data = $(this).serializeArray(),
    				mainProfilesList = '',
    				fillingsList = '';
    
    			$('.field-name-field-eo-main-profiles .field-item').each(function () {
    				mainProfilesList += ('<li>' + ($(this).text()) + '</li>');
    			});
    
    			$('.field-name-field-eo-fillings .field-item').each(function () {
    				fillingsList += ('<li>' + ($(this).text()) + '</li>');
    			});
    
    			data.push({
    				name: 'profiles',
    				value: '<ul>' + mainProfilesList + '</ul>'
    			});
    
    			data.push({
    				name: 'fillings',
    				value: '<ul>' + fillingsList + '</ul>'
    			});
    
    			data.push({
    				name: 'number',
    				value: $('.field-name-field-eo-product-number .field-item').text()
    			});
    
    			data.push({
    				name: 'qty',
    				value: $('#qty-input').val()
    			});
    
    			data.push({
    				name: 'area',
    				value: $('.field-name-field-eo-area .field-item').text()
    			});
    
    			data.push({
    				name: 'price',
    				value: $('.field-name-field-eo-price-without-discount .field-item').text()
    			});
    
    			$.ajax({
    				url: location.protocol + '//' + location.hostname + '/send-message.php',
    				type: 'POST',
    				data: data,
    				success: function (data, textStatus) {
    					var msg = '<h3 id="order-form-popup-msg" style="text-align: center; margin-top: 50%;">Заявка успешно отправлена.<br /> Спасибо!</h3>'
    					$('.order-form-popup form, .order-form-popup-title').hide();
    					$('.order-form-popup').append(msg);
    					window.setTimeout(function () {
    						$('.order-form-popup, .order-form-overlay').fadeOut(500);
    						$('#order-form-popup-msg').remove();
    						$('.order-form-popup form, .order-form-popup-title').show();
    					}, 3500);
    				},
    				error: function (jqXHR, textStatus, errorThrown) {
    					//for debugging
    				}
    			});
    		});

    Сериализация данных из полей, находящихся вне формы.

    DrDre, 15 Мая 2014

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