Completed
Push — master ( f6a37f...25a2ff )
by
unknown
9s
created
src/PageTypes/DatedUpdatePage.php 1 patch
Indentation   +55 added lines, -55 removed lines patch added patch discarded remove patch
@@ -10,70 +10,70 @@
 block discarded – undo
10 10
 
11 11
 class DatedUpdatePage extends Page
12 12
 {
13
-    /**
14
-     * Meant as an abstract base class.
15
-     *
16
-     * {@inheritDoc}
17
-     */
18
-    private static $hide_ancestor = DatedUpdatePage::class;
13
+	/**
14
+	 * Meant as an abstract base class.
15
+	 *
16
+	 * {@inheritDoc}
17
+	 */
18
+	private static $hide_ancestor = DatedUpdatePage::class;
19 19
 
20
-    private static $singular_name = 'Dated Update Page';
20
+	private static $singular_name = 'Dated Update Page';
21 21
 
22
-    private static $plural_name = 'Dated Update Pages';
22
+	private static $plural_name = 'Dated Update Pages';
23 23
 
24
-    private static $table_name = 'DatedUpdatePage';
24
+	private static $table_name = 'DatedUpdatePage';
25 25
 
26
-    private static $defaults = [
27
-        'ShowInMenus' => false,
28
-    ];
26
+	private static $defaults = [
27
+		'ShowInMenus' => false,
28
+	];
29 29
 
30
-    private static $db = [
31
-        'Abstract' => 'Text',
32
-        'Date' => 'Datetime',
33
-    ];
30
+	private static $db = [
31
+		'Abstract' => 'Text',
32
+		'Date' => 'Datetime',
33
+	];
34 34
 
35
-    /**
36
-     * Add the default for the Date being the current day.
37
-     */
38
-    public function populateDefaults()
39
-    {
40
-        parent::populateDefaults();
35
+	/**
36
+	 * Add the default for the Date being the current day.
37
+	 */
38
+	public function populateDefaults()
39
+	{
40
+		parent::populateDefaults();
41 41
 
42
-        if (!isset($this->Date) || $this->Date === null) {
43
-            $this->Date = DBDatetime::now()->Format('y-MM-dd 09:00:00');
44
-        }
45
-    }
42
+		if (!isset($this->Date) || $this->Date === null) {
43
+			$this->Date = DBDatetime::now()->Format('y-MM-dd 09:00:00');
44
+		}
45
+	}
46 46
 
47
-    public function fieldLabels($includerelations = true)
48
-    {
49
-        $labels = parent::fieldLabels($includerelations);
50
-        $labels['Date'] = _t(__CLASS__ . '.DateLabel', 'Date');
51
-        $labels['Abstract'] = _t(__CLASS__ . '.AbstractTextFieldLabel', 'Abstract');
47
+	public function fieldLabels($includerelations = true)
48
+	{
49
+		$labels = parent::fieldLabels($includerelations);
50
+		$labels['Date'] = _t(__CLASS__ . '.DateLabel', 'Date');
51
+		$labels['Abstract'] = _t(__CLASS__ . '.AbstractTextFieldLabel', 'Abstract');
52 52
 
53
-        return $labels;
54
-    }
53
+		return $labels;
54
+	}
55 55
 
56
-    public function getCMSFields()
57
-    {
58
-        $this->beforeUpdateCMSFields(function (FieldList $fields) {
59
-            $fields->addFieldToTab(
60
-                'Root.Main',
61
-                $dateTimeField = DatetimeField::create('Date', $this->fieldLabel('Date')),
62
-                'Content'
63
-            );
56
+	public function getCMSFields()
57
+	{
58
+		$this->beforeUpdateCMSFields(function (FieldList $fields) {
59
+			$fields->addFieldToTab(
60
+				'Root.Main',
61
+				$dateTimeField = DatetimeField::create('Date', $this->fieldLabel('Date')),
62
+				'Content'
63
+			);
64 64
 
65
-            $fields->addfieldToTab(
66
-                'Root.Main',
67
-                $abstractField = TextareaField::create('Abstract', $this->fieldLabel('Abstract')),
68
-                'Content'
69
-            );
70
-            $abstractField->setAttribute('maxlength', '160');
71
-            $abstractField->setRightTitle(_t(
72
-                __CLASS__ . '.AbstractDesc',
73
-                'The abstract is used as a summary on the listing pages. It is limited to 160 characters.'
74
-            ));
75
-            $abstractField->setRows(6);
76
-        });
77
-        return parent::getCMSFields();
78
-    }
65
+			$fields->addfieldToTab(
66
+				'Root.Main',
67
+				$abstractField = TextareaField::create('Abstract', $this->fieldLabel('Abstract')),
68
+				'Content'
69
+			);
70
+			$abstractField->setAttribute('maxlength', '160');
71
+			$abstractField->setRightTitle(_t(
72
+				__CLASS__ . '.AbstractDesc',
73
+				'The abstract is used as a summary on the listing pages. It is limited to 160 characters.'
74
+			));
75
+			$abstractField->setRows(6);
76
+		});
77
+		return parent::getCMSFields();
78
+	}
79 79
 }
Please login to merge, or discard this patch.
src/PageTypes/BasePage.php 1 patch
Indentation   +287 added lines, -287 removed lines patch added patch discarded remove patch
@@ -29,297 +29,297 @@
 block discarded – undo
29 29
 
30 30
 class BasePage extends SiteTree
