protected override IEnumerable <KeyValuePair <string, object> > GetClientVariables(HttpContext context)
 {
     return(new List <KeyValuePair <string, object> >(1)
     {
         RegisterObject(new
         {
             file_21 = CommonLinkUtility.GetFullAbsolutePath("~/UserControls/Common/ckeditor/plugins/filetype/images/file_21.png"),
             file_archive_21 = CommonLinkUtility.GetFullAbsolutePath("~/UserControls/Common/ckeditor/plugins/filetype/images/file_archive_21.png"),
             file_avi_21 = CommonLinkUtility.GetFullAbsolutePath("~/UserControls/Common/ckeditor/plugins/filetype/images/file_avi_21.png"),
             file_cal_21 = CommonLinkUtility.GetFullAbsolutePath("~/UserControls/Common/ckeditor/plugins/filetype/images/file_cal_21.png"),
             file_csv_21 = CommonLinkUtility.GetFullAbsolutePath("~/UserControls/Common/ckeditor/plugins/filetype/images/file_csv_21.png"),
             file_djvu_21 = CommonLinkUtility.GetFullAbsolutePath("~/UserControls/Common/ckeditor/plugins/filetype/images/file_djvu_21.png"),
             file_doc_21 = CommonLinkUtility.GetFullAbsolutePath("~/UserControls/Common/ckeditor/plugins/filetype/images/file_doc_21.png"),
             file_doct_21 = CommonLinkUtility.GetFullAbsolutePath("~/UserControls/Common/ckeditor/plugins/filetype/images/file_doct_21.png"),
             file_docx_21 = CommonLinkUtility.GetFullAbsolutePath("~/UserControls/Common/ckeditor/plugins/filetype/images/file_docx_21.png"),
             file_dvd_21 = CommonLinkUtility.GetFullAbsolutePath("~/UserControls/Common/ckeditor/plugins/filetype/images/file_dvd_21.png"),
             file_ebook_21 = CommonLinkUtility.GetFullAbsolutePath("~/UserControls/Common/ckeditor/plugins/filetype/images/file_ebook_21.png"),
             file_flv_21 = CommonLinkUtility.GetFullAbsolutePath("~/UserControls/Common/ckeditor/plugins/filetype/images/file_flv_21.png"),
             file_gdoc_21 = CommonLinkUtility.GetFullAbsolutePath("~/UserControls/Common/ckeditor/plugins/filetype/images/file_gdoc_21.png"),
             file_gsheet_21 = CommonLinkUtility.GetFullAbsolutePath("~/UserControls/Common/ckeditor/plugins/filetype/images/file_gsheet_21.png"),
             file_gslides_21 = CommonLinkUtility.GetFullAbsolutePath("~/UserControls/Common/ckeditor/plugins/filetype/images/file_gslides_21.png"),
             file_html_21 = CommonLinkUtility.GetFullAbsolutePath("~/UserControls/Common/ckeditor/plugins/filetype/images/file_html_21.png"),
             file_iaf_21 = CommonLinkUtility.GetFullAbsolutePath("~/UserControls/Common/ckeditor/plugins/filetype/images/file_iaf_21.png"),
             file_image_21 = CommonLinkUtility.GetFullAbsolutePath("~/UserControls/Common/ckeditor/plugins/filetype/images/file_image_21.png"),
             file_m2ts_21 = CommonLinkUtility.GetFullAbsolutePath("~/UserControls/Common/ckeditor/plugins/filetype/images/file_m2ts_21.png"),
             file_mkv_21 = CommonLinkUtility.GetFullAbsolutePath("~/UserControls/Common/ckeditor/plugins/filetype/images/file_mkv_21.png"),
             file_mov_21 = CommonLinkUtility.GetFullAbsolutePath("~/UserControls/Common/ckeditor/plugins/filetype/images/file_mov_21.png"),
             file_mp4_21 = CommonLinkUtility.GetFullAbsolutePath("~/UserControls/Common/ckeditor/plugins/filetype/images/file_mp4_21.png"),
             file_mpg_21 = CommonLinkUtility.GetFullAbsolutePath("~/UserControls/Common/ckeditor/plugins/filetype/images/file_mpg_21.png"),
             file_odp_21 = CommonLinkUtility.GetFullAbsolutePath("~/UserControls/Common/ckeditor/plugins/filetype/images/file_odp_21.png"),
             file_ods_21 = CommonLinkUtility.GetFullAbsolutePath("~/UserControls/Common/ckeditor/plugins/filetype/images/file_ods_21.png"),
             file_odt_21 = CommonLinkUtility.GetFullAbsolutePath("~/UserControls/Common/ckeditor/plugins/filetype/images/file_odt_21.png"),
             file_pdf_21 = CommonLinkUtility.GetFullAbsolutePath("~/UserControls/Common/ckeditor/plugins/filetype/images/file_pdf_21.png"),
             file_pps_21 = CommonLinkUtility.GetFullAbsolutePath("~/UserControls/Common/ckeditor/plugins/filetype/images/file_pps_21.png"),
             file_ppsx_21 = CommonLinkUtility.GetFullAbsolutePath("~/UserControls/Common/ckeditor/plugins/filetype/images/file_ppsx_21.png"),
             file_ppt_21 = CommonLinkUtility.GetFullAbsolutePath("~/UserControls/Common/ckeditor/plugins/filetype/images/file_ppt_21.png"),
             file_pptt_21 = CommonLinkUtility.GetFullAbsolutePath("~/UserControls/Common/ckeditor/plugins/filetype/images/file_pptt_21.png"),
             file_pptx_21 = CommonLinkUtility.GetFullAbsolutePath("~/UserControls/Common/ckeditor/plugins/filetype/images/file_pptx_21.png"),
             file_rtf_21 = CommonLinkUtility.GetFullAbsolutePath("~/UserControls/Common/ckeditor/plugins/filetype/images/file_rtf_21.png"),
             file_sound_21 = CommonLinkUtility.GetFullAbsolutePath("~/UserControls/Common/ckeditor/plugins/filetype/images/file_sound_21.png"),
             file_svg_21 = CommonLinkUtility.GetFullAbsolutePath("~/UserControls/Common/ckeditor/plugins/filetype/images/file_svg_21.png"),
             file_txt_21 = CommonLinkUtility.GetFullAbsolutePath("~/UserControls/Common/ckeditor/plugins/filetype/images/file_txt_21.png"),
             file_xls_21 = CommonLinkUtility.GetFullAbsolutePath("~/UserControls/Common/ckeditor/plugins/filetype/images/file_xls_21.png"),
             file_xlst_21 = CommonLinkUtility.GetFullAbsolutePath("~/UserControls/Common/ckeditor/plugins/filetype/images/file_xlst_21.png"),
             file_xlsx_21 = CommonLinkUtility.GetFullAbsolutePath("~/UserControls/Common/ckeditor/plugins/filetype/images/file_xlsx_21.png"),
             file_xml_21 = CommonLinkUtility.GetFullAbsolutePath("~/UserControls/Common/ckeditor/plugins/filetype/images/file_xml_21.png"),
             file_xps_21 = CommonLinkUtility.GetFullAbsolutePath("~/UserControls/Common/ckeditor/plugins/filetype/images/file_xps_21.png"),
             file_docm_21 = CommonLinkUtility.GetFullAbsolutePath("~/UserControls/Common/ckeditor/plugins/filetype/images/file_docm_21.png"),
             file_dot_21 = CommonLinkUtility.GetFullAbsolutePath("~/UserControls/Common/ckeditor/plugins/filetype/images/file_dot_21.png"),
             file_dotm_21 = CommonLinkUtility.GetFullAbsolutePath("~/UserControls/Common/ckeditor/plugins/filetype/images/file_dotm_21.png"),
             file_dotx_21 = CommonLinkUtility.GetFullAbsolutePath("~/UserControls/Common/ckeditor/plugins/filetype/images/file_dotx_21.png"),
             file_pot_21 = CommonLinkUtility.GetFullAbsolutePath("~/UserControls/Common/ckeditor/plugins/filetype/images/file_pot_21.png"),
             file_potm_21 = CommonLinkUtility.GetFullAbsolutePath("~/UserControls/Common/ckeditor/plugins/filetype/images/file_potm_21.png"),
             file_potx_21 = CommonLinkUtility.GetFullAbsolutePath("~/UserControls/Common/ckeditor/plugins/filetype/images/file_potx_21.png"),
             file_ppsm_21 = CommonLinkUtility.GetFullAbsolutePath("~/UserControls/Common/ckeditor/plugins/filetype/images/file_ppsm_21.png"),
             file_pptm_21 = CommonLinkUtility.GetFullAbsolutePath("~/UserControls/Common/ckeditor/plugins/filetype/images/file_pptm_21.png"),
             file_soundunk_21 = CommonLinkUtility.GetFullAbsolutePath("~/UserControls/Common/ckeditor/plugins/filetype/images/file_soundunk_21.png"),
             file_video_21 = CommonLinkUtility.GetFullAbsolutePath("~/UserControls/Common/ckeditor/plugins/filetype/images/file_video_21.png"),
             file_videounk_21 = CommonLinkUtility.GetFullAbsolutePath("~/UserControls/Common/ckeditor/plugins/filetype/images/file_videounk_21.png"),
             file_xlsm_21 = CommonLinkUtility.GetFullAbsolutePath("~/UserControls/Common/ckeditor/plugins/filetype/images/file_xlsm_21.png"),
             file_xlt_21 = CommonLinkUtility.GetFullAbsolutePath("~/UserControls/Common/ckeditor/plugins/filetype/images/file_xlt_21.png"),
             file_xltm_21 = CommonLinkUtility.GetFullAbsolutePath("~/UserControls/Common/ckeditor/plugins/filetype/images/file_xltm_21.png"),
             file_xltx_21 = CommonLinkUtility.GetFullAbsolutePath("~/UserControls/Common/ckeditor/plugins/filetype/images/file_xltx_21.png"),
             IsTurnOnAttachmentsGroupOperations = Defines.IsAttachmentsGroupOperationsAvailable,
             IsTurnOnOAuth = GoogleLoginProvider.Instance.IsEnabled && Convert.ToBoolean(ConfigurationManagerExtension.AppSettings["mail.google-oauth"] ?? "true"),
             OAuthLocation = VirtualPathUtility.ToAbsolute(OAuth.Location),
             userDisplayFormat = (int)UserFormatter.GetUserDisplayDefaultOrder()
         })
     });
 }
        private static void NotifyClientRegisterCallback(Context context, INotifyClient client)
        {
            #region url correction

            var absoluteUrl = new SendInterceptorSkeleton(
                "Web.UrlAbsoluter",
                InterceptorPlace.MessageSend,
                InterceptorLifetime.Global,
                (r, p) =>
            {
                if (r != null && r.CurrentMessage != null && r.CurrentMessage.ContentType == Pattern.HTMLContentType)
                {
                    var body = r.CurrentMessage.Body;

                    body = urlReplacer.Replace(body, m =>
                    {
                        var url = m.Groups["url"].Value;
                        var ind = m.Groups["url"].Index - m.Index;
                        return(string.IsNullOrEmpty(url) && ind > 0 ?
                               m.Value.Insert(ind, CommonLinkUtility.GetFullAbsolutePath(string.Empty)) :
                               m.Value.Replace(url, CommonLinkUtility.GetFullAbsolutePath(url)));
                    });

                    body = textileLinkReplacer.Replace(body, m =>
                    {
                        var url = m.Groups["link"].Value;
                        var ind = m.Groups["link"].Index - m.Index;
                        return(string.IsNullOrEmpty(url) && ind > 0 ?
                               m.Value.Insert(ind, CommonLinkUtility.GetFullAbsolutePath(string.Empty)) :
                               m.Value.Replace(url, CommonLinkUtility.GetFullAbsolutePath(url)));
                    });

                    r.CurrentMessage.Body = body;
                }
                return(false);
            });
            client.AddInterceptor(absoluteUrl);

            #endregion

            #region security and culture

            var securityAndCulture = new SendInterceptorSkeleton(
                "ProductSecurityInterceptor",
                InterceptorPlace.DirectSend,
                InterceptorLifetime.Global,
                (r, p) =>
            {
                try
                {
                    // culture
                    var u = ASC.Core.Users.Constants.LostUser;

                    if (32 <= r.Recipient.ID.Length)
                    {
                        var guid = default(Guid);
                        try
                        {
                            guid = new Guid(r.Recipient.ID);
                        }
                        catch (FormatException) { }
                        catch (OverflowException) { }

                        if (guid != default(Guid))
                        {
                            u = CoreContext.UserManager.GetUsers(guid);
                        }
                    }

                    if (ASC.Core.Users.Constants.LostUser.Equals(u))
                    {
                        u = CoreContext.UserManager.GetUserByEmail(r.Recipient.ID);
                    }

                    if (ASC.Core.Users.Constants.LostUser.Equals(u))
                    {
                        u = CoreContext.UserManager.GetUserByUserName(r.Recipient.ID);
                    }

                    if (!ASC.Core.Users.Constants.LostUser.Equals(u))
                    {
                        var culture = !string.IsNullOrEmpty(u.CultureName) ? u.GetCulture() : CoreContext.TenantManager.GetCurrentTenant().GetCulture();
                        Thread.CurrentThread.CurrentCulture   = culture;
                        Thread.CurrentThread.CurrentUICulture = culture;

                        // security
                        var tag       = r.Arguments.Find(a => a.Tag == CommonTags.ModuleID);
                        var productId = tag != null ? (Guid)tag.Value : Guid.Empty;
                        if (productId == Guid.Empty)
                        {
                            tag       = r.Arguments.Find(a => a.Tag == CommonTags.ProductID);
                            productId = tag != null ? (Guid)tag.Value : Guid.Empty;
                        }
                        if (productId == Guid.Empty)
                        {
                            productId = (Guid)(CallContext.GetData("asc.web.product_id") ?? Guid.Empty);
                        }
                        if (productId != Guid.Empty && productId != new Guid("f4d98afdd336433287783c6945c81ea0") /* ignore people product */)
                        {
                            return(!WebItemSecurity.IsAvailableForUser(productId, u.ID));
                        }
                    }

                    var tagCulture = r.Arguments.FirstOrDefault(a => a.Tag == CommonTags.Culture);
                    if (tagCulture != null)
                    {
                        var culture = CultureInfo.GetCultureInfo((string)tagCulture.Value);
                        Thread.CurrentThread.CurrentCulture   = culture;
                        Thread.CurrentThread.CurrentUICulture = culture;
                    }
                }
                catch (Exception error)
                {
                    LogManager.GetLogger("ASC").Error(error);
                }
                return(false);
            });
            client.AddInterceptor(securityAndCulture);

            #endregion

            #region white label correction

            var whiteLabel = new SendInterceptorSkeleton(
                "WhiteLabelInterceptor",
                InterceptorPlace.MessageSend,
                InterceptorLifetime.Global,
                (r, p) =>
            {
                try
                {
                    var tags = r.Arguments;

                    var logoTextTag = tags.FirstOrDefault(a => a.Tag == Constants.LetterLogoText);
                    var logoText    = logoTextTag != null ? (String)logoTextTag.Value : string.Empty;

                    if (!string.IsNullOrEmpty(logoText))
                    {
                        var body = r.CurrentMessage.Body
                                   .Replace(string.Format("${{{0}}}", Constants.LetterLogoTextTM), logoText)
                                   .Replace(string.Format("${{{0}}}", Constants.LetterLogoText), logoText);
                        r.CurrentMessage.Body = body;
                    }
                }
                catch (Exception error)
                {
                    LogManager.GetLogger("ASC").Error(error);
                }
                return(false);
            });
            client.AddInterceptor(whiteLabel);

            #endregion
        }
