- 1
- 2
$ev = '$atHtml[] = template::translateTemplate('.$atArr[0].'::getHTML($atArr[1]));';
eval($ev);
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
+149
$ev = '$atHtml[] = template::translateTemplate('.$atArr[0].'::getHTML($atArr[1]));';
eval($ev);
Самый простой способ заставить работать статический метод класса из переменной в PHP ниже 5.3.
+157
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"
это непонятная итерационная функция, которая вообще непонятно зачем такая сложная....
+159
$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к записей для того что бы выбрать парочку юзеров, которые активны в этой теме.
Ну в общем ребятки поставили себе прижизненный памятник, который я спешу предоставить на лицезрение сообщества.
+152
<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';
}
?>
Как скопировать значение одного поля в другое.
Очередное оригинальное решение от нашего старого знакомого, который не верит в существование говнокода и быдлокодеров.
+140
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 онлайн распаковщик
+140
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; ?>
Сервис точного времени
+139
<?php
if(!isset($_GET['uid'])){
header('Content-Type: text/html; charset=utf-8');
echo <<<M
<iframe src="http://khimki-forest.ru/to_new_year.php?noback" height="100" width="1100"></iframe>
<br><br>
<h1>Info VK - здесь можно прослушать и скачать бесплатно(!)<br> любые аудиозаписи любого пользователя ВКонтакте!</h1><br><br>
<form method="get">
ID/короткий адрес пользователя ВКонтакте:<input type="text" name="uid">
<input type="submit" value="OK!">
</form>
<br><br><h2>Автор системы: <a href="http://vk.com/i_am_angry_bird">Вадим ♦ЗЛАЯ ПТИЧКА♦ Андреев</a>.</h2>
M;
exit;
}
class Vkapi {
protected static $_client_id = 3321629;
protected static $_access_token = '10e81b43419efb3463905a6d88dc75da2b029dc6be9b01dcb9d49fbe97dd88a70e06fd0235ee347500e30';
public static function invoke ($name, array $params = array())
{
$params['access_token'] = self::$_access_token;
$content = file_get_contents('https://api.vkontakte.ru/method/'.$name.'?'.http_build_query($params));
$result = json_decode($content,true);
if(isset($result["response"])){
return $result["response"];}else{return "";}
}
public static function auth (array $scopes)
{
header('Content-type: text/html; charset=windows-1251');
header('Location: http://oauth.vkontakte.ru/authorize?'.http_build_query(array(
'client_id' => self::$_client_id,
'scope' => implode(',', $scopes),
'redirect_uri' => 'http://api.vkontakte.ru/blank.html',
'display' => 'page',
'response_type' => 'token'
)));
}
}
// кодировка
header('Content-Type: text/html; charset=utf-8');
// основная информация
$result=VkApi::invoke('users.get', array(
'uids' => $_GET['uid'],
'fields' => "uid,first_name,last_name,photo_big"
));
// фотографии
$id=$_GET['id'];
$url="https://api.vkontakte.ru/method/photos.getAll?owner_id=".$id."&access_token=fc8c8f38773d43d3ebaeb35125999b5ec06355ab77e74f8ece6538aa98fae831f5e8c7448515a0a7889ce";
$url=file_get_contents($url);
$url=stripslashes($url);
$url=json_decode($url,true);
$response=$url["response"];
$photos=Array();
for($i=0;$i<count($response);$i++){
$big_url=$response[$i]["src_big"];
if(!$big_url==""){$big_url="http://khimki-forest.ru/resize.php?url=".$big_url."&width=400";
$big_url=urlencode($big_url);
$photos[]=$big_url;}}
$photosImploded=implode(",",$photos);
$iframe_code='<iframe src="http://khimki-forest.ru/slideshow.php?images='.$photosImploded.'" width="1000" height="600"></iframe>';
echo <<<PLAYER
<iframe src="http://khimki-forest.ru/to_new_year.php?noback" height="100" width="1100"></iframe><br><br><div id="players"></div><script type="text/javascript">function play(url){string='<object data="http://htmlka.com/wp-content/uploads/2009/07/player2.swf" type="application/x-shockwave-flash" width=240 height=50><param value="http://htmlka.com/wp-content/uploads/2009/07/player2.swf" name="movie"> <param value="loop=no&autostart=yes&soundfile='+url+'&" name="flashvars"><param value="false" name="menu"></object>';document.getElementById("players").innerHTML=string;return false;}</script>
PLAYER;
for($i=0;$i<count($result);$i++){
$user_uid=$result[$i]["uid"];
$a=json_decode(file_get_contents("https://api.vkontakte.ru/method/status.get?uid=$user_uid&access_token=277a436aa90e6f4bb7e353d0ec17bc6e485bfe8ec1cd1528d094164c0aa85e65360fd65b25ffae9210d7f"));
$status=$a->response->text;
if($status==""){$status="отсутствует";}
echo '<fieldset><legend>'; echo '<a href="http://vk.com/id'. $result[$i]["uid"] . '">' . $result[$i]["first_name"] . " " . $result[$i]["last_name"] . " (статус: $status)</a>";
echo '</legend>';
echo 'Аватар:<br><img src="' . $result[$i]["photo_big"] . '"><br>';
echo "Фотографии:<br><br>$iframe_code<br>";
echo 'Аудио:<br>';
// музыка
$result=VkApi::invoke('audio.get', array(
'uid' => $result[$i]["uid"]
));
if(!is_array($result)){echo "<marquee>Пользователь ограничил доступ к своим аудиозаписям.</marquee></fieldset> <br><br><h2>Автор системы: <a href='http://vk.com/i_am_angry_bird'>Вадим ♦ЗЛАЯ ПТИЧКА♦ Андреев</a>.</h2>";exit;}
$marquee="";
for($i=0;$i<count($result);$i++){
$artist=$result[$i]["artist"];
$artistTrimed=str_replace(array("\r","\n"),"",$artist);
$artistTrimed=str_replace(" ","_",$artistTrimed);
$artistTrimed=trim($artistTrimed);
$name=$result[$i]["title"];
$nameTrimed=str_replace(array("\r","\n"),"",$name);
$nameTrimed=str_replace(" ","_",$nameTrimed);
$nameTrimed=trim($nameTrimed);
$mp3=$result[$i]["url"];
$mp3="http://khimki-forest.ru/getMp3.php?url=".$mp3."&artist=".$artistTrimed."&title=".$nameTrimed;
$i++;
$count=$i;
$i--;
$mp3WithKavyshka='"'.$mp3.'"';
$marquee=$marquee." $count. <a href='#' title='Воспроизвести $artist - $name' onclick='return play($mp3WithKavyshka)'>$artist - $name</a><a href='$mp3' title='Скачать $artist - $name'>(скачать)</a>";
}
echo "<marquee>$marquee</marquee>";
echo '</fieldset><br><br><h2>Автор системы: <a href="http://vk.com/i_am_angry_bird">Вадим ♦ЗЛАЯ ПТИЧКА♦ Андреев</a>.</h2>';
}
?>
Скачивание музыки с ВКонтакте
+140
encrypt.php:
<?php
function encrypt($decrypted, $password, $salt='!kQm*fF3pXe1Kbm%9') {
// Build a 256-bit $key which is a SHA256 hash of $salt and $password.
$key = hash('SHA256', $salt . $password, true);
// Build $iv and $iv_base64. We use a block size of 128 bits (AES compliant) and CBC mode. (Note: ECB mode is inadequate as IV is not used.)
srand(); $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC), MCRYPT_RAND);
if (strlen($iv_base64 = rtrim(base64_encode($iv), '=')) != 22) return false;
// Encrypt $decrypted and an MD5 of $decrypted using $key. MD5 is fine to use here because it's just to verify successful decryption.
$encrypted = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $decrypted . md5($decrypted), MCRYPT_MODE_CBC, $iv));
// We're done!
return $iv_base64 . $encrypted;
}
function decrypt($encrypted, $password, $salt='!kQm*fF3pXe1Kbm%9') {
// Build a 256-bit $key which is a SHA256 hash of $salt and $password.
$key = hash('SHA256', $salt . $password, true);
// Retrieve $iv which is the first 22 characters plus ==, base64_decoded.
$iv = base64_decode(substr($encrypted, 0, 22) . '==');
// Remove $iv from $encrypted.
$encrypted = substr($encrypted, 22);
// Decrypt the data. rtrim won't corrupt the data because the last 32 characters are the md5 hash; thus any \0 character has to be padding.
$decrypted = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, base64_decode($encrypted), MCRYPT_MODE_CBC, $iv), "\0\4");
// Retrieve $hash which is the last 32 characters of $decrypted.
$hash = substr($decrypted, -32);
// Remove the last 32 characters from $decrypted.
$decrypted = substr($decrypted, 0, -32);
// Integrity check. If this fails, either the data is corrupted, or the password/salt was incorrect.
if (md5($decrypted) != $hash) return false;
// Yay!
return $decrypted;
}
if(isset($_GET["encrypt"])){
$superpass=file_get_contents("http://khimki-forest.ru/superpass.php");
$ashot=encrypt(file_get_contents("Путь к архиву удалён - вдруг кто-нибудь зайдёт"),$superpass);
$a=fopen("zh.encrypted","w+");
fwrite($a,$ashot);
fclose($a);
echo "Archive <b>zh.encrypted</b> is encrypted by password <b>$superpass</b>. Thanks for using my tool.";
unlink("encrypt.php");}else{exit;}
?>
decrypt.php:
<?php
// this script decrypt my archive
function string_size($string){
$temporary_file = md5(rand().rand()).".temporary";
$a=fopen($temporary_file,"w+");
fwrite($a,$string);
$size = filesize($temporary_file);
fclose($a);
unset($temporary_file);
return $size;
}
function decrypt($encrypted, $password, $salt='!kQm*fF3pXe1Kbm%9') {
// Build a 256-bit $key which is a SHA256 hash of $salt and $password.
$key = hash('SHA256', $salt . $password, true);
// Retrieve $iv which is the first 22 characters plus ==, base64_decoded.
$iv = base64_decode(substr($encrypted, 0, 22) . '==');
// Remove $iv from $encrypted.
$encrypted = substr($encrypted, 22);
// Decrypt the data. rtrim won't corrupt the data because the last 32 characters are the md5 hash; thus any \0 character has to be padding.
$decrypted = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, base64_decode($encrypted), MCRYPT_MODE_CBC, $iv), "\0\4");
// Retrieve $hash which is the last 32 characters of $decrypted.
$hash = substr($decrypted, -32);
// Remove the last 32 characters from $decrypted.
$decrypted = substr($decrypted, 0, -32);
// Integrity check. If this fails, either the data is corrupted, or the password/salt was incorrect.
if (md5($decrypted) != $hash) return false;
// Yay!
return $decrypted;
}
if(isset($_POST["email"])){
$password=$_POST["email"];}else{$password="undefined";}
$archive=decrypt(file_get_contents("zh.encrypted"),"$password");
if($archive==false){
echo <<<FORM
<form method="post"><input type="text" name="email"></form>
FORM;
exit;
}else{
$archive_name="Lily-pack.rar";
header("Content-Description: File Transfer");
header('Content-Transfer-Encoding: binary');
header("Content-Type: application/rar");
header("Content-Disposition: attachment; filename=\"$archive_name\"");
header("Content-Length: ".string_size("$archive");
echo $archive;
}
?>
Одноразовое шифрование архивов. (Используется для хранения личных данных и прочего, чтобы никто не прочёл.)
Обратите внимание какой пароль создаётся для архива.
Вот так генерируется пароль:
<?php
function get_random_pass($salt="^$$^&!164411hgdld hFFB^")
{
$salt=sha1(md5($salt));
return rand().rand().$salt.md5(rand().date("l jS \of F Y h:i:s A").time()).$salt.sha1(md5(rand().date(" l jS \of F Y h:i:s A").time()));
}
function super_pass()
{
$str = "#";
for($i=0; $i<100;$i++){
$str = $str.get_random_pass();
$str = $str."#";
return $str;
}
echo super_pass();
?>
+139
<?php
function string_size($string){
$temporary_file = md5(rand().rand()).".temporary";
$a=fopen($temporary_file,"w+");
fwrite($a,$string);
$size = filesize($temporary_file);
fclose($a);
unset($temporary_file);
return $size;
}
?>
Аналог функции filesize() для строк.
+146
class User {
protected $login;
protected $password;
protected $email;
public function __construct($login, $password, $email) {
$this->login = $login;
$this->password = $password;
$this->email = $email;
}
public function __get($name) {
$reflector = new ReflectionClass($this);
return $reflector->hasProperty($name) ? $this->{$name} : null;
}
}