protected user Authenticate(DreamContext context, DreamMessage request, DekiUserLevel level) {
            user result = null;

            // get username and password
            string user;
            string password;
            if (!DreamUtil.GetAuthentication(context, request, out user, out password)) {

                // anonymous access is always granted
                if (level == DekiUserLevel.Anonymous) {

                    // TODO (steveb): missing code
                    throw new NotImplementedException("return anonymous user");
                } else {
                    throw new DreamAbortException(DreamMessage.AccessDenied(AuthenticationRealm, "authentication failed"));
                }
            }

            // validate username and password
            result = MindTouch.Deki.user.GetUserByName(user);
            if (result == null) {
                throw new DreamAbortException(DreamMessage.AccessDenied(AuthenticationRealm, "authentication failed"));
            }
            if (!result.checkPassword(password)) {
                throw new DreamAbortException(DreamMessage.AccessDenied(AuthenticationRealm, "authentication failed"));
            }
            if ((level == DekiUserLevel.Admin) && !result.isSysop()) {
                throw new DreamAbortException(DreamMessage.AccessDenied(AuthenticationRealm, "authentication failed"));
            }
            return result;
        }
Beispiel #2
0
 public Yield GetGroup(DreamContext context, DreamMessage request, Result<DreamMessage> response) {
     PermissionsBL.CheckUserAllowed(DekiContext.Current.User, Permissions.READ);
     GroupBE group = GetGroupFromUrl();
     DreamMessage responseMsg = DreamMessage.Ok(GroupBL.GetGroupXmlVerbose(group, null));
     response.Return(responseMsg);
     yield break;
 }
 public Yield GetPageTags(DreamContext context, DreamMessage request, Result<DreamMessage> response) {
     PageBE page = PageBL.AuthorizePage(DekiContext.Current.User, Permissions.READ, false);
     XUri href = DekiContext.Current.ApiUri.At("pages", page.ID.ToString(), "tags");
     XDoc doc = TagBL.GetTagListXml(TagBL.GetTagsForPage(page), "tags", href, false);
     response.Return(DreamMessage.Ok(doc));
     yield break;
 } 
Beispiel #4
0
 //--- Class Methods ---
 public static DekiContext GetContext(DreamContext dreamContext) {
     var context = dreamContext.GetState<DekiContext>();
     if(context == null) {
         throw new DekiContextAccessException("DekiContext.Current is not set, because the current DreamContext does not contain a reference");
     }
     return context;
 }
Beispiel #5
0
 public DreamMessage GetContentHandler(DreamContext context, DreamMessage message) {
     user user = Authenticate(context, message, DekiUserLevel.User);
     page page = Authorize(context, user, DekiAccessLevel.Read, "pageid");
     DekiContext deki = new DekiContext(message, this.DekiConfig);
     bool nofollow = (context.Uri.GetParam("nofollow", 0, null) != null);
     string contents = page.getContent(nofollow);
     string xml = string.Format(DekiWikiService.XHTML_LOOSE, contents);
     XDoc doc = XDoc.FromXml(xml);
     if (doc == null) {
         LogUtils.LogWarning(_log, "GetContentHandler: null document page content", page.PrefixedName, contents);
         throw new DreamAbortException(DreamMessage.BadRequest("null document"));
     }
     XDoc result = new XDoc("list");
     string type = context.Uri.GetParam("type", 0, null);
     string id = context.Uri.GetParam("id", 0, null);
     if (id != null) {
         XDoc widget = doc[string.Format("//default:span[@widgetid={0}]", id)];
         if (widget.IsEmpty) {
             LogUtils.LogWarning(_log, "GetContentHandler: widget not found for ID", id);
             return DreamMessage.NotFound("");
         }
         LogUtils.LogTrace(_log, "GetContentHandler: widget by id (id, xspan)", id, widget);
         result.Add(ConvertFromXSpan(widget));
     } else if (type != null) {
         foreach (XDoc widget in doc[string.Format("//default:span[@widgettype='{0}']", type)])
             result.Add(ConvertFromXSpan(widget));
         LogUtils.LogTrace(_log, "GetContentHandler: widget by type (type, #)", type, result.Count);
     } else {
         foreach (XDoc widget in doc["//default:span[@class='widget']"])
             result.Add(ConvertFromXSpan(widget));
         LogUtils.LogTrace(_log, "GetContentHandler: all widgets (#)", type, result.Count);
     }
     return DreamMessage.Ok(result);
 }
