]> git.immae.eu Git - github/shaarli/Shaarli.git/blame - application/LinkUtils.php
Extract the title/charset during page download, and check content type
[github/shaarli/Shaarli.git] / application / LinkUtils.php
CommitLineData
1557cefb
A
1<?php
2
3/**
d65342e3 4 * Get cURL callback function for CURLOPT_WRITEFUNCTION
1557cefb 5 *
d65342e3
A
6 * @param string $charset to extract from the downloaded page (reference)
7 * @param string $title to extract from the downloaded page (reference)
8 * @param string $curlGetInfo Optionnaly overrides curl_getinfo function
1557cefb 9 *
d65342e3 10 * @return Closure
1557cefb 11 */
d65342e3 12function get_curl_download_callback(&$charset, &$title, $curlGetInfo = 'curl_getinfo')
1557cefb 13{
d65342e3
A
14 /**
15 * cURL callback function for CURLOPT_WRITEFUNCTION (called during the download).
16 *
17 * While downloading the remote page, we check that the HTTP code is 200 and content type is 'html/text'
18 * Then we extract the title and the charset and stop the download when it's done.
19 *
20 * @param resource $ch cURL resource
21 * @param string $data chunk of data being downloaded
22 *
23 * @return int|bool length of $data or false if we need to stop the download
24 */
25 return function(&$ch, $data) use ($curlGetInfo, &$charset, &$title) {
26 $responseCode = $curlGetInfo($ch, CURLINFO_RESPONSE_CODE);
27 if (!empty($responseCode) && $responseCode != 200) {
28 return false;
29 }
30 $contentType = $curlGetInfo($ch, CURLINFO_CONTENT_TYPE);
31 if (!empty($contentType) && strpos($contentType, 'text/html') === false) {
32 return false;
33 }
34 if (empty($charset)) {
35 $charset = header_extract_charset($contentType);
36 }
37 if (empty($charset)) {
38 $charset = html_extract_charset($data);
39 }
40 if (empty($title)) {
41 $title = html_extract_title($data);
42 }
43 // We got everything we want, stop the download.
44 if (!empty($responseCode) && !empty($contentType) && !empty($charset) && !empty($title)) {
45 return false;
46 }
47
48 return strlen($data);
49 };
1557cefb
A
50}
51
52/**
d65342e3 53 * Extract title from an HTML document.
1557cefb 54 *
d65342e3 55 * @param string $html HTML content where to look for a title.
1557cefb 56 *
d65342e3 57 * @return bool|string Extracted title if found, false otherwise.
1557cefb 58 */
d65342e3 59function html_extract_title($html)
1557cefb 60{
d65342e3
A
61 if (preg_match('!<title.*?>(.*?)</title>!is', $html, $matches)) {
62 return trim(str_replace("\n", '', $matches[1]));
1557cefb 63 }
d65342e3 64 return false;
1557cefb
A
65}
66
67/**
d65342e3 68 * Extract charset from HTTP header if it's defined.
1557cefb 69 *
d65342e3 70 * @param string $header HTTP header Content-Type line.
1557cefb
A
71 *
72 * @return bool|string Charset string if found (lowercase), false otherwise.
73 */
d65342e3 74function header_extract_charset($header)
1557cefb 75{
d65342e3
A
76 preg_match('/charset="?([^; ]+)/i', $header, $match);
77 if (! empty($match[1])) {
78 return strtolower(trim($match[1]));
1557cefb
A
79 }
80
81 return false;
82}
83
84/**
85 * Extract charset HTML content (tag <meta charset>).
86 *
87 * @param string $html HTML content where to look for charset.
88 *
89 * @return bool|string Charset string if found, false otherwise.
90 */
91function html_extract_charset($html)
92{
93 // Get encoding specified in HTML header.
ce7b0b64 94 preg_match('#<meta .*charset=["\']?([^";\'>/]+)["\']? */?>#Usi', $html, $enc);
1557cefb
A
95 if (!empty($enc[1])) {
96 return strtolower($enc[1]);
97 }
98
99 return false;
100}
141a86c5
A
101
102/**
103 * Count private links in given linklist.
104 *
7af9a418 105 * @param array|Countable $links Linklist.
141a86c5
A
106 *
107 * @return int Number of private links.
108 */
109function count_private($links)
110{
111 $cpt = 0;
112 foreach ($links as $link) {
ee6f4b64
V
113 if ($link['private']) {
114 $cpt += 1;
115 }
141a86c5 116 }
9ccca401 117
141a86c5
A
118 return $cpt;
119}
9ccca401
A
120
121/**
122 * In a string, converts URLs to clickable links.
123 *
124 * @param string $text input string.
125 * @param string $redirector if a redirector is set, use it to gerenate links.
126 *
127 * @return string returns $text with all links converted to HTML links.
128 *
129 * @see Function inspired from http://www.php.net/manual/en/function.preg-replace.php#85722
130 */
131function text2clickable($text, $redirector = '')
132{
133 $regex = '!(((?:https?|ftp|file)://|apt:|magnet:)\S+[[:alnum:]]/?)!si';
134
135 if (empty($redirector)) {
136 return preg_replace($regex, '<a href="$1">$1</a>', $text);
137 }
138 // Redirector is set, urlencode the final URL.
139 return preg_replace_callback(
140 $regex,
141 function ($matches) use ($redirector) {
142 return '<a href="' . $redirector . urlencode($matches[1]) .'">'. $matches[1] .'</a>';
143 },
144 $text
145 );
146}
147
148/**
149 * Auto-link hashtags.
150 *
151 * @param string $description Given description.
152 * @param string $indexUrl Root URL.
153 *
154 * @return string Description with auto-linked hashtags.
155 */
156function hashtag_autolink($description, $indexUrl = '')
157{
158 /*
159 * To support unicode: http://stackoverflow.com/a/35498078/1484919
160 * \p{Pc} - to match underscore
161 * \p{N} - numeric character in any script
162 * \p{L} - letter from any language
163 * \p{Mn} - any non marking space (accents, umlauts, etc)
164 */
165 $regex = '/(^|\s)#([\p{Pc}\p{N}\p{L}\p{Mn}]+)/mui';
166 $replacement = '$1<a href="'. $indexUrl .'?addtag=$2" title="Hashtag $2">#$2</a>';
167 return preg_replace($regex, $replacement, $description);
168}
169
170/**
171 * This function inserts &nbsp; where relevant so that multiple spaces are properly displayed in HTML
172 * even in the absence of <pre> (This is used in description to keep text formatting).
173 *
174 * @param string $text input text.
175 *
176 * @return string formatted text.
177 */
178function space2nbsp($text)
179{
180 return preg_replace('/(^| ) /m', '$1&nbsp;', $text);
181}
182
183/**
184 * Format Shaarli's description
185 *
186 * @param string $description shaare's description.
187 * @param string $redirector if a redirector is set, use it to gerenate links.
7af9a418 188 * @param string $indexUrl URL to Shaarli's index.
9ccca401
A
189 *
190 * @return string formatted description.
191 */
192function format_description($description, $redirector = '', $indexUrl = '') {
193 return nl2br(space2nbsp(hashtag_autolink(text2clickable($description, $redirector), $indexUrl)));
194}
d592daea
A
195
196/**
197 * Generate a small hash for a link.
198 *
199 * @param DateTime $date Link creation date.
200 * @param int $id Link ID.
201 *
202 * @return string the small hash generated from link data.
203 */
204function link_small_hash($date, $id)
205{
206 return smallHash($date->format(LinkDB::LINK_DATE_FORMAT) . $id);
207}