Пример #1
0
        /// <summary>
        /// Imports xml to fill the module data
        /// </summary>
        /// <param name="moduleID">The module ID importing</param>
        /// <param name="content">The data representation to import in an XML string</param>
        /// <param name="version">The version of the export</param>
        /// <param name="userId">The user ID of the user importing the data</param>
        public void ImportModule(int moduleID, string content, string version, int userId)
        {
            var module   = ModuleController.Instance.GetModule(moduleID, DotNetNuke.Common.Utilities.Null.NullInteger, false);
            var portalId = module?.PortalID ?? Null.NullInteger;

            XmlDocument xmlDoc = new XmlDocument();

            xmlDoc.LoadXml(content);
            var xmlLinks = xmlDoc.SelectNodes("links/link");

            foreach (XmlNode xmlLink in xmlLinks)
            {
                int  viewOrder = int.TryParse(GetXmlNodeValue(xmlLink, "vieworder"), out viewOrder) ? viewOrder : 0;
                bool newWindow = bool.TryParse(GetXmlNodeValue(xmlLink, "newwindow"), out newWindow) ? newWindow : false;
                Link link      = new Link
                {
                    ModuleId    = moduleID,
                    Title       = GetXmlNodeValue(xmlLink, "title"),
                    Url         = DotNetNuke.Common.Globals.ImportUrl(moduleID, GetXmlNodeValue(xmlLink, "url")),
                    ViewOrder   = viewOrder,
                    Description = GetXmlNodeValue(xmlLink, "description"),
                    GrantRoles  = ConvertToRoleIds(portalId, GetXmlNodeValue(xmlLink, "grantroles")),
                };

                link.NewWindow = newWindow;

                if (bool.TryParse(GetXmlNodeValue(xmlLink, "trackclicks"), out bool trackClicks))
                {
                    link.TrackClicks = trackClicks;
                }
                if (bool.TryParse(GetXmlNodeValue(xmlLink, "logactivity"), out bool logActivity))
                {
                    link.LogActivity = logActivity;
                }

                if (int.TryParse(GetXmlNodeValue(xmlLink, "refreshinterval"), out int refreshInterval))
                {
                    link.RefreshInterval = refreshInterval;
                }

                link.CreatedDate   = DateTime.Now;
                link.CreatedByUser = userId;
                LinkController.DeleteLinkIfItExistsForModule(moduleID, link);
                LinkController.AddLink(link);

                // url tracking
                UrlController objUrls    = new UrlController();
                var           moduleInfo = ModuleController.Instance.GetModule(moduleID, Null.NullInteger, false);
                objUrls.UpdateUrl(
                    moduleInfo.PortalID,
                    link.Url,
                    LinkController.ConvertUrlType(DotNetNuke.Common.Globals.GetURLType(link.Url)),
                    link.LogActivity,
                    link.TrackClicks,
                    moduleID,
                    link.NewWindow);
            }
        }
Пример #2
0
        protected void cmdDelete_Click(object sender, EventArgs e)
        {
            if (cboUrls.SelectedItem != null)
            {
                UrlController objUrls = new UrlController();
                objUrls.DeleteUrl(_objPortal.PortalID, cboUrls.SelectedItem.Value);

                ShowControls();
            }
        }
Пример #3
0
        public void GetTest()
        {
            UrlController ctrl = CreateController(new[] { new Url {
                                                              Id = Guid.Empty
                                                          } });
            var result = ctrl.Get(Guid.Empty);
            var url    = GetUrlFromActionResult(result);

            Assert.AreEqual(url.Id, Guid.Empty);
        }
Пример #4
0
        public void PostTest_new()
        {
            UrlController ctrl   = CreateController(Enumerable.Empty <Url>());
            var           result = ctrl.Post(new UrlPostModel {
                OriginUrl = "https://bitly.com/"
            });
            var urls = GetUrlsFromActionResult(result);

            Assert.IsTrue(urls.Count() == 1);
        }
Пример #5
0
        public void CanRedirect()
        {
            var controller = new UrlController(null);

            CanIAddtoStorage();

            var result = controller.Redirect(1);

            Assert.NotNull(result);
            Assert.Equal("http://cool.xyz", ((RedirectResult)result).Url);
        }
Пример #6
0
        public void About()
        {
            // Arrange
            UrlController controller = new UrlController();

            // Act
            ViewResult result = controller.About() as ViewResult;

            // Assert
            Assert.AreEqual("Your application description page.", result.ViewBag.Message);
        }
Пример #7
0
        public void Contact()
        {
            // Arrange
            UrlController controller = new UrlController();

            // Act
            ViewResult result = controller.Contact() as ViewResult;

            // Assert
            Assert.IsNotNull(result);
        }
Пример #8
0
        public void Index()
        {
            // Arrange
            UrlController controller = new UrlController();

            // Act
            ViewResult result = controller.Index("") as ViewResult;

            // Assert
            Assert.IsNotNull(result);
        }
Пример #9
0
        public void About()
        {
            // Arrange
            UrlController controller = new UrlController();

            // Act
            ViewResult result = controller.About() as ViewResult;

            // Assert
            Assert.AreEqual("Your application description page.", result.ViewBag.Message);
        }
        /// <summary>
        /// cmdUpdate_Click runs when the update button is clicked
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <remarks></remarks>
        private void CmdUpdateClick(object sender, EventArgs e)
        {
            try
            {
                // verify data
                if (Page.IsValid)
                {
                    AnnouncementInfo announcement;
                    if (Model.IsAddMode)
                    {
                        // new item, create new announcement
                        announcement = new AnnouncementInfo
                        {
                            ItemID          = Model.ItemId,
                            ModuleID        = ModuleContext.ModuleId,
                            PortalID        = ModuleContext.PortalId,
                            CreatedByUserID = ModuleContext.PortalSettings.UserId,
                            CreatedOnDate   = DateTime.Now
                        };
                    }
                    else
                    {
                        // updating existing item, load it
                        announcement = Model.AnnouncementInfo;
                    }

                    announcement.Title                = txtTitle.Text;
                    announcement.ImageSource          = urlImage.FilePath;
                    announcement.Description          = teDescription.Text;
                    announcement.URL                  = ctlURL.Url;
                    announcement.PublishDate          = GetDateTimeValue(publishDate, publishTime, DateTime.Now);
                    announcement.ExpireDate           = GetDateTimeValue(expireDate, expireTime);
                    announcement.LastModifiedByUserID = ModuleContext.PortalSettings.UserId;
                    announcement.LastModifiedOnDate   = DateTime.Now;
                    if (txtViewOrder.Text != "")
                    {
                        announcement.ViewOrder = Convert.ToInt32(txtViewOrder.Text);
                    }

                    UpdateAnnouncement(this, new EditItemEventArgs(announcement));

                    // url tracking
                    var objUrls = new UrlController();
                    objUrls.UpdateUrl(ModuleContext.PortalId, ctlURL.Url, ctlURL.UrlType, ctlURL.Log, ctlURL.Track, ModuleContext.ModuleId, ctlURL.NewWindow);

                    // redirect back to page
                    Response.Redirect(ReturnURL, true);
                }
            }
            catch (Exception exc)
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }
 public MediaItemsController(GalleryController galleryController, AlbumController albumController, GalleryObjectController galleryObjectController, FileStreamController streamController, HtmlController htmlController, UrlController urlController, UserController userController, ExceptionController exController, IAuthorizationService authorizationService)
 {
     _galleryController       = galleryController;
     _albumController         = albumController;
     _galleryObjectController = galleryObjectController;
     _streamController        = streamController;
     _htmlController          = htmlController;
     _urlController           = urlController;
     _userController          = userController;
     _exController            = exController;
     _authorizationService    = authorizationService;
 }
