public static function parse_flickr($arguments, $caption = null, $parser = null)
 {
     // first things first, if we dont have a video ID, then we don't need to
     // go any further
     if (empty($arguments['id'])) {
         return;
     }
     $customise = array();
     /*** SET DEFAULTS ***/
     $fp = DataList::create('FlickrPhoto')->where('FlickrID=' . $arguments['id'])->first();
     if (!$fp) {
         return '';
     }
     $customise['FlickrImage'] = $fp;
     //set the caption
     if ($caption === null || $caption === '') {
         if (isset($arguments['caption'])) {
             $caption = $arguments['caption'];
         }
     }
     $customise['Caption'] = $caption ? Convert::raw2xml($caption) : $fp->Title;
     $customise['Position'] = !empty($arguments['position']) ? $arguments['position'] : 'center';
     $customise['Small'] = true;
     if ($customise['Position'] == 'center') {
         $customise['Small'] = false;
     }
     $fp = null;
     //overide the defaults with the arguments supplied
     $customise = array_merge($customise, $arguments);
     //get our YouTube template
     $template = new SSViewer('ShortCodeFlickrPhoto');
     //return the customised template
     return $template->process(new ArrayData($customise));
 }
 /**
  * Modified version of Breadcrumbs, to cater for viewing items.
  */
 public function Breadcrumbs($maxDepth = 20, $unlinked = false, $stopAtPageType = false, $showHidden = false)
 {
     $page = $this;
     $pages = array();
     while ($page && (!$maxDepth || count($pages) < $maxDepth) && (!$stopAtPageType || $page->ClassName != $stopAtPageType)) {
         if ($showHidden || $page->ShowInMenus || $page->ID == $this->ID) {
             $pages[] = $page;
         }
         $page = $page->Parent;
     }
     // Add on the item we're currently showing.
     $controller = Controller::curr();
     if ($controller) {
         $request = $controller->getRequest();
         if ($request->param('Action') == 'show') {
             $id = $request->param('ID');
             if ($id) {
                 $object = DataObject::get_by_id($this->getDataClass(), $id);
                 array_unshift($pages, $object);
             }
         }
     }
     $template = new SSViewer('BreadcrumbsTemplate');
     return $template->process($this->customise(new ArrayData(array('Pages' => new ArrayList(array_reverse($pages))))));
 }
 /**
  * 
  * @param SS_HTTPRequest $request
  */
 public function run($request)
 {
     $cacheBaseDir = singleton('FilesystemPublisher')->getDestDir();
     // First generate the search file for the base site
     $viewer = new SSViewer(array('StaticSearchJSON'));
     $item = new ViewableData($this);
     $json = $viewer->process($this->getAllLivePages(0));
     $domain = Config::inst()->get('FilesystemPublisher', 'static_base_url');
     $urlFragments = parse_url($domain);
     $cacheDir = $cacheBaseDir . "/" . $urlFragments['host'];
     file_put_contents($cacheDir . '/search_index.html', $json);
     if (class_exists('Subsite')) {
         // Then generate the files for the subsites
         $subsites = Subsite::all_sites();
         foreach ($subsites as $subsite) {
             $viewer = new SSViewer(array('StaticSearchJSON'));
             $item = new ViewableData($this);
             $json = $viewer->process($this->getAllLivePages($subsite->ID));
             $domains = DataObject::get("SubsiteDomain")->filter(array("SubsiteID" => $subsite->ID));
             foreach ($domains as $domain) {
                 $urlFragments = parse_url($domain->Domain);
                 $cacheDir = $cacheBaseDir . "/" . $urlFragments['path'];
                 file_put_contents($cacheDir . '/search_index.html', $json);
             }
         }
     }
     return true;
 }
 /**
  * Displays random quote from a CSV file located in a assets subfolder
  * Uses template "cwsoft-shortcode/templates/Includes/RandomQuote.ss" for output 
  * 
  * @param $arguments (csv_file = 'subfolder_in_assets/csv_file.csv')
  * @param $content = null
  * @param $parser = null
  * @return processed template RandomQuote.ss
  */
 public static function cwsShortCodeRandomQuoteHandler($arguments, $content = null, $parser = null)
 {
     // only proceed if a CSV file was specified
     if (!isset($arguments['csv_file'])) {
         return;
     }
     $data = array();
     // check if CSV file exists in assets folder
     $csvFile = ASSETS_DIR . '/' . Convert::raw2sql($arguments['csv_file']);
     if (Director::fileExists($csvFile)) {
         $csv = new CSVParser($filename = $csvFile, $delimiter = '|', $enclosure = '"');
         // iterate through imported Quotes|Author entries and store results in array
         $citations = array();
         foreach ($csv as $row) {
             // only store entries with two data fields (quotation and author)
             if (count($row) !== 2) {
                 continue;
             }
             $citations[] = $row;
         }
         // prepare data for output (randomize array and fetch first citation for output)
         shuffle($citations);
         $data = $citations[0];
     }
     // use default citation if CSV file does not exist or is invalid
     if (!(isset($data['Quote']) && isset($data['Author']))) {
         $data['Quote'] = _t('cwsShortCodeRandomQuote.DEFAULT_QUOTE', 'Only who puts his heart and soul in it, can ignite the fire in others.');
         $data['Author'] = _t('cwsShortCodeRandomQuote.DEFAULT_AUTHOR', 'Augustinus');
     }
     // load template and process data
     $template = new SSViewer('RandomQuote');
     return $template->process(new ArrayData($data));
 }
 /**
  * Displays a random image with colorbox effect from a given assets subfolder
  * Uses template "csoft-shortcode/templates/Includes/RandomImage.ss" for output 
  * 
  * @param mixed $arguments (folder='subfolder_in_assets' align='left|right')
  * @param $content = null
  * @param $parser = null
  * @return processed template RandomImage.ss
  */
 public static function cwsShortCodeRandomImageHandler($arguments, $content = null, $parser = null)
 {
     // only proceed if subfolder was defined
     if (!isset($arguments['folder'])) {
         return;
     }
     // sanitize user inputs
     $folder = Convert::raw2sql($arguments['folder']);
     $align = isset($arguments['align']) ? strtolower(Convert::raw2xml($arguments['align'])) : '';
     // fetch all images in random order from the user defined folder
     $folder = Folder::get()->filter('Filename', "assets/{$folder}/")->First();
     $randomImage = $folder ? Image::get()->filter('ParentID', $folder->ID)->sort('RAND()') : false;
     // exit if user defined folder does not contain any image
     if (!$randomImage) {
         return;
     }
     // extract image caption from image filename
     $caption = $randomImage->Title;
     if (preg_match('#(\\d*-)?(.+)\\.(jpg|gif|png)#i', $caption, $matches)) {
         $caption = ucfirst(str_replace('-', ' ', $matches[2]));
     }
     // prepare data for output
     $data = array('RandomImage' => $randomImage->First(), 'Alignment' => $align, 'Caption' => $caption);
     // load template and process data
     $template = new SSViewer('RandomImage');
     return $template->process(new ArrayData($data));
 }
 /**
  * Render a default template of results.
  * Note: You must have functions "AutoCompleteTitle()" and "AutoCompleteSummary"
  * defined on the returned objects.
  * @param DataObjectSet $results The results to render in the autocomplete box
  * @return SSViewer
  */
 public static function render($results)
 {
     if (!$results) {
         return false;
     }
     $template = new SSViewer('AutoComplete_default');
     return $template->process(new ArrayData(array('Results' => $results)));
 }
 public function augmentSidebarContent(&$content)
 {
     if ($this->owner->DateTime()->LocationID) {
         $location = $this->owner->DateTime()->Location();
         $viewer = new SSViewer('EventLocationSidebarContent');
         $content .= $viewer->process($location);
     }
 }
 /**
  * print subscribe/unsubscribe link
  */
 public function SubscribeLink()
 {
     //Requirements::css('forum_subscribe/css/style.css');
     $interface = new SSViewer('ForumSubscribe');
     $controller = new SubscribeController();
     $loggedIn = Member::currentUser() ? true : false;
     $back_url = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : false;
     return $interface->process(new ArrayData(array('LoggedIn' => $loggedIn, 'Subscribed' => $this->IsSubscribed(), 'Parent' => $this->owner, 'SubscribeLink' => $controller->Link('subscribe/' . $this->owner->ID), 'UnSubscribeLink' => $controller->Link('unsubscribe/' . $this->owner->ID), 'Settings' => $controller->Link('settings') . '?RedirectURL=' . urlencode($back_url))));
 }
 public static function ContactFormFunction()
 {
     $template = new SSViewer('ContactTemplateProvider');
     $controller = new ContactController();
     $form = $controller->ContactForm();
     // a little bit all over the show but to ensure a slightly easier upgrade for users
     // return back the same variables as previously done in comments
     return $template->process(new ArrayData(array('AddContactForm' => $form, 'SuccessMessage' => $controller->SuccessMessage())));
 }
