Wednesday, January 31, 2007
by Nik Kalyani
Wednesday, January 31, 2007 10:54:34 AM (Pacific Standard Time, UTC-08:00)

In a previous post DotNetNuke Module Settings Made Simple, I had shared some code to make DotNetNuke module settings easier to manage. One of the methods in an included class permitted the use of tokens in stored settings values. This allows for many possibilities that are user-, tab- or portal-driven. In that post, I had omitted the code for token substitution because it is a bit lengthy. Here, then, is code for substituting string tokens with portal values.

Although the intended use is for module settings, there’s no reason this code cannot be used for just about any scenario where tokens need to be injected. 

using System;
using System.Web;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Reflection;
using DotNetNuke;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Users;
using DotNetNuke.Entities.Tabs;
using DotNetNuke.Security;
using DotNetNuke.Security.Roles;
using DotNetNuke.Common;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Services.Localization;
using DotNetNuke.Entities.Portals;
using DotNetNuke.Entities.Modules.Actions;
using DotNetNuke.Services.Personalization;
using DotNetNuke.Modules.HTMLEditorProvider;
using DotNetNuke.Framework.Providers;
/* Copyright (c) 2007, Speerio, Inc. This notice may not be removed. */
namespace Speerio.DNN.Common
{
    /// <summary>
    /// Summary description for PortalTokens.
    /// </summary>
    public class PortalTokens
    {
        public const string UnknownUser = "~Public";
 
        public static string Replace(string source)
        {
            return(Replace(source, UnknownUser, null));
        }
 
        public static string Replace(string source, ModuleInfo moduleConfig)
        {
            return(Replace(source, UnknownUser, moduleConfig));
        }
 
        public static string Replace(string source, string unknownUserText, ModuleInfo moduleConfig)
        {
            PortalSettings portalSettings = (PortalSettings) HttpContext.Current.Items["PortalSettings"];
 
            // PORTALSETTINGS tokens
            source = PortalTokens.ReplacePortalTokens(source, portalSettings);
 
            // USERINFO tokens
            source = PortalTokens.ReplaceUserTokens(source, unknownUserText);
 
            // ROLEMEMBER tokens
            source = PortalTokens.ReplaceRoleTokens(source);
 
            // TABSETTINGS tokens
            source = PortalTokens.ReplaceTabTokens(source, portalSettings.ActiveTab);
 
            // MODULESETTINGS tokens
            if (moduleConfig != null)
                source = PortalTokens.ReplaceModuleTokens(source, moduleConfig);
 
            // USERPROFILE tokens
            source = PortalTokens.ReplaceProfileTokens(source);
 
            // REGEX tokens
            source = PortalTokens.ReplaceRegExTokens(source);
 
            return(source);
        }
 
        private static string ReplaceRegExTokens(string source)
        {
            // REGEX tokens
            if (source.IndexOf("<REGEX:") > -1)
            {
                int reToken = source.IndexOf ("<");
                if (reToken > -1)
                {
                    try
                    {
                        string rePair = source.Substring(reToken+1);
                        int term = rePair.IndexOf(">");
                        if (term > -1)
                        {
                            rePair = rePair.Substring(0,term);
                            string[] reParams = rePair.Split(',');
                            if (reParams.Length == 2)
                            {
                                source = source.Replace("<" + reParams[0] + "," + reParams[1] + ">","");
                                reParams[0] = reParams[0].Replace("REGEX:","");
                                source = Regex.Replace(source, reParams[0], reParams[1], RegexOptions.IgnoreCase);
                            }
                        }
                    }
                    catch
                    {
                    }
                }
            }
            return(source);
        }
                        
