コード例 #1
0
 /**
  * @return FixtureFactory
  */
 public function getFixtureFactory()
 {
     if (!$this->fixtureFactory) {
         $this->fixtureFactory = Injector::inst()->create('SilverStripe\\Dev\\BehatFixtureFactory');
     }
     return $this->fixtureFactory;
 }
コード例 #2
0
 public function __construct()
 {
     $this->session = Injector::inst()->create('SilverStripe\\Control\\Session', array());
     $this->cookies = Injector::inst()->create('SilverStripe\\Control\\Cookie_Backend');
     $this->controller = new Controller();
     $this->controller->setSession($this->session);
     $this->controller->pushCurrent();
 }
コード例 #3
0
 /**
  * Get the authenticator instance
  *
  * @return Authenticator Returns the authenticator instance for this login form.
  */
 public function getAuthenticator()
 {
     if (!class_exists($this->authenticator_class) || !is_subclass_of($this->authenticator_class, 'SilverStripe\\Security\\Authenticator')) {
         user_error("The form uses an invalid authenticator class! '{$this->authenticator_class}'" . " is not a subclass of 'Authenticator'", E_USER_ERROR);
         return null;
     }
     return Injector::inst()->get($this->authenticator_class);
 }
コード例 #4
0
 public function testWriteInto()
 {
     $factory = Injector::inst()->create('SilverStripe\\Dev\\FixtureFactory');
     $relPath = ltrim(FRAMEWORK_DIR . '/tests/testing/YamlFixtureTest.yml', '/');
     $fixture = Injector::inst()->create('SilverStripe\\Dev\\YamlFixture', $relPath);
     $fixture->writeInto($factory);
     $this->assertGreaterThan(0, $factory->getId("YamlFixtureTest_DataObject", "testobject1"));
 }
コード例 #5
0
 public function index()
 {
     foreach (ClassInfo::subclassesFor($this->class) as $subclass) {
         echo $subclass . "\n";
         /** @var CliController $task */
         $task = Injector::inst()->create($subclass);
         $task->doInit();
         $task->process();
     }
 }
コード例 #6
0
 /**
  * @param string $name Unique name for this blueprint
  * @param array|FixtureBlueprint $defaults Array of default values, or a blueprint instance
  * @return $this
  */
 public function define($name, $defaults = array())
 {
     if ($defaults instanceof FixtureBlueprint) {
         $this->blueprints[$name] = $defaults;
     } else {
         $class = $name;
         $this->blueprints[$name] = Injector::inst()->create('SilverStripe\\Dev\\FixtureBlueprint', $name, $class, $defaults);
     }
     return $this;
 }
コード例 #7
0
 public function __construct()
 {
     parent::__construct();
     $session = Injector::inst()->create('SilverStripe\\Control\\Session', isset($_SESSION) ? $_SESSION : array());
     $this->setSession($session);
     $this->pushCurrent();
     $request = new HTTPRequest(isset($_SERVER['X-HTTP-Method-Override']) ? $_SERVER['X-HTTP-Method-Override'] : $_SERVER['REQUEST_METHOD'], '/');
     $this->setRequest($request);
     $this->setResponse(new HTTPResponse());
     $this->doInit();
 }
コード例 #8
0
 public function testSanitisation()
 {
     $tests = array(array('p,strong', '<p>Leave Alone</p><div>Strip parent<strong>But keep children</strong> in order</div>', '<p>Leave Alone</p>Strip parent<strong>But keep children</strong> in order', 'Non-whitelisted elements are stripped, but children are kept'), array('p,strong', '<div>A <strong>B <div>Nested elements are still filtered</div> C</strong> D</div>', 'A <strong>B Nested elements are still filtered C</strong> D', 'Non-whitelisted elements are stripped even when children of non-whitelisted elements'), array('p', '<p>Keep</p><script>Strip <strong>including children</strong></script>', '<p>Keep</p>', 'Non-whitelisted script elements are totally stripped, including any children'), array('p[id]', '<p id="keep" bad="strip">Test</p>', '<p id="keep">Test</p>', 'Non-whitelisted attributes are stripped'), array('p[default1=default1|default2=default2|force1:force1|force2:force2]', '<p default1="specific1" force1="specific1">Test</p>', '<p default1="specific1" force1="force1" default2="default2" force2="force2">Test</p>', 'Default attributes are set when not present in input, forced attributes are always set'));
     $config = HTMLEditorConfig::get('htmleditorsanitisertest');
     foreach ($tests as $test) {
         list($validElements, $input, $output, $desc) = $test;
         $config->setOptions(array('valid_elements' => $validElements));
         $sanitiser = new HtmlEditorSanitiser($config);
         $htmlValue = Injector::inst()->create('HTMLValue', $input);
         $sanitiser->sanitise($htmlValue);
         $this->assertEquals($output, $htmlValue->getContent(), $desc);
     }
 }
