Exemplo n.º 1
0
 function getPublicKeyFromServer($server, $email)
 {
     /* refactor to 
     		$command = "gpg --keyserver ".escapeshellarg($server)." --search-keys ".escapeshellarg($email)."";
     		echo "$command\n\n";
     		
     		//execute the gnupg command
     		exec($command, $result);
     		*/
     $curl = new curl();
     // get Fingerprint
     $data = $curl->get("http://" . $server . ":11371/pks/lookup?search=" . urlencode($email) . "&op=index&fingerprint=on&exact=on");
     $data = $data['FILE'];
     preg_match_all("/<pre>([\\s\\S]*?)<\\/pre>/", $data, $matches);
     //$pub = $matches[1][1];
     preg_match_all("/<a href=\"(.*?)\">(\\w*)<\\/a>/", $matches[1][1], $matches);
     $url = $matches[1][0];
     $keyID = $matches[2][0];
     // get Public Key
     $data = $curl->get("http://" . $server . ":11371" . $url);
     $data = $data['FILE'];
     preg_match_all("/<pre>([\\s\\S]*?)<\\/pre>/", $data, $matches);
     $pub_key = trim($matches[1][0]);
     return array("keyID" => $keyID, "public_key" => $pub_key);
 }
Exemplo n.º 2
0
 function definition()
 {
     global $DB, $CFG, $COURSE;
     $mform =& $this->_form;
     $mform->addElement('textarea', 'querysql', get_string('querysql', 'block_configurable_reports'), 'rows="35" cols="80"');
     $mform->addRule('querysql', get_string('required'), 'required', null, 'client');
     $mform->setType('querysql', PARAM_RAW);
     $mform->addElement('hidden', 'courseid', $COURSE->id);
     $mform->setType('courseid', PARAM_INT);
     $this->add_action_buttons();
     $mform->addElement('static', 'note', '', get_string('listofsqlreports', 'block_configurable_reports'));
     if ($userandrepo = get_config('block_configurable_reports', 'sharedsqlrepository')) {
         $c = new curl();
         $res = $c->get("https://api.github.com/repos/{$userandrepo}/contents/");
         $res = json_decode($res);
         if (is_array($res)) {
             $reportcategories = array(get_string('choose'));
             foreach ($res as $item) {
                 if ($item->type == 'dir') {
                     $reportcategories[$item->path] = $item->path;
                 }
             }
             $mform->addElement('select', 'reportcategories', get_string('reportcategories', 'block_configurable_reports'), $reportcategories, array('onchange' => 'M.block_configurable_reports.onchange_reportcategories(this,"' . sesskey() . '")'));
             $mform->addElement('select', 'reportsincategory', get_string('reportsincategory', 'block_configurable_reports'), $reportcategories, array('onchange' => 'M.block_configurable_reports.onchange_reportsincategory(this,"' . sesskey() . '")'));
             $mform->addElement('textarea', 'remotequerysql', get_string('remotequerysql', 'block_configurable_reports'), 'rows="15" cols="90"');
         }
     }
     //$this->add_action_buttons();
 }
 /**
  * Makes a GET petition using the curl instance
  * 
  * @param string $uri
  * @return array
  */
 private function get($uri)
 {
     $response = $this->client->get(self::APIBASE . $uri);
     if ($response) {
         return json_decode($response);
     }
 }
 /**
  * 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);
         }
     }
 }
Exemplo n.º 5
0
 /**
  * ip地址查询
  */
 public function ip()
 {
     $ip = $this->post('ip');
     if (!$ip) {
         return;
     }
     $result = $ip_address = array();
     // tool.lu
     $toollu = curl::post('http://tool.lu/netcard/ajax.html', array('ip' => $ip));
     $toollu = json_decode($toollu, true);
     $result['tool.lu'] = trim($toollu['text'][2]);
     $result['纯真数据库'] = trim($toollu['text'][1]);
     // 站长工具
     $chinaz = curl::post('http://ip.chinaz.com', array('ip' => $ip));
     $chinaz = trim(preg_replace('/<.+?>/', '', $chinaz));
     $chinaz = explode('查询结果', $chinaz);
     if ($chinaz) {
         unset($chinaz[0]);
         $size = intval(count($chinaz));
         $chinaz[$size] = trim(substr($chinaz[$size], 0, strpos($chinaz[$size], 'document')));
         $address = '';
         foreach ($chinaz as $c) {
             $c = explode('==>>', $c);
             $ip_address_ = explode(':', trim($c[0]));
             $ip_address[] = trim($ip_address_[1]);
             $tmp_arr = explode("\r\n", trim($c[2]));
             $address .= trim($tmp_arr[0]) . '  ';
         }
         $result['站长工具'] = trim($address);
     }
     // 淘宝
     if ($ip_address) {
         $taobao = curl::get('http://ip.taobao.com/service/getIpInfo.php', array('ip' => $ip_address[0]));
         $taobao = json_decode($taobao, true);
         if (intval($taobao['code']) === 0) {
             $taobao = $taobao['data'];
             $result['淘宝'] = $taobao['country'] . '|' . $taobao['area'] . '|' . $taobao['region'] . '|' . $taobao['city'] . '|' . $taobao['isp'];
         }
     }
     // ipip.net
     if ($ip_address) {
         $ipip = curl::get('http://freeapi.ipip.net/' . $ip_address[0]);
         $ipip = json_decode($ipip, true);
         if (is_array($ipip)) {
             $ipipstr = '';
             foreach ($ipip as $str) {
                 $str = trim($str);
                 if (empty($str)) {
                     continue;
                 }
                 $ipipstr .= $str . ' ';
             }
             $result['ipip.net'] = $ipipstr;
         }
     }
     view::assign('input', $ip);
     view::assign('ip', $ip_address);
     view::assign('result', $result);
 }