Esempio n. 3
0
        protected void Page_Load(object sender, EventArgs e)
        {
            var currUser   = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID);
            var isVisitor  = currUser.IsVisitor();
            var isOutsider = currUser.IsOutsider();
            var isAdmin    = currUser.IsAdmin();

            var strCreateFile =
                !HideAddActions && !isVisitor
                    ? string.Format(@"<div class=""empty-folder-create empty-folder-create-editor"">
<a class=""link dotline plus empty-folder-create-document"">{0}</a>,
<a class=""link dotline empty-folder-create-spreadsheet"">{1}</a>,
<a class=""link dotline empty-folder-create-presentation"">{2}</a>,
<a class=""link dotline empty-folder-create-masterform"">{3}</a>
</div>",
                                    FilesUCResource.ButtonCreateText,
                                    FilesUCResource.ButtonCreateSpreadsheet,
                                    FilesUCResource.ButtonCreatePresentation,
                                    FilesUCResource.ButtonCreateFormTemplate)
                    : string.Empty;

            var strCreateFolder =
                !HideAddActions && !isOutsider
                    ? string.Format(@"<div class=""empty-folder-create""><a class=""empty-folder-create-folder link dotline plus"">{0}</a></div>", FilesUCResource.ButtonCreateFolder)
                    : string.Empty;

            var strDragDrop =
                !HideAddActions
                    ? string.Format("<div class=\"emptyContainer_dragDrop\" > {0}</div>", FilesUCResource.EmptyScreenDescrDragDrop.HtmlEncode())
                    : string.Empty;

            var strToParent = string.Format("<div><a class=\"empty-folder-toparent link dotline up\" >{0}</a></div>", FilesUCResource.ButtonToParentFolder);

            var strButtons = new StringBuilder();

            strButtons.Append(strCreateFile);
            strButtons.Append(strCreateFolder);

            if (AllContainers)
            {
                //my
                if (!isVisitor)
                {
                    var descrMy = string.Format(FileUtility.ExtsWebEdited.Any() ? FilesUCResource.EmptyScreenDescrMy.HtmlEncode() : FilesUCResource.EmptyScreenDescrMyPoor.HtmlEncode(),
                                                //create
                                                "<span class=\"hintCreate baseLinkAction\" >", "</span>",
                                                //upload
                                                "<span class=\"hintUpload baseLinkAction\" >", "</span>",
                                                //open
                                                "<span class=\"hintOpen baseLinkAction\" >", "</span>",
                                                //edit
                                                "<span class=\"hintEdit baseLinkAction\" >", "</span>"
                                                );
                    descrMy += strDragDrop;

                    EmptyScreenFolder.Controls.Add(new EmptyScreenControl
                    {
                        ID             = "emptyContainer_my",
                        ImgSrc         = PathProvider.GetImagePath("empty_screen_my.png"),
                        Header         = FilesUCResource.MyFiles,
                        HeaderDescribe = FilesUCResource.EmptyScreenHeader,
                        Describe       = descrMy,
                        ButtonHTML     = strButtons.ToString()
                    });

                    EmptyScreenFolder.Controls.Add(new EmptyScreenControl
                    {
                        ID             = "emptyContainer_recent",
                        ImgSrc         = PathProvider.GetImagePath("empty_screen_recent.png"),
                        Header         = FilesUCResource.Recent,
                        HeaderDescribe = FilesUCResource.EmptyScreenHeader,
                        Describe       = FilesUCResource.EmptyScreenDescrRecent.HtmlEncode()
                    });

                    EmptyScreenFolder.Controls.Add(new EmptyScreenControl
                    {
                        ID             = "emptyContainer_favorites",
                        ImgSrc         = PathProvider.GetImagePath("empty_screen_favorites.png"),
                        Header         = FilesUCResource.Favorites,
                        HeaderDescribe = FilesUCResource.EmptyScreenHeader,
                        Describe       = FilesUCResource.EmptyScreenDescrFavorites.HtmlEncode()
                    });

                    EmptyScreenFolder.Controls.Add(new EmptyScreenControl
                    {
                        ID             = "emptyContainer_templates",
                        ImgSrc         = PathProvider.GetImagePath("empty_screen_templates.png"),
                        Header         = FilesUCResource.Templates,
                        HeaderDescribe = FilesUCResource.EmptyScreenHeader,
                        Describe       = FilesUCResource.EmptyScreenDescrTemplates.HtmlEncode()
                    });

                    if (PrivacyRoomSettings.Available)
                    {
                        var privacyWithButton = false;
                        var privacyDescr      = string.Format(FilesUCResource.EmptyScreenDescrPrivacyList,
                                                              "<div class=\"empty-folder-privacy-li\">",
                                                              "</div>"
                                                              );
                        if (!PrivacyRoomSettings.Enabled)
                        {
                            if (isAdmin)
                            {
                                var link =
                                    TenantExtra.EnableControlPanel
                                    ? SetupInfo.ControlPanelUrl.TrimEnd('/') + "/privacyRoom"
                                    : CommonLinkUtility.GetAdministration(ManagementType.PrivacyRoom);

                                privacyDescr += string.Format("<p>" + FilesUCResource.EmptyScreenDescrPrivacyEnable + "</p>",
                                                              "<a href=\"" + CommonLinkUtility.GetFullAbsolutePath(link) + "\" "
                                                              + (Request.DesktopApp() ? "target=\"_blank\"" : "")
                                                              + ">",
                                                              "</a>"
                                                              );
                            }
                            else
                            {
                                privacyDescr += "<p>" + FilesUCResource.EmptyScreenDescrPrivacyAsk + "</p>";
                            }
                        }
                        else if (Request.DesktopApp())
                        {
                            privacyWithButton = true;
                        }

                        privacyDescr += string.Format("<p>" + FilesUCResource.EmptyScreenDescrPrivacyBrowser.HtmlEncode() + "</p>",
                                                      "<a href=\"https://www.onlyoffice.com/private-rooms.aspx\" target=\"_blank\">",
                                                      "</a>"
                                                      );

                        EmptyScreenFolder.Controls.Add(new EmptyScreenControl
                        {
                            ID         = "emptyContainer_privacy",
                            ImgSrc     = PathProvider.GetImagePath("empty_screen_privacy.png"),
                            Header     = FilesUCResource.PrivacyRoomEmptyFolder.HtmlEncode(),
                            Describe   = privacyDescr,
                            ButtonHTML = privacyWithButton ? strButtons.ToString() : ""
                        });
                    }
                }

                if (!CoreContext.Configuration.Personal)
                {
                    EmptyScreenFolder.Controls.Add(new EmptyScreenControl
                    {
                        ID             = "emptyContainer_forme",
                        ImgSrc         = PathProvider.GetImagePath("empty_screen_forme.png"),
                        Header         = FilesUCResource.SharedForMe,
                        HeaderDescribe = FilesUCResource.EmptyScreenHeader,
                        Describe       = FilesUCResource.EmptyScreenDescrForme.HtmlEncode()
                    });

                    EmptyScreenFolder.Controls.Add(new EmptyScreenControl
                    {
                        ID             = "emptyContainer_corporate",
                        ImgSrc         = PathProvider.GetImagePath("empty_screen_corporate.png"),
                        Header         = FilesUCResource.CorporateFiles,
                        HeaderDescribe = FilesUCResource.EmptyScreenHeader,
                        Describe       = FilesUCResource.EmptyScreenDescrCorporate.HtmlEncode() + strDragDrop,
                        ButtonHTML     = isAdmin ? strButtons.ToString() : string.Empty
                    });
                }

                //trash
                EmptyScreenFolder.Controls.Add(new EmptyScreenControl
                {
                    ID             = "emptyContainer_trash",
                    ImgSrc         = PathProvider.GetImagePath("empty_screen_trash.png"),
                    Header         = FilesUCResource.Trash,
                    HeaderDescribe = FilesUCResource.EmptyScreenHeader,
                    Describe       = FilesUCResource.EmptyScreenDescrTrash.HtmlEncode(),
                    ButtonHTML     = !isVisitor ? string.Format("<div><a href=\"#{1}\" class=\"empty-folder-goto link dotline up\">{0}</a></div>", FilesUCResource.ButtonGotoMy, Global.FolderMy) : string.Empty
                });
            }

            if (!CoreContext.Configuration.Personal)
            {
                EmptyScreenFolder.Controls.Add(new EmptyScreenControl
                {
                    ID             = "emptyContainer_project",
                    ImgSrc         = PathProvider.GetImagePath("empty_screen_project.png"),
                    Header         = FilesUCResource.ProjectFiles,
                    HeaderDescribe = FilesUCResource.EmptyScreenHeader,
                    Describe       = (!isVisitor
                                        ? FilesUCResource.EmptyScreenDescrProject.HtmlEncode()
                                        : FilesUCResource.EmptyScreenDescrProjectVisitor.HtmlEncode())
                                     + strDragDrop
                });
            }

            //Filter
            EmptyScreenFolder.Controls.Add(new EmptyScreenControl
            {
                ID             = "emptyContainer_filter",
                ImgSrc         = PathProvider.GetImagePath("empty_screen_filter.png"),
                Header         = FilesUCResource.Filter,
                HeaderDescribe = FilesUCResource.EmptyScreenFilter,
                Describe       = FilesUCResource.EmptyScreenFilterDescr.HtmlEncode(),
                ButtonHTML     = string.Format("<a class=\"clearFilterButton link dotline files-clear-filter\" >{0}</a>", FilesUCResource.ButtonClearFilter)
            });

            strButtons.Append(strToParent);

            //Subfolder
            EmptyScreenFolder.Controls.Add(new EmptyScreenControl
            {
                ID             = "emptyContainer_subfolder",
                ImgSrc         = PathProvider.GetImagePath("empty_screen.png"),
                HeaderDescribe = FilesUCResource.EmptyScreenFolderHeader,
                ButtonHTML     = strButtons.ToString()
            });
        }
