/**
  * Create member account from data array.
  * Data must contain unique identifier.
  *
  * @throws ValidationException
  * @param $data - map of member data
  * @return Member|boolean - new member (not saved to db), or false if there is an error.
  */
 public function create($data)
 {
     $result = new ValidationResult();
     if (!Checkout::member_creation_enabled()) {
         $result->error(_t("Checkout.MEMBERSHIPSNOTALLOWED", "Creating new memberships is not allowed"));
         throw new ValidationException($result);
     }
     $idfield = Config::inst()->get('Member', 'unique_identifier_field');
     if (!isset($data[$idfield]) || empty($data[$idfield])) {
         $result->error(sprintf(_t("Checkout.IDFIELDNOTFOUND", "Required field not found: %s"), $idfield));
         throw new ValidationException($result);
     }
     if (!isset($data['Password']) || empty($data['Password'])) {
         $result->error(_t("Checkout.PASSWORDREQUIRED", "A password is required"));
         throw new ValidationException($result);
     }
     $idval = $data[$idfield];
     if (ShopMember::get_by_identifier($idval)) {
         $result->error(sprintf(_t("Checkout.MEMBEREXISTS", "A member already exists with the %s %s"), _t("Member." . $idfield, $idfield), $idval));
         throw new ValidationException($result);
     }
     $member = new Member(Convert::raw2sql($data));
     $validation = $member->validate();
     if (!$validation->valid()) {
         //TODO need to handle i18n here?
         $result->error($validation->message());
     }
     if (!$result->valid()) {
         throw new ValidationException($result);
     }
     return $member;
 }
