<?php
session_start();
set_time_limit( 0 );
header( 'Content-type: text/html; charset=UTF-8' );

define( 'ROOT', 'http://'.$_SERVER['HTTP_HOST'] );
define( 'ROOT_DIR', $_SERVER['DOCUMENT_ROOT'] );

include_once ROOT_DIR . '/engine/config.php';
include_once ROOT_DIR . '/engine/func.php';




/*---Настройка цен---*/ 
if ( $_GET['func'] == 'coment' ) { 


if ( !isset( $_SESSION['id'] ) ) exit(); 

$id=intval($_POST[idtovar]);
$reyting=intval($_POST[reyting]);
if ( empty( $id ) )  exit(); 
$coment=clean($_POST[coment]);
if($reyting=='') { echo "Необходимо поставить оценку товару!"; exit;}
if($coment=='') { echo "Комментарий не должен быть пустым!"; exit;}
if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit(); 
$config_us = $pdo->Query("SELECT COUNT(*) from php_coment WHERE iduser = '" . $_SESSION['id'] . "' and idtovar='".$id."'")->fetch(PDO::FETCH_BOTH); 
if ($config_us['COUNT(*)']!=0) { 
echo 'Вы уже оставляли отзыв на данный товар!'; 
exit(); 
} else { 
$lo = $pdo->Query("SELECT login from php_user WHERE id = '" . $_SESSION['id']. "' LIMIT 1")->fetch(PDO::FETCH_BOTH);

$pdo->Query("INSERT INTO `php_coment` (	idtovar	,iduser, user, coment, reyting, cdate) VALUES('$id', '" . $_SESSION['id'] . "', '$lo[login]', '$coment', '$reyting', '".time()."')");

echo 1; 
exit(); 
} 
}


/*---Настройка цен---*/
if ( $_GET['func'] == 'set' ) {
    $pdo->Query("UPDATE `php_user` SET yandex = '" . $_POST['yandex'] . "', payeer = '" . $_POST['payeer'] . "', qiwi = '" . $_POST['qiwi'] . "' WHERE `id` = '" . $_SESSION['id'] . "' LIMIT 1");
    echo 1;
    exit();
}


/*---Удаление рекламной площадки (серфинг)---*/
if ( $_GET['func'] == 'dynlinkdel' ) {
     $del_tov = $pdo->Query("SELECT * from php_upload WHERE tovar = '" . ( int ) $_POST['id'] . "' LIMIT 1")->fetch(PDO::FETCH_BOTH);
     $d_tovar = $del_tov['catalog'];
     @unlink(ROOT_DIR.'/kukus/'.$d_tovar);

     $del_im = $pdo->Query("SELECT * from php_img WHERE tovar = '" . ( int ) $_POST['id'] . "' LIMIT 1")->fetch(PDO::FETCH_BOTH);
     $d_img = $del_im['dir'];
     @unlink(ROOT_DIR.'/'.$d_img);

     $pdo->Query( "DELETE FROM `php_upload` WHERE tovar = '" . ( int ) $_POST['id'] . "'" );
     $pdo->Query( "DELETE FROM `php_tovar` WHERE id = '" . ( int ) $_POST['id'] . "'" );
     $pdo->Query( "DELETE FROM `php_img` WHERE tovar = '" . ( int ) $_POST['id'] . "'" );
    echo 1;
    exit();
}

/*---Смена цены---*/
if ( $_GET['func'] == 'savestavka' ) {

    sleep(1);

    if ( !isset( $_SESSION['id'] ) ) exit();

    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();

     if ( !preg_match( '/^[-+]?[\d]+[\.][\d]{1,2}+$|^[-+]?[\d]+$/', $_POST['stavka'] ) ) {
        echo 'Неверная сумма!';
        exit();
    } else
    if ( empty( $_POST['stavka'] ) ) {
        echo 'Вы не указали цену!';
        exit();
    } else {

		$pdo->Query( "UPDATE php_tovar SET cena = '" . floatval( $_POST['stavka'] ) . "' WHERE id = '" . ( int ) $_POST['idpost'] . "' and user = '" . $_SESSION['id'] . "'" );
		echo 'Успешная смена цены!';
		exit();
	}

}