Beispiel #6
0
        public Yield Register(DreamContext context, DreamMessage request, Result<DreamMessage> response) {
            string servicePath = context.GetParam("service-path");
            string location = StringUtil.CreateAlphaNumericKey(8);

            // register the script
            XDoc config = new XDoc("config")
                .Elem("manifest", servicePath)
                .Elem("debug", true);

            //create the script service
            Result<Plug> res;
            yield return res = CreateService(location, "sid://mindtouch.com/2007/12/dekiscript", config, new Result<Plug>());
            Plug service = res.Value;

            // register script functions in environment
            XDoc manifest = service.Get().ToDocument();
            string ns = manifest["namespace"].AsText;
            foreach(XDoc function in manifest["function"]) {
                string name = function["name"].AsText;
                if(string.IsNullOrEmpty(ns)) {
                    _env.Vars.AddNativeValueAt(name, function["uri"].AsUri);
                } else {
                    _env.Vars.AddNativeValueAt(ns + "." + name, function["uri"].AsUri);
                }
            }
            response.Return(DreamMessage.Ok(MimeType.XML, manifest));
        }
        public Yield GetTags(DreamContext context, DreamMessage request, Result<DreamMessage> response) {
            string type = DreamContext.Current.GetParam("type", "");
            string fromStr = DreamContext.Current.GetParam("from", "");
            string toStr = DreamContext.Current.GetParam("to", "");
            bool showPages = DreamContext.Current.GetParam("pages", false);
            string partialName = DreamContext.Current.GetParam("q", "");

            // parse type
            TagType tagType = TagType.ALL;
            if(!string.IsNullOrEmpty(type) && !SysUtil.TryParseEnum(type, out tagType)) {
                throw new DreamBadRequestException("Invalid type parameter");
            }

            // check and validate from date
            DateTime from = (tagType == TagType.DATE) ? DateTime.Now : DateTime.MinValue;
            if(!string.IsNullOrEmpty(fromStr) && !DateTime.TryParse(fromStr, out from)) {
                throw new DreamBadRequestException("Invalid from date parameter");
            }

            // check and validate to date
            DateTime to = (tagType == TagType.DATE) ? from.AddDays(30) : DateTime.MaxValue;
            if(!string.IsNullOrEmpty(toStr) && !DateTime.TryParse(toStr, out to)) {
                throw new DreamBadRequestException("Invalid to date parameter");
            }

            // execute query
            var tags = TagBL.GetTags(partialName, tagType, from, to);
            XDoc doc = TagBL.GetTagListXml(tags, "tags", null, showPages);
            response.Return(DreamMessage.Ok(doc));
            yield break;
        }
 public Yield SubscribeToChange(DreamContext context, DreamMessage request, Result<DreamMessage> response) {
     var wikiId = GetWikiIdFromRequest(request);
     var pageId = context.GetParam<uint>("pageid");
     var depth = context.GetParam("depth", "0") == "0" ? false : true;
     Result<PageSubscriptionUser> userResult;
     yield return userResult = Coroutine.Invoke(GetRequestUser, request, new Result<PageSubscriptionUser>()).Catch();
     if(userResult.HasException) {
         ReturnUserError(userResult.Exception, response);
         yield break;
     }
     var userInfo = userResult.Value;
     DreamMessage pageAuth = null;
     yield return _deki
         .At("pages", pageId.ToString(), "allowed")
         .With("permissions", "read,subscribe")
         .WithHeaders(request.Headers)
         .Post(new XDoc("users").Start("user").Attr("id", userInfo.Id).End(), new Result<DreamMessage>())
         .Set(x => pageAuth = x);
     if(!pageAuth.IsSuccessful || pageAuth.ToDocument()["user/@id"].AsText != userInfo.Id.ToString()) {
         throw new DreamForbiddenException("User not permitted to subscribe to page");
     }
     var dataSession = GetDataSession(wikiId);
     dataSession.Subscribe(userInfo.Id, pageId, depth);
     response.Return(DreamMessage.Ok());
     yield break;
 }
 public Yield SubscribeToChange(DreamContext context, DreamMessage request, Result<DreamMessage> response) {
     uint pageId = context.GetParam<uint>("pageid");
     string depth = context.GetParam("depth", "0");
     Result<UserInfo> userResult;
     yield return userResult = Coroutine.Invoke(GetUserInfo, true, request, new Result<UserInfo>()).Catch();
     if(userResult.HasException) {
         ReturnUserError(userResult.Exception, response);
         yield break;
     }
     UserInfo userInfo = userResult.Value;
     DreamMessage pageAuth = null;
     yield return _deki
         .At("pages", pageId.ToString(), "allowed")
         .With("permissions", "read,subscribe")
         .WithHeaders(request.Headers)
         .Post(new XDoc("users").Start("user").Attr("id", userInfo.Id).End(), new Result<DreamMessage>())
         .Set(x => pageAuth = x);
     if(!pageAuth.IsSuccessful || pageAuth.ToDocument()["user/@id"].AsText != userInfo.Id.ToString()) {
         throw new DreamForbiddenException("User not permitted to subscribe to page");
     }
     userInfo.AddResource(pageId, depth);
     userInfo.Save();
     response.Return(DreamMessage.Ok());
     yield break;
 }
 public Yield GetPageRating(DreamContext context, DreamMessage request, Result<DreamMessage> response) {
     UserBE user = DekiContext.Current.User;
     PageBE page = PageBL.AuthorizePage(user, Permissions.READ, false);
     XDoc ret = RatingBL.GetRatingXml(page, user);
     response.Return(DreamMessage.Ok(ret));
     yield break;
 }
 public Yield PostBans(DreamContext context, DreamMessage request, Result<DreamMessage> response) {
     PermissionsBL.CheckUserAllowed(DekiContext.Current.User, Permissions.ADMIN);
     BanBE ban = BanningBL.SaveBan(request.ToDocument());
     DekiContext.Current.Instance.EventSink.BanCreated(context.StartTime, ban);
     response.Return(DreamMessage.Ok(BanningBL.GetBanXml(ban)));
     yield break;
 }
 public Yield GetPage(DreamContext context, DreamMessage request, Result<DreamMessage> response) {
     CheckResponseCache(context, false);
     PageBE page = PageBL.GetPageFromUrl(true);
     page = PageBL.AuthorizePage(DekiContext.Current.User, Permissions.READ, page, false);
     response.Return(DreamMessage.Ok(PageBL.GetPageXmlVerbose(page, null)));
     yield break;
 }
        public static CommentBE PostNewComment(PageBE page, DreamMessage request, DreamContext context) {
            ValidateCommentText(request.ContentType, request.AsText());

            CommentBE comment = new CommentBE();
            comment.Title = context.GetParam("title", string.Empty);
            comment.PageId = page.ID;
            comment.Content = request.AsText();
            comment.ContentMimeType = request.ContentType.ToString();
            comment.PosterUserId = DekiContext.Current.User.ID;
            comment.CreateDate = DateTime.UtcNow;

            //Note (MaxM): Replytoid/replies not yet exposed
            //ulong replyToId = context.GetParam<ulong>("replyto", 0);
            //if (replyToId == 0)
            //    newComment.ReplyToId = null;
            //else
            //    newComment.ReplyToId = replyToId;

            ushort commentNumber;
            uint commentId = DbUtils.CurrentSession.Comments_Insert(comment, out commentNumber);
            if (commentId == 0) {
                return null;
            } else {
                comment.Id = commentId;
                comment.Number = commentNumber;
                PageBL.Touch(page, comment.CreateDate);
                RecentChangeBL.AddCommentCreateRecentChange(comment.CreateDate, page, DekiContext.Current.User, string.Format(DekiResources.COMMENT_ADDED, comment.Number.ToString()), comment);
                return comment;
            } 
        }
 public Yield GetSiteStatus(DreamContext context, DreamMessage request, Result<DreamMessage> response) {
     PermissionsBL.CheckUserAllowed(DekiContext.Current.User, Permissions.UPDATE);
     var status = new XDoc("status")
         .Elem("state", DekiContext.Current.Instance.Status);
     response.Return(DreamMessage.Ok(status));
     yield break;
 }
