Example #1
0
        public Yield GetUsers(DreamContext context, DreamMessage request, Result <DreamMessage> response)
        {
            // TODO (steveb): add 'emailfilter' and use it to obsolete 'usernameemailfilter'; 'usernamefilter', 'fullnamefilter', and 'emailfilter'
            //                should be OR'ed together when they are present.

            PermissionsBL.CheckUserAllowed(DekiContext.Current.User, Permissions.READ);
            uint totalCount;
            uint queryCount;
            var  users  = UserBL.GetUsersByQuery(context, null, out totalCount, out queryCount);
            XDoc result = new XDoc("users");

            result.Attr("count", users.Count());
            result.Attr("querycount", queryCount);
            result.Attr("totalcount", totalCount);
            result.Attr("href", DekiContext.Current.ApiUri.At("users"));
            bool verbose = context.GetParam <bool>("verbose", true);

            foreach (UserBE u in users)
            {
                if (verbose)
                {
                    result.Add(UserBL.GetUserXmlVerbose(u, null, Utils.ShowPrivateUserInfo(u), true, true));
                }
                else
                {
                    result.Add(UserBL.GetUserXml(u, null, Utils.ShowPrivateUserInfo(u)));
                }
            }
            response.Return(DreamMessage.Ok(result));
            yield break;
        }
Example #2
0
        private IEnumerable <XDoc> YieldAll(int limit, int offset)
        {
            var docResults = new List <QueryItem>();

            _catalog.NewQuery(string.Format("SELECT id, revision, doc FROM {0} ORDER BY {0}.id{1}", _name, GetLimitAndOffsetClause(limit, offset)))
            .Execute(delegate(IDataReader dr) {
                while (dr.Read())
                {
                    var docResult = new QueryItem {
                        Id       = dr.GetInt32(0),
                        Revision = dr.GetInt32(1),
                        Doc      = dr.GetString(2)
                    };
                    docResults.Add(docResult);
                }
            });
            foreach (var docResult in docResults)
            {
                XDoc doc = XDocFactory.From(docResult.Doc, MimeType.TEXT_XML);
                Map(doc);
                doc.Attr("docstore:revision", docResult.Revision);
                doc.Attr("docstore:id", docResult.Id);
                yield return(doc);
            }
        }
Example #3
0
        public void WriteConfig()
        {
            XDoc exportDocument = new XDoc("config")
                                  .Attr("archive", Archive)
                                  .Add(ExportDocument);

            switch (Mode)
            {
            case Mode.Export:
                exportDocument.Attr("export", true);
                break;

            case Mode.Copy:
                exportDocument.Attr("copy", true);
                break;
            }
            if (DekiApi != null)
            {
                exportDocument.Attr("uri", DekiApi.Uri);
            }
            if (!string.IsNullOrEmpty(User))
            {
                exportDocument.Attr("user", User);
            }
            if (!string.IsNullOrEmpty(Password))
            {
                exportDocument.Attr("password", Password);
            }
            if (!string.IsNullOrEmpty(AuthToken))
            {
                exportDocument.Attr("authtoken", AuthToken);
            }
            if (!string.IsNullOrEmpty(FilePath))
            {
                exportDocument.Elem("target", FilePath);
            }
            if (Mode != Import.Mode.Export && !string.IsNullOrEmpty(ImportReltoPath))
            {
                exportDocument.Attr("importreltopath", ImportReltoPath);
            }
            if (Mode != Import.Mode.Import && !string.IsNullOrEmpty(ExportReltoPath))
            {
                exportDocument.Attr("exportreltopath", ExportReltoPath);
            }
            if (ImportRelto.HasValue)
            {
                exportDocument.Attr("importrelto", ImportRelto.Value);
            }
            if (ExportRelto.HasValue)
            {
                exportDocument.Attr("exportrelto", ExportRelto.Value);
            }
            string dir = Path.GetDirectoryName(Path.GetFullPath(_genConfigPath));

            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }
            exportDocument.Save(_genConfigPath);
        }
Example #4
0
        /// <summary>
        /// Query the collection based on an indexed key in the document.
        /// </summary>
        /// <param name="keyName">Name of the index key.</param>
        /// <param name="keyValue">Value of the key.</param>
        /// <param name="offset">Offset into collection.</param>
        /// <param name="limit">Maximum number of documents to retrieve.</param>
        /// <returns>Enumerable of matching documents.</returns>
        public IEnumerable <XDoc> Get(string keyName, string keyValue, int offset, int limit)
        {
            var info = _indexer.GetIndexInfo(keyName);

            if (info == null)
            {
                throw new ArgumentException(string.Format("No key '{0}' defined", keyName), "keyName");
            }
            var docs = new List <XDoc>();

            _catalog.NewQuery(string.Format("SELECT id, revision, doc FROM {0} LEFT JOIN {1} ON {0}.id = {1}.ref_id WHERE {1}.idx_value = ?KEY ORDER BY {0}.id{2}",
                                            _name, info.Table, GetLimitAndOffsetClause(limit, offset)))
            .With("KEY", keyValue)
            .Execute(delegate(IDataReader reader) {
                while (reader.Read())
                {
                    XDoc doc = XDocFactory.From(reader.GetString(2), MimeType.TEXT_XML);
                    Map(doc);
                    foreach (XDoc match in doc[info.XPath])
                    {
                        if (StringUtil.EqualsInvariant(match.AsText, keyValue))
                        {
                            int id       = reader.GetInt32(0);
                            int revision = reader.GetInt32(1);
                            doc.Attr("docstore:revision", revision);
                            doc.Attr("docstore:id", id);
                            docs.Add(doc);
                            break;
                        }
                    }
                }
            });
            return(docs);
        }
        public Yield GetGroupUsers(DreamContext context, DreamMessage request, Result <DreamMessage> response)
        {
            PermissionsBL.CheckUserAllowed(DekiContext.Current.User, Permissions.READ);
            GroupBE      group       = GetGroupFromUrl();
            DreamMessage responseMsg = null;

            uint totalCount;
            uint queryCount;
            var  usersInGroup = UserBL.GetUsersByQuery(context, group.Id, out totalCount, out queryCount);

            XDoc ret = new XDoc("users");

            ret.Attr("count", usersInGroup.Count());
            ret.Attr("querycount", queryCount);
            ret.Attr("totalcount", totalCount);
            ret.Attr("href", DekiContext.Current.ApiUri.At("groups", group.Id.ToString(), "users"));

            foreach (UserBE member in usersInGroup)
            {
                ret.Add(UserBL.GetUserXml(member, null, Utils.ShowPrivateUserInfo(member)));
            }

            responseMsg = DreamMessage.Ok(ret);

            response.Return(responseMsg);
            yield break;
        }
Example #6
0
        public static XDoc GetGroupXmlVerbose(GroupBE group, string relation)
        {
            XDoc groupXml = GetGroupXml(group, relation);

            ServiceBE authService = ServiceBL.GetServiceById(group.ServiceId);

            if (authService != null)
            {
                groupXml.Add(ServiceBL.GetServiceXml(authService, "authentication"));
            }

            groupXml.Start("users");
            if (group.UserIdsList != null)
            {
                groupXml.Attr("count", group.UserIdsList.Length);
            }

            groupXml.Attr("href", DekiContext.Current.ApiUri.At("groups", group.Id.ToString(), "users"));
            groupXml.End();

            //Permissions for the group
            RoleBE role = PermissionsBL.GetRoleById(group.RoleId);

            groupXml.Add(PermissionsBL.GetRoleXml(role, "group"));
            return(groupXml);
        }
