예제 #1
0
        //====================================================================================================
        //
        public static void housekeep(CoreController core, HouseKeepEnvironmentModel env)
        {
            try {
                //
                LogController.logInfo(core, "Housekeep, viewingsummary");
                //
                //
                // -- there is a bug and I need to move on.
                return;

                //
                // Page View Summary
                //
                {
                    DateTime datePtr = default;
                    using (var csData = new CsModel(core)) {
                        if (!csData.openSql(core.db.getSQLSelect("ccviewingsummary", "DateNumber", "TimeDuration=24 and DateNumber>=" + env.oldestVisitSummaryWeCareAbout.Date.ToOADate(), "DateNumber Desc", "", 1)))
                        {
                            datePtr = env.oldestVisitSummaryWeCareAbout;
                        }
                        else
                        {
                            datePtr = DateTime.MinValue.AddDays(csData.getInteger("DateNumber"));
                        }
                    }
                    if (datePtr < env.oldestVisitSummaryWeCareAbout)
                    {
                        datePtr = env.oldestVisitSummaryWeCareAbout;
                    }
                    pageViewSummary(core, datePtr, env.yesterday, 24, core.siteProperties.dataBuildVersion, env.oldestVisitSummaryWeCareAbout);
                }
            } catch (Exception ex) {
                LogController.logError(core, ex);
            }
        }
예제 #2
0
 public static void housekeep(CoreController core, HouseKeepEnvironmentModel env)
 {
     try {
         //
         LogController.logInfo(core, "Housekeep, grouprules");
         //
         //
         // GroupRules with bad ContentID
         //   Handled record by record removed to prevent CDEF reload
         //
         LogController.logInfo(core, "Deleting Group Rules with bad ContentID.");
         string sql = "Select ccGroupRules.ID"
                      + " From ccGroupRules LEFT JOIN ccContent on ccContent.ID=ccGroupRules.ContentID"
                      + " WHERE (ccContent.ID is null)";
         using (var csData = new CsModel(core)) {
             csData.openSql(sql);
             while (csData.ok())
             {
                 MetadataController.deleteContentRecord(core, "Group Rules", csData.getInteger("ID"));
                 csData.goNext();
             }
         }
         //
         // GroupRules with bad GroupID
         //
         LogController.logInfo(core, "Deleting Group Rules with bad GroupID.");
         sql = "delete ccGroupRules"
               + " From ccGroupRules"
               + " LEFT JOIN ccgroups on ccgroups.ID=ccGroupRules.GroupID"
               + " WHERE (ccgroups.ID is null)";
         core.db.executeNonQuery(sql);
     } catch (Exception ex) {
         LogController.logError(core, ex);
     }
 }
예제 #3
0
 //
 //=============================================================================
 //
 public static string getWhatsRelated(CoreController core)
 {
     try {
         CPClass cp = core.cpParent;
         if (core.doc.pageController.page.id == 0)
         {
             return(string.Empty);
         }
         StringBuilder items = new StringBuilder();
         using (var cs = new CsModel(core)) {
             string sql = "select rp.id,rp.name,rp.menuheadline,rp.briefFilename"
                          + " from ccpagecontenttopicrules sr"
                          + " left join ccpagecontenttopicrules rr on rr.topicid=sr.topicid"
                          + " left join ccpagecontent rp on rp.id=rr.pageid"
                          + " group by rp.id,rp.name,rp.menuheadline,rp.briefFilename"
                          + " order by count(rp.id)";
             if (cs.openSql(sql))
             {
                 do
                 {
                     int pageId = cs.getInteger("id");
                     if (!pageId.Equals(core.doc.pageController.page.id))
                     {
                         string link = cp.Content.GetPageLink(pageId);
                         if (!string.IsNullOrWhiteSpace(link))
                         {
                             if (!link.Contains("://"))
                             {
                                 link = core.webServer.requestProtocol + link;
                             }
                             string menuHeadline  = cs.getText("menuheadline");
                             string content       = HtmlController.a(string.IsNullOrWhiteSpace(menuHeadline) ? cs.getText("name") : menuHeadline, link);
                             string briefFilename = cs.getText("briefFilename");
                             if (!string.IsNullOrWhiteSpace(briefFilename))
                             {
                                 content += HtmlController.div(cp.CdnFiles.Read(briefFilename), "ccListCopy");
                             }
                             items.Append(HtmlController.li(content, "wrItem"));
                         }
                     }
                     cs.goNext();
                 } while (cs.ok());
             }
         }
         if (items.Length > 0)
         {
             return(HtmlController.div(HtmlController.h4("Whats Related") + HtmlController.ul(items.ToString(), "ccList"), "ccWhatsRelated"));
         }
         if (cp.User.IsEditing(""))
         {
             return(HtmlController.div(HtmlController.h4("Whats Related") + HtmlController.ul("<li>[empty list]</li>", "ccList"), "ccWhatsRelated"));
         }
         return(string.Empty);
     } catch (Exception ex) {
         LogController.logError(core, ex);
         return(string.Empty);
     }
 }
예제 #4
0
 //
 //====================================================================================================
 /// <summary>
 /// Add a command task to the taskQueue to be run by the taskRunner. Returns false if the task was already there (dups fround by command name and cmdDetailJson)
 /// </summary>
 /// <param name="core"></param>
 /// <param name="command"></param>
 /// <param name="cmdDetail"></param>
 /// <param name="downloadName"></param>
 /// <returns></returns>
 static public bool addTaskToQueue(CoreController core, TaskModel.CmdDetailClass cmdDetail, bool blockDuplicates, string downloadName, string downloadFilename)
 {
     try {
         //
         int downloadId = 0;
         if (!string.IsNullOrEmpty(downloadName))
         {
             Dictionary <string, string> defaultValues = ContentMetadataModel.getDefaultValueDict(core, DownloadModel.tableMetadata.contentName);
             var download = DbBaseModel.addDefault <DownloadModel>(core.cpParent, defaultValues);
             download.name          = downloadName;
             download.dateRequested = core.dateTimeNowMockable;
             download.requestedBy   = core.session.user.id;
             if (!string.IsNullOrEmpty(downloadFilename))
             {
                 //
                 // -- if the donwloadfilename is specified, save it in the download record and force the file to save with a space in content
                 download.filename.filename = FileController.getVirtualRecordUnixPathFilename(DownloadModel.tableMetadata.tableNameLower, "filename", download.id, downloadFilename);
                 download.filename.content  = " ";
             }
             downloadId = download.id;
             download.save(core.cpParent);
         }
         string cmdDetailJson = SerializeObject(cmdDetail);
         bool   allowAdd      = true;
         if (blockDuplicates)
         {
             //
             // -- Search for a duplicate
             string sql = "select top 1 id from cctasks where ((cmdDetail=" + DbController.encodeSQLText(cmdDetailJson) + ")and(datestarted is null)and(datecompleted is null))";
             using (var csData = new CsModel(core)) {
                 allowAdd = !csData.openSql(sql);
             }
         }
         //
         // -- add it to the queue and shell out to the command
         if (allowAdd)
         {
             var task = TaskModel.addEmpty <TaskModel>(core.cpParent);
             task.name             = "addon [#" + cmdDetail.addonId + "," + cmdDetail.addonName + "]";
             task.cmdDetail        = cmdDetailJson;
             task.resultDownloadId = downloadId;
             task.save(core.cpParent);
             LogController.logTrace(core, "addTaskToQueue, task added, cmdDetailJson [" + cmdDetailJson + "]");
             return(true);
         }
         LogController.logTrace(core, "addTaskToQueue, task blocked because duplicate found, cmdDetailJson [" + cmdDetailJson + "]");
         return(false);
     } catch (Exception ex) {
         LogController.logError(core, ex);
         return(false);
     }
 }
예제 #5
0
 //
 //====================================================================================================
 //
 public override string GetLayout(int layoutid)
 {
     try {
         using (var cs = new CsModel(cp.core)) {
             string sql = "select layout from ccLayouts where id=" + layoutid;
             cs.openSql(sql);
             if (cs.ok())
             {
                 return(cs.getText("layout"));
             }
         }
     } catch (Exception ex) {
         LogController.logError(cp.core, ex);
     }
     return(string.Empty);
 }
        //
        public static string getDefaultValue(CoreController core, string contentName, string fieldName)
        {
            string defaultValue = "";
            int    contentId    = ContentMetadataModel.getContentId(core, contentName);
            string SQL          = "select defaultvalue from ccfields where name=" + DbController.encodeSQLText(fieldName) + " and contentid=(" + contentId + ")";

            using (var csData = new CsModel(core)) {
                csData.openSql(SQL);
                if (csData.ok())
                {
                    defaultValue = csData.getText("defaultvalue");
                }
                csData.close();
            }
            return(defaultValue);
        }
예제 #7
0
 //====================================================================================================
 //
 public static void housekeep(CoreController core, HouseKeepEnvironmentModel env)
 {
     try {
         //
         LogController.logInfo(core, "HousekeepDaily, page content");
         {
             //
             // Move Archived pages from their current parent to their archive parent
             //
             bool   NeedToClearCache = false;
             string SQL = "select * from ccpagecontent where (( DateArchive is not null )and(DateArchive<" + core.sqlDateTimeMockable + "))and(active<>0)";
             using (var csData = new CsModel(core)) {
                 csData.openSql(SQL);
                 while (csData.ok())
                 {
                     int RecordId        = csData.getInteger("ID");
                     int ArchiveParentId = csData.getInteger("ArchiveParentID");
                     if (ArchiveParentId == 0)
                     {
                         SQL = "update ccpagecontent set DateArchive=null where (id=" + RecordId + ")";
                         core.db.executeNonQuery(SQL);
                     }
                     else
                     {
                         SQL = "update ccpagecontent set ArchiveParentID=null,DateArchive=null,parentid=" + ArchiveParentId + " where (id=" + RecordId + ")";
                         core.db.executeNonQuery(SQL);
                         NeedToClearCache = true;
                     }
                     csData.goNext();
                 }
                 csData.close();
             }
             //
             // Clear caches
             //
             if (NeedToClearCache)
             {
                 object emptyData = null;
                 core.cache.invalidate("Page Content");
                 core.cache.storeObject("PCC", emptyData);
             }
         }
     } catch (Exception ex) {
         LogController.logError(core, ex);
     }
 }
예제 #8
0
 //
 //=============================================================================
 /// <summary>
 /// Sets the MetaContent subsystem so the next call to main_GetLastMeta... returns the correct value
 /// </summary>
 /// <param name="contentId"></param>
 /// <param name="recordId"></param>
 public void setMetaContent(int contentId, int recordId)
 {
     if ((contentId != 0) && (recordId != 0))
     {
         //
         // -- open meta content record
         string Criteria      = "(ContentID=" + contentId + ")and(RecordID=" + recordId + ")";
         string FieldList     = "ID,Name,MetaDescription,OtherHeadTags,MetaKeywordList";
         string keywordList   = "";
         int    MetaContentId = 0;
         using (var csData = new CsModel(core)) {
             if (csData.open("Meta Content", Criteria, "", false, 0, FieldList))
             {
                 MetaContentId = csData.getInteger("ID");
                 core.html.addTitle(HtmlController.encodeHtml(csData.getText("Name")), "page content");
                 core.html.addMetaDescription(HtmlController.encodeHtml(csData.getText("MetaDescription")), "page content");
                 core.html.addHeadTag(csData.getText("OtherHeadTags"), "page content");
                 keywordList = csData.getText("MetaKeywordList").Replace(Environment.NewLine, ",");
             }
             csData.close();
         }
         //
         // open Keyword List
         using (var csData = new CsModel(core)) {
             string SQL = "select ccMetaKeywords.Name"
                          + " From ccMetaKeywords"
                          + " LEFT JOIN ccMetaKeywordRules on ccMetaKeywordRules.MetaKeywordID=ccMetaKeywords.ID"
                          + " Where ccMetaKeywordRules.MetaContentID=" + MetaContentId;
             csData.openSql(SQL);
             while (csData.ok())
             {
                 keywordList = keywordList + "," + csData.getText("Name");
                 csData.goNext();
             }
             if (!string.IsNullOrEmpty(keywordList))
             {
                 if (keywordList.left(1) == ",")
                 {
                     keywordList = keywordList.Substring(1);
                 }
                 keywordList = HtmlController.encodeHtml(keywordList);
                 core.html.addMetaKeywordList(keywordList, "page content");
             }
         }
     }
 }
        //
        //=============================================================================
        // Create a child content
        //=============================================================================
        //
        private static string GetContentChildTool_Options(CPClass cp, int ParentId, int DefaultValue)
        {
            string returnOptions = "";

            try {
                //
                string SQL        = null;
                int    RecordId   = 0;
                string RecordName = null;
                //
                if (ParentId == 0)
                {
                    SQL = "select Name, ID from ccContent where ((ParentID<1)or(Parentid is null)) and (AllowContentChildTool<>0);";
                }
                else
                {
                    SQL = "select Name, ID from ccContent where ParentID=" + ParentId + " and (AllowContentChildTool<>0) and not (allowcontentchildtool is null);";
                }
                using (var csData = new CsModel(cp.core)) {
                    csData.openSql(SQL);
                    while (csData.ok())
                    {
                        RecordName = csData.getText("Name");
                        RecordId   = csData.getInteger("ID");
                        if (RecordId == DefaultValue)
                        {
                            returnOptions = returnOptions + "<option value=\"" + RecordId + "\" selected>" + csData.getText("name") + "</option>";
                        }
                        else
                        {
                            returnOptions = returnOptions + "<option value=\"" + RecordId + "\" >" + csData.getText("name") + "</option>";
                        }
                        returnOptions = returnOptions + GetContentChildTool_Options(cp, RecordId, DefaultValue);
                        csData.goNext();
                    }
                    csData.close();
                }
            } catch (Exception ex) {
                LogController.logError(cp.core, ex);
                throw;
            }
            return(returnOptions);
        }
예제 #10
0
 public static void housekeep(CoreController core, HouseKeepEnvironmentModel env)
 {
     try {
         //
         LogController.logInfo(core, "HousekeepDaily, contentwatch");
         //
         using (var csData = new CsModel(core)) {
             string sql = "select cccontentwatch.id from cccontentwatch left join cccontent on cccontent.id=cccontentwatch.contentid  where (cccontent.id is null)or(cccontent.active=0)or(cccontent.active is null)";
             csData.openSql(sql);
             while (csData.ok())
             {
                 MetadataController.deleteContentRecord(core, "Content Watch", csData.getInteger("ID"));
                 csData.goNext();
             }
         }
     } catch (Exception ex) {
         LogController.logError(core, ex);
     }
 }
예제 #11
0
 //
 //====================================================================================================
 //
 public override bool OpenSQL(string sql, string dataSourcename, int pageSize, int pageNumber)
 {
     try {
         if (((string.IsNullOrEmpty(sql)) || (sql.ToLowerInvariant() == "default")) && (!string.IsNullOrEmpty(dataSourcename)) && (dataSourcename.ToLowerInvariant() != "default"))
         {
             //
             // -- arguments reversed from legacy api mistake, datasource has the query, sql has the datasource
             LogController.logWarn(cp.core, "Call to cs with arguments reversed, datasource [" + dataSourcename + "], sql [" + sql + "]");
             return(cs.openSql(dataSourcename, sql, pageSize, pageNumber));
         }
         return(cs.openSql(sql, dataSourcename, pageSize, pageNumber));
     } catch (Exception ex) {
         LogController.logError(cp.core, ex);
         throw;
     }
 }
예제 #12
0
        //
        //========================================================================
        //   Editor features are stored in the \config\EditorFeatures.txt file
        //   This is a crlf delimited list, with each row including:
        //       admin:featurelist
        //       contentmanager:featurelist
        //       public:featurelist
        //========================================================================
        //
        public static string get(CoreController core)
        {
            string result = null;

            try {
                string Description = "This tool is used to configure the wysiwyg content editor for different uses. Check the Administrator column if you want administrators to have access to this feature when editing a page. Check the Content Manager column to allow non-admins to have access to this feature. Check the Public column if you want those on the public site to have access to the feature when the editor is used for public forms.";
                string Button      = core.docProperties.getText(RequestNameButton);
                if (Button == ButtonCancel)
                {
                    //
                    // Cancel button pressed, return with nothing goes to root form
                }
                else
                {
                    StringBuilderLegacyController Content = new StringBuilderLegacyController();
                    string ButtonList = null;
                    //
                    // From here down will return a form
                    if (!core.session.isAuthenticatedAdmin())
                    {
                        //
                        // Does not have permission
                        ButtonList = ButtonCancel;
                        Content.add(AdminUIController.getFormBodyAdminOnly());
                        core.html.addTitle("Style Editor");
                        result = AdminUIController.getToolBody(core, "Site Styles", ButtonList, "", true, true, Description, "", 0, Content.text);
                    }
                    else
                    {
                        string AdminList   = "";
                        string CMList      = "";
                        string PublicList  = "";
                        int    Ptr         = 0;
                        string FeatureName = null;
                        //
                        // OK to see and use this form
                        if (Button == ButtonSave || Button == ButtonOK)
                        {
                            //
                            // Save the Previous edits
                            core.siteProperties.setProperty("Editor Background Color", core.docProperties.getText("editorbackgroundcolor"));
                            for (Ptr = 0; Ptr <= ((string[])null).GetUpperBound(0); Ptr++)
                            {
                                FeatureName = ((string[])null)[Ptr];
                                if (GenericController.toLCase(FeatureName) == "styleandformatting")
                                {
                                    //
                                    // must always be on or it throws js error (editor bug I guess)
                                    //
                                    AdminList  = AdminList + "," + FeatureName;
                                    CMList     = CMList + "," + FeatureName;
                                    PublicList = PublicList + "," + FeatureName;
                                }
                                else
                                {
                                    if (core.docProperties.getBoolean(FeatureName + ".admin"))
                                    {
                                        AdminList = AdminList + "," + FeatureName;
                                    }
                                    if (core.docProperties.getBoolean(FeatureName + ".cm"))
                                    {
                                        CMList = CMList + "," + FeatureName;
                                    }
                                    if (core.docProperties.getBoolean(FeatureName + ".public"))
                                    {
                                        PublicList = PublicList + "," + FeatureName;
                                    }
                                }
                            }
                            core.privateFiles.saveFile(InnovaEditorFeaturefilename, "admin:" + AdminList + Environment.NewLine + "contentmanager:" + CMList + Environment.NewLine + "public:" + PublicList);
                            //
                            // Clear the editor style rules template cache so next edit gets new background color
                            string EditorStyleRulesFilename = GenericController.strReplace(EditorStyleRulesFilenamePattern, "$templateid$", "0", 1, 99, 1);
                            core.privateFiles.deleteFile(EditorStyleRulesFilename);
                            //
                            using (var csData = new CsModel(core)) {
                                csData.openSql("select id from cctemplates");
                                while (csData.ok())
                                {
                                    EditorStyleRulesFilename = GenericController.strReplace(EditorStyleRulesFilenamePattern, "$templateid$", csData.getText("ID"), 1, 99, 1);
                                    core.privateFiles.deleteFile(EditorStyleRulesFilename);
                                    csData.goNext();
                                }
                            }
                        }
                        if (Button != ButtonOK)
                        {
                            //
                            // Draw the form
                            string FeatureList = core.cdnFiles.readFileText(InnovaEditorFeaturefilename);
                            if (string.IsNullOrEmpty(FeatureList))
                            {
                                FeatureList = "admin:" + InnovaEditorFeatureList + Environment.NewLine + "contentmanager:" + InnovaEditorFeatureList + Environment.NewLine + "public:" + InnovaEditorPublicFeatureList;
                            }
                            if (!string.IsNullOrEmpty(FeatureList))
                            {
                                string[] Features = stringSplit(FeatureList, Environment.NewLine);
                                AdminList = Features[0].Replace("admin:", "");
                                if (Features.GetUpperBound(0) > 0)
                                {
                                    CMList = Features[1].Replace("contentmanager:", "");
                                    if (Features.GetUpperBound(0) > 1)
                                    {
                                        PublicList = Features[2].Replace("public:", "");
                                    }
                                }
                            }
                            string Copy = Environment.NewLine + "<tr class=\"ccAdminListCaption\">"
                                          + "<td align=left style=\"width:200;\">Feature</td>"
                                          + "<td align=center style=\"width:100;\">Administrators</td>"
                                          + "<td align=center style=\"width:100;\">Content&nbsp;Managers</td>"
                                          + "<td align=center style=\"width:100;\">Public</td>"
                                          + "</tr>";
                            int RowPtr = 0;
                            for (Ptr = 0; Ptr <= ((string[])null).GetUpperBound(0); Ptr++)
                            {
                                FeatureName = ((string[])null)[Ptr];
                                if (GenericController.toLCase(FeatureName) == "styleandformatting")
                                {
                                    //
                                    // hide and force on during process - editor bug I think.
                                    //
                                }
                                else
                                {
                                    string TDLeft      = HtmlController.tableCellStart("", 0, encodeBoolean(RowPtr % 2), "left");
                                    string TDCenter    = HtmlController.tableCellStart("", 0, encodeBoolean(RowPtr % 2), "center");
                                    bool   AllowAdmin  = GenericController.encodeBoolean("," + AdminList + ",".IndexOf("," + FeatureName + ",", System.StringComparison.OrdinalIgnoreCase) + 1);
                                    bool   AllowCM     = GenericController.encodeBoolean("," + CMList + ",".IndexOf("," + FeatureName + ",", System.StringComparison.OrdinalIgnoreCase) + 1);
                                    bool   AllowPublic = GenericController.encodeBoolean("," + PublicList + ",".IndexOf("," + FeatureName + ",", System.StringComparison.OrdinalIgnoreCase) + 1);
                                    Copy += Environment.NewLine + "<tr>"
                                            + TDLeft + FeatureName + "</td>"
                                            + TDCenter + HtmlController.checkbox(FeatureName + ".admin", AllowAdmin) + "</td>"
                                            + TDCenter + HtmlController.checkbox(FeatureName + ".cm", AllowCM) + "</td>"
                                            + TDCenter + HtmlController.checkbox(FeatureName + ".public", AllowPublic) + "</td>"
                                            + "</tr>";
                                    RowPtr = RowPtr + 1;
                                }
                            }
                            Copy = ""
                                   + Environment.NewLine + "<div><b>body background style color</b> (default='white')</div>"
                                   + Environment.NewLine + "<div>" + HtmlController.inputText_Legacy(core, "editorbackgroundcolor", core.siteProperties.getText("Editor Background Color", "white")) + "</div>"
                                   + Environment.NewLine + "<div>&nbsp;</div>"
                                   + Environment.NewLine + "<div><b>Toolbar features available</b></div>"
                                   + Environment.NewLine + "<table border=\"0\" cellpadding=\"4\" cellspacing=\"0\" width=\"500px\" align=left>" + GenericController.nop(Copy) + Environment.NewLine + kmaEndTable;
                            Copy = Environment.NewLine + HtmlController.tableStart(20, 0, 0) + "<tr><td>" + GenericController.nop(Copy) + "</td></tr>\r\n" + kmaEndTable;
                            Content.add(Copy);
                            ButtonList = ButtonCancel + "," + ButtonRefresh + "," + ButtonSave + "," + ButtonOK;
                            Content.add(HtmlController.inputHidden(rnAdminSourceForm, AdminFormEditorConfig));
                            core.html.addTitle("Editor Settings");
                            result = AdminUIController.getToolBody(core, "Editor Configuration", ButtonList, "", true, true, Description, "", 0, Content.text);
                        }
                    }
                }
            } catch (Exception ex) {
                LogController.logError(core, ex);
            }
            return(result);
        }