Beispiel #15
0
		public Yield DeleteSource(DreamContext context, DreamMessage request, Result<DreamMessage> response)
		{
			Result<bool> result = new Result<bool>();
			yield return Context.Current.Instance.SourceController.Delete(context.GetParam("id"), context.GetParam("rev",null), result);

			response.Return(DreamMessage.Ok(MimeType.JSON, result.Value.ToString()));
		} 
        public Yield GetSearchDescription(DreamContext context, DreamMessage request, Result<DreamMessage> response) {
            XDoc description = new XDoc("OpenSearchDescription", "http://a9.com/-/spec/opensearch/1.1/");
            description.Elem("ShortName", string.Format(DekiResources.OPENSEARCH_SHORTNAME, DekiContext.Current.Instance.SiteName))
                       .Elem("Description", DekiResources.OPENSEARCH_DESCRIPTION)
                       .Start("Query")
                            .Attr("role", "example")
                            .Attr("searchTerms", "Wiki")
                       .End();

            // HACK HACK HACK: we can't use XUri because it encodes the "{}" characters
            string uri = DekiContext.Current.ApiUri.At("site", "opensearch").ToString();
            uri += "?q={searchTerms}&offset={startIndex}&limit={count?}&";

            description.Start("Url")
                 .Attr("type", "text/html")
                 .Attr("indexOffset", 0)
                 .Attr("template", DekiContext.Current.UiUri.At("Special:Search").ToString() + "?search={searchTerms}&offset=0&limit={count?}&format=html")
            .End()
            .Start("Url")
                 .Attr("type", "application/atom+xml")
                 .Attr("indexOffset", 0)
                 .Attr("template", uri + "format=atom")
            .End()
            .Start("Url")
                 .Attr("type", "application/rss+xml")
                 .Attr("indexOffset", 0)
                 .Attr("template", uri + "format=rss")
            .End()
            .Start("Url")
                 .Attr("type", "application/x-suggestions+json")
                 .Attr("template", DekiContext.Current.ApiUri.At("site", "opensearch", "suggestions").ToString() + "?q={searchTerms}")
             .End();
            response.Return(DreamMessage.Ok(description));
            yield break;
        }
Beispiel #17
0
        public Yield GetFileHandler(DreamContext context, DreamMessage request, Result<DreamMessage> response)
        {
            string suffixPath = string.Join("" + Path.DirectorySeparatorChar, context.GetSuffixes(UriPathFormat.Decoded));
            string filename = Path.Combine(_path, suffixPath);
            if(Directory.Exists(filename)) {
                XDoc ret = new XDoc("files");
                string pattern = context.GetParam("pattern", "");
                AddDirectories(new DirectoryInfo(filename), pattern, ret);
                AddFiles(new DirectoryInfo(filename), pattern, ret);
                response.Return(DreamMessage.Ok(ret));
                yield break;
            }

            DreamMessage message;
            try {
                message = DreamMessage.FromFile(filename, StringUtil.EqualsInvariant(context.Verb, "HEAD"));
            } catch(FileNotFoundException) {
                message = DreamMessage.NotFound("file not found");
            } catch(Exception) {
                message = DreamMessage.BadRequest("invalid path");
            }

            // open file and stream it to the requester
            response.Return(message);
        }
Beispiel #18
0
 public Yield DeleteRecord(DreamContext context, DreamMessage request, Result<DreamMessage> response)
 {
     string name = context.GetSuffix(0, UriPathFormat.Normalized);
     DeleteRecord(name);
     response.Return(DreamMessage.Ok());
     yield break;
 }
 public Yield GetArchiveFiles(DreamContext context, DreamMessage request, Result<DreamMessage> response) {
     PermissionsBL.CheckUserAllowed(DekiContext.Current.User, Permissions.ADMIN);
     IList<AttachmentBE> removedFiles = AttachmentBL.Instance.GetResources(DeletionFilter.DELETEDONLY, null, null);
     XDoc responseXml = AttachmentBL.Instance.GetFileXml(removedFiles, true, "archive", null, null);            
     response.Return(DreamMessage.Ok(responseXml));
     yield break;
 }
        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);
            DreamMessage responseMsg = null;
            if(service == null) {
                responseMsg = DreamMessage.NotFound(string.Format(DekiResources.SERVICE_NOT_FOUND, identifier));
            } else {
                responseMsg = DreamMessage.Ok(ServiceBL.GetServiceXmlVerbose(DekiContext.Current.Instance, service, null, privateDetails));
            }
            response.Return(responseMsg);
            yield break;
        }
Beispiel #21
0
 public Yield GetCommentContent(DreamContext context, DreamMessage request, Result<DreamMessage> response) {
     PageBE page = null;
     CommentBE comment = null;
     GetCommentFromRequest(context, Permissions.READ, out page, out comment);
     response.Return(DreamMessage.Ok(new MimeType(comment.ContentMimeType), comment.Content));
     yield break;
 }
Beispiel #22
0
		public Yield UpdateSource(DreamContext context, DreamMessage request, Result<DreamMessage> response)
		{
			ISource source = Context.Current.Instance.SourceController.FromJson(request.ToText());
			Result<ISource> result = new Result<ISource>();
			yield return Context.Current.Instance.SourceController.Update(context.GetParam("id"), context.GetParam("rev", null), source, result);

			response.Return(DreamMessage.Ok(MimeType.JSON, Context.Current.Instance.SourceController.ToJson(result.Value)));
		}
Beispiel #23
0
 internal IEnumerator<IYield> GetImportStatus(DreamContext context, DreamMessage request, Result<DreamMessage> response) {
     var wikiId = context.GetParam("wikiid");
     _log.DebugFormat("checking status on instance '{0}'", wikiId);
     var instance = GetInstance(wikiId, false);
     var status = instance == null ? "none" : instance.Status.ToString().ToLower();
     response.Return(DreamMessage.Ok(new XDoc("package-updater").Attr("wikiid", wikiId).Attr("status", status)));
     yield break;
 }
Beispiel #24
0
		public Yield CreatePlay(DreamContext context, DreamMessage request, Result<DreamMessage> response)
		{
			IPlay play  = Context.Current.Instance.PlayController.FromJson(request.ToText());
			Result<IPlay> result = new Result<IPlay>();
			yield return Context.Current.Instance.PlayController.Insert(play, result);

			response.Return(DreamMessage.Ok(MimeType.JSON, Context.Current.Instance.PlayController.ToJson(result.Value)));
		}
