/**
  * Calls the pluginfo.php service and returns the raw response
  *
  * @param string $component
  * @param string $version
  * @return string
  */
 protected function call_service($component, $version)
 {
     global $CFG;
     require_once $CFG->libdir . '/filelib.php';
     $curl = new curl(array('proxy' => true));
     $response = $curl->get($this->service_request_url(), $this->service_request_params($component, $version), $this->service_request_options());
     $curlerrno = $curl->get_errno();
     $curlinfo = $curl->get_info();
     if (!empty($curlerrno)) {
         throw new tool_installaddon_pluginfo_exception('err_curl_exec', array('url' => $curlinfo['url'], 'errno' => $curlerrno, 'error' => $curl->error));
     } else {
         if ($curlinfo['http_code'] != 200) {
             throw new tool_installaddon_pluginfo_exception('err_curl_http_code', array('url' => $curlinfo['url'], 'http_code' => $curlinfo['http_code']));
         } else {
             if (isset($curlinfo['ssl_verify_result']) and $curlinfo['ssl_verify_result'] != 0) {
                 throw new tool_installaddon_pluginfo_exception('err_curl_ssl_verify', array('url' => $curlinfo['url'], 'ssl_verify_result' => $curlinfo['ssl_verify_result']));
             }
         }
     }
     return $response;
 }
 /**
  * Checks if the mdeploy.php will be able to fetch the ZIP from the given URL
  *
  * This is mainly supposed to check if the transmission over HTTPS would
  * work. That is, if the CA certificates are present at the server.
  *
  * @param string $downloadurl the URL of the ZIP package to download
  * @return bool
  */
 protected function update_downloadable($downloadurl)
 {
     global $CFG;
     $curloptions = array('CURLOPT_SSL_VERIFYHOST' => 2, 'CURLOPT_SSL_VERIFYPEER' => true);
     $curl = new curl(array('proxy' => true));
     $result = $curl->head($downloadurl, $curloptions);
     $errno = $curl->get_errno();
     if (empty($errno)) {
         return true;
     } else {
         return false;
     }
 }
Beispiel #3
0
/**
 * Fetches content of file from Internet (using proxy if defined). Uses cURL extension if present.
 * Due to security concerns only downloads from http(s) sources are supported.
 *
 * @category files
 * @param string $url file url starting with http(s)://
 * @param array $headers http headers, null if none. If set, should be an
 *   associative array of header name => value pairs.
 * @param array $postdata array means use POST request with given parameters
 * @param bool $fullresponse return headers, responses, etc in a similar way snoopy does
 *   (if false, just returns content)
 * @param int $timeout timeout for complete download process including all file transfer
 *   (default 5 minutes)
 * @param int $connecttimeout timeout for connection to server; this is the timeout that
 *   usually happens if the remote server is completely down (default 20 seconds);
 *   may not work when using proxy
 * @param bool $skipcertverify If true, the peer's SSL certificate will not be checked.
 *   Only use this when already in a trusted location.
 * @param string $tofile store the downloaded content to file instead of returning it.
 * @param bool $calctimeout false by default, true enables an extra head request to try and determine
 *   filesize and appropriately larger timeout based on $CFG->curltimeoutkbitrate
 * @return stdClass|string|bool stdClass object if $fullresponse is true, false if request failed, true
 *   if file downloaded into $tofile successfully or the file content as a string.
 */
