Exemplo n.º 1
0
 //
 //====================================================================================================
 //
 public override void GoNext()
 {
     try {
         cs.goNext();
     } catch (Exception ex) {
         LogController.logError(cp.core, ex);
         throw;
     }
 }
Exemplo n.º 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);
     }
 }
Exemplo n.º 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);
     }
 }
Exemplo n.º 4
0
        //=============================================================================
        /// <summary>
        /// Go through all Content Definitions and create appropriate tables and fields.
        /// </summary>
        /// <returns></returns>
        public static string get(CoreController core)
        {
            string returnValue = "";

            try {
                Processor.Models.Domain.ContentMetadataModel metadata = null;
                StringBuilderLegacyController Stream = new StringBuilderLegacyController();
                string[,] ContentNameArray = null;
                int    ContentNameCount = 0;
                string TableName        = null;
                string ButtonList;
                //
                ButtonList = ButtonCancel + "," + ButtonRun;
                //
                Stream.add(AdminUIController.getHeaderTitleDescription("Synchronize Tables to Content Definitions", "This tools goes through all Content Definitions and creates any necessary Tables and Table Fields to support the Definition."));
                //
                if (core.docProperties.getText("Button") != "")
                {
                    //
                    //   Run Tools
                    //
                    Stream.add("Synchronizing Tables to Content Definitions<br>");
                    using (var csData = new CsModel(core)) {
                        csData.open("Content", "", "", false, 0, "id");
                        if (csData.ok())
                        {
                            do
                            {
                                metadata  = Processor.Models.Domain.ContentMetadataModel.create(core, csData.getInteger("id"));
                                TableName = metadata.tableName;
                                Stream.add("Synchronizing Content " + metadata.name + " to table " + TableName + "<br>");
                                using (var db = new DbController(core, metadata.dataSourceName)) {
                                    db.createSQLTable(TableName);
                                    if (metadata.fields.Count > 0)
                                    {
                                        foreach (var keyValuePair in metadata.fields)
                                        {
                                            ContentFieldMetadataModel field = keyValuePair.Value;
                                            Stream.add("...Field " + field.nameLc + "<br>");
                                            db.createSQLTableField(TableName, field.nameLc, field.fieldTypeId);
                                        }
                                    }
                                }
                                csData.goNext();
                            } while (csData.ok());
                            ContentNameArray = csData.getRows();
                            ContentNameCount = ContentNameArray.GetUpperBound(1) + 1;
                        }
                    }
                }
                returnValue = AdminUIController.getToolForm(core, Stream.text, ButtonList);
            } catch (Exception ex) {
                LogController.logError(core, ex);
                throw;
            }
            return(returnValue);
        }
Exemplo n.º 5
0
 //
 //=============================================================================
 // Print the See Also listing
 //   ContentName is the name of the parent table
 //   RecordID is the parent RecordID
 //=============================================================================
 //
 public static string getSeeAlso(CoreController core)
 {
     try {
         if (core.doc.pageController.page.id == 0)
         {
             return(string.Empty);
         }
         int    SeeAlsoCount = 0;
         string result       = "";
         using (var cs = new CsModel(core)) {
             if (cs.open("See Also", "(RecordID=" + core.doc.pageController.page.id + ")"))
             {
                 do
                 {
                     string link = cs.getText("Link");
                     if ((!string.IsNullOrWhiteSpace(link)) && (!link.Contains("://")))
                     {
                         link = core.webServer.requestProtocol + link;
                     }
                     string editAnchorTag = (!core.session.isEditing() ? "" : AdminUIController.getRecordEditAnchorTag(core, "See Also", cs.getInteger("ID")));
                     string pageAnchorTag = HtmlController.a(cs.getText("name"), HtmlController.encodeHtml(link));
                     string brief         = cs.getText("Brief");
                     if (!string.IsNullOrEmpty(brief))
                     {
                         brief = HtmlController.p(brief, "ccListCopy");
                     }
                     result       += HtmlController.li(editAnchorTag + pageAnchorTag + brief, "ccListItem");
                     SeeAlsoCount += 1;
                     cs.goNext();
                 } while (cs.ok());
             }
         }
         if (core.session.isEditing())
         {
             SeeAlsoCount += 1;
             foreach (var AddLink in AdminUIController.getRecordAddAnchorTag(core, "See Also", "RecordID=" + core.doc.pageController.page.id))
             {
                 if (!string.IsNullOrEmpty(AddLink))
                 {
                     result += HtmlController.li(AddLink, "ccEditWrapper ccListItem");
                 }
             }
         }
         if (SeeAlsoCount == 0)
         {
             return(string.Empty);
         }
         return(HtmlController.div(HtmlController.h4("See Also") + HtmlController.ul(result, "ccList"), "ccSeeAlso"));
     } catch (Exception ex) {
         LogController.logError(core, ex);
         return(string.Empty);
     }
 }
Exemplo n.º 6
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);
     }
 }
Exemplo n.º 7
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");
             }
         }
     }
 }
Exemplo n.º 8
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);
     }
 }
        //
        //=============================================================================
        // 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);
        }
Exemplo n.º 10
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);
     }
 }
