public function execute() { /* @var $paths Paths */ $paths = Pimple::getResource('paths'); $path = $paths->getData() . '/activity-log'; if (!file_exists($path) || !is_dir($path)) { mkdir($path, 0777); } $filename = 'GeoLite2.mmdb'; $gzPath = $path . '/' . $filename . '.gz'; $tmpPath = $path . '/' . $filename . '.tmp'; $finalPath = $path . '/' . $filename; file_put_contents($gzPath, file_get_contents($this->getDbUrl()), LOCK_EX); $this->decompressFile($gzPath, $tmpPath); if ($this->computedMd5MatchesPublishedMd5($tmpPath)) { rename($tmpPath, $finalPath); unlink($gzPath); } else { if (file_exists($gzPath)) { unlink($gzPath); } if (file_exists($tmpPath)) { unlink($tmpPath); } throw new Exception('Downloaded file does not match MD5 published by MaxMind.'); } }
/** * Check permissions * * @return void */ protected function checkPermissions() { $user = Pimple::getResource('user'); if ($user->get('user_id') !== (int) $this->request->getQuery('user_id')) { parent::checkPermissions(); } }
/** * Supply the Select object that will be manipulated by this listing. * * @param Select $select * @param DbField $primaryKey * @param Request $request */ public function __construct(Select $select, DbField $primaryKey, Request $request = null) { $this->select = $select; $this->primaryKey = $primaryKey; $this->request = $request ?: Pimple::getResource('dewdrop-request'); $this->registerSelectModifier(new SelectFilter($this->request))->registerSelectModifier(new SelectSort($this->request))->registerSelectModifier(new SelectPaginate($this->request)); }
public function getUser() { if (null === $this->user && Pimple::hasResource('user')) { $this->user = Pimple::getResource('user'); } return $this->user; }
public function getActivityLog() { if (!$this->activityLog) { $this->activityLog = Pimple::getResource('activity-log'); } return $this->activityLog; }
public function setUp() { $this->db = Pimple::getResource('db'); $this->filter = new Groups($this->component, $this->db); $this->filter->deleteCurrentSettings(); $this->fields = new Fields(); $this->fields->add('one')->setLabel('One')->add('two')->setLabel('Two')->add('three')->setLabel('Three')->add('four')->setLabel('Four'); }
public function __construct(Zend_Controller_Request_Abstract $request, Zend_Controller_Response_Abstract $response, array $invokeArgs = array()) { $this->pimple = Pimple::getInstance(); if ($this instanceof CrudInterface) { $this->addPageFactory(new CrudFactory($this)); } $this->env = new Zf1AdminEnv($this); parent::__construct($request, $response, $invokeArgs); }
/** * Create the PDO connection for PHPUnit using constants defined in * wp-config.php. * * @return PDO */ public final function getConnection() { if (!defined('WPINC')) { return $this->createDefaultDBConnection(Pimple::getResource('db')->getConnection(), Pimple::getResource('config')['db']['name']); } else { $connection = new PDO('mysql:dbname=' . DB_NAME . ';host=' . DB_HOST, DB_USER, DB_PASSWORD); return $this->createDefaultDBConnection($connection, DB_NAME); } }
/** * Filter the supplied URL. * * @param string $url * @return mixed */ public function direct($url) { if (!Pimple::hasResource('url-filter')) { return $url; } else { /* @var $filter callable */ $filter = Pimple::getResource('url-filter'); return $filter($url); } }
public static function get() { if (!self::$key) { $paths = Pimple::hasResource('paths') ? Pimple::getResource('paths') : new Paths(); $keyFile = $paths->getData() . '/activity-log/secret-session-cookie-key.php'; if (file_exists($keyFile) && is_readable($keyFile)) { self::$key = trim(file_get_contents($keyFile)); } } return self::$key; }
/** * Provide a Pimple container for retrieval of session storage. * * @param mixed $container */ public function __construct($access = null) { if ($access instanceof PimpleProper) { $access = $access['session.access']; } if (null === $access) { $access = Pimple::getResource('session.access'); } if (!$access instanceof SessionAccessInterface) { throw new Exception('Must provide a SessionAccessInterface object.'); } $this->access = $access; }
/** * Check cookies to see if any cross-request notices were set. * * Right now, we only support the "dewdrop_admin_success_notice" cookie, * which is set by the response helper object after an edit form, for * example, is successfully processed. We may at some point offer a * more flexible way of passing messages through a session API. * * @return string */ private function loadNoticeFromCookies() { if (!Pimple::getResource('paths')->isWp()) { return ''; } $notice = ''; if (isset($_COOKIE['dewdrop_admin_success_notice']) && $_COOKIE['dewdrop_admin_success_notice']) { $notice = $_COOKIE['dewdrop_admin_success_notice']; // Expire/delete cookie setcookie('dewdrop_admin_success_notice', null, 0); } return $notice; }
public function __construct(Table $table, ActivityLog $activityLog = null, Inflector $inflector = null) { $this->table = $table; $this->inflector = $inflector ?: Pimple::getResource('inflector'); $tableName = $table->getTableName(); $inflectedName = $this->inflector->singularize($this->inflector->hyphenize($tableName)); if (!$tableName) { $className = get_class($table); throw new Exception("Cannot create activity log handle for {$className} because no table name is set."); } $this->setActivityLog($activityLog ?: Pimple::getResource('activity-log'))->setName($inflectedName)->setModel($table)->addAlias($tableName); parent::__construct(); }
/** * Provide the component that these permissions should be applied to. * * @param mixed $component * @param null|bool $debug * @throws Exception */ public function __construct($component, $debug = null) { if (!$component instanceof ComponentInterface && !$component instanceof CrudInterface) { throw new Exception('Component must be CopmonentInterface or implement CrudInterface'); } $this->component = $component; $this->debug = null === $debug ? Pimple::getResource('debug') : $debug; $this->register('access', 'Allow access to the ' . $this->component->getTitle() . ' component')->set('access', true); $this->register('display-menu', 'Show the ' . $this->component->getTitle() . ' component in the menu')->set('display-menu', true); if ($this->component instanceof CrudInterface) { $this->registerAndSetDefaultsForCrudInterface($this->component); } }
public function execute() { /* @var $paths Paths */ $paths = Pimple::getResource('paths'); $path = $paths->getData() . '/activity-log'; if (!file_exists($path) || !is_dir($path)) { mkdir($path, 0777); } $fullPath = $path . '/secret-session-cookie-key.php'; if (file_exists($fullPath)) { throw new Exception('Key already present. Delete the current key file if you want to regenerate.'); } else { $key = bin2hex(random_bytes(64)); file_put_contents($fullPath, $key, LOCK_EX); } }
/** * Perform any processing or data manipulation needed before render. * * A response helper object will be passed to this method to allow you to * easily add success messages or redirects. This helper should be used * to handle these kinds of actions so that you can easily test your * page's code. * * @param ResponseHelper $responseHelper * @return ResponseHelper|null */ public function process(ResponseHelper $responseHelper) { $isCurrentUser = $this->row->get('user_id') === Pimple::getResource('user')->get('user_id'); if (!$this->component->getPermissions()->can('edit') && !$isCurrentUser) { return $responseHelper->redirectToUrl('/admin'); } if ($this->request->isPost()) { $this->inputFilter->setData($this->request->getPost()); if ($this->inputFilter->isValid()) { $this->row->hashPassword($this->request->getPost('password'))->save(); if ($isCurrentUser) { return $responseHelper->redirectToUrl('/admin'); } else { return $responseHelper->redirectToAdminPage('index'); } } } }
/** * If no $wwwPath or $docRoot are provided, pull those from the environment. * Return the supplied URL with a prefix pointing to the bower_components * folder, being careful to not double-up on slashes on either end. * * @param string $url * @param string $wwwPath * @param string $docRoot * @return string */ public function direct($url, $wwwPath = null, $docRoot = null) { if (null === $wwwPath) { if (self::$wwwPath) { $wwwPath = self::$wwwPath; } else { $paths = Pimple::getResource('paths'); $docRoot = $docRoot ?: $_SERVER['DOCUMENT_ROOT']; if (false === strpos($paths->getWww(), $docRoot)) { $wwwPath = ''; } else { $wwwPath = trim(str_replace($_SERVER['DOCUMENT_ROOT'], '', $paths->getWww() . '/'), '/'); $wwwPath = $wwwPath ? '/' . $wwwPath : ''; } self::$wwwPath = $wwwPath; } } return $wwwPath . '/bower_components/' . ltrim($url, '/'); }
public function direct(Entry $entry, ActivityLog $activityLog = null) { /* @var $resolver \Dewdrop\ActivityLog\HandlerResolver */ $resolver = Pimple::getResource('activity-log.handler-resolver'); $handlers = new HandlerContainer(); $handlers->setDefault(function (ShortcodeInterface $s) use($entry, $resolver) { try { $handler = $resolver->resolve($s->getName()); $entity = $entry->getEntity($handler, $s->getParameter('id')); return trim($this->view->activityLogEntity($entity)); } catch (ActivityLog\Exception\HandlerNotFound $e) { return '<strong>Unknown Type</strong>'; } catch (ActivityLog\Exception\EntityNotFound $e) { return '<strong>Entity Not in DB</strong>'; } }); $processor = new Processor(new RegularParser(), $handlers); return $processor->process($entry->getMessage()); }
public function getMessage($name, array $templateValues) { if (!array_key_exists($name, $this->anonymousMessages)) { throw new TemplateNotFound("Message template not found with name '{$name}'."); } $user = $this->user; if (!$user && Pimple::hasResource('user')) { $user = Pimple::getResource('user'); } $userHandler = null; try { $userHandler = $this->handlerResolver->resolve('user'); } catch (HandlerNotFound $e) { // OK to proceed without the user handler. Will just treat as anonymous. } if (!$user || !$userHandler) { $template = $this->anonymousMessages[$name]; } else { $template = $this->userMessages[$name]; // Automatically include %user% value when available. $templateValues['%user%'] = $userHandler->createEntity($user->getId()); } return $this->renderTemplateTags($template, $templateValues); }
/** * Provides a response to the request * * @return string|\Symfony\Component\HttpFoundation\RedirectResponse * @throws Exception */ public function respond() { $request = Pimple::getResource('dewdrop-request'); if ($request->isPost()) { if (6 > strlen($request->getPost('password'))) { $this->view->assign('error', 'Password must be at least 6 characters long.'); } elseif ($request->getPost('password') !== $request->getPost('confirm')) { $this->view->assign('error', 'Passwords do not match.'); } else { $userAndToken = $this->getUserAndTokenRows($this->request->query->get('token')); $userAndToken['token']->set('used', 1)->save(); $userAndToken['user']->hashPassword($request->getPost('password'))->save(); return $this->app->redirect('/auth/login?token=' . $userAndToken['token']->get('token')); } } try { $userAndToken = $this->getUserAndTokenRows($this->request->query->get('token')); $this->view->assign('user', $userAndToken['user']); } catch (Exception $e) { $this->view->assign('invalidToken', true); } $this->view->assign('password', $request->getPost('password'))->assign('confirm', $request->getPost('confirm')); return $this->renderLayout($this->view->render('reset-password.phtml')); }
/** * Optionally supply an array of fields that can be used as an initial * set for this collection. * * @param array $fields * @param UserInterface $user */ public function __construct(array $fields = null, UserInterface $user = null) { if (is_array($fields)) { foreach ($fields as $field) { $this->add($field); } } if (null !== $user) { $this->user = $user; } elseif (Pimple::hasResource('user') && Pimple::getResource('user') instanceof UserInterface) { $this->user = Pimple::getResource('user'); } }
/** * @expectedException \Dewdrop\Exception */ public function testComponentWithEmptyInitThrowsException() { require_once __DIR__ . '/../test-components/insufficient-init-method/Component.php'; new \DewdropTest\Admin\InsufficientInitMethod\Component(Pimple::getInstance()); }
/** * Setup the default changesets. If a changeset has already been configured with a given * name, the default will not be applied. This is done primarily to allow the * overrideChangesetPath() method to swap out the default paths during testing. * * @return void */ protected function initChangesets() { $mainChangesetName = Env::getInstance()->getProjectNoun(); $defaultChangesets = ['dewdrop-core' => $this->paths->getDewdropLib() . '/db/' . $this->dbType, $mainChangesetName => $this->paths->getPluginRoot() . '/db', 'dewdrop-test' => $this->paths->getDewdropLib() . '/tests/db/' . $this->dbType]; if (Pimple::hasResource('dbdeploy.changesets')) { $defaultChangesets = array_merge($defaultChangesets, Pimple::getResource('dbdeploy.changesets')); } foreach ($defaultChangesets as $name => $path) { if (!array_key_exists($name, $this->changesets)) { $this->changesets[$name] = $path; } } }
/** * Hashes the given plain text password and stores the result, which can be retrieved with getPassword() * * @param string $plaintextPassword * @return UserRowGateway */ public function hashPassword($plaintextPassword) { $encoder = Pimple::getResource('security.encoder.digest'); $this->set('password_hash', $encoder->encodePassword(trim($plaintextPassword), '')); return $this; }
<?php // On prod, most code is tucked into zend outside the doc root if (file_exists(__DIR__ . '/../zend/')) { define('APPLICATION_PATH', realpath(__DIR__ . '/../zend/')); } else { define('APPLICATION_PATH', realpath(__DIR__ . '/../')); } require_once APPLICATION_PATH . '/vendor/autoload.php'; use Dewdrop\Pimple; /* @var $silex \Silex\Application */ $silex = Pimple::getInstance(); $silex->get('/', function () { return file_get_contents(__DIR__ . '/dewdrop-index.html'); }); Pimple::getResource('admin')->registerComponentsInPath(); $silex->run();
/** * Returns table metadata filesystem path. * * @return string */ public function getTableMetadataPath() { if (null === $this->tableMetadataPath) { /* @var $paths Paths */ $paths = Pimple::getResource('paths'); $this->tableMetadataPath = $paths->getModels() . '/metadata'; } return $this->tableMetadataPath; }
/** * Get the InputFilterBuilder that can be used to create default validators * and filters for the field. * * @return InputFilterBuilder */ public function getInputFilterBuilder() { return $this->inputFilterBuilder ?: Pimple::getResource('db.field.input-filter-builder'); }
/** * Pass a whole log of stuff into the view. */ public function render() { $fields = $this->component->getFields(); $listing = $this->component->getListing(); $filter = $this->component->getVisibilityFilter(); $this->view->assign(['component' => $this->component, 'permissions' => $this->component->getPermissions(), 'singularTitle' => $this->component->getPrimaryModel()->getSingularTitle(), 'pluralTitle' => $this->component->getPrimaryModel()->getPluralTitle(), 'listing' => $listing, 'visibilityFilter' => $filter, 'groupingFilter' => $this->component->getFieldGroupsFilter(), 'fields' => $fields, 'debug' => Pimple::getResource('debug'), 'isSortable' => $this->component instanceof SortableListingInterface, 'page' => $this, 'createUrl' => $this->getCreateUrl()]); if ($this->component instanceof BulkActionProcessorInterface) { $this->view->assign(['bulkActions' => $this->component->getBulkActions(), 'bulkActionFailureMessage' => $this->bulkActionFailureMessage]); } return $this->renderView(); }
/** * Generate a URL for the provided page and params that will match the * Silex routes set up by this class. * * @param ComponentInterface $component * @param string $page * @param array $params * @return string */ public function url(ComponentInterface $component, $page, array $params = array()) { $url = '/admin/' . $component->getName() . '/' . $this->application['inflector']->hyphenize($page) . $this->assembleQueryString($params, '?'); if (Pimple::hasResource('url-filter')) { /* @var $filter callable */ $filter = Pimple::getResource('url-filter'); $url = $filter($url); } return $url; }
public function renderLinkUrl($primaryKeyValue) { $linkTemplate = $this->defaultLinkTemplate; $user = $this->user; if (null === $user && Pimple::hasResource('user') && Pimple::getResource('user') instanceof UserInterface) { $user = Pimple::getResource('user'); } foreach ($this->roleSpecificLinkTemplates as $role => $roleSpecificLinkTemplate) { if ($user && $user->hasRole($role)) { $linkTemplate = $roleSpecificLinkTemplate; } } if (!$linkTemplate) { return null; } /* @var $urlFilter callable */ $urlFilter = Pimple::getResource('url-filter'); $linkTemplate = $urlFilter($linkTemplate); return sprintf($linkTemplate, $primaryKeyValue); }