/** * 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(); }
/** * Retrieves data from cache, if it's there. If it is, but it's expired, * it performs a conditional GET to see if the data is updated. If it * isn't, it down updates the modification time of the cache file and * returns the data. If the cache is not there, or the remote file has been * modified, it is downloaded and cached. * * @param string URL of remote file to retrieve * @param int Length of time to cache file locally before asking the server * if it changed. * @return string File contents */ function retrieveFile($url, $cacheLength, $cacheDir) { $cacheID = md5($url); $cache = new Cache_Lite(array("cacheDir" => $cacheDir, "lifeTime" => $cacheLength)); if ($data = $cache->get($cacheID)) { return $data; } else { // we need to perform a request, so include HTTP_Request include_once 'HTTP/Request.php'; // HTTP_Request has moronic redirect "handling", turn that off (Alexey Borzov) $req = new HTTP_Request($url, array('allowRedirects' => false)); // if $cache->get($cacheID) found the file, but it was expired, // $cache->_file will exist if (isset($cache->_file) && file_exists($cache->_file)) { $req->addHeader('If-Modified-Since', gmdate("D, d M Y H:i:s", filemtime($cache->_file)) . " GMT"); } $req->addHeader('User-Agent', 'Firefox (WindowsXP) – Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6'); $req->sendRequest(); if (!($req->getResponseCode() == 304)) { // data is changed, so save it to cache $data = $req->getResponseBody(); $cache->save($data, $cacheID); return $data; } else { // retrieve the data, since the first time we did this failed if ($data = $cache->get($cacheID, 'default', true)) { return $data; } } } Services_ExchangeRates::raiseError("Unable to retrieve file {$url} (unknown reason)", SERVICES_EXCHANGERATES_ERROR_RETRIEVAL_FAILED); return false; }
/** * 投稿実行 */ 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(); }
/** * 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'); return $oReqeust; }
/** * @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; }
/** * @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; }
/** * 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 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"; } }
private function call($method, $args, $include_api_key = true) { $host = "rest.akismet.com"; if ($include_api_key) { $host = "{$this->api_key}.{$host}"; } $url = "http://{$host}/1.1/{$method}"; $req = new HTTP_Request($url, array("method" => "POST")); $req->addHeader("User-Agent", "Cyberspace-Networks/" . PA_VERSION); foreach ($args as $k => $v) { $req->addPostData($k, $v); } $req->sendRequest(); return $req->getResponseBody(); }
/** * 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(); }
/** * Submit REST Request to write data * * @param string $xml The command to execute * @return mixed Boolean true on success or PEAR_Error * @access private */ private function _update($xml) { global $configArray; global $timer; $this->client->setMethod('POST'); $this->client->setURL($this->host . "/update/"); if ($this->debug) { echo "<pre>POST: "; print_r($this->host . "/update/"); echo "XML:\n"; print_r($xml); echo "</pre>\n"; } // Set up XML $this->client->addHeader('Content-Type', 'text/xml; charset=utf-8'); $this->client->addHeader('Content-Length', strlen($xml)); $this->client->setBody($xml); // Send Request $result = $this->client->sendRequest(); $responseCode = $this->client->getResponseCode(); //$this->client->clearPostData(); if ($responseCode == 500 || $responseCode == 400) { $detail = $this->client->getResponseBody(); $timer->logTime("Send the update request"); // Attempt to extract the most useful error message from the response: if (preg_match("/<title>(.*)<\\/title>/msi", $detail, $matches)) { $errorMsg = $matches[1]; } else { $errorMsg = $detail; } global $logger; $logger->log("Error updating document\r\n{$xml}", PEAR_LOG_DEBUG); return new PEAR_Error("Unexpected response -- " . $errorMsg); } elseif ($configArray['System']['debugSolr'] == true) { $this->client->getResponseBody(); $timer->logTime("Get response body"); // Attempt to extract the most useful error message from the response: //print_r("Update Response:"); //print_r($detail); } if (!PEAR_Singleton::isError($result)) { return true; } else { return $result; } }
/** * 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; }
/** * Post data to TypePad api server * * @access public */ function Post($method, $params, $apiKey = '') { $path = "/{$this->apiVersion}/{$method}"; if ($apiKey == '') { $host = $this->apiServer; } else { $host = $apiKey . '.' . $this->apiServer; } $url = sprintf('http://%s:%s/%s/%s', $host, $this->apiPort, $this->apiVersion, $method); require_once PEAR_PATH . 'HTTP/Request.php'; $options = array(); $timeout = (int) $GLOBALS['app']->Registry->fetch('connection_timeout', 'Settings'); $options['timeout'] = $timeout; if ($GLOBALS['app']->Registry->fetch('proxy_enabled', 'Settings') == 'true') { if ($GLOBALS['app']->Registry->fetch('proxy_auth', 'Settings') == 'true') { $options['proxy_user'] = $GLOBALS['app']->Registry->fetch('proxy_user', 'Settings'); $options['proxy_pass'] = $GLOBALS['app']->Registry->fetch('proxy_pass', 'Settings'); } $options['proxy_host'] = $GLOBALS['app']->Registry->fetch('proxy_host', 'Settings'); $options['proxy_port'] = $GLOBALS['app']->Registry->fetch('proxy_port', 'Settings'); } $httpRequest = new HTTP_Request('', $options); $httpRequest->setURL($url); $httpRequest->addHeader('User-Agent', $this->userAgent); $httpRequest->setMethod(HTTP_REQUEST_METHOD_POST); foreach ($params as $key => $data) { $httpRequest->addPostData($key, urlencode(stripslashes($data))); } $resRequest = $httpRequest->sendRequest(); if (PEAR::isError($resRequest)) { return new Jaws_Error($resRequest->getMessage()); } elseif ($httpRequest->getResponseCode() != 200) { return new Jaws_Error('HTTP response error ' . $httpRequest->getResponseCode(), 'Policy', JAWS_ERROR_ERROR); } return $httpRequest->getResponseBody(); }
static function request($method, $url, $token = null, $params = array(), $file = null) { $req = new HTTP_Request($url); $req->setMethod($method == "get" ? HTTP_REQUEST_METHOD_GET : HTTP_REQUEST_METHOD_POST); $req->addHeader("X-Gallery-Request-Method", $method); if ($token) { $req->addHeader("X-Gallery-Request-Key", $token); } foreach ($params as $key => $value) { $req->addPostData($key, $value); } if ($file) { $req->addFile("file", $file, mime_content_type($file)); } $req->sendRequest(); switch ($req->getResponseCode()) { case 200: return json_decode($req->getResponseBody()); case 403: throw new Gallery3_Forbidden_Exception($req->getResponseBody()); default: throw new Gallery3_Exception($req->getResponseBody()); } }
function _startRequest($method) { #$req = &new HTTP_Request($this->url); $req = new HTTP_Request($this->url); $req->addHeader('User-agent', $this->userAgent); $req->addHeader('Content-type', $this->contentType); $req->setMethod($method); return $req; }
/** * @brief Tool dashboard **/ function dispTextyleToolDashboard() { set_include_path(_XE_PATH_ . "libs/PEAR"); require_once 'PEAR.php'; require_once 'HTTP/Request.php'; $oCounterModel =& getModel('counter'); $oDocumentModel =& getModel('document'); $oCommentModel =& getModel('comment'); $oTextyleModel =& getModel('textyle'); $url = sprintf("http://news.textyle.kr/%s/news.php", Context::getLangType()); $cache_file = sprintf("%sfiles/cache/textyle/news/%s%s.cache.xml", _XE_PATH_, getNumberingPath($this->module_srl), Context::getLangType()); if (!file_exists($cache_file) || filemtime($cache_file) + 60 * 60 < time()) { FileHandler::writeFile($cache_file, ''); if (__PROXY_SERVER__ !== null) { $oRequest = new HTTP_Request(__PROXY_SERVER__); $oRequest->setMethod('POST'); $oRequest->_timeout = $timeout; $oRequest->addPostData('arg', serialize(array('Destination' => $url))); } else { $oRequest = new HTTP_Request($url); if (!$content_type) { $oRequest->addHeader('Content-Type', 'text/html'); } else { $oRequest->addHeader('Content-Type', $content_type); } if (count($headers)) { foreach ($headers as $key => $val) { $oRequest->addHeader($key, $val); } } $oRequest->_timeout = 2; } if (isSiteID($this->textyle->domain)) { $oRequest->addHeader('REQUESTURL', Context::getRequestUri() . $this->textyle->domain); } else { $oRequest->addHeader('REQUESTURL', $this->textyle->domain); } $oResponse = $oRequest->sendRequest(); $body = $oRequest->getResponseBody(); FileHandler::writeFile($cache_file, $body); } if (file_exists($cache_file)) { $oXml = new XmlParser(); $buff = $oXml->parse(FileHandler::readFile($cache_file)); $item = $buff->news->item; if ($item) { if (!is_array($item)) { $item = array($item); } foreach ($item as $key => $val) { $obj = null; $obj->title = $val->body; $obj->date = $val->attrs->date; $obj->url = $val->attrs->url; $news[] = $obj; } Context::set('news', $news); } } $time = time(); $w = date("D"); while (date("D", $time) != "Sun") { $time += 60 * 60 * 24; } $time -= 60 * 60 * 24; while (date("D", $time) != "Sun") { $thisWeek[] = date("Ymd", $time); $time -= 60 * 60 * 24; } $thisWeek[] = date("Ymd", $time); asort($thisWeek); $thisWeekCounter = $oCounterModel->getStatus($thisWeek, $this->site_srl); $time -= 60 * 60 * 24; while (date("D", $time) != "Sun") { $lastWeek[] = date("Ymd", $time); $time -= 60 * 60 * 24; } $lastWeek[] = date("Ymd", $time); asort($lastWeek); $lastWeekCounter = $oCounterModel->getStatus($lastWeek, $this->site_srl); $max = 0; foreach ($thisWeek as $day) { $v = (int) $thisWeekCounter[$day]->unique_visitor; if ($v && $v > $max) { $max = $v; } $status->week[date("D", strtotime($day))]->this = $v; } foreach ($lastWeek as $day) { $v = (int) $lastWeekCounter[$day]->unique_visitor; if ($v && $v > $max) { $max = $v; } $status->week[date("D", strtotime($day))]->last = $v; } $status->week_max = $max; $idx = 0; foreach ($status->week as $key => $val) { $_item[] = sprintf("<item id=\"%d\" name=\"%s\" />", $idx, $thisWeek[$idx]); $_thisWeek[] = $val->this; $_lastWeek[] = $val->last; $idx++; } $buff = '<?xml version="1.0" encoding="utf-8" ?><Graph><gdata title="Textyle Counter" id="data2"><fact>' . implode('', $_item) . '</fact><subFact>'; $buff .= '<item id="0"><data name="' . Context::getLang('this_week') . '">' . implode('|', $_thisWeek) . '</data></item>'; $buff .= '<item id="1"><data name="' . Context::getLang('last_week') . '">' . implode('|', $_lastWeek) . '</data></item>'; $buff .= '</subFact></gdata></Graph>'; Context::set('xml', $buff); $counter = $oCounterModel->getStatus(array(0, date("Ymd")), $this->site_srl); $status->total_visitor = $counter[0]->unique_visitor; $status->visitor = $counter[date("Ymd")]->unique_visitor; $args->module_srl = $this->module_srl; $args->regdate = date("Ymd"); $output = executeQuery('textyle.getTodayCommentCount', $args); $status->comment_count = $output->data->count; $args->module_srl = $this->module_srl; $args->regdate = date("Ymd"); $output = executeQuery('textyle.getTodayTrackbackCount', $args); $status->trackback_count = $output->data->count; Context::set('status', $status); $doc_args->module_srl = array($this->textyle->get('member_srl'), $this->module_srl); $doc_args->sort_index = 'list_order'; $doc_args->order_type = 'asc'; $doc_args->list_count = 3; $output = $oDocumentModel->getDocumentList($doc_args, false, false); Context::set('newest_documents', $output->data); $com_args->module_srl = $this->textyle->get('module_srl'); $com_args->sort_index = 'list_order'; $com_args->order_type = 'asc'; $com_args->list_count = 5; $output = $oCommentModel->getTotalCommentList($com_args); Context::set('newest_comments', $output->data); unset($args); $args->module_srl = $this->module_srl; $args->page = 1; $args->list_count = 5; $output = $oTextyleModel->getTextyleGuestbookList($args); Context::set('guestbook_list', $output->data); }
function fetchUrlPear($url, $request_parameters) { if (VERBOSE) { logEvent($url . ' fetching with PEAR'); } if (0 && $GLOBALS['has_pear_http_request'] == 2) { $headreq = new HTTP_Request2($url, $request_parameters); $headreq->setHeader('User-Agent', 'phplist v' . VERSION . 'p (http://www.phplist.com)'); } else { $headreq = new HTTP_Request($url, $request_parameters); $headreq->addHeader('User-Agent', 'phplist v' . VERSION . 'p (http://www.phplist.com)'); } if (!PEAR::isError($headreq->sendRequest(false))) { $code = $headreq->getResponseCode(); if ($code != 200) { logEvent('Fetching ' . $url . ' failed, error code ' . $code); return 0; } $header = $headreq->getResponseHeader(); if (preg_match('/charset=(.*)/i', $header['content-type'], $regs)) { $remote_charset = strtoupper($regs[1]); } $request_parameters['method'] = 'GET'; if (0 && $GLOBALS['has_pear_http_request'] == 2) { $req = new HTTP_Request2($url, $request_parameters); $req->setHeader('User-Agent', 'phplist v' . VERSION . 'p (http://www.phplist.com)'); } else { $req = new HTTP_Request($url, $request_parameters); $req->addHeader('User-Agent', 'phplist v' . VERSION . 'p (http://www.phplist.com)'); } logEvent('Fetching ' . $url); if (VERBOSE && function_exists('output')) { output('Fetching remote: ' . $url); } if (!PEAR::isError($req->sendRequest(true))) { $content = $req->getResponseBody(); if ($remote_charset != 'UTF-8' && function_exists('iconv')) { $content = iconv($remote_charset, 'UTF-8//TRANSLIT', $content); } } else { logEvent('Fetching ' . $url . ' failed on GET ' . $req->getResponseCode()); return 0; } } else { logEvent('Fetching ' . $url . ' failed on HEAD'); return 0; } return $content; }
/** * Attempt to auto-detect the Trackback URL of a post. * * @param string $url URL of post with embedded RDF for the Trackback URL * @return mixed Trackback URL, or false on error * * Note: The RDF, if found, is only parsed using a regular expression. Using * the XML parser may be more successful on some occassions ... * */ function TRB_detectTrackbackUrl($url) { require_once 'HTTP/Request.php'; $retval = false; $req = new HTTP_Request($url); $req->setMethod(HTTP_REQUEST_METHOD_GET); $req->addHeader('User-Agent', 'Geeklog/' . VERSION); $response = $req->sendRequest(); if (PEAR::isError($response)) { COM_errorLog('TRB_detectTrackbackUrl: ' . $response->getMessage()); return false; } $page = $req->getResponseBody(); // search for the RDF first $startpos = strpos($page, '<rdf:RDF '); if ($startpos !== false) { $endpos = strpos($page, '</rdf:RDF>', $startpos); $endpos += strlen('</rdf:RDF>'); $rdf = substr($page, $startpos, $endpos - $startpos); // Okay, we COULD fire up the XML parser now. But then again ... if (preg_match('/trackback:ping="(.*)"/', $rdf, $matches) == 1) { if (!empty($matches[1])) { $retval = $matches[1]; } } } // no luck with the RDF? try searching for a rel="trackback" link if ($retval === false) { // remove all linefeeds first to help the regexp below $page = str_replace(array("\r", "\n"), '', $page); preg_match_all("/<a[^>]*href=[\"']([^\"']*)[\"'][^>]*>(.*?)<\\/a>/i", $page, $matches); for ($i = 0; $i < count($matches[0]); $i++) { $link = $matches[0][$i]; if (strpos($link, 'rel="trackback"') !== false) { $retval = $matches[1][$i]; break; } } } return $retval; }
/** * Handle a pingback for an entry. * * Also takes care of the speedlimit and spam. Assumes that the caller of this * function has already checked permissions! * * @param string $id ID of entry that got pinged * @param string $type type of that entry ('article' for stories, etc.) * @param string $url URL of the page that pinged us * @param string $oururl URL that got pinged on our site * @return object XML-RPC response * */ function PNB_handlePingback($id, $type, $url, $oururl) { global $_CONF, $_TABLES, $PNB_ERROR; require_once 'HTTP/Request.php'; if (!isset($_CONF['check_trackback_link'])) { $_CONF['check_trackback_link'] = 2; } // handle pingbacks to articles on our own site $skip_speedlimit = false; if ($_SERVER['REMOTE_ADDR'] == $_SERVER['SERVER_ADDR']) { if (!isset($_CONF['pingback_self'])) { $_CONF['pingback_self'] = 0; // default: skip self-pingbacks } if ($_CONF['pingback_self'] == 0) { return new XML_RPC_Response(new XML_RPC_Value($PNB_ERROR['skipped'])); } else { if ($_CONF['pingback_self'] == 2) { $skip_speedlimit = true; } } } COM_clearSpeedlimit($_CONF['commentspeedlimit'], 'pingback'); if (!$skip_speedlimit) { $last = COM_checkSpeedlimit('pingback'); if ($last > 0) { return new XML_RPC_Response(0, 49, sprintf($PNB_ERROR['speedlimit'], $last, $_CONF['commentspeedlimit'])); } } // update speed limit in any case COM_updateSpeedlimit('pingback'); if ($_SERVER['REMOTE_ADDR'] != $_SERVER['SERVER_ADDR']) { if ($_CONF['check_trackback_link'] & 4) { $parts = parse_url($url); if (empty($parts['host'])) { TRB_logRejected('Pingback: No valid URL', $url); return new XML_RPC_Response(0, 33, $PNB_ERROR['uri_invalid']); } else { $ip = gethostbyname($parts['host']); if ($ip != $_SERVER['REMOTE_ADDR']) { TRB_logRejected('Pingback: IP address mismatch', $url); return new XML_RPC_Response(0, 49, $PNB_ERROR['spam']); } } } } // See if we can read the page linking to us and extract at least // the page's title out of it ... $title = ''; $excerpt = ''; $req = new HTTP_Request($url); $req->addHeader('User-Agent', 'Geeklog/' . VERSION); $response = $req->sendRequest(); if (PEAR::isError($response)) { if ($_CONF['check_trackback_link'] & 3) { // we were supposed to check for backlinks but didn't get the page COM_errorLog("Pingback verification: " . $response->getMessage() . " when requesting {$url}"); return new XML_RPC_Response(0, 33, $PNB_ERROR['uri_invalid']); } // else: silently ignore errors - we'll simply do without the title } else { if ($req->getResponseCode() == 200) { $body = $req->getResponseBody(); if ($_CONF['check_trackback_link'] & 3) { if (!TRB_containsBacklink($body, $oururl)) { TRB_logRejected('Pingback: No link to us', $url); $comment = TRB_formatComment($url); PLG_spamAction($comment, $_CONF['spamx']); return new XML_RPC_Response(0, 49, $PNB_ERROR['spam']); } } preg_match(':<title>(.*)</title>:i', $body, $content); if (empty($content[1])) { $title = ''; // no title found } else { $title = trim(COM_undoSpecialChars($content[1])); } if ($_CONF['pingback_excerpt']) { // Check which character set the site that sent the Pingback // is using $charset = 'ISO-8859-1'; // default, see RFC 2616, 3.7.1 $ctype = $req->getResponseHeader('Content-Type'); if (!empty($ctype)) { // e.g. text/html; charset=utf-8 $c = explode(';', $ctype); foreach ($c as $ct) { $ch = explode('=', trim($ct)); if (count($ch) == 2) { if (trim($ch[0]) == 'charset') { $charset = trim($ch[1]); break; } } } } if (!empty($charset) && strcasecmp($charset, COM_getCharset()) != 0) { if (function_exists('mb_convert_encoding')) { $body = @mb_convert_encoding($body, COM_getCharset(), $charset); } elseif (function_exists('iconv')) { $body = @iconv($charset, COM_getCharset(), $body); } // else: tough luck ... } $excerpt = PNB_makeExcerpt($body, $oururl); } // we could also run the rest of the other site's page // through the spam filter here ... } else { if ($_CONF['check_trackback_link'] & 3) { COM_errorLog("Pingback verification: Got HTTP response code " . $req->getResponseCode() . " when requesting {$url}"); return new XML_RPC_Response(0, 33, $PNB_ERROR['uri_invalid']); } } // else: silently ignore errors - we'll simply do without the title } // check for spam first $saved = TRB_checkForSpam($url, $title, '', $excerpt); if ($saved == TRB_SAVE_SPAM) { return new XML_RPC_Response(0, 49, $PNB_ERROR['spam']); } // save as a trackback comment $saved = TRB_saveTrackbackComment($id, $type, $url, $title, '', $excerpt); if ($saved == TRB_SAVE_REJECT) { return new XML_RPC_Response(0, 49, $PNB_ERROR['multiple']); } if (isset($_CONF['notification']) && in_array('pingback', $_CONF['notification'])) { TRB_sendNotificationEmail($saved, 'pingback'); } return new XML_RPC_Response(new XML_RPC_Value($PNB_ERROR['success'])); }
public function extractPage($url, $match, $replace, $referer, $source, $ident = null) { global $_conf; $ret = array(); $source = @preg_replace('{' . $match . '}', $source, $url); $get_url = $referer; if ($this->extractErrors[$get_url]) { // 今回リクエストでエラーだった場合 return $this->cacheData[$url] && $this->cacheData[$url]['data'] ? $this->cacheData[$url]['data'] : $ret; } $params = array(); $params['timeout'] = $_conf['http_conn_timeout']; $params['readTimeout'] = array($_conf['http_read_timeout'], 0); if ($_conf['proxy_use']) { $params['proxy_host'] = $_conf['proxy_host']; $params['proxy_port'] = $_conf['proxy_port']; } $req = new HTTP_Request($get_url, $params); if ($this->cacheData[$url] && $this->cacheData[$url]['responseHeaders'] && $this->cacheData[$url]['responseHeaders']['last-modified'] && strlen($this->cacheData[$url]['responseHeaders']['last-modified'])) { $req->addHeader("If-Modified-Since", $this->cacheData[$url]['responseHeaders']['last-modified']); } $req->addHeader('User-Agent', !empty($_conf['expack.user_agent']) ? $_conf['expack.user_agent'] : $_SERVER['HTTP_USER_AGENT']); $response = $req->sendRequest(); $code = $req->getResponseCode(); if (PEAR::isError($response) || $code != 200 && $code != 206 && $code != 304) { $errmsg = PEAR::isError($response) ? $response->getMessage() : $code; // 今回リクエストでのエラーをオンラインキャッシュ $this->extractErrors[$get_url] = $errmsg; // サーバエラー以外なら永続キャッシュに保存 if ($code && $code < 500) { // ページが消えている場合 if ($this->_checkLost($url, $ret)) { return $this->cacheData[$url]['data']; } $this->storeCache($url, array('code' => $code, 'errmsg' => $errmsg, 'responseHeaders' => $req->getResponseHeader(), 'data' => $ret)); } return $this->cacheData[$url] && $this->cacheData[$url]['data'] ? $this->cacheData[$url]['data'] : $ret; } if ($code == 304 && $this->cacheData[$url]) { return $this->cacheData[$url]['data']; } $body = $req->getResponseBody(); preg_match_all('{' . $source . '}i', $body, $extracted, PREG_SET_ORDER); foreach ($extracted as $i => $extract) { $_url = $replace; $_referer = $referer; foreach ($extract as $j => $part) { if ($j < 1) { continue; } $_url = str_replace('$EXTRACT' . $j, $part, $_url); $_referer = str_replace('$EXTRACT' . $j, $part, $_referer); } if ($extract[1]) { $_url = str_replace('$EXTRACT', $part, $_url); $_referer = str_replace('$EXTRACT', $part, $_referer); } $ret[$i]['url'] = $_url; $ret[$i]['referer'] = $_referer; } // ページが消えている場合 if ($this->_checkLost($url, $ret)) { return $this->cacheData[$url]['data']; } if ($ident && $this->cacheData[$url] && $this->cacheData[$url]['data']) { $ret = self::_identByCacheData($ret, $this->cacheData[$url]['data'], $ident); } // 結果を永続キャッシュに保存 $this->storeCache($url, array('code' => $code, 'responseHeaders' => $req->getResponseHeader(), 'data' => $ret)); return $ret; }
/** * Send a track/pingback ping * * @access public * @param string The URL to send a trackback to * @param string The XML data with the trackback contents * @return string Reponse */ function _serendipity_send($loc, $data, $contenttype = null) { global $serendipity; $target = parse_url($loc); if ($target['query'] != '') { $target['query'] = '?' . str_replace('&', '&', $target['query']); } if ($target['scheme'] == 'https' && empty($target['port'])) { $uri = $target['scheme'] . '://' . $target['host'] . $target['path'] . $target['query']; } elseif (!is_numeric($target['port'])) { $target['port'] = 80; $uri = $target['scheme'] . '://' . $target['host'] . ':' . $target['port'] . $target['path'] . $target['query']; } require_once S9Y_PEAR_PATH . 'HTTP/Request.php'; $options = array('allowRedirects' => true, 'maxRedirects' => 5, 'method' => 'POST'); serendipity_plugin_api::hook_event('backend_http_request', $options, 'trackback_send'); serendipity_request_start(); $req = new HTTP_Request($uri, $options); if (isset($contenttype)) { $req->addHeader('Content-Type', $contenttype); } $req->addRawPostData($data, true); $res = $req->sendRequest(); if (PEAR::isError($res)) { serendipity_request_end(); return false; } $fContent = $req->getResponseBody(); serendipity_request_end(); return $fContent; }
function getRemoteResource($url, $body = null, $timeout = 3, $method = 'GET', $content_type = null, $headers = array(), $cookies = array(), $post_data = array()) { requirePear(); require_once 'HTTP/Request.php'; $parsed_url = parse_url(__PROXY_SERVER__); if ($parsed_url["host"]) { $oRequest = new HTTP_Request(__PROXY_SERVER__); $oRequest->setMethod('POST'); $oRequest->_timeout = $timeout; $oRequest->addPostData('arg', serialize(array('Destination' => $url, 'method' => $method, 'body' => $body, 'content_type' => $content_type, "headers" => $headers, "post_data" => $post_data))); } 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 (count($post_data)) { foreach ($post_data as $key => $val) { $oRequest->addPostData($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); } $oRequest->_timeout = $timeout; } $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 FileHandler::getRemoteResource($header['location'], $body, $timeout, $method, $content_type, $headers, $cookies, $post_data); } return $response; }
function get_url($url, $cache_hard = true) { global $http_cache_timeout; global $api_calls; global $cached_api_calls; # Check whether we have a cached response for this URL # Note there are two cache timestamps: fetched_on_server is tied to the # server (mothership)'s clock and fetched_on is tied to the local clock. # We are careful to compare the local now() against fetched_on and the # server's "Date:" header values against fetched_on_server. if (!$http_cache_timeout) { throw new Exception("\$http_cache_timeout not set"); } # Expire old cache entries. mysql_query('delete from http_cache where fetched_on < now() - ' . $http_cache_timeout); # Load a valid cache element, if any. $sql = 'select content, fetched_on_server from http_cache where url = \'' . mysql_real_escape_string($url) . '\' and fetched_on >= now() - ' . $http_cache_timeout; $q = mysql_query($sql); if (!$q) { throw new Exception("Getting cache, got database error: " . mysql_error()); } require_once 'HTTP/Request.php'; if ($row = mysql_fetch_row($q)) { list($content, $fetched_on) = $row; # Under "hard" caching, return the cached data without talking to server. if ($cache_hard) { message("Hard cache hit at {$url}"); return $content; } # Under "soft" caching, we make a request to ask the server if the resource # has changed since our copy. $fetched_on_http_date = date(DATE_RFC1123, from_mysql_date($fetched_on)); $req = new HTTP_Request($url); $req->addHeader('If-Modified-Since', $fetched_on_http_date); $request_timer -= microtime(true); $ok = $req->sendRequest(); $request_timer += microtime(true); $cached_api_calls = $cached_api_calls + 1; if (!PEAR::isError($ok)) { $respCode = $req->getResponseCode(); if (304 == $respCode) { # 304 Not Modified; we can use the cached copy. message('Cache hit at ' . $url . ' using If-Modified-Since: ' . $fetched_on_http_date . "Request timer: {$request_timer}" . 's'); return $content; } elseif (200 <= $respCode && $respCode < 300) { # Got an OK response, use the data. message('Cache refresh at ' . $url . ' If-Modified-Since: ' . $fetched_on_http_date . '. Request timer: ' . $request_timer . 's'); $content = $req->getResponseBody(); $fetched_on_server = mysql_date(from_http_date($req->getResponseHeader('Date'))); mysql_query('delete from http_cache where url = \'' . mysql_real_escape_string($url) . '\''); if (!insert_into('http_cache', array('url' => $url, 'content' => $content, 'fetched_on_server' => $fetched_on_server))) { throw new Exception("Database error writing to HTTP cache: " . mysql_error()); } return $content; } } else { throw new Exception("Error while GETing {$url} ({$ok})"); } } else { $req = new HTTP_Request($url); $request_timer -= microtime(true); $ok = $req->sendRequest(); $request_timer += microtime(true); $api_calls = $api_calls + 1; message("Cache miss at {$url} Request timer: " . $request_timer . "s"); if (PEAR::isError($ok)) { throw new Exception("Unknown error trying GET {$url}"); } $respCode = $req->getResponseCode(); if (200 <= $respCode && $respCode < 300) { # Got an OK response, use it. $content = $req->getResponseBody(); $fetched_on_server = mysql_date(from_http_date($req->getResponseHeader('Date'))); mysql_query('delete from http_cache where url = \'' . mysql_real_escape_string($url) . '\''); if (!insert_into('http_cache', array('url' => $url, 'content' => $content, 'fetched_on_server' => $fetched_on_server))) { throw new Exception("Database error writing to HTTP cache: " . mysql_error()); } return $content; } else { error("GET {$url} returned {$respCode}"); return null; } } }
/** * 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; }
function event_hook($event, &$bag, &$eventData) { global $serendipity; $hooks =& $bag->get('event_hooks'); if (isset($hooks[$event])) { switch ($event) { case 'backend_display': ?> <fieldset style="margin: 5px"> <legend><?php echo PLUGIN_EVENT_WEBLOGPING_PING; ?> </legend> <?php $noneclick = ''; foreach ($this->services as $index => $service) { // Detect if the current checkbox needs to be saved. We use the field chk_timestamp to see, // if the form has already been submitted and individual changes shall be preserved $selected = $serendipity['POST']['chk_timestamp'] && $serendipity['POST']['announce_entries_' . $service['name']] || !isset($serendipity['POST']['chk_timestamp']) && $this->get_config($service['name']) == 'true' ? 'checked="checked"' : ''; $noneclick .= 'document.getElementById(\'serendipity[announce_entries_' . $service['name'] . ']\').checked = false; '; $onclick = ''; if (!empty($service['supersedes'])) { $onclick = 'onclick="'; $supersedes = explode(', ', $service['supersedes']); foreach ($supersedes as $sid => $servicename) { $onclick .= 'document.getElementById(\'serendipity[announce_entries_' . $servicename . ']\').checked = false; '; } $onclick .= '"'; } $title = sprintf(PLUGIN_EVENT_WEBLOGPING_SENDINGPING, $service['name']) . (!empty($service['supersedes']) ? ' ' . sprintf(PLUGIN_EVENT_WEBLOGPING_SUPERSEDES, $service['supersedes']) : ''); ?> <input <?php echo $onclick; ?> class="input_checkbox" style="margin: 0px; padding: 0px; vertical-align: bottom;" type="checkbox" name="serendipity[announce_entries_<?php echo $service['name']; ?> ]" id="serendipity[announce_entries_<?php echo $service['name']; ?> ]" value="true" <?php echo $selected; ?> /> <label title="<?php echo $title; ?> " style="vertical-align: bottom; margin: 0px; padding: 0px;" for="serendipity[announce_entries_<?php echo $service['name']; ?> ]"> <?php echo $service['name']; ?> </label><br /> <?php } ?> <input onclick="<?php echo $noneclick; ?> " class="input_checkbox" style="margin: 0px; padding: 0px; vertical-align: bottom;" type="checkbox" value="none" id="serendipity[announce_entries_none]" /> <label title="<?php echo NONE; ?> " style="vertical-align: bottom; margin: 0px; padding: 0px;" for="serendipity[announce_entries_none]"> <?php echo NONE; ?> </label><br /> </fieldset> <?php return true; break; case 'backend_publish': if (!class_exists('XML_RPC_Base')) { include_once S9Y_PEAR_PATH . "XML/RPC.php"; } // First cycle through list of services to remove superseding services which may have been checked foreach ($this->services as $index => $service) { if (!empty($service['supersedes']) && isset($serendipity['POST']['announce_entries_' . $service['name']])) { $supersedes = explode(', ', $service['supersedes']); foreach ($supersedes as $sid => $servicename) { // A service has been checked that is superseded by another checked meta-service. Remove that service from the list of services to be ping'd unset($serendipity['POST']['announce_entries_' . $servicename]); } } } foreach ($this->services as $index => $service) { if (isset($serendipity['POST']['announce_entries_' . $service['name']]) || defined('SERENDIPITY_IS_XMLRPC') && serendipity_db_bool($this->get_config($service['name']))) { if (!defined('SERENDIPITY_IS_XMLRPC') || defined('SERENDIPITY_XMLRPC_VERBOSE')) { printf(PLUGIN_EVENT_WEBLOGPING_SENDINGPING . '...', $service['host']); } flush(); # XXX append $serendipity['indexFile'] to baseURL? $args = array(new XML_RPC_Value($serendipity['blogTitle'], 'string'), new XML_RPC_Value($serendipity['baseURL'], 'string')); if ($service['extended']) { # the checkUrl: for when the main page is not really the main page $args[] = new XML_RPC_Value('', 'string'); # the rssUrl $args[] = new XML_RPC_Value($serendipity['baseURL'] . 'rss.php?version=2.0', 'string'); } $message = new XML_RPC_Message($service['extended'] ? 'weblogUpdates.extendedPing' : 'weblogUpdates.ping', $args); $client = new XML_RPC_Client(trim($service['path']), trim($service['host'])); # 15 second timeout may not be long enough for weblogs.com $message->createPayload(); $options = array(); serendipity_plugin_api::hook_event('backend_http_request', $options, 'weblogping'); serendipity_request_start(); $req = new HTTP_Request("http://" . $service['host'] . $service['path'], $options); $req->setMethod(HTTP_REQUEST_METHOD_POST); $req->addHeader("Content-Type", "text/xml"); if (strtoupper(LANG_CHARSET) != 'UTF-8') { $payload = utf8_encode($message->payload); } else { $payload = $message->payload; } $req->addRawPostData($payload); $http_result = $req->sendRequest(); $http_response = $req->getResponseBody(); $xmlrpc_result = $message->parseResponse($http_response); if ($xmlrpc_result->faultCode()) { $out = sprintf(PLUGIN_EVENT_WEBLOGPING_SEND_FAILURE . "<br />", htmlspecialchars($xmlrpc_result->faultString())); } else { $out = PLUGIN_EVENT_WEBLOGPING_SEND_SUCCESS . "<br />"; } serendipity_request_end(); if (!defined('SERENDIPITY_IS_XMLRPC') || defined('SERENDIPITY_XMLRPC_VERBOSE')) { echo $out; } } } return true; break; case 'external_plugin': if ($eventData == 'xmlrpc_ping') { echo "XMLRPC START\n"; @define('SERENDIPITY_IS_XMLRPC', true); @define('SERENDIPITY_XMLRPC_VERBOSE', true); $this->event_hook('backend_publish', $bag, $eventData); echo "XMLRPC DONE\n"; } return true; case 'frontend_display': case 'backend_insert': case 'backend_update': case 'backend_draft': default: return false; break; } } else { return false; } }
function import() { global $serendipity; // Force user to select a blog to act on if (empty($this->data['bId']) || $this->data['bId'] == 0) { echo 'Please select a blog to import!'; return false; } // Save this so we can return it to its original value at the end of this method. $noautodiscovery = isset($serendipity['noautodiscovery']) ? $serendipity['noautodiscovery'] : false; if ($this->data['autodiscovery'] == 'false') { $serendipity['noautodiscovery'] = 1; } $this->getTransTable(); // Prepare export request $req = new HTTP_Request('http://www.blogger.com/feeds/' . $this->data['bId'] . '/archive'); $req->addHeader('GData-Version', 2); $req->addHeader('Authorization', 'AuthSub token="' . $this->data['bAuthToken'] . '"'); // Attempt fetch blog export $req->sendRequest(); // Handle errors if ($req->getResponseCode() != '200') { echo "Error occured while trying to export the blog."; return false; } // Export success echo '<span class="block_level">Successfully exported entries from Blogger</span>'; // Get Serendipity authors list $authorList = array(); $s9y_users = serendipity_fetchUsers(); foreach ($s9y_users as $user) { $authorList[$user['authorid']] = $user['username']; } unset($s9y_users); // Load export $bXml = simplexml_load_string($req->getResponseBody()); // Process entries $entryList = $entryFailList = array(); foreach ($bXml->entry as $bEntry) { // Check entry type switch ($bEntry->category['term']) { case 'http://schemas.google.com/blogger/2008/kind#post': // Process posts: // Create author if not in serendipity $author = (string) $bEntry->author->name; if (!array_search($author, $authorList)) { serendipity_db_insert('authors', array('right_publish' => 1, 'realname' => $author, 'username' => $author, 'userlevel' => 0, 'password' => md5($this->data['defaultpass']))); $authorid = serendipity_db_insert_id('authors', 'authorid'); $authorList[$authorid] = $author; } $sEntry = array('title' => $this->decode((string) $bEntry->title), 'isdraft' => $bEntry->children('http://purl.org/atom/app#')->control->draft == 'yes' ? 'true' : 'false', 'allow_comments' => count($bEntry->xpath("*[@rel='replies']")) > 0 ? 'true' : 'false', 'timestamp' => strtotime($bEntry->published), 'body' => $this->strtr((string) $bEntry->content), 'extended' => '', 'categories' => $this->data['bCategory'], 'author' => $author, 'authorid' => $authorid); // Add entry to s9y echo '..~.. '; if (is_int($id = serendipity_updertEntry($sEntry))) { // Add entry id to processed table for later lookups $entryList[(string) $bEntry->id] = array($id, $sEntry['title'], 0); } else { // Add to fail list $entryFailList[] = $sEntry['title']; } break; case 'http://schemas.google.com/blogger/2008/kind#comment': // Process comments: // Extract entry id for comment $cEntryId = $bEntry->xpath("thr:in-reply-to[@ref]"); $cEntryId = (string) $cEntryId[0]['ref']; // Check to make sure the related entry has been added to s9y if (array_key_exists($cEntryId, $entryList)) { // Add to s9y $sComment = array('entry_id ' => $entryList[$cEntryId][0], 'parent_id' => 0, 'timestamp' => strtotime($bEntry->published), 'author' => (string) $bEntry->author->name, 'email' => (string) $bEntry->author->email, 'url' => (string) isset($bEntry->author->uri) ? $bEntry->author->uri : '', 'ip' => '', 'status' => 'approved', 'body' => $this->strtr((string) $bEntry->content), 'subscribed' => 'false', 'type' => 'NORMAL'); serendipity_db_insert('comments', $sComment); // Update entry list with comment count $entryList[$cEntryId][2]++; } break; } } // Report on resultant authors echo '<span class="block_level">Current list of authors: </span>' . join(', ', array_values($authorList)); // Do cleanup and report on entries echo '<span class="block_level">The following entries were successfully imported:</span>'; echo '<ul>'; foreach ($entryList as $eId => $eDetails) { // Update comment count for entry in s9y serendipity_db_query("UPDATE " . $serendipity['dbPrefix'] . "entries SET comments = " . $eDetails[2] . " WHERE id = " . $eDetails[0]); echo '<li>' . $eDetails[1] . ' comments(' . $eDetails[2] . ')</li>'; } echo '</ul>'; // Report fails echo '<span class="block_level">The following entries ran into trouble and was not imported:</span>'; echo '<ul>'; foreach ($entryFailList as $eId => $eDetails) { echo '<li>' . $eDetails . '</li>'; } echo '</ul>'; // Reset autodiscovery $serendipity['noautodiscovery'] = $noautodiscovery; // All done! echo '<span class="msg_notice">Import finished.</span>'; return true; }
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; }
protected function _saveUserPhoto($from, $to) { $ret = ''; require_once 'HTTP/Request.php'; $req = new HTTP_Request($from); $req->addHeader('User-Agent', 'Geeklog/' . VERSION); $req->addHeader('Referer', COM_getCurrentUrl()); $res = $req->sendRequest(); if (!PEAR::isError($res)) { $img = $req->getResponseBody(); $ret = file_put_contents($to, $img); } return $ret; }