예제 #13
0
 public static void housekeep(CoreController core, HouseKeepEnvironmentModel env)
 {
     try {
         //
         LogController.logInfo(core, "Housekeep, visits");
         {
             //
             LogController.logInfo(core, "Deleting visits with no DateAdded");
             //
             core.db.sqlCommandTimeout = 180;
             core.db.executeNonQuery("delete from ccvisits where (DateAdded is null)or(DateAdded<DATEADD(year,-10,CAST(GETDATE() AS DATE)))");
         }
         {
             //
             LogController.logInfo(core, "Deleting visits with no visitor");
             //
             core.db.executeNonQuery("delete from ccvisits from ccvisits v left join ccvisitors r on r.id=v.visitorid where (r.id is null)");
         }
         if (env.archiveDeleteNoCookie)
         {
             //
             LogController.logInfo(core, "Deleting visits with no cookie support older than Midnight, Two Days Ago");
             //
             core.db.sqlCommandTimeout = 180;
             core.db.executeNonQuery("delete from ccvisits where (CookieSupport=0)and(LastVisitTime<DATEADD(day,-2,CAST(GETDATE() AS DATE)))");
         }
         DateTime OldestVisitDate = default(DateTime);
         //
         // Get Oldest Visit
         using (var csData = new CsModel(core)) {
             if (csData.openSql(core.db.getSQLSelect("ccVisits", "DateAdded", "", "dateadded", "", 1)))
             {
                 OldestVisitDate = csData.getDate("DateAdded").Date;
             }
         }
         //
         // Remove old visit records
         //   if > 30 days in visit table, limit one pass to just 30 days
         //   this is to prevent the entire server from being bogged down for one site change
         //
         if (OldestVisitDate == DateTime.MinValue)
         {
             LogController.logInfo(core, "No visit records were removed because no visit records were found while requesting the oldest visit.");
         }
         else
         {
             DateTime ArchiveDate  = core.dateTimeNowMockable.AddDays(-env.visitArchiveAgeDays).Date;
             int      DaystoRemove = encodeInteger(ArchiveDate.Subtract(OldestVisitDate).TotalDays);
             if (DaystoRemove > 30)
             {
                 ArchiveDate = OldestVisitDate.AddDays(30);
             }
             if (OldestVisitDate >= ArchiveDate)
             {
                 LogController.logInfo(core, "No records were removed because Oldest Visit Date [" + OldestVisitDate + "] >= ArchiveDate [" + ArchiveDate + "].");
             }
             else
             {
                 LogController.logInfo(core, "Removing records from [" + OldestVisitDate + "] to [" + ArchiveDate + "].");
                 DateTime SingleDate = default(DateTime);
                 SingleDate = OldestVisitDate;
                 do
                 {
                     houseKeep_App_Daily_RemoveVisitRecords(core, SingleDate);
                     SingleDate = SingleDate.AddDays(1);
                 } while (SingleDate < ArchiveDate);
             }
         }
     } catch (Exception ex) {
         LogController.logError(core, ex);
     }
 }
예제 #14
0
        //====================================================================================================
        /// <summary>
        /// Summarize the page views, excludes non-cookie visits, excludes administrator and developer visits, excludes authenticated users with ExcludeFromReporting
        /// </summary>
        /// <param name="core"></param>
        /// <param name="StartTimeDate"></param>
        /// <param name="EndTimeDate"></param>
        /// <param name="HourDuration"></param>
        /// <param name="BuildVersion"></param>
        /// <param name="OldestVisitSummaryWeCareAbout"></param>
        //
        public static void pageViewSummary(CoreController core, DateTime StartTimeDate, DateTime EndTimeDate, int HourDuration, string BuildVersion, DateTime OldestVisitSummaryWeCareAbout)
        {
            int    hint    = 0;
            string hinttxt = "";

            try {
                XmlDocument LibraryCollections = new XmlDocument();
                XmlDocument LocalCollections   = new XmlDocument();
                XmlDocument Doc = new XmlDocument();
                {
                    hint = 1;
                    DateTime PeriodStart = default;
                    PeriodStart = StartTimeDate;
                    if (PeriodStart < OldestVisitSummaryWeCareAbout)
                    {
                        PeriodStart = OldestVisitSummaryWeCareAbout;
                    }
                    DateTime PeriodDatePtr = default;
                    PeriodDatePtr = PeriodStart.Date;
                    while (PeriodDatePtr < EndTimeDate)
                    {
                        hint = 2;
                        //
                        hinttxt = ", HourDuration [" + HourDuration + "], PeriodDatePtr [" + PeriodDatePtr + "], PeriodDatePtr.AddHours(HourDuration / 2.0) [" + PeriodDatePtr.AddHours(HourDuration / 2.0) + "]";
                        int DateNumber = encodeInteger((PeriodDatePtr - default(DateTime)).TotalDays);
                        // encodeInteger(PeriodDatePtr.AddHours(HourDuration / 2.0).ToOADate());
                        int      TimeNumber = encodeInteger(PeriodDatePtr.TimeOfDay.TotalHours);
                        DateTime DateStart  = default(DateTime);
                        DateStart = PeriodDatePtr.Date;
                        DateTime DateEnd = default(DateTime);
                        DateEnd = PeriodDatePtr.AddHours(HourDuration).Date;
                        string PageTitle = "";
                        int    PageId    = 0;
                        int    PageViews = 0;
                        int    AuthenticatedPageViews = 0;
                        int    MobilePageViews        = 0;
                        int    BotPageViews           = 0;
                        int    NoCookiePageViews      = 0;
                        //
                        // Loop through all the pages hit during this period
                        //
                        //
                        // for now ignore the problem caused by addons like Blogs creating multiple 'pages' within on pageid
                        // One way to handle this is to expect the addon to set something unquie in he page title
                        // then use the title to distinguish a page. The problem with this is the current system puts the
                        // visit number and page number in the name. if we select on district name, they will all be.
                        //
                        using (var csPages = new CsModel(core)) {
                            string sql = "select distinct recordid,pagetitle from ccviewings h"
                                         + " where (h.recordid<>0)"
                                         + " and(h.dateadded>=" + DbController.encodeSQLDate(DateStart) + ")"
                                         + " and (h.dateadded<" + DbController.encodeSQLDate(DateEnd) + ")"
                                         + " and((h.ExcludeFromAnalytics is null)or(h.ExcludeFromAnalytics=0))"
                                         + "order by recordid";
                            hint = 3;
                            if (!csPages.openSql(sql))
                            {
                                //
                                // no hits found - add or update a single record for this day so we know it has been calculated
                                csPages.open("Page View Summary", "(timeduration=" + HourDuration + ")and(DateNumber=" + DateNumber + ")and(TimeNumber=" + TimeNumber + ")and(pageid=" + PageId + ")and(pagetitle=" + DbController.encodeSQLText(PageTitle) + ")");
                                if (!csPages.ok())
                                {
                                    csPages.close();
                                    csPages.insert("Page View Summary");
                                }
                                //
                                if (csPages.ok())
                                {
                                    csPages.set("name", HourDuration + " hr summary for " + DateTime.MinValue.AddDays(DateNumber) + " " + TimeNumber + ":00, " + PageTitle);
                                    csPages.set("DateNumber", DateNumber);
                                    csPages.set("TimeNumber", TimeNumber);
                                    csPages.set("TimeDuration", HourDuration);
                                    csPages.set("PageViews", PageViews);
                                    csPages.set("PageID", PageId);
                                    csPages.set("PageTitle", PageTitle);
                                    csPages.set("AuthenticatedPageViews", AuthenticatedPageViews);
                                    csPages.set("NoCookiePageViews", NoCookiePageViews);
                                    {
                                        csPages.set("MobilePageViews", MobilePageViews);
                                        csPages.set("BotPageViews", BotPageViews);
                                    }
                                }
                                csPages.close();
                                hint = 4;
                            }
                            else
                            {
                                hint = 5;
                                //
                                // add an entry for each page hit on this day
                                //
                                while (csPages.ok())
                                {
                                    PageId    = csPages.getInteger("recordid");
                                    PageTitle = csPages.getText("pagetitle");
                                    string baseCriteria = ""
                                                          + " (h.recordid=" + PageId + ")"
                                                          + " "
                                                          + " and(h.dateadded>=" + DbController.encodeSQLDate(DateStart) + ")"
                                                          + " and(h.dateadded<" + DbController.encodeSQLDate(DateEnd) + ")"
                                                          + " and((v.ExcludeFromAnalytics is null)or(v.ExcludeFromAnalytics=0))"
                                                          + " and((h.ExcludeFromAnalytics is null)or(h.ExcludeFromAnalytics=0))"
                                                          + "";
                                    if (!string.IsNullOrEmpty(PageTitle))
                                    {
                                        baseCriteria = baseCriteria + "and(h.pagetitle=" + DbController.encodeSQLText(PageTitle) + ")";
                                    }
                                    hint = 6;
                                    //
                                    // Total Page Views
                                    using (var csPageViews = new CsModel(core)) {
                                        sql = "select count(h.id) as cnt"
                                              + " from ccviewings h left join ccvisits v on h.visitid=v.id"
                                              + " where " + baseCriteria + " and (v.CookieSupport<>0)"
                                              + "";
                                        csPageViews.openSql(sql);
                                        if (csPageViews.ok())
                                        {
                                            PageViews = csPageViews.getInteger("cnt");
                                        }
                                    }
                                    //
                                    // Authenticated Visits
                                    //
                                    using (var csAuthPages = new CsModel(core)) {
                                        sql = "select count(h.id) as cnt"
                                              + " from ccviewings h left join ccvisits v on h.visitid=v.id"
                                              + " where " + baseCriteria + " and(v.CookieSupport<>0)"
                                              + " and(v.visitAuthenticated<>0)"
                                              + "";
                                        csAuthPages.openSql(sql);
                                        if (csAuthPages.ok())
                                        {
                                            AuthenticatedPageViews = csAuthPages.getInteger("cnt");
                                        }
                                    }
                                    //
                                    // No Cookie Page Views
                                    //
                                    using (var csNoCookie = new CsModel(core)) {
                                        sql = "select count(h.id) as NoCookiePageViews"
                                              + " from ccviewings h left join ccvisits v on h.visitid=v.id"
                                              + " where " + baseCriteria + " and((v.CookieSupport=0)or(v.CookieSupport is null))"
                                              + "";
                                        csNoCookie.openSql(sql);
                                        if (csNoCookie.ok())
                                        {
                                            NoCookiePageViews = csNoCookie.getInteger("NoCookiePageViews");
                                        }
                                    }
                                    //
                                    //
                                    // Mobile Visits
                                    using (var csMobileVisits = new CsModel(core)) {
                                        sql = "select count(h.id) as cnt"
                                              + " from ccviewings h left join ccvisits v on h.visitid=v.id"
                                              + " where " + baseCriteria + " and(v.CookieSupport<>0)"
                                              + " and(v.mobile<>0)"
                                              + "";
                                        csMobileVisits.openSql(sql);
                                        if (csMobileVisits.ok())
                                        {
                                            MobilePageViews = csMobileVisits.getInteger("cnt");
                                        }
                                    }
                                    //
                                    // Bot Visits
                                    using (var csBotVisits = new CsModel(core)) {
                                        sql = "select count(h.id) as cnt"
                                              + " from ccviewings h left join ccvisits v on h.visitid=v.id"
                                              + " where " + baseCriteria + " and(v.CookieSupport<>0)"
                                              + " and(v.bot<>0)"
                                              + "";
                                        csBotVisits.openSql(sql);
                                        if (csBotVisits.ok())
                                        {
                                            BotPageViews = csBotVisits.getInteger("cnt");
                                        }
                                    }
                                    //
                                    // Add or update the Visit Summary Record
                                    //
                                    using (var csPVS = new CsModel(core)) {
                                        if (!csPVS.open("Page View Summary", "(timeduration=" + HourDuration + ")and(DateNumber=" + DateNumber + ")and(TimeNumber=" + TimeNumber + ")and(pageid=" + PageId + ")and(pagetitle=" + DbController.encodeSQLText(PageTitle) + ")"))
                                        {
                                            csPVS.insert("Page View Summary");
                                        }
                                        //
                                        if (csPVS.ok())
                                        {
                                            hint = 11;
                                            string PageName = "";
                                            if (string.IsNullOrEmpty(PageTitle))
                                            {
                                                PageName = MetadataController.getRecordName(core, "page content", PageId);
                                                csPVS.set("name", HourDuration + " hr summary for " + DateTime.MinValue.AddDays(DateNumber) + " " + TimeNumber + ":00, " + PageName);
                                                csPVS.set("PageTitle", PageName);
                                            }
                                            else
                                            {
                                                csPVS.set("name", HourDuration + " hr summary for " + DateTime.MinValue.AddDays(DateNumber) + " " + TimeNumber + ":00, " + PageTitle);
                                                csPVS.set("PageTitle", PageTitle);
                                            }
                                            csPVS.set("DateNumber", DateNumber);
                                            csPVS.set("TimeNumber", TimeNumber);
                                            csPVS.set("TimeDuration", HourDuration);
                                            csPVS.set("PageViews", PageViews);
                                            csPVS.set("PageID", PageId);
                                            csPVS.set("AuthenticatedPageViews", AuthenticatedPageViews);
                                            csPVS.set("NoCookiePageViews", NoCookiePageViews);
                                            hint = 12;
                                            {
                                                csPVS.set("MobilePageViews", MobilePageViews);
                                                csPVS.set("BotPageViews", BotPageViews);
                                            }
                                        }
                                    }
                                    csPages.goNext();
                                }
                            }
                        }
                        PeriodDatePtr = PeriodDatePtr.AddHours(HourDuration);
                    }
                }
                //
                return;
            } catch (Exception ex) {
                LogController.logError(core, ex, "hint [" + hint + "]");
            }
        }
