public AjaxResponse SaveUserLanguageSettings(string lng)
        {
            var resp = new AjaxResponse();
            try
            {                
                var user = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID);

                var changelng = false;
                if (SetupInfo.EnabledCultures.Find(c => String.Equals(c.Name, lng, StringComparison.InvariantCultureIgnoreCase)) != null)
                {
                    if (user.CultureName != lng)
                    {
                        user.CultureName = lng;
                        changelng = true;
                    }
                }
                CoreContext.UserManager.SaveUserInfo(user);
                if (changelng)
                {
                    resp.rs1 = "1";
                }
                else
                {
                    resp.rs1 = "2";
                    resp.rs2 = "<div class=\"okBox\">" + Resources.Resource.SuccessfullySaveSettingsMessage + "</div>";
                }
            }
            catch (Exception e)
            {
                resp.rs1 = "0";
                resp.rs2 = "<div class=\"errorBox\">" + e.Message.HtmlEncode() + "</div>";
            }
            return resp;
        }
        public AjaxResponse RemoveUser(Guid userID)
        {
            var resp = new AjaxResponse();
            try
            {
                SecurityContext.DemandPermissions(Constants.Action_AddRemoveUser);

                var user = CoreContext.UserManager.GetUsers(userID);
                var userName = user.DisplayUserName(false);

                UserPhotoManager.RemovePhoto(Guid.Empty, userID);
                CoreContext.UserManager.DeleteUser(userID);

                MessageService.Send(HttpContext.Current.Request, MessageAction.UserDeleted, userName);

                resp.rs1 = "1";
                resp.rs2 = Resource.SuccessfullyDeleteUserInfoMessage;
            }
            catch(Exception e)
            {
                resp.rs1 = "0";
                resp.rs2 = HttpUtility.HtmlEncode(e.Message);
            }

            return resp;
        }
        public AjaxResponse RemaindPwd(string email)
        {
            AjaxResponse responce = new AjaxResponse();
            responce.rs1 = "0";

            if (!email.TestEmailRegex())
            {
                responce.rs2 = "<div>" + Resources.Resource.ErrorNotCorrectEmail + "</div>";
                return responce;
            }

            try
            {
                UserManagerWrapper.SendUserPassword(email);

                responce.rs1 = "1";
                responce.rs2 = String.Format(Resources.Resource.MessageYourPasswordSuccessfullySendedToEmail, email);
            }
            catch (Exception exc)
            {
                responce.rs2 = "<div>" + HttpUtility.HtmlEncode(exc.Message) + "</div>";
            }

            return responce;
        }
        public AjaxResponse SubscribeOnTopic(int idTopic, int statusNotify)
        {
            var resp = new AjaxResponse();

            if (statusNotify == 1 && Subscribe != null)
            {
                Subscribe(this, new SubscribeEventArgs(SubscriptionConstants.NewPostInTopic,
                                                       idTopic.ToString(),
                                                       SecurityContext.CurrentAccount.ID));

                resp.rs1 = "1";
                resp.rs2 = RenderTopicSubscription(false, idTopic);
                resp.rs3 = "subscribed";
            }
            else if (UnSubscribe != null)
            {
                UnSubscribe(this, new SubscribeEventArgs(SubscriptionConstants.NewPostInTopic,
                                                         idTopic.ToString(),
                                                         SecurityContext.CurrentAccount.ID));

                resp.rs1 = "1";
                resp.rs2 = RenderTopicSubscription(true, idTopic);
                resp.rs3 = "unsubscribed";
            }
            else
            {
                resp.rs1 = "0";
                resp.rs2 = Resources.ForumResource.ErrorSubscription;
            }
            return resp;
        }
        public AjaxResponse RemindPwd(string email)
        {
            var responce = new AjaxResponse {rs1 = "0"};

            if (!email.TestEmailRegex())
            {
                responce.rs2 = "<div>" + Resource.ErrorNotCorrectEmail + "</div>";
                return responce;
            }

            try
            {
                UserManagerWrapper.SendUserPassword(email);

                responce.rs1 = "1";
                responce.rs2 = String.Format(Resource.MessageYourPasswordSuccessfullySendedToEmail, "<b>" + email + "</b>");

                var user = CoreContext.UserManager.GetUserByEmail(email).DisplayUserName(false);
                MessageService.Send(HttpContext.Current.Request, MessageAction.UserSentPasswordChangeInstructions, user);
            }
            catch(Exception exc)
            {
                responce.rs2 = "<div>" + HttpUtility.HtmlEncode(exc.Message) + "</div>";
            }

            return responce;
        }
        public AjaxResponse SendJoinInviteMail(string email)
        {

            email = (email ?? "").Trim();
            AjaxResponse resp = new AjaxResponse();
            resp.rs1 = "0";

            try
            {
                if (!email.TestEmailRegex())
                    resp.rs2 = Resources.Resource.ErrorNotCorrectEmail;

                var user = CoreContext.UserManager.GetUserByEmail(email);
                if (!user.ID.Equals(ASC.Core.Users.Constants.LostUser.ID))
                {
                    resp.rs1 = "0";
                    resp.rs2 = CustomNamingPeople.Substitute<Resources.Resource>("ErrorEmailAlreadyExists").HtmlEncode();
                    return resp;
                }

                var tenant = CoreContext.TenantManager.GetCurrentTenant();

                if (tenant.TrustedDomainsType == TenantTrustedDomainsType.Custom)
                {
                    var address = new MailAddress(email);
                    foreach (var d in tenant.TrustedDomains)
                    {
                        if (address.Address.EndsWith("@" + d, StringComparison.InvariantCultureIgnoreCase))
                        {
                            StudioNotifyService.Instance.InviteUsers(email, "", true, false);
                            resp.rs1 = "1";
                            resp.rs2 = Resources.Resource.FinishInviteJoinEmailMessage;
                            return resp;
                        }
                    }
                }
                else if (tenant.TrustedDomainsType == TenantTrustedDomainsType.All)
                {
                    StudioNotifyService.Instance.InviteUsers(email, "", true, false);
                    resp.rs1 = "1";
                    resp.rs2 = Resources.Resource.FinishInviteJoinEmailMessage;
                    return resp;
                }

                resp.rs2 = Resources.Resource.ErrorNotCorrectEmail;
            }
            catch (FormatException)
            {
                resp.rs2 = Resources.Resource.ErrorNotCorrectEmail;
            }
            catch (Exception e)
            {
                resp.rs2 = HttpUtility.HtmlEncode(e.Message);
            }

            return resp;
        }
		public AjaxResponse SendInviteMails(string text, string emails, bool withFullAccessPrivileges)
		{
            SecurityContext.DemandPermissions(ASC.Core.Users.Constants.Action_AddRemoveUser);

			AjaxResponse resp = new AjaxResponse();
			resp.rs1 = "0";
			try
			{
                SecurityContext.DemandPermissions(ASC.Core.Users.Constants.Action_AddRemoveUser);

				string[] addresses = null;
				try
				{
					addresses = StudioNotifyService.Instance.GetEmails(emails);
					if (addresses == null || addresses.Length == 0)
						resp.rs2 = Resources.Resource.ErrorNoEmailsForInvite;
					else
					{
						foreach (var emailStr in addresses)
						{
							var email = (emailStr ?? "").Trim();
							if (!email.TestEmailRegex())
							{
								resp.rs1 = "0";
								resp.rs2 = email + " - " + Resources.Resource.ErrorNotCorrectEmail;
								return resp;
							}

							var user = CoreContext.UserManager.GetUserByEmail(email);
							if (!user.ID.Equals(ASC.Core.Users.Constants.LostUser.ID))
							{
								resp.rs1 = "0";
								resp.rs2 = email + " - " + CustomNamingPeople.Substitute<Resources.Resource>("ErrorEmailAlreadyExists").HtmlEncode();
								return resp;
							}
						}

						StudioNotifyService.Instance.InviteUsers(emails, text, false, withFullAccessPrivileges);
						resp.rs1 = "1";
						resp.rs2 = Resources.Resource.FinishInviteEmailTitle;
					}
				}
				catch
				{
					resp.rs2 = Resources.Resource.ErrorNoEmailsForInvite;
				}

			}
			catch (Exception e)
			{
				resp.rs2 = HttpUtility.HtmlEncode(e.Message);
			}

			return resp;
		}
        public object TestSmtpSettings(string email)
        {

            AjaxResponse resp = new AjaxResponse();
            if (!email.TestEmailRegex())            
                return new { Status = 0, Message = Resources.Resource.ErrorNotCorrectEmail };                            

            try
            {
                SecurityContext.DemandPermissions(SecutiryConstants.EditPortalSettings);

                MailMessage mail = new MailMessage();
                mail.To.Add(email);

                mail.Subject = Resources.Resource.TestSMTPEmailSubject;
                mail.Priority = MailPriority.Normal;
                mail.IsBodyHtml = false;
                mail.BodyEncoding = System.Text.Encoding.UTF8;
                mail.From = new MailAddress(CoreContext.Configuration.SmtpSettings.SenderAddress,
                                                    CoreContext.Configuration.SmtpSettings.SenderDisplayName,
                                                    System.Text.Encoding.UTF8);


                mail.Body = Resources.Resource.TestSMTPEmailBody;

                SmtpClient client = new SmtpClient(CoreContext.Configuration.SmtpSettings.Host, CoreContext.Configuration.SmtpSettings.Port ?? 25);
                client.EnableSsl = CoreContext.Configuration.SmtpSettings.EnableSSL;

                if (client.EnableSsl)
                {
                    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Ssl3;
                }

                if (String.IsNullOrEmpty(CoreContext.Configuration.SmtpSettings.CredentialsUserName))
                {
                    client.UseDefaultCredentials = true;
                }
                else
                {
                    client.Credentials = new NetworkCredential(
                        CoreContext.Configuration.SmtpSettings.CredentialsUserName,
                        CoreContext.Configuration.SmtpSettings.CredentialsUserPassword,
                        CoreContext.Configuration.SmtpSettings.CredentialsDomain);
                }
                client.Send(mail);

                return new { Status = 1, Message = Resources.Resource.SuccessfullySMTPTestMessage };         
            }
            catch (Exception e)
            {
                return new { Status = 0, Message = e.Message.HtmlEncode() };  
            }
        }
        public AjaxResponse RequestPayPal(int qoutaId)
        {
            var res = new AjaxResponse();

            try
            {
                if (!HttpRuntime.Cache.Get(PartnerCache).Equals(DateTime.UtcNow))
                    HttpRuntime.Cache.Insert(PartnerCache, DateTime.UtcNow);

                var partnerId = CoreContext.TenantManager.GetCurrentTenant().PartnerId;
                var partner = CoreContext.PaymentManager.GetPartner(partnerId);

                if (partner == null || partner.Status != PartnerStatus.Approved || partner.Removed || partner.PaymentMethod != PartnerPaymentMethod.PayPal)
                {
                    throw new MethodAccessException(Resource.PartnerPayPalExc);
                }

                var tenantQuota = TenantExtra.GetTenantQuota(qoutaId);

                var curruntQuota = TenantExtra.GetTenantQuota();
                if (TenantExtra.GetCurrentTariff().State == TariffState.Paid
                    && tenantQuota.ActiveUsers < curruntQuota.ActiveUsers
                    && tenantQuota.Year == curruntQuota.Year)
                {
                    throw new MethodAccessException(Resource.PartnerPayPalDowngrade);
                }

                if (tenantQuota.Price > partner.AvailableCredit)
                {
                    CoreContext.PaymentManager.RequestClientPayment(partnerId, qoutaId, false);
                    throw new Exception(Resource.PartnerRequestLimitInfo);
                }

                var usersCount = TenantStatisticsProvider.GetUsersCount();
                var usedSize = TenantStatisticsProvider.GetUsedSize();

                if (tenantQuota.ActiveUsers < usersCount || tenantQuota.MaxTotalSize < usedSize)
                {
                    res.rs2 = "quotaexceed";
                    return res;
                }

                res.rs1 = CoreContext.PaymentManager.GetButton(partner.Id, qoutaId);
            }
            catch (Exception e)
            {
                res.message = e.Message;
            }
            return res;
        }
        public AjaxResponse JoinToAffiliateProgram()
        {
            var resp = new AjaxResponse();
            try
            {
                resp.rs1 = "1";
                resp.rs2 = AffiliateHelper.Join();
            }
            catch (Exception e)
            {
                resp.rs1 = "0";
                resp.rs2 = HttpUtility.HtmlEncode(e.Message);
            }
            return resp;

        }
        public AjaxResponse RemindPwd(string email)
        {
            var response = new AjaxResponse {rs1 = "0"};

            if (!email.TestEmailRegex())
            {
                response.rs2 = "<div>" + Resource.ErrorNotCorrectEmail + "</div>";
                return response;
            }

            var tenant = CoreContext.TenantManager.GetCurrentTenant();
            if (tenant != null)
            {
                var settings = SettingsManager.Instance.LoadSettings<IPRestrictionsSettings>(tenant.TenantId);
                if (settings.Enable && !IPSecurity.IPSecurity.Verify(tenant.TenantId))
                {
                    response.rs2 = "<div>" + Resource.ErrorAccessRestricted + "</div>";
                    return response;
                }
            }

            try
            {
                UserManagerWrapper.SendUserPassword(email);

                response.rs1 = "1";
                response.rs2 = String.Format(Resource.MessageYourPasswordSuccessfullySendedToEmail, "<b>" + email + "</b>");
                var userInfo = CoreContext.UserManager.GetUserByEmail(email);

                if (userInfo.Sid != null)
                {
                    response.rs2 = "<div>" + Resource.CouldNotRecoverPasswordForLdapUser + "</div>";
                    return response;
                }

                string displayUserName = userInfo.DisplayUserName(false);

                MessageService.Send(HttpContext.Current.Request, MessageAction.UserSentPasswordChangeInstructions, displayUserName);
            }
            catch(Exception ex)
            {
                response.rs2 = "<div>" + HttpUtility.HtmlEncode(ex.Message) + "</div>";
            }

            return response;
        }
        public AjaxResponse SaveNotifyBarSettings(bool showPromotions)
        {
            AjaxResponse resp = new AjaxResponse();
            _studioNotifyBarSettings = SettingsManager.Instance.LoadSettings<StudioNotifyBarSettings>(TenantProvider.CurrentTenantID);
            _studioNotifyBarSettings.ShowPromotions = showPromotions;
            if (SettingsManager.Instance.SaveSettings<StudioNotifyBarSettings>(_studioNotifyBarSettings, TenantProvider.CurrentTenantID))
            {
                resp.rs1 = "1";
                resp.rs2 = "<div class=\"okBox\">" + Resources.Resource.SuccessfullySaveSettingsMessage + "</div>";
            }
            else
            {
                resp.rs1 = "0";
                resp.rs2 = "<div class=\"errorBox\">" + Resources.Resource.UnknownError + "</div>";
            }

            return resp;
        }
        public object SaveLanguageTimeSettings(string lng, string timeZoneID)
        {
            var resp = new AjaxResponse();
            try
            {
                SecurityContext.DemandPermissions(SecutiryConstants.EditPortalSettings);

                var tenant = CoreContext.TenantManager.GetCurrentTenant();
                var culture = CultureInfo.GetCultureInfo(lng);

                var changelng = false;
                if (SetupInfo.EnabledCultures.Find(c => String.Equals(c.Name, culture.Name, StringComparison.InvariantCultureIgnoreCase)) != null)
                {
                    if (!String.Equals(tenant.Language, culture.Name, StringComparison.InvariantCultureIgnoreCase))
                    {
                        tenant.Language = culture.Name;
                        changelng = true;
                    }
                }

                var oldTimeZone = tenant.TimeZone;
                tenant.TimeZone = new List<TimeZoneInfo>(TimeZoneInfo.GetSystemTimeZones()).Find(tz => String.Equals(tz.Id, timeZoneID));

                CoreContext.TenantManager.SaveTenant(tenant);
                
                if (!tenant.TimeZone.Id.Equals(oldTimeZone.Id) || changelng)
                {
                    AdminLog.PostAction("Settings: saved language and time zone settings with parameters language={0},time={1}", lng, timeZoneID);
                }

                if (changelng)
                {
                    return new { Status = 1, Message = String.Empty };
                }
                else
                {
                    return new { Status = 2, Message = Resources.Resource.SuccessfullySaveSettingsMessage };
                }
            }
            catch (Exception e)
            {
                return new { Status = 0, Message = e.Message.HtmlEncode() };
            }
        }       
        public AjaxResponse GetSuggest(Guid settingsID, string text, string varName)
        {
            AjaxResponse resp = new AjaxResponse();

            string startSymbols = text;
            int ind = startSymbols.LastIndexOf(",");
            if (ind != -1)
                startSymbols = startSymbols.Substring(ind + 1);

            startSymbols = startSymbols.Trim();

            var tags = new List<Tag>();

            if (!String.IsNullOrEmpty(startSymbols))
                tags = ForumDataProvider.SearchTags(TenantProvider.CurrentTenantID, startSymbols);

            int counter = 0;
            string resNames = "", resHelps = "";

            foreach (var tag in tags)
            {
                if (counter > 10)
                    break;

                resNames += tag.Name + "$";
                resHelps += tag.ID + "$";
                counter++;
            }

            resNames = resNames.TrimEnd('$');
            resHelps = resHelps.TrimEnd('$');
            resp.rs1 = resNames;
            resp.rs2 = resHelps;
            resp.rs3 = text;
            resp.rs4 = varName;

            return resp;
        }
        public AjaxResponse SubscribeOnComments(Guid postID, int statusNotify)
        {
            var resp = new AjaxResponse();
            try
            {
                if (statusNotify == 1)
                {
                    _subscriptionProvider.Subscribe(
                        ASC.Blogs.Core.Constants.NewComment,
                        postID.ToString(),
                        IAmAsRecipient
                        );


                    resp.rs1 = "1";
                    resp.rs2 = RenderCommentsSubscription(false, postID);
                }
                else
                {

                    _subscriptionProvider.UnSubscribe(
                        ASC.Blogs.Core.Constants.NewComment,
                        postID.ToString(),
                        IAmAsRecipient
                        );

                    resp.rs1 = "1";
                    resp.rs2 = RenderCommentsSubscription(true, postID);
                }
            }
            catch (Exception e)
            {
                resp.rs1 = "0";
                resp.rs2 = HttpUtility.HtmlEncode(e.Message);
            }

            return resp;
        }
        public AjaxResponse SubscribePersonalBlog(Guid userID, int statusNotify)
        {
            var resp = new AjaxResponse();
            try
            {
                if (statusNotify == 1)
                {
                    _subscriptionProvider.Subscribe(
                        ASC.Blogs.Core.Constants.NewPostByAuthor,
                        userID.ToString(),
                        IAmAsRecipient
                        );


                    resp.rs1 = "1";
                    resp.rs2 = RenderPersonalBlogSubscriptionLink(false, userID);
                }
                else
                {
                    _subscriptionProvider.UnSubscribe(
                        ASC.Blogs.Core.Constants.NewPostByAuthor,
                        userID.ToString(),
                        IAmAsRecipient
                        );

                    resp.rs1 = "1";
                    resp.rs2 = RenderPersonalBlogSubscriptionLink(true, userID);
                }
            }
            catch (Exception e)
            {
                resp.rs1 = "0";
                resp.rs2 = HttpUtility.HtmlEncode(e.Message);
            }

            return resp;
        }
        public AjaxResponse UpdateComment(string commentID, string text, string pid)
        {
            var resp = new AjaxResponse { rs1 = commentID };

            Guid? id = null;
            try
            {
                if (!String.IsNullOrEmpty(commentID))
                    id = new Guid(commentID);
            }
            catch
            {
                return new AjaxResponse();
            }

            var engine = GetEngine();

            var comment = engine.GetCommentById(id.Value);
            if (comment == null)
                throw new ApplicationException("Comment not found");

            CommunitySecurity.DemandPermissions(comment, Constants.Action_EditRemoveComment);

            comment.Content = text;

            var post = engine.GetPostById(comment.PostId);
            engine.UpdateComment(comment, post);

            resp.rs2 = text + CodeHighlighter.GetJavaScriptLiveHighlight(true);

            return resp;
        }
        public AjaxResponse AddComment(string parrentCommentID, string blogID, string text, string pid)
        {
            Guid postId;
            Guid? parentId = null;
            try
            {
                postId = new Guid(blogID);

                if (!String.IsNullOrEmpty(parrentCommentID))
                    parentId = new Guid(parrentCommentID);
            }
            catch
            {
                return new AjaxResponse();
            }

            var engine = GetEngine();

            var resp = new AjaxResponse { rs1 = parrentCommentID };

            var post = engine.GetPostById(postId);

            if (post == null)
            {
                return new AjaxResponse { rs10 = "postDeleted", rs11 = Constants.DefaultPageUrl };
            }

            CommunitySecurity.DemandPermissions(post, Constants.Action_AddComment);

            var newComment = new Comment
                {
                    PostId = postId,
                    Content = text,
                    Datetime = ASC.Core.Tenants.TenantUtil.DateTimeNow(),
                    UserID = SecurityContext.CurrentAccount.ID
                };

            if (parentId.HasValue)
                newComment.ParentId = parentId.Value;

            engine.SaveComment(newComment, post);

            //mark post as seen for the current user
            engine.SavePostReview(post, SecurityContext.CurrentAccount.ID);
            resp.rs2 = GetHTMLComment(newComment, false);

            return resp;
        }
        public AjaxResponse DoDeleteTopic(int idTopic, Guid settingsID)
        {
            _forumManager = ForumManager.GetForumManager(settingsID);
            var resp = new AjaxResponse { rs2 = idTopic.ToString() };

            var topic = ForumDataProvider.GetTopicByID(TenantProvider.CurrentTenantID, idTopic);
            if (topic == null)
            {
                resp.rs1 = "0";
                resp.rs3 = Resources.ForumUCResource.ErrorAccessDenied;
                return resp;
            }

            if (!_forumManager.ValidateAccessSecurityAction(ForumAction.TopicDelete, topic))
            {
                resp.rs1 = "0";
                resp.rs3 = Resources.ForumUCResource.ErrorAccessDenied;
                return resp;
            }

            try
            {
                List<int> removedPostIDs;
                var attachmantOffsetPhysicalPaths = ForumDataProvider.RemoveTopic(TenantProvider.CurrentTenantID, topic.ID, out removedPostIDs);

                resp.rs1 = "1";
                resp.rs3 = Resources.ForumUCResource.SuccessfullyDeleteTopicMessage;
                resp.rs4 = topic.ThreadID.ToString();
                _forumManager.RemoveAttachments(attachmantOffsetPhysicalPaths.ToArray());

                removedPostIDs.ForEach(idPost => CommonControlsConfigurer.FCKUploadsRemoveForItem(_forumManager.Settings.FileStoreModuleID, idPost.ToString()));
            }
            catch (Exception ex)
            {
                resp.rs1 = "0";
                resp.rs3 = ex.Message.HtmlEncode();
            }

            return resp;
        }
        public AjaxResponse DoStickyTopic(int idTopic, Guid settingsID)
        {
            _forumManager = ForumManager.GetForumManager(settingsID);
            var resp = new AjaxResponse { rs2 = idTopic.ToString() };

            var topic = ForumDataProvider.GetTopicByID(TenantProvider.CurrentTenantID, idTopic);
            if (topic == null)
            {
                resp.rs1 = "0";
                resp.rs3 = Resources.ForumUCResource.ErrorAccessDenied;
                return resp;
            }

            if (!_forumManager.ValidateAccessSecurityAction(ForumAction.TopicSticky, topic))
            {
                resp.rs1 = "0";
                resp.rs3 = Resources.ForumUCResource.ErrorAccessDenied;
                return resp;
            }

            topic.Sticky = !topic.Sticky;
            try
            {
                ForumDataProvider.UpdateTopic(TenantProvider.CurrentTenantID, topic.ID, topic.Title, topic.Sticky, topic.Closed);

                resp.rs1 = "1";
                if (topic.Sticky)
                {

                    resp.rs3 = Resources.ForumUCResource.SuccessfullyStickyTopicMessage;
                    resp.rs4 = Resources.ForumUCResource.ClearStickyTopicButton;
                }
                else
                {
                    resp.rs3 = Resources.ForumUCResource.SuccessfullyClearStickyTopicMessage;
                    resp.rs4 = Resources.ForumUCResource.StickyTopicButton;
                }
            }
            catch (Exception e)
            {
                resp.rs1 = "0";
                resp.rs3 = HttpUtility.HtmlEncode(e.Message);
            }
            return resp;
        }
        public AjaxResponse CheckAttachment()
        {
            var response = new AjaxResponse();

            try
            {
                using (var serverManager = new ServerManager())
                {
                    if (CoreContext.Configuration.Standalone && serverManager.Sites.SelectMany(r => r.Bindings).Any(r => r.BindingInformation.Contains("*:443:")))
                    {
                        response.status = "error";
                        return response;
                    }
                }

                response.status = "success";
            }
            catch (Exception e)
            {
                response.status = "error";
                response.message = e.Message;
            }

            return response;
        }
        public AjaxResponse SendJoinInviteMail(string email)
        {

            email = (email ?? "").Trim();
            var resp = new AjaxResponse { rs1 = "0" };

            try
            {
                if (String.IsNullOrEmpty(email))
                {
                    resp.rs2 = Resources.Resource.ErrorNotCorrectEmail;
                    return resp;
                }

                if (!email.TestEmailRegex())
                    resp.rs2 = Resources.Resource.ErrorNotCorrectEmail;

                var user = CoreContext.UserManager.GetUserByEmail(email);
                if (!user.ID.Equals(ASC.Core.Users.Constants.LostUser.ID))
                {
                    resp.rs1 = "0";
                    resp.rs2 = CustomNamingPeople.Substitute<Resources.Resource>("ErrorEmailAlreadyExists").HtmlEncode();
                    return resp;
                }

                var tenant = CoreContext.TenantManager.GetCurrentTenant();
                var trustedDomainSettings = SettingsManager.Instance.LoadSettings<StudioTrustedDomainSettings>(TenantProvider.CurrentTenantID);
                var emplType = trustedDomainSettings.InviteUsersAsVisitors ? EmployeeType.Visitor : EmployeeType.User;
                var enableInviteUsers = TenantStatisticsProvider.GetUsersCount() < TenantExtra.GetTenantQuota().ActiveUsers;

                if (!enableInviteUsers)
                    emplType = EmployeeType.Visitor;

                if (tenant.TrustedDomainsType == TenantTrustedDomainsType.Custom)
                {
                    var address = new MailAddress(email);
                    foreach (var d in tenant.TrustedDomains)
                    {
                        if (address.Address.EndsWith("@" + d, StringComparison.InvariantCultureIgnoreCase))
                        {
                            StudioNotifyService.Instance.InviteUsers(email, "", true, emplType);
                            resp.rs1 = "1";
                            resp.rs2 = Resources.Resource.FinishInviteJoinEmailMessage;
                            return resp;
                        }
                    }
                }
                else if (tenant.TrustedDomainsType == TenantTrustedDomainsType.All)
                {
                    StudioNotifyService.Instance.InviteUsers(email, "", true, emplType);
                    resp.rs1 = "1";
                    resp.rs2 = Resources.Resource.FinishInviteJoinEmailMessage;
                    return resp;
                }

                resp.rs2 = Resources.Resource.ErrorNotCorrectEmail;
            }
            catch (FormatException)
            {
                resp.rs2 = Resources.Resource.ErrorNotCorrectEmail;
            }
            catch (Exception e)
            {
                resp.rs2 = HttpUtility.HtmlEncode(e.Message);
            }

            return resp;
        }
        public AjaxResponse SubscribeOnNewTopic(int statusNotify)
        {
            var resp = new AjaxResponse();
            if (statusNotify == 1 && Subscribe != null)
            {
                Subscribe(this, new SubscribeEventArgs(SubscriptionConstants.NewTopicInForum,
                                                       null,
                                                       SecurityContext.CurrentAccount.ID));

                resp.rs1 = "1";
                resp.rs2 = RenderNewTopicSubscription(false);
            }
            else if (UnSubscribe != null)
            {
                UnSubscribe(this, new SubscribeEventArgs(SubscriptionConstants.NewTopicInForum,
                                                         null,
                                                         SecurityContext.CurrentAccount.ID));

                resp.rs1 = "1";
                resp.rs2 = RenderNewTopicSubscription(true);
            }
            else
            {
                resp.rs1 = "0";
                resp.rs2 = Resources.ForumResource.ErrorSubscription;
            }
            return resp;
        }
        public AjaxResponse SaveThreadCategory(int categoryID, string categoryName, string threadName, string threadDescription, bool isRenderCategory)
        {
            AjaxResponse resp = new AjaxResponse();

            if (!ForumManager.Instance.ValidateAccessSecurityAction(ForumAction.GetAccessForumEditor, null))
            {
                resp.rs1 = "0";
                resp.rs2 = "<div>" + Resources.ForumResource.ErrorAccessDenied + "</div>";
                return resp;
            }

            if (String.IsNullOrEmpty(threadName) || String.IsNullOrEmpty(threadName.Trim()))
            {
                resp.rs1 = "0";
                resp.rs2 = "<div>" + Resources.ForumResource.ErrorThreadEmptyName + "</div>";
                return resp;
            }

            try
            {
                var thread = new Thread()
                {
                    Title = threadName.Trim(),
                    Description = threadDescription ?? "",
                    SortOrder = 100,
                    CategoryID = categoryID
                };

                if (thread.CategoryID == -1)
                {
                    if (String.IsNullOrEmpty(categoryName) || String.IsNullOrEmpty(categoryName.Trim()))
                    {
                        resp.rs1 = "0";
                        resp.rs2 = "<div>" + Resources.ForumResource.ErrorCategoryEmptyName + "</div>";
                        return resp;
                    }

                    thread.CategoryID = ForumDataProvider.CreateThreadCategory(TenantProvider.CurrentTenantID, categoryName.Trim(), "", 100);
                }

                thread.ID = ForumDataProvider.CreateThread(TenantProvider.CurrentTenantID, thread.CategoryID,
                                                           thread.Title, thread.Description, thread.SortOrder);

                resp.rs1 = "1";
                resp.rs2 = thread.CategoryID.ToString();

                if (isRenderCategory)
                {
                    var threads = new List<Thread>();
                    var category = ForumDataProvider.GetCategoryByID(TenantProvider.CurrentTenantID, thread.CategoryID, out threads);

                    resp.rs3 = ForumEditor.RenderForumCategory(category, threads);
                }

                resp.rs4 = (categoryID == -1) ? "0" : "1";

                ForumActivityPublisher.NewThread(thread);
            }
            catch (Exception ex)
            {
                resp.rs1 = "0";
                resp.rs2 = "<div>" + ex.Message.HtmlEncode() + "</div>";
            }

            return resp;
        }
		public AjaxResponse InviteUsersFromWeb(List<ContactInfo> users, Guid deptID, bool withFullAccessPrivileges)
		{
            SecurityContext.DemandPermissions(ASC.Core.Users.Constants.Action_AddRemoveUser);


			AjaxResponse resp = new AjaxResponse();
			resp.rs1 = "0";
			try
			{
                SecurityContext.DemandPermissions(ASC.Core.Users.Constants.Action_AddRemoveUser);

				var usersToInvite = new List<UserInfo>();
				foreach (var curUser in users)
				{
					if (curUser.Skip || !(curUser.Invite || curUser.Add))
					{
						continue;
					}

					var email = curUser.Email.Trim();
					if (!email.TestEmailRegex())
					{
						resp.rs1 = "0";
						resp.rs2 = email + " - " + Resources.Resource.ErrorNotCorrectEmail;
						continue;
					}

					var user = CoreContext.UserManager.GetUserByEmail(email);
					if (user.ID.Equals(ASC.Core.Users.Constants.LostUser.ID))
					{
						var curUserInfo = new UserInfo() { FirstName = curUser.FirstName, LastName = curUser.LastName, Email = curUser.Email, ID = Guid.NewGuid() };

						if (curUser.Add && !string.IsNullOrEmpty(curUser.FirstName) && !string.IsNullOrEmpty(curUser.LastName))
						{
							if (!curUserInfo.WorkFromDate.HasValue)
								curUserInfo.WorkFromDate = TenantUtil.DateTimeNow();

							try
							{
								UserManagerWrapper.AddUser(curUserInfo, UserManagerWrapper.GeneratePassword());
								if (withFullAccessPrivileges)
								{
									ASC.Core.CoreContext.UserManager.AddUserIntoGroup(curUserInfo.ID, ASC.Core.Users.Constants.GroupAdmin.ID);
								}
								if (deptID != null && !Guid.Empty.Equals(deptID))
								{
									ASC.Core.CoreContext.UserManager.AddUserIntoGroup(curUserInfo.ID, deptID);
								}
							}
							catch(Exception e) {
								resp.rs2 = HttpUtility.HtmlEncode(e.Message);
							}
							continue;
						}
						
						if (curUser.Invite)
						{
							if (deptID != null && !Guid.Empty.Equals(deptID))
							{
								curUserInfo.Department = deptID.ToString();
							}
							usersToInvite.Add(curUserInfo);
						}
					}
				}

				StudioNotifyService.Instance.InviteOrJoinUsers(usersToInvite, string.Empty, false, withFullAccessPrivileges);
				resp.rs1 = "1";
				if (string.IsNullOrEmpty(resp.rs2))
				{
					resp.rs2 = Resources.Resource.FinishInviteEmailTitle;
				}
			}
			catch(Exception e)
			{
				resp.rs2 = HttpUtility.HtmlEncode(e.Message);
			}

			return resp;
		}
        public AjaxResponse SubscribeOnNewPosts(int statusNotify)
        {
            var resp = new AjaxResponse();
            try
            {
                if (statusNotify == 1)
                {
                    _subscriptionProvider.Subscribe(
                        ASC.Blogs.Core.Constants.NewPost,
                        null,
                        IAmAsRecipient
                        );


                    resp.rs1 = "1";
                    resp.rs2 = RenderNewPostsSubscription(false);
                }
                else
                {
                    _subscriptionProvider.UnSubscribe(
                        ASC.Blogs.Core.Constants.NewPost,
                        null,
                        IAmAsRecipient
                        );

                    resp.rs1 = "1";
                    resp.rs2 = RenderNewPostsSubscription(true);
                }
            }
            catch (Exception e)
            {
                resp.rs1 = "0";
                resp.rs2 = HttpUtility.HtmlEncode(e.Message);
            }

            return resp;
        }
        public AjaxResponse DoEditTagName(int id, string name)
        {
            AjaxResponse resp = new AjaxResponse();
            resp.rs3 = id.ToString();
            resp.rs4 = HttpUtility.HtmlEncode(name);

            var tag = ForumDataProvider.GetTagByID(TenantProvider.CurrentTenantID, id);
            if (tag == null ||
                !ForumManager.Instance.ValidateAccessSecurityAction(ForumAction.GetAccessTagEditor, null))
            {
                resp.rs1 = "0";
                resp.rs2 = Resources.ForumResource.ErrorAccessDenied;
                return resp;
            }

            tag.Name = name;
            
            try
            {
                ForumDataProvider.UpdateTag(TenantProvider.CurrentTenantID, tag.ID, tag.Name, tag.IsApproved);
                resp.rs1 = "1";            
            }
            catch(Exception e)
            {
                resp.rs1 = "0";
                resp.rs2 = e.Message.HtmlEncode();
            }
           
            return resp;
        }
        public AjaxResponse DoApprovedTopic(int idTopic, Guid settingsID)
        {
            _forumManager = ForumManager.GetForumManager(settingsID);
            var resp = new AjaxResponse { rs2 = idTopic.ToString() };

            var topic = ForumDataProvider.GetTopicByID(TenantProvider.CurrentTenantID, idTopic);
            if (topic == null)
            {
                resp.rs1 = "0";
                resp.rs3 = Resources.ForumUCResource.ErrorAccessDenied;
                return resp;
            }

            if (!_forumManager.ValidateAccessSecurityAction(ForumAction.ApprovePost, topic))
            {
                resp.rs1 = "0";
                resp.rs3 = Resources.ForumUCResource.ErrorAccessDenied;
                return resp;
            }

            try
            {
                ForumDataProvider.ApproveTopic(TenantProvider.CurrentTenantID, topic.ID);
                resp.rs1 = "1";
            }
            catch (Exception e)
            {
                resp.rs1 = "0";
                resp.rs3 = HttpUtility.HtmlEncode(e.Message);
            }

            return resp;
        }
        public AjaxResponse DoDeleteTag(int id)
        {
            AjaxResponse resp = new AjaxResponse();            
            resp.rs3 = id.ToString();
            
            if (!ForumManager.Instance.ValidateAccessSecurityAction(ForumAction.GetAccessTagEditor, null))
            {
                resp.rs1 = "0";
                resp.rs2 = Resources.ForumResource.ErrorAccessDenied;
                return resp;
            }

            try
            {
                ForumDataProvider.RemoveTag(TenantProvider.CurrentTenantID, id);
                resp.rs1 = "1";
            }
            catch(Exception e)
            {
                resp.rs1 = "0";
                resp.rs2 = e.Message.HtmlEncode();
            }
            
            return resp;
        }
        public AjaxResponse UploadCertificate(string fileName, string password)
        {
            var response = new AjaxResponse();

            try
            {
                var filePath = Path.Combine(Path.GetTempPath(), fileName);
                var store2 = new X509Store(StoreName.My, StoreLocation.LocalMachine);
                var sp = new StorePermission(PermissionState.Unrestricted) {Flags = StorePermissionFlags.AllFlags};
                sp.Assert();
                store2.Open(OpenFlags.MaxAllowed);

                var cert = fileName.EndsWith(".pfx")
                                            ? new X509Certificate2(filePath, password) {FriendlyName = fileName}
                                            : new X509Certificate2(new X509Certificate(filePath));

                store2.Add(cert);
                store2.Close();

                if (CoreContext.Configuration.Standalone)
                    UploadStandAloneCertificate(store2, cert);
                else
                    UploadSaaSCertificate(store2, cert);

                response.status = "success";
                response.message = Resource.UploadHttpsSettingsSuccess;
            }
            catch (Exception e)
            {
                response.status = "error";
                response.message = e.Message;
            }

            return response;
        }