コード例 #9
0
 /**
  * This is the main method to build the master string tables with the original strings.
  * It will search for existent modules that use the i18n feature, parse the _t() calls
  * and write the resultant files in the lang folder of each module.
  *
  * @uses DataObject->collectI18nStatics()
  *
  * @param HTTPRequest $request
  */
 public function run($request)
 {
     increase_time_limit_to();
     $collector = i18nTextCollector::create($request->getVar('locale'));
     $merge = $this->getIsMerge($request);
     // Custom writer
     $writerName = $request->getVar('writer');
     if ($writerName) {
         $writer = Injector::inst()->get($writerName);
         $collector->setWriter($writer);
     }
     // Get restrictions
     $restrictModules = $request->getVar('module') ? explode(',', $request->getVar('module')) : null;
     $collector->run($restrictModules, $merge);
     Debug::message(__CLASS__ . " completed!", false);
 }
コード例 #10
0
 public function testSendHTML()
 {
     // Set custom $project - used in email headers
     global $project;
     $oldProject = $project;
     $project = 'emailtest';
     Injector::inst()->registerService(new EmailTest_Mailer(), 'SilverStripe\\Control\\Email\\Mailer');
     $email = new Email('*****@*****.**', '*****@*****.**', 'Test send plain', 'Testing Email->send()', null, '*****@*****.**', '*****@*****.**');
     $email->attachFile(__DIR__ . '/fixtures/attachment.txt', null, 'text/plain');
     $email->addCustomHeader('foo', 'bar');
     $sent = $email->send(123);
     // Restore old project name after sending
     $project = $oldProject;
     $this->assertEquals('*****@*****.**', $sent['to']);
     $this->assertEquals('*****@*****.**', $sent['from']);
     $this->assertEquals('Test send plain', $sent['subject']);
     $this->assertContains('Testing Email-&gt;send()', $sent['content']);
     $this->assertNull($sent['plaincontent']);
     $this->assertEquals(array(0 => array('contents' => 'Hello, I\'m a text document.', 'filename' => 'attachment.txt', 'mimetype' => 'text/plain')), $sent['files']);
     $this->assertEquals(array('foo' => 'bar', 'X-SilverStripeMessageID' => 'emailtest.123', 'X-SilverStripeSite' => 'emailtest', 'Cc' => '*****@*****.**', 'Bcc' => '*****@*****.**'), $sent['customheaders']);
 }
コード例 #11
0
 /**
  *  Attempt to clean invalid HTML, which messes up diffs.
  *  This cleans code if possible, using an instance of HTMLCleaner
  *
  *  NB: By default, only extremely simple tidying is performed,
  *  by passing through DomDocument::loadHTML and saveXML
  *
  * @param string $content HTML content
  * @param HTMLCleaner $cleaner Optional instance of a HTMLCleaner class to
  *    use, overriding self::$html_cleaner_class
  * @return mixed|string
  */
 public static function cleanHTML($content, $cleaner = null)
 {
     if (!$cleaner) {
         if (self::$html_cleaner_class && class_exists(self::$html_cleaner_class)) {
             $cleaner = Injector::inst()->create(self::$html_cleaner_class);
         } else {
             //load cleaner if the dependent class is available
             $cleaner = HTMLCleaner::inst();
         }
     }
     if ($cleaner) {
         $content = $cleaner->cleanHTML($content);
     } else {
         // At most basic level of cleaning, use DOMDocument to save valid XML.
         $doc = Injector::inst()->create('HTMLValue', $content);
         $content = $doc->getContent();
     }
     // Remove empty <ins /> and <del /> tags because browsers hate them
     $content = preg_replace('/<(ins|del)[^>]*\\/>/', '', $content);
     return $content;
 }
コード例 #12
0
 /**
  * @param HTTPRequest $request
  */
 public function runTask($request)
 {
     $name = $request->param('TaskName');
     $tasks = $this->getTasks();
     $title = function ($content) {
         printf(Director::is_cli() ? "%s\n\n" : '<h1>%s</h1>', $content);
     };
     $message = function ($content) {
         printf(Director::is_cli() ? "%s\n" : '<p>%s</p>', $content);
     };
     foreach ($tasks as $task) {
         if ($task['segment'] == $name) {
             $inst = Injector::inst()->create($task['class']);
             $title(sprintf('Running Task %s', $inst->getTitle()));
             if (!$inst->isEnabled()) {
                 $message('The task is disabled');
                 return;
             }
             $inst->run($request);
             return;
         }
     }
     $message(sprintf('The build task "%s" could not be found', Convert::raw2xml($name)));
 }