예제 #15
0
        //
        //====================================================================================================
        /// <summary>
        /// add a link alias to a page as the primary
        /// </summary>
        public static void addLinkAlias(CoreController core, string linkAlias, int pageId, string queryStringSuffix, bool overRideDuplicate, bool dupCausesWarning, ref string return_WarningMessage)
        {
            string hint = "";

            try {
                //
                LogController.logTrace(core, "addLinkAlias, enter, linkAlias [" + linkAlias + "], pageID [" + pageId + "], queryStringSuffix [" + queryStringSuffix + "], overRideDuplicate [" + overRideDuplicate + "], dupCausesWarning [" + dupCausesWarning + "]");
                //
                const string SafeStringLc   = "0123456789abcdefghijklmnopqrstuvwxyz-_/.";
                bool         AllowLinkAlias = core.siteProperties.getBoolean("allowLinkAlias", true);
                //
                string normalizedLinkAlias = linkAlias;
                if (!string.IsNullOrEmpty(normalizedLinkAlias))
                {
                    //
                    // remove nonsafe URL characters
                    string Src = normalizedLinkAlias.Replace('\t', ' ');
                    normalizedLinkAlias = "";
                    for (int srcPtr = 0; srcPtr < Src.Length; srcPtr++)
                    {
                        string TestChr = Src.Substring(srcPtr, 1).ToLowerInvariant();
                        if (!SafeStringLc.Contains(TestChr))
                        {
                            TestChr = "\t";
                        }
                        normalizedLinkAlias += TestChr;
                    }
                    int Ptr = 0;
                    while (normalizedLinkAlias.Contains("\t\t") && (Ptr < 100))
                    {
                        normalizedLinkAlias = GenericController.strReplace(normalizedLinkAlias, "\t\t", "\t");
                        Ptr = Ptr + 1;
                    }
                    if (normalizedLinkAlias.Substring(normalizedLinkAlias.Length - 1) == "\t")
                    {
                        normalizedLinkAlias = normalizedLinkAlias.left(normalizedLinkAlias.Length - 1);
                    }
                    if (normalizedLinkAlias.left(1) == "\t")
                    {
                        normalizedLinkAlias = normalizedLinkAlias.Substring(1);
                    }
                    normalizedLinkAlias = GenericController.strReplace(normalizedLinkAlias, "\t", "-");
                    if (!string.IsNullOrEmpty(normalizedLinkAlias))
                    {
                        if (normalizedLinkAlias.left(1) != "/")
                        {
                            normalizedLinkAlias = "/" + normalizedLinkAlias;
                        }
                        //
                        LogController.logTrace(core, "addLinkAlias, normalized normalizedLinkAlias [" + normalizedLinkAlias + "]");
                        //
                        // Make sure there is not a folder or page in the wwwroot that matches this Alias
                        //
                        if (GenericController.toLCase(normalizedLinkAlias) == GenericController.toLCase("/" + core.appConfig.name))
                        {
                            //
                            // This alias points to the cclib folder
                            //
                            if (AllowLinkAlias)
                            {
                                return_WarningMessage = ""
                                                        + "The Link Alias being created (" + normalizedLinkAlias + ") can not be used because there is a virtual directory in your website directory that already uses this name."
                                                        + " Please change it to ensure the Link Alias is unique. To set or change the Link Alias, use the Link Alias tab and select a name not used by another page.";
                            }
                        }
                        else if (GenericController.toLCase(normalizedLinkAlias) == "/cclib")
                        {
                            //
                            // This alias points to the cclib folder
                            //
                            if (AllowLinkAlias)
                            {
                                return_WarningMessage = ""
                                                        + "The Link Alias being created (" + normalizedLinkAlias + ") can not be used because there is a virtual directory in your website directory that already uses this name."
                                                        + " Please change it to ensure the Link Alias is unique. To set or change the Link Alias, use the Link Alias tab and select a name not used by another page.";
                            }
                        }
                        else if (core.wwwFiles.pathExists(core.appConfig.localWwwPath + "\\" + normalizedLinkAlias.Substring(1)))
                        {
                            //
                            // This alias points to a different link, call it an error
                            //
                            if (AllowLinkAlias)
                            {
                                return_WarningMessage = ""
                                                        + "The Link Alias being created (" + normalizedLinkAlias + ") can not be used because there is a folder in your website directory that already uses this name."
                                                        + " Please change it to ensure the Link Alias is unique. To set or change the Link Alias, use the Link Alias tab and select a name not used by another page.";
                            }
                        }
                        else
                        {
                            //
                            // Make sure there is one here for this
                            //
                            bool flushLinkAliasCache = false;
                            int  linkAliasId         = 0;
                            using (var csData = new CsModel(core)) {
                                csData.open("Link Aliases", "name=" + DbController.encodeSQLText(normalizedLinkAlias), "", false, 0, "Name,PageID,QueryStringSuffix");
                                if (!csData.ok())
                                {
                                    //
                                    LogController.logTrace(core, "addLinkAlias, not found in Db, add");
                                    //
                                    // Alias not found, create a Link Aliases
                                    //
                                    csData.close();
                                    csData.insert("Link Aliases");
                                    if (csData.ok())
                                    {
                                        csData.set("Name", normalizedLinkAlias);
                                        csData.set("Pageid", pageId);
                                        csData.set("QueryStringSuffix", queryStringSuffix);
                                        flushLinkAliasCache = true;
                                    }
                                }
                                else
                                {
                                    int    recordPageId = csData.getInteger("pageID");
                                    string recordQss    = csData.getText("QueryStringSuffix").ToLowerInvariant();
                                    //
                                    LogController.logTrace(core, "addLinkAlias, linkalias record found by its name, record recordPageId [" + recordPageId + "], record QueryStringSuffix [" + recordQss + "]");
                                    //
                                    // Alias found, verify the pageid & QueryStringSuffix
                                    //
                                    int  CurrentLinkAliasId = 0;
                                    bool resaveLinkAlias    = false;
                                    if ((recordQss == queryStringSuffix.ToLowerInvariant()) && (pageId == recordPageId))
                                    {
                                        CurrentLinkAliasId = csData.getInteger("id");
                                        //
                                        LogController.logTrace(core, "addLinkAlias, linkalias matches name, pageid, and querystring of linkalias [" + CurrentLinkAliasId + "]");
                                        //
                                        // it maches a current entry for this link alias, if the current entry is not the highest number id,
                                        //   remove it and add this one
                                        //
                                        string sql = "select top 1 id from ccLinkAliases where (pageid=" + recordPageId + ")and(QueryStringSuffix=" + DbController.encodeSQLText(queryStringSuffix) + ") order by id desc";
                                        using (var CS3 = new CsModel(core)) {
                                            CS3.openSql(sql);
                                            if (CS3.ok())
                                            {
                                                resaveLinkAlias = (CurrentLinkAliasId != CS3.getInteger("id"));
                                            }
                                        }
                                        if (resaveLinkAlias)
                                        {
                                            //
                                            LogController.logTrace(core, "addLinkAlias, another link alias matches this pageId and QS. Move this to the top position");
                                            //
                                            core.db.executeNonQuery("delete from ccLinkAliases where id=" + CurrentLinkAliasId);
                                            using (var CS3 = new CsModel(core)) {
                                                CS3.insert("Link Aliases");
                                                if (CS3.ok())
                                                {
                                                    CS3.set("Name", normalizedLinkAlias);
                                                    CS3.set("Pageid", pageId);
                                                    CS3.set("QueryStringSuffix", queryStringSuffix);
                                                }
                                            }
                                        }
                                    }
                                    else
                                    {
                                        //
                                        LogController.logTrace(core, "addLinkAlias, linkalias matches name, but pageid and querystring are different. Add this a newest linkalias");
                                        //
                                        // link alias matches, but id/qs does not -- this is either a change, or a duplicate that needs to be blocked
                                        //
                                        if (overRideDuplicate)
                                        {
                                            //
                                            LogController.logTrace(core, "addLinkAlias, overRideDuplicate true, change the Link Alias to the new link");
                                            //
                                            // change the Link Alias to the new link
                                            csData.set("Pageid", pageId);
                                            csData.set("QueryStringSuffix", queryStringSuffix);
                                            flushLinkAliasCache = true;
                                        }
                                        else if (dupCausesWarning)
                                        {
                                            //
                                            LogController.logTrace(core, "addLinkAlias, overRideDuplicate false, dupCausesWarning true, just return user warning if this is from admin");
                                            //
                                            if (recordPageId == 0)
                                            {
                                                int PageContentCId = Models.Domain.ContentMetadataModel.getContentId(core, "Page Content");
                                                return_WarningMessage = ""
                                                                        + "This page has been saved, but the Link Alias could not be created (" + normalizedLinkAlias + ") because it is already in use for another page."
                                                                        + " To use Link Aliasing (friendly page names) for this page, the Link Alias value must be unique on this site. To set or change the Link Alias, clicke the Link Alias tab and select a name not used by another page or a folder in your website.";
                                            }
                                            else
                                            {
                                                int PageContentCid = Models.Domain.ContentMetadataModel.getContentId(core, "Page Content");
                                                return_WarningMessage = ""
                                                                        + "This page has been saved, but the Link Alias could not be created (" + normalizedLinkAlias + ") because it is already in use for another page (<a href=\"?af=4&cid=" + PageContentCid + "&id=" + recordPageId + "\">edit</a>)."
                                                                        + " To use Link Aliasing (friendly page names) for this page, the Link Alias value must be unique. To set or change the Link Alias, click the Link Alias tab and select a name not used by another page or a folder in your website.";
                                            }
                                        }
                                    }
                                }
                                linkAliasId = csData.getInteger("id");
                                csData.close();
                            }
                            if (flushLinkAliasCache)
                            {
                                //
                                // -- invalidate all linkAlias
                                core.cache.invalidateDbRecord(linkAliasId, LinkAliasModel.tableMetadata.tableNameLower);
                                //
                                // -- invalidate routemap
                                Models.Domain.RouteMapModel.invalidateCache(core);
                                core.routeMapCacheClear();
                            }
                        }
                    }
                }
                //
                LogController.logTrace(core, "addLinkAlias, exit");
                //
            } catch (Exception ex) {
                LogController.logError(core, ex, "addLinkAlias exception, hint [" + hint + "]");
                throw;
            }
        }
 //
 //====================================================================================================
 /// <summary>
 /// when breaking changes are required for data, update them here
 /// </summary>
 /// <param name="core"></param>
 /// <param name="DataBuildVersion"></param>
 public static void migrateData(CoreController core, string DataBuildVersion, string logPrefix)
 {
     try {
         CPClass cp = core.cpParent;
         //
         // -- Roll the style sheet cache if it is setup
         core.siteProperties.setProperty("StylesheetSerialNumber", (-1).ToString());
         //
         // -- verify ID is primary key on all tables with an id
         foreach (TableModel table in DbBaseModel.createList <TableModel>(cp))
         {
             if (!string.IsNullOrWhiteSpace(table.name))
             {
                 bool tableHasId = false;
                 {
                     //
                     // -- verify table as an id field
                     string    sql = "SELECT name FROM sys.columns WHERE Name = N'ID' AND Object_ID = Object_ID(N'ccmembers')";
                     DataTable dt  = cp.Db.ExecuteQuery(sql);
                     if (dt != null)
                     {
                         tableHasId = !dt.Rows.Equals(0);
                     }
                 }
                 if (tableHasId)
                 {
                     //
                     // -- table has id field, make sure it is primary key
                     string sql = ""
                                  + " select Col.Column_Name"
                                  + " from INFORMATION_SCHEMA.TABLE_CONSTRAINTS Tab, INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE Col"
                                  + " where (Col.Constraint_Name = Tab.Constraint_Name) AND (Col.Table_Name = Tab.Table_Name) AND (Constraint_Type = 'PRIMARY KEY') AND (Col.Table_Name = '" + table.name + "')";
                     bool idPrimaryKeyFound = false;
                     foreach (DataRow dr in core.db.executeQuery(sql).Rows)
                     {
                         if (GenericController.encodeText(dr["Column_Name"]).ToLower().Equals("id"))
                         {
                             idPrimaryKeyFound = true;
                             break;
                         }
                     }
                     if (!idPrimaryKeyFound)
                     {
                         try {
                             core.db.executeNonQuery("alter table " + table.name + " add primary key (ID)");
                         } catch (Exception ex) {
                             LogController.logError(core, ex, "Content Table [" + table.name + "] does not include column ID. Exception happened while adding column and setting it primarykey.");
                         }
                     }
                 }
             }
         }
         //
         // -- continue only if a previous build exists
         if (!string.IsNullOrEmpty(DataBuildVersion))
         {
             //
             // -- 4.1 to 5 conversions
             if (GenericController.versionIsOlder(DataBuildVersion, "4.1"))
             {
                 //
                 // -- create Data Migration Assets collection
                 var migrationCollection = DbBaseModel.createByUniqueName <AddonCollectionModel>(cp, "Data Migration Assets");
                 if (migrationCollection == null)
                 {
                     migrationCollection      = DbBaseModel.addDefault <AddonCollectionModel>(cp);
                     migrationCollection.name = "Data Migration Assets";
                 }
                 //
                 // -- remove all addon content fieldtype rules
                 Contensive.Models.Db.DbBaseModel.deleteRows <Contensive.Models.Db.AddonContentFieldTypeRulesModel>(cp, "(1=1)");
                 //
                 // -- delete /admin www subfolder
                 core.wwwFiles.deleteFolder("admin");
                 //
                 // -- delete .asp and .php files
                 foreach (BaseClasses.CPFileSystemBaseClass.FileDetail file in core.wwwFiles.getFileList(""))
                 {
                     if (file == null)
                     {
                         continue;
                     }
                     if (string.IsNullOrWhiteSpace(file.Name))
                     {
                         continue;
                     }
                     if (file.Name.Length < 4)
                     {
                         continue;
                     }
                     string extension = System.IO.Path.GetExtension(file.Name).ToLower(CultureInfo.InvariantCulture);
                     if ((extension == ".php") || (extension == ".asp"))
                     {
                         core.wwwFiles.deleteFile(file.Name);
                     }
                 }
                 //
                 // -- create www /cclib folder and copy in legacy resources
                 core.programFiles.copyFile("cclib.zip", "cclib.zip", core.wwwFiles);
                 core.wwwFiles.unzipFile("cclib.zip");
                 //
                 // -- remove all the old menu entries and leave the navigation entries
                 var navContent = DbBaseModel.createByUniqueName <ContentModel>(cp, Contensive.Models.Db.NavigatorEntryModel.tableMetadata.contentName);
                 if (navContent != null)
                 {
                     core.db.executeNonQuery("delete from ccMenuEntries where ((contentcontrolid<>0)and(contentcontrolid<>" + navContent.id + ")and(contentcontrolid is not null))");
                 }
                 //
                 // -- reinstall newest font-awesome collection
                 string returnErrorMessage       = "";
                 var    context                  = new Stack <string>();
                 var    nonCritialErrorList      = new List <string>();
                 var    collectionsInstalledList = new List <string>();
                 CollectionLibraryController.installCollectionFromLibrary(core, false, context, Constants.fontAwesomeCollectionGuid, ref returnErrorMessage, false, true, ref nonCritialErrorList, logPrefix, ref collectionsInstalledList);
                 //
                 // -- reinstall newest redactor collection
                 returnErrorMessage       = "";
                 context                  = new Stack <string>();
                 nonCritialErrorList      = new List <string>();
                 collectionsInstalledList = new List <string>();
                 CollectionLibraryController.installCollectionFromLibrary(core, false, context, Constants.redactorCollectionGuid, ref returnErrorMessage, false, true, ref nonCritialErrorList, logPrefix, ref collectionsInstalledList);
                 //
                 // -- addons with active-x -- remove programid and add script code that logs error
                 string newCode = ""
                                  + "function m"
                                  + " ' + CHAR(13)+CHAR(10) + ' \ncp.Site.ErrorReport(\"deprecated active-X add-on executed [#\" & cp.addon.id & \", \" & cp.addon.name & \"]\")"
                                  + " ' + CHAR(13)+CHAR(10) + ' \nend function"
                                  + "";
                 string sql = "update ccaggregatefunctions set help='Legacy activeX: ' + objectprogramId, objectprogramId=null, ScriptingCode='" + newCode + "' where (ObjectProgramID is not null)";
                 LogController.logInfo(core, "MigrateData, removing activex addons, adding exception logging, sql [" + sql + "]");
                 core.db.executeNonQuery(sql);
                 //
                 // -- create page menus from section menus
                 using (var cs = new CsModel(core)) {
                     sql = "select m.name as menuName, m.id as menuId, p.name as pageName, p.id as pageId, s.name as sectionName, m.*"
                           + " from ccDynamicMenus m"
                           + " left join ccDynamicMenuSectionRules r on r.DynamicMenuId = m.id"
                           + " left join ccSections s on s.id = r.SectionID"
                           + " left join ccPageContent p on p.id = s.RootPageID"
                           + " where (p.id is not null)and(s.active>0)"
                           + " order by m.id, s.sortorder,s.id";
                     if (cs.openSql(sql))
                     {
                         int sortOrder = 0;
                         do
                         {
                             string menuName = cs.getText("menuName");
                             if (!string.IsNullOrWhiteSpace(menuName))
                             {
                                 var menu = DbBaseModel.createByUniqueName <MenuModel>(cp, menuName);
                                 if (menu == null)
                                 {
                                     menu      = DbBaseModel.addEmpty <MenuModel>(cp);
                                     menu.name = menuName;
                                     try {
                                         menu.classItemActive = cs.getText("classItemActive");
                                         menu.classItemFirst  = cs.getText("classItemFirst");
                                         menu.classItemHover  = cs.getText("classItemHover");
                                         menu.classItemLast   = cs.getText("classItemLast");
                                         menu.classTierAnchor = cs.getText("classTierItem");
                                         menu.classTierItem   = cs.getText("classTierItem");
                                         menu.classTierList   = cs.getText("classTierList");
                                         menu.classTopAnchor  = cs.getText("classTopItem");
                                         menu.classTopItem    = cs.getText("classTopItem");
                                         menu.classTopList    = cs.getText("classTopList");
                                         menu.classTopWrapper = cs.getText("classTopWrapper");
                                     } catch (Exception ex) {
                                         LogController.logError(core, ex, "migrateData error populating menu from dynamic menu.");
                                     }
                                     menu.save(cp);
                                 }
                                 //
                                 // -- set the root page's menuHeadline to the section name
                                 var page = DbBaseModel.create <PageContentModel>(cp, cs.getInteger("pageId"));
                                 if (page != null)
                                 {
                                     page.menuHeadline = cs.getText("sectionName");
                                     page.save(cp);
                                     //
                                     // -- create a menu-page rule to attach this page to the menu in the current order
                                     var menuPageRule = DbBaseModel.addEmpty <MenuPageRuleModel>(cp);
                                     if (menuPageRule != null)
                                     {
                                         menuPageRule.name      = "Created from v4.1 menu sections " + core.dateTimeNowMockable.ToString();
                                         menuPageRule.pageId    = page.id;
                                         menuPageRule.menuId    = menu.id;
                                         menuPageRule.active    = true;
                                         menuPageRule.sortOrder = sortOrder.ToString().PadLeft(4, '0');
                                         menuPageRule.save(cp);
                                         sortOrder += 10;
                                     }
                                 }
                             }
                             cs.goNext();
                         } while (cs.ok());
                     }
                 }
                 //
                 // -- create a theme addon for each template for styles and meta content
                 using (var csTemplate = cp.CSNew()) {
                     if (csTemplate.Open("page templates"))
                     {
                         do
                         {
                             int    templateId           = csTemplate.GetInteger("id");
                             string templateStylePrepend = "";
                             string templateStyles       = csTemplate.GetText("StylesFilename");
                             //
                             // -- add shared styles to the template stylesheet
                             using (var csStyleRule = cp.CSNew()) {
                                 if (csStyleRule.Open("shared styles template rules", "(TemplateID=" + templateId + ")"))
                                 {
                                     do
                                     {
                                         int sharedStyleId = csStyleRule.GetInteger("styleid");
                                         using (var csStyle = cp.CSNew()) {
                                             if (csStyleRule.Open("shared styles", "(id=" + sharedStyleId + ")"))
                                             {
                                                 //
                                                 // -- prepend lines beginning with @ t
                                                 string styles = csStyleRule.GetText("StyleFilename");
                                                 if (!string.IsNullOrWhiteSpace(styles))
                                                 {
                                                     //
                                                     // -- trim off leading spaces, newlines, comments
                                                     styles = styles.Trim();
                                                     while (!string.IsNullOrWhiteSpace(styles) && styles.Substring(0, 1).Equals("@"))
                                                     {
                                                         if (styles.IndexOf(Environment.NewLine) >= 0)
                                                         {
                                                             templateStylePrepend += styles.Substring(0, styles.IndexOf(Environment.NewLine));
                                                             styles = styles.Substring(styles.IndexOf(Environment.NewLine) + 1).Trim();
                                                         }
                                                         else
                                                         {
                                                             templateStylePrepend += styles;
                                                             styles = string.Empty;
                                                         }
                                                     }
                                                     ;
                                                     templateStyles += Environment.NewLine + styles;
                                                 }
                                             }
                                         }
                                         csStyleRule.GoNext();
                                     } while (csStyleRule.OK());
                                 }
                             }
                             //
                             // -- create an addon
                             var themeAddon = DbBaseModel.addDefault <AddonModel>(cp);
                             themeAddon.name                   = "Theme assets for template " + csTemplate.GetText("name");
                             themeAddon.otherHeadTags          = csTemplate.GetText("otherheadtags");
                             themeAddon.javaScriptBodyEnd      = csTemplate.GetText("jsendbody");
                             themeAddon.stylesFilename.content = templateStylePrepend + Environment.NewLine + templateStyles;
                             themeAddon.collectionId           = migrationCollection.id;
                             themeAddon.save(cp);
                             //
                             // -- create an addon template rule to set dependency
                             var rule = DbBaseModel.addEmpty <AddonTemplateRuleModel>(cp);
                             rule.addonId    = themeAddon.id;
                             rule.templateId = templateId;
                             rule.save(cp);
                             //
                             csTemplate.GoNext();
                         } while (csTemplate.OK());
                     }
                 }
                 //
                 // -- reset the html minify so it is easier to resolve other issues
                 core.siteProperties.setProperty("ALLOW HTML MINIFY", false);
                 //
                 // -- remove contentcategoryid from all edit page
                 cp.Db.ExecuteNonQuery("update ccfields set Authorable=0 where name='contentcategoryid'");
                 cp.Db.ExecuteNonQuery("update ccfields set Authorable=0 where name='editsourceid'");
                 cp.Db.ExecuteNonQuery("update ccfields set Authorable=0 where name='editarchive'");
                 cp.Db.ExecuteNonQuery("update ccfields set Authorable=0 where name='editblank'");
                 //
                 // -- remove legacy workflow fields
                 UpgradeController.dropLegacyWorkflowField(core, "editsourceid");
                 cp.Db.ExecuteNonQuery("delete from ccfields where name='editsourceid'");
                 //
                 UpgradeController.dropLegacyWorkflowField(core, "editblank");
                 cp.Db.ExecuteNonQuery("delete from ccfields where name='editblank'");
                 //
                 UpgradeController.dropLegacyWorkflowField(core, "editarchive");
                 cp.Db.ExecuteNonQuery("delete from ccfields where name='editarchive'");
                 //
                 UpgradeController.dropLegacyWorkflowField(core, "contentcategoryid");
                 cp.Db.ExecuteNonQuery("delete from ccfields where name='contentcategoryid'");
                 //
                 //
                 // -- end of 4.1 to 5 conversion
             }
             //
             // -- 5.19.1223 conversion -- render AddonList no copyFilename
             if (GenericController.versionIsOlder(DataBuildVersion, "5.19.1223"))
             {
                 //
                 // -- verify design block installation
                 string returnUserError = "";
                 if (!cp.Db.IsTable("dbtext"))
                 {
                     if (!cp.Addon.InstallCollectionFromLibrary(Constants.designBlockCollectionGuid, ref returnUserError))
                     {
                         throw new Exception("Error installing Design Blocks, required for data upgrade. " + returnUserError);
                     }
                 }
                 //
                 // -- add a text block and childPageList to every page without an addonlist
                 foreach (var page in DbBaseModel.createList <PageContentModel>(cp, "(addonList is null)"))
                 {
                     convertPageContentToAddonList(core, page);
                 }
                 core.siteProperties.setProperty("PageController Render Legacy Copy", false);
             }
             //
             // -- 5.2005.9.4 conversion -- collections incorrectly marked not-updateable - mark all except themes (templates)
             if (GenericController.versionIsOlder(DataBuildVersion, "5.2005.9.4"))
             {
                 //
                 // --
                 cp.Db.ExecuteNonQuery("update ccaddoncollections set updatable=1 where name not like '%theme%'");
             }
             //
             // -- 5.2005.19.1 conversion -- rename site property EmailUrlRootRelativePrefix to LocalFileModeProtocolDomain
             if (GenericController.versionIsOlder(DataBuildVersion, "5.2005.19.1"))
             {
                 //
                 // --
                 if (string.IsNullOrWhiteSpace(cp.Site.GetText("webAddressProtocolDomain")))
                 {
                     cp.Site.SetProperty("webAddressProtocolDomain", cp.Site.GetText("EmailUrlRootRelativePrefix"));
                 }
             }
             //
             // -- delete legacy corehelp collection. Created with fields that have only field name, legacy install layed collections over the application collection
             //    new install loads fields directly from collection, which coreHelp then marks all fields inactive.
             core.db.delete("{6e905db1-d3f0-40af-aac4-4bd78e680fae}", "ccaddoncollections");
         }
         // -- Reload
         core.cache.invalidateAll();
         core.clearMetaData();
     } catch (Exception ex) {
         LogController.logError(core, ex);
         throw;
     }
 }
