diff --git a/.gitignore b/.gitignore index 894a44c..8b460f2 100644 --- a/.gitignore +++ b/.gitignore @@ -102,3 +102,8 @@ venv.bak/ # mypy .mypy_cache/ + +myvenv +db.sqlite3 +/static +.DS_Store diff --git a/.htaccess b/.htaccess new file mode 100644 index 0000000..fcb9947 --- /dev/null +++ b/.htaccess @@ -0,0 +1,7 @@ +# Подключение модуля редиректа +Options +FollowSymlinks +RewriteEngine on + +# Настройка редиректа +RewriteRule ^(.*)\.(.*)$ MainController.php?model=$1&fun=$2 [nc,qsa] +RewriteRule ^(.*)$ MainController.php?model=$1 [nc,qsa] \ No newline at end of file diff --git a/MainController.php b/MainController.php new file mode 100644 index 0000000..084d40c --- /dev/null +++ b/MainController.php @@ -0,0 +1,48 @@ +database = 'ps_main'; + $DB->database = 'qualification'; + $con = $DB->getConnection(); + + $model = isset($_GET["model"]) ? ucfirst($_GET["model"]) : ""; + $function = isset($_GET["fun"]) ? $_GET["fun"] : ""; + + // Формирование и чистка запроса + $request = $_REQUEST; + unset($request['model']); + unset($request['fun']); + + // Проврка названия модели + if ($model == "") + { + $SimpleRest->setHttpHeadersAndPrint($_SERVER['HTTP_ACCEPT'], 404); + } + else + { + require_once('model/'.$model.'.php'); + $obj = new $model(); + $obj->conn = $con; + + // Проверка названия метода + if (method_exists($model, $function)) + { + // Вызов метода + $response = $obj->$function($request); + echo json_encode($response, JSON_PRETTY_PRINT); + + // TODO: в завсисимости от ошибки менять заголовок + } + else + { + $SimpleRest->setHttpHeadersAndPrint($_SERVER['HTTP_ACCEPT'], 404); + } + } +?> diff --git a/README.md b/README.md new file mode 100644 index 0000000..d589470 --- /dev/null +++ b/README.md @@ -0,0 +1,28 @@ +## ProДосуг api +Api предназначено для работы мобильного приложения с сервером ProДосуг. + +## Требования +- Apache2 +- PHP 7+ +- MySQL 5.7+ + +## Настройка +Необходимо сохранить все файлы в нужную директорию и настроить файл `support/Config.php`. + +## Запросы +Запрос имеет вид `class.metod?request`. Пример: +```markdown +https://example.com/test.fun +https://example.com/test.funReq?test=1234 +``` + +### Ошибки +Ошибки выполнения функции хранятся в массиве по ключу `error`. Так же есть дополнительные ошибки, они отображаются при `define("DEBUG", true)` и данные ошибки хранятся в `error_debug`. +Расшифровка простых ошибок: + +- 901 - не все входные данные имеются +- 900 - ответ от бд получен но записей нету +- 910 - ответ от бд получен или все записи были внесены +- 920 - ошибки при записи +- 911 - недостаточно сторонней информации +- 912 - операция не возможно так как была проведена ранее \ No newline at end of file diff --git a/model/Event.php b/model/Event.php new file mode 100644 index 0000000..a605eb8 --- /dev/null +++ b/model/Event.php @@ -0,0 +1,571 @@ +='; + if ($Archive == 'true') + { + $article = '<='; + $arhiveTableAdd = ',create_event_profile,create_event_entryevent'; + $byToken = "create_event_event.id = create_event_entryevent.id_event_id AND + create_event_entryevent.id_user_id = create_event_profile.user_id AND + create_event_profile.hash = '$Token' AND"; + } + + if ($Poster) + { + $sqlTagTable = ", create_event_tagscommunity"; + $sqlTag = "create_event_event.id = create_event_tagscommunity.id_event_id AND create_event_tagscommunity.id_tag_id = 1 AND"; + } + else + { + if (!empty($idEvent)) + { + $sqlForId = "create_event_event.id = '$idEvent' AND"; + } + else if (count($idCategory) != 0) + { + $sqlTag = "create_event_event.id = create_event_tagscommunity.id_event_id AND"; + $sqlTagTransfer = ""; + for ($i = 0; $i < count($idCategory); $i++) + { + $idTag = $idCategory[$i]; + if ($idTag != 0) + { + $sqlTagTransfer .= "create_event_tagscommunity.id_tag_id = $idTag"; + if ($i != count($idCategory)-1) $sqlTagTransfer .= " OR "; + } + } + + $sqlTag .= " ($sqlTagTransfer) AND"; + $sqlTagTable = ", create_event_tagscommunity"; + } + + if ($Today == 'true') + { + $dateTomorrow = date('Y-m-d 00:00:00', strtotime("+1 day")); + $sqlDate = "(create_event_event.created_date >= '$dateString.000000' AND create_event_event.created_date < '$dateTomorrow.000000') AND"; + } + else if (!empty($Date)) + { + $date = date_create($Date); + $date2 = date_create($Date); + date_modify($date2, '+1 day');; + $dateString = date_format($date, 'Y-m-d 00:00:00'); + $dateTomorrow = date_format($date2, 'Y-m-d 00:00:00'); + $sqlDate = "(create_event_event.created_date >= '$dateString' AND create_event_event.created_date < '$dateTomorrow') AND"; + } + + if ($Free == 'false') + { + $sqlFree = "NOT (create_event_event.price = 0) AND"; + } + + if ($Text != '') + { + // TODO: сделать более полноценный поиск + // $sqlSerach = "MATCH (create_event_event.title, create_event_event.description) AGAINST ('$Text') AND"; + $sqlSerach = "(create_event_event.title LIKE '%$Text%' OR create_event_event.description LIKE '%$Text%') AND"; + } + } + + $sql = "SELECT + create_event_event.id, + create_event_event.title, + create_event_event.rating, + create_event_event.price, + create_event_event.description, + create_event_event.main_photo, + create_event_event.created_date, + create_event_event.end_event, + create_event_event.title_slug, + + create_event_agerating.age_rating, + + create_event_organization.title as organization_title, + create_event_organization.address as organization_address, + create_event_organization.geolocation as organization_geolocation, + + auth_user.first_name as profile_name, + auth_user.last_name as profile_surname + FROM + create_event_event, + create_event_agerating, + create_event_organization, + auth_user + $arhiveTableAdd + $sqlTagTable + WHERE + $sqlForId + $sqlDate + $sqlTag + $sqlFree + $sqlSerach + $byToken + create_event_agerating.id = create_event_event.age_rating_id AND + create_event_event.status = 1 AND + create_event_organization.id = create_event_event.id_venue_id AND + create_event_event.created_date $article '$dateString' AND + auth_user.id = create_event_event.id_author_id + ORDER BY create_event_event.created_date LIMIT 50"; + $result = mysqli_query($this->conn, $sql); + $Array['testSql'] = $sql; + + if (mysqli_num_rows($result) > 0) + { + while($row = mysqli_fetch_assoc($result)) + { + $idEventRow = $row['id']; + + $sql = "SELECT + create_event_tag.title, + create_event_tag.id + FROM + create_event_tag, + create_event_tagscommunity + WHERE + create_event_tag.id = create_event_tagscommunity.id_tag_id AND + create_event_tagscommunity.id_event_id = $idEventRow"; + $resultTag = mysqli_query($this->conn, $sql); + + $ArrayTag = array(); + while($rowTag = mysqli_fetch_assoc($resultTag)) + { + if ($rowTag['id'] != 1) + { + array_push($ArrayTag, $rowTag['title']); + } + } + + $sql = "SELECT + create_event_morephotos.image + FROM + create_event_morephotos + WHERE + create_event_morephotos.event_id = $idEventRow"; + $resultImage = mysqli_query($this->conn, $sql); + + $ArrayImage = array(); + while($rowImage = mysqli_fetch_assoc($resultImage)) + { + array_push($ArrayImage, $rowImage['image']); + } + + + $sql = "SELECT + create_event_reviews.comments as text, + create_event_reviews.date_time, + create_event_reviews.rating + FROM + create_event_reviews + WHERE + create_event_reviews.id_event_id = $idEventRow AND + create_event_reviews.comments IS NOT NULL + LIMIT 3"; + $resultComment = mysqli_query($this->conn, $sql); + + $ArrayComment = array(); + while($rowComment = mysqli_fetch_assoc($resultComment)) + { + array_push($ArrayComment, $rowComment); + } + + $row['tag'] = $ArrayTag; + $row['image'] = $ArrayImage; + $row['comment'] = $ArrayComment; + + $geoArray = str_replace(" ","", $row['organization_geolocation']); + $geoArray = explode(",", $geoArray); + $arraTest = array(); + $arraTest['latitude'] = $geoArray[0]; + $arraTest['longitude'] = $geoArray[1]; + $row['organization_geolocation'] = $arraTest; + + array_push($ArrayEvents, $row); + } + + $Array['events'] = $ArrayEvents; + $Array['error'] = "910"; + } + else + { + $Array['error'] = "900"; + if (DEBUG) $Array['error_debug'] = $sql."\n".mysqli_error($this->conn); + } + + + return $Array; + } + + public function getAllDate($req) { + $Array = array(); + $ArrayEventsDate = array(); + $dateToday = date('Y-m-d H:i:s'); + + $sql = "SELECT + create_event_event.created_date + FROM + create_event_event + WHERE + create_event_event.created_date > '$dateToday' + ORDER BY create_event_event.created_date"; + $result = mysqli_query($this->conn, $sql); + + if (mysqli_num_rows($result) > 0) + { + while($row = mysqli_fetch_assoc($result)) + { + $date = date_create($row['created_date']); + $dateString = date_format($date, 'Y-m-d'); + + if (!in_array($dateString, $ArrayEventsDate)) + { + array_push($ArrayEventsDate, date_format($date, 'Y-m-d')); + } + } + + $Array['events'] = $ArrayEventsDate; + $Array['error'] = "910"; + } + else + { + $Array['error'] = "900"; + if (DEBUG) $Array['error_debug'] = $sql."\n".mysqli_error($this->conn); + } + + return $Array; + } + + public function rec($req) { + $Array = array(); + $Token = $req['token']; + $EventID = $req['id']; + + $sql = "SELECT + user_id as id + FROM + create_event_profile + WHERE + hash = '$Token'"; + $result = mysqli_query($this->conn, $sql); + + if (mysqli_num_rows($result) > 0) + { + $data = mysqli_fetch_assoc($result); + $UserID = $data['id']; + + + $sql = "SELECT + id + FROM + create_event_event + WHERE + id = '$EventID'"; + $result = mysqli_query($this->conn, $sql); + + if (mysqli_num_rows($result) > 0) + { + $sql = "INSERT INTO create_event_entryevent (id_event_id, id_user_id) VALUES ('$EventID', '$UserID')"; + + + if (mysqli_query($this->conn, $sql)) + { + $Array['error'] = "910"; + } + else + { + if (DEBUG) $Array['error_debug'] = $sql."\n".mysqli_error($this->conn); + $Array['error'] = "920"; + } + } + else + { + $Array['error'] = "900"; + if (DEBUG) $Array['error_debug'] = $sql."\n".mysqli_error($this->conn); + } + } + else + { + $Array['error'] = "900"; + if (DEBUG) $Array['error_debug'] = $sql."\n".mysqli_error($this->conn); + } + + return $Array; + } + + public function check($req) { + $Array = array(); + $Token = $req['token']; + $EventID = $req['id']; + + $sql = "SELECT + user_id as id + FROM + create_event_profile + WHERE + hash = '$Token'"; + $result = mysqli_query($this->conn, $sql); + + if (mysqli_num_rows($result) > 0) + { + $data = mysqli_fetch_assoc($result); + $UserID = $data['id']; + + + $sql = "SELECT + id + FROM + create_event_event + WHERE + id = '$EventID'"; + $result = mysqli_query($this->conn, $sql); + + if (mysqli_num_rows($result) > 0) + { + $sql = "SELECT + id + FROM + create_event_entryevent + WHERE + id_event_id = '$EventID' AND + id_user_id = '$UserID'"; + $result = mysqli_query($this->conn, $sql); + + if (mysqli_num_rows($result) > 0) + { + $Array['error'] = "910"; + } + else + { + $Array['error'] = "900"; + if (DEBUG) $Array['error_debug'] = $sql."\n".mysqli_error($this->conn); + } + } + else + { + $Array['error'] = "900"; + if (DEBUG) $Array['error_debug'] = $sql."\n".mysqli_error($this->conn); + } + } + else + { + $Array['error'] = "900"; + if (DEBUG) $Array['error_debug'] = $sql."\n".mysqli_error($this->conn); + } + + return $Array; + } + + + public function comment($req) { + $Array = array(); + $EventID = $req['id']; + + $sql = "SELECT + create_event_reviews.comments as text, + create_event_reviews.date_time, + create_event_reviews.rating + FROM + create_event_reviews + WHERE + create_event_reviews.id_event_id = $EventID AND + create_event_reviews.comments IS NOT NULL"; + $result = mysqli_query($this->conn, $sql); + + if (mysqli_num_rows($result) > 0) + { + $ArrayComment = array(); + while($row = mysqli_fetch_assoc($result)) + { + array_push($ArrayComment, $row); + } + + $Array['events'] = $ArrayComment; + $Array['error'] = "910"; + } + else + { + $Array['error'] = "900"; + if (DEBUG) $Array['error_debug'] = $sql."\n".mysqli_error($this->conn); + } + + return $Array; + } + + public function checkReview($req) { + $Array = array(); + $Token = $req['token']; + $EventID = $req['id']; + + $sql = "SELECT + user_id as id + FROM + create_event_profile + WHERE + hash = '$Token'"; + $result = mysqli_query($this->conn, $sql); + + if (mysqli_num_rows($result) > 0) + { + $data = mysqli_fetch_assoc($result); + $UserID = $data['id']; + + + $sql = "SELECT + id + FROM + create_event_event + WHERE + id = '$EventID'"; + $result = mysqli_query($this->conn, $sql); + + if (mysqli_num_rows($result) > 0) + { + $sql = "SELECT + id + FROM + create_event_reviews + WHERE + id_event_id = '$EventID' AND + id_users_id = '$UserID'"; + $result = mysqli_query($this->conn, $sql); + + if (mysqli_num_rows($result) > 0) + { + $Array['error'] = "910"; + } + else + { + $Array['error'] = "900"; + if (DEBUG) $Array['error_debug'] = $sql."\n".mysqli_error($this->conn); + } + } + else + { + $Array['error'] = "900"; + if (DEBUG) $Array['error_debug'] = $sql."\n".mysqli_error($this->conn); + } + } + else + { + $Array['error'] = "900"; + if (DEBUG) $Array['error_debug'] = $sql."\n".mysqli_error($this->conn); + } + + return $Array; + } + + public function setComment($req) + { + $Array = array(); + $EventID = $req['id']; + $Rating = $req['rating']; + $Comment = $req['comment']; + $Token = $req['token']; + + if (!empty($EventID) && !empty($Rating) && !empty($Token)) + { + $sql = "SELECT + user_id as id + FROM + create_event_profile + WHERE + hash = '$Token'"; + $result = mysqli_query($this->conn, $sql); + + if (mysqli_num_rows($result) > 0) + { + $data = mysqli_fetch_assoc($result); + $UserID = $data['id']; + + + $sql = "SELECT + id + FROM + create_event_event + WHERE + id = '$EventID'"; + $result = mysqli_query($this->conn, $sql); + + if (mysqli_num_rows($result) > 0) + { + $CommentString = 'NULL'; + if ($Comment != '') + { + $CommentString = "'$Comment'"; + } + + $sql = "INSERT INTO create_event_reviews (id_event_id, id_users_id, rating, comments) VALUES ('$EventID', '$UserID', $Rating, $CommentString)"; + + if (mysqli_query($this->conn, $sql)) + { + $sql = "SELECT + AVG(rating) as rating + FROM + create_event_reviews + WHERE + id_event_id = '$EventID'"; + $result = mysqli_query($this->conn, $sql); + $data = mysqli_fetch_assoc($result); + $RatingEvent = $data['rating']; + + $sql = "UPDATE create_event_event SET rating = '$RatingEvent' WHERE id = $EventID"; + if (mysqli_query($this->conn, $sql)) + { + $Array['error'] = "910"; + } + else + { + if (DEBUG) $Array['error_debug'] = $sql."\n".mysqli_error($this->conn); + $Array['error'] = "920"; + } + } + else + { + if (DEBUG) $Array['error_debug'] = $sql."\n".mysqli_error($this->conn); + $Array['error'] = "920"; + } + + } + else + { + $Array['error'] = "900"; + if (DEBUG) $Array['error_debug'] = $sql."\n".mysqli_error($this->conn); + } + } + else + { + $Array['error'] = "900"; + if (DEBUG) $Array['error_debug'] = $sql."\n".mysqli_error($this->conn); + } + } + else + { + $Array['error'] = "901"; + } + + return $Array; + } + + } +?> diff --git a/model/Test.php b/model/Test.php new file mode 100644 index 0000000..5479d62 --- /dev/null +++ b/model/Test.php @@ -0,0 +1,20 @@ + diff --git a/model/User.php b/model/User.php new file mode 100644 index 0000000..d580d33 --- /dev/null +++ b/model/User.php @@ -0,0 +1,357 @@ +100 ? 8 : 2; + while(strlen($gamma) < $len) + { + $gamma .= substr(pack('H*', sha1($passw.$gamma.$salt)), 0, $n); + } + + return $str^$gamma; + } + + private function django_password_verify(string $password, string $djangoHash): bool + { + $pieces = explode('$', $djangoHash); + if (count($pieces) !== 4) { + throw new Exception("Illegal hash format"); + } + list($header, $iter, $salt, $hash) = $pieces; + // Get the hash algorithm used: + if (preg_match('#^pbkdf2_([a-z0-9A-Z]+)$#', $header, $m)) { + $algo = $m[1]; + } else { + throw new Exception(sprintf("Bad header (%s)", $header)); + } + if (!in_array($algo, hash_algos())) { + throw new Exception(sprintf("Illegal hash algorithm (%s)", $algo)); + } + + $calc = hash_pbkdf2( + $algo, + $password, + $salt, + (int) $iter, + 32, + true + ); + return hash_equals($calc, base64_decode($hash)); + } + + + // Регистарция нового пользователя + public function reg($req) + { + $Array = array(); + $name = $req['name']; + $surname = $req['surname']; + $mail = $req['mail']; + $password = md5($req['password']); + $age = $req['age']; + + if (!empty($name) && !empty($surname) && !empty($mail) && !empty($password) && !empty($age)) + { + $dateAge = date_create($age); + $age = date_format($dateAge, "Y-m-d"); + $ip = ($_SERVER['REMOTE_ADDR'] == "::1") ? 'localhost' : $_SERVER['REMOTE_ADDR']; + $today = date("Y-m-d H:i:s"); + + $sql = "SELECT username FROM auth_user WHERE username = '$mail'"; + $count = mysqli_num_rows(mysqli_query($this->conn, $sql)); + + if ($count == 0) + { + $iterations = 150000; + $salt = md5(mt_rand()); + $hash = hash_pbkdf2("sha256", $password, $salt, $iterations, 32, true); + $passwordString = "pbkdf2_sha256$$iterations$$salt$".base64_encode($hash); + +// $sql = "INSERT INTO create_event_users (name, surname, mail, password, age, status, ip, date_time) VALUES ('$name', '$surname', '$mail', '$password', '$age', 0, '$ip', '$today')"; + $sql = "INSERT INTO auth_user (username, first_name, last_name, email, is_staff, is_active, is_superuser, password) VALUES ('$mail', '$name', '$surname', '$mail', 0, 0, 0, '$passwordString')"; + + + if (mysqli_query($this->conn, $sql)) + { + $id = mysqli_insert_id($this->conn); // получение последнего id + + $sql = "INSERT INTO create_event_profile (age, user_id, ip) VALUES ('$age', '$id', '$ip')"; + mysqli_query($this->conn, $sql); + + + $idCode = base64_encode($this->strcode("$id", HACH_CODE)); // шифрование + $Url = 'http://'.$_SERVER['HTTP_HOST'].'/api/user.activation?cod='.urlencode($idCode); + + // Подкючение класса отправки писем через стороний сервер + require_once ROOT_API_DIR."support/SendMailSmtpClass.php"; + $mailSMTP = new SendMailSmtpClass(MAIL_ADDRESS, MAIL_PASSWORD, MAIL_HOST, MAIL_POSRT, 'UTF-8'); + + // От кого + $from = array(MAIL_NAME, MAIL_ADDRESS); + + // Отправляем письмо + $result = $mailSMTP->send($mail, 'Тема письма', 'Для активации аккаунта перейдите по ссылке: '.$Url, $from); + + if($result === true) + { + $Array['error'] = "910"; + } + else + { + if (DEBUG) $Array['error_debug'] = $result; + $Array['error'] = "900"; + } + + } + else + { + if (DEBUG) $Array['error_debug'] = $sql."\n".mysqli_error($this->conn); + $Array['error'] = "920"; + } + } + else + { + $Array['error'] = "912"; + if (DEBUG) $Array['error_debug'] = 'mysqli_num_rows: '.$count; + } + } + else + { + $Array['error'] = "901"; + } + + return $Array; + } + + // Активация аккаунта по ссылке из письма + public function activation($req) + { + $Array = array(); + $cod = $req['cod']; + + if (!empty($cod)) + { + $UserID = $this->strcode(base64_decode($cod), HACH_CODE); + $sql = "UPDATE auth_user SET is_active=1 WHERE id=$UserID"; + + if (mysqli_query($this->conn, $sql)) + { + $Array['error'] = "910"; + } + else + { + if (DEBUG) $Array['error_debug'] = $sql."\n".mysqli_error($this->conn); + $Array['error'] = "920"; + } + } + else + { + $Array['error'] = "901"; + } + + return $Array; + } + + + // Авторизация пользователя + public function auth($req) + { + $Array = array(); + $mail = $req['mail']; +// $password = md5($req['password']); + $password = $req['password']; + + if (!empty($mail) && !empty($password)) + { + $sql = "SELECT + auth_user.id, + auth_user.email, + auth_user.first_name, + auth_user.last_name, + auth_user.password, + + create_event_profile.age + FROM + auth_user, + create_event_profile + WHERE + auth_user.username = '$mail' AND + auth_user.is_active = 1 AND + create_event_profile.user_id = auth_user.id"; + $result = mysqli_query($this->conn, $sql); + $data = mysqli_fetch_assoc($result); + + $checkPassword = $this->django_password_verify($password, $data['password']); + + if (mysqli_num_rows($result) == 0 || $checkPassword != 1) + { + $Array['error'] = "900"; + } + else + { + $UserID = $data['id']; + $token = md5($data['mail']).md5(rand(1000000, 9999999)); // генерация токена + + $sql = "UPDATE create_event_profile SET hash='$token' WHERE user_id=$UserID"; + + if (mysqli_query($this->conn, $sql)) + { + $Array['error'] = "910"; + $Array['token'] = $token; + $Array['name'] = $data['first_name']; + $Array['surname'] = $data['last_name']; + $Array['mail'] = $data['email']; + $Array['age'] = $data['age']; + } + else + { + if (DEBUG) $Array['error_debug'] = $sql."\n".mysqli_error($this->conn); + $Array['error'] = "920"; + } + } + } + else + { + $Array['error'] = "901"; + } + + return $Array; + } + + public function edit($req) + { + $Array = array(); + $Token = $req['token']; + + $sql = "SELECT + create_event_profile.user_id as id, + auth_user.email + FROM + create_event_profile, + auth_user + WHERE + create_event_profile.hash = '$Token' AND + auth_user.id = create_event_profile.user_id"; + $result = mysqli_query($this->conn, $sql); + + if (mysqli_num_rows($result) > 0) + { + $data = mysqli_fetch_assoc($result); + $UserID = $data['id']; + $name = $req['name']; + $surname = $req['surname']; + $mail = $req['mail']; + $age = $req['age']; + $dateAge = date_create($age); + $age = date_format($dateAge, "Y-m-d"); + + if ($name != '' && $surname != '' && $age != '') + { + $sql = "SELECT username FROM auth_user WHERE username = '$mail'"; + $count = mysqli_num_rows(mysqli_query($this->conn, $sql)); + + if ($count == 0) + { + $sql = "UPDATE + create_event_profile, + auth_user + SET + create_event_profile.age = '$age', + auth_user.first_name = '$name', + auth_user.last_name = '$surname' + WHERE + create_event_profile.user_id = $UserID AND + auth_user.id = $UserID"; + + if (mysqli_query($this->conn, $sql)) + { + $Array['error'] = "910"; + $Array['age'] = $age; + } + else + { + if (DEBUG) $Array['error_debug'] = $sql."\n".mysqli_error($this->conn); + $Array['error'] = "920"; + } + } + else + { + $Array['error'] = "912"; + if (DEBUG) $Array['error_debug'] = 'mysqli_num_rows: '.$count; + } + } + } + else + { + $Array['error'] = "900"; + if (DEBUG) $Array['error_debug'] = $sql."\n".mysqli_error($this->conn); + } + + return $Array; + + } + + public function editPassword($req) + { + $Array = array(); + $passwordOld = $req['password_old']; + $passwordNew = $req['password_new']; + $token = $req['token']; + + if (!empty($token) && !empty($passwordOld) && !empty($passwordNew)) + { + $sql = "SELECT + auth_user.id, + auth_user.password + FROM + auth_user, + create_event_profile + WHERE + create_event_profile.hash = '$token' AND + auth_user.id = create_event_profile.user_id"; + $result = mysqli_query($this->conn, $sql); + $data = mysqli_fetch_assoc($result); + + $checkPassword = $this->django_password_verify($passwordOld, $data['password']); + + if (mysqli_num_rows($result) == 0 || $checkPassword != 1) + { + $Array['error'] = "900"; + } + else + { + $UserID = $data['id']; + $iterations = 150000; + $salt = md5(mt_rand()); + $hash = hash_pbkdf2("sha256", $passwordNew, $salt, $iterations, 32, true); + $passwordString = "pbkdf2_sha256$$iterations$$salt$".base64_encode($hash); + + $sql = "UPDATE auth_user SET password='$passwordString' WHERE id=$UserID"; + + if (mysqli_query($this->conn, $sql)) + { + $Array['error'] = "910"; + } + else + { + if (DEBUG) $Array['error_debug'] = $sql."\n".mysqli_error($this->conn); + $Array['error'] = "920"; + } + } + } + else + { + $Array['error'] = "901"; + } + + return $Array; + } + + } +?> \ No newline at end of file diff --git a/script.sql b/script.sql new file mode 100644 index 0000000..7c29d7f --- /dev/null +++ b/script.sql @@ -0,0 +1,25 @@ +-- Перед выполнением уберите галочку "Enable foreign key checks" +-- Before you perform uncheck "Enable foreign key checks" + +SET FOREIGN_KEY_CHECKS = 0; + +TRUNCATE TABLE `create_event_tag`; + +INSERT INTO `create_event_tag` (`id`, `title`) VALUES (NULL, 'Афиша'); +INSERT INTO `create_event_tag` (`id`, `title`) VALUES (NULL, 'Кино'); +INSERT INTO `create_event_tag` (`id`, `title`) VALUES (NULL, 'Музыка'); +INSERT INTO `create_event_tag` (`id`, `title`) VALUES (NULL, 'Музеи, выставки, библиотеки'); +INSERT INTO `create_event_tag` (`id`, `title`) VALUES (NULL, 'Фестивали, массовые гуляния, конкурсы'); +INSERT INTO `create_event_tag` (`id`, `title`) VALUES (NULL, 'Спорт'); +INSERT INTO `create_event_tag` (`id`, `title`) VALUES (NULL, 'Образование'); +INSERT INTO `create_event_tag` (`id`, `title`) VALUES (NULL, 'Услуги'); + +TRUNCATE TABLE `create_event_agerating`; + +INSERT INTO `create_event_agerating` (`id`, `age_rating`) VALUES (NULL, '0'); +INSERT INTO `create_event_agerating` (`id`, `age_rating`) VALUES (NULL, '6'); +INSERT INTO `create_event_agerating` (`id`, `age_rating`) VALUES (NULL, '12'); +INSERT INTO `create_event_agerating` (`id`, `age_rating`) VALUES (NULL, '16'); +INSERT INTO `create_event_agerating` (`id`, `age_rating`) VALUES (NULL, '18'); + +SET FOREIGN_KEY_CHECKS = 1; \ No newline at end of file diff --git a/support/Config.php b/support/Config.php new file mode 100644 index 0000000..065a4c4 --- /dev/null +++ b/support/Config.php @@ -0,0 +1,18 @@ + diff --git a/support/DataBase.php b/support/DataBase.php new file mode 100644 index 0000000..0c9b2f5 --- /dev/null +++ b/support/DataBase.php @@ -0,0 +1,30 @@ +connection = null; + + if ($this->database != null) + { + // Создание подключения + $this->connection = new mysqli($this->host, $this->username, $this->password, $this->database); + + // Проверка подключения + if ($this->connection->connect_error) { + die("Connection failed: " . $this->connection->connect_error); + } + } + + return $this->connection; + } + } +?> diff --git a/support/SendMailSmtpClass.php b/support/SendMailSmtpClass.php new file mode 100644 index 0000000..4c3acf3 --- /dev/null +++ b/support/SendMailSmtpClass.php @@ -0,0 +1,222 @@ + +* @version 1.1 +*/ +class SendMailSmtpClass { + + /** + * + * @var string $smtp_username - логин + * @var string $smtp_password - пароль + * @var string $smtp_host - хост + * @var string $smtp_from - от кого + * @var integer $smtp_port - порт + * @var string $smtp_charset - кодировка + * + */ + public $smtp_username; + public $smtp_password; + public $smtp_host; + public $smtp_from; + public $smtp_port; + public $smtp_charset; + public $boundary; + public $addFile = false; + public $multipart; + + public function __construct($smtp_username, $smtp_password, $smtp_host, $smtp_port = 25, $smtp_charset = "utf-8") { + $this->smtp_username = $smtp_username; + $this->smtp_password = $smtp_password; + $this->smtp_host = $smtp_host; + $this->smtp_port = $smtp_port; + $this->smtp_charset = $smtp_charset; + + // разделитель файлов + $this->boundary = "--".md5(uniqid(time())); + $this->multipart = ""; + } + + /** + * Отправка письма + * + * @param string $mailTo - получатель письма + * @param string $subject - тема письма + * @param string $message - тело письма + * @param string $smtp_from - отправитель. Массив с именем и e-mail + * + * @return bool|string В случаи отправки вернет true, иначе текст ошибки + * + */ + function send($mailTo, $subject, $message, $smtp_from) { + // подготовка содержимого письма к отправке + $contentMail = $this->getContentMail($subject, $message, $smtp_from); + + try { + if(!$socket = @fsockopen($this->smtp_host, $this->smtp_port, $errorNumber, $errorDescription, 30)){ + throw new Exception($errorNumber.".".$errorDescription); + } + if (!$this->_parseServer($socket, "220")){ + throw new Exception('Connection error'); + } + + $server_name = $_SERVER["SERVER_NAME"]; + fputs($socket, "EHLO $server_name\r\n"); + if(!$this->_parseServer($socket, "250")){ + // если сервер не ответил на EHLO, то отправляем HELO + fputs($socket, "HELO $server_name\r\n"); + if (!$this->_parseServer($socket, "250")) { + fclose($socket); + throw new Exception('Error of command sending: HELO'); + } + } + + fputs($socket, "AUTH LOGIN\r\n"); + if (!$this->_parseServer($socket, "334")) { + fclose($socket); + throw new Exception('Autorization error'); + } + + fputs($socket, base64_encode($this->smtp_username) . "\r\n"); + if (!$this->_parseServer($socket, "334")) { + fclose($socket); + throw new Exception('Autorization error'); + } + + fputs($socket, base64_encode($this->smtp_password) . "\r\n"); + if (!$this->_parseServer($socket, "235")) { + fclose($socket); + throw new Exception('Autorization error'); + } + + fputs($socket, "MAIL FROM: <".$this->smtp_username.">\r\n"); + if (!$this->_parseServer($socket, "250")) { + fclose($socket); + throw new Exception('Error of command sending: MAIL FROM'); + } + + $mailTo = str_replace(" ", "", $mailTo); + $emails_to_array = explode(',', $mailTo); + foreach($emails_to_array as $email) { + fputs($socket, "RCPT TO: <{$email}>\r\n"); + if (!$this->_parseServer($socket, "250")) { + fclose($socket); + throw new Exception('Error of command sending: RCPT TO'); + } + } + + fputs($socket, "DATA\r\n"); + if (!$this->_parseServer($socket, "354")) { + fclose($socket); + throw new Exception('Error of command sending: DATA'); + } + + fputs($socket, $contentMail."\r\n.\r\n"); + if (!$this->_parseServer($socket, "250")) { + fclose($socket); + throw new Exception("E-mail didn't sent"); + } + + fputs($socket, "QUIT\r\n"); + fclose($socket); + } catch (Exception $e) { + return $e->getMessage(); + } + return true; + } + + + // добавление файла в письмо + public function addFile($path){ + $file = @fopen($path, "rb"); + if(!$file) { + throw new Exception("File `{$path}` didn't open"); + } + $data = fread($file, filesize( $path ) ); + fclose($file); + $filename = basename($path); + $multipart .= "\r\n--{$this->boundary}\r\n"; + $multipart .= "Content-Type: application/octet-stream; name=\"$filename\"\r\n"; + $multipart .= "Content-Transfer-Encoding: base64\r\n"; + $multipart .= "Content-Disposition: attachment; filename=\"$filename\"\r\n"; + $multipart .= "\r\n"; + $multipart .= chunk_split(base64_encode($data)); + + $this->multipart .= $multipart; + $this->addFile = true; + } + + // парсинг ответа сервера + private function _parseServer($socket, $response) { + while (@substr($responseServer, 3, 1) != ' ') { + if (!($responseServer = fgets($socket, 256))) { + return false; + } + } + if (!(substr($responseServer, 0, 3) == $response)) { + return false; + } + return true; + } + + // подготовка содержимого письма + private function getContentMail($subject, $message, $smtp_from){ + // если кодировка windows-1251, то перекодируем тему + if( strtolower($this->smtp_charset) == "windows-1251" ){ + $subject = iconv('utf-8', 'windows-1251', $subject); + } + $contentMail = "Date: " . date("D, d M Y H:i:s") . " UT\r\n"; + $contentMail .= 'Subject: =?' . $this->smtp_charset . '?B?' . base64_encode($subject) . "=?=\r\n"; + + // заголовок письма + $headers = "MIME-Version: 1.0\r\n"; + // кодировка письма + if($this->addFile){ + // если есть файлы + $headers .= "Content-Type: multipart/mixed; boundary=\"{$this->boundary}\"\r\n"; + }else{ + $headers .= "Content-type: text/html; charset={$this->smtp_charset}\r\n"; + } + $headers .= "From: {$smtp_from[0]} <{$smtp_from[1]}>\r\n"; // от кого письмо + $contentMail .= $headers . "\r\n"; + + if($this->addFile){ + // если есть файлы + $multipart = "--{$this->boundary}\r\n"; + $multipart .= "Content-Type: text/html; charset=utf-8\r\n"; + $multipart .= "Content-Transfer-Encoding: base64\r\n"; + $multipart .= "\r\n"; + $multipart .= chunk_split(base64_encode($message)); + + // файлы + $multipart .= $this->multipart; + $multipart .= "\r\n--{$this->boundary}--\r\n"; + + $contentMail .= $multipart; + }else{ + $contentMail .= $message . "\r\n"; + } + + // если кодировка windows-1251, то все письмо перекодируем + if( strtolower($this->smtp_charset) == "windows-1251" ){ + $contentMail = iconv('utf-8', 'windows-1251', $contentMail); + } + + return $contentMail; + } + +} \ No newline at end of file diff --git a/support/SimpleRest.php b/support/SimpleRest.php new file mode 100644 index 0000000..fa41dcd --- /dev/null +++ b/support/SimpleRest.php @@ -0,0 +1,74 @@ +getHttpStatusMessage($statusCode); + + header($this->httpVersion. " ". $statusCode ." ". $statusMessage); + header("Content-Type:". $contentType); + } + + public function setHttpHeadersAndPrint($contentType, $statusCode){ + $statusMessage = $this->getHttpStatusMessage($statusCode); + $this->setHttpHeaders($contentType, $statusCode); + + printf($statusCode."\n".$statusMessage); + exit(); + } + + public function getHttpStatusMessage($statusCode){ + $httpStatus = array( + 100 => 'Continue', + 101 => 'Switching Protocols', + 200 => 'OK', + 201 => 'Created', + 202 => 'Accepted', + 203 => 'Non-Authoritative Information', + 204 => 'No Content', + 205 => 'Reset Content', + 206 => 'Partial Content', + 300 => 'Multiple Choices', + 301 => 'Moved Permanently', + 302 => 'Found', + 303 => 'See Other', + 304 => 'Not Modified', + 305 => 'Use Proxy', + 306 => '(Unused)', + 307 => 'Temporary Redirect', + 400 => 'Bad Request', + 401 => 'Unauthorized', + 402 => 'Payment Required', + 403 => 'Forbidden', + 404 => 'Not Found', + 405 => 'Method Not Allowed', + 406 => 'Not Acceptable', + 407 => 'Proxy Authentication Required', + 408 => 'Request Timeout', + 409 => 'Conflict', + 410 => 'Gone', + 411 => 'Length Required', + 412 => 'Precondition Failed', + 413 => 'Request Entity Too Large', + 414 => 'Request-URI Too Long', + 415 => 'Unsupported Media Type', + 416 => 'Requested Range Not Satisfiable', + 417 => 'Expectation Failed', + 500 => 'Internal Server Error', + 501 => 'Not Implemented', + 502 => 'Bad Gateway', + 503 => 'Service Unavailable', + 504 => 'Gateway Timeout', + 505 => 'HTTP Version Not Supported'); + + return ($httpStatus[$statusCode]) ? $httpStatus[$statusCode] : $status[500]; + } + } +?> \ No newline at end of file