function getUrl($url, $requestType = 'GET', $timeout = 30) { $curl = new curl(); $curl->curl($url); if ($requestType == "POST") { $postString = ""; foreach ($postArray as $postField => $postValue) { $postString .= "{$postField}=" . $postValue . "&"; } $postString .= "Enter="; $curl->setopt(CURLOPT_POST, 1); $curl->setopt(CURLOPT_POSTFIELDS, $postString); } $curl->setopt(CURLOPT_FRESH_CONNECT, TRUE); $curl->setopt(CURLOPT_SSL_VERIFYPEER, FALSE); $curl->setopt(CURLOPT_USERAGENT, MAGPIE_USER_AGENT); $curl->setopt(CURLOPT_FOLLOWLOCATION, 1); // allow redirects $curl->setopt(CURLOPT_RETURNTRANSFER, 1); // return into a variable $curl->setopt(CURLOPT_FORBID_REUSE, 1); $curl->setopt(CURLOPT_TIMEOUT, $timeout); // times out after x seconds $result = $curl->exec(); // run the whole process $curl->close(); return $result; }
/** * The contructor is a copy of the stock simplepie File class which has * been modifed to add in use the Moodle curl class rather than php curl * functions. */ function moodle_simplepie_file($url, $timeout = 10, $redirects = 5, $headers = null, $useragent = null, $force_fsockopen = false) { $this->url = $url; $this->method = SIMPLEPIE_FILE_SOURCE_REMOTE | SIMPLEPIE_FILE_SOURCE_CURL; $curl = new curl(); $curl->setopt(array('CURLOPT_HEADER' => true)); try { $this->headers = $curl->get($url); } catch (moodle_exception $e) { $this->error = 'cURL Error: ' . $curl->error; $this->success = false; return false; } $parser =& new SimplePie_HTTP_Parser($this->headers); if ($parser->parse()) { $this->headers = $parser->headers; $this->body = $parser->body; $this->status_code = $parser->status_code; if (($this->status_code == 300 || $this->status_code == 301 || $this->status_code == 302 || $this->status_code == 303 || $this->status_code == 307 || $this->status_code > 307 && $this->status_code < 400) && isset($this->headers['location']) && $this->redirects < $redirects) { $this->redirects++; $location = SimplePie_Misc::absolutize_url($this->headers['location'], $url); return $this->SimplePie_File($location, $timeout, $redirects, $headers); } } }
function readFeed($url, $type = '') { $this->url = $url; $this->type = $type; $urltocapture = new curl($this->url); $urltocapture->setopt(CURLOPT_HTTPGET, true); $this->fileRead = $urltocapture->exec(); if (empty($this->fileRead) or !$this->fileRead) { return 101; } $ext = new btext(); $this->feedArray = $ext->xml2array($this->fileRead); switch ($this->type) { case 'youtube': return $this->youtube(); break; case 'vimeo': return $this->vimeo(); break; case 'dailymotion': return $this->dailymotion(); break; default: return false; break; } }
/** * Check if the remote site is valid (not localhost and available by the hub) * Note: it doesn't matter if the site returns a 404 error. * The point here is to check if the site exists. It does not matter if the hub can not call the site, * as by security design, a hub should never call a site. * However an admin user registering his site should be able to access the site, * as people searching on the hub. * So we want: * a) to check that the url is not a local address * b) to check that the site return some not empty headers * (it exists, at least the domain name is registered) * @param string $url the site url * @return boolean true if the site is valid */ public function is_remote_site_valid($url) { global $CFG; require_once $CFG->libdir . '/filelib.php'; //Check if site is valid if (strpos($url, 'http://localhost') !== false or strpos($url, 'http://127.0.0.1') !== false) { return false; } $curl = new curl(); $curl->setopt(array('CURLOPT_FOLLOWLOCATION' => true, 'CURLOPT_MAXREDIRS' => 3)); $curl->head($url); $info = $curl->get_info(); // Return true if return code is OK (200) or redirection (302). // Redirection occurs for many reasons including redirection to another site that handles single sign-on. if ($info['http_code'] === 200 || $info['http_code'] === 302) { return true; } // Some sites respond to head() with a 503. // As a fallback try get(). // We don't just always do get() as it is much slower than head(). $curl->get($url); $info = $curl->get_info(); if ($info['http_code'] === 200 || $info['http_code'] === 302) { return true; } return false; }
/** * Parses one file (either html or css) * * @param string $baseurl (optional) URL of the file where link to this file was found * @param string $relativeurl relative or absolute link to the file * @param array $list * @param bool $mainfile true only for main HTML false and false for all embedded/linked files */ protected function parse_file($baseurl, $relativeurl, &$list, $mainfile = false) { if (preg_match('/([\'"])(.*)\\1/', $relativeurl, $matches)) { $relativeurl = $matches[2]; } if (empty($baseurl)) { $url = $relativeurl; } else { $url = htmlspecialchars_decode(url_to_absolute($baseurl, $relativeurl)); } if (in_array($url, $this->processedfiles)) { // avoid endless recursion return; } $this->processedfiles[] = $url; $curl = new curl(); $curl->setopt(array('CURLOPT_FOLLOWLOCATION' => true, 'CURLOPT_MAXREDIRS' => 3)); $msg = $curl->head($url); $info = $curl->get_info(); if ($info['http_code'] != 200) { if ($mainfile) { $list['error'] = $msg; } } else { $csstoanalyze = ''; if ($mainfile && (strstr($info['content_type'], 'text/html') || empty($info['content_type']))) { // parse as html $htmlcontent = $curl->get($info['url']); $ddoc = new DOMDocument(); @$ddoc->loadHTML($htmlcontent); // extract <img> $tags = $ddoc->getElementsByTagName('img'); foreach ($tags as $tag) { $url = $tag->getAttribute('src'); $this->add_image_to_list($info['url'], $url, $list); } // analyse embedded css (<style>) $tags = $ddoc->getElementsByTagName('style'); foreach ($tags as $tag) { if ($tag->getAttribute('type') == 'text/css') { $csstoanalyze .= $tag->textContent . "\n"; } } // analyse links to css (<link type='text/css' href='...'>) $tags = $ddoc->getElementsByTagName('link'); foreach ($tags as $tag) { if ($tag->getAttribute('type') == 'text/css' && strlen($tag->getAttribute('href'))) { $this->parse_file($info['url'], $tag->getAttribute('href'), $list); } } } else { if (strstr($info['content_type'], 'css')) { // parse as css $csscontent = $curl->get($info['url']); $csstoanalyze .= $csscontent . "\n"; } else { if (strstr($info['content_type'], 'image/')) { // download this file $this->add_image_to_list($info['url'], $info['url'], $list); } else { $list['error'] = get_string('validfiletype', 'repository_url'); } } } // parse all found css styles if (strlen($csstoanalyze)) { $urls = extract_css_urls($csstoanalyze); if (!empty($urls['property'])) { foreach ($urls['property'] as $url) { $this->add_image_to_list($info['url'], $url, $list); } } if (!empty($urls['import'])) { foreach ($urls['import'] as $cssurl) { $this->parse_file($info['url'], $cssurl, $list); } } } } }
/** * The contructor is a copy of the stock simplepie File class which has * been modifed to add in use the Moodle curl class rather than php curl * functions. */ function moodle_simplepie_file($url, $timeout = 10, $redirects = 5, $headers = null, $useragent = null, $force_fsockopen = false) { $this->url = $url; $this->method = SIMPLEPIE_FILE_SOURCE_REMOTE | SIMPLEPIE_FILE_SOURCE_CURL; $curl = new curl(); $curl->setopt(array('CURLOPT_HEADER' => true, 'CURLOPT_TIMEOUT' => $timeout, 'CURLOPT_CONNECTTIMEOUT' => $timeout)); if ($headers !== null) { // translate simplepie headers to those class curl expects foreach ($headers as $headername => $headervalue) { $headerstr = "{$headername}: {$headervalue}"; $curl->setHeader($headerstr); } } $this->headers = $curl->get($url); if ($curl->error) { $this->error = 'cURL Error: ' . $curl->error; $this->success = false; return false; } $parser = new SimplePie_HTTP_Parser($this->headers); if ($parser->parse()) { $this->headers = $parser->headers; $this->body = $parser->body; $this->status_code = $parser->status_code; if (($this->status_code == 300 || $this->status_code == 301 || $this->status_code == 302 || $this->status_code == 303 || $this->status_code == 307 || $this->status_code > 307 && $this->status_code < 400) && isset($this->headers['location']) && $this->redirects < $redirects) { $this->redirects++; $location = SimplePie_Misc::absolutize_url($this->headers['location'], $url); return $this->moodle_simplepie_file($location, $timeout, $redirects, $headers); } } }
/** * From a URL, fetch the calendar and return an iCalendar object. * * @param string $url The iCalendar URL * @return stdClass The iCalendar object */ function calendar_get_icalendar($url) { global $CFG; require_once $CFG->libdir . '/filelib.php'; $curl = new curl(); $curl->setopt(array('CURLOPT_FOLLOWLOCATION' => 1, 'CURLOPT_MAXREDIRS' => 5)); $calendar = $curl->get($url); // Http code validation should actually be the job of curl class. if (!$calendar || $curl->info['http_code'] != 200 || !empty($curl->errorno)) { throw new moodle_exception('errorinvalidicalurl', 'calendar'); } $ical = new iCalendar(); $ical->unserialize($calendar); return $ical; }
/** * internal function that I use to make all the requests to flickr * * @param string $method The Flickr Method that is being requested * @param array $params An array of the various required and optional fields needed to make the mthod request * * @return array The xml turned into an array * @access public */ function makeRequest($method, $params) { $this->_clearErrors(); $useCURL = in_array('curl', get_loaded_extensions()); $params['method'] = $method; $params['api_key'] = $this->_api_key; $args = array(); foreach ($params as $k => $v) { array_push($args, urlencode($k) . '=' . urlencode($v)); } $query_str = implode('&', $args); $request = $this->_flickr_api_url . '?' . $query_str; // full url to request $hit_flickr = true; // whether or not to make a request to flickr $request_hash = md5($request); if ($this->_cache_enabled) { if ($this->_cache_type == 'db') { $now = time(); $rows = $this->_cache->findMany("WHERE request = '" . $request_hash . "' AND date_expire > {$now}"); // if any rows found, then use cached response if (count($rows) > 0) { $xml = $rows[0]->response; $hit_flickr = $xml == '' ? true : false; } } else { $now = time(); $file = $this->_cache_dir . md5($request) . '.cache'; if (file_exists($file)) { $xml = file_get_contents($file); $hit_flickr = $xml == '' ? true : false; } } } // only hit flickr if cached request not found above if ($hit_flickr) { // whether or not to use curl for request if ($useCURL) { $c = new curl($request); $c->setopt(CURLOPT_FOLLOWLOCATION, true); $xml = $c->exec(); $error = $c->hasError(); if ($error) { $this->_error_msg = $error; return false; } $c->close(); } else { // curl not available so use fsockopen $url_parsed = parse_url($request); $host = $url_parsed["host"]; $port = $url_parsed['port'] == 0 ? 80 : $url_parsed['port']; $path = $url_parsed["path"] . ($url_parsed['query'] != '' ? $path .= "?{$url_parsed[query]}" : ''); $headers = "GET {$path} HTTP/1.0\r\n"; $headers .= "Host: {$host}\r\n\r\n"; $fp = fsockopen($host, $port, $errno, $errstr, 30); if (!$fp) { $this->_error_msg = $errstr; $this->_error_code = $errno; return false; } else { fwrite($fp, $headers); while (!feof($fp)) { $xml .= fgets($fp, 1024); } fclose($fp); /* this seems stupid, but it removes the headers from the response; if you know a better way let me know */ $xml_start = strpos($xml, '<?xml'); $xml = substr($xml, $xml_start, strlen($xml)); } } if ($this->_cache_enabled) { // store the cached request if ($this->_cache_type == 'db') { $this->_cache->request = $request_hash; $this->_cache->response = $xml; $this->_cache->date_expire = strtotime("+ {$this->_cache_expire} seconds", time()); $this->_cache->save(); } else { $file = $this->_cache_dir . $request_hash . '.cache'; $fp = fopen($file, "w"); $result = fwrite($fp, $xml); fclose($fp); } } } if ($this->_debug) { echo '<h2>XML Response</h2>'; echo '<pre class="xml">'; echo htmlspecialchars($xml); echo '</pre>'; } $xml_parser = xml_parser_create(); xml_parse_into_struct($xml_parser, $xml, $data); xml_parser_free($xml_parser); return $data; }
function fetch_request($request) { $c = new curl(array('cache' => true, 'module_cache' => 'tag_youtube')); $c->setopt(array('CURLOPT_TIMEOUT' => 3, 'CURLOPT_CONNECTTIMEOUT' => 3)); $response = $c->get($request); $xml = new SimpleXMLElement($response); return $this->render_video_list($xml); }
$array['error'] = "Please enter file url"; echo json_encode($array); exit; } //Checkinf if extension is wrong $types = strtolower($Cbucket->configs['allowed_types']); $types_array = preg_replace('/,/', ' ', $types); $types_array = explode(' ', $types_array); $extension_whitelist = $types_array; if (!in_array($ext, $extension_whitelist)) { $array['error'] = "This file type is not allowed"; echo json_encode($array); exit; } $curl = new curl($file); $curl->setopt(CURLOPT_FOLLOWLOCATION, true); //Checking if file size is not that goood if (!is_numeric($curl->file_size) || $curl->file_size == '') { $array['error'] = "Unknown file size"; echo json_encode($array); exit; } if (phpversion() < '5.3.0') { //Here we will get file size and write it in a file //called dummy_log $darray = array('file_size' => $curl->file_size, 'file_name' => $file_name . '.' . $ext, 'time_started' => time(), 'byte_size' => 0); $do = fopen($dummy_file, 'w+'); fwrite($do, json_encode($darray)); fclose($do); } //Opening video file
function capture() { $obj = new stdClass(); $arry = $this->readFeed($this->feed['url'], $this->feed['type']); $obj->title = $arry['title']; $obj->description = $arry['description']; $obj->videoThumbnail = $arry['videoThumbnail']; $obj->videoTags = $arry['videoTags']; $obj->videoSrc = $arry['videoSrc']; if (empty($obj->title) or empty($obj->videoSrc) or empty($obj->videoThumbnail)) { if (!empty($arry['error'])) { return $arry['error']; } else { return $arry; } } $obj->fileName = time() . $this->video_id . ".jpg"; $urltocapture = new curl($obj->videoThumbnail); $urltocapture->setopt(CURLOPT_HTTPGET, true); $obj->fileContent = $urltocapture->exec(); $obj->type = $this->feed['type']; return $obj; }
public function validate_receiver($receiver) { $plagiarismsettings = $this->get_settings(); $url = URKUND_INTEGRATION_SERVICE . '/receivers' . '/' . trim($receiver); $headers = array('Accept-Language: ' . $plagiarismsettings['urkund_lang']); $allowedstatus = array(URKUND_STATUSCODE_PROCESSED, URKUND_STATUSCODE_NOT_FOUND, URKUND_STATUSCODE_BAD_REQUEST, URKUND_STATUSCODE_GONE); // Use Moodle curl wrapper. $c = new curl(array('proxy' => true)); $c->setopt(array()); $c->setopt(array('CURLOPT_RETURNTRANSFER' => 1, 'CURLOPT_HTTPAUTH' => CURLAUTH_BASIC, 'CURLOPT_USERPWD' => $plagiarismsettings['urkund_username'] . ":" . $plagiarismsettings['urkund_password'])); $c->setHeader($headers); $response = $c->get($url); $httpstatus = $c->info['http_code']; if (!empty($httpstatus)) { if (in_array($httpstatus, $allowedstatus)) { if ($httpstatus == URKUND_STATUSCODE_PROCESSED) { // Valid address found, return true. return true; } else { return $httpstatus; } } } return false; }
/** * Sends a request to fetch data. * * @see block_tag_youtube::service * @deprecated since Moodle 2.8.8, 2.9.2 and 3.0 MDL-49085 - please do not use this function any more. * @param string $request * @throws coding_exception */ public function fetch_request($request) { throw new coding_exception('Sorry, this function has been deprecated in Moodle 2.8.8, 2.9.2 and 3.0. Use block_tag_youtube::get_service instead.'); $c = new curl(array('cache' => true, 'module_cache' => 'tag_youtube')); $c->setopt(array('CURLOPT_TIMEOUT' => 3, 'CURLOPT_CONNECTTIMEOUT' => 3)); $response = $c->get($request); $xml = new SimpleXMLElement($response); return $this->render_video_list($xml); }
<?php include_once "class.curl.php"; // // Create a new instance of the curl class and point it // at the page to be fetched. // $c = new curl("http://www.csworks.com/resume/cv.shtml"); // // By default, curl doesn't follow redirections and this // page may or may not be available via redirection. // $c->setopt(CURLOPT_FOLLOWLOCATION, true); // // By default, the curl class expects to return data to // the caller. // echo $c->exec(); // // Check to see if there was an error and, if so, print // the associated error message. // if ($theError = $c->hasError()) { echo $theError; } // // Done with the cURL, so get rid of the cURL related resources. // $c->close();
private function curl_post($URL = NULL, $POST_DATA = NULL) { if ($URL == NULL || $POST_DATA == NULL) { trigger_error("curl_post() ERROR: URL or POST_DATA has not been setted.", E_USER_ERROR); } $URL = new curl($URL); $URL->setopt(CURLOPT_FOLLOWLOCATION, TRUE); $URL->setopt(CURLOPT_SSL_VERIFYPEER, FALSE); $URL->setopt(CURLOPT_SSL_VERIFYHOST, FALSE); $URL->setopt(CURLOPT_POST, TRUE); $URL->setopt(CURLOPT_POSTFIELDS, $POST_DATA); $URL->setopt(CURLOPT_USERAGENT, "User-Agent: IIC2.0/PC 2.3.0230"); $curl_result = $URL->exec(); if ($theError = $URL->hasError()) { echo $theError; } $URL->close(); return $curl_result; }
/** * Execute an API request. * * This is a copy/paste from the parent class that uses Moodle's implementation * of curl. Portions have been removed or altered. * * @param Google_Http_Request $request the http request to be executed * @return Google_Http_Request http request with the response http code, response * headers and response body filled in * @throws Google_IO_Exception on curl or IO error */ public function executeRequest(Google_Http_Request $request) { $curl = new curl(); if ($request->getPostBody()) { $curl->setopt(array('CURLOPT_POSTFIELDS' => $request->getPostBody())); } $requestHeaders = $request->getRequestHeaders(); if ($requestHeaders && is_array($requestHeaders)) { $curlHeaders = array(); foreach ($requestHeaders as $k => $v) { $curlHeaders[] = "{$k}: {$v}"; } $curl->setopt(array('CURLOPT_HTTPHEADER' => $curlHeaders)); } $curl->setopt(array('CURLOPT_URL' => $request->getUrl())); $curl->setopt(array('CURLOPT_CUSTOMREQUEST' => $request->getRequestMethod())); $curl->setopt(array('CURLOPT_USERAGENT' => $request->getUserAgent())); $curl->setopt(array('CURLOPT_FOLLOWLOCATION' => false)); $curl->setopt(array('CURLOPT_SSL_VERIFYPEER' => true)); $curl->setopt(array('CURLOPT_RETURNTRANSFER' => true)); $curl->setopt(array('CURLOPT_HEADER' => true)); if ($request->canGzip()) { $curl->setopt(array('CURLOPT_ENCODING' => 'gzip,deflate')); } $curl->setopt($this->options); $respdata = $this->do_request($curl, $request); $infos = $curl->get_info(); $respheadersize = $infos['header_size']; $resphttpcode = (int) $infos['http_code']; $curlerrornum = $curl->get_errno(); $curlerror = $curl->error; if ($respdata != CURLE_OK) { throw new Google_IO_Exception($curlerror); } list($responseHeaders, $responseBody) = $this->parseHttpResponse($respdata, $respheadersize); return array($responseBody, $responseHeaders, $resphttpcode); }
/** * Request gadget metadata from shindig * * Takes $gadget as a parameter and adds height and name for it */ function set_gadget_metadata($gadget_url, $gadget) { global $CFG; require_once $CFG->dirroot . '/mod/widgetspace/lib/container.php'; $gadget_container = new GadgetContainer(null); $shindig_url = $gadget_container->get_shindig_url(); $request = $shindig_url . '/gadgets/metadata?st=0:0:0:0:0:0:0'; $c = new curl(); $c->setopt(array('CURLOPT_TIMEOUT' => 3, 'CURLOPT_CONNECTTIMEOUT' => 3, 'CURLOPT_HTTPHEADER' => array("Content-Type: application/json", "Accept: application/json"))); // , "Content-length: ".strlen($data) $data = '{"context":{"view":"canvas","container":"default"},"gadgets":[{"url":"' . $gadget_url . '", "moduleId":0}]}'; $response = $c->post($request, $data); $json = json_decode($response); // var_dump($json); $gadgets = $json->gadgets; //set height of gadget $gadget->height = $gadgets[0]->height == 0 ? 200 : $gadgets[0]->height; $gadget->name = $gadgets[0]->title; //set name of gadget $gadget->thumbnail = $gadgets[0]->thumbnail; $gadget->screenshot = $gadgets[0]->screenshot; $gadget->description = $gadgets[0]->description; }
/** * @param string $path Unused * @param array $params * @return array */ function getfiletree($path, $params = array()) { $this->_clearErrors(); $params['auth_token'] = $this->auth_token; $params['folder_id'] = 0; $params['api_key'] = $this->api_key; $params['action'] = 'get_account_tree'; $params['onelevel'] = 1; $params['params[]'] = 'nozip'; $c = new curl(array('debug' => $this->debug, 'cache' => true, 'module_cache' => 'repository')); $c->setopt(array('CURLOPT_FOLLOWLOCATION' => 1)); try { $args = array(); $xml = $c->get($this->_box_api_url, $params); } catch (Exception $e) { } $ret = array(); $o = simplexml_load_string(trim($xml)); if ($o->status == 'listing_ok') { $tree = $o->tree->folder; $this->buildtree($tree, $ret); } return $ret; }
function bigbluebuttonbn_wrap_xml_load_file($url, $method = BIGBLUEBUTTONBN_METHOD_GET, $data = null) { if (bigbluebuttonbn_debugdisplay()) { error_log("Request to: " . $url); } if (extension_loaded('curl')) { $c = new curl(); $c->setopt(array("SSL_VERIFYPEER" => true)); if ($method == BIGBLUEBUTTONBN_METHOD_POST) { if (!is_null($data)) { if (!is_array($data)) { $options['CURLOPT_HTTPHEADER'] = array('Content-Type: text/xml', 'Content-Length: ' . strlen($data), 'Content-Language: en-US'); $response = $c->post($url, $data, $options); } else { $response = $c->post($url, $data); } } else { $response = $c->post($url); } } else { $response = $c->get($url); } if ($response) { $previous = libxml_use_internal_errors(true); try { $xml = new SimpleXMLElement($response, LIBXML_NOCDATA); return $xml; } catch (Exception $e) { libxml_use_internal_errors($previous); $error = 'Caught exception: ' . $e->getMessage(); error_log($error); return NULL; } } else { error_log("No response on wrap_simplexml_load_file"); return NULL; } } else { $previous = libxml_use_internal_errors(true); try { $xml = simplexml_load_file($url, 'SimpleXMLElement', LIBXML_NOCDATA); return $xml; } catch (Exception $e) { libxml_use_internal_errors($previous); return NULL; } } }
/** * @link http://docs.moodle.org/dev/Authentication_plugins#loginpage_hook.28.29 * * Hook for overriding behaviour of login page. * Another auth hook. Process login if $authorizationcode is defined in OAuth url. * Makes cURL POST/GET request to social webservice and fill response data to Moodle user. * We check access tokens in cookies, if the ones exists - get it from $_COOKIE, if no - setcookie * * @uses $SESSION, $CFG, $DB core global objects/variables * @return void or @moodle_exception if OAuth request returns error or fail * * @author Igor Sazonov ( @tigusigalpa ) */ function loginpage_hook() { global $SESSION, $CFG, $DB; $access_token = false; $authorizationcode = optional_param('oauthcode', '', PARAM_TEXT); // get authorization code from url if (!empty($authorizationcode)) { $authprovider = required_param('authprovider', PARAM_TEXT); // get authorization provider (webservice name) $hack_authprovider = $authprovider == 'yahoo1' || $authprovider == 'yahoo2' ? 'yahoo' : $authprovider; $config_field_str = 'auth_lenauth_' . $hack_authprovider . '_social_id_field'; $this->_field_shortname = $this->_oauth_config->{$config_field_str}; $this->_field_id = $this->_lenauth_get_fieldid(); $params = array(); // params to generate data for token request $encode_params = true; $code = true; $redirect_uri = true; $curl_header = false; $curl_options = array(); //if we have access_token in $_COOKIE, so do not need to make request fot the one $this->_send_oauth_request = !isset($_COOKIE[$authprovider]['access_token']) ? true : false; //if service is not enabled, why should we make request? hack protect. maybe $enabled_str = 'auth_lenauth_' . $hack_authprovider . '_enabled'; if (empty($this->_oauth_config->{$enabled_str})) { throw new moodle_exception('Service not enabled in your LenAuth Settings', 'auth_lenauth'); } switch ($authprovider) { case 'facebook': /** * @link https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow/v2.0#exchangecode */ $params['client_id'] = $this->_oauth_config->auth_lenauth_facebook_app_id; $params['client_secret'] = $this->_oauth_config->auth_lenauth_facebook_app_secret; break; case 'google': /** * @link https://developers.google.com/accounts/docs/OAuth2Login#exchangecode */ $params['client_id'] = $this->_oauth_config->auth_lenauth_google_client_id; $params['client_secret'] = $this->_oauth_config->auth_lenauth_google_client_secret; $params['grant_type'] = $this->_settings[$authprovider]['grant_type']; break; case 'yahoo1': if (!isset($_COOKIE[$authprovider]['access_token']) && !isset($_COOKIE[$authprovider]['oauth_verifier'])) { $params = array_merge($this->_lenauth_yahoo_request_array($this->_oauth_config->auth_lenauth_yahoo_consumer_secret . '&'), array('oauth_callback' => $this->_lenauth_redirect_uri($authprovider))); $code = false; $redirect_uri = false; $this->_send_oauth_request = isset($_REQUEST['oauth_token'], $_REQUEST['oauth_verifier']) ? false : true; $oauth_verifier = false; // yahoo =)) if (!$this->_send_oauth_request && isset($SESSION->yahoo_expires) && !empty($SESSION->yahoo_expires)) { $access_token = $SESSION->yahoo_access_token = optional_param('oauth_token', '', PARAM_TEXT); setcookie($authprovider . '[access_token]', $access_token, time() + $SESSION->yahoo_expires); $oauth_verifier = $SESSION->yahoo_oauth_verifier = optional_param('oauth_verifier', '', PARAM_TEXT); setcookie($authprovider . '[oauth_verifier]', $oauth_verifier, time() + $SESSION->yahoo_expires); } else { } } else { $this->_send_oauth_request = false; } break; case 'yahoo2': $params['grant_type'] = $this->_settings[$authprovider]['grant_type']; $curl_options = array('USERPWD' => $this->_oauth_config->auth_lenauth_yahoo_consumer_key . ':' . $this->_oauth_config->auth_lenauth_yahoo_consumer_secret); break; case 'twitter': if (!empty($this->_oauth_config->auth_lenauth_twitter_enabled)) { if (!isset($_COOKIE[$authprovider]['access_token'])) { $params = array_merge($this->_lenauth_twitter_request_array($this->_oauth_config->auth_lenauth_twitter_consumer_secret . '&'), array('oauth_callback' => $this->_lenauth_redirect_uri($authprovider))); $code = false; $redirect_uri = false; $this->_send_oauth_request = isset($_REQUEST['oauth_token'], $_REQUEST['oauth_verifier']) ? false : true; $oauth_verifier = false; if (!$this->_send_oauth_request && isset($_COOKIE[$authprovider]['oauth_token_secret'])) { $access_token = $SESSION->twitter_access_token = optional_param('oauth_token', '', PARAM_TEXT); setcookie($authprovider . '[access_token]', $access_token, time() + $this->_settings[$authprovider]['expire'], '/'); $oauth_verifier = $SESSION->twitter_oauth_verifier = optional_param('oauth_verifier', '', PARAM_TEXT); setcookie($authprovider . '[oauth_verifier]', $oauth_verifier, time() + $this->_settings[$authprovider]['expire'], '/'); } else { $curl_header = $this->_lenauth_set_twitter_header($params); } //$curl_header = $this->_lenauth_set_twitter_header($params, $access_token/*, $oauth_token_secret = false*/); /*$curl_options = array( 'CURLOPT_RETURNTRANSFER' => true, 'CURLOPT_FOLLOWLOCATION' => true ); if ( !empty( $params['oauth_callback'] ) ) { $curl_options['CURLOPT_POSTFIELDS'] = http_build_query( array() ); }*/ //TWITTER IS GOOD!! $encode_params = false; } else { $this->_send_oauth_request = false; } } break; case 'vk': /** * @link http://vk.com/dev/auth_sites */ $params['client_id'] = $this->_oauth_config->auth_lenauth_vk_app_id; $params['client_secret'] = $this->_oauth_config->auth_lenauth_vk_app_secret; break; case 'yandex': $params['grant_type'] = $this->_settings[$authprovider]['grant_type']; $params['client_id'] = $this->_oauth_config->auth_lenauth_yandex_app_id; $params['client_secret'] = $this->_oauth_config->auth_lenauth_yandex_app_password; break; case 'mailru': $params['client_id'] = $this->_oauth_config->auth_lenauth_mailru_site_id; $params['client_secret'] = $this->_oauth_config->auth_lenauth_mailru_client_secret; $params['grant_type'] = $this->_settings[$authprovider]['grant_type']; break; //odnoklassniki.ru was wrote by school programmers at 1st class and it not used mojority. bye-bye! /*case 'ok': $params['client_id'] = $this->_oauth_config->ok_app_id; $params['client_secret'] = $this->_oauth_config->ok_secret_key; break;*/ //odnoklassniki.ru was wrote by school programmers at 1st class and it not used mojority. bye-bye! /*case 'ok': $params['client_id'] = $this->_oauth_config->ok_app_id; $params['client_secret'] = $this->_oauth_config->ok_secret_key; break;*/ default: // if authorization provider is wrong throw new moodle_exception('Unknown OAuth Provider', 'auth_lenauth'); } // url for catch token value // exception for Yahoo OAuth, because it like.. if ($code) { $params['code'] = $authorizationcode; } if ($redirect_uri) { $params['redirect_uri'] = $this->_lenauth_redirect_uri($authprovider); } //require cURL from Moodle core require_once $CFG->libdir . '/filelib.php'; // requires library with cURL class $curl = new curl(); //hack for twitter and Yahoo if (!empty($curl_options) && is_array($curl_options)) { $curl->setopt($curl_options); } $curl->resetHeader(); // clean cURL header from garbage //Twitter and Yahoo has an own cURL headers, so let them to be! if (!$curl_header) { $curl->setHeader('Content-Type: application/x-www-form-urlencoded'); } else { $curl->setHeader($curl_header); } // cURL REQUEST for tokens if we hasnt it in $_COOKIE if ($this->_send_oauth_request) { if ($this->_curl_type == 'post') { $curl_tokens_values = $curl->post($this->_settings[$authprovider]['request_token_url'], $encode_params ? $this->_generate_query_data($params) : $params); } else { $curl_tokens_values = $curl->get($this->_settings[$authprovider]['request_token_url'] . '?' . ($encode_params ? $this->_generate_query_data($params) : $params)); } } // check for token response if (!empty($curl_tokens_values) || !$this->_send_oauth_request) { $token_values = array(); // parse token values switch ($authprovider) { case 'facebook': if ($this->_send_oauth_request || !isset($_COOKIE[$authprovider]['access_token'])) { parse_str($curl_tokens_values, $token_values); $expires = $token_values['expires']; //5183999 = 2 months $access_token = $token_values['access_token']; if (!empty($expires) && !empty($access_token)) { setcookie($authprovider . '[access_token]', $access_token, time() + $expires, '/'); } else { throw new moodle_exception('Can not get access for "access_token" or/and "expires" params after request', 'auth_lenauth'); } } else { if (isset($_COOKIE[$authprovider]['access_token'])) { $access_token = $_COOKIE[$authprovider]['access_token']; } else { throw new moodle_exception('Someting wrong, maybe expires', 'auth_lenauth'); } } break; case 'google': if ($this->_send_oauth_request || !isset($_COOKIE[$authprovider]['access_token'])) { $token_values = json_decode($curl_tokens_values, true); $expires = $token_values['expires_in']; //3600 = 1 hour $access_token = $token_values['access_token']; if (!empty($access_token) && !empty($expires)) { setcookie($authprovider . '[access_token]', $access_token, time() + $expires, '/'); } else { throw new moodle_exception('Can not get access for "access_token" or/and "expires" params after request', 'auth_lenauth'); } } else { if (isset($_COOKIE[$authprovider]['access_token'])) { $access_token = $_COOKIE[$authprovider]['access_token']; } else { throw new moodle_exception('Someting wrong, maybe expires', 'auth_lenauth'); } } break; case 'yahoo1': if ($this->_send_oauth_request || !isset($_COOKIE[$authprovider]['oauth_token_secret'])) { parse_str($curl_tokens_values, $token_values); $expires = $SESSION->yahoo_expires = $token_values['oauth_expires_in']; //3600 = 1 hour $access_token = $SESSION->yahoo_access_token = $token_values['oauth_token']; setcookie($authprovider . '[oauth_token_secret]', $token_values['oauth_token_secret'], time() + $SESSION->yahoo_expires); $xoauth_request_auth_url = $token_values['xoauth_request_auth_url']; } else { if (isset($_COOKIE[$authprovider]['access_token'], $_COOKIE[$authprovider]['oauth_verifier']) || isset($SESSION->yahoo_access_token, $SESSION->yahoo_oauth_verifier)) { $access_token = isset($_COOKIE[$authprovider]['access_token']) ? $_COOKIE[$authprovider]['access_token'] : $SESSION->yahoo_access_token; $oauth_verifier = isset($_COOKIE[$authprovider]['oauth_verifier']) ? $_COOKIE[$authprovider]['oauth_verifier'] : $SESSION->yahoo_oauth_verifier; } else { throw new moodle_exception('Someting wrong, maybe expires', 'auth_lenauth'); } } break; case 'yahoo2': if ($this->_send_oauth_request || !isset($_COOKIE[$authprovider]['access_token'])) { $token_values = json_decode($curl_tokens_values, true); $expires = $token_values['expires_in']; //3600 = 1 hour $access_token = $token_values['access_token']; $refresh_token = $token_values['refresh_token']; $user_id = $token_values['xoauth_yahoo_guid']; if (!empty($expires) && !empty($access_token)) { setcookie($authprovider . '[access_token]', $access_token, time() + $expires, '/'); if (!empty($user_id)) { setcookie($authprovider . '[user_id]', $user_id, time() + $expires, '/'); } } else { throw new moodle_exception('Can not get access for "access_token" or/and "expires" params after request', 'auth_lenauth'); } } else { if (isset($_COOKIE[$authprovider]['access_token'], $_COOKIE[$authprovider]['user_id'])) { $access_token = $_COOKIE[$authprovider]['access_token']; $user_id = $_COOKIE[$authprovider]['user_id']; } else { throw new moodle_exception('Someting wrong, maybe expires', 'auth_lenauth'); } } break; case 'twitter': if ($this->_send_oauth_request || !isset($_COOKIE[$authprovider]['oauth_token_secret'])) { parse_str($curl_tokens_values, $token_values); $access_token = $SESSION->twitter_access_token = $token_values['oauth_token']; setcookie($authprovider . '[oauth_token_secret]', $token_values['oauth_token_secret'], time() + $this->_settings[$authprovider]['expire'], '/'); } else { if (isset($_COOKIE[$authprovider]['access_token'], $_COOKIE[$authprovider]['oauth_token_secret']) || isset($SESSION->twitter_access_token, $SESSION->twitter_oauth_verifier)) { $access_token = isset($_COOKIE[$authprovider]['access_token']) ? $_COOKIE[$authprovider]['access_token'] : $SESSION->twitter_access_token; $oauth_verifier = isset($_COOKIE[$authprovider]['oauth_verifier']) ? $_COOKIE[$authprovider]['oauth_verifier'] : $SESSION->twitter_oauth_verifier; } else { throw new moodle_exception('Someting wrong, maybe expires', 'auth_lenauth'); } } break; case 'vk': if ($this->_send_oauth_request || !isset($_COOKIE[$authprovider]['access_token'])) { $token_values = json_decode($curl_tokens_values, true); if (isset($token_values['error'])) { throw new moodle_exception('Native VK Error ' . $token_values['error'] . (isset($token_values['error_description']) ? ' with description: ' . $token_values['error_description'] : ''), 'auth_lenauth'); } $expires = $token_values['expires_in']; //86400 = 24 hours $access_token = $token_values['access_token']; if (!empty($access_token) && !empty($expires)) { setcookie($authprovider . '[access_token]', $access_token, time() + $expires, '/'); } $user_id = $token_values['user_id']; if (!empty($user_id)) { setcookie($authprovider . '[user_id]', $user_id, time() + $expires, '/'); } /** * VK user may do not enter email, soooo =(( */ $user_email = isset($token_values['email']) ? $token_values['email'] : false; // WOW!!! So early???))) Awesome! if (!empty($user_email)) { setcookie($authprovider . '[user_email]', $user_email, time() + $expires, '/'); } } else { if (isset($_COOKIE[$authprovider]['access_token'], $_COOKIE[$authprovider]['user_id'])) { $access_token = $_COOKIE[$authprovider]['access_token']; $user_id = $_COOKIE[$authprovider]['user_id']; if (isset($_COOKIE[$authprovider]['user_email'])) { $user_email = $_COOKIE[$authprovider]['user_email']; } } else { throw new moodle_exception('Someting wrong, maybe expires', 'auth_lenauth'); } } break; case 'yandex': if ($this->_send_oauth_request || !isset($_COOKIE[$authprovider]['access_token'])) { $token_values = json_decode($curl_tokens_values, true); $expires = $token_values['expires_in']; //31536000 = 1 year $access_token = $token_values['access_token']; if (!empty($expires) && !empty($access_token)) { setcookie($authprovider . '[access_token]', $access_token, time() + $expires, '/'); } else { throw new moodle_exception('Can not get access for "access_token" or/and "expires" params after request', 'auth_lenauth'); } } else { if (isset($_COOKIE[$authprovider]['access_token'])) { $access_token = $_COOKIE[$authprovider]['access_token']; } else { throw new moodle_exception('Someting wrong, maybe expires', 'auth_lenauth'); } } break; case 'mailru': if ($this->_send_oauth_request || !isset($_COOKIE[$authprovider]['access_token'])) { $token_values = json_decode($curl_tokens_values, true); $expires = $token_values['expires_in']; //86400 = 24 hours $access_token = $token_values['access_token']; if (!empty($expires) && !empty($access_token)) { setcookie($authprovider . '[access_token]', $access_token, time() + $expires, '/'); } else { //check native errors if exists if (isset($token_values['error'])) { switch ($token_values['error']) { case 'invalid_client': throw new moodle_exception('Mail.RU invalid OAuth settings. Check your Private Key and Secret Key', 'auth_lenauth'); default: throw new moodle_exception('Mail.RU Unknown Error with code: ' . $token_values['error']); } } if (empty($expires) || empty($access_token)) { throw new moodle_exception('Can not get access for "access_token" or/and "expires" params after request', 'auth_lenauth'); } } } else { if (isset($_COOKIE[$authprovider]['access_token'])) { $access_token = $_COOKIE[$authprovider]['access_token']; } else { throw new moodle_exception('Someting wrong, maybe expires', 'auth_lenauth'); } } break; /*case 'ok': $token_values = json_decode( $curl_tokens_values, true ); $access_token = $token_values['access_token']; break;*/ /*case 'ok': $token_values = json_decode( $curl_tokens_values, true ); $access_token = $token_values['access_token']; break;*/ default: throw new moodle_exception('Unknown OAuth Provider', 'auth_lenauth'); } } if (!empty($access_token)) { $queryparams = array(); // array to generate data for final request to get user data $request_api_url = $this->_settings[$authprovider]['request_api_url']; //some services check accounts for verifier, so we will check it too. No unverified accounts, only verified! only hardCORE! $is_verified = true; $image_url = ''; switch ($authprovider) { case 'facebook': $queryparams['access_token'] = $access_token; $curl_response = $curl->get($request_api_url . '?' . $this->_generate_query_data($queryparams)); $curl_final_data = json_decode($curl_response, true); $social_uid = $curl_final_data['id']; $user_email = $curl_final_data['email']; $first_name = $curl_final_data['first_name']; $last_name = $curl_final_data['last_name']; $is_verified = $curl_final_data['verified']; if ($this->_oauth_config->auth_lenauth_retrieve_avatar) { $image_url = 'http://graph.facebook.com/' . $social_uid . '/picture'; } break; /** * @link https://developers.google.com/accounts/docs/OAuth2Login#obtaininguserprofileinformation */ /** * @link https://developers.google.com/accounts/docs/OAuth2Login#obtaininguserprofileinformation */ case 'google': $queryparams['access_token'] = $access_token; $queryparams['alt'] = 'json'; $curl_response = $curl->get($request_api_url . '?' . $this->_generate_query_data($queryparams)); $curl_final_data = json_decode($curl_response, true); if (isset($curl_final_data['error'])) { if (!empty($curl_final_data['error']['errors']) && is_array($curl_final_data['error']['errors'])) { foreach ($curl_final_data['error']['errors'] as $error) { throw new moodle_exception('Native Google error. Message: ' . $error['message'], 'auth_lenauth'); } } else { throw new moodle_exception('Native Google error', 'auth_lenauth'); } } $social_uid = $curl_final_data['id']; $user_email = $curl_final_data['emails'][0]['value']; $first_name = $curl_final_data['name']['givenName']; $last_name = $curl_final_data['name']['familyName']; if ($this->_oauth_config->auth_lenauth_retrieve_avatar) { $image_url = isset($curl_final_data['image']['url']) ? $curl_final_data['image']['url'] : ''; } break; case 'yahoo1': if (!$oauth_verifier) { header('Location: ' . $xoauth_request_auth_url); // yahoo =)) die; } $queryparams1 = array_merge($this->_lenauth_yahoo_request_array($this->_oauth_config->auth_lenauth_yahoo_consumer_secret . '&' . $_COOKIE[$authprovider]['oauth_token_secret']), array('oauth_token' => $access_token, 'oauth_verifier' => $oauth_verifier)); $curl_response_pre = $curl->get($request_api_url . '?' . $this->_generate_query_data($queryparams1)); parse_str($curl_response_pre, $values); $queryparams2 = array_merge($this->_lenauth_yahoo_request_array($this->_oauth_config->auth_lenauth_yahoo_consumer_secret . '&' . $values['oauth_token_secret']), array('oauth_token' => $values['oauth_token'], 'oauth_session_handle' => $values['oauth_session_handle'])); $yet_another = $curl->post($request_api_url . '?' . $this->_generate_query_data($queryparams2)); parse_str($yet_another, $yet_another_values); $params = array('q' => 'SELECT * FROM social.profile where guid="' . $yet_another_values['xoauth_yahoo_guid'] . '"', 'format' => 'json', 'env' => 'http://datatables.org/alltables.env'); $auth_array = array_merge($this->_lenauth_yahoo_request_array($this->_oauth_config->auth_lenauth_yahoo_consumer_secret . '&' . $yet_another_values['oauth_token_secret']), array('realm' => 'yahooapis.com', 'oauth_token' => $yet_another_values['oauth_token'])); $header = ''; foreach ($auth_array as $key => $value) { $header .= ($header === '' ? ' ' : ',') . $this->urlEncodeRfc3986($key) . '="' . $this->urlEncodeRfc3986($value) . '"'; } $curl->setHeader(array('Expect:', 'Accept: application/json', 'Authorization: OAuth ' . $header)); $curl_response = $curl->post($this->_settings[$authprovider]['yql_url'] . '?' . $this->_generate_query_data($params)); $curl_final_data = json_decode($curl_response, true); $social_uid = $curl_final_data['query']['results']['profile']['guid']; $emails = $curl_final_data['query']['results']['profile']['emails']; if (!empty($emails) && is_array($emails)) { foreach ($emails as $email_array) { $user_email = $email_array['handle']; if (isset($email_array['primary'])) { break; } } } $first_name = $curl_final_data['query']['results']['profile']['givenName']; $last_name = $curl_final_data['query']['results']['profile']['familyName']; if ($this->_oauth_config->auth_lenauth_retrieve_avatar) { $image_url = isset($curl_final_data['query']['results']['profile']['image']['imageUrl']) ? $curl_final_data['query']['results']['profile']['image']['imageUrl'] : ''; } break; case 'yahoo2': $request_api_url = 'https://social.yahooapis.com/v1/user/' . $user_id . '/profile?format=json'; $queryparams['access_token'] = $access_token; $now_header = array('Authorization: Bearer ' . $access_token, 'Accept: application/json', 'Content-Type: application/json'); $curl->resetHeader(); $curl->setHeader($now_header); $curl_response = $curl->get($request_api_url, $queryparams); $curl->resetHeader(); $curl_final_data = json_decode($curl_response, true); $social_uid = $curl_final_data['profile']['guid']; $emails = $curl_final_data['profile']['emails']; if (!empty($emails) && is_array($emails)) { foreach ($emails as $email_array) { $user_email = $email_array['handle']; if (isset($email_array['primary'])) { break; } } } $first_name = $curl_final_data['profile']['givenName']; $last_name = $curl_final_data['profile']['familyName']; if ($this->_oauth_config->auth_lenauth_retrieve_avatar) { $image_url = isset($curl_final_data['profile']['image']['imageUrl']) ? $curl_final_data['profile']['image']['imageUrl'] : ''; } break; case 'twitter': if (!$oauth_verifier) { header('Location: ' . $this->_settings[$authprovider]['request_api_url'] . '?' . http_build_query(array('oauth_token' => $access_token))); die; } $queryparams = array_merge($this->_lenauth_twitter_request_array(), array('oauth_verifier' => $oauth_verifier, 'oauth_token' => $access_token, 'oauth_token_secret' => $_COOKIE[$authprovider]['oauth_token_secret'])); $curl_header = $this->_lenauth_set_twitter_header($queryparams, $access_token, $_COOKIE[$authprovider]['oauth_token_secret']); $curl->setHeader($curl_header); $curl_final_data_pre = $curl->post($this->_settings[$authprovider]['token_url'], $queryparams); $json_decoded = json_decode($curl_final_data_pre, true); if (isset($json_decoded['error']) && isset($json_decoded['request'])) { throw new moodle_exception('Native Twitter Error: ' . $json_decoded['error'] . '. For request ' . $json_decoded['request'], 'auth_lenauth'); } parse_str($curl_final_data_pre, $curl_final_data); $social_uid = $curl_final_data['user_id']; if ($this->_oauth_config->auth_lenauth_retrieve_avatar) { $image_url_pre = 'https://twitter.com/' . $curl_final_data['screen_name'] . '/profile_image?size=original'; $image_header = get_headers($image_url_pre, 1); $image_url = $image_header['location']; } break; case 'vk': /** * @link http://vk.com/dev/api_requests */ $queryparams['access_token'] = $access_token; $queryparams['user_id'] = !empty($user_id) ? $user_id : false; $queryparams['v'] = self::$vk_api_version; $curl_response = $curl->post($request_api_url, $this->_generate_query_data($queryparams)); $curl_final_data = json_decode($curl_response, true); //$social_uid = ( isset( $user_id ) ) ? $user_id : $curl_final_data['response'][0]['id']; //dont forget about this $social_uid = $queryparams['user_id']; /** * If user_email is empty, its not so scare, because its second login and */ $user_email = isset($user_email) ? $user_email : false; //hack, because VK has bugs sometimes $first_name = $curl_final_data['response'][0]['first_name']; $last_name = $curl_final_data['response'][0]['last_name']; /** * @link http://vk.com/dev/users.get */ $fields_array = array('avatar' => 'photo_200'); $additional_fields_pre = $curl->get('http://api.vk.com/method/users.get?user_ids=' . $social_uid . '&fields=' . join(',', $fields_array)); $additional_fields = json_decode($additional_fields_pre, true); if ($this->_oauth_config->auth_lenauth_retrieve_avatar) { $image_url = isset($additional_fields['response'][0][$fields_array['avatar']]) ? $additional_fields['response'][0][$fields_array['avatar']] : ''; } break; /** * @link http://api.yandex.ru/oauth/doc/dg/reference/accessing-protected-resource.xml * @link http://api.yandex.ru/login/doc/dg/reference/request.xml */ /** * @link http://api.yandex.ru/oauth/doc/dg/reference/accessing-protected-resource.xml * @link http://api.yandex.ru/login/doc/dg/reference/request.xml */ case 'yandex': $queryparams['format'] = $this->_settings[$authprovider]['format']; $queryparams['oauth_token'] = $access_token; $curl_response = $curl->get($request_api_url . '?' . $this->_generate_query_data($queryparams)); $curl_final_data = json_decode($curl_response, true); $social_uid = $curl_final_data['id']; /** * fix @since 24.12.2014. Thanks for Yandex Tech team guys!! * @link https://tech.yandex.ru/passport/ */ $user_email = $curl_final_data['default_email']; //was $curl_final_data['emails'][0]; - wrong! $first_name = $curl_final_data['first_name']; $last_name = $curl_final_data['last_name']; $nickname = $curl_final_data['display_name']; //for future if ($this->_oauth_config->auth_lenauth_retrieve_avatar) { /** * @link https://tech.yandex.ru/passport/doc/dg/reference/response-docpage/#norights_5 */ $yandex_avatar_size = 'islands-200'; if (isset($curl_final_data['default_avatar_id'])) { $image_url = 'https://avatars.yandex.net/get-yapic/' . $curl_final_data['default_avatar_id'] . '/' . $yandex_avatar_size; } } break; case 'mailru': $queryparams['app_id'] = $params['client_id']; $secret_key = $params['client_secret']; /** * @link http://api.mail.ru/docs/reference/rest/users-getinfo/ */ $queryparams['method'] = 'users.getInfo'; $queryparams['session_key'] = $access_token; $queryparams['secure'] = 1; /** * Additional security from mail.ru * @link http://api.mail.ru/docs/guides/restapi/#sig */ ksort($queryparams); $sig = ''; foreach ($queryparams as $k => $v) { $sig .= "{$k}={$v}"; } $queryparams['sig'] = md5($sig . $secret_key); $curl_response = $curl->post($request_api_url, $this->_generate_query_data($queryparams)); $curl_final_data = json_decode($curl_response, true); $social_uid = $curl_final_data[0]['uid']; $user_email = $curl_final_data[0]['email']; $first_name = $curl_final_data[0]['first_name']; $last_name = $curl_final_data[0]['last_name']; $is_verified = $curl_final_data[0]['is_verified']; $birthday = $curl_final_data[0]['birthday']; //dd.mm.YYYY if ($this->_oauth_config->auth_lenauth_retrieve_avatar) { $image_url = isset($curl_final_data[0]['pic_big']) ? $curl_final_data[0]['pic_big'] : ''; } break; /*case 'ok': $queryparams['access_token'] = $access_token; $queryparams['method'] = 'users.getCurrentUser'; $queryparams['sig'] = md5( 'application_key=' . $this->_oauth_config->ok_public_key . 'method=' . $queryparams['method'] . md5( $queryparams['access_token'] . $this->_oauth_config->ok_secret_key ) ); $queryparams['application_key'] = $this->_oauth_config->ok_public_key; $curl_response = $curl->get( $request_api_url . '?' . $this->_generate_query_data( $queryparams ) ); $curl_final_data = json_decode( $curl_response, true ); $first_name = $curl_final_data['first_name']; $last_name = $curl_final_data['last_name']; $social_uid = $curl_final_data['uid']; break;*/ /*case 'ok': $queryparams['access_token'] = $access_token; $queryparams['method'] = 'users.getCurrentUser'; $queryparams['sig'] = md5( 'application_key=' . $this->_oauth_config->ok_public_key . 'method=' . $queryparams['method'] . md5( $queryparams['access_token'] . $this->_oauth_config->ok_secret_key ) ); $queryparams['application_key'] = $this->_oauth_config->ok_public_key; $curl_response = $curl->get( $request_api_url . '?' . $this->_generate_query_data( $queryparams ) ); $curl_final_data = json_decode( $curl_response, true ); $first_name = $curl_final_data['first_name']; $last_name = $curl_final_data['last_name']; $social_uid = $curl_final_data['uid']; break;*/ default: throw new moodle_exception('Unknown OAuth Provider', 'auth_lenauth'); } /** * Check for email returned by webservice. If exist - check for user with this email in Moodle Database */ if (!empty($curl_final_data)) { if (!empty($social_uid)) { if ($is_verified) { if (!empty($user_email)) { if ($err = email_is_not_allowed($user_email)) { throw new moodle_exception($err, 'auth_lenauth'); } $user_lenauth = $DB->get_record('user', array('email' => $user_email, 'deleted' => 0, 'mnethostid' => $CFG->mnet_localhost_id)); } else { if (empty($user_lenauth)) { $user_lenauth = $this->_lenauth_get_userdata_by_social_id($social_uid); } /*if ( empty( $user_lenauth ) ) { $user_lenauth = $DB->get_record('user', array('username' => $username, 'deleted' => 0, 'mnethostid' => $CFG->mnet_localhost_id)); }*/ } } else { throw new moodle_exception('Your social account is not verified', 'auth_lenauth'); } } else { throw new moodle_exception('Empty Social UID', 'auth_lenauth'); } } else { /** * addon @since 24.12.2014 * I forgot about clear $_COOKIE, thanks again for Yandex Tech Team guys!!! */ @setcookie($authprovider, null, time() - 3600); throw new moodle_exception('Final request returns nothing', 'auth_lenauth'); } $last_user_number = intval($this->_oauth_config->auth_lenauth_last_user_number); $last_user_number = empty($last_user_number) ? 1 : $last_user_number + 1; //$username = $this->_oauth_config->auth_lenauth_user_prefix . $last_user_number; //@todo /** * If user with email from webservice not exists, we will create an account */ if (empty($user_lenauth)) { $username = $this->_oauth_config->auth_lenauth_user_prefix . $last_user_number; //check for username exists in DB $user_lenauth_check = $DB->get_record('user', array('username' => $username)); $i_check = 0; while (!empty($user_lenauth_check)) { $user_lenauth_check = $user_lenauth_check + 1; $username = $this->_oauth_config->auth_lenauth_user_prefix . $last_user_number; $user_lenauth_check = $DB->get_record('user', array('username' => $username)); $i_check++; if ($i_check > 20) { throw new moodle_exception('Something wrong with usernames of LenAuth users. Limit of 20 queries is out. Check last mdl_user table of Moodle', 'auth_lenauth'); } } // create user HERE $user_lenauth = create_user_record($username, '', 'lenauth'); /** * User exists... */ } else { $username = $user_lenauth->username; } set_config('auth_lenauth_last_user_number', $last_user_number, 'auth/lenauth'); if (!empty($social_uid)) { $user_social_uid_custom_field = new stdClass(); $user_social_uid_custom_field->userid = $user_lenauth->id; $user_social_uid_custom_field->fieldid = $this->_field_id; $user_social_uid_custom_field->data = $social_uid; if (!$DB->record_exists('user_info_data', array('userid' => $user_lenauth->id, 'fieldid' => $this->_field_id))) { $DB->insert_record('user_info_data', $user_social_uid_custom_field); } else { $record = $DB->get_record('user_info_data', array('userid' => $user_lenauth->id, 'fieldid' => $this->_field_id)); $user_social_uid_custom_field->id = $record->id; $DB->update_record('user_info_data', $user_social_uid_custom_field); } } //add_to_log( SITEID, 'auth_lenauth', '', '', $username . '/' . $user_email . '/' . $userid ); // complete Authenticate user authenticate_user_login($username, null); // fill $newuser object with response data from webservices $newuser = new stdClass(); if (!empty($user_email)) { $newuser->email = $user_email; } if (!empty($first_name)) { $newuser->firstname = $first_name; } if (!empty($last_name)) { $newuser->lastname = $last_name; } if (!empty($this->_oauth_config->auth_lenauth_default_country)) { $newuser->country = $this->_oauth_config->auth_lenauth_default_country; } if ($user_lenauth) { // update user record if (!empty($newuser)) { $newuser->id = $user_lenauth->id; /*require_once( $CFG->libdir . '/gdlib.php' ); $fs = get_file_storage(); $file_obj = $fs->create_file_from_url( array( 'contextid' => context_user::instance( $newuser->id, MUST_EXIST )->id, 'component' => 'user', 'filearea' => 'icon', 'itemid' => 0, 'filepath' => '/', 'source' => '', 'filename' => 'f' . $newuser->id . '.' . $ext ), $image_url ); //$newuser->picture = $file_obj->get_id();*/ $user_lenauth = (object) array_merge((array) $user_lenauth, (array) $newuser); $DB->update_record('user', $user_lenauth); if ($this->_oauth_config->auth_lenauth_retrieve_avatar) { //processing user avatar from social webservice if (!empty($image_url) && intval($user_lenauth->picture) === 0) { $image_header = get_headers($image_url, 1); if (isset($image_header['Content-Type']) && is_string($image_header['Content-Type']) && in_array($image_header['Content-Type'], array_keys(self::$_allowed_icons_types))) { $mime = $image_header['Content-Type']; } else { if (isset($image_header['Content-Type'][0]) && is_string($image_header['Content-Type'][0]) && in_array($image_header['Content-Type'][0], array_keys(self::$_allowed_icons_types))) { $mime = $image_header['Content-Type'][0]; } } $ext = $this->_lenauth_get_image_extension_from_mime($mime); if ($ext) { //create temp file $tempfilename = substr(microtime(), 0, 10) . '.tmp'; $templfolder = $CFG->tempdir . '/filestorage'; if (!file_exists($templfolder)) { mkdir($templfolder, $CFG->directorypermissions); } @chmod($templfolder, 0777); $tempfile = $templfolder . '/' . $tempfilename; if (copy($image_url, $tempfile)) { require_once $CFG->libdir . '/gdlib.php'; $usericonid = process_new_icon(context_user::instance($newuser->id, MUST_EXIST), 'user', 'icon', 0, $tempfile); if ($usericonid) { $DB->set_field('user', 'picture', $usericonid, array('id' => $newuser->id)); } unset($tempfile); } @chmod($templfolder, $CFG->directorypermissions); } } } } complete_user_login($user_lenauth); // complete user login // Redirection $urltogo = $CFG->wwwroot; if (user_not_fully_set_up($user_lenauth)) { $urltogo = $CFG->wwwroot . '/user/edit.php'; } else { if (isset($SESSION->wantsurl) && strpos($SESSION->wantsurl, $CFG->wwwroot) === 0) { $urltogo = $SESSION->wantsurl; unset($SESSION->wantsurl); } else { unset($SESSION->wantsurl); } } } redirect($urltogo); } else { throw new moodle_exception('Could not get access to access token. Check your App Settings', 'auth_lenauth'); } } }
/** * Send an API request to Google. * * This method overwrite the parent one so that the Google SDK will use our class * curl to proceed with the requests. This allows us to have control over the * proxy parameters and other stuffs. * * Note that the caching support of the Google SDK has been removed from this function. * * @param Google_HttpRequest $request the http request to be executed * @return Google_HttpRequest http request with the response http code, response * headers and response body filled in * @throws Google_IOException on curl or IO error */ public function makeRequest(Google_HttpRequest $request) { if (array_key_exists($request->getRequestMethod(), self::$ENTITY_HTTP_METHODS)) { $request = $this->processEntityRequest($request); } $curl = new curl(); $curl->setopt($this->curlParams); $curl->setopt(array('CURLOPT_URL' => $request->getUrl())); $requestHeaders = $request->getRequestHeaders(); if ($requestHeaders && is_array($requestHeaders)) { $parsed = array(); foreach ($requestHeaders as $k => $v) { $parsed[] = "{$k}: {$v}"; } $curl->setHeader($parsed); } $curl->setopt(array('CURLOPT_CUSTOMREQUEST' => $request->getRequestMethod(), 'CURLOPT_USERAGENT' => $request->getUserAgent())); $respdata = $this->do_request($curl, $request); // Retry if certificates are missing. if ($curl->get_errno() == CURLE_SSL_CACERT) { error_log('SSL certificate problem, verify that the CA cert is OK.' . ' Retrying with the CA cert bundle from google-api-php-client.'); $curl->setopt(array('CURLOPT_CAINFO' => dirname(__FILE__) . '/io/cacerts.pem')); $respdata = $this->do_request($curl, $request); } $infos = $curl->get_info(); $respheadersize = $infos['header_size']; $resphttpcode = (int) $infos['http_code']; $curlerrornum = $curl->get_errno(); $curlerror = $curl->error; if ($curlerrornum != CURLE_OK) { throw new Google_IOException("HTTP Error: ({$resphttpcode}) {$curlerror}"); } // Parse out the raw response into usable bits. list($responseHeaders, $responseBody) = self::parseHttpResponse($respdata, $respheadersize); // Fill in the apiHttpRequest with the response values. $request->setResponseHttpCode($resphttpcode); $request->setResponseHeaders($responseHeaders); $request->setResponseBody($responseBody); return $request; }
/** * $options['username'] and $options['password'] must be * given, we will use them to obtain a valid auth_token * To get a token, you should use following code: * * <code> * $box = new boxclient('dmls97d8j3i9tn7av8y71m9eb55vrtj4'); * Get a ticket * $t = $box->getTicket(); * $box->getAuthToken($t['ticket'], array( * 'username'=>'*****@*****.**', * 'password'=>'xxx')); * </code> * * @param string $ticket * @param string $username * @param string $password * @return mixed */ function getAuthToken($ticket, $username, $password) { $c = new curl(array('debug' => $this->debug)); $c->setopt(array('CURLOPT_FOLLOWLOCATION' => 0)); $param = array('login_form1' => '', 'login' => $username, 'password' => $password, 'dologin' => 1, '__login' => 1); try { $ret = $c->post('http://www.box.net/api/1.0/auth/' . $ticket, $param); } catch (moodle_exception $e) { $this->setError(0, 'connection time-out or invalid url'); return false; } $header = $c->getResponse(); if (empty($header['location'])) { throw new repository_exception('invalidpassword', 'repository_boxnet'); } $location = $header['location']; preg_match('#auth_token=(.*)$#i', $location, $matches); $auth_token = $matches[1]; if (!empty($auth_token)) { $this->auth_token = $auth_token; return $auth_token; } else { throw new repository_exception('invalidtoken', 'repository_boxnet'); } }
function bigbluebuttonbn_wrap_simplexml_load_file($url) { if (extension_loaded('curl')) { $c = new curl(); $c->setopt(array("SSL_VERIFYPEER" => true)); $response = $c->get($url); if ($response) { $previous = libxml_use_internal_errors(true); try { $xml = new SimpleXMLElement($response, LIBXML_NOCDATA); return $xml; } catch (Exception $e) { libxml_use_internal_errors($previous); error_log("The XML response is not correct on wrap_simplexml_load_file: " . $e->getMessage()); return NULL; } } else { error_log("No response on wrap_simplexml_load_file"); return NULL; } } else { $previous = libxml_use_internal_errors(true); try { $xml = simplexml_load_file($url, 'SimpleXMLElement', LIBXML_NOCDATA); return $xml; } catch (Exception $e) { libxml_use_internal_errors($previous); return NULL; } } }
error("errorupdating"); } } else { $configfield = new stdClass(); $configfield->value = $value; $configfield->plugin = 'plagiarism'; $configfield->name = $field; if (!$DB->insert_record('config_plugins', $configfield)) { error("errorinserting"); } } } } cache_helper::invalidate_by_definition('core', 'config', array(), 'plagiarism'); $c = new curl(array('proxy' => true)); $c->setopt(array('CURLOPT_HTTPAUTH' => CURLAUTH_BASIC, 'CURLOPT_USERPWD' => $data->urkund_username . ":" . $data->urkund_password)); $html = $c->post($data->urkund_api); $response = $c->getResponse(); // Now check to see if username/password is correct. - this check could probably be improved further. if ($c->info['http_code'] == '401') { // Disable urkund as this config isn't correct. $rec = $DB->get_record('config_plugins', array('name' => 'urkund_use', 'plugin' => 'plagiarism')); $rec->value = 0; $DB->update_record('config_plugins', $rec); echo $OUTPUT->notification(get_string('savedconfigfailed', 'plagiarism_urkund')); } else { echo $OUTPUT->notification(get_string('savedconfigsuccess', 'plagiarism_urkund'), 'notifysuccess'); } } $invalidhandlers = urkund_check_event_handlers(); if (!empty($invalidhandlers)) {
/** * Check for the availability of a resource by URL. * * Check is performed using an HTTP HEAD call. * * @param $url string A valid URL * @return bool|string True if no issue is found. The error string message, otherwise */ function scorm_check_url($url) { $curl = new curl(); if (!ini_get('open_basedir') and !ini_get('safe_mode')) { // Same options as in {@link download_file_content()}, used in {@link scorm_parse_scorm()}. $curl->setopt(array('CURLOPT_FOLLOWLOCATION' => true, 'CURLOPT_MAXREDIRS' => 5)); } $cmsg = $curl->head($url); $info = $curl->get_info(); if (empty($info['http_code']) || $info['http_code'] != 200) { return get_string('invalidurlhttpcheck', 'scorm', array('cmsg' => $cmsg)); } return true; }
<?php include_once "class.curl.php"; // // Create a new instance of the curl class and point it // at the page to be fetched. // $c = new curl("http://www.csworks.com/development/dumpState.php"); // // By default, curl doesn't follow redirections and this // page may or may not be available via redirection. // $c->setopt(CURLOPT_FOLLOWLOCATION, true); $c->setopt(CURLOPT_POST, true); $theFields = array('foo' => '1', 'bar' => array(2, 3, 4), 'baz' => array(array(5, 6), array(7, 8))); $c->setopt(CURLOPT_POSTFIELDS, $c->asPostString($theFields)); // // By default, the curl class expects to return data to // the caller. // echo $c->exec(); // // Check to see if there was an error and, if so, print // the associated error message. // if ($theError = $c->hasError()) { echo $theError; } // // Done with the cURL, so get rid of the cURL related resources. //