public function MetaTags(&$tags) { if (Director::isDev() or Director::isTest()) { $tags .= '<meta name="robots" content="noindex, nofollow" />'; } return $tags; }
public static function forceNonWWW() { if (!Director::isDev() && !Director::isTest() && strpos($_SERVER['HTTP_HOST'], 'www') === 0) { $destURL = str_replace(Director::protocol() . 'www.', Director::protocol(), Director::absoluteURL($_SERVER['REQUEST_URI'])); self::force_redirect($destURL); } }
public function getURLPrefix() { $url = parent::getURLPrefix(); if (Director::isDev() || Director::isTest()) { $urlarray = parse_url($url); // define override if (defined('DEV_SUBSITE_' . Subsite::currentSubsiteID())) { $subsiteurl = 'DEV_SUBSITE_' . Subsite::currentSubsiteID(); return constant($subsiteurl) . $urlarray['path']; } if (!Subsite::currentSubsite() instanceof Subsite) { return $url; } // if set in config settings $currentDomain = Subsite::currentSubsite()->getPrimarySubsiteDomain(); if (Director::isTest()) { $currentDomain = Subsite::currentSubsite()->TestDomainID ? Subsite::currentSubsite()->TestDomain() : $currentDomain; } if (Director::isDev()) { $currentDomain = Subsite::currentSubsite()->DevDomainID ? Subsite::currentSubsite()->DevDomain() : $currentDomain; } if (!$currentDomain) { return $url; } return $currentDomain->getFullProtocol() . $currentDomain->Domain . $urlarray['path']; } return $url; }
public function XrequireDefaultRecords() { foreach ($this->config()->get('records') as $code => $record) { if ($record['IsDev'] && Director::isDev() || $record['IsTest'] && Director::isTest() || $record['IsLive'] && Director::isLive()) { if (!($discountType = StreakDiscountType::get_by_code($code))) { $discountType = StreakDiscountType::create(); DB::alteration_message("Added discount type '{$code}'", "changed"); } // if the record is using default code then update from config. if ($code == self::DefaultCode) { $record['Code'] = $this->config()->get('default_code'); } else { $record['Code'] = $code; } $title = $record['Title']; // if the record is using default title then update from config as hasn't changed, if different // then leave alone if ($title == self::DefaultTitle) { $record['Title'] = $this->config()->get('default_title'); } $data = array_diff_key($record, array_flip(array('IsDev', 'IsTest', 'IsLive'))); $discountType->update($data); $discountType->write(); } } }
/** * Log something into our log file * @param $environment = string (minimum environment state for logging this message) * @param $message = string (the message body) **/ static function Log($message = '', $environment = 'dev') { // only proceed if LogJam is enabled if (static::$enabled) { // make sure our log level matches our environment level, otherwise break out if (Director::isLive() && $environment != 'live') { return false; } else { if (Director::isTest() && ($environment != 'live' || $environment != 'test')) { return false; } } // trace the origin call $trace = SS_Backtrace::filtered_backtrace(); $trace = $trace[0]; $file = isset($trace['file']) ? $trace['file'] : ''; $line = isset($trace['line']) ? $trace['line'] : ''; // construct the line in our file $output = 'LogJam: '; $output .= $message; $output .= ' (line ' . $line . ' in ' . $file . ')'; // piggy-back PHP error_log return error_log($output); } return false; }
public function init() { parent::init(); $this->extend('init'); $canAccess = !Director::isLive() && (Director::isDev() || Director::isTest() || Director::is_cli() || Permission::check("ADMIN")); if (!$canAccess) { return Security::permissionFailure($this); } Requirements::javascript('framework/thirdparty/jquery/jquery.js'); Requirements::javascript('testsession/javascript/testsession.js'); }
/** * @var bool * * @throws Exception */ public static function requireRecords($force = false) { if (self::$ran && !$force) { return true; } self::$ran = true; if (!(Director::isDev() || Director::isTest())) { throw new Exception('requireRecords can only be run in development or test environments'); } $factory = Injector::inst()->create('PopulateFactory'); foreach (self::config()->get('truncate_objects') as $objName) { $versions = array(); if (class_exists($objName)) { foreach (DataList::create($objName) as $obj) { // if the object has the versioned extension, make sure we delete // that as well if ($obj->hasExtension('Versioned')) { foreach ($obj->getVersionedStages() as $stage) { $versions[$stage] = true; $obj->deleteFromStage($stage); } } try { @$obj->delete(); } catch (Exception $e) { // notice } } } if ($versions) { self::truncate_versions($objName, $versions); } foreach ((array) ClassInfo::getValidSubClasses($objName) as $table) { self::truncate_table($table); self::truncate_versions($table, $versions); } self::truncate_table($objName); } foreach (self::config()->get('include_yaml_fixtures') as $fixtureFile) { $fixture = new YamlFixture($fixtureFile); $fixture->writeInto($factory); $fixture = null; } // hook allowing extensions to clean up records, modify the result or // export the data to a SQL file (for importing performance). $static = !(isset($this) && get_class($this) == __CLASS__); if ($static) { $populate = Injector::inst()->create('Populate'); } else { $populate = $this; } $populate->extend('onAfterPopulateRecords'); return true; }
public function EnvironmentType() { if (Director::isLive()) { return "live"; } else { if (Director::isTest()) { return "test"; } else { return "dev"; } } }
public function contentcontrollerInit($controller) { $minicart = Director::isDev() || Director::isTest() ? 'minicart.js' : 'minicart.min.js'; $settings = MiniCart::getMiniCartConfig(); $config = SiteConfig::current_site_config(); Requirements::javascript(MODULE_MINICART_DIR . '/bower_components/minicart/dist/' . $minicart); Requirements::customScript('paypal.minicart.render(' . $settings . ');', 'minicart'); // reset cart after successful checkout if (isset($_GET['ppsuccess']) || $this->owner->ID == $config->MiniCartReturnPageID) { Requirements::customScript('paypal.minicart.reset();', 'minicart_reset'); } }
/** * generates piwik tracking code out of config vars and Piwik.ss template * @param $wrap wrap inside <script> tags, e.g. for templates */ public function getPiwik($wrap = true) { if (Director::isDev() && !Config::inst()->get('PiwikExtension', 'show_on_dev')) { return false; } if (Director::isTest() && !Config::inst()->get('PiwikExtension', 'show_on_test')) { return false; } if (Director::isLive() && !Config::inst()->get('PiwikExtension', 'show_on_live')) { return false; } $data = array('WrapInJsTags' => $wrap, 'URL' => Config::inst()->get('PiwikExtension', 'piwik_server'), 'SiteID' => Config::inst()->get('PiwikExtension', 'piwik_site_id')); return ArrayData::create($data)->renderWith(array('Piwik')); }
public function EnvironmentIcon() { if (Director::isLive()) { $mode = 'live'; } else { if (Director::isTest()) { $mode = 'test'; } else { if (Director::isDev()) { $mode = 'dev'; } } } return '<span class="environment-icon ' . $mode . '"></span>'; }
/** * generates piwik tracking code out of config vars and Piwik.ss template * @param $wrap wrap inside <script> tags, e.g. for templates */ public function getPiwik($wrap = true) { if (Director::isDev() && !Config::inst()->get('PiwikExtension', 'show_on_dev')) { return false; } if (Director::isTest() && !Config::inst()->get('PiwikExtension', 'show_on_test')) { return false; } if (Director::isLive() && !Config::inst()->get('PiwikExtension', 'show_on_live')) { return false; } //used for overwriting defaults in SiteConfig, e.g. for different SiteIDs in a Subsite installation $currentSiteConfig = Controller::curr()->hasMethod('getSiteConfig') ? Controller::curr()->getSiteConfig() : SiteConfig::current_site_config(); $data = array('WrapInJsTags' => $wrap, 'URL' => Config::inst()->get('PiwikExtension', 'piwik_server'), 'SiteID' => Config::inst()->get('PiwikExtension', 'piwik_site_id'), 'SiteConfig' => $currentSiteConfig); return ArrayData::create($data)->renderWith(array('Piwik')); }
/** * Initialisation function that is run before any action on the controller is called. * * @uses BasicAuth::requireLogin() */ function init() { // Test and development sites should be secured, via basic-auth if(Director::isTest() && $this->basicAuthEnabled && Security::database_is_ready()) { BasicAuth::requireLogin("SilverStripe test website. Use your CMS login", "ADMIN"); } // Directly access the session variable just in case the Group or Member tables don't yet exist if(Session::get('loggedInAs') && Security::database_is_ready()) { if($member = Member::currentUser()) { Cookie::set("PastMember", true); DB::query("UPDATE Member SET LastVisited = NOW() WHERE ID = $member->ID", null); } } // This is used to test that subordinate controllers are actually calling parent::init() - a common bug $this->baseInitCalled = true; }
public function updateCMSFields(FieldList $fields) { if ($this->owner->ID != 0) { $domains = $this->owner->Domains()->map('ID', 'Domain'); if (Director::isDev() || Director::isTest()) { if (defined('DEV_SUBSITE_' . $this->owner->ID)) { $subsiteurl = 'DEV_SUBSITE_' . $this->owner->ID; $wardingfield = LiteralField::create("WarningDomain", "<p class=\"message warning\">While running in dev or test mode," . " the current domain will be used: <strong>" . constant($subsiteurl) . "</strong></p>"); $fields->addFieldToTab("Root.DomainEnvironments", $wardingfield); } } $fields->addFieldToTab('Root.DomainEnvironments', TextField::create('Live', 'Live', $this->owner->domain())->setReadonly(true)); $fields->addFieldToTab('Root.DomainEnvironments', DropdownField::create('TestDomainID', 'Test', $domains)); $fields->addFieldToTab('Root.DomainEnvironments', DropdownField::create('DevDomainID', 'Dev', $domains)); $fields->makeFieldReadonly('Live'); } }
/** * @var bool * * @throws Exception */ public static function requireRecords($force = false) { if (self::$ran && !$force) { return true; } self::$ran = true; if (!(Director::isDev() || Director::isTest())) { throw new Exception('requireRecords can only be run in development or test environments'); } $factory = Injector::inst()->create('PopulateFactory'); foreach (self::config()->get('truncate_objects') as $objName) { $versions = array(); if (class_exists($objName)) { foreach (DataList::create($objName) as $obj) { // if the object has the versioned extension, make sure we delete // that as well if ($obj->hasExtension('Versioned')) { foreach ($obj->getVersionedStages() as $stage) { $versions[$stage] = true; $obj->deleteFromStage($stage); } } try { @$obj->delete(); } catch (Exception $e) { // notice } } } if ($versions) { self::truncate_versions($objName, $versions); } foreach (ClassInfo::getValidSubClasses($objName) as $table) { self::truncate_table($table); self::truncate_versions($table, $versions); } self::truncate_table($objName); } foreach (self::config()->get('include_yaml_fixtures') as $fixtureFile) { $fixture = new YamlFixture($fixtureFile); $fixture->writeInto($factory); $fixture = null; } return true; }
/** * Safeguard a method by catching exceptions/errors that might be thrown and redirect them to the log * @param \Closure $method * @param string $errorMessage custom message to write to the log * @return mixed whatever your closure returns * @throws \Exception any exception that occurred (only in dev and test environments) */ public static function safeguard(\Closure $method, $errorMessage) { set_error_handler(function ($severity, $message, $file, $line) { throw new \ErrorException($message, 0, $severity, $file, $line); }, E_WARNING & E_USER_WARNING & E_ERROR & E_USER_ERROR & E_RECOVERABLE_ERROR); try { $retVal = $method(); restore_error_handler(); return $retVal; } catch (\Exception $ex) { \SS_Log::log($errorMessage, \SS_Log::WARN); \SS_Log::log($ex, \SS_Log::WARN); // In dev and test environments, throw the exception! if (\Director::isDev() || \Director::isTest()) { restore_error_handler(); throw $ex; } } restore_error_handler(); }
/** * will download the file and return it * @param string $url * @return data */ public static function DownloadFile($url, $timeout = 60) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5); curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); if (Director::isDev() || Director::isTest()) { curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, '1'); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, '0'); } $result = curl_exec($ch); $code = curl_getinfo($ch, CURLINFO_HTTP_CODE); if ($code != 200) { $err = curl_error($ch); curl_close($ch); throw new Exception($err . ' code ' . $code); } curl_close($ch); return $result; }
protected function compile() { if (!$this->compiled && (static::$flush && Config::inst()->get(__CLASS__, 'compile_in_flush') || Director::isLive() && Config::inst()->get(__CLASS__, 'compile_in_live') || Director::isTest() && Config::inst()->get(__CLASS__, 'compile_in_test') || Director::isDev() && Config::inst()->get(__CLASS__, 'compile_in_dev'))) { // only allow compile to run once $this->compiled = true; foreach ($this->files as $category => $files) { foreach ($files as $source => $target) { $this->{"compile{$category}File"}($source, $target); } } if ($this->log) { $js = []; foreach ($this->log as $line) { $type = 'log'; if (is_array($line)) { $type = $line[1]; $line = $line[0]; } $js[] = sprintf("console.%s(%s);", $type, json_encode($line)); } Requirements::customScript(implode(PHP_EOL, $js)); } $this->log = []; $this->filesCacheSave(); } }
/** * This function will return true if the site is in a live environment. For information about * environment types, see {@link Director::set_environment_type()}. * * @return bool */ public static function isLive() { return !(Director::isDev() || Director::isTest()); }
/** * This function will return true if the site is in a test environment. * For information about environment types, see {@link Director::set_environment_type()}. * * @return bool */ public function IsTest() { return Director::isTest(); }
<?php // Try to load from PEAR first if (@(include_once 'FirePHPCore/fb.php')) { $status = "via PEAR."; // If not installed in PEAR, load the version included in this module } else { if (@(include_once __DIR__ . '/code/core/lib/fb.php')) { $status = "via SS_FirePHP."; } else { user_error('FirePHP PEAR module was not found, and the included FirePHP Core is corrupt.'); } } // Only enable FirePHP in Dev and Test mode, never in Live. // Note that if you give the SS_FirePHP folder (or its top-level // parent folder) a name that sorts alphanumerically *before* // mysite, then it won't be able to detect this and you'll have to // enable it manually from mysite/_config.php if (isset($status) && (Director::isDev() || Director::isTest())) { FB::setEnabled(true); FB::log('FirePHP loaded ' . $status); }
/** * Tests isDev, isTest, isLive set from querystring */ public function testQueryIsEnvironment() { // Reset unset($_SESSION['isDev']); unset($_SESSION['isLive']); unset($_GET['isTest']); unset($_GET['isDev']); // Test isDev=1 $_GET['isDev'] = '1'; $this->assertTrue(Director::isDev()); $this->assertFalse(Director::isTest()); $this->assertFalse(Director::isLive()); // Test persistence unset($_GET['isDev']); $this->assertTrue(Director::isDev()); $this->assertFalse(Director::isTest()); $this->assertFalse(Director::isLive()); // Test change to isTest $_GET['isTest'] = '1'; $this->assertFalse(Director::isDev()); $this->assertTrue(Director::isTest()); $this->assertFalse(Director::isLive()); // Test persistence unset($_GET['isTest']); $this->assertFalse(Director::isDev()); $this->assertTrue(Director::isTest()); $this->assertFalse(Director::isLive()); }
/** * Returns false if the non-prefilterable parts of the rule aren't met, and true if they are */ function matchesVariantRules($rules) { foreach ($rules as $k => $v) { switch (strtolower($k)) { case 'classexists': case 'moduleexists': break; case 'environment': switch (strtolower($v)) { case 'live': if (!Director::isLive()) return false; break; case 'test': if (!Director::isTest()) return false; break; case 'dev': if (!Director::isDev()) return false; break; default: user_error('Unknown environment '.$v.' in config fragment', E_USER_ERROR); } break; case 'envvarset': if (isset($_ENV[$k])) break; return false; case 'constantdefined': if (defined($k)) break; return false; default: if (isset($_ENV[$k]) && $_ENV[$k] == $v) break; if (defined($k) && constant($k) == $v) break; return false; } } return true; }
/** * @return bool */ public static function isTest() { return Director::isTest(); }
/** * Returns false if the non-prefilterable parts of the rule aren't met, and true if they are */ public function matchesVariantRules($rules) { $matches = "undefined"; // Needs to be truthy, but not true foreach ($rules as $k => $v) { switch (strtolower($k)) { case 'classexists': case 'moduleexists': break; case 'environment': switch (strtolower($v)) { case 'live': $matches = $matches && Director::isLive(); break; case 'test': $matches = $matches && Director::isTest(); break; case 'dev': $matches = $matches && Director::isDev(); break; default: user_error('Unknown environment ' . $v . ' in config fragment', E_USER_ERROR); } break; case 'envvarset': $matches = $matches && isset($_ENV[$v]); break; case 'constantdefined': $matches = $matches && defined($v); break; default: $matches = $matches && (isset($_ENV[$k]) && $_ENV[$k] == $v || defined($k) && constant($k) == $v); break; } if ($matches === false) { return $matches; } } return $matches; }
/** * Initialisation function that is run before any action on the controller is called. */ function init() { // Test and development sites should be secured, via basic-auth if (ClassInfo::hasTable("Group") && ClassInfo::hasTable("Member") && Director::isTest() && $this->basicAuthEnabled) { BasicAuth::requireLogin("SilverStripe test website. Use your CMS login", "ADMIN"); } // Cookie::set("PastVisitor", true); // ClassInfo::hasTable() called to ensure that we're not in a very-first-setup stage if (ClassInfo::hasTable("Group") && ClassInfo::hasTable("Member") && ($member = Member::currentUser())) { Cookie::set("PastMember", true); DB::query("UPDATE Member SET LastVisited = NOW() WHERE ID = {$member->ID}", null); } // This is used to test that subordinate controllers are actually calling parent::init() - a common bug $this->baseInitCalled = true; }
public static function isLive($skipDatabase = false) { return !(Director::isDev($skipDatabase) || Director::isTest($skipDatabase)); }
<?php global $project; $project = 'mysite'; global $database; $database = ''; require_once 'conf/ConfigureFromEnv.php'; // Set the site locale i18n::set_locale('en_US'); if (Director::isTest()) { SS_Log::add_writer(new SS_LogFileWriter('../silverstripe-errors-warnings.log'), SS_Log::WARN, '<='); SS_Log::add_writer(new SS_LogFileWriter('../silverstripe-errors.log'), SS_Log::ERR); } if (Director::isLive()) { SS_Log::add_writer(new SS_LogEmailWriter('*****@*****.**'), SS_Log::ERR); }
public function show() { return Director::isDev() or Director::isTest() ? 1 : 0; }
/** * Once ContentController has been initiated, do our stuff * @return ArrayList **/ public function PageInfo() { $mode = 'DEV'; if (Director::isTest()) { $mode = 'TEST'; } $data = array('CanEmulateUser' => $this->CanEmulateUser(), 'Mode' => $mode, 'TimeToLoad' => round(microtime(true) - $_SERVER["REQUEST_TIME_FLOAT"], 2)); // dump out our debug data return ArrayData::create($data); }