summaryrefslogtreecommitdiff
path: root/search.php
blob: aa19f904a0c6281c13a7177f295f7e9c6462be4d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
<?php

define("VERSION", "2.0.2");

/**
 * Load and parse the config file, setting any defaults here if non-required
 * fields are not set
 *
 * @return string[]
 * @author Phil Burton <phil@pgburton.com>
 * @throws Exception when file is not readable
 * @throws Exception when ini file fails to parse
 * @throws Exception when url not found in ini file
 * @throws Exception when command not found in ini file
 * @throws Exception when pagesize is set incorrectly
 */
function getConfig()
{
    $config = false;

    if (!is_readable("config.ini")) {
        throw new Exception('File config.ini does not exist');
    }
    if (!$config = parse_ini_file("config.ini")) {
        throw new Exception('Could not parse ini file', 1);
    }
    if (!isset($config["url"])) {
        throw new Exception('`url` not found in ini file', 1);
    }
    if (!isset($config["command"])) {
        throw new Exception('`command` not found in ini file', 1);
    }

    // Set default page size if it's not in the config
    if (!isset($config["pagesize"])) {
        $config["pagesize"] = 3;
    } elseif (!is_int((int)$config["pagesize"]) || $config["pagesize"] < 1) {
        throw new Exception('Page size ' . $config["pagesize"]  . ' not valid in config', 1);
    }
    // hash the password
    if (isset($config['password'])) {
        $config['hash'] = hash("sha256", $config['password']);
    }
    return $config;
}

/**
 * Use curl to find get the plain text file for a url
 * Using the sha256 hashed password if it's been set in the config
 *
 * @param  string[] $config
 * @return StdClass[]
 * @author Phil Burton <phil@pgburton.com>
 */
function getResultsFromUrl($config)
{
    $curl = curl_init($config["url"] . "?format=plain");
    if (isset($config["hash"])) {
        curl_setopt($curl, CURLOPT_HTTPHEADER, array("Cookie: password=" . $config["hash"]));
    }
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    $output = explode("\n", curl_exec($curl));
    curl_close($curl);

    if (!isset($output)) {
        throw new Exception(
            "Could not retrive results from http server `"
            . $config["url"]
            . "?format=json` using password="
            . (isset($config["hash"]) ? "true" : "false"),
            1
        );
    }
    return $output;
}

/**
 * Return the help text
 *
 * @param  StdClass[] $config
 * @return string
 * @author Phil Burton <phil@pgburton.com>
 */
function getHelp($config)
{
    return "Usage: !" . $config["command"] . " [query] #[page] | "
        . "e.g: !" . $config["command"] . " intense | "
        . "!" . $config["command"] . " intense marcus | "
        . "!" . $config["command"] . " intense marcus #2 (returns the second page of results)";
}

/**
 * Get the version string
 *
 * @param  stdClass[] $config
 * @return string
 * @author Phil Burton <phil@pgburton.com>
 */
function getVersion($config)
{
    return $config["command"] . " v" . VERSION;
}

/**
 * Output the given string, adding a new line at the end
 * If pieces is an array, use the glue to implode and output a single string
 *
 * EXIT
 *
 * @param  string|string[] $pieces
 * @param  string $glue
 * @param  bool $sderr
 * @author Phil Burton <phil@pgburton.com>
 */
function output($pieces, $glue = " - ", $stderr = false)
{
    $out = "";
    if (!is_array($pieces)) {
        $out = $pieces . "\n";
    } else {
        $out = implode($glue, $pieces) . "\n";
    }

    if ($stderr) {
        fwrite(STDERR, $out . "\n");
    } else {
        echo $out;
    }

    exit;
}

/**
 * Read stdin and return as a string
 *
 * @return string
 * @author Phil Burton <phil@pgburton.com>
 */
function read_stdin()
{
    $fr = fopen("php://stdin", "r");
    $input = fgets($fr, 128);
    $input = rtrim($input);
    fclose($fr);
    return $input;
}

/**
 * Get the start and end index positions for the required page and
 * page size
 *
 * @param  int $page
 * @param  int $pagesize
 * @return int[]
 * @author Phil Burton <phil@pgburton.com>
 */
function getPaginationBounds($page, $pagesize)
{
    return [
        "start" => ($page - 1) * $pagesize,
        "end" => (($page - 1) * $pagesize) + ($pagesize - 1)
    ];
}

/**
 * Loop through the stdin and parse the arguments given
 * If we hit a "special" argument then run the specific code and exit
 * Otherwise we set the page and search terms and return them as an array
 *
 * @param  $config
 * @return mixed[]
 * @author Phil Burton <phil@pgburton.com>
 */
function getFormattedArguments($config)
{
    $args = explode(" ", read_stdin());

    if (!isset($args) || empty($args)) {
        throw new Exception("No arguments found");
    }
    // Loop the raw arguments and create our formated argument array
    $formatArgs = [];
    $formatArgs["search"] = [];
    foreach ($args as $arg) {
        // Switch to check for special arguments
        // output should exit but incase it errors we double break
        switch ($arg) {
            case "--version":
            case "-v": // Flow through
                output(getVersion($config));
                break 2;
            case "--help":
            case "-h": // Flow through
                output(getHelp($config));
                break 2;
        }

        // Check to see if we have a page specified
        if (strpos($arg, "#") === 0) {
            $formatArgs["page"] = substr($arg, 1);
            continue;
        }

        // If we reach here, then the argument is a search term
        $formatArgs["search"][] = $arg;
    }

    // If we reach this point we must have at least one search term
    if (empty($formatArgs["search"])) {
        throw new Exception("Please Enter a search term");
    }

    if (!isset($formatArgs["page"])) {
        $formatArgs["page"] = 1;
    } elseif (!is_int((int)$formatArgs["page"]) || $formatArgs["page"] < 1) {
        throw new Exception("Page number `" . $formatArgs["page"] . "` is not valid");
    }

    return $formatArgs;
}

/*********************************
 * ENTRY POINT FOR FUNCTION HERE *
 *********************************/
try {
    $config = getConfig();
    $content = getResultsFromUrl($config);
    $arguments = getFormattedArguments($config);

    // parse the arguments
    $page = $arguments["page"];

    $out = [];

    // Really slow search
    $results = [];
    foreach ($content as $upload) {
        $match = false;
        foreach ($arguments["search"] as $arg) {
            if (!is_null($arg) && stripos($upload, $arg) === false) {
                $match = false;
                break;
            }
            $match = true;
        }
        if ($match) {
            $results[] = $config["url"] . "/" . rawurlencode($upload);
        }
    }

    if (empty($results)) {
        output("No results found");
    }

    $count = count($results);
    $i = 0;
    $bounds = getPaginationBounds($page, $config["pagesize"]);

    if ($bounds["start"] > ($count - 1)) {
        throw new Exception("No results for this page");
    }

    foreach ($results as $result) {
        if ($i < $bounds["start"] || $i > $bounds["end"]) {
            $i++;
            continue;
        }
        $out[] = $i + 1 . ": " . $result;
        $i++;
    }

    if ($count > 3) {
        $out[] = "results (" . $count . ")";
    }

    output($out);

} catch (Exception $e) {
    output($e->getMessage(), " - ", ($e->getCode() == 1));
}