function download_file_content($url, $headers = null, $postdata = null, $fullresponse = false, $timeout = 300, $connecttimeout = 20, $skipcertverify = false, $tofile = NULL, $calctimeout = false)
{
    global $CFG;
    // Only http and https links supported.
    if (!preg_match('|^https?://|i', $url)) {
        if ($fullresponse) {
            $response = new stdClass();
            $response->status = 0;
            $response->headers = array();
            $response->response_code = 'Invalid protocol specified in url';
            $response->results = '';
            $response->error = 'Invalid protocol specified in url';
            return $response;
        } else {
            return false;
        }
    }
    $options = array();
    $headers2 = array();
    if (is_array($headers)) {
        foreach ($headers as $key => $value) {
            if (is_numeric($key)) {
                $headers2[] = $value;
            } else {
                $headers2[] = "{$key}: {$value}";
            }
        }
    }
    if ($skipcertverify) {
        $options['CURLOPT_SSL_VERIFYPEER'] = false;
    } else {
        $options['CURLOPT_SSL_VERIFYPEER'] = true;
    }
    $options['CURLOPT_CONNECTTIMEOUT'] = $connecttimeout;
    $options['CURLOPT_FOLLOWLOCATION'] = 1;
    $options['CURLOPT_MAXREDIRS'] = 5;
    // Use POST if requested.
    if (is_array($postdata)) {
        $postdata = format_postdata_for_curlcall($postdata);
    } else {
        if (empty($postdata)) {
            $postdata = null;
        }
    }
    // Optionally attempt to get more correct timeout by fetching the file size.
    if (!isset($CFG->curltimeoutkbitrate)) {
        // Use very slow rate of 56kbps as a timeout speed when not set.
        $bitrate = 56;
    } else {
        $bitrate = $CFG->curltimeoutkbitrate;
    }
    if ($calctimeout and !isset($postdata)) {
        $curl = new curl();
        $curl->setHeader($headers2);
        $curl->head($url, $postdata, $options);
        $info = $curl->get_info();
        $error_no = $curl->get_errno();
        if (!$error_no && $info['download_content_length'] > 0) {
            // No curl errors - adjust for large files only - take max timeout.
            $timeout = max($timeout, ceil($info['download_content_length'] * 8 / ($bitrate * 1024)));
        }
    }
    $curl = new curl();
    $curl->setHeader($headers2);
    $options['CURLOPT_RETURNTRANSFER'] = true;
    $options['CURLOPT_NOBODY'] = false;
    $options['CURLOPT_TIMEOUT'] = $timeout;
    if ($tofile) {
        $fh = fopen($tofile, 'w');
        if (!$fh) {
            if ($fullresponse) {
                $response = new stdClass();
                $response->status = 0;
                $response->headers = array();
                $response->response_code = 'Can not write to file';
                $response->results = false;
                $response->error = 'Can not write to file';
                return $response;
            } else {
                return false;
            }
        }
        $options['CURLOPT_FILE'] = $fh;
    }
    if (isset($postdata)) {
        $content = $curl->post($url, $postdata, $options);
    } else {
        $content = $curl->get($url, null, $options);
    }
    if ($tofile) {
        fclose($fh);
        @chmod($tofile, $CFG->filepermissions);
    }
    /*
        // Try to detect encoding problems.
        if ((curl_errno($ch) == 23 or curl_errno($ch) == 61) and defined('CURLOPT_ENCODING')) {
            curl_setopt($ch, CURLOPT_ENCODING, 'none');
            $result = curl_exec($ch);
        }
    */
    $info = $curl->get_info();
    $error_no = $curl->get_errno();
    $rawheaders = $curl->get_raw_response();
    if ($error_no) {
        $error = $content;
        if (!$fullresponse) {
            debugging("cURL request for \"{$url}\" failed with: {$error} ({$error_no})", DEBUG_ALL);
            return false;
        }
        $response = new stdClass();
        if ($error_no == 28) {
            $response->status = '-100';
            // Mimic snoopy.
        } else {
            $response->status = '0';
        }
        $response->headers = array();
        $response->response_code = $error;
        $response->results = false;
        $response->error = $error;
        return $response;
    }
    if ($tofile) {
        $content = true;
    }
    if (empty($info['http_code'])) {
        // For security reasons we support only true http connections (Location: file:// exploit prevention).
        $response = new stdClass();
        $response->status = '0';
        $response->headers = array();
        $response->response_code = 'Unknown cURL error';
        $response->results = false;
        // do NOT change this, we really want to ignore the result!
        $response->error = 'Unknown cURL error';
    } else {
        $response = new stdClass();
        $response->status = (string) $info['http_code'];
        $response->headers = $rawheaders;
        $response->results = $content;
        $response->error = '';
        // There might be multiple headers on redirect, find the status of the last one.
        $firstline = true;
        foreach ($rawheaders as $line) {
            if ($firstline) {
                $response->response_code = $line;
                $firstline = false;
            }
            if (trim($line, "\r\n") === '') {
                $firstline = true;
            }
        }
    }
    if ($fullresponse) {
        return $response;
    }
    if ($info['http_code'] != 200) {
        debugging("cURL request for \"{$url}\" failed, HTTP response code: " . $response->response_code, DEBUG_ALL);
        return false;
    }
    return $response->results;
}
Beispiel #4
0
 /**
  * Test curl agent settings.
  */
 public function test_curl_useragent()
 {
     $curl = new testable_curl();
     $options = $curl->get_options();
     $this->assertNotEmpty($options);
     $curl->call_apply_opt($options);
     $this->assertTrue(in_array('User-Agent: MoodleBot/1.0', $curl->header));
     $this->assertFalse(in_array('User-Agent: Test/1.0', $curl->header));
     $options['CURLOPT_USERAGENT'] = 'Test/1.0';
     $curl->call_apply_opt($options);
     $this->assertTrue(in_array('User-Agent: Test/1.0', $curl->header));
     $this->assertFalse(in_array('User-Agent: MoodleBot/1.0', $curl->header));
     $curl->set_option('CURLOPT_USERAGENT', 'AnotherUserAgent/1.0');
     $curl->call_apply_opt();
     $this->assertTrue(in_array('User-Agent: AnotherUserAgent/1.0', $curl->header));
     $this->assertFalse(in_array('User-Agent: Test/1.0', $curl->header));
     $curl->set_option('CURLOPT_USERAGENT', 'AnotherUserAgent/1.1');
     $options = $curl->get_options();
     $curl->call_apply_opt($options);
     $this->assertTrue(in_array('User-Agent: AnotherUserAgent/1.1', $curl->header));
     $this->assertFalse(in_array('User-Agent: AnotherUserAgent/1.0', $curl->header));
     $curl->unset_option('CURLOPT_USERAGENT');
     $curl->call_apply_opt();
     $this->assertTrue(in_array('User-Agent: MoodleBot/1.0', $curl->header));
     // Finally, test it via exttests, to ensure the agent is sent properly.
     // Matching.
     $testurl = $this->getExternalTestFileUrl('/test_agent.php');
     $extcurl = new curl();
     $contents = $extcurl->get($testurl, array(), array('CURLOPT_USERAGENT' => 'AnotherUserAgent/1.2'));
     $response = $extcurl->getResponse();
     $this->assertSame('200 OK', reset($response));
     $this->assertSame(0, $extcurl->get_errno());
     $this->assertSame('OK', $contents);
     // Not matching.
     $contents = $extcurl->get($testurl, array(), array('CURLOPT_USERAGENT' => 'NonMatchingUserAgent/1.2'));
     $response = $extcurl->getResponse();
     $this->assertSame('200 OK', reset($response));
     $this->assertSame(0, $extcurl->get_errno());
     $this->assertSame('', $contents);
 }