예제 #17
0
        //
        //====================================================================================================
        //
        public static string get(CoreController core)
        {
            string tempGetForm_QuickStats = null;

            try {
                string sql        = null;
                string RowColor   = null;
                string Panel      = null;
                int    VisitID    = 0;
                int    VisitCount = 0;
                double PageCount  = 0;
                StringBuilderLegacyController Stream = new StringBuilderLegacyController();
                //
                // --- Start a form to make a refresh button
                Stream.add(core.html.getPanelButtons(ButtonCancel + "," + ButtonRefresh));
                Stream.add("<input TYPE=\"hidden\" NAME=\"asf\" VALUE=\"" + AdminFormQuickStats + "\">");
                Stream.add(core.html.getPanel(" "));
                //

                // --- Indented part (Title Area plus page)
                //
                Stream.add("<table border=\"0\" cellpadding=\"20\" cellspacing=\"0\" width=\"100%\"><tr><td>" + SpanClassAdminNormal);
                Stream.add("<h1>Real-Time Activity Report</h1>");
                //
                // --- set column width
                //
                Stream.add("<h2>Visits Today</h2>");
                Stream.add("<table border=\"0\" cellpadding=\"3\" cellspacing=\"0\" width=\"100%\" style=\"background-color:white;border-top:1px solid #888;\">");
                //
                // ----- All Visits Today
                //
                using (var csData = new CsModel(core)) {
                    sql = "SELECT Count(ccVisits.ID) AS VisitCount, Avg(ccVisits.PageVisits) AS PageCount FROM ccVisits WHERE ((ccVisits.StartTime)>" + DbController.encodeSQLDate(core.doc.profileStartTime.Date) + ");";
                    csData.openSql(sql);
                    if (csData.ok())
                    {
                        VisitCount = csData.getInteger("VisitCount");
                        PageCount  = csData.getNumber("pageCount");
                        Stream.add("<tr>");
                        Stream.add("<td style=\"border-bottom:1px solid #888;\" valign=top>" + SpanClassAdminNormal + "All Visits</span></td>");
                        Stream.add("<td style=\"width:150px;border-bottom:1px solid #888;\" valign=top>" + SpanClassAdminNormal + "<a target=\"_blank\" href=\"/" + HtmlController.encodeHtml(core.appConfig.adminRoute + "?" + rnAdminForm + "=" + AdminFormReports + "&rid=3&DateFrom=" + core.doc.profileStartTime + "&DateTo=" + core.doc.profileStartTime.ToShortDateString()) + "\">" + VisitCount + "</A>, " + string.Format("{0:N2}", PageCount) + " pages/visit.</span></td>");
                        Stream.add("<td style=\"border-bottom:1px solid #888;\" valign=top>" + SpanClassAdminNormal + "This includes all visitors to the website, including guests, bots and administrators. Pages/visit includes page hits and not ajax or remote method hits.</span></td>");
                        Stream.add("</tr>");
                    }
                }
                //
                // ----- Non-Bot Visits Today
                //
                using (var csData = new CsModel(core)) {
                    sql = "SELECT Count(ccVisits.ID) AS VisitCount, Avg(ccVisits.PageVisits) AS PageCount FROM ccVisits WHERE (ccVisits.CookieSupport=1)and((ccVisits.StartTime)>" + DbController.encodeSQLDate(core.doc.profileStartTime.Date) + ");";
                    csData.openSql(sql);
                    if (csData.ok())
                    {
                        VisitCount = csData.getInteger("VisitCount");
                        PageCount  = csData.getNumber("pageCount");
                        Stream.add("<tr>");
                        Stream.add("<td style=\"border-bottom:1px solid #888;\" valign=top>" + SpanClassAdminNormal + "Non-bot Visits</span></td>");
                        Stream.add("<td style=\"border-bottom:1px solid #888;\" valign=top>" + SpanClassAdminNormal + "<a target=\"_blank\" href=\"/" + HtmlController.encodeHtml(core.appConfig.adminRoute + "?" + rnAdminForm + "=" + AdminFormReports + "&rid=3&DateFrom=" + core.doc.profileStartTime.ToShortDateString() + "&DateTo=" + core.doc.profileStartTime.ToShortDateString()) + "\">" + VisitCount + "</A>, " + string.Format("{0:N2}", PageCount) + " pages/visit.</span></td>");
                        Stream.add("<td style=\"border-bottom:1px solid #888;\" valign=top>" + SpanClassAdminNormal + "This excludes hits from visitors identified as bots. Pages/visit includes page hits and not ajax or remote method hits.</span></td>");
                        Stream.add("</tr>");
                    }
                }
                //
                // ----- Visits Today by new visitors
                //
                using (var csData = new CsModel(core)) {
                    sql = "SELECT Count(ccVisits.ID) AS VisitCount, Avg(ccVisits.PageVisits) AS PageCount FROM ccVisits WHERE (ccVisits.CookieSupport=1)and(ccVisits.StartTime>" + DbController.encodeSQLDate(core.doc.profileStartTime.Date) + ")AND(ccVisits.VisitorNew<>0);";
                    csData.openSql(sql);
                    if (csData.ok())
                    {
                        VisitCount = csData.getInteger("VisitCount");
                        PageCount  = csData.getNumber("pageCount");
                        Stream.add("<tr>");
                        Stream.add("<td style=\"border-bottom:1px solid #888;\" valign=top>" + SpanClassAdminNormal + "Visits by New Visitors</span></td>");
                        Stream.add("<td style=\"border-bottom:1px solid #888;\" valign=top>" + SpanClassAdminNormal + "<a target=\"_blank\" href=\"/" + HtmlController.encodeHtml(core.appConfig.adminRoute + "?" + rnAdminForm + "=" + AdminFormReports + "&rid=3&ExcludeOldVisitors=1&DateFrom=" + core.doc.profileStartTime.ToShortDateString() + "&DateTo=" + core.doc.profileStartTime.ToShortDateString()) + "\">" + VisitCount + "</A>, " + string.Format("{0:N2}", PageCount) + " pages/visit.</span></td>");
                        Stream.add("<td style=\"border-bottom:1px solid #888;\" valign=top>" + SpanClassAdminNormal + "This includes only new visitors not identified as bots. Pages/visit includes page hits and not ajax or remote method hits.</span></td>");
                        Stream.add("</tr>");
                    }
                    csData.close();
                }
                //
                Stream.add("</table>");
                //
                // ----- Visits currently online
                //
                {
                    Panel = "";
                    Stream.add("<h2>Current Visits</h2>");
                    using (var csData = new CsModel(core)) {
                        sql = "SELECT ccVisits.HTTP_REFERER as referer,ccVisits.remote_addr as Remote_Addr, ccVisits.LastVisitTime as LastVisitTime, ccVisits.PageVisits as PageVisits, ccMembers.Name as MemberName, ccVisits.ID as VisitID, ccMembers.ID as MemberID"
                              + " FROM ccVisits LEFT JOIN ccMembers ON ccVisits.memberId = ccMembers.ID"
                              + " WHERE (((ccVisits.LastVisitTime)>" + DbController.encodeSQLDate(core.doc.profileStartTime.AddHours(-1)) + "))"
                              + " ORDER BY ccVisits.LastVisitTime DESC;";
                        csData.openSql(sql);
                        if (csData.ok())
                        {
                            Panel    = Panel + "<table width=\"100%\" border=\"0\" cellspacing=\"1\" cellpadding=\"2\">";
                            Panel    = Panel + "<tr bgcolor=\"#B0B0B0\">";
                            Panel    = Panel + "<td width=\"20%\" align=\"left\">" + SpanClassAdminNormal + "User</td>";
                            Panel    = Panel + "<td width=\"20%\" align=\"left\">" + SpanClassAdminNormal + "IP&nbsp;Address</td>";
                            Panel    = Panel + "<td width=\"20%\" align=\"left\">" + SpanClassAdminNormal + "Last&nbsp;Page&nbsp;Hit</td>";
                            Panel    = Panel + "<td width=\"10%\" align=\"right\">" + SpanClassAdminNormal + "Page&nbsp;Hits</td>";
                            Panel    = Panel + "<td width=\"10%\" align=\"right\">" + SpanClassAdminNormal + "Visit</td>";
                            Panel    = Panel + "<td width=\"30%\" align=\"left\">" + SpanClassAdminNormal + "Referer</td>";
                            Panel    = Panel + "</tr>";
                            RowColor = "ccPanelRowEven";
                            while (csData.ok())
                            {
                                VisitID = csData.getInteger("VisitID");
                                Panel   = Panel + "<tr class=\"" + RowColor + "\">";
                                Panel   = Panel + "<td align=\"left\">" + SpanClassAdminNormal + "<a target=\"_blank\" href=\"/" + HtmlController.encodeHtml(core.appConfig.adminRoute + "?" + rnAdminForm + "=" + AdminFormReports + "&rid=16&MemberID=" + csData.getInteger("MemberID")) + "\">" + csData.getText("MemberName") + "</A></span></td>";
                                Panel   = Panel + "<td align=\"left\">" + SpanClassAdminNormal + csData.getText("Remote_Addr") + "</span></td>";
                                Panel   = Panel + "<td align=\"left\">" + SpanClassAdminNormal + csData.getDate("LastVisitTime").ToString("") + "</span></td>";
                                Panel   = Panel + "<td align=\"right\">" + SpanClassAdminNormal + "<a target=\"_blank\" href=\"/" + core.appConfig.adminRoute + "?" + rnAdminForm + "=" + AdminFormReports + "&rid=10&VisitID=" + VisitID + "\">" + csData.getText("PageVisits") + "</A></span></td>";
                                Panel   = Panel + "<td align=\"right\">" + SpanClassAdminNormal + "<a target=\"_blank\" href=\"/" + core.appConfig.adminRoute + "?" + rnAdminForm + "=" + AdminFormReports + "&rid=17&VisitID=" + VisitID + "\">" + VisitID + "</A></span></td>";
                                Panel   = Panel + "<td align=\"left\">" + SpanClassAdminNormal + "&nbsp;" + csData.getText("referer") + "</span></td>";
                                Panel   = Panel + "</tr>";
                                if (RowColor == "ccPanelRowEven")
                                {
                                    RowColor = "ccPanelRowOdd";
                                }
                                else
                                {
                                    RowColor = "ccPanelRowEven";
                                }
                                csData.goNext();
                            }
                            Panel = Panel + "</table>";
                        }
                        csData.close();
                    }
                    Stream.add(core.html.getPanel(Panel, "ccPanel", "ccPanelShadow", "ccPanelHilite", "100%", 0));
                }
                Stream.add("</td></tr></table>");
                //Stream.Add(htmlController.form_end());
                //
                tempGetForm_QuickStats = HtmlController.form(core, Stream.text);
                core.html.addTitle("Quick Stats");
                return(tempGetForm_QuickStats);
                //
                // ----- Error Trap
                //
            } catch (Exception ex) {
                LogController.logError(core, ex);
            }
            return(tempGetForm_QuickStats);
        }
예제 #18
0
        //
        //====================================================================================================
        /// <summary>
        /// Checks if the member is a content manager for the specific content, Which includes transversing up the tree to find the next rule that applies. Member must be checked for authenticated and main_IsAdmin already
        /// </summary>
        /// <param name="core"></param>
        /// <param name="contentId"></param>
        /// <param name="returnAllowEdit"></param>
        /// <param name="returnAllowAdd"></param>
        /// <param name="returnAllowDelete"></param>
        /// <param name="usedContentIdList"></param>
        //========================================================================
        //
        private static UserContentPermissions getUserAuthoringPermissions_ContentManager(CoreController core, ContentMetadataModel cdef, List <int> usedContentIdList)
        {
            var result = new UserContentPermissions {
                allowAdd    = false,
                allowDelete = false,
                allowEdit   = false,
                allowSave   = false
            };

            try {
                if (usedContentIdList.Contains(cdef.id))
                {
                    //
                    // failed usedContentIdList test, this content id was in the child path
                    //
                    throw new ArgumentException("ContentID [" + cdef.id + "] was found to be in it's own parentid path.");
                }
                else if (cdef.id < 1)
                {
                    //
                    // ----- not a valid contentname
                    //
                }
                else if (core.doc.contentAccessRights_NotList.Contains(cdef.id))
                {
                    //
                    // ----- was previously found to not be a Content Manager
                    //
                }
                else if (core.doc.contentAccessRights_List.Contains(cdef.id))
                {
                    //
                    // ----- was previously found to be a Content Manager
                    //
                    result.allowEdit   = true;
                    result.allowSave   = true;
                    result.allowAdd    = core.doc.contentAccessRights_AllowAddList.Contains(cdef.id);
                    result.allowDelete = core.doc.contentAccessRights_AllowDeleteList.Contains(cdef.id);
                }
                else
                {
                    //
                    // ----- Must test it
                    //
                    string SQL = "SELECT ccGroupRules.ContentID,allowAdd,allowDelete"
                                 + " FROM ccGroupRules RIGHT JOIN ccMemberRules ON ccGroupRules.GroupId = ccMemberRules.GroupID"
                                 + " WHERE ("
                                 + " (ccMemberRules.memberId=" + DbController.encodeSQLNumber(core.session.user.id) + ")"
                                 + " AND(ccMemberRules.active<>0)"
                                 + " AND(ccGroupRules.active<>0)"
                                 + " AND(ccGroupRules.ContentID=" + cdef.id + ")"
                                 + " AND((ccMemberRules.DateExpires is null)OR(ccMemberRules.DateExpires>" + DbController.encodeSQLDate(core.doc.profileStartTime) + "))"
                                 + ");";
                    using (var csData = new CsModel(core)) {
                        csData.openSql(SQL);
                        if (csData.ok())
                        {
                            result.allowEdit   = true;
                            result.allowSave   = true;
                            result.allowAdd    = csData.getBoolean("allowAdd");
                            result.allowDelete = csData.getBoolean("allowDelete");
                        }
                    }
                    //
                    if (!result.allowEdit)
                    {
                        //
                        // ----- Not a content manager for this one, check the parent
                        if (cdef.parentId > 0)
                        {
                            var parentCdef = ContentMetadataModel.create(core, cdef.parentId);
                            usedContentIdList.Add(cdef.id);
                            getUserAuthoringPermissions_ContentManager(core, cdef, usedContentIdList);
                        }
                    }
                    if (result.allowEdit)
                    {
                        //
                        // ----- Was found to be true
                        //
                        core.doc.contentAccessRights_List.Add(cdef.id);
                        if (result.allowEdit)
                        {
                            core.doc.contentAccessRights_AllowAddList.Add(cdef.id);
                        }
                        if (result.allowDelete)
                        {
                            core.doc.contentAccessRights_AllowDeleteList.Add(cdef.id);
                        }
                    }
                    else
                    {
                        //
                        // ----- Was found to be false
                        //
                        core.doc.contentAccessRights_NotList.Add(cdef.id);
                    }
                }
            } catch (Exception ex) {
                LogController.logError(core, ex);
                throw;
            }
            return(result);
        }
        //=============================================================================
        //   Print the manual query form
        //=============================================================================
        //
        public static string get(CoreController core)
        {
            string result = null;

            try {
                //
                int    TableColSpan = 0;
                bool   TableEvenRow = false;
                string SQL          = null;
                string TableName    = null;
                string ButtonList;
                //
                ButtonList = ButtonCancel;
                result     = AdminUIController.getHeaderTitleDescription("Get Content Database Schema", "This tool displays all tables and fields required for the current Content Defintions.");
                //
                TableColSpan = 3;
                result      += HtmlController.tableStart(2, 0, 0);
                SQL          = "SELECT DISTINCT ccTables.Name as TableName, ccFields.Name as FieldName, ccFieldTypes.Name as FieldType"
                               + " FROM ((ccContent LEFT JOIN ccTables ON ccContent.ContentTableId = ccTables.ID) LEFT JOIN ccFields ON ccContent.Id = ccFields.ContentID) LEFT JOIN ccFieldTypes ON ccFields.Type = ccFieldTypes.ID"
                               + " ORDER BY ccTables.Name, ccFields.Name;";
                using (var csData = new CsModel(core)) {
                    csData.openSql(SQL);
                    TableName = "";
                    while (csData.ok())
                    {
                        if (TableName != csData.getText("TableName"))
                        {
                            TableName = csData.getText("TableName");
                            result   += HtmlController.tableRow("<B>" + TableName + "</b>", TableColSpan, TableEvenRow);
                        }
                        result      += HtmlController.tableRowStart();
                        result      += HtmlController.td("&nbsp;", "", 0, TableEvenRow);
                        result      += HtmlController.td(csData.getText("FieldName"), "", 0, TableEvenRow);
                        result      += HtmlController.td(csData.getText("FieldType"), "", 0, TableEvenRow);
                        result      += kmaEndTableRow;
                        TableEvenRow = !TableEvenRow;
                        csData.goNext();
                    }
                }
                //
                // Field Type Definitions
                //
                result += HtmlController.tableRow("<br><br><B>Field Type Definitions</b>", TableColSpan, TableEvenRow);
                result += HtmlController.tableRow("Boolean - Boolean values 0 and 1 are stored in a database long integer field type", TableColSpan, TableEvenRow);
                result += HtmlController.tableRow("Lookup - References to related records stored as database long integer field type", TableColSpan, TableEvenRow);
                result += HtmlController.tableRow("Integer - database long integer field type", TableColSpan, TableEvenRow);
                result += HtmlController.tableRow("Float - database floating point value", TableColSpan, TableEvenRow);
                result += HtmlController.tableRow("Date - database DateTime field type.", TableColSpan, TableEvenRow);
                result += HtmlController.tableRow("AutoIncrement - database long integer field type. Field automatically increments when a record is added.", TableColSpan, TableEvenRow);
                result += HtmlController.tableRow("Text - database character field up to 255 characters.", TableColSpan, TableEvenRow);
                result += HtmlController.tableRow("LongText - database character field up to 64K characters.", TableColSpan, TableEvenRow);
                result += HtmlController.tableRow("TextFile - references a filename in the Content Files folder. Database character field up to 255 characters. ", TableColSpan, TableEvenRow);
                result += HtmlController.tableRow("File - references a filename in the Content Files folder. Database character field up to 255 characters. ", TableColSpan, TableEvenRow);
                result += HtmlController.tableRow("Redirect - This field has no database equivelent. No Database field is required.", TableColSpan, TableEvenRow);
                //
                // Spacers
                //
                result += HtmlController.tableRowStart();
                result += HtmlController.td(nop2(20, 1), "20");
                result += HtmlController.td(nop2(300, 1), "300");
                result += HtmlController.td("&nbsp;", "100%");
                result += kmaEndTableRow;
                result += kmaEndTable;
                //
                result = AdminUIController.getToolForm(core, result, ButtonList);
                //
                // ----- Error Trap
                //
            } catch (Exception ex) {
                LogController.logError(core, ex);
            }
            return(result);
        }
예제 #20
0
        //
        //===============================================================================================================================
        //   Is Group Member of a GroupIDList
        //===============================================================================================================================
        //
        public static bool isInGroupList(CoreController core, int MemberID, bool isAuthenticated, string GroupIDList, bool adminReturnsTrue)
        {
            bool returnREsult = false;

            try {
                //
                string sql           = null;
                string Criteria      = null;
                string WorkingIDList = null;
                //
                returnREsult = false;
                if (isAuthenticated)
                {
                    WorkingIDList = GroupIDList;
                    WorkingIDList = GenericController.strReplace(WorkingIDList, " ", "");
                    while (GenericController.strInstr(1, WorkingIDList, ",,") != 0)
                    {
                        WorkingIDList = GenericController.strReplace(WorkingIDList, ",,", ",");
                    }
                    if (!string.IsNullOrEmpty(WorkingIDList))
                    {
                        if (strMid(WorkingIDList, 1) == ",")
                        {
                            if (strLen(WorkingIDList) <= 1)
                            {
                                WorkingIDList = "";
                            }
                            else
                            {
                                WorkingIDList = strMid(WorkingIDList, 2);
                            }
                        }
                    }
                    if (!string.IsNullOrEmpty(WorkingIDList))
                    {
                        if (WorkingIDList.right(1) == ",")
                        {
                            if (strLen(WorkingIDList) <= 1)
                            {
                                WorkingIDList = "";
                            }
                            else
                            {
                                WorkingIDList = GenericController.strMid(WorkingIDList, 1, strLen(WorkingIDList) - 1);
                            }
                        }
                    }
                    if (string.IsNullOrEmpty(WorkingIDList))
                    {
                        if (adminReturnsTrue)
                        {
                            //
                            // check if memberid is admin
                            //
                            sql = "select top 1 m.id"
                                  + " from ccmembers m"
                                  + " where"
                                  + " (m.id=" + MemberID + ")"
                                  + " and(m.active<>0)"
                                  + " and("
                                  + " (m.admin<>0)"
                                  + " or(m.developer<>0)"
                                  + " )"
                                  + " ";
                            using (var csData = new CsModel(core)) {
                                returnREsult = csData.openSql(sql);
                            }
                        }
                    }
                    else
                    {
                        //
                        // check if they are admin or in the group list
                        //
                        if (GenericController.strInstr(1, WorkingIDList, ",") != 0)
                        {
                            Criteria = "r.GroupID in (" + WorkingIDList + ")";
                        }
                        else
                        {
                            Criteria = "r.GroupID=" + WorkingIDList;
                        }
                        Criteria = ""
                                   + "(" + Criteria + ")"
                                   + " and(r.id is not null)"
                                   + " and((r.DateExpires is null)or(r.DateExpires>" + DbController.encodeSQLDate(core.dateTimeNowMockable) + "))"
                                   + " ";
                        if (adminReturnsTrue)
                        {
                            Criteria = "(" + Criteria + ")or(m.admin<>0)or(m.developer<>0)";
                        }
                        Criteria = ""
                                   + "(" + Criteria + ")"
                                   + " and(m.active<>0)"
                                   + " and(m.id=" + MemberID + ")";
                        //
                        sql = "select top 1 m.id"
                              + " from ccmembers m"
                              + " left join ccMemberRules r on r.Memberid=m.id"
                              + " where" + Criteria;
                        using (var csData = new CsModel(core)) {
                            csData.openSql(sql);
                            returnREsult = csData.ok();
                        }
                    }
                }
            } catch (Exception ex) {
                LogController.logError(core, ex);
                throw;
            }
            return(returnREsult);
        }