Ejemplo n.º 10
0
 /**
  * Render the object using SSViewer
  * @return string
  */
 public function forPDF($variables = array())
 {
     Config::nest();
     Config::inst()->update('Director', 'alternate_base_url', static::get_render_host());
     $file = $this->owner->getPDFTemplate();
     $viewer = new SSViewer($file);
     $output = $viewer->process($this->owner, $variables);
     Config::unnest();
     return $output;
 }
 public static function parse($arguments, $content = null, $parser = null)
 {
     if (!array_key_exists('repo', $arguments) || empty($arguments['repo']) || strpos($arguments['repo'], '/') <= 0) {
         return '<p><i>GitHub repository undefined</i></p>';
     }
     //Get Config
     $config = Config::inst()->forClass('GitHubShortCode');
     $obj = new ViewableData();
     //Add the Respository Setting
     $obj->Repository = $arguments['repo'];
     //Add Layout
     if (array_key_exists('layout', $arguments) && ($arguments['layout'] == 'inline' || $arguments['layout'] == 'stacked')) {
         $obj->Layout = $arguments['layout'];
     } else {
         $obj->Layout = 'inline';
     }
     //Add the button config
     if (array_key_exists('show', $arguments) && ($arguments['show'] == 'both' || $arguments['show'] == 'stars' || $arguments['show'] == 'forks')) {
         $obj->ShowButton = $arguments['show'];
     } else {
         $obj->ShowButton = 'both';
     }
     //Retrieve Stats
     SS_Cache::set_cache_lifetime('GitHubShortCode', $config->CacheTime);
     $cacheKey = md5('GitHubShortCode_' . $arguments['repo']);
     $cache = SS_Cache::factory('GitHubShortCode');
     $cachedData = $cache->load($cacheKey);
     if ($cachedData == null) {
         $response = self::getFromAPI($arguments['repo'], $config);
         //Verify a 200, if not say the repo errored out and cache false
         if (empty($response) || $response === false || !property_exists($response, 'watchers') || !property_exists($response, 'forks')) {
             $cachedData = array('stargazers' => 'N/A', 'forks' => 'N/A');
         } else {
             if ($config->UseShortHandNumbers == true) {
                 $stargazers = self::shortHandNumber($response->stargazers_count);
                 $forks = self::shortHandNumber($response->forks);
             } else {
                 $stargazers = number_format($response->stargazers_count);
                 $forks = number_format($response->forks);
             }
             $cachedData = array('stargazers' => $stargazers, 'forks' => $forks);
         }
         //Cache response to file system
         $cache->save(serialize($cachedData), $cacheKey);
     } else {
         $cachedData = unserialize($cachedData);
     }
     $obj->Stargazers = $cachedData['stargazers'];
     $obj->Forks = $cachedData['forks'];
     //Init ss viewer and render
     Requirements::css(GITHUBSHORTCODE_BASE . '/css/GitHubButtons.css');
     $ssViewer = new SSViewer('GitHubButtons');
     return $ssViewer->process($obj);
 }