31 31
 {
32
-    private static $icon = 'cwp/cwp:images/icons/sitetree_images/page.png';
32
+	private static $icon = 'cwp/cwp:images/icons/sitetree_images/page.png';
33 33
 
34
-    /**
35
-     * Hide this page type from the CMS. hide_ancestor is slightly misnamed, should really be just "hide"
36
-     *
37
-     * {@inheritDoc}
38
-     */
39
-    private static $hide_ancestor = BasePage::class;
34
+	/**
35
+	 * Hide this page type from the CMS. hide_ancestor is slightly misnamed, should really be just "hide"
36
+	 *
37
+	 * {@inheritDoc}
38
+	 */
39
+	private static $hide_ancestor = BasePage::class;
40 40
 
41
-    private static $pdf_export = false;
41
+	private static $pdf_export = false;
42 42
 
43
-    /*
43
+	/*
44 44
     *Domain to generate PDF's from, DOES not include protocol
45 45
     *i.e. google.com not http://google.com
46 46
     */
47
-    private static $pdf_base_url = "";
48
-
49
-    /**
50
-     * Allow custom overriding of the path to the WKHTMLTOPDF binary, in cases
51
-     * where multiple versions of the binary are available to choose from. This
52
-     * should be the full path to the binary (e.g. /usr/local/bin/wkhtmltopdf)
53
-     * @see BasePage_Controller::generatePDF();
54
-     */
55
-    private static $wkhtmltopdf_binary = null;
56
-
57
-    private static $generated_pdf_path = 'assets/_generated_pdfs';
58
-
59
-    private static $api_access = [
60
-        'view' => [
61
-            'Locale', 'URLSegment', 'Title', 'MenuTitle', 'Content', 'MetaDescription',
62
-            'ExtraMenu', 'Sort', 'Version', 'ParentID', 'ID'
63
-        ],
64
-        'edit' => [
65
-            'Locale', 'URLSegment', 'Title', 'MenuTitle', 'Content', 'MetaDescription',
66
-            'ExtraMenu', 'Sort', 'Version', 'ParentID', 'ID'
67
-        ],
68
-    ];
69
-
70
-    private static $table_name = 'BasePage';
71
-
72
-    public static $related_pages_title = 'Related pages';
73
-
74
-    private static $many_many = [
75
-        'Terms' => TaxonomyTerm::class,
76
-        'RelatedPages' => BasePage::class,
77
-    ];
78
-
79
-    private static $many_many_extraFields = [
80
-        'RelatedPages' => [
81
-            'SortOrder' => 'Int',
82
-        ],
83
-    ];
84
-
85
-    private static $plural_name = 'Base Pages';
86
-
87
-    /**
88
-     * Get the footer holder.
89
-     */
90
-    public function getFooter()
91
-    {
92
-        return FooterHolder::get_one(FooterHolder::class);
93
-    }
94
-
95
-    /**
96
-     * Return the full filename of the pdf file, including path & extension
97
-     */
98
-    public function getPdfFilename()
99
-    {
100
-        $baseName = sprintf('%s-%s', $this->URLSegment, $this->ID);
101
-
102
-        $folderPath = Config::inst()->get(BasePage::class, 'generated_pdf_path');
103
-        if ($folderPath[0] != '/') {
104
-            $folderPath = BASE_PATH . '/' . $folderPath;
105
-        }
106
-
107
-        return sprintf('%s/%s.pdf', $folderPath, $baseName);
108
-    }
109
-
110
-    /**
111
-     * Build pdf link for template.
112
-     */
113
-    public function PdfLink()
114
-    {
115
-        if (!Config::inst()->get(BasePage::class, 'pdf_export')) {
116
-            return false;
117
-        }
118
-
119
-        $path = $this->getPdfFilename();
120
-
121
-        if ((Versioned::get_stage() === Versioned::LIVE) && file_exists($path)) {
122
-            return Director::baseURL() . preg_replace('#^/#', '', Director::makeRelative($path));
123
-        }
124
-        return $this->Link('downloadpdf');
125
-    }
126
-
127
-    public function RelatedPages()
128
-    {
129
-        return $this->getManyManyComponents('RelatedPages')->sort('SortOrder');
130
-    }
131
-
132
-    public function RelatedPagesTitle()
133
-    {
134
-        return $this->stat('related_pages_title');
135
-    }
136
-
137
-    /**
138
-     * Remove linked pdf when publishing the page,
139
-     * as it would be out of date.
140
-     */
141
-    public function onAfterPublish()
142
-    {
143
-        $filepath = $this->getPdfFilename();
144
-        if (file_exists($filepath)) {
145
-            unlink($filepath);
146
-        }
147
-    }
148
-
149
-    /**
150
-     * Remove linked pdf when unpublishing the page,
151
-     * so it's no longer valid.
152
-     *
153
-     * @return boolean
154
-     */
155
-    public function doUnpublish()
156
-    {
157
-        if (!parent::doUnpublish()) {
158
-            return false;
159
-        }
160
-
161
-        $filepath = $this->getPdfFilename();
162
-        if (file_exists($filepath)) {
163
-            unlink($filepath);
164
-        }
165
-
166
-        return true;
167
-    }
168
-
169
-    /**
170
-     * @deprecated 2.0.0 remove with other deprecations
171
-     * @todo Remove once CWP moves to 3.3 core (which includes this in SiteTree)
172
-     * @return self
173
-     */
174
-    public function doRestoreToStage()
175
-    {
176
-        $this->invokeWithExtensions('onBeforeRestoreToStage', $this);
177
-        $result = parent::doRestoreToStage();
178
-        $this->invokeWithExtensions('onAfterRestoreToStage', $this);
179
-
180
-        return $result;
181
-    }
182
-
183
-    public function getCMSFields()
184
-    {
185
-        $this->beforeUpdateCMSFields(function (FieldList $fields) {
186
-            // Related Pages
187
-            $components = GridFieldConfig_RelationEditor::create();
188
-            $components->removeComponentsByType(GridFieldAddNewButton::class);
189
-            $components->removeComponentsByType(GridFieldEditButton::class);
190
-            $components->removeComponentsByType(GridFieldFilterHeader::class);
191
-            $components->addComponent(new GridFieldSortableRows('SortOrder'));
192
-
193
-            /** @var GridFieldDataColumns $dataColumns */
194
-            $dataColumns = $components->getComponentByType(GridFieldDataColumns::class);
195
-            $dataColumns->setDisplayFields([
196
-                'Title' => _t(__CLASS__ . '.ColumnTitle', 'Title'),
197
-                'ClassName' => _t(__CLASS__ . '.ColumnPageType', 'Page Type')
198
-            ]);
199
-
200
-            $fields->findOrMakeTab(
201
-                'Root.RelatedPages',
202
-                _t(__CLASS__ . '.RelatedPages', 'Related pages')
203
-            );
204
-            $fields->addFieldToTab(
205
-                'Root.RelatedPages',
206
-                GridField::create(
207
-                    'RelatedPages',
208
-                    _t(__CLASS__ . '.RelatedPages', 'Related pages'),
209
-                    $this->RelatedPages(),
210
-                    $components
211
-                )
212
-            );
213
-
214
-            // Taxonomies - Unless they have their own 'Tags' field (such as in Blog, etc)
215
-            $hasMany = $this->hasMany();
216
-            $manyMany = $this->manyMany();
217
-            if (!isset($hasMany['Tags']) && !isset($manyMany['Tags'])) {
218
-                $components = GridFieldConfig_RelationEditor::create();
219
-                $components->removeComponentsByType(GridFieldAddNewButton::class);
220
-                $components->removeComponentsByType(GridFieldEditButton::class);
221
-
222
-                /** @var GridFieldAddExistingAutocompleter $autoCompleter */
223
-                $autoCompleter = $components->getComponentByType(GridFieldAddExistingAutocompleter::class);
224
-                $autoCompleter->setResultsFormat('$Name ($TaxonomyName)');
225
-
226
-                /** @var GridFieldDataColumns $dataColumns */
227
-                $dataColumns = $components->getComponentByType(GridFieldDataColumns::class);
228
-                $dataColumns->setDisplayFields([
229
-                    'Name' => _t(__CLASS__ . '.Term', 'Term'),
230
-                    'TaxonomyName' => _t(__CLASS__ . '.Taxonomy', 'Taxonomy')
231
-                ]);
232
-
233
-                $fields->findOrMakeTab('Root.Tags', _t(__CLASS__ . '.TagsTabTitle', 'Tags'));
234
-                $fields->addFieldToTab(
235
-                    'Root.Tags',
236
-                    TreeMultiselectField::create(
237
-                        'Terms',
238
-                        _t(__CLASS__ . '.Terms', 'Terms'),
239
-                        TaxonomyTerm::class
240
-                    )->setDescription(_t(__CLASS__ . '.TermsDescription', 'Click to search for additional terms'))
241
-                );
242
-            }
243
-        });
244
-        return parent::getCMSFields();
245
-    }
246
-
247
-    /**
248
-     * Provides data for translation navigation.
249
-     * Collects all site translations, marks the current one, and redirects
250
-     * to the translated home page if a. there is a translated homepage and b. the
251
-     * translation of the specific page is not available.
252
-     * @todo re-implement with Fluent
253
-     */
254
-    public function getAvailableTranslations()
255
-    {
256
-        if (!class_exists('Translatable')) {
257
-            return false;
258
-        }
259
-
260
-        $translations = new ArrayList();
261
-        $globalTranslations = Translatable::get_existing_content_languages();
262
-
263
-        foreach ($globalTranslations as $loc => $langName) {
264
-            // Find out the language name in native language.
265
-            $nativeLangName = i18n::get_language_name($loc, true);
266
-            if (!$nativeLangName) {
267
-                $nativeLangName = i18n::get_language_name(i18n::get_lang_from_locale($loc), true);
268
-            }
269
-            if (!$nativeLangName) {
270
-                // Fall back to the locale name.
271
-                $nativeLangName = $langName;
272
-            }
273
-
274
-            // Eliminate the part in brackets (e.g. [mandarin])
275
-            $nativeLangName = preg_replace('/ *[\(\[].*$/', '', $nativeLangName);
276
-
277
-            // Find out the link to the translated page.
278
-            $link = null;
279
-            $page = $this->getTranslation($loc);
280
-            if ($page) {
281
-                $link = $page->Link();
282
-            }
283
-            if (!$link) {
284
-                // Fall back to the home page
285
-                $link = Translatable::get_homepage_link_by_locale($loc);
286
-            }
287
-            if (!$link) {
288
-                continue;
289
-            }
290
-
291
-            // Assemble the table for the switcher.
292
-            $translations->push(new ArrayData(array(
293
-                'Locale' => i18n::convert_rfc1766($loc),
294
-                'LangName' => $nativeLangName,
295
-                'Link' => $link,
296
-                'Current' => (Translatable::get_current_locale()==$loc)
297
-            )));
298
-        }
299
-
300
-        if ($translations->count()>1) {
301
-            return $translations;
302
-        } else {
303
-            return null;
304
-        }
305
-    }
306
-
307
-    /**
308
-     * Returns the native language name for the selected locale/language, empty string if Translatable is not available
309
-     *
310
-     * @return string
311
-     * @todo re-implement with Fluent
312
-     */
313
-    public function getSelectedLanguage()
314
-    {
315
-        if (!class_exists('Translatable')) {
316
-            return '';
317
-        }
318
-
319
-        $language = explode('_', Translatable::get_current_locale());
320
-        $languageCode = array_shift($language);
321
-        $nativeName = i18n::get_language_name($languageCode, true);
322
-
323
-        return $nativeName;
324
-    }
47
+	private static $pdf_base_url = "";
48
+
49
+	/**
50
+	 * Allow custom overriding of the path to the WKHTMLTOPDF binary, in cases
51
+	 * where multiple versions of the binary are available to choose from. This
52
+	 * should be the full path to the binary (e.g. /usr/local/bin/wkhtmltopdf)
53
+	 * @see BasePage_Controller::generatePDF();
54
+	 */
55
+	private static $wkhtmltopdf_binary = null;
56
+
57
+	private static $generated_pdf_path = 'assets/_generated_pdfs';
58
+
59
+	private static $api_access = [
60
+		'view' => [
61
+			'Locale', 'URLSegment', 'Title', 'MenuTitle', 'Content', 'MetaDescription',
62
+			'ExtraMenu', 'Sort', 'Version', 'ParentID', 'ID'
63
+		],
64
+		'edit' => [
65
+			'Locale', 'URLSegment', 'Title', 'MenuTitle', 'Content', 'MetaDescription',
66
+			'ExtraMenu', 'Sort', 'Version', 'ParentID', 'ID'
67
+		],
68
+	];
69
+
70
+	private static $table_name = 'BasePage';
71
+
72
+	public static $related_pages_title = 'Related pages';
73
+
74
+	private static $many_many = [
75
+		'Terms' => TaxonomyTerm::class,
76
+		'RelatedPages' => BasePage::class,
77
+	];
78
+
79
+	private static $many_many_extraFields = [
80
+		'RelatedPages' => [
81
+			'SortOrder' => 'Int',
82
+		],
83
+	];
84
+
85
+	private static $plural_name = 'Base Pages';
86
+
87
+	/**
88
+	 * Get the footer holder.
89
+	 */
90
+	public function getFooter()
91
+	{
92
+		return FooterHolder::get_one(FooterHolder::class);
93
+	}
94
+
95
+	/**
96
+	 * Return the full filename of the pdf file, including path & extension
97
+	 */
98
+	public function getPdfFilename()
99
+	{
100
+		$baseName = sprintf('%s-%s', $this->URLSegment, $this->ID);
101
+
102
+		$folderPath = Config::inst()->get(BasePage::class, 'generated_pdf_path');
103
+		if ($folderPath[0] != '/') {
104
+			$folderPath = BASE_PATH . '/' . $folderPath;
105
+		}
106
+
107
+		return sprintf('%s/%s.pdf', $folderPath, $baseName);
108
+	}
109
+
110
+	/**
111
+	 * Build pdf link for template.
112
+	 */
113
+	public function PdfLink()
114
+	{
115
+		if (!Config::inst()->get(BasePage::class, 'pdf_export')) {
116
+			return false;
117
+		}
118
+
119
+		$path = $this->getPdfFilename();
120
+
121
+		if ((Versioned::get_stage() === Versioned::LIVE) && file_exists($path)) {
122
+			return Director::baseURL() . preg_replace('#^/#', '', Director::makeRelative($path));
123
+		}
124
+		return $this->Link('downloadpdf');
125
+	}
126
+
127
+	public function RelatedPages()
128
+	{
129
+		return $this->getManyManyComponents('RelatedPages')->sort('SortOrder');
130
+	}
131
+
132
+	public function RelatedPagesTitle()
133
+	{
134
+		return $this->stat('related_pages_title');
135
+	}
136
+
137
+	/**
138
+	 * Remove linked pdf when publishing the page,
139
+	 * as it would be out of date.
140
+	 */
141
+	public function onAfterPublish()
142
+	{
143
+		$filepath = $this->getPdfFilename();
144
+		if (file_exists($filepath)) {
145
+			unlink($filepath);
146
+		}
147
+	}
148
+
149
+	/**
150
+	 * Remove linked pdf when unpublishing the page,
151
+	 * so it's no longer valid.
152
+	 *
153
+	 * @return boolean
154
+	 */
155
+	public function doUnpublish()
156
+	{
157
+		if (!parent::doUnpublish()) {
158
+			return false;
159
+		}
160
+
161
+		$filepath = $this->getPdfFilename();
162
+		if (file_exists($filepath)) {
163
+			unlink($filepath);
164
+		}
165
+
166
+		return true;
167
+	}
168
+
169
+	/**
170
+	 * @deprecated 2.0.0 remove with other deprecations
171
+	 * @todo Remove once CWP moves to 3.3 core (which includes this in SiteTree)
172
+	 * @return self
173
+	 */
174
+	public function doRestoreToStage()
175
+	{
176
+		$this->invokeWithExtensions('onBeforeRestoreToStage', $this);
177
+		$result = parent::doRestoreToStage();
178
+		$this->invokeWithExtensions('onAfterRestoreToStage', $this);
179
+
180
+		return $result;
181
+	}
182
+
183
+	public function getCMSFields()
184
+	{
185
+		$this->beforeUpdateCMSFields(function (FieldList $fields) {
186
+			// Related Pages
187
+			$components = GridFieldConfig_RelationEditor::create();
188
+			$components->removeComponentsByType(GridFieldAddNewButton::class);
189
+			$components->removeComponentsByType(GridFieldEditButton::class);
190
+			$components->removeComponentsByType(GridFieldFilterHeader::class);
191
+			$components->addComponent(new GridFieldSortableRows('SortOrder'));
192
+
193
+			/** @var GridFieldDataColumns $dataColumns */
194
+			$dataColumns = $components->getComponentByType(GridFieldDataColumns::class);
195
+			$dataColumns->setDisplayFields([
196
+				'Title' => _t(__CLASS__ . '.ColumnTitle', 'Title'),
197
+				'ClassName' => _t(__CLASS__ . '.ColumnPageType', 'Page Type')
198
+			]);
199
+
200
+			$fields->findOrMakeTab(
201
+				'Root.RelatedPages',
202
+				_t(__CLASS__ . '.RelatedPages', 'Related pages')
203
+			);
204
+			$fields->addFieldToTab(
205
+				'Root.RelatedPages',
206
+				GridField::create(
207
+					'RelatedPages',
208
+					_t(__CLASS__ . '.RelatedPages', 'Related pages'),
209
+					$this->RelatedPages(),
210
+					$components
211
+				)
212
+			);
213
+
214
+			// Taxonomies - Unless they have their own 'Tags' field (such as in Blog, etc)
215
+			$hasMany = $this->hasMany();
216
+			$manyMany = $this->manyMany();
217
+			if (!isset($hasMany['Tags']) && !isset($manyMany['Tags'])) {
218
+				$components = GridFieldConfig_RelationEditor::create();
219
+				$components->removeComponentsByType(GridFieldAddNewButton::class);
220
+				$components->removeComponentsByType(GridFieldEditButton::class);
221
+
222
+				/** @var GridFieldAddExistingAutocompleter $autoCompleter */
223
+				$autoCompleter = $components->getComponentByType(GridFieldAddExistingAutocompleter::class);
224
+				$autoCompleter->setResultsFormat('$Name ($TaxonomyName)');
225
+
226
+				/** @var GridFieldDataColumns $dataColumns */
227
+				$dataColumns = $components->getComponentByType(GridFieldDataColumns::class);
228
+				$dataColumns->setDisplayFields([
229
+					'Name' => _t(__CLASS__ . '.Term', 'Term'),
230
+					'TaxonomyName' => _t(__CLASS__ . '.Taxonomy', 'Taxonomy')
231
+				]);
232
+
233
+				$fields->findOrMakeTab('Root.Tags', _t(__CLASS__ . '.TagsTabTitle', 'Tags'));
234
+				$fields->addFieldToTab(
235
+					'Root.Tags',
236
+					TreeMultiselectField::create(
237
+						'Terms',
238
+						_t(__CLASS__ . '.Terms', 'Terms'),
239
+						TaxonomyTerm::class
240
+					)->setDescription(_t(__CLASS__ . '.TermsDescription', 'Click to search for additional terms'))
241
+				);
242
+			}
243
+		});
244
+		return parent::getCMSFields();
245
+	}
246
+
247
+	/**
248
+	 * Provides data for translation navigation.
249
+	 * Collects all site translations, marks the current one, and redirects
250
+	 * to the translated home page if a. there is a translated homepage and b. the
251
+	 * translation of the specific page is not available.
252
+	 * @todo re-implement with Fluent
253
+	 */
254
+	public function getAvailableTranslations()
255
+	{
256
+		if (!class_exists('Translatable')) {
257
+			return false;
258
+		}
259
+
260
+		$translations = new ArrayList();
261
+		$globalTranslations = Translatable::get_existing_content_languages();
262
+
263
+		foreach ($globalTranslations as $loc => $langName) {
264
+			// Find out the language name in native language.
265
+			$nativeLangName = i18n::get_language_name($loc, true);
266
+			if (!$nativeLangName) {
267
+				$nativeLangName = i18n::get_language_name(i18n::get_lang_from_locale($loc), true);
268
+			}
269
+			if (!$nativeLangName) {
270
+				// Fall back to the locale name.
271
+				$nativeLangName = $langName;
272
+			}
273
+
274
+			// Eliminate the part in brackets (e.g. [mandarin])
275
+			$nativeLangName = preg_replace('/ *[\(\[].*$/', '', $nativeLangName);
276
+
277
+			// Find out the link to the translated page.
278
+			$link = null;
279
+			$page = $this->getTranslation($loc);
280
+			if ($page) {
281
+				$link = $page->Link();
282
+			}
283
+			if (!$link) {
284
+				// Fall back to the home page
285
+				$link = Translatable::get_homepage_link_by_locale($loc);
286
+			}
287
+			if (!$link) {
288
+				continue;
289
+			}
290
+
291
+			// Assemble the table for the switcher.
292
+			$translations->push(new ArrayData(array(
293
+				'Locale' => i18n::convert_rfc1766($loc),
294
+				'LangName' => $nativeLangName,
295
+				'Link' => $link,
296
+				'Current' => (Translatable::get_current_locale()==$loc)
297
+			)));
298
+		}
299
+
300
+		if ($translations->count()>1) {
301
+			return $translations;
302
+		} else {
303
+			return null;
304
+		}
305
+	}
306
+
307
+	/**
308
+	 * Returns the native language name for the selected locale/language, empty string if Translatable is not available
309
+	 *
310
+	 * @return string
311
+	 * @todo re-implement with Fluent
312
+	 */
313
+	public function getSelectedLanguage()
314
+	{
315
+		if (!class_exists('Translatable')) {
316
+			return '';
317
+		}
318
+
319
+		$language = explode('_', Translatable::get_current_locale());
320
+		$languageCode = array_shift($language);
321
+		$nativeName = i18n::get_language_name($languageCode, true);
322
+
323
+		return $nativeName;
324
+	}
325 325
 }
Please login to merge, or discard this patch.
src/PageTypes/BasePageController.php 2 patches
Indentation   +345 added lines, -345 removed lines patch added patch discarded remove patch
@@ -23,355 +23,355 @@
 block discarded – undo
23 23
 
24 24
 class BasePageController extends ContentController