Esempio n. 2
0
 /**
  * set_default_quality
  *
  * @deprecated 4.0 Use the "ImagickBackend.default_quality" config setting instead
  * @param int $quality
  * @return void
  */
 public static function set_default_quality($quality)
 {
     Deprecation::notice('4.0', 'Use the "ImagickBackend.default_quality" config setting instead');
     if (is_numeric($quality) && (int) $quality >= 0 && (int) $quality <= 100) {
         Config::inst()->update('ImagickBackend', 'default_quality', (int) $quality);
     }
 }
 public function sendMessage($source, $message, $recipients, $arguments = array())
 {
     $from = empty($arguments['from']) ? Config::inst()->get(get_class($this), 'default_from') : $arguments['from'];
     $subject = empty($arguments['subject']) ? Config::inst()->get(get_class($this), 'default_subject') : $arguments['subject'];
     // Split users and send individually
     $this->sendIndividualMessages($source, $message, $recipients, $from, $subject);
 }
 public function preRequest(SS_HTTPRequest $request, Session $session, DataModel $model)
 {
     if (!$this->testSessionEnvironment->isRunningTests()) {
         return;
     }
     $testState = $this->testSessionEnvironment->getState();
     // Date and time
     if (isset($testState->datetime)) {
         SS_Datetime::set_mock_now($testState->datetime);
     }
     // Register mailer
     if (isset($testState->mailer)) {
         $mailer = $testState->mailer;
         Email::set_mailer(new $mailer());
         Config::inst()->update("Email", "send_all_emails_to", null);
     }
     // Allows inclusion of a PHP file, usually with procedural commands
     // to set up required test state. The file can be generated
     // through {@link TestSessionStubCodeWriter}, and the session state
     // set through {@link TestSessionController->set()} and the
     // 'testsession.stubfile' state parameter.
     if (isset($testState->stubfile)) {
         $file = $testState->stubfile;
         if (!Director::isLive() && $file && file_exists($file)) {
             // Connect to the database so the included code can interact with it
             global $databaseConfig;
             if ($databaseConfig) {
                 DB::connect($databaseConfig);
             }
             include_once $file;
         }
     }
 }
 public function testRequestProtocolReflectedInGetOembedFromUrl()
 {
     Config::inst()->update('Oembed', 'providers', array('http://*.silverstripe.com/watch*' => array('http' => 'http://www.silverstripe.com/oembed/', 'https' => 'https://www.silverstripe.com/oembed/?scheme=https'), 'https://*.silverstripe.com/watch*' => array('http' => 'http://www.silverstripe.com/oembed/', 'https' => 'https://www.silverstripe.com/oembed/?scheme=https')));
     Config::inst()->update('Director', 'alternate_protocol', 'http');
     foreach (array('http', 'https') as $protocol) {
         $url = $protocol . '://www.silverstripe.com/watch12345';
         $result = Oembed::get_oembed_from_url($url);
         $this->assertInstanceOf('Oembed_Result', $result);
         $this->assertEquals($result->getOembedURL(), 'http://www.silverstripe.com/oembed/?format=json&url=' . urlencode($url), 'Returns http based URLs when request is over http, regardless of source URL');
     }
     Config::inst()->update('Director', 'alternate_protocol', 'https');
     foreach (array('http', 'https') as $protocol) {
         $url = $protocol . '://www.silverstripe.com/watch12345';
         $result = Oembed::get_oembed_from_url($url);
         $this->assertInstanceOf('Oembed_Result', $result);
         $this->assertEquals($result->getOembedURL(), 'https://www.silverstripe.com/oembed/?scheme=https&format=json&url=' . urlencode($url), 'Returns https based URLs when request is over https, regardless of source URL');
     }
     Config::inst()->update('Director', 'alternate_protocol', 'foo');
     foreach (array('http', 'https') as $protocol) {
         $url = $protocol . '://www.silverstripe.com/watch12345';
         $result = Oembed::get_oembed_from_url($url);
         $this->assertInstanceOf('Oembed_Result', $result);
         $this->assertEquals($result->getOembedURL(), 'http://www.silverstripe.com/oembed/?format=json&url=' . urlencode($url), 'When request protocol doesn\'t have specific handler, fall back to first option');
     }
 }
 /**
  * Bulk load a set of members using the same meta-data rules as if they were to log in
  * @param SS_List $members A list of members
  * @return IntercomBulkJob
  */
 public function bulkLoadUsers(SS_List $members)
 {
     $userFields = Config::inst()->get('Intercom', 'user_fields');
     $companyFields = Config::inst()->get('Intercom', 'company_fields');
     $scriptTags = new IntercomScriptTags();
     // Build the batch API submission
     foreach ($members as $member) {
         $settings = $scriptTags->getIntercomSettings($member);
         unset($settings['app_id']);
         unset($settings['user_hash']);
         foreach ($settings as $k => $v) {
             if (!in_array($k, $userFields)) {
                 $settings['custom_attributes'][$k] = $v;
                 unset($settings[$k]);
             }
         }
         if (isset($settings['company'])) {
             foreach ($settings['company'] as $k => $v) {
                 if (!in_array($k, $companyFields)) {
                     $settings['company']['custom_attributes'][$k] = $v;
                     unset($settings['company'][$k]);
                 }
             }
         }
         $items[] = ['data_type' => 'user', 'method' => 'post', 'data' => $settings];
     }
     $result = $this->getClient()->bulkUsers(['items' => $items]);
     return $this->getBulkJob($result->get('id'));
 }
 public function testEnablePluginsByArrayWithPaths()
 {
     Config::inst()->update('Director', 'alternate_base_url', 'http://mysite.com/subdir');
     $c = new TinyMCEConfig();
     $c->setTheme('modern');
     $c->setOption('language', 'es');
     $c->disablePlugins('table', 'emoticons', 'paste', 'code', 'link', 'importcss');
     $c->enablePlugins(array('plugin1' => 'mypath/plugin1.js', 'plugin2' => '/anotherbase/mypath/plugin2.js', 'plugin3' => 'https://www.google.com/plugin.js', 'plugin4' => null, 'plugin5' => null));
     $attributes = $c->getAttributes();
     $config = Convert::json2array($attributes['data-config']);
     $plugins = $config['external_plugins'];
     $this->assertNotEmpty($plugins);
     // Plugin specified via relative url
     $this->assertContains('plugin1', array_keys($plugins));
     $this->assertEquals('http://mysite.com/subdir/mypath/plugin1.js', $plugins['plugin1']);
     // Plugin specified via root-relative url
     $this->assertContains('plugin2', array_keys($plugins));
     $this->assertEquals('http://mysite.com/anotherbase/mypath/plugin2.js', $plugins['plugin2']);
     // Plugin specified with absolute url
     $this->assertContains('plugin3', array_keys($plugins));
     $this->assertEquals('https://www.google.com/plugin.js', $plugins['plugin3']);
     // Plugin specified with standard location
     $this->assertContains('plugin4', array_keys($plugins));
     $this->assertEquals('http://mysite.com/subdir/framework/thirdparty/tinymce/plugins/plugin4/plugin.min.js', $plugins['plugin4']);
     // Check that internal plugins are extractable separately
     $this->assertEquals(['plugin4', 'plugin5'], $c->getInternalPlugins());
     // Test plugins included via gzip compresser
     Config::inst()->update('HTMLEditorField', 'use_gzip', true);
     $this->assertEquals('framework/thirdparty/tinymce/tiny_mce_gzip.php?js=1&plugins=plugin4,plugin5&themes=modern&languages=es&diskcache=true&src=true', $c->getScriptURL());
     // If gzip is disabled only the core plugin is loaded
     Config::inst()->remove('HTMLEditorField', 'use_gzip');
     $this->assertEquals('framework/thirdparty/tinymce/tinymce.min.js', $c->getScriptURL());
 }
 public function setUp()
 {
     parent::setUp();
     Config::nest();
     Config::inst()->update('HtmlEditorField_Toolbar', 'fileurl_scheme_whitelist', array('http'));
     Config::inst()->update('HtmlEditorField_Toolbar', 'fileurl_domain_whitelist', array('example.com'));
 }
 /**
  * Return the title, description, keywords and language metatags.
  * 
  * @todo Move <title> tag in separate getter for easier customization and more obvious usage
  * 
  * @param boolean|string $includeTitle Show default <title>-tag, set to false for custom templating
  * @return string The XHTML metatags
  */
 public function MetaTags($includeTitle = true)
 {
     $tags = "";
     if ($includeTitle === true || $includeTitle == 'true') {
         $tags .= "<title>" . Convert::raw2xml($this->Title) . "</title>\n";
     }
     $generator = trim(Config::inst()->get('SiteTree', 'meta_generator'));
     if (!empty($generator)) {
         $tags .= "<meta name=\"generator\" content=\"" . Convert::raw2att($generator) . "\" />\n";
     }
     $charset = Config::inst()->get('ContentNegotiator', 'encoding');
     $tags .= "<meta http-equiv=\"Content-type\" content=\"text/html; charset={$charset}\" />\n";
     if ($this->MetaDescription) {
         $tags .= "<meta name=\"description\" content=\"" . Convert::raw2att($this->MetaDescription) . "\" />\n";
     }
     if ($this->ExtraMeta) {
         $tags .= $this->ExtraMeta . "\n";
     }
     if (Permission::check('CMS_ACCESS_CMSMain') && in_array('CMSPreviewable', class_implements($this)) && !$this instanceof ErrorPage) {
         $tags .= "<meta name=\"x-page-id\" content=\"{$this->ID}\" />\n";
         $tags .= "<meta name=\"x-cms-edit-link\" content=\"" . $this->CMSEditLink() . "\" />\n";
     }
     $this->extend('MetaTags', $tags);
     return $tags;
 }