Beispiel #5
0
 /**
  * Makes cURL request to get data from the remote site
  *
  * @return string raw request result
  * @throws checker_exception
  */
 protected function get_response()
 {
     global $CFG;
     require_once $CFG->libdir . '/filelib.php';
     $curl = new \curl(array('proxy' => true));
     $response = $curl->post($this->prepare_request_url(), $this->prepare_request_params(), $this->prepare_request_options());
     $curlerrno = $curl->get_errno();
     if (!empty($curlerrno)) {
         throw new checker_exception('err_response_curl', 'cURL error ' . $curlerrno . ': ' . $curl->error);
     }
     $curlinfo = $curl->get_info();
     if ($curlinfo['http_code'] != 200) {
         throw new checker_exception('err_response_http_code', $curlinfo['http_code']);
     }
     return $response;
 }
Beispiel #6
0
 /**
  * Checks if the mdeploy.php will be able to fetch the ZIP from the given URL
  *
  * This is mainly supposed to check if the transmission over HTTPS would
  * work. That is, if the CA certificates are present at the server.
  *
  * @param string $downloadurl the URL of the ZIP package to download
  * @return bool
  */
 protected function update_downloadable($downloadurl)
 {
     global $CFG;
     $curloptions = array('CURLOPT_SSL_VERIFYHOST' => 2, 'CURLOPT_SSL_VERIFYPEER' => true);
     $cacertfile = $CFG->dataroot . '/moodleorgca.crt';
     if (is_readable($cacertfile)) {
         // Do not use CA certs provided by the operating system. Instead,
         // use this CA cert to verify the updates provider.
         $curloptions['CURLOPT_CAINFO'] = $cacertfile;
     }
     $curl = new curl(array('proxy' => true));
     $result = $curl->head($downloadurl, $curloptions);
     $errno = $curl->get_errno();
     if (empty($errno)) {
         return true;
     } else {
         return false;
     }
 }