Exemplo n.º 6
0
 private function _get_collection($keyword)
 {
     global $OUTPUT;
     $list = array();
     $this->api = 'http://www.merlot.org/merlot/materials.rest?keywords=' . urlencode($keyword) . '&licenseKey=' . $this->licensekey;
     $c = new curl(array('cache' => true, 'module_cache' => 'repository'));
     $content = $c->get($this->api);
     $xml = simplexml_load_string($content);
     foreach ($xml->results->material as $entry) {
         $list[] = array('title' => (string) $entry->title, 'thumbnail' => $OUTPUT->pix_url('f/unknown-32')->out(false), 'date' => userdate((int) $entry->creationDate), 'size' => '', 'source' => (string) $entry->URL);
     }
     return $list;
 }
Exemplo n.º 7
0
 /**
  * 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;
 }
Exemplo n.º 8
0
 /**
  * Private method to get youtube search results
  * @param string $keyword
  * @param int $start
  * @param int $max max results
  * @param string $sort
  * @return array
  */
 private function _get_collection($keyword, $start, $max, $sort)
 {
     $list = array();
     $this->feed_url = 'http://gdata.youtube.com/feeds/api/videos?q=' . urlencode($keyword) . '&format=5&start-index=' . $start . '&max-results=' . $max . '&orderby=' . $sort;
     $c = new curl(array('cache' => true, 'module_cache' => 'repository'));
     $content = $c->get($this->feed_url);
     $xml = simplexml_load_string($content);
     $media = $xml->entry->children('http://search.yahoo.com/mrss/');
     $links = $xml->children('http://www.w3.org/2005/Atom');
     foreach ($xml->entry as $entry) {
         $media = $entry->children('http://search.yahoo.com/mrss/');
         $title = $media->group->title;
         $attrs = $media->group->thumbnail[2]->attributes();
         $thumbnail = $attrs['url'];
         $arr = explode('/', $entry->id);
         $id = $arr[count($arr) - 1];
         $source = 'http://www.youtube.com/v/' . $id . '#' . $title;
         $list[] = array('title' => (string) $title, 'thumbnail' => (string) $attrs['url'], 'thumbnail_width' => 150, 'thumbnail_height' => 120, 'size' => '', 'date' => '', 'source' => $source);
     }
     return $list;
 }
Exemplo n.º 9
0
 /**
  * Checks if the schema existing fields are properly set, triggers an exception otherwise.
  *
  * @throws \moodle_exception
  * @param array $fields
  * @param bool $requireexisting Require the fields to exist, otherwise exception.
  * @return void
  */
 protected function validate_fields(&$fields, $requireexisting = false)
 {
     global $CFG;
     foreach ($fields as $fieldname => $data) {
         $url = $this->engine->get_connection_url('/schema/fields/' . $fieldname);
         $results = $this->curl->get($url);
         if ($this->curl->error) {
             throw new \moodle_exception('errorcreatingschema', 'search_solr', '', $this->curl->error);
         }
         if (!$results) {
             throw new \moodle_exception('errorcreatingschema', 'search_solr', '', get_string('nodatafromserver', 'search_solr'));
         }
         $results = json_decode($results);
         if ($requireexisting && !empty($results->error) && $results->error->code === 404) {
             $a = new \stdClass();
             $a->fieldname = $fieldname;
             $a->setupurl = $CFG->wwwroot . '/search/engine/solr/setup_schema.php';
             throw new \moodle_exception('errorvalidatingschema', 'search_solr', '', $a);
         }
         // The field should not exist so we only accept 404 errors.
         if (empty($results->error) || !empty($results->error) && $results->error->code !== 404) {
             if (!empty($results->error)) {
                 throw new \moodle_exception('errorcreatingschema', 'search_solr', '', $results->error->msg);
             } else {
                 // All these field attributes are set when fields are added through this script and should
                 // be returned and match the defined field's values.
                 if (empty($results->field) || !isset($results->field->type) || !isset($results->field->multiValued) || !isset($results->field->indexed) || !isset($results->field->stored)) {
                     throw new \moodle_exception('errorcreatingschema', 'search_solr', '', get_string('schemafieldautocreated', 'search_solr', $fieldname));
                 } else {
                     if ($results->field->type !== $data['type'] && ($data['type'] !== 'text' || $results->field->type !== 'text_general') || $results->field->multiValued !== false || $results->field->indexed !== $data['indexed'] || $results->field->stored !== $data['stored']) {
                         throw new \moodle_exception('errorcreatingschema', 'search_solr', '', get_string('schemafieldautocreated', 'search_solr', $fieldname));
                     } else {
                         // The field already exists and it is properly defined, no need to create it.
                         unset($fields[$fieldname]);
                     }
                 }
             }
         }
     }
 }
Exemplo n.º 10
0
 /**
  * Request token for authentication
  * This is the first step to use OAuth, it will return oauth_token and oauth_token_secret
  * @return array
  */
 public function request_token()
 {
     $this->sign_secret = $this->consumer_secret . '&';
     $params = $this->prepare_oauth_parameters($this->request_token_api, array(), 'GET');
     $content = $this->http->get($this->request_token_api, $params, $this->http_options);
     // Including:
     //     oauth_token
     //     oauth_token_secret
     $result = $this->parse_result($content);
     if (empty($result['oauth_token'])) {
         throw new moodle_exception('Error while requesting an oauth token');
     }
     // build oauth authrize url
     if (!empty($this->oauth_callback)) {
         // url must be rawurlencode
         $result['authorize_url'] = $this->authorize_url . '?oauth_token=' . $result['oauth_token'] . '&oauth_callback=' . rawurlencode($this->oauth_callback->out(false));
     } else {
         // no callback
         $result['authorize_url'] = $this->authorize_url . '?oauth_token=' . $result['oauth_token'];
     }
     return $result;
 }