Ejemplo n.º 12
0
 public static function IconShortCodeHandler($arguments, $caption = null, $parser = null)
 {
     $customise = array();
     /*** SET DEFAULTS ***/
     $customise['type'] = 'fa-check';
     //overide the defaults with the arguments supplied
     $customise = array_merge($customise, $arguments);
     //get our Sched template
     $template = new SSViewer('Icon');
     //return the customized template
     return $template->process(new ArrayData($customise));
 }
 public function checkMaintenance()
 {
     $checkHomeForMaintenance = SiteConfig::current_site_config();
     if ($checkHomeForMaintenance->Maintenance == 1) {
         if ($this->owner->URLSegment != 'Security') {
             Requirements::clear();
             $view = new SSViewer(array('MaintenanceView'));
             echo $view->process(_t('Maintenance.MESSAGE', "Site under maintenance"));
             exit;
         }
     }
 }
 /**
  * Return a breadcrumb trail to this page. Excludes "hidden" pages (with ShowInMenus=0) by default.
  *
  * @param int         $maxDepth The maximum depth to traverse.
  * @param bool        $unlinked Do not make page names links
  * @param bool|string $stopAtPageType ClassName of a page to stop the upwards traversal.
  * @param bool        $showHidden Include pages marked with the attribute ShowInMenus = 0
  * @return HTMLText The breadcrumb trail.
  */
 public function PerformantBreadcrumbs($maxDepth = 20, $unlinked = false, $stopAtPageType = false, $showHidden = false)
 {
     $page = $this->asDataNode();
     $pages = array();
     while ($page && (!$maxDepth || count($pages) < $maxDepth) && (!$stopAtPageType || $page->ClassName != $stopAtPageType)) {
         if ($showHidden || $page->ShowInMenus || $page->ID == $this->ID) {
             $pages[] = $page;
         }
         $page = $page->getParent();
     }
     $template = new SSViewer('BreadcrumbsTemplate');
     return $template->process($this->customise(new ArrayData(array('Pages' => new ArrayList(array_reverse($pages))))));
 }
 public static function parse($arguments, $content = null, $parser = null)
 {
     if (!array_key_exists('package', $arguments) || empty($arguments['package']) || strpos($arguments['package'], '/') <= 0) {
         return '<p><i>Packagist package undefined</i></p>';
     }
     //Get Config
     $config = Config::inst()->forClass('PackagistShortCode');
     $obj = new ViewableData();
     //Add the Respository Setting
     $obj->Package = $arguments['package'];
     //Add the button config
     if (array_key_exists('mode', $arguments) && ($arguments['mode'] == 'total' || $arguments['mode'] == 'monthly' || $arguments['mode'] == 'daily')) {
         $obj->DisplayMode = $arguments['mode'];
     } else {
         $obj->DisplayMode = 'total';
     }
     //Retrieve Stats
     SS_Cache::set_cache_lifetime('PackagistShortCode', $config->CacheTime);
     $cacheKey = md5('packagistshortcode_' . $arguments['package']);
     $cache = SS_Cache::factory('PackagistShortCode');
     $cachedData = $cache->load($cacheKey);
     if ($cachedData == null) {
         $response = self::getFromAPI($arguments['package']);
         //Verify a 200, if not say the repo errored out and cache false
         if (empty($response) || $response === false || !property_exists($response, 'package')) {
             $cachedData = array('total' => 'N/A', 'monthly' => 'N/A', 'daily' => 'N/A');
         } else {
             if ($config->UseShortHandNumbers == true) {
                 $totalDownloads = self::shortHandNumber($response->package->downloads->total);
                 $monthlyDownloads = self::shortHandNumber($response->package->downloads->monthly);
                 $dailyDownloads = self::shortHandNumber($response->package->downloads->daily);
             } else {
                 $totalDownloads = number_format($response->package->downloads->total);
                 $monthlyDownloads = number_format($response->package->downloads->monthly);
                 $dailyDownloads = number_format($response->package->downloads->daily);
             }
             $cachedData = array('total' => $totalDownloads, 'monthly' => $monthlyDownloads, 'daily' => $dailyDownloads);
         }
         //Cache response to file system
         $cache->save(serialize($cachedData), $cacheKey);
     } else {
         $cachedData = unserialize($cachedData);
     }
     $obj->TotalDownloads = $cachedData['total'];
     $obj->MonthlyDownloads = $cachedData['monthly'];
     $obj->DailyDownloads = $cachedData['daily'];
     //Init ss viewer and render
     Requirements::css(PACKAGISTSHORTCODE_BASE . '/css/PackagistButton.css');
     $ssViewer = new SSViewer('PackagistButton');
     return $ssViewer->process($obj);
 }
 /**
  * Only works on a functional newsrecord!
  * This one isn't global, only works if controller is a NHP :D
  * @param array $arguments null
  * @return String Parsed for template.
  */
 public static function createSlideshow($arguments)
 {
     if (Controller::curr() instanceof NewsHolderPage_Controller && ($record = Controller::curr()->getNews())) {
         $SiteConfig = SiteConfig::current_site_config();
         if ($SiteConfig->SlideshowInitial) {
             $template = 'NewsSlideShowFirst';
         } else {
             $template = 'NewsSlideShowAll';
         }
         $record->Image = $record->SlideshowImages()->sort('SortOrder ASC');
         $template = new SSViewer($template);
         return $template->process($record);
     }
 }
 /**
  * @inheritdoc
  */
 public function run($request)
 {
     /* Get the protocol and host */
     list($protocol, $host) = explode('://', Director::absoluteBaseURL());
     $host = trim($host, '/\\');
     try {
         /* Flush via SSViewer, this is a clean flush */
         echo 'Flushing SSViewer caches<br />';
         SSViewer::flush_template_cache();
         /* Remove the entire cache directory forcefully. Hard, unclean flush */
         echo 'Removing temp folder ' . TEMP_FOLDER . '<br />';
         exec('rm -rf ' . TEMP_FOLDER);
         if (!file_exists(TEMP_FOLDER)) {
             /* Show a success-message if the TEMP_FOLDER is gone */
             echo 'Succesfully purged the temporary folder. A rebuild of caches is necessary now.<br />';
         }
         /* Flush Varnish. If it isn't available, this _might_ crash. Previous statements have been executed though */
         echo "Flushing Varnish cache for host {$host}<br />";
         exec('flushvarnish -h ' . $host);
         /* Be friendly to the user */
         echo 'Done clearing caches, please reload your site: <a href="' . Director::absoluteBaseURL() . '">here</a><br />';
         echo 'Please note, all protocols have the same cache, so not only ' . $protocol . 'is cleared';
     } catch (Exception $e) {
         /* When boom, error out */
         echo 'Error while clearing caches: ' . $e->getMessage();
     }
 }
 /**
  * Sets the theme to the current site theme
  **/
 function onBeforeSecurityLogin()
 {
     $site = Multisites::inst()->getCurrentSite();
     if ($site && $site->Theme) {
         SSViewer::set_theme($site->Theme);
     }
 }
 /**
  * Called from templates to get rendered blocks for the given area
  * @param string $area
  * @param integer $limit Limit the items to this number, or null for no limit
  */
 public function BlockArea($area, $limit = null)
 {
     if ($this->owner->ID <= 0) {
         return;
     }
     // blocks break on fake pages ie Security/login
     $list = $this->getBlockList($area);
     foreach ($list as $block) {
         if (!$block->canView()) {
             $list->remove($block);
         }
     }
     if ($limit !== null) {
         $list = $list->limit($limit);
     }
     $data['BlockArea'] = $list;
     $data['AreaID'] = $area;
     $data = $this->owner->customise($data);
     $template[] = 'BlockArea_' . $area;
     if (SSViewer::hasTemplate($template)) {
         return $data->renderWith($template);
     } else {
         return $data->renderWith('BlockArea');
     }
 }