Beispiel #7
0
 /**
  * Download the given file into the given destination.
  *
  * This is basically a simplified version of {@link download_file_content()} from
  * Moodle itself, tuned for fetching files from moodle.org servers. Same code is used
  * in mdeploy.php for fetching available updates.
  *
  * @param string $source file url starting with http(s)://
  * @param string $target store the downloaded content to this file (full path)
  * @throws tool_installaddon_installer_exception
  */
 public function download_file($source, $target)
 {
     global $CFG;
     require_once $CFG->libdir . '/filelib.php';
     $targetfile = fopen($target, 'w');
     if (!$targetfile) {
         throw new tool_installaddon_installer_exception('err_download_write_file', $target);
     }
     $options = array('file' => $targetfile, 'timeout' => 300, 'followlocation' => true, 'maxredirs' => 3, 'ssl_verifypeer' => true, 'ssl_verifyhost' => 2);
     $curl = new curl(array('proxy' => true));
     $result = $curl->download_one($source, null, $options);
     $curlinfo = $curl->get_info();
     fclose($targetfile);
     if ($result !== true) {
         throw new tool_installaddon_installer_exception('err_curl_exec', array('url' => $source, 'errorno' => $curl->get_errno(), 'error' => $result));
     } else {
         if (empty($curlinfo['http_code']) or $curlinfo['http_code'] != 200) {
             throw new tool_installaddon_installer_exception('err_curl_http_code', array('url' => $source, 'http_code' => $curlinfo['http_code']));
         } else {
             if (isset($curlinfo['ssl_verify_result']) and $curlinfo['ssl_verify_result'] != 0) {
                 throw new tool_installaddon_installer_exception('err_curl_ssl_verify', array('url' => $source, 'ssl_verify_result' => $curlinfo['ssl_verify_result']));
             }
         }
     }
 }