Пример #12
0
 protected void cmdDelete_Click(object sender, EventArgs e)
 {
     if (cboUrls.SelectedItem != null)
     {
         var objUrls = new UrlController();
         objUrls.DeleteUrl(_objPortal.PortalID, cboUrls.SelectedItem.Value);
         LoadUrls();                //we must reload the url list
     }
     _doRenderTypeControls = false; //Must not render on this postback
     _doRenderTypes        = false;
     _doChangeURL          = false;
 }
Пример #13
0
        /// <summary>
        /// ImportModule implements the IPortable ImportModule Interface
        /// </summary>
        /// <param name="moduleId">The Id of the module to be imported</param>
        /// <history>
        ///		[cnurse]	    17 Nov 2004	documented
        ///		[aglenwright]	18 Feb 2006	Added new fields: Createddate, description,
        ///                             modifiedbyuser, modifieddate, OwnedbyUser, SortorderIndex
        ///                             Added DocumentsSettings
        ///   [togrean]     10 Jul 2007 Fixed issues with importing documet settings since new fileds
        ///                             were added: AllowSorting, default folder, list name
        ///   [togrean]     13 Jul 2007 Added support for importing documents Url tracking options
        /// </history>
        public void ImportModule(int moduleId, string content, string version, int userId)
        {
            var mCtrl  = new ModuleController();
            var module = mCtrl.GetModule(moduleId, Null.NullInteger);

            var xmlDocuments  = Globals.GetContent(content, "documents");
            var documentNodes = xmlDocuments.SelectNodes("document");
            var now           = DateTime.Now;

            foreach (XmlNode documentNode in documentNodes)
            {
                var strUrl   = documentNode ["url"].InnerText;
                var document = new DocumentInfo {
                    ModuleId         = moduleId,
                    Title            = documentNode ["title"].InnerText,
                    Category         = documentNode ["category"].InnerText,
                    Description      = XmlUtils.GetNodeValue(documentNode, "description"),
                    OwnedByUserId    = XmlUtils.GetNodeValueInt(documentNode, "ownedbyuserid"),
                    SortOrderIndex   = XmlUtils.GetNodeValueInt(documentNode, "sortorderindex"),
                    LinkAttributes   = XmlUtils.GetNodeValue(documentNode, "linkattributes"),
                    ForceDownload    = XmlUtils.GetNodeValueBoolean(documentNode, "forcedownload"),
                    StartDate        = GetNodeValueDateNullable(documentNode, "startDate"),
                    EndDate          = GetNodeValueDateNullable(documentNode, "endDate"),
                    CreatedByUserId  = userId,
                    ModifiedByUserId = userId,
                    CreatedDate      = now,
                    ModifiedDate     = now,
                    Url = strUrl.StartsWith("fileid=", StringComparison.InvariantCultureIgnoreCase) ?
                          strUrl : Globals.ImportUrl(moduleId, strUrl)
                };

                DocumentsDataProvider.Instance.Add(document);

                // Update Tracking options
                var urlType = document.Url.StartsWith("fileid=", StringComparison.InvariantCultureIgnoreCase) ? "F" : "U";

                var urlCtrl = new UrlController();
                // If nodes not found, all values will be false
                urlCtrl.UpdateUrl(
                    module.PortalID,
                    document.Url,
                    urlType,
                    XmlUtils.GetNodeValueBoolean(documentNode, "logactivity"),
                    XmlUtils.GetNodeValueBoolean(documentNode, "trackclicks", true),
                    moduleId,
                    XmlUtils.GetNodeValueBoolean(documentNode, "newwindow"));
            }

            ImportSettings(module, content);

            ModuleSynchronizer.Synchronize(module.ModuleID, module.TabModuleID);
        }
Пример #14
0
        public void PostTest_alreadyExist()
        {
            string        shortUrl = Settings.GetShortUrl("randomString");
            UrlController ctrl     = CreateController(new [] { new Url {
                                                                   OriginUrl = "https://bitly.com", ShortUrl = shortUrl
                                                               } });
            var result = ctrl.Post(new UrlPostModel {
                OriginUrl = "https://bitly.com/"
            });
            var urls = GetUrlsFromActionResult(result);

            Assert.AreEqual(urls.First().ShortUrl, shortUrl);
        }
Пример #15
0
        /// <summary>
        /// Imports xml to fill the module data
        /// </summary>
        /// <param name="moduleID">The module ID importing</param>
        /// <param name="content">The data representation to import in an XML string</param>
        /// <param name="version">The version of the export</param>
        /// <param name="userId">The user ID of the user importing the data</param>
        public void ImportModule(int moduleID, string content, string version, int userId)
        {
            XmlDocument xmlDoc = new XmlDocument();

            xmlDoc.LoadXml(content);
            var xmlLinks = xmlDoc.SelectNodes("links");

            foreach (XmlNode xmlLink in xmlLinks)
            {
                int  viewOrder = int.TryParse(xmlLink.SelectSingleNode("vieworder").Value, out viewOrder) ? viewOrder : 0;
                bool newWindow = bool.TryParse(xmlLink.SelectSingleNode("newwindow").Value, out newWindow) ? newWindow : false;
                Link link      = new Link
                {
                    ModuleId    = moduleID,
                    Title       = xmlLink.SelectSingleNode("title").Value,
                    Url         = DotNetNuke.Common.Globals.ImportUrl(moduleID, xmlLink.SelectSingleNode("url").Value),
                    ViewOrder   = viewOrder,
                    Description = xmlLink.SelectSingleNode("description").Value
                };

                link.NewWindow = newWindow;

                try
                {
                    link.TrackClicks = bool.Parse(xmlLink.SelectSingleNode("trackclicks").Value);
                }
                catch
                {
                    link.TrackClicks = false;
                }

                link.CreatedDate   = DateTime.Now;
                link.CreatedByUser = userId;
                LinkController.DeleteLinkIfItExistsForModule(moduleID, link);
                LinkController.AddLink(link);

                // url tracking
                UrlController objUrls    = new UrlController();
                var           moduleInfo = ModuleController.Instance.GetModule(moduleID, Null.NullInteger, false);
                objUrls.UpdateUrl(
                    moduleInfo.PortalID,
                    link.Url,
                    LinkController.ConvertUrlType(DotNetNuke.Common.Globals.GetURLType(link.Url)),
                    false,
                    link.TrackClicks,
                    moduleID,
                    link.NewWindow);
            }
        }
        public void GetShortUrlReturnsNotFoundWhenIndexOutOfRange()
        {
            // Mock setup
            var validator = new Mock <IDomainValidatorService>();
            var shortUrl  = new Mock <IShortUrlService>();

            shortUrl.Setup(s => s.GetUrl(0))
            .Throws <ArgumentOutOfRangeException>();

            // Run tests
            var controller = new UrlController(validator.Object, shortUrl.Object);
            var result     = controller.GetShortUrl(0);

            // Assertions
            Assert.IsType <NotFoundResult>(result);
        }