Esempio n. 10
0
 /**
  * __construct
  *
  * @param string $filename = null
  * @return void
  */
 public function __construct($filename = null)
 {
     if (is_string($filename)) {
         parent::__construct($filename);
     }
     $this->setQuality(Config::inst()->get('ImagickBackend', 'default_quality'));
 }
    /**
     * Constructor.
     *
     * @param Controller $controller
     * @param string $name method on the $controller
     * @param FieldList $fields
     * @param FieldList $actions
     * @param bool $checkCurrentUser - show logout button if logged in
     */
    public function __construct($controller, $name, $fields = null, $actions = null, $checkCurrentUser = true)
    {
        parent::__construct($controller, $name, $fields, $actions, $checkCurrentUser);
        // will be used to get correct Link()
        $this->ldapSecController = Injector::inst()->create('LDAPSecurityController');
        $usernameField = new TextField('Username', _t('Member.USERNAME', 'Username'), null, null, $this);
        $this->Fields()->replaceField('Email', $usernameField);
        $this->setValidator(new RequiredFields('Username', 'Password'));
        if (Security::config()->remember_username) {
            $usernameField->setValue(Session::get('SessionForms.MemberLoginForm.Email'));
        } else {
            // Some browsers won't respect this attribute unless it's added to the form
            $this->setAttribute('autocomplete', 'off');
            $usernameField->setAttribute('autocomplete', 'off');
        }
        // Users can't change passwords unless appropriate a LDAP user with write permissions is
        // configured the LDAP connection binding
        $this->Actions()->remove($this->Actions()->fieldByName('forgotPassword'));
        $allowPasswordChange = Config::inst()->get('LDAPService', 'allow_password_change');
        if ($allowPasswordChange && $name != 'LostPasswordForm' && !Member::currentUser()) {
            $forgotPasswordLink = sprintf('<p id="ForgotPassword"><a href="%s">%s</a></p>', $this->ldapSecController->Link('lostpassword'), _t('Member.BUTTONLOSTPASSWORD', "I've lost my password"));
            $forgotPassword = new LiteralField('forgotPassword', $forgotPasswordLink);
            $this->Actions()->add($forgotPassword);
        }
        // Focus on the Username field when the page is loaded
        Requirements::block('MemberLoginFormFieldFocus');
        $js = <<<JS
\t\t\t(function() {
\t\t\t\tvar el = document.getElementById("Username");
\t\t\t\tif(el && el.focus && (typeof jQuery == 'undefined' || jQuery(el).is(':visible'))) el.focus();
\t\t\t})();
JS;
        Requirements::customScript($js, 'LDAPLoginFormFieldFocus');
    }
 /**
  * Allows for hooking in to modify the table of the snippet class for the search engine
  */
 public static function requireTable()
 {
     //Add fulltext searchable extension
     Snippet::add_extension("FulltextSearchable('Title,Description,Tags')");
     //Change to MyISAM for the engine for snippet tables
     Config::inst()->update('Snippet', 'create_table_options', array('MySQLDatabase' => 'ENGINE=MyISAM'));
 }