Exemplo n.º 11
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);
        }
        //
        //=============================================================================
        /// <summary>
        /// Remove all Content Fields and rebuild them from the fields found in a table
        /// </summary>
        /// <param name="core"></param>
        /// <returns></returns>
        //
        public static string get(CoreController core)
        {
            string result = "";

            try {
                string Button = core.docProperties.getText("Button");
                StringBuilderLegacyController Stream = new StringBuilderLegacyController();
                //
                //   print out the submit form
                //
                Stream.add("<table border=\"0\" cellpadding=\"11\" cellspacing=\"0\" width=\"100%\">");
                //
                Stream.add("<tr><td colspan=\"2\">" + SpanClassAdminNormal);
                Stream.add("Delete the current content field definitions for this Content Definition, and recreate them from the table referenced by this content.");
                Stream.add("</SPAN></td></tr>");
                //
                Stream.add("<tr>");
                Stream.add("<TD>" + SpanClassAdminNormal + "Content Name</SPAN></td>");
                Stream.add("<TD><Select name=\"ContentName\">");
                int ItemCount = 0;
                using (var csData = new CsModel(core)) {
                    csData.open("Content", "", "name");
                    while (csData.ok())
                    {
                        Stream.add("<option value=\"" + csData.getText("name") + "\">" + csData.getText("name") + "</option>");
                        ItemCount = ItemCount + 1;
                        csData.goNext();
                    }
                }
                if (ItemCount == 0)
                {
                    Stream.add("<option value=\"-1\">System</option>");
                }
                Stream.add("</select></td>");
                Stream.add("</tr>");
                //
                Stream.add("<tr>");
                Stream.add("<TD>&nbsp;</td>");
                Stream.add("<TD>" + HtmlController.inputSubmit(ButtonCreateFields) + "</td>");
                Stream.add("</tr>");
                //
                Stream.add("<tr>");
                Stream.add("<td width=\"150\"><IMG alt=\"\" src=\"" + cdnPrefix + "Images/spacer.gif\" width=\"150\" height=\"1\"></td>");
                Stream.add("<td width=\"99%\"><IMG alt=\"\" src=\"" + cdnPrefix + "Images/spacer.gif\" width=\"100%\" height=\"1\"></td>");
                Stream.add("</tr>");
                Stream.add("</TABLE>");
                Stream.add("</form>");
                //
                //   process the button if present
                //
                if (Button == ButtonCreateFields)
                {
                    string ContentName = core.docProperties.getText("ContentName");
                    if (string.IsNullOrEmpty(ContentName))
                    {
                        Stream.add("Select a content before submitting. Fields were not changed.");
                    }
                    else
                    {
                        int ContentId = ContentMetadataModel.getContentId(core, ContentName);
                        if (ContentId == 0)
                        {
                            Stream.add("GetContentID failed. Fields were not changed.");
                        }
                        else
                        {
                            MetadataController.deleteContentRecords(core, "Content Fields", "ContentID=" + DbController.encodeSQLNumber(ContentId));
                            //
                            // todo -- looks like the tool code did not come with the migration ?
                            //
                        }
                    }
                }
                string ButtonList = "";
                result = AdminUIController.getToolForm(core, Stream.text, ButtonList);
            } catch (Exception ex) {
                LogController.logError(core, ex);
            }
            return(result);
        }
Exemplo n.º 13
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."));
            }
        }
Exemplo n.º 14
0
        //
        //====================================================================================================
        /// <summary>
        /// Send the Member his username and password
        /// </summary>
        /// <param name="Email"></param>
        /// <returns></returns>
        public static bool sendPassword(CoreController core, string Email, ref string returnUserMessage)
        {
            bool result = false;

            returnUserMessage = "";
            try {
                const string passwordChrs       = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345678999999";
                const int    passwordChrsLength = 62;
                //
                string workingEmail = GenericController.encodeText(Email);
                //
                string Message     = "";
                string FromAddress = "";
                string subject     = "";
                if (string.IsNullOrEmpty(workingEmail))
                {
                    ErrorController.addUserError(core, "Please enter your email address before requesting your username and password.");
                }
                else
                {
                    int atPtr = GenericController.strInstr(1, workingEmail, "@");
                    if (atPtr < 2)
                    {
                        //
                        // email not valid
                        //
                        ErrorController.addUserError(core, "Please enter a valid email address before requesting your username and password.");
                    }
                    else
                    {
                        string EMailName = strMid(workingEmail, 1, atPtr - 1);
                        //
                        LogController.addSiteActivity(core, "password request for email " + workingEmail, core.session.user.id, core.session.user.organizationId);
                        //
                        bool allowEmailLogin = core.siteProperties.getBoolean("allowEmailLogin", false);
                        int  recordCnt       = 0;
                        using (var csData = new CsModel(core)) {
                            string sqlCriteria = "(email=" + DbController.encodeSQLText(workingEmail) + ")";
                            sqlCriteria = sqlCriteria + "and((dateExpires is null)or(dateExpires>" + DbController.encodeSQLDate(core.dateTimeNowMockable) + "))";
                            csData.open("People", sqlCriteria, "ID", true, core.session.user.id, "username,password", 1);
                            if (!csData.ok())
                            {
                                //
                                // valid login account for this email not found
                                //
                                if (encodeText(strMid(workingEmail, atPtr + 1)).ToLowerInvariant() == "contensive.com")
                                {
                                    //
                                    // look for expired account to renew
                                    //
                                    csData.close();
                                    csData.open("People", "((email=" + DbController.encodeSQLText(workingEmail) + "))", "ID");
                                    if (csData.ok())
                                    {
                                        //
                                        // renew this old record
                                        //
                                        csData.set("developer", "1");
                                        csData.set("admin", "1");
                                        if (csData.getDate("dateExpires") > DateTime.MinValue)
                                        {
                                            csData.set("dateExpires", core.dateTimeNowMockable.AddDays(7).Date.ToString());
                                        }
                                    }
                                    else
                                    {
                                        //
                                        // inject support record
                                        //
                                        csData.close();
                                        csData.insert("people");
                                        csData.set("name", "Contensive Support");
                                        csData.set("email", workingEmail);
                                        csData.set("developer", "1");
                                        csData.set("admin", "1");
                                        csData.set("dateExpires", core.dateTimeNowMockable.AddDays(7).Date.ToString());
                                    }
                                }
                                else
                                {
                                    ErrorController.addUserError(core, "No current user was found matching this email address. Please try again. ");
                                }
                            }
                            if (csData.ok())
                            {
                                FromAddress = core.siteProperties.getText("EmailFromAddress", "info@" + core.webServer.requestDomain);
                                subject     = "Password Request at " + core.webServer.requestDomain;
                                Message     = "";
                                while (csData.ok())
                                {
                                    bool updateUser = false;
                                    if (string.IsNullOrEmpty(Message))
                                    {
                                        Message  = "This email was sent in reply to a request at " + core.webServer.requestDomain + " for the username and password associated with this email address. ";
                                        Message += "If this request was made by you, please return to the login screen and use the following:\r\n";
                                        Message += Environment.NewLine;
                                    }
                                    else
                                    {
                                        Message += Environment.NewLine;
                                        Message += "Additional user accounts with the same email address: \r\n";
                                    }
                                    //
                                    // username
                                    //
                                    string Username   = csData.getText("Username");
                                    bool   usernameOK = true;
                                    int    Ptr        = 0;
                                    if (!allowEmailLogin)
                                    {
                                        if (Username != Username.Trim())
                                        {
                                            Username   = Username.Trim();
                                            updateUser = true;
                                        }
                                        if (string.IsNullOrEmpty(Username))
                                        {
                                            usernameOK = false;
                                            Ptr        = 0;
                                            while (!usernameOK && (Ptr < 100))
                                            {
                                                Username   = EMailName + encodeInteger(Math.Floor(encodeNumber(Microsoft.VisualBasic.VBMath.Rnd() * 9999)));
                                                usernameOK = !core.session.isLoginOK(Username, "test");
                                                Ptr        = Ptr + 1;
                                            }
                                            if (usernameOK)
                                            {
                                                updateUser = true;
                                            }
                                        }
                                        Message += " username: "******"Password");
                                        if (Password.Trim() != Password)
                                        {
                                            Password   = Password.Trim();
                                            updateUser = true;
                                        }
                                        if (string.IsNullOrEmpty(Password))
                                        {
                                            for (Ptr = 0; Ptr <= 8; Ptr++)
                                            {
                                                int Index = encodeInteger(Microsoft.VisualBasic.VBMath.Rnd() * passwordChrsLength);
                                                Password = Password + strMid(passwordChrs, Index, 1);
                                            }
                                            updateUser = true;
                                        }
                                        Message += " password: "******"username", Username);
                                            csData.set("password", Password);
                                        }
                                        recordCnt = recordCnt + 1;
                                    }
                                    csData.goNext();
                                }
                            }
                        }
                    }
                }
                if (result)
                {
                    string sendStatus = "";
                    EmailController.queueAdHocEmail(core, "Password Email", core.session.user.id, workingEmail, FromAddress, subject, Message, "", "", "", true, false, 0, ref sendStatus);
                }
            } catch (Exception ex) {
                LogController.logError(core, ex);
                throw;
            }
            return(result);
        }