Exemplo n.º 11
0
 public function curl_request($action, $collection = null)
 {
     $curl = new curl();
     switch ($action) {
         case 'user':
             $url = $this->backpack . "/displayer/convert/email";
             $param = array('email' => $this->email);
             break;
         case 'groups':
             $url = $this->backpack . '/displayer/' . $this->backpackuid . '/groups.json';
             break;
         case 'badges':
             $url = $this->backpack . '/displayer/' . $this->backpackuid . '/group/' . $collection . '.json';
             break;
     }
     $options = array('FRESH_CONNECT' => true, 'RETURNTRANSFER' => true, 'FORBID_REUSE' => true, 'HEADER' => 0, 'HTTPHEADER' => array('Expect:'), 'CONNECTTIMEOUT' => 3);
     if ($action == 'user') {
         $out = $curl->post($url, $param, $options);
     } else {
         $out = $curl->get($url, array(), $options);
     }
     return json_decode($out);
 }
Exemplo n.º 12
0
 /**
  * Send the request via our curl object.
  *
  * @param curl $curl prepared curl object.
  * @param Google_HttpRequest $request The request.
  * @return string result of the request.
  */
 private function do_request($curl, $request)
 {
     $url = $request->getUrl();
     $method = $request->getRequestMethod();
     switch (strtoupper($method)) {
         case 'POST':
             $ret = $curl->post($url, $request->getPostBody());
             break;
         case 'GET':
             $ret = $curl->get($url);
             break;
         case 'HEAD':
             $ret = $curl->head($url);
             break;
         case 'PUT':
             $ret = $curl->put($url);
             break;
         default:
             throw new coding_exception('Unknown request type: ' . $method);
             break;
     }
     return $ret;
 }