Example #7
0
        public XDoc GetAttachmentRevisionListXml(IList <ResourceBE> fileList, XUri href)
        {
            XDoc attachmentListDoc = null;

            attachmentListDoc = new XDoc("files");
            attachmentListDoc.Attr("count", fileList == null ? 0 : fileList.Count);
            if (href != null)
            {
                attachmentListDoc.Attr("href", href);
            }

            if (fileList != null)
            {
                List <ResourceBE> sortedFiles = new List <ResourceBE>(fileList);
                sortedFiles = SortFileListByNameAndRevision(sortedFiles);

                //HACK: Convenient place to ensure all images that haven't been identified are looked at
                IdentifyUnknownImages(sortedFiles);

                //Add attachment info to list wrapper xml
                foreach (ResourceBE att in sortedFiles)
                {
                    attachmentListDoc.Add(GetFileXml(att, true, null, null));
                }
            }

            return(attachmentListDoc);
        }
Example #8
0
        private static XDoc AppendBanXml(XDoc doc, BanBE ban)
        {
            UserBE createdBy = UserBL.GetUserById(ban.ByUserId);

            doc.Attr("id", ban.Id);
            doc.Attr("href", DekiContext.Current.ApiUri.At("site", "bans", ban.Id.ToString()));
            if (createdBy != null)
            {
                doc.Add(UserBL.GetUserXml(createdBy, "createdby", Utils.ShowPrivateUserInfo(createdBy)));
            }
            doc.Elem("date.modified", ban.LastEdit);
            doc.Elem("description", ban.Reason);
            doc.Elem("date.expires", ban.Expires);
            doc.Add(PermissionsBL.GetPermissionXml(ban.RevokeMask, "revoked"));
            doc.Start("ban.addresses");
            if (ban.BanAddresses != null)
            {
                foreach (string address in ban.BanAddresses)
                {
                    doc.Elem("address", address);
                }
            }
            doc.End();
            doc.Start("ban.users");
            if (ban.BanUserIds != null)
            {
                var banUsers = DbUtils.CurrentSession.Users_GetByIds(ban.BanUserIds);
                foreach (UserBE u in banUsers)
                {
                    doc.Add(UserBL.GetUserXml(u, null, Utils.ShowPrivateUserInfo(createdBy)));
                }
            }
            doc.End();
            return(doc);
        }
Example #9
0
        public XDoc GetTagXml(TagBE tag, bool showPages, string pageFilterLanguage)
        {
            string uriText = null, titleText = null;

            switch (tag.Type)
            {
            case TagType.DEFINE:
                uriText   = Utils.AsPublicUiUri(tag.DefinedTo.Title);
                titleText = tag.Name;
                break;

            case TagType.DATE:
                uriText = _dekiContext.UiUri.Uri.AtPath("Special:Events").With("from", tag.Name).ToString();
                DateTime date = DateTime.ParseExact(tag.Name, "yyyy-MM-dd", _culture, DateTimeStyles.None);
                titleText = date.ToString("D", _culture);
                break;

            case TagType.TEXT:
                if (null != tag.DefinedTo)
                {
                    uriText = Utils.AsPublicUiUri(tag.DefinedTo.Title);
                }
                else
                {
                    uriText = _dekiContext.UiUri.AtPath("Special:Tags").With("tag", tag.Name).ToString();
                }
                titleText = tag.Name;
                break;
            }
            XDoc result = new XDoc("tag");

            result.Attr("value", tag.PrefixedName);
            result.Attr("id", tag.Id);
            result.Attr("href", _dekiContext.ApiUri.At("site", "tags", tag.Id.ToString()).ToString());
            if (tag.OccuranceCount > 0)
            {
                result.Attr("count", tag.OccuranceCount);
            }

            result.Elem("type", tag.Type.ToString().ToLowerInvariant());
            result.Elem("uri", uriText);
            result.Elem("title", titleText);
            if (null != tag.RelatedPages)
            {
                result.Add(PageBL.GetPageListXml(tag.RelatedPages, "related"));
            }

            if (showPages)
            {
                IList <PageBE> pages = GetTaggedPages(tag);
                if (pageFilterLanguage != null)
                {
                    // filter pages by language
                    pages = (from page in pages where page.Language == pageFilterLanguage select page).ToList();
                }
                result.Add(PageBL.GetPageListXml(pages, "pages"));
            }
            return(result);
        }
Example #10
0
        public static XDoc ConvertFromXSpan(XDoc xspanWidget)
        {
            XDoc data = XDoc.FromXSpan(xspanWidget);

            data.Attr("id", xspanWidget["@widgetid"].Contents);
            data.Attr("type", xspanWidget["@widgettype"].Contents);
            return(data);
        }
Example #11
0
        public static XDoc GetServiceXml(ServiceBE service, string relation)
        {
            XDoc serviceXml = new XDoc(string.IsNullOrEmpty(relation) ? "service" : "service." + relation);

            serviceXml.Attr("id", service.Id);
            serviceXml.Attr("href", DekiContext.Current.ApiUri.At("site", "services", service.Id.ToString()));
            return(serviceXml);
        }
        public XDoc SlideShow(
            [DekiExtParam("list of image URIs")] ArrayList uris,
            [DekiExtParam("slideshow width (default: 300px)", true)] float?width,
            [DekiExtParam("slideshow height (default: 300px)", true)] float?height,
            [DekiExtParam("interval in seconds (default: 5.0)", true)] double?interval,
            [DekiExtParam("slideshow effect; one of {slideright, slideleft, slideup, squeezeleft, squeezeright, squeezeup, squeezedown, fadeout} (default: 'fadeout')", true)] string effect
            )
        {
            // convert URIs to XUri objects
            XUri[] xuris = new XUri[uris.Count];
            for (int i = 0; i < uris.Count; ++i)
            {
                xuris[i] = SysUtil.ChangeType <XUri>(uris[i]);
                if (xuris[i] == null)
                {
                    throw new ArgumentNullException(string.Format("entry {0} is null", i));
                }
            }

            // create response document
            string id     = "_" + StringUtil.CreateAlphaNumericKey(8);
            XDoc   result = new XDoc("html")
                            .Start("head")
                            .Start("link").Attr("type", "text/css").Attr("rel", "stylesheet").Attr("href", Files.At("slideshow.css")).End()
                            .Start("script").Attr("type", "text/javascript").Attr("src", Files.At("slideshow.js")).End()
                            .End();

            result.Start("body")
            .Start("div").Attr("id", id).Attr("class", "yui-sldshw-displayer").Attr("style", string.Format("width:{0};height:{1};", AsSize(width ?? 300), AsSize(height ?? 300)));

            // add each image
            int counter = 0;

            foreach (XUri uri in xuris)
            {
                ++counter;
                result.Start("img");
                result.Attr("id", id + counter);
                if (counter == 1)
                {
                    result.Attr("class", "yui-sldshw-active yui-sldshw-frame");
                }
                else
                {
                    result.Attr("class", "yui-sldshw-cached yui-sldshw-frame");
                }
                result.Attr("src", uri).Attr("onclick", string.Format("{0}.transition();", id)).End();
            }
            result.End().End();

            // add code to kick star the slideshow
            result.Start("tail")
            .Start("script").Attr("type", "text/javascript")
            .Value(string.Format("var {0} = new YAHOO.myowndb.slideshow('{0}', {{ interval: {1}, effect: YAHOO.myowndb.slideshow.effects.{2} }}); {0}.loop();", id, (int)((interval ?? 5.0) * 1000), (effect ?? "fadeOut").ToLowerInvariant()))
            .End();
            result.End();
            return(result);
        }
Example #13
0
        public static XDoc GetGroupXml(GroupBE group, string relation)
        {
            XDoc groupXml = new XDoc(string.IsNullOrEmpty(relation) ? "group" : "group." + relation);

            groupXml.Attr("id", group.Id);
            groupXml.Attr("href", DekiContext.Current.ApiUri.At("groups", group.Id.ToString()));
            groupXml.Start("groupname").Value(group.Name).End();

            return(groupXml);
        }