Exemplo n.º 15
0
        //
        //=============================================================================
        // Normalize the Index page Columns, setting proper values for IndexColumn, etc.
        //=============================================================================
        //
        private static void NormalizeIndexColumns(CoreController core, int ContentID)
        {
            try {
                //
                int ColumnWidth      = 0;
                int ColumnWidthTotal = 0;
                int ColumnCounter    = 0;
                int IndexColumn      = 0;
                using (var csData = new CsModel(core)) {
                    csData.open("Content Fields", "(ContentID=" + ContentID + ")", "IndexColumn");
                    if (!csData.ok())
                    {
                        throw (new GenericException("Unexpected exception")); // Call handleLegacyClassErrors2("NormalizeIndexColumns", "Could not read Content Field Definitions")
                    }
                    else
                    {
                        //
                        // Adjust IndexSortOrder to be 0 based, count by 1
                        //
                        ColumnCounter = 0;
                        while (csData.ok())
                        {
                            IndexColumn = csData.getInteger("IndexColumn");
                            ColumnWidth = csData.getInteger("IndexWidth");
                            if ((IndexColumn == 0) || (ColumnWidth == 0))
                            {
                                csData.set("IndexColumn", 0);
                                csData.set("IndexWidth", 0);
                                csData.set("IndexSortPriority", 0);
                            }
                            else
                            {
                                //
                                // Column appears in Index, clean it up
                                //
                                csData.set("IndexColumn", ColumnCounter);
                                ColumnCounter    += 1;
                                ColumnWidthTotal += ColumnWidth;
                            }
                            csData.goNext();
                        }
                        if (ColumnCounter == 0)
                        {
                            //
                            // No columns found, set name as Column 0, active as column 1
                            //
                            csData.goFirst();
                            while (csData.ok())
                            {
                                switch (GenericController.toUCase(csData.getText("name")))
                                {
                                case "ACTIVE": {
                                    csData.set("IndexColumn", 0);
                                    csData.set("IndexWidth", 20);
                                    ColumnWidthTotal += 20;
                                    break;
                                }

                                case "NAME": {
                                    csData.set("IndexColumn", 1);
                                    csData.set("IndexWidth", 80);
                                    ColumnWidthTotal += 80;
                                    break;
                                }

                                default: {
                                    // do nothing
                                    break;
                                }
                                }
                                csData.goNext();
                            }
                        }
                        //
                        // ----- Now go back and set a normalized Width value
                        //
                        if (ColumnWidthTotal > 0)
                        {
                            csData.goFirst();
                            while (csData.ok())
                            {
                                ColumnWidth = csData.getInteger("IndexWidth");
                                ColumnWidth = encodeInteger((ColumnWidth * 100) / (double)ColumnWidthTotal);
                                csData.set("IndexWidth", ColumnWidth);
                                csData.goNext();
                            }
                        }
                    }
                }
                //
                // ----- now fixup Sort Priority so only visible fields are sorted.
                //
                using (var csData = new CsModel(core)) {
                    csData.open("Content Fields", "(ContentID=" + ContentID + ")", "IndexSortPriority, IndexColumn");
                    if (!csData.ok())
                    {
                        throw (new GenericException("Unexpected exception")); // Call handleLegacyClassErrors2("NormalizeIndexColumns", "Error reading Content Field Definitions")
                    }
                    else
                    {
                        //
                        // Go through all fields, clear Sort Priority if it does not appear
                        //
                        int SortValue     = 0;
                        int SortDirection = 0;
                        SortValue = 0;
                        while (csData.ok())
                        {
                            SortDirection = 0;
                            if (csData.getInteger("IndexColumn") == 0)
                            {
                                csData.set("IndexSortPriority", 0);
                            }
                            else
                            {
                                csData.set("IndexSortPriority", SortValue);
                                SortDirection = csData.getInteger("IndexSortDirection");
                                if (SortDirection == 0)
                                {
                                    SortDirection = 1;
                                }
                                else
                                {
                                    if (SortDirection > 0)
                                    {
                                        SortDirection = 1;
                                    }
                                    else
                                    {
                                        SortDirection = -1;
                                    }
                                }
                                SortValue += 1;
                            }
                            csData.set("IndexSortDirection", SortDirection);
                            csData.goNext();
                        }
                    }
                }
                return;
            } catch (Exception ex) {
                LogController.logError(core, ex);
            }
        }
        //
        //=============================================================================
        // Find and Replace launch tool
        //=============================================================================
        //
        public static string get(CoreController core)
        {
            string result = "";

            try {
                StringBuilderLegacyController Stream = new StringBuilderLegacyController();
                //
                Stream.add(AdminUIController.getHeaderTitleDescription("Find and Replace", "This tool runs a find and replace operation on content throughout the site."));
                //
                // Process the form
                //
                string Button      = core.docProperties.getText("button");
                bool   IsDeveloper = core.session.isAuthenticatedDeveloper();
                int    RowPtr      = 0;
                string CDefList    = "";
                string FindText    = "";
                string ReplaceText = "";
                string lcName      = null;
                if (Button == ButtonFindAndReplace)
                {
                    int RowCnt = core.docProperties.getInteger("CDefRowCnt");
                    if (RowCnt > 0)
                    {
                        for (RowPtr = 0; RowPtr < RowCnt; RowPtr++)
                        {
                            if (core.docProperties.getBoolean("Cdef" + RowPtr))
                            {
                                lcName = GenericController.toLCase(core.docProperties.getText("CDefName" + RowPtr));
                                if (IsDeveloper || (lcName == "page content") || (lcName == "copy content") || (lcName == "page templates"))
                                {
                                    CDefList = CDefList + "," + lcName;
                                }
                            }
                        }
                        if (!string.IsNullOrEmpty(CDefList))
                        {
                            CDefList = CDefList.Substring(1);
                        }
                        FindText    = core.docProperties.getText("FindText");
                        ReplaceText = core.docProperties.getText("ReplaceText");
                        //string QS = "app=" + encodeNvaArgument(core.appConfig.name) + "&FindText=" + encodeNvaArgument(FindText) + "&ReplaceText=" + encodeNvaArgument(ReplaceText) + "&CDefNameList=" + encodeNvaArgument(CDefList);
                        var cmdDetail = new TaskModel.CmdDetailClass {
                            addonId   = 0,
                            addonName = "GetForm_FindAndReplace",
                            args      = new System.Collections.Generic.Dictionary <string, string> {
                                { "app", core.appConfig.name },
                                { "FindText", FindText },
                                { "ReplaceText", ReplaceText },
                                { "CDefNameList", CDefList }
                            }
                        };
                        TaskSchedulerController.addTaskToQueue(core, cmdDetail, false);
                        Stream.add("Find and Replace has been requested for content definitions [" + CDefList + "], finding [" + FindText + "] and replacing with [" + ReplaceText + "]");
                    }
                }
                else
                {
                    CDefList    = "Page Content,Copy Content,Page Templates";
                    FindText    = "";
                    ReplaceText = "";
                }
                //
                // Display form
                //
                int FindRows = core.docProperties.getInteger("SQLRows");
                if (FindRows == 0)
                {
                    FindRows = core.userProperty.getInteger("FindAndReplaceFindRows", 1);
                }
                else
                {
                    core.userProperty.setProperty("FindAndReplaceFindRows", FindRows.ToString());
                }
                int ReplaceRows = core.docProperties.getInteger("ReplaceRows");
                if (ReplaceRows == 0)
                {
                    ReplaceRows = core.userProperty.getInteger("FindAndReplaceReplaceRows", 1);
                }
                else
                {
                    core.userProperty.setProperty("FindAndReplaceReplaceRows", ReplaceRows.ToString());
                }
                //
                Stream.add("<div>Find</div>");
                Stream.add("<TEXTAREA NAME=\"FindText\" ROWS=\"" + FindRows + "\" ID=\"FindText\" STYLE=\"width: 800px;\">" + FindText + "</TEXTAREA>");
                Stream.add("&nbsp;<INPUT TYPE=\"Text\" TabIndex=-1 NAME=\"FindTextRows\" SIZE=\"3\" VALUE=\"" + FindRows + "\" ID=\"\"  onchange=\"FindText.rows=FindTextRows.value; return true\"> Rows");
                Stream.add("<br><br>");
                //
                Stream.add("<div>Replace it with</div>");
                Stream.add("<TEXTAREA NAME=\"ReplaceText\" ROWS=\"" + ReplaceRows + "\" ID=\"ReplaceText\" STYLE=\"width: 800px;\">" + ReplaceText + "</TEXTAREA>");
                Stream.add("&nbsp;<INPUT TYPE=\"Text\" TabIndex=-1 NAME=\"ReplaceTextRows\" SIZE=\"3\" VALUE=\"" + ReplaceRows + "\" ID=\"\"  onchange=\"ReplaceText.rows=ReplaceTextRows.value; return true\"> Rows");
                Stream.add("<br><br>");
                string TopHalf    = "";
                string BottomHalf = "";
                //
                using (var csData = new CsModel(core)) {
                    csData.open("Content");
                    while (csData.ok())
                    {
                        string RecordName = csData.getText("Name");
                        lcName = GenericController.toLCase(RecordName);
                        if (IsDeveloper || (lcName == "page content") || (lcName == "copy content") || (lcName == "page templates"))
                        {
                            int RecordId = csData.getInteger("ID");
                            if (GenericController.strInstr(1, "," + CDefList + ",", "," + RecordName + ",") != 0)
                            {
                                TopHalf = TopHalf + "<div>" + HtmlController.checkbox("Cdef" + RowPtr, true) + HtmlController.inputHidden("CDefName" + RowPtr, RecordName) + "&nbsp;" + csData.getText("Name") + "</div>";
                            }
                            else
                            {
                                BottomHalf = BottomHalf + "<div>" + HtmlController.checkbox("Cdef" + RowPtr, false) + HtmlController.inputHidden("CDefName" + RowPtr, RecordName) + "&nbsp;" + csData.getText("Name") + "</div>";
                            }
                        }
                        csData.goNext();
                        RowPtr += 1;
                    }
                }
                Stream.add(TopHalf + BottomHalf + HtmlController.inputHidden("CDefRowCnt", RowPtr));
                //
                result = AdminUIController.getToolForm(core, Stream.text, ButtonCancel + "," + ButtonFindAndReplace);
            } catch (Exception ex) {
                LogController.logError(core, ex);
            }
            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);
        }
