protected function rewriteImages($obj, $field) { preg_match_all('/<img[^>]*>/', $obj->{$field}, $imageTags, PREG_SET_ORDER); if ($imageTags) { foreach ($imageTags as $imageTag) { preg_match('/src=["\'](.+?)["\']/', $imageTag[0], $imageUrlMatch); if (!$imageUrlMatch) { continue; } $oldImageUrl = $imageUrlMatch[1]; $oldImageUrlNormalized = $this->normalizeImageUrl($oldImageUrl); // Ignore absolute urls since they'll continue to work if (Director::is_absolute_url($oldImageUrlNormalized)) { continue; } // TODO Fix relative images $newImageUrl = rtrim($this->imagePath, '/') . '/' . ltrim($oldImageUrlNormalized, '/'); if ($this->getOldBaseUrl()) { $oldImageUrlAbs = rtrim($this->getOldBaseUrl(), '/') . '/' . trim($oldImageUrlNormalized, '/'); } else { $oldImageUrlAbs = $oldImageUrlNormalized; } $this->images[$oldImageUrlAbs] = $newImageUrl; // TODO More robust replacement $obj->{$field} = str_replace($oldImageUrl, $newImageUrl, $obj->{$field}); } $obj->write(); } }
public function testIsAbsoluteUrl() { $this->assertTrue(Director::is_absolute_url('http://test.com')); $this->assertTrue(Director::is_absolute_url('https://test.com')); $this->assertTrue(Director::is_absolute_url(' https://test.com/testpage ')); $this->assertFalse(Director::is_absolute_url('test.com/testpage')); $this->assertTrue(Director::is_absolute_url('ftp://test.com')); $this->assertFalse(Director::is_absolute_url('/relative')); $this->assertFalse(Director::is_absolute_url('relative')); $this->assertFalse(Director::is_absolute_url('/relative/?url=http://test.com')); }
/** * Adds the default languages if they are missing */ public function requireDefaultRecords() { parent::requireDefaultRecords(); $defaultLangs = array_keys($this->defaultLanguages); $dbLangCount = SnippetLanguage::get()->filter('Name', $defaultLangs)->filter('UserLanguage', 0)->Count(); if ($dbLangCount < count($defaultLangs)) { foreach ($this->defaultLanguages as $name => $data) { if (!SnippetLanguage::get()->find('Name', $name)) { $lang = new SnippetLanguage(); $lang->Name = $name; $lang->FileExtension = $data['Extension']; $lang->HighlightCode = $data['HighlightCode']; $lang->UserLanguage = false; $lang->write(); DB::alteration_message('Created snippet language "' . $name . '"', 'created'); } } } //Look for config languages $configLanguages = CodeBank::config()->extra_languages; if (!empty($configLanguages)) { foreach ($configLanguages as $language) { //Validate languages if (empty($language['Name']) || empty($language['FileName']) || empty($language['HighlightCode']) || empty($language['Brush'])) { user_error('Invalid snippet user language found in config, user languages defined in config must contain a Name, FileName, HighlightCode and Brush file path', E_USER_WARNING); continue; } $lang = SnippetLanguage::get()->filter('Name', Convert::raw2sql($language['Name']))->filter('HighlightCode', Convert::raw2sql($language['HighlightCode']))->filter('UserLanguage', true)->first(); if (empty($lang) || $lang === false || $lang->ID <= 0) { if (Director::is_absolute($language['Brush']) || Director::is_absolute_url($language['Brush'])) { user_error('Invalid snippet user language found in config, user languages defined in config must contain a path to the brush relative to the SilverStripe base (' . Director::baseFolder() . ')', E_USER_WARNING); continue; } if (preg_match('/\\.js$/', $language['Brush']) == 0) { user_error('Invalid snippet user language found in config, user languages defined in config must be javascript files', E_USER_WARNING); continue; } //Add language $lang = new SnippetLanguage(); $lang->Name = $language['Name']; $lang->FileExtension = $language['FileName']; $lang->HighlightCode = $language['HighlightCode']; $lang->BrushFile = $language['Brush']; $lang->UserLanguage = true; $lang->write(); DB::alteration_message('Created snippet user language "' . $language['Name'] . '"', 'created'); } } } }
public function testIsAbsoluteUrl() { $this->assertTrue(Director::is_absolute_url('http://test.com/testpage')); $this->assertTrue(Director::is_absolute_url('ftp://test.com')); $this->assertFalse(Director::is_absolute_url('test.com/testpage')); $this->assertFalse(Director::is_absolute_url('/relative')); $this->assertFalse(Director::is_absolute_url('relative')); $this->assertTrue(Director::is_absolute_url("https://test.com/?url=http://foo.com")); $this->assertTrue(Director::is_absolute_url("trickparseurl:http://test.com")); $this->assertTrue(Director::is_absolute_url('//test.com')); $this->assertTrue(Director::is_absolute_url('/////test.com')); $this->assertTrue(Director::is_absolute_url(' ///test.com')); $this->assertTrue(Director::is_absolute_url('http:test.com')); $this->assertTrue(Director::is_absolute_url('//http://test.com')); }
/** * Returns text of link, either as entered for External or generated from Internal. If Internal an target page * isn't found then returns LinkAttributeExtension.InternalLink.MissingTarget message e.g. '[linked page not found]' type message * * @return string */ public function ResolvedLink() { $link = ''; if ($this->IsExternal()) { $externalLink = $this()->ExternalLink; if (!\Director::is_absolute_url($externalLink)) { $link = \Director::protocol() . $externalLink; } else { $link = $externalLink; } } elseif ($this()->InternalLink()) { $link = $this()->InternalLink()->Link(); } return $link; }
/** * Handles requests to view a vidyard video in the cms * @param {SS_HTTPRequest} $request HTTP Request object * @return {string} Rendered view on success null on error * @throws SS_HTTPResponse_Exception */ public function viewvidyard(SS_HTTPRequest $request) { $file = null; $url = null; if ($fileUrl = $request->getVar('VidyardURL')) { // If this isn't an absolute URL, or is, but is to this site, try and get the File object // that is associated with it if (Director::is_absolute_url($fileUrl) && !Director::is_site_url($fileUrl) && Vidyard::validateVidyardURL($fileUrl)) { list($file, $url) = $this->getVideoByURL($fileUrl); } else { throw new SS_HTTPResponse_Exception('"VidyardURL" is not a valid Vidyard Video', 400); } } else { throw new SS_HTTPResponse_Exception('Need "VidyardURL" parameter to identify the file', 400); } $fileWrapper = new VidyardInsertMedia_Embed($url, $file); $fields = $this->getFieldsForVidyard($url, $fileWrapper); return $fileWrapper->customise(array('Fields' => $fields))->renderWith('HtmlEditorField_viewfile'); }
/** * View of a single file, either on the filesystem or on the web. */ public function viewfile($request) { // TODO Would be cleaner to consistently pass URL for both local and remote files, // but GridField doesn't allow for this kind of metadata customization at the moment. if ($url = $request->getVar('FileURL')) { if (Director::is_absolute_url($url) && !Director::is_site_url($url)) { $url = $url; $file = new File(array('Title' => basename($url), 'Filename' => $url)); } else { $url = Director::makeRelative($request->getVar('FileURL')); $url = preg_replace('/_resampled\\/[^-]+-/', '', $url); $file = File::get()->filter('Filename', $url)->first(); if (!$file) { $file = new File(array('Title' => basename($url), 'Filename' => $url)); } } } elseif ($id = $request->getVar('ID')) { $file = DataObject::get_by_id('File', $id); $url = $file->RelativeLink(); } else { throw new LogicException('Need either "ID" or "FileURL" parameter to identify the file'); } // Instanciate file wrapper and get fields based on its type // Check if appCategory is an image and exists on the local system, otherwise use oEmbed to refference a // remote image if ($file && $file->appCategory() == 'image' && Director::is_site_url($url)) { $fileWrapper = new HtmlEditorField_Image($url, $file); } elseif (!Director::is_site_url($url)) { $fileWrapper = new HtmlEditorField_Embed($url, $file); } else { $fileWrapper = new HtmlEditorField_File($url, $file); } $fields = $this->getFieldsForFile($url, $fileWrapper); $this->extend('updateFieldsForFile', $fields, $url, $fileWrapper); return $fileWrapper->customise(array('Fields' => $fields))->renderWith($this->templateViewFile); }
/** * Checks if a given URL is relative by checking * {@link is_absolute_url()}. * * @param string $url * @return boolean */ public static function is_relative_url($url) { return !Director::is_absolute_url($url); }
/** * Get remote File given url * * @param string $fileUrl Absolute URL * @return array * @throws SS_HTTPResponse_Exception */ protected function viewfile_getRemoteFileByURL($fileUrl) { if (!Director::is_absolute_url($fileUrl)) { throw $this->getErrorFor(_t("HTMLEditorField_Toolbar.ERROR_ABSOLUTE", "Only absolute urls can be embedded")); } $scheme = strtolower(parse_url($fileUrl, PHP_URL_SCHEME)); $allowed_schemes = self::config()->fileurl_scheme_whitelist; if (!$scheme || $allowed_schemes && !in_array($scheme, $allowed_schemes)) { throw $this->getErrorFor(_t("HTMLEditorField_Toolbar.ERROR_SCHEME", "This file scheme is not included in the whitelist")); } $domain = strtolower(parse_url($fileUrl, PHP_URL_HOST)); $allowed_domains = self::config()->fileurl_domain_whitelist; if (!$domain || $allowed_domains && !in_array($domain, $allowed_domains)) { throw $this->getErrorFor(_t("HTMLEditorField_Toolbar.ERROR_HOSTNAME", "This file hostname is not included in the whitelist")); } return [null, $fileUrl]; }
/** * Returns whether the given url is an internal url * * @param string $url URL to check * * @return bool * * @author Sebastian Diel <*****@*****.**> * @since 09.05.2012 */ public function isInternalUrl($url) { $isInternalUrl = false; if (Director::is_absolute_url($url) && strpos($url, $_SERVER['SERVER_NAME'])) { $isInternalUrl = true; } return $isInternalUrl; }
/** * Generate the JavaScript that will set TinyMCE's configuration: * - Parse all configurations into JSON objects to be used in JavaScript * - Includes TinyMCE and configurations using the {@link Requirements} system * * @return array */ protected function getConfig() { $settings = $this->getSettings(); // https://www.tinymce.com/docs/configure/url-handling/#document_base_url $settings['document_base_url'] = Director::absoluteBaseURL(); // https://www.tinymce.com/docs/api/class/tinymce.editormanager/#baseURL $tinyMCEBaseURL = Controller::join_links(Director::absoluteBaseURL(), $this->config()->base_dir); $settings['baseURL'] = $tinyMCEBaseURL; // map all plugins to absolute urls for loading $plugins = array(); foreach ($this->getPlugins() as $plugin => $path) { if (!$path) { // Empty paths: Convert to urls in standard base url $path = Controller::join_links($tinyMCEBaseURL, "plugins/{$plugin}/plugin.min.js"); } elseif (!Director::is_absolute_url($path)) { // Non-absolute urls are made absolute $path = Director::absoluteURL($path); } $plugins[$plugin] = $path; } // https://www.tinymce.com/docs/configure/integration-and-setup/#external_plugins if ($plugins) { $settings['external_plugins'] = $plugins; } // https://www.tinymce.com/docs/configure/editor-appearance/#groupingtoolbarcontrols $buttons = $this->getButtons(); $settings['toolbar'] = []; foreach ($buttons as $rowButtons) { $row = implode(' ', $rowButtons); if (count($buttons) > 1) { $settings['toolbar'][] = $row; } else { $settings['toolbar'] = $row; } } // https://www.tinymce.com/docs/configure/content-appearance/#content_css $settings['content_css'] = $this->getEditorCSS(); // https://www.tinymce.com/docs/configure/editor-appearance/#theme_url $theme = $this->getTheme(); if (!Director::is_absolute_url($theme)) { $theme = Controller::join_links($tinyMCEBaseURL, "themes/{$theme}/theme.min.js"); } $settings['theme_url'] = $theme; // Send back return $settings; }
/** * View of a single file, either on the filesystem or on the web. */ public function viewfile($request) { $file = null; $url = null; // TODO Would be cleaner to consistently pass URL for both local and remote files, // but GridField doesn't allow for this kind of metadata customization at the moment. if ($fileUrl = $request->getVar('FileURL')) { // If this isn't an absolute URL, or is, but is to this site, try and get the File object // that is associated with it if (!Director::is_absolute_url($fileUrl) || Director::is_site_url($fileUrl)) { list($file, $url) = $this->viewfile_getLocalFileByURL($fileUrl); } else { list($file, $url) = $this->viewfile_getRemoteFileByURL($fileUrl); } } elseif ($id = $request->getVar('ID')) { list($file, $url) = $this->viewfile_getLocalFileByID($id); } else { throw new SS_HTTPResponse_Exception('Need either "ID" or "FileURL" parameter to identify the file', 400); } // Instanciate file wrapper and get fields based on its type // Check if appCategory is an image and exists on the local system, otherwise use oEmbed to refference a // remote image if (!$file || !$url) { throw new SS_HTTPResponse_Exception('Unable to find file to view', 404); } elseif ($file->appCategory() == 'image' && Director::is_site_url($url)) { $fileWrapper = new HtmlEditorField_Image($url, $file); } elseif (!Director::is_site_url($url)) { $fileWrapper = new HtmlEditorField_Embed($url, $file); } else { $fileWrapper = new HtmlEditorField_File($url, $file); } $fields = $this->getFieldsForFile($url, $fileWrapper); $this->extend('updateFieldsForFile', $fields, $url, $fileWrapper); return $fileWrapper->customise(array('Fields' => $fields))->renderWith($this->templateViewFile); }
/** * Login form handler method * * This method is called when the user clicks on "Log in" * * @param array $data Submitted data */ public function dologin($data) { if($this->performLogin($data)) { Session::clear('SessionForms.MemberLoginForm.Email'); Session::clear('SessionForms.MemberLoginForm.Remember'); if(Member::currentUser()->isPasswordExpired()) { if(isset($_REQUEST['BackURL']) && $backURL = $_REQUEST['BackURL']) { Session::set('BackURL', $backURL); } $cp = new ChangePasswordForm($this->controller, 'ChangePasswordForm'); $cp->sessionMessage('Your password has expired. Please choose a new one.', 'good'); Director::redirect('Security/changepassword'); } elseif( isset($_REQUEST['BackURL']) && $_REQUEST['BackURL'] && ( // absolute redirection URLs may cause spoofing !Director::is_absolute_url($_REQUEST['BackURL']) // absolute URLs on the current domain are allowed || strpos($_REQUEST['BackURL'], Director::absoluteBaseURL()) !== FALSE ) ) { Director::redirect($_REQUEST['BackURL']); } else { $member = Member::currentUser(); if($member) { $firstname = Convert::raw2xml($member->FirstName); if(!empty($data['Remember'])) { Session::set('SessionForms.MemberLoginForm.Remember', '1'); $member->logIn(true); } else { $member->logIn(); } Session::set('Security.Message.message', sprintf(_t('Member.WELCOMEBACK', "Welcome Back, %s"), $firstname) ); Session::set("Security.Message.type", "good"); } Director::redirectBack(); } } else { Session::set('SessionForms.MemberLoginForm.Email', $data['Email']); Session::set('SessionForms.MemberLoginForm.Remember', isset($data['Remember'])); if(isset($_REQUEST['BackURL'])) $backURL = $_REQUEST['BackURL']; else $backURL = null; if($backURL) Session::set('BackURL', $backURL); if($badLoginURL = Session::get("BadLoginURL")) { Director::redirect($badLoginURL); } else { // Show the right tab on failed login $loginLink = Director::absoluteURL(Security::Link("login")); if($backURL) $loginLink .= '?BackURL=' . urlencode($backURL); Director::redirect($loginLink . '#' . $this->FormName() .'_tab'); } } }
/** * @param string $wsdl * @throws ConfigurationException * @return void */ public function setWsdl($wsdl) { if (!\Director::is_absolute_url($wsdl)) { throw new ConfigurationException("Wsdl needs to be an absolute url"); } $this->wsdl = $wsdl; }
/** * @param string $gatewayUrl * @throws \Heystack\Core\Exception\ConfigurationException * @return void */ public function setGatewayUrl($gatewayUrl) { if (!\Director::is_absolute_url($gatewayUrl)) { throw new ConfigurationException("Gateway url needs to be an absolute url"); } $this->gatewayUrl = $gatewayUrl; }