Exemplo n.º 1
0
        public static string GetUrlLocalUri(XUri confBaseUri, string url, bool includeQuery, bool decode)
        {
            if (string.IsNullOrEmpty(url))
            {
                return(null);
            }

            if (url.StartsWithInvariantIgnoreCase(confBaseUri.ToString()))
            {
                //Remove the wiki path prefix (everything before display generally)
                url = confBaseUri.SchemeHostPort + url.Substring(confBaseUri.ToString().Length);
            }

            XUri uri = XUri.TryParse(url);

            if (uri == null)
            {
                return(null);
            }
            string ret = uri.Path;

            if (decode)
            {
                ret = XUri.Decode(ret);
            }

            if (includeQuery && !string.IsNullOrEmpty(uri.QueryFragment))
            {
                ret += uri.QueryFragment;
            }
            return(ret);
        }
Exemplo n.º 2
0
        private RoleBE GetRoleFromUrl(bool mustExist)
        {
            RoleBE r;
            string roleid = DreamContext.Current.GetParam("roleid");

            // Double decoding of name is done to work around a mod_proxy issue that strips out slashes
            roleid = XUri.Decode(roleid);
            if (roleid.StartsWith("="))
            {
                string name = roleid.Substring(1);
                r = PermissionsBL.GetRoleByName(name);
                if (r == null && mustExist)
                {
                    throw new SiteRoleNameNotFoundException(name);
                }
            }
            else
            {
                uint roleIdInt;
                if (!uint.TryParse(roleid, out roleIdInt))
                {
                    throw new SiteRoleIdInvalidArgumentException();
                }
                r = PermissionsBL.GetRoleById(roleIdInt);
                if (r == null && mustExist)
                {
                    throw new SiteRoleIdNotFoundException(roleIdInt);
                }
            }
            return(r);
        }
Exemplo n.º 3
0
        private GroupBE GetGroupFromUrl()
        {
            GroupBE g;
            string  groupid = DreamContext.Current.GetParam("groupid");

            //Double decoding of name is done to work around a mod_proxy issue that strips out slashes
            groupid = XUri.Decode(groupid);
            if (groupid.StartsWith("="))
            {
                string name = groupid.Substring(1);
                g = GroupBL.GetGroupByName(name);
                if (g == null)
                {
                    throw new GroupNotFoundException(name);
                }
            }
            else
            {
                uint groupIdInt;
                if (!uint.TryParse(groupid, out groupIdInt))
                {
                    throw new GroupIdInvalidArgumentException();
                }
                g = GroupBL.GetGroupById(groupIdInt);
                if (g == null)
                {
                    throw new GroupIdNotFoundException(groupIdInt);
                }
            }
            return(g);
        }
Exemplo n.º 4
0
        public Yield ProxyToService(DreamContext context, DreamMessage request, Result <DreamMessage> response)
        {
            PermissionsBL.IsUserAllowed(DekiContext.Current.User, Permissions.ADMIN);

            //Private feature requires api-key
            var identifier = context.GetParam("id");

            ServiceRepository.IServiceInfo serviceInfo = null;
            if (identifier.StartsWith("="))
            {
                serviceInfo = DekiContext.Current.Instance.RunningServices[XUri.Decode(identifier.Substring(1))];
            }
            else
            {
                uint serviceId;
                if (uint.TryParse(identifier, out serviceId))
                {
                    serviceInfo = DekiContext.Current.Instance.RunningServices[serviceId];
                }
                else
                {
                    throw new DreamBadRequestException(string.Format("Invalid id '{0}'", identifier));
                }
            }
            if (serviceInfo == null)
            {
                throw new ServiceNotFoundException(identifier);
            }
            var proxyUri = serviceInfo.ServiceUri.At(context.GetSuffixes(UriPathFormat.Original).Skip(1).ToArray());

            yield return(context.Relay(Plug.New(proxyUri), request, response));
        }