Exemplo n.º 18
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 + "]");
            }
        }
Exemplo n.º 19
0
        //
        //====================================================================================================
        /// <summary>
        /// Process manual changes needed for special cases
        /// </summary>
        /// <param name="isDelete"></param>
        /// <param name="contentName"></param>
        /// <param name="recordId"></param>
        /// <param name="recordName"></param>
        /// <param name="recordParentID"></param>
        /// <param name="useContentWatchLink"></param>
        public static void processAfterSave(CoreController core, bool isDelete, string contentName, int recordId, string recordName, int recordParentID, bool useContentWatchLink)
        {
            try {
                PageContentModel.markReviewed(core.cpParent, recordId);
                string tableName = MetadataController.getContentTablename(core, contentName);
                //
                // -- invalidate the specific cache for this record
                core.cache.invalidateDbRecord(recordId, tableName);
                //
                string tableNameLower = tableName.ToLower(CultureInfo.InvariantCulture);
                if (tableNameLower == AddonCollectionModel.tableMetadata.tableNameLower)
                {
                    //
                    // -- addon collection
                    processAfterSave_AddonCollection(core, isDelete, contentName, recordId, recordName, recordParentID, useContentWatchLink);
                }
                else if (tableNameLower == LinkForwardModel.tableMetadata.tableNameLower)
                {
                    //
                    // -- link forward
                    core.routeMapCacheClear();
                }
                else if (tableNameLower == LinkAliasModel.tableMetadata.tableNameLower)
                {
                    //
                    // -- link alias
                    core.routeMapCacheClear();
                }
                else if (tableNameLower == AddonModel.tableMetadata.tableNameLower)
                {
                    //
                    // -- addon
                    core.routeMapCacheClear();
                }
                else if (tableNameLower == PersonModel.tableMetadata.tableNameLower)
                {
                    //
                    // -- PersonModel
                    var person = PersonModel.create <PersonModel>(core.cpParent, recordId);
                    if (person != null)
                    {
                        if (isDelete)
                        {
                            LogController.addSiteActivity(core, "deleting user #" + recordId + " (" + recordName + ")", recordId, person.organizationId);
                        }
                        else
                        {
                            LogController.addSiteActivity(core, "saving changes to user #" + recordId + " (" + recordName + ")", recordId, person.organizationId);
                        }
                    }
                }
                else if (tableNameLower == OrganizationModel.tableMetadata.tableNameLower)
                {
                    //
                    // -- Log Activity for changes to people and organizattions
                    if (isDelete)
                    {
                        LogController.addSiteActivity(core, "deleting organization #" + recordId + " (" + recordName + ")", 0, recordId);
                    }
                    else
                    {
                        LogController.addSiteActivity(core, "saving changes to organization #" + recordId + " (" + recordName + ")", 0, recordId);
                    }
                }
                else if (tableNameLower == SitePropertyModel.tableMetadata.tableNameLower)
                {
                    //
                    // -- Site Properties
                    switch (GenericController.toLCase(recordName))
                    {
                    case "allowlinkalias":
                        PageContentModel.invalidateCacheOfTable <PageContentModel>(core.cpParent);
                        break;

                    case "sectionlandinglink":
                        PageContentModel.invalidateCacheOfTable <PageContentModel>(core.cpParent);
                        break;

                    case Constants._siteproperty_serverPageDefault_name:
                        PageContentModel.invalidateCacheOfTable <PageContentModel>(core.cpParent);
                        break;
                    }
                }
                else if (tableNameLower == PageContentModel.tableMetadata.tableNameLower)
                {
                    //
                    // -- set ChildPagesFound true for parent page
                    if (recordParentID > 0)
                    {
                        if (!isDelete)
                        {
                            core.db.executeNonQuery("update ccpagecontent set ChildPagesfound=1 where ID=" + recordParentID);
                        }
                    }
                    if (isDelete)
                    {
                        //
                        // Clear the Landing page and page not found site properties
                        if (recordId == GenericController.encodeInteger(core.siteProperties.getText("PageNotFoundPageID", "0")))
                        {
                            core.siteProperties.setProperty("PageNotFoundPageID", "0");
                        }
                        if (recordId == core.siteProperties.landingPageID)
                        {
                            core.siteProperties.setProperty("landingPageId", "0");
                        }
                        //
                        // Delete Link Alias entries with this PageID
                        core.db.executeNonQuery("delete from cclinkAliases where PageID=" + recordId);
                    }
                    DbBaseModel.invalidateCacheOfRecord <PageContentModel>(core.cpParent, recordId);
                }
                else if (tableNameLower == LibraryFilesModel.tableMetadata.tableNameLower)
                {
                    //
                    // --
                    processAfterSave_LibraryFiles(core, isDelete, contentName, recordId, recordName, recordParentID, useContentWatchLink);
                }
                //
                // Process Addons marked to trigger a process call on content change
                //
                Dictionary <string, string> instanceArguments;
                bool onChangeAddonsAsync = core.siteProperties.getBoolean("execute oncontentchange addons async", false);
                using (var csData = new CsModel(core)) {
                    int contentId = ContentMetadataModel.getContentId(core, contentName);
                    csData.open("Add-on Content Trigger Rules", "ContentID=" + contentId, "", false, 0, "addonid");
                    string Option_String = null;
                    if (isDelete)
                    {
                        instanceArguments = new Dictionary <string, string> {
                            { "action", "contentdelete" },
                            { "contentid", contentId.ToString() },
                            { "recordid", recordId.ToString() }
                        };
                        Option_String = ""
                                        + Environment.NewLine + "action=contentdelete"
                                        + Environment.NewLine + "contentid=" + contentId
                                        + Environment.NewLine + "recordid=" + recordId + "";
                    }
                    else
                    {
                        instanceArguments = new Dictionary <string, string> {
                            { "action", "contentchange" },
                            { "contentid", contentId.ToString() },
                            { "recordid", recordId.ToString() }
                        };
                        Option_String = ""
                                        + Environment.NewLine + "action=contentchange"
                                        + Environment.NewLine + "contentid=" + contentId
                                        + Environment.NewLine + "recordid=" + recordId + "";
                    }
                    while (csData.ok())
                    {
                        var addon = DbBaseModel.create <AddonModel>(core.cpParent, csData.getInteger("Addonid"));
                        if (addon != null)
                        {
                            if (onChangeAddonsAsync)
                            {
                                //
                                // -- execute addon async
                                core.addon.executeAsync(addon, instanceArguments);
                            }
                            else
                            {
                                //
                                // -- execute addon
                                core.addon.execute(addon, new CPUtilsBaseClass.addonExecuteContext {
                                    addonType             = CPUtilsBaseClass.addonContext.ContextOnContentChange,
                                    backgroundProcess     = false,
                                    errorContextMessage   = "",
                                    argumentKeyValuePairs = instanceArguments
                                });
                            }
                        }
                        csData.goNext();
                    }
                }
            } catch (Exception ex) {
                LogController.logError(core, ex);
            }
        }
