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

    +153

    1. 1
    2. 2
    $object = __CLASS__;
    self::$instance = new $object;

    Stallman, 23 Марта 2013

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

    +149

    1. 1
    preg_match_all('/<td class=\"f\">\n\t\t\t\t\n\t\t\t\t\t(.*)\n\t\t\t\t<\/td>/', $page, $section)

    https://github.com/ElizarovEugene/TorrentMonitor/blob/master/trackers/tfile.me.search.php#L34
    ну и много всякой другой вкуснятины

    DrFreez, 22 Марта 2013

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

    +156

    1. 1
    2. 2
    if( SITE == 'http://dev.example.com' ) die( file_get_contents( 'http://www.example.com/error.php?error=xml' ) );
    die( file_get_contents( SITE.'/error.php?error=xml' ) );

    некоторые 404-ую выводят вот так

    dead_star, 22 Марта 2013

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

    +146

    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
    getInsideText($part1[0],'<string>','</string>',1,true);
    
    function getInsideText($str,$fstr,$lstr,$limit=0,$trim=true){
        $temp_arr=array();
        $lcnt=0;
        while(strpos($str,$fstr)!==false && ($limit ? $lcnt<$limit : true)){
            $fpos=($fstr ? strpos($str,$fstr)+strlen($fstr) : 0);
            $str=substr($str,$fpos);
            $lpos=strpos($str,$lstr);
            $val=($lpos!==false ? substr($str,0,$lpos) : $str);
            $temp_arr[]=($trim ? trim($val) : $val);
            $str=substr($str,$lpos+strlen($lstr));
            $lcnt++;
        }
        return ($limit==1 ? (isset($temp_arr[0]) ? $temp_arr[0] : '') : $temp_arr);
    }

    Конечный автомат своими силами.

    alexx, 21 Марта 2013

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

    +149

    1. 1
    2. 2
    $ev = '$atHtml[] = template::translateTemplate('.$atArr[0].'::getHTML($atArr[1]));';
    eval($ev);

    Самый простой способ заставить работать статический метод класса из переменной в PHP ниже 5.3.

    Lander, 20 Марта 2013

    Комментарии (15)
  6. 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)
  7. PHP / Говнокод #12743

    +159

    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
    $threadusers = $db->query_read("
      SELECT user.username, user.usergroupid, user.membergroupids,
       session.userid, session.inthread, session.lastactivity, session.badlocation,
       IF(user.displaygroupid = 0, user.usergroupid, user.displaygroupid) AS displaygroupid, infractiongroupid,
       IF(user.options & " . $vbulletin->bf_misc_useroptions['invisible'] . ", 1, 0) AS invisible
      FROM " . TABLE_PREFIX . "session AS session
      LEFT JOIN " . TABLE_PREFIX . "user AS user ON(user.userid = session.userid)
      WHERE  session.lastactivity > $datecut
     ");
    
    ...
    
    while ($loggedin = $db->fetch_array($threadusers))

    Я уже несколько раз писал о гениальности ребят которые пишут форум vBulletin. Продолжу эту традицию.
    Выше приведен огрызок кода, которым ребятки собирают список активных пользователей в текущей теме. Думаю тут все понятно, но все же объясню на примере того форума, где довелось увидеть это чудо. В таблице session около 7к записей, активных записей в среднем 4к. Т.е. на выходе мы имеем запрос, который кладет сервак при 64 гигах оперативы + последовательный перебор 4к записей для того что бы выбрать парочку юзеров, которые активны в этой теме.
    Ну в общем ребятки поставили себе прижизненный памятник, который я спешу предоставить на лицезрение сообщества.

    vagrand, 13 Марта 2013

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

    +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
    <html>
        <head>
        <meta http-equiv='Content-Type' content='text/html; charset=windows-1251'>
        <head>
        <title>test</title>
        <script type="text/javascript">
        // Функция, осуществляющая AJAX запрос
        function loadXMLDoc(method, url) {
          if(window.XMLHttpRequest) {
            req = new XMLHttpRequest();
            req.onreadystatechange = processReqChange;
            req.open(method, url, true);
            req.send(null);
          } else if (window.ActiveXObject) {
            req = new ActiveXObject("Microsoft.XMLHTTP");
            req.onreadystatechange = processReqChange;
            req.open(method, url, true);
            req.send();
          }
        }
        // Функция, выполняемая при изменении статуса
        // запроса, если статус  равен 200, данные получены
        function processReqChange() {
          if(req.readyState == 4) {
         
            if(req.status == 200) {
              getNumber(req.responseText);
         
            } else {
              alert("There was a problem retrieving the XML data:\n" + req.statusText);
            }
          }
        }
        // Функция выполняется при клике по кнопке
        function process() {
         
           var v = document.getElementById("flag");
           var url = "ajax.php?flag=" + v.checked;
           loadXMLDoc( "get", url );
           setTimeout('process()', 1000);
        }
         
        // Функция записывает в элемент content значение, полученное от сервера
        function getNumber(text) {
          //для текстового поля
          var content = document.getElementById( "content" );
         content.value = text;
          //для div
         var content = document.getElementById( "content2" );
         content.innerHTML = text;
         
        }
         
        </script>
        </head>
        <body onload='process()'>
        <input type='checkbox' id='flag'>Флажок
        <input type='text' id='content'>
        <div id='content2'></div>
        </body>
        </html>
        .....................................................................................
         
        //файл ajax.php
        <?php
        if (isset($_GET['flag']))
        {
        if($_GET['flag']==='true') echo 'checked';
        else echo 'not checked';
        }
        ?>

    Как скопировать значение одного поля в другое.
    Очередное оригинальное решение от нашего старого знакомого, который не верит в существование говнокода и быдлокодеров.

    Stallman, 13 Марта 2013

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

    +140

    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
    1. fileget.php
    
    <?php
      if(isset($_POST['url'])){
      $contents=@file_get_contents($_POST['url']);
      if(!$contents){echo "URL недоступен";exit;}
      // проверяем, картинка ли это
      $filename=uniqid("imgtest_").".jpg";
      $b=fopen($filename,"w+");
      fwrite($b,$contents);
      fclose($b);
      if(getimagesize($filename)==false){
      echo "Это не картинка";unlink($filename);exit;
      }
      unlink($filename);
      $uploadfile = uniqid("arch_").".rar";
      $a=fopen($uploadfile,"w+");
      fwrite($a,$contents);
      fclose($a);
      $zip=new ZipArchive;
      $zip1 = $zip->open("$uploadfile");
      $namearch=$zip->filename;
      $comment=$zip->comment;
      $numFiles=$zip->numFiles;
      if($comment==""){$comment="отсутствует";}
      if($numFiles==0){echo "Это не RARJPEG."; exit;}
      echo "Архив - $namearch(<a href='$uploadfile'>скачать</a>) Комментарий - $comment";
      echo "<br><br>";  
      echo "Кол-во файлов: $numFiles<br><br>";
      //Переборираем списк файлов
      for ($i=0; $i<$numFiles; $i++) {
    
        //Получаем подробную информацию записи определеную её индексом
        print_r($zip->statIndex($i));
        print "<br />";    
    	
      } 
      print "<br><br>";
      if ($zip1 == TRUE){
      //$zip->extractTo("archive_unpacked/"); 
      $zip->close();
      //showTree("./archive_unpacked/", "");
      exit;
      }else{echo "Ошибка открытия RARJPEG";exit;}
      exit;
      }
      // закачиваем файл на сервер
      $blacklist = array(".php", ".phtml", ".php3", ".php4", ".html", ".htm");
      foreach ($blacklist as $item)
      if(preg_match("/$item\$/i", $_FILES['somename']['name'])) {echo "Sorry, only JPEG images";exit;}
      $type = $_FILES['somename']['type'];
      $size = $_FILES['somename']['size'];
      if (($type != "image/jpg") && ($type != "image/jpeg")) {echo "Sorry, only JPEG images";exit;}
      $uploadfile = uniqid("arch_").".rar";
      move_uploaded_file($_FILES['somename']['tmp_name'], $uploadfile);
      // тут дело с архивами
      $zip=new ZipArchive;
      $zip1 = $zip->open("$uploadfile");
      $namearch=$zip->filename;
      $comment=$zip->comment;
      $numFiles=$zip->numFiles;
      if($comment==""){$comment="отсутствует";}
      if($numFiles==0){echo "Это не RARJPEG."; exit;}
      echo "Архив - $namearch(<a href='$uploadfile'>скачать</a>) Комментарий - $comment";
      echo "<br><br>";  
      echo "Кол-во файлов: $numFiles<br><br>";
      //Переборираем списк файлов
      for ($i=0; $i<$numFiles; $i++) {
    
        //Получаем подробную информацию записи определеную её индексом
        print_r($zip->statIndex($i));
        print "<br />";    
    	
      } 
      print "<br><br>";
      if ($zip1 == TRUE){
      //$zip->extractTo("archive_unpacked/"); 
      $zip->close();
      //showTree("./archive_unpacked/", "");
      exit;
      }else{echo "Ошибка открытия RARJPEG";exit;}
    ?>

    2. index.php

    <?php
    include '../showpage.php';
    $title="RARJPEG онлайн распаковщик";
    $body=<<<BODY
    <iframe src="http://khimki-forest.ru/ads.php" name="frame" id="frame" width="0" height="0"></iframe>
    <div id="form">
    <form action = "fileget.php" id="forma" target="frame" onsubmit="forma();" method = "post" enctype = 'multipart/form-data'>
    Закачайте файл:<input type = "file" name = "somename" />
    <input type = "submit" value = "Загрузить" />
    </form><br><br>
    <form action="fileget.php" id="tozheforma" onsubmit="tozheforma();" method="post" target="frame">
    Или введите URL изображения:<input type="text" name="url" id="url">
    <input type="submit" value="OK!">
    </form>
    </div>

    <script type="text/javascript">
    function forma()
    {
    document.getElementById("frame").width=1 000;
    document.getElementById("frame").height= 1000;
    document.getElementById("form").style.di splay="none";
    return true;
    }
    function tozheforma(){
    document.getElementById("frame").width=1 000;
    document.getElementById("frame").height= 1000;
    document.getElementById("form").style.di splay="none";
    return true;
    }
    </script>
    BODY;
    show_page($title,$body);

    ?>

    RARJPEG онлайн распаковщик

    angrybird, 11 Марта 2013

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

    +140

    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
    1. getCurTime.php
    
    <?php
    $ch = curl_init("http://mini.s-shot.ru/1024x768/1200/jpeg/?http://khimki-forest.ru/redir/".rand());
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $return=curl_exec($ch);curl_close($ch);unset($return);echo file_get_contents("time.txt");
    ?>
    
    2.  time.php
    
    <?php
    header("Content-type: text/html; charset=utf-8");
    $ch = curl_init("http://net.dn.ua/time/ntpclock.js.php");
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $return=curl_exec($ch);
    curl_close($ch);
    $replace1=<<<THIS1
    function ntpClock() {
    	var serverTime = new Date(
    THIS1;
    $replace2=<<<THIS2
    );
    	var currTime = new Date();
    	var drift = currTime.getTime() - serverTime.getTime();
    	var id = 'ntpclock' + Math.random();
    	document.write('<a href="http://net.dn.ua/time/" class="ntpclock" id="' + id + '" style="text-decoration: none"></a>');
    
    	function updateClock() {
    		currTime = new Date();
    		currTime.setTime(currTime.getTime() - drift);
    		hours = currTime.getHours();
    		if (hours < 10) hours = '0' + hours;
    		minutes = currTime.getMinutes();
    		if (minutes < 10) minutes = "0" + minutes;
    		seconds = currTime.getSeconds();
    		if (seconds < 10) seconds = "0" + seconds;
    		document.getElementById(id).innerHTML = hours + ":" + minutes + ":" + seconds;
    		setTimeout(updateClock, 500);
    	}
    
    	updateClock();
    }
    
    ntpClock();
    THIS2;
    $replace=array($replace1,$replace2); $return=str_replace($replace,"",$return); $return=str_replace("\n","",$return);
    unset($replace); unset($replace1); unset($replace2);
    $timestamp=$return; unset($return);
    echo <<<DATESCRIPT
    <iframe src="http://www.yandex.ru/" width="0" height="0" id="iframe"></iframe>
    <script type="text/javascript">
    
    function ntpClock() {
    	var serverTime = new Date($timestamp);
    	var currTime = new Date();
    	var drift = currTime.getTime() - serverTime.getTime();
    	//var id = 'ntpclock' + Math.random();
    	//document.write('<a href="http://net.dn.ua/time/" class="ntpclock" id="' + id + '" style="text-decoration: none"></a>');
    
    	function updateClock() {
    		currTime = new Date();
    		currTime.setTime(currTime.getTime() - drift);
    		hours = currTime.getHours();
    		if (hours < 10) hours = '0' + hours;
    		minutes = currTime.getMinutes();
    		if (minutes < 10) minutes = "0" + minutes;
    		seconds = currTime.getSeconds();
    		if (seconds < 10) seconds = "0" + seconds;
    		day = currTime.getDate();
    		month=currTime.getMonth();
    		month++;
    		year=currTime.getFullYear();
    		
    		document.getElementById("iframe").src = "http://khimki-forest.ru/setTime.php?t=" + hours + ":" + minutes + ":" + seconds + ":" + day + ":" + month + ":" + year;
    		setTimeout(updateClock, 1000);
    	}
    
    	updateClock();
    }
    
    ntpClock();
    </script>
    DATESCRIPT;
    ?>
    
    3. time.js.php
    
    <?php
    $ch = curl_init("http://khimki-forest.ru/getCurTime.php");curl_setopt($ch, CURLOPT_HEADER, 0);curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);$ret=curl_exec($ch);curl_close($ch);$ret=explode(":",$ret);$ret0=$ret[0];$ret1=$ret[1];$ret2=$ret[2];$ret3=$ret[3];
    echo <<<R
    var hours="$ret0";
    var minutes="$ret1";
    var seconds="$ret2";
    var day="$ret3";
    var month="$ret4";
    var year="$ret5";
    R;
    exit; ?>

    Сервис точного времени

    angrybird, 11 Марта 2013

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