Exemplo n.º 5
0
        public Yield GetServiceById(DreamContext context, DreamMessage request, Result <DreamMessage> response)
        {
            bool privateDetails = PermissionsBL.IsUserAllowed(DekiContext.Current.User, Permissions.ADMIN);

            //Private feature requires api-key
            var  identifier = context.GetParam("id");
            uint serviceId  = 0;

            if (identifier.StartsWith("="))
            {
                var serviceInfo = DekiContext.Current.Instance.RunningServices[XUri.Decode(identifier.Substring(1))];
                if (serviceInfo != null)
                {
                    serviceId = serviceInfo.ServiceId;
                }
            }
            else
            {
                if (!uint.TryParse(identifier, out serviceId))
                {
                    throw new DreamBadRequestException(string.Format("Invalid id '{0}'", identifier));
                }
            }
            ServiceBE service = ServiceBL.GetServiceById(serviceId);

            if (service == null)
            {
                throw new ServiceNotFoundException(identifier);
            }
            response.Return(DreamMessage.Ok(ServiceBL.GetServiceXmlVerbose(DekiContext.Current.Instance, service, null, privateDetails)));
            yield break;
        }
Exemplo n.º 6
0
        private UserBE GetUserFromUrl()
        {
            UserBE u      = null;
            string userid = DreamContext.Current.GetParam("userid");

            //Double decoding of name is done to work around a mod_proxy issue that strips out slashes
            userid = XUri.Decode(userid);
            if (StringUtil.EqualsInvariantIgnoreCase(userid.Trim(), "current"))
            {
                u = DekiContext.Current.User;
            }
            else if (userid.StartsWith("="))
            {
                string name = userid.Substring(1);
                u = DbUtils.CurrentSession.Users_GetByName(name);
            }
            else
            {
                uint userIdInt;
                if (!uint.TryParse(userid, out userIdInt))
                {
                    throw new UserIdInvalidArgumentException();
                }
                u = UserBL.GetUserById(userIdInt);
            }
            return(u);
        }
Exemplo n.º 7
0
        /// <summary>
        /// Get all suffixes.
        /// </summary>
        /// <param name="format">Uri path format for suffixes.</param>
        /// <returns>Array of suffixes.</returns>
        public string[] GetSuffixes(UriPathFormat format)
        {
            EnsureFeatureIsSet();
            string[] result = new string[_suffixes.Length];
            switch (format)
            {
            case UriPathFormat.Original:
                for (int i = 0; i < result.Length; ++i)
                {
                    result[i] = _suffixes[i];
                }
                break;

            case UriPathFormat.Decoded:
                for (int i = 0; i < result.Length; ++i)
                {
                    result[i] = XUri.Decode(_suffixes[i]);
                }
                break;

            case UriPathFormat.Normalized:
                for (int i = 0; i < result.Length; ++i)
                {
                    result[i] = XUri.Decode(_suffixes[i]).ToLowerInvariant();
                }
                break;

            default:
                throw new ArgumentException("format");
            }
            return(result);
        }
Exemplo n.º 8
0
        public Yield GetFile(DreamContext context, DreamMessage request, Result <DreamMessage> response)
        {
            if (_directoryInfo == null)
            {
                throw new DreamBadRequestException("folder is misconfigured");
            }

            // Extract the filename
            string filename = context.GetParam("filename", String.Empty);

            filename = XUri.Decode(filename);
            if (filename.Contains(".."))
            {
                response.Return(DreamMessage.Forbidden("Relative paths are not allowed"));
                yield break;
            }
            FileInfo currentFile = new FileInfo(_directoryInfo.FullName + Path.DirectorySeparatorChar + filename);

            // Retrieve the file
            DreamMessage message = GetFile(currentFile.FullName);

            message.Headers.ContentDisposition = new ContentDisposition(true, currentFile.CreationTimeUtc, currentFile.LastWriteTimeUtc, null, currentFile.Name, currentFile.Length);
            response.Return(message);
            yield break;
        }
