コード例 #1
0
 /**
  * Get the full form (e.g. /home/) relative link to the home page for the current HTTP_HOST value. Note that the
  * link is trimmed of leading and trailing slashes before returning to ensure consistency.
  *
  * @return string
  */
 public static function get_homepage_link()
 {
     if (!self::$cached_homepage_link) {
         // TODO Move to 'homepagefordomain' module
         if (class_exists('HomepageForDomainExtension')) {
             $host = str_replace('www.', null, $_SERVER['HTTP_HOST']);
             $SQL_host = Convert::raw2sql($host);
             $candidates = DataObject::get('SiteTree', "\"HomepageForDomain\" LIKE '%{$SQL_host}%'");
             if ($candidates) {
                 foreach ($candidates as $candidate) {
                     if (preg_match('/(,|^) *' . preg_quote($host) . ' *(,|$)/', $candidate->HomepageForDomain)) {
                         self::$cached_homepage_link = trim($candidate->RelativeLink(true), '/');
                     }
                 }
             }
         }
         if (!self::$cached_homepage_link) {
             // TODO Move to 'translatable' module
             if (class_exists('Translatable') && Object::has_extension('SiteTree', 'Translatable') && ($link = Translatable::get_homepage_link_by_locale(Translatable::get_current_locale()))) {
                 self::$cached_homepage_link = $link;
             } else {
                 self::$cached_homepage_link = self::get_default_homepage_link();
             }
         }
     }
     return self::$cached_homepage_link;
 }
コード例 #2
0
 public static function create_slug($obj, $field)
 {
     if (!isset($_REQUEST[$field])) {
         $title = $obj->{$field};
     } else {
         $title = $_REQUEST[$field];
     }
     $slug = singleton('SiteTree')->generateURLSegment($title);
     $original_slug = $slug;
     $i = 0;
     $class = $obj->class;
     if (!Object::has_extension($class, "Sluggable")) {
         while ($parent = get_parent_class($obj)) {
             if (Object::has_extension($parent, "Sluggable")) {
                 $class = $parent;
                 break;
             } else {
                 $obj = singleton($parent);
             }
         }
     }
     while ($t = DataList::create($class)->filter(array("Slug" => "{$slug}"))->exclude(array("{$class}.ID" => $obj->ID))->first()) {
         $i++;
         $slug = $original_slug . "-{$i}";
     }
     $obj->Slug = $slug;
 }
コード例 #3
0
ファイル: CMSMain.php プロジェクト: redema/silverstripe-cms
	public function init() {
		// set reading lang
		if(Object::has_extension('SiteTree', 'Translatable') && !$this->request->isAjax()) {
			Translatable::choose_site_locale(array_keys(Translatable::get_existing_content_languages('SiteTree')));
		}
		
		parent::init();
		
		Requirements::css(CMS_DIR . '/css/screen.css');
		
		Requirements::combine_files(
			'cmsmain.js',
			array_merge(
				array(
					CMS_DIR . '/javascript/CMSMain.js',
					CMS_DIR . '/javascript/CMSMain.EditForm.js',
					CMS_DIR . '/javascript/CMSMain.AddForm.js',
					CMS_DIR . '/javascript/CMSPageHistoryController.js',
					CMS_DIR . '/javascript/CMSMain.Tree.js',
					CMS_DIR . '/javascript/SilverStripeNavigator.js'
				),
				Requirements::add_i18n_javascript(CMS_DIR . '/javascript/lang', true, true)
			)
		);

		CMSBatchActionHandler::register('publish', 'CMSBatchAction_Publish');
		CMSBatchActionHandler::register('unpublish', 'CMSBatchAction_Unpublish');
		CMSBatchActionHandler::register('delete', 'CMSBatchAction_Delete');
		CMSBatchActionHandler::register('deletefromlive', 'CMSBatchAction_DeleteFromLive');
	}
コード例 #4
0
 /**
  * Load the extra static definitions for the given extension
  * class name, called by {@link Object::add_extension()}
  * 
  * @param string $class Class name of the owner class (or owner base class)
  * @param string $extension Class name of the extension class
  */
 public static function load_extra_statics($class, $extension)
 {
     if (!empty(self::$extra_statics_loaded[$class][$extension])) {
         return;
     }
     self::$extra_statics_loaded[$class][$extension] = true;
     // If the extension has been manually applied to a subclass, we should ignore that.
     if (Object::has_extension(get_parent_class($class), $extension)) {
         return;
     }
     $callable = array($extension, 'extraDBFields');
     if (!is_callable($callable)) {
         $callable = array($extension, 'extraStatics');
     }
     $statics = call_user_func($callable);
     if ($statics) {
         foreach ($statics as $name => $newVal) {
             if (isset(self::$decoratable_statics[$name])) {
                 // Array to be merged
                 if (self::$decoratable_statics[$name]) {
                     $origVal = self::uninherited_static($class, $name);
                     // Can't use add_static_var() here as it would merge the array rather than replacing
                     self::set_static($class, $name, array_merge((array) $origVal, $newVal));
                     // Value to be overwritten
                 } else {
                     Object::set_static($class, $name, $newVal);
                 }
             }
         }
         DataObject::$cache_has_own_table[$class] = null;
         DataObject::$cache_has_own_table_field[$class] = null;
     }
 }
