/** * Includes a file in template. Handy for adding html files to tpl files * * @param array The parameters passed into the function. * The parameters that can be passed to this function are as follows. * - <b>name</b>: The name of the file. * @param Smarty The smarty object rendering the template. * @return The rendered asset. */ function smarty_function_include_file($Params, &$Smarty) { $Name = ltrim(ArrayValue('name', $Params), '/'); if (strpos($Name, '..') !== false) { return '<!-- Error, moving up directory path not allowed -->'; } if (IsUrl($Name)) { return '<!-- Error, urls are not allowed -->'; } $filename = rtrim($Smarty->template_dir, '/') . '/' . $Name; if (!file_exists($filename)) { return '<!-- Error, file does not exist -->'; } return file_get_contents($filename); }
<?php if (!defined('APPLICATION')) { exit; } $User = val('User', Gdn::controller()); if (!$User && Gdn::session()->isValid()) { $User = Gdn::session()->User; } if (!$User) { return; } $Photo = $User->Photo; if ($Photo) { if (!IsUrl($Photo)) { $Photo = Gdn_Upload::url(changeBasename($Photo, 'p%s')); } } else { $Photo = UserModel::getDefaultAvatarUrl($User, 'profile'); } if ($User->Banned) { $BannedPhoto = c('Garden.BannedPhoto', 'https://c3409409.ssl.cf0.rackcdn.com/images/banned_large.png'); if ($BannedPhoto) { $Photo = Gdn_Upload::url($BannedPhoto); } } if ($Photo) { ?> <div class="Photo PhotoWrap PhotoWrapLarge <?php echo val('_CssClass', $User); ?>
public static function CssPath($ThemeType, $Filename, $Folder) { if (!$ThemeType) { $ThemeType = IsMobile() ? 'mobile' : 'desktop'; } // 1. Check for a url. if (IsUrl($Filename)) { return array($Filename, $Filename); } // 2. Check for a full path. if (strpos($Filename, '/') !== FALSE) { $Filename = '/' . ltrim($Filename, '/'); $Path = PATH_ROOT . $Filename; if (file_exists($Path)) { return array($Path, $Filename); } else { return FALSE; } } // 3. Check the theme. if ($Theme = Gdn::ThemeManager()->ThemeFromType($ThemeType)) { $Paths[] = array(PATH_THEMES . "/{$Theme}/design/{$Filename}", "/themes/{$Theme}/design/{$Filename}"); } if ($Folder) { // 4. Check static, a plugin or application. if (in_array($Folder, array('resources', 'static'))) { $path = "/resources/css/{$Filename}"; $Paths[] = array(PATH_ROOT . $path, $path); } elseif (StringBeginsWith($Folder, 'plugins/')) { $Folder = substr($Folder, strlen('plugins/')); $Paths[] = array(PATH_PLUGINS . "/{$Folder}/design/{$Filename}", "/plugins/{$Folder}/design/{$Filename}"); $Paths[] = array(PATH_PLUGINS . "/{$Folder}/{$Filename}", "/plugins/{$Folder}/{$Filename}"); } else { $Paths[] = array(PATH_APPLICATIONS . "/{$Folder}/design/{$Filename}", "/applications/{$Folder}/design/{$Filename}"); } } // 5. Check the default. if ($Folder != 'dashboard') { $Paths[] = array(PATH_APPLICATIONS . '/dashboard/design/$Filename', "/applications/dashboard/design/{$Filename}"); } foreach ($Paths as $Info) { if (file_exists($Info[0])) { return $Info; } } return FALSE; }
/** * @param SideMenuModule $Module * @param string $CurrentUrl */ public function BuildEditMenu(&$Module, $CurrentUrl = '') { if (!$this->User) { return; } $Module->HtmlId = 'UserOptions'; $Module->AutoLinkGroups = FALSE; $Session = Gdn::Session(); $ViewingUserID = $Session->UserID; $Module->AddItem('Options', '', FALSE, array('class' => 'SideMenu')); // Check that we have the necessary tools to allow image uploading $AllowImages = C('Garden.Profile.EditPhotos', TRUE) && Gdn_UploadImage::CanUploadImages(); // Is the photo hosted remotely? $RemotePhoto = IsUrl($this->User->Photo); if ($this->User->UserID != $ViewingUserID) { // Include user js files for people with edit users permissions if (CheckPermission('Garden.Users.Edit') || CheckPermission('Moderation.Profiles.Edit')) { // $this->AddJsFile('jquery.gardenmorepager.js'); $this->AddJsFile('user.js'); } $Module->AddLink('Options', Sprite('SpProfile') . ' ' . T('Edit Profile'), UserUrl($this->User, '', 'edit'), array('Garden.Users.Edit', 'Moderation.Profiles.Edit'), array('class' => 'Popup EditAccountLink')); $Module->AddLink('Options', Sprite('SpProfile') . ' ' . T('Edit Account'), '/user/edit/' . $this->User->UserID, 'Garden.Users.Edit', array('class' => 'Popup EditAccountLink')); $Module->AddLink('Options', Sprite('SpDelete') . ' ' . T('Delete Account'), '/user/delete/' . $this->User->UserID, 'Garden.Users.Delete', array('class' => 'Popup DeleteAccountLink')); if ($this->User->Photo != '' && $AllowImages) { $Module->AddLink('Options', Sprite('SpDelete') . ' ' . T('Remove Picture'), CombinePaths(array(UserUrl($this->User, '', 'removepicture'), $Session->TransientKey())), array('Garden.Users.Edit', 'Moderation.Profiles.Edit'), array('class' => 'RemovePictureLink')); } $Module->AddLink('Options', Sprite('SpPreferences') . ' ' . T('Edit Preferences'), UserUrl($this->User, '', 'preferences'), array('Garden.Users.Edit', 'Moderation.Profiles.Edit'), array('class' => 'Popup PreferencesLink')); // Add profile options for everyone $Module->AddLink('Options', Sprite('SpPicture') . ' ' . T('Change Picture'), UserUrl($this->User, '', 'picture'), array('Garden.Users.Edit', 'Moderation.Profiles.Edit'), array('class' => 'PictureLink')); if ($this->User->Photo != '' && $AllowImages && !$RemotePhoto) { $Module->AddLink('Options', Sprite('SpThumbnail') . ' ' . T('Edit Thumbnail'), UserUrl($this->User, '', 'thumbnail'), array('Garden.Users.Edit', 'Moderation.Profiles.Edit'), array('class' => 'ThumbnailLink')); } } else { // Add profile options for the profile owner // Don't allow account editing if it has been turned off. // Don't allow password editing if using SSO Connect ONLY. // This is for security. We encountered the case where a customer charges // for membership using their external application and use SSO to let // their customers into Vanilla. If you allow those people to change their // password in Vanilla, they will then be able to log into Vanilla using // Vanilla's login form regardless of the state of their membership in the // external app. if (C('Garden.UserAccount.AllowEdit') && C('Garden.Registration.Method') != 'Connect') { $Module->AddLink('Options', Sprite('SpEdit') . ' ' . T('Edit Profile'), '/profile/edit', FALSE, array('class' => 'Popup EditAccountLink')); // No password may have been set if they have only signed in with a connect plugin $PasswordLabel = T('Change My Password'); if ($this->User->HashMethod && $this->User->HashMethod != "Vanilla") { $PasswordLabel = T('Set A Password'); } $Module->AddLink('Options', Sprite('SpPassword') . ' ' . $PasswordLabel, '/profile/password', FALSE, array('class' => 'Popup PasswordLink')); } $Module->AddLink('Options', Sprite('SpPreferences') . ' ' . T('Notification Preferences'), UserUrl($this->User, '', 'preferences'), FALSE, array('class' => 'Popup PreferencesLink')); if ($AllowImages) { $Module->AddLink('Options', Sprite('SpPicture') . ' ' . T('Change My Picture'), '/profile/picture', array('Garden.Profiles.Edit', 'Garden.ProfilePicture.Edit'), array('class' => 'PictureLink')); } if ($this->User->Photo != '' && $AllowImages && !$RemotePhoto) { $Module->AddLink('Options', Sprite('SpThumbnail') . ' ' . T('Edit My Thumbnail'), '/profile/thumbnail', array('Garden.Profiles.Edit', 'Garden.ProfilePicture.Edit'), array('class' => 'ThumbnailLink')); } } if ($this->User->UserID == $ViewingUserID || $Session->CheckPermission('Garden.Users.Edit')) { $this->SetData('Connections', array()); $this->EventArguments['User'] = $this->User; $this->FireEvent('GetConnections'); if (count($this->Data('Connections')) > 0) { $Module->AddLink('Options', Sprite('SpConnection') . ' ' . T('Social'), '/profile/connections', 'Garden.SignIn.Allow'); } } }
public function SetCalculatedFields(&$User) { if ($v = GetValue('Attributes', $User)) { if (is_string($v)) { SetValue('Attributes', $User, @unserialize($v)); } } if ($v = GetValue('Permissions', $User)) { SetValue('Permissions', $User, @unserialize($v)); } if ($v = GetValue('Preferences', $User)) { SetValue('Preferences', $User, @unserialize($v)); } if ($v = GetValue('Photo', $User)) { if (!IsUrl($v)) { $PhotoUrl = Gdn_Upload::Url(ChangeBasename($v, 'n%s')); } else { $PhotoUrl = $v; } SetValue('PhotoUrl', $User, $PhotoUrl); } if ($v = GetValue('AllIPAddresses', $User)) { $IPAddresses = explode(',', $v); foreach ($IPAddresses as $i => $IPAddress) { $IPAddresses[$i] = ForceIPv4($IPAddress); } SetValue('AllIPAddresses', $User, $IPAddresses); } TouchValue('_CssClass', $User, ''); if ($v = GetValue('Banned', $User)) { SetValue('_CssClass', $User, 'Banned'); } $this->EventArguments['User'] =& $User; $this->FireEvent('SetCalculatedFields'); }
/** * Returns an img tag. */ function img($Image, $Attributes = '', $WithDomain = false) { if ($Attributes != '') { $Attributes = Attribute($Attributes); } if (preg_match('/^(.*)AvatarFirstLetter_(.+)$/', $Image, $matches)) { $name = $matches[2]; $firstLetter = substr($name, 0, 1); $rgb = AvatarFirstLetter::stringToColor($name); $Image = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVQI12NgYAAAAAMAASDVlMcAAAAASUVORK5CYII='; $output = '<span class="AvatarFirstLetter" style="background-color: ' . $rgb . ';">'; $output .= '<img src="' . $Image . '"' . $Attributes . ' />'; $output .= '<span>' . $firstLetter . '</span>'; $output .= '</span>'; return $output; } if (!IsUrl($Image)) { $Image = SmartAsset($Image, $WithDomain); } return '<img src="' . $Image . '"' . $Attributes . ' />'; }
/** * * * @param $Path * @param $Controller */ public function init($Path, $Controller) { $Smarty = $this->smarty(); // Get a friendly name for the controller. $ControllerName = get_class($Controller); if (StringEndsWith($ControllerName, 'Controller', true)) { $ControllerName = substr($ControllerName, 0, -10); } // Get an ID for the body. $BodyIdentifier = strtolower($Controller->ApplicationFolder . '_' . $ControllerName . '_' . Gdn_Format::alphaNumeric(strtolower($Controller->RequestMethod))); $Smarty->assign('BodyID', $BodyIdentifier); //$Smarty->assign('Config', Gdn::Config()); // Assign some information about the user. $Session = Gdn::session(); if ($Session->isValid()) { $User = array('Name' => $Session->User->Name, 'Photo' => '', 'CountNotifications' => (int) val('CountNotifications', $Session->User, 0), 'CountUnreadConversations' => (int) val('CountUnreadConversations', $Session->User, 0), 'SignedIn' => true); $Photo = $Session->User->Photo; if ($Photo) { if (!IsUrl($Photo)) { $Photo = Gdn_Upload::Url(ChangeBasename($Photo, 'n%s')); } } else { if (function_exists('UserPhotoDefaultUrl')) { $Photo = UserPhotoDefaultUrl($Session->User, 'ProfilePhoto'); } elseif ($ConfigPhoto = C('Garden.DefaultAvatar')) { $Photo = Gdn_Upload::url($ConfigPhoto); } else { $Photo = Asset('/applications/dashboard/design/images/defaulticon.png', true); } } $User['Photo'] = $Photo; } else { $User = false; /*array( 'Name' => '', 'CountNotifications' => 0, 'SignedIn' => FALSE);*/ } $Smarty->assign('User', $User); // Make sure that any datasets use arrays instead of objects. foreach ($Controller->Data as $Key => $Value) { if ($Value instanceof Gdn_DataSet) { $Controller->Data[$Key] = $Value->resultArray(); } elseif ($Value instanceof stdClass) { $Controller->Data[$Key] = (array) $Value; } } $BodyClass = val('CssClass', $Controller->Data, '', true); $Sections = Gdn_Theme::section(null, 'get'); if (is_array($Sections)) { foreach ($Sections as $Section) { $BodyClass .= ' Section-' . $Section; } } $Controller->Data['BodyClass'] = $BodyClass; // Set the current locale for themes to take advantage of. $Locale = Gdn::locale()->Locale; $CurrentLocale = array('Key' => $Locale, 'Lang' => str_replace('_', '-', $Locale)); if (class_exists('Locale')) { $CurrentLocale['Language'] = Locale::getPrimaryLanguage($Locale); $CurrentLocale['Region'] = Locale::getRegion($Locale); $CurrentLocale['DisplayName'] = Locale::getDisplayName($Locale, $Locale); $CurrentLocale['DisplayLanguage'] = Locale::getDisplayLanguage($Locale, $Locale); $CurrentLocale['DisplayRegion'] = Locale::getDisplayRegion($Locale, $Locale); } $Smarty->assign('CurrentLocale', $CurrentLocale); $Smarty->assign('Assets', (array) $Controller->Assets); $Smarty->assign('Path', Gdn::request()->path()); // Assign the controller data last so the controllers override any default data. $Smarty->assign($Controller->Data); $Smarty->Controller = $Controller; // for smarty plugins $Smarty->security = true; $Smarty->security_settings['IF_FUNCS'] = array_merge($Smarty->security_settings['IF_FUNCS'], array('Category', 'CheckPermission', 'InSection', 'InCategory', 'MultiCheckPermission', 'GetValue', 'SetValue', 'Url')); $Smarty->security_settings['MODIFIER_FUNCS'] = array_merge($Smarty->security_settings['MODIFIER_FUNCS'], array('sprintf')); $Smarty->secure_dir = array($Path); }
/** * Takes the path to an asset (image, js file, css file, etc) and prepends the web root. * * @param string $Destination The subpath of the asset. * @param bool|string $WithDomain Whether or not to include the domain in the final URL. * @param bool $AddVersion Whether or not to add a cache-busting version querystring parameter to the URL. * @return string Returns the URL of the asset. */ function smartAsset($Destination = '', $WithDomain = false, $AddVersion = false) { $Destination = str_replace('\\', '/', $Destination); if (IsUrl($Destination)) { $Result = $Destination; } else { $Result = Gdn::Request()->UrlDomain($WithDomain) . Gdn::Request()->AssetRoot() . '/' . ltrim($Destination, '/'); } if ($AddVersion) { if (strpos($Result, '?') === false) { $Result .= '?'; } else { $Result .= '&'; } // Figure out which version to put after the asset. $Version = APPLICATION_VERSION; if (preg_match('`^/([^/]+)/([^/]+)/`', $Destination, $Matches)) { $Type = $Matches[1]; $Key = $Matches[2]; static $ThemeVersion = null; switch ($Type) { case 'plugins': $PluginInfo = Gdn::PluginManager()->GetPluginInfo($Key); $Version = GetValue('Version', $PluginInfo, $Version); break; case 'themes': if ($ThemeVersion === null) { $ThemeInfo = Gdn::ThemeManager()->GetThemeInfo(Theme()); if ($ThemeInfo !== false) { $ThemeVersion = GetValue('Version', $ThemeInfo, $Version); } else { $ThemeVersion = $Version; } } $Version = $ThemeVersion; break; } } $Result .= 'v=' . urlencode($Version); } return $Result; }
private static function _processImportUriCB($m) { $uri = trim($m[1], '()"\' '); // We want to grab the import. if (strpos($uri, '//') !== false) { $path = $uri; } elseif ($uri[0] == '/') { $path = self::_realpath(self::$_docRoot, $uri); } else { $path = realpath2(self::$_currentDir . '/' . trim($uri, '/\\')); if (substr_compare(self::$_docRoot, $path, 0, strlen($path)) != 0) { return "/* Error: {$uri} isn't in the webroot. */\n"; } elseif (substr_compare($path, '.css', -4, 4, true) != 0) { return "/* Error: {$uri} must end in .css. */\n"; } } $css = file_get_contents($path); // Not so fast, we've got to rewrite this file too. What's more, the current dir and path are different. $bak = array(self::$_currentDir, self::$_prependPath, self::$_docRoot, self::$debugText); self::$debugText = ''; if (IsUrl($path)) { $newCurrentDir = $path; $newDocRoot = $path; } else { $newDocRoot = self::$_docRoot; $newCurrentDir = realpath2($currentDirBak . realpath2(dirname($uri))); } $css = self::rewrite($css, $newCurrentDir, $newDocRoot); list(self::$_currentDir, self::$_prependPath, self::$_docRoot, self::$debugText) = $bak; return "/* @include url('{$uri}'); */\n" . $css; }
/** * Special manipulations. */ public function ParseSpecialFields($Fields = array()) { if (!is_array($Fields)) { return $Fields; } foreach ($Fields as $Label => $Value) { if ($Value == '') { continue; } // Use plaintext for building these $Value = Gdn_Format::Text($Value); switch ($Label) { case 'Twitter': $Fields['Twitter'] = Anchor('@' . $Value, 'http://twitter.com/' . $Value); break; case 'Facebook': $Fields['Facebook'] = Anchor($Value, 'http://facebook.com/' . $Value); break; case 'LinkedIn': $Fields['LinkedIn'] = Anchor($Value, 'http://www.linkedin.com/in/' . $Value); break; case 'Google': $Fields['Google'] = Anchor('Google+', $Value, '', array('rel' => 'me')); break; case 'Website': $LinkValue = IsUrl($Value) ? $Value : 'http://' . $Value; $Fields['Website'] = Anchor($Value, $LinkValue); break; case 'Real Name': $Fields['Real Name'] = Wrap(htmlspecialchars($Value), 'span', array('itemprop' => 'name')); break; } } return $Fields; }
/** * Lookup the path to a CSS file and return its info array * * @param string $Filename name/relative path to css file * @param string $Folder optional. app or plugin folder to search * @param string $ThemeType mobile or desktop * @return array|bool */ public static function cssPath($Filename, $Folder = '', $ThemeType = '') { if (!$ThemeType) { $ThemeType = IsMobile() ? 'mobile' : 'desktop'; } // 1. Check for a url. if (IsUrl($Filename)) { return array($Filename, $Filename); } $Paths = array(); // 2. Check for a full path. if (strpos($Filename, '/') !== false) { $Filename = ltrim($Filename, '/'); // Direct path was given $Filename = "/{$Filename}"; $Path = PATH_ROOT . $Filename; if (file_exists($Path)) { Deprecated("AssetModel::CssPath() with direct paths"); return array($Path, $Filename); } return false; } // 3. Check the theme. $Theme = Gdn::ThemeManager()->ThemeFromType($ThemeType); if ($Theme) { $Path = "/{$Theme}/design/{$Filename}"; $Paths[] = array(PATH_THEMES . $Path, "/themes{$Path}"); } // 4. Static, Plugin, or App relative file if ($Folder) { if (in_array($Folder, array('resources', 'static'))) { $Path = "/resources/design/{$Filename}"; $Paths[] = array(PATH_ROOT . $Path, $Path); // A plugin-relative path was given } elseif (stringBeginsWith($Folder, 'plugins/')) { $Folder = substr($Folder, strlen('plugins/')); $Path = "/{$Folder}/design/{$Filename}"; $Paths[] = array(PATH_PLUGINS . $Path, "/plugins{$Path}"); // Allow direct-to-file links for plugins $Paths[] = array(PATH_PLUGINS . "/{$Folder}/{$Filename}", "/plugins/{$Folder}/{$Filename}", true); // deprecated // An app-relative path was given } else { $Path = "/{$Folder}/design/{$Filename}"; $Paths[] = array(PATH_APPLICATIONS . $Path, "/applications{$Path}"); } } // 5. Check the default application. if ($Folder != 'dashboard') { $Paths[] = array(PATH_APPLICATIONS . "/dashboard/design/{$Filename}", "/applications/dashboard/design/{$Filename}", true); // deprecated } foreach ($Paths as $Info) { if (file_exists($Info[0])) { if (!empty($Info[2])) { // This path is deprecated. unset($Info[2]); Deprecated("The css file '{$Filename}' in folder '{$Folder}'"); } return $Info; } } if (!(StringEndsWith($Filename, 'custom.css') || StringEndsWith($Filename, 'customadmin.css'))) { trace("Could not find file '{$Filename}' in folder '{$Folder}'."); } return false; }
/** * Takes the path to an asset (image, js file, css file, etc) and prepends the web root. * * @param string $Destination The subpath of the asset. * @param bool|string $WithDomain Whether or not to include the domain in the final URL. * @param bool $AddVersion Whether or not to add a cache-busting version querystring parameter to the URL. * @return string Returns the URL of the asset. */ function smartAsset($Destination = '', $WithDomain = false, $AddVersion = false) { $Destination = str_replace('\\', '/', $Destination); if (IsUrl($Destination)) { $Result = $Destination; } else { $Result = Gdn::Request()->UrlDomain($WithDomain) . Gdn::Request()->AssetRoot() . '/' . ltrim($Destination, '/'); } if ($AddVersion) { $Version = assetVersion($Destination); $Result .= (strpos($Result, '?') === false ? '?' : '&') . 'v=' . urlencode($Version); } return $Result; }
} $Photo = $User->Photo; if ($User->Banned) { $BannedPhoto = C('Garden.BannedPhoto', 'http://cdn.vanillaforums.com/images/banned_large.png'); if ($BannedPhoto) { $Photo = Gdn_Upload::Url($BannedPhoto); } } if ($Photo) { ?> <div class="Photo PhotoWrap PhotoWrapLarge <?php echo GetValue('_CssClass', $User); ?> "> <?php if (IsUrl($Photo)) { $Img = Img($Photo, array('class' => 'ProfilePhotoLarge')); } else { $Img = Img(Gdn_Upload::Url(ChangeBasename($Photo, 'p%s')), array('class' => 'ProfilePhotoLarge')); } if (!$User->Banned && C('Garden.Profile.EditPhotos', TRUE) && (Gdn::Session()->UserID == $User->UserID || Gdn::Session()->CheckPermission('Garden.Users.Edit'))) { echo Anchor(Wrap(T('Change Picture')), '/profile/picture?userid=' . $User->UserID, 'ChangePicture'); } echo $Img; ?> </div> <?php } else { if ($User->UserID == Gdn::Session()->UserID || Gdn::Session()->CheckPermission('Garden.Users.Edit')) { ?> <div class="Photo"><?php
/** * 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 (GetValue('_hint', $Attributes) == 'inline') { $Path = GetValue('_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; }
$RemotePhoto = IsUrl($this->User->Photo, 0, 7); // Define the current profile picture $Picture = ''; if ($this->User->Photo != '') { if (IsUrl($this->User->Photo)) { $Picture = Img($this->User->Photo, array('class' => 'ProfilePhotoLarge')); } else { $Picture = Img(Gdn_Upload::Url(ChangeBasename($this->User->Photo, 'p%s')), array('class' => 'ProfilePhotoLarge')); } } // Define the current thumbnail icon $Thumbnail = $this->User->Photo; if (!$Thumbnail && function_exists('UserPhotoDefaultUrl')) { $Thumbnail = UserPhotoDefaultUrl($this->User); } if ($Thumbnail && !IsUrl($Thumbnail)) { $Thumbnail = Gdn_Upload::Url(ChangeBasename($Thumbnail, 'n%s')); } $Thumbnail = Img($Thumbnail, array('alt' => T('Thumbnail'))); ?> <div class="SmallPopup"> <h2 class="H"><?php echo $this->Data('Title'); ?> </h2> <?php echo $this->Form->Open(array('enctype' => 'multipart/form-data')); echo $this->Form->Errors(); ?> <ul> <?php
<?php if (!defined('APPLICATION')) { exit; } $Session = Gdn::session(); // Check that we have the necessary tools to allow image uploading $AllowImages = Gdn_UploadImage::CanUploadImages(); // Is the photo hosted remotely? $RemotePhoto = IsUrl($this->User->Photo, 0, 7); // Define the current profile picture $Picture = ''; if ($this->User->Photo != '') { if (IsUrl($this->User->Photo)) { $Picture = img($this->User->Photo, array('class' => 'ProfilePhotoLarge')); } else { $Picture = img(Gdn_Upload::url(changeBasename($this->User->Photo, 'p%s')), array('class' => 'ProfilePhotoLarge')); } } // Define the current thumbnail icon $Thumbnail = $this->User->Photo; if (!$Thumbnail && function_exists('UserPhotoDefaultUrl')) { $Thumbnail = UserPhotoDefaultUrl($this->User); } if ($Thumbnail && !isUrl($Thumbnail)) { $Thumbnail = Gdn_Upload::url(changeBasename($Thumbnail, 'n%s')); } $Thumbnail = img($Thumbnail, array('alt' => t('Thumbnail'))); ?> <div class="SmallPopup FormTitleWrapper"> <h1 class="H"><?php
/** * Generic save procedure. * * $Settings controls certain save functionality * * SaveRoles - Save 'RoleID' field as user's roles. Default false. * HashPassword - Hash the provided password on update. Default true. * FixUnique - Try to resolve conflicts with unique constraints on Name and Email. Default false. * ValidateEmail - Make sure the provided email addresses is formattted properly. Default true. * NoConfirmEmail - Disable email confirmation. Default false. * */ public function save($FormPostValues, $Settings = false) { // See if the user's related roles should be saved or not. $SaveRoles = val('SaveRoles', $Settings); // Define the primary key in this model's table. $this->defineSchema(); // Custom Rule: This will make sure that at least one role was selected if saving roles for this user. if ($SaveRoles) { $this->Validation->addRule('OneOrMoreArrayItemRequired', 'function:ValidateOneOrMoreArrayItemRequired'); // $this->Validation->AddValidationField('RoleID', $FormPostValues); $this->Validation->applyRule('RoleID', 'OneOrMoreArrayItemRequired'); } else { $this->Validation->unapplyRule('RoleID', 'OneOrMoreArrayItemRequired'); } // Make sure that checkbox vals are saved as the appropriate value if (array_key_exists('ShowEmail', $FormPostValues)) { $FormPostValues['ShowEmail'] = forceBool($FormPostValues['ShowEmail'], '0', '1', '0'); } if (array_key_exists('Banned', $FormPostValues)) { $FormPostValues['Banned'] = forceBool($FormPostValues['Banned'], '0', '1', '0'); } if (array_key_exists('Confirmed', $FormPostValues)) { $FormPostValues['Confirmed'] = forceBool($FormPostValues['Confirmed'], '0', '1', '0'); } if (array_key_exists('Verified', $FormPostValues)) { $FormPostValues['Verified'] = forceBool($FormPostValues['Verified'], '0', '1', '0'); } unset($FormPostValues['Admin']); // Validate the form posted values if (array_key_exists('Gender', $FormPostValues)) { $FormPostValues['Gender'] = self::fixGender($FormPostValues['Gender']); } if (array_key_exists('DateOfBirth', $FormPostValues) && $FormPostValues['DateOfBirth'] == '0-00-00') { $FormPostValues['DateOfBirth'] = null; } $UserID = val('UserID', $FormPostValues); $User = array(); $Insert = $UserID > 0 ? false : true; if ($Insert) { $this->addInsertFields($FormPostValues); } else { $this->addUpdateFields($FormPostValues); $User = $this->getID($UserID, DATASET_TYPE_ARRAY); if (!$User) { $User = array(); } // Block banning the superadmin or System accounts if (val('Admin', $User) == 2 && val('Banned', $FormPostValues)) { $this->Validation->addValidationResult('Banned', 'You may not ban a System user.'); } elseif (val('Admin', $User) && val('Banned', $FormPostValues)) { $this->Validation->addValidationResult('Banned', 'You may not ban a user with the Admin flag set.'); } } $this->EventArguments['FormPostValues'] = $FormPostValues; $this->fireEvent('BeforeSaveValidation'); $RecordRoleChange = true; if ($UserID && val('FixUnique', $Settings)) { $UniqueValid = $this->validateUniqueFields(val('Name', $FormPostValues), val('Email', $FormPostValues), $UserID, true); if (!$UniqueValid['Name']) { unset($FormPostValues['Name']); } if (!$UniqueValid['Email']) { unset($FormPostValues['Email']); } $UniqueValid = true; } else { $UniqueValid = $this->validateUniqueFields(val('Name', $FormPostValues), val('Email', $FormPostValues), $UserID); } // Add & apply any extra validation rules: if (array_key_exists('Email', $FormPostValues) && val('ValidateEmail', $Settings, true)) { $this->Validation->applyRule('Email', 'Email'); } // AllIPAdresses is stored as a CSV, so handle the case where an array is submitted. if (array_key_exists('AllIPAddresses', $FormPostValues) && is_array($FormPostValues['AllIPAddresses'])) { $FormPostValues['AllIPAddresses'] = implode(',', $FormPostValues['AllIPAddresses']); } if ($this->validate($FormPostValues, $Insert) && $UniqueValid) { // All fields on the form that need to be validated (including non-schema field rules defined above) $Fields = $this->Validation->validationFields(); $RoleIDs = val('RoleID', $Fields, 0); $Username = val('Name', $Fields); $Email = val('Email', $Fields); // Only fields that are present in the schema $Fields = $this->Validation->schemaValidationFields(); // Remove the primary key from the fields collection before saving $Fields = removeKeyFromArray($Fields, $this->PrimaryKey); if (!$Insert && array_key_exists('Password', $Fields) && val('HashPassword', $Settings, true)) { // Encrypt the password for saving only if it won't be hashed in _Insert() $PasswordHash = new Gdn_PasswordHash(); $Fields['Password'] = $PasswordHash->hashPassword($Fields['Password']); $Fields['HashMethod'] = 'Vanilla'; } // Check for email confirmation. if (self::requireConfirmEmail() && !val('NoConfirmEmail', $Settings)) { // Email address has changed if (isset($Fields['Email']) && (array_key_exists('Confirmed', $Fields) && $Fields['Confirmed'] == 0 || $UserID == Gdn::session()->UserID && $Fields['Email'] != Gdn::session()->User->Email && !Gdn::session()->checkPermission('Garden.Users.Edit'))) { $Attributes = val('Attributes', Gdn::session()->User); if (is_string($Attributes)) { $Attributes = @unserialize($Attributes); } $ConfirmEmailRoleID = RoleModel::getDefaultRoles(RoleModel::TYPE_UNCONFIRMED); if (!empty($ConfirmEmailRoleID)) { // The confirm email role is set and it exists so go ahead with the email confirmation. $NewKey = randomString(8); $EmailKey = touchValue('EmailKey', $Attributes, $NewKey); $Fields['Attributes'] = serialize($Attributes); $Fields['Confirmed'] = 0; } } } $this->EventArguments['SaveRoles'] =& $SaveRoles; $this->EventArguments['RoleIDs'] =& $RoleIDs; $this->EventArguments['Fields'] =& $Fields; $this->fireEvent('BeforeSave'); $User = array_merge($User, $Fields); // Check the validation results again in case something was added during the BeforeSave event. if (count($this->Validation->results()) == 0) { // If the primary key exists in the validated fields and it is a // numeric value greater than zero, update the related database row. if ($UserID > 0) { // If they are changing the username & email, make sure they aren't // already being used (by someone other than this user) if (val('Name', $Fields, '') != '' || val('Email', $Fields, '') != '') { if (!$this->validateUniqueFields($Username, $Email, $UserID)) { return false; } } if (array_key_exists('Attributes', $Fields) && !is_string($Fields['Attributes'])) { $Fields['Attributes'] = serialize($Fields['Attributes']); } // Perform save DB operation $this->SQL->put($this->Name, $Fields, array($this->PrimaryKey => $UserID)); // Record activity if the person changed his/her photo. $Photo = val('Photo', $FormPostValues); if ($Photo !== false) { if (val('CheckExisting', $Settings)) { $User = $this->getID($UserID); $OldPhoto = val('Photo', $User); } if (isset($OldPhoto) && $OldPhoto != $Photo) { if (IsUrl($Photo)) { $PhotoUrl = $Photo; } else { $PhotoUrl = Gdn_Upload::url(changeBasename($Photo, 'n%s')); } $ActivityModel = new ActivityModel(); if ($UserID == Gdn::session()->UserID) { $HeadlineFormat = t('HeadlineFormat.PictureChange', '{RegardingUserID,You} changed {ActivityUserID,your} profile picture.'); } else { $HeadlineFormat = t('HeadlineFormat.PictureChange.ForUser', '{RegardingUserID,You} changed the profile picture for {ActivityUserID,user}.'); } $ActivityModel->save(array('ActivityUserID' => $UserID, 'RegardingUserID' => Gdn::session()->UserID, 'ActivityType' => 'PictureChange', 'HeadlineFormat' => $HeadlineFormat, 'Story' => img($PhotoUrl, array('alt' => t('Thumbnail'))))); } } } else { $RecordRoleChange = false; if (!$this->validateUniqueFields($Username, $Email)) { return false; } // Define the other required fields: $Fields['Email'] = $Email; $Fields['Roles'] = $RoleIDs; // Make sure that the user is assigned to one or more roles: $SaveRoles = false; // And insert the new user. $UserID = $this->_insert($Fields, $Settings); if ($UserID) { // Report that the user was created. $ActivityModel = new ActivityModel(); $ActivityModel->save(array('ActivityType' => 'Registration', 'ActivityUserID' => $UserID, 'HeadlineFormat' => t('HeadlineFormat.Registration', '{ActivityUserID,You} joined.'), 'Story' => t('Welcome Aboard!')), false, array('GroupBy' => 'ActivityTypeID')); // Report the creation for mods. $ActivityModel->save(array('ActivityType' => 'Registration', 'ActivityUserID' => Gdn::session()->UserID, 'RegardingUserID' => $UserID, 'NotifyUserID' => ActivityModel::NOTIFY_MODS, 'HeadlineFormat' => t('HeadlineFormat.AddUser', '{ActivityUserID,user} added an account for {RegardingUserID,user}.'))); } } // Now update the role settings if necessary. if ($SaveRoles) { // If no RoleIDs were provided, use the system defaults if (!is_array($RoleIDs)) { $RoleIDs = RoleModel::getDefaultRoles(RoleModel::TYPE_MEMBER); } $this->saveRoles($UserID, $RoleIDs, $RecordRoleChange); } // Send the confirmation email. if (isset($EmailKey)) { if (!is_array($User)) { $User = $this->getID($UserID, DATASET_TYPE_ARRAY); } $this->sendEmailConfirmationEmail($User, true); } $this->EventArguments['UserID'] = $UserID; $this->fireEvent('AfterSave'); } else { $UserID = false; } } else { $UserID = false; } // Clear cached user data if (!$Insert && $UserID) { $this->clearCache($UserID, array('user')); } return $UserID; }
/** * Returns an img tag. */ function Img($Image, $Attributes = '', $WithDomain = FALSE) { if ($Attributes == '') { $Attributes = array(); } if (!IsUrl($Image)) { $Image = SmartAsset($Image, $WithDomain); } return '<img src="' . $Image . '"' . Attribute($Attributes) . ' />'; }
/** * Returns an img tag. * * @param $Image * @param string $Attributes * @param bool|false $WithDomain * @return string */ function img($Image, $Attributes = '', $WithDomain = false) { if ($Attributes != '') { $Attributes = attribute($Attributes); } if (!IsUrl($Image)) { $Image = smartAsset($Image, $WithDomain); } return '<img src="' . $Image . '"' . $Attributes . ' />'; }
/** * Connect the user with an external source. * * This controller method is meant to be used with plugins that set its data array to work. * Events: ConnectData * * @since 2.0.0 * @access public * * @param string $Method Used to register multiple providers on ConnectData event. */ public function Connect($Method) { $this->AddJsFile('entry.js'); $this->View = 'connect'; $IsPostBack = $this->Form->IsPostBack() && $this->Form->GetFormValue('Connect', NULL) !== NULL; if (!$IsPostBack) { // Here are the initial data array values. that can be set by a plugin. $Data = array('Provider' => '', 'ProviderName' => '', 'UniqueID' => '', 'FullName' => '', 'Name' => '', 'Email' => '', 'Photo' => '', 'Target' => $this->Target()); $this->Form->SetData($Data); $this->Form->AddHidden('Target', $this->Request->Get('Target', '/')); } // The different providers can check to see if they are being used and modify the data array accordingly. $this->EventArguments = array($Method); // Fire ConnectData event & error handling. $CurrentData = $this->Form->FormValues(); try { $this->FireEvent('ConnectData'); } catch (Gdn_UserException $Ex) { $this->Form->AddError($Ex); return $this->Render('ConnectError'); } catch (Exception $Ex) { if (Debug()) { $this->Form->AddError($Ex); } else { $this->Form->AddError('There was an error fetching the connection data.'); } return $this->Render('ConnectError'); } if (!UserModel::NoEmail()) { if (!$this->Form->GetFormValue('Email') || $this->Form->GetFormValue('EmailVisible')) { $this->Form->SetFormValue('EmailVisible', TRUE); $this->Form->AddHidden('EmailVisible', TRUE); if ($IsPostBack) { $this->Form->SetFormValue('Email', GetValue('Email', $CurrentData)); } } } $FormData = $this->Form->FormValues(); // debug // Make sure the minimum required data has been provided to the connect. if (!$this->Form->GetFormValue('Provider')) { $this->Form->AddError('ValidateRequired', T('Provider')); } if (!$this->Form->GetFormValue('UniqueID')) { $this->Form->AddError('ValidateRequired', T('UniqueID')); } if (!$this->Data('Verified')) { // Whatever event handler catches this must Set the data 'Verified' to true to prevent a random site from connecting without credentials. // This must be done EVERY postback and is VERY important. $this->Form->AddError('The connection data has not been verified.'); } if ($this->Form->ErrorCount() > 0) { return $this->Render(); } $UserModel = Gdn::UserModel(); // Check to see if there is an existing user associated with the information above. $Auth = $UserModel->GetAuthentication($this->Form->GetFormValue('UniqueID'), $this->Form->GetFormValue('Provider')); $UserID = GetValue('UserID', $Auth); // Check to synchronise roles upon connecting. if (($this->Data('Trusted') || C('Garden.SSO.SynchRoles')) && $this->Form->GetFormValue('Roles', NULL) !== NULL) { $SaveRoles = TRUE; // Translate the role names to IDs. $Roles = $this->Form->GetFormValue('Roles', NULL); $Roles = RoleModel::GetByName($Roles); $RoleIDs = array_keys($Roles); if (empty($RoleIDs)) { // The user must have at least one role. This protects that. $RoleIDs = $this->UserModel->NewUserRoleIDs(); } $this->Form->SetFormValue('RoleID', $RoleIDs); } else { $SaveRoles = FALSE; } if ($UserID) { // The user is already connected. $this->Form->SetFormValue('UserID', $UserID); if (C('Garden.Registration.ConnectSynchronize', TRUE)) { $User = Gdn::UserModel()->GetID($UserID, DATASET_TYPE_ARRAY); $Data = $this->Form->FormValues(); // Don't overwrite the user photo if the user uploaded a new one. $Photo = GetValue('Photo', $User); if (!GetValue('Photo', $Data) || $Photo && !IsUrl($Photo)) { unset($Data['Photo']); } // Synchronize the user's data. $UserModel->Save($Data, array('NoConfirmEmail' => TRUE, 'FixUnique' => TRUE, 'SaveRoles' => $SaveRoles)); } // Always save the attributes because they may contain authorization information. if ($Attributes = $this->Form->GetFormValue('Attributes')) { $UserModel->SaveAttribute($UserID, $Attributes); } // Sign the user in. Gdn::Session()->Start($UserID, TRUE, (bool) $this->Form->GetFormValue('RememberMe', TRUE)); Gdn::UserModel()->FireEvent('AfterSignIn'); // $this->_SetRedirect(TRUE); $this->_SetRedirect($this->Request->Get('display') == 'popup'); } elseif ($this->Form->GetFormValue('Name') || $this->Form->GetFormValue('Email')) { $NameUnique = C('Garden.Registration.NameUnique', TRUE); $EmailUnique = C('Garden.Registration.EmailUnique', TRUE); $AutoConnect = C('Garden.Registration.AutoConnect'); // Get the existing users that match the name or email of the connection. $Search = FALSE; if ($this->Form->GetFormValue('Name') && $NameUnique) { $UserModel->SQL->OrWhere('Name', $this->Form->GetFormValue('Name')); $Search = TRUE; } if ($this->Form->GetFormValue('Email') && ($EmailUnique || $AutoConnect)) { $UserModel->SQL->OrWhere('Email', $this->Form->GetFormValue('Email')); $Search = TRUE; } if ($Search) { $ExistingUsers = $UserModel->GetWhere()->ResultArray(); } else { $ExistingUsers = array(); } // Check to automatically link the user. if ($AutoConnect && count($ExistingUsers) > 0) { foreach ($ExistingUsers as $Row) { if ($this->Form->GetFormValue('Email') == $Row['Email']) { $UserID = $Row['UserID']; $this->Form->SetFormValue('UserID', $UserID); $Data = $this->Form->FormValues(); if (C('Garden.Registration.ConnectSynchronize', TRUE)) { // Don't overwrite a photo if the user has already uploaded one. $Photo = GetValue('Photo', $Row); if (!GetValue('Photo', $Data) || $Photo && !StringBeginsWith($Photo, 'http')) { unset($Data['Photo']); } $UserModel->Save($Data, array('NoConfirmEmail' => TRUE, 'FixUnique' => TRUE, 'SaveRoles' => $SaveRoles)); } if ($Attributes = $this->Form->GetFormValue('Attributes')) { $UserModel->SaveAttribute($UserID, $Attributes); } // Save the userauthentication link. $UserModel->SaveAuthentication(array('UserID' => $UserID, 'Provider' => $this->Form->GetFormValue('Provider'), 'UniqueID' => $this->Form->GetFormValue('UniqueID'))); // Sign the user in. Gdn::Session()->Start($UserID, TRUE, (bool) $this->Form->GetFormValue('RememberMe', TRUE)); Gdn::UserModel()->FireEvent('AfterSignIn'); // $this->_SetRedirect(TRUE); $this->_SetRedirect($this->Request->Get('display') == 'popup'); $this->Render(); return; } } } $CurrentUserID = Gdn::Session()->UserID; // Massage the existing users. foreach ($ExistingUsers as $Index => $UserRow) { if ($EmailUnique && $UserRow['Email'] == $this->Form->GetFormValue('Email')) { $EmailFound = $UserRow; break; } if ($UserRow['Name'] == $this->Form->GetFormValue('Name')) { $NameFound = $UserRow; } if ($CurrentUserID > 0 && $UserRow['UserID'] == $CurrentUserID) { unset($ExistingUsers[$Index]); $CurrentUserFound = TRUE; } } if (isset($EmailFound)) { // The email address was found and can be the only user option. $ExistingUsers = array($UserRow); $this->SetData('NoConnectName', TRUE); } elseif (isset($CurrentUserFound)) { $ExistingUsers = array_merge(array('UserID' => 'current', 'Name' => sprintf(T('%s (Current)'), Gdn::Session()->User->Name)), $ExistingUsers); } if (!isset($NameFound) && !$IsPostBack) { $this->Form->SetFormValue('ConnectName', $this->Form->GetFormValue('Name')); } $this->SetData('ExistingUsers', $ExistingUsers); if (UserModel::NoEmail()) { $EmailValid = TRUE; } else { $EmailValid = ValidateRequired($this->Form->GetFormValue('Email')); } if ($this->Form->GetFormValue('Name') && $EmailValid && (!is_array($ExistingUsers) || count($ExistingUsers) == 0)) { // There is no existing user with the suggested name so we can just create the user. $User = $this->Form->FormValues(); $User['Password'] = RandomString(50); // some password is required $User['HashMethod'] = 'Random'; $User['Source'] = $this->Form->GetFormValue('Provider'); $User['SourceID'] = $this->Form->GetFormValue('UniqueID'); $User['Attributes'] = $this->Form->GetFormValue('Attributes', NULL); $User['Email'] = $this->Form->GetFormValue('ConnectEmail', $this->Form->GetFormValue('Email', NULL)); // $UserID = $UserModel->InsertForBasic($User, FALSE, array('ValidateEmail' => FALSE, 'NoConfirmEmail' => TRUE, 'SaveRoles' => $SaveRoles)); $UserID = $UserModel->Register($User, array('CheckCaptcha' => FALSE, 'ValidateEmail' => FALSE, 'NoConfirmEmail' => TRUE, 'SaveRoles' => $SaveRoles)); $User['UserID'] = $UserID; $this->Form->SetValidationResults($UserModel->ValidationResults()); if ($UserID) { $UserModel->SaveAuthentication(array('UserID' => $UserID, 'Provider' => $this->Form->GetFormValue('Provider'), 'UniqueID' => $this->Form->GetFormValue('UniqueID'))); $this->Form->SetFormValue('UserID', $UserID); Gdn::Session()->Start($UserID, TRUE, (bool) $this->Form->GetFormValue('RememberMe', TRUE)); Gdn::UserModel()->FireEvent('AfterSignIn'); // Send the welcome email. if (C('Garden.Registration.SendConnectEmail', FALSE)) { try { $UserModel->SendWelcomeEmail($UserID, '', 'Connect', array('ProviderName' => $this->Form->GetFormValue('ProviderName', $this->Form->GetFormValue('Provider', 'Unknown')))); } catch (Exception $Ex) { // Do nothing if emailing doesn't work. } } $this->_SetRedirect(TRUE); } } } // Save the user's choice. if ($IsPostBack) { // The user has made their decision. $PasswordHash = new Gdn_PasswordHash(); $UserSelect = $this->Form->GetFormValue('UserSelect'); if (!$UserSelect || $UserSelect == 'other') { // The user entered a username. $ConnectNameEntered = TRUE; if ($this->Form->ValidateRule('ConnectName', 'ValidateRequired')) { $ConnectName = $this->Form->GetFormValue('ConnectName'); $User = FALSE; if (C('Garden.Registration.NameUnique')) { // Check to see if there is already a user with the given name. $User = $UserModel->GetWhere(array('Name' => $ConnectName))->FirstRow(DATASET_TYPE_ARRAY); } if (!$User) { $this->Form->ValidateRule('ConnectName', 'ValidateUsername'); } } } else { // The user selected an existing user. $ConnectNameEntered = FALSE; if ($UserSelect == 'current') { if (Gdn::Session()->UserID == 0) { // This shouldn't happen, but a use could sign out in another browser and click submit on this form. $this->Form->AddError('@You were uexpectidly signed out.'); } else { $UserSelect = Gdn::Session()->UserID; } } $User = $UserModel->GetID($UserSelect, DATASET_TYPE_ARRAY); } if (isset($User) && $User) { // Make sure the user authenticates. if (!$User['UserID'] == Gdn::Session()->UserID) { if ($this->Form->ValidateRule('ConnectPassword', 'ValidateRequired', sprintf(T('ValidateRequired'), T('Password')))) { try { if (!$PasswordHash->CheckPassword($this->Form->GetFormValue('ConnectPassword'), $User['Password'], $User['HashMethod'], $this->Form->GetFormValue('ConnectName'))) { if ($ConnectNameEntered) { $this->Form->AddError('The username you entered has already been taken.'); } else { $this->Form->AddError('The password you entered is incorrect.'); } } } catch (Gdn_UserException $Ex) { $this->Form->AddError($Ex); } } } } elseif ($this->Form->ErrorCount() == 0) { // The user doesn't exist so we need to add another user. $User = $this->Form->FormValues(); $User['Name'] = $User['ConnectName']; $User['Password'] = RandomString(50); // some password is required $User['HashMethod'] = 'Random'; $UserID = $UserModel->Register($User, array('CheckCaptcha' => FALSE, 'NoConfirmEmail' => TRUE, 'SaveRoles' => $SaveRoles)); $User['UserID'] = $UserID; $this->Form->SetValidationResults($UserModel->ValidationResults()); if ($UserID) { // // Add the user to the default roles. // $UserModel->SaveRoles($UserID, C('Garden.Registration.DefaultRoles')); // Send the welcome email. $UserModel->SendWelcomeEmail($UserID, '', 'Connect', array('ProviderName' => $this->Form->GetFormValue('ProviderName', $this->Form->GetFormValue('Provider', 'Unknown')))); } } if ($this->Form->ErrorCount() == 0) { // Save the authentication. if (isset($User) && GetValue('UserID', $User)) { $UserModel->SaveAuthentication(array('UserID' => $User['UserID'], 'Provider' => $this->Form->GetFormValue('Provider'), 'UniqueID' => $this->Form->GetFormValue('UniqueID'))); $this->Form->SetFormValue('UserID', $User['UserID']); } // Sign the appropriate user in. Gdn::Session()->Start($this->Form->GetFormValue('UserID'), TRUE, (bool) $this->Form->GetFormValue('RememberMe', TRUE)); Gdn::UserModel()->FireEvent('AfterSignIn'); $this->_SetRedirect(TRUE); } } $this->Render(); }
/** * Returns an img tag. * * @param $Image * @param string $Attributes * @param bool|false $WithDomain * @return string */ function img($Image, $Attributes = '', $WithDomain = false) { if ($Attributes != '') { $Attributes = attribute($Attributes); } if (!IsUrl($Image)) { $Image = smartAsset($Image, $WithDomain); } return '<img src="' . htmlspecialchars($Image, ENT_QUOTES) . '"' . $Attributes . ' />'; }
/** * Takes the path to an asset (image, js file, css file, etc) and prepends the webroot. */ function Asset($Destination = '', $WithDomain = FALSE, $AddVersion = FALSE) { $Destination = str_replace('\\', '/', $Destination); if (IsUrl($Destination)) { $Result = $Destination; } else { $Parts = array(Gdn_Url::WebRoot($WithDomain), $Destination); if (!$WithDomain) { array_unshift($Parts, '/'); } $Result = CombinePaths($Parts, '/'); } if ($AddVersion) { if (strpos($Result, '?') === FALSE) { $Result .= '?'; } else { $Result .= '&'; } // Figure out which version to put after the asset. $Version = APPLICATION_VERSION; if (preg_match('`^/([^/]+)/([^/]+)/`', $Destination, $Matches)) { $Type = $Matches[1]; $Key = $Matches[2]; static $ThemeVersion = NULL; switch ($Type) { case 'plugins': $PluginInfo = Gdn::PluginManager()->GetPluginInfo($Key); $Version = GetValue('Version', $PluginInfo, $Version); break; case 'themes': if ($ThemeVersion === NULL) { $ThemeInfo = Gdn::ThemeManager()->GetThemeInfo(Theme()); if ($ThemeInfo !== FALSE) { $ThemeVersion = GetValue('Version', $ThemeInfo, $Version); } else { $ThemeVersion = $Version; } } $Version = $ThemeVersion; break; } } $Result .= 'v=' . urlencode($Version); } return $Result; }