Beispiel #8
0
    /**
     * Returns information about file in this repository by reference
     *
     * If the file is an image we download the contents and save it in our filesystem
     * so we can generate thumbnails. Otherwise we just request the file size.
     * Returns null if file not found or can not be accessed
     *
     * @param stdClass $reference file reference db record
     * @return stdClass|null contains one of the following:
     *   - 'filesize' (for non-image files or files we failed to retrieve fully because of timeout)
     *   - 'filepath' (for image files that we retrieived and saved)
     */
    public function get_file_by_reference($reference) {
        global $USER;
        $ref = @unserialize(base64_decode($reference->reference));
        if (!isset($ref->url) || !($url = $this->appendtoken($ref->url))) {
            // Occurs when the user isn't known..
            return null;
        }

        $return = null;
        $cookiepathname = $this->prepare_file($USER->id. '_'. uniqid('', true). '.cookie');
        $c = new curl(array('cookie' => $cookiepathname));
        if (file_extension_in_typegroup($ref->filename, 'web_image')) {
            $path = $this->prepare_file('');
            $result = $c->download_one($url, null, array('filepath' => $path, 'followlocation' => true, 'timeout' => self::SYNCIMAGE_TIMEOUT));
            if ($result === true) {
                $return = (object)array('filepath' => $path);
            }
        } else {
            $result = $c->head($url, array('followlocation' => true, 'timeout' => self::SYNCFILE_TIMEOUT));
        }
        // Delete cookie jar.
        if (file_exists($cookiepathname)) {
            unlink($cookiepathname);
        }

        $this->connection_result($c->get_errno());
        $curlinfo = $c->get_info();
        if ($return === null && isset($curlinfo['http_code']) && $curlinfo['http_code'] == 200
                && array_key_exists('download_content_length', $curlinfo)
                && $curlinfo['download_content_length'] >= 0) {
            // we received a correct header and at least can tell the file size
            $return = (object)array('filesize' => $curlinfo['download_content_length']);
        }
        return $return;
    }
Beispiel #9
0
 public function sync_reference(stored_file $file)
 {
     global $USER;
     if ($file->get_referencelastsync() + DAYSECS > time() || !$this->connection_result()) {
         // Synchronise not more often than once a day.
         // if we had several unsuccessfull attempts to connect to server - do not try any more.
         return false;
     }
     $ref = @unserialize(base64_decode($file->get_reference()));
     if (!isset($ref->url) || !($url = $this->appendtoken($ref->url))) {
         // Occurs when the user isn't known..
         $file->set_missingsource();
         return true;
     }
     $cookiepathname = $this->prepare_file($USER->id . '_' . uniqid('', true) . '.cookie');
     $c = new curl(array('cookie' => $cookiepathname));
     if (file_extension_in_typegroup($ref->filename, 'web_image')) {
         $path = $this->prepare_file('');
         $result = $c->download_one($url, null, array('filepath' => $path, 'followlocation' => true, 'timeout' => $CFG->repositorysyncimagetimeout));
         if ($result === true) {
             $fs = get_file_storage();
             list($contenthash, $filesize, $newfile) = $fs->add_file_to_pool($path);
             $file->set_synchronized($contenthash, $filesize);
             return true;
         }
     } else {
         $result = $c->head($url, array('followlocation' => true, 'timeout' => $CFG->repositorysyncfiletimeout));
     }
     // Delete cookie jar.
     if (file_exists($cookiepathname)) {
         unlink($cookiepathname);
     }
     $this->connection_result($c->get_errno());
     $curlinfo = $c->get_info();
     if (isset($curlinfo['http_code']) && $curlinfo['http_code'] == 200 && array_key_exists('download_content_length', $curlinfo) && $curlinfo['download_content_length'] >= 0) {
         // we received a correct header and at least can tell the file size
         $file->set_synchronized(null, $curlinfo['download_content_length']);
         return true;
     }
     $file->set_missingsource();
     return true;
 }
Beispiel #10
0
 public function test_curl_post()
 {
     $testurl = $this->getExternalTestFileUrl('/test_post.php');
     // Test post request.
     $curl = new curl();
     $contents = $curl->post($testurl, 'data=moodletest');
     $response = $curl->getResponse();
     $this->assertSame('200 OK', reset($response));
     $this->assertSame(0, $curl->get_errno());
     $this->assertSame('OK', $contents);
     // Test 100 requests.
     $curl = new curl();
     $curl->setHeader('Expect: 100-continue');
     $contents = $curl->post($testurl, 'data=moodletest');
     $response = $curl->getResponse();
     $this->assertSame('200 OK', reset($response));
     $this->assertSame(0, $curl->get_errno());
     $this->assertSame('OK', $contents);
 }