Beispiel #25
0
		public Yield GetInfo(DreamContext aContext, DreamMessage aRequest, Result<DreamMessage> aResponse)
		{
			XDoc xmlInfo = new XDoc("info");
			xmlInfo.Elem("User", Context.Current.User);
			xmlInfo.Elem("About", "Foiremuses web service (c) 2011 Vincent DARON / Danny WILLEM");
			aResponse.Return(DreamMessage.Ok(MimeType.XML, xmlInfo));
			yield break;
		}
        public Yield PutSiteRole(DreamContext context, DreamMessage request, Result<DreamMessage> response) {
            PermissionsBL.CheckUserAllowed(DekiContext.Current.User, Permissions.ADMIN);

            RoleBE role = GetRoleFromUrl(false);
            role = PermissionsBL.PutRole(role, request, context);
            response.Return(DreamMessage.Ok(PermissionsBL.GetRoleXml(role, null)));
            yield break;
        }
 public Yield GetArchive(DreamContext context, DreamMessage request, Result<DreamMessage> response) {
     PermissionsBL.CheckUserAllowed(DekiContext.Current.User, Permissions.ADMIN);
     XDoc ret = new XDoc("archive");
     ret.Start("pages.archive").Attr("href", DekiContext.Current.ApiUri.At("archive", "pages")).End();
     ret.Start("files.archive").Attr("href", DekiContext.Current.ApiUri.At("archive", "files")).End();
     response.Return(DreamMessage.Ok(ret));
     yield break;
 }
Beispiel #28
0
 public DreamMessage PostTidyXHmlt(DreamContext context, DreamMessage message) {
     string baseHref = context.Uri.GetParam("base", "");
     string pageID = context.Uri.GetParam("context", "");
     bool toEdit = context.Uri.GetParam<bool>("toEdit", false);
     XDoc doc = XDoc.FromHtml(new StreamReader(message.Stream, message.ContentEncoding));
     XHTMLConverter.Convert(doc, baseHref, pageID, toEdit);
     return DreamMessage.Ok(MimeType.XHTML, doc.Root.ToXHtml());
 }
        private Yield PrologueMediaWikiConverterContext(DreamContext context, DreamMessage request, Result<DreamMessage> response) {
            MediaWikiConverterContext mwContext = new MediaWikiConverterContext(Config);
            DreamContext.Current.SetState<MediaWikiConverterContext>(mwContext);

            // continue processing
            response.Return(request);
            yield break;
        }
Beispiel #30
0
        //--- Class Methods ---
        private static PageBE PageBL_GetPageFromUrl(DreamContext context, bool mustExist) {

            // TODO (steveb): replace all PageBL_GetPageFromUrl() calls

            var pageid = context.GetParam(PARAM_PAGEID);
            var redirects = DreamContext.Current.GetParam(PARAM_REDIRECTS, int.MaxValue);
            return PageBL_GetPage(pageid, redirects, mustExist);
        }
        internal IEnumerator <IYield> PostUpdateTemplates(DreamContext context, DreamMessage request, Result <DreamMessage> response)
        {
            var doc     = request.ToDocument();
            var wikiId  = doc["@wikiid"].AsText;
            var apiUri  = doc["uri"].AsText;
            var force   = doc["@force"].AsBool ?? false;
            var init    = doc["@init"].AsBool ?? false;
            var apiPlug = CreateApiPlug(apiUri, wikiId);

            _log.DebugFormat("received manual tickle from '{0}' @ '{1}' with force={2} and init={3}", wikiId, apiUri, force, init);
            XDoc importReport = null;

            yield return(GetInstance(wikiId, true).UpdatePackages(apiPlug, wikiId, _apikey, force, init, new Result <XDoc>()).Set(x => importReport = x));

            response.Return(DreamMessage.Ok(importReport));
            yield break;
        }
        public Yield SubscribeUserToChange(DreamContext context, DreamMessage request, Result <DreamMessage> response)
        {
            Result <PageSubscriptionUser> userResult;

            yield return(userResult = Coroutine.Invoke(GetRequestUser, request, new Result <PageSubscriptionUser>()).Catch());

            if (userResult.HasException)
            {
                ReturnUserError(userResult.Exception, response);
                yield break;
            }
            var userInfo = userResult.Value;
            var pageId   = context.GetParam <uint>("pageid");
            var userId   = context.GetParam <uint>("userid");

            if (userId != userInfo.Id && !userInfo.IsAdmin)
            {
                response.Return(DreamMessage.Forbidden("Administrator access is required."));
                yield break;
            }
            var          wikiId  = GetWikiIdFromRequest(request);
            DreamMessage userMsg = null;

            yield return(_deki.At("users", userId.ToString()).Get(new Result <DreamMessage>()).Set(x => userMsg = x));

            if (!userMsg.IsSuccessful)
            {
                response.Return(userMsg);
            }
            DreamMessage pageAuth = null;

            yield return(_deki
                         .At("pages", pageId.ToString(), "allowed")
                         .With("permissions", "read,subscribe")
                         .WithHeaders(request.Headers)
                         .Post(new XDoc("users").Start("user").Attr("id", userInfo.Id).End(), new Result <DreamMessage>())
                         .Set(x => pageAuth = x));

            if (!pageAuth.IsSuccessful || pageAuth.ToDocument()["user/@id"].AsText != userInfo.Id.ToString())
            {
                throw new DreamForbiddenException("User not permitted to subscribe to page");
            }
            GetDataSession(wikiId).Subscribe(userId, pageId, context.GetParam("depth", "0") == "0" ? false : true);
            response.Return(DreamMessage.Ok());
            yield break;
        }
 private Yield PrologueSiteIdHeader(DreamContext context, DreamMessage request, Result <DreamMessage> response)
 {
     if (context.Feature.MainStage.Access == DreamAccess.Public)
     {
         if (string.IsNullOrEmpty(request.Headers["X-Deki-Site"]))
         {
             string wikiId = context.GetParam("siteid", null);
             if (string.IsNullOrEmpty(wikiId))
             {
                 throw new DreamBadRequestException("request must contain either an X-Deki-Site header or siteid query parameter");
             }
             request.Headers.Add("X-Deki-Site", "id=" + wikiId);
         }
     }
     response.Return(request);
     yield break;
 }