Exemplo n.º 13
0
 /**
  * Authentication hook - is called every time user hit the login page
  * The code is run only if the param code is mentionned.
  */
 public function loginpage_hook()
 {
     global $USER, $SESSION, $CFG, $DB;
     // Check the Google authorization code.
     $authorizationcode = optional_param('code', '', PARAM_TEXT);
     if (!empty($authorizationcode)) {
         $authprovider = required_param('authprovider', PARAM_ALPHANUMEXT);
         require_once $CFG->dirroot . '/auth/googleoauth2/classes/provider/' . $authprovider . '.php';
         $providerclassname = 'provideroauth2' . $authprovider;
         $provider = new $providerclassname();
         // Try to get an access token (using the authorization code grant).
         $token = $provider->getAccessToken('authorization_code', ['code' => $authorizationcode]);
         $accesstoken = $token->accessToken;
         $refreshtoken = $token->refreshToken;
         $tokenexpires = $token->expires;
         // With access token request by curl the email address.
         if (!empty($accesstoken)) {
             try {
                 // We got an access token, let's now get the user's details.
                 $userdetails = $provider->getUserDetails($token);
                 // Use these details to create a new profile.
                 switch ($authprovider) {
                     case 'battlenet':
                         // Battlenet as no email notion.
                         // TODO: need to check the idp table for matching user and request user to add his email.
                         // TODO: It will be similar logic for twitter.
                         $useremail = $userdetails->id . '@fakebattle.net';
                         break;
                     case 'github':
                         $useremails = $provider->getUserEmails($token);
                         // Going to try to find someone with a similar email using googleoauth2 auth.
                         $fallbackuseremail = '';
                         foreach ($useremails as $githubuseremail) {
                             if ($githubuseremail->verified) {
                                 if ($DB->record_exists('user', array('auth' => 'googleoauth2', 'email' => $githubuseremail->email))) {
                                     $useremail = $githubuseremail->email;
                                 }
                                 $fallbackuseremail = $githubuseremail->email;
                             }
                         }
                         // If we didn't find anyone then we take a verified email address.
                         if (empty($useremail)) {
                             $useremail = $fallbackuseremail;
                         }
                         break;
                     case 'vk':
                         // VK doesn't return the email address?
                         if ($userdetails->uid) {
                             $useremail = 'id' . $userdetails->uid . '@vkmessenger.com';
                         }
                         break;
                     default:
                         $useremail = $userdetails->email;
                         break;
                 }
                 $verified = 1;
             } catch (Exception $e) {
                 // Failed to get user details.
                 throw new moodle_exception('faileduserdetails', 'auth_googleoauth2');
             }
             // Throw an error if the email address is not verified.
             if (!$verified) {
                 throw new moodle_exception('emailaddressmustbeverified', 'auth_googleoauth2');
             }
             // Prohibit login if email belongs to the prohibited domain.
             if ($err = email_is_not_allowed($useremail)) {
                 throw new moodle_exception($err, 'auth_googleoauth2');
             }
             // If email not existing in user database then create a new username (userX).
             if (empty($useremail) or $useremail != clean_param($useremail, PARAM_EMAIL)) {
                 throw new moodle_exception('couldnotgetuseremail', 'auth_googleoauth2');
                 // TODO: display a link for people to retry.
             }
             // Get the user.
             // Don't bother with auth = googleoauth2 because authenticate_user_login() will fail it if it's not 'googleoauth2'.
             $user = $DB->get_record('user', array('email' => $useremail, 'deleted' => 0, 'mnethostid' => $CFG->mnet_localhost_id));
             // Create the user if it doesn't exist.
             if (empty($user)) {
                 // Deny login if setting "Prevent account creation when authenticating" is on.
                 if ($CFG->authpreventaccountcreation) {
                     throw new moodle_exception("noaccountyet", "auth_googleoauth2");
                 }
                 // Get following incremented username.
                 $googleuserprefix = core_text::strtolower(get_config('auth/googleoauth2', 'googleuserprefix'));
                 $lastusernumber = get_config('auth/googleoauth2', 'lastusernumber');
                 $lastusernumber = empty($lastusernumber) ? 1 : $lastusernumber + 1;
                 // Check the user doesn't exist.
                 $nextuser = $DB->record_exists('user', array('username' => $googleuserprefix . $lastusernumber));
                 while ($nextuser) {
                     $lastusernumber++;
                     $nextuser = $DB->record_exists('user', array('username' => $googleuserprefix . $lastusernumber));
                 }
                 set_config('lastusernumber', $lastusernumber, 'auth/googleoauth2');
                 $username = $googleuserprefix . $lastusernumber;
                 // Retrieve more information from the provider.
                 $newuser = new stdClass();
                 $newuser->email = $useremail;
                 switch ($authprovider) {
                     case 'battlenet':
                         // Battlenet as no firstname/lastname notion.
                         $newuser->firstname = $userdetails->display_name;
                         $newuser->lastname = '[' . $userdetails->clan_tag . ']';
                         break;
                     case 'github':
                     case 'dropbox':
                         // As Github/Dropbox doesn't provide firstname/lastname, we'll split the name at the first whitespace.
                         $githubusername = explode(' ', $userdetails->name, 2);
                         $newuser->firstname = $githubusername[0];
                         $newuser->lastname = $githubusername[1];
                         break;
                     default:
                         $newuser->firstname = $userdetails->firstName;
                         $newuser->lastname = $userdetails->lastName;
                         break;
                 }
                 // Some providers allow empty firstname and lastname.
                 if (empty($newuser->firstname)) {
                     $newuser->firstname = get_string('unknownfirstname', 'auth_googleoauth2');
                 }
                 if (empty($newuser->lastname)) {
                     $newuser->lastname = get_string('unknownlastname', 'auth_googleoauth2');
                 }
                 // Retrieve country and city if the provider failed to give it.
                 if (!isset($newuser->country) or !isset($newuser->city)) {
                     $googleipinfodbkey = get_config('auth/googleoauth2', 'googleipinfodbkey');
                     if (!empty($googleipinfodbkey)) {
                         require_once $CFG->libdir . '/filelib.php';
                         $curl = new curl();
                         $locationdata = $curl->get('http://api.ipinfodb.com/v3/ip-city/?key=' . $googleipinfodbkey . '&ip=' . getremoteaddr() . '&format=json');
                         $locationdata = json_decode($locationdata);
                     }
                     if (!empty($locationdata)) {
                         // TODO: check that countryCode does match the Moodle country code.
                         $newuser->country = isset($newuser->country) ? isset($newuser->country) : $locationdata->countryCode;
                         $newuser->city = isset($newuser->city) ? isset($newuser->city) : $locationdata->cityName;
                     }
                 }
                 create_user_record($username, '', 'googleoauth2');
             } else {
                 $username = $user->username;
             }
             // Authenticate the user.
             // TODO: delete this log later.
             require_once $CFG->dirroot . '/auth/googleoauth2/lib.php';
             $userid = empty($user) ? 'new user' : $user->id;
             oauth_add_to_log(SITEID, 'auth_googleoauth2', '', '', $username . '/' . $useremail . '/' . $userid);
             $user = authenticate_user_login($username, null);
             if ($user) {
                 // Set a cookie to remember what auth provider was selected.
                 setcookie('MOODLEGOOGLEOAUTH2_' . $CFG->sessioncookie, $authprovider, time() + DAYSECS * 60, $CFG->sessioncookiepath, $CFG->sessioncookiedomain, $CFG->cookiesecure, $CFG->cookiehttponly);
                 // Prefill more user information if new user.
                 if (!empty($newuser)) {
                     $newuser->id = $user->id;
                     $DB->update_record('user', $newuser);
                     $user = (object) array_merge((array) $user, (array) $newuser);
                 }
                 complete_user_login($user);
                 // Let's save/update the access token for this user.
                 $cansaveaccesstoken = get_config('auth/googleoauth2', 'saveaccesstoken');
                 if (!empty($cansaveaccesstoken)) {
                     $existingaccesstoken = $DB->get_record('auth_googleoauth2_user_idps', array('userid' => $user->id, 'provider' => $authprovider));
                     if (empty($existingaccesstoken)) {
                         $accesstokenrow = new stdClass();
                         $accesstokenrow->userid = $user->id;
                         switch ($authprovider) {
                             case 'battlenet':
                                 $accesstokenrow->provideruserid = $userdetails->id;
                                 break;
                             default:
                                 $accesstokenrow->provideruserid = $userdetails->uid;
                                 break;
                         }
                         $accesstokenrow->provider = $authprovider;
                         $accesstokenrow->accesstoken = $accesstoken;
                         $accesstokenrow->refreshtoken = $refreshtoken;
                         $accesstokenrow->expires = $tokenexpires;
                         $DB->insert_record('auth_googleoauth2_user_idps', $accesstokenrow);
                     } else {
                         $existingaccesstoken->accesstoken = $accesstoken;
                         $DB->update_record('auth_googleoauth2_user_idps', $existingaccesstoken);
                     }
                 }
                 // Check if the user picture is the default and retrieve the provider picture.
                 if (empty($user->picture)) {
                     switch ($authprovider) {
                         case 'battlenet':
                             require_once $CFG->libdir . '/filelib.php';
                             require_once $CFG->libdir . '/gdlib.php';
                             $imagefilename = $CFG->tempdir . '/googleoauth2-portrait-' . $user->id;
                             $imagecontents = download_file_content($userdetails->portrait_url);
                             file_put_contents($imagefilename, $imagecontents);
                             if ($newrev = process_new_icon(context_user::instance($user->id), 'user', 'icon', 0, $imagefilename)) {
                                 $DB->set_field('user', 'picture', $newrev, array('id' => $user->id));
                             }
                             unlink($imagefilename);
                             break;
                         default:
                             // TODO retrieve other provider profile pictures.
                             break;
                     }
                 }
                 // Create event for authenticated user.
                 $event = \auth_googleoauth2\event\user_loggedin::create(array('context' => context_system::instance(), 'objectid' => $user->id, 'relateduserid' => $user->id, 'other' => array('accesstoken' => $accesstoken)));
                 $event->trigger();
                 // Redirection.
                 if (user_not_fully_set_up($USER)) {
                     $urltogo = $CFG->wwwroot . '/user/edit.php';
                     // We don't delete $SESSION->wantsurl yet, so we get there later.
                 } else {
                     if (isset($SESSION->wantsurl) and strpos($SESSION->wantsurl, $CFG->wwwroot) === 0) {
                         $urltogo = $SESSION->wantsurl;
                         // Because it's an address in this site.
                         unset($SESSION->wantsurl);
                     } else {
                         // No wantsurl stored or external - go to homepage.
                         $urltogo = $CFG->wwwroot . '/';
                         unset($SESSION->wantsurl);
                     }
                 }
                 $loginrecord = array('userid' => $USER->id, 'time' => time(), 'auth' => 'googleoauth2', 'subtype' => $authprovider);
                 $DB->insert_record('auth_googleoauth2_logins', $loginrecord);
                 redirect($urltogo);
             } else {
                 // Authenticate_user_login() failure, probably email registered by another auth plugin.
                 // Do a check to confirm this hypothesis.
                 $userexist = $DB->get_record('user', array('email' => $useremail));
                 if (!empty($userexist) and $userexist->auth != 'googleoauth2') {
                     $a = new stdClass();
                     $a->loginpage = (string) new moodle_url(empty($CFG->alternateloginurl) ? '/login/index.php' : $CFG->alternateloginurl);
                     $a->forgotpass = (string) new moodle_url('/login/forgot_password.php');
                     throw new moodle_exception('couldnotauthenticateuserlogin', 'auth_googleoauth2', '', $a);
                 } else {
                     throw new moodle_exception('couldnotauthenticate', 'auth_googleoauth2');
                 }
             }
         } else {
             throw new moodle_exception('couldnotgetgoogleaccesstoken', 'auth_googleoauth2');
         }
     } else {
         // If you are having issue with the display buttons option, add the button code directly in the theme login page.
         if (get_config('auth/googleoauth2', 'oauth2displaybuttons') and empty($_POST['username']) and empty($_POST['password'])) {
             // Display the button on the login page.
             require_once $CFG->dirroot . '/auth/googleoauth2/lib.php';
             // Insert the html code below the login field.
             // Code/Solution from Elcentra plugin: https://moodle.org/plugins/view/auth_elcentra.
             global $PAGE, $CFG;
             $PAGE->requires->jquery();
             $content = str_replace(array("\n", "\r"), array("\\\n", "\\\r"), auth_googleoauth2_display_buttons(false));
             $PAGE->requires->css('/auth/googleoauth2/style.css');
             $PAGE->requires->js_init_code("buttonsCodeOauth2 = '{$content}';");
             $PAGE->requires->js(new moodle_url($CFG->wwwroot . "/auth/googleoauth2/script.js"));
         }
     }
 }