Esempio n. 13
0
 public function testNice()
 {
     $time = DBField::create_field('Time', '17:15:55');
     $this->assertEquals('5:15pm', $time->Nice());
     Config::inst()->update('Time', 'nice_format', 'H:i:s');
     $this->assertEquals('17:15:55', $time->Nice());
 }
 /**
  * @param   $key The nav key, e.g. "doc", "userhelp"
  * @return HTMLText
  */
 public static function GlobalNav($key)
 {
     $baseURL = GlobalNavSiteTreeExtension::get_toolbar_baseurl();
     Requirements::css(Controller::join_links($baseURL, Config::inst()->get('GlobalNav', 'css_path')));
     // If this method haven't been called before, get the toolbar and cache it
     if (self::$global_nav_html === null) {
         // Set the default to empty
         self::$global_nav_html = '';
         // Prevent recursion from happening
         if (empty($_GET['globaltoolbar'])) {
             $host = GlobalNavSiteTreeExtension::get_toolbar_hostname();
             $path = Director::makeRelative(GlobalNavSiteTreeExtension::get_navbar_filename($key));
             if (Config::inst()->get('GlobalNav', 'use_localhost')) {
                 self::$global_nav_html = file_get_contents(BASE_PATH . $path);
             } else {
                 $url = Controller::join_links($baseURL, $path, '?globaltoolbar=true');
                 $connectionTimeout = Config::inst()->get('GlobalNavTemplateProvider', 'connection_timeout');
                 $transferTimeout = Config::inst()->get('GlobalNavTemplateProvider', 'transfer_timeout');
                 // Get the HTML and cache it
                 self::$global_nav_html = self::curl_call($url, $connectionTimeout, $transferTimeout);
             }
         }
     }
     $html = DBField::create_field('HTMLText', self::$global_nav_html);
     $html->setOptions(array('shortcodes' => false));
     return $html;
 }