Exemplo n.º 20
0
        //
        //========================================================================
        //
        public static string get(CoreController core)
        {
            try {
                //
                string   Button        = null;
                string   SQL           = null;
                string   RQS           = null;
                int      PageSize      = 0;
                int      PageNumber    = 0;
                int      TopCount      = 0;
                int      RowPointer    = 0;
                int      DataRowCount  = 0;
                string   PreTableCopy  = "";
                string   PostTableCopy = "";
                int      ColumnPtr     = 0;
                string[] ColCaption    = null;
                string[] ColAlign      = null;
                string[] ColWidth      = null;
                string[,] Cells = null;
                string AdminURL                    = null;
                int    RowCnt                      = 0;
                int    RowPtr                      = 0;
                int    ContentId                   = 0;
                string Format                      = null;
                string Name                        = null;
                string title                       = null;
                string Description                 = null;
                string ButtonCommaListLeft         = null;
                string ButtonCommaListRight        = null;
                int    ContentPadding              = 0;
                string ContentSummary              = "";
                StringBuilderLegacyController Tab0 = new StringBuilderLegacyController();
                StringBuilderLegacyController Tab1 = new StringBuilderLegacyController();
                string Content                     = "";
                string SQLFieldName                = null;
                var    adminMenu                   = new EditTabModel();
                //
                const int ColumnCnt = 4;
                //
                Button    = core.docProperties.getText(RequestNameButton);
                ContentId = core.docProperties.getInteger("ContentID");
                Format    = core.docProperties.getText("Format");
                //
                title                = "Custom Report Manager";
                Description          = "Custom Reports are a way for you to create a snapshot of data to view or download. To request a report, select the Custom Reports tab, check the report(s) you want, and click the [Request Download] Button. When your report is ready, it will be available in the <a href=\"?" + rnAdminForm + "=30\">Download Manager</a>. To create a new custom report, select the Request New Report tab, enter a name and SQL statement, and click the Apply button.";
                ContentPadding       = 0;
                ButtonCommaListLeft  = ButtonCancel + "," + ButtonDelete + "," + ButtonRequestDownload;
                ButtonCommaListRight = "";
                SQLFieldName         = "SQLQuery";
                //
                if (!core.session.isAuthenticatedAdmin())
                {
                    //
                    // Must be a developer
                    //
                    Description = Description + "You can not access the Custom Report Manager because your account is not configured as an administrator.";
                }
                else
                {
                    //
                    // Process Requests
                    //
                    if (!string.IsNullOrEmpty(Button))
                    {
                        switch (Button)
                        {
                        case ButtonCancel:
                            return(core.webServer.redirect("/" + core.appConfig.adminRoute, "CustomReports, Cancel Button Pressed"));

                        case ButtonDelete:
                            RowCnt = core.docProperties.getInteger("RowCnt");
                            if (RowCnt > 0)
                            {
                                for (RowPtr = 0; RowPtr < RowCnt; RowPtr++)
                                {
                                    if (core.docProperties.getBoolean("Row" + RowPtr))
                                    {
                                        MetadataController.deleteContentRecord(core, "Custom Reports", core.docProperties.getInteger("RowID" + RowPtr));
                                    }
                                }
                            }
                            break;

                        case ButtonRequestDownload:
                        case ButtonApply:
                            //
                            Name = core.docProperties.getText("name");
                            SQL  = core.docProperties.getText(SQLFieldName);
                            if (!string.IsNullOrEmpty(Name) || !string.IsNullOrEmpty(SQL))
                            {
                                if ((string.IsNullOrEmpty(Name)) || (string.IsNullOrEmpty(SQL)))
                                {
                                    Processor.Controllers.ErrorController.addUserError(core, "A name and SQL Query are required to save a new custom report.");
                                }
                                else
                                {
                                    int customReportId = 0;
                                    using (var csData = new CsModel(core)) {
                                        csData.insert("Custom Reports");
                                        if (csData.ok())
                                        {
                                            customReportId = csData.getInteger("id");
                                            csData.set("Name", Name);
                                            csData.set(SQLFieldName, SQL);
                                        }
                                        csData.close();
                                    }
                                    requestDownload(core, customReportId);
                                }
                            }
                            //
                            RowCnt = core.docProperties.getInteger("RowCnt");
                            if (RowCnt > 0)
                            {
                                for (RowPtr = 0; RowPtr < RowCnt; RowPtr++)
                                {
                                    if (core.docProperties.getBoolean("Row" + RowPtr))
                                    {
                                        int customReportId = core.docProperties.getInteger("RowID" + RowPtr);
                                        using (var csData = new CsModel(core)) {
                                            csData.openRecord("Custom Reports", customReportId);
                                            if (csData.ok())
                                            {
                                                SQL  = csData.getText(SQLFieldName);
                                                Name = csData.getText("Name");
                                            }
                                        }
                                        requestDownload(core, customReportId);
                                    }
                                }
                            }
                            break;
                        }
                    }
                    //
                    // Build Tab0
                    //
                    Tab0.add("<p>The following is a list of available custom reports.</p>");
                    //
                    RQS      = core.doc.refreshQueryString;
                    PageSize = core.docProperties.getInteger(RequestNamePageSize);
                    if (PageSize == 0)
                    {
                        PageSize = 50;
                    }
                    PageNumber = core.docProperties.getInteger(RequestNamePageNumber);
                    if (PageNumber == 0)
                    {
                        PageNumber = 1;
                    }
                    AdminURL = "/" + core.appConfig.adminRoute;
                    TopCount = PageNumber * PageSize;
                    //
                    // Setup Headings
                    //
                    ColCaption = new string[ColumnCnt + 1];
                    ColAlign   = new string[ColumnCnt + 1];
                    ColWidth   = new string[ColumnCnt + 1];
                    Cells      = new string[PageSize + 1, ColumnCnt + 1];
                    //
                    ColCaption[ColumnPtr] = "Select<br><img alt=\"space\" src=\"" + cdnPrefix + "images/spacer.gif\" width=10 height=1>";
                    ColAlign[ColumnPtr]   = "center";
                    ColWidth[ColumnPtr]   = "10";
                    ColumnPtr             = ColumnPtr + 1;
                    //
                    ColCaption[ColumnPtr] = "Name";
                    ColAlign[ColumnPtr]   = "left";
                    ColWidth[ColumnPtr]   = "100%";
                    ColumnPtr             = ColumnPtr + 1;
                    //
                    ColCaption[ColumnPtr] = "Created By<br><img alt=\"space\" src=\"" + cdnPrefix + "images/spacer.gif\" width=100 height=1>";
                    ColAlign[ColumnPtr]   = "left";
                    ColWidth[ColumnPtr]   = "100";
                    ColumnPtr             = ColumnPtr + 1;
                    //
                    ColCaption[ColumnPtr] = "Date Created<br><img alt=\"space\" src=\"" + cdnPrefix + "images/spacer.gif\" width=150 height=1>";
                    ColAlign[ColumnPtr]   = "left";
                    ColWidth[ColumnPtr]   = "150";
                    ColumnPtr             = ColumnPtr + 1;
                    //
                    //   Get Data
                    //
                    using (var csData = new CsModel(core)) {
                        RowPointer = 0;
                        if (!csData.open("Custom Reports"))
                        {
                            Cells[0, 1] = "There are no custom reports defined";
                            RowPointer  = 1;
                        }
                        else
                        {
                            DataRowCount = csData.getRowCount();
                            while (csData.ok() && (RowPointer < PageSize))
                            {
                                int customReportId = csData.getInteger("ID");
                                Cells[RowPointer, 0] = HtmlController.checkbox("Row" + RowPointer) + HtmlController.inputHidden("RowID" + RowPointer, customReportId);
                                Cells[RowPointer, 1] = csData.getText("name");
                                Cells[RowPointer, 2] = csData.getText("CreatedBy");
                                Cells[RowPointer, 3] = csData.getDate("DateAdded").ToShortDateString();
                                RowPointer           = RowPointer + 1;
                                csData.goNext();
                            }
                        }
                        csData.close();
                    }
                    string Cell = null;
                    Tab0.add(HtmlController.inputHidden("RowCnt", RowPointer));
                    Cell = AdminUIController.getReport(core, RowPointer, ColCaption, ColAlign, ColWidth, Cells, PageSize, PageNumber, PreTableCopy, PostTableCopy, DataRowCount, "ccPanel");
                    Tab0.add("<div>" + Cell + "</div>");
                    //
                    // Build RequestContent Form
                    //
                    Tab1.add("<p>Use this form to create a new custom report. Enter the SQL Query for the report, and a name that will be used as a caption.</p>");
                    //
                    Tab1.add("<table border=\"0\" cellpadding=\"3\" cellspacing=\"0\" width=\"100%\">");
                    //
                    Tab1.add("<tr>");
                    Tab1.add("<td align=right>Name</td>");
                    Tab1.add("<td>" + HtmlController.inputText_Legacy(core, "Name", "", 1, 40) + "</td>");
                    Tab1.add("</tr>");
                    //
                    Tab1.add("<tr>");
                    Tab1.add("<td align=right>SQL Query</td>");
                    Tab1.add("<td>" + HtmlController.inputText_Legacy(core, SQLFieldName, "", 8, 40) + "</td>");
                    Tab1.add("</tr>");
                    //
                    Tab1.add("<tr><td width=\"120\"><img alt=\"space\" src=\"" + cdnPrefix + "images/spacer.gif\" width=\"120\" height=\"1\"></td><td width=\"100%\">&nbsp;</td></tr></table>");
                    //
                    // Build and add tabs
                    //
                    adminMenu.addEntry("Custom&nbsp;Reports", Tab0.text, "ccAdminTab");
                    adminMenu.addEntry("Request&nbsp;New&nbsp;Report", Tab1.text, "ccAdminTab");
                    Content = adminMenu.getTabs(core);
                    //
                }
                //
                core.html.addTitle("Custom Reports");
                //
                return(AdminUIController.getToolBody(core, title, ButtonCommaListLeft, ButtonCommaListRight, true, true, Description, ContentSummary, ContentPadding, Content));
            } catch (Exception ex) {
                LogController.logError(core, ex);
                return(toolExceptionMessage);
            }
        }