Beispiel #34
0
        public static IList <ServiceBE> GetServicesByQuery(DreamContext context, out uint totalCount, out uint queryCount)
        {
            ServiceType   filterType = context.GetParam("type", ServiceType.UNDEFINED);
            uint          limit, offset;
            SortDirection sortDir;
            string        sortFieldString;

            Utils.GetOffsetAndCountFromRequest(context, 100, out limit, out offset, out sortDir, out sortFieldString);

            // Attempt to read the sort field.  If a parsing error occurs, default to undefined.
            ServicesSortField sortField = ServicesSortField.UNDEFINED;

            if (!String.IsNullOrEmpty(sortFieldString))
            {
                try { sortField = SysUtil.ChangeType <ServicesSortField>(sortFieldString); } catch { }
            }
            return(DbUtils.CurrentSession.Services_GetByQuery(filterType == ServiceType.UNDEFINED ? null : filterType.ToString(), sortDir, sortField, offset, limit, out totalCount, out queryCount));
        }
Beispiel #35
0
        public Yield PutRecord(DreamContext context, DreamMessage request, Result <DreamMessage> response)
        {
            DirectoryRecord record = new DirectoryRecord();

            record.Name  = context.GetSuffix(0, UriPathFormat.Normalized);
            record.Value = request.ToDocument();
            int ttl = context.GetParam <int>(TIME_TO_LIVE, -1);

            if (ttl >= 0)
            {
                record.Expiration = DateTime.UtcNow.AddSeconds(ttl);
            }

            // add value to directory
            InsertRecord(record);
            response.Return(DreamMessage.Ok());
            yield break;
        }
Beispiel #36
0
        protected override DreamAccess DetermineAccess(DreamContext context, string key)
        {
            var dekiContext = DekiContext.CurrentOrNull;

            if (dekiContext != null && dekiContext.HasInstance)
            {
                //For features considered 'private' or 'internal', having a correct api-key or admin rights is required
                if (!string.IsNullOrEmpty(key) && (key.EqualsInvariant(dekiContext.Instance.ApiKey) || key.EqualsInvariant(MasterApiKey)))
                {
                    return(DreamAccess.Internal);
                }
                if (PermissionsBL.IsUserAllowed(dekiContext.User, Permissions.ADMIN))
                {
                    return(DreamAccess.Internal);
                }
            }
            return(base.DetermineAccess(context, key));
        }
Beispiel #37
0
        private T Resolve <T>(DreamContext context)
        {
            var instance = context.Container.Resolve <T>();
            var dekiKey  = GetType().Assembly.GetName().GetPublicKey();
            var dreamKey = typeof(DreamService).Assembly.GetName().GetPublicKey();

            if (dekiKey.Length <= 0 || !dekiKey.SequenceEqual(dreamKey))
            {
                return(instance);
            }
            var instanceKey = instance.GetType().Assembly.GetName().GetPublicKey();

            if (dekiKey.Length > 0 && !dekiKey.SequenceEqual(instanceKey))
            {
                throw new DreamAbortException(DreamMessage.InternalError(string.Format("{0} must have same assembly signature as DekiWikiService", typeof(T))));
            }
            return(instance);
        }
Beispiel #38
0
        public Yield UserLogin(DreamContext context, DreamMessage request, Result <DreamMessage> response)
        {
            //This will attempt to bind to ldap with credentials from http header.
            //Non authentication exceptions will be returned to user.
            //Authentication failure will result in a DreamMessage.AccessDenied response
            LdapClient ldapClient = GetLdapClient(context, request, true);
            XDoc       userXml    = ldapClient.GetUserInfo(true, 3, ldapClient.UserName);

            if (userXml == null)
            {
                response.Return(DreamMessage.NotFound(string.Format("User '{0}' not found. Search query used: '{1}'", ldapClient.UserName, ldapClient.BuildUserSearchQuery(ldapClient.UserName))));
            }
            else
            {
                response.Return(DreamMessage.Ok(userXml));
            }
            yield break;
        }
Beispiel #39
0
        public Yield GetUserInfo(DreamContext context, DreamMessage request, Result <DreamMessage> response)
        {
            string     username = context.GetParam("username");
            LdapClient ldap     = GetLdapClient(context, request, false);

            XDoc userXml = ldap.GetUserInfo(true, 3, username);

            if (userXml == null)
            {
                response.Return(DreamMessage.NotFound(string.Format("User '{0}' not found. Search query used: '{1}'", username, ldap.BuildUserSearchQuery(username))));
            }
            else
            {
                response.Return(DreamMessage.Ok(userXml));
            }

            yield break;
        }
        public DreamMessage GetEditorSelect(DreamContext context, DreamMessage message)
        {
            XDoc   widgets    = GetWidgets();
            string template   = GetStorageContent("widget-editor-select.html");
            string widgetHtml = "";

            foreach (XDoc widget in widgets["widget"])
            {
                string name = widget.Contents;
                if (name == "dekibizcard")
                {
                    name = "BizCard";
                }
                widgetHtml += "<option value='" + widget.Contents + "'>" + name + "</option>";
            }

            return(DreamMessage.Ok(MimeType.HTML, ReplaceVariables(template, new MyDictionary("%%WIDGETS%%", widgetHtml))));
        }
        private void GetCommentFromRequest(DreamContext context, Permissions access, out PageBE page, out CommentBE comment)
        {
            page    = null;
            comment = null;

            ushort commentNumber = context.GetParam <ushort>("commentnumber");

            if (commentNumber != 0)
            {
                page    = PageBL_AuthorizePage(context, null, Permissions.READ, false);
                comment = DbUtils.CurrentSession.Comments_GetByPageIdNumber(page.ID, commentNumber);
            }

            if (comment == null)
            {
                throw new CommentNotFoundException();
            }
        }
Beispiel #42
0
        public DreamMessage PostEditHandler(DreamContext context, DreamMessage message)
        {
            XDoc xhtml = message.ContentType.Contains("/html")
                ? XDoc.FromHtml(new StreamReader(message.Stream, message.ContentEncoding))
                : message.Document;

            if (xhtml == null || xhtml.IsEmpty)
            {
                LogUtils.LogWarning(_log, "PostEditHandler: null/empty input document");
                throw new DreamAbortException(DreamMessage.BadRequest("null/empty input document"));
            }
            string baseHref = context.Uri.GetParam("baseHref", 0, "http://mos/");
            string pageID   = context.Uri.GetParam("context", "");

            XHTMLConverter.Convert(xhtml, baseHref, pageID, true);
            ConvertAllWidgets("PostEditHandler", xhtml, "edit", pageID);
            return(DreamMessage.Ok(MimeType.XHTML, xhtml.ToXHtml()));
        }