Ejemplo n.º 20
0
 public function init()
 {
     parent::init();
     $themeDir = SSViewer::get_theme_folder();
     Requirements::javascript('framework/thirdparty/jquery/jquery.js');
     if (Locator::getLocations()) {
         Requirements::javascript('http://maps.google.com/maps/api/js?sensor=false');
         Requirements::javascript('locator/thirdparty/handlebars/handlebars-v1.3.0.js');
         Requirements::javascript('locator/thirdparty/jquery-store-locator/js/jquery.storelocator.js');
     }
     Requirements::css('locator/css/map.css');
     $featured = Locator::getLocations(array('Featured' => 1))->count() > 0 ? 'featuredLocations: true' : 'featuredLocations: false';
     // map config based on user input in Settings tab
     // AutoGeocode or Full Map
     $load = $this->data()->AutoGeocode ? 'autoGeocode: true, fullMapStart: false,' : 'autoGeocode: false, fullMapStart: true, storeLimit: 1000, maxDistance: true,';
     $base = Director::baseFolder();
     $themePath = $base . '/' . $themeDir;
     $listTemplatePath = file_exists($themePath . '/templates/location-list-description.html') ? $themeDir . '/templates/location-list-description.html' : 'locator/templates/location-list-description.html';
     $infowindowTemplatePath = file_exists($themePath . '/templates/infowindow-description.html') ? $themeDir . '/templates/infowindow-description.html' : 'locator/templates/infowindow-description.html';
     // in page or modal
     $modal = $this->data()->ModalWindow ? 'modalWindow: true' : 'modalWindow: false';
     $kilometer = $this->data()->Unit == 'km' ? 'lengthUnit: "km"' : 'lengthUnit: "m"';
     $link = $this->Link() . 'xml.xml';
     // init map
     if (Locator::getLocations()) {
         Requirements::customScript("\n                \$(function(\$) {\n                    \$('#map-container').storeLocator({\n                        " . $load . "\n                        dataLocation: '" . $link . "',\n                        listTemplatePath: '" . $listTemplatePath . "',\n                        infowindowTemplatePath: '" . $infowindowTemplatePath . "',\n                        originMarker: true,\n                        " . $modal . ',
                     ' . $featured . ",\n                        slideMap: false,\n                        zoomLevel: 0,\n                        distanceAlert: 120,\n                        formID: 'Form_LocationSearch',\n                        inputID: 'Form_LocationSearch_address',\n                        categoryID: 'Form_LocationSearch_category',\n                        distanceAlert: -1,\n                        " . $kilometer . '
                 });
             });
         ');
     }
 }
 /**
  * Renders the map info window for the DataObject.
  *
  * Be sure to define a template for that, named by the decorated class suffixed with _MapInfoWindow
  * e.g. MyPage_MapInfoWindow
  *
  * You can change the suffix globally by editing the MapExtension.map_info_window_suffix config val
  *
  * @return string
  */
 public function getMappableMapContent()
 {
     $defaultTemplate = 'MapInfoWindow';
     $classTemplate = SSViewer::get_templates_by_class($this->owner->ClassName, Config::inst()->get('MapExtension', 'map_info_window_suffix'));
     $template = count($classTemplate) ? $classTemplate : $defaultTemplate;
     return MapUtil::sanitize($this->owner->renderWith($template));
 }
