public function BlogTags()
    {
        if ($newsIndex = $this->NewsIndex()) {
            $alRet = new ArrayList();
            $arrTags = array();
            $strTable = Versioned::current_stage() == 'Stage' ? 'NewsPost' : 'NewsPost_Live';
            $results = DB::query('SELECT `Tags` AS Tags, COUNT(1) AS Items
				FROM ' . $strTable . '
				WHERE `Tags` IS NOT NULL
				GROUP BY Tags');
            while ($row = $results->nextRecord()) {
                $arrCurrentItems = explode(',', $row['Tags']);
                foreach ($arrCurrentItems as $strItem) {
                    $strItem = trim($strItem);
                    $strLower = strtolower($strItem);
                    if (!array_key_exists($strLower, $arrTags)) {
                        $arrTags[$strLower] = new ArrayData(array('Tag' => $strItem, 'Count' => $row['Items'], 'Link' => $newsIndex->Link('tag/' . urlencode($strItem))));
                    } else {
                        $arrayData = $arrTags[$strLower];
                        $arrayData->Count += $row['Items'];
                    }
                }
            }
            foreach ($arrTags as $arrTag) {
                $alRet->push($arrTag);
            }
            return $alRet->sort('Count')->limit(SiteConfig::current_site_config()->NumberOfTags ?: PHP_INT_MAX);
        }
    }
 public function onBeforeInit()
 {
     // Determine if this page is of a non-cacheable type
     $ignoredClasses = DynamicCache::config()->ignoredPages;
     $ignoredByClass = false;
     if ($ignoredClasses) {
         foreach ($ignoredClasses as $ignoredClass) {
             if (is_a($this->owner->data(), $ignoredClass, true)) {
                 $ignoredByClass = true;
                 break;
             }
         }
     }
     $isStage = ($stage = Versioned::current_stage()) && $stage !== 'Live';
     // Set header disabling caching if
     // - current page is an ignored page type
     // - current_stage is not live
     if ($ignoredByClass || $isStage) {
         $header = DynamicCache::config()->optOutHeaderString;
         header($header);
     }
     // Flush cache if requested
     if (isset($_GET['flush']) || isset($_GET['cache']) && $_GET['cache'] === 'flush' && Permission::check('ADMIN')) {
         DynamicCache::inst()->clear();
     }
 }
 /**
  * Augment queries so that we don't fetch unpublished articles.
  **/
 public function augmentSQL(SQLQuery &$query)
 {
     $stage = Versioned::current_stage();
     if ($stage == 'Live' || !Permission::check("VIEW_DRAFT_CONTENT")) {
         $query->addWhere("PublishDate < '" . Convert::raw2sql(SS_Datetime::now()) . "'");
     }
 }
 /**
  * Provides a front-end utility menu with administrative functions and developer tools
  * Relies on SilverStripeNavigator
  * 
  * @return string
  */
 public function BetterNavigator()
 {
     $isDev = Director::isDev();
     if ($isDev || Permission::check('CMS_ACCESS_CMSMain') || Permission::check('VIEW_DRAFT_CONTENT')) {
         if ($this->owner && $this->owner->dataRecord) {
             //Get SilverStripeNavigator links & stage info (CMS/Stage/Live/Archive)
             $nav = array();
             $navigator = new SilverStripeNavigator($this->owner->dataRecord);
             $items = $navigator->getItems();
             foreach ($items as $item) {
                 $nav[$item->getName()] = array('Link' => $item->getLink(), 'Active' => $item->isActive());
             }
             //Is the logged in member nominated as a developer?
             $member = Member::currentUser();
             $devs = Config::inst()->get('BetterNavigator', 'developers');
             $isDeveloper = $member && is_array($devs) ? in_array($member->Email, $devs) : false;
             //Add other data for template
             $nav = array_merge($nav, array('Member' => $member, 'Stage' => Versioned::current_stage(), 'LoginLink' => Config::inst()->get('Security', 'login_url'), 'Mode' => Director::get_environment_type(), 'IsDeveloper' => $isDeveloper));
             //Merge with page data, send to template and render
             $nav = new ArrayData($nav);
             $page = $this->owner->customise($nav);
             return $page->renderWith('BetterNavigator');
         }
     }
     return false;
 }
 /**
  * Return an ArrayList of pages with the Element Page Extension
  *
  * @return ArrayList
  */
 public function getOwnerPage()
 {
     $originalMode = Versioned::current_stage();
     Versioned::reading_stage('Stage');
     foreach (get_declared_classes() as $class) {
         if (is_subclass_of($class, 'SiteTree')) {
             $object = singleton($class);
             $classes = ClassInfo::subclassesFor('ElementPageExtension');
             $isElemental = false;
             foreach ($classes as $extension) {
                 if ($object->hasExtension($extension)) {
                     $isElemental = true;
                 }
             }
             if ($isElemental) {
                 $page = $class::get()->filter('ElementAreaID', $this->ID);
                 if ($page && $page->exists()) {
                     Versioned::reading_stage($originalMode);
                     return $page->first();
                 }
             }
         }
     }
     Versioned::reading_stage($originalMode);
     return false;
 }
 public function updateDynamicListCMSFields($fields)
 {
     // Make sure the draft records are being looked at.
     $stage = Versioned::current_stage();
     Versioned::reading_stage('Stage');
     $used = EditableFormField::get()->filter(array('ClassName:PartialMatch' => 'DynamicList'));
     // Determine whether this dynamic list is being used anywhere.
     $found = array();
     foreach ($used as $field) {
         // This information is stored using a serialised list, therefore we need to iterate through.
         if ($field->getSetting('ListTitle') === $this->owner->Title) {
             // Make sure there are no duplicates recorded.
             if (!isset($found[$field->ParentID]) && ($form = UserDefinedForm::get()->byID($field->ParentID))) {
                 $found[$field->ParentID] = "<a href='{$form->CMSEditLink()}'>{$form->Title}</a>";
             }
         }
     }
     // Display whether there were any dynamic lists found on user defined forms.
     if (count($found)) {
         $fields->removeByName('UsedOnHeader');
         $fields->addFieldToTab('Root.Main', HeaderField::create('UsedOnHeader', 'Used On', 5));
     }
     $display = count($found) ? implode('<br>', $found) : 'This dynamic list is <strong>not</strong> used.';
     $fields->removeByName('UsedOn');
     $fields->addFieldToTab('Root.Main', LiteralField::create('UsedOn', '<div>' . $display . '</div>'));
     Versioned::reading_stage($stage);
 }
Ejemplo n.º 7
0
 protected function findOldPage($urlSegment)
 {
     // Build the query by  replacing `SiteTree` with `SiteTree_versions` in a regular query.
     // Note that this should *really* be handled by a more full-featured data mapper; as it stands
     // this is a bit of a hack.
     $origStage = Versioned::current_stage();
     Versioned::reading_stage('Stage');
     $versionedQuery = singleton('SiteTree')->extendedSQL('');
     Versioned::reading_stage($origStage);
     foreach ($versionedQuery->from as $k => $v) {
         $versionedQuery->renameTable($k, $k . '_versions');
     }
     $versionedQuery->select = array("`SiteTree_versions`.RecordID");
     $versionedQuery->where[] = "`SiteTree_versions`.`WasPublished` = 1 AND `URLSegment` = '{$urlSegment}'";
     $versionedQuery->orderby = '`LastEdited` DESC, `SiteTree_versions`.`WasPublished`';
     $versionedQuery->limit = 1;
     $result = $versionedQuery->execute();
     if ($result->numRecords() == 1 && ($redirectPage = $result->nextRecord())) {
         $redirectObj = DataObject::get_by_id('SiteTree', $redirectPage['RecordID']);
         if ($redirectObj) {
             // Double-check by querying this page in the same way that getNestedController() does.  This
             // will prevent query muck-ups from modules such as subsites
             $doubleCheck = SiteTree::get_by_url($redirectObj->URLSegment);
             if ($doubleCheck) {
                 return $redirectObj;
             }
         }
     }
     return false;
 }
 /**
  * 
  * Initialises a pre-built cache (via {@link CacheableNavigation_Rebuild})
  * used by front-end calling logic e.g. via $CachedData blocks in .ss templates
  * unless build_on_reload is set to false in YML config.
  * 
  * Called using SilverStripe's extend() method in {@link ContentController}.
  * 
  * @param Controller $controller
  * @return void
  * @see {@link CacheableNavigation_Rebuild}.
  * @see {@link CacheableNavigation_Clean}.
  * @todo add queuedjob chunking ala BuildTask to this csche-rebuild logic.
  * At the moment we attempt to skip it if build_cache_onload is set to false 
  * in YML Config
  */
 public function contentControllerInit($controller)
 {
     // Skip if flushing or the project instructs us to do so
     $skip = self::is_flush($controller) || !self::build_cache_onload();
     $service = new CacheableNavigationService();
     $currentStage = Versioned::current_stage();
     $stage_mode_mapping = array("Stage" => "stage", "Live" => "live");
     $service->set_mode($stage_mode_mapping[$currentStage]);
     $siteConfig = SiteConfig::current_site_config();
     if (!$siteConfig->exists()) {
         $siteConfig = $this->owner->getSiteConfig();
     }
     $service->set_config($siteConfig);
     if ($_cached_navigation = $service->getCacheableFrontEnd()->load($service->getIdentifier())) {
         if (!$skip && !$_cached_navigation->get_completed()) {
             $service->refreshCachedConfig();
             if (class_exists('Subsite')) {
                 $pages = DataObject::get("Page", "\"SubsiteID\" = '" . $siteConfig->SubsiteID . "'");
             } else {
                 $pages = DataObject::get("Page");
             }
             if ($pages->exists()) {
                 foreach ($pages as $page) {
                     $service->set_model($page);
                     $service->refreshCachedPage(true);
                 }
             }
             $service->completeBuild();
             $_cached_navigation = $service->getCacheableFrontEnd()->load($service->getIdentifier());
         }
         Config::inst()->update('Cacheable', '_cached_navigation', $_cached_navigation);
     }
 }
 /**
  * Helper method to get content languages from the live DB table.
  * Most of the code is borrowed from the Translatable::get_live_content_languages method.
  * This method operates on "SiteTree" and makes a distinction between Live and Stage.
  * @return array
  */
 public static function get_content_languages()
 {
     $table = Versioned::current_stage() == 'Live' ? 'SiteTree_Live' : 'SiteTree';
     if (class_exists('SQLSelect')) {
         $query = new SQLSelect("Distinct \"Locale\"", "\"{$table}\"");
     } else {
         // SS 3.1 compat
         $query = new SQLQuery("Distinct \"Locale\"", array("\"{$table}\""));
     }
     $query = $query->setGroupBy('"Locale"');
     $dbLangs = $query->execute()->column();
     $langlist = array_merge((array) Translatable::default_locale(), (array) $dbLangs);
     $returnMap = array();
     $allCodes = array_merge(Config::inst()->get('i18n', 'all_locales'), Config::inst()->get('i18n', 'common_locales'));
     foreach ($langlist as $langCode) {
         if ($langCode && isset($allCodes[$langCode])) {
             if (is_array($allCodes[$langCode])) {
                 $returnMap[$langCode] = $allCodes[$langCode]['name'];
             } else {
                 $returnMap[$langCode] = $allCodes[$langCode];
             }
         }
     }
     return $returnMap;
 }
 public function check(Discount $discount)
 {
     $products = $discount->Products();
     // if no products in the discount even
     if (!$products->exists()) {
         $curr = Versioned::current_stage();
         Versioned::reading_stage('Stage');
         $products = $discount->Products();
         if (!$products->exists()) {
             return true;
         }
         $constraintproductids = $products->map('ID', 'ID')->toArray();
         Versioned::reading_stage($curr);
     } else {
         $constraintproductids = $products->map('ID', 'ID')->toArray();
     }
     // uses 'DiscountedProductID' so that subclasses of projects (say a custom nested set of products) can define the
     // underlying DiscountedProductID.
     $cartproductids = $this->order->Items()->map('ProductID', 'DiscountedProductID')->toArray();
     $intersection = array_intersect($constraintproductids, $cartproductids);
     $incart = $discount->ExactProducts ? array_values($constraintproductids) === array_values($intersection) : count($intersection) > 0;
     if (!$incart) {
         $this->error(_t('ProductsDiscountConstraint.MISSINGPRODUCT', "The required products are not in the cart."));
     }
     return $incart;
 }
 /**
  * SSCompactNavigator first checks if you are allowed to see the navigation bar, and if so, then checks
  * if third party templates have been specified. If so, it loads them, and provides them with the required
  * variables. If not, it loads the defaults instead.
  */
 public function SSCompactNavigator()
 {
     if (Director::isDev() || Permission::check('CMS_ACCESS_CMSMain')) {
         $RenderTemplate = isset(CompactNavigator::$Template) ? CompactNavigator::$Template : $this->class;
         if (isset(CompactNavigator::$CssTheme)) {
             Requirements::css(CompactNavigator::$CssTheme);
         } else {
             Requirements::css('compactnavigator/css/CompactNavigator.css');
         }
         if (isset(CompactNavigator::$JsTheme)) {
             Requirements::javascript(CompactNavigator::$JsTheme);
         } else {
             Requirements::javascript('compactnavigator/scripts/CompactNavigator.js');
         }
         if (class_exists("CMSMain")) {
             $this->owner->cmsLink = Controller::join_links(singleton("CMSMain")->Link("edit"), "show");
         }
         $this->owner->adminLink = self::$adminLink;
         if ($date = Versioned::current_archived_date()) {
             $this->owner->DisplayMode = 'Archived';
             $this->owner->ArDate = Object::create('Datetime', $date, null);
         } else {
             $this->owner->DisplayMode = Versioned::current_stage();
         }
         return $this->owner->renderWith(array($RenderTemplate, 'CompactNavigatior'));
     }
 }
Ejemplo n.º 12
0
 function Dates()
 {
     Requirements::themedCSS('archivewidget');
     $results = new DataObjectSet();
     $container = BlogTree::current();
     $ids = $container->BlogHolderIDs();
     $stage = Versioned::current_stage();
     $suffix = !$stage || $stage == 'Stage' ? "" : "_{$stage}";
     $monthclause = method_exists(DB::getConn(), 'formattedDatetimeClause') ? DB::getConn()->formattedDatetimeClause('"Date"', '%m') : 'MONTH("Date")';
     $yearclause = method_exists(DB::getConn(), 'formattedDatetimeClause') ? DB::getConn()->formattedDatetimeClause('"Date"', '%Y') : 'YEAR("Date")';
     if ($this->DisplayMode == 'month') {
         $sqlResults = DB::query("\n\t\t\t\tSELECT DISTINCT CAST({$monthclause} AS " . DB::getConn()->dbDataType('unsigned integer') . ") AS \"Month\", {$yearclause} AS \"Year\"\n\t\t\t\tFROM \"SiteTree{$suffix}\" INNER JOIN \"BlogEntry{$suffix}\" ON \"SiteTree{$suffix}\".\"ID\" = \"BlogEntry{$suffix}\".\"ID\"\n\t\t\t\tWHERE \"ParentID\" IN (" . implode(', ', $ids) . ")\n\t\t\t\tORDER BY \"Year\" DESC, \"Month\" DESC;");
     } else {
         $sqlResults = DB::query("\n\t\t\t\tSELECT DISTINCT {$yearclause} AS \"Year\" \n\t\t\t\tFROM \"SiteTree{$suffix}\" INNER JOIN \"BlogEntry{$suffix}\" ON \"SiteTree{$suffix}\".\"ID\" = \"BlogEntry{$suffix}\".\"ID\"\n\t\t\t\tWHERE \"ParentID\" IN (" . implode(', ', $ids) . ")\n\t\t\t\tORDER BY \"Year\" DESC");
     }
     if ($sqlResults) {
         foreach ($sqlResults as $sqlResult) {
             $isMonthDisplay = $this->DisplayMode == 'month';
             $monthVal = isset($sqlResult['Month']) ? (int) $sqlResult['Month'] : 1;
             $month = $isMonthDisplay ? $monthVal : 1;
             $year = $sqlResult['Year'] ? (int) $sqlResult['Year'] : date('Y');
             $date = DBField::create('Date', array('Day' => 1, 'Month' => $month, 'Year' => $year));
             if ($isMonthDisplay) {
                 $link = $container->Link('date') . '/' . $sqlResult['Year'] . '/' . sprintf("%'02d", $monthVal);
             } else {
                 $link = $container->Link('date') . '/' . $sqlResult['Year'];
             }
             $results->push(new ArrayData(array('Date' => $date, 'Link' => $link)));
         }
     }
     return $results;
 }
 /**
  * This returns the workflow requests outstanding for this user.
  * It does one query against draft for change requests, and another
  * request against live for the deletion requests (which are not in draft
  * any more), and merges the result sets together.
  */
 function sourceRecords($params)
 {
     increase_time_limit_to(120);
     $currentStage = Versioned::current_stage();
     $changes = WorkflowTwoStepRequest::get_by_author('WorkflowPublicationRequest', Member::currentUser(), array('AwaitingApproval'));
     if ($changes) {
         foreach ($changes as $change) {
             $change->RequestType = "Publish";
         }
     }
     Versioned::reading_stage(Versioned::get_live_stage());
     $deletions = WorkflowTwoStepRequest::get_by_author('WorkflowDeletionRequest', Member::currentUser(), array('AwaitingApproval'));
     if ($deletions) {
         foreach ($deletions as $deletion) {
             $deletion->RequestType = "Deletion";
         }
     }
     if ($changes && $deletions) {
         $changes->merge($deletions);
     } else {
         if ($deletions) {
             $changes = $deletions;
         }
     }
     return $changes;
 }
Ejemplo n.º 14
0
 /**
  * When an error page is published, create a static HTML page with its
  * content, so the page can be shown even when SilverStripe is not
  * functioning correctly before publishing this page normally.
  * @param string|int $fromStage Place to copy from. Can be either a stage name or a version number.
  * @param string $toStage Place to copy to. Must be a stage name.
  * @param boolean $createNewVersion Set this to true to create a new version number.  By default, the existing version number will be copied over.
  */
 function publish($fromStage, $toStage, $createNewVersion = false)
 {
     // Temporarily log out when producing this page
     $loggedInMember = Member::currentUser();
     Session::clear("loggedInAs");
     $alc_enc = isset($_COOKIE['alc_enc']) ? $_COOKIE['alc_enc'] : null;
     Cookie::set('alc_enc', null);
     $oldStage = Versioned::current_stage();
     // Run the page
     Requirements::clear();
     $controller = new ErrorPage_Controller($this);
     $errorContent = $controller->run(array())->getBody();
     if (!file_exists("../assets")) {
         mkdir("../assets", 02775);
     }
     if ($fh = fopen("../assets/error-{$this->ErrorCode}.html", "w")) {
         fwrite($fh, $errorContent);
         fclose($fh);
     }
     // Restore the version we're currently connected to.
     Versioned::reading_stage($oldStage);
     // Log back in
     if ($loggedInMember) {
         Session::set("loggedInAs", $loggedInMember->ID);
     }
     if (isset($alc_enc)) {
         Cookie::set('alc_enc', $alc_enc);
     }
     return $this->extension_instances['Versioned']->publish($fromStage, $toStage, $createNewVersion);
 }
 public function onBeforeWrite()
 {
     parent::onBeforeWrite();
     // only operate on staging content
     if (Versioned::current_stage() != 'Live') {
         if (strlen($this->owner->PublishOnDate)) {
             $changed = $this->owner->getChangedFields();
             $changed = isset($changed['PublishOnDate']);
             if ($changed && $this->owner->PublishJobID) {
                 if ($this->owner->PublishJob()->exists()) {
                     $this->owner->PublishJob()->delete();
                 }
                 $this->owner->PublishJobID = 0;
             }
             if (!$this->owner->PublishJobID && strtotime($this->owner->PublishOnDate) > time()) {
                 $job = new WorkflowPublishTargetJob($this->owner, 'publish');
                 $this->owner->PublishJobID = singleton('QueuedJobService')->queueJob($job, $this->owner->PublishOnDate);
             }
         }
         if (strlen($this->owner->UnPublishOnDate)) {
             $changed = $this->owner->getChangedFields();
             $changed = isset($changed['UnPublishOnDate']);
             if ($changed && $this->owner->UnPublishJobID) {
                 if ($this->owner->UnPublishJob()->exists()) {
                     $this->owner->UnPublishJob()->delete();
                 }
                 $this->owner->UnPublishJobID = 0;
             }
             if (!$this->owner->UnPublishJobID && strtotime($this->owner->UnPublishOnDate) > time()) {
                 $job = new WorkflowPublishTargetJob($this->owner, 'unpublish');
                 $this->owner->UnPublishJobID = singleton('QueuedJobService')->queueJob($job, $this->owner->UnPublishOnDate);
             }
         }
     }
 }
 function Dates()
 {
     Requirements::themedCSS('archivewidget');
     $results = new DataObjectSet();
     $container = BlogTree::current();
     $ids = $container->BlogHolderIDs();
     $stage = Versioned::current_stage();
     $suffix = !$stage || $stage == 'Stage' ? "" : "_{$stage}";
     $monthclause = method_exists(DB::getConn(), 'formattedDatetimeClause') ? DB::getConn()->formattedDatetimeClause('"Date"', '%m') : 'MONTH("Date")';
     $yearclause = method_exists(DB::getConn(), 'formattedDatetimeClause') ? DB::getConn()->formattedDatetimeClause('"Date"', '%Y') : 'YEAR("Date")';
     $sqlResults = DB::query("\n\t\t\tSELECT DISTINCT CAST({$monthclause} AS " . DB::getConn()->dbDataType('unsigned integer') . ") AS \"Month\", {$yearclause} AS \"Year\"\n\t\t\tFROM \"SiteTree{$suffix}\" INNER JOIN \"BlogEntry{$suffix}\" ON \"SiteTree{$suffix}\".\"ID\" = \"BlogEntry{$suffix}\".\"ID\"\n\t\t\tWHERE \"ParentID\" IN (" . implode(', ', $ids) . ")\n\t\t\tORDER BY \"Year\" DESC, \"Month\" DESC;");
     if ($this->ShowLastYears == 0) {
         $cutOffYear = 0;
     } else {
         $cutOffYear = (int) date("Y") - $this->ShowLastYears;
     }
     $years = array();
     if (Director::get_current_page()->ClassName == 'BlogHolder') {
         $urlParams = Director::urlParams();
         $yearParam = $urlParams['ID'];
         $monthParam = $urlParams['OtherID'];
     } else {
         $date = new DateTime(Director::get_current_page()->Date);
         $yearParam = $date->format("Y");
         $monthParam = $date->format("m");
     }
     if ($sqlResults) {
         foreach ($sqlResults as $sqlResult) {
             $isMonthDisplay = true;
             $year = $sqlResult['Year'] ? (int) $sqlResult['Year'] : date('Y');
             $isMonthDisplay = $year > $cutOffYear;
             // $dateFormat = 'Month'; else $dateFormat = 'Year';
             $monthVal = isset($sqlResult['Month']) ? (int) $sqlResult['Month'] : 1;
             $month = $isMonthDisplay ? $monthVal : 1;
             $date = DBField::create('Date', array('Day' => 1, 'Month' => $month, 'Year' => $year));
             if ($isMonthDisplay) {
                 $link = $container->Link('date') . '/' . $sqlResult['Year'] . '/' . sprintf("%'02d", $monthVal);
             } else {
                 $link = $container->Link('date') . '/' . $sqlResult['Year'];
             }
             if ($isMonthDisplay || !$isMonthDisplay && !in_array($year, $years)) {
                 $years[] = $year;
                 $current = false;
                 $children = new DataObjectSet();
                 $LinkingMode = "link";
                 if ($isMonthDisplay && $yearParam == $year && $monthParam == $month || !$isMonthDisplay && $yearParam == $year) {
                     $LinkingMode = "current";
                     $current = true;
                     if ($this->ShowChildren && $isMonthDisplay) {
                         $filter = $yearclause . ' = ' . $year . ' AND ' . $monthclause . ' = ' . $month;
                         $children = DataObject::get('BlogEntry', $filter, "Date DESC");
                     }
                 }
                 $results->push(new ArrayData(array('Date' => $date, 'Year' => $year, 'Link' => $link, 'NoMonth' => !$isMonthDisplay, 'LinkingMode' => $LinkingMode, 'Children' => $children)));
                 unset($children);
             }
         }
     }
     return $results;
 }
 public static function get_navbar_html($page = null)
 {
     // remove the protocol from the URL, otherwise we run into https/http issues
     $url = self::remove_protocol_from_url(self::get_toolbar_hostname());
     $static = true;
     if (!$page instanceof SiteTree) {
         $page = Director::get_current_page();
         $static = false;
     }
     // In some cases, controllers are bound to "mock" pages, like Security. In that case,
     // throw the "default section" as the current controller.
     if (!$page instanceof SiteTree || !$page->isInDB()) {
         $controller = ModelAsController::controller_for($page = SiteTree::get_by_link(Config::inst()->get('GlobalNav', 'default_section')));
     } else {
         // Use controller_for to negotiate sub controllers, e.g. /showcase/listing/slug
         // (Controller::curr() would return the nested RequestHandler)
         $controller = ModelAsController::controller_for($page);
     }
     // Ensure staging links are not exported to the nav
     $origStage = Versioned::current_stage();
     Versioned::reading_stage('Live');
     $html = ViewableData::create()->customise(array('ToolbarHostname' => $url, 'Scope' => $controller, 'ActivePage' => $page, 'ActiveParent' => $page instanceof SiteTree && $page->Parent()->exists() ? $page->Parent() : $page, 'StaticRender' => $static, 'GoogleCustomSearchId' => Config::inst()->get('GlobalNav', 'google_search_id')))->renderWith('GlobalNavbar');
     Versioned::reading_stage($origStage);
     return $html;
 }
Ejemplo n.º 18
0
 public function getActiveHomePageBlocks()
 {
     $blocks = $this->data()->HomePageBlocks();
     if (Versioned::current_stage() === 'Live') {
         $blocks = $blocks->filter('IsActive', 1);
     }
     return $blocks;
 }
 public function index()
 {
     if (Versioned::current_stage() == 'Stage') {
         $this->redirect($this->data()->Link() . '?stage=Live');
         return;
     }
     return array();
 }
 public function onBeforeInit()
 {
     // If not on live site, set header disabling caching to prevent caching of draft content
     if (($stage = Versioned::current_stage()) && $stage !== 'Live') {
         $header = DynamicCache::config()->optOutHeaderString;
         header($header);
     }
 }
 public function onBeforeWrite()
 {
     parent::onBeforeWrite();
     if (!$this->Title) {
         $this->Title = Config::inst()->get($this->class, 'title');
     }
     if (Widget::has_extension('Versioned') && Versioned::current_stage() == 'Stage') {
         $this->publishAfterWrite = true;
     }
 }
 /**
  * Augment queries so that we don't fetch unpublished articles.
  *
  * @param SQLQuery $query
  */
 public function augmentSQL(SQLQuery &$query)
 {
     $stage = Versioned::current_stage();
     if (Controller::curr() instanceof LeftAndMain) {
         return;
     }
     if ($stage == 'Live' || !Permission::check('VIEW_DRAFT_CONTENT')) {
         $query->addWhere(sprintf('"PublishDate" < \'%s\'', Convert::raw2sql(SS_Datetime::now())));
     }
 }
 public function BusinessList()
 {
     $array = $this->getChildIDs();
     if ($array && count($array)) {
         $extension = '';
         if (Versioned::current_stage() == "Live") {
             $extension = "_Live";
         }
         return DataObject::get("BusinessPage", "\"SiteTree{$extension}\".\"ID\" IN (" . implode(",", $array) . ")");
     }
 }
 /**
  * Returns all events unfiltered.
  * @return DataList
  */
 public function getItems()
 {
     $itemClass = $this->stat('item_class');
     $items = $itemClass::get();
     //move it to an extension?
     if (Versioned::current_stage() === 'Live') {
         $items = $items->filter('IsActive', 1);
     }
     $this->extend('updateGetItems', $items);
     return $items;
 }
 public function onBeforeDelete()
 {
     if (Widget::has_extension('Versioned')) {
         $currentStage = Versioned::current_stage();
         Versioned::reading_stage('Stage');
         parent::onBeforeDelete();
         Versioned::reading_stage('Live');
         parent::onBeforeDelete();
         Versioned::reading_stage($currentStage);
     } else {
         parent::onBeforeDelete();
     }
 }
Ejemplo n.º 26
0
 /**
  * {@inheritdoc}
  */
 public function stageChildren($showAll = false)
 {
     $staged = parent::stageChildren($showAll);
     if (!$this->shouldFilter() && $this->subclassForBlog() && !Permission::check('VIEW_DRAFT_CONTENT')) {
         $stage = Versioned::current_stage();
         if ($stage == 'Stage') {
             $stage = '';
         } elseif ($stage) {
             $stage = '_' . $stage;
         }
         $dataQuery = $staged->dataQuery()->innerJoin('BlogPost', sprintf('"BlogPost%s"."ID" = "SiteTree%s"."ID"', $stage, $stage))->where(sprintf('"PublishDate" < \'%s\'', Convert::raw2sql(SS_Datetime::now())));
         $staged = $staged->setDataQuery($dataQuery);
     }
     return $staged;
 }
Ejemplo n.º 27
0
 public function ArchiveDates()
 {
     $list = ArrayList::create();
     $stage = Versioned::current_stage();
     $query = new SQLQuery(array());
     $query->selectField("DATE_FORMAT(`Date`,'%Y_%M_%m')", "DateString")->setFrom("ArticlePage_{$stage}")->setOrderBy("Date", "ASC")->setDistinct(true);
     $result = $query->execute();
     if ($result) {
         while ($record = $result->nextRecord()) {
             list($year, $monthName, $monthNumber) = explode('_', $record['DateString']);
             $list->push(ArrayData::create(array('Year' => $year, 'MonthName' => $monthName, 'MonthNumber' => $monthNumber, 'Link' => $this->Link("date/{$year}/{$monthNumber}"), 'ArticleCount' => ArticlePage::get()->where("\n\t\t\t\t\t\t\tDATE_FORMAT(`Date`,'%Y%m') = '{$year}{$monthNumber}'\n\t\t\t\t\t\t\tAND ParentID = {$this->ID}\n\t\t\t\t\t\t")->count())));
         }
     }
     return $list;
 }
Ejemplo n.º 28
0
 /**
  * Confirm that DataObject::get_one() gets records from SiteTree_Live
  */
 function testGetOneFromLive()
 {
     $s = new SiteTree();
     $s->Title = "V1";
     $s->URLSegment = "get-one-test-page";
     $s->write();
     $s->publish("Stage", "Live");
     $s->Title = "V2";
     $s->write();
     $oldStage = Versioned::current_stage();
     Versioned::reading_stage('Live');
     $checkSiteTree = DataObject::get_one("SiteTree", "URLSegment = 'get-one-test-page'");
     $this->assertEquals("V1", $checkSiteTree->Title);
     Versioned::reading_stage($oldStage);
 }
 public function createDashboard($name, $createDefault = false)
 {
     $url = preg_replace('/ +/', '-', trim($name));
     // Replace any spaces
     $url = preg_replace('/[^A-Za-z0-9.+_\\-]/', '', $url);
     // Replace non alphanumeric characters
     $url = strtolower($url);
     $existing = $this->getNamedDashboard($url);
     if ($existing) {
         return $existing;
     }
     $dashboard = new DashboardPage();
     $dashboard->URLSegment = $url;
     $dashboard->Title = trim($name);
     $dashboard->OwnerID = $this->owner->ID;
     $dashboard->write();
     if ($createDefault) {
         $currentStage = null;
         if (Widget::has_extension('Versioned')) {
             $currentStage = Versioned::current_stage();
             Versioned::reading_stage('Stage');
         }
         $layout = Config::inst()->get('DashboardUser', 'default_layout');
         if (count($layout)) {
             foreach ($layout as $type => $properties) {
                 if (class_exists($type)) {
                     $dashlet = $type::create();
                     /* @var $dashlet Dashlet */
                     $dashletColumn = isset($properties['DashletColumn']) ? $properties['DashletColumn'] : 0;
                     $db = $dashboard->getDashboard($dashletColumn);
                     if ($db && $dashlet->canCreate()) {
                         $dashlet->ParentID = $db->ID;
                         if (is_array($properties)) {
                             $dashlet->update($properties);
                         }
                         $dashlet->write();
                     }
                 }
             }
         }
         if ($currentStage) {
             Versioned::reading_stage($currentStage);
         }
         $dashboard = $this->getNamedDashboard($url);
         $this->owner->extend('updateCreatedDashboard', $dashboard);
     }
     return $dashboard;
 }
 /**
  * Provides a front-end utility menu with administrative functions and developer tools
  * Relies on SilverStripeNavigator
  *
  * @return string
  */
 public function BetterNavigator()
 {
     // Make sure this is a page
     if (!($this->owner && $this->owner->dataRecord && $this->owner->dataRecord instanceof SiteTree && $this->owner->dataRecord->ID > 0)) {
         return false;
     }
     // Only show navigator to appropriate users
     $isDev = Director::isDev();
     $canViewDraft = Permission::check('VIEW_DRAFT_CONTENT') || Permission::check('CMS_ACCESS_CMSMain');
     if ($isDev || $canViewDraft) {
         // Get SilverStripeNavigator links & stage info (CMS/Stage/Live/Archive)
         $nav = array();
         $viewing = '';
         $navigator = new SilverStripeNavigator($this->owner->dataRecord);
         $items = $navigator->getItems();
         foreach ($items as $item) {
             $name = $item->getName();
             $active = $item->isActive();
             $nav[$name] = array('Link' => $item->getLink(), 'Active' => $active);
             if ($active) {
                 if ($name == 'LiveLink') {
                     $viewing = 'Live';
                 }
                 if ($name == 'StageLink') {
                     $viewing = 'Draft';
                 }
                 if ($name == 'ArchiveLink') {
                     $viewing = 'Archived';
                 }
             }
         }
         // Only show edit link if user has permission to edit this page
         $editLink = $this->owner->dataRecord->canEdit() && Permission::check('CMS_ACCESS_CMSMain') || $isDev ? $nav['CMSLink']['Link'] : false;
         // Is the logged in member nominated as a developer?
         $member = Member::currentUser();
         $devs = Config::inst()->get('BetterNavigator', 'developers');
         $identifierField = Member::config()->unique_identifier_field;
         $isDeveloper = $member && is_array($devs) ? in_array($member->{$identifierField}, $devs) : false;
         // Add other data for template
         $backURL = '?BackURL=' . urlencode($this->owner->Link());
         $bNData = array_merge($nav, array('Member' => $member, 'Stage' => Versioned::current_stage(), 'Viewing' => $viewing, 'LoginLink' => Config::inst()->get('Security', 'login_url') . $backURL, 'LogoutLink' => 'Security/logout' . $backURL, 'EditLink' => $editLink, 'Mode' => Director::get_environment_type(), 'IsDeveloper' => $isDeveloper));
         // Merge with page data, send to template and render
         $bNData = new ArrayData($bNData);
         $page = $this->owner->customise(array('BetterNavigator' => $bNData));
         return $page->renderWith('BetterNavigator');
     }
     return false;
 }