コード例 #5
0
 private static function generateExtensionMap()
 {
     // get a list of classes
     $classes = array_unique(array_merge(array_keys(ClassInfo::allClasses()), get_declared_classes()));
     // die(print_r($classes,1));
     // Silverstripe has broken clases floating around, we need to blacklist them or it's bad times
     $blacklist = array('SapphireTestReporter', 'SapphireTest', 'SapphireTestSuite', 'CliTestReporter', 'SilverStripeListener', 'TeamCityListener', 'SS_TestListener');
     $blacklistLC = array_map('strtolower', $blacklist);
     // init some vars
     $extMap = $dOClasses = $dODClasses = array();
     // Sort Classes
     foreach ($classes as $class) {
         if (!in_array(strtolower($class), $blacklistLC)) {
             // this breaks when we start looking at some of the broken requires in SapphireTest
             if (is_subclass_of($class, 'DataObject')) {
                 $dOClasses[] = $class;
             }
             if (is_subclass_of($class, 'Extension')) {
                 $dODClasses[] = $class;
             }
         }
     }
     // Find out what is applied to what
     foreach ($dODClasses as $dOD) {
         foreach ($dOClasses as $dO) {
             if (Object::has_extension($dO, $dOD)) {
                 $extMap[$dOD][] = $dO;
             }
         }
     }
     // Cache the map
     self::$extensionMap = $extMap;
 }
コード例 #6
0
 /**
  * FixMe: Currently only db and has_one fields are cached.
  * @param string|int $identifier an identifier which will be used for key generation
  * @param callable $callback the function which can be called to fetch the data
  * @return DataObject
  */
 protected function cache($identifier, $callback)
 {
     $serializer = CacheHelper::get_serializer();
     // check for cacheable extension of data object class
     $className = $this->dataClass;
     if (Object::has_extension($className, 'CacheableExtension')) {
         // search in cache
         $cache = CacheHelper::get_cache();
         $key = CacheHelper::to_key("{$className}.{$identifier}");
         if ($data = $cache->load($key)) {
             return $serializer->deserialize($data);
         } else {
             // if not found in cache, perform callback
             $data = $callback();
             if (!$data) {
                 // if result is empty, return null
                 return null;
             }
             $cachedFunctions = array_keys($data->hasOne());
             foreach ($cachedFunctions as $fn) {
                 $data->{$fn}();
             }
             $cache->save($serializer->serialize($data), $key);
             // return result
             return $data;
         }
     } else {
         return $callback();
     }
 }
コード例 #7
0
 function getManagedModels()
 {
     $classes = $this->stat('managed_models');
     if (is_string($classes)) {
         $matches = explode(",", $classes);
         foreach ($matches as $key => $value) {
             $matches[$key] = substr($value, 10);
         }
         // remove "decorator:"
         if (is_array($matches)) {
             $classes = array();
             foreach (ClassInfo::subclassesFor('DataObject') as $class) {
                 $add = false;
                 // used to guarantee that if multiple matches on a class it's not added multiple times.
                 foreach ($matches as $match) {
                     if (Object::has_extension($class, $match)) {
                         $add = true;
                     }
                 }
                 if ($add) {
                     $classes[] = $class;
                 }
             }
             if (count($class) > 1) {
                 array_unshift($classes, 'All');
             }
         } else {
             $classes = array($classes);
         }
     }
     return $classes;
 }
コード例 #8
0
 public function testEnableWithCustomClasses()
 {
     FulltextSearchable::enable(array('File'));
     $this->assertTrue(Object::has_extension('File', 'FulltextSearchable'));
     // TODO This shouldn't need all arguments included
     Object::remove_extension('File', 'FulltextSearchable(\'"Filename","Title","Content"\')');
     $this->assertFalse(Object::has_extension('File', 'FulltextSearchable'));
 }
 /**
  * Getter for the rules class
  * Based on your needs, different rule classes could be used
  * The module comes bundled with the base rules, and subsite rules
  * TODO this could easily be amended to be configurable, so that custom rules could be used
  *
  * @return string
  */
 public static function get_rules_class()
 {
     $class = 'UploadDirRules';
     if (class_exists('Subsite') && Object::has_extension('Subsite', 'AssetsFolderExtension')) {
         $class = 'SubsiteUploadDirRules';
     }
     return $class;
 }
 public function __construct(DataObject $original)
 {
     $class = $original->class;
     if (TD_SS_COMPATIBILITY == TD_COMPAT_SS30X && !Object::has_extension($class, 'TranslatableDataObject') || TD_SS_COMPATIBILITY == TD_COMPAT_SS31X && !$class::has_extension('TranslatableDataObject')) {
         trigger_error("Parameter given does not have the required 'TranslatableDataObject' extension", E_USER_ERROR);
     }
     $this->original = $original;
     parent::__construct();
 }
 /**
  * Find out which classes are extended by this extension.
  *
  * Originally from: http://stackoverflow.com/a/26148610/2754026
  *
  * @return array Array of strings
  */
 public static function getExtendedClasses()
 {
     $classes = array();
     foreach (ClassInfo::subclassesFor('Object') as $class_name) {
         if (Object::has_extension($class_name, __CLASS__)) {
             $classes[] = $class_name;
         }
     }
     return $classes;
 }