예제 #21
0
        //
        //========================================================================
        //
        //========================================================================
        //
        public static string get(CPClass cp)
        {
            string tempGetForm_HouseKeepingControl = null;

            try {
                //
                StringBuilderLegacyController Content = new StringBuilderLegacyController();
                string   Copy                  = null;
                string   SQL                   = null;
                string   Button                = null;
                int      PagesTotal            = 0;
                string   Caption               = null;
                DateTime DateValue             = default(DateTime);
                string   AgeInDays             = null;
                int      ArchiveRecordAgeDays  = 0;
                string   ArchiveTimeOfDay      = null;
                bool     ArchiveAllowFileClean = false;
                string   ButtonList            = "";
                string   Description           = null;
                //
                Button = cp.core.docProperties.getText(RequestNameButton);
                if (Button == ButtonCancel)
                {
                    //
                    //
                    //
                    return(cp.core.webServer.redirect("/" + cp.core.appConfig.adminRoute, "HouseKeepingControl, Cancel Button Pressed"));
                }
                else if (!cp.core.session.isAuthenticatedAdmin())
                {
                    //
                    //
                    //
                    ButtonList = ButtonCancel;
                    Content.add(AdminUIController.getFormBodyAdminOnly());
                }
                else
                {
                    //
                    string tableBody = "";
                    //
                    // Set defaults
                    //
                    ArchiveRecordAgeDays  = (cp.core.siteProperties.getInteger("ArchiveRecordAgeDays", 0));
                    ArchiveTimeOfDay      = cp.core.siteProperties.getText("ArchiveTimeOfDay", "12:00:00 AM");
                    ArchiveAllowFileClean = (cp.core.siteProperties.getBoolean("ArchiveAllowFileClean", false));
                    //
                    // Process Requests
                    //
                    switch (Button)
                    {
                    case ButtonOK:
                    case ButtonSave:
                        //
                        ArchiveRecordAgeDays = cp.core.docProperties.getInteger("ArchiveRecordAgeDays");
                        cp.core.siteProperties.setProperty("ArchiveRecordAgeDays", GenericController.encodeText(ArchiveRecordAgeDays));
                        //
                        ArchiveTimeOfDay = cp.core.docProperties.getText("ArchiveTimeOfDay");
                        cp.core.siteProperties.setProperty("ArchiveTimeOfDay", ArchiveTimeOfDay);
                        //
                        ArchiveAllowFileClean = cp.core.docProperties.getBoolean("ArchiveAllowFileClean");
                        cp.core.siteProperties.setProperty("ArchiveAllowFileClean", GenericController.encodeText(ArchiveAllowFileClean));
                        break;
                    }
                    //
                    if (Button == ButtonOK)
                    {
                        return(cp.core.webServer.redirect("/" + cp.core.appConfig.adminRoute, "StaticPublishControl, OK Button Pressed"));
                    }
                    //
                    // ----- Status
                    //
                    tableBody += HtmlController.tableRowStart() + "<td colspan=\"3\" class=\"ccPanel3D ccAdminEditSubHeader\"><b>Status</b>" + tableCellEnd + kmaEndTableRow;
                    //
                    // ----- Visits Found
                    //
                    PagesTotal = 0;
                    SQL        = "SELECT Count(ID) as Result FROM ccVisits;";
                    using (var csData = new CsModel(cp.core)) {
                        csData.openSql(SQL);
                        if (csData.ok())
                        {
                            PagesTotal = csData.getInteger("Result");
                        }
                    }
                    tableBody += AdminUIController.getEditRowLegacy(cp.core, SpanClassAdminNormal + PagesTotal, "Visits Found", "", false, false, "");
                    //
                    // ----- Oldest Visit
                    //
                    Copy      = "unknown";
                    AgeInDays = "unknown";
                    using (var csData = new CsModel(cp.core)) {
                        SQL = cp.core.db.getSQLSelect("ccVisits", "DateAdded", "", "ID", "", 1);
                        csData.openSql(SQL);
                        if (csData.ok())
                        {
                            DateValue = csData.getDate("DateAdded");
                            if (DateValue != DateTime.MinValue)
                            {
                                Copy      = GenericController.encodeText(DateValue);
                                AgeInDays = GenericController.encodeText(encodeInteger(Math.Floor(encodeNumber(cp.core.doc.profileStartTime - DateValue))));
                            }
                        }
                    }
                    tableBody += (AdminUIController.getEditRowLegacy(cp.core, SpanClassAdminNormal + Copy + " (" + AgeInDays + " days)", "Oldest Visit", "", false, false, ""));
                    //
                    // ----- Viewings Found
                    //
                    PagesTotal = 0;
                    SQL        = "SELECT Count(ID) as result  FROM ccViewings;";
                    using (var csData = new CsModel(cp.core)) {
                        csData.openSql(SQL);
                        if (csData.ok())
                        {
                            PagesTotal = csData.getInteger("Result");
                        }
                        csData.close();
                    }
                    tableBody += (AdminUIController.getEditRowLegacy(cp.core, SpanClassAdminNormal + PagesTotal, "Viewings Found", "", false, false, ""));
                    //
                    tableBody += (HtmlController.tableRowStart() + "<td colspan=\"3\" class=\"ccPanel3D ccAdminEditSubHeader\"><b>Options</b>" + tableCellEnd + kmaEndTableRow);
                    //
                    Caption    = "Archive Age";
                    Copy       = HtmlController.inputText_Legacy(cp.core, "ArchiveRecordAgeDays", ArchiveRecordAgeDays.ToString(), -1, 20) + "&nbsp;Number of days to keep visit records. 0 disables housekeeping.";
                    tableBody += (AdminUIController.getEditRowLegacy(cp.core, Copy, Caption));
                    //
                    Caption    = "Housekeeping Time";
                    Copy       = HtmlController.inputText_Legacy(cp.core, "ArchiveTimeOfDay", ArchiveTimeOfDay, -1, 20) + "&nbsp;The time of day when record deleting should start.";
                    tableBody += (AdminUIController.getEditRowLegacy(cp.core, Copy, Caption));
                    //
                    Caption    = "Purge Content Files";
                    Copy       = HtmlController.checkbox("ArchiveAllowFileClean", ArchiveAllowFileClean) + "&nbsp;Delete Contensive content files with no associated database record.";
                    tableBody += (AdminUIController.getEditRowLegacy(cp.core, Copy, Caption));
                    //
                    Content.add(AdminUIController.editTable(tableBody));
                    Content.add(HtmlController.inputHidden(rnAdminSourceForm, AdminformHousekeepingControl));
                    ButtonList = ButtonCancel + ",Refresh," + ButtonSave + "," + ButtonOK;
                }
                //
                Caption     = "Data Housekeeping Control";
                Description = "This tool is used to control the database record housekeeping process. This process deletes visit history records, so care should be taken before making any changes.";
                tempGetForm_HouseKeepingControl = AdminUIController.getToolBody(cp.core, Caption, ButtonList, "", false, false, Description, "", 0, Content.text);
                //
                cp.core.html.addTitle(Caption);
            } catch (Exception ex) {
                LogController.logError(cp.core, ex);
            }
            return(tempGetForm_HouseKeepingControl);
        }
예제 #22
0
        //
        //=============================================================================
        //   Export the Admin List form results
        //=============================================================================
        //
        public static string get(CoreController core, AdminDataModel adminData)
        {
            string result = "";

            try {
                //
                bool   AllowContentAccess                    = false;
                string ButtonCommaList                       = "";
                string ExportName                            = null;
                string Description                           = null;
                string Content                               = "";
                string Button                                = null;
                int    RecordLimit                           = 0;
                int    recordCnt                             = 0;
                string sqlFieldList                          = "";
                string SQLFrom                               = "";
                string SQLWhere                              = "";
                string SQLOrderBy                            = "";
                bool   IsLimitedToSubContent                 = false;
                string ContentAccessLimitMessage             = "";
                Dictionary <string, bool> FieldUsedInColumns = new Dictionary <string, bool>();
                Dictionary <string, bool> IsLookupFieldValid = new Dictionary <string, bool>();
                IndexConfigClass          IndexConfig        = null;
                string          SQL                          = null;
                bool            IsRecordLimitSet             = false;
                string          RecordLimitText              = null;
                var             cacheNameList                = new List <string>();
                DataSourceModel datasource                   = DataSourceModel.create(core.cpParent, adminData.adminContent.dataSourceId, ref cacheNameList);
                //
                // ----- Process Input
                //
                Button = core.docProperties.getText("Button");
                if (Button == ButtonCancelAll)
                {
                    //
                    // Cancel out to the main page
                    //
                    return(core.webServer.redirect("?", "CancelAll button pressed on Index Export"));
                }
                else if (Button != ButtonCancel)
                {
                    //
                    // get content access rights
                    //
                    var userContentPermissions = PermissionController.getUserContentPermissions(core, adminData.adminContent);
                    if (!userContentPermissions.allowEdit)
                    {
                        //
                        // You must be a content manager of this content to use this tool
                        //
                        Content = ""
                                  + "<p>You must be a content manager of " + adminData.adminContent.name + " to use this tool. Hit Cancel to return to main admin page.</p>"
                                  + HtmlController.inputHidden(RequestNameAdminSubForm, AdminFormIndex_SubFormExport) + "";
                        ButtonCommaList = ButtonCancelAll;
                    }
                    else
                    {
                        IsRecordLimitSet = false;
                        if (string.IsNullOrEmpty(Button))
                        {
                            //
                            // Set Defaults
                            //
                            ExportName      = "";
                            RecordLimit     = 0;
                            RecordLimitText = "";
                        }
                        else
                        {
                            ExportName      = core.docProperties.getText("ExportName");
                            RecordLimitText = core.docProperties.getText("RecordLimit");
                            if (!string.IsNullOrEmpty(RecordLimitText))
                            {
                                IsRecordLimitSet = true;
                                RecordLimit      = GenericController.encodeInteger(RecordLimitText);
                            }
                        }
                        if (string.IsNullOrEmpty(ExportName))
                        {
                            ExportName = adminData.adminContent.name + " export for " + core.session.user.name;
                        }
                        //
                        // Get the SQL parts
                        //
                        IndexConfig = IndexConfigClass.get(core, adminData);
                        ListView.setIndexSQL(core, adminData, IndexConfig, ref AllowContentAccess, ref sqlFieldList, ref SQLFrom, ref SQLWhere, ref SQLOrderBy, ref IsLimitedToSubContent, ref ContentAccessLimitMessage, ref FieldUsedInColumns, IsLookupFieldValid);
                        if (!AllowContentAccess)
                        {
                            //
                            // This should be caught with check earlier, but since I added this, and I never make mistakes, I will leave this in case there is a mistake in the earlier code
                            //
                            Processor.Controllers.ErrorController.addUserError(core, "Your account does not have access to any records in '" + adminData.adminContent.name + "'.");
                        }
                        else
                        {
                            //
                            // Get the total record count
                            //
                            SQL = "select count(" + adminData.adminContent.tableName + ".ID) as cnt from " + SQLFrom + " where " + SQLWhere;
                            using (var csData = new CsModel(core)) {
                                csData.openSql(SQL, datasource.name);
                                if (csData.ok())
                                {
                                    recordCnt = csData.getInteger("cnt");
                                }
                            }
                            //
                            // Build the SQL
                            //
                            SQL = "select";
                            if (IsRecordLimitSet && (datasource.dbTypeId != DataSourceTypeODBCMySQL))
                            {
                                SQL += " Top " + RecordLimit;
                            }
                            SQL += " " + adminData.adminContent.tableName + ".* From " + SQLFrom + " WHERE " + SQLWhere;
                            if (!string.IsNullOrEmpty(SQLOrderBy))
                            {
                                SQL += " Order By" + SQLOrderBy;
                            }
                            if (IsRecordLimitSet && (datasource.dbTypeId == DataSourceTypeODBCMySQL))
                            {
                                SQL += " Limit " + RecordLimit;
                            }
                            //
                            // Assumble the SQL
                            //
                            if (recordCnt == 0)
                            {
                                //
                                // There are no records to request
                                //
                                Content = ""
                                          + "<p>This selection has no records. Hit Cancel to return to the " + adminData.adminContent.name + " list page.</p>"
                                          + HtmlController.inputHidden(RequestNameAdminSubForm, AdminFormIndex_SubFormExport) + "";
                                ButtonCommaList = ButtonCancel;
                            }
                            else if (Button == ButtonRequestDownload)
                            {
                                //
                                // Request the download
                                //
                                var ExportCSVAddon = DbBaseModel.create <AddonModel>(core.cpParent, addonGuidExportCSV);
                                if (ExportCSVAddon == null)
                                {
                                    LogController.logError(core, new GenericException("ExportCSV addon not found. Task could not be added to task queue."));
                                }
                                else
                                {
                                    var docProperties = new Dictionary <string, string> {
                                        { "sql", SQL },
                                        { "datasource", "default" }
                                    };
                                    var cmdDetail = new TaskModel.CmdDetailClass {
                                        addonId   = ExportCSVAddon.id,
                                        addonName = ExportCSVAddon.name,
                                        args      = docProperties
                                    };
                                    TaskSchedulerController.addTaskToQueue(core, cmdDetail, false, ExportName, "export_" + adminData.adminContent.name.Replace(" ", "_") + ".csv");
                                }
                                //
                                Content = ""
                                          + "<p>Your export has been requested and will be available shortly in the <a href=\"?" + rnAdminForm + "=" + AdminFormDownloads + "\">Download Manager</a>. Hit Cancel to return to the " + adminData.adminContent.name + " list page.</p>"
                                          + HtmlController.inputHidden(RequestNameAdminSubForm, AdminFormIndex_SubFormExport) + "";
                                //
                                ButtonCommaList = ButtonCancel;
                            }
                            else
                            {
                                //
                                // no button or refresh button, Ask are you sure
                                //
                                Content += HtmlController.div(
                                    HtmlController.label("Export Name", "export-name")
                                    + HtmlController.inputText(core, "ExportName", ExportName, "form-control", "export-name")
                                    , "form-group");
                                Content += HtmlController.div(
                                    HtmlController.label("Records Found", "records-found")
                                    + HtmlController.inputText(core, "RecordCnt", recordCnt.ToString(), "form-control", "records-found", true)
                                    , "form-group");
                                Content += HtmlController.div(
                                    HtmlController.label("Record Limit", "record-limit")
                                    + HtmlController.inputText(core, "RecordLimit", RecordLimitText, "form-control", "record-limit")
                                    , "form-group");
                                if (core.session.isAuthenticatedDeveloper())
                                {
                                    Content += HtmlController.div(
                                        HtmlController.label("Results SQL", "export-query")
                                        + HtmlController.inputTextarea(core, "sql", SQL, 4, -1, "export-query", false, false, "form-control")
                                        , "form-group");
                                }
                                //
                                Content = ""
                                          //+ "\r<style>"
                                          //+ cr2 + ".exportTblCaption {width:100px;}"
                                          //+ cr2 + ".exportTblInput {}"
                                          //+ "\r</style>"
                                          + Content + HtmlController.inputHidden(RequestNameAdminSubForm, AdminFormIndex_SubFormExport) + "";
                                ButtonCommaList = ButtonCancel + "," + ButtonRequestDownload;
                                if (core.session.isAuthenticatedDeveloper())
                                {
                                    ButtonCommaList = ButtonCommaList + "," + ButtonRefresh;
                                }
                            }
                        }
                    }
                    //
                    Description = "<p>This tool creates an export of the current admin list page results. If you would like to download the current results, select a format and press OK. Your search results will be submitted for export. Your download will be ready shortly in the download manager. To exit without requesting an output, hit Cancel.</p>";
                    result      = AdminUIController.getToolBody(core, adminData.adminContent.name + " Export", ButtonCommaList, "", false, false, Description, "", 10, Content);
                }
            } catch (Exception ex) {
                LogController.logError(core, ex);
            }
            return(result);
        }