Esempio n. 4
0
        public void ProcessRequest(HttpContext context)
        {
            if (!ProcessAuthorization(context))
            {
                AccessDenied(context);
                return;
            }

            var productId    = ParseGuid(context.Request[ProductParam]);
            var product      = WebItemManager.Instance[productId.GetValueOrDefault()];
            var products     = WebItemManager.Instance.GetItemsAll <IProduct>().ToDictionary(p => p.GetSysName());
            var title        = context.Request[TitleParam] ?? Resources.Resource.RecentActivity;
            var lastModified = GetLastModified(context);

            var feeds = FeedAggregateDataProvider.GetFeeds(new FeedApiFilter
            {
                Product = product != null ? product.GetSysName() : null,
                From    = lastModified ?? DateTime.UtcNow.AddDays(-14),
                To      = DateTime.UtcNow,
                OnlyNew = true
            })
                        .OrderByDescending(f => f.CreateOn)
                        .Take(100)
                        .Select(f => f.ToFeedMin())
                        .ToList();

            if (lastModified != null && feeds.Count == 0)
            {
                context.Response.StatusCode        = (int)HttpStatusCode.NotModified;
                context.Response.StatusDescription = "Not Modified";
            }

            var feedItems = feeds.Select(f =>
            {
                var item = new SyndicationItem(
                    HttpUtility.HtmlDecode((products.ContainsKey(f.Product) ? products[f.Product].Name + ": " : string.Empty) + f.Title),
                    string.Empty,
                    new Uri(CommonLinkUtility.GetFullAbsolutePath(f.ItemUrl)),
                    f.Id,
                    new DateTimeOffset(TenantUtil.DateTimeToUtc(f.Date)))
                {
                    PublishDate = f.Date,
                };
                if (f.Author != null && f.Author.UserInfo != null)
                {
                    var u = f.Author.UserInfo;
                    item.Authors.Add(new SyndicationPerson(u.Email, u.DisplayUserName(false), CommonLinkUtility.GetUserProfile(u.ID)));
                }
                return(item);
            });

            var lastUpdate = DateTime.UtcNow;

            if (feeds.Count > 0)
            {
                lastUpdate = feeds.Max(x => x.Date);
            }

            var feed = new SyndicationFeed(
                CoreContext.TenantManager.GetCurrentTenant().Name,
                string.Empty,
                new Uri(context.Request.GetUrlRewriter(), VirtualPathUtility.ToAbsolute("~/feed.aspx")),
                TenantProvider.CurrentTenantID.ToString(),
                new DateTimeOffset(lastUpdate),
                feedItems);

            var tenantSettings = SettingsManager.Instance.LoadSettings <TenantInfoSettings>(TenantProvider.CurrentTenantID);
            var url            = tenantSettings.GetAbsoluteCompanyLogoPath();

            if (!string.IsNullOrEmpty(url))
            {
                feed.ImageUrl = new Uri(CommonLinkUtility.GetFullAbsolutePath(url));
            }


            var rssFormatter = new Atom10FeedFormatter(feed);
            var settings     = new XmlWriterSettings
            {
                CheckCharacters  = false,
                ConformanceLevel = ConformanceLevel.Document,
                Encoding         = Encoding.UTF8,
                Indent           = true,
            };

            using (var writer = XmlWriter.Create(context.Response.Output, settings))
            {
                rssFormatter.WriteTo(writer);
            }
            context.Response.Charset     = Encoding.UTF8.WebName;
            context.Response.ContentType = "application/atom+xml";
            context.Response.AddHeader("ETag", DateTime.UtcNow.ToString("yyyyMMddHHmmss"));
            context.Response.AddHeader("Last-Modified", DateTime.UtcNow.ToString("R"));
        }
