From 1f2fbac2075a3cb9bc3c8613d2f8b18bd7bf6582 Mon Sep 17 00:00:00 2001 From: Dave Cooper Date: Thu, 28 May 2015 15:54:31 +0800 Subject: [PATCH] MDL-49497 curl: Allow configurable User-Agent. Thanks to Kartik Yadav for assistance with this patch. --- lib/filelib.php | 32 +++++++++++++++++++++++++++----- 1 file changed, 27 insertions(+), 5 deletions(-) diff --git a/lib/filelib.php b/lib/filelib.php index b893cf22f98..69d8da0e18d 100644 --- a/lib/filelib.php +++ b/lib/filelib.php @@ -2683,7 +2683,8 @@ class curl { public $emulateredirects = null; /** @var array cURL options */ - private $options; + protected $options; + /** @var string Proxy host */ private $proxy_host = ''; /** @var string Proxy auth */ @@ -2975,7 +2976,7 @@ class curl { * @param array $options * @return resource The curl handle */ - private function apply_opt($curl, $options) { + protected function apply_opt($curl, $options) { // Clean up $this->cleanopt(); // set cookie @@ -3004,15 +3005,36 @@ class curl { } $this->setopt($options); - // reset before set options + + // Reset before set options. curl_setopt($curl, CURLOPT_HEADERFUNCTION, array(&$this,'formatHeader')); - // set headers + + // Setting the User-Agent based on options provided. + $useragent = ''; + + if (!empty($options['CURLOPT_USERAGENT'])) { + $useragent = $options['CURLOPT_USERAGENT']; + } else if (!empty($this->options['CURLOPT_USERAGENT'])) { + $useragent = $this->options['CURLOPT_USERAGENT']; + } else { + $useragent = 'MoodleBot/1.0'; + } + + // Set headers. if (empty($this->header)) { $this->setHeader(array( - 'User-Agent: MoodleBot/1.0', + 'User-Agent: ' . $useragent, 'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7', 'Connection: keep-alive' )); + } else if (!in_array('User-Agent: ' . $useragent, $this->header)) { + // Remove old User-Agent if one existed. + // We have to partial search since we don't know what the original User-Agent is. + if ($match = preg_grep('/User-Agent.*/', $this->header)) { + $key = array_keys($match)[0]; + unset($this->header[$key]); + } + $this->setHeader(array('User-Agent: ' . $useragent)); } curl_setopt($curl, CURLOPT_HTTPHEADER, $this->header);