예제 #23
0
        //
        //===========================================================================
        //
        public static string get(CoreController core, AdminDataModel adminData, IndexConfigClass indexConfig, PermissionController.UserContentPermissions userContentPermissions, string sql, DataSourceModel dataSource, Dictionary <string, bool> FieldUsedInColumns, Dictionary <string, bool> IsLookupFieldValid)
        {
            try {
                bool allowDelete      = (adminData.adminContent.allowDelete) && (userContentPermissions.allowDelete) && (indexConfig.allowDelete);
                var  DataTable_HdrRow = new StringBuilder("<tr>");
                //
                // Row Number Column
                DataTable_HdrRow.Append("<td width=20 align=center valign=bottom class=\"small ccAdminListCaption\">Row</td>");
                //
                // Edit Column
                DataTable_HdrRow.Append("<td width=20 align=center valign=bottom class=\"small ccAdminListCaption\">Edit</td>");
                //
                // Delete Select Box Columns
                if (!allowDelete)
                {
                    DataTable_HdrRow.Append("<td width=20 align=center valign=bottom class=\"small ccAdminListCaption\"><input TYPE=CheckBox disabled=\"disabled\"></td>");
                }
                else
                {
                    DataTable_HdrRow.Append("<td width=20 align=center valign=bottom class=\"small ccAdminListCaption\"><input TYPE=CheckBox OnClick=\"CheckInputs('DelCheck',this.checked);\"></td>");
                }
                //
                // -- create header
                int ColumnWidthTotal = 0;
                foreach (var column in indexConfig.columns)
                {
                    if (column.Width < 1)
                    {
                        column.Width = 1;
                    }
                    ColumnWidthTotal += column.Width;
                }
                foreach (var column in indexConfig.columns)
                {
                    //
                    // ----- print column headers - anchored so they sort columns
                    //
                    int ColumnWidth = encodeInteger((100 * column.Width) / (double)ColumnWidthTotal);
                    //
                    // if this is a current sort ,add the reverse flag
                    //
                    StringBuilder buttonHref = new StringBuilder();
                    buttonHref.Append("/" + core.appConfig.adminRoute + "?" + rnAdminForm + "=" + AdminFormIndex + "&SetSortField=" + column.Name + "&RT=0&" + RequestNameTitleExtension + "=" + GenericController.encodeRequestVariable(adminData.titleExtension) + "&cid=" + adminData.adminContent.id + "&ad=" + adminData.ignore_legacyMenuDepth);
                    if (!indexConfig.sorts.ContainsKey(column.Name))
                    {
                        buttonHref.Append("&SetSortDirection=1");
                    }
                    else
                    {
                        switch (indexConfig.sorts[column.Name].direction)
                        {
                        case 1: {
                            buttonHref.Append("&SetSortDirection=2");
                            break;
                        }

                        case 2: {
                            buttonHref.Append("&SetSortDirection=0");
                            break;
                        }

                        default: {
                            // nothing
                            break;
                        }
                        }
                    }
                    //
                    // -- column header includes WherePairCount
                    if (!adminData.wherePair.Count.Equals(0))
                    {
                        int ptr = 0;
                        foreach (var kvp in adminData.wherePair)
                        {
                            if (!string.IsNullOrWhiteSpace(kvp.Key))
                            {
                                buttonHref.Append("&wl" + ptr + "=" + GenericController.encodeRequestVariable(kvp.Value));
                                buttonHref.Append("&wr" + ptr + "=" + GenericController.encodeRequestVariable(kvp.Value));
                                ptr++;
                            }
                        }
                    }
                    string buttonFace = adminData.adminContent.fields[column.Name.ToLowerInvariant()].caption;
                    buttonFace = GenericController.strReplace(buttonFace, " ", "&nbsp;");
                    string SortTitle = "Sort A-Z";
                    //
                    if (indexConfig.sorts.ContainsKey(column.Name))
                    {
                        string sortSuffix = ((indexConfig.sorts.Count < 2) ? "" : indexConfig.sorts[column.Name].order.ToString());
                        switch (indexConfig.sorts[column.Name].direction)
                        {
                        case 1: {
                            buttonFace = iconArrowDown + sortSuffix + "&nbsp;" + buttonFace;
                            SortTitle  = "Sort Z-A";
                            break;
                        }

                        case 2: {
                            buttonFace = iconArrowUp + sortSuffix + "&nbsp;" + buttonFace;
                            SortTitle  = "Remove Sort";
                            break;
                        }

                        default: {
                            // nothing
                            break;
                        }
                        }
                    }
                    if (indexConfig.allowColumnSort)
                    {
                        buttonFace = HtmlController.a(buttonFace, new CPBase.BaseModels.HtmlAttributesA()
                        {
                            title  = SortTitle,
                            href   = buttonHref.ToString(),
                            @class = "ccAdminListCaption"
                        });
                    }
                    adminData.buttonObjectCount += 1;
                    DataTable_HdrRow.Append("<td width=\"" + ColumnWidth + "%\" valign=bottom align=left class=\"small ccAdminListCaption\">");
                    DataTable_HdrRow.Append(buttonFace);
                    DataTable_HdrRow.Append("</td>");
                }
                DataTable_HdrRow.Append("</tr>");
                //
                // -- generic admin url for edit and add links
                string adminEditPresetArgQsList = "";
                string adminUrlBase             = "\\" + core.appConfig.adminRoute + "?" + rnAdminAction + "=" + Constants.AdminActionNop + "&cid=" + adminData.adminContent.id + "&" + RequestNameTitleExtension + "=" + GenericController.encodeRequestVariable(adminData.titleExtension) + "&ad=" + adminData.ignore_legacyMenuDepth + "&" + rnAdminSourceForm + "=" + adminData.adminForm + "&" + rnAdminForm + "=" + AdminFormEdit;
                if (!adminData.wherePair.Count.Equals(0))
                {
                    int WhereCount = 0;
                    foreach (var kvp in adminData.wherePair)
                    {
                        adminEditPresetArgQsList += "&" + encodeRequestVariable(kvp.Key) + "=" + GenericController.encodeRequestVariable(kvp.Value);
                        WhereCount++;
                    }
                    adminUrlBase += adminEditPresetArgQsList;
                }
                //
                // -- output data rows
                var    dataTableRows = new StringBuilder();
                string rowColor      = "";
                int    rowNumber     = 0;
                int    rowNumberLast = 0;
                using (var csData = new CsModel(core)) {
                    if (csData.openSql(sql, dataSource.name, indexConfig.recordsPerPage, indexConfig.pageNumber))
                    {
                        rowNumber     = indexConfig.recordTop;
                        rowNumberLast = indexConfig.recordTop + indexConfig.recordsPerPage;
                        //
                        // --- Print out the records
                        while ((csData.ok()) && (rowNumber < rowNumberLast))
                        {
                            int recordId = csData.getInteger("ID");
                            if (rowColor == "class=\"ccAdminListRowOdd\"")
                            {
                                rowColor = "class=\"ccAdminListRowEven\"";
                            }
                            else
                            {
                                rowColor = "class=\"ccAdminListRowOdd\"";
                            }
                            //
                            // -- new row
                            dataTableRows.Append(Environment.NewLine + "<tr>");
                            //
                            // --- row number column
                            dataTableRows.Append("<td align=right " + rowColor + ">" + (rowNumber + 1).ToString() + "</td>");
                            //
                            // --- edit column
                            dataTableRows.Append("<td align=center " + rowColor + ">" + getRecordEditAnchorTag(adminUrlBase + "&id=" + recordId) + "</td>");
                            //
                            // --- Delete Checkbox Columns
                            if (allowDelete)
                            {
                                dataTableRows.Append("<td align=center " + rowColor + "><input TYPE=CheckBox NAME=row" + rowNumber + " VALUE=1 ID=\"DelCheck\"><input type=hidden name=rowid" + rowNumber + " VALUE=" + recordId + "></span></td>");
                            }
                            else
                            {
                                dataTableRows.Append("<td align=center " + rowColor + "><input TYPE=CheckBox disabled=\"disabled\" NAME=row" + rowNumber + " VALUE=1><input type=hidden name=rowid" + rowNumber + " VALUE=" + recordId + "></span></td>");
                            }
                            //
                            // --- field columns
                            foreach (var column in indexConfig.columns)
                            {
                                string columnNameLc = column.Name.ToLowerInvariant();
                                if (FieldUsedInColumns.ContainsKey(columnNameLc))
                                {
                                    if (FieldUsedInColumns[columnNameLc])
                                    {
                                        dataTableRows.Append((Environment.NewLine + "<td valign=\"middle\" " + rowColor + " align=\"left\">" + SpanClassAdminNormal));
                                        dataTableRows.Append(getGridCell(core, adminData, column.Name, csData, IsLookupFieldValid[columnNameLc], GenericController.toLCase(adminData.adminContent.tableName) == "ccemail"));
                                        dataTableRows.Append(("&nbsp;</span></td>"));
                                    }
                                }
                            }
                            dataTableRows.Append(("\n    </tr>"));
                            csData.goNext();
                            rowNumber = rowNumber + 1;
                        }
                        dataTableRows.Append("<input type=hidden name=rowcnt value=" + rowNumber + ">");
                        //
                        // --- print out the stuff at the bottom
                        //
                        int RecordTop_NextPage = indexConfig.recordTop;
                        if (csData.ok())
                        {
                            RecordTop_NextPage = rowNumber;
                        }
                        int RecordTop_PreviousPage = indexConfig.recordTop - indexConfig.recordsPerPage;
                        if (RecordTop_PreviousPage < 0)
                        {
                            RecordTop_PreviousPage = 0;
                        }
                    }
                }
                //
                // Header at bottom
                //
                if (rowColor == "class=\"ccAdminListRowOdd\"")
                {
                    rowColor = "class=\"ccAdminListRowEven\"";
                }
                else
                {
                    rowColor = "class=\"ccAdminListRowOdd\"";
                }
                string blankRow = "<tr><td colspan=" + (indexConfig.columns.Count + 3) + " " + rowColor + " style=\"text-align:left ! important;\">{msg}</td></tr>";
                if (rowNumber == 0)
                {
                    //
                    // -- No records found
                    dataTableRows.Append(blankRow.Replace("{msg}", "----- no records were found -----"));
                }
                else
                {
                    if (rowNumber < rowNumberLast)
                    {
                        //
                        // --End of list
                        dataTableRows.Append(blankRow.Replace("{msg}", "----- end of list -----"));
                    }
                }
                if (indexConfig.allowAddRow)
                {
                    //
                    // optional AddRow
                    foreach (var addTag in getRecordAddAnchorTag(core, adminData.adminContent.name, adminEditPresetArgQsList, false, userContentPermissions.allowAdd))
                    {
                        dataTableRows.Append(blankRow.Replace("{msg}", addTag));
                    }
                }
                //
                // Add another header to the data rows
                //
                dataTableRows.Append(DataTable_HdrRow.ToString());
                //
                var DataTable_FindRow = new StringBuilder();
                if (indexConfig.allowFind)
                {
                    //
                    // ----- DataTable_FindRow
                    //
                    DataTable_FindRow.Append("<tr><td colspan=" + (3 + indexConfig.columns.Count) + " style=\"background-color:black;height:1;\"></td></tr>");
                    DataTable_FindRow.Append("<tr>");
                    DataTable_FindRow.Append("<td valign=\"middle\" colspan=3 width=\"60\" class=\"ccPanel\" align=center style=\"vertical-align:middle;padding:8px;text-align:center ! important;\">");
                    DataTable_FindRow.Append(AdminUIController.getButtonPrimary(ButtonFind, "", false, "FindButton") + "</td>");
                    int ColumnPointer = 0;
                    var listOfMatches = new List <FindWordMatchEnum> {
                        FindWordMatchEnum.matchincludes, FindWordMatchEnum.MatchEquals, FindWordMatchEnum.MatchTrue, FindWordMatchEnum.MatchFalse
                    };
                    foreach (var column in indexConfig.columns)
                    {
                        string FieldName     = GenericController.toLCase(column.Name);
                        string FindWordValue = "";
                        if (indexConfig.findWords.ContainsKey(FieldName))
                        {
                            var findWord = indexConfig.findWords[FieldName];
                            if (listOfMatches.Any(s => findWord.MatchOption.Equals(s)))
                            {
                                FindWordValue = findWord.Value;
                            }
                        }
                        DataTable_FindRow.Append(Environment.NewLine + "<td valign=\"middle\" align=\"center\" class=\"ccPanel3DReverse\" style=\"padding:8px;\">"
                                                 + "<input type=hidden name=\"FindName" + ColumnPointer + "\" value=\"" + FieldName + "\">"
                                                 + "<input class=\"form-control findInput\"  onkeypress=\"KeyCheck(event);\"  type=text id=\"F" + ColumnPointer + "\" name=\"FindValue" + ColumnPointer + "\" value=\"" + FindWordValue + "\" style=\"padding-right:.2rem;padding-left:.2rem;\">"
                                                 + "</td>");
                        ColumnPointer += 1;
                    }
                    DataTable_FindRow.Append("</tr>");
                }
                //
                // Assemble DataTable
                //
                string grid = ""
                              + "<table ID=\"DataTable\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\" style=\"Background-Color:white;\">"
                              + DataTable_HdrRow + dataTableRows + DataTable_FindRow + "</table>";
                return(grid);
            } catch (Exception ex) {
                LogController.logError(core, ex);
                return(HtmlController.div("There was an error creating the record list."));
            }
        }
