/** * Send a trackback to a site * * @access public * @param string $title Title of the Site * @param string $excerpt The Excerpt * @param string $permalink The Permalink to send * @param array $to Where to send the trackback */ function SendTrackback($title, $excerpt, $permalink, $to) { $title = urlencode(stripslashes($title)); $excerpt = urlencode(stripslashes($excerpt)); $blog_name = urlencode(stripslashes($this->gadget->registry->fetch('site_name', 'Settings'))); $permalink = urlencode($permalink); require_once PEAR_PATH . 'HTTP/Request.php'; $options = array(); $timeout = (int) $this->gadget->registry->fetch('connection_timeout', 'Settings'); $options['timeout'] = $timeout; if ($this->gadget->registry->fetch('proxy_enabled', 'Settings') == 'true') { if ($this->gadget->registry->fetch('proxy_auth', 'Settings') == 'true') { $options['proxy_user'] = $this->gadget->registry->fetch('proxy_user', 'Settings'); $options['proxy_pass'] = $this->gadget->registry->fetch('proxy_pass', 'Settings'); } $options['proxy_host'] = $this->gadget->registry->fetch('proxy_host', 'Settings'); $options['proxy_port'] = $this->gadget->registry->fetch('proxy_port', 'Settings'); } $httpRequest = new HTTP_Request('', $options); $httpRequest->setMethod(HTTP_REQUEST_METHOD_POST); foreach ($to as $url) { $httpRequest->setURL($url); $httpRequest->addPostData('title', $title); $httpRequest->addPostData('url', $permalink); $httpRequest->addPostData('blog_name', $blog_name); $httpRequest->addPostData('excerpt', $excerpt); $resRequest = $httpRequest->sendRequest(); $httpRequest->clearPostData(); } }
/** * Método que encapsula a chamada do WEB SERVICE que traduz um arquivo .HTML em outras extensões. * Utilizado para exportar dados para arquivos a desejo do usuário. * * @param texto $arquivoFetch nome do arquivo a ser utilizado para exportação, desde a pasta 'html'. * @param texto $extensaoDestino mine type para arquivo exportado. * @param texto $nomeArquivo nome a ser exibido no download do arquivo. */ function exportarDados($arquivoFetch, $nomeArquivo = "Relatório.pdf", $extensaoDestino = "application/pdf", $fazerDownload = true) { $codigoHtml = $this->smarty->fetch($arquivoFetch); $codigoHtml = str_replace("html/css/", URL_COMPLETA . "html/css/", $codigoHtml); $codigoHtml = str_replace("html/img/", URL_COMPLETA . "html/img/", $codigoHtml); $request = new HTTP_Request(WEBSERVICE_BROFFICE_URL); $request->setMethod("POST"); $request->addHeader("Content-Type", "text/html"); $request->addHeader("Accept", $extensaoDestino); $request->setBody($codigoHtml); $request->sendRequest(); $status = $request->getResponseCode(); //echo $request->getResponseBody(); die; if ($status != 200) { echo "Ocorreu um erro na conversão. Favor entrar em contato com o administrador."; die; } if ($fazerDownload) { header("Content-Type: " . $extensaoDestino . "\n"); header("Content-Disposition: attachment; filename=" . $nomeArquivo); echo $request->getResponseBody(); die; } return $request->getResponseBody(); }
function fetchData($username, $password) { switch ($this->options['cryptType']) { case 'blowfish': include_once 'Crypt/Blowfish.php'; $bf = new Crypt_Blowfish($this->options['cryptKey']); $password = $bf->encrypt($password); $password = base64_encode($password); break; default: if (function_exists($this->options['cryptType'])) { $password = $this->options['cryptType']($password); } break; } $req = new HTTP_Request(); $req->setURL($this->options['URL']); $req->setMethod(HTTP_REQUEST_METHOD_GET); $req->addQueryString($this->options['usernameKey'], $username); $req->addQueryString($this->options['passwordKey'], $password); if (!PEAR::isError($req->sendRequest())) { $response = $req->getResponseBody(); } else { return false; } $unserializer = new XML_Unserializer(); if ($unserializer->unserialize($response)) { $this->result_value = $unserializer->getUnserializedData(); if ($this->result_value[$this->options['resultKey']] == $this->options['correctValue']) { return true; } } return false; }
/** * @brief HTTP request 객체 생성 **/ function getRequest($url) { $oReqeust = new HTTP_Request($url); $oReqeust->addHeader('Content-Type', 'application/xml'); $oReqeust->setMethod('GET'); return $oReqeust; }
/** * Sets the input xml file to be parsed * * @access public * @param string $file Filename(full path) * @return mixed True on success or error on failure */ function setInputFile($file) { require_once PEAR_PATH . 'HTTP/Request.php'; $httpRequest = new HTTP_Request($file, $this->_params); $httpRequest->setMethod(HTTP_REQUEST_METHOD_GET); $resRequest = $httpRequest->sendRequest(); if (PEAR::isError($resRequest)) { return $resRequest; } elseif ($httpRequest->getResponseCode() != 200) { return $this->raiseError('HTTP response error', HTTP_REQUEST_ERROR_RESPONSE); } $data = trim($httpRequest->getResponseBody()); if (version_compare(PHP_VERSION, '5.0.0', '<')) { if (preg_match('/<?xml.*encoding=[\'"](.*?)[\'"].*?>/m', $data, $matches)) { $srcenc = strtoupper($matches[1]); if (!in_array($srcenc, $this->_validEncodings)) { if (function_exists('iconv')) { $data = @iconv($srcenc, 'UTF-8', $data); } elseif (function_exists('mb_list_encodings') && in_array($srcenc, array_map('strtoupper', mb_list_encodings()))) { $data = @mb_convert_encoding($data, 'UTF-8', $srcenc); } } } } $this->setInputString($data); return true; }
function save($data) { if (!$data['GA_optin']) { trigger_error('did not opt to join'); return true; } $options = $this->getOptions(); $request = new HTTP_Request($options['hostname'] . '/offsite-join.tcl'); $request->setMethod(HTTP_REQUEST_METHOD_POST); $request->addPostData('domain', $options['domain']); if ($options['source']) { $request->addPostData('source', $options['source']); } if ($options['update']) { $request->addPostData('update', $options['update']); } foreach ($this->translate($data) as $name => $value) { $request->addPostData($name, $value); } if (!PEAR::isError($request->sendRequest())) { $message = trim($request->getResponseBody()); if ('OK' == $message) { return true; } else { $this->ERROR = $message; trigger_error($message); return false; } } }
/** * Helper function to fetch HTTP-URLs * * @param string $url * @return string * @todo Error handling is missing */ protected function _fetch($url) { require_once S9Y_PEAR_PATH . 'HTTP/Request.php'; $request = new HTTP_Request($url); $request->setMethod(HTTP_REQUEST_METHOD_GET); $request->sendRequest(); return $request->getResponseBody(); }
/** * @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; }
/** * 投稿実行 */ public function post() { $hr = new HTTP_Request($this->getPostUrl()); $hr->addHeader('X-WSSE', $this->wsse); $hr->addHeader('Accept', 'application/x.atom+xml, application/xml, text/xml, */*'); $hr->addHeader('Authorization', 'WSSE profile="UsernameToken"'); $hr->addHeader('Content-Type', 'application/x.atom+xml'); $hr->addRawPostData($this->getRawdata()); $hr->setMethod(HTTP_REQUEST_METHOD_POST); $hr->sendRequest(); $hr->clearPostData(); }
/** * */ function getURL($url) { require_once PEAR_PATH . 'HTTP/Request.php'; $httpRequest = new HTTP_Request($url); $httpRequest->setMethod(HTTP_REQUEST_METHOD_GET); $resRequest = $httpRequest->sendRequest(); if (!PEAR::isError($resRequest) && $httpRequest->getResponseCode() == 200) { $data = $httpRequest->getResponseBody(); } else { $data = @file_get_contents($url); } return $data; }
/** * Send an HTTP HEAD request for the given URL * * @param string $url URL to request * @param string &$errmsg error message, if any (on return) * @return int HTTP response code or 777 on error * */ function doHeadRequest($url, &$errmsg) { require_once 'HTTP/Request.php'; $req = new HTTP_Request($url); $req->setMethod(HTTP_REQUEST_METHOD_HEAD); $req->addHeader('User-Agent', 'Geeklog/' . VERSION); $response = $req->sendRequest(); if (PEAR::isError($response)) { $errmsg = $response->getMessage(); return 777; } else { return $req->getResponseCode(); } }
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; }
function sendNotification($message, $regId) { $apikey = "AIzaSyDh3_C0r5OxdGGHN516XleJ1G_-aAMxEC4"; $rq = new HTTP_Request("https://android.googleapis.com/gcm/send"); $rq->setMethod(HTTP_REQUEST_METHOD_POST); $rq->addHeader("Authorization", "key=" . $apikey); $rq->addPostData("registration_id", $regId); $rq->addPostData("collapse_key", "1"); $rq->addPostData("data.message", $message); if (!PEAR::isError($rq->sendRequest())) { print "\n" . $rq->getResponseBody(); } else { print "\nError has occurred"; } }
/** * Posts data to the URL * * @access public * @param string $url URL address * @param array $params Associated name/data values * @param string $response Response body * @return mixed Response code on success, otherwise Jaws_Error */ function post($url, $params = array(), &$response) { $httpRequest = new HTTP_Request($url, $this->options); $httpRequest->addHeader('User-Agent', $this->user_agent); $httpRequest->setMethod(HTTP_REQUEST_METHOD_POST); // add post data foreach ($params as $key => $data) { $httpRequest->addPostData($key, urlencode($data)); } $result = $httpRequest->sendRequest(); if (PEAR::isError($result)) { return Jaws_Error::raiseError($result->getMessage(), $result->getCode(), $this->default_error_level, 1); } $response = $httpRequest->getResponseBody(); return $httpRequest->getResponseCode(); }
function process($table, $data) { $req = new HTTP_Request($this->api_url); $req->setMethod(HTTP_REQUEST_METHOD_GET); foreach ($data as $key => $val) { $req->addQueryString($key, $val); } $req->addQueryString('org', trim($this->org_id)); $req->addQueryString('table', $table); if (!PEAR::isError($req->sendRequest())) { $out = $req->getResponseBody(); } else { $out = null; } return $out; }
/** * preprocess Index action. * * @access public * @return string Forward name (null if no errors.) */ function prepare() { if ($this->af->validate() == 0) { /// download file $url = sprintf('%s/repository.sphp', rtrim($this->af->get('repository_url'), '/')); $cache_file = $this->backend->ctl->repositoryURL2CacheFile($url); $repo_data = unserialize(file_get_contents($cache_file)); list($package, $version) = explode('@', $this->af->get('target_package')); $urls = array(); foreach ($repo_data as $package_name => $package_data) { if ($package_name == $package) { foreach ($package_data as $_pdata) { if ($_pdata['version'] == $version) { $urls = $_pdata['urls']; $filesize = $_pdata['size']; } } } } require_once 'HTTP/Request.php'; $req = new HTTP_Request(); $req->setMethod(HTTP_REQUEST_METHOD_HEAD); $command = 'no command'; foreach ($urls as $_url_data) { $_url = $_url_data['url']; $req->setURL($_url); $req->sendRequest(); if ($req->getResponseCode() == "302") { $headers = $req->getResponseHeader(); $req->setURL($headers['location']); } $req->sendRequest(); if ($req->getResponseCode() == '200') { $data_file = $this->backend->ctl->package2dataFile($package, $version); if ($this->fetchTgzFile($data_file, $req->getUrl())) { if (filesize($data_file) == $filesize || !$filesize) { chmod($data_file, 0666); return null; } } } } $this->ae->add('wget failed', _('file download failed.') . '[debug]' . sprintf('SIZE:[datafile,%d => repos,%d]', filesize($data_file), $filesize)); } return 'json_error_reload'; }
/** * Fire request via HTTP to the Flickr API * * @param array $arguments List of query string pairs * @return array */ public function sendRequest(array $arguments) { $params = ''; foreach ($arguments as $key => $argument) { $params .= "{$key}=" . urlencode($argument) . "&"; } $url = $this->_url . "?" . $params; require_once S9Y_PEAR_PATH . 'HTTP/Request.php'; $request = new HTTP_Request($url); $request->setMethod(HTTP_REQUEST_METHOD_GET); $request->sendRequest(); $response = unserialize($request->getResponseBody()); if ($response['stat'] != 'ok') { throw new Exception($response['message'], $response['code']); } return $response; }
/** * @throws BadRequestException * @param $method * @param $args * @return mixed */ public function call($method, $args) { $req = new HTTP_Request($this->conf->endpoint . $method); $req->setMethod('POST'); $args['app_id'] = $this->conf->app_id; foreach ($args as $key => $value) { $req->addPostData($key, $value); } $sig = sign($args, $this->conf->key); $req->addPostData('signature', $sig['signature']); $req->addPostData('time', $sig['time']); $req->sendRequest(); if ($req->getResponseCode() != 200) { throw new BadRequestException($req->getResponseBody()); } return json_decode($req->getResponseBody()); }
/** * 配信サーバへリクエストを送信する. * * @param string $mode * @param array $arrParams 追加パラメータ.連想配列で渡す. * @return string|object レスポンスボディ|エラー時にはPEAR::Errorオブジェクトを返す. */ function request($mode, $arrParams = array(), $arrCookies = array()) { $objReq = new HTTP_Request(); $objReq->setUrl(OSTORE_URL . 'upgrade/index.php'); $objReq->setMethod('POST'); $objReq->addPostData('mode', $mode); $objReq->addPostDataArray($arrParams); foreach ($arrCookies as $cookie) { $objReq->addCookie($cookie['name'], $cookie['value']); } $e = $objReq->sendRequest(); if (PEAR::isError($e)) { return $e; } else { return $objReq; } }
/** * _request * 发出请求,统一错误解析 * * @param string $type * @param array $data * @param bool $isPost * * @return array */ private function _request($type, $data = array(), $isPost = false) { // 需要 appToken if (!$data['appToken'] && !in_array($type, $this->noNeedAppToken)) { $data['appToken'] = $this->getAppToken(); } // 需要 accessToken if (!$data['accessToken'] && !in_array($type, $this->noNeedAccessToken)) { $data['accessToken'] = $this->getAccessToken(); } // 请求地址 $requestUrl = $this->apiHost . $type; // 指定请求的超时时间 $httpRequest = new HTTP_Request($requestUrl, HTTP_Request::METHOD_GET, array('connect_timeout' => 1, 'timeout' => 2)); // 文件上传 if ($type == '/v1/thread/upload') { $httpRequest->addFileParameter('pic', $data['pic']); unset($data['pic']); } // post数据 if ($isPost) { $httpRequest->setMethod(HTTP_Request::METHOD_POST); foreach ($data as $name => $value) { $httpRequest->addPostParameter($name, $value); } } else { $httpRequest->setUrl($requestUrl . '?' . http_build_query($data)); } // 发送请求 try { $response = $httpRequest->send(); $result = json_decode($response->getBody(), true); } catch (Exception $e) { throw new Exception($e->getMessage(), $e->getCode()); } if ($response->getStatus() != 200) { throw new Exception('接口请求失败', $response->getStatus()); return false; } if ($result['errCode']) { throw new Exception($result['errMsg'], $result['errCode']); return false; } return $result['data']; }
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; }
/** * Get the Pingback URL for a given URL * * @param string $url URL to get the Pingback URL for * @return string Pingback URL or empty string * */ function PNB_getPingbackUrl($url) { require_once 'HTTP/Request.php'; $retval = ''; $req = new HTTP_Request($url); $req->setMethod(HTTP_REQUEST_METHOD_HEAD); $req->addHeader('User-Agent', 'glFusion/' . GVERSION); $response = $req->sendRequest(); if (PEAR::isError($response)) { COM_errorLog('Pingback (HEAD): ' . $response->getMessage()); return false; } else { $retval = $req->getResponseHeader('X-Pingback'); } if (empty($retval)) { // search for <link rel="pingback"> $req = new HTTP_Request($url); $req->setMethod(HTTP_REQUEST_METHOD_GET); $req->addHeader('User-Agent', 'glFusion/' . GVERSION); $response = $req->sendRequest(); if (PEAR::isError($response)) { COM_errorLog('Pingback (GET): ' . $response->getMessage()); return false; } elseif ($req->getResponseCode() == 200) { $body = $req->getResponseBody(); // only search for the first match - it doesn't make sense to have // more than one pingback URL $found = preg_match("/<link rel=\"pingback\"[^>]*href=[\"']([^\"']*)[\"'][^>]*>/i", $body, $matches); if ($found === 1 && !empty($matches[1])) { $url = str_replace('&', '&', $matches[1]); $retval = urldecode($url); } } else { COM_errorLog('Pingback (GET): Got HTTP response code ' . $req->getResponseCode() . " when requesting {$url}"); return false; } } return $retval; }
/** * @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 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; }
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; }
/** * Extract terms from the Solr index. * * @param string $field Field to extract terms from * @param string $start Starting term to extract (blank for beginning * of list) * @param int $limit Maximum number of terms to return (-1 for no * limit) * @param bool $returnSolrError Should we fail outright on syntax error * (false) or treat it as an empty result set with an error key set (true)? * * @return array Associative array parsed from Solr JSON * response; meat of the response is in the ['terms'] element, which contains * an index named for the requested term, which in turn contains an associative * array of term => count in index. * @access public */ public function getTerms($field, $start, $limit, $returnSolrError = false) { $this->client->setMethod('GET'); $this->client->setURL($this->host . '/term'); $this->client->addQueryString('terms', 'true'); $this->client->addQueryString('terms.fl', $field); $this->client->addQueryString('terms.lower.incl', 'false'); $this->client->addQueryString('terms.lower', $start); $this->client->addQueryString('terms.limit', $limit); $this->client->addQueryString('terms.sort', 'index'); $this->client->addQueryString('wt', 'json'); $result = $this->client->sendRequest(); if (!PEAR_Singleton::isError($result)) { // Process the JSON response: $data = $this->_process($this->client->getResponseBody(), $returnSolrError); // Tidy the data into a more usable format: if (isset($data['terms'])) { $data['terms'] = array($data['terms'][0] => $this->_processTerms($data['terms'][1])); } return $data; } else { return $result; } }
/** * Calculates infos on the given file and returns an array containing these infos */ function GetFileInfo($url) { global $serendipity; $this->log("GetFileInfo for {$url}"); $fileInfo = array(); //caching metadata $cacheOptions = array('lifeTime' => '2592000', 'automaticSerialization' => true, 'cacheDir' => $serendipity['serendipityPath'] . 'templates_c/'); if (serendipity_db_bool($this->get_config('use_cache', 'true'))) { $this->log("GetFileInfo: Trying cached infos"); //md5 for not having strange characters in that id.. $cacheId = md5($url) . '.2'; include_once S9Y_PEAR_PATH . "Cache/Lite.php"; $cache = new Cache_Lite($cacheOptions); if ($fileInfo = $cache->get($cacheId)) { $this->log("GetFileInfo: Cached infos found in file {$cacheId}"); //return directly on cache hit return $fileInfo; } } //cache miss! -> get data, store it in cache and return. // translate pontential relative url to absolute url if (preg_match('@https?://@', $url)) { $absolute_url = $url; } else { $absolute_url = $this->GetHostUrl() . $url; } if ($this->debug) { $fileInfo['absolute_url'] = $absolute_url; } // Now remove configured base URL $rel_path = str_replace($serendipity['baseURL'], "", $absolute_url); if ($this->debug) { $fileInfo['rel_path'] = $rel_path; } // do we have a local file here? //$localMediaFile = $serendipity['serendipityPath'] . $urlParts['path']; $localMediaFile = $serendipity['serendipityPath'] . $rel_path; $fileInfo['localMediaFile'] = $localMediaFile; $this->log("Absolute_url: {$absolute_url} - Relative: {$localMediaFile}"); // Remember extension of file list($sName, $fileInfo['extension']) = serendipity_parseFileName($localMediaFile); if (file_exists($localMediaFile)) { $this->log("GetFileInfo: Local file exists"); $fileInfo['length'] = filesize($localMediaFile); $fileInfo['md5'] = md5_file($localMediaFile); $this->GetID3Infos($localMediaFile, $fileInfo); $this->log(print_r($fileInfo, true)); // Set default $fileInfo['mime'] = $this->getFileMime($fileInfo['extension'], $fileInfo['mime']); } elseif (preg_match('@https?://@', $url)) { include_once S9Y_PEAR_PATH . 'HTTP/Request.php'; if (function_exists('serendipity_request_start')) { serendipity_request_start(); } $this->Log("Execute HTTP_Request for {$url}"); $http = new HTTP_Request($url); $http->setMethod(HTTP_REQUEST_METHOD_HEAD); if (!PEAR::isError($http->sendRequest(false))) { $fileInfo['length'] = intval($http->getResponseHeader('content-length')); $fileInfo['md5'] = $http->getResponseHeader('content-md5'); //will return false if not present $fileInfo['mime'] = $http->getResponseHeader('content-type'); $this->Log("Filling MIME with HTTP Header: " . print_r($fileInfo, true)); } if (function_exists('serendipity_request_end')) { serendipity_request_end(); } } else { // Not found locally and no URL $fileInfo['notfound'] = true; } if (serendipity_db_bool($this->get_config('use_cache', 'true'))) { $cache->save($fileInfo, $cacheId); } return $fileInfo; }
function GetMyIp() { Checks(); $sock = new sockets(); if ($sock->GET_INFO("DoNotResolvInternetIP") == 1) { $ip = $sock->GET_INFO("PublicIPAddress"); if ($ip != null) { return $ip; } } $time = file_time_min("/usr/share/artica-postfix/ressources/logs/web/myIP.conf"); if ($time < 60) { return trim(@file_get_contents("/usr/share/artica-postfix/ressources/logs/web/myIP.conf")); } @unlink("/usr/share/artica-postfix/ressources/logs/web/myIP.conf"); include_once "HTTP/Request.php"; include_once 'Net/DNSBL.php'; $ini = new Bs_IniHandler(); $sock = new sockets(); $datas = $sock->GET_INFO("ArticaProxySettings"); $ini->loadString($datas); $ArticaProxyServerEnabled = $ini->_params["PROXY"]["ArticaProxyServerEnabled"]; $ArticaProxyServerName = $ini->_params["PROXY"]["ArticaProxyServerName"]; $ArticaProxyServerPort = $ini->_params["PROXY"]["ArticaProxyServerPort"]; $ArticaProxyServerUsername = $ini->_params["PROXY"]["ArticaProxyServerUsername"]; $ArticaProxyServerUserPassword = $ini->_params["PROXY"]["ArticaProxyServerUserPassword"]; $ArticaCompiledProxyUri = $ini->_params["PROXY"]["ArticaCompiledProxyUri"]; $req = new HTTP_Request("http://www.artica.fr/my-ip.php"); $req->setURL("http://www.artica.fr/my-ip.php"); $req->setMethod(HTTP_REQUEST_METHOD_GET); if ($ArticaProxyServerEnabled == "yes") { $req->setProxy($ArticaProxyServerName, $ArticaProxyServerPort, $ArticaProxyServerUsername, $ArticaProxyServerUserPassword); } $req->sendRequest(); $code = $req->getResponseCode(); $datas = trim($req->getResponseBody()); writelogs("http://www.artica.fr/my-ip.php -> ({$datas})"); if (preg_match("#([0-9\\.]+)#", $datas, $re)) { $myip = $re[1]; writelogs("http://www.artica.fr/my-ip.php -> {$code} ({$datas})"); } else { writelogs("Unable to preg_match datas...."); } if ($myip != null) { @file_put_contents("/usr/share/artica-postfix/ressources/logs/web/myIP.conf", $myip); @chmod("/usr/share/artica-postfix/ressources/logs/web/myIP.conf", 775); $sock->SET_INFO("PublicIPAddress", $myip); } }
function _request($url, $body = null, $content_type = 'text/html', $method = 'GET', $headers = array(), $cookies = array()) { set_include_path(_XE_PATH_ . "libs/PEAR"); require_once 'PEAR.php'; require_once 'HTTP/Request.php'; $url_info = parse_url($url); $host = $url_info['host']; if (__PROXY_SERVER__ !== null) { $oRequest = new HTTP_Request(__PROXY_SERVER__); $oRequest->setMethod('POST'); $oRequest->addPostData('arg', serialize(array('Destination' => $url, 'method' => $method, 'body' => $body, 'content_type' => $content_type, "headers" => $headers))); } else { $oRequest = new HTTP_Request($url); if (count($headers)) { foreach ($headers as $key => $val) { $oRequest->addHeader($key, $val); } } if ($cookies[$host]) { foreach ($cookies[$host] as $key => $val) { $oRequest->addCookie($key, $val); } } if (!$content_type) { $oRequest->addHeader('Content-Type', 'text/html'); } else { $oRequest->addHeader('Content-Type', $content_type); } $oRequest->setMethod($method); if ($body) { $oRequest->setBody($body); } } $oResponse = $oRequest->sendRequest(); $code = $oRequest->getResponseCode(); $header = $oRequest->getResponseHeader(); $response = $oRequest->getResponseBody(); if ($c = $oRequest->getResponseCookies()) { foreach ($c as $k => $v) { $cookies[$host][$v['name']] = $v['value']; } } if ($code > 300 && $code < 399 && $header['location']) { return $this->_request($header['location'], $body, $content_type, $method, $headers, $cookies); } if ($code != 200) { return; } return $response; }
/** * 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; }