Exemplo n.º 14
0
 * A Moodle block for creating Configurable Reports
 * @package blocks
 * @author: Juan leyva <http://www.twitter.com/jleyvadelgado>
 * @date: 2009
 */
define('AJAX_SCRIPT', true);
require dirname(dirname(dirname(__FILE__))) . '/config.php';
require_once $CFG->libdir . '/filelib.php';
$action = required_param('action', PARAM_ALPHA);
if (!($userandrepo = get_config('block_configurable_reports', 'crrepository'))) {
    echo json_encode(array());
    die;
}
$c = new curl();
if ($action == 'listreports') {
    if ($res = $c->get("https://api.github.com/repos/{$userandrepo}/contents/")) {
        $data = json_decode($res);
        if (!is_array($data)) {
            echo json_encode(array());
            die;
        }
        foreach ($data as $key => $d) {
            if ($d->type != 'dir') {
                unset($data[$key]);
            }
        }
        echo json_encode($data);
        die;
    }
} else {
    if ($action == 'listcategory') {
Exemplo n.º 15
0
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;
        }
    }
}
Exemplo n.º 16
0
/**
 * 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;
}
Exemplo n.º 17
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;
}
Exemplo n.º 18
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);
 }
Exemplo n.º 19
0
 /**
  * Authentication hook - is called every time user hit the login page
  * The code is run only if the param code is mentionned.
  */
 function loginpage_hook()
 {
     global $USER, $SESSION, $CFG, $DB;
     //check the Google authorization code
     $authorizationcode = optional_param('code', '', PARAM_TEXT);
     if (!empty($authorizationcode)) {
         $authprovider = required_param('authprovider', PARAM_ALPHANUMEXT);
         //set the params specific to the authentication provider
         $params = array();
         switch ($authprovider) {
             case 'google':
                 $params['client_id'] = get_config('auth/googleoauth2', 'googleclientid');
                 $params['client_secret'] = get_config('auth/googleoauth2', 'googleclientsecret');
                 $requestaccesstokenurl = 'https://accounts.google.com/o/oauth2/token';
                 $params['grant_type'] = 'authorization_code';
                 $params['redirect_uri'] = $CFG->wwwroot . '/auth/googleoauth2/google_redirect.php';
                 $params['code'] = $authorizationcode;
                 break;
             case 'facebook':
                 $params['client_id'] = get_config('auth/googleoauth2', 'facebookclientid');
                 $params['client_secret'] = get_config('auth/googleoauth2', 'facebookclientsecret');
                 $requestaccesstokenurl = 'https://graph.facebook.com/oauth/access_token';
                 $params['redirect_uri'] = $CFG->wwwroot . '/auth/googleoauth2/facebook_redirect.php';
                 $params['code'] = $authorizationcode;
                 break;
             case 'messenger':
                 $params['client_id'] = get_config('auth/googleoauth2', 'messengerclientid');
                 $params['client_secret'] = get_config('auth/googleoauth2', 'messengerclientsecret');
                 $requestaccesstokenurl = 'https://oauth.live.com/token';
                 $params['redirect_uri'] = $CFG->wwwroot . '/auth/googleoauth2/messenger_redirect.php';
                 $params['code'] = $authorizationcode;
                 $params['grant_type'] = 'authorization_code';
                 break;
             default:
                 throw new moodle_exception('unknown_oauth2_provider');
                 break;
         }
         //request by curl an access token and refresh token
         require_once $CFG->libdir . '/filelib.php';
         if ($authprovider == 'messenger') {
             //Windows Live returns an "Object moved" error with curl->post() encoding
             $curl = new curl();
             $postreturnvalues = $curl->get('https://oauth.live.com/token?client_id=' . urlencode($params['client_id']) . '&redirect_uri=' . urlencode($params['redirect_uri']) . '&client_secret=' . urlencode($params['client_secret']) . '&code=' . urlencode($params['code']) . '&grant_type=authorization_code');
         } else {
             $curl = new curl();
             $postreturnvalues = $curl->post($requestaccesstokenurl, $params);
         }
         switch ($authprovider) {
             case 'google':
                 $postreturnvalues = json_decode($postreturnvalues);
                 $accesstoken = $postreturnvalues->access_token;
                 //$refreshtoken = $postreturnvalues->refresh_token;
                 //$expiresin = $postreturnvalues->expires_in;
                 //$tokentype = $postreturnvalues->token_type;
                 break;
             case 'facebook':
                 parse_str($postreturnvalues, $returnvalues);
                 $accesstoken = $returnvalues['access_token'];
                 break;
             case 'messenger':
                 $accesstoken = json_decode($postreturnvalues)->access_token;
                 break;
             default:
                 break;
         }
         //with access token request by curl the email address
         if (!empty($accesstoken)) {
             //get the username matching the email
             switch ($authprovider) {
                 case 'google':
                     $params = array();
                     $params['access_token'] = $accesstoken;
                     $params['alt'] = 'json';
                     $postreturnvalues = $curl->get('https://www.googleapis.com/userinfo/email', $params);
                     $postreturnvalues = json_decode($postreturnvalues);
                     $useremail = $postreturnvalues->data->email;
                     $verified = $postreturnvalues->data->isVerified;
                     break;
                 case 'facebook':
                     $params = array();
                     $params['access_token'] = $accesstoken;
                     $postreturnvalues = $curl->get('https://graph.facebook.com/me', $params);
                     $facebookuser = json_decode($postreturnvalues);
                     $useremail = $facebookuser->email;
                     $verified = $facebookuser->verified;
                     break;
                 case 'messenger':
                     $params = array();
                     $params['access_token'] = $accesstoken;
                     $postreturnvalues = $curl->get('https://apis.live.net/v5.0/me', $params);
                     $messengeruser = json_decode($postreturnvalues);
                     $useremail = $messengeruser->emails->preferred;
                     $verified = 1;
                     //not super good but there are no way to check it yet:
                     //http://social.msdn.microsoft.com/Forums/en-US/messengerconnect/thread/515d546d-1155-4775-95d8-89dadc5ee929
                     break;
                 default:
                     break;
             }
             //throw an error if the email address is not verified
             if (!$verified) {
                 throw new moodle_exception('emailaddressmustbeverified', 'auth_googleoauth2');
             }
             //if email not existing in user database then create a new username (userX).
             if (empty($useremail) or $useremail != clean_param($useremail, PARAM_EMAIL)) {
                 throw new moodle_exception('couldnotgetuseremail');
                 //TODO: display a link for people to retry
             }
             //get the user - don't bother with auth = googleoauth2 because
             //authenticate_user_login() will fail it if it's not 'googleoauth2'
             $user = $DB->get_record('user', array('email' => $useremail, 'deleted' => 0, 'mnethostid' => $CFG->mnet_localhost_id));
             //create the user if it doesn't exist
             if (empty($user)) {
                 //get following incremented username
                 $lastusernumber = get_config('auth/googleoauth2', 'lastusernumber');
                 $lastusernumber = empty($lastusernumber) ? 1 : $lastusernumber++;
                 //check the user doesn't exist
                 $nextuser = $DB->get_record('user', array('username' => get_config('auth/googleoauth2', 'googleuserprefix') . $lastusernumber));
                 while (!empty($nextuser)) {
                     $lastusernumber = $lastusernumber + 1;
                     $nextuser = $DB->get_record('user', array('username' => get_config('auth/googleoauth2', 'googleuserprefix') . $lastusernumber));
                 }
                 set_config('lastusernumber', $lastusernumber, 'auth/googleoauth2');
                 $username = get_config('auth/googleoauth2', 'googleuserprefix') . $lastusernumber;
                 //retrieve more information from the provider
                 $newuser = new stdClass();
                 $newuser->email = $useremail;
                 switch ($authprovider) {
                     case 'google':
                         $params = array();
                         $params['access_token'] = $accesstoken;
                         $params['alt'] = 'json';
                         $userinfo = $curl->get('https://www.googleapis.com/oauth2/v1/userinfo', $params);
                         $userinfo = json_decode($userinfo);
                         //email, id, name, verified_email, given_name, family_name, link, gender, locale
                         $newuser->auth = 'googleoauth2';
                         if (!empty($userinfo->given_name)) {
                             $newuser->firstname = $userinfo->given_name;
                         }
                         if (!empty($userinfo->family_name)) {
                             $newuser->lastname = $userinfo->family_name;
                         }
                         if (!empty($userinfo->locale)) {
                             //$newuser->lang = $userinfo->locale;
                             //TODO: convert the locale into correct Moodle language code
                         }
                         break;
                     case 'facebook':
                         $newuser->firstname = $facebookuser->first_name;
                         $newuser->lastname = $facebookuser->last_name;
                         break;
                     case 'messenger':
                         $newuser->firstname = $messengeruser->first_name;
                         $newuser->lastname = $messengeruser->last_name;
                         break;
                     default:
                         break;
                 }
                 //retrieve country and city if the provider failed to give it
                 if (!isset($newuser->country) or !isset($newuser->city)) {
                     $googleipinfodbkey = get_config('auth/googleoauth2', 'googleipinfodbkey');
                     if (!empty($googleipinfodbkey)) {
                         $locationdata = $curl->get('http://api.ipinfodb.com/v3/ip-city/?key=' . $googleipinfodbkey . '&ip=' . getremoteaddr() . '&format=json');
                         $locationdata = json_decode($locationdata);
                     }
                     if (!empty($locationdata)) {
                         //TODO: check that countryCode does match the Moodle country code
                         $newuser->country = isset($newuser->country) ? isset($newuser->country) : $locationdata->countryCode;
                         $newuser->city = isset($newuser->city) ? isset($newuser->city) : $locationdata->cityName;
                     }
                 }
             } else {
                 $username = $user->username;
             }
             //authenticate the user
             //TODO: delete this log later
             $userid = empty($user) ? 'new user' : $user->id;
             add_to_log(SITEID, 'auth_googleoauth2', '', '', $username . '/' . $useremail . '/' . $userid);
             $user = authenticate_user_login($username, null);
             if ($user) {
                 //set a cookie to remember what auth provider was selected
                 setcookie('MOODLEGOOGLEOAUTH2_' . $CFG->sessioncookie, $authprovider, time() + DAYSECS * 60, $CFG->sessioncookiepath, $CFG->sessioncookiedomain, $CFG->cookiesecure, $CFG->cookiehttponly);
                 //prefill more user information if new user
                 if (!empty($newuser)) {
                     $newuser->id = $user->id;
                     $DB->update_record('user', $newuser);
                 }
                 complete_user_login($user);
                 // Redirection
                 if (user_not_fully_set_up($USER)) {
                     $urltogo = $CFG->wwwroot . '/user/edit.php';
                     // We don't delete $SESSION->wantsurl yet, so we get there later
                 } else {
                     if (isset($SESSION->wantsurl) and strpos($SESSION->wantsurl, $CFG->wwwroot) === 0) {
                         $urltogo = $SESSION->wantsurl;
                         // Because it's an address in this site
                         unset($SESSION->wantsurl);
                     } else {
                         // No wantsurl stored or external - go to homepage
                         $urltogo = $CFG->wwwroot . '/';
                         unset($SESSION->wantsurl);
                     }
                 }
                 redirect($urltogo);
             }
         } else {
             throw new moodle_exception('couldnotgetgoogleaccesstoken', 'auth_googleoauth2');
         }
     }
 }