コード例 #12
0
 static function GetVersionedClass()
 {
     $classes = array();
     foreach (ClassInfo::subClassesFor('DataObject') as $class) {
         if (Object::has_extension($class, 'Versioned')) {
             $classes[] = $class;
         }
     }
     return $classes;
 }
 function synchroniseUDatabase()
 {
     $sync = parent::synchroniseUDatabase();
     $sync = $sync && !(Object::has_extension('Product', 'ProductWithVariationDecorator') && $this->owner->HasVariations());
     if ($sync) {
         if (empty($this->owner->Title)) {
             return $this->notifyError('SS_FIELDS_MISSING', 'Title');
         }
         return true;
     }
 }
コード例 #14
0
 public function init()
 {
     //setting the uploads directory to make sure images uploaded through the content
     //editor are saved the right place
     $curr = LeftAndMain::curr();
     if ($curr) {
         //Debug::dump(get_class($curr));
         //Debug::dump(ClassInfo::ancestry($curr));
         $currClass = null;
         foreach (ClassInfo::ancestry($curr) as $class) {
             foreach (self::$supported_classes as $supported_class) {
                 if ($class == $supported_class) {
                     $currClass = $class;
                 }
             }
         }
         //Debug::dump($currClass);
         //switch (get_class($curr)) {
         switch ($currClass) {
             //Page administration
             case 'CMSPagesController':
             case 'CMSPageEditController':
                 $page = $curr->currentPage();
                 if ($page && $page->hasExtension('AssetsFolderExtension')) {
                     Upload::config()->uploads_folder = $page->getAssetsFolderDirName();
                 }
                 //Debug::dump($page->Title);
                 break;
             case 'ModelAdmin':
                 //For ModelAdmin we're falling back to cookies that we believe to have
                 //been set when setting the cms fields, see AssetFolderExtension::updateCMSFields()
                 //...as it seems to be almost impossible to figure out the current object elsewise
                 //see below for tries
                 //pull requests to fix this welcome!!!
                 //Debug::dump($this->owner->getURLParams());
                 //Debug::dump($this->owner->request->param('ModelClass'));
                 //Debug::dump($this->owner->request->remaining());
                 //Debug::dump($this->owner->request->getVars());
                 //Debug::dump($this->owner->request->params());
                 //Debug::dump($curr->currentPageID());
                 Upload::config()->uploads_folder = Cookie::get('cms-uploaddirrules-uploads-folder');
                 break;
                 //Settings
             //Settings
             case 'CMSSettingsController':
                 if (Object::has_extension('SiteConfig', 'AssetsFolderExtension')) {
                     $sc = SiteConfig::current_site_config();
                     Upload::config()->uploads_folder = $sc->getAssetsFolderDirName();
                 }
             default:
         }
     }
 }
コード例 #15
0
 public static function is_sortable_class($classname)
 {
     if (in_array($classname, self::$sortable_classes)) {
         return true;
     }
     foreach (self::$sortable_classes as $class) {
         if (is_subclass_of($classname, $class)) {
             return true;
         }
     }
     return Object::has_extension($classname, 'SortableDataObject');
 }
コード例 #16
0
 public function identifyPass()
 {
     // Check extensions on each side of this relation
     foreach ($this->fields as $field => $class) {
         if (!Object::has_extension($class, 'LegacyDataObject')) {
             throw new Exception($class . " does not have the LegacyDataObject extension");
         }
     }
     // Update remote table to include _ImportedID column
     $this->setupLocalTable();
     $this->setupRemoteTable();
 }
コード例 #17
0
 public function testWeightManipulation()
 {
     NewsPage::set_weights(array());
     $weights = array('Normal', 'Teaser', 'Headline');
     do {
         NewsPage::set_weights($weights);
         $this->assertEquals($weights, NewsPage::get_weights());
         foreach (array_slice($weights, 1) as $w) {
             $this->assertTrue(Object::has_extension('NewsHolder', "NewsWeight{$w}"));
         }
         array_pop($weights);
     } while ($weights);
 }
