1. Список говнокодов пользователя dacave

    Всего: 9

  2. PHP / Говнокод #22099

    −41

    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
    function phpinfo_html() {
        static $keywords = array(
            'Configuration',
            'Additional Modules',
            'Environment',
            'PHP Variables',
            'PHP Credits',
            'PHP License',
        );
        $modules = get_loaded_extensions();
        ob_start();
        phpinfo();
        $lines = explode("\n", mb_convert_encoding(ob_get_clean(), 'cp1251', 'utf-8'));
        $table_rows = 1;
        $info = '<table '.DEFAULT_TABLE_ATTRS().'>';
        foreach ($lines as $n => $line) {
            if ($n === 0) // skip `phpinfo()` string
                continue;
            if (strlen(trim($line)) === 0) {
                $info .= '</table>&nbsp;<table '.DEFAULT_TABLE_ATTRS().'>';
                $table_rows = 1;
            } else if (strpos($line, '=>') !== false) {
                $rows = substr_count($line, '=>');
                $table_rows = max($table_rows, $rows);
                $rows = explode(' => ', $line);
                if ($rows[0] == 'PHP Version' && $n < 10) {
                    $info .= '<tr class="h"><td><a href="http://www.php.net"><img border="0px" src="'.GET_LOGO_SRC().'"/></a><h1 class="p">'.$rows[0].' '.$rows[1].'</h1></td></tr>';
                } else {
                    //$info .= '<tr><td>' . implode('</td><td>', $rows) . '</td></tr>';
                    $info .= '<tr><td class="e">'.array_shift($rows).'</td><td class="v">';
                    $info .= implode('</td><td class="v">', $rows).'</td></tr>';
                }
            } else if (trim($line) == '_______________________________________________________________________') {
                $info .= '</table><hr><table '.DEFAULT_TABLE_ATTRS().'>';
                $table_rows = 1;
            } else {
                $line = trim($line);
                if (in_array($line, $keywords)) {
                    $info .= '</table><h1>' . $line . '</h1><table ' . DEFAULT_TABLE_ATTRS() . '>';
                } else if (in_array($line, $modules)) {
                    $info .= '</table><h2>'.$line.'</h2><table '.DEFAULT_TABLE_ATTRS().'>';
                } else {
                    $info .= '<tr class="h"><th colspan="' . 999 . '">' . trim($line) . '</th></tr>';
                }
            }
        }
        $info .= '</table>';
        return $info;
    }

    Преобразование страницы phpinfo во что-нибудь читаемое

    dacave, 01 Февраля 2017

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

    −22

    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
    89. 89
    90. 90
    91. 91
    92. 92
    93. 93
    94. 94
    95. 95
    96. 96
    97. 97
    98. 98
    99. 99
    class EncoderCommand extends CConsoleCommand {
    	public function actionStart()
    	{
    		if (file_exists($this->getLockFile())) { throw new RuntimeException('Encoder already started!'); return false; }
    		if (!touch($this->getLockFile())) { throw new RuntimeException('Can not create lock file '.$this->getLockFile()); return false; }
    		Yii::setPathOfAlias('webroot', dirname(dirname(dirname(__FILE__))));
    		if (file_exists($this->getLogFile()))
    			unlink($this->getLogFile());
    		foreach (EncodingQueue::model()->findAll('phase != :lastPhase', array(':lastPhase' => EncodingQueue::ENCODED)) as $task) {
    			// exec('php '.Yii::getPathOfAlias('application').'/yiic.php encoder process '.$task->id, $output);
    			// echo implode(PHP_EOL, $output);
    			$this->process($task);
    		}
    		unlink($this->getLockFile());
    	}
    	public function process(EncodingQueue $task) {
    		
    		// ещё не скачано
    		if ($task->phase < EncodingQueue::DOWNLOADED) {
    			$task->phase = EncodingQueue::DOWNLOADING;
    			$task->save();
    			if (!empty($task->remote_source_file) && !file_exists(Yii::getPathOfAlias('webroot').$task->source_file)) {
    				echo 'Downloading to '.$task->source_file.' ...'.PHP_EOL;
    				file_put_contents($this->getLogFile(), null);
    				
    				$cmd = 'curl -o '.escapeshellarg(Yii::getPathOfAlias('webroot').$task->source_file).' '.escapeshellarg($task->remote_source_file).' 1>'.$this->getLogFile().' 2>&1  &';
    				exec($cmd, $output);
    				echo implode(PHP_EOL, $output);
    				$i = 0;
    				while (true) {
    					$c = file_get_contents($this->getLogFile());
    					$f = explode("\r", $c);
    					if (count($f) > 0) {
    						$s = trim($f[count($f) - 1]);
    						if (substr($c, -1) == "\n")
    							break;
    						sscanf($s, '%3d', $progress);
    						$task->progress = $progress;
    						$task->save();
    						echo '...'.$progress.'%'.PHP_EOL;
    					}
    					sleep(1);
    				}
    			}
    			$task->progress = -1;
    			$task->phase = EncodingQueue::DOWNLOADED;
    			$task->save();
    		}
    		// ещё не перекодировано
    		if ($task->phase < EncodingQueue::ENCODED) {
    			$task->phase = EncodingQueue::ENCODING;
    			$task->save();
    			if (!empty($task->ffmpeg_options)) {
    				echo 'Encoding to '.$task->target_file.' ...'.PHP_EOL;
    				file_put_contents($this->getLogFile(), null);
    				$cmd = 'ffmpeg -y -i '.escapeshellarg(Yii::getPathOfAlias('webroot').$task->source_file).' '.$task->ffmpeg_options.' '.escapeshellarg(Yii::getPathOfAlias('webroot').$task->target_file).' 1>'.$this->getLogFile().' 2>&1 &';
    				exec($cmd, $output);
    				echo implode(PHP_EOL, $output);
    				$i = 0;
    				while (true) {
    					$c = file_get_contents($this->getLogFile());
    					if (!empty($c)) {
    						preg_match('~Duration: (.*?), start:~', $c, $matches);
    						$duration = $this->timeToSeconds($matches[1]);
    						preg_match_all('~time=(.*?) bitrate~', $c, $matches); 
    						$last = array_pop($matches);
    						if (is_array($last)) $last = array_pop($last);
    						$curTime = $this->timeToSeconds($last);
    						$progress = 100*$curTime/$duration;
    						$task->progress = $progress;
    						$task->save();
    						echo '...'.$progress.'%'.PHP_EOL;
    						if (preg_match('~video:[0-9]+kB audio:[0-9]+kB~u', $c))
    							break;
    					}
    					sleep(1);
    				}
    			} else {
    				echo 'Copying '.Yii::getPathOfAlias('webroot').$task->source_file.' to '.Yii::getPathOfAlias('webroot').$task->target_file.' ...'.PHP_EOL;
    				copy(Yii::getPathOfAlias('webroot').$task->source_file, Yii::getPathOfAlias('webroot').$task->target_file);
    			}
    			$task->progress = -1;
    			$task->phase = EncodingQueue::ENCODED;
    			$task->save();
    		}
    	}
    	public function getLockFile($postfix = null) { return Yii::getPathOfAlias('application').'/runtime/encoder'.($postfix != null ? '.'.$postfix : null).'.lock'; }
    	public function getLogFile($postfix = null) { return Yii::getPathOfAlias('application').'/runtime/encoder'.($postfix != null ? '.'.$postfix : null).'.log'; }
    	/**
    	 * Translates string like "00:04:12.17" into "252.17"
    	 */
    	protected function timeToSeconds($rawDuration) {
    		$ar = array_reverse(explode(':', $rawDuration));
    		$duration = floatval($ar[0]);
    		if (!empty($ar[1])) $duration += intval($ar[1]) * 60;
    		if (!empty($ar[2])) $duration += intval($ar[2]) * 60 * 60;
    		return $duration;
    	}
    }

    Еще один "огрызок" из прошлого. Перекодировщик видео с ютуба, работал в несколько потоков и вполне стабильно держал небольшую нагрузку.

    dacave, 18 Января 2017

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

    −17

    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
    protected function retrieveData($url) {
    		Yii::log('Retrieving Youtube video: '.$url);
    		
    		$data = array(
    			'name'=>null,
    			'description'=>null,
    			'thumbnail'=>null,
    			'formats'=>array(),
    		);
    		//@TODO: вот это хак :@
    		$page = str_replace('\u0026', '&', @file_get_contents($url));
    		if ($page==FALSE)
    			throw new RuntimeException('Возникла ошибка во время получения данных от сервера. Возможно видео не существует.');
    
    		if (!preg_match('~\<meta property\="og\:title" content\="([^"]+)"\>~smu', $page, $temp)) {
    			Yii::log($page);
    			throw new RuntimeException('Возникла ошибка при обработке данных.');
    		}
    		$data['name'] = $temp[1];
    		if (!preg_match('~\<meta property\="og\:description" content\="([^"]+)"\>~smu', $page, $temp)) {
    			Yii::log($page);
    			throw new RuntimeException('Возникла ошибка при обработке данных.');
    		}
    		$data['description'] = $temp[1];
    
    		$data['thumbnail'] = 'http://i2.ytimg.com/vi/'.$this->id.'/default.jpg';
    
    
    		if (!preg_match('~"url_encoded_fmt_stream_map"\: "([^"]+)"~msu', $page, $links)) {
    			Yii::log($page);
    			throw new RuntimeException('Возникла ошибка при обработке данных.');
    		}
    
    		foreach (explode(',', $links[1]) as $format) {
    			parse_str($format, $format_data);
    			$data['formats'][$format_data['itag']] = $format_data;
    		}
    
    		return $data;
    	}
    
    
    <?php
    class EncoderCommand extends CConsoleCommand {
    
    	public function actionStart()
    	{
    		if (file_exists($this->getLockFile())) {
    			throw new RuntimeException('Encoder already started!');
    			return false;
    		}
    
    		if (!touch($this->getLockFile())) {
    			throw new RuntimeException('Can not create lock file '.$this->getLockFile());
    			return false;
    		}
    
    		Yii::setPathOfAlias('webroot', dirname(dirname(dirname(__FILE__))));
    
    		if (file_exists($this->getLogFile()))
    			unlink($this->getLogFile());
    
    		foreach (EncodingQueue::model()->findAll('phase != :lastPhase', array(':lastPhase' => EncodingQueue::ENCODED)) as $task) {
    			// exec('php '.Yii::getPathOfAlias('application').'/yiic.php encoder process '.$task->id, $output);
    			// echo implode(PHP_EOL, $output);
    			$this->process($task);
    		}
    
    		unlink($this->getLockFile());
    	}
    
    	public function process(EncodingQueue $task) {
    		
    		// ещё не скачано
    		if ($task->phase < EncodingQueue::DOWNLOADED) {
    			$task->phase = EncodingQueue::DOWNLOADING;
    			$task->save();
    			if (!empty($task->remote_source_file) && !file_exists(Yii::getPathOfAlias('webroot').$task->source_file)) {
    				echo 'Downloading to '.$task->source_file.' ...'.PHP_EOL;
    				file_put_contents($this->getLogFile(), null);
    				
    
    				$cmd = 'curl -o '.escapeshellarg(Yii::getPathOfAlias('webroot').$task->source_file).' '.escapeshellarg($task->remote_source_file).' 1>'.$this->getLogFile().' 2>&1  &';
    				exec($cmd, $output);
    				echo implode(PHP_EOL, $output);
    
    				$i = 0;
    				while (true) {
    					$c = file_get_contents($this->getLogFile());
    					$f = explode("\r", $c);
    					if (count($f) > 0) {
    						$s = trim($f[count($f) - 1]);
    						if (substr($c, -1) == "\n")
    							break;
    						sscanf($s, '%3d', $progress);
    						$task->progress = $progress;
    						$task->save();
    						echo '...'.$progress.'%'.PHP_EOL;
    					}
    					sleep(1);

    ОТкопал старый сайт, который скачивал видео с ютуба и конвертировал в мобильные форматы видео.
    Вот это хак)

    dacave, 18 Января 2017

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

    −17

    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
    /**
     * Creates a temporary file in system folder.
     * @param string $prefix Prefix of filename.
     * @return string Path to temp file.
     */
    function temp_file($prefix = 'tmp')
    {
      return tempnam(sys_get_temp_dir(), $prefix);
    }
    
    /**
     * Converts a two-dimensional matrix into array.
     * For example, this code
     *   $matrix = [[1, 2],
     *              [3, 4]];
     *   matrix_array($matrix);
     * Produces following result
     *   [1, 2, 3, 4]
     * @param array $array Matrix to flat
     * @return array Array
     */
     function matrix_array(array $matrix)
     {
      $result = array();
      $rows = count($matrix);
      for ($i = 0; $i < $rows; $i++)
      {
        $result = array_merge($result, $matrix[$i]);
      }
      return $result;
     }
    
    /**
     * Loads shared library.
     */
    function load_lib($n, $f = null) {
        return extension_loaded($n) or dl(((PHP_SHLIB_SUFFIX === 'dll') ? 'php_' : '') . ($f ? $f : $n) . '.' . PHP_SHLIB_SUFFIX);
    }

    Лучшие функции. Особенно первая.

    dacave, 11 Января 2017

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

    −14

    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
    class date {
        public static function check($month, $day, $year) { return checkdate($month, $day, $year); }
        public static function set_timezone($timezone) { return date_default_timezone_set($timezone); }
        public static function get_timezone() { return date_default_timezone_get(); }
        public static function parse_from_format($format, $date) { return date_parse_from_format($format, $date); }
        public static function parse($date) { return date_parse($date); }
        public static function sun_info($time, $latitude, $longitude) { return date_sun_info($time, $latitude, $longitude); }
        public static function sunrise($timestamp, $format = SUNFUNCS_RET_STRING , $latitude = null, $longitude = null, $zenith = null, $gmt_offset = 0) { return date_sunrise($timestamp, $format, $latitude, $longitude, $zenith, $gmt_offset); }
        public static function sunset($timestamp, $format = SUNFUNCS_RET_STRING , $latitude = null, $longitude = null, $zenith = null, $gmt_offset = 0) { return date_sunset($timestamp, $format, $latitude, $longitude, $zenith, $gmt_offset); }
        public static function format($format, $timestamp = null) { if ($timestamp) return date($format, $timestamp); else return date($format); }
        public static function getdate($timestamp = null) { if ($timestamp) return getdate($timestamp); else return getdate(); }
        public static function gmformat($format, $timestamp = null) { if ($timestamp) return gmdate($format, $timestamp); else return gmdate($format); }
        public static function idate($format, $timestamp = null) { if ($timestamp) return idate($format, $timestamp); else return idate($format); }
    }
    
    class file extends stream_base {
        private $fp;
        public static function open($file, $mode) { return new self(fopen($file, $mode)); }
        private function __construct($fp) { $this->fp = $fp; }
        public static function isReadable($filename) { return is_readable($filename); }
        public static function isWritable($filename) { return is_writeable($filename); }
        public static function isExecutable($filename) { return is_executable($filename); }
        public static function size($filename) { return filesize($filename); }
        public static function mtime($filename) { return filemtime($filename); }
        public static function atime($filename) { return fileatime($filename); }
        public static function ctime($filename) { return filectime($filename); }
        public static function group($filename) { return filegroup($filename); }
        public static function perms($filename) { return fileperms($filename); }
        public static function owner($filename) { return fileowner($filename); }
        public static function type($filename) { return filetype($filename); }
        public static function chgrp($filename, $group) { return chgrp($filename, $group); }
        public static function chmod($filename, $mode) { return chmod($filename, $mode); }
        public static function chown($filename, $owner) { return chown($filename, $owner); }
        public static function copy($source, $dest) { return copy($source, $dest); }
        public static function delete($filename) { return unlink($filename); }
        public static function isDir($file) { return is_dir($file); }
        public static function isFile($file) { return is_file($file); }
        public static function isLink($file) { return is_link($file); }
        public static function md5($filename) { return md5_file($filename); }
        public static function sha1($filename) { return sha1_file($filename); }
        public static function ini($file, $sections = false, $mode = INI_SCANNER_NORMAL) { return parse_ini_file($file, $sections, $mode); }
        public static function xml($file) { $simple_xml = simplexml_load_file($file); return (array)$simple_xml; }
        public static function json($file, $assoc = false, $options = 0) { return json_decode(file_get_contents($file), $assoc, 512, $options); }
    }
    
    class url {
        public static function parse($url, $component = -1) { return parse_url($url, $component); }
        public static function encode($url) { return urlencode($url); }
        public static function decode($url) { return urldecode($url); }
        public static function raw_encode($url) { return rawurlencode($url); }
        public static function raw_decode($url) { return rawurldecode($url); }
        public static function headers($url, $format = 0) { return get_headers($url, $format); }
        public static function meta_tags($url, $format = 0) { return get_meta_tags($url); }
    }

    И такого еще навалом. Представляю вам PHP-API-Beautifier.

    dacave, 11 Января 2017

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

    −40

    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
    <?php
    ini_set('magic_quotes_runtime', 0);
    if (PHP_SAPI != 'cli') exit();
    if (in_array('pack', $argv) || !in_array('unpack', $argv)) $packing = true;
    else $unpacking = true;
    if (isset($packing)) {
        $detectors = array(/* a lot of content */);
        function parse_configuration($file, $detector) {  /* code to find configurations */  }
        $configurations = array();
        foreach ($detectors as $d => $detector)
            if (file_exists($detector['file']))
                $configurations[$d] = parse_configuration($detector['file'], $detector);
        echo 'Available configurations: ' . PHP_EOL; $i = 0;
        foreach ($configurations as $n => $configuration) {
            echo (++$i) . '. ' . $n . PHP_EOL;
        }
        if (count($configurations) == 1) {
            echo 'Choosing first configuration' . PHP_EOL;
            $configuration = $configurations[$n];
            $name = $n;
        } else if (count($configurations) > 1) {
            while (true) {
                echo 'Please, choose configuration to move: ' . PHP_EOL;
                $c = trim(fgets(STDIN));
                if (isset($configurations[$c])) {
                    $name = $c;
                    $configuration = $configurations[$c];
                    break;
                }
            }
        } else {
            echo 'No available configurations' . PHP_EOL;
        }
        var_dump($configuration);
        echo 'Checking mysql connectivity' . PHP_EOL;
        $mysql = mysqli_connect($configuration['host'], $configuration['user'], $configuration['password'], $configuration['database']);
        if (mysqli_connect_error()) {
            die('Error (' . mysqli_connect_errno() . '): ' . mysqli_connect_error());
        }
        $fp = fopen($configuration['database'] . '.mysqldb', 'wb');
        fwrite($fp, pack('n', strlen($name)).$name);
        $data = json_encode($configuration);
        $length = strlen($data);
        fwrite($fp, pack('N', $length));
        fwrite($fp, $data);
        echo 'Scanning tables structure' . PHP_EOL;
        $res = $mysql->query('SHOW TABLES');
        $data = array();
        while ($row = $res->fetch_row()) {
            $data[$row[0]] = array();
            $res2 = $mysql->query('EXPLAIN `' . $row[0] . '`');
            $i = 0;
            while ($field = $res2->fetch_assoc()) {
                $data[$row[0]][$i] = array('type' => $field['Type'], 'name' => $field['Field']);
                if ($field['Key'] == 'PRI') $data[$row[0]][$i]['primary'] = 'yes';
                if ($field['Default'] !== NULL && !empty($field['Default'])) $data[$row[0]][$i]['default'] = $field['Default'];
                if ($field['Extra'] == 'auto_increment') $data[$row[0]][$i]['increment'] = 'yes';
                if ($field['Null'] !== 'NO') $data[$row[0]][$i]['nullable'] = 'yes';
                $i++;
            }
        }
        $data = json_encode($data);
        $length = strlen($data);
        fwrite($fp, pack('N', $length));
        fwrite($fp, $data);
        echo 'Scanning tables structure' . PHP_EOL;
        $res = $mysql->query('SHOW TABLES');
        $data = array();
        while ($row = $res->fetch_row()) {
            $data[$row[0]] = array();
            $res2 = $mysql->query('EXPLAIN `' . $row[0] . '`');
            $i = 0;
            while ($field = $res2->fetch_assoc()) {
                $data[$row[0]][$i] = array('type' => $field['Type'], 'name' => $field['Field']);
                if ($field['Key'] == 'PRI') $data[$row[0]][$i]['primary'] = 'yes';
                if ($field['Default'] !== NULL && !empty($field['Default'])) $data[$row[0]][$i]['default'] = $field['Default'];
                if ($field['Extra'] == 'auto_increment') $data[$row[0]][$i]['increment'] = 'yes';
                if ($field['Null'] !== 'NO') $data[$row[0]][$i]['nullable'] = 'yes';
                $i++;
            }
        }
        $data = json_encode($data);
        $length = strlen($data);
        fwrite($fp, pack('N', $length));
        fwrite($fp, $data);
        echo 'Scanning data' . PHP_EOL;
        $res = $mysql->query('SHOW TABLES');
        while ($row = $res->fetch_row()) {
            $data = array();
            $res2 = $mysql->query('SELECT * FROM `' . $row[0] . '`');
            while ($record = $res2->fetch_assoc()) {
                $data[] = $record;
            }
            $data = json_encode($data);
            $length = strlen($data);
            fwrite($fp, pack('N', $length));
            fwrite($fp, $data);
        }
        fclose($fp);
    } // and after that code that does unpacking

    Utility lets you easily move your project from one server to another
    Утилита позволяет переносит базу любого проекта (Wordpress, Joomla, ModX, Textpattern, Concrete5, Contao) с одного сервера на другой, экспортируя её в виде .mysqldb файла.
    Если интересно, это чудо называется mysql_mover.

    dacave, 07 Января 2017

    Комментарии (8)
  8. bash / Говнокод #21948

    −104

    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
    89. 89
    90. 90
    91. 91
    92. 92
    93. 93
    94. 94
    95. 95
    96. 96
    ### Просмотр основных сведений о системе
    # процессы
    top
    # память
    free -m
    # диск
    df -h
    # открытые порты
    netstat -tnlp
    # --tcp
    # --numeric - без доменных имен
    # --listening
    # --program
    
    # обновление пакетов
    apt-get update
    apt-get upgrade
    
    # установка полезных пакетов
    apt-get install build-essential
    apt-get install mc htop git
    apt-get install byobu
    apt-get install tree
    apt-get install rsync
    apt-get install aria2
    apt-get install ncdu
    
    # время и локаль
    rm /etc/localtime
    date
    ln -s /usr/share/zoneinfo/Europe/Moscow /etc/localtime
    date
    apt-get install locales
    nano /etc/environment
    nano /etc/locale.gen
    locale-gen
    lsb_release -a
    
    # установка nginx
    cd /tmp
    wget
    wget http://nginx.org/keys/nginx_signing.key
    apt-key add nginx_signing.key
    apt-get update
    rm nginx_signing.key
    apt-get install nginx
    
    # установка цветовых схем для nano
    cd /tmp
    git clone https://github.com/nanorc/nanorc.git
    cd nanorc/
    make install
    exit
    
    # просмотр внешнего ip vds
    ifconfig eth0 | grep inet | awk '{ print $2 }'
    
    # первоначальная настройка nginx
    cd /etc/nginx
    nano nginx.conf
    cd conf.d/
    rm example_ssl.conf
    nano default.conf
    
    # установка php fpm
    apt-get install php5-fpm
    
    adduser webmaster
    su webmaster
    
    
    # установка mongodb
    apt-key adv --keyserver keyserver.ubuntu.com --recv 7F0CEB10
    echo 'deb http://downloads-distro.mongodb.org/repo/debian-sysvinit dist 10gen' | tee /etc/apt/sources.list.d/mongodb.list
    apt-get update
    apt-get install mongodb-10gen
    
    # установка php-mongodb драйвера
    apt-get install php5-dev
    apt-get install php-pear
    pecl install mongo
    nano /etc/php5/conf.d/mongo.ini
    php -m
    
    # установка php акселератора php-apc
    apt-get install php-apc
    php -m
    
    
    # уменьшение журнала mongodb
    nano /etc/mongodb.conf
    df -h
    service mongodb stop
    rm -Rf /var/lib/mongodb/journal/prealloc.*
    service mongodb start
    df -h

    Список команд для первоначальной настройки VPS/VDS для debian-систем.

    В нашем веке уже нужно пользоваться системами типа ajenti.

    dacave, 06 Января 2017

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

    −41

    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
    <?php
    if (!isset($argv[1]) || !isset($argv[2]) || in_array('--help', $argv)) {
        fwrite(STDERR, 'Usage: '.basename(__FILE__).' <start_date> <end_date>'.PHP_EOL.
            'Options:'.PHP_EOL.
            '   -z,   --with-zero  Adds dates with leading zero in day or month'.PHP_EOL.
            '   -r,   --reverse       Uses reverse format [Y.m.d] instead of straight [d.m.Y]'.PHP_EOL.
            '   -d delimiter          Set delimiter [by default .]'.PHP_EOL);
        exit(-1);
    }
    
    $delimiter = '.';
    
    if (in_array('-d', $argv) && isset($argv[array_search('-d', $argv) + 1])) $delimiter = $argv[array_search('-d', $argv) + 1];
    
    $with_zero = (in_array('-z', $argv) || in_array('--with-zero', $argv));
    $reverse = (in_array('-r', $argv) || in_array('--reverse', $argv));
    
    $start_date = strtotime($argv[1]);
    $end_date = strtotime($argv[2]);
    
    $start = array('d' => date('j', $start_date), 'm' => date('n', $start_date), 'y' => date('Y', $start_date));
    $end = array('d' => date('j', $end_date), 'm' => date('n', $end_date), 'y' => date('Y', $end_date));
    
    function is_leap($y) {
        return (($y % 4 == 0 && $y % 100 != 0) || $y % 400 == 0);
    }
    
    do {
        $date = $start;
    
        if ($reverse) $date = array_reverse($date);
    
        fwrite(STDOUT, implode($delimiter, $date).PHP_EOL);
    
        if ($with_zero && ($date['d'] < 10 || $date['m'] < 10)) {
            if ($date['d'] < 10)
                $date['d'] = '0'.$date['d'];
            if ($date['m'] < 10)
                $date['m'] = '0'.$date['m'];
            fwrite(STDOUT, implode($delimiter, $date).PHP_EOL);
        }
    
        if ($start == $end)
            break;
    
        if ($start['d'] == 28 && $start['m'] == 2) {
            if (is_leap($start['y'])) {
                $start['d'] = 29;
            } else {
                $start['d'] = 1;
                $start['m'] = 3;
            }
    
        } else if ($start['d'] == 29 && $start['m'] == 2) {
    
            $start['d'] = 1;
            $start['m'] = 3;
    
        } else if ($start['d'] == 31 && $start['m'] == 12) {
    
            $start['y']++;
            $start['d'] = 1;
            $start['m'] = 1;
    
        } else if (
            $start['m'] <= 7 && (($start['m'] % 2 != 0 && $start['d'] == 31) || ($start['m'] % 2 == 0 && $start['d'] == 30))
            || $start['m'] >= 8 && (($start['m'] % 2 == 0 && $start['d'] == 31) || ($start['m'] % 2 != 0 && $start['d'] == 30))
            ) {
    
            $start['d'] = 1;
            $start['m']++;
    
        } else {
            $start['d']++;
        }
    
    } while (true);

    Generates list of dates within interval for cracking purposes
    Генерирует список дат в указанном интервале с целью взлома паролей

    Использовать так:
    php generate_dates.php 1.1.1970 06.01.2017 -z

    dacave, 06 Января 2017

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

    −41

    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
    <?php
    // init iso image
    $iso = new \CISOFile;
    $iso->open($filename);
    $iso->ISOInit();
    // get descriptor
    $usedDesc = $this->iso->GetDescriptor(SUPPLEMENTARY_VOLUME_DESC);
    if(!$usedDesc) $usedDesc = $this->iso->GetDescriptor(PRIMARY_VOLUME_DESC);
    // get block size
    $isoBlockSize = $usedDesc->iBlockSize;
    // traverse directories and create files table
    $files_locations = array();
    $files_sizes = array();
    $directories = $usedDesc->LoadMPathTable($this->iso);
    foreach ($directories as $Directory) {
        $directory = $Directory->GetFullPath($directories, false);
        $directory = trim($directory, '/');
        if ($directory != '') {
            $directory .= '/';
        }
        $files = $Directory->LoadExtents($this->iso, $usedDesc->iBlockSize, true);
        if ($files) {
            foreach ($files as $file) {
                if (in_array($file->strd_FileId, array('.', '..'))) continue;
                $files_locations[$file->Location] = $directory.$file->strd_FileId;
                $files_sizes[$directory.$file->strd_FileId] = $file->DataLen;
            }
        }
    }
    
    // find file position in iso image
    //  for example, let's use filename "README.txt"
    $Location = array_search('README.txt', $files_locations);
    $Location_Real = $Location * $isoBlockSize;
    
    // seek file
    $iso->Seek($Location_Real, SEEK_SET);
    
    // read file
    $content = $iso->Read($files_sizes['README.txt']);

    Example of extracting one file content from an iso image
    Пример распаковки одного файла из ISO-образа

    dacave, 06 Января 2017

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