/** * Revoke a user's app auth on Facebook * * @param string $providerUserId * * @throws \DreamFactory\Platform\Exceptions\BadRequestException */ protected function _revokeAuthorization($providerUserId = null) { $_id = $providerUserId ?: null; if (empty($providerUserId) && null === ($_id = $this->getConfig('provider_user_id'))) { $_profile = $this->getUserData(); if (!empty($_profile) && null !== ($_id = $_profile->getUserId())) { throw new BadRequestException('Revocation not possible without provider user ID.'); } } $_result = $this->fetch('/' . $_id . '/permissions', array(), HttpMethod::Delete); if (true !== ($_success = Option::get($_result, 'result', false))) { if (HttpResponse::BadRequest !== Option::get($_result, 'code')) { Log::error('Facebook revocation for user ID "' . $_id . '" FAILED.'); return; } else { Log::debug('Facebook revocation for user ID "' . $_id . '" already completed.'); } } else { Log::debug('Facebook revocation for user ID "' . $_id . '" successful.'); } parent::_revokeAuthorization(); }
/** * Creates a provider configuration from a template * * @param string $providerId * @param array|BaseProviderConfig $config Additional configuration options or overrides * @param string $fromTemplate The template to use if different from $providerId * * @throws \DreamFactory\Oasys\Exceptions\OasysConfigurationException * @return ProviderConfigLike */ public static function createFromTemplate($providerId, $config = null, $fromTemplate = null) { /** @var array $_defaults */ $_defaults = static::getTemplate($fromTemplate ?: $providerId); if (empty($_defaults)) { Log::notice('Auto-template for "' . $providerId . '" not found.'); $_defaults = array(); } // Merge in the template, stored stuff and user supplied stuff $_config = null !== $config ? array_merge($_defaults, Option::clean($config)) : $_defaults; Option::set($_config, 'provider_id', $providerId); if (null === ($_type = Option::get($_config, 'type'))) { throw new OasysConfigurationException('You must specify the "type" of provider when using auto-generated configurations.'); } $_typeName = ProviderConfigTypes::nameOf($_type); // Build the class name for the type of authentication of this provider $_class = str_ireplace('oauth', 'OAuth', BaseProvider::DEFAULT_CONFIG_NAMESPACE . ucfirst(Inflector::deneutralize(strtolower($_typeName) . '_provider_config'))); // Log::debug( 'Determined class of service to be: ' . $_typeName . '::' . $_class ); // Instantiate! return new $_class($_config); }
/** * Returns the validated URL that has been called to get here * * @param bool $includeQuery If true, query string is included * @param bool $includePath If true, the uri path is included * * @return string */ public static function currentUrl($includeQuery = true, $includePath = true) { // Are we SSL? Check for load balancer protocol as well... $_port = intval(Option::get($_SERVER, 'HTTP_X_FORWARDED_PORT', Option::get($_SERVER, 'SERVER_PORT', 80))); $_protocol = Option::get($_SERVER, 'HTTP_X_FORWARDED_PROTO', 'http' . (Option::getBool($_SERVER, 'HTTPS') ? 's' : null)) . '://'; $_host = Option::get($_SERVER, 'HTTP_X_FORWARDED_HOST', Option::get($_SERVER, 'HTTP_HOST', gethostname())); $_parts = parse_url($_protocol . $_host . Option::get($_SERVER, 'REQUEST_URI')); if ((empty($_port) || !is_numeric($_port)) && null !== ($_parsePort = Option::get($_parts, 'port'))) { $_port = @intval($_parsePort); } if (null !== ($_query = Option::get($_parts, 'query'))) { $_query = static::urlSeparator($_query) . http_build_query(explode('&', $_query)); } if (false !== strpos($_host, ':') || $_protocol == 'https://' && $_port == 443 || $_protocol == 'http://' && $_port == 80) { $_port = null; } else { $_port = ':' . $_port; } if (false !== strpos($_host, ':')) { $_port = null; } $_currentUrl = $_protocol . $_host . $_port . (true === $includePath ? Option::get($_parts, 'path') : null) . (true === $includeQuery ? $_query : null); if (\Kisma::get('debug.curl.current_url')) { Log::debug('Parsed current URL to be: ' . $_currentUrl, $_parts); } return $_currentUrl; }
/** * Checks the progress of any in-flight OAuth requests * * * @throws \Exception|\OAuthException * @throws \DreamFactory\Oasys\Exceptions\RedirectRequiredException * @return string */ public function checkAuthenticationProgress() { if ($this->_config->getAccessToken()) { $this->_setToken(); return true; } $_state = $this->_config->getState(); $_accessToken = null; $_requestToken = Option::request('oauth_token'); $_tokenSecret = Option::request('oauth_secret', $this->_config->getAccessTokenSecret()); $_verifier = Option::request('oauth_verifier'); try { // No auth yet if (null === $_requestToken) { $_url = $this->_config->getEndpointUrl(EndpointTypes::REQUEST_TOKEN); $_token = $this->getRequestToken($_url); $this->setAccessTokenSecret($_tokenSecret = Option::get($_token, 'oauth_token_secret')); $this->setState(1); // Construct the redirect for authorization $_redirectUrl = $this->getEndpointUrl(EndpointTypes::AUTHORIZE) . '?oauth_token=' . Option::get($_token, 'oauth_token'); if (!empty($this->_redirectProxyUrl)) { $_redirectUrl = $this->_redirectProxyUrl . '?redirect=' . urlencode($_redirectUrl); } $this->_config->setAuthorizeUrl($_redirectUrl); if (Flows::SERVER_SIDE == $this->_config->getFlowType()) { throw new RedirectRequiredException($_redirectUrl); } header('Location: ' . $_redirectUrl); exit; } // Step 2! if (!empty($_requestToken) && !empty($_verifier)) { $this->_client->setToken($_requestToken, $_tokenSecret); $_accessToken = $this->_client->getAccessToken($this->_config->getEndpointUrl(EndpointTypes::ACCESS_TOKEN)); $this->_config->setState($_state = 2); $this->_config->setToken($_accessToken); $this->_config->setAccessToken($_accessToken['oauth_token']); $this->_config->setAccessTokenSecret($_accessToken['oauth_token_secret']); } // Set the token, now ready for action if (2 == $_state) { $this->_setToken(); } } catch (\OAuthException $_ex) { Log::error('OAuth exception: ' . $_ex->getMessage()); throw $_ex; } return true; }
/** * Makes a list of available templates * * @param string $pattern * * @return void */ protected static function _loadTemplates($pattern = self::DEFAULT_TEMPLATE_PATTERN) { if (array() !== (static::$_templateCache = Oasys::getStore()->get('oasys.template_cache', array()))) { // Loaded from cache... return; } $_list = array(); foreach (static::$_providerPaths as $_path) { $_templates = glob($_path . '/Templates/' . $pattern); foreach ($_templates as $_template) { $_templateName = str_ireplace('.template.php', null, basename($_template)); $_templateId = Inflector::neutralize($_templateName); // Skip base classes in these directories... if ('base_' == substr($_templateId, 0, 4)) { continue; } $_list[$_templateId] = $_path . '/Templates/' . $_template; unset($_template, $_templateId, $_templateName); } unset($_path, $_templates); } // Merge in the found templates Oasys::getStore()->set('oasys.template_cache', static::$_templateCache = array_merge(static::$_templateCache, $_list)); Log::debug('Cached templates: ' . implode(', ', array_keys(static::$_templateCache))); }
{ return static::$_logFileName; } /** * @param string $logFilePath * * @deprecated in v0.2.20. To be removed in v0.3.0. Replaced by Monolog formatter */ public static function setLogFilePath($logFilePath) { static::$_logFilePath = $logFilePath; } /** * @return string * @deprecated in v0.2.20. To be removed in v0.3.0. Replaced by Monolog formatter */ public static function getLogFilePath() { return static::$_logFilePath; } /** * @return boolean * @deprecated in v0.2.20. To be removed in v0.3.0. Replaced by Monolog formatter */ public static function getLogFileValid() { return static::$_logFileValid; } } Log::checkSystemLogPath();
$_fabricHosted = false; if (!defined('DSP_VERSION') && file_exists(__DIR__ . '/constants.config.php')) { require __DIR__ . '/constants.config.php'; } /** * Load any environment variables first thing as they may be used by the database config */ /** @noinspection PhpIncludeInspection */ if (false !== ($_envConfig = Pii::includeIfExists(__DIR__ . ENV_CONFIG_PATH, true))) { if (!empty($_envConfig) && is_array($_envConfig)) { foreach ($_envConfig as $_key => $_value) { if (!is_string($_value)) { $_value = json_encode($_value); } if (false === putenv($_key . '=' . $_value)) { Log::error('Error setting environment variable: ' . $_key . ' = ' . $_value); } } } } /** * Load up the database configuration, free edition, private hosted, or others. * Look for non-default database config to override. */ if (false === ($_dbConfig = Pii::includeIfExists(__DIR__ . DATABASE_CONFIG_PATH, true))) { if (Fabric::fabricHosted()) { $_fabricHosted = true; list($_dbConfig, $_metadata) = Fabric::initialize(); } else { /** * Database names vary by type of DSP:
/** * Saves off any data to the file system */ protected function _save() { $_file = $this->_storagePath . DIRECTORY_SEPARATOR . $this->_fileName; $_data = json_encode($this->contents()); if ($this->_compressStore) { $_data = Utility\Storage::freeze($this->contents()); } if (false === file_put_contents($_file, $_data)) { Utility\Log::error('Unable to store Oasys data in "' . $_file . '". System error.'); return false; } return true; }
* This file is part of the DreamFactory Oasys (Open Authentication SYStem) * * DreamFactory Oasys (Open Authentication SYStem) <http://dreamfactorysoftware.github.io> * Copyright 2014 DreamFactory Software, Inc. <*****@*****.**> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ use Kisma\Core\Utility\Log; /** * bootstrap.php * Bootstrap script for Oasys PHPUnit tests */ // Composer require dirname(__DIR__) . '/vendor/autoload.php'; // Testing keys if (file_exists(__DIR__ . '/config/keys.php')) { /** @noinspection PhpIncludeInspection */ require_once __DIR__ . '/config/keys.php'; } Log::setDefaultLog(__DIR__ . '/log/oasys.tests.log');
* console.php * This is the main configuration file for the DreamFactory Services Platform server console. */ if (!defined('DSP_VERSION') && file_exists(__DIR__ . '/constants.config.php')) { require __DIR__ . '/constants.config.php'; } $_configFileList = array('dbConfig' => array(true, 'database'), 'commonConfig' => array(true, 'common')); /** * Load any environment variables first thing as they may be used by the database config */ if (file_exists(__DIR__ . '/env.config.php')) { /** @noinspection PhpIncludeInspection */ if (false !== ($_envConfig = @(require __DIR__ . '/env.config.php')) && !empty($_envConfig) && is_array($_envConfig)) { foreach ($_envConfig as $_envVar) { if (false === putenv($_envVar)) { Log::error('Error setting environment variable: ' . $_envVar); } } } } /** * Load up the common configurations between the web and background apps, * setting globals whilst at it. */ $_commonConfig = (require __DIR__ . '/common.config.php'); /** * Load up the database configuration, free edition, private hosted, or others. * Look for non-default database config to override. */ $_dbConfig = array(); if (file_exists(__DIR__ . '/database.config.php')) {
/** * Retrieves the users' profile from the provider and stores it */ protected function _updateUserProfile() { $_profile = $this->getUserData(); if (!empty($_profile)) { // For us... $_profile->setProviderId($this->_providerId); $this->setConfig('provider_user_id', $_id = $_profile->getUserId()); // For posterity - Check if method exists so testing works. /** @noinspection PhpUndefinedMethodInspection */ if (method_exists(Oasys::getStore(), 'setProviderUserId')) { Oasys::getStore()->setProviderUserId($_id); } // A tag Log::debug('User profile updated [' . $this->_providerId . ':' . $_id . ']'); } }
/** * @param PackageInterface $package * * @throws \InvalidArgumentException * @return string */ protected function _validatePackage(PackageInterface $package) { $_packageName = $package->getPrettyName(); $_parts = explode('/', $_packageName, 2); $this->_extra = Option::clean($package->getExtra()); $this->_config = Option::get($this->_extra, 'config', array()); $this->_plugIn = static::DSP_PLUGIN_PACKAGE_TYPE == $package->getType(); // Only install DreamFactory packages if not a plug-in if (static::PACKAGE_PREFIX != ($_vendor = @current($_parts)) && !$this->_plugIn) { throw new \InvalidArgumentException('This package is not a DreamFactory package and cannot be installed by this installer.' . PHP_EOL . ' * Name: ' . $_packageName . PHP_EOL . ' * Parts: ' . implode(' / ', $_parts) . PHP_EOL); } // Effectively /docRoot/shared/[vendor]/[namespace]/[package] Log::debug('Package "' . $_packageName . '" installation type: ' . ($this->_plugIn ? 'Plug-in' : 'Package')); $this->_packageName = $_packageName; $this->_installPath = $this->_buildInstallPath($_vendor, @end($_parts)); // Link path for plug-ins $_extra = Option::clean($package->getExtra()); $this->_linkName = Option::get($_extra, 'link_name', $_parts[1]); // Relative to composer.json... i.e. web/[link_name] $this->_linkPath = trim(static::PLUG_IN_LINK_PATH . '/' . $this->_linkName, '/'); Log::info('Platform Installer Debug > ' . $_packageName . ' > Version ' . $package->getVersion()); Log::debug(' * Install path: ' . $this->_installPath); if ($this->_plugIn) { Log::debug(' * Link name: ' . $this->_linkName); Log::debug(' * Link path: ' . $this->_linkPath); } return true; }
/** * Response is always empty from this call. HTTP response code of 204 is success. Anything is an error. * * @param string $object * @param string $id * @param array $fields * * @throws InternalServerErrorException * @return bool|mixed */ public function updateObject($object, $id, $fields = array()) { $_response = $this->fetch('/services/data/' . static::API_VERSION_TAG . '/sobjects/' . $object . '/' . $id, json_encode($fields), static::Patch); // Curl error is false... if (false === $_response) { return false; } if (HttpResponse::NoContent == Curl::getLastHttpCode()) { return true; } // Sometimes they send back xml... if (is_string($_response) && false !== stripos($_response, '<?xml')) { try { if (null === ($_response = Convert::toObject(simplexml_load_string($_response)))) { throw new InternalServerErrorException('Unrecognizable response from server: ' . print_r($_response, true)); } // Otherwise we have a nice object which we return as json } catch (\Exception $_ex) { // error... Log::error('Exception parsing response: ' . print_r($_response, true)); } } return $_response; }
* * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ use DreamFactory\Oasys\Oasys; use DreamFactory\Oasys\Components\GenericUser; use DreamFactory\Oasys\Enums\Flows; use DreamFactory\Oasys\Exceptions\OasysException; use DreamFactory\Oasys\Stores\FileSystem; use Kisma\Core\Utility\Convert; use Kisma\Core\Utility\Log; require_once dirname(__DIR__) . '/bootstrap.php'; Log::setDefaultLog(__DIR__ . '/../log/error.log'); $_config = null; // Choose the provider to test //$_providerId = 'facebook'; //$_providerId = 'github'; //$_providerId = 'twitter'; $_providerId = 'google_plus'; switch ($_providerId) { case 'facebook': $_config = array('flow_type' => Flows::CLIENT_SIDE, 'client_id' => FACEBOOK_CLIENT_ID, 'client_secret' => FACEBOOK_CLIENT_SECRET); break; case 'github': $_config = array('flow_type' => Flows::CLIENT_SIDE, 'client_id' => GITHUB_CLIENT_ID, 'client_secret' => GITHUB_CLIENT_SECRET); break; case 'google_plus': $_config = array('flow_type' => Flows::CLIENT_SIDE, 'client_id' => GOOGLE_CLIENT_ID, 'client_secret' => GOOGLE_CLIENT_SECRET);
/** * @param array|null $parameters * * @return bool */ public function execute($parameters = null) { if (empty($parameters)) { $_result = $this->_statement->execute(); } else { $_result = $this->_statement->execute($parameters); } if (false === $_result) { $this->_errorInfo = $this->_statement->errorInfo(); Log::error('SQL error: [' . $this->_errorInfo[0] . '-' . $this->_errorInfo[1] . '] ' . $this->_errorInfo[2]); } return $this->_executeResult = $_result; }
/** * Choose your destructor! */ public function __destruct() { if (is_resource($this->_handle)) { if (false === @fclose($this->_handle)) { Log::error('Error whilst closing file: ' . $this->_fileName); } } }
protected function _checkSystemState() { $_error = false; $_state = SystemManager::getSystemState(); if (!$this->_activated && $_state != PlatformStates::INIT_REQUIRED) { $_state = PlatformStates::ADMIN_REQUIRED; } if (!empty($this->_remoteError)) { $_error = 'error=' . urlencode($this->_remoteError); } if (PlatformStates::READY == $_state) { $_defaultApp = Pii::getParam('dsp.default_app', static::DEFAULT_STARTUP_APP); // Try local launchpad if (is_file(\Kisma::get('app.app_path') . $_defaultApp)) { $_defaultApp = rtrim($_defaultApp . Curl::urlSeparator($_defaultApp) . $_error, '?'); $this->redirect($_defaultApp); } // Log::notice( // 'No default application defined/found. Running launchpad...' . // PHP_EOL . // '==============================' . // PHP_EOL . // 'Config dump:' . // PHP_EOL . // print_r( \Kisma::get( null ), true ) . // '==============================' . // PHP_EOL . // '==============================' . // PHP_EOL . // 'Params dump:' . // PHP_EOL . // print_r( Pii::params(), true ) . // '==============================' . // PHP_EOL // ); // If we have no app, run the launchpad $this->redirect(static::DEFAULT_STARTUP_APP); } else { if (!$this->_handleAction($_state)) { Log::error('Invalid state "' . $_state . '" or no handler configured.'); } } }
* * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ use Kisma\Core\Utility\Log; /** * bootstrap.php * Bootstrap script for PHPUnit tests */ $_basePath = dirname(__DIR__); // Composer $_autoloader = (require $_basePath . '/vendor/autoload.php'); // Load up Yii require_once $_basePath . '/vendor/dreamfactory/yii/framework/yii.php'; // Yii debug settings defined('YII_DEBUG') or define('YII_DEBUG', true); defined('YII_TRACE_LEVEL') or define('YII_TRACE_LEVEL', 3); $_config = (require __DIR__ . '/config/portal-sandbox.config.php'); // Testing keys if (file_exists(__DIR__ . '/config/keys.php')) { /** @noinspection PhpIncludeInspection */ require_once __DIR__ . '/config/keys.php'; } Log::setDefaultLog(__DIR__ . '/log/portal-sandbox.tests.log'); // Create the application but don't run (false at the end) $_app = DreamFactory\Yii\Utility\Pii::run(__DIR__, $_autoloader, 'DreamFactory\\Platform\\Yii\\Components\\PlatformConsoleApplication', $_config, false);