Пример #17
0
        private void InitializeControllerWithUnauthorizedContext()
        {
            var mockHttpContextAccessor = new Mock <IHttpContextAccessor>();
            var context  = new DefaultHttpContext();
            var claims   = new[] { new Claim(ClaimTypes.Name, "fake") }; //fake claim, treba biti type NameIdentifier
            var identity = new ClaimsIdentity(claims, "Basic");

            context.User = new GenericPrincipal(identity, new[] { "fake", "roles" });

            ControllerContext controllerContext = new ControllerContext();

            controllerContext.HttpContext = context;

            mockHttpContextAccessor.Setup(_ => _.HttpContext).Returns(context);
            _controller = new UrlController(_mockService.Object, mockHttpContextAccessor.Object);
            _controller.ControllerContext = controllerContext;
        }
Пример #18
0
        public async Task Test_InflateAction_NullInput()
        {
            // Setup
            var urlShortnerServiceMock = new Mock <IUrlShortnerService>();
            var mapperMock             = new Mock <IMapper>();


            //urlShortnerServiceMock.Setup(s => s.InflateShortenedUrl(It.IsAny<string>()))
            //    .Returns(Task.FromResult<string>(null));

            var urlController = new UrlController(urlShortnerServiceMock.Object, mapperMock.Object);

            var result = await urlController.Inflate("sds");

            // Assert
            Assert.IsTrue(result is NotFoundResult);
        }
Пример #19
0
        public string GetProperty(string strPropertyName, string strFormat, CultureInfo formatProvider,
                                  UserInfo accessingUser, Scope accessLevel, ref bool propertyNotFound)
        {
            string outputFormat = strFormat == string.Empty ? "g" : strFormat;

            strPropertyName = strPropertyName.ToLowerInvariant();

            if (File != null)
            {
                switch (strPropertyName)
                {
                case "name":
                    return(PropertyAccess.FormatString(File.FileName, strFormat));

                case "folder":
                    return
                        (PropertyAccess.FormatString(
                             FolderManager.Instance.GetFolder(File.FolderId).FolderName,
                             strFormat));

                case "path":
                    return
                        (PropertyAccess.FormatString(
                             FolderManager.Instance.GetFolder(File.FolderId).FolderPath,
                             strFormat));

                case "size":
                    return(File.Size.ToString(outputFormat, formatProvider));

                case "sizemb":
                    return((File.Size / 1024 ^ 2).ToString(outputFormat, formatProvider));

                case "extension":
                    return(PropertyAccess.FormatString(File.Extension, strFormat));
                }
            }
            if (strPropertyName == "clicks")
            {
                var tracking = new UrlController().GetUrlTracking(_portalId, _fileIdentifier, _moduleId);
                return(tracking != null?tracking.Clicks.ToString(outputFormat, formatProvider) : "");
            }
            propertyNotFound = true;
            return(string.Empty);
        }
Пример #20
0
        public async Task Test_ShortenAction_NullInputUrl()
        {
            // Setup
            var urlShortnerServiceMock = new Mock <IUrlShortnerService>();
            var mapperMock             = new Mock <IMapper>();

            // Action
            var urlController = new UrlController(urlShortnerServiceMock.Object, mapperMock.Object);

            urlController.ModelState.AddModelError("Url", "Url is missing");

            var result = await urlController.Shorten(new ShortenUrlRequest
            {
                Url = null
            });

            // Assert
            Assert.IsTrue(result is BadRequestObjectResult);
        }
        public async Task GetShortUrlReturnsRedirectResultWhenShortUrlIsValid()
        {
            // Mock setup
            var validator = new Mock <IDomainValidatorService>();
            var shortUrl  = new Mock <IShortUrlService>();

            shortUrl.Setup(s => s.GetUrl(0))
            .Returns(Url);

            // Run tests
            var controller = new UrlController(validator.Object, shortUrl.Object);
            await controller.CreateShortUrl(Url);

            var result = controller.GetShortUrl(0);

            // Assertions
            var response = Assert.IsType <RedirectResult>(result);

            Assert.Equal(Url, response.Url);
        }
Пример #22
0
        public async Task Test_InflateAction_ValidHash()
        {
            // Setup
            const string originalUrl = "http://example.com";

            var urlShortnerServiceMock = new Mock <IUrlShortnerService>();
            var mapperMock             = new Mock <IMapper>();


            urlShortnerServiceMock.Setup(s => s.InflateShortenedUrl(It.IsAny <string>()))
            .Returns(Task.FromResult <string>(originalUrl));

            // Action
            var urlController = new UrlController(urlShortnerServiceMock.Object, mapperMock.Object);

            var result = await urlController.Inflate("sds");

            // Assert
            Assert.IsTrue(result is OkObjectResult);
            Assert.AreEqual(((OkObjectResult)result).Value, originalUrl);
        }
        public async Task CreateShortUrlReturnsBadRequestResultIfUrlInvalid()
        {
            // Mock setup
            var validator = new Mock <IDomainValidatorService>();

            validator.Setup(v => v.IsValidDomain(InvalidUrl))
            .ReturnsAsync(false);
            var shortUrl = new Mock <IShortUrlService>();

            // Run tests
            var controller = new UrlController(validator.Object, shortUrl.Object);
            var result     = await controller.CreateShortUrl(InvalidUrl);

            // Assertions
            var response = Assert.IsType <BadRequestObjectResult>(result);

            Assert.NotNull(response.Value);
            Assert.IsType <Dictionary <string, string> >(response.Value);
            Assert.Equal(1, (response.Value as IDictionary <string, string>)?.Keys.Count);
            Assert.True((response.Value as IDictionary <string, string>)?.ContainsKey("error"));
            Assert.Equal("invalid url", (response.Value as IDictionary <string, string>)?["error"]);
        }
