/** * @param $uri * * @return SimpleXMLElement * @throws Exception */ public static function makeAPICall($uri) { require_once 'HTTP/Request.php'; $params = array('method' => HTTP_REQUEST_METHOD_GET, 'allowRedirects' => FALSE); $request = new HTTP_Request(self::$_apiURL . $uri, $params); $result = $request->sendRequest(); if (PEAR::isError($result)) { CRM_Core_Error::fatal($result->getMessage()); } if ($request->getResponseCode() != 200) { CRM_Core_Error::fatal(ts('Invalid response code received from Sunlight servers: %1', array(1 => $request->getResponseCode()))); } $string = $request->getResponseBody(); return simplexml_load_string($string); }
/** * 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->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; }
/** * 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; }
/** * 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'; }
/** * serendipity_plugin_zooomr::getURL() * downloads the content from an URL and returns it as a string * * @author Stefan Lange-Hegermann * @since 02.08.2006 * @param string $url URL to get * @return string downloaded Data from "$url" */ function get_url($url) { require_once S9Y_PEAR_PATH . 'HTTP/Request.php'; $req = new HTTP_Request($url); if (PEAR::isError($req->sendRequest()) || $req->getResponseCode() != '200') { $store = file_get_contents($url); } else { $store = $req->getResponseBody(); } return $store; }
function sendRequest($return_body = true) { $this->Response = $this->HttpRequest->sendRequest(); $this->code = $this->HttpRequest->getResponseCode(); if (PEAR::isError($this->Response)) { $this->error = $this->Response->getMessage(); return false; } else { return $return_body ? $this->HttpRequest->getResponseBody() : true; } }
/** * */ 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; }
/** * 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; }
/** * @param $values * * @return bool */ public static function checkAddress(&$values) { if (self::$_disabled) { return FALSE; } if (!isset($values['street_address']) || !isset($values['city']) && !isset($values['state_province']) && !isset($values['postal_code'])) { return FALSE; } $userID = Civi::settings()->get('address_standardization_userid'); $url = Civi::settings()->get('address_standardization_url'); if (empty($userID) || empty($url)) { return FALSE; } $address2 = str_replace(',', '', $values['street_address']); $XMLQuery = '<AddressValidateRequest USERID="' . $userID . '"><Address ID="0"><Address1>' . CRM_Utils_Array::value('supplemental_address_1', $values, '') . '</Address1><Address2>' . $address2 . '</Address2><City>' . $values['city'] . '</City><State>' . $values['state_province'] . '</State><Zip5>' . $values['postal_code'] . '</Zip5><Zip4>' . CRM_Utils_Array::value('postal_code_suffix', $values, '') . '</Zip4></Address></AddressValidateRequest>'; require_once 'HTTP/Request.php'; $request = new HTTP_Request(); $request->setURL($url); $request->addQueryString('API', 'Verify'); $request->addQueryString('XML', $XMLQuery); $response = $request->sendRequest(); $session = CRM_Core_Session::singleton(); $code = $request->getResponseCode(); if ($code != 200) { $session->setStatus(ts('USPS Address Lookup Failed with HTTP status code: %1', array(1 => $code))); return FALSE; } $responseBody = $request->getResponseBody(); $xml = simplexml_load_string($responseBody); if (is_null($xml) || is_null($xml->Address)) { $session->setStatus(ts('Your USPS API Lookup has Failed.')); return FALSE; } if ($xml->Number == '80040b1a') { $session->setStatus(ts('Your USPS API Authorization has Failed.')); return FALSE; } if (array_key_exists('Error', $xml->Address)) { $session->setStatus(ts('Address not found in USPS database.')); return FALSE; } $values['street_address'] = (string) $xml->Address->Address2; $values['city'] = (string) $xml->Address->City; $values['state_province'] = (string) $xml->Address->State; $values['postal_code'] = (string) $xml->Address->Zip5; $values['postal_code_suffix'] = (string) $xml->Address->Zip4; if (array_key_exists('Address1', $xml->Address)) { $values['supplemental_address_1'] = (string) $xml->Address->Address1; } return TRUE; }
/** * 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(); } }
/** * @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()); }
/** * 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; } }
function getXMLArray($file, $forced_encoding = null) { require_once (defined('S9Y_PEAR_PATH') ? S9Y_PEAR_PATH : S9Y_INCLUDE_PATH . 'bundled-libs/') . 'HTTP/Request.php'; $req = new HTTP_Request($file); if (PEAR::isError($req->sendRequest()) || $req->getResponseCode() != '200') { if (ini_get("allow_url_fopen")) { $data = file_get_contents($file); } else { $data = ""; } } else { $data = $req->getResponseBody(); } if (trim($data) == '') { return false; } return $this->parseXML($data, $forced_encoding); }
/** * preprocess Index action. * * @access public * @return string Forward name (null if no errors.) */ function prepare() { if ($this->af->validate() == 0) { $url = sprintf('%s/repository.sphp', rtrim($this->af->get('repository_url'), '/')); require_once 'HTTP/Request.php'; $req = new HTTP_Request($url); $req->sendRequest(); if ($req->getResponseCode() == '200') { $data = $req->getResponseBody(); $ret = @unserialize($data); if (is_array($ret)) { $this->af->setApp('repository_data', $ret); $cache_file = $this->backend->ctl->repositoryURL2CacheFile($url); file_put_contents($cache_file, $data); chmod($cache_file, 0666); return null; } } } $this->ae->add('repository_url', _('The repository is not available!')); return 'json_error'; }
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; }
/** * Retrieve Free/Busy data for the specified resource. * * @param string $resource Fetch the Free/Busy data for this resource. * * @return Horde_Icalendar_Vfreebusy The Free/Busy data. */ public function get($resource) { global $conf; $url = self::getUrl($resource); Horde::log(sprintf('Freebusy URL for resource %s is %s', $resource, $url), 'DEBUG'); list($user, $domain) = explode('@', $resource); if (empty($domain)) { $domain = $conf['kolab']['filter']['email_domain']; } /** * This section matches Kronolith_Freebusy and should be merged with it * again in a single Horde_Freebusy module. */ $options = array('method' => 'GET', 'timeout' => 5, 'allowRedirects' => true); if (!empty($conf['http']['proxy']['proxy_host'])) { $options = array_merge($options, $conf['http']['proxy']); } $http = new HTTP_Request($url, $options); $http->setBasicAuth($conf['kolab']['filter']['calendar_id'] . '@' . $domain, $conf['kolab']['filter']['calendar_pass']); @$http->sendRequest(); if ($http->getResponseCode() != 200) { throw new Horde_Kolab_Resource_Exception(sprintf('Unable to retrieve free/busy information for %s', $resource), Horde_Kolab_Resource_Exception::NO_FREEBUSY); } $vfb_text = $http->getResponseBody(); // Detect the charset of the iCalendar data. $contentType = $http->getResponseHeader('Content-Type'); if ($contentType && strpos($contentType, ';') !== false) { list(, $charset, ) = explode(';', $contentType); $vfb_text = Horde_String::convertCharset($vfb_text, trim(str_replace('charset=', '', $charset)), 'UTF-8'); } $iCal = new Horde_Icalendar(); $iCal->parsevCalendar($vfb_text, 'VCALENDAR'); $vfb =& $iCal->findComponent('VFREEBUSY'); if ($vfb === false) { throw new Horde_Kolab_Resource_Exception(sprintf('Invalid or no free/busy information available for %s', $resource), Horde_Kolab_Resource_Exception::NO_FREEBUSY); } $vfb->simplify(); return $vfb; }
function get_gg_status($numer_gg, $haslo_gg, $szukany_numer, &$error, &$gg_status_widocznosc) { define("GG_WELCOME", 0x1); define("GG_LOGIN", 0xc); define("GG_LOGIN60", 0x15); define("GG_LOGIN_OK", 0x3); define("GG_LOGIN_FAILED", 0x9); define("GG_NEW_STATUS", 0x2); define("GG_STATUS", 0x2); define("GG_STATUS_NOT_AVAIL", 0x1); define("GG_STATUS_NOT_AVAIL_DESCR", 0x15); define("GG_STATUS_AVAIL", 0x2); define("GG_STATUS_AVAIL_DESCR", 0x4); define("GG_STATUS_BUSY", 0x3); define("GG_STATUS_BUSY_DESCR", 0x5); define("GG_STATUS_INVISIBLE", 0x14); define("GG_NOTIFY", 0x10); define("GG_NOTIFY_REPLY", 0xc); define("GG_NOTIFY_REPLY60", 0x11); define("GG_USER_NORMAL", 0x3); define("GG_USER_BLOCKED", 0x4); define("GG_SEND_MSG", 0xb); define("GG_CLASS_MSG", 0x4); define("GG_CLASS_CHAT", 0x8); define("GG_CLASS_ACK", 0x20); define("GG_SEND_MSG_ACK", 0x5); define("GG_ACK_DELIVERED", 0x2); define("GG_ACK_QUEUED", 0x3); define("GG_RECV_MSG", 0xa); define("GG_LOGIN_FAILED2", 0xb); define("GG_ACK_MBOXFULL", 0x4); define("DISCONNECTED", 0x100); define("GG_PUBDIR50_REQUEST", 0x14); define("GG_PUBDIR50_REPLY", 0xe); define("GG_PUBDIR50_SEARCH", 0x3); // // Getting a logon server // require_once S9Y_PEAR_PATH . 'HTTP/Request.php'; serendipity_request_start(); $req = new HTTP_Request('http://appmsg.gadu-gadu.pl:80/appsvc/appmsg.asp?fmnumber=<' . $numer_gg . '>'); if (PEAR::isError($req->sendRequest()) || $req->getResponseCode() != '200') { $error = PLUGIN_GGOPIS_MSG_NOCONNTOAPPMSG . $errno . " - " . $errstr . "\n"; serendipity_request_end(); return false; } else { $buf = $req->getResponseBody(); preg_match("/\\s([\\d\\.]{8,16})\\:([\\d]{1,5})\\s/", $buf, $adres); $host = $adres[1]; $port = $adres[2]; serendipity_request_end(); } // // Connecting to a server // require_once S9Y_PEAR_PATH . 'Net/Socket.php'; $conn = new Net_Socket(); if (!$conn->connect($host, $port, null, 10)) { $error = PLUGIN_GGOPIS_MSG_CONNERROR . ": {$errno} - {$errstr}\n\n"; return false; } // // Getting data from a server - // receiving a key needed to calculate // a hash from your password // if (!($data = $conn->read(12))) { $error = PLUGIN_GGOPIS_MSG_CONNUNEXPCLOSED . "\n\n"; $conn->disconnect(); return false; } $tab = unpack("Vtyp/Vrozmiar/Vklucz", $data); // Calculating a password hash $hash = $this->calculate_hash($haslo_gg, $tab['klucz']); $data = pack("VVVVVVvVvVvCCa" . strlen(""), GG_LOGIN60, 0x20 + strlen(""), $numer_gg, $hash, GG_STATUS_AVAIL, 0x20, 0, 0, 0, 0, 0, 0x14, 0xbe, ""); // Sending a password hash - logging to a GG server $conn->write($data); if (!($data1 = $conn->read(8))) { $error = PLUGIN_GGOPIS_MSG_UNKNOWNERROR . "\n"; $conn->disconnect(); return false; } // Checking a login status $tab = unpack("Vlogin_status/Vrozmiar", $data1); if ($tab['login_status'] != GG_LOGIN_OK) { $error = PLUGIN_GGOPIS_MSG_INCORRPASSWD . "\n\n"; $conn->disconnect(); return false; } // Sending a contact list with one contact $data = pack("VVVC", GG_NOTIFY, 5, $szukany_numer, GG_USER_NORMAL); if (!$conn->write($data)) { $error = PLUGIN_GGOPIS_MSG_SENDCONTACTSERROR . "\n\n"; $conn->disconnect(); return false; } // Receiving a packet with the next packet specification $gg_opis = ''; $data = $conn->read(8); if (strlen($data) > 0) { $tab = unpack("Vtyp/Vrozmiar", $data); // Pobranie pakietu opisu // DEBUG: echo $tab['rozmiar']; $data = $conn->read($tab['rozmiar']); if ($tab['rozmiar'] > 14) { $tablica = unpack("Iuin/Cstatus/Iremoteip/Sremoteport/Cversion/Cimagesize/Cunknown/Cdescription_size/a*description", $data); // Getting a status description, and converting it from CP1250 (that's how it's encoded) to UTF8 $gg_opis = $this->cp1250_to_utf8($tablica['description']); // Getting a status itself $gg_status_flaga = $tablica['status']; } else { $tablica = unpack("Iuin/Cstatus", $data); // Getting a status $gg_status_flaga = $tablica['status']; } if (empty($gg_opis)) { $gg_opis = PLUGIN_GGOPIS_MSG_NOSTATUSDESC; } // Choosing a status icon to display switch ($gg_status_flaga) { case GG_STATUS_NOT_AVAIL: case GG_STATUS_NOT_AVAIL_DESCR: $gg_status_widocznosc = 'gg11'; break; case GG_STATUS_AVAIL: case GG_STATUS_AVAIL_DESCR: $gg_status_widocznosc = 'gg12'; break; case GG_STATUS_BUSY: case GG_STATUS_BUSY_DESCR: $gg_status_widocznosc = 'gg13'; break; default: $gg_status_widocznosc = 'gg11'; } } else { $gg_opis = PLUGIN_GGOPIS_MSG_NOSTATUSDESC; } // Closing a connection to the server $conn->disconnect(); return $gg_opis; }
function phoneblogz_upload_fromurl($name, $type, $url) { global $serendipity; if (empty($name)) { return array('error' => "Empty filename"); } $upload = array('path' => $serendipity['uploadPath'], 'url' => $serendipity['uploadHTTPPath'], 'error' => false); if (!is_writable($upload['path'])) { $upload['error'] = "Don't have write permission to " . $upload['path']; return $upload; } $number = ''; $filename = $name; while (file_exists($upload['path'] . "/{$filename}")) { $filename = str_replace("{$number}.{$ext}", ++$number . ".{$ext}", $filename); } $new_file = $upload['path'] . "/{$filename}"; $ifp = @fopen($new_file, 'wb'); if (!$ifp) { return array('error' => "Could not write file {$new_file}."); } require_once S9Y_PEAR_PATH . 'HTTP/Request.php'; $req = new HTTP_Request($url); if (PEAR::isError($req->sendRequest()) || $req->getResponseCode() != '200') { return array('error' => "Could not download file " . htmlspecialchars($url)); } $fc = $req->getResponseBody(); $success = @fwrite($ifp, $fc); fclose($ifp); // Set correct file permissions $stat = @stat(dirname($new_file)); $perms = $stat['mode'] & 0777; @chmod($new_file, $perms); // Compute the URL $url = $upload['url'] . "/{$filename}"; return array('file' => $new_file, 'url' => $url); }
function saveAndResponseMyBlogAvatar($eventData, $url) { global $serendipity; $request_pars['allowRedirects'] = false; $this->log("saveAndResponseMyBlogAvatar: " . $url); // First a dummy icon is fetched. This is done by fetching a MyBlog Avatar for a not existing domain. // If we have done this before, the dummy_md5 is already set, so we can skip this fetching here. if (!isset($this->mybloglog_dummy_md5)) { $cachefilename = '_mybloglogdummy.md5'; $cache_file = $this->getCacheDirectory() . '/' . $cachefilename; // Look up the cache for the md5 of the MyBlogLog dummy icon saved earlier: if (file_exists($cache_file) && time() - filemtime($cache_file) < $this->cache_seconds) { $fp = fopen($cache_file, 'rb'); $this->mybloglog_dummy_md5 = fread($fp, filesize($cache_file)); fclose($fp); $this->log("Loaded dummy MD5: " . $this->mybloglog_dummy_md5); } else { // dummy MD5 file was not cached or was too old. We have to fetch the dummy icon now $dummyurl = 'http://pub.mybloglog.com/coiserv.php?href=http://grunz.grunz.grunz&n=*'; $this->log("trying dummyUrl: " . $dummyurl); if (function_exists('serendipity_request_start')) { serendipity_request_start(); } $reqdummy = new HTTP_Request($dummyurl, $request_pars); if (PEAR::isError($reqdummy->sendRequest()) || $reqdummy->getResponseCode() != '200') { if (function_exists('serendipity_request_start')) { serendipity_request_end(); } $this->avatarConfiguration["mybloglog_dummy_error!"] = $reqdummy->getResponseCode(); // unable to fetch a dummy picture! $this->log("unable to fetch a dummy picture!" . $dummyurl); return false; // what can we say else.. } else { // Allow only images as Avatar! $mime = $reqdummy->getResponseHeader("content-type"); $this->log("MyBlogLog Avatar fetch mimetype: {$mime}"); $mimeparts = explode('/', $mime); if (count($mimeparts) != 2 || $mimeparts[0] != 'image') { // unable to fetch a dummy picture! $this->log("unable to fetch a dummy picture!" . $dummyurl); if (function_exists('serendipity_request_start')) { serendipity_request_end(); } return false; // what can we say else.. } $fContent = $reqdummy->getResponseBody(); $this->mybloglog_dummy_md5 = md5($fContent); // Save MD5 of dummy icon for later runs $fp = fopen($cache_file, 'wb'); fwrite($fp, $this->mybloglog_dummy_md5); fclose($fp); $this->log("dummy MD5 saved: " . $this->mybloglog_dummy_md5); } if (function_exists('serendipity_request_start')) { serendipity_request_end(); } } } // Fetch the correct icon and compare: if (isset($this->mybloglog_dummy_md5)) { $cachefilename = $this->getCacheFilePath($eventData); // fetch the icon if (function_exists('serendipity_request_start')) { serendipity_request_start(); } $this->log("Fetching mbl: " . $url); $req = new HTTP_Request($url, $request_pars); if (PEAR::isError($req->sendRequest()) || $req->getResponseCode() != '200') { if (function_exists('serendipity_request_start')) { serendipity_request_end(); } $this->log("Unable to fetch the correct image!"); // Unable to fetch the correct image! return false; } else { // Test, if this realy is an image! $mime_type = $req->getResponseHeader('content-type'); if (!empty($mime_type)) { $mt_parts = explode('/', $mime_type); } if (isset($mt_parts) && is_array($mt_parts) && $mt_parts[0] == 'image') { $fContent = $req->getResponseBody(); $avtmd5 = md5($fContent); $this->log("mbl image fetched, MD5: " . $avtmd5); if ($this->mybloglog_dummy_md5 != $avtmd5) { $this->log("caching mbl image: " . $cachefilename); $this->cacheAvatar($eventData, $fContent, $req); } } else { $this->log("MyBlogLog did not return an image: " . $mime_type); $avtmd5 = $this->mybloglog_dummy_md5; // Declare it as dummy in order not to save it. } } if (function_exists('serendipity_request_start')) { serendipity_request_end(); } if ($this->mybloglog_dummy_md5 == $avtmd5) { // This seems to be a dummy avatar! return false; } else { $this->show($cachefilename); return true; } } return false; }
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; }
function event_hook($event, &$bag, &$eventData, $addData = null) { global $serendipity; $debug = true; $hooks =& $bag->get('event_hooks'); if (isset($hooks[$event])) { $captchas_ttl = $this->get_config('captchas_ttl', 7); $_captchas = $this->get_config('captchas', 'yes'); $captchas = $_captchas !== 'no' && ($_captchas === 'yes' || $_captchas === 'scramble' || serendipity_db_bool($_captchas)); // Check if the entry is older than the allowed amount of time. Enforce kaptchas if that is true // of if kaptchas are activated for every entry $show_captcha = $captchas && isset($eventData['timestamp']) && ($captchas_ttl < 1 || $eventData['timestamp'] < time() - $captchas_ttl * 60 * 60 * 24) ? true : false; // Plugins can override with custom captchas if (isset($serendipity['plugins']['disable_internal_captcha'])) { $show_captcha = false; } $forcemoderation = $this->get_config('forcemoderation', 60); $forcemoderation_treat = $this->get_config('forcemoderation_treat', 'moderate'); $forcemoderationt = $this->get_config('forcemoderationt', 60); $forcemoderationt_treat = $this->get_config('forcemoderationt_treat', 'moderate'); $links_moderate = $this->get_config('links_moderate', 10); $links_reject = $this->get_config('links_reject', 20); if (function_exists('imagettftext') && function_exists('imagejpeg')) { $max_char = 5; $min_char = 3; $use_gd = true; } else { $max_char = $min_char = 5; $use_gd = false; } switch ($event) { case 'fetchcomments': if (is_array($eventData) && !$_SESSION['serendipityAuthedUser'] && serendipity_db_bool($this->get_config('hide_email', false))) { // Will force emails to be not displayed in comments and RSS feed for comments. Will not apply to logged in admins (so not in the backend as well) @reset($eventData); while (list($idx, $comment) = each($eventData)) { $eventData[$idx]['no_email'] = true; } } break; case 'frontend_saveComment': /* $fp = fopen('/tmp/spamblock2.log', 'a'); fwrite($fp, date('Y-m-d H:i') . "\n" . print_r($eventData, true) . "\n" . print_r($addData, true) . "\n"); fclose($fp); */ if (!is_array($eventData) || serendipity_db_bool($eventData['allow_comments'])) { $this->checkScheme(); $serendipity['csuccess'] = 'true'; $logfile = $this->logfile = $this->get_config('logfile', $serendipity['serendipityPath'] . 'spamblock.log'); $required_fields = $this->get_config('required_fields', ''); $checkmail = $this->get_config('checkmail'); // Check CSRF [comments only, cannot be applied to trackbacks] if ($addData['type'] == 'NORMAL' && serendipity_db_bool($this->get_config('csrf', true))) { if (!serendipity_checkFormToken(false)) { $this->log($logfile, $eventData['id'], 'REJECTED', PLUGIN_EVENT_SPAMBLOCK_CSRF_REASON, $addData); $eventData = array('allow_comments' => false); $serendipity['messagestack']['comments'][] = PLUGIN_EVENT_SPAMBLOCK_CSRF_REASON; } } // Check required fields if ($addData['type'] == 'NORMAL' && !empty($required_fields)) { $required_field_list = explode(',', $required_fields); foreach ($required_field_list as $required_field) { $required_field = trim($required_field); if (empty($addData[$required_field])) { $this->log($logfile, $eventData['id'], 'REJECTED', PLUGIN_EVENT_SPAMBLOCK_REASON_REQUIRED_FIELD, $addData); $eventData = array('allow_comments' => false); $serendipity['messagestack']['comments'][] = sprintf(PLUGIN_EVENT_SPAMBLOCK_REASON_REQUIRED_FIELD, $required_field); return false; } } } /* if ($addData['type'] != 'NORMAL' && empty($addData['name'])) { $eventData = array('allow_coments' => false); $this->log($logfile, $eventData['id'], 'INVALIDGARV', 'INVALIDGARV', $addData); return false; } */ // Check whether to allow comments from registered authors if (serendipity_userLoggedIn() && $this->inGroup()) { return true; } // Check if the user has verified himself via email already. if ($addData['type'] == 'NORMAL' && (string) $checkmail === 'verify_once') { $auth = serendipity_db_query("SELECT *\n FROM {$serendipity['dbPrefix']}options\n WHERE okey = 'mail_confirm'\n AND name = '" . serendipity_db_escape_string($addData['email']) . "'\n AND value = '" . serendipity_db_escape_string($addData['name']) . "'", true); if (!is_array($auth)) { // Filter authors names, Filter URL, Filter Content, Filter Emails, Check for maximum number of links before rejecting // moderate false if (false === $this->wordfilter($logfile, $eventData, $wordmatch, $addData, true)) { // already there #$this->log($logfile, $eventData['id'], 'REJECTED', PLUGIN_EVENT_SPAMBLOCK_FILTER_WORDS, $addData); // already there #$eventData = array('allow_comments' => false); // already there #$serendipity['messagestack']['emails'][] = PLUGIN_EVENT_SPAMBLOCK_ERROR_BODY; return false; } elseif (serendipity_db_bool($this->get_config('killswitch', false)) === true) { $this->log($logfile, $eventData['id'], 'REJECTED', PLUGIN_EVENT_SPAMBLOCK_REASON_KILLSWITCH, $addData); $eventData = array('allow_comments' => false); $serendipity['messagestack']['comments'][] = PLUGIN_EVENT_SPAMBLOCK_ERROR_KILLSWITCH; return false; } else { $this->log($logfile, $eventData['id'], 'MODERATE', PLUGIN_EVENT_SPAMBLOCK_CHECKMAIL_VERIFICATION_MAIL, $addData); $eventData['moderate_comments'] = true; $eventData['status'] = 'confirm1'; $serendipity['csuccess'] = 'moderate'; $serendipity['moderate_reason'] = PLUGIN_EVENT_SPAMBLOCK_CHECKMAIL_VERIFICATION_MAIL; return false; } } else { // User is allowed to post message, bypassing other checks as if he were logged in. return true; } } // Check if entry title is the same as comment body if (serendipity_db_bool($this->get_config('entrytitle')) && trim($eventData['title']) == trim($addData['comment'])) { $this->log($logfile, $eventData['id'], 'REJECTED', PLUGIN_EVENT_SPAMBLOCK_REASON_TITLE, $addData); $eventData = array('allow_comments' => false); $serendipity['messagestack']['comments'][] = PLUGIN_EVENT_SPAMBLOCK_ERROR_BODY; return false; } // Check for global emergency moderation if (serendipity_db_bool($this->get_config('killswitch', false)) === true) { $this->log($logfile, $eventData['id'], 'REJECTED', PLUGIN_EVENT_SPAMBLOCK_REASON_KILLSWITCH, $addData); $eventData = array('allow_comments' => false); $serendipity['messagestack']['comments'][] = PLUGIN_EVENT_SPAMBLOCK_ERROR_KILLSWITCH; return false; } // Check for not allowing trackbacks/pingbacks/wfwcomments if (($addData['type'] != 'NORMAL' || $addData['source'] == 'API') && $this->get_config('disable_api_comments', 'none') != 'none') { if ($this->get_config('disable_api_comments') == 'reject') { $this->log($logfile, $eventData['id'], 'REJECTED', PLUGIN_EVENT_SPAMBLOCK_REASON_API, $addData); $eventData = array('allow_comments' => false); $serendipity['messagestack']['comments'][] = PLUGIN_EVENT_SPAMBLOCK_REASON_API; return false; } elseif ($this->get_config('disable_api_comments') == 'moderate') { $this->log($logfile, $eventData['id'], 'MODERATE', PLUGIN_EVENT_SPAMBLOCK_REASON_API, $addData); $eventData['moderate_comments'] = true; $serendipity['csuccess'] = 'moderate'; $serendipity['moderate_reason'] = PLUGIN_EVENT_SPAMBLOCK_REASON_API; } } // Check if sender ip is matching trackback/pingback ip (ip validation) $trackback_ipvalidation_option = $this->get_config('trackback_ipvalidation', 'moderate'); if (($addData['type'] == 'TRACKBACK' || $addData['type'] == 'PINGBACK') && $trackback_ipvalidation_option != 'no') { $this->IsHardcoreSpammer(); $exclude_urls = explode(';', $this->get_config('trackback_ipvalidation_url_exclude', $this->get_default_exclude_urls())); $found_exclude_url = false; foreach ($exclude_urls as $exclude_url) { $exclude_url = trim($exclude_url); if (empty($exclude_url)) { continue; } $found_exclude_url = preg_match('@' . $exclude_url . '@', $addData['url']); if ($found_exclude_url) { break; } } if (!$found_exclude_url) { $parts = @parse_url($addData['url']); $tipval_method = $trackback_ipvalidation_option == 'reject' ? 'REJECTED' : 'MODERATE'; // Getting host from url successfully? if (!is_array($parts)) { // not a valid URL $this->log($logfile, $eventData['id'], $tipval_method, sprintf(PLUGIN_EVENT_SPAMBLOCK_REASON_IPVALIDATION, $addData['url'], '', ''), $addData); if ($trackback_ipvalidation_option == 'reject') { $eventData = array('allow_comments' => false); $serendipity['messagestack']['comments'][] = sprintf(PLUGIN_EVENT_SPAMBLOCK_REASON_IPVALIDATION, $addData['url']); return false; } else { $eventData['moderate_comments'] = true; $serendipity['csuccess'] = 'moderate'; $serendipity['moderate_reason'] = sprintf(PLUGIN_EVENT_SPAMBLOCK_REASON_IPVALIDATION, $addData['url']); } } $trackback_ip = preg_replace('/[^0-9.]/', '', gethostbyname($parts['host'])); $sender_ip = preg_replace('/[^0-9.]/', '', $_SERVER['REMOTE_ADDR']); $sender_ua = $debug ? ', ua="' . $_SERVER['HTTP_USER_AGENT'] . '"' : ''; // Is host ip and sender ip matching? if ($trackback_ip != $sender_ip) { $this->log($logfile, $eventData['id'], $tipval_method, sprintf(PLUGIN_EVENT_SPAMBLOCK_REASON_IPVALIDATION, $parts['host'], $trackback_ip, $sender_ip . $sender_ua), $addData); if ($trackback_ipvalidation_option == 'reject') { $eventData = array('allow_comments' => false); $serendipity['messagestack']['comments'][] = sprintf(PLUGIN_EVENT_SPAMBLOCK_REASON_IPVALIDATION, $parts['host'], $trackback_ip, $sender_ip . $sender_ua); return false; } else { $eventData['moderate_comments'] = true; $serendipity['csuccess'] = 'moderate'; $serendipity['moderate_reason'] = sprintf(PLUGIN_EVENT_SPAMBLOCK_REASON_IPVALIDATION, $parts['host'], $trackback_ip, $sender_ip . $sender_ua); } } } } // Filter Akismet Blacklist? $akismet_apikey = $this->get_config('akismet'); $akismet = $this->get_config('akismet_filter'); if (!empty($akismet_apikey) && ($akismet == 'moderate' || $akismet == 'reject') && !isset($addData['skip_akismet'])) { $spam = $this->getBlacklist('akismet.com', $akismet_apikey, $eventData, $addData); if ($spam['is_spam'] !== false) { $this->IsHardcoreSpammer(); if ($akismet == 'moderate') { $this->log($logfile, $eventData['id'], 'MODERATE', PLUGIN_EVENT_SPAMBLOCK_REASON_AKISMET_SPAMLIST . ': ' . $spam['message'], $addData); $eventData['moderate_comments'] = true; $serendipity['csuccess'] = 'moderate'; $serendipity['moderate_reason'] = PLUGIN_EVENT_SPAMBLOCK_ERROR_BODY . ' (Akismet)'; } else { $this->log($logfile, $eventData['id'], 'REJECTED', PLUGIN_EVENT_SPAMBLOCK_REASON_AKISMET_SPAMLIST . ': ' . $spam['message'], $addData); $eventData = array('allow_comments' => false); $serendipity['messagestack']['comments'][] = PLUGIN_EVENT_SPAMBLOCK_ERROR_BODY; return false; } } } // Check Trackback URLs? if (($addData['type'] == 'TRACKBACK' || $addData['type'] == 'PINGBACK') && serendipity_db_bool($this->get_config('trackback_check_url'))) { require_once S9Y_PEAR_PATH . 'HTTP/Request.php'; if (function_exists('serendipity_request_start')) { serendipity_request_start(); } $req = new HTTP_Request($addData['url'], array('allowRedirects' => true, 'maxRedirects' => 5, 'readTimeout' => array(5, 0))); $is_valid = false; if (PEAR::isError($req->sendRequest()) || $req->getResponseCode() != '200') { $is_valid = false; } else { $fdata = $req->getResponseBody(); // Check if the target page contains a link to our blog if (preg_match('@' . preg_quote($serendipity['baseURL'], '@') . '@i', $fdata)) { $is_valid = true; } else { $is_valid = false; } } if (function_exists('serendipity_request_end')) { serendipity_request_end(); } if ($is_valid === false) { $this->log($logfile, $eventData['id'], 'REJECTED', PLUGIN_EVENT_SPAMBLOCK_REASON_TRACKBACKURL, $addData); $eventData = array('allow_comments' => false); $serendipity['messagestack']['comments'][] = PLUGIN_EVENT_SPAMBLOCK_REASON_TRACKBACKURL; return false; } } if (false === $this->wordfilter($logfile, $eventData, $wordmatch, $addData)) { return false; } // Check for maximum number of links before rejecting $link_count = substr_count(strtolower($addData['comment']), 'http://'); if ($links_reject > 0 && $link_count > $links_reject) { $this->log($logfile, $eventData['id'], 'REJECTED', PLUGIN_EVENT_SPAMBLOCK_REASON_LINKS_REJECT, $addData); $eventData = array('allow_comments' => false); $serendipity['messagestack']['comments'][] = PLUGIN_EVENT_SPAMBLOCK_ERROR_BODY; return false; } // Captcha checking if ($show_captcha && $addData['type'] == 'NORMAL') { if (!isset($_SESSION['spamblock']['captcha']) || !isset($serendipity['POST']['captcha']) || strtolower($serendipity['POST']['captcha']) != strtolower($_SESSION['spamblock']['captcha'])) { $this->log($logfile, $eventData['id'], 'REJECTED', sprintf(PLUGIN_EVENT_SPAMBLOCK_REASON_CAPTCHAS, $serendipity['POST']['captcha'], $_SESSION['spamblock']['captcha']), $addData); $eventData = array('allow_comments' => false); $serendipity['messagestack']['comments'][] = PLUGIN_EVENT_SPAMBLOCK_ERROR_CAPTCHAS; return false; } else { // DEBUG // $this->log($logfile, $eventData['id'], 'REJECTED', 'Captcha passed: ' . $serendipity['POST']['captcha'] . ' / ' . $_SESSION['spamblock']['captcha'] . ' // Source: ' . $_SERVER['REQUEST_URI'], $addData); } } else { // DEBUG // $this->log($logfile, $eventData['id'], 'REJECTED', 'Captcha not needed: ' . $serendipity['POST']['captcha'] . ' / ' . $_SESSION['spamblock']['captcha'] . ' // Source: ' . $_SERVER['REQUEST_URI'], $addData); } // Check for forced comment moderation (X days) if ($addData['type'] == 'NORMAL' && $forcemoderation > 0 && $eventData['timestamp'] < time() - $forcemoderation * 60 * 60 * 24) { $this->log($logfile, $eventData['id'], $forcemoderation_treat, PLUGIN_EVENT_SPAMBLOCK_REASON_FORCEMODERATION, $addData); if ($forcemoderation_treat == 'reject') { $eventData = array('allow_comments' => false); $serendipity['messagestack']['comments'][] = PLUGIN_EVENT_SPAMBLOCK_REASON_FORCEMODERATION; return false; } else { $eventData['moderate_comments'] = true; $serendipity['csuccess'] = 'moderate'; $serendipity['moderate_reason'] = PLUGIN_EVENT_SPAMBLOCK_REASON_FORCEMODERATION; } } // Check for forced trackback moderation if ($addData['type'] != 'NORMAL' && $forcemoderationt > 0 && $eventData['timestamp'] < time() - $forcemoderationt * 60 * 60 * 24) { $this->log($logfile, $eventData['id'], $forcemoderationt_treat, PLUGIN_EVENT_SPAMBLOCK_REASON_FORCEMODERATION, $addData); if ($forcemoderationt_treat == 'reject') { $eventData = array('allow_comments' => false); $serendipity['messagestack']['comments'][] = PLUGIN_EVENT_SPAMBLOCK_REASON_FORCEMODERATION; return false; } else { $eventData['moderate_comments'] = true; $serendipity['csuccess'] = 'moderate'; $serendipity['moderate_reason'] = PLUGIN_EVENT_SPAMBLOCK_REASON_FORCEMODERATION; } } // Check for maximum number of links before forcing moderation if ($links_moderate > 0 && $link_count > $links_moderate) { $this->log($logfile, $eventData['id'], 'REJECTED', PLUGIN_EVENT_SPAMBLOCK_REASON_LINKS_MODERATE, $addData); $eventData['moderate_comments'] = true; $serendipity['csuccess'] = 'moderate'; $serendipity['moderate_reason'] = PLUGIN_EVENT_SPAMBLOCK_REASON_LINKS_MODERATE; } // Check for identical comments. We allow to bypass trackbacks from our server to our own blog. if ($this->get_config('bodyclone', true) === true && $_SERVER['REMOTE_ADDR'] != $_SERVER['SERVER_ADDR'] && $addData['type'] != 'PINGBACK') { $query = "SELECT count(id) AS counter FROM {$serendipity['dbPrefix']}comments WHERE type = '" . $addData['type'] . "' AND body = '" . serendipity_db_escape_string($addData['comment']) . "'"; $row = serendipity_db_query($query, true); if (is_array($row) && $row['counter'] > 0) { $this->IsHardcoreSpammer(); $this->log($logfile, $eventData['id'], 'REJECTED', PLUGIN_EVENT_SPAMBLOCK_REASON_BODYCLONE, $addData); $eventData = array('allow_comments' => false); $serendipity['messagestack']['comments'][] = PLUGIN_EVENT_SPAMBLOCK_ERROR_BODY; return false; } } // Check last IP if ($addData['type'] == 'NORMAL' && $this->get_config('ipflood', 2) != 0) { $query = "SELECT max(timestamp) AS last_post FROM {$serendipity['dbPrefix']}comments WHERE ip = '" . serendipity_db_escape_string($_SERVER['REMOTE_ADDR']) . "'"; $row = serendipity_db_query($query, true); if (is_array($row) && $row['last_post'] > time() - $this->get_config('ipflood', 2) * 60) { $this->log($logfile, $eventData['id'], 'REJECTED', PLUGIN_EVENT_SPAMBLOCK_REASON_IPFLOOD, $addData); $eventData = array('allow_comments' => false); $serendipity['messagestack']['comments'][] = PLUGIN_EVENT_SPAMBLOCK_ERROR_IP; return false; } } if ($addData['type'] == 'NORMAL' && (string) $checkmail === 'verify_always') { $this->log($logfile, $eventData['id'], 'MODERATE', PLUGIN_EVENT_SPAMBLOCK_CHECKMAIL_VERIFICATION_MAIL, $addData); $eventData['moderate_comments'] = true; $eventData['status'] = 'confirm'; $serendipity['csuccess'] = 'moderate'; $serendipity['moderate_reason'] = PLUGIN_EVENT_SPAMBLOCK_CHECKMAIL_VERIFICATION_MAIL; return false; } // Check invalid email if ($addData['type'] == 'NORMAL' && serendipity_db_bool($this->get_config('checkmail', false))) { if (!empty($addData['email']) && strstr($addData['email'], '@') === false) { $this->log($logfile, $eventData['id'], 'REJECTED', PLUGIN_EVENT_SPAMBLOCK_REASON_CHECKMAIL, $addData); $eventData = array('allow_comments' => false); $serendipity['messagestack']['comments'][] = PLUGIN_EVENT_SPAMBLOCK_REASON_CHECKMAIL; return false; } } if ($eventData['moderate_comments'] == true) { return false; } } return true; break; case 'frontend_comment': if (serendipity_db_bool($this->get_config('hide_email', false))) { echo '<div class="serendipity_commentDirection serendipity_comment_spamblock">' . PLUGIN_EVENT_SPAMBLOCK_HIDE_EMAIL_NOTICE . '</div>'; } if ((string) $this->get_config('checkmail') === 'verify_always' || (string) $this->get_config('checkmail') === 'verify_once') { echo '<div class="serendipity_commentDirection serendipity_comment_spamblock">' . PLUGIN_EVENT_SPAMBLOCK_CHECKMAIL_VERIFICATION_INFO . '</div>'; } if (serendipity_db_bool($this->get_config('csrf', true))) { echo serendipity_setFormToken('form'); } // Check whether to allow comments from registered authors if (serendipity_userLoggedIn() && $this->inGroup()) { return true; } if ($show_captcha) { echo '<div class="serendipity_commentDirection serendipity_comment_captcha">'; if (!isset($serendipity['POST']['preview']) || strtolower($serendipity['POST']['captcha'] != strtolower($_SESSION['spamblock']['captcha']))) { echo '<br />' . PLUGIN_EVENT_SPAMBLOCK_CAPTCHAS_USERDESC . '<br />'; echo $this->show_captcha($use_gd); echo '<br />'; echo '<label for="captcha">' . PLUGIN_EVENT_SPAMBLOCK_CAPTCHAS_USERDESC3 . '</label><br /><input class="input_textbox" type="text" size="5" name="serendipity[captcha]" value="" id="captcha" />'; } elseif (isset($serendipity['POST']['captcha'])) { echo '<input type="hidden" name="serendipity[captcha]" value="' . serendipity_specialchars($serendipity['POST']['captcha']) . '" />'; } echo '</div>'; } return true; break; case 'external_plugin': $parts = explode('_', (string) $eventData); if (!empty($parts[1])) { $param = (int) $parts[1]; } else { $param = null; } $methods = array('captcha'); if (!in_array($parts[0], $methods)) { return; } list($musec, $msec) = explode(' ', microtime()); $srand = (double) $msec + (double) $musec * 100000; srand($srand); mt_srand($srand); $width = 120; $height = 40; $bgcolors = explode(',', $this->get_config('captcha_color', '255,255,255')); $fontfiles = array('Vera.ttf', 'VeraSe.ttf', 'chumbly.ttf', '36daysago.ttf'); if ($use_gd) { $strings = $this->random_string($max_char, $min_char); $fontname = $fontfiles[array_rand($fontfiles)]; $font = $serendipity['serendipityPath'] . 'plugins/serendipity_event_spamblock/' . $fontname; if (!file_exists($font)) { // Search in shared plugin directory $font = S9Y_INCLUDE_PATH . 'plugins/serendipity_event_spamblock/' . $fontname; } if (!file_exists($font)) { die(PLUGIN_EVENT_SPAMBLOCK_ERROR_NOTTF); } header('Content-Type: image/jpeg'); $image = imagecreate($width, $height); // recommended use of imagecreatetruecolor() returns a black backgroundcolor $bgcol = imagecolorallocate($image, trim($bgcolors[0]), trim($bgcolors[1]), trim($bgcolors[2])); // imagettftext($image, 10, 1, 1, 15, imagecolorallocate($image, 255, 255, 255), $font, 'String: ' . $string); $pos_x = 5; foreach ($strings as $idx => $charidx) { $color = imagecolorallocate($image, mt_rand(50, 235), mt_rand(50, 235), mt_rand(50, 235)); $size = mt_rand(15, 21); $angle = mt_rand(-20, 20); $pos_y = ceil($height - mt_rand($size / 3, $size / 2)); imagettftext($image, $size, $angle, $pos_x, $pos_y, $color, $font, $this->chars[$charidx]); $pos_x = $pos_x + $size + 2; } if ($_captchas === 'scramble') { $line_diff = mt_rand(5, 15); $pixel_col = imagecolorallocate($image, trim($bgcolors[0]) - mt_rand(10, 50), trim($bgcolors[1]) - mt_rand(10, 50), trim($bgcolors[2]) - mt_rand(10, 50)); for ($y = $line_diff; $y < $height; $y += $line_diff) { $row_diff = mt_rand(5, 15); for ($x = $row_diff; $x < $width; $x += $row_diff) { imagerectangle($image, $x, $y, $x + 1, $y + 1, $pixel_col); } } } imagejpeg($image, NULL, 90); // NULL fixes https://bugs.php.net/bug.php?id=63920 imagedestroy($image); } else { header('Content-Type: image/png'); $output_char = strtolower($_SESSION['spamblock']['captcha'][$parts[1] - 1]); $cap = $serendipity['serendipityPath'] . 'plugins/serendipity_event_spamblock/captcha_' . $output_char . '.png'; if (!file_exists($cap)) { $cap = S9Y_INCLUDE_PATH . 'plugins/serendipity_event_spamblock/captcha_' . $output_char . '.png'; } if (file_exists($cap)) { echo file_get_contents($cap); } } return true; break; case 'backend_comments_top': // Tell Akismet about spam or not spam $tell_id = null; if (isset($serendipity['GET']['spamIsSpam'])) { $tell_spam = true; $tell_id = $serendipity['GET']['spamIsSpam']; } if (isset($serendipity['GET']['spamNotSpam'])) { $tell_spam = false; $tell_id = $serendipity['GET']['spamNotSpam']; } if ($tell_id !== null) { $akismet_apikey = $this->get_config('akismet'); $akismet = $this->get_config('akismet_filter'); if (!empty($akismet_apikey)) { $this->tellAboutComment('akismet.com', $akismet_apikey, $tell_id, $tell_spam); } } // Add Author to blacklist. If already filtered, it will be removed from the filter. (AKA "Toggle") if (isset($serendipity['GET']['spamBlockAuthor'])) { $item = $this->getComment('author', $serendipity['GET']['spamBlockAuthor']); $items =& $this->checkFilter('authors', $item, true); $this->set_config('contentfilter_authors', implode(';', $items)); } // Add URL to blacklist. If already filtered, it will be removed from the filter. (AKA "Toggle") if (isset($serendipity['GET']['spamBlockURL'])) { $item = $this->getComment('url', $serendipity['GET']['spamBlockURL']); $items =& $this->checkFilter('urls', $item, true); $this->set_config('contentfilter_urls', implode(';', $items)); } // Add E-mail to blacklist. If already filtered, it will be removed from the filter. (AKA "Toggle") if (isset($serendipity['GET']['spamBlockEmail'])) { $item = $this->getComment('email', $serendipity['GET']['spamBlockEmail']); $items =& $this->checkFilter('emails', $item, true); $this->set_config('contentfilter_emails', implode(';', $items)); } echo '<a class="button_link" title="' . PLUGIN_EVENT_SPAMBLOCK_CONFIG . '" href="serendipity_admin.php?serendipity[adminModule]=plugins&serendipity[plugin_to_conf]=' . $this->instance . '"><span class="icon-medkit"></span><span class="visuallyhidden"> ' . PLUGIN_EVENT_SPAMBLOCK_CONFIG . '</span></a>'; return true; break; case 'backend_view_comment': $author_is_filtered = $this->checkFilter('authors', $eventData['author']); $clink = 'comment_' . $eventData['id']; $randomString = '&random=' . substr(sha1(rand()), 0, 10); # the random string will force browser to reload the page, # so the server knows who to block/unblock when clicking again on the same link, # see http://stackoverflow.com/a/2573986/2508518, http://stackoverflow.com/a/14043346/2508518 $akismet_apikey = $this->get_config('akismet'); $akismet = $this->get_config('akismet_filter'); if (!empty($akismet_apikey)) { $eventData['action_more'] .= ' <a class="button_link actions_extra" title="' . PLUGIN_EVENT_SPAMBLOCK_SPAM . '" href="serendipity_admin.php?serendipity[adminModule]=comments&serendipity[spamIsSpam]=' . $eventData['id'] . $addData . '#' . $clink . '"><span class="icon-block"></span><span class="visuallyhidden"> ' . PLUGIN_EVENT_SPAMBLOCK_SPAM . '</span></a>'; $eventData['action_more'] .= ' <a class="button_link actions_extra" title="' . PLUGIN_EVENT_SPAMBLOCK_NOT_SPAM . '" href="serendipity_admin.php?serendipity[adminModule]=comments&serendipity[spamNotSpam]=' . $eventData['id'] . $addData . '#' . $clink . '"><span class="icon-ok-circled"></span><span class="visuallyhidden"> ' . PLUGIN_EVENT_SPAMBLOCK_NOT_SPAM . '</span></a>'; } $eventData['action_author'] .= ' <a class="button_link" title="' . ($author_is_filtered ? PLUGIN_EVENT_SPAMBLOCK_REMOVE_AUTHOR : PLUGIN_EVENT_SPAMBLOCK_ADD_AUTHOR) . '" href="serendipity_admin.php?serendipity[adminModule]=comments&serendipity[spamBlockAuthor]=' . $eventData['id'] . $addData . $randomString . '#' . $clink . '"><span class="icon-' . ($author_is_filtered ? 'ok-circled' : 'block') . '"></span><span class="visuallyhidden"> ' . ($author_is_filtered ? PLUGIN_EVENT_SPAMBLOCK_REMOVE_AUTHOR : PLUGIN_EVENT_SPAMBLOCK_ADD_AUTHOR) . '</span></a>'; if (!empty($eventData['url'])) { $url_is_filtered = $this->checkFilter('urls', $eventData['url']); $eventData['action_url'] .= ' <a class="button_link" title="' . ($url_is_filtered ? PLUGIN_EVENT_SPAMBLOCK_REMOVE_URL : PLUGIN_EVENT_SPAMBLOCK_ADD_URL) . '" href="serendipity_admin.php?serendipity[adminModule]=comments&serendipity[spamBlockURL]=' . $eventData['id'] . $addData . $randomString . '#' . $clink . '"><span class="icon-' . ($url_is_filtered ? 'ok-circled' : 'block') . '"></span><span class="visuallyhidden"> ' . ($url_is_filtered ? PLUGIN_EVENT_SPAMBLOCK_REMOVE_URL : PLUGIN_EVENT_SPAMBLOCK_ADD_URL) . '</span></a>'; } if (!empty($eventData['email'])) { $email_is_filtered = $this->checkFilter('emails', $eventData['email']); $eventData['action_email'] .= ' <a class="button_link" title="' . ($email_is_filtered ? PLUGIN_EVENT_SPAMBLOCK_REMOVE_EMAIL : PLUGIN_EVENT_SPAMBLOCK_ADD_EMAIL) . '" href="serendipity_admin.php?serendipity[adminModule]=comments&serendipity[spamBlockEmail]=' . $eventData['id'] . $addData . $randomString . '#' . $clink . '"><span class="icon-' . ($email_is_filtered ? 'ok-circled' : 'block') . '"></span><span class="visuallyhidden"> ' . ($email_is_filtered ? PLUGIN_EVENT_SPAMBLOCK_REMOVE_EMAIL : PLUGIN_EVENT_SPAMBLOCK_ADD_EMAIL) . '</span></a>'; } return true; break; case 'backend_sidebar_admin_appearance': echo '<li><a href="serendipity_admin.php?serendipity[adminModule]=plugins&serendipity[plugin_to_conf]=' . $this->instance . '">' . PLUGIN_EVENT_SPAMBLOCK_TITLE . '</a></li>'; return true; break; default: return false; break; } } else { return false; } }
if (!serendipity_checkDirUpload($serendipity['POST']['target_directory'][$tindex])) { $messages[] = '<span class="msg_error"><span class="icon-attention-circled"></span> ' . PERM_DENIED . '</span>'; return; } $realname = $tfile; if (file_exists($target)) { $messages[] = '<span class="msg_error"><span class="icon-attention-circled"></span> ' . $target . ' - ' . ERROR_FILE_EXISTS_ALREADY . '</span>'; $realname = serendipity_imageAppend($tfile, $target, $serendipity['serendipityPath'] . $serendipity['uploadPath'] . $serendipity['POST']['target_directory'][$tindex]); } require_once S9Y_PEAR_PATH . 'HTTP/Request.php'; $options = array('allowRedirects' => true, 'maxRedirects' => 5); serendipity_plugin_api::hook_event('backend_http_request', $options, 'image'); serendipity_request_start(); $req = new HTTP_Request($serendipity['POST']['imageurl'], $options); // Try to get the URL if (PEAR::isError($req->sendRequest()) || $req->getResponseCode() != '200') { $messages[] = sprintf('<span class="msg_error"><span class="icon-attention-circled"></span> ' . REMOTE_FILE_NOT_FOUND . '</span>', $serendipity['POST']['imageurl']); } else { // Fetch file $fContent = $req->getResponseBody(); if ($serendipity['POST']['imageimporttype'] == 'hotlink') { $tempfile = $serendipity['serendipityPath'] . $serendipity['uploadPath'] . '/hotlink_' . time(); $fp = fopen($tempfile, 'w'); fwrite($fp, $fContent); fclose($fp); $image_id = @serendipity_insertHotlinkedImageInDatabase($tfile, $serendipity['POST']['imageurl'], $authorid, null, $tempfile); $messages[] = sprintf('<span class="msg_success"><span class="icon-ok-circled"></span> ' . HOTLINK_DONE . '</span>', $serendipity['POST']['imageurl'], $tfile . ''); serendipity_plugin_api::hook_event('backend_image_addHotlink', $tempfile); } else { $fp = fopen($target, 'w'); fwrite($fp, $fContent);
/** * 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 updateTwitterTimelineCache($cachefile) { global $serendipity; $cachetime = (int) $this->get_config('cachetime', 300); if (!file_exists($cachefile) || filemtime($cachefile) < time() - $cachetime) { require_once S9Y_PEAR_PATH . 'HTTP/Request.php'; $service = $this->get_config('service'); $username = $this->get_config('username'); $number = $this->get_config('number'); if (serendipity_db_bool($this->get_config('toall_only', false))) { $number = 50; // Fetch many in the hope, that there are enough globals with it. } if ($service == 'identi.ca') { $service_url = 'http://identi.ca/api'; $status_url = 'http://identi.ca/notice/'; $search_twitter_uri = $service_url . '/statuses/user_timeline/' . $username . '.json?count=' . $number; } else { $followme_url = 'https://twitter.com/' . $username; $service_url = 'https://api.twitter.com'; $status_url = 'https://twitter.com/' . $username . '/statuses/'; $search_twitter_uri = 'https://api.twitter.com/1/statuses/user_timeline.json?screen_name=' . $username . '&count=' . $number; } serendipity_request_start(); $req = new HTTP_Request($search_twitter_uri); $req->sendRequest(); $response = trim($req->getResponseBody()); $error = $req->getResponseCode(); serendipity_request_end(); if ($error == 200 && !empty($response)) { $fp = fopen($cachefile, 'w'); fwrite($fp, serialize($response)); fflush($fp); fclose($fp); } } }
function urlcheck($uri) { // These two substring comparisons are faster than one regexp. if ('http://' != substr($uri, 0, 7) && 'https://' != substr($uri, 0, 8)) { return false; } // Disabled by now. May get enabled in the future, but for now the extra HTTP call isn't worth trying. return true; require_once S9Y_PEAR_PATH . 'HTTP/Request.php'; serendipity_request_start(); $req = new HTTP_Request($uri); if (PEAR::isError($req->sendRequest()) || !preg_match('@^[23]..@', $req->getResponseCode())) { serendipity_request_end(); return false; } else { serendipity_request_end(); return true; } }
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()); } }
/** * Webページを取得する * * 200 OK * 206 Partial Content * 304 Not Modified → 失敗扱い * * @return array|false 成功したらページ内容を返す。失敗したらfalseを返す。 */ public static function getWebPage($url, &$error_msg, $timeout = 15) { if (!class_exists('HTTP_Request', false)) { require 'HTTP/Request.php'; } $params = array("timeout" => $timeout); if (!empty($_conf['proxy_use'])) { $params['proxy_host'] = $_conf['proxy_host']; $params['proxy_port'] = $_conf['proxy_port']; } $req = new HTTP_Request($url, $params); //$req->addHeader("X-PHP-Version", phpversion()); $response = $req->sendRequest(); if (PEAR::isError($response)) { $error_msg = $response->getMessage(); } else { $code = $req->getResponseCode(); if ($code == 200 || $code == 206) { // || $code == 304) { return $req->getResponseBody(); } else { //var_dump($req->getResponseHeader()); $error_msg = $code; } } return false; }
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; }
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 __validateLinks($a_links) { global $tree; if (!@(include_once 'HTTP/Request.php')) { $this->__appendLogMessage('LinkChecker: Pear HTTP_Request is not installed. Aborting'); return array(); } foreach ($a_links as $link) { // #10091 - internal if ($link['scheme'] == 'internal') { $obj_id = ilObject::_lookupObjId($link['ref_id']); if (!$obj_id || ilObject::_lookupType($obj_id) != $link['obj_type'] || $tree->isDeleted($link['ref_id'])) { $invalid[] = $link; } } else { if (gethostbyname($link['host']) == $link['host']) { $invalid[] = $link; continue; } if ($link['scheme'] !== 'http' and $link['scheme'] !== 'https') { continue; } require_once './Services/Http/classes/class.ilProxySettings.php'; if (ilProxySettings::_getInstance()->isActive()) { $options = array('proxy_host' => ilProxySettings::_getInstance()->getHost(), 'proxy_port' => ilProxySettings::_getInstance()->getPort()); } else { $options = array(); } $req = new HTTP_Request($link['complete'], $options); $req->sendRequest(); switch ($req->getResponseCode()) { // EVERYTHING OK case '200': // In the moment 301 will be handled as ok // In the moment 301 will be handled as ok case '301': case '302': break; default: $link['http_status_code'] = $req->getResponseCode(); $invalid[] = $link; break; } } } return $invalid ? $invalid : array(); }