コード例 #13
0
 public function createDataObject($row)
 {
     // Add joined record
     $joinRow = [];
     $joinAlias = $this->manipulator->getJoinAlias();
     $prefix = $joinAlias . '_';
     foreach ($row as $key => $value) {
         if (strpos($key, $prefix) === 0) {
             $joinKey = substr($key, strlen($prefix));
             $joinRow[$joinKey] = $value;
             unset($row[$key]);
         }
     }
     // Create parent record
     $record = parent::createDataObject($row);
     // Create joined record
     if ($joinRow) {
         $joinClass = $this->manipulator->getJoinClass();
         $joinQueryParams = $this->manipulator->extractInheritableQueryParameters($this->dataQuery);
         $joinRecord = Injector::inst()->create($joinClass, $joinRow, false, $this->model, $joinQueryParams);
         $record->setJoin($joinRecord, $joinAlias);
     }
     return $record;
 }
コード例 #14
0
    // For SQlite3 memory databases (mainly for testing purposes)
    if (defined('SS_DATABASE_MEMORY')) {
        $databaseConfig["memory"] = SS_DATABASE_MEMORY;
    }
}
if (defined('SS_SEND_ALL_EMAILS_TO')) {
    Email::config()->send_all_emails_to = SS_SEND_ALL_EMAILS_TO;
}
if (defined('SS_SEND_ALL_EMAILS_FROM')) {
    Email::config()->send_all_emails_from = SS_SEND_ALL_EMAILS_FROM;
}
if (defined('SS_DEFAULT_ADMIN_USERNAME')) {
    if (!defined('SS_DEFAULT_ADMIN_PASSWORD')) {
        user_error("SS_DEFAULT_ADMIN_PASSWORD must be defined in your _ss_environment.php," . "if SS_DEFAULT_ADMIN_USERNAME is defined.  See " . "http://doc.silverstripe.org/framework/en/topics/environment-management for more information", E_USER_ERROR);
    } else {
        Security::setDefaultAdmin(SS_DEFAULT_ADMIN_USERNAME, SS_DEFAULT_ADMIN_PASSWORD);
    }
}
if (defined('SS_USE_BASIC_AUTH') && SS_USE_BASIC_AUTH) {
    BasicAuth::config()->entire_site_protected = SS_USE_BASIC_AUTH;
}
if (defined('SS_ERROR_LOG')) {
    $logger = Injector::inst()->get('Logger');
    if ($logger instanceof Logger) {
        $logger->pushHandler(new StreamHandler(BASE_PATH . '/' . SS_ERROR_LOG, Logger::WARNING));
    } else {
        user_error("SS_ERROR_LOG setting only works with Monolog, you are using another logger", E_USER_WARNING);
    }
}
// Allow database adapters to handle their own configuration
DatabaseAdapterRegistry::autoconfigure();
コード例 #15
0
 /**
  * Return a {@link FormTemplateHelper} for this form. If one has not been
  * set, return the default helper.
  *
  * @return FormTemplateHelper
  */
 public function getTemplateHelper()
 {
     if ($this->templateHelper) {
         if (is_string($this->templateHelper)) {
             return Injector::inst()->get($this->templateHelper);
         }
         return $this->templateHelper;
     }
     return FormTemplateHelper::singleton();
 }
コード例 #16
0
 public function handleRequest(HTTPRequest $request, DataModel $model)
 {
     // If this is the final portion of the request (i.e. the URL is just /admin), direct to the default panel
     if ($request->allParsed()) {
         $segment = Config::inst()->get($this->config()->default_panel, 'url_segment');
         $this->redirect(Controller::join_links(self::admin_url(), $segment, '/'));
         return $this->getResponse();
     } else {
         $rules = self::rules();
         foreach ($rules as $pattern => $controller) {
             if (($arguments = $request->match($pattern, true)) !== false) {
                 $controllerObj = Injector::inst()->create($controller);
                 $controllerObj->setSession($this->session);
                 return $controllerObj->handleRequest($request, $model);
             }
         }
     }
     return $this->httpError(404, 'Not found');
 }