        private static string ReplacePortalTokens(string source, PortalSettings portalSettings)
        {
            if (source.IndexOf("[PORTALSETTINGS:") > -1)
            {
                try { source = source.Replace("[PORTALSETTINGS:PortalId]",portalSettings.PortalId.ToString()); } catch {}
                try { source = source.Replace("[PORTALSETTINGS:UploadDirectory]",portalSettings.HomeDirectory); } catch {}
                try { source = source.Replace("[PORTALSETTINGS:HomeDirectory]",portalSettings.HomeDirectory); } catch {}
                try { source = source.Replace("[PORTALSETTINGS:PortalName]",portalSettings.PortalName); } catch {}
                try { source = source.Replace("[PORTALSETTINGS:AdministratorId]",portalSettings.AdministratorId.ToString()); } catch {}
                try { source = source.Replace("[PORTALSETTINGS:AdministratorRoleId]",portalSettings.AdministratorRoleId.ToString()); } catch {}
                try { source = source.Replace("[PORTALSETTINGS:DefaultLanguage]",portalSettings.DefaultLanguage); } catch {}
            }
            return(source);
        }
 
        private static string ReplaceUserTokens(string source, string unknownUserText)
        {
            if (source.IndexOf("[USERINFO:") > -1)                        
            {
                try
                {
                    bool auth = HttpContext.Current.Request.IsAuthenticated;
                    UserInfo userInfo = null;
                    if (auth)
                        userInfo = (UserInfo) HttpContext.Current.Items["UserInfo"];
 
                    try { source = source.Replace("[USERINFO:UserID]",(auth ? userInfo.UserID.ToString() : unknownUserText)); } catch {}
                    try { source = source.Replace("[USERINFO:FullName]",(auth ? userInfo.FirstName + " " + userInfo.LastName : unknownUserText)); } catch {}
                    try { source = source.Replace("[USERINFO:FirstName]",(auth ? userInfo.FirstName : unknownUserText)); } catch {}
                    try { source = source.Replace("[USERINFO:LastName]",(auth ? userInfo.LastName : unknownUserText)); } catch {}
                    try { source = source.Replace("[USERINFO:Street]",(auth ? userInfo.Profile.Street : unknownUserText)); } catch {}
                    try { source = source.Replace("[USERINFO:City]",(auth ? userInfo.Profile.City : unknownUserText)); } catch {}
                    try { source = source.Replace("[USERINFO:Region]",(auth ? userInfo.Profile.Region : unknownUserText)); } catch {}
                    try { source = source.Replace("[USERINFO:PostalCode]",(auth ? userInfo.Profile.PostalCode : unknownUserText)); } catch {}
                    try { source = source.Replace("[USERINFO:Country]",(auth ? userInfo.Profile.Country : unknownUserText)); } catch {}
                    try { source = source.Replace("[USERINFO:Password]",(auth ? userInfo.Membership.Password : unknownUserText)); } catch {}
                    try { source = source.Replace("[USERINFO:Email]",(auth ? userInfo.Membership.Email : unknownUserText)); } catch {}
                    try { source = source.Replace("[USERINFO:Unit]",(auth ? userInfo.Profile.Unit : unknownUserText)); } catch {}
                    try { source = source.Replace("[USERINFO:Telephone]",(auth ? userInfo.Profile.Telephone : unknownUserText)); } catch {}
                    try { source = source.Replace("[USERINFO:Username]",(auth ? userInfo.Username : unknownUserText)); } catch {}
                    try { source = source.Replace("[USERINFO:IsSuperUser]",(auth ? userInfo.IsSuperUser.ToString() : unknownUserText)); } catch {}
                    try { source = source.Replace("[USERINFO:AffiliateID]",(auth ? userInfo.AffiliateID.ToString() : unknownUserText)); } catch {}
                    try { source = source.Replace("[USERINFO:Website]",(auth ? userInfo.Profile.Website : unknownUserText)); } catch {}
                    try { source = source.Replace("[USERINFO:TimeZone]",(auth ? userInfo.Profile.TimeZone.ToString() : unknownUserText)); } catch {}
                    try { source = source.Replace("[USERINFO:IM]",(auth ? userInfo.Profile.IM : unknownUserText)); } catch {}
                    try { source = source.Replace("[USERINFO:Fax]",(auth ? userInfo.Profile.Fax : unknownUserText)); } catch {}
                    try { source = source.Replace("[USERINFO:Cell]",(auth ? userInfo.Profile.Cell : unknownUserText)); } catch {}
 
                }
                catch
                {
                }
            }
            return(source);
        }
 
 
        private static string ReplaceRoleTokens(string source)
        {
            string tmp = source;
 
            if (source.IndexOf("<ROLEMEMBER:") > -1)
            {
                try
                {
                    string pattern = "(?<token>\\<ROLEMEMBER:(?<roles>.*?)\\|(?<unknown>.*?)\\>)";
                    Regex r = new Regex(pattern, RegexOptions.IgnoreCase );
 
                    ArrayList tokens = new ArrayList(10);
                    ArrayList roles = new ArrayList(10);
                    ArrayList unknowns = new ArrayList(10);
                    Match m;                           
                    for (m = r.Match(source); m.Success; m = m.NextMatch())
                    {
                        tokens.Add(m.Groups["token"].ToString());
                        roles.Add(m.Groups["roles"].ToString().Trim());
                        unknowns.Add(m.Groups["unknown"].ToString().Trim());
                    }
 
                    RoleController roleController = new RoleController();
                    bool auth = HttpContext.Current.Request.IsAuthenticated;
                    UserInfo userInfo = null;
                    string[] userRoles = {};
                    if (auth)
                    {
                        userInfo = (UserInfo) HttpContext.Current.Items["UserInfo"];
                        userRoles = roleController.GetPortalRolesByUser(userInfo.UserID, userInfo.PortalID);
                        if (userRoles != null)
                        {
                            for(int u=0;u<userRoles.Length;u++)
                                userRoles[u] = userRoles[u].ToLower();
                        }
                    }
                    for(int idx=0;idx<tokens.Count;idx++)
                    {
                        string token = tokens[idx].ToString();
                        string defaultValue = unknowns[idx].ToString();
                        string[] roleList = roles[idx].ToString().Split(',');
                        string selectedRole = "";
                        for(int l=0;l<roleList.Length;l++)
                        {
                            for(int u=0;u<userRoles.Length;u++)
                            {
                                if (roleList[l].ToLower() == userRoles[u])
                                {
                                    selectedRole = roleList[l];
                                    break;
                                }
                            }
                            if (selectedRole != "")
                                break;
                        }
 
                        try { source = source.Replace(tokens[idx].ToString(), (selectedRole == "" ? defaultValue : selectedRole));  } 
                        catch {}
                    }
                    return(source);
                }
                catch
                {              
                }
            }
            return(source);
        }
 
 
        private static string ReplaceProfileTokens(string source)
        {
            string tmp = source;
 
            if (source.IndexOf("<USERPROFILE:") > -1)
            {
                try
                {
                    string pattern = "(?<token><USERPROFILE:(?<container>.*?),(?<key>.*?),(?<unknown>.*?)>)";
                    Regex r = new Regex(pattern, RegexOptions.IgnoreCase );
 
                    ArrayList tokens = new ArrayList(10);
                    ArrayList containers = new ArrayList(10);
                    ArrayList keys = new ArrayList(10);
                    ArrayList unknowns = new ArrayList(10);
                    Match m;                           
                    for (m = r.Match(source); m.Success; m = m.NextMatch())
                    {
                        tokens.Add(m.Groups["token"].ToString());
                        containers.Add(m.Groups["container"].ToString().Trim());
                        keys.Add(m.Groups["key"].ToString().Trim());
                        unknowns.Add(m.Groups["unknown"].ToString().Trim());
                    }
                    for(int idx=0;idx<tokens.Count;idx++)
                    {
                        object keyObject = Personalization.GetProfile(containers[idx].ToString(),keys[idx].ToString());
                        string keyValue = "";
                        if (keyObject != null)
                            keyValue = keyObject.ToString();
                        try { source = source.Replace(tokens[idx].ToString(), (keyValue == "" ? unknowns[idx].ToString() : keyValue));  } catch {}
                    }
                    return(source);
                }
                catch
                {              
                }
            }
            return(source);
        }
 
