Get the router object
public static router ( ) : Gdn_Router | ||
return | Gdn_Router |
/** * Custom finalization. * * @throws Exception */ public function afterImport() { // Set up the routes to redirect from their older counterparts. $Router = Gdn::router(); // Categories $Router->SetRoute('forumdisplay\\.php\\?f=(\\d+)', 'categories/$1', 'Permanent'); $Router->SetRoute('archive\\.php/f-(\\d+)\\.html', 'categories/$1', 'Permanent'); // Discussions & Comments $Router->SetRoute('showthread\\.php\\?t=(\\d+)', 'discussion/$1', 'Permanent'); //$Router->SetRoute('showthread\.php\?p=(\d+)', 'discussion/comment/$1#Comment_$1', 'Permanent'); //$Router->SetRoute('showpost\.php\?p=(\d+)', 'discussion/comment/$1#Comment_$1', 'Permanent'); $Router->SetRoute('archive\\.php/t-(\\d+)\\.html', 'discussion/$1', 'Permanent'); // Profiles $Router->SetRoute('member\\.php\\?u=(\\d+)', 'profile/$1/x', 'Permanent'); $Router->SetRoute('usercp\\.php', 'profile', 'Permanent'); $Router->SetRoute('profile\\.php', 'profile', 'Permanent'); // Other $Router->SetRoute('attachment\\.php\\?attachmentid=(\\d+)', 'discussion/download/$1', 'Permanent'); $Router->SetRoute('search\\.php', 'discussions', 'Permanent'); $Router->SetRoute('private\\.php', 'messages/all', 'Permanent'); $Router->SetRoute('subscription\\.php', 'discussions/bookmarked', 'Permanent'); // Make different sizes of avatars $this->ProcessAvatars(); // Prep config for ProfileExtender plugin based on imported fields $this->ProfileExtenderPrep(); // Set guests to System user to prevent security issues $SystemUserID = Gdn::userModel()->GetSystemUserID(); $this->SQL->update('Discussion')->set('InsertUserID', $SystemUserID)->where('InsertUserID', 0)->put(); $this->SQL->update('Comment')->set('InsertUserID', $SystemUserID)->where('InsertUserID', 0)->put(); }
/** * Custom finalization. */ public function afterImport() { // Set up the routes to redirect from their older counterparts. $Router = Gdn::router(); $Router->SetRoute('\\?CategoryID=(\\d+)(?:&page=(\\d+))?', 'categories/$1/p$2', 'Permanent'); $Router->SetRoute('\\?page=(\\d+)', 'discussions/p$1', 'Permanent'); $Router->SetRoute('comments\\.php\\?DiscussionID=(\\d+)', 'discussion/$1/x', 'Permanent'); $Router->SetRoute('comments\\.php\\?DiscussionID=(\\d+)&page=(\\d+)', 'discussion/$1/x/p$2', 'Permanent'); $Router->SetRoute('account\\.php\\?u=(\\d+)', 'dashboard/profile/$1/x', 'Permanent'); }
<?php echo $this->Form->open(); echo $this->Form->errors(); ?> <ul> <li> <?php echo $this->Form->label('Route Expression', 'Route'); $Attributes = array('class' => 'InputBox WideInput'); if ($this->Route['Reserved']) { //$Attributes['value'] = $this->Route; $Attributes['disabled'] = 'disabled'; } echo $this->Form->textBox('Route', $Attributes); ?> </li> <li> <?php echo $this->Form->label('Target', 'Target'); echo $this->Form->textBox('Target', array('class' => 'InputBox WideInput')); ?> </li> <li> <?php echo $this->Form->label('Type', 'Route Type'); echo $this->Form->dropDown('Type', Gdn::router()->getRouteTypes()); ?> </li> </ul> <?php echo $this->Form->close('Save');
public function withRoute($Route) { $ParsedURI = Gdn::router()->getDestination($Route); if ($ParsedURI) { $this->_environmentElement('URI', $ParsedURI); } return $this; }
/** * Go to requested Target() or the default controller if none was set. * * @access public * @since 2.0.0 * * @return string URL. */ public function redirectTo() { $Target = $this->target(); return $Target == '' ? Gdn::router()->getDestination('DefaultController') : $Target; }
/** * Homepage management screen. * * @since 2.0.0 * @access public */ public function homepage() { $this->permission('Garden.Settings.Manage'); // Page setup $this->addSideMenu('dashboard/settings/homepage'); $this->title(t('Homepage')); $CurrentRoute = val('Destination', Gdn::router()->getRoute('DefaultController'), ''); $this->setData('CurrentTarget', $CurrentRoute); if (!$this->Form->authenticatedPostBack()) { $this->Form->setData(array('Target' => $CurrentRoute)); } else { $NewRoute = val('Target', $this->Form->formValues(), ''); Gdn::router()->deleteRoute('DefaultController'); Gdn::router()->setRoute('DefaultController', $NewRoute, 'Internal'); $this->setData('CurrentTarget', $NewRoute); // Save the preferred layout setting saveToConfig(array('Vanilla.Discussions.Layout' => val('DiscussionsLayout', $this->Form->formValues(), ''), 'Vanilla.Categories.Layout' => val('CategoriesLayout', $this->Form->formValues(), ''))); $this->informMessage(t("Your changes were saved successfully.")); } $this->render(); }
/** * Default all discussions view: chronological by most recent comment. * * @since 2.0.0 * @access public * * @param int $Page Multiplied by PerPage option to determine offset. */ public function index($Page = false) { // Figure out which discussions layout to choose (Defined on "Homepage" settings page). $Layout = c('Vanilla.Discussions.Layout'); switch ($Layout) { case 'table': if ($this->SyndicationMethod == SYNDICATION_NONE) { $this->View = 'table'; } break; default: // $this->View = 'index'; break; } Gdn_Theme::section('DiscussionList'); // Check for the feed keyword. if ($Page === 'feed' && $this->SyndicationMethod != SYNDICATION_NONE) { $Page = 'p1'; } // Determine offset from $Page list($Offset, $Limit) = offsetLimit($Page, c('Vanilla.Discussions.PerPage', 30), true); $Page = PageNumber($Offset, $Limit); // Allow page manipulation $this->EventArguments['Page'] =& $Page; $this->EventArguments['Offset'] =& $Offset; $this->EventArguments['Limit'] =& $Limit; $this->fireEvent('AfterPageCalculation'); // Set canonical URL $this->canonicalUrl(url(ConcatSep('/', 'discussions', PageNumber($Offset, $Limit, true, false)), true)); // We want to limit the number of pages on large databases because requesting a super-high page can kill the db. $MaxPages = c('Vanilla.Discussions.MaxPages'); if ($MaxPages && $Page > $MaxPages) { throw notFoundException(); } // Setup head. if (!$this->data('Title')) { $Title = c('Garden.HomepageTitle'); $DefaultControllerRoute = val('Destination', Gdn::router()->GetRoute('DefaultController')); if ($Title && $DefaultControllerRoute == 'discussions') { $this->title($Title, ''); } else { $this->title(t('Recent Discussions')); } } if (!$this->Description()) { $this->Description(c('Garden.Description', null)); } if ($this->Head) { $this->Head->AddRss(url('/discussions/feed.rss', true), $this->Head->title()); } // Add modules $this->addModule('DiscussionFilterModule'); $this->addModule('NewDiscussionModule'); $this->addModule('CategoriesModule'); $this->addModule('BookmarkedModule'); $this->setData('Breadcrumbs', array(array('Name' => t('Recent Discussions'), 'Url' => '/discussions'))); // Set criteria & get discussions data $this->setData('Category', false, true); $DiscussionModel = new DiscussionModel(); // Check for individual categories. $categoryIDs = $this->getCategoryIDs(); $where = array(); if ($categoryIDs) { $where['d.CategoryID'] = CategoryModel::filterCategoryPermissions($categoryIDs); } else { $DiscussionModel->Watching = true; } // Get Discussion Count $CountDiscussions = $DiscussionModel->getCount($where); if ($MaxPages) { $CountDiscussions = min($MaxPages * $Limit, $CountDiscussions); } $this->setData('CountDiscussions', $CountDiscussions); // Get Announcements $this->AnnounceData = $Offset == 0 ? $DiscussionModel->GetAnnouncements($where) : false; $this->setData('Announcements', $this->AnnounceData !== false ? $this->AnnounceData : array(), true); // Get Discussions $this->DiscussionData = $DiscussionModel->getWhere($where, $Offset, $Limit); $this->setData('Discussions', $this->DiscussionData, true); $this->setJson('Loading', $Offset . ' to ' . $Limit); // Build a pager $PagerFactory = new Gdn_PagerFactory(); $this->EventArguments['PagerType'] = 'Pager'; $this->fireEvent('BeforeBuildPager'); if (!$this->data('_PagerUrl')) { $this->setData('_PagerUrl', 'discussions/{Page}'); } $this->Pager = $PagerFactory->GetPager($this->EventArguments['PagerType'], $this); $this->Pager->ClientID = 'Pager'; $this->Pager->configure($Offset, $Limit, $this->data('CountDiscussions'), $this->data('_PagerUrl')); PagerModule::Current($this->Pager); $this->setData('_Page', $Page); $this->setData('_Limit', $Limit); $this->fireEvent('AfterBuildPager'); // Deliver JSON data if necessary if ($this->_DeliveryType != DELIVERY_TYPE_ALL) { $this->setJson('LessRow', $this->Pager->toString('less')); $this->setJson('MoreRow', $this->Pager->toString('more')); $this->View = 'discussions'; } $this->render(); }
/** * Get the URL of a given type. * * @param string $URLType * @param string $Redirect * @return bool|mixed|string */ protected function _getURL($URLType, $Redirect) { $SessionAuthenticator = Gdn::session()->getPreference('Authenticator'); $AuthenticationScheme = $SessionAuthenticator ? $SessionAuthenticator : 'default'; try { $Authenticator = $this->getAuthenticator($AuthenticationScheme); } catch (Exception $e) { $Authenticator = $this->getAuthenticator(); } if (!is_null($Redirect) && ($Redirect == '' || $Redirect == '/')) { $Redirect = Gdn::router()->getDestination('DefaultController'); } if (is_null($Redirect)) { $Redirect = ''; } // Ask the authenticator for this URLType $Return = $Authenticator->getURL($URLType); // If it doesn't know, get the default from our config file if (!$Return) { $Return = c('Garden.Authenticator.' . $URLType, false); } if (!$Return) { return false; } $ExtraReplacementParameters = array('Path' => $Redirect, 'Scheme' => $AuthenticationScheme); // Extended return type, allows provider values to be replaced into final URL if (is_array($Return)) { $ExtraReplacementParameters = array_merge($ExtraReplacementParameters, $Return['Parameters']); $Return = $Return['URL']; } $FullRedirect = $Redirect != '' ? Url($Redirect, true) : ''; $ExtraReplacementParameters['Redirect'] = $FullRedirect; $ExtraReplacementParameters['CurrentPage'] = $FullRedirect; // Support legacy sprintf syntax $Return = sprintf($Return, $AuthenticationScheme, urlencode($Redirect), $FullRedirect); // Support new named parameter '{}' syntax $Return = $this->replaceAuthPlaceholders($Return, $ExtraReplacementParameters); if ($this->protocol() == 'https') { $Return = str_replace('http:', 'https:', Url($Return, true)); } return $Return; }
/** * Show list of current routes. * * @since 2.0.0 * @access public */ public function index() { $this->permission('Garden.Settings.Manage'); $this->setHighlightRoute('dashboard/routes'); $this->title(t('Routes')); $this->MyRoutes = Gdn::router()->Routes; $this->render(); }
/** * @param SiteLinkMenuModule $sender */ public function siteNavModule_default_handler($sender) { // Grab the default route so that we don't add a link to it twice. $home = trim(val('Destination', Gdn::router()->GetRoute('DefaultController')), '/'); // Add the site discussion links. if ($home !== 'categories') { $sender->addLink('main.categories', array('text' => t('All Categories', 'Categories'), 'url' => '/categories', 'icon' => icon('th-list'), 'sort' => 1)); } if ($home !== 'discussions') { $sender->addLink('main.discussions', array('text' => t('Recent Discussions'), 'url' => '/discussions', 'icon' => icon('discussion'), 'sort' => 1)); } // Add favorites. $sender->addGroup('favorites', array('text' => t('Favorites'))); if (Gdn::session()->isValid()) { $sender->addLink('favorites.bookmarks', array('text' => t('My Bookmarks'), 'url' => '/discussions/bookmarked', 'icon' => icon('star'), 'badge' => countString(Gdn::session()->User->CountBookmarks, url('/discussions/userbookmarkcount')))); $sender->addLink('favorites.discussions', array('text' => t('My Discussions'), 'url' => '/discussions/mine', 'icon' => icon('discussion'), 'badge' => countString(Gdn::session()->User->CountDiscussions))); $sender->addLink('favorites.drafts', array('text' => t('Drafts'), 'url' => '/drafts', 'icon' => icon('compose'), 'badge' => countString(Gdn::session()->User->CountDrafts))); } }
/** * Parses the query string looking for supplied request parameters. Places * anything useful into this object's Controller properties. * * @param int $FolderDepth */ protected function analyzeRequest(&$Request) { // Here is the basic format of a request: // [/application]/controller[/method[.json|.xml]]/argn|argn=valn // Here are some examples of what this method could/would receive: // /application/controller/method/argn // /controller/method/argn // /application/controller/argn // /controller/argn // /controller // Clear the slate $this->_ApplicationFolder = ''; $this->ControllerName = ''; $this->ControllerMethod = 'index'; $this->_ControllerMethodArgs = array(); $this->Request = $Request->path(false); $PathAndQuery = $Request->PathAndQuery(); $MatchRoute = Gdn::router()->matchRoute($PathAndQuery); // We have a route. Take action. if ($MatchRoute !== false) { switch ($MatchRoute['Type']) { case 'Internal': $Request->pathAndQuery($MatchRoute['FinalDestination']); $this->Request = $Request->path(false); break; case 'Temporary': safeHeader("HTTP/1.1 302 Moved Temporarily"); safeHeader("Location: " . Url($MatchRoute['FinalDestination'])); exit; break; case 'Permanent': safeHeader("HTTP/1.1 301 Moved Permanently"); safeHeader("Location: " . Url($MatchRoute['FinalDestination'])); exit; break; case 'NotAuthorized': safeHeader("HTTP/1.1 401 Not Authorized"); $this->Request = $MatchRoute['FinalDestination']; break; case 'NotFound': safeHeader("HTTP/1.1 404 Not Found"); $this->Request = $MatchRoute['FinalDestination']; break; case 'Test': $Request->pathAndQuery($MatchRoute['FinalDestination']); $this->Request = $Request->path(false); decho($MatchRoute, 'Route'); decho(array('Path' => $Request->path(), 'Get' => $Request->get()), 'Request'); die; } } switch ($Request->outputFormat()) { case 'rss': $this->_SyndicationMethod = SYNDICATION_RSS; $this->_DeliveryMethod = DELIVERY_METHOD_RSS; break; case 'atom': $this->_SyndicationMethod = SYNDICATION_ATOM; $this->_DeliveryMethod = DELIVERY_METHOD_RSS; break; case 'default': default: $this->_SyndicationMethod = SYNDICATION_NONE; break; } if ($this->Request == '') { $DefaultController = Gdn::router()->getRoute('DefaultController'); $this->Request = $DefaultController['Destination']; } $Parts = explode('/', str_replace('\\', '/', $this->Request)); /** * The application folder is either the first argument or is not provided. The controller is therefore * either the second argument or the first, depending on the result of the previous statement. Check that. */ try { // if the 1st argument is a valid application, check if it has a controller matching the 2nd argument if (in_array($Parts[0], $this->enabledApplicationFolders())) { $this->findController(1, $Parts); } // if no match, see if the first argument is a controller $this->findController(0, $Parts); // 3] See if there is a plugin trying to create a root method. list($MethodName, $DeliveryMethod) = $this->_splitDeliveryMethod(GetValue(0, $Parts), true); if ($MethodName && Gdn::pluginManager()->hasNewMethod('RootController', $MethodName, true)) { $this->_DeliveryMethod = $DeliveryMethod; $Parts[0] = $MethodName; $Parts = array_merge(array('root'), $Parts); $this->findController(0, $Parts); } throw new GdnDispatcherControllerNotFoundException(); } catch (GdnDispatcherControllerFoundException $e) { switch ($this->_DeliveryMethod) { case DELIVERY_METHOD_JSON: case DELIVERY_METHOD_XML: $this->_DeliveryType = DELIVERY_TYPE_DATA; break; case DELIVERY_METHOD_TEXT: $this->_DeliveryType = DELIVERY_TYPE_VIEW; break; case DELIVERY_METHOD_XHTML: case DELIVERY_METHOD_RSS: break; default: $this->_DeliveryMethod = DELIVERY_METHOD_XHTML; break; } return true; } catch (GdnDispatcherControllerNotFoundException $e) { $this->EventArguments['Handled'] = false; $Handled =& $this->EventArguments['Handled']; $this->fireEvent('NotFound'); if (!$Handled) { safeHeader("HTTP/1.1 404 Not Found"); $Request->withRoute('Default404'); return $this->analyzeRequest($Request); } } }
?> </th> <th class="Alt"><?php echo t('Type'); ?> </th> </tr> </thead> <tbody> <?php $i = 0; $Alt = FALSE; foreach ($this->MyRoutes as $Route => $RouteData) { $Alt = !$Alt; $Target = $RouteData['Destination']; $RouteType = t(Gdn::router()->RouteTypes[$RouteData['Type']]); $Reserved = $RouteData['Reserved']; ?> <tr<?php echo $Alt ? ' class="Alt"' : ''; ?> > <td class="Info"> <strong><?php echo $Route; ?> </strong> <div> <?php echo anchor(t('Edit'), '/dashboard/routes/edit/' . trim($RouteData['Key'], '='), 'EditRoute SmallButton');
/** * Rewrite the request based on rewrite rules (currently called routes in Vanilla). * * This method modifies the passed {@link $request} object. It can also cause a redirect if a rule matches that * specifies a redirect. * * @param Gdn_Request $request The request to rewrite. */ private function rewriteRequest($request) { $pathAndQuery = $request->PathAndQuery(); $matchRoute = Gdn::router()->matchRoute($pathAndQuery); // We have a route. Take action. if (!empty($matchRoute)) { $dest = $matchRoute['FinalDestination']; if (strpos($dest, '?') === false) { // The rewrite rule doesn't include a query string so keep the current one intact. $request->path($dest); } else { // The rewrite rule has a query string so rewrite that too. $request->pathAndQuery($dest); } switch ($matchRoute['Type']) { case 'Internal': // Do nothing. The request has been rewritten. break; case 'Temporary': safeHeader("HTTP/1.1 302 Moved Temporarily"); safeHeader("Location: " . url($matchRoute['FinalDestination'])); exit; break; case 'Permanent': safeHeader("HTTP/1.1 301 Moved Permanently"); safeHeader("Location: " . url($matchRoute['FinalDestination'])); exit; break; case 'NotAuthorized': safeHeader("HTTP/1.1 401 Not Authorized"); break; case 'NotFound': safeHeader("HTTP/1.1 404 Not Found"); break; case 'Drop': die; case 'Test': decho($matchRoute, 'Route'); decho(array('Path' => $request->path(), 'Get' => $request->get()), 'Request'); die; } } elseif (in_array($request->path(), ['', '/'])) { $this->isHomepage = true; $defaultController = Gdn::router()->getRoute('DefaultController'); $request->pathAndQuery($defaultController['Destination']); } return $request; }
public function onDisable() { Gdn::router()->deleteRoute('^@(.*)'); }
/** * Render the entire head module. */ public function toString() { // Add the canonical Url if necessary. if (method_exists($this->_Sender, 'CanonicalUrl') && !c('Garden.Modules.NoCanonicalUrl', false)) { $CanonicalUrl = $this->_Sender->canonicalUrl(); if (!isUrl($CanonicalUrl)) { $CanonicalUrl = Gdn::router()->ReverseRoute($CanonicalUrl); } $this->_Sender->canonicalUrl($CanonicalUrl); // $CurrentUrl = url('', true); // if ($CurrentUrl != $CanonicalUrl) { $this->addTag('link', array('rel' => 'canonical', 'href' => $CanonicalUrl)); // } } // Include facebook open-graph meta information. if ($FbAppID = c('Plugins.Facebook.ApplicationID')) { $this->addTag('meta', array('property' => 'fb:app_id', 'content' => $FbAppID)); } $SiteName = c('Garden.Title', ''); if ($SiteName != '') { $this->addTag('meta', array('property' => 'og:site_name', 'content' => $SiteName)); } $Title = Gdn_Format::text($this->title('', true)); if ($Title != '') { $this->addTag('meta', array('property' => 'og:title', 'itemprop' => 'name', 'content' => $Title)); } if (isset($CanonicalUrl)) { $this->addTag('meta', array('property' => 'og:url', 'content' => $CanonicalUrl)); } if ($Description = $this->_Sender->Description()) { $this->addTag('meta', array('name' => 'description', 'property' => 'og:description', 'itemprop' => 'description', 'content' => $Description)); } // Default to the site logo if there were no images provided by the controller. if (count($this->_Sender->Image()) == 0) { $Logo = c('Garden.ShareImage', c('Garden.Logo', '')); if ($Logo != '') { // Fix the logo path. if (stringBeginsWith($Logo, 'uploads/')) { $Logo = substr($Logo, strlen('uploads/')); } $Logo = Gdn_Upload::url($Logo); $this->addTag('meta', array('property' => 'og:image', 'itemprop' => 'image', 'content' => $Logo)); } } else { foreach ($this->_Sender->Image() as $Img) { $this->addTag('meta', array('property' => 'og:image', 'itemprop' => 'image', 'content' => $Img)); } } $this->fireEvent('BeforeToString'); $Tags = $this->_Tags; // Make sure that css loads before js (for jquery) usort($this->_Tags, array('HeadModule', 'TagCmp')); // "link" comes before "script" $Tags2 = $this->_Tags; // Start with the title. $Head = '<title>' . Gdn_Format::text($this->title()) . "</title>\n"; $TagStrings = array(); // Loop through each tag. foreach ($this->_Tags as $Index => $Attributes) { $Tag = $Attributes[self::TAG_KEY]; // Inline the content of the tag, if necessary. if (val('_hint', $Attributes) == 'inline') { $Path = val('_path', $Attributes); if (!stringBeginsWith($Path, 'http')) { $Attributes[self::CONTENT_KEY] = file_get_contents($Path); if (isset($Attributes['src'])) { $Attributes['_src'] = $Attributes['src']; unset($Attributes['src']); } if (isset($Attributes['href'])) { $Attributes['_href'] = $Attributes['href']; unset($Attributes['href']); } } } // If we set an IE conditional AND a "Not IE" condition, we will need to make a second pass. do { // Reset tag string $TagString = ''; // IE conditional? Validates condition. $IESpecific = isset($Attributes['_ie']) && preg_match('/((l|g)t(e)? )?IE [0-9\\.]/', $Attributes['_ie']); // Only allow $NotIE if we're not doing a conditional this loop. $NotIE = !$IESpecific && isset($Attributes['_notie']); // Open IE conditional tag if ($IESpecific) { $TagString .= '<!--[if ' . $Attributes['_ie'] . ']>'; } if ($NotIE) { $TagString .= '<!--[if !IE]> -->'; } // Build tag $TagString .= ' <' . $Tag . Attribute($Attributes, '_'); if (array_key_exists(self::CONTENT_KEY, $Attributes)) { $TagString .= '>' . $Attributes[self::CONTENT_KEY] . '</' . $Tag . '>'; } elseif ($Tag == 'script') { $TagString .= '></script>'; } else { $TagString .= ' />'; } // Close IE conditional tag if ($IESpecific) { $TagString .= '<![endif]-->'; } if ($NotIE) { $TagString .= '<!-- <![endif]-->'; } // Cleanup (prevent infinite loop) if ($IESpecific) { unset($Attributes['_ie']); } $TagStrings[] = $TagString; } while ($IESpecific && isset($Attributes['_notie'])); // We need a second pass } //endforeach $Head .= implode("\n", array_unique($TagStrings)); foreach ($this->_Strings as $String) { $Head .= $String; $Head .= "\n"; } return $Head; }
/** * Show list of current routes. * * @since 2.0.0 * @access public */ public function index() { $this->permission('Garden.Settings.Manage'); $this->addSideMenu('dashboard/routes'); $this->addJsFile('routes.js'); $this->title(t('Routes')); $this->MyRoutes = Gdn::router()->Routes; $this->render(); }
/** * * * @param $Path * @param bool $Text * @param null $Format * @param array $Options * @return mixed|null|string */ public static function link($Path, $Text = false, $Format = null, $Options = array()) { $Session = Gdn::session(); $Class = val('class', $Options, ''); $WithDomain = val('WithDomain', $Options); $Target = val('Target', $Options, ''); if ($Target == 'current') { $Target = trim(url('', true), '/ '); } if (is_null($Format)) { $Format = '<a href="%url" class="%class">%text</a>'; } switch ($Path) { case 'activity': touchValue('Permissions', $Options, 'Garden.Activity.View'); break; case 'category': $Breadcrumbs = Gdn::controller()->data('Breadcrumbs'); if (is_array($Breadcrumbs) && count($Breadcrumbs) > 0) { $Last = array_pop($Breadcrumbs); $Path = val('Url', $Last); $DefaultText = val('Name', $Last, T('Back')); } else { $Path = '/'; $DefaultText = c('Garden.Title', T('Back')); } if (!$Text) { $Text = $DefaultText; } break; case 'dashboard': $Path = 'dashboard/settings'; touchValue('Permissions', $Options, array('Garden.Settings.Manage', 'Garden.Settings.View')); if (!$Text) { $Text = t('Dashboard'); } break; case 'home': $Path = '/'; if (!$Text) { $Text = t('Home'); } break; case 'inbox': $Path = 'messages/inbox'; touchValue('Permissions', $Options, 'Garden.SignIn.Allow'); if (!$Text) { $Text = t('Inbox'); } if ($Session->isValid() && $Session->User->CountUnreadConversations) { $Class = trim($Class . ' HasCount'); $Text .= ' <span class="Alert">' . $Session->User->CountUnreadConversations . '</span>'; } if (!$Session->isValid() || !Gdn::applicationManager()->checkApplication('Conversations')) { $Text = false; } break; case 'forumroot': $Route = Gdn::router()->getDestination('DefaultForumRoot'); if (is_null($Route)) { $Path = '/'; } else { $Path = combinePaths(array('/', $Route)); } break; case 'profile': touchValue('Permissions', $Options, 'Garden.SignIn.Allow'); if (!$Text && $Session->isValid()) { $Text = $Session->User->Name; } if ($Session->isValid() && $Session->User->CountNotifications) { $Class = trim($Class . ' HasCount'); $Text .= ' <span class="Alert">' . $Session->User->CountNotifications . '</span>'; } break; case 'user': $Path = 'profile'; touchValue('Permissions', $Options, 'Garden.SignIn.Allow'); if (!$Text && $Session->isValid()) { $Text = $Session->User->Name; } break; case 'photo': $Path = 'profile'; TouchValue('Permissions', $Options, 'Garden.SignIn.Allow'); if (!$Text && $Session->isValid()) { $IsFullPath = strtolower(substr($Session->User->Photo, 0, 7)) == 'http://' || strtolower(substr($Session->User->Photo, 0, 8)) == 'https://'; $PhotoUrl = $IsFullPath ? $Session->User->Photo : Gdn_Upload::url(changeBasename($Session->User->Photo, 'n%s')); $Text = img($PhotoUrl, array('alt' => $Session->User->Name)); } break; case 'drafts': TouchValue('Permissions', $Options, 'Garden.SignIn.Allow'); if (!$Text) { $Text = t('My Drafts'); } if ($Session->isValid() && $Session->User->CountDrafts) { $Class = trim($Class . ' HasCount'); $Text .= ' <span class="Alert">' . $Session->User->CountDrafts . '</span>'; } break; case 'discussions/bookmarked': TouchValue('Permissions', $Options, 'Garden.SignIn.Allow'); if (!$Text) { $Text = t('My Bookmarks'); } if ($Session->isValid() && $Session->User->CountBookmarks) { $Class = trim($Class . ' HasCount'); $Text .= ' <span class="Count">' . $Session->User->CountBookmarks . '</span>'; } break; case 'discussions/mine': TouchValue('Permissions', $Options, 'Garden.SignIn.Allow'); if (!$Text) { $Text = t('My Discussions'); } if ($Session->isValid() && $Session->User->CountDiscussions) { $Class = trim($Class . ' HasCount'); $Text .= ' <span class="Count">' . $Session->User->CountDiscussions . '</span>'; } break; case 'register': if (!$Text) { $Text = t('Register'); } $Path = registerUrl($Target); break; case 'signin': case 'signinout': // The destination is the signin/signout toggle link. if ($Session->isValid()) { if (!$Text) { $Text = T('Sign Out'); } $Path = signOutUrl($Target); $Class = concatSep(' ', $Class, 'SignOut'); } else { if (!$Text) { $Text = t('Sign In'); } $Path = signInUrl($Target); if (signInPopup() && strpos(Gdn::Request()->Url(), 'entry') === false) { $Class = concatSep(' ', $Class, 'SignInPopup'); } } break; } if ($Text == false && strpos($Format, '%text') !== false) { return ''; } if (val('Permissions', $Options) && !$Session->checkPermission($Options['Permissions'], false)) { return ''; } $Url = Gdn::request()->url($Path, $WithDomain); if ($TK = val('TK', $Options)) { if (in_array($TK, array(1, 'true'))) { $TK = 'TransientKey'; } $Url .= (strpos($Url, '?') === false ? '?' : '&') . $TK . '=' . urlencode(Gdn::session()->transientKey()); } if (strcasecmp(trim($Path, '/'), Gdn::request()->path()) == 0) { $Class = concatSep(' ', $Class, 'Selected'); } // Build the final result. $Result = $Format; $Result = str_replace('%url', $Url, $Result); $Result = str_replace('%text', $Text, $Result); $Result = str_replace('%class', $Class, $Result); return $Result; }
/** * @param NavModule $sender */ public function siteNavModule_init_handler($sender) { // Grab the default route so that we don't add a link to it twice. $home = trim(val('Destination', Gdn::router()->getRoute('DefaultController')), '/'); // Add the site discussion links. $sender->addLinkIf($home !== 'categories', t('All Categories', 'Categories'), '/categories', 'main.categories', '', 1, array('icon' => 'th-list')); $sender->addLinkIf($home !== 'discussions', t('Recent Discussions'), '/discussions', 'main.discussions', '', 1, array('icon' => 'discussion')); $sender->addGroup(t('Favorites'), 'favorites', '', 3); if (Gdn::session()->isValid()) { $sender->addLink(t('My Bookmarks'), '/discussions/bookmarked', 'favorites.bookmarks', '', array(), array('icon' => 'star', 'badge' => Gdn::session()->User->CountBookmarks)); $sender->addLink(t('My Discussions'), '/discussions/mine', 'favorites.discussions', '', array(), array('icon' => 'discussion', 'badge' => Gdn::session()->User->CountDiscussions)); $sender->addLink(t('Drafts'), '/drafts', 'favorites.drafts', '', array(), array('icon' => 'compose', 'badge' => Gdn::session()->User->CountDrafts)); } $user = Gdn::controller()->data('Profile'); if (!$user) { return; } $sender->addGroupToSection('Profile', t('Posts'), 'posts'); $sender->addLinkToSection('Profile', t('Discussions'), userUrl($user, '', 'discussions'), 'posts.discussions', '', array(), array('icon' => 'discussion', 'badge' => val('CountDiscussions', $user))); $sender->addLinkToSection('Profile', t('Comments'), userUrl($user, '', 'comments'), 'posts.comments', '', array(), array('icon' => 'comment', 'badge' => val('CountComments', $user))); }