Exemplo n.º 9
0
        /// <summary>
        /// Retrieves the user-friendly name of this title
        /// </summary>
        public static string AsUserFriendlyName(this Title title)
        {
            if (title.IsFile)
            {
                return(title.AppendFilenameQueryAnchor(String.Empty, false));
            }
            else
            {
                string result = title.AsPrefixedDbPath().Replace('_', ' ');
                if (!title.HasAnchor && !title.HasQuery)
                {
                    // Check if there is a translated name for the page
                    string resourceResult = title.GetTranslatedName();
                    if (resourceResult != null)
                    {
                        return(resourceResult);
                    }

                    // check if page has a display name (always the case for new pages after Olympic)
                    if (!string.IsNullOrEmpty(title.DisplayName))
                    {
                        return(title.DisplayName);
                    }
                }

                // replace '//' with '%2f' ('//' was used as encoding for '/' in titles)
                result = result.Trim('/').Replace("//", "%2f");

                // split path into segments
                string[] segments = result.Split('/');
                result = segments[segments.Length - 1];
                return(title.AppendFilenameQueryAnchor(XUri.Decode(result.Replace("%2f", "/")), false));
            }
        }
Exemplo n.º 10
0
        public Yield ExpandFolder(DreamContext context, DreamMessage request, Result <DreamMessage> response)
        {
            if (_directoryInfo == null)
            {
                throw new DreamBadRequestException("folder is misconfigured");
            }

            // Extract the folder to expand
            string foldername = context.GetParam("foldername", String.Empty);

            foldername = XUri.Decode(foldername);
            if (foldername.Contains(".."))
            {
                response.Return(DreamMessage.Forbidden("Relative paths are not allowed"));
                yield break;
            }

            // Extract the search pattern
            string pattern = context.GetParam("pattern", null);

            DirectoryInfo currentDirectory = new DirectoryInfo(_directoryInfo.FullName + Path.DirectorySeparatorChar + foldername);
            XDoc          result           = new XDoc("results");

            // If specified, retrieve all the directories under the current directory
            bool topDirectoryOnly = context.GetParam("topDirectoryOnly", false);

            if (!topDirectoryOnly)
            {
                foreach (DirectoryInfo directory in currentDirectory.GetDirectories())
                {
                    string encodedDirectoryName = XUri.DoubleEncodeSegment((foldername + Path.DirectorySeparatorChar + directory.Name).Replace("+", "%2b"));
                    XUri   dynamicExpandUri     = DreamContext.Current.AsPublicUri(Self.At("expand", encodedDirectoryName)).With("dream.out.format", "json");
                    if (null != pattern)
                    {
                        dynamicExpandUri = dynamicExpandUri.With("pattern", pattern);
                    }
                    result.Start("result").Elem("name", directory.Name).Elem("dynamicexpanduri", dynamicExpandUri.ToString()).End();
                }
            }

            // Retrieve files according to the search pattern
            FileInfo[] files;
            if (null != pattern)
            {
                files = currentDirectory.GetFiles(pattern, SearchOption.TopDirectoryOnly);
            }
            else
            {
                files = currentDirectory.GetFiles();
            }
            foreach (FileInfo file in files)
            {
                string encodedFileName = XUri.DoubleEncodeSegment((foldername + Path.DirectorySeparatorChar + file.Name).Replace("+", "%2b"));
                XUri   href            = DreamContext.Current.AsPublicUri(Self.At("doc", encodedFileName));
                result.Start("result").Elem("name", file.Name).Elem("href", href.ToString()).Elem("labelstyle", "iconitext-16 ext-" + file.Extension.TrimStart('.').ToLowerInvariant()).End();
            }

            response.Return(DreamMessage.Ok(result));
            yield break;
        }
