1<?php
2
3namespace dokuwiki\plugin\xref;
4
5use dokuwiki\HTTP\DokuHTTPClient;
6
7class Grok
8{
9
10    protected $baseUrl;
11    protected $def;
12    protected $path;
13
14    public function __construct($reference, $baseUrl = 'https://codesearch.dokuwiki.org')
15    {
16        $heuristic = new Heuristics($reference);
17        $this->def = $heuristic->getDef();
18        $this->path = $heuristic->getPath();
19        $this->baseUrl = rtrim($baseUrl, '/');
20    }
21
22    /**
23     * Return the URL that leads to the search interface
24     *
25     * @return string
26     */
27    public function getSearchUrl()
28    {
29        if ($this->def === '' && $this->path === '') return $this->baseUrl;
30
31        $url = $this->baseUrl . '/search?';
32        $param = [
33            'project' => 'dokuwiki',
34            'defs' => $this->def,
35            'path' => $this->path,
36        ];
37        $url .= buildURLparams($param, '&');
38        return $url;
39    }
40
41    /**
42     * Return the URL that allows to query the API
43     *
44     * @return string
45     */
46    public function getAPIUrl()
47    {
48        $url = $this->baseUrl . '/api/v1/search?';
49        $param = [
50            'projects' => 'dokuwiki',
51            'def' => $this->def,
52            'path' => $this->path,
53        ];
54        $url .= buildURLparams($param, '&');
55        return $url;
56    }
57
58    /**
59     * Return the number of results to expect
60     *
61     * @return false|int false on errors
62     */
63    public function getResultCount()
64    {
65        if ($this->def === '' && $this->path === '') return 0;
66
67        $http = new DokuHTTPClient();
68        $http->timeout = 5;
69        $json = $http->get($this->getAPIUrl());
70        if (!$json) return false;
71        $data = json_decode($json, true);
72        if (!$data) return false;
73        if (!isset($data['resultCount'])) return false;
74        return $data['resultCount'];
75    }
76}
77