dolibarr 21.0.3
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 == 'HEAD') {
152 curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'HEAD'); // HTTP request is 'HEAD'
153 curl_setopt($ch, CURLOPT_NOBODY, true);
154 } elseif ($postorget == 'DELETE') {
155 curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE'); // POST
156 } else {
157 curl_setopt($ch, CURLOPT_POST, 0); // GET
158 }
159
160 //if USE_PROXY constant set at begin of this method.
161 if ($USE_PROXY) {
162 dol_syslog("getURLContent set proxy to ".$PROXY_HOST.":".$PROXY_PORT." - ".$PROXY_USER.":".$PROXY_PASS);
163 //curl_setopt ($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP); // Curl 7.10
164 curl_setopt($ch, CURLOPT_PROXY, $PROXY_HOST.":".$PROXY_PORT);
165 if ($PROXY_USER) {
166 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $PROXY_USER.":".$PROXY_PASS);
167 }
168 }
169
170 $newUrl = $url;
171 $maxRedirection = 5;
172 $info = array();
173 $response = '';
174
175 do {
176 if ($maxRedirection < 1) {
177 break;
178 }
179
180 curl_setopt($ch, CURLOPT_URL, $newUrl);
181
182 // Parse $newUrl
183 $newUrlArray = parse_url($newUrl);
184 $hosttocheck = $newUrlArray['host'];
185 $hosttocheck = str_replace(array('[', ']'), '', $hosttocheck); // Remove brackets of IPv6
186
187 // Deny some reserved host names
188 if (in_array($hosttocheck, array('metadata.google.internal'))) {
189 $info['http_code'] = 400;
190 $info['content'] = 'Error bad hostname '.$hosttocheck.' (Used by Google metadata). This value for hostname is not allowed.';
191 break;
192 }
193
194 // Clean host name $hosttocheck to convert it into an IP $iptocheck
195 if (in_array($hosttocheck, array('localhost', 'localhost.domain'))) {
196 $iptocheck = '127.0.0.1';
197 } elseif (in_array($hosttocheck, array('ip6-localhost', 'ip6-loopback'))) {
198 $iptocheck = '::1';
199 } else {
200 // Resolve $hosttocheck to get the IP $iptocheck
201 if (function_exists('gethostbyname')) {
202 $iptocheck = gethostbyname($hosttocheck);
203 } else {
204 $iptocheck = $hosttocheck;
205 }
206 // TODO Resolve ip v6
207 }
208
209 // Check $iptocheck is an IP (v4 or v6), if not clear value.
210 if (!filter_var($iptocheck, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_IPV6)) { // This is not an IP, we clean data
211 $iptocheck = '0'; //
212 }
213
214 if ($iptocheck) {
215 $tmpresult = isIPAllowed($iptocheck, $localurl);
216 if ($tmpresult) {
217 $info['http_code'] = 400;
218 $info['content'] = $tmpresult;
219 break;
220 }
221 }
222
223 if ($iptocheck) {
224 // Set CURLOPT_CONNECT_TO so curl will not try another resolution that may give a different result. Possible only on PHP v7+
225 if (defined('CURLOPT_CONNECT_TO')) {
226 $connect_to = array(sprintf("%s:%d:%s:%d", $newUrlArray['host'], empty($newUrlArray['port']) ? '' : $newUrlArray['port'], $iptocheck, empty($newUrlArray['port']) ? '' : $newUrlArray['port']));
227 //var_dump($newUrlArray);
228 //var_dump($connect_to);
229 curl_setopt($ch, CURLOPT_CONNECT_TO, $connect_to);
230 }
231 }
232
233 // Moving these just before the curl_exec option really limits
234 // on windows PHP 7.4.
235 curl_setopt($ch, CURLOPT_PROTOCOLS, $protocols);
236 curl_setopt($ch, CURLOPT_REDIR_PROTOCOLS, $protocols);
237 /* CURLOPT_REDIR_PROTOCOLS_STR available from PHP 7.85.0
238 if (version_compare(PHP_VERSION, '8.3.0', '>=') && version_compare(curl_version()['version'], '7.85.0', '>=')) {
239 curl_setopt($ch, CURLOPT_REDIR_PROTOCOLS_STR, implode(",", array_keys($redir_list)));
240 }
241 */
242
243 // Getting response from server
244 $response = curl_exec($ch);
245
246 $info = curl_getinfo($ch); // Reading of request must be done after sending request
247 $http_code = $info['http_code'];
248
249 if ($followlocation && ($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307)) {
250 $newUrl = $info['redirect_url'];
251 $maxRedirection--;
252 // TODO Use $info['local_ip'] and $info['primary_ip'] ?
253 continue;
254 }
255
256 $http_code = 0;
257 } while ($http_code);
258
259 $request = curl_getinfo($ch, CURLINFO_HEADER_OUT); // Reading of request must be done after sending request
260
261 dol_syslog("getURLContent request=".$request);
262 if (getDolGlobalInt('MAIN_CURL_DEBUG')) {
263 // This may contains binary data, so we don't output response by default.
264 dol_syslog("getURLContent request=".$request, LOG_DEBUG, 0, '_curl');
265 dol_syslog("getURLContent response =".$response, LOG_DEBUG, 0, '_curl');
266 }
267 dol_syslog("getURLContent response size=".strlen($response)); // This may contains binary data, so we don't output it
268
269 $rep = array();
270 if (curl_errno($ch)) {
271 // Add keys to $rep
272 $rep['content'] = $response;
273
274 // moving to display page to display curl errors
275 $rep['curl_error_no'] = curl_errno($ch);
276 $rep['curl_error_msg'] = curl_error($ch);
277
278 dol_syslog("getURLContent response array is ".implode(',', $rep));
279 } else {
280 //$info = curl_getinfo($ch);
281
282 // Add keys to $rep
283 $rep = $info;
284 //$rep['header_size']=$info['header_size'];
285 //$rep['http_code']=$info['http_code'];
286 dol_syslog("getURLContent http_code=".$rep['http_code']);
287
288 // Add more keys to $rep
289 if ($response) {
290 $rep['content'] = $response;
291 }
292 $rep['curl_error_no'] = '';
293 $rep['curl_error_msg'] = '';
294 }
295
296 //closing the curl
297 curl_close($ch);
298
299 return $rep;
300}
301
309function isIPAllowed($iptocheck, $localurl)
310{
311 if ($localurl == 0) { // Only external url allowed (dangerous, may allow to get malware)
312 if (!filter_var($iptocheck, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
313 // 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...
314 $errormsg = 'Error bad hostname IP (private or reserved range). Must be an external URL.';
315 return $errormsg;
316 }
317 if (!empty($_SERVER["SERVER_ADDR"]) && $iptocheck == $_SERVER["SERVER_ADDR"]) {
318 $errormsg = 'Error bad hostname IP (IP is a local IP). Must be an external URL.';
319 return $errormsg;
320 }
321 if (getDolGlobalString('MAIN_SECURITY_ANTI_SSRF_SERVER_IP') && in_array($iptocheck, explode(',', getDolGlobalString('MAIN_SECURITY_ANTI_SSRF_SERVER_IP')))) {
322 $errormsg = 'Error bad hostname IP (IP is a local IP defined into MAIN_SECURITY_SERVER_IP). Must be an external URL.';
323 return $errormsg;
324 }
325 }
326 if ($localurl == 1) { // Only local url allowed (dangerous, may allow to get metadata on server or make internal port scanning)
327 // 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...
328 if (filter_var($iptocheck, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
329 $errormsg = 'Error bad hostname '.$iptocheck.'. Must be a local URL.';
330 return $errormsg;
331 }
332 if (getDolGlobalString('MAIN_SECURITY_ANTI_SSRF_SERVER_IP') && !in_array($iptocheck, explode(',', getDolGlobalString('MAIN_SECURITY_ANTI_SSRF_SERVER_IP')))) {
333 $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.';
334 return $errormsg;
335 }
336 }
337
338 // Common check on ip (local and external)
339 // See list on https://tagmerge.com/gist/a7b9d57ff8ec11d63642f8778609a0b8
340 // Not evasive url that ar enot IP are excluded by test on IP v4/v6 validity.
341 $arrayofmetadataserver = array(
342 '100.100.100.200' => 'Alibaba',
343 '192.0.0.192' => 'Oracle',
344 '192.80.8.124' => 'Packet',
345 '100.88.222.5' => 'Tencent cloud',
346 );
347 foreach ($arrayofmetadataserver as $ipofmetadataserver => $nameofmetadataserver) {
348 if ($iptocheck == $ipofmetadataserver) {
349 $errormsg = 'Error bad hostname IP (Used by '.$nameofmetadataserver.' metadata server). This IP is forbidden.';
350 return $errormsg;
351 }
352 }
353
354 return '';
355}
356
365function getDomainFromURL($url, $mode = 0)
366{
367 $arrayof2levetopdomain = array(
368 'co.at', 'or.at', 'gv.at',
369 'avocat.fr', 'aeroport.fr', 'veterinaire.fr',
370 'com.ng', 'gov.ng', 'gov.ua', 'com.ua', 'in.ua', 'org.ua', 'edu.ua', 'net.ua',
371 'net.uk', 'org.uk', 'gov.uk', 'co.uk',
372 'com.mx'
373 );
374
375 // Set if tld is on 2 levels
376 $tldon2level = 0;
377 $parts = array_reverse(explode('.', $url));
378 if (!empty($parts[1]) && in_array($parts[1].'.'.$parts[0], $arrayof2levetopdomain)) {
379 $tldon2level = 1;
380 }
381
382 if ($tldon2level && $mode > 0) {
383 $mode++;
384 }
385
386 $tmpdomain = preg_replace('/^https?:\/\//i', '', $url); // Remove http(s)://
387 $tmpdomain = preg_replace('/\/.*$/i', '', $tmpdomain); // Remove part after /
388 if ($mode == 3) {
389 $tmpdomain = preg_replace('/^.*\.([^\.]+)\.([^\.]+)\.([^\.]+)\.([^\.]+)$/', '\1.\2.\3.\4', $tmpdomain);
390 } elseif ($mode == 2) {
391 $tmpdomain = preg_replace('/^.*\.([^\.]+)\.([^\.]+)\.([^\.]+)$/', '\1.\2.\3', $tmpdomain); // Remove part 'www.' before 'abc.mydomain.com'
392 } elseif ($mode == 1) {
393 $tmpdomain = preg_replace('/^.*\.([^\.]+)\.([^\.]+)$/', '\1.\2', $tmpdomain); // Remove part 'www.abc.' before 'mydomain.com'
394 }
395
396 if (empty($mode)) {
397 if ($tldon2level) {
398 $tmpdomain = preg_replace('/^.*\.([^\.]+)\.([^\.]+)\.([^\.]+)$/', '\1.\2.\3', $tmpdomain); // Remove part 'www.abc.' before 'mydomain.com'
399 $tmpdomain = preg_replace('/\.[^\.]+\.[^\.]+$/', '', $tmpdomain); // Remove TLD (.com.mx, .co.uk, ...)
400 } else {
401 $tmpdomain = preg_replace('/^.*\.([^\.]+)\.([^\.]+)$/', '\1.\2', $tmpdomain); // Remove part 'www.abc.' before 'mydomain.com'
402 $tmpdomain = preg_replace('/\.[^\.]+$/', '', $tmpdomain); // Remove TLD (.com, .net, ...)
403 }
404 }
405
406 return $tmpdomain;
407}
408
418function getRootURLFromURL($url)
419{
420 return preg_replace('/^([a-z]*:\/\/[^\/]*).*/i', '$1', $url);
421}
422
429function removeHtmlComment($content)
430{
431 $content = preg_replace('/<!--[^\-]+-->/', '', $content);
432 return $content;
433}
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