Example #14
0
 public void LogSpaceConversion(XDoc spaceManifest, string space, string confUrl, string mtPath) {
     string xpath = string.Format("space[@space='{0}']", space);
     XDoc spaceXml = spaceManifest[xpath];
     
     if(spaceXml.IsEmpty) {
         spaceManifest.Start("url");
         spaceManifest.Attr("space", space);
         spaceManifest.Attr("c.path", Utils.GetUrlLocalUri(_confBaseUrl, confUrl, false, false));
         spaceManifest.Attr("mt.path", mtPath);
         spaceManifest.End();
     }
 }
Example #15
0
        private XDoc GetFileXml(IList <ResourceBE> files, bool verbose, bool list, string fileSuffix, bool?explicitRevisionInfo, int?totalCount, XUri listUri)
        {
            Dictionary <uint, UserBE>  users = new Dictionary <uint, UserBE>();
            Dictionary <ulong, PageBE> pages = new Dictionary <ulong, PageBE>();
            List <uint> parentIds            = new List <uint>();

            //Collect related entity id's
            foreach (ResourceBE f in files)
            {
                users[f.UserId]             = null;
                pages[f.ParentPageId.Value] = null;
                parentIds.Add(f.ResourceId);
            }

            //Perform batch lookups of related entities
            users = _session.Users_GetByIds(users.Keys.ToArray()).AsHash(e => e.ID);
            if (verbose)
            {
                pages = PageBL.GetPagesByIdsPreserveOrder(pages.Keys.ToArray()).AsHash(e => e.ID);
            }

            //Associate properties with the given attachments
            files = _resourceBL.PopulateChildren(files.ToArray(), new[] { ResourceBE.Type.PROPERTY }, explicitRevisionInfo ?? false);

            XDoc ret = XDoc.Empty;

            if (list)
            {
                List <ResourceBE> sortedFiles = new List <ResourceBE>(files);
                files = SortFileListByNameAndRevision(sortedFiles).ToArray();
                ret   = new XDoc(string.IsNullOrEmpty(fileSuffix) ? "files" : "files." + fileSuffix);
                ret.Attr("count", files.Count);
                if (totalCount != null)
                {
                    ret.Attr("totalcount", totalCount.Value);
                }
                if (listUri != null)
                {
                    ret.Attr("href", listUri);
                }
            }
            foreach (ResourceBE f in files)
            {
                UserBE updatedByUser;
                PageBE parentPage;
                users.TryGetValue(f.UserId, out updatedByUser);
                pages.TryGetValue(f.ParentPageId.Value, out parentPage);
                ret = AppendFileXml(ret, f, fileSuffix, explicitRevisionInfo, updatedByUser, parentPage);
            }

            return(ret);
        }
Example #16
0
 public void AppendXml(XDoc doc)
 {
     doc.Start("param").Attr("name", Name).Attr("type", DekiScriptLiteral.AsScriptTypeName(ScriptType));
     if (Default.IsNil)
     {
         doc.Attr("optional", Optional ? "true" : null);
     }
     else
     {
         doc.Attr("default", Default.ToString());
     }
     doc.Value(Hint);
     doc.End();
 }
Example #17
0
        public void LogSpaceConversion(XDoc spaceManifest, string space, string confUrl, string mtPath)
        {
            string xpath    = string.Format("space[@space='{0}']", space);
            XDoc   spaceXml = spaceManifest[xpath];

            if (spaceXml.IsEmpty)
            {
                spaceManifest.Start("url");
                spaceManifest.Attr("space", space);
                spaceManifest.Attr("c.path", Utils.GetUrlLocalUri(_confBaseUrl, confUrl, false, false));
                spaceManifest.Attr("mt.path", mtPath);
                spaceManifest.End();
            }
        }
Example #18
0
        public void LogCommentConversion(XDoc spaceManifest, string space, RemoteComment comment, string mtPath) {
            string xpath = string.Format("comment[@c.commentid='{0}']", comment.id);
            XDoc commentXml = spaceManifest[xpath];

            if(commentXml.IsEmpty) {
                spaceManifest.Start("comment");
                spaceManifest.Attr("c.space", space);
                spaceManifest.Attr("c.commentid", comment.id);
                spaceManifest.Attr("c.pageid", comment.pageId);
                spaceManifest.Attr("c.path", Utils.GetUrlLocalUri(_confBaseUrl, comment.url, true, false));
                spaceManifest.Attr("mt.path", mtPath);
                spaceManifest.End();
            }
        }
Example #19
0
        public static XDoc GetUserMetricsXml(UserBE user)
        {
            var metrics = DbUtils.CurrentSession.Users_GetUserMetrics(user.ID);
            var ret     = new XDoc("metrics");

            ret.Attr("user.id", user.ID);
            ret.Attr("href", DekiContext.Current.ApiUri.At("users", user.ID.ToString(), "metrics"));
            ret.Elem("metric.comments", metrics.CommentPosts);
            ret.Elem("metric.pages-created", metrics.PagesCreated);
            ret.Elem("metric.pages-edited", metrics.PagesChanged);
            ret.Elem("metric.files-added", metrics.FilesUploaded);
            ret.Elem("metric.ratings-up", metrics.UpRatings);
            ret.Elem("metric.ratings-down", metrics.DownRatings);
            return(ret);
        }
Example #20
0
 private static void EnsureAttribute(XDoc doc, string attr, string def)
 {
     if (doc["@" + attr].IsEmpty)
     {
         doc.Attr(attr, def);
     }
 }
Example #21
0
        public void LogCommentConversion(XDoc spaceManifest, string space, RemoteComment comment, string mtPath)
        {
            string xpath      = string.Format("comment[@c.commentid='{0}']", comment.id);
            XDoc   commentXml = spaceManifest[xpath];

            if (commentXml.IsEmpty)
            {
                spaceManifest.Start("comment");
                spaceManifest.Attr("c.space", space);
                spaceManifest.Attr("c.commentid", comment.id);
                spaceManifest.Attr("c.pageid", comment.pageId);
                spaceManifest.Attr("c.path", Utils.GetUrlLocalUri(_confBaseUrl, comment.url, true, false));
                spaceManifest.Attr("mt.path", mtPath);
                spaceManifest.End();
            }
        }
Example #22
0
        public void LogUserConversion(XDoc spaceManifest, string confUserName, string mtUserId, string mtUserName, string confUserUrl)
        {
            string xpath   = string.Format("user[@c.username='******']", confUserName);
            XDoc   userXml = spaceManifest[xpath];

            if (userXml.IsEmpty)
            {
                spaceManifest.Start("user");
                spaceManifest.Attr("c.username", confUserName);
                spaceManifest.Attr("mt.userid", mtUserId);
                spaceManifest.Attr("mt.username", mtUserName);
                spaceManifest.Attr("c.path", Utils.GetUrlLocalUri(_confBaseUrl, confUserUrl, false, true));
                spaceManifest.Attr("mt.path", Utils.GetDekiUserPageByUserName(mtUserName));
                spaceManifest.End();
            }
        }
Example #23
0
        private void BuildResultXmlFragment(XDoc doc, LoggedSearchResultBE pick)
        {
            doc.Attr("type", pick.Type.ToString().ToLower())
            .Elem("date.selected", pick.Created)
            .Start("page")
            .Attr("id", pick.PageId)
            .Attr("href", _apiUri.At("pages", pick.PageId.ToString()).AsPublicUri())
            .End();
            switch (pick.Type)
            {
            case SearchResultType.File:
                doc.Start("file")
                .Attr("id", pick.TypeId)
                .Attr("href", _apiUri.At("files", pick.TypeId.ToString(), "info").AsPublicUri())
                .End();
                break;

            case SearchResultType.Comment:
                doc.Start("comment")
                .Attr("id", pick.TypeId)
                .Attr("href", _apiUri.At("comments", pick.TypeId.ToString()).AsPublicUri())
                .End();
                break;
            }
        }