Beispiel #11
0
 /**
  * Checks if $CFG->behat_wwwroot is available
  *
  * @return bool
  */
 public static function is_server_running()
 {
     global $CFG;
     $request = new curl();
     $request->get($CFG->behat_wwwroot);
     if ($request->get_errno() === 0) {
         return true;
     }
     return false;
 }
 /**
  * Test curl class.
  */
 public function test_curl_class()
 {
     global $CFG;
     // Test https success.
     $testhtml = $this->getExternalTestFileUrl('/test.html');
     $curl = new curl();
     $contents = $curl->get($testhtml);
     $this->assertSame('47250a973d1b88d9445f94db4ef2c97a', md5($contents));
     $this->assertSame(0, $curl->get_errno());
     $curl = new curl();
     $tofile = "{$CFG->tempdir}/test.html";
     @unlink($tofile);
     $fp = fopen($tofile, 'w');
     $result = $curl->get($testhtml, array(), array('CURLOPT_FILE' => $fp));
     $this->assertTrue($result);
     fclose($fp);
     $this->assertFileExists($tofile);
     $this->assertSame($contents, file_get_contents($tofile));
     @unlink($tofile);
     $curl = new curl();
     $tofile = "{$CFG->tempdir}/test.html";
     @unlink($tofile);
     $result = $curl->download_one($testhtml, array(), array('filepath' => $tofile));
     $this->assertTrue($result);
     $this->assertFileExists($tofile);
     $this->assertSame($contents, file_get_contents($tofile));
     @unlink($tofile);
     // Test full URL redirects.
     $testurl = $this->getExternalTestFileUrl('/test_redir.php');
     $curl = new curl();
     $contents = $curl->get("{$testurl}?redir=2", array(), array('CURLOPT_MAXREDIRS' => 2));
     $this->assertSame(0, $curl->get_errno());
     $this->assertSame(2, $curl->info['redirect_count']);
     $this->assertSame('done', $contents);
     $curl = new curl();
     $curl->emulateredirects = true;
     $contents = $curl->get("{$testurl}?redir=2", array(), array('CURLOPT_MAXREDIRS' => 2));
     $this->assertSame(0, $curl->get_errno());
     $this->assertSame(2, $curl->info['redirect_count']);
     $this->assertSame('done', $contents);
     $curl = new curl();
     $contents = $curl->get("{$testurl}?redir=3", array(), array('CURLOPT_FOLLOWLOCATION' => 0));
     $this->assertSame(0, $curl->get_errno());
     $this->assertSame(302, $curl->info['http_code']);
     $this->assertSame('', $contents);
     $curl = new curl();
     $curl->emulateredirects = true;
     $contents = $curl->get("{$testurl}?redir=3", array(), array('CURLOPT_FOLLOWLOCATION' => 0));
     $this->assertSame(0, $curl->get_errno());
     $this->assertSame(302, $curl->info['http_code']);
     $this->assertSame('', $contents);
     $curl = new curl();
     $contents = $curl->get("{$testurl}?redir=2", array(), array('CURLOPT_MAXREDIRS' => 1));
     $this->assertSame(CURLE_TOO_MANY_REDIRECTS, $curl->get_errno());
     $this->assertNotEmpty($contents);
     $curl = new curl();
     $curl->emulateredirects = true;
     $contents = $curl->get("{$testurl}?redir=2", array(), array('CURLOPT_MAXREDIRS' => 1));
     $this->assertSame(CURLE_TOO_MANY_REDIRECTS, $curl->get_errno());
     $this->assertNotEmpty($contents);
     $curl = new curl();
     $tofile = "{$CFG->tempdir}/test.html";
     @unlink($tofile);
     $fp = fopen($tofile, 'w');
     $result = $curl->get("{$testurl}?redir=1", array(), array('CURLOPT_FILE' => $fp));
     $this->assertTrue($result);
     fclose($fp);
     $this->assertFileExists($tofile);
     $this->assertSame('done', file_get_contents($tofile));
     @unlink($tofile);
     $curl = new curl();
     $curl->emulateredirects = true;
     $tofile = "{$CFG->tempdir}/test.html";
     @unlink($tofile);
     $fp = fopen($tofile, 'w');
     $result = $curl->get("{$testurl}?redir=1", array(), array('CURLOPT_FILE' => $fp));
     $this->assertTrue($result);
     fclose($fp);
     $this->assertFileExists($tofile);
     $this->assertSame('done', file_get_contents($tofile));
     @unlink($tofile);
     $curl = new curl();
     $tofile = "{$CFG->tempdir}/test.html";
     @unlink($tofile);
     $result = $curl->download_one("{$testurl}?redir=1", array(), array('filepath' => $tofile));
     $this->assertTrue($result);
     $this->assertFileExists($tofile);
     $this->assertSame('done', file_get_contents($tofile));
     @unlink($tofile);
     $curl = new curl();
     $curl->emulateredirects = true;
     $tofile = "{$CFG->tempdir}/test.html";
     @unlink($tofile);
     $result = $curl->download_one("{$testurl}?redir=1", array(), array('filepath' => $tofile));
     $this->assertTrue($result);
     $this->assertFileExists($tofile);
     $this->assertSame('done', file_get_contents($tofile));
     @unlink($tofile);
     // Test relative location redirects.
     $testurl = $this->getExternalTestFileUrl('/test_relative_redir.php');
     $curl = new curl();
     $contents = $curl->get($testurl);
     $this->assertSame(0, $curl->get_errno());
     $this->assertSame(1, $curl->info['redirect_count']);
     $this->assertSame('done', $contents);
     $curl = new curl();
     $curl->emulateredirects = true;
     $contents = $curl->get($testurl);
     $this->assertSame(0, $curl->get_errno());
     $this->assertSame(1, $curl->info['redirect_count']);
     $this->assertSame('done', $contents);
     // Test different redirect types.
     $testurl = $this->getExternalTestFileUrl('/test_relative_redir.php');
     $curl = new curl();
     $contents = $curl->get("{$testurl}?type=301");
     $this->assertSame(0, $curl->get_errno());
     $this->assertSame(1, $curl->info['redirect_count']);
     $this->assertSame('done', $contents);
     $curl = new curl();
     $curl->emulateredirects = true;
     $contents = $curl->get("{$testurl}?type=301");
     $this->assertSame(0, $curl->get_errno());
     $this->assertSame(1, $curl->info['redirect_count']);
     $this->assertSame('done', $contents);
     $curl = new curl();
     $contents = $curl->get("{$testurl}?type=302");
     $this->assertSame(0, $curl->get_errno());
     $this->assertSame(1, $curl->info['redirect_count']);
     $this->assertSame('done', $contents);
     $curl = new curl();
     $curl->emulateredirects = true;
     $contents = $curl->get("{$testurl}?type=302");
     $this->assertSame(0, $curl->get_errno());
     $this->assertSame(1, $curl->info['redirect_count']);
     $this->assertSame('done', $contents);
     $curl = new curl();
     $contents = $curl->get("{$testurl}?type=303");
     $this->assertSame(0, $curl->get_errno());
     $this->assertSame(1, $curl->info['redirect_count']);
     $this->assertSame('done', $contents);
     $curl = new curl();
     $curl->emulateredirects = true;
     $contents = $curl->get("{$testurl}?type=303");
     $this->assertSame(0, $curl->get_errno());
     $this->assertSame(1, $curl->info['redirect_count']);
     $this->assertSame('done', $contents);
     $curl = new curl();
     $contents = $curl->get("{$testurl}?type=307");
     $this->assertSame(0, $curl->get_errno());
     $this->assertSame(1, $curl->info['redirect_count']);
     $this->assertSame('done', $contents);
     $curl = new curl();
     $curl->emulateredirects = true;
     $contents = $curl->get("{$testurl}?type=307");
     $this->assertSame(0, $curl->get_errno());
     $this->assertSame(1, $curl->info['redirect_count']);
     $this->assertSame('done', $contents);
     $curl = new curl();
     $contents = $curl->get("{$testurl}?type=308");
     $this->assertSame(0, $curl->get_errno());
     $this->assertSame(1, $curl->info['redirect_count']);
     $this->assertSame('done', $contents);
     $curl = new curl();
     $curl->emulateredirects = true;
     $contents = $curl->get("{$testurl}?type=308");
     $this->assertSame(0, $curl->get_errno());
     $this->assertSame(1, $curl->info['redirect_count']);
     $this->assertSame('done', $contents);
 }
