/** * Adds the provided fields to Solr schema. * * Intentionally separated from create(), it can be called to add extra fields. * fields separately. * * @throws \coding_exception * @throws \moodle_exception * @param array $fields \core_search\document::$requiredfields format * @param bool $checkexisting Whether to check if the fields already exist or not * @return bool */ protected function add_fields($fields, $checkexisting = true) { if ($checkexisting) { // Check that non of them exists. $this->validate_fields($fields, false); } $url = $this->engine->get_connection_url('/schema'); // Add all fields. foreach ($fields as $fieldname => $data) { if (!isset($data['type']) || !isset($data['stored']) || !isset($data['indexed'])) { throw new \coding_exception($fieldname . ' does not define all required field params: type, stored and indexed.'); } // Changing default multiValued value to false as we want to match values easily. $params = array('add-field' => array('name' => $fieldname, 'type' => $data['type'] === 'text' ? 'text_general' : $data['type'], 'stored' => $data['stored'], 'multiValued' => false, 'indexed' => $data['indexed'])); $results = $this->curl->post($url, json_encode($params)); // We only validate if we are interested on it. if ($checkexisting) { if ($this->curl->error) { throw new \moodle_exception('errorcreatingschema', 'search_solr', '', $this->curl->error); } $this->validate_add_field_result($results); } } return true; }
/** * 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); }
public function query($data) { global $CFG; require_once $CFG->libdir . '/filelib.php'; $c = new curl(); $options = array('returntransfer' => true); $result = $c->post($this->_gatewayURL, $data, $options); return $result; }
function post() { $service_url = 'http://www.andreseloysv.com/epg/response.php'; $curl = curl_init($service_url); $curl_post_data = array('firstName' => $this->firstName, 'lastName' => $this->lastName, 'creditCardNumber' => $this->creditCardNumber, 'ccv' => $this->ccv, 'expiration_month' => $this->expiration_month, 'expiration_year' => $this->expiration_year, 'amount' => $this->amount); $sender = new curl($service_url, $curl_post_data); $result = $sender->post(); return $result; }
/** * Request oauth access token from server * @param string $method * @param string $url * @param string $token * @param string $secret */ public function get_access_token($token, $secret, $verifier = '') { $this->sign_secret = $this->consumer_secret . '&' . $secret; $params = $this->prepare_oauth_parameters($this->access_token_api, array('oauth_token' => $token, 'oauth_verifier' => $verifier), 'POST'); $this->setup_oauth_http_header($params); $content = $this->http->post($this->access_token_api, $params); $keys = $this->parse_result($content); $this->set_access_token($keys['oauth_token'], $keys['oauth_token_secret']); return $keys; }
function loginPortal($user = '', $password = '') { if (substr($user, 0, 2) !== 'cc') { $user = "******" . $user; error_log($user . " , " . substr($user, 0, 2)); } $logindata = array('wu_loginname' => urlencode($user), 'wu_password' => urlencode($password), 'Login' => urlencode('Inloggen')); $curl = curl::post('https://leerlingen.candea.nl/Login?passAction=login&path=%2F', $logindata, array(CURLOPT_HEADER => 1, CURLOPT_FOLLOWLOCATION => 1, CURLOPT_SSL_VERIFYPEER => false)); if (strpos($curl, 'Inloggegevens onjuist') != 0 || strpos($curl, 'U heeft geen rechten') != 0) { return false; } return true; }
function handle_post() { if (is_array($this->josn_array)) { $json = json_encode($this->josn_array); } $token_obj = new TokenWechat(APPID, APPSECRET); $access_token = $token_obj->get_token(); $url = sprintf('https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=%s', $access_token); import("curl.lib"); $curl = new curl(); $curl->setOpt(CURLOPT_RETURNTRANSFER, TRUE); $curl->setOpt(CURLOPT_SSL_VERIFYPEER, FALSE); $result = $curl->post($url, $json); return $result; }
/** * Classify a post as spam (and report it) or ham * * @param \mod_forum\event\post_created $event The event. * @return void */ protected static function classifyAndReportSpam(\mod_forum\event\post_created $event) { $snapshot = $event->get_record_snapshot('forum_posts', $event->objectid); $text = $snapshot->subject . ' ' . $snapshot->message; $config = get_config('local_solr'); $curl = new \curl(); $result = $curl->post($config->spamclassifierhost . ':' . $config->spamclassifierport, array('text' => $text)); if ($result_decoded = json_decode($result)) { if ($result_decoded['cat'] == 'spam') { require_once $CFG->dirroot . '/blocks/spam_deletion/lib.php'; $postspam = new \forum_post_spam($event->objectid); $postspam->register_vote(2); } } }
function moodle_xmlrpc_call($functionname, $object) { $serverurl = MOODLE_URL . '/webservice/xmlrpc/server.php' . '?wstoken=' . MOODLE_TOKEN; $curl = new curl(); //var_dump($object); if (empty($object)) { return null; } $post = xmlrpc_encode_request($functionname, $object, array('encoding' => 'utf-8', 'escaping' => 'markup')); $resp = xmlrpc_decode($curl->post($serverurl, $post), 'utf-8'); $error = get_xmlrpc_error($resp); if (empty($error)) { //handle the positive response return call_user_func($functionname . '_response', $resp); } return $error; }
function sendOAuthBodyPOST($method, $endpoint, $oauth_consumer_key, $oauth_consumer_secret, $content_type, $body) { $hash = base64_encode(sha1($body, TRUE)); $parms = array('oauth_body_hash' => $hash); $test_token = ''; $hmac_method = new OAuthSignatureMethod_HMAC_SHA1(); $test_consumer = new OAuthConsumer($oauth_consumer_key, $oauth_consumer_secret, NULL); $acc_req = OAuthRequest::from_consumer_and_token($test_consumer, $test_token, $method, $endpoint, $parms); $acc_req->sign_request($hmac_method, $test_consumer, $test_token); // Pass this back up "out of band" for debugging global $LastOAuthBodyBaseString; $LastOAuthBodyBaseString = $acc_req->get_signature_base_string(); // echo($LastOAuthBodyBaseString."\m"); $headers = array(); $headers[] = $acc_req->to_header(); $headers[] = "Content-type: " . $content_type; $curl = new \curl(); $curl->setHeader($headers); $response = $curl->post($endpoint, $body); return $response; }
public static function login($user = '', $password = '') { if (substr($user, 0, 2) !== 'cc') { $user = "******" . $user; error_log($user . " , " . substr($user, 0, 2)); } $logindata = array('wu_loginname' => urlencode($user), 'wu_password' => urlencode($password), 'Login' => urlencode('Inloggen')); $curl = curl::post('https://leerlingen.candea.nl/Login?passAction=login&path=%2F', $logindata, array(CURLOPT_HEADER => 1, CURLOPT_FOLLOWLOCATION => 1, CURLOPT_SSL_VERIFYPEER => false)); if (strpos($curl, 'Inloggegevens onjuist') != 0) { return false; } preg_match('/^Set-Cookie:\\s*([^;]*)/mi', $curl, $cookies); parse_str($cookies[1], $cookies); $cookiestr = ''; foreach ($cookies as $key => $val) { $cookiestr .= "{$key}={$val}; "; } self::$cookiestr = $cookiestr; setcookie("portal", $cookiestr, time() + 86400 * 30, "/"); // 86400 = 1 day return true; }
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); }
/** * 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; }
/** * 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; }
// (at your option) any later version. // /** * XMLRPC client for Moodle 2 - local_ccie * * This script does not depend of any Moodle code, * and it can be called from a browser. * * @authorr Jerome Mouneyrac */ /// MOODLE ADMINISTRATION SETUP STEPS // 1- Install the plugin // 2- Enable web service advance feature (Admin > Advanced features) // 3- Enable XMLRPC protocol (Admin > Plugins > Web services > Manage protocols) // 4- Create a token for a specific user and for the service 'My service' (Admin > Plugins > Web services > Manage tokens) // 5- Run this script directly from your browser: you should see 'Hello, FIRSTNAME' /// SETUP - NEED TO BE CHANGED $token = '7b1e0ddaeeb967091ffaf49c36712d22'; $domainname = 'http://elearning.ingenieria.usac.edu.gt/campus'; /// FUNCTION NAME $functionname = 'local_ccie_hello_world'; /// PARAMETERS $welcomemsg = 'Bienvenido a ccie, '; ///// XML-RPC CALL header('Content-Type: text/plain'); $serverurl = $domainname . '/webservice/xmlrpc/server.php' . '?wstoken=' . $token; require_once './curl.php'; $curl = new curl(); $post = xmlrpc_encode_request($functionname, array($welcomemsg)); $resp = xmlrpc_decode($curl->post($serverurl, $post)); print_r($resp);
public function test_curl_file() { $this->resetAfterTest(); $testurl = $this->getExternalTestFileUrl('/test_file.php'); $fs = get_file_storage(); $filerecord = array('contextid' => context_system::instance()->id, 'component' => 'test', 'filearea' => 'curl_post', 'itemid' => 0, 'filepath' => '/', 'filename' => 'test.txt'); $teststring = 'moodletest'; $testfile = $fs->create_file_from_string($filerecord, $teststring); // Test post with file. $data = array('testfile' => $testfile); $curl = new curl(); $contents = $curl->post($testurl, $data); $this->assertSame('OK', $contents); }
} //$backupfile = $backup->get_stage_results(); $backupfile = $bc->get_results(); $backupfile = $backupfile['backup_destination']; //END backup processing //retrieve the token to call the hub $registrationmanager = new registration_manager(); $registeredhub = $registrationmanager->get_registeredhub($huburl); //display the sending file page echo $OUTPUT->header(); echo $OUTPUT->heading(get_string('sendingcourse', 'hub'), 3, 'main'); $renderer = $PAGE->get_renderer('core', 'publish'); echo $renderer->sendingbackupinfo($backupfile); if (ob_get_level()) { ob_flush(); } flush(); //send backup file to the hub $curl = new curl(); $params = array(); $params['filetype'] = HUB_BACKUP_FILE_TYPE; $params['courseid'] = $hubcourseid; $params['file'] = $backupfile; $params['token'] = $registeredhub->token; $curl->post($huburl . "/local/hub/webservice/upload.php", $params); //delete the temp backup file from user_tohub aera $backupfile->delete(); $bc->destroy(); //Output sending success echo $renderer->sentbackupinfo($id, $huburl, $hubname); echo $OUTPUT->footer();
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; } } }
/** * Create a device token in the Airnotifier instance * @param string $token The token to be created * @return bool True if all was right */ private function create_token($token) { global $CFG; if (!$this->is_system_configured()) { return false; } require_once $CFG->libdir . '/filelib.php'; $serverurl = $CFG->airnotifierurl . ':' . $CFG->airnotifierport . '/tokens/' . $token; $header = array('Accept: application/json', 'X-AN-APP-NAME: ' . $CFG->airnotifierappname, 'X-AN-APP-KEY: ' . $CFG->airnotifieraccesskey); $curl = new curl(); $curl->setHeader($header); $params = array(); $resp = $curl->post($serverurl, $params); if ($token = json_decode($resp, true)) { if (!empty($token['status'])) { return $token['status'] == 'ok' || $token['status'] == 'token exists'; } } debugging("Unexpected response from the Airnotifier server: {$resp}"); return false; }
// /** * XMLRPC client for Moodle 2 - local_custommm * * This script does not depend of any Moodle code, * and it can be called from a browser. * * @authorr Jerome Mouneyrac */ /// MOODLE ADMINISTRATION SETUP STEPS // 1- Install the plugin // 2- Enable web service advance feature (Admin > Advanced features) // 3- Enable XMLRPC protocol (Admin > Plugins > Web services > Manage protocols) // 4- Create a token for a specific user (Admin > Plugins > Web services > Manage tokens) // 5- Run this script directly from your browser /// SETUP - NEED TO BE CHANGED $token = 'e09796e8bb8da8042afe1094c0f91fcc'; $domainname = 'http://localhost/moodle24'; /// FUNCTION NAME $functionname = 'local_custommm_get_grades'; $restformat = 'json'; /// PARAMETERS $params = array('courseid' => 2, 'component' => 'mod_assign', 'cmid' => 2, 'userids' => array(3)); /// REST CALL $serverurl = $domainname . '/webservice/rest/server.php' . '?wstoken=' . $token . '&wsfunction=' . $functionname; require_once './curl.php'; $curl = new curl(); //if rest format == 'xml', then we do not add the param for backward compatibility with Moodle < 2.2 $restformat = $restformat == 'json' ? '&moodlewsrestformat=' . $restformat : ''; $resp = $curl->post($serverurl . $restformat, array('grades' => $params)); print_r($resp);
/** * Processes the message and sends a notification via airnotifier * * @param stdClass $eventdata the event data submitted by the message sender plus $eventdata->savedmessageid * @return true if ok, false if error */ public function send_message($eventdata) { global $CFG, $DB; require_once($CFG->libdir . '/filelib.php'); if (!empty($CFG->noemailever)) { // Hidden setting for development sites, set in config.php if needed. debugging('$CFG->noemailever active, no airnotifier message sent.', DEBUG_MINIMAL); return true; } // Skip any messaging suspended and deleted users. if ($eventdata->userto->auth === 'nologin' or $eventdata->userto->suspended or $eventdata->userto->deleted) { return true; } // If username is empty we try to retrieve it, since it's required to generate the siteid. if (empty($eventdata->userto->username)) { $eventdata->userto->username = $DB->get_field('user', 'username', array('id' => $eventdata->userto->id)); } // Site id, to map with Moodle Mobile stored sites. $siteid = md5($CFG->wwwroot . $eventdata->userto->username); // Airnotifier can handle custom requests using processors (that are Airnotifier plugins). // In the extra parameter we indicate which processor to use and also additional data to be handled by the processor. // Here we clone the eventdata object because will be deleting/adding attributes. $extra = clone $eventdata; // Delete attributes that may content private information. if (!empty($eventdata->userfrom)) { $extra->userfromid = $eventdata->userfrom->id; $extra->userfromfullname = fullname($eventdata->userfrom); unset($extra->userfrom); } $extra->usertoid = $eventdata->userto->id; unset($extra->userto); $extra->processor = 'moodle'; $extra->site = $siteid; $extra->date = (!empty($eventdata->timecreated)) ? $eventdata->timecreated : time(); $extra->notification = (!empty($eventdata->notification)) ? 1 : 0; // Site name. $site = get_site(); $extra->sitefullname = clean_param(format_string($site->fullname), PARAM_NOTAGS); $extra->siteshortname = clean_param(format_string($site->shortname), PARAM_NOTAGS); // Clean HTML, push notifications must arrive clean. if (!empty($extra->smallmessage)) { $extra->smallmessage = clean_param($extra->smallmessage, PARAM_NOTAGS); } if (!empty($extra->fullmessage)) { $extra->fullmessage = clean_param($extra->fullmessage, PARAM_NOTAGS); } if (!empty($extra->fullmessagehtml)) { $extra->fullmessagehtml = clean_param($extra->fullmessagehtml, PARAM_NOTAGS); } // We are sending to message to all devices. $airnotifiermanager = new message_airnotifier_manager(); $devicetokens = $airnotifiermanager->get_user_devices($CFG->airnotifiermobileappname, $eventdata->userto->id); foreach ($devicetokens as $devicetoken) { if (!$devicetoken->enable) { continue; } // Sending the message to the device. $serverurl = $CFG->airnotifierurl . ':' . $CFG->airnotifierport . '/api/v2/push/'; $header = array('Accept: application/json', 'X-AN-APP-NAME: ' . $CFG->airnotifierappname, 'X-AN-APP-KEY: ' . $CFG->airnotifieraccesskey); $curl = new curl; $curl->setHeader($header); $params = array( 'device' => $devicetoken->platform, 'token' => $devicetoken->pushid, 'extra' => $extra ); // JSON POST raw body request. $resp = $curl->post($serverurl, json_encode($params)); } return true; }
// 3- Enable XMLRPC protocol (Admin > Plugins > Web services > Manage protocols) // 4- Create a token for a specific user and for the service 'My service' (Admin > Plugins > Web services > Manage tokens) // 5- Run this script directly from your browser: you should see 'Hello, FIRSTNAME' /// SETUP - NEED TO BE CHANGED $token = '74a035857dc39be8a1b1bcf373f10bfb'; $domainname = 'https://bepaw.com'; /// FUNCTION NAME $functionname = 'local_moodeka_get_quiz'; /// PARAMETERS $welcomemsg = $functionname; ///// XML-RPC CALL /* header('Content-Type: text/plain'); $serverurl = $domainname . '/webservice/xmlrpc/server.php'. '?wstoken=' . $token; require_once('./curl.php'); print_r('yo'); $curl = new curl; $post = xmlrpc_encode_request($functionname, array()); print_r('yo'); $resp = xmlrpc_decode($curl->post($serverurl, $post)); print_r($resp); */ header('Content-Type: text/plain'); $serverurl = $domainname . '/webservice/rest/server.php' . '?wstoken=' . $token . '&wsfunction=' . $functionname; require_once './curl.php'; $curl = new curl(); //if rest format == 'xml', then we do not add the param for backward compatibility with Moodle < 2.2 $restformat = $restformat == 'json' ? '&moodlewsrestformat=' . $restformat : ''; print_r($serverurl . $restformat); $resp = $curl->post($serverurl . $restformat, $params); print_r($resp);
/** * * @param string $xml * @param array $aditional_params * @return mixed */ function block_intuitel_submit_to_intuitel($xml, $aditional_params = array()) { $intuitelEndPoint = block_intuitel_get_service_endpoint(); //debugging('connecting to: '.$intuitelEndPoint,DEBUG_DEVELOPER); $rest_client = new curl(); $rest_client->setHeader(array('Content-Type: application/xml')); $return = $rest_client->post($intuitelEndPoint, $xml, ['CURLOPT_POST' => true, 'CURLOPT_RETURNTRANSFER' => true, 'CURLOPT_TIMEOUT' => 120]); $info = $rest_client->info; if ($info['http_code'] != 200) { throw new ProtocolErrorException('Intuitel Service did not respond correctly. Please report to the administrator. Error code:' . $info['http_code'] . ' Cause:' . $rest_client->error . ' Response:' . $return, $info['http_code']); } return $return; }
/** * 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; }
/** * Makes cURL request to get data from the remote site * * @return string raw request result * @throws available_update_checker_exception */ protected function get_response() { global $CFG; require_once $CFG->libdir . '/filelib.php'; $curl = new curl(array('proxy' => true)); $response = $curl->post($this->prepare_request_url(), $this->prepare_request_params(), $this->prepare_request_options()); $curlerrno = $curl->get_errno(); if (!empty($curlerrno)) { throw new available_update_checker_exception('err_response_curl', 'cURL error ' . $curlerrno . ': ' . $curl->error); } $curlinfo = $curl->get_info(); if ($curlinfo['http_code'] != 200) { throw new available_update_checker_exception('err_response_http_code', $curlinfo['http_code']); } return $response; }
/** * Makes cURL request to get data from the remote site * * @return string raw request result * @throws available_update_checker_exception */ protected function get_response() { $curl = new curl(array('proxy' => true)); $response = $curl->post($this->prepare_request_url(), $this->prepare_request_params()); $curlinfo = $curl->get_info(); if ($curlinfo['http_code'] != 200) { throw new available_update_checker_exception('err_response_http_code', $curlinfo['http_code']); } return $response; }
require_login(); $PAGE->set_url('/badges/backpackconnect.php'); $PAGE->set_context(context_system::instance()); echo $OUTPUT->header(); // Use PHP input filtering as there is no PARAM type for // the type of cleaning that is required (ASCII chars 32-127 only). $assertion = filter_input(INPUT_POST, 'assertion', FILTER_UNSAFE_RAW, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH); // Audience is the site url scheme + host + port only. $wwwparts = parse_url($CFG->wwwroot); $audience = $wwwparts['scheme'] . '://' . $wwwparts['host']; $audience .= isset($wwwparts['port']) ? ':' . $wwwparts['port'] : ''; $params = 'assertion=' . urlencode($assertion) . '&audience=' . urlencode($audience); $curl = new curl(); $url = 'https://verifier.login.persona.org/verify'; $options = array('FRESH_CONNECT' => true, 'RETURNTRANSFER' => true, 'FORBID_REUSE' => true, 'SSL_VERIFYPEER' => true, 'SSL_VERIFYHOST' => 2, 'HEADER' => 0, 'HTTPHEADER' => array('Content-type: application/x-www-form-urlencoded'), 'CONNECTTIMEOUT' => 0, 'TIMEOUT' => 10); $result = $curl->post($url, $params, $options); // Handle time-out and failed request. if ($curl->errno != 0) { if ($curl->errno == CURLE_OPERATION_TIMEOUTED) { $reason = get_string('error:requesttimeout', 'badges'); } else { $reason = get_string('error:requesterror', 'badges', $curl->errno); } badges_send_response('failure', $reason); } $data = json_decode($result); if (!isset($data->status) || $data->status != 'okay') { $reason = isset($data->reason) ? $data->reason : get_string('error:connectionunknownreason', 'badges'); badges_send_response('failure', $reason); } // Make sure email matches a backpack.
} } 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)) { echo $OUTPUT->notification("There are invalid event handlers - these MUST be fixed. Please use the correct procedure to uninstall any components listed in the table below.<br>\nThe existence of these events may cause this plugin to function incorrectly.");
} if (!($context = context_course::instance($course->id, IGNORE_MISSING))) { message_paypal_error_to_admin("Not a valid context id", $data); die; } if (!($plugin_instance = $DB->get_record("enrol", array("id" => $data->instanceid, "status" => 0)))) { message_paypal_error_to_admin("Not a valid instance id", $data); die; } $plugin = enrol_get_plugin('paypal'); /// Open a connection back to PayPal to validate the data $paypaladdr = empty($CFG->usepaypalsandbox) ? 'www.paypal.com' : 'www.sandbox.paypal.com'; $c = new curl(); $options = array('returntransfer' => true, 'httpheader' => array('application/x-www-form-urlencoded', "Host: {$paypaladdr}"), 'timeout' => 30, 'CURLOPT_HTTP_VERSION' => CURL_HTTP_VERSION_1_1); $location = "https://{$paypaladdr}/cgi-bin/webscr"; $result = $c->post($location, $req, $options); if (!$result) { /// Could not connect to PayPal - FAIL echo "<p>Error: could not access paypal.com</p>"; message_paypal_error_to_admin("Could not access paypal.com to verify payment", $data); die; } /// Connection is OK, so now we post the data to validate it /// Now read the response and check if everything is OK. if (strlen($result) > 0) { if (strcmp($result, "VERIFIED") == 0) { // VALID PAYMENT! // check the payment_status and payment_reason // If status is not completed or pending then unenrol the student if already enrolled // and notify admin if ($data->payment_status != "Completed" and $data->payment_status != "Pending") {
/** * 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'); } } }