dolibarr 21.0.4
geturl.lib.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2008-2020 Laurent Destailleur <eldy@users.sourceforge.net>
3 * Copyright (C) 2024 MDW <mdeweerd@users.noreply.github.com>
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 3 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <https://www.gnu.org/licenses/>.
17 * or see https://www.gnu.org/
18 */
19
42function getURLContent($url, $postorget = 'GET', $param = '', $followlocation = 1, $addheaders = array(), $allowedschemes = array('http', 'https'), $localurl = 0, $ssl_verifypeer = -1)
43{
44 //declaring of global variables
45 global $conf;
46 $USE_PROXY = !getDolGlobalString('MAIN_PROXY_USE') ? 0 : $conf->global->MAIN_PROXY_USE;
47 $PROXY_HOST = !getDolGlobalString('MAIN_PROXY_HOST') ? 0 : $conf->global->MAIN_PROXY_HOST;
48 $PROXY_PORT = !getDolGlobalString('MAIN_PROXY_PORT') ? 0 : $conf->global->MAIN_PROXY_PORT;
49 $PROXY_USER = !getDolGlobalString('MAIN_PROXY_USER') ? 0 : $conf->global->MAIN_PROXY_USER;
50 $PROXY_PASS = !getDolGlobalString('MAIN_PROXY_PASS') ? 0 : $conf->global->MAIN_PROXY_PASS;
51
52 dol_syslog("getURLContent postorget=".$postorget." URL=".$url." param=".$param);
53
54 if (!function_exists('curl_init')) {
55 return array('http_code' => 500, 'content' => '', 'curl_error_no' => 1, 'curl_error_msg' => 'PHP curl library must be installed');
56 }
57
58 //setting the curl parameters.
59 $ch = curl_init();
60
61 /*print $API_Endpoint."-".$API_version."-".$PAYPAL_API_USER."-".$PAYPAL_API_PASSWORD."-".$PAYPAL_API_SIGNATURE."<br>";
62 print $USE_PROXY."-".$gv_ApiErrorURL."<br>";
63 print $nvpStr;
64 exit;*/
65 curl_setopt($ch, CURLOPT_VERBOSE, 1);
66 curl_setopt($ch, CURLOPT_USERAGENT, 'Dolibarr geturl function');
67
68 // We use @ here because this may return warning if safe mode is on or open_basedir is on (following location is forbidden when safe mode is on).
69 // We force value to false so we will manage redirection ourself later.
70 @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
71
72 if (is_array($addheaders) && count($addheaders)) {
73 curl_setopt($ch, CURLOPT_HTTPHEADER, $addheaders);
74 }
75 curl_setopt($ch, CURLINFO_HEADER_OUT, true); // To be able to retrieve request header and log it
76
77 // By default use the TLS version decided by PHP.
78 // You can force, if supported a version like TLSv1 or TLSv1.2
79 if (getDolGlobalString('MAIN_CURL_SSLVERSION')) {
80 curl_setopt($ch, CURLOPT_SSLVERSION, $conf->global->MAIN_CURL_SSLVERSION);
81 }
82 //curl_setopt($ch, CURLOPT_SSLVERSION, 6); for tls 1.2
83
84 // Turning on or off the ssl target certificate
85 if ($ssl_verifypeer < 0) {
86 global $dolibarr_main_prod;
87 $ssl_verifypeer = ($dolibarr_main_prod ? true : false);
88 }
89 if (getDolGlobalString('MAIN_CURL_DISABLE_VERIFYPEER')) {
90 $ssl_verifypeer = 0;
91 }
92
93 // Turning off the server and peer verification(TrustManager Concept).
94 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, ($ssl_verifypeer ? true : false));
95 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, ($ssl_verifypeer ? true : false));
96
97 // Restrict use to some protocols only
98 $protocols = 0;
99 $redir_list = array();
100 if (is_array($allowedschemes)) {
101 foreach ($allowedschemes as $allowedscheme) {
102 if ($allowedscheme == 'http') {
103 $protocols |= CURLPROTO_HTTP;
104 $redir_list["HTTP"] = 1;
105 } elseif ($allowedscheme == 'https') {
106 $protocols |= CURLPROTO_HTTPS;
107 $redir_list["HTTPS"] = 1;
108 } elseif ($allowedscheme == 'ftp') {
109 $protocols |= CURLPROTO_FTP;
110 $redir_list["FTP"] = 1;
111 } elseif ($allowedscheme == 'ftps') {
112 $protocols |= CURLPROTO_FTPS;
113 $redir_list["FTPS"] = 1;
114 }
115 }
116 }
117
118 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, getDolGlobalInt('MAIN_USE_CONNECT_TIMEOUT', 5));
119 curl_setopt($ch, CURLOPT_TIMEOUT, getDolGlobalInt('MAIN_USE_RESPONSE_TIMEOUT', 30));
120
121 // limit size of downloaded files.
122 $maxsize = getDolGlobalInt('MAIN_SECURITY_MAXFILESIZE_DOWNLOADED');
123 if ($maxsize && defined('CURLOPT_MAXFILESIZE_LARGE')) {
124 curl_setopt($ch, CURLOPT_MAXFILESIZE_LARGE, $maxsize); // @phan-suppress-current-line PhanTypeMismatchArgumentNullableInternal
125 }
126 if ($maxsize && defined('CURLOPT_MAXFILESIZE')) {
127 curl_setopt($ch, CURLOPT_MAXFILESIZE, $maxsize);
128 }
129
130 //curl_setopt($ch, CURLOPT_SAFE_UPLOAD, true); // PHP 5.5
131 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // We want response
132 if ($postorget == 'POST') {
133 curl_setopt($ch, CURLOPT_POST, 1); // POST
134 curl_setopt($ch, CURLOPT_POSTFIELDS, $param); // Setting param x=a&y=z as POST fields
135 } elseif ($postorget == 'POSTALREADYFORMATED') {
136 curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST'); // HTTP request is 'POST' but param string is taken as it is
137 curl_setopt($ch, CURLOPT_POSTFIELDS, $param); // param = content of post, like a xml string
138 } elseif ($postorget == 'PUT') {
139 $array_param = null;
140 curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT'); // HTTP request is 'PUT'
141 if (!is_array($param)) {
142 parse_str($param, $array_param); // @phan-suppress-current-line PhanPluginConstantVariableNull
143 } else {
144 dol_syslog("parameter param must be a string", LOG_WARNING);
145 $array_param = $param;
146 }
147 curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($array_param)); // Setting param x=a&y=z as PUT fields
148 } elseif ($postorget == 'PUTALREADYFORMATED') {
149 curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT'); // HTTP request is 'PUT'
150 curl_setopt($ch, CURLOPT_POSTFIELDS, $param); // param = content of post, like a xml string
151 } elseif ($postorget == 'PATCH') {
152 $array_param = null;
153 curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PATCH'); // RFC 5789
154 if (!is_array($param)) {
155 parse_str($param, $array_param); // @phan-suppress-current-line PhanPluginConstantVariableNull
156 } else {
157 dol_syslog("parameter param must be a string", LOG_WARNING);
158 $array_param = $param;
159 }
160 curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($array_param));
161 } elseif ($postorget == 'PATCHALREADYFORMATED') {
162 curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PATCH'); // RFC 5789
163 curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
164 } elseif ($postorget == 'HEAD') {
165 curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'HEAD'); // HTTP request is 'HEAD'
166 curl_setopt($ch, CURLOPT_NOBODY, true);
167 } elseif ($postorget == 'DELETE') {
168 curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE'); // POST
169 } else {
170 curl_setopt($ch, CURLOPT_POST, 0); // GET
171 }
172
173 //if USE_PROXY constant set at begin of this method.
174 if ($USE_PROXY) {
175 dol_syslog("getURLContent set proxy to ".$PROXY_HOST.":".$PROXY_PORT." - ".$PROXY_USER.":".$PROXY_PASS);
176 //curl_setopt ($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP); // Curl 7.10
177 curl_setopt($ch, CURLOPT_PROXY, $PROXY_HOST.":".$PROXY_PORT);
178 if ($PROXY_USER) {
179 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $PROXY_USER.":".$PROXY_PASS);
180 }
181 }
182
183 $newUrl = $url;
184 $maxRedirection = 5;
185 $info = array();
186 $response = '';
187
188 do {
189 if ($maxRedirection < 1) {
190 break;
191 }
192
193 curl_setopt($ch, CURLOPT_URL, $newUrl);
194
195 // Parse $newUrl
196 $newUrlArray = parse_url($newUrl);
197 $hosttocheck = $newUrlArray['host'];
198 $hosttocheck = str_replace(array('[', ']'), '', $hosttocheck); // Remove brackets of IPv6
199
200 // Deny some reserved host names
201 if (in_array($hosttocheck, array('metadata.google.internal'))) {
202 $info['http_code'] = 400;
203 $info['content'] = 'Error bad hostname '.$hosttocheck.' (Used by Google metadata). This value for hostname is not allowed.';
204 break;
205 }
206
207 // Clean host name $hosttocheck to convert it into an IP $iptocheck
208 if (in_array($hosttocheck, array('localhost', 'localhost.domain'))) {
209 $iptocheck = '127.0.0.1';
210 } elseif (in_array($hosttocheck, array('ip6-localhost', 'ip6-loopback'))) {
211 $iptocheck = '::1';
212 } else {
213 // Resolve $hosttocheck to get the IP $iptocheck
214 if (function_exists('gethostbyname')) {
215 $iptocheck = gethostbyname($hosttocheck);
216 } else {
217 $iptocheck = $hosttocheck;
218 }
219 // TODO Resolve ip v6
220 }
221
222 // Check $iptocheck is an IP (v4 or v6), if not clear value.
223 if (!filter_var($iptocheck, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_IPV6)) { // This is not an IP, we clean data
224 $iptocheck = '0'; //
225 }
226
227 if ($iptocheck) {
228 $tmpresult = isIPAllowed($iptocheck, $localurl);
229 if ($tmpresult) {
230 $info['http_code'] = 400;
231 $info['content'] = $tmpresult;
232 break;
233 }
234 }
235
236 if ($iptocheck) {
237 // Set CURLOPT_CONNECT_TO so curl will not try another resolution that may give a different result. Possible only on PHP v7+
238 if (defined('CURLOPT_CONNECT_TO')) {
239 $connect_to = array(sprintf("%s:%d:%s:%d", $newUrlArray['host'], empty($newUrlArray['port']) ? '' : $newUrlArray['port'], $iptocheck, empty($newUrlArray['port']) ? '' : $newUrlArray['port']));
240 //var_dump($newUrlArray);
241 //var_dump($connect_to);
242 curl_setopt($ch, CURLOPT_CONNECT_TO, $connect_to);
243 }
244 }
245
246 // Moving these just before the curl_exec option really limits
247 // on windows PHP 7.4.
248 curl_setopt($ch, CURLOPT_PROTOCOLS, $protocols);
249 curl_setopt($ch, CURLOPT_REDIR_PROTOCOLS, $protocols);
250 /* CURLOPT_REDIR_PROTOCOLS_STR available from PHP 7.85.0
251 if (version_compare(PHP_VERSION, '8.3.0', '>=') && version_compare(curl_version()['version'], '7.85.0', '>=')) {
252 curl_setopt($ch, CURLOPT_REDIR_PROTOCOLS_STR, implode(",", array_keys($redir_list)));
253 }
254 */
255
256 // Getting response from server
257 $response = curl_exec($ch);
258
259 $info = curl_getinfo($ch); // Reading of request must be done after sending request
260 $http_code = $info['http_code'];
261
262 if ($followlocation && ($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307)) {
263 $newUrl = $info['redirect_url'];
264 $maxRedirection--;
265 // TODO Use $info['local_ip'] and $info['primary_ip'] ?
266 continue;
267 }
268
269 $http_code = 0;
270 } while ($http_code);
271
272 $request = curl_getinfo($ch, CURLINFO_HEADER_OUT); // Reading of request must be done after sending request
273
274 dol_syslog("getURLContent request=".$request);
275 if (getDolGlobalInt('MAIN_CURL_DEBUG')) {
276 // This may contains binary data, so we don't output response by default.
277 dol_syslog("getURLContent request=".$request, LOG_DEBUG, 0, '_curl');
278 dol_syslog("getURLContent response =".$response, LOG_DEBUG, 0, '_curl');
279 }
280 dol_syslog("getURLContent response size=".strlen($response)); // This may contains binary data, so we don't output it
281
282 $rep = array();
283 if (curl_errno($ch)) {
284 // Add keys to $rep
285 $rep['content'] = $response;
286
287 // moving to display page to display curl errors
288 $rep['curl_error_no'] = curl_errno($ch);
289 $rep['curl_error_msg'] = curl_error($ch);
290
291 dol_syslog("getURLContent response array is ".implode(',', $rep));
292 } else {
293 //$info = curl_getinfo($ch);
294
295 // Add keys to $rep
296 $rep = $info;
297 //$rep['header_size']=$info['header_size'];
298 //$rep['http_code']=$info['http_code'];
299 dol_syslog("getURLContent http_code=".$rep['http_code']);
300
301 // Add more keys to $rep
302 if ($response) {
303 $rep['content'] = $response;
304 }
305 $rep['curl_error_no'] = '';
306 $rep['curl_error_msg'] = '';
307 }
308
309 //closing the curl
310 curl_close($ch);
311
312 return $rep;
313}
314
322function isIPAllowed($iptocheck, $localurl)
323{
324 if ($localurl == 0) { // Only external url allowed (dangerous, may allow to get malware)
325 if (!filter_var($iptocheck, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
326 // Deny ips like 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, 0.0.0.0/8, 169.254.0.0/16, 127.0.0.0/8 et 240.0.0.0/4, ::1/128, ::/128, ::ffff:0:0/96, fe80::/10...
327 $errormsg = 'Error bad hostname IP (private or reserved range). Must be an external URL.';
328 return $errormsg;
329 }
330 if (!empty($_SERVER["SERVER_ADDR"]) && $iptocheck == $_SERVER["SERVER_ADDR"]) {
331 $errormsg = 'Error bad hostname IP (IP is a local IP). Must be an external URL.';
332 return $errormsg;
333 }
334 if (getDolGlobalString('MAIN_SECURITY_ANTI_SSRF_SERVER_IP') && in_array($iptocheck, explode(',', getDolGlobalString('MAIN_SECURITY_ANTI_SSRF_SERVER_IP')))) {
335 $errormsg = 'Error bad hostname IP (IP is a local IP defined into MAIN_SECURITY_SERVER_IP). Must be an external URL.';
336 return $errormsg;
337 }
338 }
339 if ($localurl == 1) { // Only local url allowed (dangerous, may allow to get metadata on server or make internal port scanning)
340 // Deny ips NOT like 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, 0.0.0.0/8, 169.254.0.0/16, 127.0.0.0/8 et 240.0.0.0/4, ::1/128, ::/128, ::ffff:0:0/96, fe80::/10...
341 if (filter_var($iptocheck, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
342 $errormsg = 'Error bad hostname '.$iptocheck.'. Must be a local URL.';
343 return $errormsg;
344 }
345 if (getDolGlobalString('MAIN_SECURITY_ANTI_SSRF_SERVER_IP') && !in_array($iptocheck, explode(',', getDolGlobalString('MAIN_SECURITY_ANTI_SSRF_SERVER_IP')))) {
346 $errormsg = 'Error bad hostname IP (IP is not a local IP defined into list MAIN_SECURITY_SERVER_IP). Must be a local URL in allowed list.';
347 return $errormsg;
348 }
349 }
350
351 // Common check on ip (local and external)
352 // See list on https://tagmerge.com/gist/a7b9d57ff8ec11d63642f8778609a0b8
353 // Not evasive url that ar enot IP are excluded by test on IP v4/v6 validity.
354 $arrayofmetadataserver = array(
355 '100.100.100.200' => 'Alibaba',
356 '192.0.0.192' => 'Oracle',
357 '192.80.8.124' => 'Packet',
358 '100.88.222.5' => 'Tencent cloud',
359 );
360 foreach ($arrayofmetadataserver as $ipofmetadataserver => $nameofmetadataserver) {
361 if ($iptocheck == $ipofmetadataserver) {
362 $errormsg = 'Error bad hostname IP (Used by '.$nameofmetadataserver.' metadata server). This IP is forbidden.';
363 return $errormsg;
364 }
365 }
366
367 return '';
368}
369
378function getDomainFromURL($url, $mode = 0)
379{
380 $arrayof2levetopdomain = array(
381 'co.at', 'or.at', 'gv.at',
382 'avocat.fr', 'aeroport.fr', 'veterinaire.fr',
383 'com.ng', 'gov.ng', 'gov.ua', 'com.ua', 'in.ua', 'org.ua', 'edu.ua', 'net.ua',
384 'net.uk', 'org.uk', 'gov.uk', 'co.uk',
385 'com.mx'
386 );
387
388 // Set if tld is on 2 levels
389 $tldon2level = 0;
390 $parts = array_reverse(explode('.', $url));
391 if (!empty($parts[1]) && in_array($parts[1].'.'.$parts[0], $arrayof2levetopdomain)) {
392 $tldon2level = 1;
393 }
394
395 if ($tldon2level && $mode > 0) {
396 $mode++;
397 }
398
399 $tmpdomain = preg_replace('/^https?:\/\//i', '', $url); // Remove http(s)://
400 $tmpdomain = preg_replace('/\/.*$/i', '', $tmpdomain); // Remove part after /
401 if ($mode == 3) {
402 $tmpdomain = preg_replace('/^.*\.([^\.]+)\.([^\.]+)\.([^\.]+)\.([^\.]+)$/', '\1.\2.\3.\4', $tmpdomain);
403 } elseif ($mode == 2) {
404 $tmpdomain = preg_replace('/^.*\.([^\.]+)\.([^\.]+)\.([^\.]+)$/', '\1.\2.\3', $tmpdomain); // Remove part 'www.' before 'abc.mydomain.com'
405 } elseif ($mode == 1) {
406 $tmpdomain = preg_replace('/^.*\.([^\.]+)\.([^\.]+)$/', '\1.\2', $tmpdomain); // Remove part 'www.abc.' before 'mydomain.com'
407 }
408
409 if (empty($mode)) {
410 if ($tldon2level) {
411 $tmpdomain = preg_replace('/^.*\.([^\.]+)\.([^\.]+)\.([^\.]+)$/', '\1.\2.\3', $tmpdomain); // Remove part 'www.abc.' before 'mydomain.com'
412 $tmpdomain = preg_replace('/\.[^\.]+\.[^\.]+$/', '', $tmpdomain); // Remove TLD (.com.mx, .co.uk, ...)
413 } else {
414 $tmpdomain = preg_replace('/^.*\.([^\.]+)\.([^\.]+)$/', '\1.\2', $tmpdomain); // Remove part 'www.abc.' before 'mydomain.com'
415 $tmpdomain = preg_replace('/\.[^\.]+$/', '', $tmpdomain); // Remove TLD (.com, .net, ...)
416 }
417 }
418
419 return $tmpdomain;
420}
421
431function getRootURLFromURL($url)
432{
433 return preg_replace('/^([a-z]*:\/\/[^\/]*).*/i', '$1', $url);
434}
435
442function removeHtmlComment($content)
443{
444 $content = preg_replace('/<!--[^\-]+-->/', '', $content);
445 return $content;
446}
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
getDomainFromURL($url, $mode=0)
Function get second level domain name.
isIPAllowed($iptocheck, $localurl)
Is IP allowed.
getRootURLFromURL($url)
Function root url from a long url For example: https://www.abc.mydomain.com/dir/page....
getURLContent($url, $postorget='GET', $param='', $followlocation=1, $addheaders=array(), $allowedschemes=array('http', 'https'), $localurl=0, $ssl_verifypeer=-1)
Function to get a content from an URL (use proxy if proxy defined).
removeHtmlComment($content)
Function to remove comments into HTML content.
global $conf
The following vars must be defined: $type2label $form $conf, $lang, The following vars may also be de...
Definition member.php:79