コード例 #18
0
 function handleAction($request)
 {
     // This method can't be called without ajax.
     if (!$this->parentController->isAjax()) {
         $this->parentController->redirectBack();
         return;
     }
     $actions = $this->batchActions();
     $actionClass = $actions[$request->param('BatchAction')]['class'];
     $actionHandler = new $actionClass();
     // Sanitise ID list and query the database for apges
     $ids = split(' *, *', trim($request->requestVar('csvIDs')));
     foreach ($ids as $k => $v) {
         if (!is_numeric($v)) {
             unset($ids[$k]);
         }
     }
     if ($ids) {
         if (Object::has_extension('SiteTree', 'Translatable')) {
             Translatable::disable_locale_filter();
         }
         $pages = DataObject::get($this->recordClass, sprintf('"%s"."ID" IN (%s)', ClassInfo::baseDataClass($this->recordClass), implode(", ", $ids)));
         if (Object::has_extension('SiteTree', 'Translatable')) {
             Translatable::enable_locale_filter();
         }
         if (Object::has_extension($this->recordClass, 'Versioned')) {
             // If we didn't query all the pages, then find the rest on the live site
             if (!$pages || $pages->Count() < sizeof($ids)) {
                 foreach ($ids as $id) {
                     $idsFromLive[$id] = true;
                 }
                 if ($pages) {
                     foreach ($pages as $page) {
                         unset($idsFromLive[$page->ID]);
                     }
                 }
                 $idsFromLive = array_keys($idsFromLive);
                 $sql = sprintf('"%s"."ID" IN (%s)', $this->recordClass, implode(", ", $idsFromLive));
                 $livePages = Versioned::get_by_stage($this->recordClass, 'Live', $sql);
                 if ($pages) {
                     $pages->merge($livePages);
                 } else {
                     $pages = $livePages;
                 }
             }
         }
     } else {
         $pages = new DataObjectSet();
     }
     return $actionHandler->run($pages);
 }
コード例 #19
0
 public function importPass()
 {
     if (ImportHelper::is_a($this->targetClass, 'SiteTree')) {
         throw new InvalidArgumentException("Don't run TruncateImporter on a SiteTree class");
     }
     // Check extensions
     if (!Object::has_extension($this->targetClass, 'LegacyDataObject')) {
         throw new Exception($this->targetClass . " does not have the LegacyDataObject extension");
     }
     // Update remote table to include _ImportedID column
     $this->setupRemoteTable();
     // Delete all existing records
     $existingRecords = DataObject::get($this->targetClass);
     $existingCount = $existingRecords->count();
     // Get other records
     $query = $this->getRemoteObjectsQuery();
     $remoteObjects = $this->task->query($query);
     $remoteCount = $remoteObjects->numRecords();
     // Start
     $this->task->message(" * Replacing {$existingCount} records with {$remoteCount} ones");
     // Truncate all tables
     $tables = ClassInfo::dataClassesFor($this->targetClass);
     foreach ($tables as $table) {
         DB::query('TRUNCATE "' . $table . '"');
     }
     $this->task->message(" * " . count($tables) . " tables truncated");
     // Add all objects
     $total = 0;
     foreach ($remoteObjects as $remoteObject) {
         // Show progress indicator
         $this->task->progress(++$total, $remoteCount);
         // Make new object
         $class = isset($remoteObject['ClassName']) && ImportHelper::is_a($remoteObject['ClassName'], $this->targetClass) ? $remoteObject['ClassName'] : $this->targetClass;
         // Direct copy data into the new object
         $localObject = $class::create();
         foreach ($remoteObject as $field => $value) {
             $localObject->{$field} = $value;
         }
         $localObject->LegacyID = $remoteObject['ID'];
         $localObject->write(false, true);
     }
     // Bulk update remote table
     $conn = $this->task->getRemoteConnection();
     $baseTable = $this->getRemoteBaseTable();
     $conn->query('UPDATE "' . $baseTable . '" SET "_ImportedID" = "ID", "_ImportedDate" = NOW()');
     // Done!
     $this->task->message(" * Result: {$total} added");
 }
コード例 #20
0
 public function onAfterInit()
 {
     // Flexslider options
     $animate = $this->owner->Animate ? 'true' : 'false';
     $loop = $this->owner->Loop ? 'true' : 'false';
     $sync = $this->owner->ThumbnailNav == true ? "sync: '#carousel'," : "";
     $before = method_exists($this->owner->ClassName, 'flexSliderBeforeAction') ? $this->owner->flexSliderBeforeAction() : "function(){}";
     $after = method_exists($this->owner->ClassName, 'flexSliderAfterAction') ? $this->owner->flexSliderAfterAction() : "function(){}";
     $speed = method_exists($this->owner->ClassName, 'setFlexSliderSpeed') ? $this->owner->setFlexSliderSpeed() : 7000;
     // only call custom script if page has Slides and DataExtension
     if (Object::has_extension($this->owner->data()->ClassName, 'FlexSlider')) {
         if ($this->owner->data()->Slides()->exists()) {
             Requirements::customScript("\n                (function(\$) {\n                    \$(document).ready(function(){\n                        \$('.flexslider').flexslider({\n                            slideshow: " . $animate . ",\n                            animation: '" . $this->owner->Animation . "',\n                            animationLoop: " . $loop . ",\n                            controlNav: true,\n                            directionNav: true,\n                            prevText: '',\n                            nextText: '',\n                            pauseOnAction: true,\n                            pauseOnHover: true,\n                            " . $sync . "\n                            start: function(slider){\n                              \$('body').removeClass('loading');\n                            },\n                            before: " . $before . ",\n                            after: " . $after . ",\n                            slideshowSpeed: " . $speed . "\n                        });\n                    });\n                }(jQuery));");
         }
     }
 }