/*---Настройка цен---*/ 
if ( $_GET['func'] == 'arrow_tovar' ) { 

sleep(1); 

if ( !isset( $_SESSION['id'] ) ) exit(); 

if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit(); 
$config_us = $pdo->Query("SELECT * from php_user WHERE id = '" . $_SESSION['id'] . "'")->fetch(PDO::FETCH_BOTH); 
if (49 > $config_us['money'] ) { 
echo 'На Вашем рекламном счету недостаточно средств!'; 
exit(); 
} else { 
$pdo->Query("UPDATE `php_tovar` SET data_up = '" . time() . "' WHERE `user` = '" . $_SESSION['id'] . "' and `id` = '" . ( int ) $_POST['id'] . "' LIMIT 1"); 
$pdo->Query("UPDATE `php_user` SET `money` = `money` - '49' WHERE `id` = '" . $_SESSION['id'] . "'"); 
echo 1; 
exit(); 
} 
}



/*---Новое сообщение---*/
if ( $_GET['func'] == 'newmsg' ) {

    sleep(1);

    if ( !isset( $_SESSION['id'] ) ) exit();

    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();

    $_POST['text'] = trim( $_POST['text'] );


    $text = $_POST['text'];

    $sql = mysql_query( "SELECT id FROM php_user WHERE id = '" . ( int ) $_POST['id'] . "' LIMIT 1" );
    $row = mysql_fetch_array( $sql );

    if ( mysql_num_rows( $sql ) == 0 ) {
        echo 'Пользователь не найден!';
        exit();
    } else
    if ( ( int ) $_POST['id'] == $_SESSION['id'] ) {
        echo 2;
        exit();
    } else
    if ( empty( $_POST['text'] ) ) {
        echo 2;
        exit();
    } else {
        mysql_query( "INSERT INTO php_messages SET from_id = '" . $_SESSION['id'] . "', to_id = '" . ( int ) $_POST['id'] . "', text = '" . substr( $text, 0, 1000 ) . "', data = '" . time() . "', m_state = 'inbox', m_type = 0, history = '" . $_SESSION['id'] . "'" );
        mysql_query( "INSERT INTO php_messages SET from_id = '" . $_SESSION['id'] . "', to_id = '" . ( int ) $_POST['id'] . "', text = '" . substr( $text, 0, 1000 ) . "', data = '" . time() . "', m_state = 'outbox', m_type = 0, history = '" . ( int ) $_POST['id'] . "'" );

        echo 1;
        exit();
    }
}

/*---Удаление личных входящих сообщений---*/
if ( $_GET['func'] == 'delmsgin' ) {

    if ( !isset( $_SESSION['id'] ) ) exit();

    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();

    $msg = mysql_query( "SELECT from_id, to_id, m_state, from_del, to_del FROM php_messages WHERE id = '" . ( int ) $_POST['id'] . "' LIMIT 1" );

    if ( mysql_num_rows( $msg ) > 0 ) {
        $row = mysql_fetch_array( $msg );

        if ( $row['m_state'] == 'inbox' and $row['to_id'] == $_SESSION['id'] ) {
            mysql_query( "UPDATE php_messages SET to_del = 1 WHERE id = '" . ( int ) $_POST['id'] . "'" );

            echo 1;
            exit();
        } else
        if ( $row['m_state'] == 'outbox' and $row['from_id'] == $_SESSION['id'] ) {
            mysql_query( "UPDATE php_messages SET from_del = 1 WHERE id = '" . ( int ) $_POST['id'] . "'" );

            echo 1;
            exit();
        }
    }
}

/*---Удаление всех личных входящих сообщений---*/
if ( $_GET['func'] == 'delmsginall' ) {

    if ( !isset( $_SESSION['id'] ) ) exit();

    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();

    $msg = mysql_query( "SELECT id, from_id, to_id, m_state, from_del, to_del, history FROM php_messages WHERE (from_id = '" . ( int ) $_POST['id'] . "' and to_id = '" . $_SESSION['id'] . "') or (from_id = '" . $_SESSION['id'] . "' and to_id = '" . ( int ) $_POST['id'] . "')" );

    if ( mysql_num_rows( $msg ) > 0 ) {
        while ( $row = mysql_fetch_array( $msg ) ) {

            if ( $row['m_state'] == 'inbox' and $row['to_id'] == $_SESSION['id'] ) {
                mysql_query( "UPDATE php_messages SET to_del = 1, m_type = 1 WHERE id = '" . $row['id'] . "'" );
            }
            if ( $row['m_state'] == 'outbox' and $row['from_id'] == $_SESSION['id']) {
                mysql_query( "UPDATE php_messages SET from_del = 1 WHERE id = '" . $row['id'] . "'" );
            }
        }
        echo 1;
        exit();
    }
}