Example #24
0
        private void InsertRecord(DirectoryRecord record)
        {
            // add value to directory
            lock (_directory) {
                _directory[record.Name] = record;
            }

            // check if value has an expiration time
            if (record.HasExpiration)
            {
                TimerFactory.New(record.Expiration, OnExpire, record.Name, TaskEnv.New());
            }

            SaveToFileSystem(record.Name, record.Value);

            // notify event channel
            XDoc notify = new XDoc("insert").Attr("name", record.Name);

            if (record.HasExpiration)
            {
                notify.Attr("expire", record.Expiration);
            }
            notify.Add(record.Value);
            _events.Post(notify, new Result <DreamMessage>(TimeSpan.MaxValue));
        }
Example #25
0
        private static void WriteXSpan(XmlNode node, XDoc output)
        {
            switch (node.NodeType)
            {
            case XmlNodeType.Document:
                WriteXSpan(((XmlDocument)node).DocumentElement, output);
                break;

            case XmlNodeType.Element:
                XDoc childOutput = output.Start("span");
                childOutput.Attr("class", node.Name);
                foreach (XmlNode attr in node.Attributes)
                {
                    output.Attr("xml:" + attr.Name, attr.Value);
                }
                foreach (XmlNode child in node.ChildNodes)
                {
                    WriteXSpan(child, output);
                }
                output.End();
                break;

            case XmlNodeType.Text:
                output.Value(node.Value);
                break;
            }
        }
Example #26
0
 static void AddFile(attachments attachment, XDoc doc, bool wrap)
 {
     if (wrap)
     {
         doc.Start("file");
     }
     doc
     .Attr("id", attachment.ID.ToString())
     .Attr("page", attachment.From.ToString())
     .Start("full-name").Value(attachment.GetFullName()).End()
     .Start("name").Value(attachment.Name).End()
     .Start("extension").Value(attachment.Extension).End()
     .Start("filename").Value(attachment.FileName).End()
     .Start("description").Value(attachment.Description).End()
     .Start("size").Value(attachment.FileSize.ToString()).End()
     .Start("type").Value(attachment.FileType).End()
     .Start("timestamp").Value(attachment.TimeStamp).End()
     .Start("user").Value(attachment.UserText).End();
     if (attachment.Removed != DateTime.MinValue)
     {
         doc.Start("removed").Value(attachment.Removed).End()
         .Start("removed-by").Value(attachment.RemovedByText).End();
     }
     if (wrap)
     {
         doc.End();
     }
 }
Example #27
0
        internal static XDoc ExecuteFork(Plug env, DreamHeaders headers, XDoc fork)
        {
            // execute script commands
            XDoc   reply = new XDoc("results");
            string ID    = fork["@ID"].Contents;

            if (!string.IsNullOrEmpty(ID))
            {
                reply.Attr("ID", ID);
            }

            // TODO (steveb): we should use a 'fixed capacity' cue which marks itself as done when 'count' is reached

            XDoc forks = fork.Elements;

            foreach (XDoc cmd in forks)
            {
                // TODO (steveb): we should be doing this in parallel, not sequentially!

                try {
                    reply.Add(ExecuteCommand(env, headers, cmd));
                } catch (Exception e) {
                    reply.Add(new XException(e));
                }
            }
            return(reply);
        }
 //--- Methods ---
 public XDoc ToXml(XUri uri) {
     XDoc result = new XDoc("function");
     result.Attr("transform", Transform);
     if(IsProperty) {
         result.Attr("usage", "property");
     }
     result.Elem("name", Name);
     result.Elem("uri", uri);
     result.Elem("description", Description);
     if(Access != DreamAccess.Public) {
         result.Elem("access", Access.ToString().ToLowerInvariant());
     }
     foreach(DekiScriptParameter param in Parameters) {
         param.AppendXml(result);
     }
     result.Start("return").Attr("type", DekiScriptLiteral.AsScriptTypeName(ReturnType)).End();
     return result;
 }
Example #29
0
        public Yield GetGroups(DreamContext context, DreamMessage request, Result<DreamMessage> response) {
            PermissionsBL.CheckUserAllowed(DekiContext.Current.User, Permissions.READ);
            uint totalCount, queryCount;
            IList<GroupBE> groups = GroupBL.GetGroupsByQuery(context, out totalCount, out queryCount);

            XDoc result = new XDoc("groups");
            result.Attr("count", groups.Count);
            result.Attr("querycount", queryCount);
            result.Attr("totalcount", totalCount);
            result.Attr("href", DekiContext.Current.ApiUri.At("groups"));

            foreach(GroupBE g in groups) {
                result.Add(GroupBL.GetGroupXmlVerbose(g, null));
            }

            response.Return(DreamMessage.Ok(result));
            yield break;
        }
Example #30
0
 //--- Methods ---
 public XDoc ToXml() {
     XDoc result = new XDoc("group");
     result.Attr("name", Name);
     if(HasCustom) {
         foreach(KeyValuePair<string, string> custom in ArrayUtil.AllKeyValues(Custom)) {
             result.Elem(custom.Key, custom.Value);
         }
     }
     return result;
 }
        public Yield GetServices(DreamContext context, DreamMessage request, Result<DreamMessage> response) {

            bool privateDetails = PermissionsBL.IsUserAllowed(DekiContext.Current.User, Permissions.ADMIN);

            //Private feature requires api-key
            uint totalCount;
            uint queryCount;
            IList<ServiceBE> services = ServiceBL.GetServicesByQuery(context, out totalCount, out queryCount);
            XDoc result = new XDoc("services");
            result.Attr("count", services.Count);
            result.Attr("querycount", queryCount);
            result.Attr("totalcount", totalCount);
            result.Attr("href", DekiContext.Current.ApiUri.At("site", "services"));
            foreach(ServiceBE s in services) {
                result.Add(ServiceBL.GetServiceXmlVerbose(DekiContext.Current.Instance, s, null, privateDetails));
            }
            response.Return(DreamMessage.Ok(result));
            yield break;
        }
 public Yield GetSiteRoles(DreamContext context, DreamMessage request, Result<DreamMessage> response) {
     IList<RoleBE> roles = DbUtils.CurrentSession.RolesRestrictions_GetRoles();
     XDoc ret = new XDoc("roles");
     ret.Attr("href", DekiContext.Current.ApiUri.At("site", "roles"));
     if (roles != null) {
         foreach (RoleBE r in roles) {
             ret.Add(PermissionsBL.GetRoleXml(r, null));
         }
     }
     response.Return(DreamMessage.Ok(ret));
     yield break;
 }
Example #33
0
        internal static XDoc ExecuteScript(Plug env, DreamHeaders headers, XDoc script) {

            // execute script commands
            XDoc reply = new XDoc("results");
            string ID = script["@ID"].Contents;
            if(!string.IsNullOrEmpty(ID)) {
                reply.Attr("ID", ID);
            }
            foreach(XDoc cmd in script.Elements) {
                reply.Add(ExecuteCommand(env, headers, cmd));
            }
            return reply;
        }
Example #34
0
        public void LogPageConversion(XDoc spaceManifest, ACConverterPageInfo pageInfo) {
            string xpath = string.Format("page[@c.pageid='{0}']", pageInfo.ConfluencePage.id);
            XDoc pageXml = spaceManifest[xpath];

            if(pageXml.IsEmpty) {
                spaceManifest.Start("page");
                spaceManifest.Attr("c.space", pageInfo.ConfluencePage.space);
                spaceManifest.Attr("c.pageid", pageInfo.ConfluencePage.id);
                spaceManifest.Attr("c.parentpageid", pageInfo.ConfluencePage.parentId);
                spaceManifest.Attr("c.path", Utils.GetUrlLocalUri(_confBaseUrl, pageInfo.ConfluencePage.url, true, false));
                spaceManifest.Attr("c.tinyurl", pageInfo.TinyUrl);
                spaceManifest.Attr("mt.pageid", pageInfo.DekiPageId);
                spaceManifest.Attr("mt.path", pageInfo.DekiPageUrl);
                spaceManifest.Attr("title", pageInfo.PageTitle);
                spaceManifest.End();
            }
        }