Esempio n. 5
0
        private void PageLoad()
        {
            var editPossible = !RequestEmbedded;
            var isExtenral   = false;

            File file;
            var  fileUri = string.Empty;

            try
            {
                if (string.IsNullOrEmpty(RequestFileUrl))
                {
                    var app = ThirdPartySelector.GetAppByFileId(RequestFileId);
                    if (app == null)
                    {
                        var ver = string.IsNullOrEmpty(Request[FilesLinkUtility.Version]) ? -1 : Convert.ToInt32(Request[FilesLinkUtility.Version]);
                        file = DocumentServiceHelper.GetParams(RequestFileId, ver, RequestShareLinkKey, editPossible, !RequestView, true, out _configuration);
                        if (_valideShareLink)
                        {
                            _configuration.Document.SharedLinkKey += RequestShareLinkKey;
                        }
                    }
                    else
                    {
                        isExtenral = true;

                        bool editable;
                        _thirdPartyApp = true;
                        file           = app.GetFile(RequestFileId, out editable);
                        file           = DocumentServiceHelper.GetParams(file, true, editPossible ? FileShare.ReadWrite : FileShare.Read, false, editable, editable, editable, true, out _configuration);

                        _configuration.Document.Url = app.GetFileStreamUrl(file);
                        _configuration.EditorConfig.Customization.GobackUrl = string.Empty;
                    }
                }
                else
                {
                    isExtenral = true;

                    fileUri = RequestFileUrl;
                    var fileTitle = Request[FilesLinkUtility.FileTitle];
                    if (string.IsNullOrEmpty(fileTitle))
                    {
                        fileTitle = Path.GetFileName(HttpUtility.UrlDecode(fileUri)) ?? "";
                    }

                    file = new File
                    {
                        ID    = RequestFileUrl,
                        Title = Global.ReplaceInvalidCharsAndTruncate(fileTitle)
                    };

                    file = DocumentServiceHelper.GetParams(file, true, FileShare.Read, false, false, false, false, false, out _configuration);
                    _configuration.Document.Permissions.Edit          = editPossible && !CoreContext.Configuration.Standalone;
                    _configuration.Document.Permissions.Rename        = false;
                    _configuration.Document.Permissions.Review        = false;
                    _configuration.Document.Permissions.FillForms     = false;
                    _configuration.Document.Permissions.ChangeHistory = false;
                    _editByUrl = true;

                    _configuration.Document.Url = fileUri;
                }
                ErrorMessage = _configuration.ErrorMessage;
            }
            catch (Exception ex)
            {
                Global.Logger.Warn("DocEditor", ex);
                ErrorMessage = ex.Message;
                return;
            }

            if (_configuration.EditorConfig.ModeWrite && FileConverter.MustConvert(file))
            {
                Folder folder;
                try
                {
                    file = FileConverter.ExecDuplicate(file, RequestShareLinkKey, out folder);
                }
                catch (Exception ex)
                {
                    _configuration = null;
                    Global.Logger.Error("DocEditor", ex);
                    ErrorMessage = ex.Message;
                    return;
                }

                var comment = "#message/" + HttpUtility.UrlEncode(string.Format(FilesCommonResource.CopyToForEdit, folder.Title));

                Response.Redirect(FilesLinkUtility.GetFileWebEditorUrl(file.ID) + comment);
                return;
            }

            Title = file.Title;

            if (_configuration.EditorConfig.Customization.Goback == null || string.IsNullOrEmpty(_configuration.EditorConfig.Customization.Goback.Url))
            {
                _configuration.EditorConfig.Customization.GobackUrl = Request[FilesLinkUtility.FolderUrl] ?? "";
            }

            _configuration.EditorConfig.Customization.IsRetina = TenantLogoManager.IsRetina(Request);

            if (RequestEmbedded)
            {
                _configuration.Type = Services.DocumentService.Configuration.EditorType.Embedded;

                _configuration.EditorConfig.Embedded.ShareLinkParam = string.IsNullOrEmpty(RequestShareLinkKey) ? string.Empty : "&" + FilesLinkUtility.DocShareKey + "=" + RequestShareLinkKey;
            }
            else
            {
                _configuration.Type = IsMobile ? Services.DocumentService.Configuration.EditorType.Mobile : Services.DocumentService.Configuration.EditorType.Desktop;

                if (FileSharing.CanSetAccess(file) &&
                    !(file.Encrypted &&
                      (!Request.DesktopApp() ||
                       CoreContext.Configuration.Personal)))
                {
                    _configuration.EditorConfig.SharingSettingsUrl = CommonLinkUtility.GetFullAbsolutePath(
                        Share.Location
                        + "?" + FilesLinkUtility.FileId + "=" + HttpUtility.UrlEncode(file.ID.ToString())
                        + (Request.DesktopApp() ? "&desktop=true" : string.Empty));
                }
            }

            if (!isExtenral)
            {
                _docKeyForTrack = DocumentServiceHelper.GetDocKey(file.ID, -1, DateTime.MinValue);

                FileMarker.RemoveMarkAsNew(file);
            }

            if (SecurityContext.IsAuthenticated)
            {
                _configuration.EditorConfig.SaveAsUrl = _configuration.EditorConfig.MergeFolderUrl = CommonLinkUtility.GetFullAbsolutePath(SaveAs.GetUrl);
            }

            if (_configuration.EditorConfig.ModeWrite)
            {
                _tabId = FileTracker.Add(file.ID);

                Global.SocketManager.FilesChangeEditors(file.ID);

                if (SecurityContext.IsAuthenticated)
                {
                    _configuration.EditorConfig.FileChoiceUrl = CommonLinkUtility.GetFullAbsolutePath(FileChoice.GetUrlForEditor);
                }
            }
            else
            {
                _linkToEdit = _editByUrl
                                  ? CommonLinkUtility.GetFullAbsolutePath(FilesLinkUtility.GetFileWebEditorExternalUrl(fileUri, file.Title))
                                  : CommonLinkUtility.GetFullAbsolutePath(FilesLinkUtility.GetFileWebEditorUrl(file.ID));

                if (FileConverter.MustConvert(_configuration.Document.Info.File))
                {
                    _editByUrl = true;
                }
            }
        }
 private string PerformUrl(string url)
 {
     return(CommonLinkUtility.GetFullAbsolutePath(url));
 }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (UserProfileHelper == null)
            {
                UserProfileHelper = new ProfileHelper(SecurityContext.CurrentAccount.ID.ToString());
            }
            UserInfo         = UserProfileHelper.UserInfo;
            ShowSocialLogins = UserInfo.IsMe();

            IsAdmin = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID).IsAdmin() ||
                      WebItemSecurity.IsProductAdministrator(WebItemManager.PeopleProductID, SecurityContext.CurrentAccount.ID);

            IsVisitor = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID).IsVisitor();

            if (!IsAdmin && (UserInfo.Status != EmployeeStatus.Active))
            {
                Response.Redirect(CommonLinkUtility.GetFullAbsolutePath("~/products/people/"), true);
            }

            Role = GetRole();

            Actions = new AllowedActions(UserInfo);

            LdapFields = ASC.ActiveDirectory.Base.Settings.LdapSettings.GetImportedFields;

            HappyBirthday = CheckHappyBirthday();

            ContactPhones.DataSource = UserProfileHelper.Phones;
            ContactPhones.DataBind();

            ContactEmails.DataSource = UserProfileHelper.Emails;
            ContactEmails.DataBind();

            ContactMessengers.DataSource = UserProfileHelper.Messengers;
            ContactMessengers.DataBind();

            ContactSoccontacts.DataSource = UserProfileHelper.Contacts;
            ContactSoccontacts.DataBind();

            _deleteProfileContainer.Options.IsPopup = true;

            Page.RegisterStyle("~/usercontrols/users/userprofile/css/userprofilecontrol_style.less")
            .RegisterBodyScripts(VirtualPathUtility.ToAbsolute("~/usercontrols/users/userprofile/js/userprofilecontrol.js"));

            if (Actions.AllowEdit)
            {
                _editControlsHolder.Controls.Add(LoadControl(PwdTool.Location));
            }
            if (Actions.AllowEdit || (UserInfo.IsOwner() && IsAdmin))
            {
                var control = (UserEmailChange)LoadControl(UserEmailChange.Location);
                control.UserInfo = UserInfo;
                control.RegisterStylesAndScripts = false;
                userEmailChange.Controls.Add(control);
            }

            if (ShowSocialLogins && AccountLinkControl.IsNotEmpty)
            {
                var accountLink = (AccountLinkControl)LoadControl(AccountLinkControl.Location);
                accountLink.ClientCallback = "loginCallback";
                accountLink.SettingsView   = true;
                _accountPlaceholder.Controls.Add(accountLink);
            }

            var emailControl = (UserEmailControl)LoadControl(UserEmailControl.Location);

            emailControl.User   = UserInfo;
            emailControl.Viewer = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID);
            _phEmailControlsHolder.Controls.Add(emailControl);

            var photoControl = (LoadPhotoControl)LoadControl(LoadPhotoControl.Location);

            photoControl.User = UserInfo;
            loadPhotoWindow.Controls.Add(photoControl);

            if (UserInfo.IsMe() && SetupInfo.EnabledCultures.Count > 1)
            {
                _phLanguage.Controls.Add(LoadControl(UserLanguage.Location));
            }

            if ((UserInfo.IsLDAP() && !String.IsNullOrEmpty(UserInfo.MobilePhone)) ||
                !String.IsNullOrEmpty(UserInfo.MobilePhone) ||
                UserInfo.IsMe())
            {
                ShowPrimaryMobile = true;
                if (Actions.AllowEdit && (!UserInfo.IsLDAP() || UserInfo.IsLDAP() && !LdapFields.Contains(LdapMapping.MobilePhoneAttribute)))
                {
                    var changeMobile = (ChangeMobileNumber)LoadControl(ChangeMobileNumber.Location);
                    changeMobile.User = UserInfo;
                    ChangeMobileHolder.Controls.Add(changeMobile);
                }
            }

            if (TfaAppAuthSettings.IsVisibleSettings && TfaAppAuthSettings.Enable && TfaAppUserSettings.EnableForUser(UserInfo.ID) && (UserInfo.IsMe() || IsAdmin))
            {
                ShowTfaAppSettings = true;

                if (UserInfo.IsMe() || IsAdmin)
                {
                    var resetApp = (ResetAppDialog)LoadControl(ResetAppDialog.Location);
                    resetApp.User = UserInfo;
                    _backupCodesPlaceholder.Controls.Add(resetApp);
                }
                if (UserInfo.IsMe())
                {
                    var showBackup = (ShowBackupCodesDialog)LoadControl(ShowBackupCodesDialog.Location);
                    showBackup.User = UserInfo;
                    _backupCodesPlaceholder.Controls.Add(showBackup);
                }
            }

            if (UserInfo.BirthDate.HasValue)
            {
                switch (HappyBirthday)
                {
                case 0:
                    BirthDayText = Resource.DrnToday;
                    break;

                case 1:
                    BirthDayText = Resource.DrnTomorrow;
                    break;

                case 2:
                    BirthDayText = Resource.In + " " + DateTimeExtension.Yet(2);
                    break;

                case 3:
                    BirthDayText = Resource.In + " " + DateTimeExtension.Yet(3);
                    break;

                default:
                    BirthDayText = String.Empty;
                    break;
                }
            }

            if (UserInfo.Status != EmployeeStatus.Terminated)
            {
                Groups = CoreContext.UserManager.GetUserGroups(UserInfo.ID).ToList();
            }
        }
Esempio n. 8
0
        public static bool CheckDocServiceUrl()
        {
            var          key = GenerateRevisionId(Guid.NewGuid().ToString());
            string       fileUri;
            const string toExtension   = ".docx";
            var          fileExtension = FileUtility.GetInternalExtension(toExtension);
            var          path          = FileConstant.NewDocPath + "default/new" + fileExtension;

            if (!string.IsNullOrEmpty(FilesLinkUtility.DocServiceStorageUrl))
            {
                try
                {
                    var storeTemplate = Global.GetStoreTemplate();
                    using (var stream = storeTemplate.GetReadStream("", path))
                    {
                        fileUri = Web.Core.Files.DocumentService.GetExternalUri(FilesLinkUtility.DocServiceStorageUrl, stream, MimeMapping.GetMimeMapping(toExtension), key, FileUtility.SignatureSecret);
                    }
                }
                catch (Exception ex)
                {
                    Global.Logger.Error("DocService check error", ex);
                    throw new Exception("Storage url: " + ex.Message);
                }

                try
                {
                    string tmp;
                    Web.Core.Files.DocumentService.GetConvertedUri(FilesLinkUtility.DocServiceConverterUrl, fileUri, fileExtension, toExtension, key, false, FileUtility.SignatureSecret, out tmp);
                }
                catch (Exception ex)
                {
                    Global.Logger.Error("DocService check error", ex);
                    throw new Exception("Converter url: " + ex.Message);
                }
            }

            if (!string.IsNullOrEmpty(FilesLinkUtility.DocServiceConverterUrl))
            {
                try
                {
                    var storeTemplate = Global.GetStoreTemplate();
                    var uri           = storeTemplate.GetUri("", path);
                    var url           = CommonLinkUtility.GetFullAbsolutePath(uri.ToString());

                    fileUri = ReplaceCommunityAdress(url, FilesLinkUtility.DocServicePortalUrl);

                    key = GenerateRevisionId(Guid.NewGuid().ToString());
                    string tmp;
                    Web.Core.Files.DocumentService.GetConvertedUri(FilesLinkUtility.DocServiceConverterUrl, fileUri, fileExtension, toExtension, key, false, FileUtility.SignatureSecret, out tmp);
                }
                catch (Exception ex)
                {
                    Global.Logger.Error("DocService check error", ex);
                    throw new Exception("Community server url: " + ex.Message);
                }
            }

            if (!string.IsNullOrEmpty(FilesLinkUtility.DocServiceCommandUrl))
            {
                try
                {
                    string version;
                    Web.Core.Files.DocumentService.CommandRequest(FilesLinkUtility.DocServiceCommandUrl, CommandMethod.Version, key, null, null, null, FileUtility.SignatureSecret, out version);
                }
                catch (Exception ex)
                {
                    Global.Logger.Error("DocService check error", ex);
                    throw new Exception("Command url: " + ex.Message);
                }
            }

            return(true);
        }