Пример #24
0
        protected void buttonImport_Click(object sender, EventArgs e)
        {
            try {
                var fromModule = ModuleController.Instance.GetModule(int.Parse(comboModule.SelectedValue), TabId, false);
                foreach (ListItem item in listDocuments.Items)
                {
                    if (item.Selected)
                    {
                        var document = GetDocument(int.Parse(item.Value), fromModule);
                        if (document != null)
                        {
                            // get original document tracking data
                            var ctrlUrl     = new UrlController();
                            var urlTracking = ctrlUrl.GetUrlTracking(PortalId, document.Url, document.ModuleId);

                            // import document
                            document.ItemId   = Null.NullInteger;
                            document.ModuleId = ModuleId;
                            DocumentsDataProvider.Instance.Add(document);

                            // add new url tracking data
                            if (urlTracking != null)
                            {
                                // WTF: using url.Clicks, url.LastClick, url.CreatedDate overload not working?
                                ctrlUrl.UpdateUrl(PortalId, document.Url, urlTracking.UrlType,
                                                  urlTracking.LogActivity, urlTracking.TrackClicks,
                                                  ModuleId, urlTracking.NewWindow);
                            }
                        }
                    }
                }

                ModuleSynchronizer.Synchronize(ModuleId, TabModuleId);
                Response.Redirect(Globals.NavigateURL(), true);
            }
            catch (Exception ex) {
                Exceptions.ProcessModuleLoadException(this, ex);
            }
        }