Example #35
0
        public void LogFileConversion(XDoc spaceManifest, RemoteAttachment fileInfo, string contentUrl) {
            string xpath = string.Format("file[@c.fileid='{0}']", fileInfo.id);

            XDoc fileXml = spaceManifest[xpath];
            if(fileXml.IsEmpty) {
                spaceManifest.Start("file");
                spaceManifest.Attr("c.fileid", fileInfo.id);
                spaceManifest.Attr("c.pageid", fileInfo.pageId);
                spaceManifest.Attr("c.filename", fileInfo.fileName);
                spaceManifest.Attr("c.filesize", fileInfo.fileSize);
                spaceManifest.Attr("c.mimetype", fileInfo.contentType);
                spaceManifest.Attr("c.path", Utils.GetUrlLocalUri(_confBaseUrl, fileInfo.url, false, true));
                spaceManifest.Attr("mt.path", Utils.GetApiUrl(Utils.GetUrlLocalUri(_confBaseUrl, contentUrl, true, true)));
                spaceManifest.End();
            }
        }
Example #36
0
        internal static XDoc ExecuteFork(Plug env, DreamHeaders headers, XDoc fork) {

            // execute script commands
            XDoc reply = new XDoc("results");
            string ID = fork["@ID"].Contents;
            if(!string.IsNullOrEmpty(ID)) {
                reply.Attr("ID", ID);
            }

            // TODO (steveb): we should use a 'fixed capacity' cue which marks itself as done when 'count' is reached

            XDoc forks = fork.Elements;
            foreach(XDoc cmd in forks) {

                // TODO (steveb): we should be doing this in parallel, not sequentially!

                try {
                    reply.Add(ExecuteCommand(env, headers, cmd));
                } catch(Exception e) {
                    reply.Add(new XException(e));
                }
            }
            return reply;
        }
 private void SaveConvertedUsersAndGroups()
 {
     XDoc usersDoc = new XDoc(ConvertedUsersRootName);
     foreach (string tWikiUserName in _convertedUsers.Keys)
     {
         XDoc userDoc = new XDoc(ConvertedUserTagName);
         userDoc.Attr(TWikiUserNameAttribute, tWikiUserName);
         userDoc.Attr(DekiUserNameAttribute, _convertedUsers[tWikiUserName].DekiName);
         usersDoc.Add(userDoc);
     }
     foreach (string tWikiGroupName in _convertedGroups.Keys)
     {
         XDoc groupDoc = new XDoc(ConvertedGroupTagName);
         groupDoc.Attr(TWikiGroupNameAttribute, tWikiGroupName);
         groupDoc.Attr(DekiGroupNameAttribute, _convertedGroups[tWikiGroupName].DekiName);
         usersDoc.Add(groupDoc);
     }
     usersDoc.Save(ConvertedUsersFileName);
 }