コード例 #21
0
 public function updateCMSFields(FieldList $fields)
 {
     Requirements::css(SEO_DIR . '/css/seo.css');
     // check for Google Sitemaps module & notification;
     $GSMactive = Config::inst()->get('GoogleSitemap', 'enabled', Config::INHERITED);
     $GSMping = Config::inst()->get('GoogleSitemap', 'google_notification_enabled', Config::INHERITED);
     // check for Redirectmanager
     $RedirActive = Object::has_extension("ContentController", "RedirectedURLHandler");
     //$template = new SSViewer('AdminSiteConfigSeoTips');
     //$seotips = $template->process($this->owner->customise(new ArrayData(array(
     $seotips = $this->owner->customise(new ArrayData(array('GSMactive' => $GSMactive, 'GSMping' => $GSMping, 'RedirActive' => $RedirActive)))->renderWith('AdminSiteConfigSeoTips');
     $fields->addFieldToTab("Root.Main", LiteralField::create('SEOtips', $seotips));
     // SEOTITLE
     // parse out the title tag as used by the theme;
     $loader = SS_TemplateLoader::instance();
     $theme = Config::inst()->get('SSViewer', 'theme');
     $foundpath = $loader->findTemplates("main/Page", $theme);
     // TODO: this is a guess...
     $path = $foundpath['main'];
     if (file_exists($path)) {
         $templatecode = file_get_contents($path);
     } else {
         throw new Exception('Failed to identify path');
     }
     if ($templatecode && strpos($templatecode, '<title>')) {
         $templatetag = explode('<title>', $templatecode);
         $templatetag = array_pop($templatetag);
         $templatetag = explode('</title>', $templatetag);
         $templatetag = array_shift($templatetag);
     } else {
         $templatetag = false;
     }
     //		$template = SSViewer::fromString($titlehtml);
     //		$fulltitle = $template->process($this->owner);
     if ($templatetag) {
         $templatetag = "<br />Current template title tag: " . $templatetag;
     } else {
         $templatetag = "";
     }
     // FIXME - not sure of the intention of this value, but set it to avoid site config breaking
     $titlehtml = '';
     $fields->addFieldToTab("Root.Main", $seotitlefield = TextField::create('SEOTitleTemplate')->SetRightTitle("For SEO preview (valid js expression, available vars: page_title, page_menutitle, '.\n\t\t\t\t\t'page_metadata_title), eg:<br /> page_title + ' &raquo; ' +\n\t\t\t\tsiteconfig_title [OR] (page_metadata_title ? page_metadata_title : page_title)" . $titlehtml));
     // set default/initial value
     if (!$this->owner->SEOTitleTemplate) {
         $seotitlefield->setValue("page_title + ' &raquo; ' + siteconfig_title");
     }
 }
コード例 #22
0
 /**
  * Load the extra static definitions for the given extension
  * class name, called by {@link Object::add_extension()}
  * 
  * @param string $class Class name of the owner class (or owner base class)
  * @param string $extension Class name of the extension class
  */
 public static function load_extra_statics($class, $extension)
 {
     if (!empty(self::$extra_statics_loaded[$class][$extension])) {
         return;
     }
     self::$extra_statics_loaded[$class][$extension] = true;
     if (preg_match('/^([^(]*)/', $extension, $matches)) {
         $extensionClass = $matches[1];
     } else {
         user_error("Bad extenion '{$extension}' - can't find classname", E_USER_WARNING);
         return;
     }
     // @deprecated 2.4 - use extraStatics() now, not extraDBFields()
     if (method_exists($extensionClass, 'extraDBFields')) {
         user_error('DataExtension::extraDBFields() is deprecated. Please use extraStatics() instead.', E_USER_NOTICE);
         $extraStaticsMethod = 'extraDBFields';
     } else {
         $extraStaticsMethod = 'extraStatics';
     }
     // If the extension has been manually applied to a subclass, we should ignore that.
     if (Object::has_extension(get_parent_class($class), $extensionClass)) {
         return;
     }
     // If there aren't any extraStatics we shouldn't try to load them.
     if (!method_exists($extensionClass, $extraStaticsMethod)) {
         return;
     }
     $statics = call_user_func(array($extensionClass, $extraStaticsMethod), $class, $extension);
     if ($statics) {
         foreach ($statics as $name => $newVal) {
             if (isset(self::$extendable_statics[$name])) {
                 // Array to be merged
                 if (self::$extendable_statics[$name]) {
                     $origVal = Object::uninherited_static($class, $name);
                     // Can't use add_static_var() here as it would merge the array rather than replacing
                     Object::set_static($class, $name, array_merge((array) $origVal, $newVal));
                     // Value to be overwritten
                 } else {
                     Object::set_static($class, $name, $newVal);
                 }
             }
         }
         DataObject::$cache_has_own_table[$class] = null;
         DataObject::$cache_has_own_table_field[$class] = null;
     }
 }