コード例 #17
0
 function CacheBlock_CacheBlockTemplate(&$res, $sub)
 {
     // Get the block counter
     $block = ++$res['subblocks'];
     // Build the key for this block from the global key (evaluated in a closure within the template),
     // the passed cache key, the block index, and the sha hash of the template.
     $res['php'] .= '$keyExpression = function() use ($scope, $cache) {' . PHP_EOL;
     $res['php'] .= '$val = \'\';' . PHP_EOL;
     if ($globalKey = SSViewer::config()->get('global_key')) {
         // Embed the code necessary to evaluate the globalKey directly into the template,
         // so that SSTemplateParser only needs to be called during template regeneration.
         // Warning: If the global key is changed, it's necessary to flush the template cache.
         $parser = Injector::inst()->get(__CLASS__, false);
         $result = $parser->compileString($globalKey, '', false, false);
         if (!$result) {
             throw new SSTemplateParseException('Unexpected problem parsing template', $parser);
         }
         $res['php'] .= $result . PHP_EOL;
     }
     $res['php'] .= 'return $val;' . PHP_EOL;
     $res['php'] .= '};' . PHP_EOL;
     $key = 'sha1($keyExpression())' . '.\'_' . sha1($sub['php']) . (isset($res['key']) && $res['key'] ? "_'.sha1(" . $res['key'] . ")" : "'") . ".'_{$block}'";
     // block index
     // Get any condition
     $condition = isset($res['condition']) ? $res['condition'] : '';
     $res['php'] .= 'if (' . $condition . '($partial = $cache->load(' . $key . '))) $val .= $partial;' . PHP_EOL;
     $res['php'] .= 'else { $oldval = $val; $val = "";' . PHP_EOL;
     $res['php'] .= $sub['php'] . PHP_EOL;
     $res['php'] .= $condition . ' $cache->save($val); $val = $oldval . $val;' . PHP_EOL;
     $res['php'] .= '}';
 }
コード例 #18
0
 /**
  * Return the string-format type for the given field.
  *
  * @param string $field
  * @return string 'xml'|'raw'
  */
 public function escapeTypeForField($field)
 {
     $class = $this->castingClass($field) ?: $this->config()->default_cast;
     // TODO: It would be quicker not to instantiate the object, but to merely
     // get its class from the Injector
     return Injector::inst()->get($class, true)->config()->escape_type;
 }
コード例 #19
0
 /**
  * Construct a new SQLSelect.
  *
  * @param array|string $select An array of SELECT fields.
  * @param array|string $from An array of FROM clauses. The first one should be just the table name.
  * Each should be ANSI quoted.
  * @param array $where An array of WHERE clauses.
  * @param array $orderby An array ORDER BY clause.
  * @param array $groupby An array of GROUP BY clauses.
  * @param array $having An array of HAVING clauses.
  * @param array|string $limit A LIMIT clause or array with limit and offset keys
  * @return static
  */
 public static function create($select = "*", $from = array(), $where = array(), $orderby = array(), $groupby = array(), $having = array(), $limit = array())
 {
     return Injector::inst()->createWithArgs(__CLASS__, func_get_args());
 }
コード例 #20
0
 /**
  * Returns the parser that is set for template generation
  *
  * @return TemplateParser
  */
 public function getParser()
 {
     if (!$this->parser) {
         $this->setParser(Injector::inst()->get('SilverStripe\\View\\SSTemplateParser'));
     }
     return $this->parser;
 }
コード例 #21
0
/**
 * Creates a class instance by the "singleton" design pattern.
 * It will always return the same instance for this class,
 * which can be used for performance reasons and as a simple
 * way to access instance methods which don't rely on instance
 * data (e.g. the custom SilverStripe static handling).
 *
 * @param string $className
 * @return mixed
 */
function singleton($className)
{
    if ($className === 'SilverStripe\\Core\\Config\\Config') {
        throw new InvalidArgumentException("Don't pass Config to singleton()");
    }
    if (!isset($className)) {
        throw new InvalidArgumentException("singleton() Called without a class");
    }
    if (!is_string($className)) {
        throw new InvalidArgumentException("singleton() passed bad class_name: " . var_export($className, true));
    }
    return Injector::inst()->get($className);
}
コード例 #22
0
 /**
  * Defines a default list of filters for the search context.
  *
  * If a filter class mapping is defined on the data object,
  * it is constructed here. Otherwise, the default filter specified in
  * {@link DBField} is used.
  *
  * @todo error handling/type checking for valid FormField and SearchFilter subclasses?
  *
  * @return array
  */
 public function defaultSearchFilters()
 {
     $filters = array();
     foreach ($this->searchableFields() as $name => $spec) {
         if (empty($spec['filter'])) {
             /** @skipUpgrade */
             $filters[$name] = 'PartialMatchFilter';
         } elseif ($spec['filter'] instanceof SearchFilter) {
             $filters[$name] = $spec['filter'];
         } else {
             $filters[$name] = Injector::inst()->create($spec['filter'], $name);
         }
     }
     return $filters;
 }