Esempio n. 9
0
        public VoipUpload DeleteUploadedFile(AudioType audioType, string fileName)
        {
            if (!CRMSecurity.IsAdmin)
            {
                throw CRMSecurity.CreateSecurityException();
            }

            var store  = Global.GetStore();
            var path   = Path.Combine(audioType.ToString().ToLower(), fileName);
            var result = new VoipUpload
            {
                AudioType = audioType,
                Name      = fileName,
                Path      = CommonLinkUtility.GetFullAbsolutePath(store.GetUri(path).ToString())
            };

            if (!store.IsFile("voip", path))
            {
                throw new ItemNotFoundException();
            }
            store.Delete("voip", path);

            var dao     = DaoFactory.GetVoipDao();
            var numbers = dao.GetNumbers();

            var defAudio = StorageFactory.GetStorage("", "crm").ListFiles("voip", "default/" + audioType.ToString().ToLower(), "*.*", true).FirstOrDefault();

            if (defAudio == null)
            {
                return(result);
            }

            foreach (var number in numbers)
            {
                switch (audioType)
                {
                case AudioType.Greeting:
                    if (number.Settings.GreetingAudio == result.Path)
                    {
                        number.Settings.GreetingAudio = CommonLinkUtility.GetFullAbsolutePath(defAudio.ToString());
                    }
                    break;

                case AudioType.HoldUp:
                    if (number.Settings.HoldAudio == result.Path)
                    {
                        number.Settings.HoldAudio = CommonLinkUtility.GetFullAbsolutePath(defAudio.ToString());
                    }
                    break;

                case AudioType.Queue:
                    var queue = number.Settings.Queue;
                    if (queue != null && queue.WaitUrl == result.Path)
                    {
                        queue.WaitUrl = CommonLinkUtility.GetFullAbsolutePath(defAudio.ToString());
                    }
                    break;

                case AudioType.VoiceMail:
                    if (number.Settings.VoiceMail == result.Path)
                    {
                        number.Settings.VoiceMail = CommonLinkUtility.GetFullAbsolutePath(defAudio.ToString());
                    }
                    break;
                }

                dao.SaveOrUpdateNumber(number);
            }

            return(result);
        }
Esempio n. 10
0
 public static string GetStoredUrl(Uri uri)
 {
     return(GetStoredUrl(!uri.IsAbsoluteUri ? CommonLinkUtility.GetFullAbsolutePath(uri.ToString()) : uri.ToString()));
 }