コード例 #23
0
 public function run($request)
 {
     if (!(\Permission::check('ADMIN') || \Director::is_cli())) {
         exit("Invalid");
     }
     $service = singleton('ElasticaService');
     $items = explode(',', $request->getVar('ids'));
     if (!count($items)) {
         return;
     }
     $baseType = $request->getVar('base') ? $request->getVar('base') : 'SiteTree';
     $recurse = $request->getVar('recurse') ? true : false;
     foreach ($items as $id) {
         $id = (int) $id;
         if (!$id) {
             continue;
         }
         \Versioned::reading_stage('Stage');
         $item = $baseType::get()->byID($id);
         if ($item) {
             $this->reindex($item, $recurse, $baseType, $service, 'Stage');
         }
         \Versioned::reading_stage('Live');
         $item = $baseType::get()->byID($id);
         if ($item) {
             $this->reindex($item, $recurse, $baseType, $service, 'Live');
         }
     }
     return;
     foreach ($this->getIndexedClasses() as $class) {
         $logFunc("Indexing items of type {$class}");
         $this->startBulkIndex();
         foreach ($class::get() as $record) {
             $logFunc("Indexing " . $record->Title);
             $this->index($record);
         }
         if (\Object::has_extension($class, 'Versioned')) {
             $live = \Versioned::get_by_stage($class, 'Live');
             foreach ($live as $liveRecord) {
                 $logFunc("Indexing Live record " . $liveRecord->Title);
                 $this->index($liveRecord, 'Live');
             }
         }
         $this->endBulkIndex();
     }
 }
コード例 #24
0
 /**
  * @return string
  */
 public function Field()
 {
     Requirements::css(SAPPHIRE_DIR . '/thirdparty/jquery-ui-themes/smoothness/jquery.ui.all.css');
     Requirements::add_i18n_javascript(SAPPHIRE_DIR . '/javascript/lang');
     Requirements::javascript(SAPPHIRE_DIR . '/thirdparty/jquery/jquery.js');
     Requirements::javascript(SAPPHIRE_DIR . '/thirdparty/jquery-ui/jquery-ui.js');
     if ($this->form->getRecord() && $this->form->getRecord()->exists()) {
         $record = $this->form->getRecord();
         if (Object::has_extension('SiteTree', 'Translatable') && $record->Locale) {
             $iframe = "iframe?locale=" . $record->Locale;
         } else {
             $iframe = "iframe";
         }
         return $this->createTag('iframe', array('name' => $this->Name() . '_iframe', 'src' => Controller::join_links($this->Link(), $iframe), 'style' => 'height: 152px; width: 100%; border: none;')) . $this->createTag('input', array('type' => 'hidden', 'id' => $this->ID(), 'name' => $this->Name() . 'ID', 'value' => $this->attrValue()));
     }
     $this->setValue(sprintf(_t('FileIFrameField.ATTACHONCESAVED', '%ss can be attached once you have saved the record for the first time.'), $this->FileTypeName()));
     return FormField::field();
 }
コード例 #25
0
 public function init()
 {
     // set reading lang
     if (Object::has_extension('ContentModule', 'Translatable') && !$this->request->isAjax()) {
         Translatable::choose_site_locale(array_keys(Translatable::get_existing_content_languages('ContentModule')));
     }
     parent::init();
     Versioned::reading_stage("Stage");
     Requirements::css(CMS_DIR . '/css/screen.css');
     Requirements::css(INPAGE_MODULES_DIR . '/css/ContentModule_Admin.css');
     Requirements::combine_files('contentmodulemain.js', array_merge(array(CMS_DIR . '/javascript/CMSPageHistoryController.js')));
     //CMSBatchActionHandler::register('publish', 'CMSBatchAction_Publish');
     //CMSBatchActionHandler::register('unpublish', 'CMSBatchAction_Unpublish');
     //CMSBatchActionHandler::register('delete', 'CMSBatchAction_Delete');
     //CMSBatchActionHandler::register('deletefromlive', 'CMSBatchAction_DeleteFromLive');
     if (isset($_REQUEST['ID'])) {
         $this->setCurrentPageID($_REQUEST['ID']);
     }
 }