Beispiel #43
0
        private DreamCookie(string name, string value, XUri uri, DateTime expires, int version, bool secure, bool discard, string comment, XUri commentUri, bool httpOnly, bool skipContextDiscovery)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentException("Name cannot be empty");
            }
            _name  = name;
            _value = value;
            if (uri != null)
            {
                _uri = uri.WithoutQuery().WithoutCredentials().WithoutFragment().AsLocalUri();
                if (!skipContextDiscovery)
                {
                    DreamContext dc = DreamContext.CurrentOrNull;
                    if (dc != null)
                    {
                        _publicUri       = dc.PublicUri;
                        _localMachineUri = dc.Env.LocalMachineUri;
                    }
                }
            }

            // auto-convert very old expiration dates to max since they are most likely bogus
            if (expires.Year < 2000)
            {
                expires = DateTime.MaxValue;
            }
            if (expires != DateTime.MaxValue)
            {
                expires = expires.ToUniversalTime();

                // need to trim milliseconds of the passed in date
                expires = new DateTime(expires.Year, expires.Month, expires.Day, expires.Hour, expires.Minute, expires.Second, 0, DateTimeKind.Utc).ToUniversalTime();
            }

            // initialize cookie
            _expires    = expires;
            _version    = version;
            _secure     = secure;
            _discard    = discard;
            _comment    = comment;
            _commentUri = commentUri;
            _httpOnly   = httpOnly;
        }
Beispiel #44
0
        internal Yield PublishEvent(DreamContext context, DreamMessage request, Result <DreamMessage> response)
        {
            DispatcherEvent ev;

            try {
                ev = new DispatcherEvent(request);
                _log.DebugFormat("{0} received event '{1}'", this.Self.Uri, ev.Id);
                if (ev.Channel.Scheme == "pubsub")
                {
                    response.Return(DreamMessage.Forbidden("events published into this service cannot be of scheme 'pubsub'"));
                    yield break;
                }
                _dispatcher.Dispatch(ev);
                response.Return(DreamMessage.Ok(ev.GetEventEnvelope()));
            } catch (Exception e) {
                response.Return(DreamMessage.BadRequest(e.Message));
            }
            yield break;
        }
 public Yield FeatureGetGroups(DreamContext context, DreamMessage request, Result <DreamMessage> response)
 {
     Authenticate(context, request);
     Group[] groups = GetGroups();
     if (groups == null)
     {
         response.Return(DreamMessage.NotFound("No groups found"));
     }
     else
     {
         XDoc result = new XDoc("groups");
         foreach (Group group in groups)
         {
             result.Add(group.ToXml());
         }
         response.Return(DreamMessage.Ok(result));
     }
     yield break;
 }
        public Yield GetFileDescription(DreamContext context, DreamMessage request, Result <DreamMessage> response)
        {
            PageBE     parentPage          = null;
            ResourceBE file                = GetAttachment(context, request, Permissions.READ, true, false, out parentPage);
            ResourceBE descriptionProperty = PropertyBL.Instance.GetAttachmentDescription(file.ResourceId);

            if (descriptionProperty == null)
            {
                // reply with no data
                response.Return(DreamMessage.Ok());
            }
            else
            {
                // reply with description
                var content = ResourceContentBL.Instance.Get(descriptionProperty);
                response.Return(DreamMessage.Ok(content.MimeType, content.ToText()));
            }
            yield break;
        }
Beispiel #47
0
        internal Yield PutEntry(DreamContext context, DreamMessage request, Result <DreamMessage> response)
        {
            if (request.ToDocument().Name != "entry")
            {
                throw new DreamBadRequestException("invalid format");
            }
            string id = context.GetParam("id");

            // prepare entry
            XAtomEntry entry = new XAtomEntry(request.ToDocument());
            XUri       link  = Self.At(id);

            entry.Id = link;
            entry.AddLink(link, XAtomBase.LinkRelation.Edit, null, 0, null);

            // update feed
            XAtomFeed  feed = _feed;
            XAtomEntry oldEntry;

            if (feed != null)
            {
                lock (feed) {
                    oldEntry = new XAtomEntry(feed[string.Format("entry[id='{0}']", link)]);
                    if (!oldEntry.IsEmpty)
                    {
                        oldEntry.Replace(entry);
                    }
                }
            }
            else
            {
                throw new DreamBadRequestException("not initialized");
            }
            if (oldEntry.IsEmpty)
            {
                response.Return(DreamMessage.NotFound("entry not found"));
            }
            else
            {
                response.Return(DreamMessage.Ok(MimeType.ATOM, entry));
            }
            yield break;
        }
Beispiel #48
0
        internal Yield Notify(DreamContext context, DreamMessage request, Result <DreamMessage> response)
        {
            XDoc doc = request.ToDocument();

            yield return(Async.Fork(() => {
                uint pageId = doc["pageid"].AsUInt ?? 0;
                string user = doc["user/uri"].AsUri.Path;
                Subscription subscription;
                lock (_subscriptions) {
                    if (_subscriptions.TryGetValue(pageId, out subscription))
                    {
                        subscription.Changed(user);
                        _log.DebugFormat("page {0} changed by {1}", pageId, user);
                    }
                }
            }, new Result()).Catch());

            response.Return(DreamMessage.Ok());
        }
Beispiel #49
0
        internal static SetDiscriminator GetSetDiscriminatorFromRequest(DreamContext context, uint defaultCount, string defaultSortBy)
        {
            var discriminator = new SetDiscriminator();

            discriminator.Offset = context.GetParam <uint>("offset", 0);
            discriminator.Limit  = defaultCount;
            var limit = context.GetParam("limit", null) ?? context.GetParam("count", null) ?? context.GetParam("max", discriminator.Limit.ToString());

            if (limit.EqualsInvariantIgnoreCase("all"))
            {
                discriminator.Limit = uint.MaxValue;
            }
            else if (!uint.TryParse(limit, out discriminator.Limit))
            {
                throw new LimitParameterInvalidArgumentException();
            }
            discriminator.SetSortInfo(context.GetParam("sortby", ""), defaultSortBy);
            return(discriminator);
        }