Exemplo n.º 20
0
 /**
  * Returns information about file in this repository by reference
  * {@link repository::get_file_reference()}
  * {@link repository::get_file()}
  *
  * Returns null if file not found or is not readable
  *
  * @param stdClass $reference file reference db record
  * @return null|stdClass that has 'filepath' property
  */
 public function get_file_by_reference($reference) {
     global $USER;
     $ref = unserialize($reference->reference);
     if (!isset($ref->url)) {
         // this is an old-style reference in DB. We need to fix it
         $ref = unserialize($this->fix_old_style_reference($reference->reference));
     }
     if (!isset($ref->url)) {
         return null;
     }
     $c = new curl;
     $url = $this->get_file_download_link($ref->url);
     if (file_extension_in_typegroup($ref->path, 'web_image')) {
         $saveas = $this->prepare_file('');
         try {
             $result = $c->download_one($url, array(), array('filepath' => $saveas, 'timeout' => self::SYNCIMAGE_TIMEOUT, 'followlocation' => true));
             $info = $c->get_info();
             if ($result === true && isset($info['http_code']) && $info['http_code'] == 200) {
                 return (object)array('filepath' => $saveas);
             }
         } catch (Exception $e) {}
     }
     $c->get($url, null, array('timeout' => self::SYNCIMAGE_TIMEOUT, 'followlocation' => true, 'nobody' => true));
     $info = $c->get_info();
     if (isset($info['http_code']) && $info['http_code'] == 200 &&
             array_key_exists('download_content_length', $info) &&
             $info['download_content_length'] >= 0) {
         return (object)array('filesize' => (int)$info['download_content_length']);
     }
     return null;
 }
