Sends the request, calling necessary utility functions to update built-in properties.
public send_request ( boolean $parse = false ) : string | ||
$parse | boolean | (Optional) Whether to parse the response with ResponseCore or not. |
리턴 | string | The resulting unparsed data from the request. |
/** * upload() * * Processes uploaded backup file. * * @return array True on upload success; false otherwise. */ function upload() { if (isset($_POST['upload']) && $_POST['upload'] == 'local') { if (pb_backupbuddy::$options['password'] != '#PASSWORD#') { $path_parts = pathinfo($_FILES['file']['name']); if (strtolower(substr($_FILES['file']['name'], 0, 6)) == 'backup' && strtolower($path_parts['extension']) == 'zip') { if (move_uploaded_file($_FILES['file']['tmp_name'], basename($_FILES['file']['name']))) { pb_backupbuddy::alert('File Uploaded. Your backup was successfully uploaded.'); return true; } else { pb_backupbuddy::alert('Sorry, there was a problem uploading your file.', true); return false; } } else { pb_backupbuddy::alert('Only properly named BackupBuddy zip archives with a zip extension may be uploaded.', true); return false; } } else { pb_backupbuddy::alert('Upload Access Denied. To prevent unauthorized file uploads an importbuddy password must be configured and properly entered to use this feature.'); return false; } } // DOWNLOAD FILE FROM STASH TO LOCAL. if (pb_backupbuddy::_POST('upload') == 'stash') { pb_backupbuddy::set_greedy_script_limits(true); /* echo '<pre>'; print_r( $_POST ); echo '</pre>'; */ $requestcore_file = dirname(dirname(dirname(__FILE__))) . '/lib/requestcore/requestcore.class.php'; require_once $requestcore_file; $link = pb_backupbuddy::_POST('link'); $destination_file = dirname(dirname(dirname(dirname(__FILE__)))) . '/' . basename(pb_backupbuddy::_POST('link')); $destination_file = substr($destination_file, 0, stripos($destination_file, '.zip') + 4); $_GET['file'] = basename($destination_file); $request = new RequestCore($link); $request->set_write_file($destination_file); echo '<div id="pb_importbuddy_working" style="padding: 20px;">Downloading backup from Stash to `' . $destination_file . '`...<br><br><img src="' . pb_backupbuddy::plugin_url() . '/images/loading_large.gif" title="Working... Please wait as this may take a moment..."><br><br></div>'; flush(); $response = $request->send_request(false); if ($response !== true) { pb_backupbuddy::alert('Error #8548459598. Unable to download file from Stash. You may manually download it and upload to the server via FTP.'); } else { // No error. if (!file_exists($destination_file)) { pb_backupbuddy::alert('Error #34845745878. Stash returned a success but the backup file was not found locally. Check this server\'s directory write permissions. You may manually download it and upload to the server via FTP.'); } } echo '<script type="text/javascript">jQuery("#pb_importbuddy_working").hide();</script>'; } }
function sign_url_for_put($obj) { global $bucket; global $object; $timeout = 3600; //通过content上传 $options = NULL; $response = $obj->presign_url($bucket, $object, $timeout, "PUT", $options); SampleUtil::my_echo("签名的URL为:" . $response); $content = 'abcdefg'; $request = new RequestCore($response); $request->set_method('PUT'); $request->add_header('Content-Type', ''); $request->add_header('Content-Length', strlen($content)); $request->set_body($content); $request->send_request(); $res = new ResponseCore($request->get_response_header(), $request->get_response_body(), $request->get_response_code()); if ($res->isOK()) { SampleUtil::my_echo("签名上传字符串成功"); } else { SampleUtil::my_echo("签名上传字符串失败"); } //通过file上传 $file = __FILE__; if (!file_exists($file)) { throw new OSS_Exception($file . OSS_FILE_NOT_EXIST); } $options = array('Content-Type' => 'txt'); $response = $obj->presign_url($bucket, $object, $timeout, "PUT", $options); SampleUtil::my_echo("签名的URL为:" . $response); $request = new RequestCore($response); $request->set_method('PUT'); $request->add_header('Content-Type', 'txt'); $request->set_read_file($file); $request->set_read_stream_size(filesize($file)); $request->send_request(); $res = new ResponseCore($request->get_response_header(), $request->get_response_body(), $request->get_response_code()); if ($res->isOK()) { SampleUtil::my_echo("签名上传文件成功"); } else { SampleUtil::my_echo("签名上传字符串失败"); } }
/** * 调用API * @param string $apiMethod api方法名 * @param array || string $params 请求参数 * @param string $method HTTP请求类型 * @param string $headers 附加的HTTP HEADER信息 * @return string */ private function _baseControl($apiMethod, $params, $method = 'GET', $headers = array()) { $method = strtoupper($method); if (is_array($params)) { $params = http_build_query($params, '', '&'); } $url = $this->_pcs_uri_prefixs['https'] . $apiMethod . ($method == 'GET' ? '&' . $params : ''); $requestCore = new RequestCore(); $requestCore->set_request_url($url); $requestCore->set_method($method); if ($method == 'POST') { $requestCore->set_body($params); } foreach ($headers as $key => $value) { $requestCore->add_header($key, $value); } $requestCore->send_request(); $result = $requestCore->get_response_body(); return $result; }
public static function get_manage_data($settings, $suppressAuthAlert = false) { $itxapi_username = $settings['itxapi_username']; $itxapi_password = $settings['itxapi_password']; require_once dirname(__FILE__) . '/lib/class.itx_helper.php'; require_once dirname(dirname(__FILE__)) . '/_s3lib/aws-sdk/sdk.class.php'; $stash = new ITXAPI_Helper(pb_backupbuddy_destination_stash::ITXAPI_KEY, pb_backupbuddy_destination_stash::ITXAPI_URL, $itxapi_username, $itxapi_password); // get the url to use to request management credentials // url looks something like this - http://api.ithemes.com/stash/upload?apikey=sb31kesem0c879m0&expires=1347439653&subscriber=jwooley&signature=VFMbmXb5OorWwqE0iedOCsDtSgs%3D $manage_url = $stash->get_manage_url(); // create a new RequestCore to get the credentials // NOTE: RequestCore is part of the AWS SDK, it's a generic http request class. // You can use any available function to make the api request, the wordpress http class for example, // or even just the basic file_get_contents() $request = new RequestCore($manage_url); // send the api request try { $response = $request->send_request(true); } catch (Exception $e) { $error = 'Error #23873631: Unable to initiate Stash request. Details:`' . $e->getMessage() . '`.'; pb_backupbuddy::status('error', $error); echo $error; return false; } // see if the request was successful if (!$response->isOK()) { //throw new Exception('Request for management credentials failed.'); $error = 'Request for management credentials failed.'; pb_backupbuddy::status('error', $error); pb_backupbuddy::alert($error); return false; } // see if we got a json response if (!($manage_data = json_decode($response->body, true))) { $error = 'Did not get valid JSON response.'; pb_backupbuddy::status('error', $error); pb_backupbuddy::alert($error); return false; } // finally see if the API returned an error if (isset($manage_data['error'])) { $error = 'Error: ' . implode(' - ', $manage_data['error']); pb_backupbuddy::status('error', $error); if (true === $suppressAuthAlert && '3002' == $manage_data['error']['code']) { // Alert suppressed. } else { pb_backupbuddy::alert($error); } return false; } if ('1' == $settings['use_packaged_cert']) { pb_backupbuddy::status('details', 'Using packaged cacert.pem file based on destination settings.'); $manage_data['ssl.certificate_authority'] = pb_backupbuddy::plugin_path() . '/destinations/_s3lib/aws-sdk/lib/requestcore/cacert.pem'; } return $manage_data; }
private function invoke($method, $args = array(), $holder, $location = NULL) { $api = API::$API[$method]; if (!$api) { throw new Ks3ClientException($method . " Not Found API"); } if (count($args) !== 0) { if (count($args) > 1 || !is_array($args[0])) { throw new Ks3ClientException("this method only needs one array argument"); } $args = $args[0]; } if (isset($api["redirect"])) { $api = API::$API[$api["redirect"]]; } $request = new Ks3Request(); if (empty($args["Bucket"])) { if ($api["needBucket"]) { throw new Ks3ClientException($method . " this api need bucket"); } } else { $request->bucket = $args["Bucket"]; } $position = "Key"; //position主要为queryadp接口用的 if (isset($api["objectPostion"])) { $position = $api["objectPostion"]; } if (empty($args[$position])) { if ($api["needObject"]) { throw new Ks3ClientException($method . " this api need " . $position); } } else { $key = $args[$position]; $preEncoding = mb_detect_encoding($key, array("ASCII", "UTF-8", "GB2312", "GBK", "BIG5")); $holder->msg .= "key encoding " . $preEncoding . "\r\n"; if (strtolower($preEncoding) != "utf-8") { $key = iconv($preEncoding, "UTF-8", $key); } $request->key = $key; } $method = $api["method"]; if ($method == "Method") { if (empty($args["Method"])) { $request->method = "GET"; } else { $request->method = $args["Method"]; } } else { $request->method = $api["method"]; } if (KS3_API_USE_HTTPS) { $request->scheme = "https://"; } else { $request->scheme = "http://"; } $request->endpoint = $this->endpoint; //add subresource if (!empty($api["subResource"])) { $request->subResource = $api["subResource"]; } //add query params if (isset($api["queryParams"])) { foreach ($api["queryParams"] as $key => $value) { $required = FALSE; if (substr($value, 0, 1) === "!") { $required = TRUE; $value = substr($value, 1); } $index = explode("->", $value); $curIndexArg = $args; $add = TRUE; $curkey = ""; foreach ($index as $key1 => $value1) { if (!isset($curIndexArg[$value1]) && $value1 !== "*") { $add = FALSE; } else { $curkey = $value1; //星号表示所有,按照暂时的业务,默认星号后面就没了 if ($curkey == "*") { foreach ($curIndexArg as $queryK => $queryV) { if (!is_array($queryV)) { $request->addQueryParams($queryK, $queryV); } } $add = FALSE; $required = FALSE; break; } else { $curIndexArg = $curIndexArg[$value1]; } } } if (!empty($curIndexArg) && $add) { $request->addQueryParams($curkey, $curIndexArg); continue; } if ($required) { throw new Ks3ClientException($method . " param " . $value . " is required"); } } } if (isset($api["body"])) { if (isset($api["body"]["builder"])) { $builderName = $api["body"]["builder"]; $builder = new $builderName(); $request->body = $builder->build($args); } else { if (isset($api["body"]["position"])) { $position = $api["body"]["position"]; $index = explode("->", $position); $curIndexArg = $args; $add = TRUE; $curkey = ""; foreach ($index as $key1 => $value1) { if (!isset($curIndexArg[$value1])) { $add = FALSE; } else { $curIndexArg = $curIndexArg[$value1]; $curkey = $value1; } } if (!empty($curIndexArg) && $add) { $request->body = $curIndexArg; } } } } //add ext headers //TODO //sign request $signer = NULL; if (isset($api["signer"])) { $signers = explode("->", $api["signer"]); foreach ($signers as $key => $value) { $signer = new $value(); $log = $signer->sign($request, array("accessKey" => $this->accessKey, "secretKey" => $this->secretKey, "args" => $args)); if (!empty($log)) { $holder->msg .= $log . "\r\n"; } } } if ($signer === NULL || !$signer instanceof QueryAuthSigner) { $url = $request->toUrl($this->endpoint); if ($location != NULL) { $url = $location; } $httpRequest = new RequestCore($url); if (KS3_API_DEBUG_MODE === TRUE) { $httpRequest->debug_mode = TRUE; } $httpRequest->set_method($request->method); foreach ($request->headers as $key => $value) { $httpRequest->add_header($key, $value); } $httpRequest->request_body = $request->body; if (isset($args["writeCallBack"])) { $httpRequest->register_streaming_write_callback($args["writeCallBack"]); } if (isset($args["readCallBack"])) { $httpRequest->register_streaming_read_callback($args["readCallBack"]); } $read_stream = $request->read_stream; $read_length = $request->getHeader(Headers::$ContentLength); $seek_position = $request->seek_position; if (isset($read_stream)) { $httpRequest->set_read_stream($read_stream, $read_length); $httpRequest->set_seek_position($seek_position); $httpRequest->remove_header(Headers::$ContentLength); } $write_stream = $request->write_stream; if (isset($write_stream)) { $httpRequest->set_write_stream($write_stream); } $holder->msg .= "request url->" . serialize($httpRequest->request_url) . "\r\n"; $holder->msg .= "request headers->" . serialize($httpRequest->request_headers) . "\r\n"; $holder->msg .= "request body->" . $httpRequest->request_body . "\r\n"; $holder->msg .= "request read stream length->" . $read_length . "\r\n"; $holder->msg .= "request read stream seek position->" . $seek_position . "\r\n"; $httpRequest->send_request(); //print_r($httpRequest); $body = $httpRequest->get_response_body(); $data = new ResponseCore($httpRequest->get_response_header(), Utils::replaceNS2($body), $httpRequest->get_response_code()); if ($data->status == 307) { $respHeaders = $httpRequest->get_response_header(); $location = $respHeaders["location"]; if (substr($location, 0, 4) == "http") { $holder->msg .= "response code->" . $httpRequest->get_response_code() . "\r\n"; $holder->msg .= "response headers->" . serialize($httpRequest->get_response_header()) . "\r\n"; $holder->msg .= "response body->" . $body . "\r\n"; $holder->msg .= "retry request to " . $location . "\r\n"; //array($args)详见invoke开头 return $this->invoke($method, array($args), $holder, $location); } } $holder->msg .= "response code->" . $httpRequest->get_response_code() . "\r\n"; $holder->msg .= "response headers->" . serialize($httpRequest->get_response_header()) . "\r\n"; $holder->msg .= "response body->" . $body . "\r\n"; $handlers = explode("->", $api["handler"]); foreach ($handlers as $key => $value) { $handler = new $value(); $data = $handler->handle($data); } return $data; } else { $url = $request->toUrl($this->endpoint); $holder->msg .= $url . "\r\n"; return $url; } }
echo $login_welcome; pb_backupbuddy::alert(implode('<br>', $settings_result['errors'])); $credentials_form->display_settings('Connect to Stash'); } else { // No form errors; process! $itx_helper_file = dirname(dirname(__FILE__)) . '/classes/class.itx_helper.php'; require_once $itx_helper_file; $itxapi_username = $settings_result['data']['itxapi_username']; $itxapi_password = ITXAPI_Helper::get_password_hash($itxapi_username, $settings_result['data']['itxapi_password_raw']); // Generates hash for use as password for API. $requestcore_file = dirname(dirname(__FILE__)) . '/lib/requestcore/requestcore.class.php'; require_once $requestcore_file; $stash = new ITXAPI_Helper($ITXAPI_KEY, $ITXAPI_URL, $itxapi_username, $itxapi_password); $files_url = $stash->get_files_url(); $request = new RequestCore($files_url); $response = $request->send_request(true); // See if the request was successful. if (!$response->isOK()) { pb_backupbuddy::status('error', 'Stash request for files failed.'); } // See if we got a json response. if (!($stash_files = json_decode($response->body, true))) { pb_backupbuddy::status('error', 'Stash did not get valid json response.'); } // Finally see if the API returned an error. if (isset($stash_files['error'])) { if ($stash_files['error']['code'] == '3002') { pb_backupbuddy::alert('Invalid iThemes.com Member account password. Please verify your password. <a href="http://ithemes.com/member/member.php" target="_new">Forget your password?</a>'); } else { pb_backupbuddy::alert(implode(' - ', $stash_files['error'])); }
public function testPutObjectAclPresignedUrl() { $this->testPutObjectPresignedUrl(); $url = $this->client->generatePresignedUrl(array("Method" => "PUT", "Bucket" => $this->bucket, "Key" => $this->key, "Options" => array("Expires" => 60 * 10, "acl" => NULL), "Headers" => array("Content-Type" => "text/plain", "x-kss-acl" => "public-read"))); $httpRequest = new RequestCore($url); $httpRequest->set_method("PUT"); $httpRequest->add_header("Content-Type", "text/plain"); $httpRequest->add_header("x-kss-acl", "public-read"); $httpRequest->send_request(); $body = $httpRequest->get_response_body(); $this->assertEquals($httpRequest->get_response_code() . " body:" . $body, 200, "put object acl status code"); }
/** * @return array */ protected function getHttpResponse($method, $url, $body, $headers) { $request = new RequestCore($url); foreach ($headers as $key => $value) { $request->add_header($key, $value); } $request->set_method($method); $request->set_useragent(USER_AGENT); if ($method == "POST") { $request->set_body($body); } $request->send_request(); $response = array(); $response[] = (int) $request->get_response_code(); $response[] = $request->get_response_header(); $response[] = $request->get_response_body(); return $response; }
function process_remote_copy($destination_type, $file, $settings) { pb_backupbuddy::status('details', 'Copying remote `' . $destination_type . '` file `' . $file . '` down to local.'); pb_backupbuddy::set_greedy_script_limits(); if (!class_exists('backupbuddy_core')) { require_once pb_backupbuddy::plugin_path() . '/classes/core.php'; } // Determine destination filename. $destination_file = backupbuddy_core::getBackupDirectory() . basename($file); if (file_exists($destination_file)) { $destination_file = str_replace('backup-', 'backup_copy_' . pb_backupbuddy::random_string(5) . '-', $destination_file); } pb_backupbuddy::status('details', 'Filename of resulting local copy: `' . $destination_file . '`.'); if ($destination_type == 'stash2') { require_once ABSPATH . 'wp-admin/includes/file.php'; pb_backupbuddy::status('details', 'About to begin downloading from URL.'); $download = download_url($url); pb_backupbuddy::status('details', 'Download process complete.'); if (is_wp_error($download)) { $error = 'Error #832989323: Unable to download file `' . $file . '` from URL: `' . $url . '`. Details: `' . $download->get_error_message() . '`.'; pb_backupbuddy::status('error', $error); pb_backupbuddy::alert($error); return false; } else { if (false === copy($download, $destination_file)) { $error = 'Error #3329383: Unable to copy file from `' . $download . '` to `' . $destination_file . '`.'; pb_backupbuddy::status('error', $error); pb_backupbuddy::alert($error); @unlink($download); return false; } else { pb_backupbuddy::status('details', 'File saved to `' . $destination_file . '`.'); @unlink($download); return true; } } } // end stash2. if ($destination_type == 'stash') { $itxapi_username = $settings['itxapi_username']; $itxapi_password = $settings['itxapi_password']; // Load required files. pb_backupbuddy::status('details', 'Load Stash files.'); require_once pb_backupbuddy::plugin_path() . '/destinations/stash/init.php'; require_once dirname(dirname(__FILE__)) . '/destinations/_s3lib/aws-sdk/sdk.class.php'; require_once pb_backupbuddy::plugin_path() . '/destinations/stash/lib/class.itx_helper.php'; // Talk with the Stash API to get access to do things. pb_backupbuddy::status('details', 'Authenticating Stash for remote copy to local.'); $stash = new ITXAPI_Helper(pb_backupbuddy_destination_stash::ITXAPI_KEY, pb_backupbuddy_destination_stash::ITXAPI_URL, $itxapi_username, $itxapi_password); $manage_url = $stash->get_manage_url(); $request = new RequestCore($manage_url); $response = $request->send_request(true); // Validate response. if (!$response->isOK()) { $error = 'Request for management credentials failed.'; pb_backupbuddy::status('error', $error); pb_backupbuddy::alert($error); return false; } if (!($manage_data = json_decode($response->body, true))) { $error = 'Did not get valid JSON response.'; pb_backupbuddy::status('error', $error); pb_backupbuddy::alert($error); return false; } if (isset($manage_data['error'])) { $error = 'Error: ' . implode(' - ', $manage_data['error']); pb_backupbuddy::status('error', $error); pb_backupbuddy::alert($error); return false; } // Connect to S3. pb_backupbuddy::status('details', 'Instantiating S3 object.'); $s3 = new AmazonS3($manage_data['credentials']); pb_backupbuddy::status('details', 'About to get Stash object `' . $file . '`...'); try { $response = $s3->get_object($manage_data['bucket'], $manage_data['subkey'] . pb_backupbuddy_destination_stash::get_remote_path() . $file, array('fileDownload' => $destination_file)); } catch (Exception $e) { pb_backupbuddy::status('error', 'Error #5443984: ' . $e->getMessage()); error_log('err:' . $e->getMessage()); return false; } if ($response->isOK()) { pb_backupbuddy::status('details', 'Stash copy to local success.'); return true; } else { pb_backupbuddy::status('error', 'Error #894597845. Stash copy to local FAILURE. Details: `' . print_r($response, true) . '`.'); return false; } } elseif ($destination_type == 'gdrive') { die('Not implemented here.'); require_once pb_backupbuddy::plugin_path() . '/destinations/gdrive/init.php'; $settings = array_merge(pb_backupbuddy_destination_gdrive::$default_settings, $settings); if (true === pb_backupbuddy_destination_gdrive::getFile($settings, $file, $destination_file)) { // success pb_backupbuddy::status('details', 'Google Drive copy to local success.'); return true; } else { // fail pb_backupbuddy::status('details', 'Error #2332903. Google Drive copy to local FAILURE.'); return false; } } elseif ($destination_type == 's3') { require_once pb_backupbuddy::plugin_path() . '/destinations/s3/init.php'; if (true === pb_backupbuddy_destination_s3::download_file($settings, $file, $destination_file)) { // success pb_backupbuddy::status('details', 'S3 copy to local success.'); return true; } else { // fail pb_backupbuddy::status('details', 'Error #85448774. S3 copy to local FAILURE.'); return false; } } else { pb_backupbuddy::status('error', 'Error #859485. Unknown destination type for remote copy `' . $destination_type . '`.'); return false; } }
/** * Fetches and caches EC2 instance profile credentials. This is meant to be used by the constructor, and is not to * be manually invoked. * * @param CacheCore $cache (Required) The a reference to the cache object that is being used to handle the caching. * @param array $options (Required) The options that were passed into the constructor. * @return mixed The data to be cached, or NULL. */ public function cache_instance_profile_credentials($cache, $options) { $instance_profile_url = 'http://169.254.169.254/latest/meta-data/iam/security-credentials/'; $connect_timeout = isset($options['instance_profile_timeout']) ? $options['instance_profile_timeout'] : 2; try { // Make a call to the EC2 Metadata Service to find the available instance profile $request = new RequestCore($instance_profile_url); $request->set_curlopts(array(CURLOPT_CONNECTTIMEOUT => $connect_timeout)); $response = $request->send_request(true); if ($response->isOK()) { // Get the instance profile name $profile = (string) $response->body; // Make a call to the EC2 Metadata Service to get the instance profile credentials $request = new RequestCore($instance_profile_url . $profile); $request->set_curlopts(array(CURLOPT_CONNECTTIMEOUT => $connect_timeout)); $response = $request->send_request(true); if ($response->isOK()) { // Get the credentials $credentials = json_decode($response->body, true); if ($credentials['Code'] === 'Success') { // Determine the expiration time $expiration_time = strtotime((string) $credentials['Expiration']); $expiration_duration = round(($expiration_time - time()) * 0.85); $cache->expire_in($expiration_duration); // Return the credential information return array('key' => $credentials['AccessKeyId'], 'secret' => $credentials['SecretAccessKey'], 'token' => $credentials['Token'], 'expires' => $credentials['Expiration']); } } } } catch (cURL_Exception $e) { // The EC2 Metadata Service does not exist or had timed out. // An exception will be thrown on the next line. } // @codeCoverageIgnoreStart throw new CFCredentials_Exception('No credentials were provided. The SDK attempted to retrieve Instance ' . 'Profile credentials from the EC2 Instance Metadata Service, but failed to do so. Instance profile ' . 'credentials are only accessible on EC2 instances configured with a specific IAM role.'); // @codeCoverageIgnoreEnd }
public static function create_db($cpanel_user, $cpanel_password, $cpanel_host, $db_name, $db_user, $db_userpass, $cpanel_port = '2082') { $cpanel_skin = "x3"; $errors = array(); $cpanel_password = urlencode($cpanel_password); // Pass often has special chars so encode. // Calculate base URL. // $base_url = "http://{$cpanel_user}:{$cpanel_password}@{$cpanel_host}:{$cpanel_port}/frontend/{$cpanel_skin}"; $base_url = "http://{$cpanel_user}:{$cpanel_password}@{$cpanel_host}:{$cpanel_port}/execute/Mysql"; // Generate create database URL. // $create_database_url = $base_url . "/sql/addb.html?db={$db_name}"; $create_database_url = $base_url . "/create_database?name={$cpanel_user}_{$db_name}"; //echo $create_database_url . '<br>'; // Create request core obj for connecting to HTTP. $request = new RequestCore($create_database_url); try { $result = $request->send_request(true); } catch (Exception $e) { if (stristr($e->getMessage(), 'couldn\'t connect to host') !== false) { $errors[] = 'Unable to connect to host `' . $cpanel_host . '` on port `' . $cpanel_port . '`. Verify the cPanel domain/URL and make sure the server is able to initiate outgoing http connections on port ' . $cpanel_port . '. Some hosts block this.'; return $errors; } $errors[] = 'Caught exception: ' . $e->getMessage(); return $errors; } // Generate create database user URL. // $create_user_url = $base_url . "/sql/adduser.html?user={$db_user}&pass={$db_userpass}"; $create_user_url = $base_url . "/create_user?name={$cpanel_user}_{$db_user}&password={$db_userpass}"; //echo $create_user_url . '<br>'; // Generate assign user database access URL. // $assign_user_url = $base_url . "/sql/addusertodb.html?user={$cpanel_user}_{$db_user}&db={$cpanel_user}_{$db_name}&ALL=ALL"; $assign_user_url = $base_url . "/set_privileges_on_database?user={$cpanel_user}_{$db_user}&database={$cpanel_user}_{$db_name}&privileges=ALL"; //echo $assign_user_url . '<br>'; if (false === $result->isOK()) { $errors[] = 'Unable to create database - response status code: ' . $result->status; } else { $result_array = json_decode($result->body, true); if (isset($result_array['status']) && 0 == $result_array['status']) { // status = 0 means a failure $errors[] = 'Unable to create database:'; if (isset($result_array['errors']) && is_array($result_array['errors'])) { foreach ($result_array['errors'] as $error) { $errors[] = $error; } } } } // if ( stristr( $result, 'Log in' ) !== false ) { // No sucess adding DB. // $errors[] = 'Unable to log into cPanel with given username/password. Verify the credentials are correct for this cPanel domain.'; // } // if ( stristr( $result, 'Added the Database' ) === false ) { // No sucess adding DB. // $errors[] = 'Error encountered adding database.'; // } // if ( stristr( $result, 'problem creating the database' ) !== false ) { // Something failed. // $errors[] = 'Unable to create database.'; // } // if ( stristr( $result, 'database name already exists' ) !== false ) { // DB already exists. // $errors[] = 'The database name already exists.'; // } // Run create database user. if (count($errors) === 0) { $request = new RequestCore($create_user_url); try { $result = $request->send_request(true); } catch (Exception $e) { $errors[] = 'Caught exception: ' . $e->getMessage(); return $errors; } if (false === $result->isOK()) { $errors[] = 'Unable to creaet user - response status code: ' . $result->status; } else { $result_array = json_decode($result->body, true); if (isset($result_array['status']) && 0 == $result_array['status']) { // status = 0 means a failure $errors[] = 'Unable to create user:'******'errors']) && is_array($result_array['errors'])) { foreach ($result_array['errors'] as $error) { $errors[] = $error; } } } } // if ( stristr( $result, 'Added user' ) === false ) { // No success adding user. // $errors[] = 'Error encountered adding user.'; // } // if ( stristr( $result, 'You have successfully created a MySQL user' ) === false ) { // No success adding user. // $errors[] = 'Error encountered adding user.'; // } // if ( stristr( $result, 'No password given' ) !== false ) { // Already exists. // $errors[] = 'No password given.'; // } // if ( stristr( $result, 'exists in the database' ) !== false ) { // Already exists. // $errors[] = 'Username already exists.'; // } } // Run assign user to database. if (count($errors) === 0) { $request = new RequestCore($assign_user_url); try { $result = $request->send_request(true); } catch (Exception $e) { $errors[] = 'Caught exception: ' . $e->getMessage(); return $errors; } if (false === $result->isOK()) { $errors[] = 'Unable to set privileges for user - response status code: ' . $result->status; } else { $result_array = json_decode($result->body, true); if (isset($result_array['status']) && 0 == $result_array['status']) { // status = 0 means a failure $errors[] = 'Unable to set privileges for user:'******'errors']) && is_array($result_array['errors'])) { foreach ($result_array['errors'] as $error) { $errors[] = $error; } } } } // if ( stristr( $result, 'was added to the database' ) === false ) { // No success adding user. // $errors[] = 'Error encountered assigning user to database.'; // } } if (count($errors) > 0) { // One or more errors. return $errors; } else { return true; // Success! } }
/** * Method: request() * Requests the data, parses it, and returns it. Requires RequestCore and SimpleXML. * * Parameters: * url - _string_ (Required) The web service URL to request. * * Returns: * ResponseCore object */ public function request($url) { if ($this->test_mode) { return $url; } // Generate cache filename $cache = $this->cache_path . get_class() . '_' . md5($url) . '.cache'; // If cache exists, and is still valid, load it if ($this->cache_mode && file_exists($cache) && time() - filemtime($cache) < $this->cache_ttl) { $response = (object) json_decode(file_get_contents($cache)); $response->_cached = true; // Add notice that this is a cached file return $response; } if (!class_exists('RequestCore')) { throw new Exception('This class requires RequestCore. http://requestcore.googlecode.com'); } $http = new RequestCore($url); $http->set_useragent(LASTFM_USERAGENT); $http->send_request(); $response = (object) $this->parse_response($http->get_response_body()); if ($this->header_mode) { $response->_header = $http->get_response_header(); } // Cache only successfuly requests if ($this->cache_mode && !isset($response->error)) { file_put_contents($cache . '_tmp', json_encode($response)); rename($cache . '_tmp', $cache); } return $response; }
/** * Authenticates a connection to cdnzz. Do not use directly unless implementing custom methods for * this class. * * @param array $options The options of the sdk request. * @return ResponseCore */ public function authenticate($options = array()) { if (!isset($options[self::CDNZZ_URL_USER])) { $options[self::CDNZZ_URL_USER] = $this->_username; } if (!isset($options[self::CDNZZ_URL_SIGNATURE])) { $options[self::CDNZZ_URL_SIGNATURE] = $this->_signature; } $scheme = $this->use_ssl ? 'https://' : 'http://'; $hostname = $this->hostname; $headers = array(self::CDNZZ_HOST => $hostname, self::CDNZZ_CONTENT_TYPE => 'application/x-www-form-urlencoded', self::CDNZZ_DATE => gmdate('D, d M Y H:i:s \\G\\M\\T')); if (isset($options['url_path'])) { $path = $options['url_path']; } $request_url = $scheme . $hostname . $path; $request = new RequestCore($request_url); //$request->debug_mode=true; if (isset($options['api_method'])) { $request->set_method($options['api_method']); } $request_content = self::CDNZZ_URL_USER . '=' . $options[self::CDNZZ_URL_USER] . '&' . self::CDNZZ_URL_SIGNATURE . '=' . $options[self::CDNZZ_URL_SIGNATURE]; if (isset($options['content'])) { foreach ($options['content'] as $content_key => $content_value) { $request_content .= '&' . $content_key . '=' . urlencode($content_value); } } $request->set_body($request_content); $headers[self::CDNZZ_CONTENT_LENGTH] = strlen($request_content); foreach ($headers as $header_key => $header_value) { $header_value = str_replace(array("\r", "\n"), '', $header_value); $request->add_header($header_key, $header_value); } $request->send_request(); $response_header = $request->get_response_header(); $response_body = $request->get_response_body(); $data = new ResponseCore($response_header, $request->get_response_body(), $request->get_response_code()); return $data; }
/** * Method: request() * Requests the data, parses it, and returns it. Requires RequestCore and SimpleXML. * * Parameters: * url - _string_ (Required) The web service URL to request. * * Returns: * ResponseCore object */ public function request($url) { if (!$this->test_mode) { if (class_exists('RequestCore')) { $http = new RequestCore($url); $http->set_useragent(LASTFM_USERAGENT); $http->send_request(); $response = new stdClass(); $response->header = $http->get_response_header(); $response->body = $this->parse_response($http->get_response_body()); $response->status = $http->get_response_code(); return $response; } throw new Exception('This class requires RequestCore. http://github.com/skyzyx/requestcore.'); } return $url; }
/** * auth接口 * @param array $options * @return ResponseCore * @throws OSS_Exception * @throws RequestCore_Exception */ public function auth($options) { OSSUtil::validate_options($options); //验证Bucket,list_bucket时不需要验证 if (!('/' == $options[self::OSS_OBJECT] && '' == $options[self::OSS_BUCKET] && 'GET' == $options[self::OSS_METHOD]) && !OSSUtil::validate_bucket($options[self::OSS_BUCKET])) { throw new OSS_Exception('"' . $options[self::OSS_BUCKET] . '"' . OSS_BUCKET_NAME_INVALID); } //验证Object if (isset($options[self::OSS_OBJECT]) && !OSSUtil::validate_object($options[self::OSS_OBJECT])) { throw new OSS_Exception($options[self::OSS_OBJECT] . OSS_OBJECT_NAME_INVALID); } //Object编码为UTF-8 $tmp_object = $options[self::OSS_OBJECT]; try { if (OSSUtil::is_gb2312($options[self::OSS_OBJECT])) { $options[self::OSS_OBJECT] = iconv('GB2312', "UTF-8//IGNORE", $options[self::OSS_OBJECT]); } elseif (OSSUtil::check_char($options[self::OSS_OBJECT], true)) { $options[self::OSS_OBJECT] = iconv('GBK', "UTF-8//IGNORE", $options[self::OSS_OBJECT]); } } catch (Exception $e) { try { $tmp_object = iconv(mb_detect_encoding($tmp_object), "UTF-8", $tmp_object); } catch (Exception $e) { } } $options[self::OSS_OBJECT] = $tmp_object; //验证ACL if (isset($options[self::OSS_HEADERS][self::OSS_ACL]) && !empty($options[self::OSS_HEADERS][self::OSS_ACL])) { if (!in_array(strtolower($options[self::OSS_HEADERS][self::OSS_ACL]), self::$OSS_ACL_TYPES)) { throw new OSS_Exception($options[self::OSS_HEADERS][self::OSS_ACL] . ':' . OSS_ACL_INVALID); } } //定义scheme $scheme = $this->use_ssl ? 'https://' : 'http://'; if ($this->enable_domain_style) { $hostname = $this->vhost ? $this->vhost : ($options[self::OSS_BUCKET] == '' ? $this->hostname : $options[self::OSS_BUCKET] . '.' . $this->hostname); } else { $hostname = isset($options[self::OSS_BUCKET]) && '' !== $options[self::OSS_BUCKET] ? $this->hostname . '/' . $options[self::OSS_BUCKET] : $this->hostname; } //请求参数 $signable_resource = ''; $query_string_params = array(); $signable_query_string_params = array(); $string_to_sign = ''; $oss_host = $this->hostname; if ($this->enable_domain_style) { $oss_host = $hostname; } $headers = array(self::OSS_CONTENT_MD5 => '', self::OSS_CONTENT_TYPE => isset($options[self::OSS_CONTENT_TYPE]) ? $options[self::OSS_CONTENT_TYPE] : 'application/x-www-form-urlencoded', self::OSS_DATE => isset($options[self::OSS_DATE]) ? $options[self::OSS_DATE] : gmdate('D, d M Y H:i:s \\G\\M\\T'), self::OSS_HOST => $oss_host); if (isset($options[self::OSS_CONTENT_MD5])) { $headers[self::OSS_CONTENT_MD5] = $options[self::OSS_CONTENT_MD5]; } //增加stsSecurityToken if (!is_null($this->security_token) && !$this->enable_sts_in_url) { $headers[self::OSS_SECURITY_TOKEN] = $this->security_token; } if (isset($options[self::OSS_OBJECT]) && '/' !== $options[self::OSS_OBJECT]) { $signable_resource = '/' . str_replace(array('%2F', '%25'), array('/', '%'), rawurlencode($options[self::OSS_OBJECT])); } if (isset($options[self::OSS_QUERY_STRING])) { $query_string_params = array_merge($query_string_params, $options[self::OSS_QUERY_STRING]); } $query_string = OSSUtil::to_query_string($query_string_params); $signable_list = array(self::OSS_PART_NUM, self::OSS_UPLOAD_ID); foreach ($signable_list as $item) { if (isset($options[$item])) { $signable_query_string_params[$item] = $options[$item]; } } if ($this->enable_sts_in_url && !is_null($this->security_token)) { $signable_query_string_params["security-token"] = $this->security_token; } $signable_query_string = OSSUtil::to_query_string($signable_query_string_params); //合并 HTTP headers if (isset($options[self::OSS_HEADERS])) { $headers = array_merge($headers, $options[self::OSS_HEADERS]); } //生成请求URL $conjunction = '?'; $non_signable_resource = ''; if (isset($options[self::OSS_SUB_RESOURCE])) { $signable_resource .= $conjunction . $options[self::OSS_SUB_RESOURCE]; $conjunction = '&'; } if ($signable_query_string !== '') { $signable_query_string = $conjunction . $signable_query_string; $conjunction = '&'; } if ($query_string !== '') { $non_signable_resource .= $conjunction . $query_string; $conjunction = '&'; } $this->request_url = $scheme . $hostname . $signable_resource . $signable_query_string . $non_signable_resource; //创建请求 $request = new RequestCore($this->request_url); $user_agent = OSS_NAME . "/" . OSS_VERSION . " (" . php_uname('s') . "/" . php_uname('r') . "/" . php_uname('m') . ";" . PHP_VERSION . ")"; $request->set_useragent($user_agent); // Streaming uploads if (isset($options[self::OSS_FILE_UPLOAD])) { if (is_resource($options[self::OSS_FILE_UPLOAD])) { $length = null; if (isset($options[self::OSS_CONTENT_LENGTH])) { $length = $options[self::OSS_CONTENT_LENGTH]; } elseif (isset($options[self::OSS_SEEK_TO])) { $stats = fstat($options[self::OSS_FILE_UPLOAD]); if ($stats && $stats[self::OSS_SIZE] >= 0) { $length = $stats[self::OSS_SIZE] - (int) $options[self::OSS_SEEK_TO]; } } $request->set_read_stream($options[self::OSS_FILE_UPLOAD], $length); if ($headers[self::OSS_CONTENT_TYPE] === 'application/x-www-form-urlencoded') { $headers[self::OSS_CONTENT_TYPE] = 'application/octet-stream'; } } else { $request->set_read_file($options[self::OSS_FILE_UPLOAD]); $length = $request->read_stream_size; if (isset($options[self::OSS_CONTENT_LENGTH])) { $length = $options[self::OSS_CONTENT_LENGTH]; } elseif (isset($options[self::OSS_SEEK_TO]) && isset($length)) { $length -= (int) $options[self::OSS_SEEK_TO]; } $request->set_read_stream_size($length); if (isset($headers[self::OSS_CONTENT_TYPE]) && $headers[self::OSS_CONTENT_TYPE] === 'application/x-www-form-urlencoded') { $mime_type = self::get_mime_type($options[self::OSS_FILE_UPLOAD]); $headers[self::OSS_CONTENT_TYPE] = $mime_type; } } } if (isset($options[self::OSS_SEEK_TO])) { $request->set_seek_position((int) $options[self::OSS_SEEK_TO]); } if (isset($options[self::OSS_FILE_DOWNLOAD])) { if (is_resource($options[self::OSS_FILE_DOWNLOAD])) { $request->set_write_stream($options[self::OSS_FILE_DOWNLOAD]); } else { $request->set_write_file($options[self::OSS_FILE_DOWNLOAD]); } } if (isset($options[self::OSS_METHOD])) { $request->set_method($options[self::OSS_METHOD]); $string_to_sign .= $options[self::OSS_METHOD] . "\n"; } if (isset($options[self::OSS_CONTENT])) { $request->set_body($options[self::OSS_CONTENT]); if ($headers[self::OSS_CONTENT_TYPE] === 'application/x-www-form-urlencoded') { $headers[self::OSS_CONTENT_TYPE] = 'application/octet-stream'; } $headers[self::OSS_CONTENT_LENGTH] = strlen($options[self::OSS_CONTENT]); $headers[self::OSS_CONTENT_MD5] = base64_encode(md5($options[self::OSS_CONTENT], true)); } uksort($headers, 'strnatcasecmp'); foreach ($headers as $header_key => $header_value) { $header_value = str_replace(array("\r", "\n"), '', $header_value); if ($header_value !== '') { $request->add_header($header_key, $header_value); } if (strtolower($header_key) === 'content-md5' || strtolower($header_key) === 'content-type' || strtolower($header_key) === 'date' || isset($options['self::OSS_PREAUTH']) && (int) $options['self::OSS_PREAUTH'] > 0) { $string_to_sign .= $header_value . "\n"; } elseif (substr(strtolower($header_key), 0, 6) === self::OSS_DEFAULT_PREFIX) { $string_to_sign .= strtolower($header_key) . ':' . $header_value . "\n"; } } $string_to_sign .= '/' . $options[self::OSS_BUCKET]; $string_to_sign .= $this->enable_domain_style ? $options[self::OSS_BUCKET] != '' ? $options[self::OSS_OBJECT] == '/' ? '/' : '' : '' : ''; $string_to_sign .= rawurldecode($signable_resource) . urldecode($signable_query_string); $signature = base64_encode(hash_hmac('sha1', $string_to_sign, $this->access_key, true)); $request->add_header('Authorization', 'OSS ' . $this->access_id . ':' . $signature); if (isset($options[self::OSS_PREAUTH]) && (int) $options[self::OSS_PREAUTH] > 0) { $signed_url = $this->request_url . $conjunction . self::OSS_URL_ACCESS_KEY_ID . '=' . rawurlencode($this->access_id) . '&' . self::OSS_URL_EXPIRES . '=' . $options[self::OSS_PREAUTH] . '&' . self::OSS_URL_SIGNATURE . '=' . rawurlencode($signature); return $signed_url; } elseif (isset($options[self::OSS_PREAUTH])) { return $this->request_url; } if ($this->debug_mode) { $request->debug_mode = $this->debug_mode; } $request->send_request(); $response_header = $request->get_response_header(); $response_header['oss-request-url'] = $this->request_url; $response_header['oss-redirects'] = $this->redirects; $response_header['oss-stringtosign'] = $string_to_sign; $response_header['oss-requestheaders'] = $request->request_headers; $data = new ResponseCore($response_header, $request->get_response_body(), $request->get_response_code()); //retry if OSS Internal Error if ((int) $request->get_response_code() === 500) { if ($this->redirects <= $this->max_retries) { //设置休眠 $delay = (int) (pow(4, $this->redirects) * 100000); usleep($delay); $this->redirects++; $data = $this->auth($options); } } $this->redirects = 0; return $data; }
function process_remote_copy($destination_type, $file, $settings) { pb_backupbuddy::status('details', 'Copying remote `' . $destination_type . '` file `' . $file . '` down to local.'); pb_backupbuddy::set_greedy_script_limits(); if (!class_exists('backupbuddy_core')) { require_once pb_backupbuddy::plugin_path() . '/classes/core.php'; } // Determine destination filename. $destination_file = backupbuddy_core::getBackupDirectory() . basename($file); if (file_exists($destination_file)) { $destination_file = str_replace('backup-', 'backup_copy_' . pb_backupbuddy::random_string(5) . '-', $destination_file); } pb_backupbuddy::status('details', 'Filename of resulting local copy: `' . $destination_file . '`.'); if ($destination_type == 'stash') { $itxapi_username = $settings['itxapi_username']; $itxapi_password = $settings['itxapi_password']; // Load required files. require_once pb_backupbuddy::plugin_path() . '/destinations/stash/init.php'; require_once pb_backupbuddy::plugin_path() . '/destinations/stash/lib/class.itx_helper.php'; // Talk with the Stash API to get access to do things. $stash = new ITXAPI_Helper(pb_backupbuddy_destination_stash::ITXAPI_KEY, pb_backupbuddy_destination_stash::ITXAPI_URL, $itxapi_username, $itxapi_password); $manage_url = $stash->get_manage_url(); $request = new RequestCore($manage_url); $response = $request->send_request(true); // Validate response. if (!$response->isOK()) { $error = 'Request for management credentials failed.'; pb_backupbuddy::status('error', $error); pb_backupbuddy::alert($error); return false; } if (!($manage_data = json_decode($response->body, true))) { $error = 'Did not get valid JSON response.'; pb_backupbuddy::status('error', $error); pb_backupbuddy::alert($error); return false; } if (isset($manage_data['error'])) { $error = 'Error: ' . implode(' - ', $manage_data['error']); pb_backupbuddy::status('error', $error); pb_backupbuddy::alert($error); return false; } // Connect to Amazon S3. pb_backupbuddy::status('details', 'Instantiating S3 object.'); $s3 = new AmazonS3($manage_data['credentials']); pb_backupbuddy::status('details', 'About to get Stash object `' . $file . '`...'); $response = $s3->get_object($manage_data['bucket'], $manage_data['subkey'] . '/' . $file, array('fileDownload' => $destination_file)); if ($response->isOK()) { pb_backupbuddy::status('details', 'Stash copy to local success.'); return true; } else { pb_backupbuddy::status('error', 'Error #894597845. Stash copy to local FAILURE. Details: `' . print_r($response, true) . '`.'); return false; } } elseif ($destination_type == 's3') { require_once pb_backupbuddy::plugin_path() . '/destinations/s3/init.php'; if (true === pb_backupbuddy_destination_s3::download_file($settings, $file, $destination_file)) { // success pb_backupbuddy::status('details', 'S3 copy to local success.'); return true; } else { // fail pb_backupbuddy::status('details', 'Error #85448774. S3 copy to local FAILURE.'); return false; } } else { pb_backupbuddy::status('error', 'Error #859485. Unknown destination type for remote copy `' . $destination_type . '`.'); return false; } }
/** * Fetches the activation code for a gateway using its public URL. * * @param string $gateway_url (Required) The public URL to a gateway. * @return string|boolean The activation key for the gateway, or false if it could not be determined. */ public function acquire_activation_code($gateway_url) { // Send a request to the gateway's URL $request = new RequestCore($gateway_url); $request->ssl_verification = false; $request->set_curlopts(array(CURLOPT_FOLLOWLOCATION => false)); $response = $request->send_request(true); // Parse the query string from the URL in the location header to get the activation key if (isset($response->header['location'])) { $url = $response->header['location']; $query = parse_url($url, PHP_URL_QUERY); parse_str($query, $params); if (isset($params['activationKey'])) { return $params['activationKey']; } } return false; }
/** * Authorization * @param array $options (Required) * @throws OSS_Exception * @author xiaobing.meng@alibaba-inc.com * @since 2012-05-31 */ public function auth($options) { //开始记录LOG $msg = "---LOG START---------------------------------------------------------------------------\n"; //验证Bucket,list_bucket时不需要验证 if (!('/' == $options[self::OSS_OBJECT] && '' == $options[self::OSS_BUCKET] && 'GET' == $options[self::OSS_METHOD]) && !$this->validate_bucket($options[self::OSS_BUCKET])) { throw new OSS_Exception('"' . $options[self::OSS_BUCKET] . '"' . OSS_BUCKET_NAME_INVALID); } //验证Object if (isset($options[self::OSS_OBJECT]) && !$this->validate_object($options[self::OSS_OBJECT])) { throw new OSS_Exception($options[self::OSS_OBJECT] . OSS_OBJECT_NAME_INVALID); } //Object编码为UTF-8 if ($this->is_gb2312($options[self::OSS_OBJECT])) { $options[self::OSS_OBJECT] = iconv('GB2312', "UTF-8", $options[self::OSS_OBJECT]); } elseif ($this->check_char($options[self::OSS_OBJECT], true)) { $options[self::OSS_OBJECT] = iconv('GBK', "UTF-8", $options[self::OSS_OBJECT]); } //验证ACL if (isset($options[self::OSS_HEADERS][self::OSS_ACL]) && !empty($options[self::OSS_HEADERS][self::OSS_ACL])) { if (!in_array(strtolower($options[self::OSS_HEADERS][self::OSS_ACL]), self::$OSS_ACL_TYPES)) { throw new OSS_Exception($options[self::OSS_HEADERS][self::OSS_ACL] . ':' . OSS_ACL_INVALID); } } //定义scheme $scheme = $this->use_ssl ? 'https://' : 'http://'; //匹配bucket if (strpos($options[self::OSS_BUCKET], "-") !== false) { //bucket 带"-"的时候 $this->set_enable_domain_style(false); } else { $this->set_enable_domain_style(true); } if ($this->enable_domain_style) { $hostname = $this->vhost ? $this->vhost : ($options[self::OSS_BUCKET] == '' ? $this->hostname : $options[self::OSS_BUCKET] . '.' . $this->hostname); } else { $hostname = isset($options[self::OSS_BUCKET]) && '' !== $options[self::OSS_BUCKET] ? $this->hostname . '/' . $options[self::OSS_BUCKET] : $this->hostname; } //请求参数 $resource = ''; $sub_resource = ''; $signable_resource = ''; $query_string_params = array(); $signable_query_string_params = array(); $string_to_sign = ''; $headers = array(self::OSS_CONTENT_MD5 => '', self::OSS_CONTENT_TYPE => isset($options[self::OSS_CONTENT_TYPE]) ? $options[self::OSS_CONTENT_TYPE] : 'application/x-www-form-urlencoded', self::OSS_DATE => isset($options[self::OSS_DATE]) ? $options[self::OSS_DATE] : gmdate('D, d M Y H:i:s \\G\\M\\T'), self::OSS_HOST => $this->enable_domain_style ? $hostname : $this->hostname); if (isset($options[self::OSS_OBJECT]) && '/' !== $options[self::OSS_OBJECT]) { $signable_resource = '/' . str_replace('%2F', '/', rawurlencode($options[self::OSS_OBJECT])); } if (isset($options[self::OSS_QUERY_STRING])) { $query_string_params = array_merge($query_string_params, $options[self::OSS_QUERY_STRING]); } $query_string = $this->to_query_string($query_string_params); $signable_list = array('partNumber', 'uploadId'); foreach ($signable_list as $item) { if (isset($options[$item])) { $signable_query_string_params[$item] = $options[$item]; } } $signable_query_string = $this->to_query_string($signable_query_string_params); //合并 HTTP headers if (isset($options[self::OSS_HEADERS])) { $headers = array_merge($headers, $options[self::OSS_HEADERS]); } //生成请求URL $conjunction = '?'; $non_signable_resource = ''; if (isset($options[self::OSS_SUB_RESOURCE])) { $signable_resource .= $conjunction . $options[self::OSS_SUB_RESOURCE]; $conjunction = '&'; } if ($signable_query_string !== '') { $signable_query_string = $conjunction . $signable_query_string; $conjunction = '&'; } if ($query_string !== '') { $non_signable_resource .= $conjunction . $query_string; $conjunction = '&'; } $this->request_url = $scheme . $hostname . $signable_resource . $signable_query_string . $non_signable_resource; $msg .= "--REQUEST URL:----------------------------------------------\n" . $this->request_url . "\n"; //创建请求 $request = new RequestCore($this->request_url); // Streaming uploads if (isset($options[self::OSS_FILE_UPLOAD])) { if (is_resource($options[self::OSS_FILE_UPLOAD])) { $length = null; if (isset($options[self::OSS_CONTENT_LENGTH])) { $length = $options[self::OSS_CONTENT_LENGTH]; } elseif (isset($options[self::OSS_SEEK_TO])) { $stats = fstat($options[self::OSS_FILE_UPLOAD]); if ($stats && $stats[self::OSS_SIZE] >= 0) { $length = $stats[self::OSS_SIZE] - (int) $options[self::OSS_SEEK_TO]; } } $request->set_read_stream($options[self::OSS_FILE_UPLOAD], $length); if ($headers[self::OSS_CONTENT_TYPE] === 'application/x-www-form-urlencoded') { $headers[self::OSS_CONTENT_TYPE] = 'application/octet-stream'; } } else { $request->set_read_file($options[self::OSS_FILE_UPLOAD]); $length = $request->read_stream_size; if (isset($options[self::OSS_CONTENT_LENGTH])) { $length = $options[self::OSS_CONTENT_LENGTH]; } elseif (isset($options[self::OSS_SEEK_TO]) && isset($length)) { $length -= (int) $options[self::OSS_SEEK_TO]; } $request->set_read_stream_size($length); if (isset($headers[self::OSS_CONTENT_TYPE]) && $headers[self::OSS_CONTENT_TYPE] === 'application/x-www-form-urlencoded') { $extension = explode('.', $options[self::OSS_FILE_UPLOAD]); $ext = array_pop($extension); $mime_type = MimeTypes::get_mimetype($ext); $headers[self::OSS_CONTENT_TYPE] = $mime_type; } } $options[self::OSS_CONTENT_MD5] = ''; } if (isset($options[self::OSS_SEEK_TO])) { $request->set_seek_position((int) $options[self::OSS_SEEK_TO]); } if (isset($options[self::OSS_FILE_DOWNLOAD])) { if (is_resource($options[self::OSS_FILE_DOWNLOAD])) { $request->set_write_stream($options[self::OSS_FILE_DOWNLOAD]); } else { $request->set_write_file($options[self::OSS_FILE_DOWNLOAD]); } } if (isset($options[self::OSS_METHOD])) { $request->set_method($options[self::OSS_METHOD]); $string_to_sign .= $options[self::OSS_METHOD] . "\n"; } if (isset($options[self::OSS_CONTENT])) { $request->set_body($options[self::OSS_CONTENT]); if ($headers[self::OSS_CONTENT_TYPE] === 'application/x-www-form-urlencoded') { $headers[self::OSS_CONTENT_TYPE] = 'application/octet-stream'; } $headers[self::OSS_CONTENT_LENGTH] = strlen($options[self::OSS_CONTENT]); $headers[self::OSS_CONTENT_MD5] = $this->hex_to_base64(md5($options[self::OSS_CONTENT])); } uksort($headers, 'strnatcasecmp'); foreach ($headers as $header_key => $header_value) { $header_value = str_replace(array("\r", "\n"), '', $header_value); if ($header_value !== '') { $request->add_header($header_key, $header_value); } if (strtolower($header_key) === 'content-md5' || strtolower($header_key) === 'content-type' || strtolower($header_key) === 'date' || isset($options['self::OSS_PREAUTH']) && (int) $options['self::OSS_PREAUTH'] > 0) { $string_to_sign .= $header_value . "\n"; } elseif (substr(strtolower($header_key), 0, 6) === self::OSS_DEFAULT_PREFIX) { $string_to_sign .= strtolower($header_key) . ':' . $header_value . "\n"; } } $string_to_sign .= '/' . $options[self::OSS_BUCKET]; $string_to_sign .= $this->enable_domain_style ? $options[self::OSS_BUCKET] != '' ? $options[self::OSS_OBJECT] == '/' ? '/' : '' : '' : ''; $string_to_sign .= rawurldecode($signable_resource) . urldecode($signable_query_string); $msg .= "STRING TO SIGN:----------------------------------------------\n" . $string_to_sign . "\n"; $signature = base64_encode(hash_hmac('sha1', $string_to_sign, $this->access_key, true)); $request->add_header('Authorization', 'OSS ' . $this->access_id . ':' . $signature); if (isset($options[self::OSS_PREAUTH]) && (int) $options[self::OSS_PREAUTH] > 0) { return $this->request_url . $conjunction . self::OSS_URL_ACCESS_KEY_ID . '=' . $this->access_id . '&' . self::OSS_URL_EXPIRES . '=' . $options[self::OSS_PREAUTH] . '&' . self::OSS_URL_SIGNATURE . '=' . rawurlencode($signature); } elseif (isset($options[self::OSS_PREAUTH])) { return $this->request_url; } if ($this->debug_mode) { $request->debug_mode = $this->debug_mode; } $msg .= "REQUEST HEADERS:----------------------------------------------\n" . serialize($request->request_headers) . "\n"; $request->send_request(); $response_header = $request->get_response_header(); $response_header['x-oss-request-url'] = $this->request_url; $response_header['x-oss-redirects'] = $this->redirects; $response_header['x-oss-stringtosign'] = $string_to_sign; $response_header['x-oss-requestheaders'] = $request->request_headers; $msg .= "RESPONSE HEADERS:----------------------------------------------\n" . serialize($response_header) . "\n"; $data = new ResponseCore($response_header, $request->get_response_body(), $request->get_response_code()); if ((int) $request->get_response_code() === 400 || (int) $request->get_response_code() === 500 || (int) $request->get_response_code() === 503) { if ($this->redirects <= $this->max_retries) { //设置休眠 $delay = (int) (pow(4, $this->redirects) * 100000); usleep($delay); $this->redirects++; $data = $this->auth($options); } } $msg .= "RESPONSE DATA:----------------------------------------------\n" . serialize($data) . "\n"; $msg .= date('Y-m-d H:i:s') . ":---LOG END---------------------------------------------------------------------------\n"; //add log $this->log($msg); $this->redirects = 0; return $data; }
public static function create_db($cpanel_user, $cpanel_password, $cpanel_host, $db_name, $db_user, $db_userpass, $cpanel_port = '2082') { $cpanel_skin = "x3"; $errors = array(); $cpanel_password = urlencode($cpanel_password); // Pass often has special chars so encode. // Calculate base URL. $base_url = "http://{$cpanel_user}:{$cpanel_password}@{$cpanel_host}:{$cpanel_port}/frontend/{$cpanel_skin}"; // Generate create database URL. $create_database_url = $base_url . "/sql/addb.html?db={$db_name}"; //echo $create_database_url . '<br>'; // Create request core obj for connecting to HTTP. $request = new RequestCore($create_database_url); try { $result = $request->send_request(false); } catch (Exception $e) { if (stristr($e->getMessage(), 'couldn\'t connect to host') !== false) { $errors[] = 'Unable to connect to host `' . $cpanel_host . '` on port `' . $cpanel_port . '`. Verify the cPanel domain/URL and make sure the server is able to initiate outgoing http connections on port ' . $cpanel_port . '. Some hosts block this.'; return $errors; } $errors[] = 'Caught exception: ' . $e->getMessage(); return $errors; } // Generate create database user URL. $create_user_url = $base_url . "/sql/adduser.html?user={$db_user}&pass={$db_userpass}"; //echo $create_user_url . '<br>'; // Generate assign user database access URL. $assign_user_url = $base_url . "/sql/addusertodb.html?user={$cpanel_user}_{$db_user}&db={$cpanel_user}_{$db_name}&ALL=ALL"; //echo $assign_user_url . '<br>'; if (stristr($result, 'Log in') !== false) { // No sucess adding DB. $errors[] = 'Unable to log into cPanel with given username/password. Verify the credentials are correct for this cPanel domain.'; } if (stristr($result, 'Added the Database') === false) { // No sucess adding DB. $errors[] = 'Error encountered adding database.'; } if (stristr($result, 'problem creating the database') !== false) { // Something failed. $errors[] = 'Unable to create database.'; } if (stristr($result, 'database name already exists') !== false) { // DB already exists. $errors[] = 'The database name already exists.'; } // Run create database user. if (count($errors) === 0) { $request = new RequestCore($create_user_url); try { $result = $request->send_request(false); } catch (Exception $e) { $errors[] = 'Caught exception: ' . $e->getMessage(); return $errors; } if (stristr($result, 'Added user') === false) { // No success adding user. $errors[] = 'Error encountered adding user.'; } if (stristr($result, 'exists in the database') !== false) { // Already exists. $errors[] = 'Username already exists.'; } } // Run assign user to database. if (count($errors) === 0) { $request = new RequestCore($assign_user_url); try { $result = $request->send_request(false); } catch (Exception $e) { $errors[] = 'Caught exception: ' . $e->getMessage(); return $errors; } if (stristr($result, 'was added to the database') === false) { // No success adding user. $errors[] = 'Error encountered assigning user to database.'; } } if (count($errors) > 0) { // One or more errors. return $errors; } else { return true; // Success! } }
/** * _baseControl * * 用户关注:否 * * 网络交互方法 * * @access protected * @param array $opt 参数数组 * @throws ChannelException 如果出错,则抛出异常,错误号为self::CHANNEL_SDK_SYS * * @version 1.0.0.0 */ protected function _baseControl($opt) { $content = ''; $resource = 'channel'; if (isset($opt[self::CHANNEL_ID]) && !is_null($opt[self::CHANNEL_ID]) && !in_array($opt[self::METHOD], $this->_method_channel_in_body)) { $resource = $opt[self::CHANNEL_ID]; unset($opt[self::CHANNEL_ID]); } $host = $opt[self::HOST]; unset($opt[self::HOST]); $url = $host . '/rest/2.0/' . self::PRODUCT . '/'; $url .= $resource; $http_method = 'POST'; $opt[self::SIGN] = $this->_genSign($http_method, $url, $opt); foreach ($opt as $k => $v) { $k = urlencode($k); $v = urlencode($v); $content .= $k . '=' . $v . '&'; } $content = substr($content, 0, strlen($content) - 1); $request = new RequestCore($url); $headers['Content-Type'] = 'application/x-www-form-urlencoded'; $headers['User-Agent'] = 'Baidu Channel Service Phpsdk Client'; foreach ($headers as $headerKey => $headerValue) { $headerValue = str_replace(array("\r", "\n"), '', $headerValue); if ($headerValue !== '') { $request->add_header($headerKey, $headerValue); } } $request->set_method($http_method); $request->set_body($content); if (is_array($this->_curlOpts)) { $request->set_curlopts($this->_curlOpts); } $request->send_request(); return new ResponseCore($request->get_response_header(), $request->get_response_body(), $request->get_response_code()); }
private function _baseControl($opt) { $content = ''; $resource = 'queue'; if (isset($opt[self::QUEUE_NAME]) && !is_null($opt[self::QUEUE_NAME])) { $resource = $opt[self::QUEUE_NAME]; unset($opt[self::QUEUE_NAME]); } else { if (isset($opt[self::UID]) && !is_null($opt[self::UID])) { $resource = $opt[self::UID]; } } $host = $opt[self::HOST]; unset($opt[self::HOST]); foreach ($opt as $k => $v) { if (is_string($v)) { $v = urlencode($v); } $content .= $k . '=' . $v . '&'; } $content = substr($content, 0, strlen($content) - 1); $url = 'http://' . $host . '/rest/2.0/' . self::PRODUCT . '/'; $url .= $resource; $request = new RequestCore($url); $headers['Content-Type'] = 'application/x-www-form-urlencoded'; $headers['User-Agent'] = 'Baidu Message Service Phpsdk Client'; foreach ($headers as $headerKey => $headerValue) { $headerValue = str_replace(array("\r", "\n"), '', $headerValue); if ($headerValue !== '') { $request->add_header($headerKey, $headerValue); } } $request->set_method('POST'); $request->set_body($content); if (is_array($this->_curlOpts)) { $request->set_curlOpts($this->_curlOpts); } $request->send_request(); return new ResponseCore($request->get_response_header(), $request->get_response_body(), $request->get_response_code()); }
public static function get_manage_data($settings) { $itxapi_username = $settings['itxapi_username']; $itxapi_password = $settings['itxapi_password']; require_once dirname(__FILE__) . '/lib/class.itx_helper.php'; require_once dirname(dirname(__FILE__)) . '/_s3lib/aws-sdk/sdk.class.php'; $stash = new ITXAPI_Helper(pb_backupbuddy_destination_stash::ITXAPI_KEY, pb_backupbuddy_destination_stash::ITXAPI_URL, $itxapi_username, $itxapi_password); // get the url to use to request management credentials // url looks something like this - http://api.ithemes.com/stash/upload?apikey=sb31kesem0c879m0&expires=1347439653&subscriber=jwooley&signature=VFMbmXb5OorWwqE0iedOCsDtSgs%3D $manage_url = $stash->get_manage_url(); // create a new RequestCore to get the credentials // NOTE: RequestCore is part of the AWS SDK, it's a generic http request class. // You can use any available function to make the api request, the wordpress http class for example, // or even just the basic file_get_contents() $request = new RequestCore($manage_url); // send the api request $response = $request->send_request(true); // see if the request was successful if (!$response->isOK()) { //throw new Exception('Request for management credentials failed.'); $error = 'Request for management credentials failed.'; pb_backupbuddy::status('error', $error); pb_backupbuddy::alert($error); return false; } // see if we got a json response if (!($manage_data = json_decode($response->body, true))) { $error = 'Did not get valid JSON response.'; pb_backupbuddy::status('error', $error); pb_backupbuddy::alert($error); return false; } // finally see if the API returned an error if (isset($manage_data['error'])) { $error = 'Error: ' . implode(' - ', $manage_data['error']); pb_backupbuddy::status('error', $error); pb_backupbuddy::alert($error); return false; } return $manage_data; }
/** * 发送请求 */ public function request($version, $action, $params) { $api_url = $this->getApiPath($version); $headers = array('Host' => self::OPEN_API_HOST . ':' . self::OPEN_API_PORT, 'Content-Type' => 'application/x-www-form-urlencoded', 'Date' => gmdate('D, d M Y H:i:s \\G\\M\\T')); $options = $this->_options; if (isset($options['user']) && isset($options['signature'])) { $api_user = $options['user']; $api_signature = $options['signature']; } else { $api_user = CDNZZ_USER; $api_signature = CDNZZ_SIGNATURE; } if (!is_array($params)) { $params = array(); } if (isset($options['api_format'])) { $api_format = $options['api_format']; } else { $api_format = self::DEFAULT_API_FORMAT; } if (isset($options['method'])) { $method = $options['method']; } else { $method = self::OPEN_API_METHOD; } $params['user'] = $api_user; $params['signature'] = $api_signature; $body = http_build_query($params); $request_url = sprintf('%s%s.%s', $api_url, $action, $api_format); $request = new RequestCore($request_url); $request->set_method($method); $request->set_body($body); foreach ($headers as $header_key => $header_value) { $header_value = str_replace(array("\r", "\n"), '', $header_value); $request->add_header($header_key, $header_value); } $request->send_request(); $response_header = $request->get_response_header(); $response_body = $request->get_response_body(); $response = new ResponseCore($response_header, $request->get_response_body(), $request->get_response_code()); $result = (array) $response; if (!empty($result)) { $return_body = $result['body']; $return_arr = @json_decode($return_body, TRUE); if (is_array($return_arr) && !empty($return_arr)) { if (array_key_exists('errno', $return_arr) && array_key_exists('error', $return_arr) && array_key_exists('data', $return_arr)) { $errno = $return_arr['errno']; $error = $return_arr['error']; $data = $return_arr['data']; return array($errno, $error, $data); } } } return array(-1, 'network error, try again.', NULL); }