public function Tree() { $this->Permission('Candy.Settings.View'); $TreeModel = new SectionModel(); $this->AddJsFile('tree.js'); $this->Tree = $TreeModel->GetNodes(array('IncludeRoot' => True))->Result(); // array('Depth <=' => 1) $this->View = 'Tree'; $this->Title(T('Sections')); $this->Render(); }
public function Edit($Reference = '') { //$this->AddJsFile('jquery.autocomplete.pack.js'); $this->AddJsFile('jquery.textpandable.js'); $this->AddJsFile('editform.js'); $this->Form->SetModel($this->PageModel); $Session = Gdn::Session(); $SectionModel = new SectionModel(); $this->Tree = $SectionModel->DropDownArray('Name', $SectionModel->GetNodes(array('Depth >' => 0))); $this->FormatOptions = LocalizedOptions(array('Text', 'xHtml', 'Html', 'Markdown', 'Raw')); if (!$Session->CheckPermission('Candy.Pages.Raw')) { unset($this->FormatOptions['Raw']); } $this->EventArguments['FormatOptions'] =& $this->FormatOptions; $this->FireEvent('FormatOptions'); $Content = False; if ($Reference != '') { $Content = $this->PageModel->GetID($Reference); if (!IsContentOwner($Content, 'Candy.Pages.Edit')) { $Content = False; } if ($Content) { $this->Form->AddHidden('PageID', $Content->PageID); $this->Form->SetData($Content); $this->Editing = True; } } if (!$Content) { $this->Permission('Candy.Pages.Add'); } if ($this->Form->AuthenticatedPostBack()) { if ($this->Form->ButtonExists('Delete')) { $this->PageModel->Delete($Content->PageID); $this->InformMessage(T('Page deleted'), array('Sprite' => 'SkullBones', 'CssClass' => 'Dismissable AutoDismiss')); } else { $SavedID = $this->Form->Save($Content); if ($SavedID) { $Message = LocalizedMessage('Saved. You can check it here: %s', Anchor($this->Form->GetFormValue('Title'), 'content/page/' . $SavedID)); $this->InformMessage($Message, array('Sprite' => 'Check', 'CssClass' => 'Dismissable')); } } } else { $URI = trim(GetIncomingValue('URI'), '/'); if ($URI) { $this->Form->SetValue('URI', $URI); } } $this->SetData('Content', $Content, True); $this->Title(ConcatSep(' - ', T('Page'), GetValue('Title', $Content))); $this->Render(); }
/** * 文章编辑页面 */ function edit() { $art_id = $_GET['id']; if (!empty($art_id)) { //获得文章 $art = new ArticleModel(); $list = $art->getById($art_id); $this->assign('alist', $list); //获得单元 $sec = new SectionModel(); $list = $sec->order('id')->select(); $this->assign('slist', $list); //获得分类 $cat = new CategoryModel(); $list = $cat->select(); $this->assign('clist', $list); } $this->display(); }
/** * Saves a section */ public function actionSaveSection() { $this->requirePostRequest(); $section = new SectionModel(); // Set the simple stuff $section->id = craft()->request->getPost('sectionId'); $section->name = craft()->request->getPost('name'); $section->handle = craft()->request->getPost('handle'); $section->titleLabel = craft()->request->getPost('titleLabel'); $section->hasUrls = (bool) craft()->request->getPost('hasUrls'); $section->template = craft()->request->getPost('template'); // Set the locales and URL formats $locales = array(); $urlFormats = craft()->request->getPost('urlFormat'); if (Craft::hasPackage(CraftPackage::Localize)) { $localeIds = craft()->request->getPost('locales'); } else { $primaryLocaleId = craft()->i18n->getPrimarySiteLocaleId(); $localeIds = array($primaryLocaleId); } foreach ($localeIds as $localeId) { $locales[$localeId] = SectionLocaleModel::populateModel(array('locale' => $localeId, 'urlFormat' => isset($urlFormats[$localeId]) ? $urlFormats[$localeId] : null)); } $section->setLocales($locales); // Set the field layout $fieldLayout = craft()->fields->assembleLayoutFromPost(); $fieldLayout->type = ElementType::Entry; $section->setFieldLayout($fieldLayout); // Save it if (craft()->sections->saveSection($section)) { craft()->userSession->setNotice(Craft::t('Section saved.')); // TODO: Remove for 2.0 if (isset($_POST['redirect']) && strpos($_POST['redirect'], '{sectionId}') !== false) { Craft::log('The {sectionId} token within the ‘redirect’ param on sections/saveSection requests has been deprecated. Use {id} instead.', LogLevel::Warning); $_POST['redirect'] = str_replace('{sectionId}', '{id}', $_POST['redirect']); } $this->redirectToPostedUrl($section); } else { craft()->userSession->setError(Craft::t('Couldn’t save section.')); } // Send the section back to the template craft()->urlManager->setRouteVariables(array('section' => $section)); }
/** * Prepare reserved ElementModel values. * * @param array &$fields * @param BaseElementModel $element * * @return BaseElementModel */ public function prepForElementModel(array &$fields, BaseElementModel $element) { // Set author $author = Import_ElementModel::HandleAuthor; if (isset($fields[$author])) { $user = craft()->users->getUserByUsernameOrEmail($fields[$author]); $element->{$author} = is_numeric($fields[$author]) ? $fields[$author] : ($user ? $user->id : 1); unset($fields[$author]); } else { $user = craft()->userSession->getUser(); $element->{$author} = $element->{$author} ? $element->{$author} : ($user ? $user->id : 1); } // Set slug $slug = Import_ElementModel::HandleSlug; if (isset($fields[$slug])) { $element->{$slug} = ElementHelper::createSlug($fields[$slug]); unset($fields[$slug]); } // Set postdate $postDate = Import_ElementModel::HandlePostDate; if (isset($fields[$postDate])) { $element->{$postDate} = DateTime::createFromString($fields[$postDate], craft()->timezone); unset($fields[$postDate]); } // Set expiry date $expiryDate = Import_ElementModel::HandleExpiryDate; if (isset($fields[$expiryDate])) { $element->{$expiryDate} = DateTime::createFromString($fields[$expiryDate], craft()->timezone); unset($fields[$expiryDate]); } // Set enabled $enabled = Import_ElementModel::HandleEnabled; if (isset($fields[$enabled])) { $element->{$enabled} = (bool) $fields[$enabled]; unset($fields[$enabled]); } // Set title $title = Import_ElementModel::HandleTitle; if (isset($fields[$title])) { $element->getContent()->{$title} = $fields[$title]; unset($fields[$title]); } // Set parent or ancestors $parent = Import_ElementModel::HandleParent; $ancestors = Import_ElementModel::HandleAncestors; if (isset($fields[$parent])) { // Get data $data = $fields[$parent]; // Fresh up $data $data = str_replace("\n", '', $data); $data = str_replace("\r", '', $data); $data = trim($data); // Don't connect empty fields if (!empty($data)) { // Find matching element $criteria = craft()->elements->getCriteria(ElementType::Entry); $criteria->sectionId = $element->sectionId; // Exact match $criteria->search = '"' . $data . '"'; // Return the first found element for connecting if ($criteria->total()) { $element->{$parent} = $criteria->first()->id; } } unset($fields[$parent]); } elseif (isset($fields[$ancestors])) { // Get data $data = $fields[$ancestors]; // Fresh up $data $data = str_replace("\n", '', $data); $data = str_replace("\r", '', $data); $data = trim($data); // Don't connect empty fields if (!empty($data)) { // Get section data $section = new SectionModel(); $section->id = $element->sectionId; // This we append before the slugified path $sectionUrl = str_replace('{slug}', '', $section->getUrlFormat()); // Find matching element by URI (dirty, not all structures have URI's) $criteria = craft()->elements->getCriteria(ElementType::Entry); $criteria->sectionId = $element->sectionId; $criteria->uri = $sectionUrl . craft()->import->slugify($data); $criteria->limit = 1; // Return the first found element for connecting if ($criteria->total()) { $element->{$parent} = $criteria->first()->id; } } unset($fields[$ancestors]); } // Return element return $element; }
/** * Creates initial database content for the install. * * @access private * @param $inputs * @return null */ private function _createDefaultContent($inputs) { // Default tag set Craft::log('Creating the Default tag set.'); $tagSet = new TagSetModel(); $tagSet->name = Craft::t('Default'); $tagSet->handle = 'default'; // Save it if (craft()->tags->saveTagSet($tagSet)) { Craft::log('Default tag set created successfully.'); } else { Craft::log('Could not save the Default tag set.', LogLevel::Warning); } // Default field group Craft::log('Creating the Default field group.'); $group = new FieldGroupModel(); $group->name = Craft::t('Default'); if (craft()->fields->saveGroup($group)) { Craft::log('Default field group created successfully.'); } else { Craft::log('Could not save the Default field group.', LogLevel::Warning); } // Heading field Craft::log('Creating the Heading field.'); $headingField = new FieldModel(); $headingField->groupId = $group->id; $headingField->name = Craft::t('Heading'); $headingField->handle = 'heading'; $headingField->translatable = true; $headingField->type = 'PlainText'; if (craft()->fields->saveField($headingField)) { Craft::log('Heading field created successfully.'); } else { Craft::log('Could not save the Heading field.', LogLevel::Warning); } // Body field Craft::log('Creating the Body field.'); $bodyField = new FieldModel(); $bodyField->groupId = $group->id; $bodyField->name = Craft::t('Body'); $bodyField->handle = 'body'; $bodyField->translatable = true; $bodyField->type = 'RichText'; $bodyField->settings = array('configFile' => 'Standard.json'); if (craft()->fields->saveField($bodyField)) { Craft::log('Body field created successfully.'); } else { Craft::log('Could not save the Body field.', LogLevel::Warning); } // Tags field Craft::log('Creating the Tags field.'); $tagsField = new FieldModel(); $tagsField->groupId = $group->id; $tagsField->name = Craft::t('Tags'); $tagsField->handle = 'tags'; $tagsField->type = 'Tags'; $tagsField->settings = array('source' => 'tagset:' . $tagSet->id); if (craft()->fields->saveField($tagsField)) { Craft::log('Tags field created successfully.'); } else { Craft::log('Could not save the Tags field.', LogLevel::Warning); } // Homepage global set Craft::log('Creating the Homepage global set.'); $homepageLayoutFields = array(array('fieldId' => $headingField->id, 'sortOrder' => 1), array('fieldId' => $bodyField->id, 'sortOrder' => 2)); $homepageLayout = new FieldLayoutModel(); $homepageLayout->type = ElementType::GlobalSet; $homepageLayout->setFields($homepageLayoutFields); $homepageGlobalSet = new GlobalSetModel(); $homepageGlobalSet->name = Craft::t('Homepage'); $homepageGlobalSet->handle = 'homepage'; $homepageGlobalSet->setFieldLayout($homepageLayout); if (craft()->globals->saveSet($homepageGlobalSet)) { Craft::log('Homepage global set created successfully.'); } else { Craft::log('Could not save the Homepage global set.', LogLevel::Warning); } // Homepage content $vars = array('siteName' => ucfirst(craft()->request->getServerName())); Craft::log('Setting the Homepage content.'); $homepageGlobalSet->locale = $inputs['locale']; $homepageGlobalSet->getContent()->setAttributes(array('heading' => Craft::t('Welcome to {siteName}!', $vars), 'body' => '<p>' . Craft::t('It’s true, this site doesn’t have a whole lot of content yet, but don’t worry. Our web developers have just installed the CMS, and they’re setting things up for the content editors this very moment. Soon {siteName} will be an oasis of fresh perspectives, sharp analyses, and astute opinions that will keep you coming back again and again.', $vars) . '</p>')); if (craft()->globals->saveContent($homepageGlobalSet)) { Craft::log('Homepage content set successfully.'); } else { Craft::log('Could not set the Homepage content.', LogLevel::Warning); } // News section Craft::log('Creating the News section.'); $newsLayoutFields = array(array('fieldId' => $bodyField->id, 'required' => true, 'sortOrder' => 1), array('fieldId' => $tagsField->id, 'sortOrder' => 2)); $newsLayoutTabs = array(array('name' => Craft::t('Content'), 'sortOrder' => 1, 'fields' => $newsLayoutFields)); $newsLayout = new FieldLayoutModel(); $newsLayout->type = ElementType::Entry; $newsLayout->setTabs($newsLayoutTabs); $newsLayout->setFields($newsLayoutFields); $newsSection = new SectionModel(); $newsSection->name = Craft::t('News'); $newsSection->handle = 'news'; $newsSection->hasUrls = true; $newsSection->template = 'news/_entry'; $newsSection->setLocales(array($inputs['locale'] => SectionLocaleModel::populateModel(array('locale' => $inputs['locale'], 'urlFormat' => 'news/{postDate.year}/{slug}')))); $newsSection->setFieldLayout($newsLayout); if (craft()->sections->saveSection($newsSection)) { Craft::log('News section created successfully.'); } else { Craft::log('Could not save the News section.', LogLevel::Warning); } // News entry Craft::log('Creating a News entry.'); $newsEntry = new EntryModel(); $newsEntry->sectionId = $newsSection->id; $newsEntry->locale = $inputs['locale']; $newsEntry->authorId = $this->_user->id; $newsEntry->enabled = true; $newsEntry->getContent()->title = Craft::t('We just installed Craft!'); $newsEntry->getContent()->setAttributes(array('body' => '<p>' . Craft::t('Craft is the CMS that’s powering {siteName}. It’s beautiful, powerful, flexible, and easy-to-use, and it’s made by Pixel & Tonic. We can’t wait to dive in and see what it’s capable of!', $vars) . '</p><!--pagebreak--><p>' . Craft::t('This is even more captivating content, which you couldn’t see on the News index page because it was entered after a Page Break, and the News index template only likes to show the content on the first page.') . '</p><p>' . Craft::t('Craft: a nice alternative to Word, if you’re making a website.') . '</p>')); if (craft()->entries->saveEntry($newsEntry)) { Craft::log('News entry created successfully.'); } else { Craft::log('Could not save the News entry.', LogLevel::Warning); } }
<?php /** * @author asmalindi * @copyright 2011 */ require "SectionModel.php"; $sectionM = new SectionModel(); $section = new section(); if (isset($_GET['secno'])) { $secNow = $_GET['secno']; } else { $secNow = 1; } //foreach ( $row as $sectiontemp ) { //echo $director . "<br />"; //index.php?secno=3 ?> <!-- START NAVIGATION TOP --> <div id="navTop"> <ul> <?php $row = $sectionM->getSections($secNow); // while($row) //{ //print_r($row); //echo "<li><a href='index.php'> HOME</a></li>"; //if ($secNow == $row['sec_id']) { // echo "<li id='current' ><a href='index.php?secno=".$row['sec_id']."'>".$row['sec_title']."</a></li>"; // } else {
/** * 单元删除页面 */ function del() { //因为删除一个单元,就要删除其手下的分类类别,而删除分类类别后就要删除该类别下面的文章 //所有必须使用关联操作来执行 //序列化主键Id为:1,2,3,...以便批量删除 $del_id = $_POST['del_id']; $section_id = implode($del_id, ','); //实例化 $section = new SectionModel(); $category = new CategoryModel(); $article = new ArticleModel(); $menu_items = new MenuItemModel(); //如果单元删除成功 if ($section->delete($section_id)) { //删除下属分类以及分类下属文章 $where = array('sectionid' => array('in', $section_id)); //删除分类 $category->where($where)->delete(); //删除文章 $article->where($where)->delete(); //删除单元后删除菜单项中的单元 $menu_where = array('type_id' => array('in', $section_id), 'type' => 'Section'); $menu_items->where($menu_where)->delete(); $this->assign('jumpUrl', __URL__ . '/index'); $this->success('单元,菜单项以及所有相关文章类别已删除~~~~'); } else { $this->assign('jumpUrl', __URL__ . '/index'); $this->error('删除失败~~~~' . $category->getError()); } }
/** * Creates initial database content for the install. * * @param $inputs * * @return null */ private function _createDefaultContent($inputs) { // Default tag group Craft::log('Creating the Default tag group.'); $tagGroup = new TagGroupModel(); $tagGroup->name = 'Default'; $tagGroup->handle = 'default'; // Save it if (craft()->tags->saveTagGroup($tagGroup)) { Craft::log('Default tag group created successfully.'); } else { Craft::log('Could not save the Default tag group.', LogLevel::Warning); } // Default field group Craft::log('Creating the Default field group.'); $group = new FieldGroupModel(); $group->name = 'Default'; if (craft()->fields->saveGroup($group)) { Craft::log('Default field group created successfully.'); } else { Craft::log('Could not save the Default field group.', LogLevel::Warning); } // Body field Craft::log('Creating the Body field.'); $bodyField = new FieldModel(); $bodyField->groupId = $group->id; $bodyField->name = 'Body'; $bodyField->handle = 'body'; $bodyField->translatable = true; $bodyField->type = 'RichText'; $bodyField->settings = array('configFile' => 'Standard.json', 'columnType' => ColumnType::Text); if (craft()->fields->saveField($bodyField)) { Craft::log('Body field created successfully.'); } else { Craft::log('Could not save the Body field.', LogLevel::Warning); } // Tags field Craft::log('Creating the Tags field.'); $tagsField = new FieldModel(); $tagsField->groupId = $group->id; $tagsField->name = 'Tags'; $tagsField->handle = 'tags'; $tagsField->type = 'Tags'; $tagsField->settings = array('source' => 'taggroup:' . $tagGroup->id); if (craft()->fields->saveField($tagsField)) { Craft::log('Tags field created successfully.'); } else { Craft::log('Could not save the Tags field.', LogLevel::Warning); } // Homepage single section Craft::log('Creating the Homepage single section.'); $homepageLayout = craft()->fields->assembleLayout(array('Content' => array($bodyField->id)), array($bodyField->id)); $homepageLayout->type = ElementType::Entry; $homepageSingleSection = new SectionModel(); $homepageSingleSection->name = 'Homepage'; $homepageSingleSection->handle = 'homepage'; $homepageSingleSection->type = SectionType::Single; $homepageSingleSection->hasUrls = false; $homepageSingleSection->template = 'index'; $primaryLocaleId = craft()->i18n->getPrimarySiteLocaleId(); $locales[$primaryLocaleId] = new SectionLocaleModel(array('locale' => $primaryLocaleId, 'urlFormat' => '__home__')); $homepageSingleSection->setLocales($locales); // Save it if (craft()->sections->saveSection($homepageSingleSection)) { Craft::log('Homepage single section created successfully.'); } else { Craft::log('Could not save the Homepage single section.', LogLevel::Warning); } $homepageEntryTypes = $homepageSingleSection->getEntryTypes(); $homepageEntryType = $homepageEntryTypes[0]; $homepageEntryType->hasTitleField = true; $homepageEntryType->titleLabel = 'Title'; $homepageEntryType->setFieldLayout($homepageLayout); if (craft()->sections->saveEntryType($homepageEntryType)) { Craft::log('Homepage single section entry type saved successfully.'); } else { Craft::log('Could not save the Homepage single section entry type.', LogLevel::Warning); } // Homepage content $siteName = ucfirst(craft()->request->getServerName()); Craft::log('Setting the Homepage content.'); $criteria = craft()->elements->getCriteria(ElementType::Entry); $criteria->sectionId = $homepageSingleSection->id; $entryModel = $criteria->first(); $entryModel->locale = $inputs['locale']; $entryModel->getContent()->title = 'Welcome to ' . $siteName . '!'; $entryModel->setContentFromPost(array('body' => '<p>It’s true, this site doesn’t have a whole lot of content yet, but don’t worry. Our web developers have just installed the CMS, and they’re setting things up for the content editors this very moment. Soon ' . $siteName . ' will be an oasis of fresh perspectives, sharp analyses, and astute opinions that will keep you coming back again and again.</p>')); // Save the content if (craft()->entries->saveEntry($entryModel)) { Craft::log('Homepage an entry to the Homepage single section.'); } else { Craft::log('Could not save an entry to the Homepage single section.', LogLevel::Warning); } // News section Craft::log('Creating the News section.'); $newsSection = new SectionModel(); $newsSection->type = SectionType::Channel; $newsSection->name = 'News'; $newsSection->handle = 'news'; $newsSection->hasUrls = true; $newsSection->template = 'news/_entry'; $newsSection->setLocales(array($inputs['locale'] => SectionLocaleModel::populateModel(array('locale' => $inputs['locale'], 'urlFormat' => 'news/{postDate.year}/{slug}')))); if (craft()->sections->saveSection($newsSection)) { Craft::log('News section created successfully.'); } else { Craft::log('Could not save the News section.', LogLevel::Warning); } Craft::log('Saving the News entry type.'); $newsLayout = craft()->fields->assembleLayout(array('Content' => array($bodyField->id, $tagsField->id)), array($bodyField->id)); $newsLayout->type = ElementType::Entry; $newsEntryTypes = $newsSection->getEntryTypes(); $newsEntryType = $newsEntryTypes[0]; $newsEntryType->setFieldLayout($newsLayout); if (craft()->sections->saveEntryType($newsEntryType)) { Craft::log('News entry type saved successfully.'); } else { Craft::log('Could not save the News entry type.', LogLevel::Warning); } // News entry Craft::log('Creating a News entry.'); $newsEntry = new EntryModel(); $newsEntry->sectionId = $newsSection->id; $newsEntry->typeId = $newsEntryType->id; $newsEntry->locale = $inputs['locale']; $newsEntry->authorId = $this->_user->id; $newsEntry->enabled = true; $newsEntry->getContent()->title = 'We just installed Craft!'; $newsEntry->getContent()->setAttributes(array('body' => '<p>' . 'Craft is the CMS that’s powering ' . $siteName . '. It’s beautiful, powerful, flexible, and easy-to-use, and it’s made by Pixel & Tonic. We can’t wait to dive in and see what it’s capable of!' . '</p><!--pagebreak--><p>' . 'This is even more captivating content, which you couldn’t see on the News index page because it was entered after a Page Break, and the News index template only likes to show the content on the first page.' . '</p><p>' . 'Craft: a nice alternative to Word, if you’re making a website.' . '</p>')); if (craft()->entries->saveEntry($newsEntry)) { Craft::log('News entry created successfully.'); } else { Craft::log('Could not save the News entry.', LogLevel::Warning); } }
/** * Update any disable rules associated with this response. */ private function updateDisableRules() { if (!isset($this->parent)) { $this->parent = new QuestionModel(array('questionID' => $this->responseRow->questionID, 'depth' => 'question')); } $question = $this->parent; foreach ($question->prompts as $prompt) { foreach ($prompt['rules'] as $rule) { if ($prompt['promptID'] == $this->responseText) { if ($rule->enabled != 'Y') { $rule->enabled = 'Y'; $rule->save(); if (preg_match('/.+Page$/', $rule->type)) { $page = new PageModel(array('pageID' => $rule->targetID, 'depth' => 'question')); $page->save(); } elseif (preg_match('/.+Section$/', $rule->type)) { $section = new SectionModel(array('sectionID' => $rule->targetID, 'depth' => 'question')); $section->save(); } elseif (preg_match('/.+Question$/', $rule->type)) { $question = new QuestionModel(array('questionID' => $rule->targetID, 'depth' => 'question')); $question->save(); } } } else { if ($rule->enabled != 'N') { $rule->enabled = 'N'; $rule->save(); if (preg_match('/.+Page$/', $rule->type)) { $page = new PageModel(array('pageID' => $rule->targetID, 'depth' => 'question')); $page->save(); } elseif (preg_match('/.+Section$/', $rule->type)) { $section = new SectionModel(array('sectionID' => $rule->targetID, 'depth' => 'question')); $section->save(); } elseif (preg_match('/.+Question$/', $rule->type)) { $question = new QuestionModel(array('questionID' => $rule->targetID, 'depth' => 'question')); $question->save(); } } } } } }
public function actionSaveTeam() { $illegalSlugCharacters = array_merge(range(chr(0), chr(47)), range(chr(58), chr(64)), range(chr(91), chr(96)), range(chr(123), chr(127))); $this->requirePostRequest(); $id = craft()->request->getPost('teamId'); $teamName = craft()->request->getPost('teamName'); $slug = rtrim(strtolower(str_replace($illegalSlugCharacters, '_', $teamName)), '_'); if (!$id) { $counter = 1; $slugPrefix = ""; while (craft()->teamManager->getTeamBySlug($slug . $slugPrefix)) { $slugPrefix = '_' . $counter++; if ($counter > 10000) { break; } } $slug .= $slugPrefix; if ($counter > 1) { craft()->userSession->setError(Craft::t('Team "' . $teamName . '" already exists, so it was renamed to "' . ($teamName .= str_replace('_', ' ', $slugPrefix)) . '"')); } } $values = array('teamName' => $teamName, 'slug' => $slug, 'gender' => craft()->request->getPost('gender'), 'thumbnail' => craft()->request->getPost('thumbnail') == null ? null : craft()->request->getPost('thumbnail')[0], 'description' => craft()->request->getPost('description'), 'images' => craft()->request->getPost('images')); //TODO check for preconditions if ($id) { $model = craft()->teamManager->getTeam($id); $model->setAttributes($values); } else { $model = craft()->teamManager->newTeam($values); } //Create a new section $section = new SectionModel(); // Shared attributes $section->id = craft()->request->getPost('sectionId'); $section->name = $teamName; $section->handle = $slug; $section->type = SectionType::Channel; $section->enableVersioning = true; $section->hasUrls = true; $section->template = 'teams/entries/_entry'; $locales = array(); $primaryLocaleId = craft()->i18n->getPrimarySiteLocaleId(); $localeIds = array($primaryLocaleId); foreach ($localeIds as $localeId) { $locales[$localeId] = new SectionLocaleModel(array('locale' => $localeId, 'enabledByDefault' => true, 'urlFormat' => 'teams/' . $slug . '/entries/{slug}', 'nestedUrlFormat' => null)); } $section->setLocales($locales); //Create a new user group $group = new UserGroupModel(); $group->id = craft()->request->getPost('groupId'); $group->name = $teamName; $group->handle = $slug; if (craft()->sections->saveSection($section)) { $model->setAttribute('sectionId', $section->id); if (!craft()->userGroups->saveGroup($group)) { craft()->userSession->setError(Craft::t('Team group could not be saved.')); return; } $model->setAttribute('groupId', $group->id); $sectionId = $section->id; $permissions = array('accessCp', 'editEntries:' . $sectionId, 'createEntries:' . $sectionId, 'publishEntries:' . $sectionId, 'deleteEntries:' . $sectionId, 'editPeerEntries:' . $sectionId, 'publishPeerEntries:' . $sectionId, 'deletePeerEntries:' . $sectionId, 'editPeerEntryDrafts:' . $sectionId, 'publishPeerEntryDrafts:' . $sectionId, 'deletePeerEntryDrafts:' . $sectionId); if (!craft()->userPermissions->saveGroupPermissions($group->id, $permissions)) { craft()->userSession->setNotice(Craft::t('Team permissions could not be saved.')); return; } if (craft()->teamManager->saveTeam($model)) { //Apply the field layout $structure = craft()->sections->getEntryTypesByHandle('structure')[0]; //Must be the only one $model->updateEntryType($structure->fieldLayoutId); craft()->userSession->setNotice(Craft::t('Team successfully saved.')); } else { craft()->userSession->setError(Craft::t('Team could not be saved.')); } } else { craft()->userSession->setError(Craft::t('Team section could not be saved.')); } $this->redirect('teammanager'); }
/** * @param SectionModel $section * @param $localeDefinitions */ private function populateSectionLocales(SectionModel $section, $localeDefinitions) { $locales = $section->getLocales(); foreach ($localeDefinitions as $localeId => $localeDef) { $locale = array_key_exists($localeId, $locales) ? $locales[$localeId] : new SectionLocaleModel(); $locale->setAttributes(array('locale' => $localeId, 'enabledByDefault' => $localeDef['enabledByDefault'], 'urlFormat' => $localeDef['urlFormat'], 'nestedUrlFormat' => $localeDef['nestedUrlFormat'])); // Todo: Is this a hack? I don't see another way. // Todo: Might need a sorting order as well? It's NULL at the moment. craft()->db->createCommand()->insertOrUpdate('locales', array('locale' => $locale->locale), array()); $locales[$localeId] = $locale; } $section->setLocales($locales); }
/** * Returns the data model based on the primary key given in the GET variable. * If the data model is not found, an HTTP exception will be raised. * @param integer the ID of the model to be loaded */ public function loadModel($id) { $model = SectionModel::model()->findByPk($id); if ($model === null) { throw new CHttpException(404, 'The requested page does not exist.'); } return $model; }
<?php /** * @author asmalindi * @copyright 2011 */ require "CategorieModel.php"; require "SectionModel.php"; require "SectionCategorieModel.php"; $SectionM = new SectionModel(); $CategorieM = new CategorieModel(); $sectionCategorieM = new SectionCategorieModel(); $sectionCategorie = new SectionCategorie(); $categorie = new Categorie(); $Section = new Section(); include "process.php"; if (isset($_POST['submit'])) { if (isset($_POST['category']) && isset($_POST['section'])) { //echo"Register.. 111111111!"; $category = $_POST['category']; $section = $_POST['section']; $sectionCategorie->setCat_id($category); $sectionCategorie->setSec_id($section); $sectionCategorieM->addNewSectionCategorieeModel($sectionCategorie); } else { //echo"Register.. 222222222!"; } } ?> <head> <link href="menu.css" rel="stylesheet" type="text/css" />
/** * @param string $data * @param int $sectionId * * @return null|int */ private function prepareAncestorsForElement($data, $sectionId) { $parentId = null; $data = $this->freshenString($data); // Don't connect empty fields if (!empty($data)) { // Get section data $section = new SectionModel(); $section->id = $sectionId; // This we append before the slugified path $sectionUrl = str_replace('{slug}', '', $section->getUrlFormat()); // Find matching element by URI (dirty, not all structures have URI's) $criteria = craft()->elements->getCriteria(ElementType::Entry); $criteria->sectionId = $sectionId; $criteria->uri = $sectionUrl . craft()->import->slugify($data); $criteria->limit = 1; // Return the first found element for connecting if ($criteria->total()) { $parentId = $criteria->ids()[0]; } } return $parentId; }
/** * 添加新子菜单 到选中的菜单中 */ function addin() { //父菜单ID $menu_id = $_SESSION['menuid']; //首字母大写 例:Article $type = ucfirst($_POST['type']); $id = $_POST['creat_id']; //查询数据,实例化对象 if ($type == 'Article') { $obj = new ArticleModel(); } else { if ($type == 'Category') { $obj = new CategoryModel(); } else { $obj = new SectionModel(); } } $title = $obj->field('title,description')->find($id); //重写链接 $link = $id; //得到所有父菜单,然后在模板中判断选择 $menus = new MenuModel(); $menu_list = $menus->select(); //得到该父菜单下的所有子菜单 $menu_items = new MenuItemModel(); $where = array('menuid' => $menu_id); $m_items = $menu_items->where($where)->select(); //查询组建,得到相对应组建ID $components = new ComponentModel(); $coms = $components->select(); $count = count($coms); for ($i = 0; $i < $count; $i++) { if ($coms[$i]['link'] == $type) { $componentid = $coms[$i]['id']; } } $this->assign("type_id", $id); $this->assign('menu_id', $menu_id); $this->assign('link', $link); $this->assign('title', $title); $this->assign('menu_list', $menu_list); $this->assign('m_items', $m_items); $this->assign('type', $type); $this->assign('componentid', $componentid); $this->display(); }
/** * Saves a section. * * @return null */ public function actionSaveSection() { $this->requirePostRequest(); $section = new SectionModel(); // Shared attributes $section->id = craft()->request->getPost('sectionId'); $section->name = craft()->request->getPost('name'); $section->handle = craft()->request->getPost('handle'); $section->type = craft()->request->getPost('type'); $section->enableVersioning = craft()->request->getPost('enableVersioning', true); // Type-specific attributes $section->hasUrls = (bool) craft()->request->getPost('types.' . $section->type . '.hasUrls', true); $section->template = craft()->request->getPost('types.' . $section->type . '.template'); $section->maxLevels = craft()->request->getPost('types.' . $section->type . '.maxLevels'); // Locale-specific attributes $locales = array(); if (craft()->isLocalized()) { $localeIds = craft()->request->getPost('locales'); } else { $primaryLocaleId = craft()->i18n->getPrimarySiteLocaleId(); $localeIds = array($primaryLocaleId); } $isHomepage = $section->type == SectionType::Single && craft()->request->getPost('types.' . $section->type . '.homepage'); foreach ($localeIds as $localeId) { if ($isHomepage) { $urlFormat = '__home__'; $nestedUrlFormat = null; } else { $urlFormat = craft()->request->getPost('types.' . $section->type . '.urlFormat.' . $localeId); $nestedUrlFormat = craft()->request->getPost('types.' . $section->type . '.nestedUrlFormat.' . $localeId); } $locales[$localeId] = new SectionLocaleModel(array('locale' => $localeId, 'enabledByDefault' => (bool) craft()->request->getPost('defaultLocaleStatuses.' . $localeId), 'urlFormat' => $urlFormat, 'nestedUrlFormat' => $nestedUrlFormat)); } $section->setLocales($locales); $section->hasUrls = (bool) craft()->request->getPost('types.' . $section->type . '.hasUrls', true); // Save it if (craft()->sections->saveSection($section)) { craft()->userSession->setNotice(Craft::t('Section saved.')); if (isset($_POST['redirect']) && mb_strpos($_POST['redirect'], '{sectionId}') !== false) { craft()->deprecator->log('SectionsController::saveSection():sectionId_redirect', 'The {sectionId} token within the ‘redirect’ param on sections/saveSection requests has been deprecated. Use {id} instead.'); $_POST['redirect'] = str_replace('{sectionId}', '{id}', $_POST['redirect']); } $this->redirectToPostedUrl($section); } else { craft()->userSession->setError(Craft::t('Couldn’t save section.')); } // Send the section back to the template craft()->urlManager->setRouteVariables(array('section' => $section)); }
<?php /** * @author asmalindi * @copyright 2011 */ require "SectionModel.php"; include "process.php"; $SectionM = new SectionModel(); if (isset($_POST['submit'])) { if (isset($_POST['sec_id'])) { //echo"Register.. 111111111!"; $sec_id = $_POST['sec_id']; //$categorie->setCat_title($cat_title); //$CategorieM->addNewCategorie($categorie); $SectionM->removeSection($sec_id); } } ?> <head> <link href="menu.css" rel="stylesheet" type="text/css" /> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.js"></script> <script type="text/javascript" src="menu.js"></script> <style type="text/css"> <!-- body, html { margin:0; padding:0; color:#000;
/** * Create a new SectionModel object. * * @param Array array of arguments */ function __construct($args = array()) { // merge default parameters with arguments $args = array_merge(array('depth' => 'response'), $args); $this->depth = $args['depth']; // argument assertions if (!isset($args['sectionID'])) { throw new InvalidArgumentException('Missing sectionID as argument to SectionModel()'); } if (!isset(self::$sectionTable)) { self::$sectionTable = QFrame_Db_Table::getTable('section'); } if (!isset(self::$ruleTable)) { self::$ruleTable = QFrame_Db_Table::getTable('rule'); } if (!isset(self::$sectionReferenceTable)) { self::$sectionReferenceTable = QFrame_Db_Table::getTable('section_reference'); } if (!isset(self::$referenceDetailTable)) { self::$referenceDetailTable = QFrame_Db_Table::getTable('reference_detail'); } $rows = self::$sectionTable->fetchRows('sectionID', $args['sectionID']); $this->sectionRow = $rows[0]; // section row assertion if ($this->sectionRow === NULL) { throw new Exception('Section not found [' . $args['sectionID'] . ']'); } if ($args['depth'] !== 'section') { $this->_loadQuestions(); } $ruleRows = self::$ruleTable->fetchRows('targetID', $this->sectionRow->sectionID, null, $this->sectionRow->instanceID); $disableCount = 0; foreach ($ruleRows as $row) { if ($row->enabled == 'Y' && $row->type == 'disableSection') { $disableCount++; } elseif ($row->enabled == 'Y' && $row->type == 'enableSection') { $disableCount--; } } if ($this->sectionRow->defaultSectionHidden) { $disableCount++; } $page = new PageModel(array('pageID' => $this->sectionRow->pageID, 'depth' => 'page')); $disableCount += $page->disableCount; if ($disableCount != $this->sectionRow->disableCount) { $this->sectionRow->disableCount = $disableCount; $this->sectionRow->save(); } $sectionReferenceRows = self::$sectionReferenceTable->fetchRows('sectionID', $this->sectionRow->sectionID, null, $this->sectionRow->pageID); foreach ($sectionReferenceRows as $row) { $rows = self::$referenceDetailTable->fetchRows('referenceDetailID', $row->referenceDetailID, null, $this->sectionRow->instanceID); $this->referenceDetailRows[] = $rows[0]->toArray(); } }
public function prepForElementModel(&$fields, EntryModel $element) { // Set author $author = FeedMe_Element::Author; if (isset($fields[$author])) { $user = craft()->users->getUserByUsernameOrEmail($fields[$author]); $element->{$author} = is_numeric($fields[$author]) ? $fields[$author] : ($user ? $user->id : 1); //unset($fields[$author]); } else { $user = craft()->userSession->getUser(); $element->{$author} = $element->{$author} ? $element->{$author} : ($user ? $user->id : 1); } // Set slug $slug = FeedMe_Element::Slug; if (isset($fields[$slug])) { $element->{$slug} = ElementHelper::createSlug($fields[$slug]); //unset($fields[$slug]); } // Set postdate $postDate = FeedMe_Element::PostDate; if (isset($fields[$postDate])) { $d = date_parse($fields[$postDate]); $date_string = date('Y-m-d H:i:s', mktime($d['hour'], $d['minute'], $d['second'], $d['month'], $d['day'], $d['year'])); $element->{$postDate} = DateTime::createFromString($date_string, craft()->timezone); //unset($fields[$postDate]); } // Set expiry date $expiryDate = FeedMe_Element::ExpiryDate; if (isset($fields[$expiryDate])) { $d = date_parse($fields[$expiryDate]); $date_string = date('Y-m-d H:i:s', mktime($d['hour'], $d['minute'], $d['second'], $d['month'], $d['day'], $d['year'])); $element->{$expiryDate} = DateTime::createFromString($date_string, craft()->timezone); //unset($fields[$expiryDate]); } // Set enabled $enabled = FeedMe_Element::Enabled; if (isset($fields[$enabled])) { $element->{$enabled} = (bool) $fields[$enabled]; //unset($fields[$enabled]); } // Set title $title = FeedMe_Element::Title; if (isset($fields[$title])) { $element->getContent()->{$title} = $fields[$title]; //unset($fields[$title]); } // Set parent or ancestors $parent = FeedMe_Element::Parent; $ancestors = FeedMe_Element::Ancestors; if (isset($fields[$parent])) { $data = $fields[$parent]; // Don't connect empty fields if (!empty($data)) { // Find matching element $criteria = craft()->elements->getCriteria(ElementType::Entry); $criteria->sectionId = $element->sectionId; $criteria->search = '"' . $data . '"'; // Return the first found element for connecting if ($criteria->total()) { $element->{$parent} = $criteria->first()->id; } } //unset($fields[$parent]); } elseif (isset($fields[$ancestors])) { $data = $fields[$ancestors]; // Don't connect empty fields if (!empty($data)) { // Get section data $section = new SectionModel(); $section->id = $element->sectionId; // This we append before the slugified path $sectionUrl = str_replace('{slug}', '', $section->getUrlFormat()); // Find matching element by URI (dirty, not all structures have URI's) $criteria = craft()->elements->getCriteria(ElementType::Entry); $criteria->sectionId = $element->sectionId; $criteria->uri = $sectionUrl . craft()->feedMe->slugify($data); $criteria->limit = 1; // Return the first found element for connecting if ($criteria->total()) { $element->{$parent} = $criteria->first()->id; } } //unset($fields[$ancestors]); } // Return element return $element; }
/** * addSection * @param String $jsonSection [input string] * @return Boolean [success] */ private function addSection($jsonSection) { $section = new SectionModel(); $section->name = $jsonSection->name; // Set handle if it was provided if (isset($jsonSection->handle)) { $section->handle = $jsonSection->handle; } else { $section->handle = $this->generateHandle($jsonSection->name); } $section->type = $jsonSection->type; // Set enableVersioning if it was provided if (isset($jsonSection->typeSettings->enableVersioning)) { $section->enableVersioning = $jsonSection->typeSettings->enableVersioning; } else { $section->enableVersioning = 1; } // Set hasUrls if it was provided if (isset($jsonSection->typeSettings->hasUrls)) { $section->hasUrls = $jsonSection->typeSettings->hasUrls; } // Set template if it was provided if (isset($jsonSection->typeSettings->template)) { $section->template = $jsonSection->typeSettings->template; } // Set maxLevels if it was provided if (isset($jsonSection->typeSettings->maxLevels)) { $section->maxLevels = $jsonSection->typeSettings->maxLevels; } $locales = array(); $primaryLocaleId = craft()->i18n->getPrimarySiteLocaleId(); $localeIds = array($primaryLocaleId); foreach ($localeIds as $localeId) { if (isset($jsonSection->typeSettings->urlFormat)) { $urlFormat = $jsonSection->typeSettings->urlFormat; } else { $urlFormat = null; } if (isset($jsonSection->typeSettings->nestedUrlFormat)) { $nestedUrlFormat = $jsonSection->typeSettings->nestedUrlFormat; } else { $nestedUrlFormat = null; } $locales[$localeId] = new SectionLocaleModel(array('locale' => $localeId, 'enabledByDefault' => null, 'urlFormat' => $urlFormat, 'nestedUrlFormat' => $nestedUrlFormat)); } $section->setLocales($locales); if (craft()->sections->saveSection($section)) { return true; } else { return false; } }
<?php /** * @author asmalindi * @copyright 2011 */ require "SectionModel.php"; $SectionM = new SectionModel(); $Section = new Section(); include "process.php"; if (isset($_POST['submit'])) { if (isset($_POST['sec_title']) && isset($_POST['sec_url']) && isset($_POST['sec_order']) && isset($_POST['sec_despription'])) { //echo"Register.. 111111111!"; $sec_title = $_POST['sec_title']; $sec_url = $_POST['sec_url']; $sec_order = $_POST['sec_order']; $sec_despription = $_POST['sec_despription']; // $categorie->setCat_title($cat_title); // $categorie->setCat_despription($cat_despription); // $CategorieM->addNewCategorie($categorie); $Section->setSec_url($sec_url); $Section->setsSec_title($sec_title); $Section->setSec_order($sec_order); $Section->setSec_despription($sec_despription); $SectionM->addNewSection($Section); } else { echo "Register.. 222222222!"; } } ?> <head>
/** * Saves a section. * * @param SectionModel $section * @throws \Exception * @return bool */ public function saveSection(SectionModel $section) { $sectionRecord = $this->_getSectionRecordById($section->id); $isNewSection = $sectionRecord->isNewRecord(); if (!$isNewSection) { $oldSection = SectionModel::populateModel($sectionRecord); } $sectionRecord->name = $section->name; $sectionRecord->handle = $section->handle; $sectionRecord->titleLabel = $section->titleLabel; $sectionRecord->hasUrls = $section->hasUrls; if ($section->hasUrls) { $sectionRecord->template = $section->template; } else { $sectionRecord->template = $section->template = null; } $sectionRecord->validate(); $section->addErrors($sectionRecord->getErrors()); // Make sure that all of the URL formats are set properly foreach ($section->getLocales() as $localeId => $sectionLocale) { if ($section->hasUrls) { $errorKey = 'urlFormat-' . $localeId; if (empty($sectionLocale->urlFormat)) { $section->addError($errorKey, Craft::t('{attribute} cannot be blank.', array('attribute' => 'URL Format'))); } else { if (strpos($sectionLocale->urlFormat, '{slug}') === false) { $section->addError($errorKey, Craft::t('URL Format must contain “{slug}”')); } } } else { $sectionLocale->urlFormat = null; } } if (!$section->hasErrors()) { $transaction = craft()->db->beginTransaction(); try { if (!$isNewSection && $oldSection->fieldLayoutId) { // Drop the old field layout craft()->fields->deleteLayoutById($oldSection->fieldLayoutId); } // Save the new one $fieldLayout = $section->getFieldLayout(); craft()->fields->saveLayout($fieldLayout); // Update the section record/model with the new layout ID $section->fieldLayoutId = $fieldLayout->id; $sectionRecord->fieldLayoutId = $fieldLayout->id; $sectionRecord->save(false); // Now that we have a section ID, save it on the model if (!$section->id) { $section->id = $sectionRecord->id; } // Might as well update our cache of the section while we have it. // (It's possilbe that the URL format includes {section.handle} or something...) $this->_sectionsById[$section->id] = $section; // Update the sections_i18n table $newLocaleData = array(); if (!$isNewSection) { // Get the old section locales $oldSectionLocaleRecords = SectionLocaleRecord::model()->findAllByAttributes(array('sectionId' => $section->id)); $oldSectionLocales = SectionLocaleModel::populateModels($oldSectionLocaleRecords, 'locale'); } foreach ($section->getLocales() as $localeId => $locale) { $updateEntries = false; // Was this already selected? if (!$isNewSection && isset($oldSectionLocales[$localeId])) { $oldLocale = $oldSectionLocales[$localeId]; // Has the URL format changed? if ($locale->urlFormat != $oldLocale->urlFormat) { craft()->db->createCommand()->update('sections_i18n', array('urlFormat' => $locale->urlFormat), array('id' => $oldLocale->id)); $updateEntries = true; } } else { $newLocaleData[] = array($section->id, $localeId, $locale->urlFormat); if (!$isNewSection) { $updateEntries = true; } } if ($updateEntries && $section->hasUrls) { // This may take a while... set_time_limit(120); // Fetch all the entries in this section $entries = craft()->elements->getCriteria(ElementType::Entry, array('sectionId' => $section->id, 'locale' => $localeId, 'limit' => null))->find(); foreach ($entries as $entry) { $uri = craft()->templates->renderObjectTemplate($locale->urlFormat, $entry); if ($uri != $entry->uri) { craft()->db->createCommand()->update('elements_i18n', array('uri' => $uri), array('elementId' => $entry->id, 'locale' => $localeId)); } } } } // Insert the new locales craft()->db->createCommand()->insertAll('sections_i18n', array('sectionId', 'locale', 'urlFormat'), $newLocaleData); if (!$isNewSection) { // Drop the old ones $disabledLocaleIds = array_diff(array_keys($oldSectionLocales), array_keys($section->getLocales())); foreach ($disabledLocaleIds as $localeId) { craft()->db->createCommand()->delete('sections_i18n', array('id' => $oldSectionLocales[$localeId]->id)); } // Drop the old entry URIs if the section no longer has URLs if (!$section->hasUrls && $oldSection->hasUrls) { // Clear out all the URIs $entryIds = craft()->db->createCommand()->select('id')->from('entries')->where(array('sectionId' => $section->id))->queryColumn(); craft()->db->createCommand()->update('elements_i18n', array('uri' => null), array('in', 'elementId', $entryIds)); } } $transaction->commit(); } catch (\Exception $e) { $transaction->rollBack(); throw $e; } return true; } else { return false; } }
<?php /** * @author asmalindi * @copyright 2011 */ require "SectionModel.php"; $SectionM = new SectionModel(); $Section = new Section(); include "process.php"; if (isset($_POST['submit'])) { $sec_id = $_POST['sec_id']; if (isset($_POST['sec_title'])) { //echo"Register.. 111111111!"; $sec_title = $_POST['sec_title']; //$categorie->setCat_title($cat_title); //$CategorieM->addNewCategorie($categorie); $SectionM->editSection($sec_id, sec_title, $sec_title); } if (isset($_POST['sec_url'])) { $sec_url = $_POST['sec_url']; $SectionM->editSection($sec_id, sec_url, $sec_url); } if (isset($_POST['sec_order'])) { $sec_order = $_POST['sec_order']; $SectionM->editSection($sec_id, sec_order, $sec_order); } if (isset($_POST['sec_despription'])) { $sec_despription = $_POST['sec_despription']; $SectionM->editSection($sec_id, sec_despription, $sec_despription); }
/** * Creates initial database content for InstaBlog. * * @return null */ private function _createInstaBlogContent() { // InstaBlog tag group Craft::log('Creating the InstaBlog tag group.', LogLevel::Info, true, '_createInstaBlogContent', 'InstaBlog'); $tagGroup = new TagGroupModel(); $tagGroup->name = 'InstaBlog Tags'; $tagGroup->handle = 'instaBlogTags'; // Save it if (craft()->tags->saveTagGroup($tagGroup)) { Craft::log('InstaBlog tag group created successfully.', LogLevel::Info, true, '_createInstaBlogContent', 'InstaBlog'); } else { Craft::log('Could not save the InstaBlog tag group.', LogLevel::Error, true, '_createInstaBlogContent', 'InstaBlog'); } // InstaBlog field group Craft::log('Creating the InstaBlog field group.', LogLevel::Info, true, '_createInstaBlogContent', 'InstaBlog'); $group = new FieldGroupModel(); $group->name = 'InstaBlog'; if (craft()->fields->saveGroup($group)) { Craft::log('InstaBlog field group created successfully.', LogLevel::Info, true, '_createInstaBlogContent', 'InstaBlog'); } else { Craft::log('Could not save the InstaBlog field group.', LogLevel::Error, true, '_createInstaBlogContent', 'InstaBlog'); } // Body field Craft::log('Creating the InstaBlog Body field.'); $bodyField = new FieldModel(); $bodyField->groupId = $group->id; $bodyField->name = 'InstaBlog Body'; $bodyField->handle = 'instaBlogBody'; $bodyField->translatable = true; $bodyField->type = 'RichText'; $bodyField->settings = array('configFile' => 'Standard.json', 'columnType' => ColumnType::Text); if (craft()->fields->saveField($bodyField)) { Craft::log('InstaBlog Body field created successfully.', LogLevel::Info, true, '_createInstaBlogContent', 'InstaBlog'); } else { Craft::log('Could not save the InstaBlog Body field.', LogLevel::Error, true, '_createInstaBlogContent', 'InstaBlog'); } // Facebook field Craft::log('Creating the InstaBlog Facebook field.', LogLevel::Info, true, '_createInstaBlogContent', 'InstaBlog'); $facebookField = new FieldModel(); $facebookField->groupId = $group->id; $facebookField->name = 'Facebook'; $facebookField->handle = 'instaBlogFacebook'; $facebookField->translatable = false; $facebookField->type = 'PlainText'; $facebookField->instructions = 'Add your personal Facebook profile link. Example: https://www.facebook.com/xxxxxxxxxx'; if (craft()->fields->saveField($facebookField)) { Craft::log('Facebook field created successfully.', LogLevel::Info, true, '_createInstaBlogContent', 'InstaBlog'); } else { Craft::log('Could not save the Facebook field.', LogLevel::Error, true, '_createInstaBlogContent', 'InstaBlog'); } // Twitter Handle field Craft::log('Creating the InstaBlog Twitter field.', LogLevel::Info, true, '_createInstaBlogContent', 'InstaBlog'); $twitterField = new FieldModel(); $twitterField->groupId = $group->id; $twitterField->name = 'Twitter'; $twitterField->handle = 'instaBlogTwitter'; $twitterField->translatable = false; $twitterField->type = 'PlainText'; $twitterField->instructions = 'Add your personal Twitter handle. Example: @johndoe'; if (craft()->fields->saveField($twitterField)) { Craft::log('Twitter field created successfully.', LogLevel::Info, true, '_createInstaBlogContent', 'InstaBlog'); } else { Craft::log('Could not save the Twitter field.', LogLevel::Error, true, '_createInstaBlogContent', 'InstaBlog'); } // Google+ field Craft::log('Creating the InstaBlog Google+ field.', LogLevel::Info, true, '_createInstaBlogContent', 'InstaBlog'); $googlePlusField = new FieldModel(); $googlePlusField->groupId = $group->id; $googlePlusField->name = 'Google+'; $googlePlusField->handle = 'instaBlogGooglePlus'; $googlePlusField->translatable = false; $googlePlusField->type = 'PlainText'; $googlePlusField->instructions = 'Add your personal Google+ profile link. Example: https://plus.google.com/+JohnDoe'; if (craft()->fields->saveField($googlePlusField)) { Craft::log('Google+ field created successfully.', LogLevel::Info, true, '_createInstaBlogContent', 'InstaBlog'); } else { Craft::log('Could not save the Google+ field.', LogLevel::Error, true, '_createInstaBlogContent', 'InstaBlog'); } // LinkedIn field Craft::log('Creating the InstaBlog LinkedIn field.'); $linkedinField = new FieldModel(); $linkedinField->groupId = $group->id; $linkedinField->name = 'LinkedIn'; $linkedinField->handle = 'instaBlogLinkedin'; $linkedinField->translatable = false; $linkedinField->type = 'PlainText'; $linkedinField->instructions = 'Add your personal LinkedIn profile link. Example: https://www.linkedin.com/pub/john-doe/3/7aa/91b'; if (craft()->fields->saveField($linkedinField)) { Craft::log('LinkedIn field created successfully.', LogLevel::Info, true, '_createInstaBlogContent', 'InstaBlog'); } else { Craft::log('Could not save the LinkedIn field.', LogLevel::Error, true, '_createInstaBlogContent', 'InstaBlog'); } // Create the new user field layout Craft::log('Creating the new user profile layout.', LogLevel::Info, true, '_createInstaBlogContent', 'InstaBlog'); $userFieldLayout = craft()->fields->getLayoutByType(ElementType::User); $fieldsIds = $userFieldLayout->getFieldIds(); $fieldsIds[] = $facebookField->id; $fieldsIds[] = $twitterField->id; $fieldsIds[] = $googlePlusField->id; $fieldsIds[] = $linkedinField->id; craft()->fields->deleteLayoutsByType(ElementType::User); $userFieldLayout = craft()->fields->assembleLayout(array(Craft::t('Profile') => $fieldsIds), array(), false); $userFieldLayout->type = ElementType::User; if (craft()->fields->saveLayout($userFieldLayout, false)) { Craft::log('User profile layout saved successfully.', LogLevel::Info, true, '_createInstaBlogContent', 'InstaBlog'); } else { Craft::log('Could not save the user profile layout.', LogLevel::Error, true, '_createInstaBlogContent', 'InstaBlog'); } // Tags field Craft::log('Creating the Tags field.', LogLevel::Info, true, '_createInstaBlogContent', 'InstaBlog'); $tagsField = new FieldModel(); $tagsField->groupId = $group->id; $tagsField->name = 'InstaBlog Tags'; $tagsField->handle = 'instaBlogTags'; $tagsField->type = 'Tags'; $tagsField->settings = array('source' => 'taggroup:' . $tagGroup->id); if (craft()->fields->saveField($tagsField)) { Craft::log('InstaBlog Tags field created successfully.', LogLevel::Info, true, '_createInstaBlogContent', 'InstaBlog'); } else { Craft::log('Could not save the InstaBlog Tags field.', LogLevel::Error, true, '_createInstaBlogContent', 'InstaBlog'); } // InstaBlog category group Craft::log('Creating the InstaBlog category group.', LogLevel::Info, true, '_createInstaBlogContent', 'InstaBlog'); $categoryGroup = new CategoryGroupModel(); $categoryGroup->name = 'InstaBlog Categories'; $categoryGroup->handle = 'instaBlogCategories'; $categoryGroup->template = 'blog/category'; $categoryGroup->maxLevels = 1; // Locale-specific URL formats $locales = array(); foreach (craft()->i18n->getSiteLocaleIds() as $localeId) { $locales[$localeId] = new CategoryGroupLocaleModel(array('locale' => $localeId, 'urlFormat' => 'blog/category/{slug}', 'nestedUrlFormat' => null)); } $categoryGroup->setLocales($locales); // Group the field layout $categoryFieldLayout = craft()->fields->assembleLayout(array('Content' => array($bodyField->id)), array()); $categoryFieldLayout->type = ElementType::Category; $categoryGroup->setFieldLayout($categoryFieldLayout); // Save it if (craft()->categories->saveGroup($categoryGroup)) { Craft::log('InstaBlog category group created successfully.', LogLevel::Info, true, '_createInstaBlogContent', 'InstaBlog'); } else { Craft::log('Could not save the InstaBlog category group.', LogLevel::Error, true, '_createInstaBlogContent', 'InstaBlog'); } // Categories field Craft::log('Creating the InstaBlog Category field.', LogLevel::Info, true, '_createInstaBlogContent', 'InstaBlog'); $categoriesField = new FieldModel(); $categoriesField->groupId = $group->id; $categoriesField->name = 'InstaBlog Categories'; $categoriesField->handle = 'instaBlogCategories'; $categoriesField->type = 'Categories'; $categoriesField->settings = array('source' => 'group:' . $categoryGroup->id); if (craft()->fields->saveField($categoriesField)) { Craft::log('InstaBlog Category field created successfully.', LogLevel::Info, true, '_createInstaBlogContent', 'InstaBlog'); } else { Craft::log('Could not save the InstaBlog Category field.', LogLevel::Error, true, '_createInstaBlogContent', 'InstaBlog'); } // Asset field Craft::log('Creating the InstaBlog Asset field.'); $assetField = new FieldModel(); $assetField->groupId = $group->id; $assetField->name = 'Featured Image'; $assetField->handle = 'instaBlogImage'; $assetField->translatable = false; $assetField->type = 'Assets'; $assetField->settings = array('sources' => '*'); if (craft()->fields->saveField($assetField)) { Craft::log('Asset field created successfully.', LogLevel::Info, true, '_createInstaBlogContent', 'InstaBlog'); } else { Craft::log('Could not save the Asset field.', LogLevel::Error, true, '_createInstaBlogContent', 'InstaBlog'); } // InstaBlog section Craft::log('Creating the InstaBlog section.', LogLevel::Info, true, '_createInstaBlogContent', 'InstaBlog'); $instaBlogSection = new SectionModel(); $instaBlogSection->type = SectionType::Channel; $instaBlogSection->name = 'InstaBlog'; $instaBlogSection->handle = 'instaBlog'; $instaBlogSection->hasUrls = true; $instaBlogSection->template = 'blog/_entry'; // Locale-specific URL formats $locales = array(); if (craft()->isLocalized()) { $localeIds = craft()->i18n->getSiteLocaleIds(); } else { $primaryLocaleId = craft()->i18n->getPrimarySiteLocaleId(); $localeIds = array($primaryLocaleId); } foreach ($localeIds as $localeId) { $locales[$localeId] = new SectionLocaleModel(array('locale' => $localeId, 'enabledByDefault' => true, 'urlFormat' => 'blog/{slug}')); } $instaBlogSection->setLocales($locales); if (craft()->sections->saveSection($instaBlogSection)) { Craft::log('InstaBlog section created successfully.', LogLevel::Info, true, '_createInstaBlogContent', 'InstaBlog'); } else { Craft::log('Could not save the InstaBlog section.', LogLevel::Error, true, '_createInstaBlogContent', 'InstaBlog'); } // InstaBlog section entry type layout Craft::log('Saving the InstaBlog entry type.', LogLevel::Info, true, '_createInstaBlogContent', 'InstaBlog'); $instaBlogLayout = craft()->fields->assembleLayout(array('Content' => array($bodyField->id, $assetField->id, $categoriesField->id, $tagsField->id)), array($bodyField->id)); $instaBlogLayout->type = ElementType::Entry; $instaBlogEntryTypes = $instaBlogSection->getEntryTypes(); $instaBlogEntryType = $instaBlogEntryTypes[0]; $instaBlogEntryType->setFieldLayout($instaBlogLayout); if (craft()->sections->saveEntryType($instaBlogEntryType)) { Craft::log('InstaBlog entry type saved successfully.', LogLevel::Info, true, '_createInstaBlogContent', 'InstaBlog'); } else { Craft::log('Could not save the InstaBlog entry type.', LogLevel::Error, true, '_createInstaBlogContent', 'InstaBlog'); } // InstaBlog entry Craft::log('Creating a InstaBlog entry.'); $instaBlogEntry = new EntryModel(); $instaBlogEntry->sectionId = $instaBlogSection->id; $instaBlogEntry->typeId = $instaBlogEntryType->id; $instaBlogEntry->locale = $primaryLocaleId; $instaBlogEntry->authorId = craft()->userSession->getId(); $instaBlogEntry->enabled = true; $instaBlogEntry->getContent()->title = 'We just installed InstaBlog!'; $instaBlogEntry->getContent()->setAttributes(array('instaBlogBody' => '<p>' . 'Collaboratively administrate empowered markets via plug-and-play networks. Dynamically procrastinate B2C users after installed base benefits. Dramatically visualize customer directed convergence without revolutionary ROI.' . '</p><p>Efficiently unleash cross-media information without cross-media value. Quickly maximize timely deliverables for real-time schemas. Dramatically maintain clicks-and-mortar solutions without functional solutions.' . '</p><p>Completely synergize resource taxing relationships via premier niche markets. Professionally cultivate one-to-one customer service with robust ideas. Dynamically innovate resource-leveling customer service for state of the art customer service.' . '</p>')); if (craft()->entries->saveEntry($instaBlogEntry)) { Craft::log('InstaBlog entry created successfully.', LogLevel::Info, true, '_createInstaBlogContent', 'InstaBlog'); } else { Craft::log('Could not save the InstaBlog entry.', LogLevel::Error, true, '_createInstaBlogContent', 'InstaBlog'); } //Create Route for Tags $urlParts = array('blog/tag/', array('*', '[^\\/]+')); $template = 'blog/tag'; if (craft()->routes->saveRoute($urlParts, $template)) { Craft::log('InstaBlog tag route created successfully.', LogLevel::Info, true, '_createInstaBlogContent', 'InstaBlog'); } else { Craft::log('Could not create the InstaBlog tag route.', LogLevel::Error, true, '_createInstaBlogContent', 'InstaBlog'); } //Create Route for Tags $urlParts = array('blog/author/', array('*', '[^\\/]+')); $template = 'blog/author'; if (craft()->routes->saveRoute($urlParts, $template)) { Craft::log('InstaBlog author route created successfully.', LogLevel::Info, true, '_createInstaBlogContent', 'InstaBlog'); } else { Craft::log('Could not create the InstaBlog author route.', LogLevel::Error, true, '_createInstaBlogContent', 'InstaBlog'); } }
<?php /** * @author asmalindi * @copyright 2011 */ require "SectionModel.php"; include "process.php"; $SectionM = new SectionModel(); ?> <head> <link href="menu.css" rel="stylesheet" type="text/css" /> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.js"></script> <script type="text/javascript" src="menu.js"></script> <style type="text/css"> <!-- body, html { margin:0; padding:0; color:#000; background:#a7a09a; } #wrap { width:750px; margin:0 auto; background:#99c; }
/** * Saves a section. * * @param SectionModel $section * * @throws \Exception * @return bool */ public function saveSection(SectionModel $section) { if ($section->id) { $sectionRecord = SectionRecord::model()->with('structure')->findById($section->id); if (!$sectionRecord) { throw new Exception(Craft::t('No section exists with the ID “{id}”.', array('id' => $section->id))); } $oldSection = SectionModel::populateModel($sectionRecord); $isNewSection = false; } else { $sectionRecord = new SectionRecord(); $isNewSection = true; } // Shared attributes $sectionRecord->name = $section->name; $sectionRecord->handle = $section->handle; $sectionRecord->type = $section->type; $sectionRecord->enableVersioning = $section->enableVersioning; // Type-specific attributes if ($section->type == SectionType::Single) { $sectionRecord->hasUrls = $section->hasUrls = true; } else { $sectionRecord->hasUrls = $section->hasUrls; } if ($section->hasUrls) { $sectionRecord->template = $section->template; } else { $sectionRecord->template = $section->template = null; } $sectionRecord->validate(); $section->addErrors($sectionRecord->getErrors()); // Make sure that all of the URL formats are set properly $sectionLocales = $section->getLocales(); if (!$sectionLocales) { $section->addError('localeErrors', Craft::t('At least one locale must be selected for the section.')); } $firstSectionLocale = null; foreach ($sectionLocales as $localeId => $sectionLocale) { // Is this the first one? if ($firstSectionLocale === null) { $firstSectionLocale = $sectionLocale; } if ($section->type == SectionType::Single) { $errorKey = 'urlFormat-' . $localeId; if (empty($sectionLocale->urlFormat)) { $section->addError($errorKey, Craft::t('URI cannot be blank.')); } else { if ($section) { // Make sure no other elements are using this URI already $query = craft()->db->createCommand()->from('elements_i18n elements_i18n')->where(array('and', 'elements_i18n.locale = :locale', 'elements_i18n.uri = :uri'), array(':locale' => $localeId, ':uri' => $sectionLocale->urlFormat)); if ($section->id) { $query->join('entries entries', 'entries.id = elements_i18n.elementId')->andWhere('entries.sectionId != :sectionId', array(':sectionId' => $section->id)); } $count = $query->count('elements_i18n.id'); if ($count) { $section->addError($errorKey, Craft::t('This URI is already in use.')); } } } $sectionLocale->nestedUrlFormat = null; } else { if ($section->hasUrls) { $urlFormatAttributes = array('urlFormat'); $sectionLocale->urlFormatIsRequired = true; if ($section->type == SectionType::Structure && $section->maxLevels != 1) { $urlFormatAttributes[] = 'nestedUrlFormat'; $sectionLocale->nestedUrlFormatIsRequired = true; } else { $sectionLocale->nestedUrlFormat = null; } foreach ($urlFormatAttributes as $attribute) { if (!$sectionLocale->validate(array($attribute))) { $section->addError($attribute . '-' . $localeId, $sectionLocale->getError($attribute)); } } } else { $sectionLocale->urlFormat = null; $sectionLocale->nestedUrlFormat = null; } } } if (!$section->hasErrors()) { $transaction = craft()->db->getCurrentTransaction() === null ? craft()->db->beginTransaction() : null; try { // Fire an 'onBeforeSaveSection' event $event = new Event($this, array('section' => $section, 'isNewSection' => $isNewSection)); $this->onBeforeSaveSection($event); // Is the event giving us the go-ahead? if ($event->performAction) { // Do we need to create a structure? if ($section->type == SectionType::Structure) { if (!$isNewSection && $oldSection->type == SectionType::Structure) { $structure = craft()->structures->getStructureById($oldSection->structureId); $isNewStructure = false; } if (empty($structure)) { $structure = new StructureModel(); $isNewStructure = true; } $structure->maxLevels = $section->maxLevels; craft()->structures->saveStructure($structure); $sectionRecord->structureId = $structure->id; $section->structureId = $structure->id; } else { if (!$isNewSection && $oldSection->structureId) { // Delete the old one craft()->structures->deleteStructureById($oldSection->structureId); $sectionRecord->structureId = null; } } $sectionRecord->save(false); // Now that we have a section ID, save it on the model if ($isNewSection) { $section->id = $sectionRecord->id; } // Might as well update our cache of the section while we have it. (It's possible that the URL format //includes {section.handle} or something...) $this->_sectionsById[$section->id] = $section; // Update the sections_i18n table $newLocaleData = array(); if (!$isNewSection) { // Get the old section locales $oldSectionLocaleRecords = SectionLocaleRecord::model()->findAllByAttributes(array('sectionId' => $section->id)); $oldSectionLocales = SectionLocaleModel::populateModels($oldSectionLocaleRecords, 'locale'); } foreach ($sectionLocales as $localeId => $locale) { // Was this already selected? if (!$isNewSection && isset($oldSectionLocales[$localeId])) { $oldLocale = $oldSectionLocales[$localeId]; // Has anything changed? if ($locale->enabledByDefault != $oldLocale->enabledByDefault || $locale->urlFormat != $oldLocale->urlFormat || $locale->nestedUrlFormat != $oldLocale->nestedUrlFormat) { craft()->db->createCommand()->update('sections_i18n', array('enabledByDefault' => (int) $locale->enabledByDefault, 'urlFormat' => $locale->urlFormat, 'nestedUrlFormat' => $locale->nestedUrlFormat), array('id' => $oldLocale->id)); } } else { $newLocaleData[] = array($section->id, $localeId, (int) $locale->enabledByDefault, $locale->urlFormat, $locale->nestedUrlFormat); } } // Insert the new locales craft()->db->createCommand()->insertAll('sections_i18n', array('sectionId', 'locale', 'enabledByDefault', 'urlFormat', 'nestedUrlFormat'), $newLocaleData); if (!$isNewSection) { // Drop any locales that are no longer being used, as well as the associated entry/element locale // rows $droppedLocaleIds = array_diff(array_keys($oldSectionLocales), array_keys($sectionLocales)); if ($droppedLocaleIds) { craft()->db->createCommand()->delete('sections_i18n', array('and', 'sectionId = :sectionId', array('in', 'locale', $droppedLocaleIds)), array(':sectionId' => $section->id)); } } // Make sure there's at least one entry type for this section $entryTypeId = null; if (!$isNewSection) { // Let's grab all of the entry type IDs to save ourselves a query down the road if this is a Single $entryTypeIds = craft()->db->createCommand()->select('id')->from('entrytypes')->where('sectionId = :sectionId', array(':sectionId' => $section->id))->queryColumn(); if ($entryTypeIds) { $entryTypeId = array_shift($entryTypeIds); } } if (!$entryTypeId) { $entryType = new EntryTypeModel(); $entryType->sectionId = $section->id; $entryType->name = $section->name; $entryType->handle = $section->handle; if ($section->type == SectionType::Single) { $entryType->hasTitleField = false; $entryType->titleLabel = null; $entryType->titleFormat = '{section.name|raw}'; } else { $entryType->hasTitleField = true; $entryType->titleLabel = Craft::t('Title'); $entryType->titleFormat = null; } $this->saveEntryType($entryType); $entryTypeId = $entryType->id; } // Now, regardless of whether the section type changed or not, let the section type make sure // everything is cool switch ($section->type) { case SectionType::Single: // Make sure that there is one and only one Entry Type and Entry for this section. $singleEntryId = null; if (!$isNewSection) { // Make sure there's only one entry in this section $entryIds = craft()->db->createCommand()->select('id')->from('entries')->where('sectionId = :sectionId', array(':sectionId' => $section->id))->queryColumn(); if ($entryIds) { $singleEntryId = array_shift($entryIds); // If there are any more, get rid of them if ($entryIds) { craft()->elements->deleteElementById($entryIds); } // Make sure it's enabled and all that. craft()->db->createCommand()->update('elements', array('enabled' => 1, 'archived' => 0), array('id' => $singleEntryId)); craft()->db->createCommand()->update('entries', array('typeId' => $entryTypeId, 'authorId' => null, 'postDate' => DateTimeHelper::currentTimeForDb(), 'expiryDate' => null), array('id' => $singleEntryId)); } // Make sure there's only one entry type for this section if ($entryTypeIds) { $this->deleteEntryTypeById($entryTypeIds); } } if (!$singleEntryId) { // Create it, baby $singleEntry = new EntryModel(); $singleEntry->locale = $firstSectionLocale->locale; $singleEntry->sectionId = $section->id; $singleEntry->typeId = $entryTypeId; $singleEntry->getContent()->title = $section->name; craft()->entries->saveEntry($singleEntry); } break; case SectionType::Structure: if (!$isNewSection && $isNewStructure) { // Add all of the entries to the structure $criteria = craft()->elements->getCriteria(ElementType::Entry); $criteria->locale = ArrayHelper::getFirstKey($oldSectionLocales); $criteria->sectionId = $section->id; $criteria->status = null; $criteria->localeEnabled = null; $criteria->order = 'elements.id'; $criteria->limit = 25; do { $batchEntries = $criteria->find(); foreach ($batchEntries as $entry) { craft()->structures->appendToRoot($section->structureId, $entry, 'insert'); } $criteria->offset += 25; } while ($batchEntries); } break; } // Finally, deal with the existing entries... if (!$isNewSection) { $criteria = craft()->elements->getCriteria(ElementType::Entry); // Get the most-primary locale that this section was already enabled in $locales = array_values(array_intersect(craft()->i18n->getSiteLocaleIds(), array_keys($oldSectionLocales))); if ($locales) { $criteria->locale = $locales[0]; $criteria->sectionId = $section->id; $criteria->status = null; $criteria->localeEnabled = null; $criteria->limit = null; craft()->tasks->createTask('ResaveElements', Craft::t('Resaving {section} entries', array('section' => $section->name)), array('elementType' => ElementType::Entry, 'criteria' => $criteria->getAttributes())); } } $success = true; } else { $success = false; } // Commit the transaction regardless of whether we saved the section, in case something changed // in onBeforeSaveSection if ($transaction !== null) { $transaction->commit(); } } catch (\Exception $e) { if ($transaction !== null) { $transaction->rollback(); } throw $e; } } else { $success = false; } if ($success) { // Fire an 'onSaveSection' event $this->onSaveSection(new Event($this, array('section' => $section, 'isNewSection' => $isNewSection))); } return $success; }
/** * 分类编辑页面 */ function edit() { //得到Get传来的Id $cate_id = $_GET['id']; $category = new CategoryModel(); //where语句 $where = array('id' => $cate_id); //获得分类表数据库数据 $list = $category->where($where)->find(); $this->assign('clist', $list); //获得单元表的所有单元 $sec = new SectionModel(); $list = $sec->select(); $this->assign('slist', $list); $this->display(); }