Esempio n. 11
0
        private void PageLoad()
        {
            var editPossible = !RequestEmbedded;
            var isExtenral   = false;

            File file;
            var  fileUri = string.Empty;

            try
            {
                if (string.IsNullOrEmpty(RequestFileUrl))
                {
                    _fileNew = (Request["new"] ?? "") == "true";

                    var app = ThirdPartySelector.GetAppByFileId(RequestFileId);
                    if (app == null)
                    {
                        var ver = string.IsNullOrEmpty(Request[FilesLinkUtility.Version]) ? -1 : Convert.ToInt32(Request[FilesLinkUtility.Version]);

                        file = DocumentServiceHelper.GetParams(RequestFileId, ver, RequestShareLinkKey, _fileNew, editPossible, !RequestView, out _docParams);

                        _fileNew = _fileNew && file.Version == 1 && file.ConvertedType != null && file.CreateOn == file.ModifiedOn;
                    }
                    else
                    {
                        isExtenral = true;

                        bool editable;
                        _thirdPartyApp = true;
                        file           = app.GetFile(RequestFileId, out editable);
                        file           = DocumentServiceHelper.GetParams(file, true, true, true, editable, editable, editable, out _docParams);

                        _docParams.FileUri   = app.GetFileStreamUrl(file);
                        _docParams.FolderUrl = string.Empty;
                    }
                }
                else
                {
                    isExtenral = true;

                    fileUri = RequestFileUrl;
                    var fileTitle = Request[FilesLinkUtility.FileTitle];
                    if (string.IsNullOrEmpty(fileTitle))
                    {
                        fileTitle = Path.GetFileName(HttpUtility.UrlDecode(fileUri)) ?? "";
                    }

                    if (CoreContext.Configuration.Standalone)
                    {
                        try
                        {
                            var webRequest = WebRequest.Create(RequestFileUrl);
                            using (var response = webRequest.GetResponse())
                                using (var responseStream = new ResponseStream(response))
                                {
                                    var externalFileKey = DocumentServiceConnector.GenerateRevisionId(RequestFileUrl);
                                    fileUri = DocumentServiceConnector.GetExternalUri(responseStream, MimeMapping.GetMimeMapping(fileTitle), externalFileKey);
                                }
                        }
                        catch (Exception error)
                        {
                            Global.Logger.Error("Cannot receive external url for \"" + RequestFileUrl + "\"", error);
                        }
                    }

                    file = new File
                    {
                        ID    = RequestFileUrl,
                        Title = Global.ReplaceInvalidCharsAndTruncate(fileTitle)
                    };

                    file = DocumentServiceHelper.GetParams(file, true, true, true, false, false, false, out _docParams);
                    _docParams.CanEdit = editPossible && !CoreContext.Configuration.Standalone;
                    _editByUrl         = true;

                    _docParams.FileUri = fileUri;
                }
            }
            catch (Exception ex)
            {
                _errorMessage = ex.Message;
                return;
            }

            if (_docParams.ModeWrite && FileConverter.MustConvert(file))
            {
                try
                {
                    file = FileConverter.ExecDuplicate(file, RequestShareLinkKey);
                }
                catch (Exception e)
                {
                    _docParams    = null;
                    _errorMessage = e.Message;
                    return;
                }

                var comment = "#message/" + HttpUtility.UrlEncode(FilesCommonResource.CopyForEdit);

                Response.Redirect(FilesLinkUtility.GetFileWebEditorUrl(file.ID) + comment);
                return;
            }

            Title = file.Title;

            if (string.IsNullOrEmpty(_docParams.FolderUrl))
            {
                _docParams.FolderUrl = Request[FilesLinkUtility.FolderUrl] ?? "";
            }
            if (MobileDetector.IsRequestMatchesMobile(true))
            {
                _docParams.FolderUrl = string.Empty;
            }

            if (RequestEmbedded)
            {
                _docParams.Type = DocumentServiceParams.EditorType.Embedded;

                var shareLinkParam = "&" + FilesLinkUtility.DocShareKey + "=" + RequestShareLinkKey;
                _docParams.ViewerUrl   = CommonLinkUtility.GetFullAbsolutePath(FilesLinkUtility.FilesBaseAbsolutePath + FilesLinkUtility.EditorPage + "?" + FilesLinkUtility.Action + "=view" + shareLinkParam);
                _docParams.DownloadUrl = CommonLinkUtility.GetFullAbsolutePath(FilesLinkUtility.FileHandlerPath + "?" + FilesLinkUtility.Action + "=download" + shareLinkParam);
                _docParams.EmbeddedUrl = CommonLinkUtility.GetFullAbsolutePath(FilesLinkUtility.FilesBaseAbsolutePath + FilesLinkUtility.EditorPage + "?" + FilesLinkUtility.Action + "=embedded" + shareLinkParam);
            }
            else
            {
                _docParams.Type = IsMobile ? DocumentServiceParams.EditorType.Mobile : DocumentServiceParams.EditorType.Desktop;

                if (FileSharing.CanSetAccess(file))
                {
                    _docParams.SharingSettingsUrl = CommonLinkUtility.GetFullAbsolutePath(Share.Location + "?" + FilesLinkUtility.FileId + "=" + file.ID);
                }
            }

            if (!isExtenral)
            {
                _docKeyForTrack = DocumentServiceHelper.GetDocKey(file.ID, -1, DateTime.MinValue);

                FileMarker.RemoveMarkAsNew(file);
            }

            if (_docParams.ModeWrite)
            {
                _tabId                   = FileTracker.Add(file.ID, _fileNew);
                _fixedVersion            = FileTracker.FixedVersion(file.ID);
                _docParams.FileChoiceUrl = CommonLinkUtility.GetFullAbsolutePath(FileChoice.Location) + "?" + FileChoice.DocumentTypeParam + "=" + FilterType.SpreadsheetsOnly;
            }
            else
            {
                _docParams.LinkToEdit = _editByUrl
                                            ? CommonLinkUtility.GetFullAbsolutePath(FilesLinkUtility.GetFileWebEditorExternalUrl(fileUri, file.Title))
                                            : CommonLinkUtility.GetFullAbsolutePath(FilesLinkUtility.GetFileWebEditorUrl(file.ID));

                if (FileConverter.MustConvert(_docParams.File))
                {
                    _editByUrl = true;
                }
            }
        }
        private void AggregateFeeds(object interval)
        {
            if (!Monitor.TryEnter(aggregateLock))
            {
                return;
            }

            try
            {
                var start = DateTime.UtcNow;
                log.DebugFormat("Start of collecting feeds...");

                var unreadUsers = new Dictionary <int, Dictionary <Guid, int> >();

                foreach (var module in Modules)
                {
                    var result   = new List <FeedRow>();
                    var fromTime = FeedAggregateDataProvider.GetLastTimeAggregate(module.GetType().Name);
                    if (fromTime == default(DateTime))
                    {
                        fromTime = DateTime.UtcNow.Subtract((TimeSpan)interval);
                    }
                    var toTime = DateTime.UtcNow;

                    var tenants = Attempt(10, () => module.GetTenantsWithFeeds(fromTime)).ToList();
                    log.DebugFormat("Find {1} tenants for module {0}.", module.GetType().Name, tenants.Count());

                    foreach (var tenant in tenants)
                    {
                        // Warning! There is hack here!
                        // clearing the cache to get the correct acl
                        var cache = AscCache.Memory;
                        cache.Remove("acl" + tenant);
                        cache.Remove("/webitemsecurity/" + tenant);
                        cache.Remove(string.Format("sub/{0}/{1}/{2}", tenant, "6045b68c-2c2e-42db-9e53-c272e814c4ad", NotifyConstants.Event_NewCommentForMessage.ID));

                        HttpContext.Current = null;
                        try
                        {
                            if (CoreContext.TenantManager.GetTenant(tenant) == null)
                            {
                                continue;
                            }

                            CoreContext.TenantManager.SetCurrentTenant(tenant);
                            var users = CoreContext.UserManager.GetUsers();
                            // fake httpcontext break configuration manager for mono
                            if (!WorkContext.IsMono)
                            {
                                HttpContext.Current = new HttpContext(
                                    new HttpRequest("hack", CommonLinkUtility.GetFullAbsolutePath("/"), string.Empty),
                                    new HttpResponse(new StringWriter()));
                            }

                            var feeds = Attempt(10, () => module.GetFeeds(new FeedFilter(fromTime, toTime)
                            {
                                Tenant = tenant
                            }).ToList());
                            log.DebugFormat("{0} feeds in {1} tenant.", feeds.Count(), tenant);
                            foreach (var tuple in feeds)
                            {
                                if (tuple.Item1 == null)
                                {
                                    continue;
                                }

                                var r = new FeedRow
                                {
                                    Id = tuple.Item1.Id,
                                    ClearRightsBeforeInsert = tuple.Item1.Variate,
                                    Tenant       = tenant,
                                    ProductId    = module.Product,
                                    ModuleId     = tuple.Item1.Module,
                                    AuthorId     = tuple.Item1.AuthorId,
                                    ModifiedById = tuple.Item1.ModifiedBy,
                                    CreatedDate  = tuple.Item1.CreatedDate,
                                    ModifiedDate = tuple.Item1.ModifiedDate,
                                    GroupId      = tuple.Item1.GroupId,
                                    Json         = JsonConvert.SerializeObject(tuple.Item1, new JsonSerializerSettings
                                    {
                                        DateTimeZoneHandling = DateTimeZoneHandling.Utc
                                    }),
                                    Keywords = tuple.Item1.Keywords
                                };

                                foreach (var u in users)
                                {
                                    if (isStopped)
                                    {
                                        return;
                                    }
                                    if (TryAuthenticate(u.ID) && module.VisibleFor(tuple.Item1, tuple.Item2, u.ID))
                                    {
                                        r.Users.Add(u.ID);
                                    }
                                }

                                result.Add(r);
                            }
                        }
                        catch (Exception ex)
                        {
                            log.ErrorFormat("Tenant: {0}, {1}", tenant, ex);
                        }
                        finally
                        {
                            // fake httpcontext break configuration manager for mono
                            if (!WorkContext.IsMono)
                            {
                                if (HttpContext.Current != null)
                                {
                                    new DisposableHttpContext(HttpContext.Current).Dispose();
                                    HttpContext.Current = null;
                                }
                            }
                        }
                    }

                    FeedAggregateDataProvider.SaveFeeds(result, module.GetType().Name, toTime);

                    foreach (var res in result)
                    {
                        foreach (var userGuid in res.Users.Where(userGuid => !userGuid.Equals(res.ModifiedById)))
                        {
                            Dictionary <Guid, int> dictionary;
                            if (!unreadUsers.TryGetValue(res.Tenant, out dictionary))
                            {
                                dictionary = new Dictionary <Guid, int>();
                            }
                            if (dictionary.ContainsKey(userGuid))
                            {
                                ++dictionary[userGuid];
                            }
                            else
                            {
                                dictionary.Add(userGuid, 1);
                            }

                            unreadUsers[res.Tenant] = dictionary;
                        }
                    }
                }

                signalrServiceClient.SendUnreadUsers(unreadUsers);

                log.DebugFormat("Time of collecting news: {0}", DateTime.UtcNow - start);
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
            finally
            {
                Monitor.Exit(aggregateLock);
            }
        }
Esempio n. 13
0
        private void PageLoad()
        {
            var editPossible = !RequestEmbedded && !IsMobile;
            var isExtenral   = false;

            File file;
            var  fileUri = string.Empty;

            if (!ItsTry)
            {
                try
                {
                    if (string.IsNullOrEmpty(RequestFileUrl))
                    {
                        _fileNew = !string.IsNullOrEmpty(Request[UrlConstant.New]) && Request[UrlConstant.New] == "true";

                        var ver = string.IsNullOrEmpty(Request[CommonLinkUtility.Version]) ? -1 : Convert.ToInt32(Request[CommonLinkUtility.Version]);

                        file = DocumentServiceHelper.GetParams(RequestFileId, ver, RequestShareLinkKey, _fileNew, editPossible, !RequestView, out _docParams);

                        _fileNew = file.Version == 1 && file.ConvertedType != null && _fileNew && file.CreateOn == file.ModifiedOn;
                    }
                    else
                    {
                        isExtenral = true;

                        fileUri = RequestFileUrl;
                        var fileTitle = Request[CommonLinkUtility.FileTitle];
                        if (string.IsNullOrEmpty(fileTitle))
                        {
                            fileTitle = Path.GetFileName(HttpUtility.UrlDecode(fileUri)) ?? "";
                        }

                        if (CoreContext.Configuration.Standalone)
                        {
                            try
                            {
                                var webRequest = WebRequest.Create(RequestFileUrl);
                                using (var response = webRequest.GetResponse())
                                    using (var responseStream = new ResponseStream(response))
                                    {
                                        fileUri = DocumentServiceConnector.GetExternalUri(responseStream, MimeMapping.GetMimeMapping(fileTitle), "new");
                                    }
                            }
                            catch (Exception error)
                            {
                                Global.Logger.Error("Cannot receive external url for \"" + RequestFileUrl + "\"", error);
                            }
                        }

                        file = new File
                        {
                            ID    = fileUri.GetHashCode(),
                            Title = Global.ReplaceInvalidCharsAndTruncate(fileTitle)
                        };

                        file = DocumentServiceHelper.GetParams(file, true, true, true, false, false, false, out _docParams);
                        _docParams.CanEdit = editPossible && !CoreContext.Configuration.Standalone;
                        _editByUrl         = true;

                        _docParams.FileUri = fileUri;
                    }
                }
                catch (Exception ex)
                {
                    _errorMessage = ex.Message;
                    return;
                }
            }
            else
            {
                FileType tryType;
                try
                {
                    tryType = (FileType)Enum.Parse(typeof(FileType), Request[CommonLinkUtility.TryParam]);
                }
                catch
                {
                    tryType = FileType.Document;
                }

                var fileTitle = "Demo";
                fileTitle += FileUtility.InternalExtension[tryType];

                var relativeUri = string.Format(CommonLinkUtility.FileHandlerPath + UrlConstant.ParamsDemo, tryType);
                fileUri = new Uri(Request.Url, relativeUri).ToString();

                file = new File
                {
                    ID    = Guid.NewGuid(),
                    Title = Global.ReplaceInvalidCharsAndTruncate(fileTitle)
                };

                file = DocumentServiceHelper.GetParams(file, true, true, true, editPossible, editPossible, true, out _docParams);

                _docParams.FileUri = fileUri;
                _editByUrl         = true;
            }

            if (_docParams.ModeWrite && FileConverter.MustConvert(file))
            {
                try
                {
                    file = FileConverter.ExecDuplicate(file, RequestShareLinkKey);
                }
                catch (Exception e)
                {
                    _docParams    = null;
                    _errorMessage = e.Message;
                    return;
                }

                var comment = "#message/" + HttpUtility.UrlEncode(FilesCommonResource.CopyForEdit);

                Response.Redirect(CommonLinkUtility.GetFileWebEditorUrl(file.ID) + comment);
                return;
            }

            Title = HeaderStringHelper.GetPageTitle(file.Title);

            if (string.IsNullOrEmpty(_docParams.FolderUrl))
            {
                _docParams.FolderUrl = Request[CommonLinkUtility.FolderUrl] ?? "";
            }
            if (MobileDetector.IsRequestMatchesMobile(Context.Request.UserAgent, true))
            {
                _docParams.FolderUrl = string.Empty;
            }

            if (RequestEmbedded)
            {
                _docParams.Type = DocumentServiceParams.EditorType.Embedded;

                var shareLinkParam = "&" + CommonLinkUtility.DocShareKey + "=" + RequestShareLinkKey;
                _docParams.ViewerUrl   = CommonLinkUtility.GetFullAbsolutePath(CommonLinkUtility.FilesBaseAbsolutePath + CommonLinkUtility.EditorPage + "?" + CommonLinkUtility.Action + "=view" + shareLinkParam);
                _docParams.DownloadUrl = CommonLinkUtility.GetFullAbsolutePath(CommonLinkUtility.FileHandlerPath + "?" + CommonLinkUtility.Action + "=download" + shareLinkParam);
                _docParams.EmbeddedUrl = CommonLinkUtility.GetFullAbsolutePath(CommonLinkUtility.FilesBaseAbsolutePath + CommonLinkUtility.EditorPage + "?" + CommonLinkUtility.Action + "=embedded" + shareLinkParam);
            }
            else
            {
                _docParams.Type = IsMobile ? DocumentServiceParams.EditorType.Mobile : DocumentServiceParams.EditorType.Desktop;

                if (FileSharing.CanSetAccess(file))
                {
                    _docParams.SharingSettingsUrl = CommonLinkUtility.GetFullAbsolutePath(CommonLinkUtility.FilesBaseAbsolutePath + "share.aspx" + "?" + CommonLinkUtility.FileId + "=" + file.ID + "&" + CommonLinkUtility.FileTitle + "=" + HttpUtility.UrlEncode(file.Title));
                }
            }

            if (!isExtenral)
            {
                _docKeyForTrack = DocumentServiceHelper.GetDocKey(file.ID, -1, DateTime.MinValue);

                if (!ItsTry)
                {
                    FileMarker.RemoveMarkAsNew(file);
                }
            }

            if (_docParams.ModeWrite)
            {
                _tabId       = FileLocker.Add(file.ID, _fileNew);
                _lockVersion = FileLocker.LockVersion(file.ID);

                if (ItsTry)
                {
                    AppendAuthControl();
                }
            }
            else
            {
                _docParams.LinkToEdit = _editByUrl
                                            ? CommonLinkUtility.GetFullAbsolutePath(string.Format(CommonLinkUtility.FileWebEditorExternalUrlString, HttpUtility.UrlEncode(fileUri), file.Title))
                                            : FileConverter.MustConvert(_docParams.File)
                                                  ? CommonLinkUtility.GetFullAbsolutePath(CommonLinkUtility.GetFileWebEditorUrl(file.ID))
                                                  : string.Empty;
            }

            if (CoreContext.Configuration.YourDocsDemo && IsMobile)
            {
                _docParams.CanEdit = false;
            }
        }
 public string GetFullAbsolutePath(string virtualPath)
 {
     return(CommonLinkUtility.GetFullAbsolutePath(virtualPath));
 }
Esempio n. 15
0
        public void SendMsgWhatsNew(DateTime scheduleDate, INotifyClient client)
        {
            var log = LogManager.GetLogger("ASC.Notify.WhatsNew");

            if (WebItemManager.Instance.GetItemsAll <IProduct>().Count == 0)
            {
                log.Info("No products. Return from function");
                return;
            }

            log.Info("Start send whats new.");

            var products = WebItemManager.Instance.GetItemsAll().ToDictionary(p => p.GetSysName());

            foreach (var tenantid in GetChangedTenants(scheduleDate))
            {
                try
                {
                    var tenant = CoreContext.TenantManager.GetTenant(tenantid);
                    if (tenant == null ||
                        tenant.Status != TenantStatus.Active ||
                        !TimeToSendWhatsNew(TenantUtil.DateTimeFromUtc(tenant.TimeZone, scheduleDate)) ||
                        TariffState.NotPaid <= CoreContext.PaymentManager.GetTariff(tenantid).State)
                    {
                        continue;
                    }

                    CoreContext.TenantManager.SetCurrentTenant(tenant);

                    log.InfoFormat("Start send whats new in {0} ({1}).", tenant.TenantDomain, tenantid);
                    foreach (var user in CoreContext.UserManager.GetUsers())
                    {
                        if (!IsSubscribeToWhatsNew(user))
                        {
                            continue;
                        }

                        SecurityContext.AuthenticateMe(CoreContext.Authentication.GetAccountByID(user.ID));

                        var culture = string.IsNullOrEmpty(user.CultureName) ? tenant.GetCulture() : user.GetCulture();

                        Thread.CurrentThread.CurrentCulture   = culture;
                        Thread.CurrentThread.CurrentUICulture = culture;

                        var feeds = FeedAggregateDataProvider.GetFeeds(new FeedApiFilter
                        {
                            From = scheduleDate.Date.AddDays(-1),
                            To   = scheduleDate.Date.AddSeconds(-1),
                            Max  = 100,
                        });

                        var feedMinWrappers = feeds.ConvertAll(f => f.ToFeedMin());

                        var feedMinGroupedWrappers = feedMinWrappers
                                                     .Where(f =>
                                                            (f.CreatedDate == DateTime.MaxValue || f.CreatedDate >= scheduleDate.Date.AddDays(-1)) && //'cause here may be old posts with new comments
                                                            products.ContainsKey(f.Product) &&
                                                            !f.Id.StartsWith("participant")
                                                            )
                                                     .GroupBy(f => products[f.Product]);

                        var ProjectsProductName = products["projects"].Name; //from ASC.Feed.Aggregator.Modules.ModulesHelper.ProjectsProductName

                        var activities = feedMinGroupedWrappers
                                         .Where(f => f.Key.Name != ProjectsProductName) //not for project product
                                         .ToDictionary(
                            g => g.Key.Name,
                            g => g.Select(f => new WhatsNewUserActivity
                        {
                            Date            = f.CreatedDate,
                            UserName        = f.Author != null && f.Author.UserInfo != null ? f.Author.UserInfo.DisplayUserName() : string.Empty,
                            UserAbsoluteURL = f.Author != null && f.Author.UserInfo != null ? CommonLinkUtility.GetFullAbsolutePath(f.Author.UserInfo.GetUserProfilePageURL()) : string.Empty,
                            Title           = HtmlUtil.GetText(f.Title, 512),
                            URL             = CommonLinkUtility.GetFullAbsolutePath(f.ItemUrl),
                            BreadCrumbs     = new string[0],
                            Action          = getWhatsNewActionText(f)
                        }).ToList());


                        var projectActivities = feedMinGroupedWrappers
                                                .Where(f => f.Key.Name == ProjectsProductName) // for project product
                                                .SelectMany(f => f);

                        var projectActivitiesWithoutBreadCrumbs = projectActivities.Where(p => String.IsNullOrEmpty(p.ExtraLocation));

                        var whatsNewUserActivityGroupByPrjs = new List <WhatsNewUserActivity>();

                        foreach (var prawbc in projectActivitiesWithoutBreadCrumbs)
                        {
                            whatsNewUserActivityGroupByPrjs.Add(
                                new WhatsNewUserActivity
                            {
                                Date            = prawbc.CreatedDate,
                                UserName        = prawbc.Author != null && prawbc.Author.UserInfo != null ? prawbc.Author.UserInfo.DisplayUserName() : string.Empty,
                                UserAbsoluteURL = prawbc.Author != null && prawbc.Author.UserInfo != null ? CommonLinkUtility.GetFullAbsolutePath(prawbc.Author.UserInfo.GetUserProfilePageURL()) : string.Empty,
                                Title           = HtmlUtil.GetText(prawbc.Title, 512),
                                URL             = CommonLinkUtility.GetFullAbsolutePath(prawbc.ItemUrl),
                                BreadCrumbs     = new string[0],
                                Action          = getWhatsNewActionText(prawbc)
                            });
                        }

                        var groupByPrjs = projectActivities.Where(p => !String.IsNullOrEmpty(p.ExtraLocation)).GroupBy(f => f.ExtraLocation);
                        foreach (var gr in groupByPrjs)
                        {
                            var grlist = gr.ToList();
                            for (var i = 0; i < grlist.Count(); i++)
                            {
                                var ls = grlist[i];
                                whatsNewUserActivityGroupByPrjs.Add(
                                    new WhatsNewUserActivity
                                {
                                    Date            = ls.CreatedDate,
                                    UserName        = ls.Author != null && ls.Author.UserInfo != null ? ls.Author.UserInfo.DisplayUserName() : string.Empty,
                                    UserAbsoluteURL = ls.Author != null && ls.Author.UserInfo != null ? CommonLinkUtility.GetFullAbsolutePath(ls.Author.UserInfo.GetUserProfilePageURL()) : string.Empty,
                                    Title           = HtmlUtil.GetText(ls.Title, 512),
                                    URL             = CommonLinkUtility.GetFullAbsolutePath(ls.ItemUrl),
                                    BreadCrumbs     = i == 0 ? new string[1] {
                                        gr.Key
                                    } : new string[0],
                                    Action = getWhatsNewActionText(ls)
                                });
                            }
                        }

                        if (whatsNewUserActivityGroupByPrjs.Count > 0)
                        {
                            activities.Add(ProjectsProductName, whatsNewUserActivityGroupByPrjs);
                        }

                        if (0 < activities.Count)
                        {
                            log.InfoFormat("Send whats new to {0}", user.Email);
                            client.SendNoticeAsync(
                                Constants.ActionSendWhatsNew, null, user, null,
                                new TagValue(Constants.TagActivities, activities),
                                new TagValue(Constants.TagDate, DateToString(scheduleDate.AddDays(-1), culture)),
                                new TagValue(CommonTags.Priority, 1)
                                );
                        }
                    }
                }
                catch (Exception error)
                {
                    log.Error(error);
                }
            }
        }
        public object UpdatePortalName(string alias)
        {
            var enabled = SetupInfo.IsVisibleSettings("PortalRename");

            if (!enabled)
            {
                throw new SecurityException(Resources.Resource.PortalAccessSettingsTariffException);
            }

            if (CoreContext.Configuration.Personal)
            {
                throw new Exception(Resource.ErrorAccessDenied);
            }

            SecurityContext.DemandPermissions(SecutiryConstants.EditPortalSettings);

            if (String.IsNullOrEmpty(alias))
            {
                throw new ArgumentException();
            }


            var tenant = CoreContext.TenantManager.GetCurrentTenant();
            var user   = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID);

            var newAlias           = alias.ToLowerInvariant();
            var oldAlias           = tenant.TenantAlias;
            var oldVirtualRootPath = CommonLinkUtility.GetFullAbsolutePath("~").TrimEnd('/');

            if (!String.Equals(newAlias, oldAlias, StringComparison.InvariantCultureIgnoreCase))
            {
                var hostedSolution = new HostedSolution(ConfigurationManager.ConnectionStrings["default"]);
                if (!String.IsNullOrEmpty(SetupInfo.ApiSystemUrl))
                {
                    ValidatePortalName(newAlias);
                }
                else
                {
                    hostedSolution.CheckTenantAddress(newAlias.Trim());
                }


                if (!String.IsNullOrEmpty(SetupInfo.ApiCacheUrl))
                {
                    AddTenantToCache(newAlias);
                }

                tenant.TenantAlias = alias;
                tenant             = hostedSolution.SaveTenant(tenant);


                if (!String.IsNullOrEmpty(SetupInfo.ApiCacheUrl))
                {
                    RemoveTenantFromCache(oldAlias);
                }

                StudioNotifyService.Instance.PortalRenameNotify(oldVirtualRootPath);
            }
            else
            {
                throw new Exception(ResourceJS.ErrorPortalNameWasNotChanged);
            }

            var reference = CreateReference(Request, tenant.TenantDomain, tenant.TenantId, user.Email);

            return(new {
                message = Resources.Resource.SuccessfullyPortalRenameMessage,
                reference = reference
            });
        }
        public static string GetUploadChunkLocationUrl(string uploadId)
        {
            var queryString = "?uid=" + uploadId;

            return(CommonLinkUtility.GetFullAbsolutePath(GetFileUploaderHandlerVirtualPath() + queryString));
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (UserProfileHelper == null)
            {
                UserProfileHelper = new ProfileHelper(SecurityContext.CurrentAccount.ID.ToString());
            }
            UserInfo         = UserProfileHelper.UserInfo;
            ShowSocialLogins = UserInfo.IsMe();

            IsAdmin   = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID).IsAdmin();
            IsVisitor = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID).IsVisitor();

            if (!IsAdmin && (UserInfo.Status != EmployeeStatus.Active))
            {
                Response.Redirect(CommonLinkUtility.GetFullAbsolutePath("~/products/people/"), true);
            }

            AjaxPro.Utility.RegisterTypeForAjax(GetType());
            Actions = new AllowedActions(UserInfo);

            HappyBirthday = CheckHappyBirthday();

            ContactPhones.DataSource = UserProfileHelper.Phones;
            ContactPhones.DataBind();

            ContactEmails.DataSource = UserProfileHelper.Emails;
            ContactEmails.DataBind();

            ContactMessengers.DataSource = UserProfileHelper.Messengers;
            ContactMessengers.DataBind();

            ContactSoccontacts.DataSource = UserProfileHelper.Contacts;
            ContactSoccontacts.DataBind();

            _deleteProfileContainer.Options.IsPopup = true;

            Page.RegisterStyleControl(VirtualPathUtility.ToAbsolute("~/usercontrols/users/userprofile/css/userprofilecontrol_style.less"));
            Page.RegisterBodyScripts(VirtualPathUtility.ToAbsolute("~/usercontrols/users/userprofile/js/userprofilecontrol.js"));

            if (Actions.AllowEdit)
            {
                _editControlsHolder.Controls.Add(LoadControl(PwdTool.Location));
            }
            if (Actions.AllowEdit || (UserInfo.IsOwner() && IsAdmin))
            {
                var control = (UserEmailChange)LoadControl(UserEmailChange.Location);
                control.UserInfo = UserInfo;
                userEmailChange.Controls.Add(control);
            }

            if (!MobileDetector.IsMobile)
            {
                var thumbnailEditorControl = (ThumbnailEditor)LoadControl(ThumbnailEditor.Location);
                thumbnailEditorControl.Title            = Resource.TitleThumbnailPhoto;
                thumbnailEditorControl.BehaviorID       = "UserPhotoThumbnail";
                thumbnailEditorControl.JcropMinSize     = UserPhotoManager.SmallFotoSize;
                thumbnailEditorControl.JcropAspectRatio = 1;
                thumbnailEditorControl.SaveFunctionType = typeof(SavePhotoThumbnails);
                _editControlsHolder.Controls.Add(thumbnailEditorControl);
            }

            if (ShowSocialLogins && AccountLinkControl.IsNotEmpty)
            {
                var accountLink = (AccountLinkControl)LoadControl(AccountLinkControl.Location);
                accountLink.ClientCallback = "loginCallback";
                accountLink.SettingsView   = true;
                _accountPlaceholder.Controls.Add(accountLink);
            }

            var emailControl = (UserEmailControl)LoadControl(UserEmailControl.Location);

            emailControl.User   = UserInfo;
            emailControl.Viewer = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID);
            _phEmailControlsHolder.Controls.Add(emailControl);

            var photoControl = (LoadPhotoControl)LoadControl(LoadPhotoControl.Location);

            loadPhotoWindow.Controls.Add(photoControl);

            if (UserInfo.IsMe())
            {
                _phLanguage.Controls.Add(LoadControl(UserLanguage.Location));
            }

            if (StudioSmsNotificationSettings.IsVisibleSettings && (Actions.AllowEdit && !String.IsNullOrEmpty(UserInfo.MobilePhone) || UserInfo.IsMe()))
            {
                ShowPrimaryMobile = true;
                var changeMobile = (ChangeMobileNumber)LoadControl(ChangeMobileNumber.Location);
                changeMobile.User = UserInfo;
                ChangeMobileHolder.Controls.Add(changeMobile);
            }

            if (UserInfo.BirthDate.HasValue)
            {
                switch (HappyBirthday)
                {
                case 0:
                    BirthDayText = Resource.DrnToday;
                    break;

                case 1:
                    BirthDayText = Resource.DrnTomorrow;
                    break;

                case 2:
                    BirthDayText = Resource.In + " " + DateTimeExtension.Yet(2);
                    break;

                case 3:
                    BirthDayText = Resource.In + " " + DateTimeExtension.Yet(3);
                    break;

                default:
                    BirthDayText = String.Empty;
                    break;
                }
            }

            if (UserInfo.Status != EmployeeStatus.Terminated)
            {
                List <GroupInfo> Groups = CoreContext.UserManager.GetUserGroups(UserInfo.ID).ToList();
                if (!Groups.Any())
                {
                    DepartmentsRepeater.Visible = false;
                }
                else
                {
                    Groups.Sort((group1, group2) => String.Compare(group1.Name, group2.Name, StringComparison.Ordinal));
                }

                DepartmentsRepeater.DataSource = Groups;
                DepartmentsRepeater.DataBind();
            }
        }
        public void SavePost(Post post, bool isNew, bool notifyComments)
        {
            CommunitySecurity.DemandPermissions(
                new PersonalBlogSecObject(CoreContext.UserManager.GetUsers(post.UserID)),
                isNew ? Constants.Action_AddPost : Constants.Action_EditRemovePost);

            _storage.GetPostDao().SavePost(post);
            FactoryIndexer <BlogsWrapper> .IndexAsync(post);

            if (isNew)
            {
                var initiatorInterceptor = new InitiatorInterceptor(new DirectRecipient(post.UserID.ToString(), ""));
                try
                {
                    NotifyClient.BeginSingleRecipientEvent("asc_blog");
                    NotifyClient.AddInterceptor(initiatorInterceptor);

                    var tags = new List <ITagValue>
                    {
                        new TagValue(Constants.TagPostSubject, post.Title),
                        new TagValue(Constants.TagPostPreview,
                                     post.GetPreviewText(500)),
                        new TagValue(Constants.TagUserName,
                                     DisplayUserSettings.GetFullUserName(post.UserID)),
                        new TagValue(Constants.TagUserURL,
                                     CommonLinkUtility.GetFullAbsolutePath(
                                         CommonLinkUtility.GetUserProfile(post.UserID))),
                        new TagValue(Constants.TagDate,
                                     string.Format("{0:d} {0:t}", post.Datetime)),
                        new TagValue(Constants.TagURL,
                                     CommonLinkUtility.GetFullAbsolutePath(
                                         Constants.ViewBlogPageUrl +
                                         "?blogid=" + post.ID.ToString())),
                        GetReplyToTag(Guid.Empty, post)
                    };

                    NotifyClient.SendNoticeAsync(
                        Constants.NewPost,
                        null,
                        null,
                        tags.ToArray());


                    NotifyClient.SendNoticeAsync(
                        Constants.NewPostByAuthor,
                        post.UserID.ToString(),
                        null,
                        tags.ToArray());

                    NotifyClient.EndSingleRecipientEvent("asc_blog");
                }
                finally
                {
                    NotifyClient.RemoveInterceptor(initiatorInterceptor.Name);
                }
            }
            if (!notifyComments)
            {
                return;
            }

            var subscriptionProvider = NotifySource.GetSubscriptionProvider();

            subscriptionProvider.Subscribe(
                Constants.NewComment,
                post.ID.ToString(),
                NotifySource.GetRecipientsProvider().
                GetRecipient(post.UserID.ToString())
                );
        }