        private static string ReplaceTabTokens(string source, TabInfo tabSettings)
        {
            if (source.IndexOf("[TABSETTINGS:") > -1)
            {
                try
                {
                    try { source = source.Replace("[TABSETTINGS:PortalId]",tabSettings.PortalID.ToString()); } catch {}
                    try { source = source.Replace("[TABSETTINGS:TabId]",tabSettings.TabID.ToString()); } catch {}
                    try { source = source.Replace("[TABSETTINGS:TabName]",tabSettings.TabName); } catch {}
                    try { source = source.Replace("[TABSETTINGS:Title]",tabSettings.Title); } catch {}
                    try { source = source.Replace("[TABSETTINGS:AuthorizedRoles]",tabSettings.AuthorizedRoles); } catch {}
                    try { source = source.Replace("[TABSETTINGS:AdministratorRoles]",tabSettings.AdministratorRoles); } catch {}
                    try { source = source.Replace("[TABSETTINGS:ParentId]",tabSettings.ParentId.ToString()); } catch {}
                    try { source = source.Replace("[TABSETTINGS:Level]",tabSettings.Level.ToString()); } catch {}
                    try { source = source.Replace("[TABSETTINGS:Skinsource]",tabSettings.SkinPath); } catch {}
                    try { source = source.Replace("[TABSETTINGS:SkinSrc]",tabSettings.SkinSrc); } catch {}
                }
                catch
                {
                }
            }
            return(source);
        }
 
