Browse Source

chore: merge pull request #47 from cristiancmoises/main

Update search.php
Ahwx 1 month ago
parent
commit
21eea2b089
2 changed files with 107 additions and 177 deletions
  1. 52 84
      api.php
  2. 55 93
      search.php

+ 52 - 84
api.php

@@ -1,115 +1,83 @@
 <?php
 
-$query = $_GET['q'];
-
-$bookmark = null;
-if (array_key_exists("bookmark", $_GET)) {
-    $bookmark = urldecode($_GET["bookmark"]);
-}
-
-$csrftoken = null;
-if (array_key_exists("csrftoken", $_GET)) {
-    $csrftoken = $_GET["csrftoken"];
-}
-
-$url = "https://www.pinterest.com/resource/BaseSearchResource/get/";
-
-class SearchResult
-{
-    public $images;
-    public $bookmark;
-}
-
-$header_function = function($ch, $rawheader)
-{
-    global $csrftoken;
-    $len = strlen($rawheader);
-
-    $header = explode(":", $rawheader, 2);
-    if (count($header) != 2)
-        return $len;
-
-    // we are only interested in set-cookie header
-    if (trim($header[0]) != "set-cookie")
-        return $len;
-
-    $cookie = explode(";", trim($header[1]), 2);
-    $cookie = explode("=", $cookie[0], 2);
-
-    switch ($cookie[0])
-    {
-        case "csrftoken":
-            $csrftoken = $cookie[1];
-    }
-
-    return $len;
-};
-
-$prepare_search_curl_obj = function($query, $bookmark) use ($url, $header_function, $csrftoken)
-{
-    $data_param_obj = array(
-        "options"=>array(
-            "query"=>$query
-        )
-    );
-    if ($bookmark != null)
-        $data_param_obj["options"]["bookmarks"] = array($bookmark);
-
-    $data_param = urlencode(json_encode($data_param_obj));
-
-    $headers = array();
-    if ($csrftoken != null)
-    {
+// Prepare cURL object with options for the search query
+function prepareSearchCurlObj($query, $bookmark = null, $url, $csrftoken = null, $header_function) {
+    $data_param_obj = [
+        "options" => [
+            "query" => $query,
+            "bookmarks" => $bookmark ? [$bookmark] : null
+        ]
+    ];
+
+    $data_param = urlencode(json_encode(array_filter($data_param_obj['options'])));
+
+    $headers = [];
+    if ($csrftoken) {
         $headers[] = "x-csrftoken: $csrftoken";
         $headers[] = "cookie: csrftoken=$csrftoken";
     }
 
-    $finalurl = $url;
-    if ($bookmark == null)
-        $finalurl = "$url?data=$data_param";
+    $finalurl = $bookmark ? $url : "$url?data=$data_param";
 
     $ch = curl_init($finalurl);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
     curl_setopt($ch, CURLOPT_HEADERFUNCTION, $header_function);
     curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
-    if ($bookmark != null)
-    {
+
+    if ($bookmark) {
         curl_setopt($ch, CURLOPT_POST, true);
         curl_setopt($ch, CURLOPT_POSTFIELDS, "data=$data_param");
     }
+
     return $ch;
-};
+}
 
-$search = function($query, $bookmark) use($prepare_search_curl_obj)
-{
-    $ch = $prepare_search_curl_obj($query, $bookmark);
+// Search function to execute the cURL request and process the response
+function search($query, $bookmark, $url, $csrftoken, $header_function) {
+    $ch = prepareSearchCurlObj($query, $bookmark, $url, $csrftoken, $header_function);
+    
     $response = curl_exec($ch);
+    
+    if ($response === false) {
+        // Handle cURL error
+        $error = curl_error($ch);
+        curl_close($ch);
+        return json_encode(['error' => 'CURL Error: ' . $error]);
+    }
+
+    curl_close($ch); // Close cURL handle
+
     $data = json_decode($response);
-    $images = array();
-        foreach ($data->{"resource_response"}->{"data"}->{"results"} as $result)
-        {
-            $image = $result->{"images"}->{"orig"};
-            $url = $image->{"url"};
-            array_push($images, $url);
+    $images = [];
+
+    if (isset($data->resource_response->data->results)) {
+        foreach ($data->resource_response->data->results as $result) {
+            $url = $result->images->orig->url ?? null; // Use null coalescing for safety
+            if ($url) {
+                $images[] = $url;
+            }
         }
-    echo json_encode($images);
+    }
+
     $result = new SearchResult();
     $result->images = $images;
-    if (property_exists($data->{"resource_response"}, "bookmark"))
-        $result->bookmark = $data->{"resource_response"}->{"bookmark"};
+    $result->bookmark = $data->resource_response->bookmark ?? null;
+
     return $result;
-};
+}
 
-$result = $search($query, $bookmark);
+// Main execution
+header("Content-Type: application/json");
+$result = search($query, $bookmark, $url, $csrftoken, $header_function);
 
-if ($result->bookmark != null)
-{
+// Handle bookmark for pagination
+if ($result->bookmark) {
     $query_encoded = urlencode($query);
     $bookmark_encoded = urlencode($result->bookmark);
     $csrftoken_encoded = urlencode($csrftoken);
+    // Uncomment below line to display the link for next page
     // echo "<h2 style=\"text-align: center;\"><a href=\"/search.php?q=$query_encoded&bookmark=$bookmark_encoded&csrftoken=$csrftoken_encoded\">Next page</a></h2><br><br><br>";
 }
 
-    header("Content-Type: application/json");
-
+echo json_encode($result);
 ?>

+ 55 - 93
search.php

@@ -1,41 +1,31 @@
 <?php require "misc/header.php"; ?>
 <title>
 <?php
-$query = htmlspecialchars(trim($_REQUEST["q"]));
-echo $query;
+$query = htmlspecialchars(trim($_REQUEST["q"] ?? ''));
+echo $query ?: 'Search' . ' - Binternet';
 ?> - Binternet</title>
 </head>
-    <body>
-        <form class="search-container" method="get" autocomplete="off">
-            <h1><a class="no-decoration accent" href="./">Binternet</a></h1>
-            <input type="text" name="q" placeholder="Search Image"
-                <?php
-                $query_encoded = urlencode($query);
-
-                if (1 > strlen($query) || strlen($query) > 64) {
-                    header("Location: ./");
-                    die();
-                }
-
-                echo "value=\"$query\"";
-                ?>
-            >
-            <!-- <div></div> -->
-        </form>
+<body>
+    <form class="search-container" method="get" autocomplete="off">
+        <h1><a class="no-decoration accent" href="./">Binternet</a></h1>
+        <input type="text" name="q" placeholder="Search Image"
+            <?php
+            // Validate query length
+            if (strlen($query) < 1 || strlen($query) > 64) {
+                header("Location: ./");
+                exit();
+            }
+            echo "value=\"" . htmlspecialchars($query) . "\"";
+            ?>
+        >
+    </form>
 
 <?php
-$query = $_GET["q"];
-
-$bookmark = null;
-if (array_key_exists("bookmark", $_GET)) {
-    $bookmark = urldecode($_GET["bookmark"]);
-}
-
-$csrftoken = null;
-if (array_key_exists("csrftoken", $_GET)) {
-    $csrftoken = $_GET["csrftoken"];
-}
+// Fetching query and optional parameters
+$bookmark = $_GET["bookmark"] ?? null;
+$csrftoken = $_GET["csrftoken"] ?? null;
 
+// Pinterest API endpoint
 $url = "https://www.pinterest.com/resource/BaseSearchResource/get/";
 
 class SearchResult
@@ -44,112 +34,86 @@ class SearchResult
     public $bookmark;
 }
 
-$header_function = function ($ch, $rawheader) {
-    global $csrftoken;
-    $len = strlen($rawheader);
-
-    $header = explode(":", $rawheader, 2);
-    if (count($header) != 2) {
-        return $len;
-    }
-
-    // we are only interested in set-cookie header
-    if (trim($header[0]) != "set-cookie") {
-        return $len;
+// Header function to capture CSRF token from response
+$header_function = function ($ch, $rawheader) use (&$csrftoken) {
+    if (preg_match('/^set-cookie:\s*csrftoken=([^;]*)/', $rawheader, $matches)) {
+        $csrftoken = $matches[1];
     }
-
-    $cookie = explode(";", trim($header[1]), 2);
-    $cookie = explode("=", $cookie[0], 2);
-
-    switch ($cookie[0]) {
-        case "csrftoken":
-            $csrftoken = $cookie[1];
-    }
-
-    return $len;
+    return strlen($rawheader);
 };
 
-$prepare_search_curl_obj = function ($query, $bookmark) use (
-    $url,
-    $header_function,
-    $csrftoken
-) {
+// Prepare CURL object for search request
+$prepare_search_curl_obj = function ($query, $bookmark) use ($url, $header_function, $csrftoken) {
     $data_param_obj = [
         "options" => [
             "query" => $query,
         ],
     ];
-    if ($bookmark != null) {
+    
+    if ($bookmark !== null) {
         $data_param_obj["options"]["bookmarks"] = [$bookmark];
     }
 
     $data_param = urlencode(json_encode($data_param_obj));
-
     $headers = [];
-    if ($csrftoken != null) {
+    
+    if ($csrftoken !== null) {
         $headers[] = "x-csrftoken: $csrftoken";
         $headers[] = "cookie: csrftoken=$csrftoken";
     }
 
-    $finalurl = $url;
-    if ($bookmark == null) {
-        $finalurl = "$url?data=$data_param";
-    }
-
+    $finalurl = $bookmark === null ? "$url?data=$data_param" : $url;
+    
     $ch = curl_init($finalurl);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
     curl_setopt($ch, CURLOPT_HEADERFUNCTION, $header_function);
     curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
-    if ($bookmark != null) {
+    
+    if ($bookmark !== null) {
         curl_setopt($ch, CURLOPT_POST, true);
         curl_setopt($ch, CURLOPT_POSTFIELDS, "data=$data_param");
     }
+    
     return $ch;
 };
 
+// Function to perform the search and display results
 $search = function ($query, $bookmark) use ($prepare_search_curl_obj) {
     $ch = $prepare_search_curl_obj($query, $bookmark);
     $response = curl_exec($ch);
     $data = json_decode($response);
+    
     $images = [];
-    echo "<div class=img-container>";
-    if (
-        $data &&
-        property_exists($data, "resource_response") &&
-        property_exists($data->{"resource_response"}, "data") &&
-        property_exists($data->{"resource_response"}->{"data"}, "results")
-    ) {
-        foreach (
-            $data->{"resource_response"}->{"data"}->{"results"}
-            as $result
-        ) {
-            $image = $result->{"images"}->{"orig"};
-            $url = $image->{"url"};
-            array_push($images, $url);
-            echo "<a class=img-result href='/image_proxy.php?url=", $url, "'>";
-            echo "<img loading='lazy' src='/image_proxy.php?url=",
-                $url,
-                "'></a>";
+    echo "<div class='img-container'>";
+    
+    if ($data && isset($data->resource_response->data->results)) {
+        foreach ($data->resource_response->data->results as $result) {
+            $image = $result->images->orig;
+            $url = $image->url;
+            $images[] = $url;
+            echo "<a class='img-result' href='/image_proxy.php?url=" . htmlspecialchars($url) . "'>";
+            echo "<img loading='lazy' src='/image_proxy.php?url=" . htmlspecialchars($url) . "'></a>";
         }
     } else {
         echo "<p>No results found.</p>";
     }
+    
     echo "</div>";
+    
     $result = new SearchResult();
     $result->images = $images;
-    if (
-        $data &&
-        property_exists($data, "resource_response") &&
-        property_exists($data->{"resource_response"}, "bookmark")
-    ) {
-        $result->bookmark = $data->{"resource_response"}->{"bookmark"};
+    
+    if (isset($data->resource_response->bookmark)) {
+        $result->bookmark = $data->resource_response->bookmark;
     }
+    
     return $result;
 };
 
 $result = $search($query, $bookmark);
 
-if ($result->bookmark != null) {
+// Pagination link for the next page
+if ($result->bookmark !== null) {
     $query_encoded = urlencode($query);
     $bookmark_encoded = urlencode($result->bookmark);
     $csrftoken_encoded = $csrftoken ? urlencode($csrftoken) : "";
@@ -158,6 +122,4 @@ if ($result->bookmark != null) {
 }
 
 include "misc/footer.php";
-
-
 ?>