public function init(array $options) { // base url if (isset($options['baseURL'])) { $this->baseURL = $options['baseURL']; } else { $this->baseURL = 'http://' . $_SERVER['SERVER_NAME']; } if (isset($options['ezrpPath'])) { $this->ezrpPath = $options['ezrpPath']; } $this->sessionID = $options['sessionID']; $verifyURL = new Net_URL2(rtrim($this->baseURL, '/') . $this->ezrpPath); $verifyURL->setQueryVariable('ezrpd', $this->driver); $this->verifyURL = $verifyURL->getURL(); }
/** * Http request * * @param string $method * @param string $url * @param array $submit * @param string $formName * * @return HTTP_Request2_Response */ public function request($method, $url, array $submit = array(), $formName = 'form') { $this->request = new HTTP_Request2(); $url = new Net_URL2($url); $this->request->setMethod($method); if ($submit) { $submit = array_merge(array('_token' => '0dc59902014b6', '_qf__' . $formName => ''), $submit); } if ($submit && $method === 'POST') { $this->request->addPostParameter($submit); } if ($submit && $method === 'GET') { $url->setQueryVariables($submit); } $this->request->setUrl($url); $this->response = $this->request->send(); return $this; }
function devtips_extract(DevTip $tip) { global $updates_dir; $assetPath = getFileName($tip->get('date'), $tip->get('title')); $assetPath = str_replace(".markdown", "", $assetPath); # create new asset directory based on new filename if (!file_exists($updates_dir . 'images/' . $assetPath)) { mkdir($updates_dir . 'images/' . $assetPath); chmod($updates_dir . 'images/' . $assetPath, 0777); } # Download and store each asset $assets = $tip->get('assets'); $featured = null; foreach ($assets as $key => $url) { if (strpos($url, "/sponsor/") !== false) { continue; } $base = new Net_URL2('https://umaar.com/dev-tips/'); $abs = $base->resolve($url); $dest = $updates_dir . 'images/' . $assetPath . '/' . pathinfo($url)['basename']; $content = $tip->get('content'); $tip->set('content', str_replace($url, '/web/updates/images/' . $assetPath . '/' . pathinfo($url)['basename'], $content)); if (!$featured) { $tip->set('featured-image', '/web/updates/images/' . $assetPath . '/' . pathinfo($url)['basename']); } if (!file_exists($dest)) { set_time_limit(0); $fp = fopen($dest, 'w+'); //This is the file where we save the information $ch = curl_init(str_replace(" ", "%20", $abs)); //Here is the file we are downloading, replace spaces with %20 curl_setopt($ch, CURLOPT_TIMEOUT, 50); curl_setopt($ch, CURLOPT_FILE, $fp); // write curl response to file curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_exec($ch); // get curl response curl_close($ch); fclose($fp); // set proper chmod chmod($dest, 0777); } } }
/** * Parses the config and splits up the port + url * @return array */ public function parse() { $proxy = $this->config->getSystemValue('proxy'); $userpasswd = $this->config->getSystemValue('proxyuserpwd'); $result = ['host' => null, 'port' => null, 'user' => null, 'password' => null]; // we need to filter out the port -.- $url = new \Net_URL2($proxy); $port = $url->getPort(); $url->setPort(false); $host = $url->getUrl(); $result['host'] = $host; $result['port'] = $port; if ($userpasswd) { $auth = explode(':', $userpasswd, 2); $result['user'] = $auth[0]; $result['password'] = $auth[1]; } return $result; }
public function extract(\HTTP_Request2_Response $res) { $url = $res->getEffectiveUrl(); $base = new \Net_URL2($url); $sx = simplexml_load_string($res->getBody()); $linkInfos = array(); $alreadySeen = array(); foreach ($sx->entry as $entry) { $linkTitle = (string) $entry->title; foreach ($entry->link as $xlink) { $linkUrl = (string) $base->resolve((string) $xlink['href']); if (isset($alreadySeen[$linkUrl])) { continue; } if ($xlink['rel'] == 'alternate') { $linkInfos[] = new LinkInfo($linkUrl, $linkTitle, $url); } $alreadySeen[$linkUrl] = true; } } return $linkInfos; }
public function __construct($path = '', $defaults = array(), $rules = array()) { $this->path = '/' . trim(Net_URL2::removeDotSegments($path), '/'); $this->setDefaults($defaults); $this->setRules($rules); try { $this->parsePath(); } catch (Exception $e) { // The path could not be parsed correctly, treat it as fixed $this->fixed = true; $part = self::createPart(Net_URL_Mapper_Part::FIXED, $this->path, $this->path); $this->parts = array($part); } $this->getRequired(); }
/** * Constructor */ private function __construct() { //Load config $configDir = dirname(dirname(__FILE__)) . '/config'; Config::load(file_exists($configDir . '/config.php') ? require $configDir . '/config.php' : array(), require $configDir . '/defaults.php'); //Generate Current URL taking into account forwarded proto $url = \Net_URL2::getRequested(); $url->setQuery(false); $url->setPath(dirname($_SERVER['PHP_SELF'])); if (isset($_SERVER['HTTP_X_FORWARDED_PROTO'])) { $url->setScheme($_SERVER['HTTP_X_FORWARDED_PROTO']); } $this->url = $url; $this->path = $this->url->getPath(); // Initialize phpCAS proxy client $this->casClient = $this->initializeCAS(); }
/** * Sends the request and returns the response * * @throws HTTP_Request2_Exception * @return HTTP_Request2_Response */ public function send() { // Sanity check for URL if (!$this->url instanceof Net_URL2) { throw new HTTP_Request2_Exception('No URL given'); } elseif (!$this->url->isAbsolute()) { throw new HTTP_Request2_Exception('Absolute URL required'); } elseif (!in_array(strtolower($this->url->getScheme()), array('https', 'http'))) { throw new HTTP_Request2_Exception('Not a HTTP URL'); } if (empty($this->adapter)) { $this->setAdapter($this->getConfig('adapter')); } // magic_quotes_runtime may break file uploads and chunked response // processing; see bug #4543 if ($magicQuotes = ini_get('magic_quotes_runtime')) { ini_set('magic_quotes_runtime', false); } // force using single byte encoding if mbstring extension overloads // strlen() and substr(); see bug #1781, bug #10605 if (extension_loaded('mbstring') && 2 & ini_get('mbstring.func_overload')) { $oldEncoding = mb_internal_encoding(); mb_internal_encoding('iso-8859-1'); } try { $response = $this->adapter->sendRequest($this); } catch (Exception $e) { } // cleanup in either case (poor man's "finally" clause) if ($magicQuotes) { ini_set('magic_quotes_runtime', true); } if (!empty($oldEncoding)) { mb_internal_encoding($oldEncoding); } // rethrow the exception if (!empty($e)) { throw $e; } return $response; }
/** * Resolve a possibly relative URL against some absolute base URL * @param string $rel relative or absolute URL * @param string $base absolute URL * @return string absolute URL, or original URL if could not be resolved. */ function resolveURI($rel, $base) { require_once "Net/URL2.php"; try { $relUrl = new Net_URL2($rel); if ($relUrl->isAbsolute()) { return $rel; } $baseUrl = new Net_URL2($base); $absUrl = $baseUrl->resolve($relUrl); return $absUrl->getURL(); } catch (Exception $e) { common_log(LOG_WARNING, 'Unable to resolve relative link "' . $rel . '" against base "' . $base . '": ' . $e->getMessage()); return $rel; } }
/** * @param $path * @param null $document * @return array * @throws \Exception */ public static function getNormalizedFileInfo($path, $document = null) { if ($document && $document instanceof Model\Document == false) { throw new \Exception('$document has to be an instance of Document'); } $fileInfo = array(); $hostUrl = Tool::getHostUrl(); if ($path[0] != '/') { $fileInfo['fileUrl'] = $hostUrl . $document . "/{$path}"; //relative eg. ../file.css } else { $fileInfo['fileUrl'] = $hostUrl . $path; } $fileInfo['fileExtension'] = substr($path, strrpos($path, '.') + 1); $netUrl = new \Net_URL2($fileInfo['fileUrl']); $fileInfo['fileUrlNormalized'] = $netUrl->getNormalizedURL(); $fileInfo['filePathNormalized'] = PIMCORE_DOCUMENT_ROOT . str_replace($hostUrl, '', $fileInfo['fileUrlNormalized']); return $fileInfo; }
/** * Gets actual URL string. * * @return string. */ public function __toString() { return $this->_url->getURL(); }
/** * Handles HTTP redirection * * This method will throw an Exception if redirect to a non-HTTP(S) location * is attempted, also if number of redirects performed already is equal to * 'max_redirects' configuration parameter. * * @param HTTP_Request2 Original request * @param HTTP_Request2_Response Response containing redirect * @return HTTP_Request2_Response Response from a new location * @throws HTTP_Request2_Exception */ protected function handleRedirect(HTTP_Request2 $request, HTTP_Request2_Response $response) { if (is_null($this->redirectCountdown)) { $this->redirectCountdown = $request->getConfig('max_redirects'); } if (0 == $this->redirectCountdown) { $this->redirectCountdown = null; // Copying cURL behaviour throw new HTTP_Request2_MessageException('Maximum (' . $request->getConfig('max_redirects') . ') redirects followed', HTTP_Request2_Exception::TOO_MANY_REDIRECTS); } $redirectUrl = new Net_URL2($response->getHeader('location'), array(Net_URL2::OPTION_USE_BRACKETS => $request->getConfig('use_brackets'))); // refuse non-HTTP redirect if ($redirectUrl->isAbsolute() && !in_array($redirectUrl->getScheme(), array('http', 'https'))) { $this->redirectCountdown = null; throw new HTTP_Request2_MessageException('Refusing to redirect to a non-HTTP URL ' . $redirectUrl->__toString(), HTTP_Request2_Exception::NON_HTTP_REDIRECT); } // Theoretically URL should be absolute (see http://tools.ietf.org/html/rfc2616#section-14.30), // but in practice it is often not if (!$redirectUrl->isAbsolute()) { $redirectUrl = $request->getUrl()->resolve($redirectUrl); } $redirect = clone $request; $redirect->setUrl($redirectUrl); if (303 == $response->getStatus() || !$request->getConfig('strict_redirects') && in_array($response->getStatus(), array(301, 302))) { $redirect->setMethod(HTTP_Request2::METHOD_GET); $redirect->setBody(''); } if (0 < $this->redirectCountdown) { $this->redirectCountdown--; } return $this->sendRequest($redirect); }
return $http->send(); } $images = array(); for ($start = 0; $start < 200; $start += 20) { // echo $start . "\n"; $html = getContents($searchURL, $start)->getBody(); // $html = file_get_contents('images.html'); $dom = new DOMDocument(); @$dom->loadHTML($html); // grab all the on the page $xpath = new DOMXPath($dom); $hrefs = $xpath->evaluate('/html/body//div[@id="ImgCont"]//td//a'); for ($i = 0; $i < $hrefs->length; $i++) { $url = $hrefs->item($i)->getAttribute('href'); list(, $querystring) = explode('?', $url); $neturl = new Net_URL2("http://example.com/?{$querystring}"); $vars = $neturl->getQueryVariables(); if (isset($vars['imgurl'])) { $images[] = $vars['imgurl']; } } } foreach ($images as $count => $image) { preg_match_all('/([.][^.]+)$/', $image, $foo); if (!isset($foo[0][0])) { continue; } $ext = strtolower($foo[0][0]); $filename = "images/kittens/{$count}{$ext}"; echo $filename . "\n"; try {
public function MakePagination($query, $rpp_def = NULL, $location = "DB") { $return_set = array(); $this->{$location}->query($query); // This query should select all needed fields from database if ((int) $this->_S->Get('rpp') != 0) { if (isset($_POST['rpp'])) { if ((int) $_POST['rpp'] == 0) { $this->_S->Set('rpp', 50); } else { $this->_S->Set('rpp', (int) $_POST['rpp']); } } $rpp = (int) $this->_S->Get('rpp'); } else { $this->_S->Set('rpp', 50); $rpp = (int) $this->_S->Get('rpp'); } // http://pear.php.net/package/Net_URL2 $op = new Net_URL2($_SERVER["REQUEST_URI"]); $op->unsetQueryVariable('cpage'); $op->setQueryVariable('cpage', ''); $str = (string) $op; if (strpos($str, "search=1")) { $str = str_replace("search=1", "search=0", $str); } $OptionForm = new TForm(); $OptionForm->Action = $str . $this->CurrentPage; $OptionForm->Name = "paginationform"; $OptionForm->class_name = "pagination_form"; $TSelect = new TForm_TSelect('rpp'); $TSelect->class_name = 'select2'; $TSelect->style = 'width: 60px;'; $OptionForm->Add("SlRPP", $TSelect); $OptionForm->SlRPP->Label = "Rezultate pe pagina: "; $OptionForm->SlRPP->label_class = 'inline'; $OptionForm->SlRPP->AddOption('10', '10'); $OptionForm->SlRPP->AddOption('20', '20'); $OptionForm->SlRPP->AddOption('30', '30'); $OptionForm->SlRPP->AddOption('50', '50'); $OptionForm->SlRPP->AddOption('100', '100'); $OptionForm->SlRPP->Value = $rpp; $OptionForm->SlRPP->Paragraph = false; $OptionForm->SlRPP->onChange = 'this.form.submit();'; $total_pages = ceil($this->{$location}->numRows() / $rpp); if (!$this->CurrentPage || $this->CurrentPage <= 0 || $this->CurrentPage > $total_pages) { $this->CurrentPage = 1; } $return_set[1] = " LIMIT " . ($this->CurrentPage - 1) * $rpp . ", " . $rpp; $TSelect = new TForm_TSelect('pag'); $TSelect->class_name = 'select2'; $TSelect->style = 'width: 60px;'; $OptionForm->Add('SlPag', $TSelect); for ($i = 1; $i <= $total_pages; $i++) { $OptionForm->SlPag->AddOption($str . $i, $i); } $OptionForm->SlPag->Label = "Afiseaza pagina: "; $OptionForm->SlPag->label_class = 'inline'; $OptionForm->SlPag->Paragraph = false; $OptionForm->SlPag->Value = $str . $this->CurrentPage; $OptionForm->SlPag->onChange = 'pagination_check_link(this.options[this.selectedIndex].value);'; $return_set[2] = "<div class=\"result_pages\">" . $OptionForm->Html() . ""; $ppages = ''; $j = 0; $nextpage = $pervpage = ''; if ($this->CurrentPage != 1) { $pervpage = '<li><a href="' . $str . '1"> <i class="icon-double-angle-left"></i></a></li><li><a href="' . $str . ($this->CurrentPage - 1) . '"> <i class="icon-angle-left"></i></a></li>'; } else { $pervpage = '<li class="disabled"><a href="' . $str . '1"> <i class="icon-double-angle-left"></i></a></li><li class="disabled"><a href="' . $str . ($this->CurrentPage - 1) . '"> <i class="icon-angle-left"></i></a></li>'; } if ($this->CurrentPage != $total_pages) { $nextpage = '<li><a href="' . $str . ($this->CurrentPage + 1) . '"><i class="icon-angle-right"></i> </a></li><li><a href="' . $str . $total_pages . '"><i class="icon-double-angle-right"></i> </a></li>'; } else { $nextpage = '<li class="disabled"><a href="' . $str . ($this->CurrentPage + 1) . '"><i class="icon-angle-right"></i> </a></li><li class="disabled"><a href="' . $str . $total_pages . '"><i class="icon-double-angle-right"></i> </a></li>'; } for ($i = 0; $i <= $j + 10; $i++) { if ($this->CurrentPage - 5 + $i > 0 && $this->CurrentPage - 5 + $i <= $total_pages) { if ($this->CurrentPage == $this->CurrentPage - 5 + $i) { $ppages .= '<li class="active"><a>' . ($this->CurrentPage - 5 + $i) . '</a></li>'; } else { $ppages .= '<li><a href="' . $str . ($this->CurrentPage - 5 + $i) . '">' . ($this->CurrentPage - 5 + $i) . '</a></li>'; } } else { if ($this->CurrentPage - 5 + $i <= $total_pages) { $j++; } } } $return_set[2] .= '<ul class="pagination">'; if ($total_pages > 1) { $return_set[2] .= $pervpage . $ppages . $nextpage; } else { $return_set[2] .= '<li class="active"><a>' . $this->CurrentPage . '</a></li>'; } $return_set[2] .= '</ul>'; $return_set[2] .= '</div>'; return $return_set; }
public static function resolveUrl($relative_url, $base_url) { $base_url = new Net_URL2($base_url); return $base_url->resolve($relative_url)->getURL(); }
/** * Checks whether the requested URI is the authentication URI or not. * * @param string $authenticationURI * @return boolean */ private function _isAuthenticationURI($authenticationURI) { $url = new Net_URL2($authenticationURI); return $this->context->removeProxyPath($url->getPath()) == $this->_scriptName; }
/** * GET Request * * @param $url * @param $datas * @return string */ public function get_request($url, $datas = array()) { $body = ''; try { $url2 = new Net_URL2($url); foreach ($datas as $key => $val) { $url2->setQueryVariable($key, mb_convert_encoding($val, $this->response_encoding, 'UTF-8'), true); } $this->http->setURL($url2); $this->http->setMethod(HTTP_Request2::METHOD_GET); if (!empty($this->cookies)) { foreach ($this->cookies as $cookie) { $this->http->addCookie($cookie['name'], $cookie['value']); } } $response = $this->http->send(); if (count($response->getCookies())) { $this->cookies = $response->getCookies(); } $body = mb_convert_encoding($response->getBody(), 'UTF-8', $this->response_encoding); } catch (Exception $e) { debug($e->getMessage()); } return $body; }
/** * Adds a nonce to the openid.return_to URL parameter. Only used in OpenID 1.1 * * @return void */ protected function addNonce() { $nonce = $this->getNonce()->createNonceAndStore(); $returnToURL = new Net_URL2($this->message->get('openid.return_to')); $returnToURL->setQueryVariable(OpenID_Nonce::RETURN_TO_NONCE, urlencode($nonce)); $this->message->set('openid.return_to', $returnToURL->getURL()); // Observing $logMessage = "Nonce: {$nonce}\n"; $logMessage = 'New ReturnTo: ' . $returnToURL->getURL() . "\n"; $logMessage .= 'OP URIs: ' . print_r($this->serviceEndpoint->getURIs(), true); OpenID::setLastEvent(__METHOD__, $logMessage); }
/** * Returns an absolute URL using Net_URL * * @param string $url All/part of a url * @return string Full url */ function getURL($url) { include_once 'Net/URL2.php'; $obj = new Net_URL2($url); return $obj->getURL(); }
/** * Detect service from a short URL * * Takes a URL and inpects it to see if there is a service driver that can * be used to expand it. * * @param string $url The short URL to inspect * * @return object Instance of {@link Services_ShortURL_Interface} */ public static function detect($url) { $url = new Net_URL2($url); $host = $url->getHost(); if (!isset(self::$services[$host])) { throw new Services_ShortURL_Exception_UnknownService(); } return self::factory(self::$services[$host]); }
/** * Required to request the root i-name (XRI) XRD which will provide an * error message that the i-name does not exist, or else return a valid * XRD document containing the i-name's Canonical ID. * * @param string $url URI * @param string $serviceType Optional service type * * @return HTTP_Request * @todo Finish this a bit better using the QXRI rules. */ protected function get($url, $serviceType = null) { $request = new HTTP_Request2($url, HTTP_Request2::METHOD_GET, $this->getHttpRequestOptions()); $netURL = new Net_URL2($url); $request->setHeader('Accept', 'application/xrds+xml'); if ($serviceType) { $netURL->setQueryVariable('_xrd_r', 'application/xrds+xml'); $netURL->setQueryVariable('_xrd_t', $serviceType); } else { $netURL->setQueryVariable('_xrd_r', 'application/xrds+xml;sep=false'); } $request->setURL($netURL->getURL()); try { return $request->send(); } catch (HTTP_Request2_Exception $e) { throw new Services_Yadis_Exception('Invalid response to Yadis protocol received: ' . $e->getMessage(), $e->getCode()); } }
/** * Returns all cookies matching a given request URL * * The following checks are made: * - cookie domain should match request host * - cookie path should be a prefix for request path * - 'secure' cookies will only be sent for HTTPS requests * * @param Net_URL2 $url Request url * @param bool $asString Whether to return cookies as string for "Cookie: " header * * @return array|string Matching cookies */ public function getMatching(Net_URL2 $url, $asString = false) { $host = $url->getHost(); $path = $url->getPath(); $secure = 0 == strcasecmp($url->getScheme(), 'https'); $matched = $ret = array(); foreach (array_keys($this->cookies) as $domain) { if ($this->domainMatch($host, $domain)) { foreach (array_keys($this->cookies[$domain]) as $cPath) { if (0 === strpos($path, $cPath)) { foreach ($this->cookies[$domain][$cPath] as $name => $cookie) { if (!$cookie['secure'] || $secure) { $matched[$name][strlen($cookie['path'])] = $cookie; } } } } } } foreach ($matched as $cookies) { krsort($cookies); $ret = array_merge($ret, $cookies); } if (!$asString) { return $ret; } else { $str = ''; foreach ($ret as $c) { $str .= (empty($str) ? '' : '; ') . $c['name'] . '=' . $c['value']; } return $str; } }
// | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | // | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | // | | // +-----------------------------------------------------------------------+ // | Author: Richard Heyes <richard at php net> | // +-----------------------------------------------------------------------+ // $Id: example.php 235190 2007-05-08 00:04:54Z davidc $ /** * This example will decode the url given and display its * constituent parts. */ error_reporting(E_ALL | E_STRICT); //include('../URL2.php'); include 'Net/URL2.php'; //$url = &new Net_URL2('https://www.example.com/foo/bar/index.php?foo=bar'); $url = new Net_URL2('https://example.com/pls/portal30/PORTAL30.wwpob_page.changetabs?p_back_url=http%3A%2F%2Fexample.com%2Fservlet%2Fpage%3F_pageid%3D360%2C366%2C368%2C382%26_dad%3Dportal30%26_schema%3DPORTAL30&foo=bar'); ?> <html> <body> <pre> Protocol...: <?php echo $url->protocol; ?> Username...: <?php echo $url->user; ?> Password...: <?php echo $url->pass;
/** * Method which builds a URL by taking a relative URL and its corresponding * absolute URL * @param string $relativeUrl the relative URL * @param string $absoluteUrl the absolute URL with at least scheme and host * @return string the resulting absolute URL */ protected function relativeToAbsoluteUrl($relativeUrl, $absoluteUrl) { $base = new \Net_URL2($absoluteUrl); return $base->resolve($relativeUrl); }
/** * Callback function called by cURL for saving the response headers * * @param resource cURL handle * @param string response header (with trailing CRLF) * @return integer number of bytes saved * @see HTTP_Request2_Response::parseHeaderLine() */ protected function callbackWriteHeader($ch, $string) { // we may receive a second set of headers if doing e.g. digest auth if ($this->eventReceivedHeaders || !$this->eventSentHeaders) { // don't bother with 100-Continue responses (bug #15785) if (!$this->eventSentHeaders || $this->response->getStatus() >= 200) { $this->request->setLastEvent('sentHeaders', curl_getinfo($ch, CURLINFO_HEADER_OUT)); } $upload = curl_getinfo($ch, CURLINFO_SIZE_UPLOAD); // if body wasn't read by a callback, send event with total body size if ($upload > $this->position) { $this->request->setLastEvent('sentBodyPart', $upload - $this->position); $this->position = $upload; } if ($upload && (!$this->eventSentHeaders || $this->response->getStatus() >= 200)) { $this->request->setLastEvent('sentBody', $upload); } $this->eventSentHeaders = true; // we'll need a new response object if ($this->eventReceivedHeaders) { $this->eventReceivedHeaders = false; $this->response = null; } } if (empty($this->response)) { $this->response = new HTTP_Request2_Response($string, false); } else { $this->response->parseHeaderLine($string); if ('' == trim($string)) { // don't bother with 100-Continue responses (bug #15785) if (200 <= $this->response->getStatus()) { $this->request->setLastEvent('receivedHeaders', $this->response); } if ($this->request->getConfig('follow_redirects') && $this->response->isRedirect()) { $redirectUrl = new Net_URL2($this->response->getHeader('location')); // for versions lower than 5.2.10, check the redirection URL protocol if (!defined('CURLOPT_REDIR_PROTOCOLS') && $redirectUrl->isAbsolute() && !in_array($redirectUrl->getScheme(), array('http', 'https'))) { return -1; } if ($jar = $this->request->getCookieJar()) { $jar->addCookiesFromResponse($this->response, $this->request->getUrl()); if (!$redirectUrl->isAbsolute()) { $redirectUrl = $this->request->getUrl()->resolve($redirectUrl); } if ($cookies = $jar->getMatching($redirectUrl, true)) { curl_setopt($ch, CURLOPT_COOKIE, $cookies); } } } $this->eventReceivedHeaders = true; } } return strlen($string); }
/** * Guess if I can find the most significant image in a page. */ function find_image_in_gallery_page($url, &$title = "") { $page_source = file_get_contents($url); $base_url = new Net_URL2($url); $doc = new DOMDocument(); @$doc->loadHTML($page_source); $tags = $doc->getElementsByTagName('title'); foreach ($tags as $tag) { $title = trim($tag->textContent); } $imgs = $doc->getElementsByTagName('img'); $favorite_image = NULL; $contents = array(); foreach ($imgs as $img) { // A bunch of heuristics here. $parentNode = $img->parentNode; $parentNodeName = $parentNode->nodeName; $img_url = $img->getAttribute('src'); $img_url_parts = parse_url($img_url); $img_class = $img->getAttribute('class'); // http://g.e-hentai.org/ if ($img->getAttribute('id') == 'img') { $favorite_image = $img; } elseif ($img->getAttribute('id') == 'image') { $favorite_image = $img; } elseif ($img->getAttribute('id') == 'cursor_lupa') { $favorite_image = $img; } elseif ($img_class == 'pic' && preg_match('/imagetwist.com/', $img_url_parts['host'])) { $favorite_image = $img; } elseif (intval($img->getAttribute('height')) >= 350 && intval($img->getAttribute('width')) >= 350) { $favorite_image = $img; } elseif ($parentNodeName == 'a' && $parentNode->getAttribute('href') == $img->getAttribute('src')) { $favorite_image = $img; } // Other patterns for scraping? } if ($favorite_image) { return $base_url->resolve($favorite_image->getAttribute('src')); } }
/** * Sends the request and returns the response * * @throws HTTP_Request2_Exception * @return HTTP_Request2_Response */ public function send() { // Sanity check for URL if (!$this->url instanceof Net_URL2 || !$this->url->isAbsolute() || !in_array(strtolower($this->url->getScheme()), array('https', 'http'))) { throw new HTTP_Request2_LogicException('HTTP_Request2 needs an absolute HTTP(S) request URL, ' . ($this->url instanceof Net_URL2 ? "'" . $this->url->__toString() . "'" : 'none') . ' given', HTTP_Request2_Exception::INVALID_ARGUMENT); } if (empty($this->adapter)) { $this->setAdapter($this->getConfig('adapter')); } // magic_quotes_runtime may break file uploads and chunked response // processing; see bug #4543. Don't use ini_get() here; see bug #16440. if ($magicQuotes = get_magic_quotes_runtime()) { set_magic_quotes_runtime(false); } // force using single byte encoding if mbstring extension overloads // strlen() and substr(); see bug #1781, bug #10605 if (extension_loaded('mbstring') && 2 & ini_get('mbstring.func_overload')) { $oldEncoding = mb_internal_encoding(); mb_internal_encoding('8bit'); } try { $response = $this->adapter->sendRequest($this); } catch (Exception $e) { } // cleanup in either case (poor man's "finally" clause) if ($magicQuotes) { set_magic_quotes_runtime(true); } if (!empty($oldEncoding)) { mb_internal_encoding($oldEncoding); } // rethrow the exception if (!empty($e)) { throw $e; } return $response; }
/** * Given a user's WikiHow profile URL, find their avatar. * * @param string $profileUrl user page on the wiki * * @return array of data; possible members: * 'avatar' => full URL to avatar image * * @throws Exception on various low-level failures * * @todo pull location, web site, and about sections -- they aren't currently marked up cleanly. */ private function fetchProfile($profileUrl) { $client = HTTPClient::start(); $response = $client->get($profileUrl); if (!$response->isOk()) { throw new Exception("WikiHow profile page fetch failed."); // HTTP error response already logged. return false; } // Suppress warnings during HTML parsing; non-well-formed bits will // spew horrible warning everywhere even though it works fine. $old = error_reporting(); error_reporting($old & ~E_WARNING); $dom = new DOMDocument(); $ok = $dom->loadHTML($response->getBody()); error_reporting($old); if (!$ok) { throw new Exception("HTML parse failure during check for WikiHow avatar."); return false; } $data = array(); $avatar = $dom->getElementById('avatarULimg'); if ($avatar) { $src = $avatar->getAttribute('src'); $base = new Net_URL2($profileUrl); $absolute = $base->resolve($src); $avatarUrl = strval($absolute); common_log(LOG_DEBUG, "WikiHow avatar found for {$profileUrl} - {$avatarUrl}"); $data['avatar'] = $avatarUrl; } return $data; }
/** * Creates an assertion object and tries to verify its validity. * * @return array of the OpenID_Assertion_Result and OpenID_Message objects */ public function getVerifyResultsAndMessage() { $rp = $this->getORPInstance(); $url = 'http'; if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') { $url .= 's'; } $url .= '://' . $_SERVER['SERVER_NAME']; if ($_SERVER['SERVER_PORT'] != '80') { $url .= ':' . $_SERVER['SERVER_PORT']; } $url .= $_SERVER['PHP_SELF']; // Get the message contents if ($_SERVER['REQUEST_METHOD'] == 'POST') { // Can't use $_POST, it f***s with the keys (. -> _) $queryString = $this->getPHPInput(); } else { if ($_SERVER['REQUEST_METHOD'] == 'GET') { $netURL = new Net_URL2($url . '?' . $_SERVER['QUERY_STRING']); $queryString = $netURL->getQuery(); if ($queryString === false) { throw new OpenID_Exception('Invalid request'); } } else { throw new OpenID_Exception('Unknown HTTP method'); } } $requestedURL = $url . '?' . $queryString; $message = new OpenID_Message($queryString, OpenID_Message::FORMAT_HTTP); $result = $rp->verify(new Net_URL2($requestedURL), $message); return array('result' => $result, 'message' => $message); }
// | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY | // | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT | // | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | // | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | // | | // +-----------------------------------------------------------------------+ // | Author: Richard Heyes <richard at php net> | // +-----------------------------------------------------------------------+ // $Id$ /** * This example will decode the url given and display its * constituent parts. */ error_reporting(E_ALL | E_STRICT); include 'Net/URL2.php'; $url = new Net_URL2('https://example.com/pls/portal30/PORTAL30.wwpob_page.changetabs?p_back_url=http%3A%2F%2Fexample.com%2Fservlet%2Fpage%3F_pageid%3D360%2C366%2C368%2C382%26_dad%3Dportal30%26_schema%3DPORTAL30&foo=bar'); ?> <html> <body> <pre> Protocol...: <?php echo $url->protocol; ?> Username...: <?php echo $url->user; ?> Password...: <?php echo $url->pass;