Exemplo n.º 21
0
        //
        //====================================================================================================
        //
        public static string exportAscii_GetAsciiExport(CoreController core, string ContentName, int PageSize, int PageNumber)
        {
            string result = "";

            try {
                string Delimiter             = null;
                string Copy                  = "";
                string TableName             = null;
                string FieldNameVariant      = null;
                string FieldName             = null;
                string UcaseFieldName        = null;
                string iContentName          = null;
                System.Text.StringBuilder sb = new System.Text.StringBuilder();
                string TestFilename;
                //
                TestFilename = "AsciiExport" + GenericController.getRandomInteger(core) + ".txt";
                //
                iContentName = GenericController.encodeText(ContentName);
                if (PageSize == 0)
                {
                    PageSize = 1000;
                }
                if (PageNumber == 0)
                {
                    PageNumber = 1;
                }
                //
                // ----- Check for special case iContentNames
                //
                core.webServer.setResponseContentType("text/plain");
                core.html.enableOutputBuffer(false);
                TableName = DbController.getDbObjectTableName(MetadataController.getContentTablename(core, iContentName));
                switch (GenericController.toUCase(TableName))
                {
                case "CCMEMBERS":
                    //
                    // ----- People and member content export
                    //
                    if (!core.session.isAuthenticatedAdmin())
                    {
                        sb.Append("Warning: You must be a site administrator to export this information.");
                    }
                    else
                    {
                        using (var csData = new CsModel(core)) {
                            csData.open(iContentName, "", "ID", false, 0, "", PageSize, PageNumber);
                            //
                            // ----- print out the field names
                            //
                            if (csData.ok())
                            {
                                sb.Append("\"EID\"");
                                Delimiter        = ",";
                                FieldNameVariant = csData.getFirstFieldName();
                                while (!string.IsNullOrEmpty(FieldNameVariant))
                                {
                                    FieldName      = GenericController.encodeText(FieldNameVariant);
                                    UcaseFieldName = GenericController.toUCase(FieldName);
                                    if ((UcaseFieldName != "USERNAME") && (UcaseFieldName != "PASSWORD"))
                                    {
                                        sb.Append(Delimiter + "\"" + FieldName + "\"");
                                    }
                                    FieldNameVariant = csData.getNextFieldName();
                                }
                                sb.Append(Environment.NewLine);
                            }
                            //
                            // ----- print out the values
                            //
                            while (csData.ok())
                            {
                                if (!(csData.getBoolean("Developer")))
                                {
                                    Copy = SecurityController.encodeToken(core, csData.getInteger("ID"), core.doc.profileStartTime.AddDays(30));
                                    sb.Append("\"" + Copy + "\"");
                                    Delimiter        = ",";
                                    FieldNameVariant = csData.getFirstFieldName();
                                    while (!string.IsNullOrEmpty(FieldNameVariant))
                                    {
                                        FieldName      = GenericController.encodeText(FieldNameVariant);
                                        UcaseFieldName = GenericController.toUCase(FieldName);
                                        if ((UcaseFieldName != "USERNAME") && (UcaseFieldName != "PASSWORD"))
                                        {
                                            Copy = csData.getText(FieldName);
                                            if (!string.IsNullOrEmpty(Copy))
                                            {
                                                Copy = GenericController.strReplace(Copy, "\"", "'");
                                                Copy = GenericController.strReplace(Copy, Environment.NewLine, " ");
                                                Copy = GenericController.strReplace(Copy, "\r", " ");
                                                Copy = GenericController.strReplace(Copy, "\n", " ");
                                            }
                                            sb.Append(Delimiter + "\"" + Copy + "\"");
                                        }
                                        FieldNameVariant = csData.getNextFieldName();
                                    }
                                    sb.Append(Environment.NewLine);
                                }
                                csData.goNext();
                            }
                        }
                    }
                    // End Case
                    break;

                default:
                    //
                    // ----- All other content
                    //
                    if (!core.session.isAuthenticatedContentManager(iContentName))
                    {
                        sb.Append("Error: You must be a content manager to export this data.");
                    }
                    else
                    {
                        using (var csData = new CsModel(core)) {
                            csData.open(iContentName, "", "ID", false, 0, "", PageSize, PageNumber);
                            //
                            // ----- print out the field names
                            if (csData.ok())
                            {
                                Delimiter        = "";
                                FieldNameVariant = csData.getFirstFieldName();
                                while (!string.IsNullOrEmpty(FieldNameVariant))
                                {
                                    core.wwwFiles.appendFile(TestFilename, Delimiter + "\"" + FieldNameVariant + "\"");
                                    Delimiter        = ",";
                                    FieldNameVariant = csData.getNextFieldName();
                                }
                                core.wwwFiles.appendFile(TestFilename, Environment.NewLine);
                            }
                            //
                            // ----- print out the values
                            while (csData.ok())
                            {
                                Delimiter        = "";
                                FieldNameVariant = csData.getFirstFieldName();
                                while (!string.IsNullOrEmpty(FieldNameVariant))
                                {
                                    switch (csData.getFieldTypeId(GenericController.encodeText(FieldNameVariant)))
                                    {
                                    case CPContentBaseClass.FieldTypeIdEnum.FileText:
                                    case CPContentBaseClass.FieldTypeIdEnum.FileCSS:
                                    case CPContentBaseClass.FieldTypeIdEnum.FileXML:
                                    case CPContentBaseClass.FieldTypeIdEnum.FileJavascript:
                                    case CPContentBaseClass.FieldTypeIdEnum.FileHTML:
                                    case CPContentBaseClass.FieldTypeIdEnum.FileHTMLCode:
                                        Copy = csData.getTextEncoded(GenericController.encodeText(FieldNameVariant));
                                        break;

                                    case CPContentBaseClass.FieldTypeIdEnum.Lookup:
                                        Copy = csData.getText(GenericController.encodeText(FieldNameVariant));
                                        break;

                                    case CPContentBaseClass.FieldTypeIdEnum.Redirect:
                                    case CPContentBaseClass.FieldTypeIdEnum.ManyToMany:
                                        break;

                                    default:
                                        Copy = csData.getText(GenericController.encodeText(FieldNameVariant));
                                        break;
                                    }
                                    if (!string.IsNullOrEmpty(Copy))
                                    {
                                        Copy = GenericController.strReplace(Copy, "\"", "'");
                                        Copy = GenericController.strReplace(Copy, Environment.NewLine, " ");
                                        Copy = GenericController.strReplace(Copy, "\r", " ");
                                        Copy = GenericController.strReplace(Copy, "\n", " ");
                                    }
                                    core.wwwFiles.appendFile(TestFilename, Delimiter + "\"" + Copy + "\"");
                                    Delimiter        = ",";
                                    FieldNameVariant = csData.getNextFieldName();
                                }
                                core.wwwFiles.appendFile(TestFilename, Environment.NewLine);
                                csData.goNext();
                            }
                        }
                    }
                    break;
                }
                result = core.wwwFiles.readFileText(TestFilename);
                core.wwwFiles.deleteFile(TestFilename);
            } catch (Exception ex) {
                LogController.logError(core, ex);
            }
            return(result);
        }
 //
 //====================================================================================================
 /// <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;
     }
 }