Exemplo n.º 11
0
        //--- Methods ---

        /// <summary>
        /// Extract a list of suffixes and a dictionary of arguments from the request.
        /// </summary>
        /// <param name="uri">Request Uri.</param>
        /// <param name="suffixes">Extracted suffixes.</param>
        /// <param name="pathParams">Extracted path parameters.</param>
        public void ExtractArguments(XUri uri, out string[] suffixes, out Dictionary <string, string[]> pathParams)
        {
            Dictionary <string, List <string> > tmpPathParams = new Dictionary <string, List <string> >(StringComparer.OrdinalIgnoreCase);
            List <string> suffixesList = new List <string>(_paramNames.Length + (uri.Segments.Length - PathSegments.Length));

            for (int i = 0; i < _paramNames.Length; ++i)
            {
                string value = uri.Segments[_paramNames[i].Key];
                suffixesList.Add(value);
                List <string> values;
                if (!tmpPathParams.TryGetValue(_paramNames[i].Value, out values))
                {
                    values = new List <string>(1);
                    tmpPathParams.Add(_paramNames[i].Value, values);
                }
                values.Add(XUri.Decode(value));
            }
            pathParams = new Dictionary <string, string[]>(StringComparer.OrdinalIgnoreCase);
            foreach (KeyValuePair <string, List <string> > tmpPathParam in tmpPathParams)
            {
                pathParams.Add(tmpPathParam.Key, tmpPathParam.Value.ToArray());
            }
            for (int i = PathSegments.Length; i < uri.Segments.Length; ++i)
            {
                suffixesList.Add(uri.Segments[i]);
            }
            suffixes = suffixesList.ToArray();
        }
Exemplo n.º 12
0
        //--- Class Methods ---

        /// <summary>
        /// Retrieve user credentials from a request uri and/or headers.
        /// </summary>
        /// <param name="uri">Request uri.</param>
        /// <param name="headers">Request headers.</param>
        /// <param name="username">Parsed user name.</param>
        /// <param name="password">Parsed password.</param>
        /// <returns><see langword="True"/> if the credentials were succesfully parsed from request information.</returns>
        public static bool GetAuthentication(Uri uri, DreamHeaders headers, out string username, out string password)
        {
            username = null;
            password = null;

            // Authorization = Basic 1YJ1TTpPcmx4bMQ=

            // check if a user/password pair was provided in the URI
            if (!string.IsNullOrEmpty(uri.UserInfo))
            {
                string[] userPwd = uri.UserInfo.Split(new char[] { ':' }, 2);
                username = XUri.Decode(userPwd[0]);
                password = XUri.Decode((userPwd.Length > 1) ? userPwd[1] : string.Empty);
                return(true);
            }
            else
            {
                // check if authorization is in the request header
                string header = headers[DreamHeaders.AUTHORIZATION];
                if (!string.IsNullOrEmpty(header))
                {
                    // extract authorization data
                    string[] value = header.Split(new char[] { ' ' }, 2);
                    if ((value.Length == 2) && StringUtil.EqualsInvariantIgnoreCase(value[0], "Basic"))
                    {
                        string[] userPwd = Encoding.UTF8.GetString(Convert.FromBase64String(value[1])).Split(new char[] { ':' }, 2);
                        username = userPwd[0];
                        password = (userPwd.Length > 1) ? userPwd[1] : string.Empty;
                        return(true);
                    }
                }
            }
            return(false);
        }
Exemplo n.º 13
0
        /// <summary>
        /// Constructs a title from a ui uri segment (ui urls are items inserted by the editor or the user).  The ui uri is assumed to be url encoded.
        /// Ex. "index.php?title=User:Admin/MyPage", "User:Admin/MyPage", "File:User:Admin/MyPage/MyFile.jpg"
        /// </summary>
        public static Title FromUIUri(Title baseTitle, string uiUri, bool parseUri)
        {
            NS     ns;
            string filename = String.Empty;
            string query    = null;
            string anchor   = null;

            if (parseUri)
            {
                Match indexPhpMatch = INDEX_PHP_REGEX.Match(uiUri);
                if (indexPhpMatch.Success)
                {
                    uiUri = uiUri.Substring(indexPhpMatch.Length);
                    int amp = uiUri.IndexOf('&');
                    if (amp >= 0)
                    {
                        uiUri = uiUri.Substring(0, amp) + "?" + uiUri.Substring(amp + 1);
                    }
                }
                int anchorIndex = uiUri.IndexOf('#');
                if (0 <= anchorIndex && (anchorIndex + 1 <= uiUri.Length))
                {
                    anchor = uiUri.Substring(anchorIndex + 1);
                    uiUri  = uiUri.Substring(0, anchorIndex);
                    if (String.IsNullOrEmpty(uiUri.Trim()))
                    {
                        uiUri = "./";
                    }
                }
                int queryIndex = uiUri.IndexOf('?');
                if (0 <= queryIndex && (queryIndex + 1 < uiUri.Length))
                {
                    query = uiUri.Substring(queryIndex + 1);
                    uiUri = uiUri.Substring(0, queryIndex);
                }
            }
            string path = DbEncodePath(uiUri);

            StringToNSAndPath(baseTitle, path, out ns, out path);

            // if the url points to a file, extract the filename from it
            if (ns == NS.ATTACHMENT)
            {
                int filenameIndex = path.LastIndexOf('/');
                if (0 <= filenameIndex)
                {
                    filename = path.Substring(filenameIndex, path.Length - filenameIndex);
                    path     = path.Substring(0, filenameIndex);
                }
                else
                {
                    filename = path;
                    path     = String.Empty;
                }
                filename = XUri.Decode(filename.Trim('/'));
                StringToNSAndPath(baseTitle, path, out ns, out path);
            }
            return(FromDbPath(ns, path, null, filename, anchor, query));
        }