25 25
 {
26
-    private static $allowed_actions = [
27
-        'downloadpdf',
28
-        'SearchForm',
29
-        'results',
30
-    ];
31
-
32
-    /**
33
-     * How many search results should be shown per-page?
34
-     * @var int
35
-     */
36
-    public static $results_per_page = 10;
37
-
38
-    public static $search_index_class = CwpSolrIndex::class;
39
-
40
-    /**
41
-     * If spelling suggestions for searches are given, enable
42
-     * suggested searches to be followed immediately
43
-     *
44
-     * @config
45
-     * @var bool
46
-     */
47
-    private static $search_follow_suggestions = true;
48
-
49
-    /**
50
-     * Which classes should be queried when searching?
51
-     * @var array
52
-     */
53
-    public static $classes_to_search = [
54
-        [
55
-            'class' => 'Page',
56
-            'includeSubclasses' => true,
57
-        ]
58
-    ];
59
-
60
-    /**
61
-     * Serve the page rendered as PDF.
62
-     */
63
-    public function downloadpdf()
64
-    {
65
-        if (!Config::inst()->get(BasePage::class, 'pdf_export')) {
66
-            return false;
67
-        }
68
-
69
-        // We only allow producing live pdf. There is no way to secure the draft files.
70
-        Versioned::set_stage(Versioned::LIVE);
71
-
72
-        $path = $this->dataRecord->getPdfFilename();
73
-        if (!file_exists($path)) {
74
-            $this->generatePDF();
75
-        }
76
-
77
-        return HTTPRequest::send_file(file_get_contents($path), basename($path), 'application/pdf');
78
-    }
79
-
80
-    /*
26
+	private static $allowed_actions = [
27
+		'downloadpdf',
28
+		'SearchForm',
29
+		'results',
30
+	];
31
+
32
+	/**
33
+	 * How many search results should be shown per-page?
34
+	 * @var int
35
+	 */
36
+	public static $results_per_page = 10;
37
+
38
+	public static $search_index_class = CwpSolrIndex::class;
39
+
40
+	/**
41
+	 * If spelling suggestions for searches are given, enable
42
+	 * suggested searches to be followed immediately
43
+	 *
44
+	 * @config
45
+	 * @var bool
46
+	 */
47
+	private static $search_follow_suggestions = true;
48
+
49
+	/**
50
+	 * Which classes should be queried when searching?
51
+	 * @var array
52
+	 */
53
+	public static $classes_to_search = [
54
+		[
55
+			'class' => 'Page',
56
+			'includeSubclasses' => true,
57
+		]
58
+	];
59
+
60
+	/**
61
+	 * Serve the page rendered as PDF.
62
+	 */
63
+	public function downloadpdf()
64
+	{
65
+		if (!Config::inst()->get(BasePage::class, 'pdf_export')) {
66
+			return false;
67
+		}
68
+
69
+		// We only allow producing live pdf. There is no way to secure the draft files.
70
+		Versioned::set_stage(Versioned::LIVE);
71
+
72
+		$path = $this->dataRecord->getPdfFilename();
73
+		if (!file_exists($path)) {
74
+			$this->generatePDF();
75
+		}
76
+
77
+		return HTTPRequest::send_file(file_get_contents($path), basename($path), 'application/pdf');
78
+	}
79
+
80
+	/*
81 81
     * This will return either pdf_base_url from YML, CWP_SECURE_DOMAIN
82 82
     * from _ss_environment, or blank. In that order of importance.
83 83
     */
84
-    public function getPDFBaseURL()
85
-    {
86
-        //if base url YML is defined in YML, use that
87
-        if (Config::inst()->get(BasePage::class, 'pdf_base_url')) {
88
-            $pdfBaseUrl = Config::inst()->get(BasePage::class, 'pdf_base_url').'/';
89
-            //otherwise, if we are CWP use the secure domain
90
-        } elseif (Environment::getEnv('CWP_SECURE_DOMAIN')) {
91
-            $pdfBaseUrl = Environment::getEnv('CWP_SECURE_DOMAIN') . '/';
92
-            //or if neither, leave blank
93
-        } else {
94
-            $pdfBaseUrl = '';
95
-        }
96
-        return $pdfBaseUrl;
97
-    }
98
-
99
-    /*
84
+	public function getPDFBaseURL()
85
+	{
86
+		//if base url YML is defined in YML, use that
87
+		if (Config::inst()->get(BasePage::class, 'pdf_base_url')) {
88
+			$pdfBaseUrl = Config::inst()->get(BasePage::class, 'pdf_base_url').'/';
89
+			//otherwise, if we are CWP use the secure domain
90
+		} elseif (Environment::getEnv('CWP_SECURE_DOMAIN')) {
91
+			$pdfBaseUrl = Environment::getEnv('CWP_SECURE_DOMAIN') . '/';
92
+			//or if neither, leave blank
93
+		} else {
94
+			$pdfBaseUrl = '';
95
+		}
96
+		return $pdfBaseUrl;
97
+	}
98
+
99
+	/*
100 100
     * Don't use the proxy if the pdf domain is the CWP secure domain
101 101
     * Or if we aren't on a CWP server
102 102
     */
103
-    public function getPDFProxy($pdfBaseUrl)
104
-    {
105
-        if (!Environment::getEnv('CWP_SECURE_DOMAIN')
106
-            || $pdfBaseUrl == Environment::getEnv('CWP_SECURE_DOMAIN') . '/'
107
-        ) {
108
-            $proxy = '';
109
-        } else {
110
-            $proxy = ' --proxy ' . Environment::getEnv('SS_OUTBOUND_PROXY')
111
-                . ':' . Environment::getEnv('SS_OUTBOUND_PROXY_PORT');
112
-        }
113
-        return $proxy;
114
-    }
115
-
116
-    /**
117
-     * Render the page as PDF using wkhtmltopdf.
118
-     */
119
-    public function generatePDF()
120
-    {
121
-        if (!Config::inst()->get(BasePage::class, 'pdf_export')) {
122
-            return false;
123
-        }
124
-
125
-        $binaryPath = Config::inst()->get(BasePage::class, 'wkhtmltopdf_binary');
126
-        if (!$binaryPath || !is_executable($binaryPath)) {
127
-            if (Environment::getEnv('WKHTMLTOPDF_BINARY')
128
-                && is_executable(Environment::getEnv('WKHTMLTOPDF_BINARY'))
129
-            ) {
130
-                $binaryPath = Environment::getEnv('WKHTMLTOPDF_BINARY');
131
-            }
132
-        }
133
-
134
-        if (!$binaryPath) {
135
-            user_error('Neither WKHTMLTOPDF_BINARY nor BasePage.wkhtmltopdf_binary are defined', E_USER_ERROR);
136
-        }
137
-
138
-        if (Versioned::get_reading_mode() == 'Stage.Stage') {
139
-            user_error('Generating PDFs on draft is not supported', E_USER_ERROR);
140
-        }
141
-
142
-        set_time_limit(60);
143
-
144
-        // prepare the paths
145
-        $pdfFile = $this->dataRecord->getPdfFilename();
146
-        $bodyFile = str_replace('.pdf', '_pdf.html', $pdfFile);
147
-        $footerFile = str_replace('.pdf', '_pdffooter.html', $pdfFile);
148
-
149
-        // make sure the work directory exists
150
-        if (!file_exists(dirname($pdfFile))) {
151
-            Filesystem::makeFolder(dirname($pdfFile));
152
-        }
153
-
154
-        //decide the domain to use in generation
155
-        $pdfBaseUrl = $this->getPDFBaseURL();
156
-
157
-        // Force http protocol on CWP - fetching from localhost without using the proxy, SSL terminates on gateway.
158
-        if (Environment::getEnv('CWP_ENVIRONMENT')) {
159
-            Config::modify()->set(Director::class, 'alternate_protocol', 'http');
160
-            //only set alternate protocol if CWP_SECURE_DOMAIN is defined OR pdf_base_url is
161
-            if ($pdfBaseUrl) {
162
-                Config::modify()->set(Director::class, 'alternate_base_url', 'http://' . $pdfBaseUrl);
163
-            }
164
-        }
165
-
166
-        $bodyViewer = $this->getViewer('pdf');
167
-
168
-        // write the output of this page to HTML, ready for conversion to PDF
169
-        file_put_contents($bodyFile, $bodyViewer->process($this));
170
-
171
-        // get the viewer for the current template with _pdffooter
172
-        $footerViewer = $this->getViewer('pdffooter');
173
-
174
-        // write the output of the footer template to HTML, ready for conversion to PDF
175
-        file_put_contents($footerFile, $footerViewer->process($this));
176
-
177
-        //decide what the proxy should look like
178
-        $proxy = $this->getPDFProxy($pdfBaseUrl);
179
-
180
-        // finally, generate the PDF
181
-        $command = $binaryPath . $proxy . ' --outline -B 40pt -L 20pt -R 20pt -T 20pt --encoding utf-8 '
182
-            . '--orientation Portrait --disable-javascript --quiet --print-media-type ';
183
-        $retVal = 0;
184
-        $output = array();
185
-        exec(
186
-            $command . " --footer-html \"$footerFile\" \"$bodyFile\" \"$pdfFile\" &> /dev/stdout",
187
-            $output,
188
-            $retVal
189
-        );
190
-
191
-        // remove temporary file
192
-        unlink($bodyFile);
193
-        unlink($footerFile);
194
-
195
-        // output any errors
196
-        if ($retVal != 0) {
197
-            user_error('wkhtmltopdf failed: ' . implode("\n", $output), E_USER_ERROR);
198
-        }
199
-
200
-        // serve the generated file
201
-        return HTTPRequest::send_file(file_get_contents($pdfFile), basename($pdfFile), 'application/pdf');
202
-    }
203
-
204
-    /**
205
-     * Site search form
206
-     */
207
-    public function SearchForm()
208
-    {
209
-        $searchText = $this->getRequest()->getVar('Search');
210
-
211
-        $fields = FieldList::create(
212
-            TextField::create('Search', false, $searchText)
213
-        );
214
-        $actions = FieldList::create(
215
-            FormAction::create('results', _t('SilverStripe\\CMS\\Search\\SearchForm.GO', 'Go'))
216
-        );
217
-
218
-        $form = SearchForm::create($this, SearchForm::class, $fields, $actions);
219
-        $form->setFormAction('search/SearchForm');
220
-
221
-        return $form;
222
-    }
223
-
224
-    /**
225
-     * Get search form with _header suffix
226
-     *
227
-     * @return SearchForm
228
-     */
229
-    public function HeaderSearchForm()
230
-    {
231
-        return $this->SearchForm()->setTemplate('SearchForm_header');
232
-    }
233
-
234
-    /**
235
-     * Process and render search results.
236
-     *
237
-     * @param array $data The raw request data submitted by user
238
-     * @param SearchForm $form The form instance that was submitted
239
-     * @param HTTPRequest $request Request generated for this action
240
-     * @return DBHTMLText
241
-     */
242
-    public function results($data, $form, $request)
243
-    {
244
-        // Check parameters for terms, pagination, and if we should follow suggestions
245
-        $keywords = empty($data['Search']) ? '' : $data['Search'];
246
-        $start = isset($data['start']) ? $data['start'] : 0;
247
-        $suggestions = isset($data['suggestions'])
248
-            ? $data['suggestions']
249
-            : $this->config()->search_follow_suggestions;
250
-
251
-        $results = CwpSearchEngine::create()
252
-            ->search(
253
-                $keywords,
254
-                $this->getClassesToSearch(),
255
-                $this->getSearchIndex(),
256
-                $this->getSearchPageSize(),
257
-                $start,
258
-                $suggestions
259
-            );
260
-
261
-        // Customise content with these results
262
-        $properties = [
263
-            'MetaTitle' => _t(__CLASS__ . '.MetaTitle', 'Search {keywords}', ['keywords' => $keywords]),
264
-            'NoSearchResults' => _t(__CLASS__ . '.NoResult', 'Sorry, your search query did not return any results.'),
265
-            'EmptySearch' => _t(__CLASS__ . '.EmptySearch', 'Search field empty, please enter your search query.'),
266
-            'PdfLink' => '',
267
-            'Title' => _t('SilverStripe\\CMS\\Search\\SearchForm.SearchResults', 'Search Results'),
268
-        ];
269
-        $this->extend('updateSearchResults', $results, $properties);
270
-
271
-        // Customise page
272
-        $response = $this->customise($properties);
273
-        if ($results) {
274
-            $response = $response
275
-                ->customise($results)
276
-                ->customise(array( 'Results' => $results->getResults() ));
277
-        }
278
-
279
-        // Render
280
-        $templates = $this->getResultsTemplate($request);
281
-        return $response->renderWith($templates);
282
-    }
283
-
284
-    /**
285
-     * Select the template to render search results with
286
-     *
287
-     * @param HTTPRequest $request
288
-     * @return array
289
-     */
290
-    protected function getResultsTemplate($request)
291
-    {
292
-        $templates = [Page::class . '_results', Page::class];
293
-        if ($request->getVar('format') == 'rss') {
294
-            array_unshift($templates, 'Page_results_rss');
295
-        }
296
-        if ($request->getVar('format') == 'atom') {
297
-            array_unshift($templates, 'Page_results_atom');
298
-        }
299
-        return $templates;
300
-    }
301
-
302
-    /**
303
-     * Provide scripts as needed by the *default* theme.
304
-     * Override this function if you are using a custom theme based on the *default*.
305
-     *
306
-     * @deprecated 1.6..2.0 Use "starter" theme instead
307
-     */
308
-    public function getBaseScripts()
309
-    {
310
-        $scripts = array();
311
-        $this->extend('updateBaseScripts', $scripts);
312
-        return $scripts;
313
-    }
314
-
315
-    /**
316
-     * Provide stylesheets, as needed by the *default* theme assumed by this recipe.
317
-     * Override this function if you are using a custom theme based on the *default*.
318
-     *
319
-     * @deprecated 1.6..2.0 Use "starter" theme instead
320
-     */
321
-    public function getBaseStyles()
322
-    {
323
-        $styles = array();
324
-        $this->extend('updateBaseStyles', $styles);
325
-        return $styles;
326
-    }
327
-
328
-    /**
329
-     * Provide current year.
330
-     */
331
-    public function CurrentDatetime()
332
-    {
333
-        return DBDatetime::now();
334
-    }
335
-
336
-    public function getRSSLink()
337
-    {
338
-    }
339
-
340
-    /**
341
-     * Get the search index registered for this application
342
-     *
343
-     * @return CwpSearchIndex
344
-     */
345
-    protected function getSearchIndex()
346
-    {
347
-        // Will be a service name in 2.0 and returned via injector
348
-        /** @var CwpSearchIndex $index */
349
-        $index = null;
350
-        if (self::$search_index_class) {
351
-            $index = Injector::inst()->get(self::$search_index_class);
352
-        }
353
-        return $index;
354
-    }
355
-
356
-    /**
357
-     * Gets the list of configured classes to search
358
-     *
359
-     * @return array
360
-     */
361
-    protected function getClassesToSearch()
362
-    {
363
-        // Will be private static config in 2.0
364
-        return self::$classes_to_search;
365
-    }
366
-
367
-    /**
368
-     * Get page size for search
369
-     *
370
-     * @return int
371
-     */
372
-    protected function getSearchPageSize()
373
-    {
374
-        // Will be private static config in 2.0
375
-        return self::$results_per_page;
376
-    }
103
+	public function getPDFProxy($pdfBaseUrl)
104
+	{
105
+		if (!Environment::getEnv('CWP_SECURE_DOMAIN')
106
+			|| $pdfBaseUrl == Environment::getEnv('CWP_SECURE_DOMAIN') . '/'
107
+		) {
108
+			$proxy = '';
109
+		} else {
110
+			$proxy = ' --proxy ' . Environment::getEnv('SS_OUTBOUND_PROXY')
111
+				. ':' . Environment::getEnv('SS_OUTBOUND_PROXY_PORT');
112
+		}
113
+		return $proxy;
114
+	}
115
+
116
+	/**
117
+	 * Render the page as PDF using wkhtmltopdf.
118
+	 */
119
+	public function generatePDF()
120
+	{
121
+		if (!Config::inst()->get(BasePage::class, 'pdf_export')) {
122
+			return false;
123
+		}
124
+
125
+		$binaryPath = Config::inst()->get(BasePage::class, 'wkhtmltopdf_binary');
126
+		if (!$binaryPath || !is_executable($binaryPath)) {
127
+			if (Environment::getEnv('WKHTMLTOPDF_BINARY')
128
+				&& is_executable(Environment::getEnv('WKHTMLTOPDF_BINARY'))
129
+			) {
130
+				$binaryPath = Environment::getEnv('WKHTMLTOPDF_BINARY');
131
+			}
132
+		}
133
+
134
+		if (!$binaryPath) {
135
+			user_error('Neither WKHTMLTOPDF_BINARY nor BasePage.wkhtmltopdf_binary are defined', E_USER_ERROR);
136
+		}
137
+
138
+		if (Versioned::get_reading_mode() == 'Stage.Stage') {
139
+			user_error('Generating PDFs on draft is not supported', E_USER_ERROR);
140
+		}
141
+
142
+		set_time_limit(60);
143
+
144
+		// prepare the paths
145
+		$pdfFile = $this->dataRecord->getPdfFilename();
146
+		$bodyFile = str_replace('.pdf', '_pdf.html', $pdfFile);
147
+		$footerFile = str_replace('.pdf', '_pdffooter.html', $pdfFile);
148
+
149
+		// make sure the work directory exists
150
+		if (!file_exists(dirname($pdfFile))) {
151
+			Filesystem::makeFolder(dirname($pdfFile));
152
+		}
153
+
154
+		//decide the domain to use in generation
155
+		$pdfBaseUrl = $this->getPDFBaseURL();
156
+
157
+		// Force http protocol on CWP - fetching from localhost without using the proxy, SSL terminates on gateway.
158
+		if (Environment::getEnv('CWP_ENVIRONMENT')) {
159
+			Config::modify()->set(Director::class, 'alternate_protocol', 'http');
160
+			//only set alternate protocol if CWP_SECURE_DOMAIN is defined OR pdf_base_url is
161
+			if ($pdfBaseUrl) {
162
+				Config::modify()->set(Director::class, 'alternate_base_url', 'http://' . $pdfBaseUrl);
163
+			}
164
+		}
165
+
166
+		$bodyViewer = $this->getViewer('pdf');
167
+
168
+		// write the output of this page to HTML, ready for conversion to PDF
169
+		file_put_contents($bodyFile, $bodyViewer->process($this));
170
+
171
+		// get the viewer for the current template with _pdffooter
172
+		$footerViewer = $this->getViewer('pdffooter');
173
+
174
+		// write the output of the footer template to HTML, ready for conversion to PDF
175
+		file_put_contents($footerFile, $footerViewer->process($this));
176
+
177
+		//decide what the proxy should look like
178
+		$proxy = $this->getPDFProxy($pdfBaseUrl);
179
+
180
+		// finally, generate the PDF
181
+		$command = $binaryPath . $proxy . ' --outline -B 40pt -L 20pt -R 20pt -T 20pt --encoding utf-8 '
182
+			. '--orientation Portrait --disable-javascript --quiet --print-media-type ';
183
+		$retVal = 0;
184
+		$output = array();
185
+		exec(
186
+			$command . " --footer-html \"$footerFile\" \"$bodyFile\" \"$pdfFile\" &> /dev/stdout",
187
+			$output,
188
+			$retVal
189
+		);
190
+
191
+		// remove temporary file
192
+		unlink($bodyFile);
193
+		unlink($footerFile);
194
+
195
+		// output any errors
196
+		if ($retVal != 0) {
197
+			user_error('wkhtmltopdf failed: ' . implode("\n", $output), E_USER_ERROR);
198
+		}
199
+
200
+		// serve the generated file
201
+		return HTTPRequest::send_file(file_get_contents($pdfFile), basename($pdfFile), 'application/pdf');
202
+	}
203
+
204
+	/**
205
+	 * Site search form
206
+	 */
207
+	public function SearchForm()
208
+	{
209
+		$searchText = $this->getRequest()->getVar('Search');
210
+
211
+		$fields = FieldList::create(
212
+			TextField::create('Search', false, $searchText)
213
+		);
214
+		$actions = FieldList::create(
215
+			FormAction::create('results', _t('SilverStripe\\CMS\\Search\\SearchForm.GO', 'Go'))
216
+		);
217
+
218
+		$form = SearchForm::create($this, SearchForm::class, $fields, $actions);
219
+		$form->setFormAction('search/SearchForm');
220
+
221
+		return $form;
222
+	}
223
+
224
+	/**
225
+	 * Get search form with _header suffix
226
+	 *
227
+	 * @return SearchForm
228
+	 */
229
+	public function HeaderSearchForm()
230
+	{
231
+		return $this->SearchForm()->setTemplate('SearchForm_header');
232
+	}
233
+
234
+	/**
235
+	 * Process and render search results.
236
+	 *
237
+	 * @param array $data The raw request data submitted by user
238
+	 * @param SearchForm $form The form instance that was submitted
239
+	 * @param HTTPRequest $request Request generated for this action
240
+	 * @return DBHTMLText
241
+	 */
242
+	public function results($data, $form, $request)
243
+	{
244
+		// Check parameters for terms, pagination, and if we should follow suggestions
245
+		$keywords = empty($data['Search']) ? '' : $data['Search'];
246
+		$start = isset($data['start']) ? $data['start'] : 0;
247
+		$suggestions = isset($data['suggestions'])
248
+			? $data['suggestions']
249
+			: $this->config()->search_follow_suggestions;
250
+
251
+		$results = CwpSearchEngine::create()
252
+			->search(
253
+				$keywords,
254
+				$this->getClassesToSearch(),
255
+				$this->getSearchIndex(),
256
+				$this->getSearchPageSize(),
257
+				$start,
258
+				$suggestions
259
+			);
260
+
261
+		// Customise content with these results
262
+		$properties = [
263
+			'MetaTitle' => _t(__CLASS__ . '.MetaTitle', 'Search {keywords}', ['keywords' => $keywords]),
264
+			'NoSearchResults' => _t(__CLASS__ . '.NoResult', 'Sorry, your search query did not return any results.'),
265
+			'EmptySearch' => _t(__CLASS__ . '.EmptySearch', 'Search field empty, please enter your search query.'),
266
+			'PdfLink' => '',
267
+			'Title' => _t('SilverStripe\\CMS\\Search\\SearchForm.SearchResults', 'Search Results'),
268
+		];
269
+		$this->extend('updateSearchResults', $results, $properties);
270
+
271
+		// Customise page
272
+		$response = $this->customise($properties);
273
+		if ($results) {
274
+			$response = $response
275
+				->customise($results)
276
+				->customise(array( 'Results' => $results->getResults() ));
277
+		}
278
+
279
+		// Render
280
+		$templates = $this->getResultsTemplate($request);
281
+		return $response->renderWith($templates);
282
+	}
283
+
284
+	/**
285
+	 * Select the template to render search results with
286
+	 *
287
+	 * @param HTTPRequest $request
288
+	 * @return array
289
+	 */
290
+	protected function getResultsTemplate($request)
291
+	{
292
+		$templates = [Page::class . '_results', Page::class];
293
+		if ($request->getVar('format') == 'rss') {
294
+			array_unshift($templates, 'Page_results_rss');
295
+		}
296
+		if ($request->getVar('format') == 'atom') {
297
+			array_unshift($templates, 'Page_results_atom');
298
+		}
299
+		return $templates;
300
+	}
301
+
302
+	/**
303
+	 * Provide scripts as needed by the *default* theme.
304
+	 * Override this function if you are using a custom theme based on the *default*.
305
+	 *
306
+	 * @deprecated 1.6..2.0 Use "starter" theme instead
307
+	 */
308
+	public function getBaseScripts()
309
+	{
310
+		$scripts = array();
311
+		$this->extend('updateBaseScripts', $scripts);
312
+		return $scripts;
313
+	}
314
+
315
+	/**
316
+	 * Provide stylesheets, as needed by the *default* theme assumed by this recipe.
317
+	 * Override this function if you are using a custom theme based on the *default*.
318
+	 *
319
+	 * @deprecated 1.6..2.0 Use "starter" theme instead
320
+	 */
321
+	public function getBaseStyles()
322
+	{
323
+		$styles = array();
324
+		$this->extend('updateBaseStyles', $styles);
325
+		return $styles;
326
+	}
327
+
328
+	/**
329
+	 * Provide current year.
330
+	 */
331
+	public function CurrentDatetime()
332
+	{
333
+		return DBDatetime::now();
334
+	}
335
+
336
+	public function getRSSLink()
337
+	{
338
+	}
339
+
340
+	/**
341
+	 * Get the search index registered for this application
342
+	 *
343
+	 * @return CwpSearchIndex
344
+	 */
345
+	protected function getSearchIndex()
346
+	{
347
+		// Will be a service name in 2.0 and returned via injector
348
+		/** @var CwpSearchIndex $index */
349
+		$index = null;
350
+		if (self::$search_index_class) {
351
+			$index = Injector::inst()->get(self::$search_index_class);
352
+		}
353
+		return $index;
354
+	}
355
+
356
+	/**
357
+	 * Gets the list of configured classes to search
358
+	 *
359
+	 * @return array
360
+	 */
361
+	protected function getClassesToSearch()
362
+	{
363
+		// Will be private static config in 2.0
364
+		return self::$classes_to_search;
365
+	}
366
+
367
+	/**
368
+	 * Get page size for search
369
+	 *
370
+	 * @return int
371
+	 */
372
+	protected function getSearchPageSize()
373
+	{
374
+		// Will be private static config in 2.0
375
+		return self::$results_per_page;
376
+	}
377 377
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -85,7 +85,7 @@  discard block
 block discarded – undo
85 85
     {
86 86
         //if base url YML is defined in YML, use that
87 87
         if (Config::inst()->get(BasePage::class, 'pdf_base_url')) {
88
-            $pdfBaseUrl = Config::inst()->get(BasePage::class, 'pdf_base_url').'/';
88
+            $pdfBaseUrl = Config::inst()->get(BasePage::class, 'pdf_base_url') . '/';
89 89
             //otherwise, if we are CWP use the secure domain
90 90
         } elseif (Environment::getEnv('CWP_SECURE_DOMAIN')) {
91 91
             $pdfBaseUrl = Environment::getEnv('CWP_SECURE_DOMAIN') . '/';
@@ -273,7 +273,7 @@  discard block
 block discarded – undo
273 273
         if ($results) {
274 274
             $response = $response
275 275
                 ->customise($results)
276
-                ->customise(array( 'Results' => $results->getResults() ));
276
+                ->customise(array('Results' => $results->getResults()));
277 277
         }
278 278
 
279 279
         // Render
Please login to merge, or discard this patch.
src/PageTypes/EventHolder.php 1 patch
Indentation   +53 added lines, -53 removed lines patch added patch discarded remove patch
@@ -7,57 +7,57 @@
 block discarded – undo
7 7
 
8 8
 class EventHolder extends DatedUpdateHolder
9 9
 {
10
-    private static $description = 'Container page for Event Pages, provides event filtering and pagination';
11
-
12
-    private static $allowed_children = [
13
-        EventPage::class,
14
-    ];
15
-
16
-    private static $default_child = EventPage::class;
17
-
18
-    private static $update_name = 'Events';
19
-
20
-    private static $update_class = EventPage::class;
21
-
22
-    private static $icon = 'cwp/cwp:images/icons/sitetree_images/event_holder.png';
23
-
24
-    private static $singular_name = 'Event Holder';
25
-
26
-    private static $plural_name = 'Event Holders';
27
-
28
-    private static $table_name = 'EventHolder';
29
-
30
-    /**
31
-     * Find all site's news items, based on some filters.
32
-     * Omitting parameters will prevent relevant filters from being applied. The filters are ANDed together.
33
-     *
34
-     * @param string $className The name of the class to fetch.
35
-     * @param int $parentID The ID of the holder to extract the news items from.
36
-     * @param int $tagID The ID of the tag to filter the news items by.
37
-     * @param string $dateFrom The beginning of a date filter range.
38
-     * @param string $dateTo The end of the date filter range. If empty, only one day will be searched for.
39
-     * @param int $year Numeric value of the year to show.
40
-     * @param int $monthNumber Numeric value of the month to show.
41
-     *
42
-     * @returns DataList|PaginatedList
43
-     */
44
-    public static function AllUpdates(
45
-        $className = 'Events',
46
-        $parentID = null,
47
-        $tagID = null,
48
-        $dateFrom = null,
49
-        $dateTo = null,
50
-        $year = null,
51
-        $monthNumber = null
52
-    ) {
53
-        return parent::AllUpdates(
54
-            $className,
55
-            $parentID,
56
-            $tagID,
57
-            $dateFrom,
58
-            $dateTo,
59
-            $year,
60
-            $monthNumber
61
-        )->Sort('Date', 'ASC');
62
-    }
10
+	private static $description = 'Container page for Event Pages, provides event filtering and pagination';
11
+
12
+	private static $allowed_children = [
13
+		EventPage::class,
14
+	];
15
+
16
+	private static $default_child = EventPage::class;
17
+
18
+	private static $update_name = 'Events';
19
+
20
+	private static $update_class = EventPage::class;
21
+
22
+	private static $icon = 'cwp/cwp:images/icons/sitetree_images/event_holder.png';
23
+
24
+	private static $singular_name = 'Event Holder';
25
+
26
+	private static $plural_name = 'Event Holders';
27
+
28
+	private static $table_name = 'EventHolder';
29
+
30
+	/**
31
+	 * Find all site's news items, based on some filters.
32
+	 * Omitting parameters will prevent relevant filters from being applied. The filters are ANDed together.
33
+	 *
34
+	 * @param string $className The name of the class to fetch.
35
+	 * @param int $parentID The ID of the holder to extract the news items from.
36
+	 * @param int $tagID The ID of the tag to filter the news items by.
37
+	 * @param string $dateFrom The beginning of a date filter range.
38
+	 * @param string $dateTo The end of the date filter range. If empty, only one day will be searched for.
39
+	 * @param int $year Numeric value of the year to show.
40
+	 * @param int $monthNumber Numeric value of the month to show.
41
+	 *
42
+	 * @returns DataList|PaginatedList
43
+	 */
44
+	public static function AllUpdates(
45
+		$className = 'Events',
46
+		$parentID = null,
47
+		$tagID = null,
48
+		$dateFrom = null,
49
+		$dateTo = null,
50
+		$year = null,
51
+		$monthNumber = null
52
+	) {
53
+		return parent::AllUpdates(
54
+			$className,
55
+			$parentID,
56
+			$tagID,
57
+			$dateFrom,
58
+			$dateTo,
59
+			$year,
60
+			$monthNumber
61
+		)->Sort('Date', 'ASC');
62
+	}
63 63
 }
Please login to merge, or discard this patch.
src/PageTypes/NewsHolder.php 1 patch
Indentation   +46 added lines, -46 removed lines patch added patch discarded remove patch
@@ -7,50 +7,50 @@
 block discarded – undo
7 7
 
8 8
 class NewsHolder extends DatedUpdateHolder
9 9
 {
10
-    private static $description = 'Container page for News Pages, provides news filtering and pagination';
11
-
12
-    private static $allowed_children = [
13
-        NewsPage::class,
14
-    ];
15
-
16
-    private static $default_child = NewsPage::class;
17
-
18
-    private static $update_name = 'News';
19
-
20
-    private static $update_class = NewsPage::class;
21
-
22
-    private static $icon = 'cwp/cwp:images/icons/sitetree_images/news_listing.png';
23
-
24
-    private static $singular_name = 'News Holder';
25
-
26
-    private static $plural_name = 'News Holders';
27
-
28
-    private static $table_name = 'NewsHolder';
29
-
30
-    /**
31
-     * Find all site's news items, based on some filters.
32
-     * Omitting parameters will prevent relevant filters from being applied. The filters are ANDed together.
33
-     *
34
-     * @param string $className The name of the class to fetch.
35
-     * @param int $parentID The ID of the holder to extract the news items from.
36
-     * @param int $tagID The ID of the tag to filter the news items by.
37
-     * @param string $dateFrom The beginning of a date filter range.
38
-     * @param string $dateTo The end of the date filter range. If empty, only one day will be searched for.
39
-     * @param int $year Numeric value of the year to show.
40
-     * @param int $monthNumber Numeric value of the month to show.
41
-     *
42
-     * @returns DataList|PaginatedList
43
-     */
44
-    public static function AllUpdates(
45
-        $className = NewsPage::class,
46
-        $parentID = null,
47
-        $tagID = null,
48
-        $dateFrom = null,
49
-        $dateTo = null,
50
-        $year = null,
51
-        $monthNumber = null
52
-    ) {
53
-        return parent::AllUpdates($className, $parentID, $tagID, $dateFrom, $dateTo, $year, $monthNumber)
54
-            ->Sort('Date', 'DESC');
55
-    }
10
+	private static $description = 'Container page for News Pages, provides news filtering and pagination';
11
+
12
+	private static $allowed_children = [
13
+		NewsPage::class,
14
+	];
15
+
16
+	private static $default_child = NewsPage::class;
17
+
18
+	private static $update_name = 'News';
19
+
20
+	private static $update_class = NewsPage::class;
21
+
22
+	private static $icon = 'cwp/cwp:images/icons/sitetree_images/news_listing.png';
23
+
24
+	private static $singular_name = 'News Holder';
25
+
26
+	private static $plural_name = 'News Holders';
27
+
28
+	private static $table_name = 'NewsHolder';
29
+
30
+	/**
31
+	 * Find all site's news items, based on some filters.
32
+	 * Omitting parameters will prevent relevant filters from being applied. The filters are ANDed together.
33
+	 *
34
+	 * @param string $className The name of the class to fetch.
35
+	 * @param int $parentID The ID of the holder to extract the news items from.
36
+	 * @param int $tagID The ID of the tag to filter the news items by.
37
+	 * @param string $dateFrom The beginning of a date filter range.
38
+	 * @param string $dateTo The end of the date filter range. If empty, only one day will be searched for.
39
+	 * @param int $year Numeric value of the year to show.
40
+	 * @param int $monthNumber Numeric value of the month to show.
41
+	 *
42
+	 * @returns DataList|PaginatedList
43
+	 */
44
+	public static function AllUpdates(
45
+		$className = NewsPage::class,
46
+		$parentID = null,
47
+		$tagID = null,
48
+		$dateFrom = null,
49
+		$dateTo = null,
50
+		$year = null,
51
+		$monthNumber = null
52
+	) {
53
+		return parent::AllUpdates($className, $parentID, $tagID, $dateFrom, $dateTo, $year, $monthNumber)
54
+			->Sort('Date', 'DESC');
55
+	}
56 56
 }
Please login to merge, or discard this patch.
src/PageTypes/EventHolderController.php 1 patch
Indentation   +41 added lines, -41 removed lines patch added patch discarded remove patch
@@ -19,53 +19,53 @@
 block discarded – undo
19 19
  */
20 20
 class EventHolderController extends DatedUpdateHolderController
21 21
 {
22
-    public function getUpdateName()
23
-    {
24
-        $params = $this->parseParams();
25
-        if ($params['upcomingOnly']) {
26
-            return _t('CWP\\CWP\\PageTypes\\EventHolder.Upcoming', 'Upcoming events');
27
-        }
22
+	public function getUpdateName()
23
+	{
24
+		$params = $this->parseParams();
25
+		if ($params['upcomingOnly']) {
26
+			return _t('CWP\\CWP\\PageTypes\\EventHolder.Upcoming', 'Upcoming events');
27
+		}
28 28
 
29
-        return 'Events';
30
-    }
29
+		return 'Events';
30
+	}
31 31
 
32
-    /**
33
-     * Parse URL parameters.
34
-     *
35
-     * @param boolean $produceErrorMessages Set to false to omit session messages.
36
-     */
37
-    public function parseParams($produceErrorMessages = true)
38
-    {
39
-        $params = parent::parseParams($produceErrorMessages);
32
+	/**
33
+	 * Parse URL parameters.
34
+	 *
35
+	 * @param boolean $produceErrorMessages Set to false to omit session messages.
36
+	 */
37
+	public function parseParams($produceErrorMessages = true)
38
+	{
39
+		$params = parent::parseParams($produceErrorMessages);
40 40
 
41
-        // We need to set whether or not we're supposed to be displaying only upcoming events or all events.
42
-        $params['upcomingOnly'] = !($params['from'] || $params['to'] || $params['year'] || $params['month']);
41
+		// We need to set whether or not we're supposed to be displaying only upcoming events or all events.
42
+		$params['upcomingOnly'] = !($params['from'] || $params['to'] || $params['year'] || $params['month']);
43 43
 
44
-        return $params;
45
-    }
44
+		return $params;
45
+	}
46 46
 
47
-    /**
48
-     * Get the events based on the current query.
49
-     */
50
-    public function FilteredUpdates($pageSize = 20)
51
-    {
52
-        $params = $this->parseParams();
47
+	/**
48
+	 * Get the events based on the current query.
49
+	 */
50
+	public function FilteredUpdates($pageSize = 20)
51
+	{
52
+		$params = $this->parseParams();
53 53
 
54
-        $items = $this->Updates(
55
-            $params['tag'],
56
-            $params['from'],
57
-            $params['to'],
58
-            $params['year'],
59
-            $params['month']
60
-        );
54
+		$items = $this->Updates(
55
+			$params['tag'],
56
+			$params['from'],
57
+			$params['to'],
58
+			$params['year'],
59
+			$params['month']
60
+		);
61 61
 
62
-        if ($params['upcomingOnly']) {
63
-            $items = $items->filter(['Date:LessThan:Not' => DBDatetime::now()->Format('y-MM-dd')]);
64
-        }
62
+		if ($params['upcomingOnly']) {
63
+			$items = $items->filter(['Date:LessThan:Not' => DBDatetime::now()->Format('y-MM-dd')]);
64
+		}
65 65
 
66
-        // Apply pagination
67
-        $list = PaginatedList::create($items, $this->getRequest());
68
-        $list->setPageLength($pageSize);
69
-        return $list;
70
-    }
66
+		// Apply pagination
67
+		$list = PaginatedList::create($items, $this->getRequest());
68
+		$list->setPageLength($pageSize);
69
+		return $list;
70
+	}
71 71
 }
Please login to merge, or discard this patch.
src/PageTypes/DatedUpdateHolderController.php 1 patch
Indentation   +342 added lines, -342 removed lines patch added patch discarded remove patch
@@ -33,357 +33,357 @@
 block discarded – undo
33 33
  */
34 34
 class DatedUpdateHolderController extends PageController
35 35
 {
36
-    private static $allowed_actions = [
37
-        'rss',
38
-        'atom',
39
-        'DateRangeForm',
40
-    ];
41
-
42
-    private static $casting = [
43
-        'MetaTitle' => 'Text',
44
-        'FilterDescription' => 'Text',
45
-    ];
46
-
47
-    /**
48
-     * Get the meta title for the current action
49
-     *
50
-     * @return string
51
-     */
52
-    public function getMetaTitle()
53
-    {
54
-        $title = $this->data()->getTitle();
55
-        $filter = $this->FilterDescription();
56
-        if ($filter) {
57
-            $title = "{$title} - {$filter}";
58
-        }
59
-
60
-        $this->extend('updateMetaTitle', $title);
61
-        return $title;
62
-    }
63
-
64
-    /**
65
-     * Returns a description of the current filter
66
-     *
67
-     * @return string
68
-     */
69
-    public function FilterDescription()
70
-    {
71
-        $params = $this->parseParams();
72
-
73
-        $filters = array();
74
-        if ($params['tag']) {
75
-            $term = TaxonomyTerm::get_by_id(TaxonomyTerm::class, $params['tag']);
76
-            if ($term) {
77
-                $filters[] = _t(
78
-                    'CWP\\CWP\\PageTypes\\DatedUpdateHolder.FILTER_WITHIN',
79
-                    'within'
80
-                ) . ' "' . $term->Name . '"';
81
-            }
82
-        }
83
-
84
-        if ($params['from'] || $params['to']) {
85
-            if ($params['from']) {
86
-                $from = strtotime($params['from']);
87
-                if ($params['to']) {
88
-                    $to = strtotime($params['to']);
89
-                    $filters[] = _t('CWP\\CWP\\PageTypes\\DatedUpdateHolder.FILTER_BETWEEN', 'between') . ' '
90
-                        . date('j/m/Y', $from) . ' and ' . date('j/m/Y', $to);
91
-                } else {
92
-                    $filters[] = _t('CWP\\CWP\\PageTypes\\DatedUpdateHolder.FILTER_ON', 'on')
93
-                        . ' ' . date('j/m/Y', $from);
94
-                }
95
-            } else {
96
-                $to = strtotime($params['to']);
97
-                $filters[] = _t('CWP\\CWP\\PageTypes\\DatedUpdateHolder.FILTER_ON', 'on')
98
-                    . ' ' . date('j/m/Y', $to);
99
-            }
100
-        }
101
-
102
-        if ($params['year'] && $params['month']) {
103
-            $timestamp = mktime(1, 1, 1, $params['month'], 1, $params['year']);
104
-            $filters[] = _t('CWP\\CWP\\PageTypes\\DatedUpdateHolder.FILTER_IN', 'in')
105
-                . ' ' . date('F', $timestamp) . ' ' . $params['year'];
106
-        }
107
-
108
-        if ($filters) {
109
-            return $this->getUpdateName() . ' ' . implode(' ', $filters);
110
-        }
111
-    }
112
-
113
-    public function getUpdateName()
114
-    {
115
-        return Config::inst()->get($this->data()->ClassName, 'update_name');
116
-    }
117
-
118
-    protected function init()
119
-    {
120
-        parent::init();
121
-        RSSFeed::linkToFeed($this->Link() . 'rss', $this->getSubscriptionTitle());
122
-    }
123
-
124
-    /**
125
-     * Parse URL parameters.
126
-     *
127
-     * @param bool $produceErrorMessages Set to false to omit session messages.
128
-     */
129
-    public function parseParams($produceErrorMessages = true)
130
-    {
131
-        $tag = $this->request->getVar('tag');
132
-        $from = $this->request->getVar('from');
133
-        $to = $this->request->getVar('to');
134
-        $year = $this->request->getVar('year');
135
-        $month = $this->request->getVar('month');
136
-
137
-        if ($tag == '') {
138
-            $tag = null;
139
-        }
140
-        if ($from == '') {
141
-            $from = null;
142
-        }
143
-        if ($to == '') {
144
-            $to = null;
145
-        }
146
-        if ($year == '') {
147
-            $year = null;
148
-        }
149
-        if ($month == '') {
150
-            $month = null;
151
-        }
152
-
153
-        if (isset($tag)) {
154
-            $tag = (int)$tag;
155
-        }
156
-        if (isset($from)) {
157
-            $from = urldecode($from);
158
-            $parser = DBDatetime::create();
159
-            $parser->setValue($from);
160
-            $from = $parser->Format('y-MM-dd');
161
-        }
162
-        if (isset($to)) {
163
-            $to = urldecode($to);
164
-            $parser = DBDatetime::create();
165
-            $parser->setValue($to);
166
-            $to = $parser->Format('y-MM-dd');
167
-        }
168
-        if (isset($year)) {
169
-            $year = (int)$year;
170
-        }
171
-        if (isset($month)) {
172
-            $month = (int)$month;
173
-        }
174
-
175
-        // If only "To" has been provided filter by single date. Normalise by swapping with "From".
176
-        if (isset($to) && !isset($from)) {
177
-            list($to, $from) = array($from, $to);
178
-        }
179
-
180
-        // Flip the dates if the order is wrong.
181
-        if (isset($to) && isset($from) && strtotime($from)>strtotime($to)) {
182
-            list($to, $from) = array($from, $to);
183
-
184
-            if ($produceErrorMessages) {
185
-                // @todo replace
36
+	private static $allowed_actions = [
37
+		'rss',
38
+		'atom',
39
+		'DateRangeForm',
40
+	];
41
+
42
+	private static $casting = [
43
+		'MetaTitle' => 'Text',
44
+		'FilterDescription' => 'Text',
45
+	];
46
+
47
+	/**
48
+	 * Get the meta title for the current action
49
+	 *
50
+	 * @return string
51
+	 */
52
+	public function getMetaTitle()
53
+	{
54
+		$title = $this->data()->getTitle();
55
+		$filter = $this->FilterDescription();
56
+		if ($filter) {
57
+			$title = "{$title} - {$filter}";
58
+		}
59
+
60
+		$this->extend('updateMetaTitle', $title);
61
+		return $title;
62
+	}
63
+
64
+	/**
65
+	 * Returns a description of the current filter
66
+	 *
67
+	 * @return string
68
+	 */
69
+	public function FilterDescription()
70
+	{
71
+		$params = $this->parseParams();
72
+
73
+		$filters = array();
74
+		if ($params['tag']) {
75
+			$term = TaxonomyTerm::get_by_id(TaxonomyTerm::class, $params['tag']);
76
+			if ($term) {
77
+				$filters[] = _t(
78
+					'CWP\\CWP\\PageTypes\\DatedUpdateHolder.FILTER_WITHIN',
79
+					'within'
80
+				) . ' "' . $term->Name . '"';
81
+			}
82
+		}
83
+
84
+		if ($params['from'] || $params['to']) {
85
+			if ($params['from']) {
86
+				$from = strtotime($params['from']);
87
+				if ($params['to']) {
88
+					$to = strtotime($params['to']);
89
+					$filters[] = _t('CWP\\CWP\\PageTypes\\DatedUpdateHolder.FILTER_BETWEEN', 'between') . ' '
90
+						. date('j/m/Y', $from) . ' and ' . date('j/m/Y', $to);
91
+				} else {
92
+					$filters[] = _t('CWP\\CWP\\PageTypes\\DatedUpdateHolder.FILTER_ON', 'on')
93
+						. ' ' . date('j/m/Y', $from);
94
+				}
95
+			} else {
96
+				$to = strtotime($params['to']);
97
+				$filters[] = _t('CWP\\CWP\\PageTypes\\DatedUpdateHolder.FILTER_ON', 'on')
98
+					. ' ' . date('j/m/Y', $to);
99
+			}
100
+		}
101
+
102
+		if ($params['year'] && $params['month']) {
103
+			$timestamp = mktime(1, 1, 1, $params['month'], 1, $params['year']);
104
+			$filters[] = _t('CWP\\CWP\\PageTypes\\DatedUpdateHolder.FILTER_IN', 'in')
105
+				. ' ' . date('F', $timestamp) . ' ' . $params['year'];
106
+		}
107
+
108
+		if ($filters) {
109
+			return $this->getUpdateName() . ' ' . implode(' ', $filters);
110
+		}
111
+	}
112
+
113
+	public function getUpdateName()
114
+	{
115
+		return Config::inst()->get($this->data()->ClassName, 'update_name');
116
+	}
117
+
118
+	protected function init()
119
+	{
120
+		parent::init();
121
+		RSSFeed::linkToFeed($this->Link() . 'rss', $this->getSubscriptionTitle());
122
+	}
123
+
124
+	/**
125
+	 * Parse URL parameters.
126
+	 *
127
+	 * @param bool $produceErrorMessages Set to false to omit session messages.
128
+	 */
129
+	public function parseParams($produceErrorMessages = true)
130
+	{
131
+		$tag = $this->request->getVar('tag');
132
+		$from = $this->request->getVar('from');
133
+		$to = $this->request->getVar('to');
134
+		$year = $this->request->getVar('year');
135
+		$month = $this->request->getVar('month');
136
+
137
+		if ($tag == '') {
138
+			$tag = null;
139
+		}
140
+		if ($from == '') {
141
+			$from = null;
142
+		}
143
+		if ($to == '') {
144
+			$to = null;
145
+		}
146
+		if ($year == '') {
147
+			$year = null;
148
+		}
149
+		if ($month == '') {
150
+			$month = null;
151
+		}
152
+
153
+		if (isset($tag)) {
154
+			$tag = (int)$tag;
155
+		}
156
+		if (isset($from)) {
157
+			$from = urldecode($from);
158
+			$parser = DBDatetime::create();
159
+			$parser->setValue($from);
160
+			$from = $parser->Format('y-MM-dd');
161
+		}
162
+		if (isset($to)) {
163
+			$to = urldecode($to);
164
+			$parser = DBDatetime::create();
165
+			$parser->setValue($to);
166
+			$to = $parser->Format('y-MM-dd');
167
+		}
168
+		if (isset($year)) {
169
+			$year = (int)$year;
170
+		}
171
+		if (isset($month)) {
172
+			$month = (int)$month;
173
+		}
174
+
175
+		// If only "To" has been provided filter by single date. Normalise by swapping with "From".
176
+		if (isset($to) && !isset($from)) {
177
+			list($to, $from) = array($from, $to);
178
+		}
179
+
180
+		// Flip the dates if the order is wrong.
181
+		if (isset($to) && isset($from) && strtotime($from)>strtotime($to)) {
182
+			list($to, $from) = array($from, $to);
183
+
184
+			if ($produceErrorMessages) {
185
+				// @todo replace
186 186
 //                Session::setFormMessage(
187 187
 //                    'Form_DateRangeForm',
188 188
 //                    _t('DateUpdateHolder.FilterAppliedMessage', 'Filter has been applied with the dates reversed.'),
189 189
 //                    'warning'
190 190
 //                );
191
-            }
192
-        }
191
+			}
192
+		}
193 193
 
194
-        // Notify the user that filtering by single date is taking place.
195
-        if (isset($from) && !isset($to)) {
196
-            if ($produceErrorMessages) {
197
-                // @todo replace
194
+		// Notify the user that filtering by single date is taking place.
195
+		if (isset($from) && !isset($to)) {
196
+			if ($produceErrorMessages) {
197
+				// @todo replace
198 198
 //                Session::setFormMessage(
199 199
 //                    'Form_DateRangeForm',
200 200
 //                    _t('DateUpdateHolder.DateRangeFilterMessage', 'Filtered by a single date.'),
201 201
 //                    'warning'
202 202
 //                );
203
-            }
204
-        }
205
-
206
-        return [
207
-            'tag' => $tag,
208
-            'from' => $from,
209
-            'to' => $to,
210
-            'year' => $year,
211
-            'month' => $month,
212
-        ];
213
-    }
214
-
215
-    /**
216
-     * Build the link - keep the date range, reset the rest.
217
-     */
218
-    public function AllTagsLink()
219
-    {
220
-        $link = HTTP::setGetVar('tag', null, null, '&');
221
-        $link = HTTP::setGetVar('month', null, $link, '&');
222
-        $link = HTTP::setGetVar('year', null, $link, '&');
223
-        $link = HTTP::setGetVar('start', null, $link, '&');
224
-
225
-        return $link;
226
-    }
227
-
228
-    /**
229
-     * List tags and attach links.
230
-     */
231
-    public function UpdateTagsWithLinks()
232
-    {
233
-        $tags = $this->UpdateTags();
234
-
235
-        $processed = ArrayList::create();
236
-
237
-        foreach ($tags as $tag) {
238
-            // Build the link - keep the tag, and date range, but reset month, year and pagination.
239
-            $link = HTTP::setGetVar('tag', $tag->ID, null, '&');
240
-            $link = HTTP::setGetVar('month', null, $link, '&');
241
-            $link = HTTP::setGetVar('year', null, $link, '&');
242
-            $link = HTTP::setGetVar('start', null, $link, '&');
243
-
244
-            $tag->Link = $link;
245
-            $processed->push($tag);
246
-        }
247
-
248
-        return $processed;
249
-    }
250
-
251
-    /**
252
-     * Get the TaxonomyTerm related to the current tag GET parameter.
253
-     */
254
-    public function CurrentTag()
255
-    {
256
-        $tagID = $this->request->getVar('tag');
257
-
258
-        if (isset($tagID)) {
259
-            return TaxonomyTerm::get_by_id(TaxonomyTerm::class, (int)$tagID);
260
-        }
261
-    }
262
-
263
-    /**
264
-     * Extract the available months based on the current query.
265
-     * Only tag is respected. Pagination and months are ignored.
266
-     */
267
-    public function AvailableMonths()
268
-    {
269
-        $params = $this->parseParams();
270
-
271
-        return DatedUpdateHolder::ExtractMonths(
272
-            $this->Updates($params['tag'], $params['from'], $params['to']),
273
-            Director::makeRelative($_SERVER['REQUEST_URI']),
274
-            $params['year'],
275
-            $params['month']
276
-        );
277
-    }
278
-
279
-    /**
280
-     * Get the updates based on the current query.
281
-     */
282
-    public function FilteredUpdates($pageSize = 20)
283
-    {
284
-        $params = $this->parseParams();
285
-
286
-        $items = $this->Updates(
287
-            $params['tag'],
288
-            $params['from'],
289
-            $params['to'],
290
-            $params['year'],
291
-            $params['month']
292
-        );
293
-
294
-        // Apply pagination
295
-        $list = PaginatedList::create($items, $this->getRequest());
296
-        $list->setPageLength($pageSize);
297
-        return $list;
298
-    }
299
-
300
-    /**
301
-     * @return Form
302
-     */
303
-    public function DateRangeForm()
304
-    {
305
-        $dateFromTitle = DBField::create_field('HTMLText', sprintf(
306
-            '%s <span class="field-note">%s</span>',
307
-            _t('CWP\\CWP\\PageTypes\\DatedUpdateHolder.FROM_DATE', 'From date'),
308
-            _t('CWP\\CWP\\PageTypes\\DatedUpdateHolder.DATE_EXAMPLE', '(example: 2017/12/30)')
309
-        ));
310
-        $dateToTitle = DBField::create_field('HTMLText', sprintf(
311
-            '%s <span class="field-note">%s</span>',
312
-            _t('CWP\\CWP\\PageTypes\\DatedUpdateHolder.TO_DATE', 'To date'),
313
-            _t('CWP\\CWP\\PageTypes\\DatedUpdateHolder.DATE_EXAMPLE', '(example: 2017/12/30)')
314
-        ));
315
-
316
-        $fields = FieldList::create(
317
-            DateField::create('from', $dateFromTitle),
318
-            DateField::create('to', $dateToTitle),
319
-            HiddenField::create('tag')
320
-        );
321
-
322
-        $actions = FieldList::create(
323
-            FormAction::create("doDateFilter")
324
-                ->setTitle(_t(__CLASS__ . '.Filter'))
325
-                ->addExtraClass('btn btn-primary primary'),
326
-            FormAction::create("doDateReset")
327
-                ->setTitle(_t(__CLASS__ . '.Clear'))
328
-                ->addExtraClass('btn')
329
-        );
330
-
331
-        $form = Form::create($this, 'DateRangeForm', $fields, $actions);
332
-        $form->loadDataFrom($this->request->getVars());
333
-        $form->setFormMethod('get');
334
-
335
-        // Manually extract the message so we can clear it.
336
-        $form->ErrorMessage = $form->getMessage();
337
-        $form->ErrorMessageType = $form->getMessageType();
338
-        $form->clearMessage();
339
-
340
-        return $form;
341
-    }
342
-
343
-    public function doDateFilter()
344
-    {
345
-        $params = $this->parseParams();
346
-
347
-        // Build the link - keep the tag, but reset month, year and pagination.
348
-        $link = HTTP::setGetVar('from', $params['from'], $this->AbsoluteLink(), '&');
349
-        $link = HTTP::setGetVar('to', $params['to'], $link, '&');
350
-        if (isset($params['tag'])) {
351
-            $link = HTTP::setGetVar('tag', $params['tag'], $link, '&');
352
-        }
353
-
354
-        $this->redirect($link);
355
-    }
356
-
357
-    public function doDateReset()
358
-    {
359
-        $params = $this->parseParams(false);
360
-
361
-        // Reset the link - only include the tag.
362
-        $link = $this->AbsoluteLink();
363
-        if (isset($params['tag'])) {
364
-            $link = HTTP::setGetVar('tag', $params['tag'], $link, '&');
365
-        }
366
-
367
-        $this->redirect($link);
368
-    }
369
-
370
-    public function rss()
371
-    {
372
-        $rss = RSSFeed::create(
373
-            $this->Updates()->sort('Created DESC')->limit(20),
374
-            $this->Link('rss'),
375
-            $this->getSubscriptionTitle()
376
-        );
377
-        return $rss->outputToBrowser();
378
-    }
379
-
380
-    public function atom()
381
-    {
382
-        $atom = CwpAtomFeed::create(
383
-            $this->Updates()->sort('Created DESC')->limit(20),
384
-            $this->Link('atom'),
385
-            $this->getSubscriptionTitle()
386
-        );
387
-        return $atom->outputToBrowser();
388
-    }
203
+			}
204
+		}
205
+
206
+		return [
207
+			'tag' => $tag,
208
+			'from' => $from,
209
+			'to' => $to,
210
+			'year' => $year,
211
+			'month' => $month,
212
+		];
213
+	}
214
+
215
+	/**
216
+	 * Build the link - keep the date range, reset the rest.
217
+	 */
218
+	public function AllTagsLink()
219
+	{
220
+		$link = HTTP::setGetVar('tag', null, null, '&');
221
+		$link = HTTP::setGetVar('month', null, $link, '&');
222
+		$link = HTTP::setGetVar('year', null, $link, '&');
223
+		$link = HTTP::setGetVar('start', null, $link, '&');
224
+
225
+		return $link;
226
+	}
227
+
228
+	/**
229
+	 * List tags and attach links.
230
+	 */
231
+	public function UpdateTagsWithLinks()
232
+	{
233
+		$tags = $this->UpdateTags();
234
+
235
+		$processed = ArrayList::create();
236
+
237
+		foreach ($tags as $tag) {
238
+			// Build the link - keep the tag, and date range, but reset month, year and pagination.
239
+			$link = HTTP::setGetVar('tag', $tag->ID, null, '&');
240
+			$link = HTTP::setGetVar('month', null, $link, '&');
241
+			$link = HTTP::setGetVar('year', null, $link, '&');
242
+			$link = HTTP::setGetVar('start', null, $link, '&');
243
+
244
+			$tag->Link = $link;
245
+			$processed->push($tag);
246
+		}
247
+
248
+		return $processed;
249
+	}
250
+
251
+	/**
252
+	 * Get the TaxonomyTerm related to the current tag GET parameter.
253
+	 */
254
+	public function CurrentTag()
255
+	{
256
+		$tagID = $this->request->getVar('tag');
257
+
258
+		if (isset($tagID)) {
259
+			return TaxonomyTerm::get_by_id(TaxonomyTerm::class, (int)$tagID);
260
+		}
261
+	}
262
+
263
+	/**
264
+	 * Extract the available months based on the current query.
265
+	 * Only tag is respected. Pagination and months are ignored.
266
+	 */
267
+	public function AvailableMonths()
268
+	{
269
+		$params = $this->parseParams();
270
+
271
+		return DatedUpdateHolder::ExtractMonths(
272
+			$this->Updates($params['tag'], $params['from'], $params['to']),
273
+			Director::makeRelative($_SERVER['REQUEST_URI']),
274
+			$params['year'],
275
+			$params['month']
276
+		);
277
+	}
278
+
279
+	/**
280
+	 * Get the updates based on the current query.
281
+	 */
282
+	public function FilteredUpdates($pageSize = 20)
283
+	{
284
+		$params = $this->parseParams();
285
+
286
+		$items = $this->Updates(
287
+			$params['tag'],
288
+			$params['from'],
289
+			$params['to'],
290
+			$params['year'],
291
+			$params['month']
292
+		);
293
+
294
+		// Apply pagination
295
+		$list = PaginatedList::create($items, $this->getRequest());
296
+		$list->setPageLength($pageSize);
297
+		return $list;
298
+	}
299
+
300
+	/**
301
+	 * @return Form
302
+	 */
303
+	public function DateRangeForm()
304
+	{
305
+		$dateFromTitle = DBField::create_field('HTMLText', sprintf(
306
+			'%s <span class="field-note">%s</span>',
307
+			_t('CWP\\CWP\\PageTypes\\DatedUpdateHolder.FROM_DATE', 'From date'),
308
+			_t('CWP\\CWP\\PageTypes\\DatedUpdateHolder.DATE_EXAMPLE', '(example: 2017/12/30)')
309
+		));
310
+		$dateToTitle = DBField::create_field('HTMLText', sprintf(
311
+			'%s <span class="field-note">%s</span>',
312
+			_t('CWP\\CWP\\PageTypes\\DatedUpdateHolder.TO_DATE', 'To date'),
313
+			_t('CWP\\CWP\\PageTypes\\DatedUpdateHolder.DATE_EXAMPLE', '(example: 2017/12/30)')
314
+		));
315
+
316
+		$fields = FieldList::create(
317
+			DateField::create('from', $dateFromTitle),
318
+			DateField::create('to', $dateToTitle),
319
+			HiddenField::create('tag')
320
+		);
321
+
322
+		$actions = FieldList::create(
323
+			FormAction::create("doDateFilter")
324
+				->setTitle(_t(__CLASS__ . '.Filter'))
325
+				->addExtraClass('btn btn-primary primary'),
326
+			FormAction::create("doDateReset")
327
+				->setTitle(_t(__CLASS__ . '.Clear'))
328
+				->addExtraClass('btn')
329
+		);
330
+
331
+		$form = Form::create($this, 'DateRangeForm', $fields, $actions);
332
+		$form->loadDataFrom($this->request->getVars());
333
+		$form->setFormMethod('get');
334
+
335
+		// Manually extract the message so we can clear it.
336
+		$form->ErrorMessage = $form->getMessage();
337
+		$form->ErrorMessageType = $form->getMessageType();
338
+		$form->clearMessage();
339
+
340
+		return $form;
341
+	}
342
+
343
+	public function doDateFilter()
344
+	{
345
+		$params = $this->parseParams();
346
+
347
+		// Build the link - keep the tag, but reset month, year and pagination.
348
+		$link = HTTP::setGetVar('from', $params['from'], $this->AbsoluteLink(), '&');
349
+		$link = HTTP::setGetVar('to', $params['to'], $link, '&');
350
+		if (isset($params['tag'])) {
351
+			$link = HTTP::setGetVar('tag', $params['tag'], $link, '&');
352
+		}
353
+
354
+		$this->redirect($link);
355
+	}
356
+
357
+	public function doDateReset()
358
+	{
359
+		$params = $this->parseParams(false);
360
+
361
+		// Reset the link - only include the tag.
362
+		$link = $this->AbsoluteLink();
363
+		if (isset($params['tag'])) {
364
+			$link = HTTP::setGetVar('tag', $params['tag'], $link, '&');
365
+		}
366
+
367
+		$this->redirect($link);
368
+	}
369
+
370
+	public function rss()
371
+	{
372
+		$rss = RSSFeed::create(
373
+			$this->Updates()->sort('Created DESC')->limit(20),
374
+			$this->Link('rss'),
375
+			$this->getSubscriptionTitle()
376
+		);
377
+		return $rss->outputToBrowser();
378
+	}
379
+
380
+	public function atom()
381
+	{
382
+		$atom = CwpAtomFeed::create(
383
+			$this->Updates()->sort('Created DESC')->limit(20),
384
+			$this->Link('atom'),
385
+			$this->getSubscriptionTitle()
386
+		);
387
+		return $atom->outputToBrowser();
388
+	}
389 389
 }
Please login to merge, or discard this patch.
src/PageTypes/EventPage.php 2 patches
Indentation   +77 added lines, -77 removed lines patch added patch discarded remove patch
@@ -12,81 +12,81 @@
 block discarded – undo
12 12
 
13 13
 class EventPage extends DatedUpdatePage
14 14
 {
15
-    private static $description = 'Describes an event occurring on a specific date.';
16
-
17
-    private static $default_parent = EventHolder::class;
18
-
19
-    private static $can_be_root = false;
20
-
21
-    private static $icon = 'cwp/cwp:images/icons/sitetree_images/event_page.png';
22
-
23
-    private static $singular_name = 'Event Page';
24
-
25
-    private static $plural_name = 'Event Pages';
26
-
27
-    private static $db = [
28
-        'StartTime' => 'Time',
29
-        'EndTime' => 'Time',
30
-        'Location' => 'Text',
31
-    ];
32
-
33
-    private static $table_name = 'EventPage';
34
-
35
-    public function fieldLabels($includerelations = true)
36
-    {
37
-        $labels = parent::fieldLabels($includerelations);
38
-        $labels['StartTime'] = _t('CWP\\CWP\\PageTypes\\DateUpdatePage.StartTimeFieldLabel', 'Start Time');
39
-        $labels['EndTime'] = _t('CWP\\CWP\\PageTypes\\DateUpdatePage.EndTimeFieldLabel', 'End Time');
40
-        $labels['Location'] = _t('CWP\\CWP\\PageTypes\\DateUpdatePage.LocationFieldLabel', 'Location');
41
-
42
-        return $labels;
43
-    }
44
-
45
-    /**
46
-     * Add the default for the Date being the current day.
47
-     */
48
-    public function populateDefaults()
49
-    {
50
-        if (!isset($this->Date) || $this->Date === null) {
51
-            $this->Date = DBDatetime::now()->Format('y-MM-dd');
52
-        }
53
-
54
-        if (!isset($this->StartTime) || $this->StartTime === null) {
55
-            $this->StartTime = '09:00:00';
56
-        }
57
-
58
-        if (!isset($this->EndTime) || $this->EndTime === null) {
59
-            $this->EndTime = '17:00:00';
60
-        }
61
-
62
-        parent::populateDefaults();
63
-    }
64
-
65
-    public function getCMSFields()
66
-    {
67
-        $this->beforeUpdateCMSFields(function (FieldList $fields) {
68
-            $fields->removeByName('Date');
69
-
70
-            $dateTimeFields = array();
71
-
72
-            $dateTimeFields[] = $dateField = DateField::create('Date', 'Date');
73
-            $dateTimeFields[] = $startTimeField = TimeField::create(
74
-                'StartTime',
75
-                '&nbsp;&nbsp;' . $this->fieldLabel('StartTime')
76
-            );
77
-            $dateTimeFields[] = $endTimeField = TimeField::create('EndTime', $this->fieldLabel('EndTime'));
78
-
79
-            $fields->addFieldsToTab('Root.Main', [
80
-                $dateTimeField = FieldGroup::create('Date and time', $dateTimeFields),
81
-                $locationField = TextareaField::create('Location', $this->fieldLabel('Location'))
82
-            ], 'Abstract');
83
-            $locationField->setRows(4);
84
-        });
85
-        return parent::getCMSFields();
86
-    }
87
-
88
-    public function NiceLocation()
89
-    {
90
-        return nl2br(Convert::raw2xml($this->Location), true);
91
-    }
15
+	private static $description = 'Describes an event occurring on a specific date.';
16
+
17
+	private static $default_parent = EventHolder::class;
18
+
19
+	private static $can_be_root = false;
20
+
21
+	private static $icon = 'cwp/cwp:images/icons/sitetree_images/event_page.png';
22
+
23
+	private static $singular_name = 'Event Page';
24
+
25
+	private static $plural_name = 'Event Pages';
26
+
27
+	private static $db = [
28
+		'StartTime' => 'Time',
29
+		'EndTime' => 'Time',
30
+		'Location' => 'Text',
31
+	];
32
+
33
+	private static $table_name = 'EventPage';
34
+
35
+	public function fieldLabels($includerelations = true)
36
+	{
37
+		$labels = parent::fieldLabels($includerelations);
38
+		$labels['StartTime'] = _t('CWP\\CWP\\PageTypes\\DateUpdatePage.StartTimeFieldLabel', 'Start Time');
39
+		$labels['EndTime'] = _t('CWP\\CWP\\PageTypes\\DateUpdatePage.EndTimeFieldLabel', 'End Time');
40
+		$labels['Location'] = _t('CWP\\CWP\\PageTypes\\DateUpdatePage.LocationFieldLabel', 'Location');
41
+
42
+		return $labels;
43
+	}
44
+
45
+	/**
46
+	 * Add the default for the Date being the current day.
47
+	 */
48
+	public function populateDefaults()
49
+	{
50
+		if (!isset($this->Date) || $this->Date === null) {
51
+			$this->Date = DBDatetime::now()->Format('y-MM-dd');
52
+		}
53
+
54
+		if (!isset($this->StartTime) || $this->StartTime === null) {
55
+			$this->StartTime = '09:00:00';
56
+		}
57
+
58
+		if (!isset($this->EndTime) || $this->EndTime === null) {
59
+			$this->EndTime = '17:00:00';
60
+		}
61
+
62
+		parent::populateDefaults();
63
+	}
64
+
65
+	public function getCMSFields()
66
+	{
67
+		$this->beforeUpdateCMSFields(function (FieldList $fields) {
68
+			$fields->removeByName('Date');
69
+
70
+			$dateTimeFields = array();
71
+
72
+			$dateTimeFields[] = $dateField = DateField::create('Date', 'Date');
73
+			$dateTimeFields[] = $startTimeField = TimeField::create(
74
+				'StartTime',
75
+				'&nbsp;&nbsp;' . $this->fieldLabel('StartTime')
76
+			);
77
+			$dateTimeFields[] = $endTimeField = TimeField::create('EndTime', $this->fieldLabel('EndTime'));
78
+
79
+			$fields->addFieldsToTab('Root.Main', [
80
+				$dateTimeField = FieldGroup::create('Date and time', $dateTimeFields),
81
+				$locationField = TextareaField::create('Location', $this->fieldLabel('Location'))
82
+			], 'Abstract');
83
+			$locationField->setRows(4);
84
+		});
85
+		return parent::getCMSFields();
86
+	}
87
+
88
+	public function NiceLocation()
89
+	{
90
+		return nl2br(Convert::raw2xml($this->Location), true);
91
+	}
92 92
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -64,7 +64,7 @@
 block discarded – undo
64 64
 
65 65
     public function getCMSFields()
66 66
     {
67
-        $this->beforeUpdateCMSFields(function (FieldList $fields) {
67
+        $this->beforeUpdateCMSFields(function(FieldList $fields) {
68 68
             $fields->removeByName('Date');
69 69
 
70 70
             $dateTimeFields = array();
Please login to merge, or discard this patch.
src/PageTypes/BaseHomePage.php 1 patch
Indentation   +133 added lines, -133 removed lines patch added patch discarded remove patch
@@ -26,137 +26,137 @@
 block discarded – undo
26 26
  */
27 27
 class BaseHomePage extends Page
28 28
 {
29
-    private static $icon = 'cwp/cwp:images/icons/sitetree_images/home.png';
30
-
31
-    private static $hide_ancestor = BaseHomePage::class;
32
-
33
-    private static $singular_name = 'Home Page';
34
-
35
-    private static $plural_name = 'Home Pages';
36
-
37
-    private static $table_name = 'BaseHomePage';
38
-
39
-    private static $db = array(
40
-        'FeatureOneTitle' => 'Varchar(255)',
41
-        'FeatureOneCategory' => "Enum('bell,comments,film,flag,globe,group,list,phone,rss,time,user','comments')",
42
-        'FeatureOneContent' => 'HTMLText',
43
-        'FeatureOneButtonText' => 'Varchar(255)',
44
-        'FeatureTwoTitle' => 'Varchar(255)',
45
-        'FeatureTwoCategory' => "Enum('bell,comments,film,flag,globe,group,list,phone,rss,time,user','comments')",
46
-        'FeatureTwoContent' => 'HTMLText',
47
-        'FeatureTwoButtonText' => 'Varchar(255)'
48
-    );
49
-
50
-    private static $has_one = array(
51
-        'LearnMorePage' => SiteTree::class,
52
-        'FeatureOneLink' => SiteTree::class,
53
-        'FeatureTwoLink' => SiteTree::class
54
-    );
55
-
56
-    private static $has_many = array(
57
-        'Quicklinks' => 'Quicklink.Parent'
58
-    );
59
-
60
-    public function Quicklinks()
61
-    {
62
-        return $this->getComponents('Quicklinks')->sort('SortOrder');
63
-    }
64
-
65
-    public function getCMSFields()
66
-    {
67
-        $this->beforeUpdateCMSFields(function (FieldList $fields) {
68
-            // Main Content tab
69
-            $fields->addFieldToTab(
70
-                'Root.Main',
71
-                TreeDropdownField::create(
72
-                    'LearnMorePageID',
73
-                    _t(__CLASS__ . '.LearnMoreLink', 'Page to link the "Learn More" button to:'),
74
-                    SiteTree::class
75
-                ),
76
-                'Metadata'
77
-            );
78
-
79
-            $gridField = GridField::create(
80
-                'Quicklinks',
81
-                'Quicklinks',
82
-                $this->Quicklinks(),
83
-                GridFieldConfig_RelationEditor::create()
84
-            );
85
-            $gridConfig = $gridField->getConfig();
86
-            $gridConfig->getComponentByType(GridFieldAddNewButton::class)->setButtonName(
87
-                _t(__CLASS__ . '.AddNewButton', 'Add new')
88
-            );
89
-
90
-            $injector = Injector::inst();
91
-
92
-            $gridConfig->removeComponentsByType(GridFieldAddExistingAutocompleter::class);
93
-            $gridConfig->removeComponentsByType(GridFieldDeleteAction::class);
94
-            $gridConfig->addComponent($injector->create(GridFieldDeleteAction::class));
95
-            $gridConfig->addComponent($injector->create(GridFieldSortableRows::class, 'SortOrder'));
96
-            $gridField->setModelClass(Quicklink::class);
97
-
98
-            $fields->addFieldToTab('Root.Quicklinks', $gridField);
99
-
100
-            $fields->removeByName('Import');
101
-
102
-            $fields->addFieldToTab(
103
-                'Root.Features',
104
-                ToggleCompositeField::create(
105
-                    'FeatureOne',
106
-                    _t(__CLASS__ . '.FeatureOne', 'Feature One'),
107
-                    array(
108
-                        TextField::create('FeatureOneTitle', _t(__CLASS__ . '.Title', 'Title')),
109
-                        $dropdownField = DropdownField::create(
110
-                            'FeatureOneCategory',
111
-                            _t(__CLASS__ . '.FeatureCategoryDropdown', 'Category icon'),
112
-                            singleton(BaseHomePage::class)->dbObject('FeatureOneCategory')->enumValues()
113
-                        ),
114
-                        HTMLEditorField::create(
115
-                            'FeatureOneContent',
116
-                            _t(__CLASS__ . '.FeatureContentFieldLabel', 'Content')
117
-                        ),
118
-                        TextField::create(
119
-                            'FeatureOneButtonText',
120
-                            _t(__CLASS__ . '.FeatureButtonText', 'Button text')
121
-                        ),
122
-                        TreeDropdownField::create(
123
-                            'FeatureOneLinkID',
124
-                            _t(__CLASS__ . '.FeatureLink', 'Page to link to'),
125
-                            SiteTree::class
126
-                        )->setDescription(_t(__CLASS__ . '.ButtonTextRequired', 'Button text must be filled in'))
127
-                    )
128
-                )->setHeadingLevel(3)
129
-            );
130
-            $dropdownField->setEmptyString('none');
131
-
132
-            $fields->addFieldToTab('Root.Features', ToggleCompositeField::create(
133
-                'FeatureTwo',
134
-                _t(__CLASS__ . '.FeatureTwo', 'Feature Two'),
135
-                array(
136
-                    TextField::create('FeatureTwoTitle', _t(__CLASS__ . '.Title', 'Title')),
137
-                    $dropdownField = DropdownField::create(
138
-                        'FeatureTwoCategory',
139
-                        _t(__CLASS__ . '.FeatureCategoryDropdown', 'Category icon'),
140
-                        singleton(BaseHomePage::class)->dbObject('FeatureTwoCategory')->enumValues()
141
-                    ),
142
-                    HTMLEditorField::create(
143
-                        'FeatureTwoContent',
144
-                        _t(__CLASS__ . '.FeatureContentFieldLabel', 'Content')
145
-                    ),
146
-                    TextField::create(
147
-                        'FeatureTwoButtonText',
148
-                        _t(__CLASS__ . '.FeatureButtonText', 'Button text')
149
-                    ),
150
-                    TreeDropdownField::create(
151
-                        'FeatureTwoLinkID',
152
-                        _t(__CLASS__ . '.FeatureLink', 'Page to link to'),
153
-                        SiteTree::class
154
-                    )->setDescription(_t(__CLASS__ . '.ButtonTextRequired', 'Button text must be filled in'))
155
-                )
156
-            )->setHeadingLevel(3));
157
-            $dropdownField->setEmptyString('none');
158
-        });
159
-
160
-        return parent::getCMSFields();
161
-    }
29
+	private static $icon = 'cwp/cwp:images/icons/sitetree_images/home.png';
30
+
31
+	private static $hide_ancestor = BaseHomePage::class;
32
+
33
+	private static $singular_name = 'Home Page';
34
+
35
+	private static $plural_name = 'Home Pages';
36
+
37
+	private static $table_name = 'BaseHomePage';
38
+
39
+	private static $db = array(
40
+		'FeatureOneTitle' => 'Varchar(255)',
41
+		'FeatureOneCategory' => "Enum('bell,comments,film,flag,globe,group,list,phone,rss,time,user','comments')",
42
+		'FeatureOneContent' => 'HTMLText',
43
+		'FeatureOneButtonText' => 'Varchar(255)',
44
+		'FeatureTwoTitle' => 'Varchar(255)',
45
+		'FeatureTwoCategory' => "Enum('bell,comments,film,flag,globe,group,list,phone,rss,time,user','comments')",
46
+		'FeatureTwoContent' => 'HTMLText',
47
+		'FeatureTwoButtonText' => 'Varchar(255)'
48
+	);
49
+
50
+	private static $has_one = array(
51
+		'LearnMorePage' => SiteTree::class,
52
+		'FeatureOneLink' => SiteTree::class,
53
+		'FeatureTwoLink' => SiteTree::class
54
+	);
55
+
56
+	private static $has_many = array(
57
+		'Quicklinks' => 'Quicklink.Parent'
58
+	);
59
+
60
+	public function Quicklinks()
61
+	{
62
+		return $this->getComponents('Quicklinks')->sort('SortOrder');
63
+	}
64
+
65
+	public function getCMSFields()
66
+	{
67
+		$this->beforeUpdateCMSFields(function (FieldList $fields) {
68
+			// Main Content tab
69
+			$fields->addFieldToTab(
70
+				'Root.Main',
71
+				TreeDropdownField::create(
72
+					'LearnMorePageID',
73
+					_t(__CLASS__ . '.LearnMoreLink', 'Page to link the "Learn More" button to:'),
74
+					SiteTree::class
75
+				),
76
+				'Metadata'
77
+			);
78
+
79
+			$gridField = GridField::create(
80
+				'Quicklinks',
81
+				'Quicklinks',
82
+				$this->Quicklinks(),
83
+				GridFieldConfig_RelationEditor::create()
84
+			);
85
+			$gridConfig = $gridField->getConfig();
86
+			$gridConfig->getComponentByType(GridFieldAddNewButton::class)->setButtonName(
87
+				_t(__CLASS__ . '.AddNewButton', 'Add new')
88
+			);
89
+
90
+			$injector = Injector::inst();
91
+
92
+			$gridConfig->removeComponentsByType(GridFieldAddExistingAutocompleter::class);
93
+			$gridConfig->removeComponentsByType(GridFieldDeleteAction::class);
94
+			$gridConfig->addComponent($injector->create(GridFieldDeleteAction::class));
95
+			$gridConfig->addComponent($injector->create(GridFieldSortableRows::class, 'SortOrder'));
96
+			$gridField->setModelClass(Quicklink::class);
97
+
98
+			$fields->addFieldToTab('Root.Quicklinks', $gridField);
99
+
100
+			$fields->removeByName('Import');
101
+
102
+			$fields->addFieldToTab(
103
+				'Root.Features',
104
+				ToggleCompositeField::create(
105
+					'FeatureOne',
106
+					_t(__CLASS__ . '.FeatureOne', 'Feature One'),
107
+					array(
108
+						TextField::create('FeatureOneTitle', _t(__CLASS__ . '.Title', 'Title')),
109
+						$dropdownField = DropdownField::create(
110
+							'FeatureOneCategory',
111
+							_t(__CLASS__ . '.FeatureCategoryDropdown', 'Category icon'),
112
+							singleton(BaseHomePage::class)->dbObject('FeatureOneCategory')->enumValues()
113
+						),
114
+						HTMLEditorField::create(
115
+							'FeatureOneContent',
116
+							_t(__CLASS__ . '.FeatureContentFieldLabel', 'Content')
117
+						),
118
+						TextField::create(
119
+							'FeatureOneButtonText',
120
+							_t(__CLASS__ . '.FeatureButtonText', 'Button text')
121
+						),
122
+						TreeDropdownField::create(
123
+							'FeatureOneLinkID',
124
+							_t(__CLASS__ . '.FeatureLink', 'Page to link to'),
125
+							SiteTree::class
126
+						)->setDescription(_t(__CLASS__ . '.ButtonTextRequired', 'Button text must be filled in'))
127
+					)
128
+				)->setHeadingLevel(3)
129
+			);
130
+			$dropdownField->setEmptyString('none');
131
+
132
+			$fields->addFieldToTab('Root.Features', ToggleCompositeField::create(
133
+				'FeatureTwo',
134
+				_t(__CLASS__ . '.FeatureTwo', 'Feature Two'),
135
+				array(
136
+					TextField::create('FeatureTwoTitle', _t(__CLASS__ . '.Title', 'Title')),
137
+					$dropdownField = DropdownField::create(
138
+						'FeatureTwoCategory',
139
+						_t(__CLASS__ . '.FeatureCategoryDropdown', 'Category icon'),
140
+						singleton(BaseHomePage::class)->dbObject('FeatureTwoCategory')->enumValues()
141
+					),
142
+					HTMLEditorField::create(
143
+						'FeatureTwoContent',
144
+						_t(__CLASS__ . '.FeatureContentFieldLabel', 'Content')
145
+					),
146
+					TextField::create(
147
+						'FeatureTwoButtonText',
148
+						_t(__CLASS__ . '.FeatureButtonText', 'Button text')
149
+					),
150
+					TreeDropdownField::create(
151
+						'FeatureTwoLinkID',
152
+						_t(__CLASS__ . '.FeatureLink', 'Page to link to'),
153
+						SiteTree::class
154
+					)->setDescription(_t(__CLASS__ . '.ButtonTextRequired', 'Button text must be filled in'))
155
+				)
156
+			)->setHeadingLevel(3));
157
+			$dropdownField->setEmptyString('none');
158
+		});
159
+
160
+		return parent::getCMSFields();
161
+	}
162 162
 }
Please login to merge, or discard this patch.