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

    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
    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
    Нам нужно больше запросов в БД!!!!111 строим дерево меню:
        private function Stack($PageCategory) {
          $Menu = NULL;
          $Q = 'SELECT * FROM '.$this->table.' WHERE pageCategory = '.$PageCategory.' ORDER BY pagePosition;';
          $Result = $this->Result($Q);
          while($Row = mysql_fetch_assoc($Result)) {
            $Row['pageChilds'] = $this->Stack($Row['pageID']);
            $Menu[$Row['pageID']] = $Row;
          }
          return $Menu;
        }
    
    AUTOINCREMENT PHP-way:
        private function CurrentID() {
          $Q = 'SELECT MAX(pageID) as maxID FROM '.$this->table.';';
          $Row = $this->Row($Q);
          return ++$Row['maxID'];
        }
    
    Так форматируем даты:
        private function FormatDate() {
          $Year = substr($this->publication['publicationDate'], 0, 4);
          $Month = substr($this->publication['publicationDate'], 5, 2);
          $Day = substr($this->publication['publicationDate'], 8, 2);
          return $Day.'.'.$Month.'.'.$Year;
        }
    
    Просто контроллер:) А чо?
    <?php
      
      class Slider extends DataBase {
        
        private $slides;
        
        public function GetSlides() {
          $Q = 'SELECT * FROM slide ORDER BY slidePosition;';
          $this->slides = $this->Rows($Q);
        }
        
        public function ViewSlides() {
          $Slides = '';
          if($this->slides) {
            foreach($this->slides as $SlideStack) {
              $Slides .= $this->ViewSlide($SlideStack);
            }
          }
          return $Slides;
        }
        
        private function ViewSlide($SlideStack) {
          $A = '<a href="'.$SlideStack['slideLink'].'">';
          $A .= '  <div class="BannerSlide">';
          $A .= '    <img src="'.I.'/slides/'.$SlideStack['slideImage'].'.jpg">';
          $A .= '    <div class="BannerSlideText">';
          $A .= '      <div class="BannerSlideTextInner">'.$SlideStack['slideName'].'<br>';
          $A .= '        <span>'.$SlideStack['slideText'].'</span>';
          $A .= '      </div>';
          $A .= '    </div>';
          $A .= '  </div>';
          $A .= '</a>';
          return $A;
        }
        
      } // End class
      
    ?>

    Окунулся в велосипедную CMS, на которой ваяет контора http://fn85.ru/

    nik757, 18 Мая 2016

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

    +3

    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
    function pluralize($num) {
            switch ($num) {
                case 1:
                case 21:
                    $word = "товар";
                    break;
                case 2:
                case 3:
                case 4:
                case 22:
                case 23:
                case 24:
                case 32:
                case 33:
                case 34:
                    $word = "товара";
                    break;
                default:
                    $word = "товаров";
                    break;
            }
            return $word;
    }

    На продакшене.

    dgkj, 18 Мая 2016

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

    +2

    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
    <?
    $lasturl = ($_GET[url]) ? $_GET[url] : $CONFIG[site_url]; // последний урл
    
    $expire = ($_GET[expire] == 1) ? time() + 365*24*60*60 : 0;
    
    $domain = str_replace('www.', '', $_SERVER['HTTP_HOST']);
    
    if (preg_match('/^[\d\.]*$/', $domain)) $cookie_domain = $domain; // ip-домен
    else {$temp = explode('.', $domain); $temp = array('', $temp[count($temp)-2], $temp[count($temp)-1]); $cookie_domain = implode('.', $temp);}
    
    setcookie($CONFIG[cookie_name], serialize(array($_GET[user_id],$_GET[password])), $expire, $CONFIG[cookie_path], $cookie_domain,
    	$CONFIG[cookie_secure], true);
    if($_GET['iframe'])
    {
        setcookie('iframe', '1', $expire, $CONFIG[cookie_path], $cookie_domain,
            $CONFIG[cookie_secure], true);
    }
    
    $i = array_search('www.'.$domain, $CONFIG[domains]);
    
    
    if ($i && $CONFIG[domains][$i] && $i == count($CONFIG[domains]) - 1) $url = $lasturl;
    else
    	$url = 'http://'.$CONFIG[domains][$i+1].'/domain_login/?user_id='.$_GET[user_id]
    	.'&password='.$_GET[password].'&expire='.$_GET[expire].'&url='.rawurlencode($lasturl).'&iframe='.($_GET['iframe']?'1':'0');
    
    header("Location: $url");
    
    ScriptEnd();
    
    
    ?>

    ... когда хочется бросить все и уехать в деревню. Наслаждаться утренней свежестью, слушать пение птиц. День за днем восстанавливая психику так беспощадно порушенную жестокими людьми-самозванцами, порочащими нашу профессию богов!

    © "PHP. Немного боли и страдания"

    3371, 17 Мая 2016

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

    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
    public function format_phone($phone) {
            $phone       = preg_replace("/\D/", "", $phone);
            $first_digit = substr($phone, 0, 1);
            if ($first_digit == "7" || $first_digit == "8") {
                $phone = substr($phone, 1);
            }
            if ($first_digit == "+") {
                $phone = substr($phone, 2);
            }
            $p     = str_split($phone);
            $phone = "(" . $p[0] . $p[1] . $p[2] . ") " . $p[3] . $p[4] . $p[5] . "-" . $p[6] . $p[7] . "-" . $p[8] . $p[9];
            return $phone;
    }

    dgkj, 17 Мая 2016

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

    +3

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    if(!empty($arResult["PostToShow"]["SPERM"]))
    {
    	$arResult["PostToShow"]["FEED_DESTINATION"]['SELECTED'] = Array();
    	if (empty($arResult["PostToShow"]["SPERM"]))
    	{

    Проверка в битриксовском стандартном компоненте

    govnopis, 16 Мая 2016

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

    +4

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    ob_start();
    print_r($_POST);
    #error_log(print_r($_POST,true)."\n",3,"/ramdisk/addcm.log");
    $r = ob_get_contents();
    ob_end_clean();
    //$err[] = $r;

    Debug by ©senior shaurma developer

    pahhan, 16 Мая 2016

    Комментарии (0)
  7. C# / Говнокод #20016

    0

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    7. 7
    8. 8
    9. 9
    foreach (var r in rezList)
    {
        int newId = rnd.Next();
        rez.Add(new FileItem()
        {
            Id = newId,
            /* ..... */
         });
    }

    Новый способ генерирования ID...

    kontora, 16 Мая 2016

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

    +4

    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
    if ($_SESSION['USER_LOGIN_IN']) {
    if ($Page != 'notice') {
    $Num = mysqli_fetch_row(mysqli_query($CONNECT, "SELECT COUNT(`id`) FROM `notice` WHERE `status` = 0 AND `uid` = $_SESSION[USER_ID]"));
    if ($Num[0]) MessageSend(2, 'У вас есть непрочитанные уведомления. <a href="/notice">Прочитать ( <b>'.$Num[0].'</b> )</a>', '', 0);
    }
    
    
    
    
    
    $Count = mysqli_fetch_row(mysqli_query($CONNECT, "SELECT COUNT(`id`) FROM `dialog` WHERE `recive` = $_SESSION[USER_ID] AND `status` = 0"));
    if ($Count[0]) MessageSend(2, 'У вас есть непрочитанные диалоги ( <b>'.$Count[0].'</b> )', '', 0);
    }

    Кто хочет, может использовать данную уязвимость, потому что автор сего говна имеет сайт своего паршива, написанного по его же говноурокам. http://php.webtm.ru/

    Архивы с говнокодом(больше лулзов) можно скачать тут http://php.webtm.ru/archive/
    Группа вконтактке тут http://vk.com/php.youtube
    Страничка автора говноуроков(да он думал что может скрыться) http://vk.com/vyjt3dfc1azyr0lilcq ранее назывался Артем Кодов

    Keeper, 16 Мая 2016

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

    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
    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
    function loadQuestionsInTest() {
      $mysqli = connectDB();
      $testID = $_POST['testID'];
      $testSets = $mysqli -> query('select * from testsets where test_id = '.$testID.';');
      if ($testSets->num_rows > 0) {
        $query = [];
        while ($row = $testSets -> fetch_assoc()) {
          $loID = $row['lo_id'];
          $questionsCount = $row['count'];
          $questionsInLO = $mysqli -> query('select count(*) as num from questions where lo_id = '.$loID.';') -> fetch_assoc()['num'];
          if ($questionsCount > $questionsInLO)
            $questionsCount = $questionsInLO;
          $query[] = '(select id, content, result, lo_id from questions where lo_id = '.$loID.' order by rand() limit '.$questionsCount.')';
        }
        $query = implode(' union ', $query).' order by rand();';
        
        $questionRes = $mysqli -> query($query);
        $questions = array();
        while ($row = $questionRes->fetch_assoc()) {
          $questionType = json_decode($row['result']) -> type;
          if ($questionType == 'check') {
            $question = array(
              'id' => $row['id'],
              'content' => $row['content'],
              'loID' => $row['lo_id']
            );
            array_push($questions, $question);
          } else if ($questionType == 'input') {
            $questionContent = json_decode($row['result']);
            $questionText = $questionContent -> text;
            $answers = $questionContent -> answers;
            for ($i = count($answers) -1; $i >= 0; $i--)
              $questionText = mb_substr_replace($questionText, '(|answer'.$answers[$i] -> id.'|)', $answers[$i] -> posStart, $answers[$i] -> posEnd - $answers[$i] -> posStart);
            $content = array( 'type' => 'input', 'text' => $questionText );
            $question = array(
              'id' => $row['id'],
              'content' => json_encode($content, JSON_UNESCAPED_UNICODE),
              'loID' => $row['lo_id']
            );
            array_push($questions, $question);
          }
        }
        $response = json_encode($questions, JSON_UNESCAPED_UNICODE);
        echo $response;
        $mysqli -> close();
        return;
      }
      echo '[]';
      $mysqli -> close();
    }

    Моя дипломная работа по теме "тестирование студентов". Загрузка вопросов для прохождения теста из базы. Вопросы должны идти в рандомном порядке, варианты ответов тоже.

    cotheq, 16 Мая 2016

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

    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
    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
    function saveQuestion() {
    	var questionContent = {};
    	var questionResult = {};
    	switch(questionFields.attr('class')) {
    		case 'check-question':
    			questionResult.text = questionFields.children('.question-text')[0].innerText;																				
    			questionResult.type = 'check';
    			questionResult.answers = [];
    			[].forEach.call(questionFields.children('.answer-preview'), function(answerElement, i, arr) {
    				var answer = {};
    				answer.text = $(answerElement).children('.answer-text')[0].innerText;
    				answer.right = ($(answerElement).children('.answer-check')[0].checked) ? 1 : 0;
    				answer.weight = (!answer.right) ? $(answerElement).children('.answer-weight')[0].getPosition() : 1;
    				answer.weight = (answer.weight > 0 && answer.weight <= 1) ? answer.weight : 0;
    				questionResult.answers.push(answer);
    			});
    			
    			if (checkQuestionCorrect(questionResult)) {
    				questionResult= JSON.stringify(questionResult);
    				questionContent = JSON.parse(questionResult); //клонируем объект
    				[].forEach.call(questionContent.answers, function(answer, i, answers) { delete answer.right; delete answer.weight; });
    				questionContent = JSON.stringify(questionContent);
    				console.log('result: ' + questionResult);
    				console.log('content: ' + questionContent);
    				net.addQuestion(loID, questionContent, questionResult, function(r){
    					$('.add-question').slideUp(200, function(){
    						$('.add-question-row').remove();
    						openLOPreview(loID);
    					});
    				});
    			}
    		break;	
    		
    		case 'input-question':
    			var highlights = highlighter.highlights;
    			questionResult.type = 'input';
    			questionResult.text = $('#question-text-area').get(0).innerText;
    			questionResult.answers = [];
    			for (i = 0; i < highlights.length; i++) {
    				var answer = {};
    				answer.id = highlights[i].id;
    				answer.posStart = highlights[i].characterRange.start;
    				answer.posEnd = highlights[i].characterRange.end;
    				answer.text = highlights[i].answerText;
    				answer.strict = ('strict' in highlights[i]) ? highlights[i].strict : true;
    				questionResult.answers.push(answer);
    			}
    			questionResult.answers.sort(function(a, b){ return a.posStart - b.posStart; });
    			questionResult.serializedHighlight = highlighter.serialize();
    			questionResult = JSON.stringify(questionResult);
    			questionContent = JSON.stringify(questionContent);
    			
    			net.addQuestion(loID, questionContent, questionResult, function(r){
    				$('.add-question').slideUp(200, function(){
    						$('.add-question-row').remove();
    						openLOPreview(loID);
    					});
    			});	
    		break;
    		
    		default: break;
    	}							
    }

    Моя дипломная работа по теме "тестирование студентов". Конструктор тестов, обработчик кнопки сохранения вопроса. Используются библиотеки jQuery и Rangy (для работы с выделением текста).

    cotheq, 16 Мая 2016

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