Exemplo n.º 14
0
        public void Decode_extended_chars4()
        {
            const string before  = "f%7Bb\u00FCb";
            const string after   = "f{b\u00FCb";
            var          decoded = XUri.Decode(before);

            Assert.AreEqual(after, decoded);
        }
Exemplo n.º 15
0
        public void Decode_extended_chars3()
        {
            const string before  = "+F\u00F4\u00F6";
            const string after   = " F\u00F4\u00F6";
            var          decoded = XUri.Decode(before);

            Assert.AreEqual(after, decoded);
        }
Exemplo n.º 16
0
        private static XDoc BuildHtmlSiteMap(PageBE current, XDoc doc, Dictionary <ulong, PageBE> allowedPagesById, Dictionary <ulong, PageBE> filteredPagesById, int depth, bool reverse)
        {
            doc.Start("li");
            string        uri         = Utils.AsPublicUiUri(current.Title);
            List <string> classValues = new List <string>();

            if (filteredPagesById.ContainsKey(current.ID))
            {
                classValues.Add("statusRestricted");
            }
            if (current.ID == DekiContext.Current.Instance.HomePageId)
            {
                classValues.Add("statusHome");
            }

            doc.Start("a").Attr("rel", "internal").Attr("href", uri).Attr("title", current.Title.AsPrefixedUserFriendlyPath()).Attr("pageid", current.ID);
            if (classValues.Count > 0)
            {
                doc.Attr("class", string.Join(" ", classValues.ToArray()));
            }
            doc.Value(current.Title.AsUserFriendlyName()).End();

            if (depth > 0 && !ArrayUtil.IsNullOrEmpty(current.ChildPages))
            {
                PageBE[] visibleChildren = Array.FindAll(current.ChildPages, delegate(PageBE child) {
                    return(allowedPagesById.ContainsKey(child.ID));
                });
                DreamContext context = DreamContext.CurrentOrNull;
                if (context != null)
                {
                    DekiContext deki    = DekiContext.CurrentOrNull;
                    CultureInfo culture = HttpUtil.GetCultureInfoFromHeader(current.Language ?? ((deki != null) ? deki.Instance.SiteLanguage : string.Empty), context.Culture);
                    string[]    paths   = new string[visibleChildren.Length];
                    for (int i = 0; i < visibleChildren.Length; ++i)
                    {
                        paths[i] = XUri.Decode(visibleChildren[i].Title.AsPrefixedDbPath()).Replace("//", "\uFFEF").Replace("/", "\t");
                    }
                    Array.Sort(paths, visibleChildren, new CompareInfoComparer(culture.CompareInfo));
                }
                if (visibleChildren.Length > 0)
                {
                    doc.Start("ul");
                    if (reverse)
                    {
                        Array.Reverse(visibleChildren);
                    }
                    foreach (PageBE p in visibleChildren)
                    {
                        doc = BuildHtmlSiteMap(p, doc, allowedPagesById, filteredPagesById, depth - 1, reverse);
                    }
                    doc.End();
                }
            }
            doc.End();
            return(doc);
        }
