// //==================================================================================================== /// <summary> /// getFieldEditorPreference remote method /// </summary> /// <param name="cp"></param> /// <returns></returns> public override object Execute(Contensive.BaseClasses.CPBaseClass cp) { try { CoreController core = ((CPClass)cp).core; // // -- Email click detected EmailDropModel emailDrop = DbBaseModel.create <EmailDropModel>(core.cpParent, core.docProperties.getInteger(rnEmailClickFlag)); if (emailDrop != null) { PersonModel recipient = DbBaseModel.create <PersonModel>(core.cpParent, core.docProperties.getInteger(rnEmailMemberId)); if (recipient != null) { EmailLogModel log = DbBaseModel.addDefault <EmailLogModel>(core.cpParent); log.name = "User " + recipient.name + " clicked link from email drop " + emailDrop.name + " at " + core.doc.profileStartTime.ToString(); log.emailDropId = emailDrop.id; log.emailId = emailDrop.emailId; log.memberId = recipient.id; log.logType = EmailLogTypeClick; log.visitId = cp.Visit.Id; log.save(cp); } } } catch (Exception ex) { cp.Site.ErrorReport(ex); } return(""); }
// //==================================================================================================== /// <summary> /// getFieldEditorPreference remote method /// </summary> /// <param name="cp"></param> /// <returns></returns> public override object Execute(Contensive.BaseClasses.CPBaseClass cp) { try { CoreController core = ((CPClass)cp).core; int emailDropId = core.docProperties.getInteger(rnEmailOpenFlag); if (emailDropId != 0) { // // -- Email open detected. Log it and redirect to a 1x1 spacer EmailDropModel emailDrop = DbBaseModel.create <EmailDropModel>(core.cpParent, emailDropId); if (emailDrop != null) { PersonModel recipient = DbBaseModel.create <PersonModel>(core.cpParent, core.docProperties.getInteger(rnEmailMemberId)); if (recipient != null) { EmailLogModel log = DbBaseModel.addDefault <EmailLogModel>(core.cpParent); log.name = "User " + recipient.name + " opened email drop " + emailDrop.name + " at " + core.doc.profileStartTime.ToString(); log.emailDropId = emailDrop.id; log.emailId = emailDrop.emailId; log.memberId = recipient.id; log.logType = EmailLogTypeOpen; log.visitId = cp.Visit.Id; log.save(cp); } } } core.webServer.redirect(NonEncodedLink: "" + cdnPrefix + "images/spacer.gif", RedirectReason: "Group Email Open hit, redirecting to a dummy image", IsPageNotFound: false, allowDebugMessage: false); } catch (Exception ex) { cp.Site.ErrorReport(ex); } return(""); }
// //==================================================================================================== /// <summary> /// Add a user to a group with an expiration date /// </summary> /// <param name="core"></param> /// <param name="group"></param> /// <param name="user"></param> /// <param name="dateExpires"></param> public static void addUser(CoreController core, GroupModel group, PersonModel user, DateTime dateExpires) { try { var ruleList = DbBaseModel.createList <MemberRuleModel>(core.cpParent, "(MemberID=" + user.id.ToString() + ")and(GroupID=" + group.id.ToString() + ")"); if (ruleList.Count == 0) { // -- add new rule var rule = DbBaseModel.addDefault <MemberRuleModel>(core.cpParent, Models.Domain.ContentMetadataModel.getDefaultValueDict(core, "groups")); rule.groupId = group.id; rule.memberId = user.id; rule.dateExpires = dateExpires; rule.save(core.cpParent); return; } // at least one rule found, set expire date, delete the rest var ruleFirst = ruleList.First(); if (ruleFirst.dateExpires != dateExpires) { ruleFirst.dateExpires = dateExpires; ruleFirst.save(core.cpParent); } if (ruleList.Count > 1) { foreach (var rule in ruleList) { if (!rule.Equals(ruleFirst)) { DbBaseModel.delete <MemberRuleModel>(core.cpParent, rule.id); } } } } catch (Exception ex) { LogController.logError(core, ex); } }
// //==================================================================================================== /// <summary> /// setAdminSiteFieldHelp remote method /// </summary> /// <param name="cp"></param> /// <returns></returns> public override object Execute(Contensive.BaseClasses.CPBaseClass cp) { string result = ""; try { CoreController core = ((CPClass)cp).core; if (cp.User.IsAdmin) { int fieldId = cp.Doc.GetInteger("fieldId"); var help = ContentFieldHelpModel.createByFieldId(cp, fieldId); if (help == null) { help = DbBaseModel.addDefault <ContentFieldHelpModel>(core.cpParent, Processor.Models.Domain.ContentMetadataModel.getDefaultValueDict(core, ContentFieldHelpModel.tableMetadata.contentName)); help.fieldId = fieldId; } help.helpCustom = cp.Doc.GetText("helpcustom"); help.save(cp); ContentFieldModel contentField = DbBaseModel.create <ContentFieldModel>(core.cpParent, fieldId); if (contentField != null) { ContentMetadataModel.invalidateCache(core, contentField.contentId); } } } catch (Exception ex) { cp.Site.ErrorReport(ex); } return(result); }
// //==================================================================================================== /// <summary> /// Add a command task to the taskQueue to be run by the taskRunner. Returns false if the task was already there (dups fround by command name and cmdDetailJson) /// </summary> /// <param name="core"></param> /// <param name="command"></param> /// <param name="cmdDetail"></param> /// <param name="downloadName"></param> /// <returns></returns> static public bool addTaskToQueue(CoreController core, TaskModel.CmdDetailClass cmdDetail, bool blockDuplicates, string downloadName, string downloadFilename) { try { // int downloadId = 0; if (!string.IsNullOrEmpty(downloadName)) { Dictionary <string, string> defaultValues = ContentMetadataModel.getDefaultValueDict(core, DownloadModel.tableMetadata.contentName); var download = DbBaseModel.addDefault <DownloadModel>(core.cpParent, defaultValues); download.name = downloadName; download.dateRequested = core.dateTimeNowMockable; download.requestedBy = core.session.user.id; if (!string.IsNullOrEmpty(downloadFilename)) { // // -- if the donwloadfilename is specified, save it in the download record and force the file to save with a space in content download.filename.filename = FileController.getVirtualRecordUnixPathFilename(DownloadModel.tableMetadata.tableNameLower, "filename", download.id, downloadFilename); download.filename.content = " "; } downloadId = download.id; download.save(core.cpParent); } string cmdDetailJson = SerializeObject(cmdDetail); bool allowAdd = true; if (blockDuplicates) { // // -- Search for a duplicate string sql = "select top 1 id from cctasks where ((cmdDetail=" + DbController.encodeSQLText(cmdDetailJson) + ")and(datestarted is null)and(datecompleted is null))"; using (var csData = new CsModel(core)) { allowAdd = !csData.openSql(sql); } } // // -- add it to the queue and shell out to the command if (allowAdd) { var task = TaskModel.addEmpty <TaskModel>(core.cpParent); task.name = "addon [#" + cmdDetail.addonId + "," + cmdDetail.addonName + "]"; task.cmdDetail = cmdDetailJson; task.resultDownloadId = downloadId; task.save(core.cpParent); LogController.logTrace(core, "addTaskToQueue, task added, cmdDetailJson [" + cmdDetailJson + "]"); return(true); } LogController.logTrace(core, "addTaskToQueue, task blocked because duplicate found, cmdDetailJson [" + cmdDetailJson + "]"); return(false); } catch (Exception ex) { LogController.logError(core, ex); return(false); } }
// // ==================================================================================================== public static AddonMockDataModel createOrAddSettings(CPBaseClass cp, string settingsGuid) { AddonMockDataModel result = create <AddonMockDataModel>(cp, settingsGuid); if ((result == null)) { // // -- create default content result = addDefault <AddonMockDataModel>(cp); result.name = tableMetadata.contentName + " " + result.id; result.ccguid = settingsGuid; result.themeStyleId = 0; result.padTop = false; result.padBottom = false; result.padRight = false; result.padLeft = false; // // -- create custom content result.jsondata = "{\"headline\":\"Hello World\",\"items\":[{\"name\":\"Rock\",\"price\":\"$1.24\"},{\"name\":\"Nice Rock\",\"price\":\"$2.99\"}]}"; // DateTime rightNow = DateTime.Now; var layout = DbBaseModel.create <LayoutModel>(cp, Constants.guidAddonMockLayout); string defaultLayout = "<h2>{{headline}}</h2><ul>{{#items}}<hr><li><div>name: {{name}}</div><div>price: {{price}}</div></li>{{/items}}</ul><hr>"; if (layout == null) { // // -- no layout found for the default guid, create now layout = DbBaseModel.addDefault <LayoutModel>(cp); layout.name = "Addon Mock Default Layout, " + rightNow.Year + rightNow.Month.ToString().PadLeft(2, '0') + rightNow.Day.ToString().PadLeft(2, '0'); layout.ccguid = Constants.guidAddonMockLayout; layout.layout.content = defaultLayout; layout.save(cp); } if (layout.layout.content != defaultLayout) { // // -- layout does not match default content, they edited it so just create a new record layout = DbBaseModel.addDefault <LayoutModel>(cp); layout.name = "Addon Mock Default Layout, " + rightNow.Year + rightNow.Month.ToString().PadLeft(2, '0') + rightNow.Day.ToString().PadLeft(2, '0'); layout.ccguid = cp.Utils.CreateGuid(); layout.layout.content = defaultLayout; layout.save(cp); } result.layoutid = layout.id; // result.save(cp); // // -- track the last modified date cp.Content.LatestContentModifiedDate.Track(result.modifiedDate); } return(result); }
// //==================================================================================================== /// <summary> /// Add a user to a group. if group is missing and argument is name or guid, it is created. /// </summary> /// <param name="core"></param> /// <param name="groupNameIdOrGuid"></param> /// <param name="userid"></param> /// <param name="dateExpires"></param> public static void addUser(CoreController core, string groupNameIdOrGuid, int userid, DateTime dateExpires) { GroupModel group = null; if (groupNameIdOrGuid.isNumeric()) { group = DbBaseModel.create <GroupModel>(core.cpParent, GenericController.encodeInteger(groupNameIdOrGuid)); if (group == null) { LogController.logError(core, new GenericException("addUser called with invalid groupId [" + groupNameIdOrGuid + "]")); return; } } else if (GenericController.isGuid(groupNameIdOrGuid)) { group = DbBaseModel.create <GroupModel>(core.cpParent, groupNameIdOrGuid); if (group == null) { var defaultValues = ContentMetadataModel.getDefaultValueDict(core, "groups"); group = DbBaseModel.addDefault <GroupModel>(core.cpParent, defaultValues); group.ccguid = groupNameIdOrGuid; group.name = groupNameIdOrGuid; group.caption = groupNameIdOrGuid; group.save(core.cpParent); } } else { group = DbBaseModel.createByUniqueName <GroupModel>(core.cpParent, groupNameIdOrGuid); if (group == null) { group = DbBaseModel.addDefault <GroupModel>(core.cpParent, Models.Domain.ContentMetadataModel.getDefaultValueDict(core, "groups")); group.ccguid = groupNameIdOrGuid; group.name = groupNameIdOrGuid; group.caption = groupNameIdOrGuid; group.save(core.cpParent); } } var user = DbBaseModel.create <PersonModel>(core.cpParent, userid); if (user != null) { addUser(core, group, user, dateExpires); } }
// public static void process(CPBaseClass cp, HtmlDocument htmlDoc, ref List <string> userMessageList) { // // -- data attribute { string xPath = "//*[@data-layout]"; HtmlNodeCollection nodeList = htmlDoc.DocumentNode.SelectNodes(xPath); if (nodeList != null) { foreach (HtmlNode node in nodeList) { string layoutRecordName = node.Attributes["data-layout"]?.Value; node.Attributes.Remove("data-layout"); // // -- body found, set the htmlDoc to the body var layoutDoc = new HtmlDocument(); layoutDoc.LoadHtml(node.InnerHtml); // // -- process the layout DataDeleteController.process(layoutDoc); MustacheVariableController.process(layoutDoc); MustacheSectionController.process(layoutDoc); MustacheTruthyController.process(layoutDoc); MustacheInvertedSectionController.process(layoutDoc); MustacheValueController.process(layoutDoc); DataAddonController.process(cp, layoutDoc); // // -- save the alyout LayoutModel layout = null; if ((layout == null) && !string.IsNullOrWhiteSpace(layoutRecordName)) { layout = DbBaseModel.createByUniqueName <LayoutModel>(cp, layoutRecordName); if (layout == null) { layout = DbBaseModel.addDefault <LayoutModel>(cp); layout.name = layoutRecordName; } layout.layout.content = layoutDoc.DocumentNode.OuterHtml; layout.save(cp); userMessageList.Add("Saved Layout '" + layoutRecordName + "' from data-layout attribute."); } } } } }
// //==================================================================================================== /// <summary> /// getFieldEditorPreference remote method /// </summary> /// <param name="cp"></param> /// <returns></returns> public override object Execute(Contensive.BaseClasses.CPBaseClass cp) { try { CoreController core = ((CPClass)cp).core; // // -- click spam block detected { string recipientEmailToBlock = core.docProperties.getText(rnEmailBlockRecipientEmail); if (!string.IsNullOrEmpty(recipientEmailToBlock)) { List <PersonModel> recipientList = DbBaseModel.createList <PersonModel>(core.cpParent, "(email=" + DbController.encodeSQLText(recipientEmailToBlock) + ")"); foreach (var recipient in recipientList) { recipient.allowBulkEmail = false; recipient.save(cp, 0); // // -- Email spam footer was clicked, clear the AllowBulkEmail field EmailController.addToBlockList(core, recipientEmailToBlock); // // -- log entry to track the result of this email drop int emailDropId = core.docProperties.getInteger(rnEmailBlockRequestDropId); if (emailDropId != 0) { EmailDropModel emailDrop = DbBaseModel.create <EmailDropModel>(cp, emailDropId); if (emailDrop != null) { EmailLogModel log = DbBaseModel.addDefault <EmailLogModel>(core.cpParent); log.name = "User " + recipient.name + " clicked linked spam block from email drop " + emailDrop.name + " at " + core.doc.profileStartTime.ToString(); log.emailDropId = emailDrop.id; log.emailId = emailDrop.emailId; log.memberId = recipient.id; log.logType = EmailLogTypeBlockRequest; log.visitId = cp.Visit.Id; log.save(cp); } } } } return(cp.Content.GetCopy("Default Email Blocked Response Page", Resources.defaultEmailBlockedResponsePage)); } } catch (Exception ex) { cp.Site.ErrorReport(ex); } return(""); }
// // ==================================================================================================== // public static string getLayout(BaseClasses.CPBaseClass CP, string layoutName, string layoutGuid, string layoutFilename) { try { // // -- install default detail layout LayoutModel layout = DbBaseModel.create <LayoutModel>(CP, layoutGuid); if ((layout == null)) { // // -- no layout found, create it layout = DbBaseModel.addDefault <LayoutModel>(CP); layout.name = layoutName; layout.ccguid = layoutGuid; layout.save(CP); } if (string.IsNullOrEmpty(layout.layout.content)) { // // -- content is blank, populate with layoutfilename BaseClasses.CPBlockBaseClass block = CP.BlockNew(); block.Load(CP.CdnFiles.Read(layoutFilename)); layout.layout.content = block.GetInner("body"); if (string.IsNullOrEmpty(layout.layout.content)) { layout.layout.content = block.GetHtml(); } layout.save(CP); } // // -- exit if not editing if (!CP.User.IsEditingAnything) { return(layout.layout.content); } // // -- wrap with edit return(CP.Content.GetEditWrapper(layout.layout.content, layout.contentControlId, layout.id)); } catch (Exception ex) { CP.Site.ErrorReport(ex); throw; } }
// //====================================================================================================== // public static void installNode(CoreController core, XmlNode rootNode, int collectionId, ref bool return_UpgradeOK, ref string return_ErrorMessage, ref bool collectionIncludesDiagnosticAddons) { return_ErrorMessage = ""; return_UpgradeOK = true; try { string Basename = GenericController.toLCase(rootNode.Name); if (Basename == "layout") { bool IsFound = false; string layoutName = XmlController.getXMLAttribute(core, ref IsFound, rootNode, "name", "No Name"); if (string.IsNullOrEmpty(layoutName)) { layoutName = "No Name"; } string layoutGuid = XmlController.getXMLAttribute(core, ref IsFound, rootNode, "guid", layoutName); if (string.IsNullOrEmpty(layoutGuid)) { layoutGuid = layoutName; } var layout = DbBaseModel.create <LayoutModel>(core.cpParent, layoutGuid); if (layout == null) { layout = DbBaseModel.createByUniqueName <LayoutModel>(core.cpParent, layoutName); } if (layout == null) { layout = DbBaseModel.addDefault <LayoutModel>(core.cpParent); } layout.ccguid = layoutGuid; layout.name = layoutName; layout.layout.content = rootNode.InnerText; layout.installedByCollectionId = collectionId; layout.save(core.cpParent); } } catch (Exception ex) { LogController.logError(core, ex); throw; } }
// // ==================================================================================================== /// <summary> /// /// </summary> /// <param name="cp"></param> /// <returns></returns> public override object Execute(BaseClasses.CPBaseClass cp) { LibraryFilesModel image = DbBaseModel.create <LibraryFilesModel>(cp, constants.guidTemplateHeaderBrandLibraryFile); if (image == null) { image = DbBaseModel.addDefault <LibraryFilesModel>(cp); image.ccguid = constants.guidTemplateHeaderBrandLibraryFile; image.name = "Theme-Brand-Img"; image.filename = GenericController.populateFileField(cp, @"themehelpers\Brand-Default.png", LibraryFilesModel.tableMetadata.tableNameLower, "filename", image.id); image.save(cp); } StringBuilder result = new StringBuilder("<img"); result.Append(" src=\"" + cp.Http.CdnFilePathPrefix + image.filename + "\""); if (!image.width.Equals(0)) { result.Append(" width=\"" + image.width + "\""); } if (!image.height.Equals(0)) { result.Append(" height=\"" + image.height + "\""); } if (!string.IsNullOrEmpty(image.description)) { string encodedMsg = cp.Utils.EncodeHTML(image.description); result.Append(" alt=\"" + encodedMsg + "\" title=\"" + encodedMsg + "\""); } result.Append(">"); // // -- if not editing, return a linked image if (!cp.User.IsEditingAnything) { return("<a href=\"/\">" + result.ToString() + "</a>"); } // // -- editing, no link return(cp.Content.GetEditWrapper(result.ToString(), image.contentControlId, image.id)); }
// //==================================================================================================== /// <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> /// Import a file and process the html. Save the result. /// </summary> /// <param name="cp"></param> /// <param name="htmlSourceTempPathFilename"></param> /// <param name="importTypeId"></param> /// <param name="layoutId">If not 0, the imported html will be saved to the record in this table.</param> /// <param name="pageTemplateId">If not 0, the imported html will be saved to the record in this table.</param> /// <param name="emailTemplateId">If not 0, the imported html will be saved to the record in this table.</param> /// <param name="emailId">If not 0, the imported html will be saved to the record in this table.</param> /// <param name="userMessageList">If there were any processing errors caused by the data, return them here. These can be presented to the user.</param> /// <returns></returns> public static bool processImportFile(CPBaseClass cp, string htmlSourceTempPathFilename, ImporttypeEnum importTypeId, int layoutId, int pageTemplateId, int emailTemplateId, int emailId, ref List <string> userMessageList) { try { if (System.IO.Path.GetExtension(htmlSourceTempPathFilename).Equals(".zip")) { // // -- upload file is a zip and unzip to temp and copy assets to wwwroot cp.TempFiles.UnzipFile(htmlSourceTempPathFilename); cp.TempFiles.DeleteFile(htmlSourceTempPathFilename); // // -- copy non-html files to wwwroot copyNonHtmlFilesToWWW(cp, cp.TempFiles.GetPath(htmlSourceTempPathFilename), ""); } // // -- import all html files in the root folder string tempPath = cp.TempFiles.GetPath(htmlSourceTempPathFilename); bool htmlFileFound = false; foreach (var file in cp.TempFiles.FileList(tempPath)) { if (file.Extension.ToLowerInvariant().Equals(".html")) { // // -- process each html file one at a time userMessageList.Add("Processing file " + cp.CdnFiles.GetFilename(file.Name)); string newRecordName = Path.GetFileNameWithoutExtension(file.Name); htmlFileFound = true; HtmlDocument htmlDoc = new HtmlDocument(); htmlDoc.Load(cp.TempFiles.PhysicalFilePath + tempPath + file.Name, Encoding.UTF8); if (htmlDoc == null) { // // -- body tag not found, import the whole document userMessageList.Add("The file is empty."); return(false); } // // -- get record names for each import type string layoutRecordName = string.Empty; string pageTemplateRecordName = string.Empty; string emailTemplateRecordName = string.Empty; string emailRecordName = string.Empty; // // -- search for meta name=template|layout content=recordaname var metadataList = htmlDoc.DocumentNode.SelectNodes("//meta"); if (metadataList != null) { foreach (var metadataNode in metadataList) { switch (metadataNode.GetAttributeValue("name", String.Empty).ToLowerInvariant()) { case "layout": { layoutRecordName = metadataNode.GetAttributeValue("content", String.Empty); break; } case "template": case "pagetemplate": { pageTemplateRecordName = metadataNode.GetAttributeValue("content", String.Empty); break; } case "emailtemplate": { emailTemplateRecordName = metadataNode.GetAttributeValue("content", String.Empty); break; } case "email": { emailRecordName = metadataNode.GetAttributeValue("content", String.Empty); break; } default: { break; } } } } // // -- process the document html if (!processHtmlDoc(cp, htmlDoc, importTypeId, ref userMessageList)) { return(false); } // // -- save manual layout LayoutModel layout = null; { if (importTypeId.Equals(ImporttypeEnum.LayoutForAddon) && layoutId.Equals(0) & string.IsNullOrWhiteSpace(layoutRecordName)) { // // -- layout type but no layout selected, and no layout imported, use filename layoutRecordName = newRecordName; } if (importTypeId.Equals(ImporttypeEnum.LayoutForAddon) && !layoutId.Equals(0)) { layout = DbBaseModel.create <LayoutModel>(cp, layoutId); if (layout == null) { userMessageList.Add("The layout selected could not be found."); return(false); } layout.layout.content = htmlDoc.DocumentNode.OuterHtml; layout.save(cp); } // // -- save meta layout if ((layout == null) && !string.IsNullOrWhiteSpace(layoutRecordName)) { layout = DbBaseModel.createByUniqueName <LayoutModel>(cp, layoutRecordName); if (layout == null) { layout = DbBaseModel.addDefault <LayoutModel>(cp); layout.name = layoutRecordName; } layout.layout.content = htmlDoc.DocumentNode.OuterHtml; layout.save(cp); userMessageList.Add("Saved Layout '" + layoutRecordName + "'."); } } // // -- save page template PageTemplateModel pageTemplate = null; { if (importTypeId.Equals(ImporttypeEnum.PageTemplate) && pageTemplateId.Equals(0) & string.IsNullOrWhiteSpace(pageTemplateRecordName)) { // // -- layout type but no layout selected, and no layout imported, use filename pageTemplateRecordName = newRecordName; } if (importTypeId.Equals(ImporttypeEnum.PageTemplate) && !pageTemplateId.Equals(0)) { pageTemplate = DbBaseModel.create <PageTemplateModel>(cp, pageTemplateId); if (pageTemplate == null) { userMessageList.Add("The template selected could not be found."); return(false); } pageTemplate.bodyHTML = htmlDoc.DocumentNode.OuterHtml; pageTemplate.save(cp); userMessageList.Add("Saved Page Template '" + pageTemplateRecordName + "'."); } // // -- save meta template if ((pageTemplate == null) && !string.IsNullOrWhiteSpace(pageTemplateRecordName)) { pageTemplate = DbBaseModel.createByUniqueName <PageTemplateModel>(cp, pageTemplateRecordName); if (pageTemplate == null) { pageTemplate = DbBaseModel.addDefault <PageTemplateModel>(cp); pageTemplate.name = pageTemplateRecordName; } // // -- try to resolve the various relative urls possible into the primary url, then to a reoot relative url string urlProtocolDomainSlash = "https://" + cp.Site.DomainPrimary + "/"; string bodyhtml = htmlDoc.DocumentNode.OuterHtml; bodyhtml = genericController.convertLinksToAbsolute(bodyhtml, urlProtocolDomainSlash); bodyhtml = bodyhtml.Replace(urlProtocolDomainSlash, "/"); // pageTemplate.bodyHTML = bodyhtml; pageTemplate.save(cp); userMessageList.Add("Saved Page Template '" + pageTemplateRecordName + "'."); } } // // -- save email template EmailTemplateModel emailTemplate = null; { if (importTypeId.Equals(ImporttypeEnum.EmailTemplate) && emailTemplateId.Equals(0) & string.IsNullOrWhiteSpace(emailTemplateRecordName)) { // // -- type but no layout selected, and no layout imported, use filename emailTemplateRecordName = newRecordName; } if (importTypeId.Equals(ImporttypeEnum.EmailTemplate) && !emailTemplateId.Equals(0)) { emailTemplate = DbBaseModel.create <EmailTemplateModel>(cp, emailTemplateId); if (emailTemplate == null) { userMessageList.Add("The template selected could not be found."); return(false); } emailTemplate.bodyHTML = htmlDoc.DocumentNode.OuterHtml; emailTemplate.save(cp); } // // -- save meta template if ((emailTemplate == null) && !string.IsNullOrWhiteSpace(emailTemplateRecordName)) { emailTemplate = DbBaseModel.createByUniqueName <EmailTemplateModel>(cp, emailTemplateRecordName); if (emailTemplate == null) { emailTemplate = DbBaseModel.addDefault <EmailTemplateModel>(cp); emailTemplate.name = emailTemplateRecordName; } emailTemplate.bodyHTML = htmlDoc.DocumentNode.OuterHtml; emailTemplate.save(cp); userMessageList.Add("Saved Email Template '" + emailTemplateRecordName + "'."); } } // // -- save email EmailModel email = null; { if (importTypeId.Equals(5) && emailId.Equals(0) & string.IsNullOrWhiteSpace(emailRecordName)) { // // -- layout type but no layout selected, and no layout imported, use filename emailRecordName = newRecordName; } if (!emailId.Equals(0)) { email = DbBaseModel.create <EmailModel>(cp, emailId); if (email == null) { userMessageList.Add("The email selected could not be found."); return(false); } email.copyFilename.content = htmlDoc.DocumentNode.OuterHtml; email.save(cp); userMessageList.Add("Saved Email '" + emailRecordName + "'."); } // // -- save meta template if ((email == null) && !string.IsNullOrWhiteSpace(emailRecordName)) { email = DbBaseModel.createByUniqueName <EmailModel>(cp, emailRecordName); if (email == null) { email = DbBaseModel.addDefault <EmailModel>(cp); email.name = emailRecordName; } email.copyFilename.content = htmlDoc.DocumentNode.OuterHtml; email.save(cp); userMessageList.Add("Saved Email '" + emailRecordName + "'."); } } } } if (!htmlFileFound) { userMessageList.Add("No files were found with .HTML extension. Only files with .HTML extensions are imported."); return(false); } return(true); } catch (Exception ex) { cp.Site.ErrorReport(ex); throw; } }
// // ==================================================================================================== public void processButtonSubmit(CPBaseClass cp, ForumModel settings) { try { string button = cp.Doc.GetText("button"); if (!string.IsNullOrWhiteSpace(button)) { var buttonParts = button.Split('-'); switch (buttonParts[0].ToLowerInvariant()) { case "addcomment": { // // -- comment required string commentBody = cp.Doc.GetText("CommentInput"); if (!string.IsNullOrWhiteSpace(commentBody)) { // // -- if not authenticated, add user with name and email if (!cp.User.IsAuthenticated) { string commentEmail = cp.Doc.GetText("CommentUserName"); var testUserList = DbBaseModel.createList <PersonModel>(cp, "(email=" + cp.Db.EncodeSQLText(commentEmail) + ")"); if (testUserList.Count.Equals(0)) { // // -- the mail is not in use, add the guest as a new user cp.User.Logout(); user = DbBaseModel.addDefault <PersonModel>(cp); user.name = cp.Doc.GetText("CommentUserName"); user.email = commentEmail; user.save(cp); cp.User.LoginByID(user.id); } } // // -- save comment var comment = DbBaseModel.addDefault <ForumCommentModel>(cp); comment.comment = cp.Doc.GetText("CommentInput"); comment.commentid = 0; comment.forumid = settings.id; comment.name = "user " + user.id + ", " + user.name + " comment"; comment.createdBy = cp.User.Id; comment.dateAdded = DateTime.Now; comment.modifiedBy = cp.User.Id; comment.modifiedDate = DateTime.Now; comment.save(cp); } break; } case "addreply": { // // -- comment required int commentId = cp.Utils.EncodeInteger(buttonParts[1]); string replyBody = cp.Doc.GetText("replyBody" + commentId.ToString()); if (!string.IsNullOrWhiteSpace(replyBody)) { // // -- if not authenticated, add user with name and email if (!cp.User.IsAuthenticated) { string commentEmail = cp.Doc.GetText("replyUserEmail" + commentId.ToString()); var testUserList = DbBaseModel.createList <PersonModel>(cp, "(email=" + cp.Db.EncodeSQLText(commentEmail) + ")"); if (testUserList.Count.Equals(0)) { // // -- the mail is not in use, add the guest as a new user cp.User.Logout(); user = DbBaseModel.addDefault <PersonModel>(cp); user.name = cp.Doc.GetText("replyUserEmail" + commentId.ToString()); user.email = commentEmail; user.save(cp); cp.User.LoginByID(user.id); } } // // -- save comment var reply = DbBaseModel.addDefault <ForumCommentModel>(cp); reply.comment = replyBody; reply.commentid = commentId; reply.forumid = settings.id; reply.name = "user " + user.id + ", " + user.name + " comment"; reply.createdBy = cp.User.Id; reply.dateAdded = DateTime.Now; reply.modifiedBy = cp.User.Id; reply.modifiedDate = DateTime.Now; reply.save(cp); } break; } default: { break; } } } } catch (Exception ex) { cp.Site.ErrorReport(ex); throw; } }
// //====================================================================================================== // public static void installNode(CoreController core, XmlNode templateNode, int collectionId, ref bool return_UpgradeOK, ref string return_ErrorMessage, ref bool collectionIncludesDiagnosticAddons) { return_ErrorMessage = ""; return_UpgradeOK = true; try { string Basename = toLCase(templateNode.Name); if (Basename == "template") { bool IsFound = false; string templateName = XmlController.getXMLAttribute(core, ref IsFound, templateNode, "name", "No Name"); if (string.IsNullOrEmpty(templateName)) { templateName = "No Name"; } string recordGuid = XmlController.getXMLAttribute(core, ref IsFound, templateNode, "guid", templateName); if (string.IsNullOrEmpty(recordGuid)) { recordGuid = templateName; } var template = DbBaseModel.create <PageTemplateModel>(core.cpParent, recordGuid); if (template == null) { template = DbBaseModel.createByUniqueName <PageTemplateModel>(core.cpParent, templateName); } if (template == null) { template = DbBaseModel.addDefault <PageTemplateModel>(core.cpParent); } foreach (XmlNode childNode in templateNode.ChildNodes) { switch (childNode.Name.ToLowerInvariant()) { case "includeaddon": { string addonGuid = XmlController.getXMLAttribute(core, ref IsFound, childNode, "guid", ""); string addonName = XmlController.getXMLAttribute(core, ref IsFound, childNode, "name", "No Name"); if (!string.IsNullOrEmpty(addonGuid)) { var addon = DbBaseModel.create <AddonModel>(core.cpParent, addonGuid); if (addon == null) { return_ErrorMessage += "Addon dependency [" + addonName + "] for template [" + templateName + "] could not be found by its guid [" + addonGuid + "]"; } var ruleList = DbBaseModel.createList <AddonTemplateRuleModel>(core.cpParent, "(addonId=" + addon.id + ")and(addonId=" + template.id + ")"); if (ruleList.Count.Equals(0)) { var rule = DbBaseModel.addDefault <AddonTemplateRuleModel>(core.cpParent); rule.addonId = addon.id; rule.templateId = template.id; rule.save(core.cpParent); } } break; } case "bodyhtml": { template.bodyHTML = childNode.InnerText; break; } } } template.ccguid = recordGuid; template.name = templateName; //record.bodyHTML = templateNode.InnerText; template.collectionId = collectionId; template.isSecure = XmlController.getXMLAttributeBoolean(core, ref IsFound, templateNode, "issecure", false); template.save(core.cpParent); } } catch (Exception ex) { LogController.logError(core, ex); throw; } }
// //====================================================================================================== // public static void installNode(CoreController core, XmlNode AddonNode, string AddonGuidFieldName, int CollectionID, ref bool return_UpgradeOK, ref string return_ErrorMessage, ref bool collectionIncludesDiagnosticAddons) { // todo - return bool return_ErrorMessage = ""; return_UpgradeOK = true; try { string Basename = GenericController.toLCase(AddonNode.Name); if ((Basename == "page") || (Basename == "process") || (Basename == "addon") || (Basename == "add-on")) { bool IsFound = false; string addonName = XmlController.getXMLAttribute(core, ref IsFound, AddonNode, "name", "No Name"); if (string.IsNullOrEmpty(addonName)) { addonName = "No Name"; } string addonGuid = XmlController.getXMLAttribute(core, ref IsFound, AddonNode, "guid", addonName); if (string.IsNullOrEmpty(addonGuid)) { addonGuid = addonName; } string navTypeName = XmlController.getXMLAttribute(core, ref IsFound, AddonNode, "type", ""); int navTypeId = getListIndex(navTypeName, navTypeIDList); if (navTypeId == 0) { navTypeId = NavTypeIDAddon; } using (var cs = new CsModel(core)) { string Criteria = "(" + AddonGuidFieldName + "=" + DbController.encodeSQLText(addonGuid) + ")"; cs.open(AddonModel.tableMetadata.contentName, Criteria, "", false); if (cs.ok()) { // // Update the Addon // LogController.logInfo(core, MethodInfo.GetCurrentMethod().Name + ", UpgradeAppFromLocalCollection, GUID match with existing Add-on, Updating Add-on [" + addonName + "], Guid [" + addonGuid + "]"); } else { // // not found by GUID - search name against name to update legacy Add-ons // cs.close(); Criteria = "(name=" + DbController.encodeSQLText(addonName) + ")and(" + AddonGuidFieldName + " is null)"; cs.open(AddonModel.tableMetadata.contentName, Criteria, "", false); if (cs.ok()) { LogController.logInfo(core, MethodInfo.GetCurrentMethod().Name + ", UpgradeAppFromLocalCollection, Add-on name matched an existing Add-on that has no GUID, Updating legacy Aggregate Function to Add-on [" + addonName + "], Guid [" + addonGuid + "]"); } } if (!cs.ok()) { // // not found by GUID or by name, Insert a new addon // cs.close(); cs.insert(AddonModel.tableMetadata.contentName); if (cs.ok()) { LogController.logInfo(core, MethodInfo.GetCurrentMethod().Name + ", UpgradeAppFromLocalCollection, Creating new Add-on [" + addonName + "], Guid [" + addonGuid + "]"); } } if (!cs.ok()) { // // Could not create new Add-on // LogController.logInfo(core, MethodInfo.GetCurrentMethod().Name + ", UpgradeAppFromLocalCollection, Add-on could not be created, skipping Add-on [" + addonName + "], Guid [" + addonGuid + "]"); } else { int addonId = cs.getInteger("ID"); MetadataController.deleteContentRecords(core, "Add-on Include Rules", "addonid=" + addonId); MetadataController.deleteContentRecords(core, "Add-on Content Trigger Rules", "addonid=" + addonId); // cs.set("collectionid", CollectionID); cs.set(AddonGuidFieldName, addonGuid); cs.set("name", addonName); cs.set("navTypeId", navTypeId); var ArgumentList = new StringBuilder(); var StyleSheet = new StringBuilder(); if (AddonNode.ChildNodes.Count > 0) { foreach (XmlNode Addonfield in AddonNode.ChildNodes) { if (!(Addonfield is XmlComment)) { XmlNode PageInterface = Addonfield; string fieldName = null; string FieldValue = ""; switch (GenericController.toLCase(Addonfield.Name)) { case "activexdll": { // // This is handled in BuildLocalCollectionFolder // break; } case "editors": { // // list of editors // foreach (XmlNode TriggerNode in Addonfield.ChildNodes) { // int fieldTypeId = 0; string fieldType = null; switch (GenericController.toLCase(TriggerNode.Name)) { case "type": { fieldType = TriggerNode.InnerText; fieldTypeId = MetadataController.getRecordIdByUniqueName(core, "Content Field Types", fieldType); if (fieldTypeId > 0) { using (var CS2 = new CsModel(core)) { Criteria = "(addonid=" + addonId + ")and(contentfieldTypeID=" + fieldTypeId + ")"; CS2.open("Add-on Content Field Type Rules", Criteria); if (!CS2.ok()) { CS2.insert("Add-on Content Field Type Rules"); } if (CS2.ok()) { CS2.set("addonid", addonId); CS2.set("contentfieldTypeID", fieldTypeId); } } } break; } default: { // do nothing break; } } } break; } case "processtriggers": { // // list of events that trigger a process run for this addon // foreach (XmlNode TriggerNode in Addonfield.ChildNodes) { switch (GenericController.toLCase(TriggerNode.Name)) { case "contentchange": { int TriggerContentId = 0; string ContentNameorGuid = TriggerNode.InnerText; if (string.IsNullOrEmpty(ContentNameorGuid)) { ContentNameorGuid = XmlController.getXMLAttribute(core, ref IsFound, TriggerNode, "guid", ""); if (string.IsNullOrEmpty(ContentNameorGuid)) { ContentNameorGuid = XmlController.getXMLAttribute(core, ref IsFound, TriggerNode, "name", ""); } } using (var CS2 = new CsModel(core)) { Criteria = "(ccguid=" + DbController.encodeSQLText(ContentNameorGuid) + ")"; CS2.open("Content", Criteria); if (!CS2.ok()) { Criteria = "(ccguid is null)and(name=" + DbController.encodeSQLText(ContentNameorGuid) + ")"; CS2.open("content", Criteria); } if (CS2.ok()) { TriggerContentId = CS2.getInteger("ID"); } } if (TriggerContentId != 0) { using (var CS2 = new CsModel(core)) { Criteria = "(addonid=" + addonId + ")and(contentid=" + TriggerContentId + ")"; CS2.open("Add-on Content Trigger Rules", Criteria); if (!CS2.ok()) { CS2.insert("Add-on Content Trigger Rules"); if (CS2.ok()) { CS2.set("addonid", addonId); CS2.set("contentid", TriggerContentId); } } CS2.close(); } } break; } default: { // do nothing break; } } } break; } case "scripting": { // // include add-ons - NOTE - import collections must be run before interfaces // when importing a collectin that will be used for an include int scriptinglanguageid = (int)AddonController.ScriptLanguages.VBScript; string ScriptingLanguage = XmlController.getXMLAttribute(core, ref IsFound, Addonfield, "language", "").ToLowerInvariant(); if (ScriptingLanguage.Equals("javascript") || ScriptingLanguage.Equals("jscript")) { scriptinglanguageid = (int)AddonController.ScriptLanguages.Javascript; } cs.set("scriptinglanguageid", scriptinglanguageid); string ScriptingEntryPoint = XmlController.getXMLAttribute(core, ref IsFound, Addonfield, "entrypoint", ""); cs.set("ScriptingEntryPoint", ScriptingEntryPoint); int ScriptingTimeout = GenericController.encodeInteger(XmlController.getXMLAttribute(core, ref IsFound, Addonfield, "timeout", "5000")); cs.set("ScriptingTimeout", ScriptingTimeout); string ScriptingCode = ""; foreach (XmlNode ScriptingNode in Addonfield.ChildNodes) { switch (GenericController.toLCase(ScriptingNode.Name)) { case "code": { ScriptingCode += ScriptingNode.InnerText; break; } default: { // do nothing break; } } } cs.set("ScriptingCode", ScriptingCode); break; } case "activexprogramid": { // // save program id // FieldValue = Addonfield.InnerText; cs.set("ObjectProgramID", FieldValue); break; } case "navigator": { // // create a navigator entry with a parent set to this // cs.save(); string menuNameSpace = XmlController.getXMLAttribute(core, ref IsFound, Addonfield, "NameSpace", ""); if (!string.IsNullOrEmpty(menuNameSpace)) { string NavIconTypeString = XmlController.getXMLAttribute(core, ref IsFound, Addonfield, "type", ""); if (string.IsNullOrEmpty(NavIconTypeString)) { NavIconTypeString = "Addon"; } BuildController.verifyNavigatorEntry(core, new MetadataMiniCollectionModel.MiniCollectionMenuModel { menuNameSpace = menuNameSpace, name = addonName, adminOnly = false, developerOnly = false, newWindow = false, active = true, addonName = addonName, navIconType = NavIconTypeString, navIconTitle = addonName }, CollectionID); } break; } case "argument": case "argumentlist": { // // multiple argumentlist elements are concatinated with crlf ArgumentList.Append(Addonfield.InnerText.Trim(' ') + Environment.NewLine); break; } case "style": { // // import exclusive style // string NodeName = XmlController.getXMLAttribute(core, ref IsFound, Addonfield, "name", ""); string NewValue = encodeText(Addonfield.InnerText).Trim(' '); if (NewValue.left(1) != "{") { NewValue = "{" + NewValue; } if (NewValue.Substring(NewValue.Length - 1) != "}") { NewValue += "}"; } StyleSheet.Append(NodeName + " " + NewValue + Environment.NewLine); break; } case "stylesheet": case "styles": { // // import exclusive stylesheet if more then whitespace // string test = Addonfield.InnerText; test = strReplace(test, " ", ""); test = strReplace(test, "\r", ""); test = strReplace(test, "\n", ""); test = strReplace(test, "\t", ""); if (!string.IsNullOrEmpty(test)) { StyleSheet.Append(Addonfield.InnerText + Environment.NewLine); } break; } case "template": case "content": case "admin": { // // these add-ons will be "non-developer only" in navigation // fieldName = Addonfield.Name; FieldValue = Addonfield.InnerText; if (!cs.isFieldSupported(fieldName)) { // // Bad field name - need to report it somehow // } else { cs.set(fieldName, FieldValue); if (GenericController.encodeBoolean(Addonfield.InnerText)) { // // if template, admin or content - let non-developers have navigator entry // } } break; } case "icon": { // // icon // FieldValue = XmlController.getXMLAttribute(core, ref IsFound, Addonfield, "link", ""); if (!string.IsNullOrEmpty(FieldValue)) { // // Icons can be either in the root of the website or in content files // FieldValue = GenericController.strReplace(FieldValue, "\\", "/"); // make it a link, not a file if (GenericController.strInstr(1, FieldValue, "://") != 0) { // // the link is an absolute URL, leave it link this // } else { if (FieldValue.left(1) != "/") { // // make sure it starts with a slash to be consistance // FieldValue = "/" + FieldValue; } if (FieldValue.left(17) == "/contensivefiles/") { // // in content files, start link without the slash // FieldValue = FieldValue.Substring(17); } } cs.set("IconFilename", FieldValue); { cs.set("IconWidth", GenericController.encodeInteger(XmlController.getXMLAttribute(core, ref IsFound, Addonfield, "width", "0"))); cs.set("IconHeight", GenericController.encodeInteger(XmlController.getXMLAttribute(core, ref IsFound, Addonfield, "height", "0"))); cs.set("IconSprites", GenericController.encodeInteger(XmlController.getXMLAttribute(core, ref IsFound, Addonfield, "sprites", "0"))); } } break; } case "includeaddon": case "includeadd-on": case "include addon": case "include add-on": { // // processed in phase2 of this routine, after all the add-ons are installed // break; } case "form": { // // The value of this node is the xml instructions to create a form. Take then // entire node, children and all, and save them in the formxml field. // this replaces the settings add-on type, and soo to be report add-on types as well. // this removes the ccsettingpages and settingcollectionrules, etc. // { cs.set("formxml", Addonfield.InnerXml); } break; } case "javascript": case "javascriptinhead": { // // these all translate to JSFilename // fieldName = "jsfilename"; cs.set(fieldName, Addonfield.InnerText); break; } case "iniframe": { // // typo - field is inframe // fieldName = "inframe"; cs.set(fieldName, Addonfield.InnerText); break; } case "diagnostic": { bool fieldValue = encodeBoolean(Addonfield.InnerText); cs.set("diagnostic", fieldValue); collectionIncludesDiagnosticAddons = collectionIncludesDiagnosticAddons || fieldValue; break; } case "category": { if (!string.IsNullOrWhiteSpace(Addonfield.InnerText)) { AddonCategoryModel category = DbBaseModel.createByUniqueName <AddonCategoryModel>(core.cpParent, Addonfield.InnerText); if (category == null) { category = DbBaseModel.addDefault <AddonCategoryModel>(core.cpParent); category.name = Addonfield.InnerText; category.save(core.cpParent); } cs.set("addonCategoryId", category.id); } break; } case "instancesettingprimarycontentid": { int lookupContentId = 0; if (!string.IsNullOrWhiteSpace(Addonfield.InnerText)) { ContentModel lookupContent = DbBaseModel.createByUniqueName <ContentModel>(core.cpParent, Addonfield.InnerText); if (lookupContent != null) { lookupContentId = lookupContent.id; } } cs.set("instancesettingprimarycontentid", lookupContentId); break; } default: { // // All the other fields should match the Db fields // fieldName = Addonfield.Name; FieldValue = Addonfield.InnerText; if (!cs.isFieldSupported(fieldName)) { // // Bad field name - need to report it somehow // LogController.logError(core, new ApplicationException("bad field found [" + fieldName + "], in addon node [" + addonName + "], of collection [" + MetadataController.getRecordName(core, "add-on collections", CollectionID) + "]")); } else { cs.set(fieldName, FieldValue); } break; } } } } } cs.set("ArgumentList", ArgumentList.ToString()); cs.set("StylesFilename", StyleSheet.ToString()); } cs.close(); } } } catch (Exception ex) { LogController.logError(core, ex); throw; } }
// //==================================================================================================== /// <summary> /// pageManager addon interface. decode: "sortlist=childPageList_{parentId}_{listName},page{idOfChild},page{idOfChild},etc" /// </summary> /// <param name="cp"></param> /// <returns></returns> public override object Execute(Contensive.BaseClasses.CPBaseClass cp) { string returnHtml = ""; try { CoreController core = ((CPClass)cp).core; string pageCommaList = cp.Doc.GetText("sortlist"); List <string> pageList = new List <string>(pageCommaList.Split(',')); if (pageList.Count > 1) { string[] ParentPageValues = pageList[0].Split('_'); if (ParentPageValues.Count() < 3) { // // -- parent page is not valid cp.Site.ErrorReport(new ArgumentException("pageResort requires first value to identify the parent page")); } else { int parentPageId = encodeInteger(ParentPageValues[1]); if (parentPageId == 0) { // // -- parent page is not valid cp.Site.ErrorReport(new ArgumentException("pageResort requires a parent page id")); } else { // // -- create childPageIdList List <int> childPageIdList = new List <int>(); foreach (string PageIDText in pageList) { int pageId = encodeInteger(PageIDText.Replace("page", "")); if (pageId > 0) { childPageIdList.Add(pageId); } } // PageContentModel parentPage = DbBaseModel.create <PageContentModel>(core.cpParent, parentPageId); if (parentPage == null) { // // -- parent page is not valid cp.Site.ErrorReport(new ArgumentException("pageResort requires a parent page id")); } else { // // -- verify page set to required sort method Id SortMethodModel sortMethod = DbBaseModel.createByUniqueName <SortMethodModel>(core.cpParent, "By Alpha Sort Order Field"); if (sortMethod == null) { sortMethod = DbBaseModel.createByUniqueName <SortMethodModel>(core.cpParent, "Alpha Sort Order Field"); } if (sortMethod == null) { // // -- create the required sortMethod sortMethod = DbBaseModel.addDefault <SortMethodModel>(core.cpParent, Processor.Models.Domain.ContentMetadataModel.getDefaultValueDict(core, SortMethodModel.tableMetadata.contentName)); sortMethod.name = "By Alpha Sort Order Field"; sortMethod.orderByClause = "sortOrder"; sortMethod.save(core.cpParent); } if (parentPage.childListSortMethodId != sortMethod.id) { // // -- update page if not set correctly parentPage.childListSortMethodId = sortMethod.id; parentPage.save(core.cpParent); } int pagePtr = 0; foreach (var childPageId in childPageIdList) { if (childPageId == 0) { // // -- invalid child page cp.Site.ErrorReport(new GenericException("child page id is invalid from remote request [" + pageCommaList + "]")); } else { string SortOrder = (100000 + (pagePtr * 10)).ToString(); PageContentModel childPage = DbBaseModel.create <PageContentModel>(core.cpParent, childPageId); if (childPage.sortOrder != SortOrder) { childPage.sortOrder = SortOrder; childPage.save(core.cpParent); } } pagePtr += 1; } } } } } } catch (Exception ex) { cp.Site.ErrorReport(ex); } return(returnHtml); }