Beispiel #50
0
        public DreamMessage GetNavHandler(DreamContext context, DreamMessage message)
        {
            DekiContext deki = null; // new DekiContext(message, this.DekiConfig);
            page        cur  = null; // deki.GetCur(true); Max: Commented out to allow compilation

            if (cur == null)
            {
                return(DreamMessage.BadRequest("can't load page"));
            }
            int  maxLevel                = context.Uri.GetParam <int>("max-level", 1);
            bool filterRedirects         = context.Uri.GetParam <bool>("redirects", true);
            ICollection <string> columns = context.Uri.GetParams("column");
            string filter                = filterRedirects ? " AND page_is_redirect=0" : "";

            XDoc ret = new XDoc("nav");

            AddCur(deki, cur, ret, columns, filter, maxLevel);
            return(DreamMessage.Ok(ret));
        }
        public Yield SiteExport(DreamContext context, DreamMessage request, Result <DreamMessage> response)
        {
            // Retrieve the title used for path normalization (if any)
            Title relToTitle = Utils.GetRelToTitleFromUrl(context) ?? Title.FromDbPath(NS.MAIN, String.Empty, null);

            // Retrieve data to export
            XDoc requestDoc = request.ToDocument();

            if (requestDoc == null || requestDoc.IsEmpty || !requestDoc.HasName("export"))
            {
                throw new PostedDocumentInvalidArgumentException("export");
            }

            // Perform the export
            MindTouch.Deki.Export.SiteExportBuilder exportBuilder = new MindTouch.Deki.Export.SiteExportBuilder(relToTitle);
            exportBuilder.Append(requestDoc);
            response.Return(DreamMessage.Ok(exportBuilder.ToDocument()));
            yield break;
        }
Beispiel #52
0
        internal Yield GetNextQueueItem(DreamContext context, DreamMessage request, Result <DreamMessage> response)
        {
            var name          = context.GetParam("queuename");
            var queue         = GetQueue(name);
            var expireSeconds = context.GetParam <int>("expire", 0);
            var expire        = expireSeconds == 0 ? _defaultExpire : TimeSpan.FromSeconds(expireSeconds);
            var item          = queue.Dequeue(expire);

            if (item == null)
            {
                response.Return(new DreamMessage(DreamStatus.NoContent, null));
                yield break;
            }
            var msg = DreamMessage.Ok(item.Value);

            msg.Headers.Location = context.Uri.At(item.Id.ToString()).AsPublicUri();
            response.Return(msg);
            yield break;
        }
Beispiel #53
0
        private string GetPath(DreamContext context)
        {
            string[] parts = context.GetSuffixes(UriPathFormat.Decoded);
            string   path  = _path;

            foreach (string part in parts)
            {
                if (part.EqualsInvariant(".."))
                {
                    throw new DreamBadRequestException("paths cannot contain '..'");
                }
                path = Path.Combine(path, part);
            }
            if (_privateRoot && (parts.Length == 0 || (parts.Length == 1 && !Directory.Exists(path))))
            {
                throw new DreamForbiddenException("Root level access is forbidden for this storage service");
            }
            return(path);
        }
Beispiel #54
0
        public DreamMessage PostPasteHandler(DreamContext context, DreamMessage message)
        {
            XDoc xhtml = message.ContentType.Contains("/html")
                ? XDoc.FromHtml(new StreamReader(message.Stream, message.ContentEncoding))
                : message.Document;

            if (xhtml == null || xhtml.IsEmpty)
            {
                LogUtils.LogWarning(_log, "PostEditHandler: null/empty input document");
                throw new DreamAbortException(DreamMessage.BadRequest("null/empty input document"));
            }
            string baseHref = context.Uri.GetParam("baseHref", 0, "http://mos/");
            string pageID   = context.Uri.GetParam("context", "");

            XHTMLConverter.Convert(xhtml, baseHref, pageID, true);

            MindTouch.Dream.Plug plug = MindTouch.Dream.Plug.New(Env.RootUri);
            foreach (XDoc nodeWithClass in xhtml["//*[@class='vcard']"])
            {
                XDoc replacement = plug.At("wiki-data", "dekibizcard", "hcardtoedit").Post(nodeWithClass).Document;
                if (replacement != null && !replacement.IsEmpty)
                {
                    nodeWithClass.Replace(replacement);
                }
            }

            bool insertMagic = context.Uri.GetParam <bool>("insertMagic", false);

            if (insertMagic)
            {
                Plug widgetStorage = Plug.New(Env.RootUri).At("mount", "deki-widgets");
                Plug widgetToEdit  = Plug.New(Env.RootUri.At("wiki-data", "dekibizcard", "edit"));
                XDoc files         = widgetStorage.With("pattern", "*.vcf").Get().Document;
                foreach (XDoc fileName in files["file/name"])
                {
                    XDoc vcard       = XDoc.FromVersit(widgetStorage.At(fileName.Contents).Get().Text, "dekibizcard");
                    XDoc widgetXhtml = widgetToEdit.Post(vcard).Document;
                    xhtml["//body"].Add(widgetXhtml);
                }
            }
            return(DreamMessage.Ok(MimeType.HTML, xhtml.ToString()));
        }
Beispiel #55
0
        public Yield GetFileOrFolderListing(DreamContext context, DreamMessage request, Result <DreamMessage> response)
        {
            var          head = "HEAD".EqualsInvariant(context.Verb);
            var          path = GetPath(context);
            var          data = _s3Client.GetDataInfo(path, head);
            DreamMessage result;

            if (data == null)
            {
                response.Return(DreamMessage.NotFound("no such file or folder"));
                yield break;
            }
            if (data.IsDirectory)
            {
                // Note (arnec): HEAD for a directory doesn't really mean anything, so we just return ok, to indicate that it exists
                result = head ? DreamMessage.Ok() : DreamMessage.Ok(data.AsDirectoryDocument());
            }
            else
            {
                // dealing with a file request
                var filehandle = data.AsFileHandle();

                // check if request contains a 'if-modified-since' header
                if (request.CheckCacheRevalidation(filehandle.Modified) && (filehandle.Modified.Year >= 1900))
                {
                    response.Return(DreamMessage.NotModified());
                    yield break;
                }
                result = head
                             ? new DreamMessage(DreamStatus.Ok, null, filehandle.MimeType, filehandle.Size, Stream.Null)
                             : DreamMessage.Ok(filehandle.MimeType, filehandle.Size, filehandle.Stream);

                // add caching headers if file was found
                if (!head && result.IsSuccessful)
                {
                    // add caching information; this will avoid unnecessary data transfers by user-agents with caches
                    result.SetCacheMustRevalidate(filehandle.Modified);
                }
            }
            response.Return(result);
            yield break;
        }