Exemplo n.º 21
0
 /**
  * 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;
 }
 function fetch_request($request)
 {
     $c = new curl(array('cache' => true, 'module_cache' => 'tag_flickr'));
     $response = $c->get($request);
     return $response;
 }
Exemplo n.º 23
0
/**
 * Search for a tag within an XML DOMDocument
 *
 * @param  string $url The url of the cartridge to be loaded
 * @param  array  $map The map of tags to keys in the return array
 * @param  array  $propertiesmap The map of properties to keys in the return array
 * @return array An associative array with the given keys and their values from the cartridge
 * @throws moodle_exception if the cartridge could not be loaded correctly
 * @since Moodle 3.1
 */
function lti_load_cartridge($url, $map, $propertiesmap = array())
{
    global $CFG;
    require_once $CFG->libdir . "/filelib.php";
    // TODO MDL-46023 Replace this code with a call to the new library.
    $origentity = libxml_disable_entity_loader(true);
    $curl = new curl();
    $response = $curl->get($url);
    $document = new DOMDocument();
    @$document->loadXML($response, LIBXML_DTDLOAD | LIBXML_DTDATTR);
    $cartridge = new DomXpath($document);
    $errors = libxml_get_errors();
    if (count($errors) > 0) {
        $message = 'Failed to load cartridge.';
        foreach ($errors as $error) {
            $message .= "\n" . trim($error->message, "\n\r\t .") . " at line " . $error->line;
        }
        throw new moodle_exception($message);
    }
    $toolinfo = array();
    foreach ($map as $tag => $key) {
        $value = get_tag($tag, $cartridge);
        if ($value) {
            $toolinfo[$key] = $value;
        }
    }
    if (!empty($propertiesmap)) {
        foreach ($propertiesmap as $property => $key) {
            $value = get_tag("property", $cartridge, $property);
            if ($value) {
                $toolinfo[$key] = $value;
            }
        }
    }
    libxml_disable_entity_loader($origentity);
    return $toolinfo;
}
Exemplo n.º 24
0
/**
 * Checks if badges can be pushed to external backpack.
 *
 * @return string Code of backpack accessibility status.
 */
