public function __construct() { $params = IMUtil::getFromParamsPHPFile(array("oAuthClientID", "oAuthClientSecret", "oAuthRedirect", "oAuthProvider"), true); if ($params === false) { $this->errorMessage[] = "Wrong Paramters"; $this->isActive = false; return; } $this->isActive = false; $this->provider = "unspecified"; switch (strtolower($params["oAuthProvider"])) { case "google": $this->baseURL = 'https://accounts.google.com/o/oauth2/auth'; // $this->getTokenURL = 'https://accounts.google.com/o/oauth2/token'; $this->getTokenURL = 'https://www.googleapis.com/oauth2/v4/token'; $this->getInfoURL = 'https://www.googleapis.com/plus/v1/people/me/openIdConnect'; $this->infoScope = array('openid', 'profile', 'email'); /* Set up for Google * 1. Go to https://console.developers.google.com. * 2. Create a project. */ $this->isActive = true; $this->provider = "Google"; break; default: break; } $this->clientId = $params["oAuthClientID"]; $this->clientSecret = $params["oAuthClientSecret"]; $this->redirectURL = $params["oAuthRedirect"]; }
public function protectCSRF() { /* * Prevent CSRF Attack with XMLHttpRequest * http://d.hatena.ne.jp/hasegawayosuke/20130302/p1 */ $params = IMUtil::getFromParamsPHPFile(array('webServerName'), true); $webServerName = $params['webServerName']; if ($webServerName === '' || $webServerName === array() || $webServerName === array('')) { $webServerName = NULL; } if (isset($_SERVER['HTTP_X_FROM'])) { $from = parse_url($_SERVER['HTTP_X_FROM']); $fromPort = isset($from['port']) ? ':' . $from['port'] : ''; if ($fromPort === '' && $from['scheme'] === 'http') { $fromPort = ':80'; } else { if ($fromPort === '' && $from['scheme'] === 'https') { $fromPort = ':443'; } } } if (isset($_SERVER['HTTP_ORIGIN'])) { $origin = parse_url($_SERVER['HTTP_ORIGIN']); $originPort = isset($origin['port']) ? ':' . $origin['port'] : ''; if ($originPort === '' && $origin['scheme'] === 'http') { $originPort = ':80'; } else { if ($originPort === '' && $origin['scheme'] === 'https') { $originPort = ':443'; } } } if (isset($_SERVER['HTTP_HOST']) && isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest' && isset($_SERVER['HTTP_X_FROM']) && (!isset($_SERVER['HTTP_ORIGIN']) || $from['scheme'] . '://' . $from['host'] . $fromPort === $origin['scheme'] . '://' . $origin['host'] . $originPort)) { $host = $_SERVER['HTTP_HOST']; if (is_null($webServerName)) { return TRUE; } if (is_array($webServerName)) { foreach ($webServerName as $name) { if ($this->checkHost($host, $name) === TRUE) { return TRUE; } } } else { if ($this->checkHost($host, $webServerName) === TRUE) { return TRUE; } } } return FALSE; }
/** * @param $options * @param null $access * @param bool $bypassAuth */ function processingRequest($access = null, $bypassAuth = false) { $this->logger->setDebugMessage("[processingRequest]", 2); $options = $this->dbSettings->getAuthentication(); $this->outputOfProcessing = array(); $messageClass = IMUtil::getMessageClassInstance(); /* Aggregation Judgement */ $isSelect = $this->dbSettings->getAggregationSelect(); $isFrom = $this->dbSettings->getAggregationFrom(); $isGroupBy = $this->dbSettings->getAggregationGroupBy(); $isDBSupport = $this->dbClass->isSupportAggregation(); if (!$isDBSupport && ($isSelect || $isFrom || $isGroupBy)) { $this->logger->setErrorMessage($messageClass->getMessageAs(1042)); $access = "do nothing"; } else { if ($isDBSupport && ($isSelect && !$isFrom || !$isSelect && $isFrom)) { $this->logger->setErrorMessage($messageClass->getMessageAs(1043)); $access = "do nothing"; } else { if ($isDBSupport && $isSelect && $isFrom && in_array($access, array("update", "new", "create", "delete", "copy"))) { $this->logger->setErrorMessage($messageClass->getMessageAs(1044)); $access = "do nothing"; } } } // Authentication and Authorization $tableInfo = $this->dbSettings->getDataSourceTargetArray(); $access = is_null($access) ? $_POST['access'] : $access; $access = $access == "select" || $access == "load" ? "read" : $access; $this->dbSettings->setRequireAuthentication(false); $this->dbSettings->setRequireAuthorization(false); $this->dbSettings->setDBNative(false); if (!is_null($options) || $access == 'challenge' || $access == 'changepassword' || isset($tableInfo['authentication']) && (isset($tableInfo['authentication']['all']) || isset($tableInfo['authentication'][$access]))) { $this->dbSettings->setRequireAuthorization(true); $this->dbSettings->setDBNative(false); if (isset($options['user']) && $options['user'][0] == 'database_native') { $this->dbSettings->setDBNative(true); } } if (!$bypassAuth && $this->dbSettings->getRequireAuthorization()) { // Authentication required if (strlen($this->paramAuthUser) == 0 || strlen($this->paramResponse) == 0) { // No username or password $access = "do nothing"; $this->dbSettings->setRequireAuthentication(true); } // User and Password are suppried but... if ($access != 'challenge') { // Not accessing getting a challenge. if ($this->dbSettings->isDBNative()) { list($password, $challenge) = $this->decrypting($this->paramCryptResponse); if ($password !== false) { if (!$this->checkChallenge($challenge, $this->clientId)) { $access = "do nothing"; $this->dbSettings->setRequireAuthentication(true); } else { $this->dbSettings->setUserAndPasswordForAccess($this->paramAuthUser, $password); $this->logger->setDebugMessage("[checkChallenge] returns true.", 2); } } else { $this->logger->setDebugMessage("Can't decrypt."); $access = "do nothing"; $this->dbSettings->setRequireAuthentication(true); } } else { $noAuthorization = true; $authorizedGroups = $this->dbClass->getAuthorizedGroups($access); $authorizedUsers = $this->dbClass->getAuthorizedUsers($access); $this->logger->setDebugMessage(str_replace("\n", "", "contextName={$access}/access={$this->dbSettings->getDataSourceName()}/" . "authorizedUsers=" . var_export($authorizedUsers, true) . "/authorizedGroups=" . var_export($authorizedGroups, true)), 2); if (count($authorizedUsers) == 0 && count($authorizedGroups) == 0) { $noAuthorization = false; } else { $signedUser = $this->dbClass->authSupportUnifyUsernameAndEmail($this->dbSettings->getCurrentUser()); if (in_array($signedUser, $authorizedUsers)) { $noAuthorization = false; } else { if (count($authorizedGroups) > 0) { $belongGroups = $this->dbClass->authSupportGetGroupsOfUser($signedUser); $this->logger->setDebugMessage($signedUser . "=belongGroups=" . var_export($belongGroups, true), 2); if (count(array_intersect($belongGroups, $authorizedGroups)) != 0) { $noAuthorization = false; } } } } if ($noAuthorization) { $this->logger->setDebugMessage("Authorization doesn't meet the settings."); $access = "do nothing"; $this->dbSettings->setRequireAuthentication(true); } $signedUser = $this->dbClass->authSupportUnifyUsernameAndEmail($this->paramAuthUser); $authSucceed = false; if ($this->checkAuthorization($signedUser, $this->paramResponse, $this->clientId)) { $this->logger->setDebugMessage("IM-built-in Authentication succeed."); $authSucceed = true; } else { $ldap = new LDAPAuth(); $ldap->setLogger($this->logger); if ($ldap->isActive) { list($password, $challenge) = $this->decrypting($this->paramCryptResponse); if ($ldap->bindCheck($signedUser, $password)) { $this->logger->setDebugMessage("LDAP Authentication succeed."); $authSucceed = true; $this->addUser($signedUser, $password, true); } } } if (!$authSucceed) { $this->logger->setDebugMessage("Authentication doesn't meet valid.{$signedUser}/{$this->paramResponse}/{$this->clientId}"); // Not Authenticated! $access = "do nothing"; $this->dbSettings->setRequireAuthentication(true); } } } } // Come here access=challenge or authenticated access switch ($access) { case 'describe': $result = $this->dbClass->getSchema($this->dbSettings->getDataSourceName()); $this->outputOfProcessing['dbresult'] = $result; $this->outputOfProcessing['resultCount'] = 0; $this->outputOfProcessing['totalCount'] = 0; break; case 'read': case 'select': $result = $this->readFromDB(); if (isset($tableInfo['protect-reading']) && is_array($tableInfo['protect-reading'])) { $recordCount = count($result); for ($index = 0; $index < $recordCount; $index++) { foreach ($result[$index] as $field => $value) { if (in_array($field, $tableInfo['protect-reading'])) { $result[$index][$field] = "[protected]"; } } } } $this->outputOfProcessing['dbresult'] = $result; $this->outputOfProcessing['resultCount'] = $this->countQueryResult(); $this->outputOfProcessing['totalCount'] = $this->getTotalCount(); break; case 'update': if (isset($tableInfo['protect-writing']) && is_array($tableInfo['protect-writing'])) { $fieldArray = array(); $valueArray = array(); $counter = 0; $fieldValues = $this->dbSettings->getValue(); foreach ($this->dbSettings->getFieldsRequired() as $field) { if (!in_array($field, $tableInfo['protect-writing'])) { $fieldArray[] = $field; $valueArray[] = $fieldValues[$counter]; } $counter++; } $this->dbSettings->setFieldsRequired($fieldArray); $this->dbSettings->setValue($valueArray); } $this->updateDB(); break; case 'new': case 'create': $result = $this->createInDB($this->dbSettings->getDataSourceName(), $bypassAuth); $this->outputOfProcessing['newRecordKeyValue'] = $result; $this->outputOfProcessing['dbresult'] = $this->dbClass->updatedRecord(); break; case 'delete': $this->deleteFromDB($this->dbSettings->getDataSourceName()); break; case 'copy': $result = $this->copyInDB($this->dbSettings->getDataSourceName()); $this->outputOfProcessing['newRecordKeyValue'] = $result; $this->outputOfProcessing['dbresult'] = $this->dbClass->updatedRecord(); break; case 'challenge': break; case 'changepassword': if (isset($_POST['newpass'])) { $changeResult = $this->changePassword($this->paramAuthUser, $_POST['newpass']); $this->outputOfProcessing['changePasswordResult'] = $changeResult ? true : false; } else { $this->outputOfProcessing['changePasswordResult'] = false; } break; case 'unregister': if (!is_null($this->dbSettings->notifyServer) && $this->clientPusherAvailable) { $tableKeys = null; if (isset($_POST['pks'])) { $tableKeys = json_decode($_POST['pks'], true); } $this->dbSettings->notifyServer->unregister($_POST['notifyid'], $tableKeys); } break; } if ($this->logger->getDebugLevel() !== false) { $fInfo = $this->getFieldInfo($this->dbSettings->getDataSourceName()); if ($fInfo != null) { foreach ($this->dbSettings->getFieldsRequired() as $fieldName) { if (!$this->dbClass->isContainingFieldName($fieldName, $fInfo)) { $this->logger->setErrorMessage($messageClass->getMessageAs(1033, array($fieldName))); } } } } }
public function generateInitialJSCode($datasource, $options, $dbspecification, $debug) { $q = '"'; $generatedPrivateKey = null; $passPhrase = null; $browserCompatibility = null; $scriptPathPrefix = null; $scriptPathSuffix = null; $oAuthProvider = null; $oAuthClientID = null; $oAuthRedirect = null; $dbClass = null; $params = IMUtil::getFromParamsPHPFile(array("generatedPrivateKey", "passPhrase", "browserCompatibility", "scriptPathPrefix", "scriptPathSuffix", "oAuthProvider", "oAuthClientID", "oAuthRedirect", "passwordPolicy", "documentRootPrefix", "dbClass", "nonSupportMessageId", "valuesForLocalContext"), true); $generatedPrivateKey = $params["generatedPrivateKey"]; $passPhrase = $params["passPhrase"]; $browserCompatibility = $params["browserCompatibility"]; $scriptPathPrefix = $params["scriptPathPrefix"]; $scriptPathSuffix = $params["scriptPathSuffix"]; $oAuthProvider = $params["oAuthProvider"]; $oAuthClientID = $params["oAuthClientID"]; $oAuthRedirect = $params["oAuthRedirect"]; $passwordPolicy = $params["passwordPolicy"]; $dbClass = $params["dbClass"]; $nonSupportMessageId = $params["nonSupportMessageId"]; $documentRootPrefix = is_null($params["documentRootPrefix"]) ? "" : $params["documentRootPrefix"]; $valuesForLocalContext = $params["valuesForLocalContext"]; /* * Read the JS programs regarding by the developing or deployed. */ $currentDir = dirname(__FILE__) . DIRECTORY_SEPARATOR; if (file_exists($currentDir . 'INTER-Mediator-Lib.js')) { echo $this->combineScripts($currentDir); } else { readfile($currentDir . 'INTER-Mediator.js'); } /* * Generate the link to the definition file editor */ $relativeToDefFile = ''; $editorPath = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'INTER-Mediator-Support'; $defFilePath = $_SERVER['DOCUMENT_ROOT'] . $_SERVER['SCRIPT_NAME']; while (strpos($defFilePath, $editorPath) !== 0 && strlen($editorPath) > 1) { $editorPath = dirname($editorPath); $relativeToDefFile .= '..' . DIRECTORY_SEPARATOR; } $relativeToDefFile .= substr($defFilePath, strlen($editorPath) + 1); $editorPath = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'INTER-Mediator-Support' . DIRECTORY_SEPARATOR . 'defedit.html'; if (file_exists($editorPath)) { $relativeToEditor = substr($editorPath, strlen($_SERVER['DOCUMENT_ROOT'])); $this->generateAssignJS("INTERMediatorOnPage.getEditorPath", "function(){return {$q}{$relativeToEditor}?target={$relativeToDefFile}{$q};}"); } else { $this->generateAssignJS("INTERMediatorOnPage.getEditorPath", "function(){return '';}"); } /* * from db-class, determine the default key field string */ $defaultKey = null; $dbClassName = 'DB_' . (isset($dbspecification['db-class']) ? $dbspecification['db-class'] : (!is_null($dbClass) ? $dbClass : '')); if ($dbClassName !== 'DB_DefEditor' && $dbClassName !== 'DB_PageEditor') { require_once "{$dbClassName}.php"; } else { require_once dirname(__FILE__) . "/INTER-Mediator-Support/{$dbClassName}.php"; } if ((double) phpversion() < 5.3) { $dbInstance = new $dbClassName(); if ($dbInstance != null) { $defaultKey = $dbInstance->getDefaultKey(); } } else { $defaultKey = call_user_func(array($dbClassName, 'defaultKey')); } if ($defaultKey !== null) { $items = array(); foreach ($datasource as $context) { if (!array_key_exists('key', $context)) { $context['key'] = $defaultKey; } $items[] = $context; } $datasource = $items; } /* * Determine the uri of myself */ if (isset($callURL)) { $pathToMySelf = $callURL; } else { if (isset($scriptPathPrefix) || isset($scriptPathSuffix)) { $pathToMySelf = (isset($scriptPathPrefix) ? $scriptPathPrefix : '') . filter_var($_SERVER['SCRIPT_NAME']) . (isset($scriptPathSufix) ? $scriptPathSuffix : ''); } else { $pathToMySelf = filter_var($_SERVER['SCRIPT_NAME']); } } $pathToIMRootDir = ''; if (function_exists('mb_ereg_replace')) { $pathToIMRootDir = mb_ereg_replace(mb_ereg_replace("\\x5c", "/", "^{$documentRootPrefix}" . filter_var($_SERVER['DOCUMENT_ROOT'])), "", mb_ereg_replace("\\x5c", "/", dirname(__FILE__))); } $this->generateAssignJS("INTERMediatorOnPage.getEntryPath", "function(){return {$q}{$pathToMySelf}{$q};}"); $this->generateAssignJS("INTERMediatorOnPage.getIMRootPath", "function(){return {$q}{$pathToIMRootDir}{$q};}"); $this->generateAssignJS("INTERMediatorOnPage.getDataSources", "function(){return ", arrayToJSExcluding($datasource, '', array('password')), ";}"); $this->generateAssignJS("INTERMediatorOnPage.getOptionsAliases", "function(){return ", arrayToJS(isset($options['aliases']) ? $options['aliases'] : array(), ''), ";}"); $this->generateAssignJS("INTERMediatorOnPage.getOptionsTransaction", "function(){return ", arrayToJS(isset($options['transaction']) ? $options['transaction'] : '', ''), ";}"); $this->generateAssignJS("INTERMediatorOnPage.getDBSpecification", "function(){return ", arrayToJSExcluding($dbspecification, '', array('dsn', 'option', 'database', 'user', 'password', 'server', 'port', 'protocol', 'datatype')), ";}"); $isEmailAsUsernae = isset($options['authentication']) && isset($options['authentication']['email-as-username']) && $options['authentication']['email-as-username'] === true; $this->generateAssignJS("INTERMediatorOnPage.isEmailAsUsername", $isEmailAsUsernae ? "true" : "false"); $messageClass = IMUtil::getMessageClassInstance(); $this->generateAssignJS("INTERMediatorOnPage.getMessages", "function(){return ", arrayToJS($messageClass->getMessages(), ''), ";}"); if (isset($options['browser-compatibility'])) { $browserCompatibility = $options['browser-compatibility']; } foreach ($browserCompatibility as $browser => $browserInfo) { if (strtolower($browser) !== $browser) { $browserCompatibility[strtolower($browser)] = $browserCompatibility[$browser]; unset($browserCompatibility[$browser]); } } $this->generateAssignJS("INTERMediatorOnPage.browserCompatibility", "function(){return ", arrayToJS($browserCompatibility, ''), ";}"); $remoteAddr = filter_var($_SERVER['REMOTE_ADDR']); if (is_null($remoteAddr) || $remoteAddr === FALSE) { $remoteAddr = '0.0.0.0'; } $clientIdSeed = time() + $remoteAddr + mt_rand(); $randomSecret = mt_rand(); $clientId = hash_hmac('sha256', $clientIdSeed, $randomSecret); $this->generateAssignJS("INTERMediatorOnPage.clientNotificationIdentifier", "function(){return ", arrayToJS($clientId, ''), ";}"); if ($nonSupportMessageId != "") { $this->generateAssignJS("INTERMediatorOnPage.nonSupportMessageId", "{$q}{$nonSupportMessageId}{$q}"); } $pusherParams = null; if (isset($pusherParameters)) { $pusherParams = $pusherParameters; } else { if (isset($options['pusher'])) { $pusherParams = $options['pusher']; } } if (!is_null($pusherParams)) { $appKey = isset($pusherParams['key']) ? $pusherParams['key'] : "_im_key_isnt_supplied"; $chName = isset($pusherParams['channel']) ? $pusherParams['channel'] : "_im_pusher_default_channel"; $this->generateAssignJS("INTERMediatorOnPage.clientNotificationKey", "function(){return ", arrayToJS($appKey, ''), ";}"); $this->generateAssignJS("INTERMediatorOnPage.clientNotificationChannel", "function(){return ", arrayToJS($chName, ''), ";}"); } $metadata = json_decode(file_get_contents(dirname(__FILE__) . DIRECTORY_SEPARATOR . "metadata.json")); $this->generateAssignJS("INTERMediatorOnPage.metadata", "{version:{$q}{$metadata->version}{$q},releasedate:{$q}{$metadata->releasedate}{$q}}"); if (isset($prohibitDebugMode) && $prohibitDebugMode) { $this->generateAssignJS("INTERMediator.debugMode", "false"); } else { $this->generateAssignJS("INTERMediator.debugMode", $debug === false ? "false" : $debug); } // Check Authentication $boolValue = "false"; $requireAuthenticationContext = array(); if (isset($options['authentication'])) { $boolValue = "true"; } foreach ($datasource as $aContext) { if (isset($aContext['authentication'])) { $boolValue = "true"; $requireAuthenticationContext[] = $aContext['name']; } } $this->generateAssignJS("INTERMediatorOnPage.requireAuthentication", $boolValue); $this->generateAssignJS("INTERMediatorOnPage.authRequiredContext", arrayToJS($requireAuthenticationContext, '')); $ldap = new LDAPAuth(); // for PHP 5.2, 5.3 $this->generateAssignJS("INTERMediatorOnPage.isLDAP", $ldap->isActive ? "true" : "false"); $this->generateAssignJS("INTERMediatorOnPage.isOAuthAvailable", isset($oAuthProvider) ? "true" : "false"); $authObj = new OAuthAuth(); if ($authObj->isActive) { $this->generateAssignJS("INTERMediatorOnPage.oAuthClientID", $q, $oAuthClientID, $q); $this->generateAssignJS("INTERMediatorOnPage.oAuthBaseURL", $q, $authObj->oAuthBaseURL(), $q); $this->generateAssignJS("INTERMediatorOnPage.oAuthRedirect", $q, $oAuthRedirect, $q); $this->generateAssignJS("INTERMediatorOnPage.oAuthScope", $q, implode(' ', $authObj->infoScope()), $q); } $this->generateAssignJS("INTERMediatorOnPage.isNativeAuth", isset($options['authentication']) && isset($options['authentication']['user']) && $options['authentication']['user'][0] === 'database_native' ? "true" : "false"); $this->generateAssignJS("INTERMediatorOnPage.authStoring", $q, isset($options['authentication']) && isset($options['authentication']['storing']) ? $options['authentication']['storing'] : 'cookie', $q); $this->generateAssignJS("INTERMediatorOnPage.authExpired", isset($options['authentication']) && isset($options['authentication']['authexpired']) ? $options['authentication']['authexpired'] : '3600'); $this->generateAssignJS("INTERMediatorOnPage.realm", $q, isset($options['authentication']) && isset($options['authentication']['realm']) ? $options['authentication']['realm'] : '', $q); if (isset($generatedPrivateKey)) { $rsa = new Crypt_RSA(); $rsa->setPassword($passPhrase); $rsa->loadKey($generatedPrivateKey); $rsa->setPassword(); $publickey = $rsa->getPublicKey(CRYPT_RSA_PUBLIC_FORMAT_RAW); $this->generateAssignJS("INTERMediatorOnPage.publickey", "new biRSAKeyPair('", $publickey['e']->toHex(), "','0','", $publickey['n']->toHex(), "')"); if (in_array(sha1($generatedPrivateKey), array('413351603fa756ecd8270147d1a84e9a2de2a3f9', '094f61a9db51e0159fb0bf7d02a321d37f29a715')) && isset($_SERVER['SERVER_ADDR']) && $_SERVER['SERVER_ADDR'] !== '192.168.56.101') { $this->generateDebugMessageJS('Please change the value of $generatedPrivateKey in params.php.'); } } if (isset($passwordPolicy)) { $this->generateAssignJS("INTERMediatorOnPage.passwordPolicy", $q, $passwordPolicy, $q); } else { if (isset($options["authentication"]) && isset($options["authentication"]["password-policy"])) { $this->generateAssignJS("INTERMediatorOnPage.passwordPolicy", $q, $options["authentication"]["password-policy"], $q); } } if (isset($options['credit-including'])) { $this->generateAssignJS("INTERMediatorOnPage.creditIncluding", $q, $options['credit-including'], $q); } // Initial values for local context if (!isset($valuesForLocalContext)) { $valuesForLocalContext = array(); } if (isset($options['local-context'])) { foreach ($options['local-context'] as $item) { $valuesForLocalContext[$item['key']] = $item['value']; } } if (isset($valuesForLocalContext) && is_array($valuesForLocalContext) && count($valuesForLocalContext) > 0) { $this->generateAssignJS("INTERMediatorOnPage.initLocalContext", arrayToJS($valuesForLocalContext)); } }
public function test_removeNull() { $str = IMUtil::removeNull("INTER-Mediator"); $this->assertEquals($str, "INTER-Mediator"); }
function processing($dbProxyInstance, $options, $file) { try { // It the $file ('media'parameter) isn't specified, it doesn't respond an error. if (strlen($file) === 0) { $this->exitAsError(204); } // If the media parameter is an URL, the variable isURL will be set to true. $schema = array("https:", "http:", "class:"); $isURL = false; foreach ($schema as $scheme) { if (strpos($file, $scheme) === 0) { $isURL = true; break; } } list($file, $isURL) = $this->checkForFileMakerMedia($dbProxyInstance, $options, $file, $isURL); /* * If the FileMaker's object field is storing a PDF, the $file could be "http://server:16000/... * style URL. In case of an image, $file is just the path info as like above. */ $util = new IMUtil(); $file = $util->removeNull($file); if (strpos($file, '../') !== false) { return; } $target = $isURL ? $file : "{$options['media-root-dir']}/{$file}"; if (isset($options['media-context'])) { $this->checkAuthentication($dbProxyInstance, $options, $target); } $content = false; $dq = '"'; if (!$isURL) { // File path. if (!empty($file) && !file_exists($target)) { $this->exitAsError(500); } $content = file_get_contents($target); $fileName = basename($file); $qPos = strpos($fileName, "?"); if ($qPos !== false) { $fileName = substr($fileName, 0, $qPos); } header("Content-Type: " . $this->getMimeType($fileName)); header("Content-Length: " . strlen($content)); header("Content-Disposition: {$this->disposition}; filename={$dq}" . urlencode($fileName) . $dq); header('X-XSS-Protection: 1; mode=block'); header('X-Frame-Options: SAMEORIGIN'); $this->outputImage($content); } else { if (stripos($target, 'http://') === 0 || stripos($target, 'https://') === 0) { // http or https if (intval(get_cfg_var('allow_url_fopen')) === 1) { $content = file_get_contents($target); } else { if (function_exists('curl_init')) { $session = curl_init($target); curl_setopt($session, CURLOPT_HEADER, false); curl_setopt($session, CURLOPT_RETURNTRANSFER, true); $content = curl_exec($session); curl_close($session); } else { $this->exitAsError(500); } } $fileName = basename($file); $qPos = strpos($fileName, "?"); if ($qPos !== false) { $fileName = str_replace("%20", " ", substr($fileName, 0, $qPos)); } header("Content-Type: " . $this->getMimeType($fileName)); header("Content-Length: " . strlen($content)); header("Content-Disposition: {$this->disposition}; filename={$dq}" . str_replace("+", "%20", urlencode($fileName)) . $dq); header('X-XSS-Protection: 1; mode=block'); header('X-Frame-Options: SAMEORIGIN'); $this->outputImage($content); } else { if (stripos($target, 'class://') === 0) { // class $noscheme = substr($target, 8); $className = substr($noscheme, 0, strpos($noscheme, "/")); $processingObject = new $className(); $processingObject->processing($this->contextRecord, $options); } } } } catch (Exception $ex) { // do nothing } }
/** * @param $datasource * @param $options * @param $dbspec * @param $debug * @param null $target * @return bool */ function initialize($datasource, $options, $dbspec, $debug, $target = null) { $this->setUpSharedObjects(); $currentDir = dirname(__FILE__) . DIRECTORY_SEPARATOR; $currentDirParam = $currentDir . 'params.php'; $parentDirParam = dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . 'params.php'; if (file_exists($parentDirParam)) { include $parentDirParam; } else { if (file_exists($currentDirParam)) { include $currentDirParam; } } $this->clientPusherAvailable = isset($_POST["pusher"]) && $_POST["pusher"] == "yes"; $this->dbSettings->setDataSource($datasource); $this->dbSettings->setSeparator(isset($options['separator']) ? $options['separator'] : '@'); $this->formatter->setFormatter(isset($options['formatter']) ? $options['formatter'] : null); $this->dbSettings->setTargetName(!is_null($target) ? $target : (isset($_POST['name']) ? $_POST['name'] : "_im_auth")); $context = $this->dbSettings->getDataSourceTargetArray(); $dbClassName = 'DB_' . (isset($context['db-class']) ? $context['db-class'] : (isset($dbspec['db-class']) ? $dbspec['db-class'] : (isset($dbClass) ? $dbClass : ''))); $this->dbSettings->setDbSpecServer(isset($context['server']) ? $context['server'] : (isset($dbspec['server']) ? $dbspec['server'] : (isset($dbServer) ? $dbServer : ''))); $this->dbSettings->setDbSpecPort(isset($context['port']) ? $context['port'] : (isset($dbspec['port']) ? $dbspec['port'] : (isset($dbPort) ? $dbPort : ''))); $this->dbSettings->setDbSpecUser(isset($context['user']) ? $context['user'] : (isset($dbspec['user']) ? $dbspec['user'] : (isset($dbUser) ? $dbUser : ''))); $this->dbSettings->setDbSpecPassword(isset($context['password']) ? $context['password'] : (isset($dbspec['password']) ? $dbspec['password'] : (isset($dbPassword) ? $dbPassword : ''))); $this->dbSettings->setDbSpecDataType(isset($context['datatype']) ? $context['datatype'] : (isset($dbspec['datatype']) ? $dbspec['datatype'] : (isset($dbDataType) ? $dbDataType : ''))); $this->dbSettings->setDbSpecDatabase(isset($context['database']) ? $context['database'] : (isset($dbspec['database']) ? $dbspec['database'] : (isset($dbDatabase) ? $dbDatabase : ''))); $this->dbSettings->setDbSpecProtocol(isset($context['protocol']) ? $context['protocol'] : (isset($dbspec['protocol']) ? $dbspec['protocol'] : (isset($dbProtocol) ? $dbProtocol : ''))); $this->dbSettings->setDbSpecOption(isset($context['option']) ? $context['option'] : (isset($dbspec['option']) ? $dbspec['option'] : (isset($dbOption) ? $dbOption : ''))); if (isset($options['authentication']) && isset($options['authentication']['issuedhash-dsn'])) { $this->dbSettings->setDbSpecDSN($options['authentication']['issuedhash-dsn']); } else { $this->dbSettings->setDbSpecDSN(isset($context['dsn']) ? $context['dsn'] : (isset($dbspec['dsn']) ? $dbspec['dsn'] : (isset($dbDSN) ? $dbDSN : ''))); } $pusherParams = null; if (isset($pusherParameters)) { $pusherParams = $pusherParameters; } else { if (isset($options['pusher'])) { $pusherParams = $options['pusher']; } } if (!is_null($pusherParams)) { $this->dbSettings->pusherAppId = $pusherParams['app_id']; $this->dbSettings->pusherKey = $pusherParams['key']; $this->dbSettings->pusherSecret = $pusherParams['secret']; if (isset($pusherParams['channel'])) { $this->dbSettings->pusherChannel = $pusherParams['channel']; } } /* Setup Database Class's Object */ require_once "{$dbClassName}.php"; $this->dbClass = new $dbClassName(); if ($this->dbClass == null) { $this->logger->setErrorMessage("The database class [{$dbClassName}] that you specify is not valid."); echo implode('', $this->logger->getMessagesForJS()); return false; } $this->dbClass->setUpSharedObjects($this); $this->dbClass->setupConnection(); if ((!isset($prohibitDebugMode) || !$prohibitDebugMode) && $debug) { $this->logger->setDebugMode($debug); } $this->logger->setDebugMessage("The class '{$dbClassName}' was instanciated.", 2); $this->dbSettings->setAggregationSelect(isset($context['aggregation-select']) ? $context['aggregation-select'] : null); $this->dbSettings->setAggregationFrom(isset($context['aggregation-from']) ? $context['aggregation-from'] : null); $this->dbSettings->setAggregationGroupBy(isset($context['aggregation-group-by']) ? $context['aggregation-group-by'] : null); /* Authentication and Authorization Judgement */ $challengeDSN = null; if (isset($options['authentication']) && isset($options['authentication']['issuedhash-dsn'])) { $challengeDSN = $options['authentication']['issuedhash-dsn']; } else { if (isset($issuedHashDSN)) { $challengeDSN = $issuedHashDSN; } } if (!is_null($challengeDSN)) { require_once "DB_PDO.php"; $this->authDbClass = new DB_PDO(); $this->authDbClass->setUpSharedObjects($this); $this->authDbClass->setupWithDSN($challengeDSN); $this->logger->setDebugMessage("The class 'DB_PDO' was instanciated for issuedhash with {$challengeDSN}.", 2); } else { $this->authDbClass = $this->dbClass; } $this->dbSettings->notifyServer = null; if ($this->clientPusherAvailable) { require_once "NotifyServer.php"; $this->dbSettings->notifyServer = new NotifyServer(); if (isset($_POST['notifyid']) && $this->dbSettings->notifyServer->initialize($this->authDbClass, $this->dbSettings, $_POST['notifyid'])) { $this->logger->setDebugMessage("The NotifyServer was instanciated.", 2); } } $this->dbSettings->setCurrentDataAccess($this->dbClass); if (isset($context['extending-class'])) { $className = $context['extending-class']; $this->userExpanded = new $className(); if ($this->userExpanded === null) { $this->logger->setErrorMessage("The class '{$className}' wasn't instanciated."); } else { $this->logger->setDebugMessage("The class '{$className}' was instanciated.", 2); } if (is_subclass_of($this->userExpanded, 'DB_UseSharedObjects')) { $this->userExpanded->setUpSharedObjects($this); } } $this->dbSettings->setPrimaryKeyOnly(isset($_POST['pkeyonly'])); $this->dbSettings->setCurrentUser(isset($_POST['authuser']) ? $_POST['authuser'] : null); $this->dbSettings->setAuthentication(isset($options['authentication']) ? $options['authentication'] : null); $this->dbSettings->setStart(isset($_POST['start']) ? $_POST['start'] : 0); $this->dbSettings->setRecordCount(isset($_POST['records']) ? $_POST['records'] : 10000000); for ($count = 0; $count < 10000; $count++) { if (isset($_POST["condition{$count}field"])) { $this->dbSettings->addExtraCriteria($_POST["condition{$count}field"], isset($_POST["condition{$count}operator"]) ? $_POST["condition{$count}operator"] : '=', isset($_POST["condition{$count}value"]) ? $_POST["condition{$count}value"] : null); } else { break; } } for ($count = 0; $count < 10000; $count++) { if (isset($_POST["sortkey{$count}field"])) { $this->dbSettings->addExtraSortKey($_POST["sortkey{$count}field"], $_POST["sortkey{$count}direction"]); } else { break; } } for ($count = 0; $count < 10000; $count++) { if (!isset($_POST["foreign{$count}field"])) { break; } $this->dbSettings->addForeignValue($_POST["foreign{$count}field"], $_POST["foreign{$count}value"]); } for ($i = 0; $i < 1000; $i++) { if (!isset($_POST["field_{$i}"])) { break; } $this->dbSettings->addTargetField($_POST["field_{$i}"]); } for ($i = 0; $i < 1000; $i++) { if (!isset($_POST["value_{$i}"])) { break; } $util = new IMUtil(); $value = $util->removeNull(filter_var($_POST["value_{$i}"])); $this->dbSettings->addValue(get_magic_quotes_gpc() ? stripslashes($value) : $value); } if (isset($options['authentication']) && isset($options['authentication']['email-as-username'])) { $this->dbSettings->setEmailAsAccount($options['authentication']['email-as-username']); } else { if (isset($emailAsAliasOfUserName) && $emailAsAliasOfUserName) { $this->dbSettings->setEmailAsAccount($emailAsAliasOfUserName); } } for ($i = 0; $i < 1000; $i++) { if (!isset($_POST["assoc{$i}"])) { break; } $this->dbSettings->addAssociated($_POST["assoc{$i}"], $_POST["asfield{$i}"], $_POST["asvalue{$i}"]); } if (isset($options['smtp'])) { $this->dbSettings->setSmtpConfiguration($options['smtp']); } }
public function outputSecurityHeaders($params = NULL) { if (is_null($params)) { $params = IMUtil::getFromParamsPHPFile(array('xFrameOptions', 'contentSecurityPolicy'), true); } $xFrameOptions = str_replace("\r", '', str_replace("\n", '', $params['xFrameOptions'])); $contentSecurityPolicy = str_replace("\r", '', str_replace("\n", '', $params['contentSecurityPolicy'])); if (is_null($xFrameOptions) || empty($xFrameOptions)) { $xFrameOptions = 'SAMEORIGIN'; } if ($xFrameOptions !== '') { header("X-Frame-Options: {$xFrameOptions}"); } if (is_null($contentSecurityPolicy) || empty($contentSecurityPolicy)) { $contentSecurityPolicy = ''; } if ($contentSecurityPolicy !== '') { header("Content-Security-Policy: {$contentSecurityPolicy}"); } header('X-XSS-Protection: 1; mode=block'); }
function IM_Entry($datasource, $options, $dbspecification, $debug = false) { global $g_dbInstance, $g_serverSideCall; // check required PHP extensions $requiredFunctions = array('mbstring' => 'mb_internal_encoding'); if (isset($options) && is_array($options)) { foreach ($options as $key => $option) { if ($key == 'authentication' && isset($option['user']) && is_array($option['user']) && array_search('database_native', $option['user']) !== false) { // Native Authentication requires BC Math functions $requiredFunctions = array_merge($requiredFunctions, array('bcmath' => 'bcadd')); break; } } } foreach ($requiredFunctions as $key => $value) { if (!function_exists($value)) { $generator = new GenerateJSCode(); $generator->generateInitialJSCode($datasource, $options, $dbspecification, $debug); $generator->generateErrorMessageJS("PHP extension \"" . $key . "\" is required for running INTER-Mediator."); return; } } if ($debug) { $dc = new DefinitionChecker(); $defErrorMessage = $dc->checkDefinitions($datasource, $options, $dbspecification); if (strlen($defErrorMessage) > 0) { $generator = new GenerateJSCode(); $generator->generateInitialJSCode($datasource, $options, $dbspecification, $debug); $generator->generateErrorMessageJS($defErrorMessage); return; } } if (isset($g_serverSideCall) && $g_serverSideCall) { $dbInstance = new DB_Proxy(); $dbInstance->initialize($datasource, $options, $dbspecification, $debug); $dbInstance->processingRequest($options, "NON"); $g_dbInstance = $dbInstance; } else { if (!isset($_POST['access']) && isset($_GET['uploadprocess'])) { $fileUploader = new FileUploader(); $fileUploader->processInfo(); } else { if (!isset($_POST['access']) && isset($_GET['media'])) { $dbProxyInstance = new DB_Proxy(); $dbProxyInstance->initialize($datasource, $options, $dbspecification, $debug); $mediaHandler = new MediaAccess(); if (isset($_GET['attach'])) { $mediaHandler->asAttachment(); } $mediaHandler->processing($dbProxyInstance, $options, $_GET['media']); } else { if (isset($_POST['access']) && $_POST['access'] == 'uploadfile' || isset($_GET['access']) && $_GET['access'] == 'uploadfile') { $fileUploader = new FileUploader(); $fileUploader->processing($datasource, $options, $dbspecification, $debug); } else { if (!isset($_POST['access']) && !isset($_GET['media'])) { $generator = new GenerateJSCode(); $generator->generateInitialJSCode($datasource, $options, $dbspecification, $debug); } else { $dbInstance = new DB_Proxy(); $dbInstance->initialize($datasource, $options, $dbspecification, $debug); $util = new IMUtil(); if ($util->protectCSRF() === TRUE) { $dbInstance->processingRequest($options); $dbInstance->finishCommunication(false); } else { $dbInstance->addOutputData('debugMessages', 'Invalid Request Error.'); $dbInstance->addOutputData('errorMessages', array('Invalid Request Error.')); } $dbInstance->exportOutputDataAsJSON(); } } } } } }
protected function checkRedirectUrl($url, $webServerName) { if (strpos($url, 'http://') === 0 || strpos($url, 'https://') === 0) { $parsedUrl = parse_url($url); $util = new IMUtil(); if ($util->checkHost($parsedUrl['host'], $webServerName)) { return TRUE; } } return FALSE; }
private function outputImage($content) { $rotate = false; if (function_exists('exif_imagetype') && function_exists('imagejpeg') && strlen($content) > 0) { $tmpDir = ini_get('upload_tmp_dir'); if ($tmpDir === '') { $tmpDir = sys_get_temp_dir(); } $temp = 'IM_TEMP_' . str_replace(base64_encode(randomString(12)), DIRECTORY_SEPARATOR, '-') . '.jpg'; if (mb_substr($tmpDir, 1) === DIRECTORY_SEPARATOR) { $tempPath = $tmpDir . $temp; } else { $tempPath = $tmpDir . DIRECTORY_SEPARATOR . $temp; } $fp = fopen($tempPath, 'w'); if ($fp !== false) { fwrite($fp, $content); fclose($fp); $imageType = image_type_to_mime_type(exif_imagetype($tempPath)); if ($imageType === 'image/jpeg') { $image = imagecreatefromstring($content); if ($image !== false) { $exif = exif_read_data($tempPath); if ($exif !== false && !empty($exif['Orientation'])) { switch ($exif['Orientation']) { case 3: $content = imagerotate($image, 180, 0); $rotate = true; break; case 6: $content = imagerotate($image, -90, 0); $rotate = true; break; case 8: $content = imagerotate($image, 90, 0); $rotate = true; break; } } } if ($rotate === true) { header('Content-Type: image/jpeg'); ob_start(); imagejpeg($content); $size = ob_get_length(); header('Content-Length: ' . $size); $util = new IMUtil(); $util->outputSecurityHeaders(); ob_end_flush(); } imagedestroy($image); } unlink($tempPath); } } if ($rotate === false) { echo $content; } }