Example #38
0
        //--- Class Methods ---
        /// <summary>
        /// Create a service blueprint from reflection and attribute meta-data for an <see cref="IDreamService"/> implementation.
        /// </summary>
        /// <param name="type">Type of examine.</param>
        /// <returns>Xml formatted blueprint.</returns>
        public static XDoc CreateServiceBlueprint(Type type)
        {
            if(type == null) {
                throw new ArgumentNullException("type");
            }
            XDoc result = new XDoc("blueprint");

            // load assembly
            Dictionary<string, string> assemblySettings = new Dictionary<string, string>(StringComparer.Ordinal);
            string[] assemblyParts = type.Assembly.FullName.Split(',');
            foreach(string parts in assemblyParts) {
                string[] assign = parts.Trim().Split(new char[] { '=' }, 2);
                if(assign.Length == 2) {
                    assemblySettings[assign[0].Trim()] = assign[1].Trim();
                }
            }
            result.Start("assembly");
            foreach(KeyValuePair<string, string> entry in assemblySettings) {
                result.Attr(entry.Key, entry.Value);
            }
            result.Value(assemblyParts[0]);
            result.End();
            result.Elem("class", type.FullName);

            // retrieve DreamService attribute on class definition
            DreamServiceAttribute serviceAttrib = (DreamServiceAttribute)Attribute.GetCustomAttribute(type, typeof(DreamServiceAttribute), false);
            result.Elem("name", serviceAttrib.Name);
            result.Elem("copyright", serviceAttrib.Copyright);
            result.Elem("info", serviceAttrib.Info);

            // retrieve DreamServiceUID attributes
            foreach(XUri sid in serviceAttrib.GetSIDAsUris()) {
                result.Elem("sid", sid);
            }

            // check if service has blueprint settings
            foreach(DreamServiceBlueprintAttribute blueprintAttrib in Attribute.GetCustomAttributes(type, typeof(DreamServiceBlueprintAttribute), true)) {
                result.InsertValueAt(blueprintAttrib.Name, blueprintAttrib.Value);
            }

            // check if service has configuration information
            DreamServiceConfigAttribute[] configAttributes = (DreamServiceConfigAttribute[])Attribute.GetCustomAttributes(type, typeof(DreamServiceConfigAttribute), true);
            if(!ArrayUtil.IsNullOrEmpty(configAttributes)) {
                result.Start("configuration");
                foreach(DreamServiceConfigAttribute configAttr in configAttributes) {
                    result.Start("entry")
                        .Elem("name", configAttr.Name)
                        .Elem("valuetype", configAttr.ValueType)
                        .Elem("description", configAttr.Description)
                    .End();
                }
                result.End();
            }

            // retrieve DreamFeature attributes on method definitions
            result.Start("features");
            MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
            foreach(MethodInfo method in methods) {

                // retrieve feature description
                Attribute[] featureAttributes = Attribute.GetCustomAttributes(method, typeof(DreamFeatureAttribute), false);
                if(featureAttributes.Length == 0) {
                    continue;
                }
                if(method.IsGenericMethod || method.IsGenericMethodDefinition) {
                    throw new NotSupportedException(string.Format("generic methods are not supported ({0})", method.Name));
                }

                // determine access level
                string access;
                if(method.IsPublic) {
                    access = "public";
                } else if(method.IsAssembly) {
                    access = "internal";
                } else if(method.IsPrivate || method.IsFamily) {
                    access = "private";
                } else {
                    throw new NotSupportedException(string.Format("access level is not supported ({0})", method.Name));
                }

                // retrieve feature parameter descriptions, filters, prologues, and epilogues
                Attribute[] paramAttributes = Attribute.GetCustomAttributes(method, typeof(DreamFeatureParamAttribute), false);
                var pathAttributes = method.GetParameters().Select(p => {
                    var attr = (PathAttribute)p.GetCustomAttributes(typeof(PathAttribute), false).FirstOrDefault();
                    return ((attr != null) && (attr.Name == null)) ? new PathAttribute { Description = attr.Description, Name = p.Name } : attr;
                }).Where(p => p != null);
                var queryAttributes = method.GetParameters().Select(q => {
                    var attr = (QueryAttribute)q.GetCustomAttributes(typeof(QueryAttribute), false).FirstOrDefault();
                    return ((attr != null) && (attr.Name == null)) ? new QueryAttribute { Description = attr.Description, Name = q.Name } : attr;
                }).Where(q => q != null);
                Attribute[] statusAttributes = Attribute.GetCustomAttributes(method, typeof(DreamFeatureStatusAttribute), false);
                foreach(DreamFeatureAttribute featureAttrib in featureAttributes) {
                    result.Start("feature");
                    result.Elem("obsolete", featureAttrib.Obsolete);
                    result.Elem("pattern", featureAttrib.Pattern);
                    result.Elem("description", featureAttrib.Description);
                    string info = featureAttrib.Info ?? serviceAttrib.Info;
                    if(info != null) {
                        result.Elem("info", info);
                    }
                    result.Elem("method", method.Name);

                    // add parameter descriptions (as seen on the method definition)
                    foreach(DreamFeatureParamAttribute paramAttrib in paramAttributes) {
                        result.Start("param");
                        result.Elem("name", paramAttrib.Name);
                        if(!string.IsNullOrEmpty(paramAttrib.ValueType)) {
                            result.Elem("valuetype", paramAttrib.ValueType);
                        }
                        result.Elem("description", paramAttrib.Description);
                        result.End();
                    }

                    // add parameter descriptions (as seen on the method parameters)
                    foreach(PathAttribute pathAttrib in pathAttributes) {
                        result.Start("param")
                            .Elem("name", "{" + pathAttrib.Name + "}")
                            .Elem("description", pathAttrib.Description)
                        .End();
                    }

                    // add parameter descriptions (as seen on the method parameters)
                    foreach(QueryAttribute queryAttrib in queryAttributes) {
                        result.Start("param")
                            .Elem("name", queryAttrib.Name)
                            .Elem("description", queryAttrib.Description)
                        .End();
                    }

                    // add status codes
                    foreach(DreamFeatureStatusAttribute paramAttrib in statusAttributes) {
                        result.Start("status");
                        result.Attr("value", (int)paramAttrib.Status);
                        result.Value(paramAttrib.Description);
                        result.End();
                    }

                    // add access level
                    result.Elem("access", access);
                    result.End();
                }
            }
            result.End();
            return result.EndAll();
        }
        public Yield UserLogin(DreamContext context, DreamMessage request, Result<DreamMessage> response) {
            
            string userSuppliedIdentifier = context.GetParam("url", null);
            if (String.IsNullOrEmpty(userSuppliedIdentifier)) {
                _log.Info("No identifier was specified");
                throw new DreamBadRequestException("No identifier was specified.");
            }

            XUri returnUri = new XUri(context.GetParam("returnurl", null));
            String realm = context.GetParam("realm", null);
            if (String.IsNullOrEmpty(realm)) {
                realm = returnUri.WithoutPathQueryFragment().ToString();
            }

            IAuthenticationRequest openIdRequest;

            // dummy parameters required by DotNetOpenId 2.x; in 3.x, you can
            // just pass null to the OpenIdRelyingParty constructor.
            Uri identifierUri = new Uri(userSuppliedIdentifier);
            NameValueCollection queryCol = System.Web.HttpUtility.ParseQueryString(identifierUri.Query);
            OpenIdRelyingParty openid = new OpenIdRelyingParty(null, identifierUri, queryCol);
           
            // creating an OpenID request will authenticate that 
            // the endpoint exists and is an OpenID provider.
            _log.DebugFormat("Creating OpenID request: identifier {0}, return URL {1}, realm {2}", userSuppliedIdentifier, returnUri.ToString(), realm); 

            try {
                openIdRequest = openid.CreateRequest(
                    userSuppliedIdentifier,
                    realm,
                    returnUri.ToUri());
            } catch (OpenIdException ex) {
                _log.WarnFormat("'{0}' rejected as OpenID identifier: {1}", userSuppliedIdentifier, ex.Message);
                throw new DreamBadRequestException(string.Format("'{0}' is not a valid OpenID identifier. {1}", userSuppliedIdentifier, ex.Message));
            }

            // Ask for the e-mail address on this request.
            // Use both SREG and AX, to increase the odds of getting it.
            openIdRequest.AddExtension(new ClaimsRequest{
                Email = DemandLevel.Require,
            });

            var fetch = new FetchRequest();
            fetch.AddAttribute(new AttributeRequest(WellKnownAttributes.Contact.Email, true));
            openIdRequest.AddExtension(fetch);

            // The RedirectingResponse either contains a "Location" header for 
            // a HTTP GET, which will return in the response as 'endpoint', or
            // a HTML FORM which needs to be displayed to the user, which will
            // return in the response as 'form'.
            IResponse wr = openIdRequest.RedirectingResponse;

            XDoc result = new XDoc("openid");
            if (String.IsNullOrEmpty(wr.Headers["Location"])) {
                System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
                string formBody = enc.GetString(wr.Body);
                _log.DebugFormat("OpenID redirect by HTML FORM: {0}", formBody);  
                result.Attr("form", formBody);  
            } else {
                string redirectUrl = wr.Headers["Location"];
                _log.DebugFormat("OpenID redirect URL: {0}", redirectUrl);
                result.Attr("endpoint", redirectUrl);
            }

            response.Return(DreamMessage.Ok(result));
            yield break;
        }
        public Yield ValidateOpenIdResponse(DreamContext context, DreamMessage request, Result<DreamMessage> response) {
            XUri publicUri = new XUri(context.GetParam("url", null));
            NameValueCollection queryColl = System.Web.HttpUtility.ParseQueryString(context.GetParam("query", null));

            // process the response, including validating the endpoint of the claimed identifier.
            OpenIdRelyingParty openid = new OpenIdRelyingParty(null, publicUri, queryColl);
            var openIdResponse = openid.Response;

            if (openIdResponse != null) {
                switch (openIdResponse.Status) {
                    case AuthenticationStatus.Authenticated:
                       
                        // Throw an exception if there is a regex for acceptable
                        // identifiers defined, and the ID does not match.
                        if (!String.IsNullOrEmpty(_validIdPattern)) {
                            Regex identifierAccept = new Regex(_validIdPattern);
                            if (!identifierAccept.IsMatch(openIdResponse.ClaimedIdentifier)) {
                                _log.InfoFormat("Identifier {0} denied access by valid-id-pattern regular expression {1}", openIdResponse.ClaimedIdentifier, _validIdPattern);
                                throw new DreamBadRequestException("This service is configured to deny access to this OpenID identifier.");
                            }
                        }

                        var claimsResponse = openIdResponse.GetExtension<ClaimsResponse>();
                        var fetchResponse = openIdResponse.GetExtension<FetchResponse>();

                        XDoc result = new XDoc("openid");
                        result.Attr("validated", true);
                        result.Elem("identifier", openIdResponse.ClaimedIdentifier);
			
                        // SREG response
                        if (claimsResponse != null) {
                            string email = claimsResponse.Email;
                            if (email != null) {
                                result.Elem("email", email);
                                _log.DebugFormat("E-mail address from SREG: {0}", email);
                            }
                        }
                        // AX response
                        if (fetchResponse != null) {
                            foreach (AttributeValues v in fetchResponse.Attributes) {
                                if (v.TypeUri == WellKnownAttributes.Contact.Email) {
                                    IList<string> emailAddresses = v.Values;
                                    string email = emailAddresses.Count > 0 ? emailAddresses[0] : null;
                                    result.Elem("email", email);
                                    _log.DebugFormat("E-mail address from AX: {0}", email);
                                }
                            }
                        }
                        response.Return(DreamMessage.Ok(result));
                        break;
                    case AuthenticationStatus.Canceled:
                        _log.InfoFormat("Authentication was cancelled by the user.");
                        throw new DreamBadRequestException("Authentication was cancelled by the user.");
                    case AuthenticationStatus.Failed:
                        _log.InfoFormat("Authentication failed: " + openIdResponse.Exception.Message);
                        throw new DreamBadRequestException("Authentication failed: " + openIdResponse.Exception.Message);
                    default:
                        _log.WarnFormat("Authentication error: " + openIdResponse.Exception.Message);
                        throw new DreamBadRequestException("Authentication error: " + openIdResponse.Exception.Message);
                }
            } else {
                _log.Warn("OpenID response was null");
                throw new DreamBadRequestException("No OpenID response was returned.");
            }
            yield break;
        }      