Ejemplo n.º 22
0
 function init()
 {
     parent::init();
     Requirements::themedCSS('editor');
     Requirements::javascript('mysite/js/signup-now.js');
     SSViewer::setOption('rewriteHashlinks', false);
 }
 /**
  * Transforms all fields in the FieldList to use Bootstrap templates
  * @return FieldList
  */
 public function bootstrapify()
 {
     foreach ($this->owner as $f) {
         if (isset($this->ignores[$f->getName()])) {
             continue;
         }
         // If we have a Tabset, bootstrapify all Tabs
         if ($f instanceof TabSet) {
             $f->Tabs()->bootstrapify();
         }
         // If we have a Tab, bootstrapify all its Fields
         if ($f instanceof Tab) {
             $f->Fields()->bootstrapify();
         }
         $template = "Bootstrap{$f->class}_holder";
         if (SSViewer::hasTemplate($template)) {
             $f->setFieldHolderTemplate($template);
         } else {
             $f->setFieldHolderTemplate("BootstrapFieldHolder");
         }
         foreach (array_reverse(ClassInfo::ancestry($f)) as $className) {
             $bootstrapCandidate = "Bootstrap{$className}";
             $nativeCandidate = $className;
             if (SSViewer::hasTemplate($bootstrapCandidate)) {
                 $f->setTemplate($bootstrapCandidate);
                 break;
             } elseif (SSViewer::hasTemplate($nativeCandidate)) {
                 $f->setTemplate($nativeCandidate);
                 break;
             }
         }
     }
     return $this->owner;
 }
    public function run($request)
    {
        if (!Director::is_cli() && !isset($_GET['run'])) {
            DB::alteration_message('Must add ?run=1', 'error');
            return false;
        }
        if (!Director::is_cli()) {
            // - Add UTF-8 so characters will render as they should when debugging (so you can visualize inproperly formatted characters easier)
            // - Add base_tag so that printing blocks of HTML works properly with relative links (helps with visualizing errors)
            ?>
			<head>
				<?php 
            echo SSViewer::get_base_tag('');
            ?>
				<meta charset="UTF-8">
			</head>
<?php 
        }
        increase_time_limit_to(300);
        WordpressDatabase::$default_config = $this->config()->default_db;
        $this->db = $this->wordpressImportService->getDatabase();
        // Login as default admin so 'canPublish()' definitely returns true in 'SiteTree::doPublish()'
        if (!Member::currentUser()) {
            $defaultAdmin = Member::default_admin();
            if ($defaultAdmin && $defaultAdmin->exists()) {
                Session::set('loggedInAs', $defaultAdmin->ID);
            }
        }
        // Unsure if the importing functionality can ever hit this, but just incase.
        if (Versioned::current_stage() !== 'Stage') {
            throw new Exception('Versioned::current_stage() must be "Stage".');
        }
        $this->runCustom($request);
    }
 /**
  * Changes the templates of all the {@link FormField}
  * objects in a given {@link FieldList} object to those
  * that work the Bootstrap framework
  *
  * @param FieldList $fields
  */
 public static function apply_bootstrap_to_fieldlist($fields)
 {
     foreach ($fields as $f) {
         // If we have a Tabset, bootstrapify all Tabs
         if ($f instanceof TabSet) {
             self::apply_bootstrap_to_fieldlist($f->Tabs());
         }
         // If we have a Tab, bootstrapify all its Fields
         if ($f instanceof Tab) {
             self::apply_bootstrap_to_fieldlist($f->Fields());
         }
         $template = "Bootstrap{$f->class}_holder";
         if (SSViewer::hasTemplate($template)) {
             $f->setFieldHolderTemplate($template);
         } else {
             $f->setFieldHolderTemplate("BootstrapFieldHolder");
         }
         foreach (array_reverse(ClassInfo::ancestry($f)) as $className) {
             $bootstrapCandidate = "Bootstrap{$className}";
             $nativeCandidate = $className;
             if (SSViewer::hasTemplate($bootstrapCandidate)) {
                 $f->setTemplate($bootstrapCandidate);
                 break;
             } elseif (SSViewer::hasTemplate($nativeCandidate)) {
                 $f->setTemplate($nativeCandidate);
                 break;
             }
         }
     }
 }
