// //============================================================================= // 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); } }
// //==================================================================================================== // public override string GetText(string fieldName) { try { return(cs.getText(fieldName)); } catch (Exception ex) { LogController.logError(cp.core, ex); throw; } }
// //============================================================================= // 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); } }
// //============================================================================= /// <summary> /// Get the link for a Content Record by its ContentRecordKey /// </summary> /// <param name="ContentRecordKey"></param> /// <param name="DefaultLink"></param> /// <param name="IncrementClicks"></param> /// <returns></returns> public string getContentWatchLinkByKey(string ContentRecordKey, string DefaultLink, bool IncrementClicks) { string result = ""; try { using (var csData = new CsModel(core)) { if (csData.open("Content Watch", "ContentRecordKey=" + DbController.encodeSQLText(ContentRecordKey), "", false, 0, "Link,Clicks")) { result = csData.getText("Link"); if (GenericController.encodeBoolean(IncrementClicks)) { csData.set("Clicks", csData.getInteger("clicks") + 1); } } else { result = GenericController.encodeText(DefaultLink); } } return(GenericController.encodeVirtualPath(result, core.appConfig.cdnFileUrl, appRootPath, core.webServer.requestDomain)); } catch (Exception ex) { LogController.logError(core, ex); throw; } }
// //==================================================================================================== /// <summary> /// set property /// </summary> /// <param name="propertyName"></param> /// <param name="propertyValue"></param> /// <param name="keyId">keyId is like vistiId, vistorId, userId</param> public void setProperty(string propertyName, string propertyValue, int keyId) { try { if (!propertyCacheLoaded) { loadFromDb(keyId); } int Ptr = -1; if (propertyCacheCnt > 0) { Ptr = propertyCache_nameIndex.getPtr(propertyName); } if (Ptr < 0) { Ptr = propertyCacheCnt; propertyCacheCnt += 1; string[,] tempVar = new string[3, Ptr + 1]; if (propertyCache != null) { for (int Dimension0 = 0; Dimension0 < propertyCache.GetLength(0); Dimension0++) { int CopyLength = Math.Min(propertyCache.GetLength(1), tempVar.GetLength(1)); for (int Dimension1 = 0; Dimension1 < CopyLength; Dimension1++) { tempVar[Dimension0, Dimension1] = propertyCache[Dimension0, Dimension1]; } } } propertyCache = tempVar; propertyCache[0, Ptr] = propertyName; propertyCache[1, Ptr] = propertyValue; propertyCache_nameIndex.setPtr(propertyName, Ptr); // // insert a new property record, get the ID back and save it in cache // using (var csData = new CsModel(core)) { if (csData.insert("Properties")) { propertyCache[2, Ptr] = csData.getText("ID"); csData.set("name", propertyName); csData.set("FieldValue", propertyValue); csData.set("TypeID", (int)propertyType); csData.set("KeyID", keyId.ToString()); } } } else if (propertyCache[1, Ptr] != propertyValue) { propertyCache[1, Ptr] = propertyValue; int RecordId = GenericController.encodeInteger(propertyCache[2, Ptr]); string SQLNow = DbController.encodeSQLDate(core.dateTimeNowMockable); // // save the value in the property that was found // core.db.executeNonQuery("update ccProperties set FieldValue=" + DbController.encodeSQLText(propertyValue) + ",ModifiedDate=" + SQLNow + " where id=" + RecordId); } } catch (Exception ex) { LogController.logError(core, ex); } }
// //============================================================================= /// <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"); } } } }
// //==================================================================================================== // public static string getActiveEditor(CoreController core, string ContentName, int RecordID, string FieldName, string FormElements = "") { // int ContentID = 0; string Copy = null; string Stream = ""; string ButtonPanel = null; string EditorPanel = null; string PanelCopy = null; string intContentName = null; int intRecordId = 0; string strFieldName = null; // intContentName = GenericController.encodeText(ContentName); intRecordId = GenericController.encodeInteger(RecordID); strFieldName = GenericController.encodeText(FieldName); // EditorPanel = ""; ContentID = Models.Domain.ContentMetadataModel.getContentId(core, intContentName); if ((ContentID < 1) || (intRecordId < 1) || (string.IsNullOrEmpty(strFieldName))) { PanelCopy = SpanClassAdminNormal + "The information you have selected can not be accessed.</span>"; EditorPanel = EditorPanel + core.html.getPanel(PanelCopy); } else { intContentName = MetadataController.getContentNameByID(core, ContentID); if (!string.IsNullOrEmpty(intContentName)) { using (var csData = new CsModel(core)) { csData.open(intContentName, "ID=" + intRecordId); if (!csData.ok()) { PanelCopy = SpanClassAdminNormal + "The information you have selected can not be accessed.</span>"; EditorPanel = EditorPanel + core.html.getPanel(PanelCopy); } else { Copy = csData.getText(strFieldName); EditorPanel = EditorPanel + HtmlController.inputHidden("Type", FormTypeActiveEditor); EditorPanel = EditorPanel + HtmlController.inputHidden("cid", ContentID); EditorPanel = EditorPanel + HtmlController.inputHidden("ID", intRecordId); EditorPanel = EditorPanel + HtmlController.inputHidden("fn", strFieldName); EditorPanel = EditorPanel + GenericController.encodeText(FormElements); EditorPanel = EditorPanel + core.html.getFormInputHTML("ContentCopy", Copy, "3", "45", false, true); ButtonPanel = core.html.getPanelButtons(ButtonCancel + "," + ButtonSave); EditorPanel = EditorPanel + ButtonPanel; } csData.close(); } } } Stream = Stream + core.html.getPanelHeader("Contensive Active Content Editor"); Stream = Stream + core.html.getPanel(EditorPanel); Stream = HtmlController.form(core, Stream); return(Stream); }
// //==================================================================================================== // public override string GetLayout(int layoutid) { try { using (var cs = new CsModel(cp.core)) { string sql = "select layout from ccLayouts where id=" + layoutid; cs.openSql(sql); if (cs.ok()) { return(cs.getText("layout")); } } } catch (Exception ex) { LogController.logError(cp.core, ex); } return(string.Empty); }
// public static string getDefaultValue(CoreController core, string contentName, string fieldName) { string defaultValue = ""; int contentId = ContentMetadataModel.getContentId(core, contentName); string SQL = "select defaultvalue from ccfields where name=" + DbController.encodeSQLText(fieldName) + " and contentid=(" + contentId + ")"; using (var csData = new CsModel(core)) { csData.openSql(SQL); if (csData.ok()) { defaultValue = csData.getText("defaultvalue"); } csData.close(); } return(defaultValue); }
// //==================================================================================================== // public override string getLayout(string layoutName) { try { if (string.IsNullOrWhiteSpace(layoutName)) { return(string.Empty); } using (var cs = new CsModel(cp.core)) { cs.open("layouts", "name=" + DbController.encodeSQLText(layoutName), "id", false, cp.core.session.user.id, "layout"); if (cs.ok()) { return(cs.getText("layout")); } } } catch (Exception ex) { LogController.logError(cp.core, ex); } return(string.Empty); }
// //============================================================================= // 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); }
// //==================================================================================================== /// <summary> /// GetAjaxDefaultAddonOptionStringClass remote method /// </summary> /// <param name="cp"></param> /// <returns></returns> public override object Execute(Contensive.BaseClasses.CPBaseClass cp) { string returnHtml = ""; try { using (CoreController core = ((CPClass)cp).core) { using (var csData = new CsModel(core)) { string AddonGuid = core.docProperties.getText("guid"); csData.open(AddonModel.tableMetadata.contentName, "ccguid=" + DbController.encodeSQLText(AddonGuid)); if (csData.ok()) { string addonArgumentList = csData.getText("argumentlist"); bool addonIsInline = csData.getBoolean("IsInline"); string jsonCommand = ""; returnHtml = AddonController.getDefaultAddonOptions(core, addonArgumentList, AddonGuid, addonIsInline, csData.getText("name"), ref jsonCommand); } } } } catch (Exception ex) { cp.Site.ErrorReport(ex); } return(returnHtml); }
// //==================================================================================================== /// <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; } }
// //==================================================================================================== /// <summary> /// add a link alias to a page as the primary /// </summary> public static void addLinkAlias(CoreController core, string linkAlias, int pageId, string queryStringSuffix, bool overRideDuplicate, bool dupCausesWarning, ref string return_WarningMessage) { string hint = ""; try { // LogController.logTrace(core, "addLinkAlias, enter, linkAlias [" + linkAlias + "], pageID [" + pageId + "], queryStringSuffix [" + queryStringSuffix + "], overRideDuplicate [" + overRideDuplicate + "], dupCausesWarning [" + dupCausesWarning + "]"); // const string SafeStringLc = "0123456789abcdefghijklmnopqrstuvwxyz-_/."; bool AllowLinkAlias = core.siteProperties.getBoolean("allowLinkAlias", true); // string normalizedLinkAlias = linkAlias; if (!string.IsNullOrEmpty(normalizedLinkAlias)) { // // remove nonsafe URL characters string Src = normalizedLinkAlias.Replace('\t', ' '); normalizedLinkAlias = ""; for (int srcPtr = 0; srcPtr < Src.Length; srcPtr++) { string TestChr = Src.Substring(srcPtr, 1).ToLowerInvariant(); if (!SafeStringLc.Contains(TestChr)) { TestChr = "\t"; } normalizedLinkAlias += TestChr; } int Ptr = 0; while (normalizedLinkAlias.Contains("\t\t") && (Ptr < 100)) { normalizedLinkAlias = GenericController.strReplace(normalizedLinkAlias, "\t\t", "\t"); Ptr = Ptr + 1; } if (normalizedLinkAlias.Substring(normalizedLinkAlias.Length - 1) == "\t") { normalizedLinkAlias = normalizedLinkAlias.left(normalizedLinkAlias.Length - 1); } if (normalizedLinkAlias.left(1) == "\t") { normalizedLinkAlias = normalizedLinkAlias.Substring(1); } normalizedLinkAlias = GenericController.strReplace(normalizedLinkAlias, "\t", "-"); if (!string.IsNullOrEmpty(normalizedLinkAlias)) { if (normalizedLinkAlias.left(1) != "/") { normalizedLinkAlias = "/" + normalizedLinkAlias; } // LogController.logTrace(core, "addLinkAlias, normalized normalizedLinkAlias [" + normalizedLinkAlias + "]"); // // Make sure there is not a folder or page in the wwwroot that matches this Alias // if (GenericController.toLCase(normalizedLinkAlias) == GenericController.toLCase("/" + core.appConfig.name)) { // // This alias points to the cclib folder // if (AllowLinkAlias) { return_WarningMessage = "" + "The Link Alias being created (" + normalizedLinkAlias + ") can not be used because there is a virtual directory in your website directory that already uses this name." + " Please change it to ensure the Link Alias is unique. To set or change the Link Alias, use the Link Alias tab and select a name not used by another page."; } } else if (GenericController.toLCase(normalizedLinkAlias) == "/cclib") { // // This alias points to the cclib folder // if (AllowLinkAlias) { return_WarningMessage = "" + "The Link Alias being created (" + normalizedLinkAlias + ") can not be used because there is a virtual directory in your website directory that already uses this name." + " Please change it to ensure the Link Alias is unique. To set or change the Link Alias, use the Link Alias tab and select a name not used by another page."; } } else if (core.wwwFiles.pathExists(core.appConfig.localWwwPath + "\\" + normalizedLinkAlias.Substring(1))) { // // This alias points to a different link, call it an error // if (AllowLinkAlias) { return_WarningMessage = "" + "The Link Alias being created (" + normalizedLinkAlias + ") can not be used because there is a folder in your website directory that already uses this name." + " Please change it to ensure the Link Alias is unique. To set or change the Link Alias, use the Link Alias tab and select a name not used by another page."; } } else { // // Make sure there is one here for this // bool flushLinkAliasCache = false; int linkAliasId = 0; using (var csData = new CsModel(core)) { csData.open("Link Aliases", "name=" + DbController.encodeSQLText(normalizedLinkAlias), "", false, 0, "Name,PageID,QueryStringSuffix"); if (!csData.ok()) { // LogController.logTrace(core, "addLinkAlias, not found in Db, add"); // // Alias not found, create a Link Aliases // csData.close(); csData.insert("Link Aliases"); if (csData.ok()) { csData.set("Name", normalizedLinkAlias); csData.set("Pageid", pageId); csData.set("QueryStringSuffix", queryStringSuffix); flushLinkAliasCache = true; } } else { int recordPageId = csData.getInteger("pageID"); string recordQss = csData.getText("QueryStringSuffix").ToLowerInvariant(); // LogController.logTrace(core, "addLinkAlias, linkalias record found by its name, record recordPageId [" + recordPageId + "], record QueryStringSuffix [" + recordQss + "]"); // // Alias found, verify the pageid & QueryStringSuffix // int CurrentLinkAliasId = 0; bool resaveLinkAlias = false; if ((recordQss == queryStringSuffix.ToLowerInvariant()) && (pageId == recordPageId)) { CurrentLinkAliasId = csData.getInteger("id"); // LogController.logTrace(core, "addLinkAlias, linkalias matches name, pageid, and querystring of linkalias [" + CurrentLinkAliasId + "]"); // // it maches a current entry for this link alias, if the current entry is not the highest number id, // remove it and add this one // string sql = "select top 1 id from ccLinkAliases where (pageid=" + recordPageId + ")and(QueryStringSuffix=" + DbController.encodeSQLText(queryStringSuffix) + ") order by id desc"; using (var CS3 = new CsModel(core)) { CS3.openSql(sql); if (CS3.ok()) { resaveLinkAlias = (CurrentLinkAliasId != CS3.getInteger("id")); } } if (resaveLinkAlias) { // LogController.logTrace(core, "addLinkAlias, another link alias matches this pageId and QS. Move this to the top position"); // core.db.executeNonQuery("delete from ccLinkAliases where id=" + CurrentLinkAliasId); using (var CS3 = new CsModel(core)) { CS3.insert("Link Aliases"); if (CS3.ok()) { CS3.set("Name", normalizedLinkAlias); CS3.set("Pageid", pageId); CS3.set("QueryStringSuffix", queryStringSuffix); } } } } else { // LogController.logTrace(core, "addLinkAlias, linkalias matches name, but pageid and querystring are different. Add this a newest linkalias"); // // link alias matches, but id/qs does not -- this is either a change, or a duplicate that needs to be blocked // if (overRideDuplicate) { // LogController.logTrace(core, "addLinkAlias, overRideDuplicate true, change the Link Alias to the new link"); // // change the Link Alias to the new link csData.set("Pageid", pageId); csData.set("QueryStringSuffix", queryStringSuffix); flushLinkAliasCache = true; } else if (dupCausesWarning) { // LogController.logTrace(core, "addLinkAlias, overRideDuplicate false, dupCausesWarning true, just return user warning if this is from admin"); // if (recordPageId == 0) { int PageContentCId = Models.Domain.ContentMetadataModel.getContentId(core, "Page Content"); return_WarningMessage = "" + "This page has been saved, but the Link Alias could not be created (" + normalizedLinkAlias + ") because it is already in use for another page." + " To use Link Aliasing (friendly page names) for this page, the Link Alias value must be unique on this site. To set or change the Link Alias, clicke the Link Alias tab and select a name not used by another page or a folder in your website."; } else { int PageContentCid = Models.Domain.ContentMetadataModel.getContentId(core, "Page Content"); return_WarningMessage = "" + "This page has been saved, but the Link Alias could not be created (" + normalizedLinkAlias + ") because it is already in use for another page (<a href=\"?af=4&cid=" + PageContentCid + "&id=" + recordPageId + "\">edit</a>)." + " To use Link Aliasing (friendly page names) for this page, the Link Alias value must be unique. To set or change the Link Alias, click the Link Alias tab and select a name not used by another page or a folder in your website."; } } } } linkAliasId = csData.getInteger("id"); csData.close(); } if (flushLinkAliasCache) { // // -- invalidate all linkAlias core.cache.invalidateDbRecord(linkAliasId, LinkAliasModel.tableMetadata.tableNameLower); // // -- invalidate routemap Models.Domain.RouteMapModel.invalidateCache(core); core.routeMapCacheClear(); } } } } // LogController.logTrace(core, "addLinkAlias, exit"); // } catch (Exception ex) { LogController.logError(core, ex, "addLinkAlias exception, hint [" + hint + "]"); throw; } }
// //==================================================================================================== // public static void processAfterSave_LibraryFiles(CoreController core, bool isDelete, string contentName, int recordID, string recordName, int recordParentID, bool useContentWatchLink) { // // if a AltSizeList is blank, make large,medium,small and thumbnails // if (core.siteProperties.getBoolean("ImageAllowSFResize", true) && (!isDelete)) { using (var csData = new CsModel(core)) { if (csData.openRecord("library files", recordID)) { string Filename = csData.getText("filename"); int Pos = Filename.LastIndexOf("/") + 1; string FilePath = ""; if (Pos > 0) { FilePath = Filename.left(Pos); Filename = Filename.Substring(Pos); } csData.set("filesize", core.wwwFiles.getFileSize(FilePath + Filename)); Pos = Filename.LastIndexOf(".") + 1; if (Pos > 0) { string FilenameExt = Filename.Substring(Pos); string FilenameNoExt = Filename.left(Pos - 1); if (GenericController.strInstr(1, "jpg,gif,png", FilenameExt, 1) != 0) { ImageEditController sf = new ImageEditController(); if (sf.load(FilePath + Filename, core.wwwFiles)) { // // // csData.set("height", sf.height); csData.set("width", sf.width); string AltSizeList = csData.getText("AltSizeList"); bool RebuildSizes = (string.IsNullOrEmpty(AltSizeList)); if (RebuildSizes) { AltSizeList = ""; // // Attempt to make 640x // if (sf.width >= 640) { sf.height = GenericController.encodeInteger(sf.height * (640 / sf.width)); sf.width = 640; sf.save(FilePath + FilenameNoExt + "-640x" + sf.height + "." + FilenameExt, core.wwwFiles); AltSizeList = AltSizeList + Environment.NewLine + "640x" + sf.height; } // // Attempt to make 320x // if (sf.width >= 320) { sf.height = GenericController.encodeInteger(sf.height * (320 / sf.width)); sf.width = 320; sf.save(FilePath + FilenameNoExt + "-320x" + sf.height + "." + FilenameExt, core.wwwFiles); AltSizeList = AltSizeList + Environment.NewLine + "320x" + sf.height; } // // Attempt to make 160x // if (sf.width >= 160) { sf.height = GenericController.encodeInteger(sf.height * (160 / sf.width)); sf.width = 160; sf.save(FilePath + FilenameNoExt + "-160x" + sf.height + "." + FilenameExt, core.wwwFiles); AltSizeList = AltSizeList + Environment.NewLine + "160x" + sf.height; } // // Attempt to make 80x // if (sf.width >= 80) { sf.height = GenericController.encodeInteger(sf.height * (80 / sf.width)); sf.width = 80; sf.save(FilePath + FilenameNoExt + "-180x" + sf.height + "." + FilenameExt, core.wwwFiles); AltSizeList = AltSizeList + Environment.NewLine + "80x" + sf.height; } csData.set("AltSizeList", AltSizeList); } sf.Dispose(); sf = null; } } } } } } }
// //======================================================================== /// <summary> /// Control edit tab /// </summary> /// <param name="core"></param> /// <param name="adminData"></param> /// <returns></returns> public static string get(CoreController core, AdminDataModel adminData, EditorEnvironmentModel editorEnv) { string result = null; try { bool disabled = false; // var tabPanel = new StringBuilderLegacyController(); if (string.IsNullOrEmpty(adminData.adminContent.name)) { // // Content not found or not loaded if (adminData.adminContent.id == 0) { // LogController.logError(core, new GenericException("No content definition was specified for this page")); return(HtmlController.p("No content was specified.")); } else { // // Content Definition was not specified LogController.logError(core, new GenericException("The content definition specified for this page [" + adminData.adminContent.id + "] was not found")); return(HtmlController.p("No content was specified.")); } } // // ----- Authoring status bool FieldRequired = false; List <string> TabsFound = new List <string>(); foreach (KeyValuePair <string, ContentFieldMetadataModel> keyValuePair in adminData.adminContent.fields) { ContentFieldMetadataModel field = keyValuePair.Value; if ((field.editTabName.ToLowerInvariant().Equals("control info")) && (field.authorable) && (field.active)) { tabPanel.add(EditorRowClass.getEditorRow(core, field, adminData, editorEnv)); } } // // ----- RecordID { string fieldValue = (adminData.editRecord.id == 0) ? "(available after save)" : adminData.editRecord.id.ToString(); string fieldEditor = AdminUIEditorController.getTextEditor(core, "ignore", fieldValue, true, ""); string fieldHelp = "This is the unique number that identifies this record within this content."; tabPanel.add(AdminUIController.getEditRow(core, fieldEditor, "Record Number", fieldHelp, true, false, "")); } // // -- Active { string htmlId = "fieldActive"; string fieldEditor = HtmlController.checkbox("active", adminData.editRecord.active, htmlId, disabled, "", adminData.editRecord.userReadOnly); string fieldHelp = "When unchecked, add-ons can ignore this record as if it was temporarily deleted."; tabPanel.add(AdminUIController.getEditRow(core, fieldEditor, "Active", fieldHelp, false, false, htmlId)); } // // -- GUID { string guidSetHtmlId = "guidSet" + GenericController.getRandomInteger(core).ToString(); string guidInputHtmlId = "guidInput" + GenericController.getRandomInteger(core).ToString(); string fieldValue = GenericController.encodeText(adminData.editRecord.fieldsLc["ccguid"].value); string fieldEditor = ""; if (adminData.editRecord.userReadOnly) { // // -- readonly fieldEditor = AdminUIEditorController.getTextEditor(core, "ignore", fieldValue, true, ""); } else if (string.IsNullOrEmpty(fieldValue)) { // // add a set button string setButton = "<input id=\"" + guidSetHtmlId + "\" type=\"submit\" value=\"Set\" class=\"btn btn-primary btn-sm\">"; string setButtonWrapped = "<div class=\"input-group-append\">" + setButton + "</div>"; string inputCell = AdminUIEditorController.getTextEditor(core, "ccguid", "", false, guidInputHtmlId); fieldEditor = HtmlController.div(inputCell + setButtonWrapped, "input-group"); string newGuid = GenericController.getGUID(true); string onClickFn = "function(e){e.preventDefault();e.stopPropagation();$('#" + guidInputHtmlId + "').val('" + newGuid + "');}"; string script = "$('body').on('click','#" + guidSetHtmlId + "'," + onClickFn + ")"; core.html.addScriptCode(script, "Admin edit control-info-tab guid set button"); } else { // // field is read-only except for developers fieldEditor = AdminUIEditorController.getTextEditor(core, "ccguid", fieldValue, !core.session.isAuthenticatedDeveloper(), guidInputHtmlId); } string FieldHelp = "This is a unique number that identifies this record globally. A GUID is not required, but when set it should never be changed. GUIDs are used to synchronize records. When empty, you can create a new guid. Only Developers can modify the guid."; tabPanel.add(AdminUIController.getEditRow(core, fieldEditor, "GUID", FieldHelp, false, false, guidInputHtmlId)); } // // ----- EID (Encoded ID) { if (GenericController.toUCase(adminData.adminContent.tableName) == GenericController.toUCase("ccMembers")) { string htmlId = "fieldGuid"; bool AllowEId = (core.siteProperties.getBoolean("AllowLinkLogin", true)) || (core.siteProperties.getBoolean("AllowLinkRecognize", true)); string fieldHelp = "This string is an authentication token that can be used in the URL for the next 15 minutes to log in as this user."; string fieldEditor = ""; if (!AllowEId) { fieldEditor = "(link login and link recognize are disabled in security preferences)"; } else if (adminData.editRecord.id == 0) { fieldEditor = "(available after save)"; } else { string eidQueryString = "eid=" + WebUtility.UrlEncode(SecurityController.encodeToken(core, adminData.editRecord.id, core.doc.profileStartTime.AddMinutes(15))); string sampleUrl = core.webServer.requestProtocol + core.webServer.requestDomain + "/" + core.siteProperties.serverPageDefault + "?" + eidQueryString; if (core.siteProperties.getBoolean("AllowLinkLogin", true)) { fieldHelp = " If " + eidQueryString + " is added to a url querystring for this site, the user be logged in as this person."; } else { fieldHelp = " If " + eidQueryString + " is added to a url querystring for this site, the user be recognized in as this person, but not logged in."; } fieldHelp += " To enable, disable or modify this feature, use the security tab on the Preferences page."; fieldHelp += "<br>For example: " + sampleUrl; fieldEditor = AdminUIEditorController.getTextEditor(core, "ignore_eid", eidQueryString, true, htmlId); } tabPanel.add(AdminUIController.getEditRow(core, fieldEditor, "Member Link Login Querystring", fieldHelp, true, false, htmlId)); } } // // ----- Controlling Content { string HTMLFieldString = ""; string FieldHelp = "The content in which this record is stored. This is similar to a database table."; ContentFieldMetadataModel field = null; if (adminData.adminContent.fields.ContainsKey("contentcontrolid")) { field = adminData.adminContent.fields["contentcontrolid"]; // // if this record has a parent id, only include CDefs compatible with the parent record - otherwise get all for the table FieldHelp = GenericController.encodeText(field.helpMessage); FieldRequired = GenericController.encodeBoolean(field.required); int FieldValueInteger = (adminData.editRecord.contentControlId.Equals(0)) ? adminData.adminContent.id : adminData.editRecord.contentControlId; if (!core.session.isAuthenticatedAdmin()) { HTMLFieldString = HTMLFieldString + HtmlController.inputHidden("contentControlId", FieldValueInteger); } else { string RecordContentName = adminData.editRecord.contentControlId_Name; string TableName2 = MetadataController.getContentTablename(core, RecordContentName); int TableId = MetadataController.getRecordIdByUniqueName(core, "Tables", TableName2); // // Test for parentid int ParentId = 0; bool ContentSupportsParentId = false; if (adminData.editRecord.id > 0) { using (var csData = new CsModel(core)) { if (csData.openRecord(RecordContentName, adminData.editRecord.id)) { ContentSupportsParentId = csData.isFieldSupported("ParentID"); if (ContentSupportsParentId) { ParentId = csData.getInteger("ParentID"); } } } } bool IsEmptyList = false; if (core.session.isAuthenticatedAdmin()) { // // administrator, and either ( no parentid or does not support it), let them select any content compatible with the table string sqlFilter = "(ContentTableID=" + TableId + ")"; int contentCId = MetadataController.getRecordIdByUniqueName(core, ContentModel.tableMetadata.contentName, ContentModel.tableMetadata.contentName); HTMLFieldString += AdminUIEditorController.getLookupContentEditor(core, "contentcontrolid", FieldValueInteger, contentCId, ref IsEmptyList, adminData.editRecord.userReadOnly, "", "", true, sqlFilter); FieldHelp = FieldHelp + " (Only administrators have access to this control. Changing the Controlling Content allows you to change who can author the record, as well as how it is edited.)"; } } } if (string.IsNullOrEmpty(HTMLFieldString)) { HTMLFieldString = adminData.editRecord.contentControlId_Name; } tabPanel.add(AdminUIController.getEditRow(core, HTMLFieldString, "Controlling Content", FieldHelp, FieldRequired, false, "")); } // // ----- Created By { string FieldHelp = "The people account of the user who created this record."; string fieldValue = ""; if (adminData.editRecord == null) { fieldValue = "(not set)"; } else if (adminData.editRecord.id == 0) { fieldValue = "(available after save)"; } else if (adminData.editRecord.createdBy == null) { fieldValue = "(not set)"; } else { int FieldValueInteger = adminData.editRecord.createdBy.id; if (FieldValueInteger == 0) { fieldValue = "(not set)"; } else { using (var csData = new CsModel(core)) { csData.open("people", "(id=" + FieldValueInteger + ")", "name,active", false); if (!csData.ok()) { fieldValue = "#" + FieldValueInteger + ", (deleted)"; } else { fieldValue = "#" + FieldValueInteger + ", " + csData.getText("name"); if (!csData.getBoolean("active")) { fieldValue += " (inactive)"; } } csData.close(); } } } string fieldEditor = AdminUIEditorController.getTextEditor(core, "ignore_createdBy", fieldValue, true, ""); tabPanel.add(AdminUIController.getEditRow(core, fieldEditor, "Created By", FieldHelp, FieldRequired, false, "")); } // // ----- Created Date { string FieldHelp = "The date and time when this record was originally created."; string fieldValue = ""; if (adminData.editRecord == null) { fieldValue = "(not set)"; } else if (adminData.editRecord.id == 0) { fieldValue = "(available after save)"; } else { if (GenericController.encodeDateMinValue(adminData.editRecord.dateAdded) == DateTime.MinValue) { fieldValue = "(not set)"; } else { fieldValue = adminData.editRecord.dateAdded.ToString(); } } string fieldEditor = AdminUIEditorController.getTextEditor(core, "ignore_createdDate", fieldValue, true, ""); tabPanel.add(AdminUIController.getEditRow(core, fieldEditor, "Created Date", FieldHelp, FieldRequired, false, "")); } // // ----- Modified By { string FieldHelp = "The people account of the last user who modified this record."; string fieldValue = ""; if (adminData.editRecord == null) { fieldValue = "(not set)"; } else if (adminData.editRecord.id == 0) { fieldValue = "(available after save)"; } else if (adminData.editRecord.modifiedBy == null) { fieldValue = "(not set)"; } else { int FieldValueInteger = adminData.editRecord.modifiedBy.id; if (FieldValueInteger == 0) { fieldValue = "(not set)"; } else { using (var csData = new CsModel(core)) { csData.open("people", "(id=" + FieldValueInteger + ")", "name,active", false); if (!csData.ok()) { fieldValue = "#" + FieldValueInteger + ", (deleted)"; } else { fieldValue = "#" + FieldValueInteger + ", " + csData.getText("name"); if (!csData.getBoolean("active")) { fieldValue += " (inactive)"; } } csData.close(); } } } string fieldEditor = AdminUIEditorController.getTextEditor(core, "ignore_modifiedBy", fieldValue, true, ""); tabPanel.add(AdminUIController.getEditRow(core, fieldEditor, "Modified By", FieldHelp, FieldRequired, false, "")); } // // ----- Modified Date { string FieldHelp = "The date and time when this record was last modified."; string fieldValue = ""; if (adminData.editRecord == null) { fieldValue = "(not set)"; } else if (adminData.editRecord.id == 0) { fieldValue = "(available after save)"; } else { if (GenericController.encodeDateMinValue(adminData.editRecord.modifiedDate) == DateTime.MinValue) { fieldValue = "(not set)"; } else { fieldValue = adminData.editRecord.modifiedDate.ToString(); } } string fieldEditor = AdminUIEditorController.getTextEditor(core, "ignore_modifiedBy", fieldValue, true, ""); tabPanel.add(AdminUIController.getEditRow(core, fieldEditor, "Modified Date", FieldHelp, false, false, "")); } string s = AdminUIController.editTable(tabPanel.text); result = AdminUIController.getEditPanel(core, true, "Control Information", "", s); adminData.editSectionPanelCount += 1; tabPanel = null; } catch (Exception ex) { LogController.logError(core, ex); } return(result); }
// //======================================================================== // 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 = " "; 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); }
// //==================================================================================================== /// <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); }
//============================================================================= // 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(" ", "", 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(" ", "100%"); result += kmaEndTableRow; result += kmaEndTable; // result = AdminUIController.getToolForm(core, result, ButtonList); // // ----- Error Trap // } catch (Exception ex) { LogController.logError(core, ex); } return(result); }
// //======================================================================== /// <summary> /// Display a field in the admin index form /// </summary> /// <param name="core"></param> /// <param name="adminData"></param> /// <param name="fieldName"></param> /// <param name="CS"></param> /// <param name="IsLookupFieldValid"></param> /// <param name="IsEmailContent"></param> /// <returns></returns> public static string getGridCell(CoreController core, AdminDataModel adminData, string fieldName, CsModel csData, bool IsLookupFieldValid, bool IsEmailContent) { try { var Stream = new StringBuilderLegacyController(); var field = adminData.adminContent.fields[fieldName.ToLowerInvariant()]; if (field.password) { // // -- do not list password fields Stream.add("****"); } else { int Pos = 0; switch (field.fieldTypeId) { case CPContentBaseClass.FieldTypeIdEnum.File: case CPContentBaseClass.FieldTypeIdEnum.FileImage: { string filename = csData.getText(field.nameLc); filename = GenericController.strReplace(filename, "\\", "/"); Pos = filename.LastIndexOf("/") + 1; if (Pos != 0) { filename = filename.Substring(Pos); } Stream.add(filename); break; } case CPContentBaseClass.FieldTypeIdEnum.Lookup: { if (IsLookupFieldValid) { Stream.add(csData.getText("LookupTable" + field.id + "Name")); } else if (field.lookupList != "") { string[] lookups = field.lookupList.Split(','); int LookupPtr = csData.getInteger(field.nameLc) - 1; if (LookupPtr <= lookups.GetUpperBound(0)) { if (LookupPtr >= 0) { Stream.add(lookups[LookupPtr]); } } } else { Stream.add(" "); } break; } case CPContentBaseClass.FieldTypeIdEnum.MemberSelect: { if (IsLookupFieldValid) { Stream.add(csData.getText("LookupTable" + field.id + "Name")); } else { Stream.add(csData.getText(field.nameLc)); } break; } case CPContentBaseClass.FieldTypeIdEnum.Boolean: { if (csData.getBoolean(field.nameLc)) { Stream.add("yes"); } else { Stream.add("no"); } break; } case CPContentBaseClass.FieldTypeIdEnum.Currency: { string fieldValueText = csData.getText(field.nameLc); if (string.IsNullOrWhiteSpace(fieldValueText)) { Stream.add(fieldValueText); break; } Stream.add(string.Format("{0:C}", csData.getNumber(field.nameLc))); break; } case CPContentBaseClass.FieldTypeIdEnum.LongText: case CPContentBaseClass.FieldTypeIdEnum.HTML: case CPContentBaseClass.FieldTypeIdEnum.HTMLCode: { string fieldValueText = csData.getText(field.nameLc); if (fieldValueText.Length > 50) { fieldValueText = fieldValueText.left(50) + "[more]"; } Stream.add(fieldValueText); break; } case CPContentBaseClass.FieldTypeIdEnum.FileText: case CPContentBaseClass.FieldTypeIdEnum.FileCSS: case CPContentBaseClass.FieldTypeIdEnum.FileXML: case CPContentBaseClass.FieldTypeIdEnum.FileJavascript: case CPContentBaseClass.FieldTypeIdEnum.FileHTML: case CPContentBaseClass.FieldTypeIdEnum.FileHTMLCode: { string filename = csData.getText(field.nameLc); if (!string.IsNullOrEmpty(filename)) { string Copy = core.cdnFiles.readFileText(filename); Stream.add(Copy); } break; } case CPContentBaseClass.FieldTypeIdEnum.Redirect: case CPContentBaseClass.FieldTypeIdEnum.ManyToMany: { Stream.add("n/a"); break; } case CPContentBaseClass.FieldTypeIdEnum.Date: { // // -- if minvalue, use blank, if no time-part, do short-date DateTime cellValueDate = csData.getDate(field.nameLc); if (cellValueDate.Equals(DateTime.MinValue)) { Stream.add(""); } else if (cellValueDate.Equals(cellValueDate.Date)) { Stream.add(cellValueDate.ToShortDateString()); } else { Stream.add(cellValueDate.ToString()); } break; } default: { string valueString = csData.getText(field.nameLc); if (string.IsNullOrWhiteSpace(valueString)) { Stream.add(valueString); break; } Stream.add(csData.getText(field.nameLc)); break; } } } return(HtmlController.encodeHtml(Stream.text)); } catch (Exception ex) { LogController.logError(core, ex); throw; } }
// //==================================================================================================== // 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); }
// //==================================================================================================== // 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 Address</td>"; Panel = Panel + "<td width=\"20%\" align=\"left\">" + SpanClassAdminNormal + "Last Page Hit</td>"; Panel = Panel + "<td width=\"10%\" align=\"right\">" + SpanClassAdminNormal + "Page 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 + " " + 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); }
// //============================================================================= // 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(" <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(" <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) + " " + csData.getText("Name") + "</div>"; } else { BottomHalf = BottomHalf + "<div>" + HtmlController.checkbox("Cdef" + RowPtr, false) + HtmlController.inputHidden("CDefName" + RowPtr, RecordName) + " " + 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 Count = 0; int Pointer = 0; int TableId = 0; string TableName = ""; string FieldName = null; string IndexName = null; string DataSource = ""; DataTable RSSchema = null; string Button = null; string[,] Rows = null; int RowMax = 0; int RowPointer = 0; string Copy = ""; bool TableRowEven = false; int TableColSpan = 0; string ButtonList; // ButtonList = ButtonCancel + "," + ButtonSelect; result = AdminUIController.getHeaderTitleDescription("Modify Database Indexes", "This tool adds and removes database indexes."); // // Process Input // Button = core.docProperties.getText("Button"); TableId = core.docProperties.getInteger("TableID"); // // Get Tablename and DataSource // using (var csData = new CsModel(core)) { csData.openRecord("Tables", TableId, "Name,DataSourceID"); if (csData.ok()) { TableName = csData.getText("name"); DataSource = csData.getText("DataSourceID"); } } using (var db = new DbController(core, DataSource)) { // if ((TableId != 0) && (TableId == core.docProperties.getInteger("previoustableid")) && (!string.IsNullOrEmpty(Button))) { // // Drop Indexes // Count = core.docProperties.getInteger("DropCount"); if (Count > 0) { for (Pointer = 0; Pointer < Count; Pointer++) { if (core.docProperties.getBoolean("DropIndex." + Pointer)) { IndexName = core.docProperties.getText("DropIndexName." + Pointer); result += "<br>Dropping index [" + IndexName + "] from table [" + TableName + "]"; db.deleteIndex(TableName, IndexName); } } } // // Add Indexes // Count = core.docProperties.getInteger("AddCount"); if (Count > 0) { for (Pointer = 0; Pointer < Count; Pointer++) { if (core.docProperties.getBoolean("AddIndex." + Pointer)) { FieldName = core.docProperties.getText("AddIndexFieldName." + Pointer); IndexName = TableName + FieldName; result += "<br>Adding index [" + IndexName + "] to table [" + TableName + "] for field [" + FieldName + "]"; db.createSQLIndex(TableName, IndexName, FieldName); } } } } // TableColSpan = 3; result += HtmlController.tableStart(2, 0, 0); // // Select Table Form // result += HtmlController.tableRow("<br><br><B>Select table to index</b>", TableColSpan, false); result += HtmlController.tableRow(core.html.selectFromContent("TableID", TableId, "Tables", "", "Select a SQL table to start"), TableColSpan, false); if (TableId != 0) { // // Add/Drop Indexes form // result += HtmlController.inputHidden("PreviousTableID", TableId); // // Drop Indexes // result += HtmlController.tableRow("<br><br><B>Select indexes to remove</b>", TableColSpan, TableRowEven); RSSchema = db.getIndexSchemaData(TableName); if (RSSchema.Rows.Count == 0) { // // ----- no result // Copy += core.dateTimeNowMockable + " A schema was returned, but it contains no indexs."; result += HtmlController.tableRow(Copy, TableColSpan, TableRowEven); } else { Rows = db.convertDataTabletoArray(RSSchema); RowMax = Rows.GetUpperBound(1); for (RowPointer = 0; RowPointer <= RowMax; RowPointer++) { IndexName = GenericController.encodeText(Rows[5, RowPointer]); if (!string.IsNullOrEmpty(IndexName)) { result += HtmlController.tableRowStart(); Copy = HtmlController.checkbox("DropIndex." + RowPointer, false) + HtmlController.inputHidden("DropIndexName." + RowPointer, IndexName) + GenericController.encodeText(IndexName); result += HtmlController.td(Copy, "", 0, TableRowEven); result += HtmlController.td(GenericController.encodeText(Rows[17, RowPointer]), "", 0, TableRowEven); result += HtmlController.td(" ", "", 0, TableRowEven); result += kmaEndTableRow; TableRowEven = !TableRowEven; } } result += HtmlController.inputHidden("DropCount", RowMax + 1); } // // Add Indexes // TableRowEven = false; result += HtmlController.tableRow("<br><br><B>Select database fields to index</b>", TableColSpan, TableRowEven); RSSchema = db.getColumnSchemaData(TableName); if (RSSchema.Rows.Count == 0) { // // ----- no result // Copy += core.dateTimeNowMockable + " A schema was returned, but it contains no indexs."; result += HtmlController.tableRow(Copy, TableColSpan, TableRowEven); } else { Rows = db.convertDataTabletoArray(RSSchema); // RowMax = Rows.GetUpperBound(1); for (RowPointer = 0; RowPointer <= RowMax; RowPointer++) { result += HtmlController.tableRowStart(); Copy = HtmlController.checkbox("AddIndex." + RowPointer, false) + HtmlController.inputHidden("AddIndexFieldName." + RowPointer, Rows[3, RowPointer]) + GenericController.encodeText(Rows[3, RowPointer]); result += HtmlController.td(Copy, "", 0, TableRowEven); result += HtmlController.td(" ", "", 0, TableRowEven); result += HtmlController.td(" ", "", 0, TableRowEven); result += kmaEndTableRow; TableRowEven = !TableRowEven; } result += HtmlController.inputHidden("AddCount", RowMax + 1); } // // Spacers // result += HtmlController.tableRowStart(); result += HtmlController.td(nop2(300, 1), "200"); result += HtmlController.td(nop2(200, 1), "200"); result += HtmlController.td(" ", "100%"); result += kmaEndTableRow; } result += kmaEndTable; // // Buttons // result = AdminUIController.getToolForm(core, result, ButtonList); } } catch (Exception ex) { LogController.logError(core, ex); } return(result); }
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); } }
// //==================================================================================================== /// <summary> /// Get the Configure Edit /// </summary> /// <param name="cp"></param> /// <returns></returns> public static string get(CPClass cp) { CoreController core = cp.core; try { KeyPtrController Index = new KeyPtrController(); int ContentId = cp.Doc.GetInteger(RequestNameToolContentId); var contentMetadata = ContentMetadataModel.create(core, ContentId, true, true); int RecordCount = 0; int formFieldId = 0; string StatusMessage = ""; string ErrorMessage = ""; bool ReloadCDef = cp.Doc.GetBoolean("ReloadCDef"); if (contentMetadata != null) { string ToolButton = cp.Doc.GetText("Button"); // if (!string.IsNullOrEmpty(ToolButton)) { bool AllowContentAutoLoad = false; if (ToolButton != ButtonCancel) { // // Save the form changes // AllowContentAutoLoad = cp.Site.GetBoolean("AllowContentAutoLoad", true); cp.Site.SetProperty("AllowContentAutoLoad", "false"); // // ----- Save the input // RecordCount = GenericController.encodeInteger(cp.Doc.GetInteger("dtfaRecordCount")); if (RecordCount > 0) { int RecordPointer = 0; for (RecordPointer = 0; RecordPointer < RecordCount; RecordPointer++) { // string formFieldName = cp.Doc.GetText("dtfaName." + RecordPointer); CPContentBaseClass.FieldTypeIdEnum formFieldTypeId = (CPContentBaseClass.FieldTypeIdEnum)cp.Doc.GetInteger("dtfaType." + RecordPointer); formFieldId = GenericController.encodeInteger(cp.Doc.GetInteger("dtfaID." + RecordPointer)); bool formFieldInherited = cp.Doc.GetBoolean("dtfaInherited." + RecordPointer); // // problem - looking for the name in the Db using the form's name, but it could have changed. // have to look field up by id // foreach (KeyValuePair <string, Processor.Models.Domain.ContentFieldMetadataModel> cdefFieldKvp in contentMetadata.fields) { if (cdefFieldKvp.Value.id == formFieldId) { // // Field was found in CDef // if (cdefFieldKvp.Value.inherited && (!formFieldInherited)) { // // Was inherited, but make a copy of the field // using (var CSTarget = new CsModel(core)) { if (CSTarget.insert("Content Fields")) { using (var CSSource = new CsModel(core)) { if (CSSource.openRecord("Content Fields", formFieldId)) { CSSource.copyRecord(CSTarget); } } formFieldId = CSTarget.getInteger("ID"); CSTarget.set("ContentID", ContentId); } CSTarget.close(); } ReloadCDef = true; } else if ((!cdefFieldKvp.Value.inherited) && (formFieldInherited)) { // // Was a field, make it inherit from it's parent MetadataController.deleteContentRecord(core, "Content Fields", formFieldId); ReloadCDef = true; } else if ((!cdefFieldKvp.Value.inherited) && (!formFieldInherited)) { // // not inherited, save the field values and mark for a reload // { if (formFieldName.IndexOf(" ") != -1) { // // remoave spaces from new name // StatusMessage = StatusMessage + "<LI>Field [" + formFieldName + "] was renamed [" + GenericController.strReplace(formFieldName, " ", "") + "] because the field name can not include spaces.</LI>"; formFieldName = GenericController.strReplace(formFieldName, " ", ""); } // string SQL = null; // if ((!string.IsNullOrEmpty(formFieldName)) && ((int)formFieldTypeId != 0) && ((cdefFieldKvp.Value.nameLc == "") || (cdefFieldKvp.Value.fieldTypeId == 0))) { // // Create Db field, Field is good but was not before // core.db.createSQLTableField(contentMetadata.tableName, formFieldName, formFieldTypeId); StatusMessage = StatusMessage + "<LI>Field [" + formFieldName + "] was saved to this content definition and a database field was created in [" + contentMetadata.tableName + "].</LI>"; } else if ((string.IsNullOrEmpty(formFieldName)) || ((int)formFieldTypeId == 0)) { // // name blank or type=0 - do nothing but tell them // if (string.IsNullOrEmpty(formFieldName) && ((int)formFieldTypeId == 0)) { ErrorMessage += "<LI>Field number " + (RecordPointer + 1) + " was saved to this content definition but no database field was created because a name and field type are required.</LI>"; } else if (formFieldName == "unnamedfield" + formFieldId.ToString()) { ErrorMessage += "<LI>Field number " + (RecordPointer + 1) + " was saved to this content definition but no database field was created because a field name is required.</LI>"; } else { ErrorMessage += "<LI>Field [" + formFieldName + "] was saved to this content definition but no database field was created because a field type are required.</LI>"; } } else if ((formFieldName == cdefFieldKvp.Value.nameLc) && (formFieldTypeId != cdefFieldKvp.Value.fieldTypeId)) { // // Field Type changed, must be done manually // ErrorMessage += "<LI>Field [" + formFieldName + "] changed type from [" + DbBaseModel.getRecordName <ContentFieldTypeModel>(core.cpParent, (int)cdefFieldKvp.Value.fieldTypeId) + "] to [" + DbBaseModel.getRecordName <ContentFieldTypeModel>(core.cpParent, (int)formFieldTypeId) + "]. This may have caused a problem converting content.</LI>"; int DataSourceTypeId = core.db.getDataSourceType(); switch (DataSourceTypeId) { case DataSourceTypeODBCMySQL: SQL = "alter table " + contentMetadata.tableName + " change " + cdefFieldKvp.Value.nameLc + " " + cdefFieldKvp.Value.nameLc + " " + core.db.getSQLAlterColumnType(formFieldTypeId) + ";"; break; default: SQL = "alter table " + contentMetadata.tableName + " alter column " + cdefFieldKvp.Value.nameLc + " " + core.db.getSQLAlterColumnType(formFieldTypeId) + ";"; break; } core.db.executeNonQuery(SQL); } SQL = "Update ccFields" + " Set name=" + DbController.encodeSQLText(formFieldName) + ",type=" + (int)formFieldTypeId + ",caption=" + DbController.encodeSQLText(cp.Doc.GetText("dtfaCaption." + RecordPointer)) + ",DefaultValue=" + DbController.encodeSQLText(cp.Doc.GetText("dtfaDefaultValue." + RecordPointer)) + ",EditSortPriority=" + DbController.encodeSQLText(GenericController.encodeText(cp.Doc.GetInteger("dtfaEditSortPriority." + RecordPointer))) + ",Active=" + DbController.encodeSQLBoolean(cp.Doc.GetBoolean("dtfaActive." + RecordPointer)) + ",ReadOnly=" + DbController.encodeSQLBoolean(cp.Doc.GetBoolean("dtfaReadOnly." + RecordPointer)) + ",Authorable=" + DbController.encodeSQLBoolean(cp.Doc.GetBoolean("dtfaAuthorable." + RecordPointer)) + ",Required=" + DbController.encodeSQLBoolean(cp.Doc.GetBoolean("dtfaRequired." + RecordPointer)) + ",UniqueName=" + DbController.encodeSQLBoolean(cp.Doc.GetBoolean("dtfaUniqueName." + RecordPointer)) + ",TextBuffered=" + DbController.encodeSQLBoolean(cp.Doc.GetBoolean("dtfaTextBuffered." + RecordPointer)) + ",Password="******"dtfaPassword." + RecordPointer)) + ",HTMLContent=" + DbController.encodeSQLBoolean(cp.Doc.GetBoolean("dtfaHTMLContent." + RecordPointer)) + ",EditTab=" + DbController.encodeSQLText(cp.Doc.GetText("dtfaEditTab." + RecordPointer)) + ",Scramble=" + DbController.encodeSQLBoolean(cp.Doc.GetBoolean("dtfaScramble." + RecordPointer)) + ""; if (core.session.isAuthenticatedAdmin()) { SQL += ",adminonly=" + DbController.encodeSQLBoolean(cp.Doc.GetBoolean("dtfaAdminOnly." + RecordPointer)); } if (core.session.isAuthenticatedDeveloper()) { SQL += ",DeveloperOnly=" + DbController.encodeSQLBoolean(cp.Doc.GetBoolean("dtfaDeveloperOnly." + RecordPointer)); } SQL += " where ID=" + formFieldId; core.db.executeNonQuery(SQL); ReloadCDef = true; } } break; } } } } core.cache.invalidateAll(); core.clearMetaData(); } if (ToolButton == ButtonAdd) { // // ----- Insert a blank Field var defaultValues = ContentMetadataModel.getDefaultValueDict(core, ContentFieldModel.tableMetadata.contentName); var field = ContentFieldModel.addDefault <ContentFieldModel>(core.cpParent, defaultValues); field.name = "unnamedField" + field.id.ToString(); field.contentId = ContentId; field.editSortPriority = 0; field.save(core.cpParent); ReloadCDef = true; } // // ----- Button Reload CDef if (ToolButton == ButtonSaveandInvalidateCache) { core.cache.invalidateAll(); core.clearMetaData(); } // // ----- Restore Content Autoload site property // if (AllowContentAutoLoad) { cp.Site.SetProperty("AllowContentAutoLoad", AllowContentAutoLoad.ToString()); } // // ----- Cancel or Save, reload CDef and go // if ((ToolButton == ButtonCancel) || (ToolButton == ButtonOK)) { // // ----- Exit back to menu // return(core.webServer.redirect(core.appConfig.adminRoute, "Tool-ConfigureContentEdit, ok or cancel button, go to root.")); } } } // // Print Output string description = "" + HtmlController.p("Use this tool to add or modify content definition fields and the underlying sql table fields.") + ((ContentId.Equals(0)) ? "" : "" + HtmlController.ul("" + HtmlController.li(HtmlController.a("Edit Content", "?aa=0&cid=3&id=" + ContentId + "&tx=&ad=0&asf=1&af=4", "nav-link btn btn-primary"), "nav-item mr-1") + HtmlController.li(HtmlController.a("Edit Records", "?cid=" + ContentId, "nav-link btn btn-primary"), "nav-item mr-1") + HtmlController.li(HtmlController.a("Select Different Fields", "?af=105", "nav-link btn btn-primary"), "nav-item mr-1") , "nav") ); StringBuilderLegacyController Stream = new StringBuilderLegacyController(); Stream.add(AdminUIController.getHeaderTitleDescription("Manage Admin Edit Fields", description)); // // -- status of last operation if (!string.IsNullOrEmpty(StatusMessage)) { Stream.add(AdminUIController.getToolFormRow(core, "<UL>" + StatusMessage + "</UL>")); } // // -- errors with last operations if (!string.IsNullOrEmpty(ErrorMessage)) { Stream.add(HtmlController.div("There was a problem saving these changes" + "<UL>" + ErrorMessage + "</UL>", "ccError")); } if (ReloadCDef) { contentMetadata = Processor.Models.Domain.ContentMetadataModel.create(core, ContentId, true, true); } string ButtonList = ButtonCancel + "," + ButtonSelect; if (ContentId == 0) { // // content tables that have edit forms to Configure bool isEmptyList = false; Stream.add(AdminUIController.getToolFormInputRow(core, "Select a Content Definition to Configure", AdminUIEditorController.getLookupContentEditor(core, RequestNameToolContentId, ContentId, ContentMetadataModel.getContentId(core, "Content"), ref isEmptyList, false, "", "", false, ""))); } else { // // Configure edit form Stream.add(HtmlController.inputHidden(RequestNameToolContentId, ContentId)); Stream.add(core.html.getPanelTop()); ButtonList = ButtonCancel + "," + ButtonSave + "," + ButtonOK + "," + ButtonAdd; // // Get a new copy of the content definition // Stream.add(SpanClassAdminNormal + "<P><B>" + contentMetadata.name + "</b></P>"); Stream.add("<table border=\"0\" cellpadding=\"1\" cellspacing=\"1\" width=\"100%\">"); // int ParentContentId = contentMetadata.parentId; bool AllowCDefInherit = false; Processor.Models.Domain.ContentMetadataModel ParentCDef = null; if (ParentContentId == -1) { AllowCDefInherit = false; } else { AllowCDefInherit = true; string ParentContentName = MetadataController.getContentNameByID(core, ParentContentId); ParentCDef = Processor.Models.Domain.ContentMetadataModel.create(core, ParentContentId, true, true); } bool NeedFootNote1 = false; bool NeedFootNote2 = false; if (contentMetadata.fields.Count > 0) { // // -- header row Stream.add("<tr>"); Stream.add("<td valign=\"bottom\" width=\"50\" class=\"ccPanelInput\" align=\"center\"></td>"); if (!AllowCDefInherit) { Stream.add("<td valign=\"bottom\" width=\"100\" class=\"ccPanelInput\" align=\"center\">" + SpanClassAdminSmall + "<b><br>Inherited*</b></span></td>"); NeedFootNote1 = true; } else { Stream.add("<td valign=\"bottom\" width=\"100\" class=\"ccPanelInput\" align=\"center\">" + SpanClassAdminSmall + "<b><br>Inherited</b></span></td>"); } Stream.add("<td valign=\"bottom\" width=\"100\" class=\"ccPanelInput\" align=\"left\">" + SpanClassAdminSmall + "<b><br>Field</b></span></td>"); Stream.add("<td valign=\"bottom\" width=\"100\" class=\"ccPanelInput\" align=\"left\">" + SpanClassAdminSmall + "<b><br>Caption</b></span></td>"); Stream.add("<td valign=\"bottom\" width=\"100\" class=\"ccPanelInput\" align=\"left\">" + SpanClassAdminSmall + "<b><br>Edit Tab</b></span></td>"); Stream.add("<td valign=\"bottom\" width=\"100\" class=\"ccPanelInput\" align=\"left\">" + SpanClassAdminSmall + "<b><br>Default</b></span></td>"); Stream.add("<td valign=\"bottom\" width=\"50\" class=\"ccPanelInput\" align=\"left\">" + SpanClassAdminSmall + "<b><br>Type</b></span></td>"); Stream.add("<td valign=\"bottom\" width=\"50\" class=\"ccPanelInput\" align=\"left\">" + SpanClassAdminSmall + "<b>Edit<br>Order</b></span></td>"); Stream.add("<td valign=\"bottom\" width=\"50\" class=\"ccPanelInput\" align=\"center\">" + SpanClassAdminSmall + "<b><br>Active</b></span></td>"); Stream.add("<td valign=\"bottom\" width=\"50\" class=\"ccPanelInput\" align=\"center\">" + SpanClassAdminSmall + "<b>Read<br>Only</b></span></td>"); Stream.add("<td valign=\"bottom\" width=\"50\" class=\"ccPanelInput\" align=\"center\">" + SpanClassAdminSmall + "<b><br>Auth</b></span></td>"); Stream.add("<td valign=\"bottom\" width=\"50\" class=\"ccPanelInput\" align=\"center\">" + SpanClassAdminSmall + "<b><br>Req</b></span></td>"); Stream.add("<td valign=\"bottom\" width=\"50\" class=\"ccPanelInput\" align=\"center\">" + SpanClassAdminSmall + "<b><br>Unique</b></span></td>"); Stream.add("<td valign=\"bottom\" width=\"50\" class=\"ccPanelInput\" align=\"center\">" + SpanClassAdminSmall + "<b>Text<br>Buffer</b></span></td>"); Stream.add("<td valign=\"bottom\" width=\"50\" class=\"ccPanelInput\" align=\"center\">" + SpanClassAdminSmall + "<b><br>Pass</b></span></td>"); Stream.add("<td valign=\"bottom\" width=\"50\" class=\"ccPanelInput\" align=\"center\">" + SpanClassAdminSmall + "<b>Text<br>Scrm</b></span></td>"); Stream.add("<td valign=\"bottom\" width=\"50\" class=\"ccPanelInput\" align=\"left\">" + SpanClassAdminSmall + "<b><br>HTML</b></span></td>"); Stream.add("<td valign=\"bottom\" width=\"50\" class=\"ccPanelInput\" align=\"left\">" + SpanClassAdminSmall + "<b>Admin<br>Only</b></span></td>"); Stream.add("<td valign=\"bottom\" width=\"50\" class=\"ccPanelInput\" align=\"left\">" + SpanClassAdminSmall + "<b>Dev<br>Only</b></span></td>"); Stream.add("</tr>"); RecordCount = 0; // // Build a select template for Type // string TypeSelectTemplate = core.html.selectFromContent("menuname", -1, "Content Field Types", "", "unknown"); // // Index the sort order // List <FieldSortClass> fieldList = new List <FieldSortClass>(); int FieldCount = contentMetadata.fields.Count; foreach (var keyValuePair in contentMetadata.fields) { FieldSortClass fieldSort = new FieldSortClass(); string sortOrder = ""; fieldSort.field = keyValuePair.Value; sortOrder = ""; if (fieldSort.field.active) { sortOrder += "0"; } else { sortOrder += "1"; } if (fieldSort.field.authorable) { sortOrder += "0"; } else { sortOrder += "1"; } sortOrder += fieldSort.field.editTabName + getIntegerString(fieldSort.field.editSortPriority, 10) + getIntegerString(fieldSort.field.id, 10); fieldSort.sort = sortOrder; fieldList.Add(fieldSort); } fieldList.Sort((p1, p2) => p1.sort.CompareTo(p2.sort)); StringBuilderLegacyController StreamValidRows = new StringBuilderLegacyController(); var contentFieldsCdef = Processor.Models.Domain.ContentMetadataModel.createByUniqueName(core, "content fields"); foreach (FieldSortClass fieldsort in fieldList) { StringBuilderLegacyController streamRow = new StringBuilderLegacyController(); bool rowValid = true; // // If Field has name and type, it is locked and can not be changed // bool FieldLocked = (fieldsort.field.nameLc != "") && (fieldsort.field.fieldTypeId != 0); // // put the menu into the current menu format // formFieldId = fieldsort.field.id; streamRow.add(HtmlController.inputHidden("dtfaID." + RecordCount, formFieldId)); streamRow.add("<tr>"); // // edit button // streamRow.add("<td class=\"ccPanelInput\" align=\"left\">" + AdminUIController.getRecordEditAnchorTag(core, contentFieldsCdef, formFieldId) + "</td>"); // // Inherited // if (!AllowCDefInherit) { // // no parent // streamRow.add("<td class=\"ccPanelInput\" align=\"center\">" + SpanClassAdminSmall + "False</span></td>"); } else if (fieldsort.field.inherited) { // // inherited property // streamRow.add("<td class=\"ccPanelInput\" align=\"center\">" + HtmlController.checkbox("dtfaInherited." + RecordCount, fieldsort.field.inherited) + "</td>"); } else { Processor.Models.Domain.ContentFieldMetadataModel parentField = null; // // CDef has a parent, but the field is non-inherited, test for a matching Parent Field // if (ParentCDef == null) { foreach (KeyValuePair <string, Processor.Models.Domain.ContentFieldMetadataModel> kvp in ParentCDef.fields) { if (kvp.Value.nameLc == fieldsort.field.nameLc) { parentField = kvp.Value; break; } } } if (parentField == null) { streamRow.add("<td class=\"ccPanelInput\" align=\"center\">" + SpanClassAdminSmall + "False**</span></td>"); NeedFootNote2 = true; } else { streamRow.add("<td class=\"ccPanelInput\" align=\"center\">" + HtmlController.checkbox("dtfaInherited." + RecordCount, fieldsort.field.inherited) + "</td>"); } } // // name // bool tmpValue = string.IsNullOrEmpty(fieldsort.field.nameLc); rowValid = rowValid && !tmpValue; streamRow.add("<td class=\"ccPanelInput\" align=\"left\"><nobr>"); if (fieldsort.field.inherited) { streamRow.add(SpanClassAdminSmall + fieldsort.field.nameLc + " </SPAN>"); } else if (FieldLocked) { streamRow.add(SpanClassAdminSmall + fieldsort.field.nameLc + " </SPAN><input type=hidden name=dtfaName." + RecordCount + " value=\"" + fieldsort.field.nameLc + "\">"); } else { streamRow.add(HtmlController.inputText_Legacy(core, "dtfaName." + RecordCount, fieldsort.field.nameLc, 1, 10)); } streamRow.add("</nobr></td>"); // // caption // streamRow.add("<td class=\"ccPanelInput\" align=\"left\"><nobr>"); if (fieldsort.field.inherited) { streamRow.add(SpanClassAdminSmall + fieldsort.field.caption + "</SPAN>"); } else { streamRow.add(HtmlController.inputText_Legacy(core, "dtfaCaption." + RecordCount, fieldsort.field.caption, 1, 10)); } streamRow.add("</nobr></td>"); // // Edit Tab // streamRow.add("<td class=\"ccPanelInput\" align=\"left\"><nobr>"); if (fieldsort.field.inherited) { streamRow.add(SpanClassAdminSmall + fieldsort.field.editTabName + "</SPAN>"); } else { streamRow.add(HtmlController.inputText_Legacy(core, "dtfaEditTab." + RecordCount, fieldsort.field.editTabName, 1, 10)); } streamRow.add("</nobr></td>"); // // default // streamRow.add("<td class=\"ccPanelInput\" align=\"left\"><nobr>"); if (fieldsort.field.inherited) { streamRow.add(SpanClassAdminSmall + GenericController.encodeText(fieldsort.field.defaultValue) + "</SPAN>"); } else { streamRow.add(HtmlController.inputText_Legacy(core, "dtfaDefaultValue." + RecordCount, GenericController.encodeText(fieldsort.field.defaultValue), 1, 10)); } streamRow.add("</nobr></td>"); // // type // rowValid = rowValid && (fieldsort.field.fieldTypeId > 0); streamRow.add("<td class=\"ccPanelInput\" align=\"left\"><nobr>"); if (fieldsort.field.inherited) { using (var csData = new CsModel(core)) { csData.openRecord("Content Field Types", (int)fieldsort.field.fieldTypeId); if (!csData.ok()) { streamRow.add(SpanClassAdminSmall + "Unknown[" + fieldsort.field.fieldTypeId + "]</SPAN>"); } else { streamRow.add(SpanClassAdminSmall + csData.getText("Name") + "</SPAN>"); } } } else if (FieldLocked) { streamRow.add(DbBaseModel.getRecordName <ContentFieldTypeModel>(core.cpParent, (int)fieldsort.field.fieldTypeId) + HtmlController.inputHidden("dtfaType." + RecordCount, (int)fieldsort.field.fieldTypeId)); } else { string TypeSelect = TypeSelectTemplate; TypeSelect = GenericController.strReplace(TypeSelect, "menuname", "dtfaType." + RecordCount, 1, 99, 1); TypeSelect = GenericController.strReplace(TypeSelect, "=\"" + fieldsort.field.fieldTypeId + "\"", "=\"" + fieldsort.field.fieldTypeId + "\" selected", 1, 99, 1); streamRow.add(TypeSelect); } streamRow.add("</nobr></td>"); // // sort priority // streamRow.add("<td class=\"ccPanelInput\" align=\"left\"><nobr>"); if (fieldsort.field.inherited) { streamRow.add(SpanClassAdminSmall + fieldsort.field.editSortPriority + "</SPAN>"); } else { streamRow.add(HtmlController.inputText_Legacy(core, "dtfaEditSortPriority." + RecordCount, fieldsort.field.editSortPriority.ToString(), 1, 10)); } streamRow.add("</nobr></td>"); // // active // streamRow.add(configureEdit_CheckBox("dtfaActive." + RecordCount, fieldsort.field.active, fieldsort.field.inherited)); // // read only // streamRow.add(configureEdit_CheckBox("dtfaReadOnly." + RecordCount, fieldsort.field.readOnly, fieldsort.field.inherited)); // // authorable // streamRow.add(configureEdit_CheckBox("dtfaAuthorable." + RecordCount, fieldsort.field.authorable, fieldsort.field.inherited)); // // required // streamRow.add(configureEdit_CheckBox("dtfaRequired." + RecordCount, fieldsort.field.required, fieldsort.field.inherited)); // // UniqueName // streamRow.add(configureEdit_CheckBox("dtfaUniqueName." + RecordCount, fieldsort.field.uniqueName, fieldsort.field.inherited)); // // text buffered // streamRow.add(configureEdit_CheckBox("dtfaTextBuffered." + RecordCount, fieldsort.field.textBuffered, fieldsort.field.inherited)); // // password // streamRow.add(configureEdit_CheckBox("dtfaPassword." + RecordCount, fieldsort.field.password, fieldsort.field.inherited)); // // scramble // streamRow.add(configureEdit_CheckBox("dtfaScramble." + RecordCount, fieldsort.field.scramble, fieldsort.field.inherited)); // // HTML Content // streamRow.add(configureEdit_CheckBox("dtfaHTMLContent." + RecordCount, fieldsort.field.htmlContent, fieldsort.field.inherited)); // // Admin Only // if (core.session.isAuthenticatedAdmin()) { streamRow.add(configureEdit_CheckBox("dtfaAdminOnly." + RecordCount, fieldsort.field.adminOnly, fieldsort.field.inherited)); } // // Developer Only // if (core.session.isAuthenticatedDeveloper()) { streamRow.add(configureEdit_CheckBox("dtfaDeveloperOnly." + RecordCount, fieldsort.field.developerOnly, fieldsort.field.inherited)); } // streamRow.add("</tr>"); RecordCount = RecordCount + 1; // // rows are built - put the blank rows at the top // if (!rowValid) { Stream.add(streamRow.text); } else { StreamValidRows.add(streamRow.text); } } Stream.add(StreamValidRows.text); Stream.add(HtmlController.inputHidden("dtfaRecordCount", RecordCount)); } Stream.add("</table>"); // Stream.add(core.html.getPanelBottom()); if (NeedFootNote1) { Stream.add("<br>*Field Inheritance is not allowed because this Content Definition has no parent."); } if (NeedFootNote2) { Stream.add("<br>**This field can not be inherited because the Parent Content Definition does not have a field with the same name."); } } Stream.add(HtmlController.inputHidden("ReloadCDef", ReloadCDef)); // // -- assemble form return(AdminUIController.getToolForm(core, Stream.text, ButtonList)); } catch (Exception ex) { LogController.logError(core, ex); return(toolExceptionMessage); } }
//==================================================================================================== /// <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 + "]"); } }
// //============================================================================= // 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); } }
// //======================================================================== // public static void processJoinForm(CoreController core) { try { string ErrorMessage = ""; string FirstName = null; string LastName = null; string FullName = null; string Email = null; int errorCode = 0; // string loginForm_Username = ""; string loginForm_Password = ""; loginForm_Username = core.docProperties.getText("username"); loginForm_Password = core.docProperties.getText("password"); // if (!GenericController.encodeBoolean(core.siteProperties.getBoolean("AllowMemberJoin", false))) { ErrorController.addUserError(core, "This site does not accept public main_MemberShip."); } else { if (!core.session.isNewCredentialOK(loginForm_Username, loginForm_Password, ref ErrorMessage, ref errorCode)) { ErrorController.addUserError(core, ErrorMessage); } else { if (!(!core.doc.userErrorList.Count.Equals(0))) { using (var csData = new CsModel(core)) { csData.open("people", "ID=" + DbController.encodeSQLNumber(core.session.user.id)); if (!csData.ok()) { LogController.logError(core, new Exception("Could not open the current members account to set the username and password.")); } else { if ((csData.getText("username") != "") || (csData.getText("password") != "") || (csData.getBoolean("admin")) || (csData.getBoolean("developer"))) { // // if the current account can be logged into, you can not join 'into' it // core.session.logout(); } FirstName = core.docProperties.getText("firstname"); LastName = core.docProperties.getText("lastname"); FullName = FirstName + " " + LastName; Email = core.docProperties.getText("email"); csData.set("FirstName", FirstName); csData.set("LastName", LastName); csData.set("Name", FullName); csData.set("username", loginForm_Username); csData.set("password", loginForm_Password); core.session.authenticateById(core.session.user.id, core.session); } csData.close(); } } } } PersonModel.invalidateCacheOfRecord <PersonModel>(core.cpParent, core.session.user.id); } catch (Exception ex) { LogController.logError(core, ex); throw; } }
// //======================================================================== // 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%\"> </td></tr></table>"); // // Build and add tabs // adminMenu.addEntry("Custom Reports", Tab0.text, "ccAdminTab"); adminMenu.addEntry("Request New 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); } }