        private static string ReplaceModuleTokens(string source, ModuleInfo moduleConfig)
        {
            if (source.IndexOf("[MODULESETTINGS:") > -1)
            {
                try
                {
                    try { source = source.Replace("[MODULESETTINGS:ModuleId]",moduleConfig.ModuleID.ToString()); } catch {}
                    try { source = source.Replace("[MODULESETTINGS:TabId]",moduleConfig.TabID.ToString()); } catch {}
                    try { source = source.Replace("[MODULESETTINGS:ModuleDefId]",moduleConfig.ModuleDefID.ToString()); } catch {}
                    try { source = source.Replace("[MODULESETTINGS:ModuleOrder]",moduleConfig.ModuleOrder.ToString()); } catch {}
                    try { source = source.Replace("[MODULESETTINGS:PaneName]",moduleConfig.PaneName); } catch {}
                    try { source = source.Replace("[MODULESETTINGS:ModuleTitle]",moduleConfig.ModuleTitle); } catch {}
                    try { source = source.Replace("[MODULESETTINGS:AuthorizedEditRoles]",moduleConfig.AuthorizedEditRoles); } catch {}
                    try { source = source.Replace("[MODULESETTINGS:AuthorizedViewRoles]",moduleConfig.AuthorizedViewRoles); } catch {}
                    try { source = source.Replace("[MODULESETTINGS:ControlSrc]",moduleConfig.ControlSrc); } catch {}
                    try { source = source.Replace("[MODULESETTINGS:ControlTitle]",moduleConfig.ControlTitle); } catch {}
                    try { source = source.Replace("[MODULESETTINGS:DesktopModuleId]",moduleConfig.DesktopModuleID.ToString()); } catch {}
                    try { source = source.Replace("[MODULESETTINGS:FriendlyName]",moduleConfig.FriendlyName); } catch {}
 
                }
                catch
                {
                }
            }
            return(source);
        }
 
    }
}
#    Comments [1] - Trackback    

RSS feed
Search and Links
Bling

View Nik Kalyani's profile on LinkedIn

Contact me: nik*kalyani.com (replace "*")

TechBubble
www.flickr.com
This is a Flickr badge showing public photos from techbubble. Make your own badge here.
Statistics
Total Posts: 204
This Year: 22
This Month: 0
This Week: 0
Comments: 231
About the author/Disclaimer

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2008
Nik Kalyani
Sign In
All Content © 2008, Nik Kalyani