Ejemplo n.º 26
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 doPublish()
 {
     parent::doPublish();
     // Run the page (reset the theme, it might've been disabled by LeftAndMain::init())
     $oldTheme = SSViewer::current_theme();
     SSViewer::set_theme(SSViewer::current_custom_theme());
     $response = Director::test(Director::makeRelative($this->Link()));
     SSViewer::set_theme($oldTheme);
     $errorContent = $response->getBody();
     // Make the base tag dynamic.
     // $errorContent = preg_replace('/<base[^>]+href="' . str_replace('/','\\/', Director::absoluteBaseURL()) . '"[^>]*>/i', '<base href="$BaseURL" />', $errorContent);
     // Check we have an assets base directory, creating if it we don't
     if (!file_exists(ASSETS_PATH)) {
         mkdir(ASSETS_PATH, 02775);
     }
     // if the page is published in a language other than default language,
     // write a specific language version of the HTML page
     $filePath = self::get_filepath_for_errorcode($this->ErrorCode, $this->Locale);
     if ($fh = fopen($filePath, "w")) {
         fwrite($fh, $errorContent);
         fclose($fh);
     } else {
         $fileErrorText = sprintf(_t("ErrorPage.ERRORFILEPROBLEM", "Error opening file \"%s\" for writing. Please check file permissions."), $errorFile);
         FormResponse::status_message($fileErrorText, 'bad');
         FormResponse::respond();
         return;
     }
 }
 /**
  * Called from templates to get rendered blocks for the given area
  * @param string $area
  * @param integer $limit Limit the items to this number, or null for no limit
  */
 public function BlockArea($area, $limit = null)
 {
     if ($this->owner->ID <= 0) {
         return;
     }
     // blocks break on fake pages ie Security/login
     $list = $this->getBlockList($area);
     foreach ($list as $block) {
         if (!$block->canView()) {
             $list->remove($block);
         }
     }
     if ($limit !== null) {
         $list = $list->limit($limit);
     }
     $data = array();
     $data['HasBlockArea'] = $this->owner->canEdit() && isset($_REQUEST['block_preview']) && $_REQUEST['block_preview'] || $list->Count() > 0;
     $data['BlockArea'] = $list;
     $data['AreaID'] = $area;
     $data = $this->owner->customise($data);
     $template = array('BlockArea_' . $area);
     if (SSViewer::hasTemplate($template)) {
         return $data->renderWith($template);
     } else {
         return $data->renderWith('BlockArea');
     }
 }
