public function processRedirect($uri) { $records = $this->getAllRedirects(); $doRedirect = false; foreach ($records as $record) { $record = $record->attributes; // trim to tolerate whitespace in user entry $record['uri'] = trim($record['uri']); // type of match. 3 possibilities: // standard match (no *, no initial and final #) - regex_match = false // regex match (initial and final # (may also contain *)) - regex_match = true // wildcard match (no initial and final #, but does have *) - regex_match = true $regex_match = false; if (preg_match("/^#(.+)#\$/", $record['uri'], $matches)) { // all set to use the regex $regex_match = true; } elseif (strpos($record['uri'], "*")) { // not necessary to replace / with \/ here, but no harm to it either $record['uri'] = "#^" . str_replace(array("*", "/"), array("(.*)", "\\/"), $record['uri']) . '#'; $regex_match = true; } if ($regex_match) { if (preg_match($record['uri'], $uri)) { $redirectLocation = preg_replace($record['uri'], $record['location'], $uri); } } else { // Standard match if ($record['uri'] == $uri) { $redirectLocation = $record['location']; } } } return isset($redirectLocation) ? array("url" => strpos($record['location'], "http") === 0 ? $redirectLocation : UrlHelper::getSiteUrl($redirectLocation), "type" => $record['type']) : false; }
/** * Process Successful Login */ private function _handleSuccessfulLogin($setNotice) { // Get the current user $currentUser = craft()->userSession->getUser(); // Were they trying to access a URL beforehand? $returnUrl = craft()->userSession->getReturnUrl(null, true); if ($returnUrl === null || $returnUrl == craft()->request->getPath()) { // If this is a CP request and they can access the control panel, send them wherever // postCpLoginRedirect tells us if (craft()->request->isCpRequest() && $currentUser->can('accessCp')) { $postCpLoginRedirect = craft()->config->get('postCpLoginRedirect'); $returnUrl = UrlHelper::getCpUrl($postCpLoginRedirect); } else { // Otherwise send them wherever postLoginRedirect tells us $postLoginRedirect = craft()->config->get('postLoginRedirect'); $returnUrl = UrlHelper::getSiteUrl($postLoginRedirect); } } // If this was an Ajax request, just return success:true if (craft()->request->isAjaxRequest()) { $this->returnJson(array('success' => true, 'returnUrl' => $returnUrl)); } else { if ($setNotice) { craft()->userSession->setNotice(Craft::t('Logged in.')); } $this->redirectToPostedUrl($currentUser, $returnUrl); } }
/** * @inheritDoc ITask::runStep() * * @param int $step * * @return bool */ public function runStep($step) { // NOTE: Perhaps much of this should be moved into a service $batch = \Guzzle\Batch\BatchBuilder::factory()->transferRequests(20)->bufferExceptions()->build(); // Make the client $client = new \Guzzle\Http\Client(); // Set the Accept header $client->setDefaultOption('headers/Accept', '*/*'); // Loop the paths in this step foreach ($this->_paths[$step] as $path) { // Make the url, stripping 'site:' from the path if it exists $newPath = preg_replace('/site:/', '', $path, 1); $url = UrlHelper::getSiteUrl($newPath); // Create the GET request $request = $client->get($url); // Add it to the batch $batch->add($request); } // Flush the queue and retrieve the flushed items $requests = $batch->flush(); // Log any exceptions foreach ($batch->getExceptions() as $e) { Craft::log('CacheMonster: an exception occurred: ' . $e->getMessage(), LogLevel::Error); } // Clear any exceptions $batch->clearExceptions(); return true; }
/** * Start searching. * * @param mixed $collectionHandles * @param array $params [Optional] Set params. * * Available params: * - locale Search for data from a certain locale. * - keywords Search keywords. * - limit Limit the search results. * - offset Offset in the search results. * - order Order by a certain key. (Note: Only available with one collection!) * - sort Sort direction when the order param is given. (Note: Only available with one collection!) * * @return bool|array */ public function getResults($collectionHandles, $params = array()) { // Max power! craft()->config->maxPowerCaptain(); craft()->config->set('cacheElementQueries', false); // Get collections if (is_array($collectionHandles)) { $collections = craft()->amSearch_collections->getCollectionsByHandle($collectionHandles); } else { $collections = craft()->amSearch_collections->getCollectionByHandle($collectionHandles); } // Did we get any collections? if (!$collections) { return false; } elseif (!is_array($collections)) { $collections = array($collections); } // Set the important stuff $this->_siteUrl = UrlHelper::getSiteUrl('', null, null, $this->_getSearchParam('locale')); $this->_addTrailingSlash = craft()->config->get('addTrailingSlashesToUrls'); $this->_searchResults = array(); $this->_handledElements = array(); $this->_searchParams = $params; // Get plugin search settings if (!$this->_excerptPrefix) { $searchSettings = craft()->amSearch_settings->getSettingsByType(AmSearchModel::SettingSearch); if ($searchSettings) { foreach ($searchSettings as $searchSetting) { $this->{'_' . $searchSetting->handle} = $searchSetting->value; } } else { // Default $this->_excerptPrefix = '…'; $this->_excerptSuffix = '…'; $this->_charsBeforeKeywords = 100; $this->_charsAfterKeywords = 100; } } // Get data for each collection foreach ($collections as $collection) { // Set collection $this->_collection = $collection; // Get records! $this->_getRecordsForCollection(); } // Order the results by a certain key? $order = $this->_getSearchParam('order', false); $sort = $this->_getSearchParam('sort', 'asc'); if ($order && count($collections) == 1) { $this->_sortSearchResults($order, $sort); } // Limit and offset the results? $limit = $this->_getSearchParam('limit', false); if ($limit && is_numeric($limit)) { $offset = $this->_getSearchParam('offset', 0); $this->_searchResults = array_slice($this->_searchResults, $offset, $limit); } return $this->_searchResults; }
public function createTemplateUrls($plain, $html) { $record = new Postmaster_MessageTemplateRecord(); $record->plain = $plain; $record->html = $html; $record->save(); return array('text' => UrlHelper::getSiteUrl('postmaster/template/text/' . $record->id), 'html' => UrlHelper::getSiteUrl('postmaster/template/html/' . $record->id)); }
/** * Returns the element's full URL. * * @return string */ public function getEurl() { if ($this->uri !== null) { $path = $this->uri == '__home__' ? '' : $this->uri . "/" . $this->eid; $url = UrlHelper::getSiteUrl($path, null, null, $this->locale); return $url; } }
/** * Get login URL * * @param $providerHandle * @param array $params * * @return string */ public function getLoginUrl($providerHandle, array $params = []) { $params['provider'] = $providerHandle; if (isset($params['scope']) && is_array($params['scope'])) { $params['scope'] = urlencode(base64_encode(serialize($params['scope']))); } $url = UrlHelper::getSiteUrl(craft()->config->get('actionTrigger') . '/social/login', $params); return $url; }
public function findRedirectByPath($path) { $redirects = $this->getAllRedirects(); foreach ($redirects as $redirect) { $to = false; if (trim($redirect['uri'], '/') == $path) { $to = $redirect['to']; } elseif ($uri = $this->_isRedirectRegex($redirect['uri'])) { if (preg_match($uri, $path)) { $to = preg_replace($uri, $redirect['to'], $path); } } if ($to) { return ['to' => strpos($to, '://') !== false ? $to : UrlHelper::getSiteUrl($to), 'type' => $redirect['type']]; } } return false; }
public function getUrl($criteria) { if (isset($criteria['asset'])) { if (!$criteria['asset'] instanceof AssetFileModel) { $criteria['asset'] = craft()->assets->getFileById($criteria['asset']); if (!$criteria['asset']) { return null; } } if ($criteria['asset']->filename) { $options = ['id' => $criteria['asset']->id, 'filename' => $criteria['asset']->filename, 'userId' => isset($criteria['userId']) ? $criteria['userId'] : null, 'forceDownload' => isset($criteria['forceDownload']) ? $criteria['forceDownload'] : true]; if (isset($criteria['userGroupId'])) { craft()->requireEdition(Craft::Pro); $options['userGroupId'] = $criteria['userGroupId']; } $urlParam = $this->encodeUrlParam($options); return UrlHelper::getSiteUrl('secureAssetDownload/' . $urlParam); } } return null; }
/** * Returns the element's full URL. * * @return string */ public function getUrl() { if ($this->uri !== null) { return UrlHelper::getSiteUrl($this->uri); } }
/** * Takes over after a user has been activated. * * @param UserModel $user */ private function _onAfterActivateUser(UserModel $user) { // Should we log them in? $loggedIn = false; if (craft()->config->get('autoLoginAfterAccountActivation')) { $loggedIn = craft()->userSession->loginByUserId($user->id, false, true); } // Can they access the CP? if ($user->can('accessCp')) { $postCpLoginRedirect = craft()->config->get('postCpLoginRedirect'); $url = UrlHelper::getCpUrl($postCpLoginRedirect); } else { $activateAccountSuccessPath = craft()->config->getLocalized('activateAccountSuccessPath'); $url = UrlHelper::getSiteUrl($activateAccountSuccessPath); } $this->redirect($url); }
public function getLoginUrl($providerClass, $params = array()) { $params['provider'] = $providerClass; if (isset($params['scopes']) && is_array($params['scopes'])) { $params['scopes'] = urlencode(base64_encode(serialize($params['scopes']))); } $url = UrlHelper::getSiteUrl(craft()->config->get('actionTrigger') . '/social/login', $params); Craft::log(__METHOD__ . " : Authenticate : " . $url, LogLevel::Info, true); return $url; }
/** * Sets a new verification code on a user, and returns their new Password Reset URL. * * @param UserModel $user The user that should get the new Password Reset URL * * @return string The new Password Reset URL. */ public function getPasswordResetUrl(UserModel $user) { $userRecord = $this->_getUserRecordById($user->id); $unhashedVerificationCode = $this->_setVerificationCodeOnUserRecord($userRecord); $userRecord->save(); $path = craft()->config->get('actionTrigger') . '/users/setpassword'; $params = array('code' => $unhashedVerificationCode, 'id' => $userRecord->uid); $scheme = UrlHelper::getProtocolForTokenizedUrl(); if ($user->can('accessCp')) { return UrlHelper::getCpUrl($path, $params, $scheme); } else { $locale = $user->preferredLocale ?: craft()->i18n->getPrimarySiteLocaleId(); return UrlHelper::getSiteUrl($path, $params, $scheme, $locale); } }
/** * Validate that a user has access to an email address. * * @throws HttpException * @throws Exception */ public function actionValidate() { if (craft()->userSession->isLoggedIn()) { $this->redirect(''); } $code = craft()->request->getRequiredQuery('code'); $id = craft()->request->getRequiredQuery('id'); $user = craft()->users->getUserByVerificationCodeAndUid($code, $id); if (!$user) { if (($url = craft()->config->get('activateFailurePath')) != '') { $this->redirect(UrlHelper::getSiteUrl($url)); } else { throw new HttpException('200', Craft::t('Invalid verification code.')); } } if (craft()->users->activateUser($user)) { // Successfully activated user, do they require a password reset or is their password empty? // If so, send them through the password logic. if ($user->passwordResetRequired || !$user->password) { // All users that go through account activation will need to set their password. $code = craft()->users->setVerificationCodeOnUser($user); if ($user->can('accessCp')) { $url = craft()->config->getSetPasswordPath($code, $id, true, 'cp'); } else { $url = craft()->config->getSetPasswordPath($code, $id); } } else { // Log them in. // If the user can't access the CP, then send them to the front-end activateAccountSuccessPath. if (!$user->can('accessCp')) { $url = UrlHelper::getUrl(craft()->config->get('activateAccountSuccessPath')); $this->redirect($url); } else { craft()->userSession->setNotice(Craft::t('Account activated.')); $this->redirectToPostedUrl(); } } } else { if (($url = craft()->config->get('activateFailurePath')) === '') { // Failed to validate user and there is no custom validation failure path. Throw an exception. throw new HttpException('200', Craft::t('There was a problem activating this account.')); } else { // Failed to activate user and there is a custom validate failure path set, so use it. $url = UrlHelper::getSiteUrl($url); } } $this->redirect($url); }
private function _generateUrls($id, $section, $elemType) { $urls = []; $sect = craft()->elements->getCriteria($elemType); $sect->sectionId = $id; $sect->limit = null; foreach ($sect->find() as $elem) { if ($elem->url !== null) { $urlAlts = []; if (is_array($elem->locales) && count($elem->locales) > 1) { foreach ($elem->locales as $locale => $settings) { $locale = $elemType == ElementType::Category || $elemType == 'Commerce_Product' ? $settings : $locale; if ($locale !== craft()->language) { $urlAlts[] = ['locale' => str_replace('_', '-', $locale), 'url' => UrlHelper::getSiteUrl($elem->uri == '__home__' ? '' : $elem->uri, null, null, $locale)]; } } } $urls[] = ['url' => $elem->url, 'urlAlts' => $urlAlts, 'lastmod' => $elem->dateUpdated, 'frequency' => $section['frequency'], 'priority' => $section['priority']]; } } return $urls; }
/** * Login as user. * * @param array $variables * * @return bool */ public function loginAsUser($variables) { if (!isset($variables['userId'])) { return false; } if (craft()->userSession->loginByUserId($variables['userId'])) { craft()->userSession->setNotice(Craft::t('Logged in.')); craft()->amCommand->setReturnMessage(Craft::t('Login as user')); if (craft()->userSession->getUser()->can('accessCp')) { craft()->amCommand->setReturnUrl(UrlHelper::getCpUrl('dashboard')); } else { craft()->amCommand->setReturnUrl(UrlHelper::getSiteUrl('')); } return true; } else { craft()->amCommand->setReturnMessage(Craft::t('There was a problem impersonating this user.')); Craft::log(craft()->userSession->getUser()->username . ' tried to log in using userId: ' . $variables['userId'] . ' but something went wrong.', LogLevel::Error); return false; } }
/** * Gets the sitemap then caches and returns an array of the paths found in it * * TODO: let user set sitemap location(s) in the cp, default to /sitemap.xml * * @method crawlSitemapForPaths * @return array an array of $paths */ public function crawlSitemapForPaths() { // This might be heavy, probably not but better safe than sorry craft()->config->maxPowerCaptain(); $paths = array(); // Get the (one day specified) sitemap $client = new \Guzzle\Http\Client(); $response = $client->get(UrlHelper::getSiteUrl('sitemap.xml'))->send(); // Get the xml and add each url to the $paths array if ($response->isSuccessful()) { $xml = $response->xml(); foreach ($xml->url as $url) { $parts = parse_url((string) $url->loc); $paths[] = 'site:' . ltrim($parts['path'], '/'); } } // Check $paths is unique $paths = array_unique($paths); // Return the actual paths return $paths; }
/** * Redirect the browser after a user’s account has been activated. * * @param UserModel $user The user that was just activated * * @return void */ private function _redirectUserAfterAccountActivation(UserModel $user) { // Can they access the CP? if ($user->can('accessCp')) { $postCpLoginRedirect = craft()->config->get('postCpLoginRedirect'); $url = UrlHelper::getCpUrl($postCpLoginRedirect); } else { $activateAccountSuccessPath = craft()->config->getLocalized('activateAccountSuccessPath'); $url = UrlHelper::getSiteUrl($activateAccountSuccessPath); } $this->redirect($url); }
/** * Returns the element's full URL. * * @return string */ public function getUrl() { if ($this->uri !== null) { $useLocaleSiteUrl = $this->locale != craft()->language && ($localeSiteUrl = craft()->config->getLocalized('siteUrl', $this->locale)); if ($useLocaleSiteUrl) { // Temporarily set Craft to use this element's locale's site URL $siteUrl = craft()->getSiteUrl(); craft()->setSiteUrl($localeSiteUrl); } if ($this->uri == '__home__') { $url = UrlHelper::getSiteUrl(); } else { $url = UrlHelper::getSiteUrl($this->uri); } if ($useLocaleSiteUrl) { craft()->setSiteUrl($siteUrl); } return $url; } }
/** * Returns a list of localized URIs for the passed in element * @return array an array of paths */ public function getLocalizedUris($element = null) { $localizedUris = array(); if ($element) { if (craft()->isLocalized()) { $unsortedLocalizedUris = array(); $_rows = craft()->db->createCommand()->select('locale')->addSelect('uri')->from('elements_i18n')->where(array('elementId' => $element->id, 'enabled' => 1))->queryAll(); foreach ($_rows as $row) { $path = $row['uri'] == '__home__' ? '' : $row['uri']; $unsortedLocalizedUris[$row['locale']] = UrlHelper::getSiteUrl($path, null, null, $row['locale']); } $locales = craft()->i18n->getSiteLocales(); foreach ($locales as $locale) { $localeId = $locale->getId(); if (isset($unsortedLocalizedUris[$localeId])) { $urlParts = parse_url($unsortedLocalizedUris[$localeId]); array_push($localizedUris, "/" . $urlParts['path']); } } } else { array_push($localizedUris, "/" . $element->uri); } } return $localizedUris; }
/** * Sets a new verification code on a user, and returns their new Password Reset URL. * * @param UserModel $user The user that should get the new Password Reset URL * * @return string The new Password Reset URL. */ public function getPasswordResetUrl(UserModel $user) { $userRecord = $this->_getUserRecordById($user->id); $unhashedVerificationCode = $this->_setVerificationCodeOnUserRecord($userRecord); $userRecord->save(); if ($user->can('accessCp')) { $url = UrlHelper::getActionUrl('users/setpassword', array('code' => $unhashedVerificationCode, 'id' => $userRecord->uid), craft()->request->isSecureConnection() ? 'https' : 'http'); } else { // We want to hide the CP trigger if they don't have access to the CP. $path = craft()->config->get('actionTrigger') . '/users/setpassword'; $url = UrlHelper::getSiteUrl($path, array('code' => $unhashedVerificationCode, 'id' => $userRecord->uid), craft()->request->isSecureConnection() ? 'https' : 'http'); } return $url; }
/** * @todo - improve how images are being handled here * @param $prioritizedMetaModel * @throws \Exception */ public static function prepareAssetUrls(SproutSeo_MetaModel &$model) { // If a code override for ogImageSecure is provided, make sure it's an absolute URL if (!empty($model->ogImageSecure)) { if (substr($model->ogImageSecure, 0, 5) !== "https") { throw new \Exception('Open Graph Secure Image override value "' . $model->ogImageSecure . '" must be a secure, absolute url.'); } } // Modify our Assets to reference their URLs if (!empty($model->ogImage)) { // If ogImage starts with "http", roll with it // If not, then process what we have to try to extract the URL if (substr($model->ogImage, 0, 4) !== "http") { if (!is_numeric($model->ogImage)) { throw new \Exception('Open Graph Image override value "' . $model->ogImage . '" must be an absolute url.'); } $ogImage = craft()->elements->getElementById($model->ogImage); $imageUrl = (string) $ogImage->url; if (!empty($ogImage)) { // check to see if Asset already has full Site Url in folder Url if (strpos($imageUrl, "http") !== false) { $model->ogImage = $ogImage->url; } else { $model->ogImage = UrlHelper::getSiteUrl($ogImage->url); } $model->ogImageWidth = $ogImage->width; $model->ogImageHeight = $ogImage->height; $model->ogImageType = $ogImage->mimeType; if (craft()->request->isSecureConnection()) { $secureUrl = preg_replace("/^http:/i", "https:", $ogImage->url); $model->ogImageSecure = $secureUrl; } } } } if (!empty($model->twitterImage)) { // If twitterImage starts with "http", roll with it // If not, then process what we have to try to extract the URL if (substr($model->twitterImage, 0, 4) !== "http") { if (!is_numeric($model->twitterImage)) { throw new \Exception('Twitter Image override value "' . $model->twitterImage . '" must be an absolute url.'); } $twitterImage = craft()->elements->getElementById($model->twitterImage); $imageUrl = (string) $twitterImage->url; if (!empty($twitterImage)) { // check to see if Asset already has full Site Url in folder Url if (strpos($imageUrl, "http") !== false) { $model->twitterImage = $twitterImage->url; } else { $model->twitterImage = UrlHelper::getSiteUrl($twitterImage->url); } } } } }
/** * Ends a template cache. * * @param string $key The template cache key. * @param bool $global Whether the cache should be stored globally. * @param string|null $duration How long the cache should be stored for. * @param mixed|null $expiration When the cache should expire. * @param string $body The contents of the cache. * * @throws \Exception * @return null */ public function endTemplateCache($key, $global, $duration, $expiration, $body) { // If there are any transform generation URLs in the body, don't cache it. // Can't use getResourceUrl() here because that will append ?d= or ?x= to the URL. if (strpos($body, UrlHelper::getSiteUrl(craft()->config->getResourceTrigger() . '/transforms'))) { return; } // Figure out the expiration date if ($duration) { $expiration = new DateTime($duration); } if (!$expiration) { $duration = craft()->config->getCacheDuration(); if ($duration <= 0) { $duration = 31536000; // 1 year } $duration += time(); $expiration = new DateTime('@' . $duration); } // Save it $transaction = craft()->db->getCurrentTransaction() === null ? craft()->db->beginTransaction() : null; try { craft()->db->createCommand()->insert(static::$_templateCachesTable, array('cacheKey' => $key, 'locale' => craft()->language, 'path' => $global ? null : $this->_getPath(), 'expiryDate' => DateTimeHelper::formatTimeForDb($expiration), 'body' => $body), false); $cacheId = craft()->db->getLastInsertID(); // Tag it with any element criteria that were output within the cache if (!empty($this->_cacheCriteria[$key])) { $values = array(); foreach ($this->_cacheCriteria[$key] as $criteria) { $flattenedCriteria = $criteria->getAttributes(null, true); $values[] = array($cacheId, $criteria->getElementType()->getClassHandle(), JsonHelper::encode($flattenedCriteria)); } craft()->db->createCommand()->insertAll(static::$_templateCacheCriteriaTable, array('cacheId', 'type', 'criteria'), $values, false); unset($this->_cacheCriteria[$key]); } // Tag it with any element IDs that were output within the cache if (!empty($this->_cacheElementIds[$key])) { $values = array(); foreach ($this->_cacheElementIds[$key] as $elementId) { $values[] = array($cacheId, $elementId); } craft()->db->createCommand()->insertAll(static::$_templateCacheElementsTable, array('cacheId', 'elementId'), $values, false); unset($this->_cacheElementIds[$key]); } if ($transaction !== null) { $transaction->commit(); } } catch (\Exception $e) { if ($transaction !== null) { $transaction->rollback(); } throw $e; } }
/** * Sets a new verification code on a user, and returns their new Password Reset URL. * * @param UserModel $user The user that should get the new Password Reset URL * * @return string The new Password Reset URL. */ public function getPasswordResetUrl(UserModel $user) { $userRecord = $this->_getUserRecordById($user->id); $unhashedVerificationCode = $this->_setVerificationCodeOnUserRecord($userRecord); $userRecord->save(); $path = craft()->config->get('actionTrigger') . '/users/setpassword'; $params = array('code' => $unhashedVerificationCode, 'id' => $userRecord->uid); $scheme = craft()->request->isSecureConnection() ? 'https' : 'http'; if ($user->can('accessCp')) { return UrlHelper::getCpUrl($path, $params, $scheme); } else { return UrlHelper::getSiteUrl($path, $params, $scheme); } }