function badges_check_backpack_accessibility()
{
    global $CFG;
    include_once $CFG->libdir . '/filelib.php';
    // Using fake assertion url to check whether backpack can access the web site.
    $fakeassertion = new moodle_url('/badges/assertion.php', array('b' => 'abcd1234567890'));
    // Curl request to backpack baker.
    $curl = new curl();
    $options = array('FRESH_CONNECT' => true, 'RETURNTRANSFER' => true, 'HEADER' => 0, 'CONNECTTIMEOUT' => 2);
    $location = 'http://' . BADGE_BACKPACKURL . '/baker';
    $out = $curl->get($location, array('assertion' => $fakeassertion->out(false)), $options);
    $data = json_decode($out);
    if (!empty($curl->error)) {
        return 'curl-request-timeout';
    } else {
        if (isset($data->code) && $data->code == 'http-unreachable') {
            return 'http-unreachable';
        } else {
            return 'available';
        }
    }
    return false;
}
Exemplo n.º 25
0
 /**
  * Synchronize the references.
  *
  * @param stored_file $file Stored file.
  * @return boolean
  */
 public function sync_reference(stored_file $file)
 {
     if ($file->get_referencelastsync() + DAYSECS > time()) {
         // Synchronise not more often than once a day.
         return false;
     }
     $c = new curl();
     $reference = unserialize(self::convert_to_valid_reference($file->get_reference()));
     $url = $reference->downloadurl;
     if (file_extension_in_typegroup($file->get_filename(), 'web_image')) {
         $path = $this->prepare_file('');
         $result = $c->download_one($url, null, array('filepath' => $path, 'timeout' => $CFG->repositorysyncimagetimeout));
         $info = $c->get_info();
         if ($result === true && isset($info['http_code']) && $info['http_code'] == 200) {
             $fs = get_file_storage();
             list($contenthash, $filesize, $newfile) = $fs->add_file_to_pool($path);
             $file->set_synchronized($contenthash, $filesize);
             return true;
         }
     }
     $c->get($url, null, array('timeout' => $CFG->repositorysyncimagetimeout, 'followlocation' => true, 'nobody' => true));
     $info = $c->get_info();
     if (isset($info['http_code']) && $info['http_code'] == 200 && array_key_exists('download_content_length', $info) && $info['download_content_length'] >= 0) {
         $filesize = (int) $info['download_content_length'];
         $file->set_synchronized(null, $filesize);
         return true;
     }
     $file->set_missingsource();
     return true;
 }
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;
        }
    }
}
Exemplo n.º 27
0
 /**
  * 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);
         }
     }
 }
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

/** Cobalt Reports
 * A Moodle block for creating Cobalt Reports
 * @package blocks
 * @author: Juan leyva <http://www.twitter.com/jleyvadelgado>
 * @date: 2009
 */
define('AJAX_SCRIPT', true);
require(dirname(dirname(dirname(__FILE__))) . '/config.php');
require_once($CFG->libdir . '/filelib.php');

$reportname = required_param('reportname', PARAM_RAW);

if (!$userandrepo = get_config('block_cobalt_reports', 'sharedsqlrepository')) {
    echo json_encode("");
    die;
}


$c = new curl();
$content = $c->get("https://raw.github.com/$userandrepo/master/" . $reportname);
list($subject, $description, $sql) = explode('###', $content);

echo json_encode($sql);
Exemplo n.º 29
0
 public function sync_reference(stored_file $file)
 {
     global $CFG;
     if ($file->get_referencelastsync() + DAYSECS > time()) {
         // Synchronise not more often than once a day.
         return false;
     }
     $ref = unserialize($file->get_reference());
     if (!isset($ref->url)) {
         // this is an old-style reference in DB. We need to fix it
         $ref = unserialize($this->fix_old_style_reference($file->get_reference()));
     }
     if (!isset($ref->url)) {
         return false;
     }
     $c = new curl();
     $url = $this->get_file_download_link($ref->url);
     if (file_extension_in_typegroup($ref->path, 'web_image')) {
         $saveas = $this->prepare_file('');
         try {
             $result = $c->download_one($url, array(), array('filepath' => $saveas, 'timeout' => $CFG->repositorysyncimagetimeout, 'followlocation' => true));
             $info = $c->get_info();
             if ($result === true && isset($info['http_code']) && $info['http_code'] == 200) {
                 $fs = get_file_storage();
                 list($contenthash, $filesize, $newfile) = $fs->add_file_to_pool($saveas);
                 $file->set_synchronized($contenthash, $filesize);
                 return true;
             }
         } catch (Exception $e) {
         }
     }
     $c->get($url, null, array('timeout' => $CFG->repositorysyncimagetimeout, 'followlocation' => true, 'nobody' => true));
     $info = $c->get_info();
     if (isset($info['http_code']) && $info['http_code'] == 200 && array_key_exists('download_content_length', $info) && $info['download_content_length'] >= 0) {
         $filesize = (int) $info['download_content_length'];
         $file->set_synchronized(null, $filesize);
         return true;
     }
     $file->set_missingsource();
     return true;
 }
Exemplo n.º 30
0
 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);
 }