/** * Convert an address into a latitude and longitude. * * @param string $address The address to geocode. * @param string $region An optional two letter region code. * @return array An associative array with lat and lng keys. */ public static function address_to_point($address, $region = null) { // Get the URL for the Google API $url = Config::inst()->get('GoogleGeocoding', 'google_api_url'); $key = Config::inst()->get('GoogleGeocoding', 'google_api_key'); // Query the Google API $service = new RestfulService($url); $service->setQueryString(array('address' => $address, 'sensor' => 'false', 'region' => $region, 'key' => $key)); if ($service->request()->getStatusCode() === 500) { $errorMessage = '500 status code, Are you sure your SSL certificates are properly setup? You can workaround this locally by setting CURLOPT_SSL_VERIFYPEER to "false", however this is not recommended for security reasons.'; if (Director::isDev()) { throw new Exception($errorMessage); } else { user_error($errorMessage); } return false; } if (!$service->request()->getBody()) { // If blank response, ignore to avoid XML parsing errors. return false; } $response = $service->request()->simpleXML(); if ($response->status != 'OK') { return false; } $location = $response->result->geometry->location; return array('lat' => (double) $location->lat, 'lng' => (double) $location->lng); }
public function __call($method, $arguments) { // do not make requests with an invalid key if ($method != 'ping' && !$this->isApiKeyValid()) { return; } if ($this->getAutoCache()) { $cache_key = $this->makeCacheKey($method, $arguments); $cache = SS_Cache::factory(__CLASS__); if ($result = $cache->load($cache_key)) { return unserialize($result); } } try { $result = call_user_func_array(array($this->client, $method), $arguments); } catch (Exception $e) { if (Director::isDev() && $this->debug_exceptions) { var_dump($e); } $result = false; } if ($this->getAutoCache()) { $cache->save(serialize($result)); } return $result; }
/** * Checks if cdn rewrite is enabled * @return bool */ static function isEnabled() { $general = Config::inst()->get('CDNRewriteRequestFilter', 'cdn_rewrite'); $notDev = !Director::isDev() || Config::inst()->get('CDNRewriteRequestFilter', 'enable_in_dev'); $notBackend = !self::isBackend() || Config::inst()->get('CDNRewriteRequestFilter', 'enable_in_backend'); return $general && $notDev && $notBackend; }
/** * * * @param string $token * @throws RestUserException * @return \Member */ private static function get_member_from_token($token) { try { $data = self::jwt_decode($token, self::get_key()); if ($data) { // todo: check expire time if (time() > $data['expire']) { throw new RestUserException("Session expired", 403); } $id = (int) $data['userId']; $user = \DataObject::get(\Config::inst()->get('BaseRestController', 'Owner'))->byID($id); if (!$user) { throw new RestUserException("Owner not found in database", 403); } return $user; } } catch (RestUserException $e) { throw $e; } catch (\Exception $e) { if (\Director::isDev() && $token == \Config::inst()->get('JwtAuth', 'DevToken')) { return \DataObject::get(\Config::inst()->get('BaseRestController', 'Owner'))->first(); } } throw new RestUserException("Token invalid", 403); }
/** * Provides a front-end utility menu with administrative functions and developer tools * Relies on SilverStripeNavigator * * @return string */ public function BetterNavigator() { $isDev = Director::isDev(); if ($isDev || Permission::check('CMS_ACCESS_CMSMain') || Permission::check('VIEW_DRAFT_CONTENT')) { if ($this->owner && $this->owner->dataRecord) { //Get SilverStripeNavigator links & stage info (CMS/Stage/Live/Archive) $nav = array(); $navigator = new SilverStripeNavigator($this->owner->dataRecord); $items = $navigator->getItems(); foreach ($items as $item) { $nav[$item->getName()] = array('Link' => $item->getLink(), 'Active' => $item->isActive()); } //Is the logged in member nominated as a developer? $member = Member::currentUser(); $devs = Config::inst()->get('BetterNavigator', 'developers'); $isDeveloper = $member && is_array($devs) ? in_array($member->Email, $devs) : false; //Add other data for template $nav = array_merge($nav, array('Member' => $member, 'Stage' => Versioned::current_stage(), 'LoginLink' => Config::inst()->get('Security', 'login_url'), 'Mode' => Director::get_environment_type(), 'IsDeveloper' => $isDeveloper)); //Merge with page data, send to template and render $nav = new ArrayData($nav); $page = $this->owner->customise($nav); return $page->renderWith('BetterNavigator'); } } return false; }
public function requireDefaultRecords() { if (Director::isDev()) { $loader = new FixtureLoader(); $loader->loadFixtures(); } }
function init() { if (!Director::is_cli() && !Director::isDev() && !Permission::check("ADMIN")) { Security::permissionFailure(); } parent::init(); }
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; }
/** * Include requirements that deploynaut needs, such as javascript. */ public static function include_requirements() { // JS should always go to the bottom, otherwise there's the risk that Requirements // puts them halfway through the page to the nearest <script> tag. We don't want that. Requirements::set_force_js_to_bottom(true); // todo these should be bundled into the same JS as the others in "static" below. // We've deliberately not used combined_files as it can mess with some of the JS used // here and cause sporadic errors. Requirements::javascript('deploynaut/javascript/jquery.js'); Requirements::javascript('deploynaut/javascript/bootstrap.js'); Requirements::javascript('deploynaut/javascript/q.js'); Requirements::javascript('deploynaut/javascript/tablefilter.js'); Requirements::javascript('deploynaut/javascript/deploynaut.js'); Requirements::javascript('deploynaut/javascript/bootstrap.file-input.js'); Requirements::javascript('deploynaut/thirdparty/select2/dist/js/select2.min.js'); Requirements::javascript('deploynaut/javascript/selectize.js'); Requirements::javascript('deploynaut/thirdparty/bootstrap-switch/dist/js/bootstrap-switch.min.js'); Requirements::javascript('deploynaut/javascript/material.js'); // Load the buildable dependencies only if not loaded centrally. if (!is_dir(BASE_PATH . DIRECTORY_SEPARATOR . 'static')) { if (\Director::isDev()) { \Requirements::javascript('deploynaut/static/bundle-debug.js'); } else { \Requirements::javascript('deploynaut/static/bundle.js'); } } Requirements::css('deploynaut/static/style.css'); }
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 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(); } } }
public function MetaTags(&$tags) { if (Director::isDev() or Director::isTest()) { $tags .= '<meta name="robots" content="noindex, nofollow" />'; } return $tags; }
protected function getFileList($fileToFind, $ext) { $cleanExt = "." . ltrim($ext, "."); $fileNoExt = preg_replace("/(.min)?" . $cleanExt . "\$/", "", $fileToFind); // If dev mode .min has less priority return Director::isDev() ? array($fileNoExt . $cleanExt, $fileNoExt . ".min" . $cleanExt) : array($fileNoExt . ".min" . $cleanExt, $fileNoExt . $cleanExt); }
public function index() { // Prepare ApiRequestSerialiser::execute($this); ApiAuthenticator::execute($this); // Generate if ($this->status === 200) { $output = array(); $implementerclass = $this->getImplementerClass(); if (!is_null($implementerclass)) { $this->implementer = new $implementerclass(); $method = $this->method; try { $this->implementer->{$method}($this); } catch (Exception $except) { if ($this->status === 200) { $this->setError(array("status" => 500, "dev" => "Error processing request: please check your syntax against the request definition", "user" => "This request could not be processed")); } } } else { if (Director::isDev()) { $this->testOutput(); } } } else { $this->populateErrorResponse(); } // Deliver $this->setStandardHeaders(); $ApiResponse = $this->getResponseSerialiser(); // Hook to allow analytics tracking, external logging, etc $this->extend('updateController', $this); return $ApiResponse->execute($this); }
function init() { parent::init(); // Special case for dev/build: Defer permission checks to DatabaseAdmin->init() (see #4957) $requestedDevBuild = stripos($this->request->getURL(), 'dev/build') === 0; // We allow access to this controller regardless of live-status or ADMIN permission only // if on CLI. Access to this controller is always allowed in "dev-mode", or of the user is ADMIN. $canAccess = $requestedDevBuild || Director::isDev() || Director::is_cli() || Permission::check("ADMIN"); if (!$canAccess) { return Security::permissionFailure($this); } // check for valid url mapping // lacking this information can cause really nasty bugs, // e.g. when running Director::test() from a FunctionalTest instance global $_FILE_TO_URL_MAPPING; if (Director::is_cli()) { if (isset($_FILE_TO_URL_MAPPING)) { $fullPath = $testPath = BASE_PATH; while ($testPath && $testPath != "/" && !preg_match('/^[A-Z]:\\\\$/', $testPath)) { $matched = false; if (isset($_FILE_TO_URL_MAPPING[$testPath])) { $matched = true; break; } $testPath = dirname($testPath); } if (!$matched) { echo 'Warning: You probably want to define ' . 'an entry in $_FILE_TO_URL_MAPPING that covers "' . Director::baseFolder() . '"' . "\n"; } } else { echo 'Warning: You probably want to define $_FILE_TO_URL_MAPPING in ' . 'your _ss_environment.php as instructed on the "sake" page of the doc.silverstripe.org wiki' . "\n"; } } }
public function WebpackDevServer() { if (Director::isDev()) { $socket = @fsockopen('localhost', 3000, $errno, $errstr, 1); return !$socket ? false : true; } }
public function onBeforeInit() { $host = GlobalNavSiteTreeExtension::get_toolbar_hostname(); if ((isset($_REQUEST['regenerate_nav']) || isset($_REQUEST['flush'])) && $host == Director::protocolAndHost() && (Permission::check('ADMIN') || Director::isDev())) { GlobalNavSiteTreeExtension::create_static_navs(); } }
function init() { parent::init(); if (!(Director::isDev() || Director::is_cli() || Permission::check("ADMIN"))) { return Security::permissionFailure($this); } }
/** * SSCompactNavigator first checks if you are allowed to see the navigation bar, and if so, then checks * if third party templates have been specified. If so, it loads them, and provides them with the required * variables. If not, it loads the defaults instead. */ public function SSCompactNavigator() { if (Director::isDev() || Permission::check('CMS_ACCESS_CMSMain')) { $RenderTemplate = isset(CompactNavigator::$Template) ? CompactNavigator::$Template : $this->class; if (isset(CompactNavigator::$CssTheme)) { Requirements::css(CompactNavigator::$CssTheme); } else { Requirements::css('compactnavigator/css/CompactNavigator.css'); } if (isset(CompactNavigator::$JsTheme)) { Requirements::javascript(CompactNavigator::$JsTheme); } else { Requirements::javascript('compactnavigator/scripts/CompactNavigator.js'); } if (class_exists("CMSMain")) { $this->owner->cmsLink = Controller::join_links(singleton("CMSMain")->Link("edit"), "show"); } $this->owner->adminLink = self::$adminLink; if ($date = Versioned::current_archived_date()) { $this->owner->DisplayMode = 'Archived'; $this->owner->ArDate = Object::create('Datetime', $date, null); } else { $this->owner->DisplayMode = Versioned::current_stage(); } return $this->owner->renderWith(array($RenderTemplate, 'CompactNavigatior')); } }
public function Field($properties = array()) { Requirements::javascript('ajaxuploadfield/thirdparty/valums/client/fileuploader.min.js', 'fileuploader'); //configure javascript $htmlid = $this->XML_val('Name') . "_uploader"; $thislink = $this->Link('save'); $options = array('action' => $thislink, 'multiple' => false); $allowedextensions = $this->getValidator()->getAllowedExtensions(); if (is_array($allowedextensions)) { $options['allowedExtensions'] = $allowedextensions; } if ($maxfilesize = $this->getValidator()->getAllowedMaxFileSize()) { $options['sizeLimit'] = $maxfilesize; } if (Director::isDev()) { $options['debug'] = true; } $options = array_merge($options, $this->config); $encodedoptions = json_encode($options); $extraclasses = count($this->buttonClasses) ? 'class=\\"' . implode(" ", $this->buttonClasses) . '\\"' : ""; $replacementhtml = '<span id=\\"' . $htmlid . '\\"><input type=\\"submit\\" ' . $extraclasses . ' value=\\"' . $this->title . '\\" /></span>'; //store globally reachable js reference, to allow later customisations $script = <<<JS \t\t\tqq.instances = qq.instances ? qq.instances : {}; \t\t\t\$("#{$htmlid}").html("{$replacementhtml}").each(function(){ \t\t\t\tvar el = \$(this); \t\t\t\tvar options = {$encodedoptions}; \t\t\t\toptions['button'] = el[0]; \t\t\t\tvar uploader = new qq.FileUploaderBasic(options); \t\t\t\tel.data('uploader',uploader); \t\t\t\tqq.instances['{$htmlid}'] = uploader; \t\t\t}); JS; Requirements::customScript($script, 'uploader' . $this->id()); if ($this->form) { $record = $this->form->getRecord(); } $fieldName = $this->name; if (isset($record) && $record) { $imageField = $record->{$fieldName}(); } else { $imageField = ""; } $html = "<div id=\"{$htmlid}\">"; if ($imageField && $imageField->exists()) { $html .= '<div class="thumbnail">'; if ($imageField->hasMethod('Thumbnail') && $imageField->Thumbnail()) { $html .= "<img src=\"" . $imageField->Thumbnail()->getURL() . "\" />"; } else { if ($imageField->CMSThumbnail()) { $html .= "<img src=\"" . $imageField->CMSThumbnail()->getURL() . "\" />"; } } $html .= '</div>'; } $html .= $this->createTag("input", array("type" => "file", "name" => $this->name, "id" => $this->id(), 'disabled' => $this->disabled)); $html .= $this->createTag("input", array("type" => "hidden", "name" => "MAX_FILE_SIZE", "value" => $maxfilesize)); $html .= "</div>"; return $html; }
/** * Check that the user has appropriate permissions to execute this task */ public function init() { if (!Director::is_cli() && !Director::isDev() && !Permission::check('ADMIN')) { return Security::permissionFailure(); } parent::init(); }
/** * Return the payment form */ public function PayForm() { $request = $this->getRequest(); $response = Session::get('EwayResponse'); $months = array('01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'); $years = range(date('y'), date('y') + 10); //Note: years beginning with 0 might cause issues $amount = $response->Payment->TotalAmount; $amount = number_format($amount / 100, 2); $currency = $response->Payment->CurrencyCode; $fields = new FieldList(HiddenField::create('EWAY_ACCESSCODE', '', $response->AccessCode), TextField::create('PayAmount', 'Amount', $amount . ' ' . $currency)->setDisabled(true), $nameField = TextField::create('EWAY_CARDNAME', 'Card holder'), $numberField = TextField::create('EWAY_CARDNUMBER', 'Card Number'), $expMonthField = DropdownField::create('EWAY_CARDEXPIRYMONTH', 'Expiry Month', array_combine($months, $months)), $expYearField = DropdownField::create('EWAY_CARDEXPIRYYEAR', 'Expiry Year', array_combine($years, $years)), $cvnField = TextField::create('EWAY_CARDCVN', 'CVN Number'), HiddenField::create('FormActionURL', '', $response->FormActionURL)); //Test data if (Director::isDev()) { $nameField->setValue('Test User'); $numberField->setValue('4444333322221111'); $expMonthField->setValue('12'); $expYearField->setValue(date('y') + 1); $cvnField->setValue('123'); } $actions = new FieldList(FormAction::create('', 'Process')); $form = new Form($this, 'PayForm', $fields, $actions); $form->setFormAction($response->FormActionURL); Requirements::javascript(FRAMEWORK_DIR . '/thirdparty/jquery/jquery.js'); Requirements::javascript(THIRDPARTY_DIR . '/jquery-entwine/dist/jquery.entwine-dist.js'); Requirements::javascript('payment-eway/javascript/eway-form.js'); $this->extend('updatePayForm', $form); return $form; }
/** * Process a single group. * * Without queuedjobs, it's necessary to shell this out to a background task as this is * very memory intensive. * * The sub-process will then invoke $processor->runGroup() in {@see Solr_Reindex::doReindex} * * @param LoggerInterface $logger * @param SolrIndex $indexInstance Index instance * @param array $state Variant state * @param string $class Class to index * @param int $groups Total groups * @param int $group Index of group to process * @param string $taskName Name of task script to run */ protected function processGroup(LoggerInterface $logger, SolrIndex $indexInstance, $state, $class, $groups, $group, $taskName) { // Build state $statevar = json_encode($state); if (strpos(PHP_OS, "WIN") !== false) { $statevar = '"' . str_replace('"', '\\"', $statevar) . '"'; } else { $statevar = "'" . $statevar . "'"; } // Build script $indexName = $indexInstance->getIndexName(); $scriptPath = sprintf("%s%sframework%scli-script.php", BASE_PATH, DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR); $scriptTask = "php {$scriptPath} dev/tasks/{$taskName}"; $cmd = "{$scriptTask} index={$indexName} class={$class} group={$group} groups={$groups} variantstate={$statevar}"; $cmd .= " verbose=1 2>&1"; $logger->info("Running '{$cmd}'"); // Execute script via shell $res = $logger ? passthru($cmd) : `{$cmd}`; if ($logger) { $logger->info(preg_replace('/\\r\\n|\\n/', '$0 ', $res)); } // If we're in dev mode, commit more often for fun and profit if (Director::isDev()) { Solr::service($indexName)->commit(); } // This will slow down things a tiny bit, but it is done so that we don't timeout to the database during a reindex DB::query('SELECT 1'); }
function init() { parent::init(); // We allow access to this controller regardless of live-status or ADMIN permission only // if on CLI. Access to this controller is always allowed in "dev-mode", or of the user is ADMIN. $canAccess = Director::isDev() || Director::is_cli() || Permission::check("ADMIN"); if (!$canAccess) { return Security::permissionFailure($this, "This page is secured and you need administrator rights to access it. " . "Enter your credentials below and we will send you right along."); } // check for valid url mapping // lacking this information can cause really nasty bugs, // e.g. when running Director::test() from a FunctionalTest instance global $_FILE_TO_URL_MAPPING; if (Director::is_cli()) { if (isset($_FILE_TO_URL_MAPPING)) { $fullPath = $testPath = $_SERVER['SCRIPT_FILENAME']; while ($testPath && $testPath != "/" && !preg_match('/^[A-Z]:\\\\$/', $testPath)) { $matched = false; if (isset($_FILE_TO_URL_MAPPING[$testPath])) { $matched = true; break; } $testPath = dirname($testPath); } if (!$matched) { echo 'Warning: You probably want to define ' . 'an entry in $_FILE_TO_URL_MAPPING that covers "' . Director::baseFolder() . '"' . "\n"; } } else { echo 'Warning: You probably want to define $_FILE_TO_URL_MAPPING in ' . 'your _ss_environment.php as instructed on the "sake" page of the doc.silverstripe.com wiki' . "\n"; } } }
/** * Performs automatic injection of LessPhp compilation */ public function onAfterInit() { if (Director::isDev() || isset($_GET['flush'])) { $compiler = new LessPhp(); $compiler->CompileThemedCssFiles(); } }
public function index(SS_HTTPRequest $request) { if (!Director::isDev() && !Permission::check('CMS_ACCESS_CMSMain')) { return Security::permissionFailure($this); } if ($request->latestParam('ID')) { $templates = $this->templateArray(); if (isset($templates[$request->latestParam('ID')])) { $next = false; $previous = false; $useNext = false; foreach ($templates as $k => $v) { if ($useNext) { $next = new ArrayData(array('Name' => $v['Name'], 'Link' => 'patterns/index/' . $k)); break; } if ($k == $request->latestParam('ID')) { // mat $useNext = true; } else { $previous = new ArrayData(array('Name' => $v['Name'], 'Link' => 'patterns/index/' . $k)); } } return $this->customise(new ArrayData(array('ClassName' => 'Pattern', 'IsPatternLab' => true, 'PreviousPattern' => $previous, 'NextPattern' => $next, 'PatternName' => $templates[$request->latestParam('ID')]['Name'], 'Patterns' => $this->renderWith(array($templates[$request->latestParam('ID')]['Template'])))))->renderWith($templates[$request->latestParam('ID')]['Template']); } } return $this->renderWith(array(__CLASS__, 'Page')); }
/** * Handles incoming requests to the kapost service */ public function index() { //If the request is not a post request 404 if (!$this->request->isPOST()) { return ErrorPage::response_for(404); } //If the request is not the kapost user agent 404 if (self::config()->check_user_agent == true && $this->request->getHeader('User-Agent') != 'Kapost XMLRPC::Client') { return ErrorPage::response_for(404); } $methods = array_fill_keys($this->exposed_methods, array('function' => array($this, 'handleRPCMethod'))); //Disable Content Negotiator and send the text/xml header (which kapost expects) ContentNegotiator::config()->enabled = false; $this->response->addHeader('Content-Type', 'text/xml'); $server = new xmlrpc_server($methods, false); $server->compress_response = true; if (Director::isDev()) { $server->setDebug(3); //Base 64 encoded debug information is included in the response $server->exception_handling = 2; //Exception's sent to the client } //Force the internal encoding of the XMLRPC library to utf-8 $GLOBALS['xmlrpc_internalencoding'] = self::config()->database_charset; return $server->service($this->request->getBody(), true); }
/** * Use PHP to check for robots meta tag * NOTE this doesn't work locally (dev mode) */ public function getRobotsMetaTag() { if (!Director::isDev()) { $metatags = get_meta_tags(Director::absoluteBaseURL()); $robots = empty($metatags['robots']) ? false : true; } return false; }
public function init() { parent::init(); $canAccess = Director::isDev() || Director::is_cli() || Permission::check("ADMIN"); if (!$canAccess) { return Security::permissionFailure($this); } }
function init() { parent::init(); $canAccess = Director::isDev() || Director::is_cli() || !self::$check_permission || Permission::check(self::$check_permission); if (!$canAccess) { return Security::permissionFailure($this); } }