Example #41
0
 private static void FixupManifest(XDoc manifest, Opts opts) {
     if(opts.ImportOnce) {
         manifest.Attr("import-once", true);
     }
     if(opts.InitOnly) {
         manifest.Attr("init-only", true);
     }
     if(manifest["@preserve-local"].IsEmpty) {
         manifest.Attr("preserve-local", opts.PreserveLocalChanges ?? false);
     } else {
         manifest["@preserve-local"].ReplaceValue(opts.PreserveLocalChanges ?? false);
     }
     if(opts.Restriction != Restriction.Default) {
         manifest.Start("security")
             .Start("permissions.page")
                 .Elem("restriction", GetRestrictionString(opts.Restriction))
             .End()
         .End();
     }
     foreach(var capability in opts.Capabilities) {
         manifest.Start("capability").Attr("name", capability.Key);
         if(!string.IsNullOrEmpty(capability.Value)) {
             manifest.Attr("value", capability.Value);
         }
         manifest.End();
     }
 }
Example #42
0
        public Yield GetGroupUsers(DreamContext context, DreamMessage request, Result<DreamMessage> response) {
            PermissionsBL.CheckUserAllowed(DekiContext.Current.User, Permissions.READ);
            GroupBE group = GetGroupFromUrl();
            DreamMessage responseMsg = null;

            uint totalCount;
            uint queryCount;
            var usersInGroup = UserBL.GetUsersByQuery(context, group.Id, out totalCount, out queryCount);

            XDoc ret = new XDoc("users");
            ret.Attr("count", usersInGroup.Count());
            ret.Attr("querycount", queryCount);
            ret.Attr("totalcount", totalCount);
            ret.Attr("href", DekiContext.Current.ApiUri.At("groups", group.Id.ToString(), "users"));

            foreach(UserBE member in usersInGroup)
                ret.Add(UserBL.GetUserXml(member, null, Utils.ShowPrivateUserInfo(member)));

            responseMsg = DreamMessage.Ok(ret);

            response.Return(responseMsg);
            yield break;
        }
Example #43
0
 private void SaveUsersAndGroupsToXML()
 {
     XDoc doc = new XDoc(UsersAndGroupsXMLRootName);
     foreach (string confluenceUserName in _convertedUsers.Keys)
     {
         ACConverterUserInfo userInfo = _convertedUsers[confluenceUserName];
         XDoc userDoc = new XDoc(UserXMLTagName);
         userDoc.Attr(ConfluenceUserNameXMLAttributeName, confluenceUserName);
         userDoc.Attr(DekiUserNameXMLAttributeName, userInfo.DekiUserName);
         doc.Add(userDoc);
     }
     foreach (string confluenceGroupName in _convertedGroups.Keys)
     {
         ACConverterGroupInfo groupInfo = _convertedGroups[confluenceGroupName];
         XDoc groupDoc = new XDoc(GroupXMLTagName);
         groupDoc.Attr(ConfluenceGroupNameXMLAttributeName, confluenceGroupName);
         groupDoc.Attr(DekiGroupNameXMLAttributeName, groupInfo.DekiGroupName);
         doc.Add(groupDoc);
     }
     doc.Save(ConvertedUsersAndGroupsFileName);
 }
Example #44
0
 public static XDoc GetServiceXml(ServiceBE service, string relation) {
     XDoc serviceXml = new XDoc(string.IsNullOrEmpty(relation) ? "service" : "service." + relation);
     serviceXml.Attr("id", service.Id);
     serviceXml.Attr("href", DekiContext.Current.ApiUri.At("site", "services", service.Id.ToString()));
     return serviceXml;
 }
Example #45
0
 //--- Methods ---
 /// <summary>
 /// Create a new subscription set document.
 /// </summary>
 /// <returns>Set Xml document.</returns>
 public XDoc AsDocument()
 {
     XDoc doc = new XDoc("subscription-set")
         .Attr("max-failures", MaxFailures)
         .Elem("uri.owner", Owner);
     if(Version.HasValue) {
         doc.Attr("version", Version.Value);
     }
     foreach(PubSubSubscription subscription in Subscriptions) {
         doc.Add(subscription.AsDocument());
     }
     return doc;
 }
 private void ReplaceAttribute(XDoc doc, string attributeName, string pageName, string currentWeb)
 {
     string atAttributeName = "@" + attributeName;
     string link = doc[atAttributeName].AsText;
     if (link == null)
     {
         return;
     }
     string dekiUrl = GetDekiUrlFromTWikiUrl(link, currentWeb);
     if (dekiUrl != null)
     {
         doc.Attr(attributeName, dekiUrl);
     }
 }
 public static XDoc WebImage(
     [DekiScriptParam("image uri")] string uri,
     [DekiScriptParam("image width", true)] float? width,
     [DekiScriptParam("image height", true)] float? height,
     [DekiScriptParam("image alternative text", true)] string text
 ) {
     XDoc result = new XDoc("html").Start("body");
     if(uri.EndsWithInvariantIgnoreCase(".svg")) {
         result.Start("iframe").Attr("marginwidth", "0").Attr("marginheight", "0").Attr("hspace", "0").Attr("vspace", "0").Attr("frameborder", "0").Attr("scrolling", "no");
     } else {
         result.Start("img");
     }
     result.Attr("src", WebCheckUri(uri));
     result.Attr("width", WebSize(width));
     result.Attr("height", WebSize(height));
     result.Attr("alt", text);
     result.Attr("title", text);
     result.End();
     result.End();
     return result;
 }
Example #48
0
        private XDoc GetFileXml(IList<ResourceBE> files, bool verbose, bool list, string fileSuffix, bool? explicitRevisionInfo, int? totalCount, XUri listUri) {
            Dictionary<uint, UserBE> users = new Dictionary<uint, UserBE>();
            Dictionary<ulong, PageBE> pages = new Dictionary<ulong, PageBE>();
            List<uint> parentIds = new List<uint>();

            //Collect related entity id's 
            foreach(ResourceBE f in files) {
                users[f.UserId] = null;
                pages[f.ParentPageId.Value] = null;
                parentIds.Add(f.ResourceId);
            }

            //Perform batch lookups of related entities
            users = _session.Users_GetByIds(users.Keys.ToArray()).AsHash(e => e.ID);
            if(verbose) {
                pages = PageBL.GetPagesByIdsPreserveOrder(pages.Keys.ToArray()).AsHash(e => e.ID);
            }

            //Associate properties with the given attachments
            files = _resourceBL.PopulateChildren(files.ToArray(), new[] { ResourceBE.Type.PROPERTY }, explicitRevisionInfo ?? false);

            XDoc ret = XDoc.Empty;
            if(list) {
                List<ResourceBE> sortedFiles = new List<ResourceBE>(files);
                files = SortFileListByNameAndRevision(sortedFiles).ToArray();
                ret = new XDoc(string.IsNullOrEmpty(fileSuffix) ? "files" : "files." + fileSuffix);
                ret.Attr("count", files.Count);
                if(totalCount != null) {
                    ret.Attr("totalcount", totalCount.Value);
                }
                if(listUri != null) {
                    ret.Attr("href", listUri);
                }
            }
            foreach(ResourceBE f in files) {
                UserBE updatedByUser;
                PageBE parentPage;
                users.TryGetValue(f.UserId, out updatedByUser);
                pages.TryGetValue(f.ParentPageId.Value, out parentPage);
                ret = AppendFileXml(ret, f, fileSuffix, explicitRevisionInfo, updatedByUser, parentPage);
            }

            return ret;
        }
Example #49
0
 //--- Class Methods ---
 /// <summary>
 /// Convert an XSpan document to a regular Xml document.
 /// </summary>
 /// <param name="xspan">XSpan document.</param>
 /// <returns>New Xml document instance.</returns>
 public static XDoc FromXSpan(XDoc xspan)
 {
     XDoc xml = new XDoc(xspan["@class"].Contents);
     foreach(XDoc attr in xspan["@*"]) {
         if(attr.Name.StartsWithInvariant("xml:"))
             xml.Attr(attr.Name.Substring("xml:".Length), attr.Contents);
     }
     string value = xspan["text()"].Contents;
     if(value.Length != 0)
         xml.Value(value);
     foreach(XDoc child in xspan.Elements)
         xml.Add(FromXSpan(child));
     return xml;
 }