Exemplo n.º 17
0
 public static string AsPrefixedUserFriendlyPath(this Title title)
 {
     if (!title.IsFile && !title.HasAnchor && !title.HasQuery)
     {
         // this is a special/admin page, we check if there is a translated name for the page
         string resourceResult = title.GetTranslatedName();
         if (resourceResult != null)
         {
             return(resourceResult);
         }
     }
     return(title.AppendFilenameQueryAnchor(XUri.Decode(title.AsPrefixedDbPath()), false));
 }
Exemplo n.º 18
0
        public static string GetFilenameFromPathSegment(string filePathSegment)
        {
            string filename = null;

            if (filePathSegment.StartsWith("="))
            {
                filename = XUri.Decode(filePathSegment.Substring(1));
            }
            if (string.IsNullOrEmpty(filename))
            {
                throw new AttachmentMissingFilenameInvalidArgumentException();
            }
            return(filename);
        }
Exemplo n.º 19
0
 /// <summary>
 /// Constructs a title from the {pageid} parameter of a given API call.  The api param is assumed to be double url encoded.
 /// Ex.  =User:Admin%252fMyPage
 /// </summary>
 public static Title FromApiParam(string pageid)
 {
     if (pageid.StartsWith("="))
     {
         pageid = pageid.Substring(1);
         string path = DbEncodePath(XUri.Decode(pageid));
         return(FromPrefixedDbPath(path, null));
     }
     if (pageid.EqualsInvariantIgnoreCase("home"))
     {
         return(FromDbPath(NS.MAIN, String.Empty, null));
     }
     return(null);
 }
Exemplo n.º 20
0
        /// <summary>
        /// Retrieves the user-friendly display name of this title.
        /// Used to always build a display name, either from localized resources or the last segment in the path.
        /// </summary>
        public static string AsUserFriendlyDisplayName(this Title title)
        {
            string result = title.AsPrefixedDbPath().Replace('_', ' ');

            // Check if there is a translated name for the page
            string resourceResult = title.GetTranslatedName();

            if (resourceResult != null)
            {
                return(resourceResult);
            }

            // replace '//' with '%2f' ('//' was used as encoding for '/' in titles)
            result = result.Trim('/').Replace("//", "%2f");

            // split path into segments
            string[] segments = result.Split('/');
            result = segments[segments.Length - 1];
            return(title.AppendFilenameQueryAnchor(XUri.Decode(result.Replace("%2f", "/")), false));
        }
Exemplo n.º 21
0
        /// <summary>
        /// Get a suffix.
        /// </summary>
        /// <param name="index">Index of path suffix.</param>
        /// <param name="format">Uri path format.</param>
        /// <returns>Suffix.</returns>
        public string GetSuffix(int index, UriPathFormat format)
        {
            EnsureFeatureIsSet();
            string suffix = _suffixes[index];

            switch (format)
            {
            case UriPathFormat.Original:
                return(suffix);

            case UriPathFormat.Decoded:
                return(XUri.Decode(suffix));

            case UriPathFormat.Normalized:
                return(XUri.Decode(suffix).ToLowerInvariant());

            default:
                throw new ArgumentException("format");
            }
        }
Exemplo n.º 22
0
        /// <summary>
        /// Retrieves the title as a ui uri segment (ui urls can be used to access pages by pre-pending the ui host).  The output is db encoded.
        /// Ex. "index.php?title=User:Admin/MyPage", "User:Admin/MyPage"
        /// </summary>
        public string AsUiUriPath(bool forceUseIndexPhp)
        {
            string path;
            string dbPath = XUri.Decode(AsUnprefixedDbPath());

            if (forceUseIndexPhp)
            {
                path = INDEX_PHP_TITLE + AppendFilenameQueryAnchor(NSAndPathToString(Namespace, XUri.EncodeQuery(dbPath).Replace("+", "%2b")), true);
            }
            else
            {
                // returns the title in a wiki ui consumable form
                StringBuilder pathBuilder = new StringBuilder();
                string[]      segments    = AsDbSegments(dbPath);
                bool          useIndexPhp = false;
                foreach (string segment in segments)
                {
                    if (-1 < segment.IndexOfAny(INDEX_PHP_CHARS))
                    {
                        useIndexPhp = true;
                        break;
                    }
                    if (0 < pathBuilder.Length)
                    {
                        pathBuilder.Append("/");
                    }
                    pathBuilder.Append(XUri.EncodeSegment(segment));
                }
                if (useIndexPhp)
                {
                    path = INDEX_PHP_TITLE + AppendFilenameQueryAnchor(NSAndPathToString(Namespace, XUri.EncodeQuery(dbPath).Replace("+", "%2b")), true);
                }
                else
                {
                    path = AppendFilenameQueryAnchor(NSAndPathToString(Namespace, pathBuilder.ToString().Replace("?", "%3f")), false);
                }
            }

            // URL encode ?'s so they don't get confused for the query and add the filename, anchor and query
            return(path);
        }
