/** * 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>'; } }
/** * Method: __construct() * The constructor * * Access: * public * * Parameters: * $url - _string_ (Optional) The URL to request or service endpoint to query. * $proxy - _string_ (Optional) The faux-url to use for proxy settings. Takes the following format: `proxy://user:pass@hostname:port` * $helpers - _array_ (Optional) An associative array of classnames to use for request, and response functionality. Gets passed in automatically by the calling class. * * Returns: * `$this` */ public function __construct($url = null, $proxy = null, $helpers = null) { parent::__construct($url, $proxy, $helpers); // Standard settings for all requests $this->add_header('Expect', '100-continue'); $this->set_useragent(CFRUNTIME_USERAGENT); return $this; }
/** * Constructs a new instance of this class. * * @param string $url (Optional) The URL to request or service endpoint to query. * @param string $proxy (Optional) The faux-url to use for proxy settings. Takes the following format: `proxy://user:pass@hostname:port` * @param array $helpers (Optional) An associative array of classnames to use for request, and response functionality. Gets passed in automatically by the calling class. * @return $this A reference to the current instance. */ public function __construct($url = null, $proxy = null, $helpers = null) { parent::__construct($url, $proxy, $helpers); // Standard settings for all requests $this->add_header('Expect', '100-continue'); $this->set_useragent(CFRUNTIME_USERAGENT); $this->cacert_location = strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' ? true : (defined('AWS_CERTIFICATE_AUTHORITY') ? AWS_CERTIFICATE_AUTHORITY : false); return $this; }
/** * Constructs a new instance of this class. * * @param string $url (Optional) The URL to request or service endpoint to query. * @param string $proxy (Optional) The faux-url to use for proxy settings. Takes the following format: `proxy://user:pass@hostname:port` * @param array $helpers (Optional) An associative array of classnames to use for request, and response functionality. Gets passed in automatically by the calling class. * @param CFCredential $credentials (Required) The credentials to use for signing and making requests. * @return $this A reference to the current instance. */ public function __construct($url = null, $proxy = null, $helpers = null, CFCredential $credentials = null) { parent::__construct($url, $proxy, $helpers); // Standard settings for all requests $this->set_useragent(CFRUNTIME_USERAGENT); $this->credentials = $credentials; $this->cacert_location = $this->credentials['certificate_authority'] ? $this->credentials['certificate_authority'] : false; return $this; }
function closeRequestAdditionalActions($requestId) { $messageArray = array("message_value" => "Solicitud cerrada con éxito!", "message_type" => "success"); $handlerRequestCore = new RequestCore(); $requestData = $handlerRequestCore->getRequestData($requestId); // Poner aquí los ID de flujo para customización switch ($requestData["request_flow"]) { // Proceso de reclamos case '1': $messageArray = reclamoFinalizado($requestId); break; // Proceso de adquisiciones // Proceso de adquisiciones case '2': $messageArray = requisicionFinalizada($requestId); break; } return $messageArray; }
private function _preControl($http, $apiMethod, $params, $method = 'GET', $headers = array()) { $method = strtoupper($method); if (is_array($params)) { $params = http_build_query($params, '', '&'); } $url = $this->_pcs_uri_prefixs[$http] . $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; }
function crearSolicitudTarea($tipo, $id, $fecha_inicio, $fecha_fin, $titulo, $descripcion, $encargado, $prioridad, $proyeccion, $url) { LogController::logWebServiceIn('Llamada a web service: ' . __FILE__ . ' - ' . __FUNCTION__, compact('tipo', 'id', 'fecha_inicio', 'fecha_fin', 'titulo', 'descripcion', 'encargado', 'prioridad', 'proyeccion', 'url')); $returnMessage = ""; $handlerAttachmentCore = new AttachmentCore(); $handlerRequestCore = new RequestCore(); $handlerUserCore = new UserCore(); $handlerFlowSettingsCore = new FlowSettingsCore(); // Tomar datos de aprobador $flow = Flow::find(FLOW_TAREAS); $creador = User::find($encargado); if ($creador) { $jefe = User::find($creador->user_reports_to); if (!$jefe) { $jefe = User::find($flow->flow_administrator); } // Crear solicitud $request_flow = $flow->flow_id; $request_id = $handlerRequestCore->getLastGeneralRequestId() + 1; $inner_request_id = $handlerRequestCore->getLastGeneralRequestId($request_flow) + 1; $request_name = "Aprobación: " . $titulo; $request_description = "Aprobación de tarea: " . $descripcion; $request_createdby = $creador->user_id; $request_assignedto = $jefe->user_id; $handlerRequestCore->createNewRequest($request_id, $inner_request_id, $request_flow, $request_name, $request_description, $request_createdby, $request_assignedto); Tarea::create(["ef_id" => $request_id, "ext_id" => $id, "tipo" => $tipo, "titulo" => $titulo, "descripcion" => $descripcion, "encargado" => $request_createdby, "aprobador_1" => $request_assignedto, "aprobador_2" => "", "fecha_inicio" => $fecha_inicio, "fecha_fin" => $fecha_fin, "prioridad" => $prioridad, "proyeccion" => $proyeccion]); RequestMetadataCore::set($request_id, "APR-DOBLE-APROBACION", "No"); RequestMetadataCore::set($request_id, "APR-APROBADO", "No"); RequestMetadataCore::set($request_id, "APR-COMENTARIO", ""); //Tomar archivo de campo url y adjuntar if ($url != '') { $tmpFileName = basename($url); file_put_contents($tmpFileName, fopen($url, 'r')); $filetype = FlowSettingsCore::get($request_flow, "APR_FILE_ADJUNTO"); $handlerAttachmentCore->addAttachmentToRequest($request_id, $filetype, dirname(__FILE__) . "/" . $tmpFileName, $_SESSION["environment_path"], "admin", "Adjunto de tarea"); } } else { $returnMessage = "ERROR: Usuario " . $encargado . " no existe en BPM. Imposible continuar"; } return $returnMessage; }
/** * Constructs a new instance of this class. * * @param string $url (Optional) The URL to request or service endpoint to query. * @param string $proxy (Optional) The faux-url to use for proxy settings. Takes the following format: `proxy://user:pass@hostname:port` * @param array $helpers (Optional) An associative array of classnames to use for request, and response functionality. Gets passed in automatically by the calling class. * @param CFCredential $credentials (Required) The credentials to use for signing and making requests. * @return $this A reference to the current instance. */ public function __construct($url = null, $proxy = null, $helpers = null, CFCredential $credentials = null) { parent::__construct($url, $proxy, $helpers); // Standard settings for all requests $this->set_useragent(CFRUNTIME_USERAGENT); $this->credentials = $credentials; $this->cacert_location = $this->credentials['certificate_authority'] ? $this->credentials['certificate_authority'] : false; if (strpos(parse_url($url, PHP_URL_HOST), 'dynamodb') === 0) { $this->use_gzip_enconding = false; } return $this; }
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("签名上传字符串失败"); } }
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; } }
/** * Consolida las requisiciones correspondientes y mueve las solicitudes en EF * @return Array */ public function consolidarRequisiciones() { $returnArray = array('status' => true, 'message' => ''); $input = Request::createFromGlobals(); $requestCore = new \RequestCore(); $flow = $_SESSION['user_flow']; $step = FlowSettings::get($_SESSION['user_flow'], 'ADQ_STEP_CONSOLIDATION'); $requisiciones = Requisicion::getRequisicionesParaConsolidar(); $ordenescompra = OrdenCompra::getOrdenesCompraParaConsolidar(); // Tomar la tarea actual, si no está completada salir foreach ($requisiciones as $requisicion) { if ($requisicion->asignada_totalmente == 0) { $returnArray['status'] = false; $returnArray['message'] = 'La requisición ' . $requisicion->id . ' no se encuentra asignada por completo. No se puede continuar'; return $returnArray; } } // Cambiar estado de las ordenes de compra cuyas requisiciones estén totalmente asignadas foreach ($ordenescompra as $ordencompra) { $ordencompra->estado = 'C'; $ordencompra->save(); } foreach ($requisiciones as $requisicion) { // Solo completar tareas de requisiciones asignadas totalmente if ($requisicion->asignada_totalmente == 1) { // Cambiar estado a 'C' (Consolidada) $requisicion->estado = 'C'; $requisicion->save(); $task = $requisicion->ef_request->open_tasks[0]; // Completar tareas diferentes a la actual // (No se completa la actual porque EF lo hace por default) if ($task->task_id != $input->task_id) { $requestCore->completeTask($task->task_request, $task->task_id, $input->flow_id, $input->step_id, $input->user_id, 'Requisición consolidada por el usuario ' . $_SESSION['user_id'], 'next'); } } } return $returnArray; }
/** * 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; }
/** * 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 }
/** * 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; }
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; } }
public function procesarOrdenesCompra() { $input = Request::createFromGlobals(); $returnArray = array('status' => true, 'message' => ''); $requestCore = new \RequestCore(); $arrayRequisiciones = []; // Traer ordenes de compra $ordenes_compra = $this->getOrdenesCompra($input->request_id); // Iterar las ordenes de compra foreach ($ordenes_compra as $orden_compra) { // Verificar solo las que tengan cotización seleccionada $seleccionada = false; $cotizaciones = $orden_compra->cotizaciones; foreach ($cotizaciones as $cotizacion) { if ($cotizacion->estado == 'S') { $seleccionada = true; break; } } if ($seleccionada) { // Actualizar cabecera de OC $orden_compra->update(['estado' => 'S']); // Llenar arreglo con número de requisiciones correspondientes foreach ($orden_compra->lineas as $linea) { $arrayRequisiciones[] = $linea->linea_requisicion->requisicion->id; } } } // Mover ef_requests correspondientes $arrayRequisiciones = array_unique($arrayRequisiciones); foreach ($arrayRequisiciones as $id_requisicion) { $requisicion = Requisicion::find($id_requisicion); $task = $requisicion->ef_request->open_tasks[0]; // Completar tareas diferentes a la actual // (No se completa la actual porque EF lo hace por default) if ($task->task_id != $input->task_id) { $requestCore->completeTask($task->task_request, $task->task_id, $input->flow_id, $input->step_id, $input->user_id, 'Proveedor seleccionado por el usuario ' . $_SESSION['user_id'], 'next'); } } return $returnArray; }
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! } }
/** * _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()); }
function crearDocumentoYSolicitud($arrayCabecera, $arrayLineas, $tmpString, $rideContent, $rideExtension, $fullXml) { $handlerRequestCore = new RequestCore(); $handlerAttachmentCore = new AttachmentCore(); $handlerRequestMetadataCore = new RequestMetadataCore(); // Verificar el usuario creador / al que se asignará $creator = Responsable::whereRuc($arrayCabecera['ruc'])->lists('responsable')->implode(','); if (empty($creator)) { $creator = FlowSettingsCore::get(FLOW_RECEPCIONDOCUMENTOS, "RDE_DEF_ASIGNACION"); } if ($arrayCabecera["tipo_doc"] == "FAC") { $customStep = FlowSettingsCore::get(FLOW_RECEPCIONDOCUMENTOS, "RDE_STEP_FACTURAS"); } else { $customStep = FlowSettingsCore::get(FLOW_RECEPCIONDOCUMENTOS, "RDE_STEP_OTROS"); $creator = ''; } // Crear solicitud por cada proveedor $request_flow = FLOW_RECEPCIONDOCUMENTOS; $request_id = $handlerRequestCore->getLastGeneralRequestId() + 1; $inner_request_id = $handlerRequestCore->getLastGeneralRequestId($request_flow) + 1; $request_name = $request_description = $arrayCabecera["tipo_doc"] . " - " . $arrayCabecera["razonSocial"]; $request_createdby = "admin"; $request_id = $handlerRequestCore->createNewRequest($request_id, $inner_request_id, $request_flow, $request_name, $request_description, $request_createdby, $creator, $customStep); // Crear documento $arrayCabecera['ef_id'] = $request_id; $documento = Documento::create($arrayCabecera); // Setear id_documento en líneas e insertar foreach ($arrayLineas as &$linea) { $linea['id_documento'] = $documento->id; DocumentoLinea::create($linea); } // Guardar archivos temporales en disco $xmlFile = dirname(__FILE__) . "/facturas/tmpAttachments/tmp.xml"; $pdfFile = dirname(__FILE__) . "/facturas/tmpAttachments/tmp." . $rideExtension; $filetypeXml = FlowSettingsCore::get(FLOW_RECEPCIONDOCUMENTOS, "RDE_FILE_XML"); $filetypePdf = FlowSettingsCore::get(FLOW_RECEPCIONDOCUMENTOS, "RDE_FILE_PDF"); //file_put_contents($xmlFile, $tmpString); file_put_contents($xmlFile, $fullXml); $handlerAttachmentCore->addAttachmentToRequest($request_id, $filetypeXml, $xmlFile, $_SESSION["environment_path"], "admin", "Documento XML"); if (!empty($rideExtension) && !empty($rideContent)) { file_put_contents($pdfFile, $rideContent); $handlerAttachmentCore->addAttachmentToRequest($request_id, $filetypePdf, $pdfFile, $_SESSION["environment_path"], "admin", "Documento PDF"); } // Setear variables de solicitud $handlerRequestMetadataCore->setVariable($request_id, "RDE-TIPO-DOCUMENTO", $arrayCabecera["tipo_doc"]); $handlerRequestMetadataCore->setVariable($request_id, "RDE-NUM-DOCUMENTO", $arrayCabecera["estab"] . "-" . $arrayCabecera["ptoEmi"] . "-" . $arrayCabecera["secuencial"]); $handlerRequestMetadataCore->setVariable($request_id, "RDE-NOMBRE-PROVEEDOR", $arrayCabecera["razonSocial"]); }
// Form errors. 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']));
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()); }
//header('Access-Control-Allow-Origin: *'); require_once "../../includes/configuration.php"; $_SESSION["environment_path"] = dirname(dirname(getcwd())); require_once APP_BASEPATH . "/includes/Entities/User/UserCore.php"; require_once APP_BASEPATH . "/includes/Entities/Task/TaskCore.php"; require_once APP_BASEPATH . "/includes/Entities/Request/RequestCore.php"; require_once APP_BASEPATH . "/includes/Entities/RequestMetadata/RequestMetadataCore.php"; require_once APP_BASEPATH . "/includes/Entities/FlowSettings/FlowSettingsCore.php"; require_once APP_BASEPATH . "/includes/Entities/Attachment/AttachmentCore.php"; require_once APP_BASEPATH . "/includes/Entities/Filetype/FiletypeCore.php"; require_once $_SESSION["environment_path"] . "/customcode/Reclamos/includes/Entities/General/GeneralCore.php"; require_once $_SESSION["environment_path"] . "/customcode/Reclamos/includes/Entities/Clase/ClaseCore.php"; require_once $_SESSION["environment_path"] . "/customcode/Reclamos/includes/Entities/Reclamo/ReclamoCore.php"; require_once $_SESSION["environment_path"] . "/customcode/Reclamos/includes/Entities/ReclamoDetalle/ReclamoDetalleCore.php"; define("CURRENT_FLOW", "1"); $handlerRequestCore = new RequestCore(); $handlerReclamoCore = new ReclamoCore(); $handlerReclamoDetalleCore = new ReclamoDetalleCore(); $handlerRequestMetadataCore = new RequestMetadataCore(); $handlerFlowSettingsCore = new FlowSettingsCore(); $handlerAttachmentCore = new AttachmentCore(); $handlerFiletypeCore = new FiletypeCore(); $handlerGeneralCore = new GeneralCore(); $handlerClaseCore = new ClaseCore(); if ($_POST["cliente_pais"] == "ECU") { $tipo = "venta_local"; $creador = $handlerFlowSettingsCore->getSettingValue(CURRENT_FLOW, "REC_PRO_USUARIO_VL"); $asignado_a = $handlerFlowSettingsCore->getSettingValue(CURRENT_FLOW, "REC_PRO_USUARIO_VL"); } else { $tipo = "exportacion"; $creador = $handlerFlowSettingsCore->getSettingValue(CURRENT_FLOW, "REC_PRO_USUARIO_EXP");
/** * Method: copy_object() * Copies an Amazon S3 object to a new location, whether in the same Amazon S3 region, bucket, or * otherwise. * * Access: * public * * Parameters: * $source - _array_ (Required) An associative array containing two keys: `bucket`, specifying the name of the bucket containing the source object, and `filename`, specifying the file name of the source object to copy. * $dest - _array_ (Required) An associative array containing two keys: `bucket`, specifying the name of the bucket to store the destination object in, and `filename`, specifying the file name of the destination object name. * $opt - _array_ (Optional) An associative array of parameters that can have the keys listed in the following section. * * Keys for the $opt parameter: * acl - _string_ (Optional) The ACL settings for the specified object. [Allowed values: `AmazonS3::ACL_PRIVATE`, `AmazonS3::ACL_PUBLIC`, `AmazonS3::ACL_OPEN`, `AmazonS3::ACL_AUTH_READ`, `AmazonS3::ACL_OWNER_READ`, `AmazonS3::ACL_OWNER_FULL_CONTROL`]. Alternatively, an array of associative arrays. Each associative array contains an `id` and a `permission` key. The default value is <ACL_PRIVATE>. * storage - _string_ (Optional) Whether to use Standard or Reduced Redundancy storage. [Allowed values: `AmazonS3::STORAGE_STANDARD`, `AmazonS3::STORAGE_REDUCED`]. The default value is <STORAGE_STANDARD>. * versionId - _string_ (Optional) The version of the object to copy. Version IDs are returned in the `x-amz-version-id` header of any previous object-related request. * ifMatch - _string_ (Optional) The ETag header from a previous request. Copies the object if its entity tag (ETag) matches the specified tag; otherwise, the request returns a `412` HTTP status code error (precondition failed). Used in conjunction with `ifUnmodifiedSince`. * ifUnmodifiedSince - _string_ (Optional) The LastModified header from a previous request. Copies the object if it hasn't been modified since the specified time; otherwise, the request returns a `412` HTTP status code error (precondition failed). Used in conjunction with `ifMatch`. * ifNoneMatch - _string_ (Optional) The ETag header from a previous request. Copies the object if its entity tag (ETag) is different than the specified ETag; otherwise, the request returns a `412` HTTP status code error (failed condition). Used in conjunction with `ifModifiedSince`. * ifModifiedSince - _string_ (Optional) The LastModified header from a previous request. Copies the object if it has been modified since the specified time; otherwise, the request returns a `412` HTTP status code error (failed condition). Used in conjunction with `ifNoneMatch`. * headers - _array_ (Optional) Standard HTTP headers to send along in the request. * meta - _array_ (Optional) Associative array of key-value pairs. Represented by `x-amz-meta-:` Any header starting with this prefix is considered user metadata. It will be stored with the object and returned when you retrieve the object. The total size of the HTTP request, not including the body, must be less than 4 KB. * metadataDirective - _string_ (Optional) Accepts either COPY or REPLACE. You will likely never need to use this, as it manages itself with no issues. * returnCurlHandle - _boolean_ (Optional) A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests. * * Returns: * _CFResponse_ A <CFResponse> object containing a parsed HTTP response. * * See Also: * [Copying Amazon S3 Objects](http://docs.amazonwebservices.com/AmazonS3/latest/UsingCopyingObjects.html) */ public function copy_object($source, $dest, $opt = null) { if (!$opt) { $opt = array(); } $batch = array(); // Add this to our request $opt['verb'] = 'PUT'; $opt['resource'] = $dest['filename']; // Handle copy source if (isset($source['bucket']) && isset($source['filename'])) { $opt['headers']['x-amz-copy-source'] = '/' . $source['bucket'] . '/' . rawurlencode($source['filename']) . (isset($opt['versionId']) ? '?' . 'versionId=' . rawurlencode($opt['versionId']) : ''); // Append the versionId to copy, if available unset($opt['versionId']); // Determine if we need to lookup the pre-existing content-type. if (!in_array(strtolower('content-type'), array_map('strtolower', array_keys($opt['headers'])))) { $response = $this->get_object_headers($source['bucket'], $source['filename']); $opt['headers']['Content-Type'] = $response->header['content-type']; } } // Handle metadata directive $opt['headers']['x-amz-metadata-directive'] = 'COPY'; if ($source['bucket'] === $dest['bucket'] && $source['filename'] === $dest['filename']) { $opt['headers']['x-amz-metadata-directive'] = 'REPLACE'; } if (isset($opt['metadataDirective'])) { $opt['headers']['x-amz-metadata-directive'] = $opt['metadataDirective']; unset($opt['metadataDirective']); } // Handle Access Control Lists. Can also pass canned ACLs as an HTTP header. if (isset($opt['acl']) && is_array($opt['acl'])) { $batch[] = $this->set_object_acl($dest['bucket'], $dest['filename'], $opt['acl'], array('returnCurlHandle' => true)); unset($opt['acl']); } elseif (isset($opt['acl'])) { $opt['headers']['x-amz-acl'] = $opt['acl']; unset($opt['acl']); } // Handle storage settings. Can also be passed as an HTTP header. if (isset($opt['storage'])) { $opt['headers']['x-amz-storage-class'] = $opt['storage']; unset($opt['storage']); } // Handle conditional-copy parameters if (isset($opt['ifMatch'])) { $opt['headers']['x-amz-copy-source-if-match'] = $opt['ifMatch']; unset($opt['ifMatch']); } if (isset($opt['ifNoneMatch'])) { $opt['headers']['x-amz-copy-source-if-none-match'] = $opt['ifNoneMatch']; unset($opt['ifNoneMatch']); } if (isset($opt['ifUnmodifiedSince'])) { $opt['headers']['x-amz-copy-source-if-unmodified-since'] = $opt['ifUnmodifiedSince']; unset($opt['ifUnmodifiedSince']); } if (isset($opt['ifModifiedSince'])) { $opt['headers']['x-amz-copy-source-if-modified-since'] = $opt['ifModifiedSince']; unset($opt['ifModifiedSince']); } // Handle meta tags. Can also be passed as an HTTP header. if (isset($opt['meta'])) { foreach ($opt['meta'] as $meta_key => $meta_value) { // e.g., `My Meta Header` is converted to `x-amz-meta-my-meta-header`. $opt['headers']['x-amz-meta-' . strtolower(str_replace(' ', '-', $meta_key))] = $meta_value; } unset($opt['meta']); } // Authenticate to S3 $response = $this->authenticate($dest['bucket'], $opt); // Attempt to reset ACLs $http = new RequestCore(); $http->send_multi_request($batch); return $response; }
/** * 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; }
public function insertReclamo() { $input = Request::createFromGlobals(); $handlerRequestCore = new \RequestCore(); $handlerAttachmentCore = new \AttachmentCore(); $clase = Clase::find($input->reclamo['clase']); // Asignar creador $creador = $asignado_a = FlowSettingsCore::get(FLOW_RECLAMOS, "REC_PRO_USUARIO_VL"); if (FlowSettingsCore::get(FLOW_RECLAMOS, "REC_PRO_REGION_EXT") == $input->reclamo['region']) { $creador = $asignado_a = FlowSettingsCore::get(FLOW_RECLAMOS, "REC_PRO_USUARIO_EXP"); } $extemporaneo = false; $customStep = ""; foreach ($input->facturas as $factura) { if ($factura['infoFactura']['extemporaneo'] == true) { $customStep = FlowSettingsCore::get(FLOW_RECLAMOS, "REC_STEP_EXTEMPORANEAS"); $asignado_a = FlowSettingsCore::get(FLOW_RECLAMOS, "REC_USER_EXTEMPORANEAS"); $extemporaneo = true; break; } } $request_id = $handlerRequestCore->createNewRequest(0, 0, FLOW_RECLAMOS, "Reclamo - " . date("Y-m-d") . " - " . $input->cliente['nombre'], "Reclamo - " . date("Y-m-d") . " - " . $input->cliente['nombre'], $creador, $asignado_a, $customStep); $reclamo = Reclamo::create(['ef_id' => $request_id, 'cliente_codigo' => $input->cliente['codigo'], 'cliente_nombre' => $input->cliente['nombre'], 'cliente_identificacion' => $input->cliente['identificacion'], 'cliente_direccion' => $input->cliente['direccion'], 'contacto_nombre' => $input->contacto['nombre'], 'contacto_telefono' => $input->contacto['telefono'], 'contacto_email' => $input->contacto['email'], 'reclamo_descripcion' => $input->reclamo['descripcion'], 'reclamo_fecha_inicio' => date('Y-m-d H:i:s'), 'reclamo_clase' => $input->reclamo['clase'], 'reclamo_region' => $input->reclamo['region'], 'reclamo_extemporaneo' => $extemporaneo ? 1 : 0, 'reclamo_num_interno' => $input->reclamo['num_interno'], 'reclamo_monto' => $input->reclamo['total_reclamo'], 'visita_requiere' => 0]); $listaFacturas = array(); foreach ($input->facturas as $factura) { foreach ($factura['detalles'] as $detalle) { if ($detalle['cantidad_reclamo'] > 0 || $detalle['cantidad_no_facturado'] > 0) { if ($detalle['cantidad_no_facturado'] > 0) { $cantidad = $detalle['cantidad_no_facturado']; $valor = $detalle['valor_no_facturado']; $lote = $detalle['lote_no_facturado']; } else { $cantidad = $detalle['cantidad_reclamo']; $valor = $detalle['cantidad_reclamo'] * $detalle['precioUnitario']; $lote = $detalle['lote']; } ReclamoDetalle::create(['reclamo_id' => $reclamo->id, 'factura' => $factura['infoFactura']['numero_factura'], 'factura_fecha' => $factura['infoFactura']['fechaEmision'], 'producto_comercial' => $detalle['clase'], 'codigo_item' => $detalle['codigoPrincipal'], 'descripcion_item' => $detalle['descripcion'], 'precio_unitario' => $detalle['precioUnitario'], 'cantidad_original' => $detalle['cantidad'], 'cantidad_reclamo' => $cantidad, 'valor_reclamo' => $valor, 'lote_reclamo' => $lote]); $listaFacturas[] = $factura['infoFactura']['numero_factura']; } } } $listaFacturas = array_unique($listaFacturas); foreach ($input->adjuntos as $adjunto) { $handlerAttachmentCore->addAttachmentToRequest($request_id, $adjunto['filetype']['filetype_id'], $adjunto['filename'], APP_ENVPATH, 'admin', 'Adjunto del cliente'); } RequestMetadataCore::set($request_id, 'REC-CODIGO-CLIENTE', $input->cliente['codigo']); RequestMetadataCore::set($request_id, 'REC-NOMBRE-CLIENTE', $input->cliente['nombre']); RequestMetadataCore::set($request_id, 'REC-IDENTIFICACION-CLIENTE', $input->cliente['identificacion']); RequestMetadataCore::set($request_id, 'REC-EMAIL-CLIENTE', $input->cliente['email']); RequestMetadataCore::set($request_id, 'REC-EMAIL-CONTACTO', $input->contacto['email']); RequestMetadataCore::set($request_id, 'REC-CLASE', $clase->nombre); RequestMetadataCore::set($request_id, 'REC-NUMERO-FACTURA', implode(',', $listaFacturas)); RequestMetadataCore::set($request_id, 'REC-NUMERO-REC-CLIENTE', $input->reclamo['num_interno']); RequestMetadataCore::set($request_id, 'REC-DESCRIPCION', $input->reclamo['descripcion']); RequestMetadataCore::set($request_id, 'REC-MONTO-DECISION', $input->reclamo['total_reclamo']); $request = EFRequest::find($request_id); echo $request->request_inner_id; }
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! } }
/** * @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; }
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; } }
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 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; }