예제 #24
0
        public static string getEditorRow(CoreController core, ContentFieldMetadataModel field, AdminDataModel adminData, EditorEnvironmentModel editorEnv)
        {
            string whyReadOnlyMsg = "";

            Models.EditRecordModel editRecord = adminData.editRecord;
            object fieldValueObject           = editRecord.fieldsLc[field.nameLc].value;
            string fieldValue_text            = encodeText(fieldValueObject);
            int    fieldRows    = 1;
            string fieldHtmlId  = field.nameLc + field.id.ToString();
            string fieldCaption = field.caption;

            if (field.uniqueName)
            {
                fieldCaption = "&nbsp;**" + fieldCaption;
            }
            else
            {
                if (field.nameLc.ToLowerInvariant() == "email")
                {
                    if ((adminData.adminContent.tableName.ToLowerInvariant() == "ccmembers") && ((core.siteProperties.getBoolean("allowemaillogin", false))))
                    {
                        fieldCaption = "&nbsp;***" + fieldCaption;
                        editorEnv.needUniqueEmailMessage = true;
                    }
                }
            }
            if (field.required)
            {
                fieldCaption = "&nbsp;*" + fieldCaption;
            }
            adminData.formInputCount = adminData.formInputCount + 1;
            bool fieldForceReadOnly = false;

            //
            // Read only Special Cases
            if (editorEnv.isRootPage)
            {
                //
                // -- page content metadata, these are the special fields
                switch (GenericController.toLCase(field.nameLc))
                {
                case "active": {
                    //
                    // if active, it is read only -- if inactive, let them set it active.
                    fieldForceReadOnly = encodeBoolean(fieldValueObject);
                    if (fieldForceReadOnly)
                    {
                        whyReadOnlyMsg = "&nbsp;(disabled because you can not mark the landing page inactive)";
                    }
                    break;
                }

                case "dateexpires":
                case "pubdate":
                case "datearchive":
                case "blocksection":
                case "archiveparentid":
                case "hidemenu": {
                    //
                    // These fields are read only on landing pages
                    fieldForceReadOnly = true;
                    whyReadOnlyMsg     = "&nbsp;(disabled for the landing page)";
                    break;
                }

                case "allowinmenus":
                case "allowinchildlists": {
                    fieldValueObject   = "1";
                    fieldForceReadOnly = true;
                    whyReadOnlyMsg     = "&nbsp;(disabled for root pages)";
                }
                break;

                default: {
                    // do nothing
                    break;
                }
                }
            }
            //
            // Special Case - ccemail table Alloweid should be disabled if siteproperty AllowLinkLogin is false
            //
            if (GenericController.toLCase(adminData.adminContent.tableName) == "ccemail" && GenericController.toLCase(field.nameLc) == "allowlinkeid")
            {
                if (!(core.siteProperties.getBoolean("AllowLinkLogin", true)))
                {
                    fieldValueObject   = "0";
                    fieldForceReadOnly = true;
                    fieldValue_text    = "0";
                }
            }
            string     EditorString   = "";
            bool       editorReadOnly = (editorEnv.record_readOnly || field.readOnly || (editRecord.id != 0 && field.notEditable) || (fieldForceReadOnly));
            AddonModel editorAddon    = null;
            int        fieldTypeDefaultEditorAddonId = 0;
            var        fieldEditor = adminData.fieldTypeEditors.Find(x => (x.fieldTypeId == (int)field.fieldTypeId));

            if (fieldEditor != null)
            {
                fieldTypeDefaultEditorAddonId = (int)fieldEditor.editorAddonId;
                editorAddon = DbBaseModel.create <AddonModel>(core.cpParent, fieldTypeDefaultEditorAddonId);
            }
            bool useEditorAddon = false;

            if (editorAddon != null)
            {
                //
                //--------------------------------------------------------------------------------------------
                // ----- Custom Editor
                //--------------------------------------------------------------------------------------------
                //
                core.docProperties.setProperty("editorName", field.nameLc);
                core.docProperties.setProperty("editorValue", fieldValue_text);
                core.docProperties.setProperty("editorFieldId", field.id);
                core.docProperties.setProperty("editorFieldType", (int)field.fieldTypeId);
                core.docProperties.setProperty("editorReadOnly", editorReadOnly);
                core.docProperties.setProperty("editorWidth", "");
                core.docProperties.setProperty("editorHeight", "");
                if (field.fieldTypeId.isOneOf(CPContentBaseClass.FieldTypeIdEnum.HTML, CPContentBaseClass.FieldTypeIdEnum.HTMLCode, CPContentBaseClass.FieldTypeIdEnum.FileHTML, CPContentBaseClass.FieldTypeIdEnum.FileHTMLCode))
                {
                    //
                    // include html related arguments
                    core.docProperties.setProperty("editorAllowActiveContent", "1");
                    core.docProperties.setProperty("editorAddonList", editorEnv.editorAddonListJSON);
                    core.docProperties.setProperty("editorStyles", editorEnv.styleList);
                    core.docProperties.setProperty("editorStyleOptions", editorEnv.styleOptionList);
                }
                EditorString = core.addon.execute(editorAddon, new BaseClasses.CPUtilsBaseClass.addonExecuteContext {
                    addonType           = BaseClasses.CPUtilsBaseClass.addonContext.ContextEditor,
                    errorContextMessage = "field editor id:" + editorAddon.id
                });
                useEditorAddon = !string.IsNullOrEmpty(EditorString);
                if (useEditorAddon)
                {
                    //
                    // -- editor worked
                    editorEnv.formFieldList += "," + field.nameLc;
                }
                else
                {
                    //
                    // -- editor failed, determine if it is missing (or inactive). If missing, remove it from the members preferences
                    using (var csData = new CsModel(core)) {
                        if (!csData.openSql("select id from ccaggregatefunctions where id=" + editorAddon.id))
                        {
                            //
                            // -- missing, not just inactive
                            EditorString = "";
                            //
                            // load user's editor preferences to fieldEditorPreferences() - this is the editor this user has picked when there are >1
                            //   fieldId:addonId,fieldId:addonId,etc
                            //   with custom FancyBox form in edit window with button "set editor preference"
                            //   this button causes a 'refresh' action, reloads fields with stream without save
                            //
                            string tmpList  = core.userProperty.getText("editorPreferencesForContent:" + adminData.adminContent.id, "");
                            int    PosStart = GenericController.strInstr(1, "," + tmpList, "," + field.id + ":");
                            if (PosStart > 0)
                            {
                                int PosEnd = GenericController.strInstr(PosStart + 1, "," + tmpList, ",");
                                if (PosEnd == 0)
                                {
                                    tmpList = tmpList.left(PosStart - 1);
                                }
                                else
                                {
                                    tmpList = tmpList.left(PosStart - 1) + tmpList.Substring(PosEnd - 1);
                                }
                                core.userProperty.setProperty("editorPreferencesForContent:" + adminData.adminContent.id, tmpList);
                            }
                        }
                    }
                }
            }
            //
            // -- style for editor wrapper used to limit the width of some editors like integer
            string editorWrapperSyle = "";

            if (!useEditorAddon)
            {
                bool IsEmptyList = false;
                //string NonEncodedLink = null;
                //string EncodedLink = null;
                //
                // if custom editor not used or if it failed
                //
                if (field.fieldTypeId == CPContentBaseClass.FieldTypeIdEnum.Redirect)
                {
                    //
                    // ----- Default Editor, Redirect fields (the same for normal/readonly/spelling)

                    EditorString = AdminUIEditorController.getRedirectEditor(core, field, adminData, editRecord, fieldValue_text, editorReadOnly, fieldHtmlId, field.required);
                    //string RedirectPath = core.appConfig.adminRoute;
                    //if (field.redirectPath != "") {
                    //    RedirectPath = field.redirectPath;
                    //}
                    //RedirectPath = RedirectPath + "?" + RequestNameTitleExtension + "=" + GenericController.encodeRequestVariable(" For " + editRecord.nameLc + adminData.titleExtension) + "&" + RequestNameAdminDepth + "=" + (adminData.ignore_legacyMenuDepth + 1) + "&wl0=" + field.redirectId + "&wr0=" + editRecord.id;
                    //if (field.redirectContentId != 0) {
                    //    RedirectPath = RedirectPath + "&cid=" + field.redirectContentId;
                    //} else {
                    //    RedirectPath = RedirectPath + "&cid=" + ((editRecord.contentControlId.Equals(0)) ? adminData.adminContent.id : editRecord.contentControlId);
                    //}
                    //if (editRecord.id == 0) {
                    //    EditorString += ("[available after save]");
                    //} else {
                    //    RedirectPath = GenericController.strReplace(RedirectPath, "'", "\\'");
                    //    EditorString += ("<a href=\"#\"");
                    //    EditorString += (" onclick=\" window.open('" + RedirectPath + "', '_blank', 'scrollbars=yes,toolbar=no,status=no,resizable=yes'); return false;\"");
                    //    EditorString += (">");
                    //    EditorString += ("Open in New Window</A>");
                    //}
                }
                else if (editorReadOnly)
                {
                    //
                    //--------------------------------------------------------------------------------------------
                    // ----- Display fields as read only
                    //--------------------------------------------------------------------------------------------
                    //
                    if (!string.IsNullOrEmpty(whyReadOnlyMsg))
                    {
                        whyReadOnlyMsg = "<span class=\"ccDisabledReason\">" + whyReadOnlyMsg + "</span>";
                    }
                    switch (field.fieldTypeId)
                    {
                    case CPContentBaseClass.FieldTypeIdEnum.Text:
                    case CPContentBaseClass.FieldTypeIdEnum.Link:
                    case CPContentBaseClass.FieldTypeIdEnum.ResourceLink: {
                        //
                        // ----- Text Type
                        EditorString            += AdminUIEditorController.getTextEditor(core, field.nameLc, fieldValue_text, editorReadOnly, fieldHtmlId);
                        editorEnv.formFieldList += "," + field.nameLc;
                        break;
                    }

                    case CPContentBaseClass.FieldTypeIdEnum.Boolean: {
                        //
                        // ----- Boolean ReadOnly
                        EditorString            += AdminUIEditorController.getBooleanEditor(core, field.nameLc, GenericController.encodeBoolean(fieldValueObject), editorReadOnly, fieldHtmlId);
                        editorEnv.formFieldList += "," + field.nameLc;
                        editorWrapperSyle        = "max-width:400px";
                        break;
                    }

                    case CPContentBaseClass.FieldTypeIdEnum.Lookup: {
                        //
                        // ----- Lookup, readonly
                        if (field.lookupContentId != 0)
                        {
                            EditorString             = AdminUIEditorController.getLookupContentEditor(core, field.nameLc, GenericController.encodeInteger(fieldValueObject), field.lookupContentId, ref IsEmptyList, editorReadOnly, fieldHtmlId, whyReadOnlyMsg, field.required, "");
                            editorEnv.formFieldList += "," + field.nameLc;
                            editorWrapperSyle        = "max-width:400px";
                        }
                        else if (field.lookupList != "")
                        {
                            EditorString             = AdminUIEditorController.getLookupListEditor(core, field.nameLc, encodeInteger(fieldValueObject), field.lookupList.Split(',').ToList(), editorReadOnly, fieldHtmlId, whyReadOnlyMsg, field.required);
                            editorEnv.formFieldList += "," + field.nameLc;
                            editorWrapperSyle        = "max-width:400px";
                        }
                        else
                        {
                            //
                            // -- log exception but dont throw
                            LogController.logWarn(core, new GenericException("Field [" + adminData.adminContent.name + "." + field.nameLc + "] is a Lookup field, but no LookupContent or LookupList has been configured"));
                            EditorString += "[Selection not configured]";
                        }
                        break;
                    }

                    case CPContentBaseClass.FieldTypeIdEnum.Date: {
                        //
                        // ----- date, readonly
                        editorEnv.formFieldList += "," + field.nameLc;
                        EditorString             = AdminUIEditorController.getDateTimeEditor(core, field.nameLc, encodeDate(fieldValueObject), editorReadOnly, fieldHtmlId, field.required, whyReadOnlyMsg);
                        editorWrapperSyle        = "max-width:400px";
                        break;
                    }

                    case CPContentBaseClass.FieldTypeIdEnum.MemberSelect: {
                        //
                        // ----- Member Select ReadOnly
                        editorEnv.formFieldList += "," + field.nameLc;
                        EditorString             = AdminUIEditorController.getMemberSelectEditor(core, field.nameLc, encodeInteger(fieldValueObject), field.memberSelectGroupId_get(core), field.memberSelectGroupName_get(core), editorReadOnly, fieldHtmlId, field.required, whyReadOnlyMsg);
                        editorWrapperSyle        = "max-width:400px";
                        break;
                    }

                    case CPContentBaseClass.FieldTypeIdEnum.ManyToMany: {
                        //
                        //   Placeholder
                        EditorString = AdminUIEditorController.getManyToManyEditor(core, field, "field" + field.id, fieldValue_text, editRecord.id, editorReadOnly, whyReadOnlyMsg);
                        break;
                    }

                    case CPContentBaseClass.FieldTypeIdEnum.Currency: {
                        //
                        // ----- Currency ReadOnly
                        editorEnv.formFieldList += "," + field.nameLc;
                        EditorString            += (HtmlController.inputCurrency(core, field.nameLc, encodeNumber(fieldValue_text), fieldHtmlId, "text form-control", editorReadOnly, false));
                        editorWrapperSyle        = "max-width:400px";
                        break;
                    }

                    case CPContentBaseClass.FieldTypeIdEnum.Float: {
                        //
                        // ----- double/number/float
                        editorEnv.formFieldList += "," + field.nameLc;
                        EditorString            += (HtmlController.inputNumber(core, field.nameLc, encodeNumber(fieldValue_text), fieldHtmlId, "text form-control", editorReadOnly, false));
                        editorWrapperSyle        = "max-width:400px";
                        break;
                    }

                    case CPContentBaseClass.FieldTypeIdEnum.AutoIdIncrement:
                    case CPContentBaseClass.FieldTypeIdEnum.Integer: {
                        //
                        // ----- Others that simply print
                        editorEnv.formFieldList += "," + field.nameLc;
                        EditorString            += (HtmlController.inputInteger(core, field.nameLc, encodeInteger(fieldValue_text), fieldHtmlId, "text form-control", editorReadOnly, false));
                        editorWrapperSyle        = "max-width:400px";
                        break;
                    }

                    case CPContentBaseClass.FieldTypeIdEnum.HTMLCode:
                    case CPContentBaseClass.FieldTypeIdEnum.FileHTMLCode: {
                        //
                        // edit html as html (see the code)
                        editorEnv.formFieldList += "," + field.nameLc;
                        EditorString            += HtmlController.inputHidden(field.nameLc, fieldValue_text);
                        fieldRows     = (core.userProperty.getInteger(adminData.adminContent.name + "." + field.nameLc + ".RowHeight", 10));
                        EditorString += HtmlController.inputTextarea(core, field.nameLc, fieldValue_text, fieldRows, -1, fieldHtmlId, false, editorReadOnly, "form-control");
                        break;
                    }

                    case CPContentBaseClass.FieldTypeIdEnum.HTML:
                    case CPContentBaseClass.FieldTypeIdEnum.FileHTML: {
                        //
                        // ----- HTML types readonly
                        if (field.htmlContent)
                        {
                            //
                            // edit html as html (see the code)
                            editorEnv.formFieldList += "," + field.nameLc;
                            EditorString            += HtmlController.inputHidden(field.nameLc, fieldValue_text);
                            fieldRows     = (core.userProperty.getInteger(adminData.adminContent.name + "." + field.nameLc + ".RowHeight", 10));
                            EditorString += HtmlController.inputTextarea(core, field.nameLc, fieldValue_text, fieldRows, -1, fieldHtmlId, false, editorReadOnly, "form-control");
                        }
                        else
                        {
                            //
                            // edit html as wysiwyg readonly
                            editorEnv.formFieldList += "," + field.nameLc;
                            EditorString            += AdminUIEditorController.getHtmlEditor(core, field.nameLc, fieldValue_text, editorEnv.editorAddonListJSON, editorEnv.styleList, editorEnv.styleOptionList, editorReadOnly, fieldHtmlId);
                        }
                        break;
                    }

                    case CPContentBaseClass.FieldTypeIdEnum.LongText:
                    case CPContentBaseClass.FieldTypeIdEnum.FileText: {
                        //
                        // ----- LongText, TextFile
                        editorEnv.formFieldList += "," + field.nameLc;
                        EditorString            += HtmlController.inputHidden(field.nameLc, fieldValue_text);
                        fieldRows     = (core.userProperty.getInteger(adminData.adminContent.name + "." + field.nameLc + ".RowHeight", 10));
                        EditorString += HtmlController.inputTextarea(core, field.nameLc, fieldValue_text, fieldRows, -1, fieldHtmlId, false, editorReadOnly, " form-control");
                        break;
                    }

                    case CPContentBaseClass.FieldTypeIdEnum.File: {
                        //
                        // ----- File ReadOnly
                        editorEnv.formFieldList += "," + field.nameLc;
                        EditorString             = AdminUIEditorController.getFileEditor(core, field.nameLc, fieldValue_text, field.readOnly, fieldHtmlId, field.required, whyReadOnlyMsg);
                        break;
                    }

                    case CPContentBaseClass.FieldTypeIdEnum.FileImage: {
                        //
                        // ----- Image ReadOnly
                        editorEnv.formFieldList += "," + field.nameLc;
                        EditorString             = AdminUIEditorController.getImageEditor(core, field.nameLc, fieldValue_text, field.readOnly, fieldHtmlId, field.required, whyReadOnlyMsg);
                        break;
                    }

                    default: {
                        //
                        // ----- Legacy text type -- not used unless something was missed
                        editorEnv.formFieldList += "," + field.nameLc;
                        EditorString            += HtmlController.inputHidden(field.nameLc, fieldValue_text);
                        if (field.password)
                        {
                            //
                            // Password forces simple text box
                            EditorString += HtmlController.inputText_Legacy(core, field.nameLc, "*****", 0, 0, fieldHtmlId, true, true, "password form-control");
                        }
                        else if (!field.htmlContent)
                        {
                            //
                            // not HTML capable, textarea with resizing
                            if ((field.fieldTypeId == CPContentBaseClass.FieldTypeIdEnum.Text) && (fieldValue_text.IndexOf("\n") == -1) && (fieldValue_text.Length < 40))
                            {
                                //
                                // text field shorter then 40 characters without a CR
                                EditorString += HtmlController.inputText_Legacy(core, field.nameLc, fieldValue_text, 1, 0, fieldHtmlId, false, true, "text form-control");
                            }
                            else
                            {
                                //
                                // longer text data, or text that contains a CR
                                EditorString += HtmlController.inputTextarea(core, field.nameLc, fieldValue_text, 10, -1, fieldHtmlId, false, true, " form-control");
                            }
                        }
                        else if (field.htmlContent)
                        {
                            //
                            // HTMLContent true, and prefered
                            fieldRows     = (core.userProperty.getInteger(adminData.adminContent.name + "." + field.nameLc + ".PixelHeight", 500));
                            EditorString += core.html.getFormInputHTML(field.nameLc, fieldValue_text, "500", "", false, true, editorEnv.editorAddonListJSON, editorEnv.styleList, editorEnv.styleOptionList);
                            EditorString  = "<div style=\"width:95%\">" + EditorString + "</div>";
                        }
                        else
                        {
                            //
                            // HTMLContent true, but text editor selected
                            fieldRows     = (core.userProperty.getInteger(adminData.adminContent.name + "." + field.nameLc + ".RowHeight", 10));
                            EditorString += HtmlController.inputTextarea(core, field.nameLc, fieldValue_text, fieldRows, -1, fieldHtmlId, false, editorReadOnly);
                        }
                        break;
                    }
                    }
                }
                else
                {
                    //
                    // -- Not Read Only - Display fields as form elements to be modified
                    switch (field.fieldTypeId)
                    {
                    case CPContentBaseClass.FieldTypeIdEnum.Text: {
                        //
                        // ----- Text Type
                        if (field.password)
                        {
                            EditorString += AdminUIEditorController.getPasswordEditor(core, field.nameLc, fieldValue_text, false, fieldHtmlId);
                        }
                        else
                        {
                            EditorString += AdminUIEditorController.getTextEditor(core, field.nameLc, fieldValue_text, false, fieldHtmlId);
                        }
                        editorEnv.formFieldList += "," + field.nameLc;
                        break;
                    }

                    case CPContentBaseClass.FieldTypeIdEnum.Boolean: {
                        //
                        // ----- Boolean
                        EditorString            += AdminUIEditorController.getBooleanEditor(core, field.nameLc, encodeBoolean(fieldValueObject), false, fieldHtmlId);
                        editorEnv.formFieldList += "," + field.nameLc;
                        editorWrapperSyle        = "max-width:400px";
                        break;
                    }

                    case CPContentBaseClass.FieldTypeIdEnum.Lookup: {
                        //
                        // ----- Lookup
                        if (field.lookupContentId != 0)
                        {
                            EditorString             = AdminUIEditorController.getLookupContentEditor(core, field.nameLc, encodeInteger(fieldValueObject), field.lookupContentId, ref IsEmptyList, field.readOnly, fieldHtmlId, whyReadOnlyMsg, field.required, "");
                            editorEnv.formFieldList += "," + field.nameLc;
                            editorWrapperSyle        = "max-width:400px";
                        }
                        else if (field.lookupList != "")
                        {
                            EditorString             = AdminUIEditorController.getLookupListEditor(core, field.nameLc, encodeInteger(fieldValueObject), field.lookupList.Split(',').ToList(), field.readOnly, fieldHtmlId, whyReadOnlyMsg, field.required);
                            editorEnv.formFieldList += "," + field.nameLc;
                            editorWrapperSyle        = "max-width:400px";
                        }
                        else
                        {
                            //
                            // -- log exception but dont throw
                            LogController.logWarn(core, new GenericException("Field [" + adminData.adminContent.name + "." + field.nameLc + "] is a Lookup field, but no LookupContent or LookupList has been configured"));
                            EditorString += "[Selection not configured]";
                        }
                        break;
                    }

                    case CPContentBaseClass.FieldTypeIdEnum.Date: {
                        //
                        // ----- Date
                        editorEnv.formFieldList += "," + field.nameLc;
                        EditorString             = AdminUIEditorController.getDateTimeEditor(core, field.nameLc, GenericController.encodeDate(fieldValueObject), field.readOnly, fieldHtmlId, field.required, whyReadOnlyMsg);
                        editorWrapperSyle        = "max-width:400px";
                        break;
                    }

                    case CPContentBaseClass.FieldTypeIdEnum.MemberSelect: {
                        //
                        // ----- Member Select
                        editorEnv.formFieldList += "," + field.nameLc;
                        EditorString             = AdminUIEditorController.getMemberSelectEditor(core, field.nameLc, encodeInteger(fieldValueObject), field.memberSelectGroupId_get(core), field.memberSelectGroupName_get(core), field.readOnly, fieldHtmlId, field.required, whyReadOnlyMsg);
                        editorWrapperSyle        = "max-width:400px";
                        break;
                    }

                    case CPContentBaseClass.FieldTypeIdEnum.ManyToMany: {
                        //
                        //   Placeholder
                        EditorString = AdminUIEditorController.getManyToManyEditor(core, field, "field" + field.id, fieldValue_text, editRecord.id, false, whyReadOnlyMsg);
                        break;
                    }

                    case CPContentBaseClass.FieldTypeIdEnum.File: {
                        //
                        // ----- File
                        editorEnv.formFieldList += "," + field.nameLc;
                        EditorString             = AdminUIEditorController.getFileEditor(core, field.nameLc, fieldValue_text, field.readOnly, fieldHtmlId, field.required, whyReadOnlyMsg);
                        break;
                    }

                    case CPContentBaseClass.FieldTypeIdEnum.FileImage: {
                        //
                        // ----- Image ReadOnly
                        editorEnv.formFieldList += "," + field.nameLc;
                        EditorString             = AdminUIEditorController.getImageEditor(core, field.nameLc, fieldValue_text, field.readOnly, fieldHtmlId, field.required, whyReadOnlyMsg);
                        break;
                    }

                    case CPContentBaseClass.FieldTypeIdEnum.Currency: {
                        //
                        // ----- currency
                        editorEnv.formFieldList += "," + field.nameLc;
                        EditorString            += AdminUIEditorController.getCurrencyEditor(core, field.nameLc, encodeNumberNullable(fieldValueObject), field.readOnly, fieldHtmlId, field.required, whyReadOnlyMsg);
                        editorWrapperSyle        = "max-width:400px";
                        break;
                    }

                    case CPContentBaseClass.FieldTypeIdEnum.Float: {
                        //
                        // ----- double/number/float
                        editorEnv.formFieldList += "," + field.nameLc;
                        EditorString            += AdminUIEditorController.getNumberEditor(core, field.nameLc, encodeNumberNullable(fieldValueObject), field.readOnly, fieldHtmlId, field.required, whyReadOnlyMsg);
                        editorWrapperSyle        = "max-width:400px";
                        break;
                    }

                    case CPContentBaseClass.FieldTypeIdEnum.AutoIdIncrement:
                    case CPContentBaseClass.FieldTypeIdEnum.Integer: {
                        //
                        // ----- Others that simply print
                        editorEnv.formFieldList += "," + field.nameLc;
                        EditorString            += (HtmlController.inputInteger(core, field.nameLc, encodeIntegerNullable(fieldValue_text), fieldHtmlId, "text form-control", editorReadOnly, false));
                        editorWrapperSyle        = "max-width:400px";
                        break;
                    }

                    case CPContentBaseClass.FieldTypeIdEnum.Link: {
                        //
                        // ----- Link (href value
                        //
                        editorEnv.formFieldList += "," + field.nameLc;
                        EditorString             = AdminUIEditorController.getLinkEditor(core, field.nameLc, fieldValue_text, editorReadOnly, fieldHtmlId, field.required);
                        break;
                    }

                    case CPContentBaseClass.FieldTypeIdEnum.ResourceLink: {
                        //
                        // ----- Resource Link (src value)
                        //
                        editorEnv.formFieldList += "," + field.nameLc;
                        EditorString             = AdminUIEditorController.getLinkEditor(core, field.nameLc, fieldValue_text, editorReadOnly, fieldHtmlId, field.required);
                        break;
                    }

                    case CPContentBaseClass.FieldTypeIdEnum.HTMLCode:
                    case CPContentBaseClass.FieldTypeIdEnum.FileHTMLCode: {
                        //
                        // View the content as Html, not wysiwyg
                        editorEnv.formFieldList += "," + field.nameLc;
                        EditorString             = AdminUIEditorController.getHtmlCodeEditor(core, field.nameLc, fieldValue_text, editorReadOnly, fieldHtmlId);
                        break;
                    }

                    case CPContentBaseClass.FieldTypeIdEnum.HTML:
                    case CPContentBaseClass.FieldTypeIdEnum.FileHTML: {
                        //
                        // content is html
                        editorEnv.formFieldList += "," + field.nameLc;
                        if (field.htmlContent)
                        {
                            //
                            // View the content as Html, not wysiwyg
                            EditorString = AdminUIEditorController.getHtmlCodeEditor(core, field.nameLc, fieldValue_text, editorReadOnly, fieldHtmlId);
                        }
                        else
                        {
                            //
                            // wysiwyg editor
                            EditorString = AdminUIEditorController.getHtmlEditor(core, field.nameLc, fieldValue_text, editorEnv.editorAddonListJSON, editorEnv.styleList, editorEnv.styleOptionList, editorReadOnly, fieldHtmlId);
                        }
                        //
                        break;
                    }

                    case CPContentBaseClass.FieldTypeIdEnum.LongText:
                    case CPContentBaseClass.FieldTypeIdEnum.FileText: {
                        //
                        // -- Long Text, use text editor
                        editorEnv.formFieldList += "," + field.nameLc;
                        fieldRows    = (core.userProperty.getInteger(adminData.adminContent.name + "." + field.nameLc + ".RowHeight", 10));
                        EditorString = HtmlController.inputTextarea(core, field.nameLc, fieldValue_text, fieldRows, -1, fieldHtmlId, false, false, "text form-control");
                        //
                        break;
                    }

                    case CPContentBaseClass.FieldTypeIdEnum.FileCSS: {
                        //
                        // ----- CSS field
                        editorEnv.formFieldList += "," + field.nameLc;
                        fieldRows    = (core.userProperty.getInteger(adminData.adminContent.name + "." + field.nameLc + ".RowHeight", 10));
                        EditorString = HtmlController.inputTextarea(core, field.nameLc, fieldValue_text, fieldRows, -1, fieldHtmlId, false, false, "styles form-control");
                        break;
                    }

                    case CPContentBaseClass.FieldTypeIdEnum.FileJavascript: {
                        //
                        // ----- Javascript field
                        editorEnv.formFieldList += "," + field.nameLc;
                        fieldRows    = (core.userProperty.getInteger(adminData.adminContent.name + "." + field.nameLc + ".RowHeight", 10));
                        EditorString = HtmlController.inputTextarea(core, field.nameLc, fieldValue_text, fieldRows, -1, fieldHtmlId, false, false, "text form-control");
                        //
                        break;
                    }

                    case CPContentBaseClass.FieldTypeIdEnum.FileXML: {
                        //
                        // ----- xml field
                        editorEnv.formFieldList += "," + field.nameLc;
                        fieldRows    = (core.userProperty.getInteger(adminData.adminContent.name + "." + field.nameLc + ".RowHeight", 10));
                        EditorString = HtmlController.inputTextarea(core, field.nameLc, fieldValue_text, fieldRows, -1, fieldHtmlId, false, false, "text form-control");
                        //
                        break;
                    }

                    default: {
                        //
                        // ----- Legacy text type -- not used unless something was missed
                        //
                        editorEnv.formFieldList += "," + field.nameLc;
                        if (field.password)
                        {
                            //
                            // Password forces simple text box
                            EditorString = HtmlController.inputText_Legacy(core, field.nameLc, fieldValue_text, -1, -1, fieldHtmlId, true, false, "password form-control");
                        }
                        else if (!field.htmlContent)
                        {
                            //
                            // not HTML capable, textarea with resizing
                            //
                            if ((field.fieldTypeId == CPContentBaseClass.FieldTypeIdEnum.Text) && (fieldValue_text.IndexOf("\n", StringComparison.InvariantCulture) == -1) && (fieldValue_text.Length < 40))
                            {
                                //
                                // text field shorter then 40 characters without a CR
                                //
                                EditorString = HtmlController.inputText_Legacy(core, field.nameLc, fieldValue_text, 1, -1, fieldHtmlId, false, false, "text form-control");
                            }
                            else
                            {
                                //
                                // longer text data, or text that contains a CR
                                //
                                EditorString = HtmlController.inputTextarea(core, field.nameLc, fieldValue_text, 10, -1, fieldHtmlId, false, false, "text form-control");
                            }
                        }
                        else if (field.htmlContent)
                        {
                            //
                            // HTMLContent true, and prefered
                            //
                            if (string.IsNullOrEmpty(fieldValue_text))
                            {
                                //
                                // editor needs a starting p tag to setup correctly
                                //
                                fieldValue_text = HTMLEditorDefaultCopyNoCr;
                            }
                            fieldRows     = (core.userProperty.getInteger(adminData.adminContent.name + "." + field.nameLc + ".PixelHeight", 500));
                            EditorString += core.html.getFormInputHTML(field.nameLc, fieldValue_text, "500", "", false, true, editorEnv.editorAddonListJSON, editorEnv.styleList, editorEnv.styleOptionList);
                            EditorString  = "<div style=\"width:95%\">" + EditorString + "</div>";
                        }
                        else
                        {
                            //
                            // HTMLContent true, but text editor selected
                            fieldRows    = (core.userProperty.getInteger(adminData.adminContent.name + "." + field.nameLc + ".RowHeight", 10));
                            EditorString = HtmlController.inputTextarea(core, field.nameLc, HtmlController.encodeHtml(fieldValue_text), fieldRows, -1, fieldHtmlId, false, false, "text");
                        }
                        break;
                    }
                    }
                }
            }
            //
            // assemble the editor row
            return(AdminUIController.getEditRow(core, EditorString, fieldCaption, field.helpDefault, field.required, false, fieldHtmlId, editorWrapperSyle));
        }