コード例 #26
0
ファイル: FileIFrameField.php プロジェクト: normann/sapphire
 /**
  * @return string
  */
 public function Field($properties = array())
 {
     Deprecation::notice('3.0', 'Use UploadField');
     Requirements::css(FRAMEWORK_DIR . '/thirdparty/jquery-ui-themes/smoothness/jquery-ui.css');
     Requirements::add_i18n_javascript(FRAMEWORK_DIR . '/javascript/lang');
     Requirements::javascript(FRAMEWORK_DIR . '/thirdparty/jquery/jquery.js');
     Requirements::javascript(FRAMEWORK_DIR . '/thirdparty/jquery-ui/jquery-ui.js');
     if ($this->form->getRecord() && $this->form->getRecord()->exists()) {
         $record = $this->form->getRecord();
         if (class_exists('Translatable') && Object::has_extension('SiteTree', 'Translatable') && $record->Locale) {
             $iframe = "iframe?locale=" . $record->Locale;
         } else {
             $iframe = "iframe";
         }
         return $this->createTag('iframe', array('name' => $this->getName() . '_iframe', 'src' => Controller::join_links($this->Link(), $iframe), 'style' => 'height: 152px; width: 100%; border: none;')) . $this->createTag('input', array('type' => 'hidden', 'id' => $this->ID(), 'name' => $this->getName() . 'ID', 'value' => $this->attrValue()));
     } else {
         return _t('FileIFrameField.ATTACHONCESAVED', '{type}s can be attached once you have saved the record for the first time.', array('type' => $this->FileTypeName()));
     }
 }
コード例 #27
0
 public function generateScriptDataFor($type, $file = null, $stage = 'Live')
 {
     if ($stage && Object::has_extension($type, 'Versioned')) {
         Versioned::reading_stage($stage);
     }
     if (!class_exists($type)) {
         throw new Exception("Invalid type defined, no data generated");
     }
     $typeConfig = $this->configFor($type);
     $config = isset($typeConfig[$file]) ? $typeConfig[$file] : array();
     // TODO - allow for specifying things like strtotime things for dates in some manner
     $rules = isset($config['filter']) ? $config['filter'] : null;
     $list = $type::get();
     if (isset($config['generator'])) {
         $generator = Injector::inst()->create($config['generator']);
         if ($generator) {
             $list = $generator->getList();
         }
     }
     if ($rules) {
         $list = $this->applyRulesToList($list, $rules);
     }
     $template = isset($config['template']) ? $config['template'] : 'JsonSet';
     $setFields = isset($config['fields']) ? $config['fields'] : null;
     if ($setFields) {
         $setFields = explode(',', $setFields);
     }
     $order = isset($config['order']) ? $config['order'] : 'ID DESC';
     $list = $list->sort($order);
     $list = $list->filterByCallback(function ($item) use($setFields) {
         // extension check was done on the type earlier, here we're just being careful
         if ($item->hasExtension('ScriptGenieExtension') && $setFields) {
             $item->setJSONFields($setFields);
         }
         return $item->canView();
     });
     $data = ArrayData::create(array('RootObject' => isset($config['rootObject']) ? $config['rootObject'] : 'window', 'Type' => $type, 'Items' => $list));
     $output = $data->renderWith($template);
     return $output;
 }
 public function testEnable()
 {
     // test for baddies in _config.php
     if (Object::has_extension('ContentController', 'ZendSearchLuceneContentController')) {
         echo '<p>Please remove calls to ZendSearchLuceneSearchable::enable() from your _config.php file before running tests.</p>';
         die;
     }
     // Setup
     Object::remove_extension('ContentController', 'ZendSearchLuceneContentController');
     Object::remove_extension('SiteConfig', 'ZendSearchLuceneSiteConfig');
     Object::remove_extension('LeftAndMain', 'ZendSearchLuceneCMSDecorator');
     Object::remove_extension('SiteTree', 'ZendSearchLuceneSearchable');
     Object::remove_extension('File', 'ZendSearchLuceneSearchable');
     // Are we fresh?
     $this->assertFalse(Object::has_extension('ContentController', 'ZendSearchLuceneContentController'));
     $this->assertFalse(Object::has_extension('SiteConfig', 'ZendSearchLuceneSiteConfig'));
     $this->assertFalse(Object::has_extension('LeftAndMain', 'ZendSearchLuceneCMSDecorator'));
     $this->assertFalse(Object::has_extension('SiteTree', 'ZendSearchLuceneSearchable'));
     $this->assertFalse(Object::has_extension('File', 'ZendSearchLuceneSearchable'));
     ZendSearchLuceneSearchable::$pageLength = 10;
     ZendSearchLuceneSearchable::$alwaysShowPages = 3;
     ZendSearchLuceneSearchable::$maxShowPages = 8;
     ZendSearchLuceneSearchable::$encoding = 'utf-8';
     ZendSearchLuceneSearchable::$cacheDirectory = TEMP_FOLDER;
     ZendSearchLuceneWrapper::$indexName = 'Test';
     ZendSearchLuceneSearchable::enable(array());
     $this->assertTrue(Object::has_extension('ContentController', 'ZendSearchLuceneContentController'));
     $this->assertTrue(Object::has_extension('SiteConfig', 'ZendSearchLuceneSiteConfig'));
     $this->assertTrue(Object::has_extension('LeftAndMain', 'ZendSearchLuceneCMSDecorator'));
     $this->assertFalse(Object::has_extension('SiteTree', 'ZendSearchLuceneSearchable'));
     $this->assertFalse(Object::has_extension('File', 'ZendSearchLuceneSearchable'));
     ZendSearchLuceneSearchable::enable(array('File'));
     $this->assertFalse(Object::has_extension('SiteTree', 'ZendSearchLuceneSearchable'));
     $this->assertTrue(Object::has_extension('File', 'ZendSearchLuceneSearchable'));
     ZendSearchLuceneSearchable::enable(array('File', 'SiteTree'));
     $this->assertTrue(Object::has_extension('SiteTree', 'ZendSearchLuceneSearchable'));
     $this->assertTrue(Object::has_extension('File', 'ZendSearchLuceneSearchable'));
 }
