Поиск постов. Работаем с API.
Идем в api/index.php
<?php
require_once("DB.php");
require_once("Mail.php");
$db = new
DB("127.0.0.1", "SocialNetwork", "root",
"");
// 'REQUEST_METHOD'
- Какой метод был использован для запроса
страницы; к примеру 'GET', 'HEAD', 'POST', 'PUT'.
if
($_SERVER['REQUEST_METHOD'] == "GET") {
if ($_GET['url']
== "auth") {
//
} else if
($_GET['url'] == "search") {
// поиск
$tosearch =
explode(" ", $_GET['query']); // explode — Разбивает
строку с помощью разделителя
if
(count($tosearch) == 1) {
$tosearch
= str_split($tosearch[0], 2); // str_split — преобразует
строку в массив, 2 - максимальная длина
фрагмента.
}
// поиск
постов
$whereclause
= "";
$paramsarray
= array(':body'=>'%'.$_GET['query'].'%');
for ($i = 0;
$i < count($tosearch); $i++) {
if ($i %
2) {
$whereclause
.= " OR body LIKE :p$i ";
$paramsarray[":p$i"]
= $tosearch[$i];
}
}
$posts =
$db->query('SELECT posts.body FROM posts WHERE posts.body LIKE
:body '.$whereclause.'', $paramsarray);
echo
"<pre>";
print_r($posts);
echo
"</pre>";
} else if
($_GET['url'] == "users") {
//
} else if
($_GET['url'] == "comments" &&
isset($_GET['postid'])) {
//
комментарии
$output =
"";
$comments =
$db->query('SELECT comments.comment, users.username FROM comments,
users WHERE post_id = :postid AND comments.user_id = users.id',
array(':postid'=>$_GET['postid']));
$output .=
"[";
foreach($comments
as $comment) {
$output
.= "{";
$output
.= '"Comment": "'.$comment['comment'].'",';
$output
.= '"CommentedBy": "'.$comment['username'].'"';
$output
.= "},";
//echo
$comment['comment']." ~ ".$comment['username']."<hr
/>";
}
$output =
substr($output, 0, strlen($output)-1);
$output .=
"]";
echo
$output;
} else if
($_GET['url'] == "posts") {
$token =
$_COOKIE['SNID'];
$userid =
$db->query('SELECT user_id FROM login_tokens WHERE token=:token',
array(':token'=>sha1($token)))[0]['user_id'];
$followingposts
= $db->query('SELECT posts.id, posts.body, posts.posted_at,
posts.likes, users.`username` FROM users, posts, followers
WHERE
posts.user_id = followers.user_id
AND users.id
= posts.user_id
AND
follower_id = :userid
ORDER BY
posts.likes DESC;', array(':userid'=>$userid));
$response =
"[";
foreach($followingposts
as $post) {
$response
.= "{";
$response
.= '"PostId": '.$post['id'].',';
$response
.= '"PostBody": "'.$post['body'].'",';
$response
.= '"PostedBy": "'.$post['username'].'",';
$response
.= '"PostDate": "'.$post['posted_at'].'",';
$response
.= '"Likes": '.$post['likes'].'';
$response
.= "},";
}
$response =
substr($response, 0, strlen($response)-1);
$response .=
"]";
http_response_code(200);
echo
$response;
} else if
($_GET['url'] == "profileposts") {
$userid =
$db->query('SELECT id FROM users WHERE username=:username',
array(':username'=>$_GET['username']))[0]['id'];
$followingposts
= $db->query('SELECT posts.id, posts.body, posts.posted_at,
posts.likes, users.`username` FROM users, posts
WHERE
users.id = posts.user_id
AND users.id
= :userid
ORDER BY
posts.likes DESC;', array(':userid'=>$userid));
$response =
"[";
foreach($followingposts
as $post) {
$response
.= "{";
$response
.= '"PostId": '.$post['id'].',';
$response
.= '"PostBody": "'.$post['body'].'",';
$response
.= '"PostedBy": "'.$post['username'].'",';
$response
.= '"PostDate": "'.$post['posted_at'].'",';
$response
.= '"Likes": '.$post['likes'].'';
$response
.= "},";
}
$response =
substr($response, 0, strlen($response)-1);
$response .=
"]";
http_response_code(200);
echo
$response;
}
} else if
($_SERVER['REQUEST_METHOD'] == "POST") {
// Создание
аккаунта
if ($_GET['url']
== "users") {
$postBody =
file_get_contents("php://input");
$postBody =
json_decode($postBody);
$username =
$postBody->username;
$email =
$postBody->email;
$password =
$postBody->password;
if(!$db->query('SELECT
username FROM users WHERE username=:username',
array(':username'=>$username))) {
if(strlen($username)
>= 3 && strlen($username) <= 32) {
if(preg_match('/[a-zA-Z0-9_]+/', $username)) {
if(strlen($password) >= 6 &&
strlen($password) <= 60) {
if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
if(!$db->query('SELECT email FROM users WHERE
email=:email', array(':email'=>$email))) {
$db->query('INSERT INTO users VALUES (:id,
:username, :password, :email, \'0\', \'\')', array(':id'=>null,
':username'=>$username, ':password'=>password_hash($password,
PASSWORD_BCRYPT), ':email'=>$email));
Mail::sendMail('Welcome to our Social Network!',
'Your account has been created!', $email);
echo
'{ "Success": "User created!" }';
http_response_code(200);
}
else {
echo
'{ "Error": "Email in use!" }';
http_response_code(409);
}
}
else {
echo
'{ "Error": "Invalid Email!" }';
http_response_code(409);
}
}
else {
echo
'{ "Error": "Invalid Password!" }';
http_response_code(409);
}
}
else {
echo
'{ "Error": "Invalid username!" }';
http_response_code(409);
}
} else {
echo
'{ "Error": "Invalid username!" }';
http_response_code(409);
}
} else {
echo '{
"Error": "User exists!" }';
http_response_code(409);
// 409 Conflict («конфликт»)
}
}
// Логин
if ($_GET['url']
== "auth") {
$postBody =
file_get_contents("php://input");
$postBody =
json_decode($postBody);
$username =
$postBody->username;
$password =
$postBody->password;
if
($db->query('SELECT username FROM users WHERE username=:username',
array(':username'=>$username))) {
//
password_verify — Проверяет, соответствует ли
пароль хешу
if
(password_verify($password, $db->query('SELECT password FROM users
WHERE username=:username',
array(':username'=>$username))[0]['password'])) {
$cstrong
= True;
$token
= bin2hex(openssl_random_pseudo_bytes(64, $cstrong));
$user_id
= $db->query('SELECT id FROM users WHERE username=:username',
array(':username'=>$username))[0]['id'];
$db->query('INSERT
INTO login_tokens VALUE (:id, :token, :user_id)', array(':id'=>null,
':token'=>sha1($token), ':user_id'=>$user_id));
echo
'{ "Token": "'.$token.'" }';
} else {
echo
'{ "Error": "Invalid username or password!" }';
http_response_code(401);
}
} else {
echo '{
"Error": "Invalid username or password!" }';
http_response_code(401);
}
} else if
($_GET['url'] == "likes") {
// Like-button.
Копируем из класса Post
$postId =
$_GET['id'];
$token =
$_COOKIE['SNID'];
$likerId =
$db->query('SELECT user_id FROM login_tokens WHERE token=:token',
array(':token'=>sha1($token)))[0]['user_id'];
if
(!$db->query('SELECT user_id FROM post_likes WHERE post_id=:postid
AND user_id=:userid', array(':postid'=>$postId,
':userid'=>$likerId))) {
$db->query('UPDATE
posts SET likes=likes+1 WHERE id=:postid',
array(':postid'=>$postId));
$db->query('INSERT
INTO post_likes VALUES (:id, :postid, :userid)', array(':id'=>null,
':postid'=>$postId, ':userid'=>$likerId));
//Notify::createNotify("",
$postId);
} else {
$db->query('UPDATE
posts SET likes=likes-1 WHERE id=:postid',
array(':postid'=>$postId));
$db->query('DELETE
FROM post_likes WHERE post_id=:postid AND user_id=:userid',
array(':postid'=>$postId, ':userid'=>$likerId));
}
echo "{";
echo
'"Likes":';
echo
$db->query('SELECT likes FROM posts WHERE id=:postid',
array(':postid'=>$postId))[0]['likes'];
echo "}";
}
} else if
($_SERVER['REQUEST_METHOD'] == "DELETE") {
if ($_GET['url']
== "auth") {
if
(isset($_GET['token'])) {
if
($db->query("SELECT token FROM login_tokens WHERE
token=:token", array(':token'=>sha1($_GET['token'])))) {
$db->query('DELETE
FROM login_tokens WHERE token=:token',
array(':token'=>sha1($_GET['token'])));
echo
'{ "Status": "Success" }';
http_response_code(200);
} else {
echo
'{ "Error": "Invalid token" }';
http_response_code(400);
}
} else {
echo '{
"Error": "Mal-formed request" }';
http_response_code(400);
}
}
}
else {
http_response_code(405);
}
?>
Протестируем
http://newsocial.loc/api/search?query=hello
Идем в
api/index.php
Выведем
данные в формате json.
<?php
require_once("DB.php");
require_once("Mail.php");
$db
= new DB("127.0.0.1", "SocialNetwork", "root",
"");
//
'REQUEST_METHOD' - Какой метод был использован
для запроса страницы; к примеру 'GET',
'HEAD', 'POST', 'PUT'.
if
($_SERVER['REQUEST_METHOD'] == "GET") {
if
($_GET['url'] == "auth") {
//
}
else if ($_GET['url'] == "search") {
//
поиск
$tosearch
= explode(" ", $_GET['query']); // explode — Разбивает
строку с помощью разделителя
if
(count($tosearch) == 1) {
$tosearch = str_split($tosearch[0], 2); //
str_split — преобразует строку в массив, 2
- максимальная длина фрагмента.
}
//
поиск постов
$whereclause = "";
$paramsarray =
array(':body'=>'%'.$_GET['query'].'%');
for
($i = 0; $i < count($tosearch); $i++) {
if
($i % 2) {
$whereclause .= " OR body LIKE :p$i ";
$paramsarray[":p$i"] = $tosearch[$i];
}
}
$posts
= $db->query('SELECT posts.body FROM posts WHERE posts.body LIKE
:body '.$whereclause.'', $paramsarray);
echo
"<pre>";
echo
json_encode($posts);
echo
"</pre>";
}
else if ($_GET['url'] == "users") {
//
}
else if ($_GET['url'] == "comments" &&
isset($_GET['postid'])) {
//
комментарии
$output
= "";
$comments
= $db->query('SELECT comments.comment, users.username FROM
comments, users WHERE post_id = :postid AND comments.user_id =
users.id', array(':postid'=>$_GET['postid']));
$output
.= "[";
foreach($comments as $comment) {
$output .= "{";
$output .= '"Comment":
"'.$comment['comment'].'",';
$output .= '"CommentedBy":
"'.$comment['username'].'"';
$output .= "},";
//echo $comment['comment']." ~
".$comment['username']."<hr />";
}
$output
= substr($output, 0, strlen($output)-1);
$output
.= "]";
echo
$output;
}
else if ($_GET['url'] == "posts") {
$token
= $_COOKIE['SNID'];
$userid
= $db->query('SELECT user_id FROM login_tokens WHERE
token=:token', array(':token'=>sha1($token)))[0]['user_id'];
$followingposts = $db->query('SELECT posts.id,
posts.body, posts.posted_at, posts.likes, users.`username` FROM
users, posts, followers
WHERE
posts.user_id = followers.user_id
AND
users.id = posts.user_id
AND
follower_id = :userid
ORDER
BY posts.likes DESC;', array(':userid'=>$userid));
$response
= "[";
foreach($followingposts as $post) {
$response .= "{";
$response .= '"PostId":
'.$post['id'].',';
$response .= '"PostBody":
"'.$post['body'].'",';
$response .= '"PostedBy":
"'.$post['username'].'",';
$response .= '"PostDate":
"'.$post['posted_at'].'",';
$response .= '"Likes":
'.$post['likes'].'';
$response .= "},";
}
$response
= substr($response, 0, strlen($response)-1);
$response
.= "]";
http_response_code(200);
echo
$response;
}
else if ($_GET['url'] == "profileposts") {
$userid
= $db->query('SELECT id FROM users WHERE username=:username',
array(':username'=>$_GET['username']))[0]['id'];
$followingposts = $db->query('SELECT posts.id,
posts.body, posts.posted_at, posts.likes, users.`username` FROM
users, posts
WHERE
users.id = posts.user_id
AND
users.id = :userid
ORDER
BY posts.likes DESC;', array(':userid'=>$userid));
$response
= "[";
foreach($followingposts as $post) {
$response .= "{";
$response .= '"PostId":
'.$post['id'].',';
$response .= '"PostBody":
"'.$post['body'].'",';
$response .= '"PostedBy":
"'.$post['username'].'",';
$response .= '"PostDate":
"'.$post['posted_at'].'",';
$response .= '"Likes":
'.$post['likes'].'';
$response .= "},";
}
$response
= substr($response, 0, strlen($response)-1);
$response
.= "]";
http_response_code(200);
echo
$response;
}
}
else if ($_SERVER['REQUEST_METHOD'] == "POST") {
//
Создание аккаунта
if
($_GET['url'] == "users") {
$postBody
= file_get_contents("php://input");
$postBody
= json_decode($postBody);
$username
= $postBody->username;
$email
= $postBody->email;
$password
= $postBody->password;
if(!$db->query('SELECT username FROM users
WHERE username=:username', array(':username'=>$username))) {
if(strlen($username) >= 3 &&
strlen($username) <= 32) {
if(preg_match('/[a-zA-Z0-9_]+/', $username)) {
if(strlen($password) >= 6 &&
strlen($password) <= 60) {
if(filter_var($email, FILTER_VALIDATE_EMAIL))
{
if(!$db->query('SELECT email FROM
users WHERE email=:email', array(':email'=>$email))) {
$db->query('INSERT INTO users
VALUES (:id, :username, :password, :email, \'0\', \'\')',
array(':id'=>null, ':username'=>$username,
':password'=>password_hash($password, PASSWORD_BCRYPT),
':email'=>$email));
Mail::sendMail('Welcome to our Social
Network!', 'Your account has been created!', $email);
echo '{ "Success": "User
created!" }';
http_response_code(200);
} else {
echo '{ "Error": "Email
in use!" }';
http_response_code(409);
}
} else {
echo '{ "Error": "Invalid
Email!" }';
http_response_code(409);
}
} else {
echo '{ "Error": "Invalid
Password!" }';
http_response_code(409);
}
}
else {
echo '{ "Error": "Invalid
username!" }';
http_response_code(409);
}
}
else {
echo '{ "Error": "Invalid
username!" }';
http_response_code(409);
}
}
else {
echo
'{ "Error": "User exists!" }';
http_response_code(409); // 409 Conflict
(«конфликт»)
}
}
//
Логин
if
($_GET['url'] == "auth") {
$postBody
= file_get_contents("php://input");
$postBody
= json_decode($postBody);
$username
= $postBody->username;
$password
= $postBody->password;
if
($db->query('SELECT username FROM users WHERE username=:username',
array(':username'=>$username))) {
//
password_verify — Проверяет, соответствует ли
пароль хешу
if
(password_verify($password, $db->query('SELECT password FROM users
WHERE username=:username',
array(':username'=>$username))[0]['password'])) {
$cstrong = True;
$token = bin2hex(openssl_random_pseudo_bytes(64,
$cstrong));
$user_id = $db->query('SELECT id FROM users
WHERE username=:username', array(':username'=>$username))[0]['id'];
$db->query('INSERT INTO login_tokens VALUE
(:id, :token, :user_id)', array(':id'=>null,
':token'=>sha1($token), ':user_id'=>$user_id));
echo '{ "Token": "'.$token.'"
}';
}
else {
echo '{ "Error": "Invalid username
or password!" }';
http_response_code(401);
}
}
else {
echo
'{ "Error": "Invalid username or password!" }';
http_response_code(401);
}
}
else if ($_GET['url'] == "likes") {
//
Like-button. Копируем из класса Post
$postId
= $_GET['id'];
$token
= $_COOKIE['SNID'];
$likerId
= $db->query('SELECT user_id FROM login_tokens WHERE
token=:token', array(':token'=>sha1($token)))[0]['user_id'];
if
(!$db->query('SELECT user_id FROM post_likes WHERE post_id=:postid
AND user_id=:userid', array(':postid'=>$postId,
':userid'=>$likerId))) {
$db->query('UPDATE posts SET likes=likes+1
WHERE id=:postid', array(':postid'=>$postId));
$db->query('INSERT INTO post_likes VALUES (:id,
:postid, :userid)', array(':id'=>null, ':postid'=>$postId,
':userid'=>$likerId));
//Notify::createNotify("", $postId);
}
else {
$db->query('UPDATE posts SET likes=likes-1
WHERE id=:postid', array(':postid'=>$postId));
$db->query('DELETE FROM post_likes WHERE
post_id=:postid AND user_id=:userid', array(':postid'=>$postId,
':userid'=>$likerId));
}
echo
"{";
echo
'"Likes":';
echo
$db->query('SELECT likes FROM posts WHERE id=:postid',
array(':postid'=>$postId))[0]['likes'];
echo
"}";
}
}
else if ($_SERVER['REQUEST_METHOD'] == "DELETE") {
if
($_GET['url'] == "auth") {
if
(isset($_GET['token'])) {
if
($db->query("SELECT token FROM login_tokens WHERE
token=:token", array(':token'=>sha1($_GET['token'])))) {
$db->query('DELETE FROM login_tokens WHERE
token=:token', array(':token'=>sha1($_GET['token'])));
echo '{ "Status": "Success"
}';
http_response_code(200);
}
else {
echo '{ "Error": "Invalid token"
}';
http_response_code(400);
}
}
else {
echo
'{ "Error": "Mal-formed request" }';
http_response_code(400);
}
}
}
else
{
http_response_code(405);
}
?>
Протестируем:
http://newsocial.loc/api/search?query=moto
У
нас выводится: [{"body":"Post
about motos. Hello moto!","0":"Post about motos.
Hello moto!"}]
Чтобы убрать 0, нужно
пойти DP.php и
переписать вывод.
<?php
class DB {
private $pdo;
public function __construct($host, $dbname, $username, $password) {
$pdo = new
PDO('mysql:host='.$host.';dbname='.$dbname.';charset=utf8',
$username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
$this->pdo = $pdo;
}
public function query($query, $params = array()) {
$statement = $this->pdo->prepare($query);
$statement->execute($params);
if(explode(' ', $query)[0] == 'SELECT') {
$data = $statement->fetchAll(PDO::FETCH_ASSOC);
return $data;
}
}
}
?>
Протестируем:
http://newsocial.loc/api/search?query=moto
У
нас выводится: [{"body":"Post about motos.
Hello moto!"}]
Перепишем
запрос на выборку из БД в файле
api/index.php
$posts
= $db->query('SELECT posts.body, posts.posted_at FROM posts WHERE
posts.body LIKE :body '.$whereclause.'', $paramsarray);
Протестируем:
http://newsocial.loc/api/search?query=moto
У
нас выводится: [{"body":"Post about motos.
Hello moto!","posted_at":"2017-09-29 17:12:10"}]
Перепишем
запрос на выборку из БД в файле
api/index.php
$posts
= $db->query('SELECT posts.body, users.username, posts.posted_at
FROM posts, users WHERE users.id = posts.user_id AND posts.body LIKE
:body '.$whereclause.'', $paramsarray);
Протестируем:
http://newsocial.loc/api/search?query=moto
У
нас выводится: [{"body":"Post about motos.
Hello moto!","username":"Masha","posted_at":"2017-09-29
17:12:10"}]
Ограничим
количество выводимых постов.
$posts
= $db->query('SELECT posts.body, users.username, posts.posted_at
FROM posts, users WHERE users.id = posts.user_id AND posts.body LIKE
:body '.$whereclause.' LIMIT 10', $paramsarray);
Комментариев нет:
Отправить комментарий