Beispiel #56
0
            public Yield CallPlug(DreamContext context, DreamMessage request, Result <DreamMessage> response)
            {
                _log.Debug("callplug start");
                var guid = Guid.NewGuid();

                ContextVar = new ContextLifeSpan(guid);
                context.SetState(guid);
                _log.Debug("setting disposable state");
                context.SetState(ContextVar);
                Result <DreamMessage> sub;

                _log.Debug("calling plug");
                yield return(sub = Self.At("calledplug").GetAsync());

                _log.Debug("return from plug");
                if (!sub.Value.IsSuccessful)
                {
                    response.Return(sub.Value);
                }
                var contextVar = context.GetState <ContextLifeSpan>();

                if (contextVar == null)
                {
                    throw new Exception("context instance is gone");
                }
                if (contextVar.Guid != guid)
                {
                    throw new Exception("context guid is wrong");
                }
                if (contextVar != ContextVar)
                {
                    throw new Exception("context instance changed");
                }
                if (contextVar.IsDisposed)
                {
                    throw new Exception("context is disposed");
                }
                _log.Debug("callplug return");
                response.Return(DreamMessage.Ok());
                _log.Debug("callplug end");
                yield break;
            }
Beispiel #57
0
 protected Yield ReplaceSubscribeSet(DreamContext context, DreamMessage request, Result <DreamMessage> response)
 {
     try {
         string setId = context.GetParam("id");
         _log.DebugFormat("Updating set {0}", setId);
         if (!string.IsNullOrEmpty(request.Headers.DreamEventId))
         {
             _log.DebugFormat("'{0}' update is event: {1} - {2}", setId, request.Headers.DreamEventChannel, request.Headers.DreamEventId);
         }
         XDoc subscriptionDocument = request.ToDocument();
         PubSubSubscriptionSet set = _dispatcher.ReplaceSet(setId, subscriptionDocument);
         if (set != null)
         {
             long?version = subscriptionDocument["@version"].AsLong;
             if (version.HasValue && version.Value <= set.Version)
             {
                 _log.DebugFormat("set not modified: {0}", setId);
                 response.Return(DreamMessage.NotModified());
             }
             else
             {
                 if (version.HasValue)
                 {
                     _log.DebugFormat("Updating set '{0}' from version {1} to {2}", setId, set.Version, version);
                 }
                 else
                 {
                     _log.DebugFormat("Updating set '{0}'", setId);
                 }
                 response.Return(DreamMessage.Ok());
             }
         }
         else
         {
             _log.DebugFormat("no such set: {0}", setId);
             response.Return(DreamMessage.NotFound("There is no subscription set at this location"));
         }
     } catch (ArgumentException e) {
         response.Return(DreamMessage.Forbidden(e.Message));
     }
     yield break;
 }
Beispiel #58
0
        public ArrayList Issues(
            [DekiExtParam("query expression (default: all issues)", true)] string query,
            [DekiExtParam("number of items to skip (default: 0)", true)] int?offset,
            [DekiExtParam("maximum number of items to return (default: 100)", true)] int?limit,
            [DekiExtParam("get only issues updated after specified date.", true)] string since
            )
        {
            Login();
            var request = _server.At("rest", "project", "issues");

            // check if a query was provided
            if (!string.IsNullOrEmpty(query))
            {
                request = request.With("filter", query);
            }

            // check if a limit and offset were provided
            if (offset.HasValue)
            {
                request = request.With("after", offset.Value);
            }
            request = request.With("max", limit ?? 100);

            // check if a date limit was provide
            if (!string.IsNullOrEmpty(since))
            {
                DreamContext context = DreamContext.CurrentOrNull;
                CultureInfo  culture = (context == null) ? CultureInfo.CurrentCulture : context.Culture;
                double       dummy;
                var          date = DekiScriptLibrary.CultureDateTimeParse(since, culture, out dummy);
                request = request.With("updatedAfter", date.ToEpoch());
            }
            var doc = request.Get().ToDocument();

            var result = new ArrayList();

            foreach (var issue in doc["issue"])
            {
                result.Add(ConvertIssue(issue));
            }
            return(result);
        }
        public Yield GetSiteLogo(DreamContext context, DreamMessage request, Result <DreamMessage> response)
        {
            DreamMessage responseMsg = null;
            DateTime     modified    = DekiContext.Current.Instance.Storage.GetSiteFileTimestamp(LOGO_LABEL);

            try {
                if (modified != DateTime.MinValue)
                {
                    if (request.CheckCacheRevalidation(modified))
                    {
                        responseMsg = DreamMessage.NotModified();
                    }
                }

                if (responseMsg == null)
                {
                    StreamInfo file = DekiContext.Current.Instance.Storage.GetSiteFile(LOGO_LABEL, false);
                    if (file != null)
                    {
                        responseMsg = DreamMessage.Ok(MimeType.PNG, file.Length, file.Stream);

                        //Build the content disposition headers
                        responseMsg.Headers.ContentDisposition = new ContentDisposition(true, file.Modified ?? DateTime.UtcNow, null, null, "logo.png", file.Length);

                        //Set caching headers
                        responseMsg.SetCacheMustRevalidate(modified);
                    }
                    else
                    {
                        responseMsg = DreamMessage.NotFound("Logo has not been uploaded");
                    }
                }
            } catch {
                if (responseMsg != null)
                {
                    responseMsg.Close();
                }
                throw;
            }
            response.Return(responseMsg);
            yield break;
        }
Beispiel #60
0
        public Yield GetArchivePages(DreamContext context, DreamMessage request, Result <DreamMessage> response)
        {
            PermissionsBL.CheckUserAllowed(DekiContext.Current.User, Permissions.ADMIN);
            uint          limit, offset;
            SortDirection sortDir;
            string        sortField;

            Utils.GetOffsetAndCountFromRequest(context, 100, out limit, out offset, out sortDir, out sortField);
            Title  filterTitle = null;
            string titleStr    = context.GetParam("title", null);

            if (!string.IsNullOrEmpty(titleStr))
            {
                filterTitle = Title.FromUIUri(null, titleStr, false);
            }
            XDoc responseXml = PageArchiveBL.GetArchivedPagesXml(limit, offset, filterTitle);

            response.Return(DreamMessage.Ok(responseXml));
            yield break;
        }