コード例 #29
0
 protected function processAll($filepath, $preview = false)
 {
     $this->extend('updateColumnMap', $this->columnMap);
     // we have to check for the existence of this in case the stockcontrol module hasn't been loaded
     // and the CSV still contains a Stock column
     self::$hasStockImpl = Object::has_extension('Product', 'ProductStockDecorator');
     $results = parent::processAll($filepath, $preview);
     //After results have been processed, publish all created & updated products
     $objects = new DataObjectSet();
     $objects->merge($results->Created());
     $objects->merge($results->Updated());
     foreach ($objects as $object) {
         if (!$object->ParentID) {
             //set parent page
             if (is_numeric(self::$parentpageid) && DataObject::get_by_id('ProductGroup', self::$parentpageid)) {
                 //cached option
                 $object->ParentID = self::$parentpageid;
             } elseif ($parentpage = DataObject::get_one('ProductGroup', "\"Title\" = 'Products'", '"Created" DESC')) {
                 //page called 'Products'
                 $object->ParentID = self::$parentpageid = $parentpage->ID;
             } elseif ($parentpage = DataObject::get_one('ProductGroup', "\"ParentID\" = 0", '"Created" DESC')) {
                 //root page
                 $object->ParentID = self::$parentpageid = $parentpage->ID;
             } elseif ($parentpage = DataObject::get_one('ProductGroup', "", '"Created" DESC')) {
                 //any product page
                 $object->ParentID = self::$parentpageid = $parentpage->ID;
             } else {
                 $object->ParentID = self::$parentpageid = 0;
             }
         }
         $object->extend('updateImport');
         //could be used for setting other attributes, such as stock level
         $object->writeToStage('Stage');
         $object->publish('Stage', 'Live');
     }
     return $results;
 }
コード例 #30
0
 /**
  * Helper method for applicablePages() methods.  Acts as a skeleton implementation.
  *
  * @param array $ids The IDs passed to applicablePages
  * @param string $methodName The canXXX() method to call on each page to check if the action is applicable
  * @param bool $checkStagePages Set to true if you want to check stage pages
  * @param bool $checkLivePages Set to true if you want to check live pages (e.g, for deleted-from-draft)
  * @return array
  */
 public function applicablePagesHelper($ids, $methodName, $checkStagePages = true, $checkLivePages = true)
 {
     if (!is_array($ids)) {
         user_error("Bad \$ids passed to applicablePagesHelper()", E_USER_WARNING);
     }
     if (!is_string($methodName)) {
         user_error("Bad \$methodName passed to applicablePagesHelper()", E_USER_WARNING);
     }
     $applicableIDs = array();
     $managedClass = $this->managedClass;
     $draftPages = DataObject::get($managedClass)->byIDs($ids);
     // Filter out the live-only ids
     $onlyOnLive = array_fill_keys($ids, true);
     if ($checkStagePages) {
         foreach ($draftPages as $obj) {
             unset($onlyOnLive[$obj->ID]);
             if ($obj->{$methodName}()) {
                 $applicableIDs[] = $obj->ID;
             }
         }
     }
     $onlyOnLive = array_keys($onlyOnLive);
     if ($checkLivePages && $onlyOnLive && Object::has_extension($managedClass, 'SilverStripe\\ORM\\Versioning\\Versioned')) {
         // Get the pages that only exist on live (deleted from stage)
         $livePages = Versioned::get_by_stage($managedClass, "Live")->byIDs($onlyOnLive);
         foreach ($livePages as $obj) {
             if ($obj->{$methodName}()) {
                 $applicableIDs[] = $obj->ID;
             }
         }
     }
     return $applicableIDs;
 }