Ejemplo n.º 28
0
	protected function _runtemplate($template, $data = null) {
		if ($data === null) $data = $this->data;
		if (is_array($data)) $data = $this->data->customise($data);
		
		$viewer = SSViewer::fromString($template);
		return $viewer->process($data);
	}
 /**
  * Sets the theme to the current site theme
  **/
 public function onAfterInit()
 {
     $site = Multisites::inst()->getCurrentSite();
     if ($site && ($theme = $site->getSiteTheme())) {
         SSViewer::set_theme($theme);
     }
 }
 /**
  * looked-up the email template_paths.
  * if not set, will look up both theme folder and project folder
  * in both cases, email folder exsits or Email folder exists
  * return an array containing all folders pointing to the bunch of email templates
  *
  * @return array
  */
 public static function template_paths()
 {
     if (!isset(self::$template_paths)) {
         if (class_exists('SiteConfig') && ($config = SiteConfig::current_site_config()) && $config->Theme) {
             $theme = $config->Theme;
         } elseif (SSViewer::current_custom_theme()) {
             $theme = SSViewer::current_custom_theme();
         } elseif (SSViewer::current_theme()) {
             $theme = SSViewer::current_theme();
         } else {
             $theme = false;
         }
         if ($theme) {
             if (file_exists("../" . THEMES_DIR . "/" . $theme . "/templates/email")) {
                 self::$template_paths[] = THEMES_DIR . "/" . $theme . "/templates/email";
             }
             if (file_exists("../" . THEMES_DIR . "/" . $theme . "/templates/Email")) {
                 self::$template_paths[] = THEMES_DIR . "/" . $theme . "/templates/Email";
             }
         }
         $project = project();
         if (file_exists("../" . $project . '/templates/email')) {
             self::$template_paths[] = $project . '/templates/email';
         }
         if (file_exists("../" . $project . '/templates/Email')) {
             self::$template_paths[] = $project . '/templates/Email';
         }
     } else {
         if (is_string(self::$template_paths)) {
             self::$template_paths = array(self::$template_paths);
         }
     }
     return self::$template_paths;
 }