Exemplo n.º 23
0
 /// <summary>
 /// Helper method to encode a given path in a database-friendly format
 /// </summary>
 public static string DbEncodePath(string path)
 {
     // encodes the specified path using the same format as the database
     path = XUri.Decode(path);
     path = path.ReplaceAll(
         "%", "%25",
         "[", "%5B",
         "]", "%5D",
         "{", "%7B",
         "}", "%7D",
         "|", "%7C",
         "+", "%2B",
         "<", "%3C",
         ">", "%3E",
         "#", "%23",
         "//", "%2F",
         " ", "_"
         );
     path = path.Trim(TRIM_CHARS).Replace("%2F", "//");
     return(path);
 }
Exemplo n.º 24
0
        public TagBE GetTagFromPathSegment(string tagPathSegment)
        {
            TagBE tag = null;
            uint  id  = 0;

            string tagId = tagPathSegment;

            if (uint.TryParse(tagId, out id))
            {
                tag = _session.Tags_GetById(id);
            }
            else
            {
                if (tagId.StartsWith("="))
                {
                    string prefixedName = tagId.Substring(1);
                    prefixedName = XUri.Decode(prefixedName);
                    TagBE tmpTag = ParseTag(prefixedName);
                    tag = _session.Tags_GetByNameAndType(tmpTag.Name, tmpTag.Type);
                }
            }
            if (tag != null)
            {
                IList <TagBE> tags = new List <TagBE>();
                tags.Add(tag);
                tags = FilterDisallowed(tags);
                if (tags.Count == 0)
                {
                    tag = null;
                }
            }
            if (tag == null)
            {
                throw new TagNotFoundException();
            }

            return(tag);
        }
Exemplo n.º 25
0
        private void MovePageStubs()
        {
            string rootPageName = string.Empty;

            //string rootPageName = CreateRootPageForExport();

            Log.Info("Retrieving all space information...");
            List <RemoteSpaceSummary> confluenceSpaces = new List <RemoteSpaceSummary>(_confluenceService.GetSpaces());

            //Sort spaces by keyname to help show progress of conversion
            confluenceSpaces.Sort(delegate(RemoteSpaceSummary s1, RemoteSpaceSummary s2) { return(string.Compare(s1.key, s2.key)); });

            foreach (RemoteSpaceSummary space in confluenceSpaces)
            {
                if (!_processPesonalSpaces && space.type == ConfluencePersonalSpaceTypeName)
                {
                    continue;
                }

                //NOTE (maxm): not sure why personal spaces are being processed even if
                // the _spacesToConvert is defined from configuration. Commented it out.
                if ((_spacesToConvert.Count > 0)
                    /*&& (space.type != ConfluencePersonalSpaceTypeName)*/ &&
                    (!_spacesToConvert.Contains(space.key.ToLower())))
                {
                    continue;
                }

                Log.DebugFormat("Retrieving top pages for {0} space '{1}' ({2})", space.type, space.key, space.name);
                RemotePageSummary[] confluenceRemoteTopPages = _confluenceService.GetTopLevelPages(space.key);

                if (confluenceRemoteTopPages.Length == 0)
                {
                    Log.WarnFormat("space '{0}' has 0 top level pages!", confluenceRemoteTopPages.Length);
                }

                //Get teamlabel for the space to be utilized in location management
                string spaceTeamLabel = "";
                if (_rpcclient != null)
                {
                    Log.DebugFormat("Retrieving team label for space '{0}'", space.key);
                    spaceTeamLabel = GetValidTeamLabel(space.key);
                }

                //Restore manifest from disk
                XDoc spaceManifest = GetManifestFromDisk(space.key) ?? new XDoc("manifest");

                //Compute the location for the root page of the space
                string spaceRootPath = ComputeSpaceRootPath(rootPageName, space, spaceTeamLabel);

                try {
                    //Create page for the space root
                    CreateDekiPage(_dekiPlug, spaceRootPath, space.name, DateTime.Now, DefaultSpaceContents);

                    //Pages within the root are processed recursively starting with the root pages.
                    foreach (RemotePageSummary remotePageSummary in confluenceRemoteTopPages)
                    {
                        MovePageStubs(spaceManifest, spaceRootPath, spaceRootPath, remotePageSummary, Utils.DoubleUrlEncode(remotePageSummary.title),
                                      remotePageSummary.title, null);
                    }

                    //Log root page of space
                    LogSpaceConversion(spaceManifest, space.key, space.url, XUri.Decode(spaceRootPath));

                    MoveNewsPagesWithoutContent(spaceManifest, space.key, spaceRootPath);
                } catch (Exception x) {
                    Log.Error("Error during stub creation", x);
                } finally {
                    //Save the space manifest to disk
                    PersistManifestToDisk(space.key, spaceManifest);
                }
            }
        }
