Use this if you want premature exits instead of the \c exit function.
static public cleanExit ( ) |
public static function redirectToErrorPage() { $acessErrorPage = '/page/gift-law'; header( 'Location: ' . $acessErrorPage ); eZExecution::cleanExit(); }
/** * * Builds the response-data. * * @return mixed|void * */ public function run() { $content = $this->content; $status = $this->options['status']; $options = $this->options; // Give response header for status code header('HTTP/1.1 ' . $status . ' ' . $this->codes[$status]); switch ($options['type']) { case 'json': $options['headers'] += array('Content-type' => 'application/json'); $this->headers($options['headers']); echo json_encode($content); break; case 'jsonEncoded': $options['headers'] += array('Content-type' => 'application/json'); $this->headers($options['headers']); return compact('content'); case 'tpl': /** Default pagelayout. */ $options += array('pagelayout' => 'pagelayout.tpl'); return $this->renderTpl($content, $options); case 'text': return array('pagelayout' => false, 'content' => $this->content); case 'xml': $options['headers'] += array('Content-type' => 'text/xml'); $this->headers($options['headers']); echo $content; break; } Router::handleEZXFormToken(true); return \eZExecution::cleanExit(); }
function handleFileDownload($contentObject, $contentObjectAttribute, $type, $fileInfo) { $fileName = $fileInfo['filepath']; $file = eZClusterFileHandler::instance($fileName); if ($fileName != "" and $file->exists()) { $fileSize = $file->size(); if (isset($_SERVER['HTTP_RANGE']) && preg_match("/^bytes=(\\d+)-(\\d+)?\$/", trim($_SERVER['HTTP_RANGE']), $matches)) { $fileOffset = $matches[1]; $contentLength = isset($matches[2]) ? $matches[2] - $matches[1] + 1 : $fileSize - $matches[1]; } else { $fileOffset = 0; $contentLength = $fileSize; } // Figure out the time of last modification of the file right way to get the file mtime ... the $fileModificationTime = $file->mtime(); // stop output buffering, and stop the session so that browsing can be continued while downloading eZSession::stop(); ob_end_clean(); eZFile::downloadHeaders($fileName, self::dispositionType($fileInfo['mime_type']) === 'attachment', false, $fileOffset, $contentLength, $fileSize); try { $file->passthrough($fileOffset, $contentLength); } catch (eZClusterFileHandlerNotFoundException $e) { eZDebug::writeError($e->getMessage, __METHOD__); header($_SERVER["SERVER_PROTOCOL"] . ' 500 Internal Server Error'); } catch (eZClusterFileHandlerGeneralException $e) { eZDebug::writeError($e->getMessage, __METHOD__); header($_SERVER["SERVER_PROTOCOL"] . ' 404 Not Found'); } eZExecution::cleanExit(); } return eZBinaryFileHandler::RESULT_UNAVAILABLE; }
/** * Creates a new test database * * @param ezpDsn $dsn * @param array $sqlFiles array( array( string => string ) ) * @param bool $removeExisting * @return mixed */ public static function create(ezpDsn $dsn) { //oracle unit test doesn't support creating database, just use database string if ($dsn->parts['phptype'] === 'oracle') { $db = ezpDatabaseHelper::useDatabase($dsn); eZDBTool::cleanup($db); return $db; } $dsnRoot = clone $dsn; $dsnRoot->parts['database'] = null; try { $dbRoot = ezpDatabaseHelper::dbAsRootInstance($dsnRoot); if (!$dbRoot->IsConnected) { throw new Exception($dbRoot->ErrorMessage); } } catch (Exception $e) { echo $e->getMessage() . PHP_EOL; eZExecution::cleanExit(); } if (self::exists($dbRoot, $dsn->database)) { $db = ezpDatabaseHelper::useDatabase($dsn); self::clean($db); } else { $dbRoot->createDatabase($dsn->database); $db = ezpDatabaseHelper::useDatabase($dsn); } return $db; }
/** * @param string $clusterIdentifier * @throws eZDBException */ public static function fill($clusterIdentifier) { $configPath = "extension/ezoscar/bin/php/seo/config.json"; $cli = eZCLI::instance(); $config = file_get_contents($configPath); if(!$config) { $cli->output("Bad filepath for config file"); eZExecution::cleanExit(); } $config = json_decode($config, true); $db = MMDB::instance(); $rows = $db->arrayQuery(sprintf("SELECT * FROM mm_seo WHERE cluster_identifier = '%s'", $clusterIdentifier)); $progressBar = new ezcConsoleProgressbar( new ezcConsoleOutput(), count($rows), array( 'emptyChar' => ' ', 'barChar' => '=' ) ); $progressBar->start(); foreach($rows as $row) { if(!array_key_exists($clusterIdentifier, $config)) { continue; } $fq = $config[$clusterIdentifier][$row["application_identifier"]]["filters"]; $solrBase = new eZSolrBase(); $params = array( 'indent' => 'on', 'q' => '"'.$row['keyword'].'"', 'fq' => $fq, 'start' => 0, 'rows' => 0, 'fl' => '', 'qt' => 'ezpublish', 'explainOther' => '', 'hl.fl' => '', ); $results = $solrBase->rawSolrRequest('/select', $params); $num_found = $results['response']['numFound']; $db->query(sprintf("UPDATE mm_seo SET nb_results=%d, speciality_url='%s', keyword_url='%s' WHERE id=%d", $num_found, self::sanitize($row["speciality"]), self::sanitize($row["keyword"]), $row["id"])); $progressBar->advance(); } $progressBar->finish(); $cli->output(); }
function exitError($msg = false) { $erroMsg = 'Newsletter image error ' . $_SERVER['REQUEST_URI']; if ($msg) { $erroMsg .= "\n$msg"; } eZDebug::writeError( $erroMsg ); header('HTTP/1.0 404 Not Found'); eZExecution::cleanExit(); }
public function contentBuildResult() { $errorCode = empty( $this->errorCode ) ? '500' : $this->errorCode; $errorCodeList = HttpTool::$statusReason; $errorCodeKey = array_key_exists( $errorCode, $errorCodeList ) ? $errorCode : '500'; $errorMsg = $errorCode . ' ' . $errorCodeList[$errorCodeKey]; header( "HTTP/1.1 $errorMsg" ); header( "Status: $errorMsg" ); echo "ERROR: $errorMsg"; eZExecution::cleanExit(); }
function exitWithInternalError( $errorText ) { header( $_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error' ); //include_once( 'extension/ezjscore/classes/ezjscajaxcontent.php' ); $contentType = ezjscAjaxContent::getHttpAccept(); // set headers if ( $contentType === 'xml' ) header('Content-Type: text/xml; charset=utf-8'); else if ( $contentType === 'json' ) header('Content-Type: text/javascript; charset=utf-8'); echo ezjscAjaxContent::autoEncode( array( 'error_text' => $errorText, 'content' => '' ), $contentType ); eZExecution::cleanExit(); }
function modify($tpl, $operatorName, $operatorParameters, $rootNamespace, $currentNamespace, &$operatorValue, $namedParameters) { $redirectUri = $namedParameters['url']; // if $redirectUri is not starting with scheme:// if (!preg_match('#^\\w+://#', $redirectUri)) { // path to eZ Publish index $indexDir = eZSys::indexDir(); /* We need to make sure we have one and only one slash at the concatenation point between $indexDir and $redirectUri. */ $redirectUri = rtrim($indexDir, '/') . '/' . ltrim($redirectUri, '/'); } // Redirect to $redirectUri by returning status code 301 and exit. eZHTTPTool::redirect($redirectUri, array(), 301); eZExecution::cleanExit(); }
/** * Passthrough file, and exit cleanly */ function downloadFile($filePath) { if (!file_exists($filePath)) { header("HTTP/1.1 404 Not Found"); eZExecution::cleanExit(); } ob_clean(); header("Pragma: public"); header("Expires: 0"); // set expiration time header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("Content-Type: application/force-download"); header("Content-Type: application/octet-stream"); header("Content-Type: application/download"); header("Content-Disposition: attachment; filename=" . basename($filePath)); header("Content-Transfer-Encoding: binary"); header("Content-Length: " . filesize($filePath)); ob_end_clean(); @readfile($filePath); eZExecution::cleanExit(); }
function templateOperatorDownload($tpl, &$persistentData, $stepData) { $singleOperator = $persistentData['single-operator']; $useInput = $persistentData['use-input']; $useOutput = $persistentData['use-output']; $parameterCheck = $persistentData['parameter-check']; $useInput = true; $useOutput = false; $parameterCheck = 2; $operatorName = $persistentData['name']; $className = $persistentData['class-name']; if (!$className) { $fullClassName = 'Template' . strtoupper($operatorName[0]) . substr($operatorName, 1) . 'Operator'; } else { $fullClassName = $className; } $filename = strtolower($fullClassName) . '.php'; $description = $persistentData['description']; $creator = $persistentData['creator-name']; $example = $persistentData['example-code']; $brief = ''; $full = ''; $lines = explode("\n", $description); if (count($lines) > 0) { $brief = $lines[0]; $full = implode("\n", array_slice($lines, 1)); } $tpl->setVariable('full_class_name', $fullClassName); $tpl->setVariable('class_name', $className); $tpl->setVariable('file_name', $filename); $tpl->setVariable('operator_name', $operatorName); $tpl->setVariable('example_code', $example); $tpl->setVariable('creator_name', $creator); $tpl->setVariable('description_brief', $brief); $tpl->setVariable('description_full', $full); $tpl->setVariable('single_operator', $singleOperator); $tpl->setVariable('use_input', $useInput); $tpl->setVariable('use_output', $useOutput); $tpl->setVariable('parameter_check', $parameterCheck); $content = $tpl->fetch('design:setup/templateoperator_code.tpl'); $contentLength = strlen($content); $mimeType = 'application/octet-stream'; $version = eZPublishSDK::version(); header("Pragma: "); header("Cache-Control: "); header("Content-Length: {$contentLength}"); header("Content-Type: {$mimeType}"); header("X-Powered-By: eZ Publish {$version}"); header("Content-Disposition: attachment; filename={$filename}"); header("Content-Transfer-Encoding: binary"); ob_end_clean(); print $content; fflush(); eZExecution::cleanExit(); }
/** * Prepares a file for Download and terminates the execution. * This method will: * - empty the output buffer * - stop buffering * - stop the active session (in order to allow concurrent browsing while downloading) * * @param string $file Path to the local file * @param bool $isAttachedDownload Determines weather to download the file as an attachment ( download popup box ) or not. * @param string $overrideFilename * @param int $startOffset Offset to start transfer from, in bytes * @param int $length Data size to transfer * * @return bool false if error */ static function download($file, $isAttachedDownload = true, $overrideFilename = false, $startOffset = 0, $length = false) { if (!file_exists($file)) { return false; } ob_end_clean(); eZSession::stop(); self::downloadHeaders($file, $isAttachedDownload, $overrideFilename, $startOffset, $length); self::downloadContent($file, $startOffset, $length); eZExecution::cleanExit(); }
/** * oAuth2 response handler function. Terminates execution after sending the headers. * * @param string $httpHeader The HTTP header to be sent as a response * @param string $location The location to redirect to. No redirection is done if not provided. * * @return void */ function response($httpHeader, $location = null) { header("HTTP/1.1 {$httpHeader}"); if ($location !== null) { // debug stuff: echo "header( \"Location: $location\" );\n"; header("Location: {$location}"); } eZExecution::cleanExit(); }
/** * Throws an error message back to the user. This will stop all execution. * * @param {String} $str Message to send back to user. */ function throwError($str) { echo '{"result":null,"id":null,"error":{"errstr":"' . addslashes($str) . '","errfile":"","errline":null,"errcontext":"","level":"FATAL"}}'; eZDB::checkTransactionCounter(); eZExecution::cleanExit(); }
static function download($file, $isAttachedDownload = true, $overrideFilename = false) { if (file_exists($file)) { $mimeinfo = eZMimeType::findByURL($file); ob_clean(); header('X-Powered-By: eZ Publish'); header('Content-Length: ' . filesize($file)); header('Content-Type: ' . $mimeinfo['name']); // Fixes problems with IE when opening a file directly header("Pragma: "); header("Cache-Control: "); /* Set cache time out to 10 minutes, this should be good enough to work around an IE bug */ header("Expires: " . gmdate('D, d M Y H:i:s', time() + 600) . ' GMT'); if ($overrideFilename) { $mimeinfo['filename'] = $overrideFilename; } if ($isAttachedDownload) { header('Content-Disposition: attachment; filename=' . $mimeinfo['filename']); } else { header('Content-Disposition: inline; filename=' . $mimeinfo['filename']); } header('Content-Transfer-Encoding: binary'); header('Accept-Ranges: bytes'); ob_end_clean(); @readfile($file); eZExecution::cleanExit(); } else { return false; } }
/** * Goes trough the access matching rules and returns the access match. * The returned match is an associative array with: * name => string Name of the siteaccess (same as folder name) * type => int The constant that represent the matching used * uri_part => array(string) List of path elements that was used in start of url for the match * * @since 4.4 * @param eZURI $uri * @param string $host * @param string(numeric) $port * @param string $file Example '/index.php' * @return array */ public static function match(eZURI $uri, $host, $port = 80, $file = '/index.php') { eZDebugSetting::writeDebug('kernel-siteaccess', array('uri' => $uri, 'host' => $host, 'port' => $port, 'file' => $file), __METHOD__); $ini = eZINI::instance(); if ($ini->hasVariable('SiteAccessSettings', 'StaticMatch')) { $match = $ini->variable('SiteAccessSettings', 'StaticMatch'); if ($match != '') { $access = array('name' => $match, 'type' => eZSiteAccess::TYPE_STATIC, 'uri_part' => array()); return $access; } } list($siteAccessList, $order) = $ini->variableMulti('SiteAccessSettings', array('AvailableSiteAccessList', 'MatchOrder')); $access = array('name' => $ini->variable('SiteSettings', 'DefaultAccess'), 'type' => eZSiteAccess::TYPE_DEFAULT, 'uri_part' => array()); if ($order == 'none') { return $access; } $order = $ini->variableArray('SiteAccessSettings', 'MatchOrder'); // Change the default type to eZSiteAccess::TYPE_URI if we're using URI MatchOrder. // This is to keep backward compatiblity with the ezurl operator. ezurl has since // rev 4949 added default siteaccess to generated URLs, even when there is // no siteaccess in the current URL. if (in_array('uri', $order)) { $access['type'] = eZSiteAccess::TYPE_URI; } foreach ($order as $matchprobe) { $name = ''; $type = ''; $match_type = ''; $uri_part = array(); switch ($matchprobe) { case 'servervar': if ($serversiteaccess = eZSys::serverVariable($ini->variable('SiteAccessSettings', 'ServerVariableName'), true)) { $access['name'] = $serversiteaccess; $access['type'] = eZSiteAccess::TYPE_SERVER_VAR; return $access; } else { continue; } break; case 'port': if ($ini->hasVariable('PortAccessSettings', $port)) { $access['name'] = $ini->variable('PortAccessSettings', $port); $access['type'] = eZSiteAccess::TYPE_PORT; return $access; } else { continue; } break; case 'uri': $type = eZSiteAccess::TYPE_URI; $match_type = $ini->variable('SiteAccessSettings', 'URIMatchType'); if ($match_type == 'map') { if ($ini->hasVariable('SiteAccessSettings', 'URIMatchMapItems')) { $match_item = $uri->element(0); $matchMapItems = $ini->variableArray('SiteAccessSettings', 'URIMatchMapItems'); foreach ($matchMapItems as $matchMapItem) { $matchMapURI = $matchMapItem[0]; $matchMapAccess = $matchMapItem[1]; if ($access['name'] == $matchMapAccess and in_array($matchMapAccess, $siteAccessList)) { $uri_part = array($matchMapURI); } if ($matchMapURI == $match_item and in_array($matchMapAccess, $siteAccessList)) { $uri->increase(1); $uri->dropBase(); $access['name'] = $matchMapAccess; $access['type'] = $type; $access['uri_part'] = array($matchMapURI); return $access; } } } } else { if ($match_type == 'element') { $match_index = $ini->variable('SiteAccessSettings', 'URIMatchElement'); $elements = $uri->elements(false); $elements = array_slice($elements, 0, $match_index); $name = implode('_', $elements); $uri_part = $elements; } else { if ($match_type == 'text') { $match_item = $uri->elements(); $matcher_pre = $ini->variable('SiteAccessSettings', 'URIMatchSubtextPre'); $matcher_post = $ini->variable('SiteAccessSettings', 'URIMatchSubtextPost'); } else { if ($match_type == 'regexp') { $match_item = $uri->elements(); $matcher = $ini->variable('SiteAccessSettings', 'URIMatchRegexp'); $match_num = $ini->variable('SiteAccessSettings', 'URIMatchRegexpItem'); } else { continue; } } } } break; case 'host': $type = eZSiteAccess::TYPE_HTTP_HOST; $match_type = $ini->variable('SiteAccessSettings', 'HostMatchType'); $match_item = $host; if ($match_type == 'map') { if ($ini->hasVariable('SiteAccessSettings', 'HostMatchMapItems')) { $matchMapItems = $ini->variableArray('SiteAccessSettings', 'HostMatchMapItems'); foreach ($matchMapItems as $matchMapItem) { $matchMapHost = $matchMapItem[0]; $matchMapAccess = $matchMapItem[1]; if ($matchMapHost == $host) { $access['name'] = $matchMapAccess; $access['type'] = $type; return $access; } } } } else { if ($match_type == 'element') { $match_index = $ini->variable('SiteAccessSettings', 'HostMatchElement'); $match_arr = explode('.', $match_item); $name = $match_arr[$match_index]; } else { if ($match_type == 'text') { $matcher_pre = $ini->variable('SiteAccessSettings', 'HostMatchSubtextPre'); $matcher_post = $ini->variable('SiteAccessSettings', 'HostMatchSubtextPost'); } else { if ($match_type == 'regexp') { $matcher = $ini->variable('SiteAccessSettings', 'HostMatchRegexp'); $match_num = $ini->variable('SiteAccessSettings', 'HostMatchRegexpItem'); } else { continue; } } } } break; case 'host_uri': $type = eZSiteAccess::TYPE_HTTP_HOST_URI; if ($ini->hasVariable('SiteAccessSettings', 'HostUriMatchMapItems')) { $uriString = $uri->elements(); $matchMapItems = $ini->variableArray('SiteAccessSettings', 'HostUriMatchMapItems'); $defaultHostMatchMethod = $ini->variable('SiteAccessSettings', 'HostUriMatchMethodDefault'); foreach ($matchMapItems as $matchMapItem) { $matchHost = $matchMapItem[0]; $matchURI = $matchMapItem[1]; $matchAccess = $matchMapItem[2]; $matchHostMethod = isset($matchMapItem[3]) ? $matchMapItem[3] : $defaultHostMatchMethod; if ($matchURI !== '' && !preg_match("@^{$matchURI}\\b@", $uriString)) { continue; } switch ($matchHostMethod) { case 'strict': $hasHostMatch = $matchHost === $host; break; case 'start': $hasHostMatch = strpos($host, $matchHost) === 0; break; case 'end': $hasHostMatch = strstr($host, $matchHost) === $matchHost; break; case 'part': $hasHostMatch = strpos($host, $matchHost) !== false; break; default: $hasHostMatch = false; eZDebug::writeError("Unknown host_uri host match: {$matchHostMethod}", "access"); break; } if ($hasHostMatch) { if ($matchURI !== '') { $matchURIFolders = explode('/', $matchURI); $uri->increase(count($matchURIFolders)); $uri->dropBase(); $access['uri_part'] = $matchURIFolders; } $access['name'] = $matchAccess; $access['type'] = $type; return $access; } } } break; case 'index': $type = eZSiteAccess::TYPE_INDEX_FILE; $match_type = $ini->variable('SiteAccessSettings', 'IndexMatchType'); $match_item = $file; if ($match_type == 'element') { $match_index = $ini->variable('SiteAccessSettings', 'IndexMatchElement'); $match_pos = strpos($match_item, '.php'); if ($match_pos !== false) { $match_item = substr($match_item, 0, $match_pos); $match_arr = explode('_', $match_item); $name = $match_arr[$match_index]; } } else { if ($match_type == 'text') { $matcher_pre = $ini->variable('SiteAccessSettings', 'IndexMatchSubtextPre'); $matcher_post = $ini->variable('SiteAccessSettings', 'IndexMatchSubtextPost'); } else { if ($match_type == 'regexp') { $matcher = $ini->variable('SiteAccessSettings', 'IndexMatchRegexp'); $match_num = $ini->variable('SiteAccessSettings', 'IndexMatchRegexpItem'); } else { continue; } } } break; default: eZDebug::writeError("Unknown access match: {$matchprobe}", "access"); break; } if ($match_type == 'regexp') { $name = self::matchRegexp($match_item, $matcher, $match_num); } else { if ($match_type == 'text') { $name = self::matchText($match_item, $matcher_pre, $matcher_post); } } if (isset($name) && $name != '') { $nameClean = self::washName($name); if (in_array($nameClean, $siteAccessList)) { if ($nameClean !== $name) { if (!$ini->hasVariable('SiteAccessSettings', 'NormalizeSANames') || $ini->variable('SiteAccessSettings', 'NormalizeSANames') == 'enabled') { $name = $nameClean; if ($ini->hasVariable('SiteAccessSettings', 'RedirectOnNormalize') && $ini->variable('SiteAccessSettings', 'RedirectOnNormalize') == 'enabled') { header($_SERVER['SERVER_PROTOCOL'] . " 301 Moved Permanently"); header("Status: 301 Moved Permanently"); $uriSlice = $uri->URIArray; array_shift($uriSlice); $newUri = $name . '/' . implode('/', $uriSlice); $location = eZSys::indexDir() . "/" . eZURI::encodeIRI($newUri); header("Location: " . $location); eZExecution::cleanExit(); } } } if ($type == eZSiteAccess::TYPE_URI) { if ($match_type == 'element') { $uri->increase($match_index); $uri->dropBase(); } else { if ($match_type == 'regexp') { $uri->setURIString($match_item); } else { if ($match_type == 'text') { $uri->setURIString($match_item); } } } } $access['type'] = $type; $access['name'] = $name; $access['uri_part'] = $uri_part; return $access; } } } return $access; }
static function checkUser(&$siteBasics, &$url) { $http = eZHTTPTool::instance(); if (!$http->hasSessionVariable(self::STEP)) { $http->setSessionVariable(self::STEP, self::STEP_PRE_CHECK_USER_INFO); } $loginStep =& $http->sessionVariable(self::STEP); if ($http->hasSessionVariable(self::FORCE_LOGIN) && $loginStep < self::STEP_PRE_COLLECT_USER_INFO) { $loginStep = self::STEP_PRE_COLLECT_USER_INFO; } switch ($loginStep) { case self::STEP_PRE_CHECK_USER_INFO: $ini = eZINI::instance(); $handlerList = array('standard'); if ($ini->hasVariable('UserSettings', 'LoginHandler')) { $handlerList = $ini->variable('UserSettings', 'LoginHandler'); } if ($http->hasSessionVariable(self::LAST_HANDLER_NAME)) { $http->removeSessionVariable(self::LAST_HANDLER_NAME); } foreach ($handlerList as $handler) { $userObject = eZUserLoginHandler::instance($handler); if ($userObject) { $check = $userObject->checkUser($siteBasics, $url); if ($check === null) { eZUserLoginHandler::sessionCleanup(); return null; } $http->setSessionVariable(self::LAST_CHECK_REDIRECT, $check); $http->setSessionVariable(self::LAST_HANDLER_NAME, $handler); } } $http->setSessionVariable(self::STEP, self::STEP_PRE_COLLECT_USER_INFO); return eZUserLoginHandler::checkUser($siteBasics, $url); break; case self::STEP_PRE_COLLECT_USER_INFO: $http->setSessionVariable(self::STEP, self::STEP_POST_COLLECT_USER_INFO); $handler = null; if ($http->hasSessionVariable(self::LAST_HANDLER_NAME)) { $handlerName = $http->sessionVariable(self::LAST_HANDLER_NAME); $handler = eZUserLoginHandler::instance($handlerName); } if ($handler) { return $handler->preCollectUserInfo(); } else { $redirect =& $http->sessionVariable(self::LAST_CHECK_REDIRECT); if (!$redirect) { $redirect = array('module' => 'user', 'function' => 'login'); } return $redirect; } break; case self::STEP_POST_COLLECT_USER_INFO: $http->setSessionVariable(self::STEP, self::STEP_LOGIN_USER); $handler = null; if ($http->hasSessionVariable(self::LAST_HANDLER_NAME)) { $handlerName = $http->sessionVariable(self::LAST_HANDLER_NAME); $handler = eZUserLoginHandler::instance($handlerName); } if ($handler) { // Use specified login handler to handle Login info input if (!$handler->postCollectUserInfo()) { eZUserLoginHandler::sessionCleanup(); eZHTTPTool::redirect('/'); eZExecution::cleanExit(); } } return eZUserLoginHandler::checkUser($siteBasics, $url); break; case self::STEP_LOGIN_USER: $ini = eZINI::instance(); $handlerList = array('standard'); if ($ini->hasVariable('UserSettings', 'LoginHandler')) { $handlerList = $ini->variable('UserSettings', 'LoginHandler'); } $userInfoArray =& $http->sessionVariable(self::USER_INFO); $http->removeSessionVariable(self::USER_INFO); if ($http->hasSessionVariable(self::FORCE_LOGIN)) { $http->removeSessionVariable(self::FORCE_LOGIN); } $user = null; if (is_array($userInfoArray) and $userInfoArray['login'] and $userInfoArray['password']) { foreach ($handlerList as $handler) { $userObject = eZUserLoginHandler::instance($handler); if ($userObject) { $user = $userObject->loginUser($userInfoArray['login'], $userInfoArray['password']); if (is_subclass_of($user, 'eZUser')) { eZUserLoginHandler::sessionCleanup(); return null; } else { if (is_array($user)) { eZUserLoginHandler::sessionCleanup(); return $user; } } } } } $http->setSessionVariable(self::STEP, self::STEP_PRE_CHECK_USER_INFO); return eZUserLoginHandler::checkUser($siteBasics, $url); break; } }
function datatypeDownload($tpl, &$persistentData, $stepData) { $datatypeName = $persistentData['name']; $classInput = $persistentData['class-input']; $descName = $persistentData['desc-name']; $className = $persistentData['class-name']; $constantName = $persistentData['constant-name']; $creator = $persistentData['creator-name']; $description = $persistentData['description']; $datatypeName = $persistentData['datatype-name']; $filename = strtolower($className) . '.php'; $brief = ''; $full = ''; $lines = explode("\n", $description); if (count($lines) > 0) { $brief = $lines[0]; $full = implode("\n", array_slice($lines, 1)); } $tpl->setVariable('full_class_name', $className); $tpl->setVariable('constant_name', $constantName); $tpl->setVariable('datatype_name', $datatypeName); $tpl->setVariable('desc_name', $descName); $tpl->setVariable('file_name', $filename); $tpl->setVariable('creator_name', $creator); $tpl->setVariable('description_brief', $brief); $tpl->setVariable('description_full', $full); $tpl->setVariable('class_input', $classInput); $content = $tpl->fetch('design:setup/datatype_code.tpl'); $contentLength = strlen($content); $mimeType = 'application/octet-stream'; $version = eZPublishSDK::version(); header("Pragma: "); header("Cache-Control: "); header("Content-Length: {$contentLength}"); header("Content-Type: {$mimeType}"); header("X-Powered-By: eZ Publish {$version}"); header("Content-Disposition: attachment; filename={$filename}"); header("Content-Transfer-Encoding: binary"); ob_end_clean(); print $content; flush(); eZExecution::cleanExit(); }
/** * output the pdf code, streaming it to the browser * the relevant headers are set so that hopefully the browser will recognise it */ function stream($options = '') { // setting the options allows the adjustment of the headers // values at the moment are: // 'Content-Disposition'=>'filename' - sets the filename, though not too sure how well this will // work as in my trial the browser seems to use the filename of the php file with .pdf on the end // 'Accept-Ranges'=>1 or 0 - if this is not set to 1, then this header is not included, off by default // this header seems to have caused some problems despite tha fact that it is supposed to solve // them, so I am leaving it off by default. // 'compress'=> 1 or 0 - apply content stream compression, this is on (1) by default if (!is_array($options)) { $options = array(); } if (isset($options['compress']) && $options['compress'] == 0) { $tmp = $this->output(1); } else { $tmp = $this->output(); } $tmp = ltrim($tmp); ob_clean(); header('Pragma: '); header('Cache-Control: '); /* Set cache time out to 10 seconds, this should be good enough to work around an IE bug */ header("Expires: " . gmdate('D, d M Y H:i:s', time() + 10) . ' GMT'); header('X-Powered-By: eZ Publish'); header('Content-Length: ' . strlen($tmp)); header('Content-Type: application/pdf'); header('Content-Transfer-Encoding: binary'); header('Accept-Ranges: bytes'); ob_end_clean(); echo $tmp; eZExecution::cleanExit(); }
/** * Performs a redirection */ protected function redirect() { $GLOBALS['eZRedirection'] = true; $ini = eZINI::instance(); $automaticRedirect = true; if ($GLOBALS['eZDebugAllowed'] && ($redirUri = $ini->variable('DebugSettings', 'DebugRedirection')) !== 'disabled') { if ($redirUri == "enabled") { $automaticRedirect = false; } else { $uri = eZURI::instance(eZSys::requestURI()); $uri->toBeginning(); foreach ($ini->variableArray("DebugSettings", "DebugRedirection") as $redirUri) { $redirUri = new eZURI($redirUri); if ($redirUri->matchBase($uri)) { $automaticRedirect = false; break; } } } } $redirectURI = eZSys::indexDir(); $moduleRedirectUri = $this->module->redirectURI(); if ($ini->variable('URLTranslator', 'Translation') === 'enabled' && eZURLAliasML::urlTranslationEnabledByUri(new eZURI($moduleRedirectUri))) { $translatedModuleRedirectUri = $moduleRedirectUri; if (eZURLAliasML::translate($translatedModuleRedirectUri, true)) { $moduleRedirectUri = $translatedModuleRedirectUri; if (strlen($moduleRedirectUri) > 0 && $moduleRedirectUri[0] !== '/') { $moduleRedirectUri = '/' . $moduleRedirectUri; } } } if (preg_match('#^(\\w+:)|^//#', $moduleRedirectUri)) { $redirectURI = $moduleRedirectUri; } else { $leftSlash = strlen($redirectURI) > 0 && $redirectURI[strlen($redirectURI) - 1] === '/'; $rightSlash = strlen($moduleRedirectUri) > 0 && $moduleRedirectUri[0] === '/'; if (!$leftSlash && !$rightSlash) { // Both are without a slash, so add one $moduleRedirectUri = '/' . $moduleRedirectUri; } else { if ($leftSlash && $rightSlash) { // Both are with a slash, so we remove one $moduleRedirectUri = substr($moduleRedirectUri, 1); } } $redirectURI .= $moduleRedirectUri; } eZStaticCache::executeActions(); eZDB::checkTransactionCounter(); if ($automaticRedirect) { eZHTTPTool::redirect($redirectURI, array(), $this->module->redirectStatus()); } else { // Make sure any errors or warnings are reported if ($ini->variable('DebugSettings', 'DisplayDebugWarnings') === 'enabled') { if (isset($GLOBALS['eZDebugError']) && $GLOBALS['eZDebugError']) { eZAppendWarningItem(array('error' => array('type' => 'error', 'number' => 1, 'count' => $GLOBALS['eZDebugErrorCount']), 'identifier' => 'ezdebug-first-error', 'text' => ezpI18n::tr('index.php', 'Some errors occurred, see debug for more information.'))); } if (isset($GLOBALS['eZDebugWarning']) && $GLOBALS['eZDebugWarning']) { eZAppendWarningItem(array('error' => array('type' => 'warning', 'number' => 1, 'count' => $GLOBALS['eZDebugWarningCount']), 'identifier' => 'ezdebug-first-warning', 'text' => ezpI18n::tr('index.php', 'Some general warnings occured, see debug for more information.'))); } } $tpl = eZTemplate::factory(); $tpl->setVariable('site', $this->site); $tpl->setVariable('warning_list', !empty($this->warningList) ? $this->warningList : false); $tpl->setVariable('redirect_uri', eZURI::encodeURL($redirectURI)); $templateResult = $tpl->fetch('design:redirect.tpl'); eZDebug::addTimingPoint("Script end"); eZDisplayResult($templateResult); } eZExecution::cleanExit(); }
public function contentBuildResult() { $oldSkipPage = SolrSafeOperatorHelper::getCustomParameter($this->applicationObject->identifier, 'SkipExitPage', 'application'); $skipPage = $oldSkipPage || !$this->exitStrategy(); $this->pushResult('user' , self::user()); $this->pushResult('country', LocaleTool::countryISO3166Code()); if ( $skipPage ) { $_REQUEST['proceed'] = 'proceed'; $_COOKIE[$this->cookieKey()] = '1'; if ( ContextTool::instance()->isMobile() ) $_REQUEST['r'] = 1; } if( isset($_REQUEST['proceed']) && isset($_COOKIE[$this->cookieKey()]) && filter_var($_COOKIE[$this->cookieKey()], FILTER_VALIDATE_INT)) { // proceed to iframe view $this->iframeBuildResult( ); } elseif( isset($_REQUEST['proceed']) ) { // proceed requested but no cookie, we ask again and force redirect to make sure we the proper layout header('Location: '.ContextTool::instance()->domain().$this->applicationLocalized()->applicationUrl()); eZExecution::cleanExit(); } else { // normal exit page vie $isMobile = ContextTool::instance()->isMobile(); $urlToRedirect = isset($_REQUEST['r']) ? trim($_REQUEST['r']) : null; if ($this->isExitApplication() && $this->displayIframe()) { $serverUrl = ContextTool::instance()->domain(); $params = array( 'r' => urlencode($urlToRedirect), 'exit_strategy' => 0, 'display_iframe' => $this->displayIframe(), 'new_window' => $this->newWindow() ); $urlToRedirect = $serverUrl . '/external/exit/?' . http_build_query($params); $this->pushResult('decode_url', false); $this->pushResult('server_url', $serverUrl); } if($isMobile){ if($this->applicationObject()->externalLinkHandler()) { $externalUrl = $this->applicationObject()->externalLinkHandler()->getNodeUrl( $this->node ); $urlToRedirect = isset($externalUrl) ? $externalUrl : $urlToRedirect ; if(SolrSafeOperatorHelper::getCustomParameter($this->applicationObject->identifier, 'usePostMethod', 'application' )){ $url = $this->applicationObject()->externalLinkHandler()->getNodeUrl( $this->node ); $url = $this->getDeeplink( $url ); if ($url == null && isset($_REQUEST['r'])) { $url = urldecode($_REQUEST['r']); } $url = in_array('arg', array_keys($this->_params['UserParameters'])) ? $url . $this->_params['UserParameters']['arg'] : $url; $this->pushResult('postParams', $url); } } else { $urlToRedirect = '/bad_config'; } } $this->pushResult('back_url', ContextTool::instance()->backUrl()); $this->pushResult('url', $urlToRedirect); $this->pushResult('deeplink', urlencode( $this->getDeeplink() )); // Because we are passing boolean parameters to final URL, we need to make isset check. if ( $this->isDeeplinkApplication() || $this->isExitApplication() ) { if ( isset( $_GET['display_iframe'] ) ) { $this->pushResult('display_iframe', $this->displayIframe()); } if ( isset( $_GET['new_window'] ) ) { $this->pushResult('new_window', $this->newWindow()); } if ( isset( $_GET['exit_strategy'] ) ) { $this->pushResult('exit_strategy', $this->exitStrategy()); } } } if($this->node && $this->node->attribute('url_alias') != "") { $this->pushResult('article_url', end(explode("/", $this->node->attribute('url_alias')))); /* @type $pfDM eZContentObjectAttribute[] */ $pf = NodeTool::getPublisherNodeFromNode( $this->node ); $pfDM = $pf->DataMap(); $pfID = PublisherFolderTool::getPathToIDMapping( $pfDM['path']->content() ); $this->pushResult( 'pfid', $pfID['pfid'] . '/' ); } $oldOpenInNewWindow = SolrSafeOperatorHelper::getCustomParameter($this->applicationObject()->identifier, 'openInNewWindow', 'application'); $openInNewWindow = $this->newWindow() || $oldOpenInNewWindow; $this->pushResult('application', $this->applicationObject); $this->pushResult('open_in_new_window', $openInNewWindow); $this->pushResult('cookie_key', $this->cookieKey()); $this->pushResult('node', $this->node); if( SolrSafeOperatorHelper::featureIsActive( 'GoogleAnalytics' ) ) { $this->pushResult( 'gtm_variables', $this->getGTMTags( $this->node ) ); if( $this->node ) { $publisherNodeId = PublisherFolderTool::getPublisherNodeIdFromArticleNode($this->node); if ($publisherNodeId) { $publisherInfos = PublisherFolderTool::getNodeIdToPathMapping( $publisherNodeId ); $publisherPath = $publisherInfos['path']; $this->pushResult( 'publisher', $this->applicationLocalized()->getPublisherFolderFromPath( $publisherPath ) ); } } } }
public function gfo() { echo $this->getFocusOn(); eZExecution::cleanExit(); }
/** * Handles redirection to the mobile optimized interface * */ public function redirect() { $http = eZHTTPTool::instance(); $currentSiteAccess = eZSiteAccess::current(); if ($http->hasGetVariable('notmobile')) { setcookie('eZMobileDeviceDetect', 1, time() + (int) eZINI::instance()->variable('SiteAccessSettings', 'MobileDeviceDetectCookieTimeout'), '/'); $http->redirect(eZSys::indexDir()); eZExecution::cleanExit(); } if (!isset($_COOKIE['eZMobileDeviceDetect']) && !in_array($currentSiteAccess['name'], eZINI::instance()->variable('SiteAccessSettings', 'MobileSiteAccessList'))) { $currentUrl = eZSys::serverURL() . eZSys::requestURI(); $redirectUrl = eZINI::instance()->variable('SiteAccessSettings', 'MobileSiteAccessURL'); // Do not redirect if already on the redirect url if (strpos($currentUrl, $redirectUrl) !== 0) { // Default siteaccess name needs to be removed from the uri when redirecting $uri = explode('/', ltrim(eZSys::requestURI(), '/')); if (array_shift($uri) == $currentSiteAccess['name']) { $http->redirect($redirectUrl . '/' . implode('/', $uri)); } else { $http->redirect($redirectUrl . eZSys::requestURI()); } } eZExecution::cleanExit(); } }
/** * Sets the module to redirect at the end of the execution * * @param string $uri the URI to redirect to * * @see setRedirectURI(), setExitStatus() * * @return void */ function redirectTo($uri) { $originalURI = $uri; $uri = preg_replace("#(^.*)(/+)\$#", "\$1", $uri); if (strlen($originalURI) != 0 and strlen($uri) == 0) { $uri = '/'; } $urlComponents = parse_url($uri); // eZSys::hostname() can contain port if present. // So parsing it with parse_url() as well to only get host. $currentHostname = eZSys::hostname(); $currentHostnameParsed = parse_url($currentHostname, PHP_URL_HOST); $currentHostname = $currentHostnameParsed ? $currentHostnameParsed : $currentHostname; if (isset($urlComponents['host']) && $urlComponents['host'] !== $currentHostname) { $allowedHosts = $this->getAllowedRedirectHosts(); if (!isset($allowedHosts[$urlComponents['host']])) { // Non-authorized host, return only the URI (without host) + query string and fragment if present. eZDebug::writeError("Redirection requested on non-authorized host '{$urlComponents['host']}'"); header($_SERVER['SERVER_PROTOCOL'] . ' 403 Forbidden'); echo "Redirection requested on non-authorized host"; eZDB::checkTransactionCounter(); eZExecution::cleanExit(); } } $this->RedirectURI = $uri; $this->setExitStatus(self::STATUS_REDIRECT); }
/** * Handles redirection to the mobile optimized interface * */ public function redirect() { $http = eZHTTPTool::instance(); $currentSiteAccess = eZSiteAccess::current(); if ( $http->hasGetVariable( 'notmobile' ) ) { setcookie( 'eZMobileDeviceDetect', 1, time() + (int)eZINI::instance()->variable( 'SiteAccessSettings', 'MobileDeviceDetectCookieTimeout' ), '/' ); $http->redirect( eZSys::indexDir() ); eZExecution::cleanExit(); } if ( !isset( $_COOKIE['eZMobileDeviceDetect'] ) && !in_array( $currentSiteAccess['name'], eZINI::instance()->variable( 'SiteAccessSettings', 'MobileSiteAccessList' ) ) ) { $http->redirect( eZINI::instance()->variable( 'SiteAccessSettings', 'MobileSiteAccessURL' ) ); eZExecution::cleanExit(); } }
function contentPDFPassthrough($cacheFile) { $file = eZClusterFileHandler::instance($cacheFile); if (!$file->exists()) { eZDebug::writeError("Cache-file for pdf doesn't exist", 'content::pdf::contentPDFPassthrough'); return; } $file->fetch(true); ob_clean(); header('Pragma: '); header('Cache-Control: '); /* Set cache time out to 10 seconds, this should be good enough to work around an IE bug */ header("Expires: " . gmdate('D, d M Y H:i:s', time() + 10) . ' GMT'); header('X-Powered-By: ' . eZPublishSDK::EDITION); header('Content-Length: ' . $file->size()); header('Content-Type: application/pdf'); header('Content-Transfer-Encoding: binary'); header('Accept-Ranges: bytes'); ob_end_clean(); $fp = @fopen($cacheFile, 'r'); @fpassthru($fp); fclose($fp); eZExecution::cleanExit(); }
/** * Returns a shared instance of the eZUser class pr $id value. * If user can not be fetched, then anonymous user is returned and * a warning trown, if anonymous user can not be fetched, then NoUser * is returned and another warning is thrown. * * @param int|false $id On false: Gets current user id from session * or from {@link eZUser::anonymousId()} if not set. * @return eZUser */ static function instance($id = false) { if (!empty($GLOBALS["eZUserGlobalInstance_{$id}"])) { return $GLOBALS["eZUserGlobalInstance_{$id}"]; } $userId = $id; $currentUser = null; $http = eZHTTPTool::instance(); $anonymousUserID = self::anonymousId(); $sessionHasStarted = eZSession::hasStarted(); // If not specified get the current user if ($userId === false) { if ($sessionHasStarted) { $userId = $http->sessionVariable('eZUserLoggedInID'); if (!is_numeric($userId)) { $userId = $anonymousUserID; eZSession::setUserID($userId); $http->setSessionVariable('eZUserLoggedInID', $userId); } } else { $userId = $anonymousUserID; eZSession::setUserID($userId); } } // Check user cache (this effectivly fetches user from cache) // user not found if !isset( isset( $userCache['info'][$userId] ) ) $userCache = self::getUserCacheByUserId($userId); if (isset($userCache['info'][$userId])) { $userArray = $userCache['info'][$userId]; if (is_numeric($userArray['contentobject_id'])) { $currentUser = new eZUser($userArray); $currentUser->setUserCache($userCache); } } $ini = eZINI::instance(); // Check if: // - the user has not logged out, // - the user is not logged in, // - and if a automatic single sign on plugin is enabled. if (!self::$userHasLoggedOut && is_object($currentUser) && !$currentUser->isRegistered()) { $ssoHandlerArray = $ini->variable('UserSettings', 'SingleSignOnHandlerArray'); if (!empty($ssoHandlerArray)) { $ssoUser = false; foreach ($ssoHandlerArray as $ssoHandler) { $className = 'eZ' . $ssoHandler . 'SSOHandler'; if (class_exists($className)) { $impl = new $className(); $ssoUser = $impl->handleSSOLogin(); // If a user was found via SSO, then use it if ($ssoUser !== false) { $currentUser = $ssoUser; $userId = $currentUser->attribute('contentobject_id'); $userInfo = array(); $userInfo[$userId] = array('contentobject_id' => $userId, 'login' => $currentUser->attribute('login'), 'email' => $currentUser->attribute('email'), 'password_hash' => $currentUser->attribute('password_hash'), 'password_hash_type' => $currentUser->attribute('password_hash_type')); eZSession::setUserID($userId); $http->setSessionVariable('eZUserLoggedInID', $userId); eZUser::updateLastVisit($userId); eZUser::setCurrentlyLoggedInUser($currentUser, $userId); eZHTTPTool::redirect(eZSys::wwwDir() . eZSys::indexFile(false) . eZSys::requestURI() . eZSys::queryString(), array(), 302); eZExecution::cleanExit(); } } else { eZDebug::writeError("Undefined ssoHandler class: {$className}", __METHOD__); } } } } if ($userId != $anonymousUserID) { $sessionInactivityTimeout = $ini->variable('Session', 'ActivityTimeout'); if (!isset($GLOBALS['eZSessionIdleTime'])) { eZUser::updateLastVisit($userId); } else { $sessionIdle = $GLOBALS['eZSessionIdleTime']; if ($sessionIdle > $sessionInactivityTimeout) { eZUser::updateLastVisit($userId); } } } if (!$currentUser) { $currentUser = eZUser::fetch(self::anonymousId()); eZDebug::writeWarning('User not found, returning anonymous'); } if (!$currentUser) { $currentUser = new eZUser(array('id' => -1, 'login' => 'NoUser')); eZDebug::writeWarning('Anonymous user not found, returning NoUser'); } $GLOBALS["eZUserGlobalInstance_{$id}"] = $currentUser; return $currentUser; }
public static function writeEndpoints() { self::init(); echo '<pre>'; foreach (self::$functionList as $className => $classFunctions) { foreach ($classFunctions as $function) { echo 'FunctionList[]=' . $className . '_' . $function . "\n"; } } echo "\n"; foreach (self::$endpoints as $endPoint => $className) { foreach (self::$functionList[$className] as $function) { $namespace = array('class' => $className); if (self::$classes[$endPoint] !== false) { $namespace['function'] = $function; } echo '[ezjscServer_' . implode('_', $namespace) . ']' . "\n"; echo 'Class=' . $endPoint . "\n\n"; $namespace['function'] = $function; echo 'Functions[]=' . implode('_', $namespace) . "\n\n"; } } echo '</pre>'; \eZExecution::cleanExit(); }
<?php /** * File containing the pixelate tool handler * * @copyright Copyright (C) eZ Systems AS. * @license For full copyright and license information view LICENSE file distributed with this source code. * @version //autogentag// * @package ezie */ $prepare_action = new eZIEImagePreAction(); $http = eZHTTPTool::instance(); $region = null; if ($prepare_action->hasRegion()) { $region = $prepare_action->getRegion(); } // retrieve image dimensions $analyzer = new eZIEImageAnalyzer($prepare_action->getImagePath()); $imageconverter = new eZIEezcImageConverter(eZIEImageToolPixelate::filter($analyzer->data->width, $analyzer->data->height, $region)); $imageconverter->perform($prepare_action->getImagePath(), $prepare_action->getNewImagePath()); eZIEImageToolResize::doThumb($prepare_action->getNewImagePath(), $prepare_action->getNewThumbnailPath()); echo (string) $prepare_action; eZExecution::cleanExit();
/** * Sends a http request to the specified host. Using https:// requires compiled in OpenSSL support. * * @param string $uri http/https address or only path to send request to current eZ Publish instance * examples: http://ez.no, https://secure.ez.no or content/view/full/2 * @param int|false $port Which port to connect to, default 80, uses port in $uri if present when $port = false * @param array|false $postParameters Optional post parameters array, if no post parameters are present, a GET request will be sent * @param string $userAgent User agent string, default will be 'eZ Publish' * @param bool $passthrough Will send result directly to client, default: true * @param array $cookies Optional hash of cookie name => values to add to http header * @return string|false String if http request, or false if an error occurs. * If $passthrough = true, program will end here and send result directly to client. */ static function sendHTTPRequest($uri, $port = false, $postParameters = false, $userAgent = 'eZ Publish', $passthrough = true, array $cookies = array()) { preg_match("/^((http[s]?:\\/\\/)([a-zA-Z0-9_.-]+)(\\:(d+))?)?([\\/]?[~]?(\\.?[^.]+[~]?)*)/i", $uri, $matches); $protocol = $matches[2]; $host = $matches[3]; $uriPort = $matches[5]; $path = $matches[6]; // Use port from uri if set and port parameter evaluates to false if ($uriPort && !$port) { $port = $uriPort; } else { if (!$port) { $port = 80; } } if (!$path) { $path = '/'; } $data = ''; if ($postParameters) { $method = 'POST'; foreach ($postParameters as $paramName => $paramData) { if (!is_array($paramData)) { if ($data !== '') { $data .= '&'; } $data .= urlencode($paramName) . '=' . urlencode($paramData); } else { foreach ($paramData as $value) { if ($data !== '') { $data .= '&'; } $data .= urlencode($paramName) . '[]=' . urlencode($value); } } } } else { $method = 'GET'; } if (!$host) { $host = $_SERVER['HTTP_HOST']; $filename = $host; if ($path[0] != '/') { $path = $_SERVER['SCRIPT_NAME'] . '/' . $path; } else { $path = $_SERVER['SCRIPT_NAME'] . $path; } } else { if (!$protocol || $protocol == 'https://') { $filename = 'ssl://' . $host; } else { $filename = 'tcp://' . $host; } } // make sure we have a valid hostname or call to fsockopen() will fail $parsedUrl = parse_url($filename); $ip = isset($parsedUrl['host']) ? gethostbyname($parsedUrl['host']) : ''; $checkIP = ip2long($ip); if ($checkIP == -1 || $checkIP === false) { return false; } $fp = fsockopen($filename, $port); // make sure we have a valid stream resource or calls to other file // functions will fail if (!$fp) { return false; } $cookieStr = ''; foreach ($cookies as $name => $value) { if ($cookieStr === '') { $cookieStr = "Cookie: {$name}={$value}"; } else { $cookieStr .= "; {$name}={$value}"; } } $usePort = $port != 80 && $protocol === 'http://' && ($port != 443 && $protocol === 'https://'); $request = $method . ' ' . $path . ' ' . 'HTTP/1.1' . "\r\n" . "Host: {$host}" . ($usePort ? ":{$port}" : '') . "\r\n" . "Accept: */*\r\n" . "Content-type: application/x-www-form-urlencoded\r\n" . "Content-length: " . strlen($data) . "\r\n" . $cookieStr . "User-Agent: {$userAgent}\r\n" . "Pragma: no-cache\r\n" . "Connection: close\r\n\r\n"; fputs($fp, $request); if ($method == 'POST') { fputs($fp, $data); } $buf = ''; if ($passthrough) { ob_end_clean(); $header = true; $character = ''; while ($header) { $buffer = $character; while (!feof($fp)) { $character = fgetc($fp); if ($character == "\r") { fgetc($fp); $character = fgetc($fp); if ($character == "\r") { fgetc($fp); $header = false; } break; } else { $buffer .= $character; } } header($buffer); } header('Content-Location: ' . $protocol . $host . ($usePort ? ":{$port}" : '') . $path); fpassthru($fp); eZExecution::cleanExit(); } else { $buf = ''; while (!feof($fp)) { $buf .= fgets($fp, 128); } } fclose($fp); return $buf; }