/*---Удаление личных исходящих сообщений---*/
if ( $_GET['func'] == 'delmsgout' ) {

    if ( !isset( $_SESSION['id'] ) ) exit();

    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();

    $msg = mysql_query( "SELECT from_id, to_id, m_state, from_del, to_del FROM php_messages WHERE id = '" . ( int ) $_POST['id'] . "' LIMIT 1" );

    if ( mysql_num_rows( $msg ) > 0 ) {
        $row = mysql_fetch_array( $msg );

        if ( $row['m_state'] == 'inbox' and $row['to_id'] == $_SESSION['id'] ) {
            mysql_query( "UPDATE php_messages SET from_del = 1 WHERE id = '" . ( int ) $_POST['id'] . "'" );

            echo 1;
            exit();
        } else
        if ( $row['m_state'] == 'outbox' and $row['from_id'] == $_SESSION['id'] ) {
            mysql_query( "UPDATE php_messages SET to_del = 1 WHERE id = '" . ( int ) $_POST['id'] . "'" );

            echo 1;
            exit();
        }
    }
}

/*---Удаление всех личных исходящих сообщений---*/
if ( $_GET['func'] == 'delmsgoutall' ) {

    if ( !isset( $_SESSION['id'] ) ) exit();

    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();

    $msg = mysql_query( "SELECT id, from_id, to_id, m_state, from_del, to_del, history FROM php_messages WHERE (from_id = '" . ( int ) $_POST['id'] . "' and to_id = '" . $_SESSION['id'] . "') or (from_id = '" . $_SESSION['id'] . "' and to_id = '" . ( int ) $_POST['id'] . "')" );

    if ( mysql_num_rows( $msg ) > 0 ) {
        while ( $row = mysql_fetch_array( $msg ) ) {

            if ( $row['m_state'] == 'inbox' and $row['to_id'] == $_SESSION['id'] ) {
                mysql_query( "UPDATE php_messages SET from_del = 1 WHERE id = '" . $row['id'] . "'" );
            }
            if ( $row['m_state'] == 'outbox' and $row['from_id'] == $_SESSION['id'] ) {
                mysql_query( "UPDATE php_messages SET to_del = 1 WHERE id = '" . $row['id'] . "'" );
            }
        }
        echo 1;
        exit();
    }
}







/*---Восстановления пароля---*/
if ( $_GET['func'] == 'resore_pass' ) {
    sleep(1);

    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) exit();

    if ( !preg_match( "/^(?:[a-z0-9]+(?:[-_]?[a-z0-9\.\-\_]+)?@[a-z0-9]+(?:\.?[a-z0-9]+)?\.[a-z]{2,5})$/i", $_POST['email'] ) ) {
        echo 'Неверно указан email, проверьте введенные данные!';
        exit();
    } else {
        $sql = mysql_query( "SELECT id, login FROM php_user WHERE email = '" . check_text( $_POST['email'] ) . "'" );
        if ( mysql_num_rows( $sql ) > 0 ) {
            $row = mysql_fetch_array( $sql );


            $recovery_pass = generate( 8 );

            include_once ROOT_DIR . '/engine/libmail.php'; // подключаем SMTP class

            $message = '
            <html>
            <head>
            <title>Восстановление пароля на проекте ' . $config_site['sitename'] . '</title>
            <style type="text/css">
            html, body {
                margin:0;
                margin-left:5px;
                padding:0;
                font-size:12px;
            }
            p {
                margin:0;
                padding:3px;
            }
            </style>
            </head>
            <body>
            <p>Здравствуйте, <b>' . $row['login'] . '</b>.</p>
            <p>--------------------------------------------------------------------------</p>
            <p>Для входа на сайт используйте следующие данные:</p>
            <p>--------------------------------------------------------------------------</p>
            логин: <b>' . check_text( $row['login'] ) . '</b><br />
            новый пароль: <b>' . $recovery_pass . '</b><br />
            IP: <b>' . real_IP() . '</b><br />
            Дата: <b>' . date( 'd.m.Y H:i', time() ) . '</b><br />
            <p>--------------------------------------------------------------------------</p>
            <p>Письмо отправлено автоматически. На него отвечать не нужно.</p>
            </body>
            </html>';

            $m = new Mail;
            $m->From( 'Администрация;' . $config_site['smtp_email'] ); // от кого отправляется почта
            $m->To( $_POST['email'] ); // кому адресованно
            $m->Subject( 'Восстановление пароля на проекте ' . $_SERVER["HTTP_HOST"] );
            $m->Body( $message );
            //$m->Cc( "copy@asd.com"); // копия письма отправится по этому адресу
            //$m->Bcc( "bcopy@asd.com"); // скрытая копия отправится по этому адресу
            $m->Priority( 3 ); // приоритет письма
            //$m->Attach( "asd.gif","", "image/gif" ) ; // прикрепленный файл
            $m->smtp_on( $config_site['smtp_port'], $config_site['smtp_email'], $config_site['password'], $config_site['port'] ); // если указана эта команда, отправка пойдет через SMTP
            $m->Send(); // а теперь пошла отправка

            $pdo->Query( "UPDATE php_user SET pass = '" . pass_hash( $recovery_pass ) . "' WHERE id = '" . $row['id'] . "'" );
            echo 'Вам отправлен новый пароль!';
            exit();
        } else {
            echo 'Указанный email не существует!';
            exit();
        }
    }
}