Exemplo n.º 26
0
        /// <summary>
        /// Render Basic Authentication value.
        /// </summary>
        /// <param name="username">User name.</param>
        /// <param name="password">Password.</param>
        /// <returns>Basic Authentication string.</returns>
        public static string RenderBasicAuthentication(string username, string password)
        {
            string credentials = XUri.Decode(username ?? string.Empty) + ":" + XUri.Decode(password ?? string.Empty);

            return(Convert.ToBase64String(Encoding.UTF8.GetBytes(credentials)));
        }
Exemplo n.º 27
0
        //--- Class Methods ---
        public static bool TryParse(string source, out XDataUri uri)
        {
            if (string.IsNullOrEmpty(source))
            {
                uri = null;
                return(false);
            }

            // check if source starts with "data:"
            if (!source.StartsWithInvariantIgnoreCase(DATA_SCHEME))
            {
                uri = null;
                return(false);
            }

            // check if source contains a comma
            var comma = source.IndexOf(",", DATA_SCHEME.Length, StringComparison.Ordinal);

            if (comma < 0)
            {
                uri = null;
                return(false);
            }

            // parse key-value pairs between scheme and comma
            string mime    = null;
            string charset = null;
            var    base64  = false;
            var    temp    = source.Substring(DATA_SCHEME.Length, comma - DATA_SCHEME.Length);

            foreach (var header in temp.Split(';'))
            {
                var    equal = header.IndexOfInvariant("=");
                string name;
                string value;
                if (equal == -1)
                {
                    name  = string.IsNullOrEmpty(mime) ? "mime" : "base64";
                    value = XUri.Decode(header).Trim();
                }
                else
                {
                    name  = XUri.Decode(header.Substring(0, equal)).Trim();
                    value = XUri.Decode(header.Substring(equal + 1)).Trim();
                }
                switch (name.ToLowerInvariant())
                {
                case "mime":
                    mime = value;
                    break;

                case "charset":
                    charset = value;
                    break;

                case "base64":
                    base64 = value.EqualsInvariantIgnoreCase(BASE64_ENCODING);
                    break;

                default:

                    // NOTE (steveb): we're ignoring additional meta-data since it's not useful for our use case
                    break;
                }
            }

            // compute mime-type
            var mimeType = MimeType.TEXT;

            if (!string.IsNullOrEmpty(mime))
            {
                mimeType = !string.IsNullOrEmpty(charset) ? new MimeType(string.Format("{0};charset={1}", mime, charset)) : new MimeType(mime);
            }

            // create data uri wrapper
            uri = new XDataUri {
                MimeType = mimeType,
                Base64   = base64
            };
            return(true);
        }
 public static string UriDecode(
     [DekiScriptParam("text to decode")] string text
     )
 {
     return(XUri.Decode(text));
 }