예제 #25
0
 //
 //=========================================================================================
 // Summarize the visits
 //   excludes non-cookie visits
 //   excludes administrator and developer visits
 //   excludes authenticated users with ExcludeFromReporting
 //
 // Average time on site
 //
 //   Example data
 //   Pages       TimeToLastHit
 //   1           0           - hit 1 page, start time = last time
 //   10          3510        - hit 10 pages, first hit time - last hit time = 3510
 //   2           30          - hit 2 pages, first hit time - last hit time = 30
 //
 // AveReadTime is the average time spent reading pages
 //   this is calculated from the multi-page visits only
 //   = MultiPageTimeToLastHitSum / ( MultiPageHitCnt - MultiPageVisitCnt )
 //   = ( 3510 + 30 ) / ((10+2) - 2 )
 //   = 354
 //
 // TotalTimeOnSite is the total time people spent reading pages
 //   There are two parts:
 //     1) the TimeToLastHit, which covers all but the last hit of each visit
 //     2) assume the last hit of each visit is the AveReadTime
 //   = MultiPageTimeToLastHitSum + ( AveReadTime * VisitCnt )
 //   = ( 3510 + 30 ) + ( 354 * 3 )
 //   = 4602
 //
 // AveTimeOnSite
 //   = TotalTimeOnSite / TotalHits
 //   = 4602 / 3
 //   = 1534
 //
 //=========================================================================================
 //
 private static void summarizePeriod(CoreController core, HouseKeepEnvironmentModel env, DateTime StartTimeDate, DateTime EndTimeDate, int HourDuration, string BuildVersion, DateTime OldestVisitSummaryWeCareAbout)
 {
     try {
         //
         if (string.CompareOrdinal(BuildVersion, CoreController.codeVersion()) >= 0)
         {
             DateTime PeriodStart = default(DateTime);
             PeriodStart = StartTimeDate;
             if (PeriodStart < OldestVisitSummaryWeCareAbout)
             {
                 PeriodStart = OldestVisitSummaryWeCareAbout;
             }
             double StartTimeHoursSinceMidnight = PeriodStart.TimeOfDay.TotalHours;
             PeriodStart = PeriodStart.Date.AddHours(StartTimeHoursSinceMidnight);
             DateTime PeriodDatePtr = default(DateTime);
             PeriodDatePtr = PeriodStart;
             while (PeriodDatePtr < EndTimeDate)
             {
                 //
                 int      DateNumber = encodeInteger(PeriodDatePtr.AddHours(HourDuration / 2.0).ToOADate());
                 int      TimeNumber = encodeInteger(PeriodDatePtr.TimeOfDay.TotalHours);
                 DateTime DateStart  = default(DateTime);
                 DateStart = PeriodDatePtr.Date;
                 DateTime DateEnd = default(DateTime);
                 DateEnd = PeriodDatePtr.AddHours(HourDuration).Date;
                 //
                 // No Cookie Visits
                 //
                 string SQL = "select count(v.id) as NoCookieVisits"
                              + " from ccvisits v"
                              + " where (v.CookieSupport<>1)"
                              + " and(v.dateadded>=" + DbController.encodeSQLDate(DateStart) + ")"
                              + " and (v.dateadded<" + DbController.encodeSQLDate(DateEnd) + ")"
                              + " and((v.ExcludeFromAnalytics is null)or(v.ExcludeFromAnalytics=0))"
                              + "";
                 int NoCookieVisits = 0;
                 using (var csData = new CsModel(core)) {
                     core.db.sqlCommandTimeout = 180;
                     csData.openSql(SQL);
                     if (csData.ok())
                     {
                         NoCookieVisits = csData.getInteger("NoCookieVisits");
                     }
                 }
                 //
                 // Total Visits
                 //
                 SQL = "select count(v.id) as VisitCnt ,Sum(v.PageVisits) as HitCnt ,sum(v.TimetoLastHit) as TimeOnSite"
                       + " from ccvisits v"
                       + " where (v.CookieSupport<>0)"
                       + " and(v.dateadded>=" + DbController.encodeSQLDate(DateStart) + ")"
                       + " and (v.dateadded<" + DbController.encodeSQLDate(DateEnd) + ")"
                       + " and((v.ExcludeFromAnalytics is null)or(v.ExcludeFromAnalytics=0))"
                       + "";
                 //
                 int VisitCnt = 0;
                 int HitCnt   = 0;
                 using (var csData = new CsModel(core)) {
                     core.db.sqlCommandTimeout = 180;
                     csData.openSql(SQL);
                     if (csData.ok())
                     {
                         VisitCnt = csData.getInteger("VisitCnt");
                         HitCnt   = csData.getInteger("HitCnt");
                         double TimeOnSite = csData.getNumber("TimeOnSite");
                     }
                 }
                 //
                 // -- Visits by new visitors
                 int    NewVisitorVisits    = 0;
                 int    SinglePageVisits    = 0;
                 int    AuthenticatedVisits = 0;
                 int    MobileVisits        = 0;
                 int    BotVisits           = 0;
                 double AveTimeOnSite       = 0;
                 if (VisitCnt > 0)
                 {
                     SQL = "select count(v.id) as NewVisitorVisits"
                           + " from ccvisits v"
                           + " where (v.CookieSupport<>0)"
                           + " and(v.dateadded>=" + DbController.encodeSQLDate(DateStart) + ")"
                           + " and (v.dateadded<" + DbController.encodeSQLDate(DateEnd) + ")"
                           + " and((v.ExcludeFromAnalytics is null)or(v.ExcludeFromAnalytics=0))"
                           + " and(v.VisitorNew<>0)"
                           + "";
                     using (var csData = new CsModel(core)) {
                         core.db.sqlCommandTimeout = 180;
                         csData.openSql(SQL);
                         if (csData.ok())
                         {
                             NewVisitorVisits = csData.getInteger("NewVisitorVisits");
                         }
                     }
                     //
                     // Single Page Visits
                     //
                     SQL = "select count(v.id) as SinglePageVisits"
                           + " from ccvisits v"
                           + " where (v.CookieSupport<>0)"
                           + " and(v.dateadded>=" + DbController.encodeSQLDate(DateStart) + ")"
                           + " and (v.dateadded<" + DbController.encodeSQLDate(DateEnd) + ")"
                           + " and((v.ExcludeFromAnalytics is null)or(v.ExcludeFromAnalytics=0))"
                           + " and(v.PageVisits=1)"
                           + "";
                     using (var csData = new CsModel(core)) {
                         core.db.sqlCommandTimeout = 180;
                         csData.openSql(SQL);
                         if (csData.ok())
                         {
                             SinglePageVisits = csData.getInteger("SinglePageVisits");
                         }
                     }
                     //
                     // Multipage Visits
                     //
                     SQL = "select count(v.id) as VisitCnt ,sum(v.PageVisits) as HitCnt ,sum(v.TimetoLastHit) as TimetoLastHitSum "
                           + " from ccvisits v"
                           + " where (v.CookieSupport<>0)"
                           + " and(v.dateadded>=" + DbController.encodeSQLDate(DateStart) + ")"
                           + " and (v.dateadded<" + DbController.encodeSQLDate(DateEnd) + ")"
                           + " and((v.ExcludeFromAnalytics is null)or(v.ExcludeFromAnalytics=0))"
                           + " and(PageVisits>1)"
                           + "";
                     int    MultiPageHitCnt           = 0;
                     int    MultiPageVisitCnt         = 0;
                     double MultiPageTimetoLastHitSum = 0;
                     using (var csData = new CsModel(core)) {
                         core.db.sqlCommandTimeout = 180;
                         csData.openSql(SQL);
                         if (csData.ok())
                         {
                             MultiPageVisitCnt         = csData.getInteger("VisitCnt");
                             MultiPageHitCnt           = csData.getInteger("HitCnt");
                             MultiPageTimetoLastHitSum = csData.getNumber("TimetoLastHitSum");
                         }
                     }
                     //
                     // Authenticated Visits
                     //
                     SQL = "select count(v.id) as AuthenticatedVisits "
                           + " from ccvisits v"
                           + " where (v.CookieSupport<>0)"
                           + " and(v.dateadded>=" + DbController.encodeSQLDate(DateStart) + ")"
                           + " and (v.dateadded<" + DbController.encodeSQLDate(DateEnd) + ")"
                           + " and((v.ExcludeFromAnalytics is null)or(v.ExcludeFromAnalytics=0))"
                           + " and(VisitAuthenticated<>0)"
                           + "";
                     using (var csData = new CsModel(core)) {
                         core.db.sqlCommandTimeout = 180;
                         csData.openSql(SQL);
                         if (csData.ok())
                         {
                             AuthenticatedVisits = csData.getInteger("AuthenticatedVisits");
                         }
                     }
                     //
                     //
                     // Mobile Visits
                     //
                     SQL = "select count(v.id) as cnt "
                           + " from ccvisits v"
                           + " where (v.CookieSupport<>0)"
                           + " and(v.dateadded>=" + DbController.encodeSQLDate(DateStart) + ")"
                           + " and (v.dateadded<" + DbController.encodeSQLDate(DateEnd) + ")"
                           + " and((v.ExcludeFromAnalytics is null)or(v.ExcludeFromAnalytics=0))"
                           + " and(Mobile<>0)"
                           + "";
                     using (var csData = new CsModel(core)) {
                         core.db.sqlCommandTimeout = 180;
                         csData.openSql(SQL);
                         if (csData.ok())
                         {
                             MobileVisits = csData.getInteger("cnt");
                         }
                     }
                     //
                     // Bot Visits
                     //
                     SQL = "select count(v.id) as cnt "
                           + " from ccvisits v"
                           + " where (v.CookieSupport<>0)"
                           + " and(v.dateadded>=" + DbController.encodeSQLDate(DateStart) + ")"
                           + " and (v.dateadded<" + DbController.encodeSQLDate(DateEnd) + ")"
                           + " and((v.ExcludeFromAnalytics is null)or(v.ExcludeFromAnalytics=0))"
                           + " and(Bot<>0)"
                           + "";
                     using (var csData = new CsModel(core)) {
                         core.db.sqlCommandTimeout = 180;
                         csData.openSql(SQL);
                         if (csData.ok())
                         {
                             BotVisits = csData.getInteger("cnt");
                         }
                     }
                     //
                     if ((MultiPageHitCnt > MultiPageVisitCnt) && (HitCnt > 0))
                     {
                         int    AveReadTime     = encodeInteger(MultiPageTimetoLastHitSum / (MultiPageHitCnt - MultiPageVisitCnt));
                         double TotalTimeOnSite = MultiPageTimetoLastHitSum + (AveReadTime * VisitCnt);
                         AveTimeOnSite = TotalTimeOnSite / VisitCnt;
                     }
                 }
                 //
                 // Add or update the Visit Summary Record
                 //
                 using (var csData = new CsModel(core)) {
                     core.db.sqlCommandTimeout = 180;
                     csData.open("Visit Summary", "(timeduration=" + HourDuration + ")and(DateNumber=" + DateNumber + ")and(TimeNumber=" + TimeNumber + ")");
                     if (!csData.ok())
                     {
                         csData.close();
                         csData.insert("Visit Summary");
                     }
                     //
                     if (csData.ok())
                     {
                         csData.set("name", HourDuration + " hr summary for " + DateTime.FromOADate(DateNumber).ToShortDateString() + " " + TimeNumber + ":00");
                         csData.set("DateNumber", DateNumber);
                         csData.set("TimeNumber", TimeNumber);
                         csData.set("Visits", VisitCnt);
                         csData.set("PagesViewed", HitCnt);
                         csData.set("TimeDuration", HourDuration);
                         csData.set("NewVisitorVisits", NewVisitorVisits);
                         csData.set("SinglePageVisits", SinglePageVisits);
                         csData.set("AuthenticatedVisits", AuthenticatedVisits);
                         csData.set("NoCookieVisits", NoCookieVisits);
                         csData.set("AveTimeOnSite", AveTimeOnSite);
                         {
                             csData.set("MobileVisits", MobileVisits);
                             csData.set("BotVisits", BotVisits);
                         }
                     }
                 }
                 PeriodDatePtr = PeriodDatePtr.AddHours(HourDuration);
             }
             {
                 //
                 // Delete any daily visit summary duplicates during this period(keep the first)
                 //
                 string SQL = "delete from ccvisitsummary"
                              + " where id in ("
                              + " select d.id from ccvisitsummary d,ccvisitsummary f"
                              + " where f.datenumber=d.datenumber"
                              + " and f.datenumber>" + env.oldestVisitSummaryWeCareAbout.ToOADate() + " and f.datenumber<" + env.yesterday.ToOADate() + " and f.TimeDuration=24"
                              + " and d.TimeDuration=24"
                              + " and f.id<d.id"
                              + ")";
                 core.db.sqlCommandTimeout = 180;
                 core.db.executeNonQuery(SQL);
                 //
                 // Find missing daily summaries, summarize that date
                 //
                 SQL = core.db.getSQLSelect("ccVisitSummary", "DateNumber", "TimeDuration=24 and DateNumber>=" + env.oldestVisitSummaryWeCareAbout.Date.ToOADate(), "DateNumber,TimeNumber");
                 using (var csData = new CsModel(core)) {
                     csData.openSql(SQL);
                     DateTime datePtr = env.oldestVisitSummaryWeCareAbout;
                     while (datePtr <= env.yesterday)
                     {
                         if (!csData.ok())
                         {
                             //
                             // Out of data, start with this DatePtr
                             //
                             VisitSummaryClass.summarizePeriod(core, env, datePtr, datePtr, 24, core.siteProperties.dataBuildVersion, env.oldestVisitSummaryWeCareAbout);
                         }
                         else
                         {
                             DateTime workingDate = DateTime.MinValue.AddDays(csData.getInteger("DateNumber"));
                             if (datePtr < workingDate)
                             {
                                 //
                                 // There are missing dates, update them
                                 //
                                 VisitSummaryClass.summarizePeriod(core, env, datePtr, workingDate.AddDays(-1), 24, core.siteProperties.dataBuildVersion, env.oldestVisitSummaryWeCareAbout);
                             }
                         }
                         if (csData.ok())
                         {
                             //
                             // if there is more data, go to the next record
                             //
                             csData.goNext();
                         }
                         datePtr = datePtr.AddDays(1).Date;
                     }
                     csData.close();
                 }
             }
         }
         //
         return;
     } catch (Exception ex) {
         LogController.logError(core, ex);
     }
 }
예제 #26
0
 public static void housekeep(CoreController core, HouseKeepEnvironmentModel env)
 {
     try {
         //
         LogController.logInfo(core, "Housekeep, metadata");
         //
         //
         // block duplicate redirect fields (match contentid+fieldtype+caption)
         //
         LogController.logInfo(core, "Inactivate duplicate redirect fields");
         int    FieldContentId = 0;
         string FieldLast      = null;
         string FieldNew       = null;
         int    FieldRecordId  = 0;
         using (var csData = new CsModel(core)) {
             csData.openSql("Select ID, ContentID, Type, Caption from ccFields where (active<>0)and(Type=" + (int)CPContentBaseClass.FieldTypeIdEnum.Redirect + ") Order By ContentID, Caption, ID");
             FieldLast = "";
             while (csData.ok())
             {
                 FieldContentId = csData.getInteger("Contentid");
                 string FieldCaption = csData.getText("Caption");
                 FieldNew = FieldContentId + FieldCaption;
                 if (FieldNew == FieldLast)
                 {
                     FieldRecordId = csData.getInteger("ID");
                     core.db.executeNonQuery("Update ccFields set active=0 where ID=" + FieldRecordId + ";");
                 }
                 FieldLast = FieldNew;
                 csData.goNext();
             }
         }
         //
         // convert FieldTypeLongText + htmlContent to FieldTypeHTML
         LogController.logInfo(core, "convert FieldTypeLongText + htmlContent to FieldTypeHTML.");
         string sql = "update ccfields set type=" + (int)CPContentBaseClass.FieldTypeIdEnum.HTML + " where type=" + (int)CPContentBaseClass.FieldTypeIdEnum.LongText + " and ( htmlcontent<>0 )";
         core.db.executeNonQuery(sql);
         //
         // Content TextFile types with no controlling record
         //
         if (GenericController.encodeBoolean(core.siteProperties.getText("ArchiveAllowFileClean", "false")))
         {
             //
             int DSType = core.db.getDataSourceType();
             LogController.logInfo(core, "Content TextFile types with no controlling record.");
             using (var csData = new CsModel(core)) {
                 sql = "SELECT DISTINCT ccTables.Name as TableName, ccFields.Name as FieldName"
                       + " FROM (ccFields LEFT JOIN ccContent ON ccFields.ContentId = ccContent.ID) LEFT JOIN ccTables ON ccContent.ContentTableId = ccTables.ID"
                       + " Where (((ccFields.Type) = 10))"
                       + " ORDER BY ccTables.Name";
                 csData.openSql(sql);
                 while (csData.ok())
                 {
                     //
                     // Get all the files in this path, and check that the record exists with this in its field
                     //
                     string FieldName = csData.getText("FieldName");
                     string TableName = csData.getText("TableName");
                     string PathName  = TableName + "\\" + FieldName;
                     List <CPFileSystemBaseClass.FileDetail> FileList = core.cdnFiles.getFileList(PathName);
                     if (FileList.Count > 0)
                     {
                         core.db.executeNonQuery("CREATE INDEX temp" + FieldName + " ON " + TableName + " (" + FieldName + ")");
                         foreach (CPFileSystemBaseClass.FileDetail file in FileList)
                         {
                             string Filename        = file.Name;
                             string VirtualFileName = PathName + "\\" + Filename;
                             string VirtualLink     = GenericController.strReplace(VirtualFileName, "\\", "/");
                             long   FileSize        = file.Size;
                             if (FileSize == 0)
                             {
                                 sql = "update " + TableName + " set " + FieldName + "=null where (" + FieldName + "=" + DbController.encodeSQLText(VirtualFileName) + ")or(" + FieldName + "=" + DbController.encodeSQLText(VirtualLink) + ")";
                                 core.db.executeNonQuery(sql);
                                 core.cdnFiles.deleteFile(VirtualFileName);
                             }
                             else
                             {
                                 using (var csTest = new CsModel(core)) {
                                     sql = "SELECT ID FROM " + TableName + " WHERE (" + FieldName + "=" + DbController.encodeSQLText(VirtualFileName) + ")or(" + FieldName + "=" + DbController.encodeSQLText(VirtualLink) + ")";
                                     if (!csTest.openSql(sql))
                                     {
                                         core.cdnFiles.deleteFile(VirtualFileName);
                                     }
                                 }
                             }
                         }
                         if (DSType == 1)
                         {
                             // access
                             sql = "Drop INDEX temp" + FieldName + " ON " + TableName;
                         }
                         else if (DSType == 2)
                         {
                             // sql server
                             sql = "DROP INDEX " + TableName + ".temp" + FieldName;
                         }
                         else
                         {
                             // mysql
                             sql = "ALTER TABLE " + TableName + " DROP INDEX temp" + FieldName;
                         }
                         core.db.executeNonQuery(sql);
                     }
                     csData.goNext();
                 }
             }
         }
     } catch (Exception ex) {
         LogController.logError(core, ex);
     }
 }
예제 #27
0
 //
 //=========================================================================================
 /// <summary>
 /// summarized visits hourly
 /// </summary>
 /// <param name="core"></param>
 /// <param name="env"></param>
 public static void housekeep(CoreController core, HouseKeepEnvironmentModel env)
 {
     try {
         //
         LogController.logInfo(core, "Housekeep, visitsummary");
         //
         bool newHour = (core.dateTimeNowMockable.Hour != env.lastCheckDateTime.Hour);
         if (env.forceHousekeep || newHour)
         {
             //
             // Set NextSummaryStartDate based on the last time we ran hourly summarization
             //
             DateTime LastTimeSummaryWasRun = env.visitArchiveDate;
             core.db.sqlCommandTimeout = 180;
             using (var csData = new CsModel(core)) {
                 if (csData.openSql(core.db.getSQLSelect("ccVisitSummary", "DateAdded", "(timeduration=1)and(Dateadded>" + DbController.encodeSQLDate(env.visitArchiveDate) + ")", "id Desc", "", 1)))
                 {
                     LastTimeSummaryWasRun = csData.getDate("DateAdded");
                     LogController.logInfo(core, "Update hourly visit summary, last time summary was run was [" + LastTimeSummaryWasRun + "]");
                 }
                 else
                 {
                     LogController.logInfo(core, "Update hourly visit summary, no hourly summaries were found, set start to [" + LastTimeSummaryWasRun + "]");
                 }
             }
             DateTime NextSummaryStartDate = LastTimeSummaryWasRun;
             //
             // Each hourly entry includes visits that started during that hour, but we do not know when they finished (maybe during last hour)
             //   Find the oldest starttime of all the visits with endtimes after the LastTimeSummaryWasRun. Resummarize all periods
             //   from then to now
             //
             //   For the past 24 hours, find the oldest visit with the last viewing during the last hour
             //
             DateTime StartOfHour     = (new DateTime(LastTimeSummaryWasRun.Year, LastTimeSummaryWasRun.Month, LastTimeSummaryWasRun.Day, LastTimeSummaryWasRun.Hour, 1, 1)).AddHours(-1); // (Int(24 * LastTimeSummaryWasRun) / 24) - PeriodStep
             DateTime OldestDateAdded = StartOfHour;
             core.db.sqlCommandTimeout = 180;
             using (var csData = new CsModel(core)) {
                 if (csData.openSql(core.db.getSQLSelect("ccVisits", "DateAdded", "LastVisitTime>" + DbController.encodeSQLDate(StartOfHour), "dateadded", "", 1)))
                 {
                     OldestDateAdded = csData.getDate("DateAdded");
                     if (OldestDateAdded < NextSummaryStartDate)
                     {
                         NextSummaryStartDate = OldestDateAdded;
                         LogController.logInfo(core, "Update hourly visit summary, found a visit with the last viewing during the past hour. It started [" + OldestDateAdded + "], before the last summary was run.");
                     }
                 }
             }
             DateTime PeriodStartDate = core.dateTimeNowMockable.Date.AddDays(-90);
             double   PeriodStep      = 1;
             int      HoursPerDay     = 0;
             core.db.sqlCommandTimeout = 180;
             for (double PeriodDatePtr = PeriodStartDate.ToOADate(); PeriodDatePtr <= OldestDateAdded.ToOADate(); PeriodDatePtr += PeriodStep)
             {
                 //
                 // Verify there are 24 hour records for every day back the past 90 days
                 //
                 DateTime DateofMissingSummary = DateTime.MinValue;
                 using (var csData = new CsModel(core)) {
                     if (csData.openSql("select count(id) as HoursPerDay from ccVisitSummary where TimeDuration=1 and DateNumber=" + encodeInteger(PeriodDatePtr) + " group by DateNumber"))
                     {
                         HoursPerDay = csData.getInteger("HoursPerDay");
                     }
                     csData.close();
                     if (HoursPerDay < 24)
                     {
                         DateofMissingSummary = DateTime.FromOADate(PeriodDatePtr);
                         break;
                     }
                 }
                 if ((DateofMissingSummary != DateTime.MinValue) && (DateofMissingSummary < NextSummaryStartDate))
                 {
                     LogController.logInfo(core, "Found a missing hourly period in the visit summary table [" + DateofMissingSummary + "], it only has [" + HoursPerDay + "] hourly summaries.");
                     NextSummaryStartDate = DateofMissingSummary;
                 }
                 //
                 // Now summarize all visits during all hourly periods between OldestDateAdded and the previous Hour
                 //
                 LogController.logInfo(core, "Summaryize visits hourly, starting [" + NextSummaryStartDate + "]");
                 PeriodStep = (double)1 / (double)24;
                 VisitSummaryClass.summarizePeriod(core, env, NextSummaryStartDate, core.dateTimeNowMockable, 1, core.siteProperties.dataBuildVersion, env.oldestVisitSummaryWeCareAbout);
             }
         }
     } catch (Exception ex) {
         LogController.logError(core, ex);
     }
 }