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 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;
 }
        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;
        }
Esempio n. 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;
 }
Esempio n. 5
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;
 }
Esempio n. 6
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);
 }
        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;
        }
Esempio n. 8
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;
 }
Esempio n. 9
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 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 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;
        }
Esempio n. 12
0
 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;
 } 
 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;
 }
Esempio n. 14
0
        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;
            } 
        }
Esempio n. 15
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;
 }
Esempio n. 16
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()));
		} 
Esempio n. 17
0
 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;
 }
Esempio n. 18
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);
        }
        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;
        }
 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 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;
 }
Esempio n. 22
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;
 }
 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;
 }
        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;
        }
        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;
        }
Esempio n. 26
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;
		}
Esempio n. 27
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);
        }
Esempio n. 28
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)));
		}
Esempio n. 29
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());
 }
Esempio n. 30
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)));
		}