aboutsummaryrefslogtreecommitdiff
path: root/src/phinde/HubUrlExtractor.php
blob: da29650cf0b4363927f48778a5ca372db2754d1d (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
<?php
namespace phinde;

/**
 * Perform WebSub discovery for "hub" and "self" URLs
 *
 * @link https://www.w3.org/TR/websub/#discovery
 */
class HubUrlExtractor
{
    /**
     * HTTP request object that's used to do the requests
     *
     * @var \HTTP_Request2
     */
    protected $request;

    /**
     * Get the hub and self/canonical URL of a given topic URL.
     * Uses link headers and parses HTML link rels.
     *
     * @param string $url       Topic URL
     * @param int    $redirects Number of redirects that were followed
     *
     * @return array Array of URLs with keys: hub, self.
     *               - "self" value is the URL
     *               - "hub"  value is an array of URLs
     *               Keys may be there but most not if the URL
     *               does not advertise them.
     */
    public function getUrls($url, $redirects = 0)
    {
        //at first, try a HEAD request that does not transfer so much data
        $req = $this->getRequest();
        $req->setUrl($url);
        $req->setMethod(\HTTP_Request2::METHOD_HEAD);
        $req->setConfig('follow_redirects', false);
        $res = $req->send();

        if (intval($res->getStatus() / 100) >= 4
            && $res->getStatus() != 405 //method not supported/allowed
        ) {
            return [];
        }

        $url  = $res->getEffectiveUrl();
        $base = new \Net_URL2($url);

        $urls = $this->extractHeader($res);
        if (count($urls) === 2) {
            return $this->absolutifyUrls($urls, $base);
        }

        if ($res->isRedirect()) {
            //we tried header links and that failed, now follow the redirect
            if ($redirects > 5) {
                return [];
            }
            $redirectUrl = (string) $base->resolve($res->getHeader('location'));
            return $this->getUrls($redirectUrl, $redirects + 1);
        }

        list($type) = explode(';', $res->getHeader('Content-type'));
        if ($type != 'text/html' && $type != 'text/xml'
            && $type != 'application/xhtml+xml'
            && $type != 'application/atom+xml'
            && $type != 'application/rss+xml'
            && $res->getStatus() != 405//HEAD method not allowed
        ) {
            //we will not be able to extract links from the content
            return $urls;
        }

        //HEAD failed, do a normal GET
        $req->setMethod(\HTTP_Request2::METHOD_GET);
        $res = $req->send();
        if (intval($res->getStatus() / 100) >= 4) {
            return $urls;
        }

        //yes, maybe the server does return this header now
        // e.g. PHP's Phar::webPhar() does not work with HEAD
        // https://bugs.php.net/bug.php?id=51918
        $urls = array_merge($this->extractHeader($res), $urls);
        if (count($urls) === 2) {
            return $this->absolutifyUrls($urls, $base);
        }

        $urls = [];//do not mix header and content links

        $body = $res->getBody();
        $doc = $this->loadHtml($body, $res);

        $xpath = new \DOMXPath($doc);
        $xpath->registerNamespace('h', 'http://www.w3.org/1999/xhtml');
        $xpath->registerNamespace('atom', 'http://www.w3.org/2005/Atom');

        if ($type === 'application/atom+xml') {
            $tagQuery = '/atom:feed/atom:link[';

        } else if ($type === 'application/rss+xml') {
            $tagQuery = '/rss/channel/*[(self::link or self::atom:link) and ';

        } else {
            $tagQuery = '/*[self::html or self::h:html]'
                . '/*[self::head or self::h:head]'
                . '/*[(self::link or self::h:link)'
                . ' and';
        }
        $nodeList = $xpath->query(
            $tagQuery
            . ' ('
            . '  contains(concat(" ", normalize-space(@rel), " "), " hub ")'
            . '  or'
            . '  contains(concat(" ", normalize-space(@rel), " "), " canonical ")'
            . '  or'
            . '  contains(concat(" ", normalize-space(@rel), " "), " self ")'
            . ' )'
            . ']'
        );

        if ($nodeList->length == 0) {
            //topic has no links
            return $urls;
        }

        foreach ($nodeList as $link) {
            $uri  = $link->attributes->getNamedItem('href')->nodeValue;
            $types = explode(
                ' ', $link->attributes->getNamedItem('rel')->nodeValue
            );
            foreach ($types as $type) {
                if ($type == 'canonical') {
                    $type = 'self';
                }
                if ($type == 'self' && !isset($urls['self'])) {
                    $urls['self'] = $uri;
                } else if ($type == 'hub') {
                    $urls['hub'][] = $uri;
                }
            }
        }

        //<base href=".."> extraction is not necessary; RFC 5988 says:
        // Note that any base IRI from the message's content is not applied.
        return $this->absolutifyUrls($urls, $base);
    }

    /**
     * Extract hub url from the HTTP response headers.
     *
     * @param object $res HTTP response
     *
     * @return array Array with maximal two keys: hub and self
     */
    protected function extractHeader(\HTTP_Request2_Response $res)
    {
        $http = new \HTTP2();

        $urls = array();
        $links = $http->parseLinks($res->getHeader('Link'));
        foreach ($links as $link) {
            if (isset($link['_uri']) && isset($link['rel'])) {
                if (array_search('hub', $link['rel']) !== false) {
                    $urls['hub'][] = $link['_uri'];
                }
                if (!isset($urls['self'])
                    && array_search('self', $link['rel']) !== false
                ) {
                    $urls['self'] = $link['_uri'];
                }
            }
        }
        return $urls;
    }

    /**
     * Load a DOMDocument from the given HTML or XML
     *
     * @param string $sourceBody Content of $source URI
     * @param object $res        HTTP response from fetching $source
     *
     * @return \DOMDocument DOM document object with HTML/XML loaded
     */
    protected static function loadHtml($sourceBody, \HTTP_Request2_Response $res)
    {
        $doc = new \DOMDocument();

        libxml_clear_errors();
        $old = libxml_use_internal_errors(true);

        $typeParts = explode(';', $res->getHeader('content-type'));
        $type = $typeParts[0];
        if ($type == 'application/xhtml+xml'
            || $type == 'application/xml'
            || $type == 'text/xml'
            || $type == 'application/atom+xml'
            || $type == 'application/rss+xml'
        ) {
            $doc->loadXML($sourceBody);
        } else {
            $doc->loadHTML($sourceBody);
        }

        libxml_clear_errors();
        libxml_use_internal_errors($old);

        return $doc;
    }

    /**
     * Returns the HTTP request object clone that can be used
     * for one HTTP request.
     *
     * @return HTTP_Request2 Clone of the setRequest() object
     */
    public function getRequest()
    {
        if ($this->request === null) {
            $request = new HttpRequest();
            $this->setRequestTemplate($request);
        }

        //we need to clone because previous requests could have
        //set internal variables like POST data that we don't want now
        return clone $this->request;
    }

    /**
     * Sets a custom HTTP request object that will be used to do HTTP requests
     *
     * @param object $request Request object
     *
     * @return self
     */
    public function setRequestTemplate(\HTTP_Request2 $request)
    {
        $this->request = $request;
        return $this;
    }

    /**
     * Make the list of urls absolute
     *
     * @param array  $urls Array of maybe relative URLs, or array of URLs
     * @param object $base Base URL to resolve the relatives against
     *
     * @return array List of absolute URLs
     */
    protected function absolutifyUrls($urls, \Net_URL2 $base)
    {
        foreach ($urls as $key => $url) {
            if (is_array($url)) {
                foreach ($url as $singleKey => $singleUrl) {
                    $urls[$key][$singleKey] = (string) $base->resolve($singleUrl);
                }
            } else {
                $urls[$key] = (string) $base->resolve($url);
            }
        }
        return $urls;
    }
}
?>