コード例 #23
0
 /**
  * Create new item.
  *
  * @param string|int $id
  * @param bool $setID
  * @return DataObject
  */
 public function getNewItem($id, $setID = true)
 {
     $class = $this->stat('tree_class');
     $object = Injector::inst()->create($class);
     if ($setID) {
         $object->ID = $id;
     }
     return $object;
 }
コード例 #24
0
 /**
  * Reset the testing database's schema.
  * @param bool $includeExtraDataObjects If true, the extraDataObjects tables will also be included
  */
 public function resetDBSchema($includeExtraDataObjects = false)
 {
     if (self::using_temp_db()) {
         DataObject::reset();
         // clear singletons, they're caching old extension info which is used in DatabaseAdmin->doBuild()
         Injector::inst()->unregisterAllObjects();
         $dataClasses = ClassInfo::subclassesFor('SilverStripe\\ORM\\DataObject');
         array_shift($dataClasses);
         DB::quiet();
         $schema = DB::get_schema();
         $extraDataObjects = $includeExtraDataObjects ? $this->extraDataObjects : null;
         $schema->schemaUpdate(function () use($dataClasses, $extraDataObjects) {
             foreach ($dataClasses as $dataClass) {
                 // Check if class exists before trying to instantiate - this sidesteps any manifest weirdness
                 if (class_exists($dataClass)) {
                     $SNG = singleton($dataClass);
                     if (!$SNG instanceof TestOnly) {
                         $SNG->requireTable();
                     }
                 }
             }
             // If we have additional dataobjects which need schema, do so here:
             if ($extraDataObjects) {
                 foreach ($extraDataObjects as $dataClass) {
                     $SNG = singleton($dataClass);
                     if (singleton($dataClass) instanceof DataObject) {
                         $SNG->requireTable();
                     }
                 }
             }
         });
         ClassInfo::reset_db_cache();
         singleton('SilverStripe\\ORM\\DataObject')->flushCache();
     }
 }
コード例 #25
0
 /**
  * @todo documentation
  *
  * @todo figure out how we pass configuration parameters to
  *       search filters (note: parameter hack now in place to pass in the required full path - using $this->name
  *       won't work)
  *
  * @param string $name Override name of this field
  * @return SearchFilter
  */
 public function defaultSearchFilter($name = null)
 {
     $name = $name ? $name : $this->name;
     $filterClass = $this->stat('default_search_filter_class');
     return Injector::inst()->create($filterClass, $name);
 }
コード例 #26
0
 /**
  * Pushes this controller onto the stack of current controllers. This means that any redirection,
  * session setting, or other things that rely on Controller::curr() will now write to this
  * controller object.
  */
 public function pushCurrent()
 {
     array_unshift(self::$controller_stack, $this);
     // Create a new session object
     if (!$this->session) {
         if (isset(self::$controller_stack[1])) {
             $this->session = self::$controller_stack[1]->getSession();
         } else {
             $this->session = Injector::inst()->create('SilverStripe\\Control\\Session', array());
         }
     }
 }
コード例 #27
0
 /**
  * Get an asset renamer for the given filename.
  *
  * @param string $fileID Adapter specific identifier for this file/version
  * @return AssetNameGenerator
  */
 protected function fileGeneratorFor($fileID)
 {
     return Injector::inst()->createWithArgs('AssetNameGenerator', array($fileID));
 }
コード例 #28
0
    /**
     * Generate a secure token which can be used as a crypto key.
     * Returns the token and suggests PHP configuration to set it.
     */
    public function generatesecuretoken()
    {
        $generator = Injector::inst()->create('SilverStripe\\Security\\RandomGenerator');
        $token = $generator->randomToken('sha1');
        $body = <<<TXT
Generated new token. Please add the following code to your YAML configuration:

Security:
  token: {$token}

TXT;
        $response = new HTTPResponse($body);
        return $response->addHeader('Content-Type', 'text/plain');
    }
コード例 #29
0
 /**
  * @return AssetStore
  */
 protected function getAssetStore()
 {
     return Injector::inst()->get('AssetStore');
 }
コード例 #30
0
 /**
  * Create an instance of an appropriate DebugView object.
  *
  * @return DebugView
  */
 public static function create_debug_view()
 {
     $service = Director::is_cli() || Director::is_ajax() ? 'SilverStripe\\Dev\\CliDebugView' : 'SilverStripe\\Dev\\DebugView';
     return Injector::inst()->get($service);
 }