Exemplo n.º 23
0
        //
        //========================================================================
        //
        public static string getForm_Edit_LinkAliases(CoreController core, AdminDataModel adminData, bool readOnlyField)
        {
            string tempGetForm_Edit_LinkAliases = null;

            try {
                //
                // Link Alias value from the admin data
                //
                string TabDescription = "Link Aliases are URLs used for this content that are more friendly to users and search engines. If you set the Link Alias field, this name will be used on the URL for this page. If you leave the Link Alias blank, the page name will be used. Below is a list of names that have been used previously and are still active. All of these entries when used in the URL will resolve to this page. The first entry in this list will be used to create menus on the site. To move an entry to the top, type it into the Link Alias field and save.";
                string tabContent     = "&nbsp;";
                if (!core.siteProperties.allowLinkAlias)
                {
                    //
                    // Disabled
                    //
                    TabDescription = "<p>The Link Alias feature is currently disabled. To enable Link Aliases, check the box marked 'Allow Link Alias' on the Page Settings page found on the Navigator under 'Settings'.</p><p>" + TabDescription + "</p>";
                }
                else
                {
                    //
                    // Link Alias Field
                    //
                    string linkAlias = "";
                    if (adminData.adminContent.fields.ContainsKey("linkalias"))
                    {
                        linkAlias = GenericController.encodeText(adminData.editRecord.fieldsLc["linkalias"].value);
                    }
                    StringBuilderLegacyController form = new StringBuilderLegacyController();
                    form.add("<tr><td class=\"ccAdminEditCaption\">" + SpanClassAdminSmall + "Link Alias</td>");
                    form.add("<td class=\"ccAdminEditField\" align=\"left\" colspan=\"2\">" + SpanClassAdminNormal);
                    if (readOnlyField)
                    {
                        form.add(linkAlias);
                    }
                    else
                    {
                        form.add(HtmlController.inputText_Legacy(core, "LinkAlias", linkAlias));
                    }
                    form.add("</span></td></tr>");
                    //
                    // Override Duplicates
                    //
                    form.add("<tr><td class=\"ccAdminEditCaption\">" + SpanClassAdminSmall + "Override Duplicates</td>");
                    form.add("<td class=\"ccAdminEditField\" align=\"left\" colspan=\"2\">" + SpanClassAdminNormal);
                    if (readOnlyField)
                    {
                        form.add("No");
                    }
                    else
                    {
                        form.add(HtmlController.checkbox("OverrideDuplicate", false));
                    }
                    form.add("</span></td></tr>");
                    //
                    // Table of old Link Aliases
                    //
                    // todo
                    int    LinkCnt  = 0;
                    string LinkList = "";
                    using (var csData = new CsModel(core)) {
                        csData.open("Link Aliases", "pageid=" + adminData.editRecord.id, "ID Desc", true, 0, "name");
                        while (csData.ok())
                        {
                            LinkList += "<div style=\"margin-left:4px;margin-bottom:4px;\">" + HtmlController.encodeHtml(csData.getText("name")) + "</div>";
                            LinkCnt  += 1;
                            csData.goNext();
                        }
                    }
                    if (LinkCnt > 0)
                    {
                        form.add("<tr><td class=\"ccAdminEditCaption\">" + SpanClassAdminSmall + "Previous Link Alias List</td>");
                        form.add("<td class=\"ccAdminEditField\" align=\"left\" colspan=\"2\">" + SpanClassAdminNormal);
                        form.add(LinkList);
                        form.add("</span></td></tr>");
                    }
                    tabContent = AdminUIController.editTable(form.text);
                }
                //
                tempGetForm_Edit_LinkAliases     = AdminUIController.getEditPanel(core, true, "Link Aliases", TabDescription, tabContent);
                adminData.editSectionPanelCount += 1;
            } catch (Exception ex) {
                LogController.logError(core, ex);
            }
            return(tempGetForm_Edit_LinkAliases);
        }
Exemplo n.º 24
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);
     }
 }
Exemplo n.º 25
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);
        }