/** * {@inheritdoc} */ public function getUserEntityByUserCredentials($username, $password, $grantType, ClientEntityInterface $clientEntity) { $di = new Di(); /** @var Security $security */ $security = $di->getShared('security'); $user = Users::query()->where("username = :username:")->bind(['username' => $username])->limit(1)->execute()->toArray(); $correctDetails = false; if (count($user) === 1) { $user = current($user); if ($security->checkHash($password, $user['password'])) { $correctDetails = true; } else { $security->hash(rand()); } } else { // prevent timing attacks $security->hash(rand()); } if ($correctDetails) { //$scope = new ScopeEntity(); //$scope->setIdentifier('email'); //$scopes[] = $scope; return new UserEntity($user); } return null; }
public function modulesClosure(IntegrationTester $I) { $I->wantTo('handle request and get content by using single modules strategy (closure)'); Di::reset(); $_GET['_url'] = '/login'; $di = new FactoryDefault(); $di->set('router', function () { $router = new Router(false); $router->add('/index', ['controller' => 'index', 'module' => 'frontend', 'namespace' => 'Phalcon\\Test\\Modules\\Frontend\\Controllers']); $router->add('/login', ['controller' => 'login', 'module' => 'backend', 'namespace' => 'Phalcon\\Test\\Modules\\Backend\\Controllers']); return $router; }); $application = new Application(); $view = new View(); $application->registerModules(['frontend' => function ($di) use($view) { /** @var \Phalcon\DiInterface $di */ $di->set('view', function () use($view) { $view->setViewsDir(PATH_DATA . 'modules/frontend/views/'); return $view; }); }, 'backend' => function ($di) use($view) { /** @var \Phalcon\DiInterface $di */ $di->set('view', function () use($view) { $view->setViewsDir(PATH_DATA . 'modules/backend/views/'); return $view; }); }]); $application->setDI($di); $I->assertEquals('<html>here</html>' . PHP_EOL, $application->handle()->getContent()); }
/** * Constructor. */ public function __construct() { /** * Create default DI. */ $di = new DI\FactoryDefault(); /** * Get config. */ $this->_config = Config::factory(); if (!$this->_config->installed) { define('CHECK_REQUIREMENTS', true); require_once PUBLIC_PATH . '/requirements.php'; } /** * Setup Registry. */ $registry = new Registry(); $registry->modules = array_merge([self::SYSTEM_DEFAULT_MODULE, 'user'], $this->_config->modules->toArray()); $registry->widgets = $this->_config->widgets->toArray(); $registry->directories = (object) ['engine' => ROOT_PATH . '/app/engine/', 'modules' => ROOT_PATH . '/app/modules/', 'plugins' => ROOT_PATH . '/app/plugins/', 'widgets' => ROOT_PATH . '/app/widgets/', 'libraries' => ROOT_PATH . '/app/libraries/']; $di->set('registry', $registry); // Store config in the DI container. $di->setShared('config', $this->_config); parent::__construct($di); }
/** * Register the services here to make them general or register in the ModuleDefinition to make them module-specific */ public function registerServices() { $di = new FactoryDefault(); $loader = new Loader(); $namespaces = []; $map = (require_once __DIR__ . '/../autoload_namespaces.php'); foreach ($map as $k => $values) { $k = trim($k, '\\'); if (!isset($namespaces[$k])) { $dir = '/' . str_replace('\\', '/', $k) . '/'; $namespaces[$k] = implode($dir . ';', $values) . $dir; } } $loader->registerNamespaces($namespaces); $loader->register(); /** * Register a router */ $di->set('router', function () { $router = new Router(); $router->setDefaultModule('frontend'); //set frontend routes $router->mount(new FrontendRoutes()); // return $router; }); $this->setDI($di); }
/** * {@inheritdoc} */ public function getClientEntity($clientIdentifier, $grantType, $clientSecret = null, $mustValidateSecret = true) { $di = new Di(); /** @var Security $security */ $security = $di->getShared('security'); $client = Clients::query()->where("id = :id:")->bind(['id' => $clientIdentifier])->limit(1)->execute()->toArray(); $correctDetails = false; if (count($client) === 1) { $client = current($client); if ($mustValidateSecret) { if ($security->checkHash($clientSecret, $client['secret'])) { $correctDetails = true; } else { $security->hash(rand()); } } else { $correctDetails = true; } } else { // prevent timing attacks $security->hash(rand()); } if ($correctDetails) { $clientEntity = new ClientEntity(); $clientEntity->setIdentifier($clientIdentifier); $clientEntity->setName($client['name']); $clientEntity->setRedirectUri($client['redirect_url']); return $clientEntity; } return null; }
public function get($routeName, $routeParams = array()) { $url = $this->di->get('url'); $options = array('for' => $routeName); $options = array_merge($options, $routeParams); return $url->get($options); }
/** * Inject of Phalcon dependency container * * @param \Phalcon\DI\FactoryDefault $dependency * @throws BaseException */ public function __construct(\Phalcon\DI\FactoryDefault $dependency) { if ($dependency->has('config') === true) { $this->config = $dependency->get('config')->sms->toArray(); } else { throw new BaseException('SMS', 'Please setup your configuration to $dependency', 500); } }
/** * Constructs the app. * * Checks singleton instance * Adds a dependency injector if none provided * Sets the notFound handler * * @param FactoryDefault $dependencyInjector * @throws \RuntimeException */ public function __construct($dependencyInjector = null) { if (self::$app === null) { if ($dependencyInjector === null) { $dependencyInjector = new FactoryDefault(); } $dependencyInjector->setShared('response', Response::class); $dependencyInjector->setShared('router', Router::class); if (!$dependencyInjector->has('eventsManager')) { $dependencyInjector->setShared('eventsManager', \Phalcon\Events\Manager::class); } if (!$dependencyInjector->has('request')) { $dependencyInjector->setShared('request', \Phalcon\Http\Request::class); } parent::__construct($dependencyInjector); self::$app = $this; $this->setEventsManager($dependencyInjector->getShared('eventsManager')); $this->addHeaderHandler(new HeaderHandler\Accept()); $app = self::$app; $this->_errorHandler = function (\Exception $ex) { return $this->errorHandler($ex); }; $this->_notFoundHandler = function () { return $this->notFoundHandler(); }; } else { throw new \RuntimeException("Can't instance App more than once"); } }
private function setServices() { $di = new FactoryDefault(); $di->set('config', $this->setConfig()); $this->setAutoloaders(); $di->set('url', $this->setUrl(), true); $di->set('router', $this->setRouter()); $this->setDI($di); $di->set('view', $this->setView(), true); $di->set('db', $this->setDb()); $di->set('modelsMetadata', $this->setModelsMetadata()); $di->set('session', $this->setSession()); $this->setDI($di); }
public static function setUpBeforeClass() { $basedir = realpath(__DIR__ . '/../../'); $testdir = $basedir . '/tests'; self::$viewsdir = realpath($testdir . '/views/') . '/'; include_once $basedir . "/vendor/autoload.php"; $di = new DI(); $di->set('form', "Logikos\\Forms\\Form"); $di->set('url', function () { $url = new \Phalcon\Mvc\Url(); $url->setBaseUri('/'); return $url; }); static::$di = $di; }
/** * Sends an email using MailGun * @author salvipascual * @param String $to, email address of the receiver * @param String $subject, subject of the email * @param String $body, body of the email in HTML * @param Array $images, paths to the images to embeb * @param Array $attachments, paths to the files to attach * */ public function sendEmail($to, $subject, $body, $images = array(), $attachments = array()) { // do not email if there is an error $response = $this->deliveryStatus($to); if ($response != 'ok') { return; } // select the from email using the jumper $from = $this->nextEmail($to); $domain = explode("@", $from)[1]; // create the list of images if (!empty($images)) { $images = array('inline' => $images); } // crate the list of attachments // TODO add list of attachments // create the array send $message = array("from" => "Apretaste <{$from}>", "to" => $to, "subject" => $subject, "html" => $body, "o:tracking" => false, "o:tracking-clicks" => false, "o:tracking-opens" => false); // get the key from the config $di = \Phalcon\DI\FactoryDefault::getDefault(); $mailgunKey = $di->get('config')['mailgun']['key']; // send the email via MailGun $mgClient = new Mailgun($mailgunKey); $result = $mgClient->sendMessage($domain, $message, $images); }
public function getShared($name, $parameters = null) { if ($this->_init) { $this->checkPermission($name); } return parent::getShared($name, $parameters); }
/** * Get Enum Column values * * @access public * @param {string} $columnName * @return {array} */ public function getEnumValues($columnName = null) { $di = PhDi::getDefault(); if ($columnName == null) { return array(); } $sql = "SHOW COLUMNS FROM `" . $this->getSource() . "` LIKE '{$columnName}'"; $resultSet = $di['db']->query($sql); $resultSet->setFetchMode(Phalcon\Db::FETCH_ASSOC); $result = $resultSet->fetchAll($resultSet); if (!empty($result)) { $types = null; if (isset($result[0]['Type'])) { $types = $result[0]['Type']; } else { return array(); } $values = explode("','", preg_replace("/(enum)\\('(.+?)'\\)/", "\\2", $types)); $assoc_values = array(); foreach ($values as $value) { $assoc_values[$value] = ucwords(str_replace('_', ' ', $value)); } return $assoc_values; } return false; }
/** * 初始化view */ protected function initView() { $config = $this->config; $debug = $this->debug; $this->di->setShared('view', function () use($config, $debug) { $view = new View(); $view->setViewsDir($config->application->viewsDir); $viewEngines = ['.phtml' => 'Phalcon\\Mvc\\View\\Engine\\Php']; if ($config->offsetExists('volt')) { $viewEngines['.volt'] = function ($view, $di) use($config, $debug) { $volt = new VoltEngine($view, $di); $volt->setOptions(array('compiledPath' => $config->volt->cacheDir, 'compiledExtension' => ".compiled", 'compiledSeparator' => '_', 'compileAlways' => $debug)); $compiler = $volt->getCompiler(); foreach ($config->volt->extension as $k => $v) { $compiler->addExtension($v); } foreach ($config->volt->func as $k => $v) { $compiler->addFunction($k, $v); } $filterList = $config->volt->filter; foreach ($filterList as $k => $v) { $compiler->addFilter($k, $v); } return $volt; }; } $view->registerEngines($viewEngines); return $view; }); }
/** * Smarty plugin * * @package Smarty * @subpackage PluginsFunction */ function smarty_function_apretaste_support_email($params, $template) { // get the support email from the configs $di = \Phalcon\DI\FactoryDefault::getDefault(); $supportEmail = $di->get("config")["contact"]["support"]; return $supportEmail; }
/** * @param $name * @param $message * @param $type */ public static function log($name, $message, $type) { $typeName = self::getTypeString($type); $logger = FactoryDefault::getDefault()->get('logger'); $logger->name = $name; $logger->{$typeName}($message); }
public function __construct() { parent::__construct(); $this->setShared(Services::REQUEST, new \PhalconRest\Http\Request()); $this->setShared(Services::RESPONSE, new \PhalconRest\Http\Response()); $this->setShared(Services::AUTH_MANAGER, new \PhalconRest\Auth\Manager()); $this->setShared(Services::FRACTAL_MANAGER, function () { $className = '\\League\\Fractal\\Manager'; if (!class_exists($className)) { throw new Exception(ErrorCodes::GEN_SYSTEM, '\\League\\Fractal\\Manager was requested, but class could not be found'); } return new $className(); }); $this->setShared(Services::TOKEN_PARSER, function () { return new \PhalconRest\Auth\TokenParser\JWT('this_should_be_changed'); }); $this->setShared(Services::API_SERVICE, function () { return new \PhalconRest\Api\Service(); }); $this->setShared(Services::QUERY, function () { return new \PhalconRest\Data\Query(); }); $this->setShared(Services::PHQL_QUERY_PARSER, function () { return new \PhalconRest\Data\Query\Parser\Phql(); }); $this->setShared(Services::URL_QUERY_PARSER, function () { return new \PhalconRest\Data\Query\Parser\Url(); }); }
public function setUp() { $this->task = new ImportDmmTask(); $di = new Di\FactoryDefault(); $db = function () { return new Mysql(array("host" => $GLOBALS['db_host'], "username" => $GLOBALS['db_username'], "password" => $GLOBALS['db_password'], "dbname" => 'yinxing')); }; $di->set('dbSlave', $db); $di->set('dbMaster', $db); $di->set('moduleManager', function () { return new ModuleManager(); }); /** @var Mysql $mysql */ $mysql = $di->get('dbMaster'); $mysql->query(file_get_contents(__DIR__ . '/../../sql/evamovie_2015-10-20.sql')); }
public function setUp() { static::$di = new Di(); Di::setDefault(static::$di); putenv('APP_ENV'); unset($_ENV['APP_ENV'], $_SERVER['APP_ENV']); }
public function _before() { parent::_before(); PhDI::reset(); $di = new PhDI(); PhTTag::setDI($di); }
/** * Render the template and return the HTML content * * @author salvipascual * @param Service $service, service to be rendered * @param Response $response, response object to render * @return String, template in HTML * @throw Exception */ public function renderHTML($service, $response) { // get the path $di = \Phalcon\DI\FactoryDefault::getDefault(); $wwwroot = $di->get('path')['root']; // select the right file to load if ($response->internal) { $userTemplateFile = "{$wwwroot}/app/templates/{$response->template}"; } else { $userTemplateFile = "{$wwwroot}/services/{$service->serviceName}/templates/{$response->template}"; } // creating and configuring a new Smarty object $smarty = new Smarty(); $smarty->addPluginsDir("{$wwwroot}/app/plugins/"); $smarty->setTemplateDir("{$wwwroot}/app/layouts/"); $smarty->setCompileDir("{$wwwroot}/temp/templates_c/"); $smarty->setCacheDir("{$wwwroot}/temp/cache/"); // disabling cache and debugging $smarty->force_compile = true; $smarty->debugging = false; $smarty->caching = false; // list the system variables $systemVariables = array("APRETASTE_USER_TEMPLATE" => $userTemplateFile, "APRETASTE_SERVICE_NAME" => strtoupper($service->serviceName), "APRETASTE_SERVICE_RELATED" => $this->getServicesRelatedArray($service->serviceName), "APRETASTE_SERVICE_CREATOR" => $service->creatorEmail, "APRETASTE_TOP_AD" => "", "APRETASTE_BOTTOM_AD" => ""); // merge all variable sets and assign them to Smarty $templateVariables = array_merge($systemVariables, $response->content); $smarty->assign($templateVariables); // renderig and removing tabs, double spaces and break lines $renderedTemplate = $smarty->fetch("email_default.tpl"); return preg_replace('/\\s+/S', " ", $renderedTemplate); }
/** * Write error to log * * @param $type * @param $message * @param $file * @param $line * @param string $trace * @throws \Phalcon\Exception */ protected static function logError($type, $message, $file, $line, $trace = '') { $di = Di::getDefault(); $template = "[%s] %s (File: %s Line: [%s])"; $logMessage = sprintf($template, $type, $message, $file, $line); if ($di->has('profiler')) { $profiler = $di->get('profiler'); if ($profiler) { $profiler->addError($logMessage, $trace); } } if ($trace) { $logMessage .= $trace . PHP_EOL; } else { $logMessage .= PHP_EOL; } if ($di->has('logger')) { $logger = $di->get('logger'); if ($logger) { $logger->error($logMessage); } else { throw new PhException($logMessage); } } else { throw new PhException($logMessage); } }
public function get($alias, $parameters = null) { $result = parent::get($alias, $parameters); $injector = new \Vegas\Mvc\Di\Manager(); $injector->setDI($this); $injector->inject($result); return $result; }
/** * Escape dangerous strings before passing it to mysql * * @author salvipascual * @param String $str, text to scape * @return String, scaped text ready to be sent to mysql * */ public function escape($str) { // get the scaped string $di = \Phalcon\DI\FactoryDefault::getDefault(); $safeStr = $di->get('db')->escapeString($str); // remove the ' at the beginning and end of the string return substr(substr($safeStr, 0, -1), 1); }
public function __construct(array $entireAppConfig) { parent::__construct(); $this->set('config', new Config($entireAppConfig), true); $this->setEventsManager(); $this->set('dispatcher', new Dispatcher($this), true); $this->set('view', new View()); }
public function setUp() { static::$di = new Di(); Di::setDefault(static::$di); ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL); }
/** * Creates the profiler and starts the logging */ public function __construct() { $this->_profiler = new Profiler(); $di = Di::getDefault(); if ($di->has('loggerDb')) { $this->_logger = $di->get('loggerDb'); } }
/** * Register the services here to make them general or register in the ModuleDefinition to make them module-specific */ protected function registerServices() { $di = new FactoryDefault(); require '../../../autoloader.php'; $loader = new Loader(); /** * We're a registering a set of directories taken from the configuration file */ $loader->registerDirs(array(__DIR__ . '/../apps/library/'))->register(); $router = new Router(); $router->setDefaultModule("frontend"); //Registering a router $di->set('router', function () use($router) { return $router; }); $this->setDI($di); }
/** * @dataProvider additionEmptyDataProvider * @expectedException \SMSFactory\Exceptions\BaseException * @expectedExceptionCode 500 */ public function testSendCatchExceptionsForNotConfiguredProviders($provider) { $this->di->set('config', function () { return new Config(require './phpunit/data/empty.php'); }); $callInstance = new Sender($this->di); $this->assertInstanceOf('SMSFactory\\Sender', $callInstance, "[-] Provider instance error"); $callInstance->call($provider)->setRecipient($this->phone)->send($this->message); }
public function countMediumtypeClippings($mediumtype) { $config = \Phalcon\DI\FactoryDefault::getDefault()->getShared('config'); $modelsManager = $this->getDi()->getShared('modelsManager'); $phql = 'SELECT COUNT(clippings.uid) as clippingscount, SUM(medium.reach) as mediumreach FROM reportingtool\\Models\\Clippings as clippings LEFT JOIN reportingtool\\Models\\Projects as projects ON projects.uid=clippings.pid LEFT JOIN reportingtool\\Models\\Medium as medium ON medium.uid=clippings.mediumuid ' . 'WHERE medium.deleted =0 AND medium.hidden=0 AND clippings.deleted=0 AND clippings.hidden =0 AND projects.deleted=0 AND projects.hidden = 0 AND medium.mediumtype = ?1'; $sQuery = $modelsManager->createQuery($phql); $rResults = $sQuery->execute(array(1 => $mediumtype)); return $rResults[0]; }