/** * Create an HTTP_Request object and set all parameters necessary to * perform fetches for this comic. * * @param timestamp $date Date of the comic to retrieve (default today) */ function _initHTTP($date, $url) { if (is_null($this->http)) { $options = array(); if (isset($GLOBALS['conf']['http']['proxy']) && !empty($GLOBALS['conf']['http']['proxy']['proxy_host'])) { $options = array_merge($options, $GLOBALS['conf']['http']['proxy']); } require_once 'HTTP/Request.php'; $this->http = new HTTP_Request($url, $options); $v = $this->getOverride("referer", $date); if (!is_null($v)) { $this->http->addHeader('Referer', $v); } $v = $this->getOverride("agent"); if (!is_null($v)) { $this->http->addHeader('User-Agent', $v); } $user = $this->getOverride("user", $date); $pass = $this->getOverride("pass", $date); if (!is_null($user) and !is_null($pass)) { $this->http->setBasicAuth($user, $pass); } foreach ($this->getOverride('cookies', $date) as $name => $value) { $this->http->addCookie($name, $value); } foreach ($this->getOverride('headers', $date) as $name => $value) { $this->addHeader($name, $value); } } }
/** * @brief HTTP request 객체 생성 **/ function getRequest($url) { $oReqeust = new HTTP_Request($url); $oReqeust->addHeader('Content-Type', 'application/xml'); $oReqeust->setMethod('GET'); $oReqeust->setBasicAuth($this->getUserID(), $this->getPassword()); return $oReqeust; }
function getRequestInstance($url, $http_verb = 'GET', $options = array(), $body = '') { $default_options = array('header' => array(), 'params' => array()); $options = array_merge($default_options, $options); $options['header']['user-agent'] = empty($options['header']['user-agent']) ? 'Akelos PHP Framework AkHttpClient (http://akelos.org)' : $options['header']['user-agent']; list($user_name, $password) = $this->_extractUserNameAndPasswordFromUrl($url); require_once AK_VENDOR_DIR . DS . 'pear' . DS . 'HTTP' . DS . 'Request.php'; $this->{'_setParamsFor' . ucfirst(strtolower($http_verb))}($url, $options['params']); $this->HttpRequest =& new HTTP_Request($url); $user_name ? $this->HttpRequest->setBasicAuth($user_name, $password) : null; $this->HttpRequest->setMethod(constant('HTTP_REQUEST_METHOD_' . $http_verb)); if ($http_verb == 'PUT' && !empty($options['params'])) { $this->setBody(http_build_query($options['params'])); } if (!empty($body)) { $this->setBody($body); } if (!empty($options['file'])) { $this->HttpRequest->addFile($options['file']['inputname'], $options['file']['filename']); } !empty($options['params']) && $this->addParams($options['params']); $this->addHeaders($options['header']); return $this->HttpRequest; }
/** * Retrieve Free/Busy data for the specified resource. * * @param string $resource Fetch the Free/Busy data for this resource. * * @return Horde_Icalendar_Vfreebusy The Free/Busy data. */ public function get($resource) { global $conf; $url = self::getUrl($resource); Horde::log(sprintf('Freebusy URL for resource %s is %s', $resource, $url), 'DEBUG'); list($user, $domain) = explode('@', $resource); if (empty($domain)) { $domain = $conf['kolab']['filter']['email_domain']; } /** * This section matches Kronolith_Freebusy and should be merged with it * again in a single Horde_Freebusy module. */ $options = array('method' => 'GET', 'timeout' => 5, 'allowRedirects' => true); if (!empty($conf['http']['proxy']['proxy_host'])) { $options = array_merge($options, $conf['http']['proxy']); } $http = new HTTP_Request($url, $options); $http->setBasicAuth($conf['kolab']['filter']['calendar_id'] . '@' . $domain, $conf['kolab']['filter']['calendar_pass']); @$http->sendRequest(); if ($http->getResponseCode() != 200) { throw new Horde_Kolab_Resource_Exception(sprintf('Unable to retrieve free/busy information for %s', $resource), Horde_Kolab_Resource_Exception::NO_FREEBUSY); } $vfb_text = $http->getResponseBody(); // Detect the charset of the iCalendar data. $contentType = $http->getResponseHeader('Content-Type'); if ($contentType && strpos($contentType, ';') !== false) { list(, $charset, ) = explode(';', $contentType); $vfb_text = Horde_String::convertCharset($vfb_text, trim(str_replace('charset=', '', $charset)), 'UTF-8'); } $iCal = new Horde_Icalendar(); $iCal->parsevCalendar($vfb_text, 'VCALENDAR'); $vfb =& $iCal->findComponent('VFREEBUSY'); if ($vfb === false) { throw new Horde_Kolab_Resource_Exception(sprintf('Invalid or no free/busy information available for %s', $resource), Horde_Kolab_Resource_Exception::NO_FREEBUSY); } $vfb->simplify(); return $vfb; }
function willRequest($request) { // お気に入り作成をフックする if (preg_match("|^/favorites/create/(\\d+)|", $this->server->request['path'], $match)) { $id = $match[1]; $url = $this->server->config['Twitter']['api']; $url .= '/status/show/' . $id . '.json'; $req = new HTTP_Request($url); if (isset($_SERVER["PHP_AUTH_USER"])) { $req->setBasicAuth($_SERVER["PHP_AUTH_USER"], @$_SERVER["PHP_AUTH_PW"]); } $result = $req->sendRequest(); if (PEAR::isError($result)) { return; } if ($req->getResponseCode() != 200) { return; } $json = json_decode($req->getResponseBody()); $title = $json->text; $href = 'http://twitter.com/' . $json->user->screen_name . '/status/' . $id; $created = date('Y-m-d\\TH:i:s\\Z'); $nonce = pack('H*', sha1(md5(time()))); $pass_digest = base64_encode(pack('H*', sha1($nonce . $created . $this->server->config['Plugin']['HatenaBookmark']['password']))); $wsse = 'UsernameToken Username="******", '; $wsse .= 'PasswordDigest="' . $pass_digest . '", '; $wsse .= 'Nonce="' . base64_encode($nonce) . '",'; $wsse .= 'Created="' . $created . '"'; $req = new HTTP_Request('http://b.hatena.ne.jp/atom/post'); $req->setMethod(HTTP_REQUEST_METHOD_POST); $req->addHeader('WWW-Authenticate', 'WSSE profile="UsernameToken"'); $req->addHeader('X-WSSE', $wsse); $req->addHeader('Content-Type', 'application/x.atom+xml'); $xml = '<?xml version="1.0" encoding="utf-8"?>' . '<entry xmlns="http://purl.org/atom/ns#">' . '<title>' . $title . '</title>' . '<link rel="related" type="text/html" href="' . $href . '" />' . '<summary type="text/plain"></summary>' . '</entry>'; $req->addRawPostData($xml); $req->sendRequest(); } return $request; }
/** * @brief rss 주소로 부터 내용을 받아오는 함수 * * tistory 의 경우 원본 주소가 location 헤더를 뿜는다.(내용은 없음) 이를 해결하기 위한 수정 **/ function rss_request($rss_url) { // request rss $rss_url = Context::convertEncodingStr($rss_url); $URL_parsed = parse_url($rss_url); if (strpos($URL_parsed["host"], 'naver.com')) { $rss_url = iconv('UTF-8', 'euc-kr', $rss_url); } $rss_url = str_replace(array('%2F', '%3F', '%3A', '%3D', '%3B', '%26'), array('/', '?', ':', '=', ';', '&'), urlencode($rss_url)); $URL_parsed = parse_url($rss_url); $host = $URL_parsed["host"]; $port = $URL_parsed["port"]; if ($port == 0) { $port = 80; } $path = $URL_parsed["path"]; if ($URL_parsed["query"] != '') { $path .= "?" . $URL_parsed["query"]; } $oReqeust = new HTTP_Request($rss_url); $oReqeust->addHeader('Content-Type', 'application/xml'); $oReqeust->addHeader('User-agent', 'RSS Reader Widget (XE ' . __ZBXE_VERSION__ . ' (http://www.xpressengine.com); PEAR HTTP_Request class (http://pear.php.net))'); $oReqeust->setMethod('GET'); $user = $URL_parsed["user"]; $pass = $URL_parsed["pass"]; if ($user) { $oReqeust->setBasicAuth($user, $pass); } $oResponse = $oReqeust->sendRequest(); if (PEAR::isError($oResponse)) { return; } $header = $oReqeust->getResponseHeader(); if ($header['location']) { return $this->rss_request(trim($header['location'])); } else { return $oReqeust->getResponseBody(); } }
function post($img_index) { global $image_files; $url = 'http://twitter.com/account/update_profile_image.json'; $file_name = $image_files[$img_index]; if (!file_exists($file_name)) { result('画像ファイル名が不正です。'); } $pathinfo = pathinfo($file_name); $extension = strtolower($pathinfo['extension']); switch ($extension) { case 'png': case 'gif': // do nothing. break; case 'jpeg': case 'jpg': $extension = 'jpg'; break; default: result('画像の拡張子が不正です。'); } $request = new HTTP_Request($url); $request->setMethod(HTTP_REQUEST_METHOD_POST); $request->setBasicAuth(USERNAME, PASSWORD); $result = $request->addFile('image', $file_name, "image/{$extension}"); if (PEAR::isError($result)) { result($result->getMessager()); } $response = $request->sendRequest(); if (PEAR::isError($response)) { result($response->getMessage()); } $body = $request->getResponseBody(); return true; }
/** * callMethod * * @access private * @param string $method_name * @param array $send_param * @param string $method * @return string result XML data */ private function callMethod($method_name, $send_param = array(), $method = 'post') { $request = new HTTP_Request($this->api_url . $method_name); $request->setBasicAuth($this->username, $this->password); if ($method == "post") { $request->setMethod(HTTP_REQUEST_METHOD_POST); } if (count($send_param) != 0) { foreach ($send_param as $key => $value) { if ($key == "photo" && $method_name == "photo_add") { $request->addFile($key, $value, $this->getMime($value)); } else { if ($method == "post") { $request->addPostData($key, $value, true); } else { $request->addQueryString($key, $value, true); } } } } $response = $request->sendRequest(); if (PEAR::isError($response)) { return $response; } else { $body = $request->getResponseBody(); if (strpos($body, 'rsp stat="fail"') !== false) { preg_match('|err code="(.*?)" msg="(.*?)"|', $body, $matches); $code = 0; if (isset($this->error_code[$matches[1]])) { $code = $this->error_code[$matches[1]]; } return PEAR::raiseError($matches[1] . ':' . $matches[2], $code); } else { return $body; } } }
/** * Get the PukiWiki output externally via http * * @param string $page * @return string pukiwiki skin output */ function http_pkwk_output($page) { usleep($this->CONF['WAITTIME']); // edit.php if (defined('EDIT_OK') && EDIT_OK && defined('PKWK_SCRIPT_FILENAME')) { $script = get_pkwk_topurl() . ($GLOBALS['script_directory_index'] == PKWK_SCRIPT_FILENAME ? '' : PKWK_SCRIPT_FILENAME); } else { $script = get_script_uri(); } $url = $script . '?cmd=read&page=' . rawurlencode($page); // cmd=read to support old versions such as 1.4.3 $url .= '&statichtml'; // cmd=read to support old versions such as 1.4.3 $url .= '&' . $this->plugin; // $this->plugin flag can be used like USER_AGENT to know agent is the statichtml plugin. if (is_includable('HTTP/Request.php') && $this->CONF['username'] != '') { require_once 'HTTP/Request.php'; $req = new HTTP_Request($url); $req->setMethod(HTTP_REQUEST_METHOD_GET); //$req->addPostData('pass', $GLOBALS['ADMINPASS']); $req->setBasicAuth($this->CONF['username'], $this->CONF['userpass']); $response = $req->sendRequest(); // ToDo: How to find BasicAuth was failed? if (PEAR::isError($response)) { //echo $response->getMessage(); return FALSE; } else { $html = $req->getResponseBody(); } } else { $html = file_get_contents($url); } return $html; }
/** * Tries to logon to the HTTP server with given id and password * * @access public * * @param string $source Authentication source to be used * @param string $external_uid The ID entered * @param string $external_passwd The password of the user * * @return boolean True if the authentication was a success, false * otherwise */ public function Authenticate($source, $external_uid, $external_passwd) { require_once 'HTTP/Request.php'; // Set some default HTTP request options $request_options['method'] = 'GET'; $request_options['timeout'] = 5; $request_options['allowRedirects'] = true; $enc = ExternalAuthenticator::getAuthEnc($source); $port = ExternalAuthenticator::getAuthPort($source); $folder = ExternalAuthenticator::getOption($source, 'folder'); $proxy = ExternalAuthenticator::getOption($source, 'proxy'); $proxy_port = ExternalAuthenticator::getOption($source, 'proxy_port'); $proxy_user = ExternalAuthenticator::getOption($source, 'proxy_user'); $proxy_pass = ExternalAuthenticator::getOption($source, 'proxy_pass'); if (!is_null($proxy) && !is_null($proxy_port)) { ExternalAuthenticator::AuthLog($external_uid . '.http - Proxy is set to ' . $proxy . ':' . $proxy_port); $request_options['proxy_host'] = $proxy; $request_options['proxy_port'] = $proxy_port; } else { ExternalAuthenticator::AuthLog($external_uid . '.http - Proxy is not set'); } if (!is_null($proxy_user)) { ExternalAuthenticator::AuthLog($external_uid . '.http - Proxy user is set to ' . $proxy_user); $request_options['proxy_user'] = $proxy_user; if (!is_null($proxy_pass)) { ExternalAuthenticator::AuthLog($external_uid . '.http - Proxy password is set'); $request_options['proxy_pass'] = $proxy_pass; } else { ExternalAuthenticator::AuthLog($external_uid . '.http - Proxy password is NOT set'); } } else { ExternalAuthenticator::AuthLog($external_uid . '.http - Proxy user is NOT set'); } if ($enc == 'ssl') { $url = 'https://'; } else { $url = 'http://'; } $url .= ExternalAuthenticator::getAuthServer($source); if (!is_null($port)) { $url .= ':' . $port; } if (!is_null($folder)) { $url .= $folder; } ExternalAuthenticator::AuthLog($external_uid . '.http - Authentication URL is set to ' . $url); $request = new HTTP_Request($url, $request_options); $request->setBasicAuth($external_uid, $external_passwd); ExternalAuthenticator::AuthLog($external_uid . '.http - Sending authentication request'); $request->sendRequest(); // HTTP code 200 means everything is OK if ($request->getResponseCode() == 200) { ExternalAuthenticator::AuthLog($external_uid . '.http - Remote server returned code 200'); return true; } else { ExternalAuthenticator::AuthLog($external_uid . '.http - Authentication failed with HTTP code ' . $request->getResponseCode()); ExternalAuthenticator::setAuthMessage(_t('ExternalAuthenticator.Failed')); return false; } }
function createTwitterRequest() { $url = $this->config['Twitter']['api']; if (isset($_SERVER['PATH_INFO'])) { $url .= $_SERVER['PATH_INFO']; } if (isset($_SERVER['QUERY_STRING'])) { $url .= '?' . $_SERVER['QUERY_STRING']; } $option = array('allow_redirect' => false); $req = new HTTP_Request($url, array_merge($this->config['HTTP_Request'], $option)); $req->setMethod($_SERVER['REQUEST_METHOD']); if (isset($_SERVER["PHP_AUTH_USER"])) { $req->setBasicAuth($_SERVER["PHP_AUTH_USER"], @$_SERVER["PHP_AUTH_PW"]); } foreach ($_POST as $k => $v) { $req->setPostData($k, $v); } return $req; }
/** * Generates an API request * * @param $path string The path, eg "slices" * @param $id string The id of the object, optional and really only used for slices and zones * @param $action string Any action to take on the object, for instance "reboot" * @param $method string The HTTP method for the request * @param $parameters array Any post/query string parameters * @param $postbody string The raw postbody, used in lieu of $parameters * @return string The response body */ public function request($path,$id=null,$action=null,$method='GET',$parameters=null,$postbody=null,$cached=false) { // append slashes where needed if ($id!='') $path.='/'; if (($action!=null) && ($id!=null)) $id.='/'; // build the url $url="https://api.slicehost.com/{$path}{$id}{$action}.xml"; if ($cached) { if (isset(self::$_cache[$url])) { return self::$_cache[$url]; } } // create a request $request=new HTTP_Request($url); // set the auth $request->setBasicAuth($this->key,''); // set the method $method=strtoupper($method); $request->setMethod($method); // $postbody was specified, so this is an xml request if ($postbody) { $request->addHeader('Content-Type','text/xml'); $request->addRawPostData($postbody); } // since we are posting well formed xml documents instead of // post data, all the parameters will be appended as query strings // since they are only used in the api in weird places. if ($parameters) foreach($parameters as $key=>$value) $request->addQueryString($key,$value); // send it off $request->sendRequest(true); // if success, build the response objects, otherwise throw an exception. $repcode=$request->getResponseCode(); switch($repcode) { case 200: case 201: case 204: $result=$this->build_response($request->getResponseBody()); self::$_cache[$url]=$result; return $result; default: throw new SlicehostException("$url.\nResponse Code $repcode.\n\n{$request->getResponseBody()}\n\n"); } }
/** * Checks the validity of the supplied Twitter credentials. * * Will return false if the username/password combo fails to login. * * @param string $username - The supplied Twitter username * @param boolean $empty - Optional flag, decides whether the email is optional or not * @param array $params - The extra parameters provided by SmartyValidate * @param array $formvars - The other form variables provided by the form * @return boolean - True if email exists, false if not. */ public function isValidTwitterCredentials($username, $empty, &$params, &$formvars) { // Test Parameters if (!isset($username) || !isset($formvars[$params['field2']])) { return $empty; } $username = cleanValue($username); $password = $formvars[$params['field2']]; $req = new HTTP_Request('http://twitter.com/account/verify_credentials.xml'); $req->setMethod(HTTP_REQUEST_METHOD_POST); $req->setBasicAuth($username, $password); $response = $req->sendRequest(); $responseCode = $req->getResponseCode(); $responseBody = $req->getResponseBody(); if ($responseCode == '200') { return true; } return false; }
/** * Stream handler interface lock() method (experimental ...) * * @access private * @return bool true on success else false */ function stream_lock($mode) { /* TODO: - think over how to refresh locks */ $ret = false; // LOCK is only supported by DAV Level 2 if (!isset($this->dav_level["2"])) { return false; } switch ($mode & ~LOCK_NB) { case LOCK_UN: if ($this->locktoken) { $req = new HTTP_Request($this->url); $req->setMethod(HTTP_REQUEST_METHOD_UNLOCK); if (is_string($this->user)) { $req->setBasicAuth($this->user, @$this->pass); } $req->addHeader("Lock-Token", "<{$this->locktoken}>"); $req->sendRequest(); $ret = $req->getResponseCode() == 204; } break; case LOCK_SH: case LOCK_EX: $body = sprintf('<?xml version="1.0" encoding="utf-8" ?> <D:lockinfo xmlns:D="DAV:"> <D:lockscope><D:%s/></D:lockscope> <D:locktype><D:write/></D:locktype> <D:owner>%s</D:owner> </D:lockinfo>', $mode & LOCK_SH ? "shared" : "exclusive", get_class($this)); // TODO better owner string $req = new HTTP_Request($this->url); $req->setMethod(HTTP_REQUEST_METHOD_LOCK); if (is_string($this->user)) { $req->setBasicAuth($this->user, @$this->pass); } if ($this->locktoken) { // needed for refreshing a lock $req->addHeader("Lock-Token", "<{$this->locktoken}>"); } $req->addHeader("Timeout", "Infinite, Second-4100000000"); $req->addHeader("Content-Type", 'text/xml; charset="utf-8"'); $req->addRawPostData($body); $req->sendRequest(); $ret = $req->getResponseCode() == 200; if ($ret) { $propinfo = new HTTP_WebDAV_Client_parse_lock_response($req->getResponseBody()); $this->locktoken = $propinfo->locktoken; // TODO deal with timeout } break; default: break; } return $ret; }
/** * get http contents with Basic Authentication if required * * Requirement: HTTP/Request.php * * @access public * @param string $url URL * @param string $user BasicAuth username * @param string $pass BasicAuth pass * @return mixed (string)contents if succeeded, FALSE if failed * @see file_get_contents() */ function http_get_contents($url, $user = '', $pass = '') { if ($user == '') { return file_get_contents($url); } require_once 'HTTP/Request.php'; $req = new HTTP_Request($url); $req->setMethod(HTTP_REQUEST_METHOD_GET); $req->setBasicAuth($user, $pass); if (PEAR::isError($req->sendRequest())) { return FALSE; } return $req->getResponseBody(); }
/** * Execute external or internal URLs and return server response. * * @param string $url * Request URL. * @param bool $addCookie * Whether to provide a cookie. Should be true to access internal URLs. * * @return string * Response from URL. */ public static function getServerResponse($url, $addCookie = TRUE) { CRM_Core_TemporaryErrorScope::ignoreException(); require_once 'HTTP/Request.php'; $request = new HTTP_Request($url); if ($addCookie) { foreach ($_COOKIE as $name => $value) { $request->addCookie($name, $value); } } if (isset($_SERVER['AUTH_TYPE'])) { $request->setBasicAuth($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']); } $config = CRM_Core_Config::singleton(); if ($config->userFramework == 'WordPress') { session_write_close(); } $request->sendRequest(); $response = $request->getResponseBody(); return $response; }
/** * Triggers a URL. * * @param string $url The URL to be triggered. * * @return boolean|PEAR_Error True if successfull. */ private function triggerUrl($url) { global $conf; if (!empty($conf['kolab']['no_triggering'])) { return true; } $options['method'] = 'GET'; $options['timeout'] = 5; $options['allowRedirects'] = true; if (isset($conf['http']['proxy']) && !empty($conf['http']['proxy']['proxy_host'])) { $options = array_merge($options, $conf['http']['proxy']); } $http = new HTTP_Request($url, $options); $http->setBasicAuth($GLOBALS['registry']->getAuth(), $GLOBALS['registry']->getAuthCredential('password')); @$http->sendRequest(); if ($http->getResponseCode() != 200) { return PEAR::raiseError(sprintf(Horde_Kolab_Storage_Translation::t("Unable to trigger URL %s. Response: %s"), $url, $http->getResponseCode())); } return true; }