/*---Изменение аватара---*/
if ( $_GET['func'] == 'newavatar' ) {

    if ( !isset( $_SESSION['id'] ) ) exit();

    if ( !$_FILES['newavatar']['name'] ) {
        echo 'Вы не выбрали аватара';
        exit();
    } else
    if ( $_FILES["newavatar"]["size"] <= 0 and $_FILES["newavatar"]["size"] > 200 * 1024 ) {
        echo 'Максималный размер аватара 200 кб.!';
        exit();
    } else
    if ( $_FILES['newavatar']['type'] != 'image/jpg' and  $_FILES['newavatar']['type'] != 'image/jpeg' and $_FILES['newavatar']['type'] != 'image/png' and $_FILES['newavatar']['type'] != 'image/gif') {
        echo 'Неверный формат изображения!';
        exit();
    } else
    if ( is_uploaded_file( $_FILES["newavatar"]["tmp_name"] ) ) {
        $imgwh = GetImageSize( $_FILES["newavatar"]["tmp_name"] );

        if ( $imgwh[0] > 100 or $imgwh[1] > 100 or $imgwh[0] < 100 or $imgwh[1] < 100 ) {
            echo 'Допустимый размер аватара 100 х 100!';
            exit();
        } else {
            $type_file = str_replace("theme/tmp/", "", basename($_FILES['newavatar']['type']));

            if ( $config_user['avatar'] != 'no.png' ) {
                unlink( ROOT_DIR . '/temp/avatar/' . $config_user['avatar'] );
            }

            if ( @move_uploaded_file( $_FILES['newavatar']['tmp_name'], "temp/avatar/" . $_SESSION["id"] . "avatar." . $type_file ) ) {
                mysql_query( "UPDATE php_user SET avatar = '" . $_SESSION['id'] . "avatar." . $type_file . "' WHERE id='" . $_SESSION['id'] . "'" );
                echo 1;
                exit();
            } else {
                echo 'Произошла внутренняя ошибка! Попробуйте позже!';
                exit();
            }
        }
    } else {
        echo 'Произошла внутренняя ошибка! Попробуйте позже!';
        exit();
    }
}

/*---Загрузка скринов---*/
if ( $_GET['func'] == 'addavatar' ) {

    if ( !isset( $_SESSION['id'] ) ) exit();

    if ( !$_FILES['addavatar']['name'] ) {
        echo 'Вы не выбрали скрин';
        exit();
    } else
    if ( $_FILES["addavatar"]["size"] <= 0 and $_FILES["addavatar"]["size"] > 2000 * 1024 ) {
        echo 'Максималный размер скрина 2000 кб.!';
        exit();
    } else
    if ( $_FILES['addavatar']['type'] != 'image/jpg' and  $_FILES['addavatar']['type'] != 'image/jpeg' and $_FILES['addavatar']['type'] != 'image/png' and $_FILES['addavatar']['type'] != 'image/gif') {
        echo 'Неверный формат изображения!';
        exit();
    } else
    if ( is_uploaded_file( $_FILES["addavatar"]["tmp_name"] ) ) {

      $sctopr=clean_get($_POST[tov]);

    $sc_ajax = mysql_fetch_array( mysql_query( "SELECT id FROM php_tovar WHERE id = '".$sctopr."' and user = '" . $_SESSION['id'] . "'" ) );

      if ( $sctopr == ( int ) $sc_ajax['id'] ) {


           $sctovar=clean_get($_POST[tov]);

            $type_file = str_replace("theme/tmp/", "", basename($_FILES['addavatar']['type']));
            $timesc = time();
            if ( @move_uploaded_file( $_FILES['addavatar']['tmp_name'], "temp/scrin/" . $timesc . "." . $type_file ) ) {
                $pdo->Query("INSERT INTO `php_gallery` VALUES('', '".$sctovar."', '" . $timesc . "." . $type_file . "', '" . $_SESSION['id'] . "')");

                echo 1;
                exit();
            } else {
                echo 'Произошла внутренняя ошибка! Попробуйте позже!';
                exit();
            }


      } else {
        echo 'Вы грузите скрины не к своему товару!';
		exit();

      }



    } else {
        echo 'Произошла внутренняя ошибка! Попробуйте позже!';
        exit();
    }


}


?>