Example #50
0
        /// <summary>
        /// Read a Versit string from a text reader and parse it into an Xml document.
        /// </summary>
        /// <param name="reader">Source reader.</param>
        /// <param name="root">Name to use as thexml document root node.</param>
        /// <returns>Xml document instance.</returns>
        public static XDoc FromVersit(TextReader reader, string root)
        {
            string value = reader.ReadToEnd().Trim();
            XDoc result = new XDoc(string.IsNullOrEmpty(root) ? "root" : root);

            // NOTE (steveb): the versit format is "KEY;ATTR_KEY=ATTR_VALUE;ATTR_KEY=ATTR_VALUE:VALUE\r\n"

            // join line continuations
            value = value.Replace("\r\n ", "");

            // split lines
            string[] lines = value.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);

            // process each line
            foreach(string line in lines) {
                if(line.StartsWithInvariant("BEGIN:")) {
                    result.Start(line.Substring(6).ToLowerInvariant());
                } else if(line.StartsWithInvariant("END:")) {
                    result.End();
                } else {
                    string[] pair = line.Split(new[] { ':' }, 2);
                    string[] attrs = pair[0].Split(';');
                    result.Start(attrs[0].ToLowerInvariant());
                    for(int i = 1; i < attrs.Length; ++i) {
                        string[] attr = attrs[i].Split(new[] { '=' }, 2);
                        result.Attr(attr[0].ToLowerInvariant(), (attr.Length > 1) ? DecodeVersitString(attr[1]) : string.Empty);
                    }
                    if(pair.Length > 1) {
                        result.Value(DecodeVersitString(pair[1]));
                    }
                    result.End();
                }
            }
            return result;
        }
Example #51
0
        public static XDoc GetGroupXml(GroupBE group, string relation) {
            XDoc groupXml = new XDoc(string.IsNullOrEmpty(relation) ? "group" : "group." + relation);

            groupXml.Attr("id", group.Id);
            groupXml.Attr("href", DekiContext.Current.ApiUri.At("groups", group.Id.ToString()));
            groupXml.Start("groupname").Value(group.Name).End();

            return groupXml;
        }
Example #52
0
 private static void WriteXSpan(XmlNode node, XDoc output)
 {
     switch(node.NodeType) {
     case XmlNodeType.Document:
         WriteXSpan(((XmlDocument)node).DocumentElement, output);
         break;
     case XmlNodeType.Element:
         XDoc childOutput = output.Start("span");
         childOutput.Attr("class", node.Name);
         foreach(XmlNode attr in node.Attributes) {
             output.Attr("xml:" + attr.Name, attr.Value);
         }
         foreach(XmlNode child in node.ChildNodes) {
             WriteXSpan(child, output);
         }
         output.End();
         break;
     case XmlNodeType.Text:
         output.Value(node.Value);
         break;
     }
 }
Example #53
0
        public static XDoc GetUserXml(UserBE user, string relation, bool showPrivateInfo) {
            XDoc userXml = new XDoc(string.IsNullOrEmpty(relation) ? "user" : "user." + relation);
            userXml.Attr("id", user.ID);
            userXml.Attr("href", DekiContext.Current.ApiUri.At("users", user.ID.ToString()));
            userXml.Elem("nick", user.Name);
            userXml.Elem("username", user.Name);
            userXml.Elem("fullname", user.RealName ?? String.Empty);

            // check if we can add the email address
            if(showPrivateInfo) {
                userXml.Elem("email", user.Email);
            } else {
                userXml.Start("email").Attr("hidden", true).End();
            }

            // add gravatar
            if(!IsAnonymous(user) && !string.IsNullOrEmpty(user.Email)) {
                DekiContext context = DekiContext.CurrentOrNull;
                XUri gravatar = new XUri("http://www.gravatar.com/avatar");
                string hash = string.Empty;
                if(context != null) {
                    DekiInstance deki = context.Instance;
                    string secure = context.Instance.GravatarSalt ?? string.Empty;
                    if(!secure.EqualsInvariantIgnoreCase("hidden")) {
                        hash = StringUtil.ComputeHashString(secure + (user.Email ?? string.Empty).Trim().ToLowerInvariant(), System.Text.Encoding.UTF8);
                    }

                    // add size, if any
                    string size = deki.GravatarSize;
                    if(size != null) {
                        gravatar = gravatar.With("s", size);
                    }

                    // add rating, if any
                    string rating = deki.GravatarRating;
                    if(rating != null) {
                        gravatar = gravatar.With("r", rating);
                    }

                    // add default icon, if any
                    string def = deki.GravatarDefault;
                    if(def != null) {
                        gravatar = gravatar.With("d", def);
                    }
                }
                if(!string.IsNullOrEmpty(hash)) {
                    userXml.Elem("hash.email", hash);
                    userXml.Elem("uri.gravatar", gravatar.At(hash + ".png"));
                } else {
                    userXml.Elem("hash.email", string.Empty);
                    userXml.Elem("uri.gravatar", gravatar.At("no-email.png"));
                }
            }
            return userXml;
        }
        public Yield GetUsers(DreamContext context, DreamMessage request, Result<DreamMessage> response) {

            // TODO (steveb): add 'emailfilter' and use it to obsolete 'usernameemailfilter'; 'usernamefilter', 'fullnamefilter', and 'emailfilter' 
            //                should be OR'ed together when they are present.

            PermissionsBL.CheckUserAllowed(DekiContext.Current.User, Permissions.READ);
            uint totalCount;
            uint queryCount;
            IList<UserBE> users = UserBL.GetUsersByQuery(context, null, out totalCount, out queryCount);
            XDoc result = new XDoc("users");
            result.Attr("count", users.Count);
            result.Attr("querycount", queryCount);
            result.Attr("totalcount", totalCount);
            result.Attr("href", DekiContext.Current.ApiUri.At("users"));
            foreach (UserBE u in users) {
                result.Add(UserBL.GetUserXmlVerbose(u, null, Utils.ShowPrivateUserInfo(u)));
            }
            response.Return(DreamMessage.Ok(result));
            yield break;
        }
Example #55
0
        public XDoc Table(
            [DekiExtParam("SELECT query")] string query
        ) {
            XDoc result = new XDoc("html")
                .Start("head")
                    .Start("script").Attr("type", "text/javascript").Attr("src", Files.At("sorttable.js")).End()
                    .Start("style").Attr("type", "text/css").Value(@".feedtable {
    border:1px solid #999;
    line-height:1.5em;
    overflow:hidden;
    width:100%;
}
.feedtable th {
    background-color:#ddd;
    border-bottom:1px solid #999;
    font-size:14px;
}
.feedtable tr {
    background-color:#FFFFFF;
}
.feedtable tr.feedroweven td {
    background-color:#ededed;
}").End()
                .End()
                .Start("body");
            result.Start("table").Attr("border", 0).Attr("cellpadding", 0).Attr("cellspacing", 0).Attr("class", "feedtable sortable");
            _catalog.NewQuery(query).Execute(delegate(IDataReader reader) {

                // capture row columns
                result.Start("thead").Start("tr");
                int count = reader.FieldCount;
                for(int i = 0; i < count; ++i) {
                    result.Start("th").Elem("strong", reader.GetName(i)).End();
                }
                result.End().End();

                // read records
                int rowcount = 0;
                result.Start("tbody");
                while(reader.Read()) {
                    result.Start("tr");
                    result.Attr("class", ((rowcount++ & 1) == 0) ? "feedroweven" : "feedrowodd");
                    for (int i = 0; i < count; ++i) {
                        string val = string.Empty;

                        try {
                            if (!reader.IsDBNull(i)) {
                                val = reader.GetValue(i).ToString();
                            }
                        } catch { }
                     
                        result.Elem("td", val);
                    }
                    result.End();
                }
                result.End();
            });
            result.End().End();
            return result;
        }