Пример #25
0
        /// -----------------------------------------------------------------------------
        /// <summary>
        /// This handler handles requests for LinkClick.aspx, but only those specifc
        /// to file serving
        /// </summary>
        /// <param name="context">System.Web.HttpContext)</param>
        /// <remarks>
        /// </remarks>
        /// <history>
        ///     [cpaterra]	4/19/2006	Created
        /// </history>
        /// -----------------------------------------------------------------------------
        public void ProcessRequest(HttpContext context)
        {
            PortalSettings _portalSettings = PortalController.GetCurrentPortalSettings();
            int            TabId           = -1;
            int            ModuleId        = -1;

            try
            {
                //get TabId
                if (context.Request.QueryString["tabid"] != null)
                {
                    Int32.TryParse(context.Request.QueryString["tabid"], out TabId);
                }

                //get ModuleId
                if (context.Request.QueryString["mid"] != null)
                {
                    Int32.TryParse(context.Request.QueryString["mid"], out ModuleId);
                }
            }
            catch (Exception)
            {
                //The TabId or ModuleId are incorrectly formatted (potential DOS)
                Exceptions.Exceptions.ProcessHttpException(context.Request);
            }

            //get Language
            string Language = _portalSettings.DefaultLanguage;

            if (context.Request.QueryString["language"] != null)
            {
                Language = context.Request.QueryString["language"];
            }
            else
            {
                if (context.Request.Cookies["language"] != null)
                {
                    Language = context.Request.Cookies["language"].Value;
                }
            }
            if (LocaleController.Instance.IsEnabled(ref Language, _portalSettings.PortalId))
            {
                Localization.Localization.SetThreadCultures(new CultureInfo(Language), _portalSettings);
                Localization.Localization.SetLanguage(Language);
            }

            //get the URL
            string URL              = "";
            bool   blnClientCache   = true;
            bool   blnForceDownload = false;

            if (context.Request.QueryString["fileticket"] != null)
            {
                URL = "FileID=" + FileLinkClickController.Instance.GetFileIdFromLinkClick(context.Request.QueryString);
            }
            if (context.Request.QueryString["userticket"] != null)
            {
                URL = "UserId=" + UrlUtils.DecryptParameter(context.Request.QueryString["userticket"]);
            }
            if (context.Request.QueryString["link"] != null)
            {
                URL = context.Request.QueryString["link"];
                if (URL.ToLowerInvariant().StartsWith("fileid="))
                {
                    URL = ""; //restrict direct access by FileID
                }
            }
            if (!String.IsNullOrEmpty(URL))
            {
                URL = URL.Replace(@"\", @"/");

                //update clicks, this must be done first, because the url tracker works with unmodified urls, like tabid, fileid etc
                var objUrls = new UrlController();
                objUrls.UpdateUrlTracking(_portalSettings.PortalId, URL, ModuleId, -1);
                TabType UrlType = Globals.GetURLType(URL);
                if (UrlType == TabType.Tab)
                {
                    //verify whether the tab is exist, otherwise throw out 404.
                    if (new TabController().GetTab(int.Parse(URL), _portalSettings.PortalId, false) == null)
                    {
                        Exceptions.Exceptions.ProcessHttpException();
                    }
                }
                if (UrlType != TabType.File)
                {
                    URL = Globals.LinkClick(URL, TabId, ModuleId, false);
                }

                if (UrlType == TabType.File && URL.ToLowerInvariant().StartsWith("fileid=") == false)
                {
                    //to handle legacy scenarios before the introduction of the FileServerHandler
                    var fileName = Path.GetFileName(URL);

                    var folderPath = URL.Substring(0, URL.LastIndexOf(fileName));
                    var folder     = FolderManager.Instance.GetFolder(_portalSettings.PortalId, folderPath);

                    var file = FileManager.Instance.GetFile(folder, fileName);

                    URL = "FileID=" + file.FileId;
                }

                //get optional parameters
                if (context.Request.QueryString["clientcache"] != null)
                {
                    blnClientCache = bool.Parse(context.Request.QueryString["clientcache"]);
                }
                if ((context.Request.QueryString["forcedownload"] != null) || (context.Request.QueryString["contenttype"] != null))
                {
                    blnForceDownload = bool.Parse(context.Request.QueryString["forcedownload"]);
                }
                var contentDisposition = blnForceDownload ? ContentDisposition.Attachment : ContentDisposition.Inline;

                //clear the current response
                context.Response.Clear();
                var fileManager = FileManager.Instance;
                try
                {
                    switch (UrlType)
                    {
                    case TabType.File:
                        var download = false;
                        var file     = fileManager.GetFile(int.Parse(UrlUtils.GetParameterValue(URL)));
                        if (file != null)
                        {
                            if (!file.IsEnabled)
                            {
                                if (context.Request.IsAuthenticated)
                                {
                                    context.Response.Redirect(Globals.AccessDeniedURL(Localization.Localization.GetString("FileAccess.Error")), true);
                                }
                                else
                                {
                                    context.Response.Redirect(Globals.AccessDeniedURL(), true);
                                }
                            }

                            try
                            {
                                var folderMapping = FolderMappingController.Instance.GetFolderMapping(file.PortalId, file.FolderMappingID);
                                var directUrl     = fileManager.GetUrl(file);
                                if (directUrl.Contains("LinkClick") || (blnForceDownload && folderMapping.FolderProviderType == "StandardFolderProvider"))
                                {
                                    fileManager.WriteFileToResponse(file, contentDisposition);
                                    download = true;
                                }
                                else
                                {
                                    context.Response.Redirect(directUrl, /*endResponse*/ true);
                                }
                            }
                            catch (PermissionsNotMetException)
                            {
                                if (context.Request.IsAuthenticated)
                                {
                                    context.Response.Redirect(Globals.AccessDeniedURL(Localization.Localization.GetString("FileAccess.Error")), true);
                                }
                                else
                                {
                                    context.Response.Redirect(Globals.AccessDeniedURL(), true);
                                }
                            }
                            catch (Exception ex)
                            {
                                Logger.Error(ex);
                            }
                        }

                        if (!download)
                        {
                            Exceptions.Exceptions.ProcessHttpException(URL);
                        }
                        break;

                    case TabType.Url:
                        //prevent phishing by verifying that URL exists in URLs table for Portal
                        if (objUrls.GetUrl(_portalSettings.PortalId, URL) != null)
                        {
                            context.Response.Redirect(URL, true);
                        }
                        break;

                    default:
                        //redirect to URL
                        context.Response.Redirect(URL, true);
                        break;
                    }
                }
                catch (ThreadAbortException exc)
                {
                    Logger.Error(exc);
                }
                catch (Exception)
                {
                    Exceptions.Exceptions.ProcessHttpException(URL);
                }
            }
            else
            {
                Exceptions.Exceptions.ProcessHttpException(URL);
            }
        }
        public override void HandleRequest()
        {
            string       output       = null;
            DialogParams dialogParams = Content.FromJson <DialogParams>();            // This uses the new JSON Extensions in DotNetNuke.Common.Utilities.JsonExtensionsWeb

            string link = dialogParams.LinkUrl;

            dialogParams.LinkClickUrl = link;

            if (dialogParams != null)
            {
                if (!(dialogParams.LinkAction == "GetLinkInfo"))
                {
                    if (dialogParams.Track)
                    {
                        string tempVar = dialogParams.LinkUrl;
                        dialogParams.LinkClickUrl = GetLinkClickURL(ref dialogParams, ref tempVar);
                        dialogParams.LinkUrl      = tempVar;
                        UrlTrackingInfo linkTrackingInfo = _urlController.GetUrlTracking(dialogParams.PortalId, dialogParams.LinkUrl, dialogParams.ModuleId);

                        if (linkTrackingInfo != null)
                        {
                            dialogParams.Track       = linkTrackingInfo.TrackClicks;
                            dialogParams.TrackUser   = linkTrackingInfo.LogActivity;
                            dialogParams.DateCreated = linkTrackingInfo.CreatedDate.ToString();
                            dialogParams.LastClick   = linkTrackingInfo.LastClick.ToString();
                            dialogParams.Clicks      = linkTrackingInfo.Clicks.ToString();
                        }
                        else
                        {
                            dialogParams.Track     = false;
                            dialogParams.TrackUser = false;
                        }
                        dialogParams.LinkUrl = link;
                    }
                }

                switch (dialogParams.LinkAction)
                {
                case "GetLoggingInfo":                         //also meant for the tracking tab but this is to retrieve the user information
                    DateTime logStartDate = DateTime.MinValue;
                    DateTime logEndDate   = DateTime.MinValue;
                    string   logText      = "<table><tr><th>Date</th><th>User</th></tr><tr><td colspan='2'>The selected date-range did<br /> not return any results.</td></tr>";

                    if (DateTime.TryParse(dialogParams.LogStartDate, out logStartDate))
                    {
                        if (!(DateTime.TryParse(dialogParams.LogEndDate, out logEndDate)))
                        {
                            logEndDate = logStartDate.AddDays(1);
                        }

                        UrlController _urlController = new UrlController();
                        ArrayList     urlLog         = _urlController.GetUrlLog(dialogParams.PortalId, GetLinkUrl(ref dialogParams, dialogParams.LinkUrl), dialogParams.ModuleId, logStartDate, logEndDate);

                        if (urlLog != null)
                        {
                            logText = GetUrlLoggingInfo(urlLog);
                        }
                    }

                    dialogParams.TrackingLog = logText;

                    break;

                case "GetLinkInfo":
                    if (dialogParams.Track)
                    {
                        link = link.Replace(@"\", @"/");

                        //this section is for when the user clicks ok in the dialog box, we actually create a record for the linkclick urls.
                        if (!(dialogParams.LinkUrl.ToLower().Contains("linkclick.aspx")))
                        {
                            dialogParams.LinkClickUrl = GetLinkClickURL(ref dialogParams, ref link);
                        }

                        _urlController.UpdateUrl(dialogParams.PortalId, link, GetURLType(Globals.GetURLType(link)), dialogParams.TrackUser, true, dialogParams.ModuleId, false);
                    }
                    else
                    {
                        //this section is meant for retrieving/displaying the original links and determining if the links are being tracked(making sure the track checkbox properly checked)
                        UrlTrackingInfo linkTrackingInfo = null;

                        if (dialogParams.LinkUrl.Contains("fileticket"))
                        {
                            var queryString     = dialogParams.LinkUrl.Split('=');
                            var encryptedFileId = queryString[1].Split('&')[0];

                            string   fileID    = UrlUtils.DecryptParameter(encryptedFileId, dialogParams.PortalGuid);
                            FileInfo savedFile = _fileController.GetFileById(Int32.Parse(fileID), dialogParams.PortalId);

                            linkTrackingInfo = _urlController.GetUrlTracking(dialogParams.PortalId, string.Format("fileID={0}", fileID), dialogParams.ModuleId);
                        }
                        else if (dialogParams.LinkUrl.ToLowerInvariant().Contains("linkclick.aspx"))
                        {
                            try
                            {
                                if (dialogParams.LinkUrl.Contains("?"))
                                {
                                    link = dialogParams.LinkUrl.Split('?')[1].Split('&')[0];
                                    if (link.Contains("="))
                                    {
                                        link = link.Split('=')[1];
                                    }
                                }

                                int tabId;
                                if (int.TryParse(link, out tabId))                                     //if it's a tabid get the tab path
                                {
                                    dialogParams.LinkClickUrl = TabController.Instance.GetTab(tabId, dialogParams.PortalId, true).FullUrl;
                                    linkTrackingInfo          = _urlController.GetUrlTracking(dialogParams.PortalId, tabId.ToString(), dialogParams.ModuleId);
                                }
                                else
                                {
                                    dialogParams.LinkClickUrl = HttpContext.Current.Server.UrlDecode(link);                                             //get the actual link
                                    linkTrackingInfo          = _urlController.GetUrlTracking(dialogParams.PortalId, dialogParams.LinkClickUrl, dialogParams.ModuleId);
                                }
                            }
                            catch (Exception ex)
                            {
                                Logger.Error(ex);
                                dialogParams.LinkClickUrl = dialogParams.LinkUrl;
                            }
                        }

                        if (linkTrackingInfo == null)
                        {
                            dialogParams.Track     = false;
                            dialogParams.TrackUser = false;
                        }
                        else
                        {
                            dialogParams.Track     = linkTrackingInfo.TrackClicks;
                            dialogParams.TrackUser = linkTrackingInfo.LogActivity;
                        }
                    }
                    break;
                }
                output = dialogParams.ToJson();
            }

            Response.Write(output);
        }
Пример #27
0
        private void DoRenderTypeControls()
        {
            string _Url     = Convert.ToString(ViewState["Url"]);
            string _Urltype = Convert.ToString(ViewState["UrlType"]);
            var    objUrls  = new UrlController();

            if (!String.IsNullOrEmpty(_Urltype))
            {
                //load listitems
                switch (optType.SelectedItem.Value)
                {
                case "N":     //None
                    URLRow.Visible    = false;
                    TabRow.Visible    = false;
                    FileRow.Visible   = false;
                    UserRow.Visible   = false;
                    ImagesRow.Visible = false;
                    break;

                case "I":     //System Image
                    URLRow.Visible    = false;
                    TabRow.Visible    = false;
                    FileRow.Visible   = false;
                    UserRow.Visible   = false;
                    ImagesRow.Visible = true;

                    cboImages.Items.Clear();

                    string strImagesFolder = Path.Combine(Globals.ApplicationMapPath, PortalSettings.DefaultIconLocation.Replace('/', '\\'));
                    foreach (string strImage in Directory.GetFiles(strImagesFolder))
                    {
                        string img = strImage.Replace(strImagesFolder, "").Trim('/').Trim('\\');
                        cboImages.Items.Add(new ListItem(img, string.Format("~/{0}/{1}", PortalSettings.DefaultIconLocation, img).ToLower()));
                    }

                    ListItem selecteItem = cboImages.Items.FindByValue(_Url.ToLower());
                    if (selecteItem != null)
                    {
                        selecteItem.Selected = true;
                    }
                    break;

                case "U":     //Url
                    URLRow.Visible    = true;
                    TabRow.Visible    = false;
                    FileRow.Visible   = false;
                    UserRow.Visible   = false;
                    ImagesRow.Visible = false;
                    if (String.IsNullOrEmpty(txtUrl.Text))
                    {
                        txtUrl.Text = _Url;
                    }
                    if (String.IsNullOrEmpty(txtUrl.Text))
                    {
                        txtUrl.Text = "http://";
                    }
                    txtUrl.Visible = true;

                    cmdSelect.Visible = true;

                    cboUrls.Visible   = false;
                    cmdAdd.Visible    = false;
                    cmdDelete.Visible = false;
                    break;

                case "T":     //tab
                    URLRow.Visible    = false;
                    TabRow.Visible    = true;
                    FileRow.Visible   = false;
                    UserRow.Visible   = false;
                    ImagesRow.Visible = false;

                    cboTabs.IncludeAllTabTypes = false;
                    cboTabs.IncludeActiveTab   = IncludeActiveTab;
                    cboTabs.UndefinedItem      = new ListItem(DynamicSharedConstants.Unspecified, string.Empty);

                    if (!string.IsNullOrEmpty(_Url))
                    {
                        PortalSettings _settings = PortalController.Instance.GetCurrentPortalSettings();
                        var            tabId     = Int32.Parse(_Url);
                        var            page      = TabController.Instance.GetTab(tabId, _settings.PortalId);
                        cboTabs.SelectedPage = page;
                    }
                    break;

                case "F":     //file
                    URLRow.Visible    = false;
                    TabRow.Visible    = false;
                    FileRow.Visible   = true;
                    UserRow.Visible   = false;
                    ImagesRow.Visible = false;

                    //select folder
                    //We Must check if selected folder has changed because of a property change (Secure, Database)
                    string FileName       = string.Empty;
                    string FolderPath     = string.Empty;
                    string LastFileName   = string.Empty;
                    string LastFolderPath = string.Empty;
                    //Let's try to remember last selection
                    if (ViewState["LastFolderPath"] != null)
                    {
                        LastFolderPath = Convert.ToString(ViewState["LastFolderPath"]);
                    }
                    if (ViewState["LastFileName"] != null)
                    {
                        LastFileName = Convert.ToString(ViewState["LastFileName"]);
                    }
                    if (_Url != string.Empty)
                    {
                        //Let's use the new URL
                        FileName   = _Url.Substring(_Url.LastIndexOf("/") + 1);
                        FolderPath = _Url.Replace(FileName, "");
                    }
                    else
                    {
                        //Use last settings
                        FileName   = LastFileName;
                        FolderPath = LastFolderPath;
                    }

                    ctlFile.FilePath = FolderPath + FileName;

                    txtUrl.Visible = false;
                    break;

                case "M":     //membership users
                    URLRow.Visible    = false;
                    TabRow.Visible    = false;
                    FileRow.Visible   = false;
                    UserRow.Visible   = true;
                    ImagesRow.Visible = false;
                    if (String.IsNullOrEmpty(txtUser.Text))
                    {
                        txtUser.Text = _Url;
                    }
                    break;
                }
            }
            else
            {
                URLRow.Visible    = false;
                ImagesRow.Visible = false;
                TabRow.Visible    = false;
                FileRow.Visible   = false;
                UserRow.Visible   = false;
            }
        }
Пример #28
0
        private void DoChangeURL()
        {
            string _Url     = Convert.ToString(ViewState["Url"]);
            string _Urltype = Convert.ToString(ViewState["UrlType"]);

            if (!String.IsNullOrEmpty(_Url))
            {
                var    objUrls     = new UrlController();
                string TrackingUrl = _Url;

                _Urltype = Globals.GetURLType(_Url).ToString("g").Substring(0, 1);
                if (_Urltype == "U" && (_Url.StartsWith("~/" + PortalSettings.DefaultIconLocation, StringComparison.InvariantCultureIgnoreCase)))
                {
                    _Urltype = "I";
                }
                ViewState["UrlType"] = _Urltype;
                if (_Urltype == "F")
                {
                    if (_Url.ToLower().StartsWith("fileid="))
                    {
                        TrackingUrl = _Url;
                        var objFile = FileManager.Instance.GetFile(int.Parse(_Url.Substring(7)));
                        if (objFile != null)
                        {
                            _Url = objFile.Folder + objFile.FileName;
                        }
                    }
                    else
                    {
                        //to handle legacy scenarios before the introduction of the FileServerHandler
                        var fileName   = Path.GetFileName(_Url);
                        var folderPath = _Url.Substring(0, _Url.LastIndexOf(fileName));
                        var folder     = FolderManager.Instance.GetFolder(_objPortal.PortalID, folderPath);
                        var fileId     = -1;
                        if (folder != null)
                        {
                            var file = FileManager.Instance.GetFile(folder, fileName);
                            if (file != null)
                            {
                                fileId = file.FileId;
                            }
                        }
                        TrackingUrl = "FileID=" + fileId.ToString();
                    }
                }
                if (_Urltype == "M")
                {
                    if (_Url.ToLower().StartsWith("userid="))
                    {
                        UserInfo objUser = UserController.GetUserById(_objPortal.PortalID, int.Parse(_Url.Substring(7)));
                        if (objUser != null)
                        {
                            _Url = objUser.Username;
                        }
                    }
                }
                UrlTrackingInfo objUrlTracking = objUrls.GetUrlTracking(_objPortal.PortalID, TrackingUrl, ModuleID);
                if (objUrlTracking != null)
                {
                    chkNewWindow.Checked = objUrlTracking.NewWindow;
                    chkTrack.Checked     = objUrlTracking.TrackClicks;
                    chkLog.Checked       = objUrlTracking.LogActivity;
                }
                else //the url does not exist in the tracking table
                {
                    chkTrack.Checked = false;
                    chkLog.Checked   = false;
                }
                ViewState["Url"] = _Url;
            }
            else
            {
                if (!String.IsNullOrEmpty(_Urltype))
                {
                    optType.ClearSelection();
                    if (optType.Items.FindByValue(_Urltype) != null)
                    {
                        optType.Items.FindByValue(_Urltype).Selected = true;
                    }
                    else
                    {
                        optType.Items[0].Selected = true;
                    }
                }
                else
                {
                    if (optType.Items.Count > 0)
                    {
                        optType.ClearSelection();
                        optType.Items[0].Selected = true;
                    }
                }
                chkNewWindow.Checked = false; //Need check
                chkTrack.Checked     = false; //Need check
                chkLog.Checked       = false; //Need check
            }

            //Url type changed, then we must draw the controlos for that type
            _doRenderTypeControls = true;
        }
Пример #29
0
        /// <summary>
        /// ExportModule implements the IPortable ExportModule Interface
        /// </summary>
        /// <param name="moduleId">The Id of the module to be exported</param>
        /// <history>
        ///		[cnurse]	    17 Nov 2004	documented
        ///		[aglenwright]	18 Feb 2006	Added new fields: Createddate, description,
        ///                             modifiedbyuser, modifieddate, OwnedbyUser, SortorderIndex
        ///                             Added DocumentsSettings
        ///   [togrean]     10 Jul 2007 Fixed issues with importing documet settings since new fileds
        ///                             were added: AllowSorting, default folder, list name
        ///   [togrean]     13 Jul 2007 Added support for exporting documents Url tracking options
        /// </history>
        public string ExportModule(int moduleId)
        {
            var mCtrl  = new ModuleController();
            var module = mCtrl.GetModule(moduleId, Null.NullInteger);

            var strXml = new StringBuilder("<documents>");

            try {
                var documents = DocumentsDataProvider.Instance.GetDocuments(moduleId, module.PortalID);

                var now = DateTime.Now;
                if (documents.Any())
                {
                    foreach (var document in documents)
                    {
                        strXml.Append("<document>");
                        strXml.AppendFormat("<title>{0}</title>", XmlUtils.XMLEncode(document.Title));
                        strXml.AppendFormat("<url>{0}</url>", XmlUtils.XMLEncode(document.Url));
                        strXml.AppendFormat("<category>{0}</category>", XmlUtils.XMLEncode(document.Category));
                        strXml.AppendFormat(
                            "<description>{0}</description>",
                            XmlUtils.XMLEncode(document.Description));
                        strXml.AppendFormat(
                            "<forcedownload>{0}</forcedownload>",
                            XmlUtils.XMLEncode(document.ForceDownload.ToString()));
                        strXml.AppendFormat("<startDate>{0}</startDate>", XmlUtils.XMLEncode(document.StartDate.ToString()));
                        strXml.AppendFormat("<endDate>{0}</endDate>", XmlUtils.XMLEncode(document.EndDate.ToString()));
                        strXml.AppendFormat(
                            "<ownedbyuserid>{0}</ownedbyuserid>",
                            XmlUtils.XMLEncode(document.OwnedByUserId.ToString()));
                        strXml.AppendFormat(
                            "<sortorderindex>{0}</sortorderindex>",
                            XmlUtils.XMLEncode(document.SortOrderIndex.ToString()));
                        strXml.AppendFormat(
                            "<linkattributes>{0}</linkattributes>",
                            XmlUtils.XMLEncode(document.LinkAttributes));

                        // Export Url Tracking options too
                        var urlCtrl         = new UrlController();
                        var urlTrackingInfo = urlCtrl.GetUrlTracking(module.PortalID, document.Url, moduleId);

                        if ((urlTrackingInfo != null))
                        {
                            strXml.AppendFormat(
                                "<logactivity>{0}</logactivity>",
                                XmlUtils.XMLEncode(urlTrackingInfo.LogActivity.ToString()));
                            strXml.AppendFormat(
                                "<trackclicks>{0}</trackclicks>",
                                XmlUtils.XMLEncode(urlTrackingInfo.TrackClicks.ToString()));
                            strXml.AppendFormat("<newwindow>{0}</newwindow>", XmlUtils.XMLEncode(urlTrackingInfo.NewWindow.ToString()));
                        }
                        strXml.Append("</document>");
                    }
                }

                ExportSettings(module, strXml);
            }
            catch (Exception ex) {
                Exceptions.LogException(ex);
            }
            finally {
                // make sure XML is valid
                strXml.Append("</documents>");
            }

            return(strXml.ToString());
        }
Пример #30
0
        private void SaveMedia()
        {
            var objMediaController = new MediaController();
            var objMedia           = new MediaInfo();

            try
            {
                // Update settings in the database
                if (this.radMediaType.SelectedIndex == 0) // standard file system
                {
                    if (string.Equals(ctlURL.UrlType, "F"))
                    {
                        IFileInfo objFile = FileManager.Instance.GetFile(int.Parse(Regex.Match(this.ctlURL.Url, "\\d+").Value, System.Globalization.NumberStyles.Integer));
                        if (objFile != null)
                        {
                            if (string.IsNullOrEmpty(this.txtWidth.Text))
                            {
                                this.txtWidth.Text = objFile.Width.ToString();
                            }
                            if (string.IsNullOrEmpty(this.txtHeight.Text))
                            {
                                this.txtHeight.Text = objFile.Height.ToString();
                            }
                        }
                    }
                }

                var sec = new PortalSecurity();

                objMedia.ModuleID  = ModuleId;
                objMedia.MediaType = this.radMediaType.SelectedIndex;
                switch (this.radMediaType.SelectedIndex)
                {
                case 0:     // standard file system
                    objMedia.Src = this.ctlURL.Url;
                    break;

                case 1:     // embed code
                    objMedia.Src = this.txtEmbed.Text;
                    break;

                case 2:     // oembed url
                    objMedia.Src = this.txtOEmbed.Text;
                    break;
                }

                // ensure that youtube gets formatted correctly
                objMedia.Src = ReformatForYouTube(objMedia.Src);

                objMedia.Alt = sec.InputFilter(this.txtAlt.Text, PortalSecurity.FilterFlag.NoMarkup);
                if (!(string.IsNullOrEmpty(this.txtWidth.Text)))
                {
                    objMedia.Width = int.Parse(sec.InputFilter(this.txtWidth.Text, PortalSecurity.FilterFlag.NoMarkup), System.Globalization.NumberStyles.Integer);
                }
                if (!(string.IsNullOrEmpty(this.txtHeight.Text)))
                {
                    objMedia.Height = int.Parse(sec.InputFilter(this.txtHeight.Text, PortalSecurity.FilterFlag.NoMarkup), System.Globalization.NumberStyles.Integer);
                }
                objMedia.NavigateUrl    = sec.InputFilter(this.ctlNavigateUrl.Url, PortalSecurity.FilterFlag.NoMarkup);
                objMedia.MediaAlignment = int.Parse(sec.InputFilter(this.ddlImageAlignment.SelectedValue, PortalSecurity.FilterFlag.NoMarkup), System.Globalization.NumberStyles.Integer);
                objMedia.AutoStart      = this.chkAutoStart.Checked;
                objMedia.MediaLoop      = this.chkLoop.Checked;
                objMedia.LastUpdatedBy  = this.UserId;
                objMedia.MediaMessage   = sec.InputFilter(this.txtMessage.Text, PortalSecurity.FilterFlag.NoScripting);

                // url tracking
                var objUrls = new UrlController();
                objUrls.UpdateUrl(PortalId, this.ctlNavigateUrl.Url, this.ctlNavigateUrl.UrlType, this.ctlNavigateUrl.Log, this.ctlNavigateUrl.Track, ModuleId, this.ctlNavigateUrl.NewWindow);

                // update settings/preferences
                SaveMediaSettings();

                // add/update
                if (p_isNew)
                {
                    // add new media
                    objMediaController.AddMedia(objMedia);
                }
                else
                {
                    // update existing media
                    objMediaController.UpdateMedia(objMedia);
                }

                // save the update into the journal
                if (PostToJournal)
                {
                    AddMediaUpdateToJournal(objMedia);
                }

                // notify the site administrators
                if (NotifyOnUpdate)
                {
                    SendNotificationToMessageCenter(objMedia);
                }
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.LogException(exc);
                //ProcessModuleLoadException(Me, exc)
            }
        }
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            this.cmdDisplay.Click += this.cmdDisplay_Click;

            try
            {
                // this needs to execute always to the client script code is registred in InvokePopupCal
                this.cmdStartCalendar.NavigateUrl = Calendar.InvokePopupCal(this.txtStartDate);
                this.cmdEndCalendar.NavigateUrl   = Calendar.InvokePopupCal(this.txtEndDate);
                if (!this.Page.IsPostBack)
                {
                    if (!string.IsNullOrEmpty(this._URL))
                    {
                        this.lblLogURL.Text = this.URL; // saved for loading Log grid
                        TabType URLType = Globals.GetURLType(this._URL);
                        if (URLType == TabType.File && this._URL.StartsWith("fileid=", StringComparison.InvariantCultureIgnoreCase) == false)
                        {
                            // to handle legacy scenarios before the introduction of the FileServerHandler
                            var fileName = Path.GetFileName(this._URL);

                            var folderPath = this._URL.Substring(0, this._URL.LastIndexOf(fileName));
                            var folder     = FolderManager.Instance.GetFolder(this.PortalSettings.PortalId, folderPath);

                            var file = FileManager.Instance.GetFile(folder, fileName);

                            this.lblLogURL.Text = "FileID=" + file.FileId;
                        }

                        var             objUrls        = new UrlController();
                        UrlTrackingInfo objUrlTracking = objUrls.GetUrlTracking(this.PortalSettings.PortalId, this.lblLogURL.Text, this.ModuleID);
                        if (objUrlTracking != null)
                        {
                            if (string.IsNullOrEmpty(this._FormattedURL))
                            {
                                this.lblURL.Text = Globals.LinkClick(this.URL, this.PortalSettings.ActiveTab.TabID, this.ModuleID, false);
                                if (!this.lblURL.Text.StartsWith("http") && !this.lblURL.Text.StartsWith("mailto"))
                                {
                                    this.lblURL.Text = Globals.AddHTTP(this.Request.Url.Host) + this.lblURL.Text;
                                }
                            }
                            else
                            {
                                this.lblURL.Text = this._FormattedURL;
                            }

                            this.lblCreatedDate.Text = objUrlTracking.CreatedDate.ToString();

                            if (objUrlTracking.TrackClicks)
                            {
                                this.pnlTrack.Visible = true;
                                if (string.IsNullOrEmpty(this._TrackingURL))
                                {
                                    if (!this.URL.StartsWith("http"))
                                    {
                                        this.lblTrackingURL.Text = Globals.AddHTTP(this.Request.Url.Host);
                                    }

                                    this.lblTrackingURL.Text += Globals.LinkClick(this.URL, this.PortalSettings.ActiveTab.TabID, this.ModuleID, objUrlTracking.TrackClicks);
                                }
                                else
                                {
                                    this.lblTrackingURL.Text = this._TrackingURL;
                                }

                                this.lblClicks.Text = objUrlTracking.Clicks.ToString();
                                if (!Null.IsNull(objUrlTracking.LastClick))
                                {
                                    this.lblLastClick.Text = objUrlTracking.LastClick.ToString();
                                }
                            }

                            if (objUrlTracking.LogActivity)
                            {
                                this.pnlLog.Visible = true;

                                this.txtStartDate.Text = DateTime.Today.AddDays(-6).ToShortDateString();
                                this.txtEndDate.Text   = DateTime.Today.AddDays(1).ToShortDateString();
                            }
                        }
                    }
                    else
                    {
                        this.Visible = false;
                    }
                }
            }
            catch (Exception exc) // Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }
Пример #32
0
 public UrlConfig(ILogger log, UrlController controller)
 {
     _log        = log;
     _controller = controller;
 }