/**
 * Calls a remote server externallib web services during import
 * We use the Moodle curl cache to store responses (for 120 secs default)
 * @param string $function
 * @param array $params (name => value)
 * @return array json decoded result or false if not configured
 */
function oublog_import_remote_call($function, $params = null)
{
    $settings = get_config('mod_oublog');
    if (empty($settings->remoteserver) && empty($settings->remotetoken)) {
        return false;
    }
    if (is_null($params)) {
        $params = array();
    }
    $curl = new curl(array('cache' => true, 'module_cache' => 'oublog_import'));
    $url = $settings->remoteserver . '/webservice/rest/server.php';
    $params['moodlewsrestformat'] = 'json';
    $params['wsfunction'] = $function;
    $params['wstoken'] = $settings->remotetoken;
    $options = array();
    $options['RETURNTRANSFER'] = true;
    $options['SSL_VERIFYPEER'] = false;
    $result = $curl->get($url, $params, $options);
    $json = json_decode($result);
    if (empty($result) || $curl->get_errno() || !empty($json->exception)) {
        $errinfo = !empty($json->exception) ? !empty($json->debuginfo) ? $json->debuginfo : $json->message : $curl->error;
        throw new moodle_exception('Failed to contact ' . $settings->remoteserver . ' : ' . $errinfo);
        return false;
    }
    return $json;
}
Beispiel #14
0
    /**
     * Checks if the mdeploy.php will be able to fetch the ZIP from the given URL
     *
     * This is mainly supposed to check if the transmission over HTTPS would
     * work. That is, if the CA certificates are present at the server.
     *
     * @param string $downloadurl the URL of the ZIP package to download
     * @return bool
     */
    protected function update_downloadable($downloadurl) {
        global $CFG;

        $curloptions = array(
            'CURLOPT_SSL_VERIFYHOST' => 2,      // this is the default in {@link curl} class but just in case
            'CURLOPT_SSL_VERIFYPEER' => true,
        );

        $curl = new curl(array('proxy' => true));
        $result = $curl->head($downloadurl, $curloptions);
        $errno = $curl->get_errno();
        if (empty($errno)) {
            return true;
        } else {
            return false;
        }
    }
Beispiel #15
0
 /**
  * Get box.net file info
  *
  * @param string $fileid
  * @param int $timeout request timeout in seconds
  * @return stdClass|null
  */
 function get_file_info($fileid, $timeout = 0)
 {
     $this->_clearErrors();
     $params = array();
     $params['action'] = 'get_file_info';
     $params['file_id'] = $fileid;
     $params['auth_token'] = $this->auth_token;
     $params['api_key'] = $this->api_key;
     $http = new curl(array('debug' => $this->debug));
     $xml = $http->get($this->_box_api_url, $params, array('timeout' => $timeout));
     if (!$http->get_errno()) {
         $o = simplexml_load_string(trim($xml));
         if ($o->status == 's_get_file_info') {
             return $o->info;
         }
     }
     return null;
 }