- 1
$data_move = date("d.m.Y", mktime(0, 0, 0, (int)date("m",time()), (int)date("d",time()), (int)date("Y",time())));
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
+154
$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()) - в первую следующего.
+154
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.
+154
foreach($arr as $val)
$data[uniqid()] = $val;
Ну для ооочень медленных серверов =)
+154
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'];
}
дали проект чтобы разобрался)
+154
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';
}
...
+154
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;
<...>
Задача: развернуть строку текста (Абв->Вба).
+154
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
+154
(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 для каждой страницы прямо из урла. Предназначалось в качестве костыля для джумлы, так как через пых не работало, а разбираться никто не стал :)
+154
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 строчке, это некое подобие шаблонизатора
+154
$('.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
}
});
});
Сериализация данных из полей, находящихся вне формы.