Esempio n. 15
0
 /**
  * Filter a backtrace so that it doesn't show the calls to the
  * debugging system, which is useless information.
  *
  * @param array $bt Backtrace to filter
  * @param null|array $ignoredFunctions List of extra functions to filter out
  * @return array
  */
 public static function filter_backtrace($bt, $ignoredFunctions = null)
 {
     $defaultIgnoredFunctions = array('SS_Log::log', 'SS_Backtrace::backtrace', 'SS_Backtrace::filtered_backtrace', 'Zend_Log_Writer_Abstract->write', 'Zend_Log->log', 'Zend_Log->__call', 'Zend_Log->err', 'DebugView->writeTrace', 'CliDebugView->writeTrace', 'Debug::emailError', 'Debug::warningHandler', 'Debug::noticeHandler', 'Debug::fatalHandler', 'errorHandler', 'Debug::showError', 'Debug::backtrace', 'exceptionHandler');
     if ($ignoredFunctions) {
         foreach ($ignoredFunctions as $ignoredFunction) {
             $defaultIgnoredFunctions[] = $ignoredFunction;
         }
     }
     while ($bt && in_array(self::full_func_name($bt[0]), $defaultIgnoredFunctions)) {
         array_shift($bt);
     }
     $ignoredArgs = Config::inst()->get('SS_Backtrace', 'ignore_function_args');
     // Filter out arguments
     foreach ($bt as $i => $frame) {
         $match = false;
         if (!empty($bt[$i]['class'])) {
             foreach ($ignoredArgs as $fnSpec) {
                 if (is_array($fnSpec) && $bt[$i]['class'] == $fnSpec[0] && $bt[$i]['function'] == $fnSpec[1]) {
                     $match = true;
                 }
             }
         } else {
             if (in_array($bt[$i]['function'], $ignoredArgs)) {
                 $match = true;
             }
         }
         if ($match) {
             foreach ($bt[$i]['args'] as $j => $arg) {
                 $bt[$i]['args'][$j] = '<filtered>';
             }
         }
     }
     return $bt;
 }
 /**
  * Gets a thumbnail for this file given a size. If it's an Image,
  * it will render the actual file. If not, it will provide an icon based
  * on the extension.
  * @param  int $w The width of the image
  * @param  int $h The height of the image
  * @return Image_Cached
  */
 public function getPreviewThumbnail($w = null, $h = null)
 {
     if (!$w) {
         $w = $this->owner->config()->grid_thumbnail_width;
     }
     if (!$h) {
         $h = $this->owner->config()->grid_thumbnail_height;
     }
     if ($this->IsImage()) {
         return $this->owner->CroppedImage($w, $h);
     }
     $sizes = Config::inst()->forClass('FileAttachmentField')->icon_sizes;
     sort($sizes);
     foreach ($sizes as $size) {
         if ($w <= $size) {
             if ($this->owner instanceof Folder) {
                 $file = $this->getFilenameForType('_folder', $size);
             } else {
                 $file = $this->getFilenameForType($this->owner->getExtension(), $size);
             }
             if (!file_exists(BASE_PATH . '/' . $file)) {
                 $file = $this->getFilenameForType('_blank', $size);
             }
             return new Image_Cached(Director::makeRelative($file));
         }
     }
 }
 /**
  * Provides a GUI for the insert/edit shortcode popup
  * @return Form
  **/
 public function ShortcodeForm()
 {
     if (!Permission::check('CMS_ACCESS_CMSMain')) {
         return;
     }
     Config::inst()->update('SSViewer', 'theme_enabled', false);
     // create a list of shortcodable classes for the ShortcodeType dropdown
     $classList = ClassInfo::implementorsOf('Shortcodable');
     $classes = array();
     foreach ($classList as $class) {
         $classes[$class] = singleton($class)->singular_name();
     }
     // load from the currently selected ShortcodeType or Shortcode data
     $classname = false;
     $shortcodeData = false;
     if ($shortcode = $this->request->requestVar('Shortcode')) {
         $shortcode = str_replace("", '', $shortcode);
         //remove BOM inside string on cursor position...
         $shortcodeData = singleton('ShortcodableParser')->the_shortcodes(array(), $shortcode);
         if (isset($shortcodeData[0])) {
             $shortcodeData = $shortcodeData[0];
             $classname = $shortcodeData['name'];
         }
     } else {
         $classname = $this->request->requestVar('ShortcodeType');
     }
     if ($shortcodeData) {
         $headingText = _t('Shortcodable.EDITSHORTCODE', 'Edit Shortcode');
     } else {
         $headingText = _t('Shortcodable.INSERTSHORTCODE', 'Insert Shortcode');
     }
     // essential fields
     $fields = FieldList::create(array(CompositeField::create(LiteralField::create('Heading', sprintf('<h3 class="htmleditorfield-shortcodeform-heading insert">%s</h3>', $headingText)))->addExtraClass('CompositeField composite cms-content-header nolabel'), LiteralField::create('shortcodablefields', '<div class="ss-shortcodable content">'), DropdownField::create('ShortcodeType', 'ShortcodeType', $classes, $classname)->setHasEmptyDefault(true)->addExtraClass('shortcode-type')));
     // attribute and object id fields
     if ($classname) {
         if (class_exists($classname)) {
             $class = singleton($classname);
             if (is_subclass_of($class, 'DataObject')) {
                 if (singleton($classname)->hasMethod('get_shortcodable_records')) {
                     $dataObjectSource = $classname::get_shortcodable_records();
                 } else {
                     $dataObjectSource = $classname::get()->map()->toArray();
                 }
                 $fields->push(DropdownField::create('id', $class->singular_name(), $dataObjectSource)->setHasEmptyDefault(true));
             }
             if ($attrFields = $classname::shortcode_attribute_fields()) {
                 $fields->push(CompositeField::create($attrFields)->addExtraClass('attributes-composite'));
             }
         }
     }
     // actions
     $actions = FieldList::create(array(FormAction::create('insert', _t('Shortcodable.BUTTONINSERTSHORTCODE', 'Insert shortcode'))->addExtraClass('ss-ui-action-constructive')->setAttribute('data-icon', 'accept')->setUseButtonTag(true)));
     // form
     $form = Form::create($this, "ShortcodeForm", $fields, $actions)->loadDataFrom($this)->addExtraClass('htmleditorfield-form htmleditorfield-shortcodable cms-dialog-content');
     if ($shortcodeData) {
         $form->loadDataFrom($shortcodeData['atts']);
     }
     $this->extend('updateShortcodeForm', $form);
     return $form;
 }
 public function tearDown()
 {
     parent::tearDown();
     Config::inst()->update('LeftAndMain', 'extra_requirements_css', $this->backupCss);
     Config::inst()->update('LeftAndMain', 'extra_requirements_javascript', $this->backupJs);
     Requirements::set_combined_files_enabled($this->backupCombined);
 }
 public function validateTOTP($token)
 {
     assert(is_string($token));
     if (!$this->owner->Has2FA) {
         return true;
     }
     $seed = $this->OTPSeed();
     if (!$seed) {
         return true;
     }
     $window = (int) \Config::inst()->get(__CLASS__, 'totp_window');
     $totp = new TOTP($seed, array('window' => $window));
     $valid = $totp->validate($token);
     if (!$valid) {
         foreach ($this->owner->BackupTokens() as $bt) {
             if ($bt->Value == $token) {
                 $valid = true;
                 if ($bt::config()->single_use) {
                     $bt->delete();
                 }
             }
         }
     }
     return $valid;
 }
 public function testModifierFailure()
 {
     if (!ShopTools::DBConn()->supportsTransactions()) {
         $this->markTestSkipped('The Database doesn\'t support transactions.');
     }
     Config::inst()->update('Order', 'modifiers', array('OrderModifierTest_TestModifier'));
     $order = $this->createOrder();
     $order->calculate();
     $order->write();
     // 408 from items + 10 from modifier + 25% from tax
     $this->assertEquals('522.5', $order->Total);
     $amounts = array();
     foreach ($order->Modifiers()->sort('Sort') as $modifier) {
         $amounts[] = (string) $modifier->Amount;
     }
     $this->assertEquals(array('10', '104.5'), $amounts);
     OrderModifierTest_TestModifier::$value = 42;
     try {
         // Calculate will now fail!
         $order->calculate();
     } catch (Exception $e) {
     }
     // reload order from DB
     $order = Order::get()->byID($order->ID);
     // Order Total should not have changed
     $this->assertEquals('522.5', $order->Total);
     $amounts = array();
     foreach ($order->Modifiers()->sort('Sort') as $modifier) {
         $amounts[] = (string) $modifier->Amount;
     }
     $this->assertEquals(array('10', '104.5'), $amounts, 'Modifiers aren\'t allowed to change upon failure');
 }
 /**
  * @param string $keywords
  * @param array $filters [optional]
  * @param array $facetSpec [optional]
  * @param int $start [optional]
  * @param int $limit [optional]
  * @param string $sort [optional]
  * @return ArrayData
  */
 function searchFromVars($keywords, array $filters = array(), array $facetSpec = array(), $start = -1, $limit = -1, $sort = '')
 {
     $searchable = ShopSearch::get_searchable_classes();
     $matches = new ArrayList();
     foreach ($searchable as $className) {
         $list = DataObject::get($className);
         // get searchable fields
         $keywordFields = $this->scaffoldSearchFields($className);
         // convert that list into something we can pass to Datalist::filter
         $keywordFilter = array();
         if (!empty($keywords)) {
             foreach ($keywordFields as $searchField) {
                 $name = strpos($searchField, ':') !== FALSE ? $searchField : "{$searchField}:PartialMatch";
                 $keywordFilter[$name] = $keywords;
             }
         }
         if (count($keywordFilter) > 0) {
             $list = $list->filterAny($keywordFilter);
         }
         // add in any other filters
         $list = FacetHelper::inst()->addFiltersToDataList($list, $filters);
         // add any matches to the big list
         $matches->merge($list);
     }
     return new ArrayData(array('Matches' => $matches, 'Facets' => FacetHelper::inst()->buildFacets($matches, $facetSpec, (bool) Config::inst()->get('ShopSearch', 'auto_facet_attributes'))));
 }
 /**
  * Body for the preview iframe with just the typography styles included
  * @return string html
  */
 public function preview()
 {
     Requirements::clear();
     // Should contain text styles of the page by Silverstripe theme conventions.
     Requirements::css('themes/' . Config::inst()->get('SSViewer', 'theme') . '/css/editor.css');
     return $this->renderWith('PreviewFrame');
 }
 public function setUp()
 {
     parent::setUp();
     // Set backend
     AssetStoreTest_SpyStore::activate('DBFileTest');
     Config::inst()->update('Director', 'alternate_base_url', '/mysite/');
 }
 /**
  * Configure server files for this store
  *
  * @param bool $forceOverwrite Force regeneration even if files already exist
  */
 protected function configureServer($forceOverwrite = false)
 {
     // Get server type
     $type = isset($_SERVER['SERVER_SOFTWARE']) ? $_SERVER['SERVER_SOFTWARE'] : '*';
     list($type) = explode('/', strtolower($type));
     // Determine configurations to write
     $rules = \Config::inst()->get(get_class($this), 'server_configuration', \Config::FIRST_SET);
     if (empty($rules[$type])) {
         return;
     }
     $configurations = $rules[$type];
     // Apply each configuration
     $config = new \League\Flysystem\Config();
     $config->set('visibility', 'private');
     foreach ($configurations as $file => $template) {
         if ($forceOverwrite || !$this->has($file)) {
             // Evaluate file
             $content = $this->renderTemplate($template);
             $success = $this->write($file, $content, $config);
             if (!$success) {
                 throw new \Exception("Error writing server configuration file \"{$file}\"");
             }
         }
     }
 }
 public function getEditForm($id = null, $fields = null)
 {
     $classname = $this->modelClass;
     $list = $classname::get();
     $listField = GridField::create($this->sanitiseClassName($this->modelClass), false, $list, $fieldConfig = GridFieldConfig_RecordEditor::create($this->stat('page_length'))->removeComponentsByType('GridFieldFilterHeader'));
     if (!$this->stat('enable_sorting')) {
         $summary_fields = Config::inst()->get($this->modelClass, 'summary_fields');
         $sorting = array();
         foreach ($summary_fields as $col) {
             $sorting[$col] = 'FieldNameNoSorting';
         }
         $fieldConfig->getComponentByType('GridFieldSortableHeader')->setFieldSorting($sorting);
     }
     // Validation
     if (singleton($this->modelClass)->hasMethod('getCMSValidator')) {
         $detailValidator = singleton($this->modelClass)->getCMSValidator();
         $listField->getConfig()->getComponentByType('GridFieldDetailForm')->setValidator($detailValidator);
     }
     $form = new Form($this, 'EditForm', new FieldList($listField), new FieldList());
     $form->addExtraClass('cms-edit-form cms-panel-padded center');
     $form->setTemplate($this->getTemplatesWithSuffix('_EditForm'));
     $editFormAction = Controller::join_links($this->Link($this->sanitiseClassName($this->modelClass)), 'EditForm');
     $form->setFormAction($editFormAction);
     $form->setAttribute('data-pjax-fragment', 'CurrentForm');
     $this->extend('updateEditForm', $form);
     return $form;
 }
    /**
     * Init
     * 	Include the javascript we will need
     *
     * @return void
     * @author Andrew Lowther <*****@*****.**>
     **/
    public function init()
    {
        parent::init();
        // Get the config variables we'll need
        $config = Config::inst()->get('MediaManager', 'Cloudinary');
        // Inject them into the global scope
        Requirements::customScript(<<<JS
\t\t\t;(function (window, undefined) {
\t\t\t\twindow.mediamanager = window.mediamanager || {};
\t\t\t\twindow.mediamanager.cloudinary = {
\t\t\t\t\tcloud_name: "{$config['cloud_name']}",
\t\t\t\t\tapi_key: "{$config['api_key']}"
\t\t\t\t}
\t\t\t}/)(window);
JS
);
        // Get the base javascript path
        $BaseJsPath = MEDIAMANAGER_CORE_PATH . '/javascript';
        // Combine the cloudinary files into one super file
        Requirements::combine_files('cloudinary.js', array("{$BaseJsPath}/cloudinary/js/load-image.min.js", "{$BaseJsPath}/cloudinary/js/canvas-to-blob.min.js", "{$BaseJsPath}/cloudinary/js/jquery.fileupload.js", "{$BaseJsPath}/cloudinary/js/jquery.ui.widget.js", "{$BaseJsPath}/cloudinary/js/jquery.fileupload-process.js", "{$BaseJsPath}/cloudinary/js/jquery.fileupload-image.js", "{$BaseJsPath}/cloudinary/js/jquery.fileupload-validate.js", "{$BaseJsPath}/cloudinary/js/jquery.cloudinary.js"));
        // Same again for our files
        Requirements::combine_files('mediamanager.js', array("{$BaseJsPath}/mediamanager/mediamanager.core.js"));
        // Set the cloudinary config
        \Cloudinary::config($config);
    }
 /**
  * Get the API key to use
  *
  * @return string
  */
 public static function get_mailchimp_api_key()
 {
     if (defined('SS_MAILCHIMP_API_KEY')) {
         return SS_MAILCHIMP_API_KEY;
     }
     return Config::inst()->get(__CLASS__, 'mailchimp_api_key');
 }
 public function updateFields($fields)
 {
     Requirements::javascript(MISDIRECTION_PATH . '/javascript/misdirection-fallback.js');
     // Update any fields that are displayed when not viewing a page.
     $tab = 'Root.Misdirection';
     $options = array('Nearest' => 'Nearest Parent', 'This' => 'This Page', 'URL' => 'URL');
     if ($this->owner instanceof SiteConfig) {
         $tab = 'Root.Pages';
         unset($options['This']);
     }
     // Retrieve the fallback mapping selection.
     $fields->addFieldToTab($tab, HeaderField::create('FallbackHeader', 'Fallback'));
     $fields->addFieldToTab($tab, DropdownField::create('Fallback', 'To', $options)->addExtraClass('fallback')->setHasEmptyDefault(true)->setRightTitle('This will be used when children result in a <strong>page not found</strong>'));
     $fields->addFieldToTab($tab, TextField::create('FallbackLink', 'URL')->addExtraClass('fallback-link'));
     // Retrieve the response code selection.
     $responses = Config::inst()->get('SS_HTTPResponse', 'status_codes');
     $selection = array();
     foreach ($responses as $code => $description) {
         if ($code >= 300 && $code < 400) {
             $selection[$code] = "{$code}: {$description}";
         }
     }
     $fields->addFieldToTab($tab, DropdownField::create('FallbackResponseCode', 'Response Code', $selection)->addExtraClass('fallback-response-code'));
     // Allow extension customisation.
     $this->owner->extend('updateMisdirectionFallbackExtensionFields', $fields);
 }
 public static function setupCache($ip)
 {
     $driver = Config::inst()->get('IPInfoCache', 'Driver');
     if (!$driver) {
         foreach (self::$defaultDrivers as $defaultDriver) {
             if (class_exists($defaultDriver)) {
                 $driver = $defaultDriver;
                 break;
             }
         }
         if (!$driver) {
             user_error('A driver needs to be specified');
         }
     }
     $ipService = new $driver();
     $dbJson = $ipService->processIP($ip);
     // do not cache a empty object
     if ($dbJson) {
         $cache = IPInfoCache::create();
         $cache->IP = $ip;
         $cache->Info = $dbJson;
         $cache->write();
     }
     return $ipService->getJSON();
 }
 /**
  * Answers the unicode value for the icon with the given name.
  *
  * @param string $name
  * @return string
  */
 protected function getIconUnicode($name)
 {
     $icons = Config::inst()->get(__CLASS__, 'icons');
     if (isset($icons[$name])) {
         return $icons[$name];
     }
 }