Esempio n. 20
0
        private void InitScript()
        {
            var inlineScript = new StringBuilder();

            inlineScript.AppendFormat("\nASC.Files.Constants.URL_WCFSERVICE = \"{0}\";" +
                                      "ASC.Files.Constants.DocsAPIundefined = \"{1}\";",
                                      PathProvider.GetFileServicePath,
                                      FilesCommonResource.DocsAPIundefined);

            if (!CoreContext.Configuration.Personal)
            {
                inlineScript.AppendFormat("\nASC.Files.Constants.URL_MAIL_ACCOUNTS = \"{0}\";",
                                          CommonLinkUtility.GetFullAbsolutePath("~/addons/mail/#accounts"));
            }

            var docServiceParams = new DocumentServiceParams
            {
                DocKeyForTrack     = _docKeyForTrack,
                EditByUrl          = _editByUrl,
                LinkToEdit         = _linkToEdit,
                OpeninigDate       = DateTime.UtcNow.ToString(CultureInfo.InvariantCulture),
                ShareLinkParam     = string.IsNullOrEmpty(RequestShareLinkKey) ? string.Empty : "&" + FilesLinkUtility.DocShareKey + "=" + RequestShareLinkKey,
                ServerErrorMessage = ErrorMessage,
                TabId         = _tabId.ToString(),
                ThirdPartyApp = _thirdPartyApp,
            };

            if (_configuration != null)
            {
                docServiceParams.FileId          = _configuration.Document.Info.File.ID.ToString();
                docServiceParams.FileProviderKey = _configuration.Document.Info.File.ProviderKey;
                docServiceParams.FileVersion     = _configuration.Document.Info.File.Version;

                _configuration.Token = DocumentServiceHelper.GetSignature(_configuration);

                if (!string.IsNullOrEmpty(_configuration.Token))
                {
                    _configuration.EditorConfig.CallbackUrl = DocumentServiceTracker.GetCallbackUrl(_configuration.Document.Info.File.ID.ToString());
                }
            }

            inlineScript.AppendFormat("\nASC.Files.Editor.docServiceParams = {0};",
                                      DocumentServiceParams.Serialize(docServiceParams));

            inlineScript.AppendFormat("\nASC.Files.Editor.configurationParams = {0};",
                                      Services.DocumentService.Configuration.Serialize(_configuration));

            if (Request.DesktopApp() && SecurityContext.IsAuthenticated)
            {
                var user = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID);

                var displayName = DisplayUserSettings.GetFullUserName(user);
                var email       = user.Email;

                inlineScript.AppendFormat("\nASC.displayName = \"{0}\";" +
                                          "\nASC.email = \"{1}\";",
                                          displayName,
                                          email);
            }

            InlineScripts.Scripts.Add(new Tuple <string, bool>(inlineScript.ToString(), false));
        }
Esempio n. 21
0
        private void InitScript()
        {
            var inlineScript = new StringBuilder();

            inlineScript.AppendFormat("\nASC.Files.Constants.URL_WCFSERVICE = \"{0}\";",
                                      PathProvider.GetFileServicePath);

            if (!CoreContext.Configuration.Personal)
            {
                inlineScript.AppendFormat("\nASC.Files.Constants.URL_MAIL_ACCOUNTS = \"{0}\";",
                                          CommonLinkUtility.GetFullAbsolutePath("~/addons/mail/#accounts"));
            }

            if (SecurityContext.IsAuthenticated && !CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID).IsVisitor())
            {
                inlineScript.AppendFormat("ASC.Files.Constants.URL_HANDLER_CREATE = \"{0}\";" +
                                          "ASC.Files.Constants.TitleNewFileText = \"{1}\";" +
                                          "ASC.Files.Constants.TitleNewFileSpreadsheet = \"{2}\";" +
                                          "ASC.Files.Constants.TitleNewFilePresentation = \"{3}\";",
                                          CommonLinkUtility.GetFullAbsolutePath(FilesLinkUtility.FileHandlerPath),
                                          FilesJSResource.TitleNewFileText,
                                          FilesJSResource.TitleNewFileSpreadsheet,
                                          FilesJSResource.TitleNewFilePresentation);
            }

            var isRetina = TenantLogoManager.IsRetina(Request);

            inlineScript.AppendFormat("\nASC.Files.Editor.brandingLogoUrl = \"{0}\";" +
                                      "ASC.Files.Editor.brandingLogoEmbeddedUrl = \"{1}\";" +
                                      "ASC.Files.Editor.brandingCustomerLogo = \"{2}\";" +
                                      "ASC.Files.Editor.brandingCustomer = \"{3}\";" +
                                      "ASC.Files.Editor.brandingSite = \"{4}\";",
                                      CommonLinkUtility.GetFullAbsolutePath(TenantLogoHelper.GetLogo(WhiteLabelLogoTypeEnum.DocsEditor, !isRetina)),
                                      CommonLinkUtility.GetFullAbsolutePath(TenantLogoHelper.GetLogo(WhiteLabelLogoTypeEnum.Dark, !isRetina)),
                                      CommonLinkUtility.GetFullAbsolutePath(TenantLogoHelper.GetLogo(WhiteLabelLogoTypeEnum.Dark, !isRetina)),
                                      (SettingsManager.Instance.LoadSettings <TenantWhiteLabelSettings>(TenantProvider.CurrentTenantID).LogoText ?? "").Replace("\\", "\\\\").Replace("\"", "\\\"").Replace("/", "\\/"),
                                      CompanyWhiteLabelSettings.Instance.Site);

            inlineScript.AppendFormat("\nASC.Files.Editor.docKeyForTrack = \"{0}\";" +
                                      "ASC.Files.Editor.shareLinkParam = \"{1}\";" +
                                      "ASC.Files.Editor.serverErrorMessage = \"{2}\";" +
                                      "ASC.Files.Editor.editByUrl = ({3} == true);" +
                                      "ASC.Files.Editor.fixedVersion = ({4} == true);" +
                                      "ASC.Files.Editor.tabId = \"{5}\";" +
                                      "ASC.Files.Editor.thirdPartyApp = ({6} == true);" +
                                      "ASC.Files.Editor.openinigDate = \"{7}\";",
                                      _docKeyForTrack,
                                      string.IsNullOrEmpty(RequestShareLinkKey) ? string.Empty : "&" + FilesLinkUtility.DocShareKey + "=" + RequestShareLinkKey,
                                      (_errorMessage ?? "").Replace("\n", "\\n").Replace("\r", "").Replace("\"", "\\\""),
                                      _editByUrl.ToString().ToLower(),
                                      _fixedVersion.ToString().ToLower(),
                                      _tabId,
                                      _thirdPartyApp.ToString().ToLower(),
                                      DateTime.UtcNow.ToString(CultureInfo.InvariantCulture));

            if (!CoreContext.Configuration.Standalone)
            {
                inlineScript.AppendFormat("\nASC.Files.Editor.showAbout = true;" +
                                          "ASC.Files.Editor.feedbackUrl = \"{0}\";",
                                          AdditionalWhiteLabelSettings.Instance.FeedbackAndSupportEnabled
                                              ? CommonLinkUtility.GetRegionalUrl(
                                              AdditionalWhiteLabelSettings.Instance.FeedbackAndSupportUrl,
                                              CultureInfo.CurrentCulture.TwoLetterISOLanguageName)
                                              : string.Empty);
            }
            else if (_docParams != null)
            {
                inlineScript.AppendFormat("\nASC.Files.Editor.licenseUrl = \"{0}\";" +
                                          "ASC.Files.Editor.customerId = \"{1}\";",
                                          PathProvider.GetLicenseUrl(_docParams.File),
                                          LicenseReader.CustomerId);
            }

            inlineScript.Append(BuildOptions());

            inlineScript.Append(BuildPlugins());

            inlineScript.AppendFormat("\nASC.Files.Editor.docServiceParams = {0};",
                                      DocumentServiceParams.Serialize(_docParams));

            InlineScripts.Scripts.Add(new Tuple <string, bool>(inlineScript.ToString(), false));
        }