Completed
Push — master ( 58895a...0930e8 )
by Robbie
15s
created
src/PageTypes/DatedUpdatePage.php 2 patches
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('DateUpdatePage.DateLabel', 'Date');
51
-        $labels['Abstract'] = _t('DateUpdatePage.AbstractTextFieldLabel', 'Abstract');
47
+	public function fieldLabels($includerelations = true)
48
+	{
49
+		$labels = parent::fieldLabels($includerelations);
50
+		$labels['Date'] = _t('DateUpdatePage.DateLabel', 'Date');
51
+		$labels['Abstract'] = _t('DateUpdatePage.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
-                'DateUpdatePage.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
+				'DateUpdatePage.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.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -55,7 +55,7 @@
 block discarded – undo
55 55
 
56 56
     public function getCMSFields()
57 57
     {
58
-        $this->beforeUpdateCMSFields(function (FieldList $fields) {
58
+        $this->beforeUpdateCMSFields(function(FieldList $fields) {
59 59
             $fields->addFieldToTab(
60 60
                 'Root.Main',
61 61
                 $dateTimeField = DatetimeField::create('Date', $this->fieldLabel('Date')),
Please login to merge, or discard this patch.
src/PageTypes/BasePage.php 2 patches
Indentation   +286 added lines, -286 removed lines patch added patch discarded remove patch
@@ -29,296 +29,296 @@
 block discarded – undo
29 29
 
30 30
 class BasePage extends SiteTree
31 31
 {
32
-    private static $icon = 'cwp/images/icons/sitetree_images/page.png';
32
+	private static $icon = '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
-    public $pageIcon = 'images/icons/sitetree_images/page.png';
88
-
89
-    /**
90
-     * Get the footer holder.
91
-     */
92
-    public function getFooter()
93
-    {
94
-        return FooterHolder::get_one(FooterHolder::class);
95
-    }
96
-
97
-    /**
98
-     * Return the full filename of the pdf file, including path & extension
99
-     */
100
-    public function getPdfFilename()
101
-    {
102
-        $baseName = sprintf('%s-%s', $this->URLSegment, $this->ID);
103
-
104
-        $folderPath = Config::inst()->get(BasePage::class, 'generated_pdf_path');
105
-        if ($folderPath[0] != '/') {
106
-            $folderPath = BASE_PATH . '/' . $folderPath;
107
-        }
108
-
109
-        return sprintf('%s/%s.pdf', $folderPath, $baseName);
110
-    }
111
-
112
-    /**
113
-     * Build pdf link for template.
114
-     */
115
-    public function PdfLink()
116
-    {
117
-        if (!Config::inst()->get(BasePage::class, 'pdf_export')) {
118
-            return false;
119
-        }
120
-
121
-        $path = $this->getPdfFilename();
122
-
123
-        if ((Versioned::get_stage() === Versioned::LIVE) && file_exists($path)) {
124
-            return Director::baseURL() . preg_replace('#^/#', '', Director::makeRelative($path));
125
-        }
126
-        return $this->Link('downloadpdf');
127
-    }
128
-
129
-    public function RelatedPages()
130
-    {
131
-        return $this->getManyManyComponents('RelatedPages')->sort('SortOrder');
132
-    }
133
-
134
-    public function RelatedPagesTitle()
135
-    {
136
-        return $this->stat('related_pages_title');
137
-    }
138
-
139
-    /**
140
-     * Remove linked pdf when publishing the page,
141
-     * as it would be out of date.
142
-     */
143
-    public function onAfterPublish()
144
-    {
145
-        $filepath = $this->getPdfFilename();
146
-        if (file_exists($filepath)) {
147
-            unlink($filepath);
148
-        }
149
-    }
150
-
151
-    /**
152
-     * Remove linked pdf when unpublishing the page,
153
-     * so it's no longer valid.
154
-     *
155
-     * @return boolean
156
-     */
157
-    public function doUnpublish()
158
-    {
159
-        if (!parent::doUnpublish()) {
160
-            return false;
161
-        }
162
-
163
-        $filepath = $this->getPdfFilename();
164
-        if (file_exists($filepath)) {
165
-            unlink($filepath);
166
-        }
167
-
168
-        return true;
169
-    }
170
-
171
-    /**
172
-     * @deprecated 2.0.0 remove with other deprecations
173
-     * @todo Remove once CWP moves to 3.3 core (which includes this in SiteTree)
174
-     * @return self
175
-     */
176
-    public function doRestoreToStage()
177
-    {
178
-        $this->invokeWithExtensions('onBeforeRestoreToStage', $this);
179
-        $result = parent::doRestoreToStage();
180
-        $this->invokeWithExtensions('onAfterRestoreToStage', $this);
181
-
182
-        return $result;
183
-    }
184
-
185
-    public function getCMSFields()
186
-    {
187
-        $this->beforeUpdateCMSFields(function (FieldList $fields) {
188
-            // Related Pages
189
-            $components = GridFieldConfig_RelationEditor::create();
190
-            $components->removeComponentsByType(GridFieldAddNewButton::class);
191
-            $components->removeComponentsByType(GridFieldEditButton::class);
192
-            $components->removeComponentsByType(GridFieldFilterHeader::class);
193
-            $components->addComponent(new GridFieldSortableRows('SortOrder'));
194
-
195
-            $dataColumns = $components->getComponentByType(GridFieldDataColumns::class);
196
-            $dataColumns->setDisplayFields([
197
-                'Title' => _t('BasePage.ColumnTitle', 'Title'),
198
-                'ClassName' => _t('BasePage.ColumnPageType', 'Page Type')
199
-            ]);
200
-
201
-            $fields->findOrMakeTab(
202
-                'Root.RelatedPages',
203
-                _t('BasePage.RelatedPages', 'Related pages')
204
-            );
205
-            $fields->addFieldToTab(
206
-                'Root.RelatedPages',
207
-                GridField::create(
208
-                    'RelatedPages',
209
-                    _t('BasePage.RelatedPages', 'Related pages'),
210
-                    $this->RelatedPages(),
211
-                    $components
212
-                )
213
-            );
214
-
215
-            // Taxonomies - Unless they have their own 'Tags' field (such as in Blog, etc)
216
-            $hasMany = $this->hasMany();
217
-            $manyMany = $this->manyMany();
218
-            if (!isset($hasMany['Tags']) && !isset($manyMany['Tags'])) {
219
-                $components = GridFieldConfig_RelationEditor::create();
220
-                $components->removeComponentsByType(GridFieldAddNewButton::class);
221
-                $components->removeComponentsByType(GridFieldEditButton::class);
222
-
223
-                $autoCompleter = $components->getComponentByType(GridFieldAddExistingAutocompleter::class);
224
-                $autoCompleter->setResultsFormat('$Name ($TaxonomyName)');
225
-
226
-                $dataColumns = $components->getComponentByType(GridFieldDataColumns::class);
227
-                $dataColumns->setDisplayFields([
228
-                    'Name' => _t('BasePage.Term', 'Term'),
229
-                    'TaxonomyName' => _t('BasePage.Taxonomy', 'Taxonomy')
230
-                ]);
231
-
232
-                $fields->findOrMakeTab('Root.Tags', _t('BasePage.TagsTabTitle', 'Tags'));
233
-                $fields->addFieldToTab(
234
-                    'Root.Tags',
235
-                    TreeMultiselectField::create(
236
-                        'Terms',
237
-                        _t('BasePage.Terms', 'Terms'),
238
-                        TaxonomyTerm::class
239
-                    )->setDescription(_t('BasePage.TermsDescription', 'Click to search for additional terms'))
240
-                );
241
-            }
242
-        });
243
-        return parent::getCMSFields();
244
-    }
245
-
246
-    /**
247
-     * Provides data for translation navigation.
248
-     * Collects all site translations, marks the current one, and redirects
249
-     * to the translated home page if a. there is a translated homepage and b. the
250
-     * translation of the specific page is not available.
251
-     * @todo re-implement with Fluent
252
-     */
253
-    public function getAvailableTranslations()
254
-    {
255
-        if (!class_exists('Translatable')) {
256
-            return false;
257
-        }
258
-
259
-        $translations = new ArrayList();
260
-        $globalTranslations = Translatable::get_existing_content_languages();
261
-
262
-        foreach ($globalTranslations as $loc => $langName) {
263
-            // Find out the language name in native language.
264
-            $nativeLangName = i18n::get_language_name($loc, true);
265
-            if (!$nativeLangName) {
266
-                $nativeLangName = i18n::get_language_name(i18n::get_lang_from_locale($loc), true);
267
-            }
268
-            if (!$nativeLangName) {
269
-                // Fall back to the locale name.
270
-                $nativeLangName = $langName;
271
-            }
272
-
273
-            // Eliminate the part in brackets (e.g. [mandarin])
274
-            $nativeLangName = preg_replace('/ *[\(\[].*$/', '', $nativeLangName);
275
-
276
-            // Find out the link to the translated page.
277
-            $link = null;
278
-            $page = $this->getTranslation($loc);
279
-            if ($page) {
280
-                $link = $page->Link();
281
-            }
282
-            if (!$link) {
283
-                // Fall back to the home page
284
-                $link = Translatable::get_homepage_link_by_locale($loc);
285
-            }
286
-            if (!$link) {
287
-                continue;
288
-            }
289
-
290
-            // Assemble the table for the switcher.
291
-            $translations->push(new ArrayData(array(
292
-                'Locale' => i18n::convert_rfc1766($loc),
293
-                'LangName' => $nativeLangName,
294
-                'Link' => $link,
295
-                'Current' => (Translatable::get_current_locale()==$loc)
296
-            )));
297
-        }
298
-
299
-        if ($translations->count()>1) {
300
-            return $translations;
301
-        } else {
302
-            return null;
303
-        }
304
-    }
305
-
306
-    /**
307
-     * Returns the native language name for the selected locale/language, empty string if Translatable is not available
308
-     *
309
-     * @return string
310
-     * @todo re-implement with Fluent
311
-     */
312
-    public function getSelectedLanguage()
313
-    {
314
-        if (!class_exists('Translatable')) {
315
-            return '';
316
-        }
317
-
318
-        $language = explode('_', Translatable::get_current_locale());
319
-        $languageCode = array_shift($language);
320
-        $nativeName = i18n::get_language_name($languageCode, true);
321
-
322
-        return $nativeName;
323
-    }
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
+	public $pageIcon = 'images/icons/sitetree_images/page.png';
88
+
89
+	/**
90
+	 * Get the footer holder.
91
+	 */
92
+	public function getFooter()
93
+	{
94
+		return FooterHolder::get_one(FooterHolder::class);
95
+	}
96
+
97
+	/**
98
+	 * Return the full filename of the pdf file, including path & extension
99
+	 */
100
+	public function getPdfFilename()
101
+	{
102
+		$baseName = sprintf('%s-%s', $this->URLSegment, $this->ID);
103
+
104
+		$folderPath = Config::inst()->get(BasePage::class, 'generated_pdf_path');
105
+		if ($folderPath[0] != '/') {
106
+			$folderPath = BASE_PATH . '/' . $folderPath;
107
+		}
108
+
109
+		return sprintf('%s/%s.pdf', $folderPath, $baseName);
110
+	}
111
+
112
+	/**
113
+	 * Build pdf link for template.
114
+	 */
115
+	public function PdfLink()
116
+	{
117
+		if (!Config::inst()->get(BasePage::class, 'pdf_export')) {
118
+			return false;
119
+		}
120
+
121
+		$path = $this->getPdfFilename();
122
+
123
+		if ((Versioned::get_stage() === Versioned::LIVE) && file_exists($path)) {
124
+			return Director::baseURL() . preg_replace('#^/#', '', Director::makeRelative($path));
125
+		}
126
+		return $this->Link('downloadpdf');
127
+	}
128
+
129
+	public function RelatedPages()
130
+	{
131
+		return $this->getManyManyComponents('RelatedPages')->sort('SortOrder');
132
+	}
133
+
134
+	public function RelatedPagesTitle()
135
+	{
136
+		return $this->stat('related_pages_title');
137
+	}
138
+
139
+	/**
140
+	 * Remove linked pdf when publishing the page,
141
+	 * as it would be out of date.
142
+	 */
143
+	public function onAfterPublish()
144
+	{
145
+		$filepath = $this->getPdfFilename();
146
+		if (file_exists($filepath)) {
147
+			unlink($filepath);
148
+		}
149
+	}
150
+
151
+	/**
152
+	 * Remove linked pdf when unpublishing the page,
153
+	 * so it's no longer valid.
154
+	 *
155
+	 * @return boolean
156
+	 */
157
+	public function doUnpublish()
158
+	{
159
+		if (!parent::doUnpublish()) {
160
+			return false;
161
+		}
162
+
163
+		$filepath = $this->getPdfFilename();
164
+		if (file_exists($filepath)) {
165
+			unlink($filepath);
166
+		}
167
+
168
+		return true;
169
+	}
170
+
171
+	/**
172
+	 * @deprecated 2.0.0 remove with other deprecations
173
+	 * @todo Remove once CWP moves to 3.3 core (which includes this in SiteTree)
174
+	 * @return self
175
+	 */
176
+	public function doRestoreToStage()
177
+	{
178
+		$this->invokeWithExtensions('onBeforeRestoreToStage', $this);
179
+		$result = parent::doRestoreToStage();
180
+		$this->invokeWithExtensions('onAfterRestoreToStage', $this);
181
+
182
+		return $result;
183
+	}
184
+
185
+	public function getCMSFields()
186
+	{
187
+		$this->beforeUpdateCMSFields(function (FieldList $fields) {
188
+			// Related Pages
189
+			$components = GridFieldConfig_RelationEditor::create();
190
+			$components->removeComponentsByType(GridFieldAddNewButton::class);
191
+			$components->removeComponentsByType(GridFieldEditButton::class);
192
+			$components->removeComponentsByType(GridFieldFilterHeader::class);
193
+			$components->addComponent(new GridFieldSortableRows('SortOrder'));
194
+
195
+			$dataColumns = $components->getComponentByType(GridFieldDataColumns::class);
196
+			$dataColumns->setDisplayFields([
197
+				'Title' => _t('BasePage.ColumnTitle', 'Title'),
198
+				'ClassName' => _t('BasePage.ColumnPageType', 'Page Type')
199
+			]);
200
+
201
+			$fields->findOrMakeTab(
202
+				'Root.RelatedPages',
203
+				_t('BasePage.RelatedPages', 'Related pages')
204
+			);
205
+			$fields->addFieldToTab(
206
+				'Root.RelatedPages',
207
+				GridField::create(
208
+					'RelatedPages',
209
+					_t('BasePage.RelatedPages', 'Related pages'),
210
+					$this->RelatedPages(),
211
+					$components
212
+				)
213
+			);
214
+
215
+			// Taxonomies - Unless they have their own 'Tags' field (such as in Blog, etc)
216
+			$hasMany = $this->hasMany();
217
+			$manyMany = $this->manyMany();
218
+			if (!isset($hasMany['Tags']) && !isset($manyMany['Tags'])) {
219
+				$components = GridFieldConfig_RelationEditor::create();
220
+				$components->removeComponentsByType(GridFieldAddNewButton::class);
221
+				$components->removeComponentsByType(GridFieldEditButton::class);
222
+
223
+				$autoCompleter = $components->getComponentByType(GridFieldAddExistingAutocompleter::class);
224
+				$autoCompleter->setResultsFormat('$Name ($TaxonomyName)');
225
+
226
+				$dataColumns = $components->getComponentByType(GridFieldDataColumns::class);
227
+				$dataColumns->setDisplayFields([
228
+					'Name' => _t('BasePage.Term', 'Term'),
229
+					'TaxonomyName' => _t('BasePage.Taxonomy', 'Taxonomy')
230
+				]);
231
+
232
+				$fields->findOrMakeTab('Root.Tags', _t('BasePage.TagsTabTitle', 'Tags'));
233
+				$fields->addFieldToTab(
234
+					'Root.Tags',
235
+					TreeMultiselectField::create(
236
+						'Terms',
237
+						_t('BasePage.Terms', 'Terms'),
238
+						TaxonomyTerm::class
239
+					)->setDescription(_t('BasePage.TermsDescription', 'Click to search for additional terms'))
240
+				);
241
+			}
242
+		});
243
+		return parent::getCMSFields();
244
+	}
245
+
246
+	/**
247
+	 * Provides data for translation navigation.
248
+	 * Collects all site translations, marks the current one, and redirects
249
+	 * to the translated home page if a. there is a translated homepage and b. the
250
+	 * translation of the specific page is not available.
251
+	 * @todo re-implement with Fluent
252
+	 */
253
+	public function getAvailableTranslations()
254
+	{
255
+		if (!class_exists('Translatable')) {
256
+			return false;
257
+		}
258
+
259
+		$translations = new ArrayList();
260
+		$globalTranslations = Translatable::get_existing_content_languages();
261
+
262
+		foreach ($globalTranslations as $loc => $langName) {
263
+			// Find out the language name in native language.
264
+			$nativeLangName = i18n::get_language_name($loc, true);
265
+			if (!$nativeLangName) {
266
+				$nativeLangName = i18n::get_language_name(i18n::get_lang_from_locale($loc), true);
267
+			}
268
+			if (!$nativeLangName) {
269
+				// Fall back to the locale name.
270
+				$nativeLangName = $langName;
271
+			}
272
+
273
+			// Eliminate the part in brackets (e.g. [mandarin])
274
+			$nativeLangName = preg_replace('/ *[\(\[].*$/', '', $nativeLangName);
275
+
276
+			// Find out the link to the translated page.
277
+			$link = null;
278
+			$page = $this->getTranslation($loc);
279
+			if ($page) {
280
+				$link = $page->Link();
281
+			}
282
+			if (!$link) {
283
+				// Fall back to the home page
284
+				$link = Translatable::get_homepage_link_by_locale($loc);
285
+			}
286
+			if (!$link) {
287
+				continue;
288
+			}
289
+
290
+			// Assemble the table for the switcher.
291
+			$translations->push(new ArrayData(array(
292
+				'Locale' => i18n::convert_rfc1766($loc),
293
+				'LangName' => $nativeLangName,
294
+				'Link' => $link,
295
+				'Current' => (Translatable::get_current_locale()==$loc)
296
+			)));
297
+		}
298
+
299
+		if ($translations->count()>1) {
300
+			return $translations;
301
+		} else {
302
+			return null;
303
+		}
304
+	}
305
+
306
+	/**
307
+	 * Returns the native language name for the selected locale/language, empty string if Translatable is not available
308
+	 *
309
+	 * @return string
310
+	 * @todo re-implement with Fluent
311
+	 */
312
+	public function getSelectedLanguage()
313
+	{
314
+		if (!class_exists('Translatable')) {
315
+			return '';
316
+		}
317
+
318
+		$language = explode('_', Translatable::get_current_locale());
319
+		$languageCode = array_shift($language);
320
+		$nativeName = i18n::get_language_name($languageCode, true);
321
+
322
+		return $nativeName;
323
+	}
324 324
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -184,7 +184,7 @@  discard block
 block discarded – undo
184 184
 
185 185
     public function getCMSFields()
186 186
     {
187
-        $this->beforeUpdateCMSFields(function (FieldList $fields) {
187
+        $this->beforeUpdateCMSFields(function(FieldList $fields) {
188 188
             // Related Pages
189 189
             $components = GridFieldConfig_RelationEditor::create();
190 190
             $components->removeComponentsByType(GridFieldAddNewButton::class);
@@ -292,11 +292,11 @@  discard block
 block discarded – undo
292 292
                 'Locale' => i18n::convert_rfc1766($loc),
293 293
                 'LangName' => $nativeLangName,
294 294
                 'Link' => $link,
295
-                'Current' => (Translatable::get_current_locale()==$loc)
295
+                'Current' => (Translatable::get_current_locale() == $loc)
296 296
             )));
297 297
         }
298 298
 
299
-        if ($translations->count()>1) {
299
+        if ($translations->count() > 1) {
300 300
             return $translations;
301 301
         } else {
302 302
             return null;
Please login to merge, or discard this patch.
src/PageTypes/BaseHomePageController.php 1 patch
Indentation   +15 added lines, -15 removed lines patch added patch discarded remove patch
@@ -6,20 +6,20 @@
 block discarded – undo
6 6
 
7 7
 class BaseHomePageController extends PageController
8 8
 {
9
-    public function getNewsPage()
10
-    {
11
-        return NewsHolder::get_one(NewsHolder::class);
12
-    }
9
+	public function getNewsPage()
10
+	{
11
+		return NewsHolder::get_one(NewsHolder::class);
12
+	}
13 13
 
14
-    /**
15
-     * @param int $amount The amount of items to provide.
16
-     */
17
-    public function getNewsItems($amount = 2)
18
-    {
19
-        $newsHolder = $this->getNewsPage();
20
-        if ($newsHolder) {
21
-            $controller = NewsHolderController::create($newsHolder);
22
-            return $controller->Updates()->limit($amount);
23
-        }
24
-    }
14
+	/**
15
+	 * @param int $amount The amount of items to provide.
16
+	 */
17
+	public function getNewsItems($amount = 2)
18
+	{
19
+		$newsHolder = $this->getNewsPage();
20
+		if ($newsHolder) {
21
+			$controller = NewsHolderController::create($newsHolder);
22
+			return $controller->Updates()->limit($amount);
23
+		}
24
+	}
25 25
 }
Please login to merge, or discard this patch.
src/PageTypes/EventPage.php 2 patches
Indentation   +60 added lines, -60 removed lines patch added patch discarded remove patch
@@ -12,83 +12,83 @@
 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.';
15
+	private static $description = 'Describes an event occurring on a specific date.';
16 16
 
17
-    private static $default_parent = EventHolder::class;
17
+	private static $default_parent = EventHolder::class;
18 18
 
19
-    private static $can_be_root = false;
19
+	private static $can_be_root = false;
20 20
 
21
-    private static $icon = 'cwp/images/icons/sitetree_images/event_page.png';
21
+	private static $icon = 'cwp/images/icons/sitetree_images/event_page.png';
22 22
 
23
-    public $pageIcon =  'images/icons/sitetree_images/event_page.png';
23
+	public $pageIcon =  'images/icons/sitetree_images/event_page.png';
24 24
 
25
-    private static $singular_name = 'Event Page';
25
+	private static $singular_name = 'Event Page';
26 26
 
27
-    private static $plural_name = 'Event Pages';
27
+	private static $plural_name = 'Event Pages';
28 28
 
29
-    private static $db = [
30
-        'StartTime' => 'Time',
31
-        'EndTime' => 'Time',
32
-        'Location' => 'Text',
33
-    ];
29
+	private static $db = [
30
+		'StartTime' => 'Time',
31
+		'EndTime' => 'Time',
32
+		'Location' => 'Text',
33
+	];
34 34
 
35
-    private static $table_name = 'EventPage';
35
+	private static $table_name = 'EventPage';
36 36
 
37
-    public function fieldLabels($includerelations = true)
38
-    {
39
-        $labels = parent::fieldLabels($includerelations);
40
-        $labels['StartTime'] = _t('DateUpdatePage.StartTimeFieldLabel', 'Start Time');
41
-        $labels['EndTime'] = _t('DateUpdatePage.EndTimeFieldLabel', 'End Time');
42
-        $labels['Location'] = _t('DateUpdatePage.LocationFieldLabel', 'Location');
37
+	public function fieldLabels($includerelations = true)
38
+	{
39
+		$labels = parent::fieldLabels($includerelations);
40
+		$labels['StartTime'] = _t('DateUpdatePage.StartTimeFieldLabel', 'Start Time');
41
+		$labels['EndTime'] = _t('DateUpdatePage.EndTimeFieldLabel', 'End Time');
42
+		$labels['Location'] = _t('DateUpdatePage.LocationFieldLabel', 'Location');
43 43
 
44
-        return $labels;
45
-    }
44
+		return $labels;
45
+	}
46 46
 
47
-    /**
48
-     * Add the default for the Date being the current day.
49
-     */
50
-    public function populateDefaults()
51
-    {
52
-        if (!isset($this->Date) || $this->Date === null) {
53
-            $this->Date = DBDatetime::now()->Format('y-MM-dd');
54
-        }
47
+	/**
48
+	 * Add the default for the Date being the current day.
49
+	 */
50
+	public function populateDefaults()
51
+	{
52
+		if (!isset($this->Date) || $this->Date === null) {
53
+			$this->Date = DBDatetime::now()->Format('y-MM-dd');
54
+		}
55 55
 
56
-        if (!isset($this->StartTime) || $this->StartTime === null) {
57
-            $this->StartTime = '09:00:00';
58
-        }
56
+		if (!isset($this->StartTime) || $this->StartTime === null) {
57
+			$this->StartTime = '09:00:00';
58
+		}
59 59
 
60
-        if (!isset($this->EndTime) || $this->EndTime === null) {
61
-            $this->EndTime = '17:00:00';
62
-        }
60
+		if (!isset($this->EndTime) || $this->EndTime === null) {
61
+			$this->EndTime = '17:00:00';
62
+		}
63 63
 
64
-        parent::populateDefaults();
65
-    }
64
+		parent::populateDefaults();
65
+	}
66 66
 
67
-    public function getCMSFields()
68
-    {
69
-        $this->beforeUpdateCMSFields(function (FieldList $fields) {
70
-            $fields->removeByName('Date');
67
+	public function getCMSFields()
68
+	{
69
+		$this->beforeUpdateCMSFields(function (FieldList $fields) {
70
+			$fields->removeByName('Date');
71 71
 
72
-            $dateTimeFields = array();
72
+			$dateTimeFields = array();
73 73
 
74
-            $dateTimeFields[] = $dateField = DateField::create('Date', 'Date');
75
-            $dateTimeFields[] = $startTimeField = TimeField::create(
76
-                'StartTime',
77
-                '  ' . $this->fieldLabel('StartTime')
78
-            );
79
-            $dateTimeFields[] = $endTimeField = TimeField::create('EndTime', $this->fieldLabel('EndTime'));
74
+			$dateTimeFields[] = $dateField = DateField::create('Date', 'Date');
75
+			$dateTimeFields[] = $startTimeField = TimeField::create(
76
+				'StartTime',
77
+				'  ' . $this->fieldLabel('StartTime')
78
+			);
79
+			$dateTimeFields[] = $endTimeField = TimeField::create('EndTime', $this->fieldLabel('EndTime'));
80 80
 
81
-            $fields->addFieldsToTab('Root.Main', [
82
-                $dateTimeField = FieldGroup::create('Date and time', $dateTimeFields),
83
-                $locationField = TextareaField::create('Location', $this->fieldLabel('Location'))
84
-            ], 'Abstract');
85
-            $locationField->setRows(4);
86
-        });
87
-        return parent::getCMSFields();
88
-    }
81
+			$fields->addFieldsToTab('Root.Main', [
82
+				$dateTimeField = FieldGroup::create('Date and time', $dateTimeFields),
83
+				$locationField = TextareaField::create('Location', $this->fieldLabel('Location'))
84
+			], 'Abstract');
85
+			$locationField->setRows(4);
86
+		});
87
+		return parent::getCMSFields();
88
+	}
89 89
 
90
-    public function NiceLocation()
91
-    {
92
-        return nl2br(Convert::raw2xml($this->Location), true);
93
-    }
90
+	public function NiceLocation()
91
+	{
92
+		return nl2br(Convert::raw2xml($this->Location), true);
93
+	}
94 94
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -20,7 +20,7 @@  discard block
 block discarded – undo
20 20
 
21 21
     private static $icon = 'cwp/images/icons/sitetree_images/event_page.png';
22 22
 
23
-    public $pageIcon =  'images/icons/sitetree_images/event_page.png';
23
+    public $pageIcon = 'images/icons/sitetree_images/event_page.png';
24 24
 
25 25
     private static $singular_name = 'Event Page';
26 26
 
@@ -66,7 +66,7 @@  discard block
 block discarded – undo
66 66
 
67 67
     public function getCMSFields()
68 68
     {
69
-        $this->beforeUpdateCMSFields(function (FieldList $fields) {
69
+        $this->beforeUpdateCMSFields(function(FieldList $fields) {
70 70
             $fields->removeByName('Date');
71 71
 
72 72
             $dateTimeFields = array();
Please login to merge, or discard this patch.
src/PageTypes/DatedUpdateHolder.php 2 patches
Indentation   +243 added lines, -243 removed lines patch added patch discarded remove patch
@@ -17,247 +17,247 @@
 block discarded – undo
17 17
 
18 18
 class DatedUpdateHolder extends Page
19 19
 {
20
-    /**
21
-     * Meant as an abstract base class.
22
-     *
23
-     * {@inheritDoc}
24
-     */
25
-    private static $hide_ancestor = DatedUpdateHolder::class;
26
-
27
-    private static $update_name = 'Updates';
28
-
29
-    private static $update_class = DatedUpdatePage::class;
30
-
31
-    private static $singular_name = 'Dated Update Holder';
32
-
33
-    private static $plural_name = 'Dated Update Holders';
34
-
35
-    private static $table_name = 'DatedUpdateHolder';
36
-
37
-    /**
38
-     * Find all distinct tags (TaxonomyTerms) associated with the DatedUpdatePages under this holder.
39
-     */
40
-    public function UpdateTags()
41
-    {
42
-        $siteTree = DataObject::getSchema()->tableName(SiteTree::class);
43
-        $taxonomy = DataObject::getSchema()->tableName(TaxonomyTerm::class);
44
-
45
-        $tags = TaxonomyTerm::get()
46
-            ->innerJoin('BasePage_Terms', sprintf('"%s"."ID"="BasePage_Terms"."TaxonomyTermID"', $taxonomy))
47
-            ->innerJoin(
48
-                $siteTree,
49
-                sprintf(
50
-                    '"%s"."ID" = "BasePage_Terms"."BasePageID" AND "%s"."ParentID" = \'%d\'',
51
-                    $siteTree,
52
-                    $siteTree,
53
-                    $this->ID
54
-                )
55
-            )
56
-            ->sort('Name');
57
-
58
-        return $tags;
59
-    }
60
-
61
-    /**
62
-     * Wrapper to find all updates belonging to this holder, based on some filters.
63
-     */
64
-    public function Updates($tagID = null, $dateFrom = null, $dateTo = null, $year = null, $monthNumber = null)
65
-    {
66
-        $className = Config::inst()->get($this->ClassName, 'update_class');
67
-        return static::AllUpdates($className, $this->ID, $tagID, $dateFrom, $dateTo, $year, $monthNumber);
68
-    }
69
-
70
-    /**
71
-     * Find all site's updates, based on some filters.
72
-     * Omitting parameters will prevent relevant filters from being applied. The filters are ANDed together.
73
-     *
74
-     * @param string $className The name of the class to fetch.
75
-     * @param int|null $parentID The ID of the holder to extract the updates from.
76
-     * @param int|null $tagID The ID of the tag to filter the updates by.
77
-     * @param string|null $dateFrom The beginning of a date filter range.
78
-     * @param string|null $dateTo The end of the date filter range. If empty, only one day will be searched for.
79
-     * @param int|null $year Numeric value of the year to show.
80
-     * @param int|null $monthNumber Numeric value of the month to show.
81
-     *
82
-     * @returns DataList | PaginatedList
83
-     */
84
-    public static function AllUpdates(
85
-        $className = DatedUpdatePage::class,
86
-        $parentID = null,
87
-        $tagID = null,
88
-        $dateFrom = null,
89
-        $dateTo = null,
90
-        $year = null,
91
-        $monthNumber = null
92
-    ) {
93
-
94
-        $items = $className::get();
95
-        $dbTableName = DataObject::getSchema()->tableForField($className, 'Date');
96
-        if (!$dbTableName) {
97
-            $dbTableName = DatedUpdatePage::class;
98
-        }
99
-
100
-        // Filter by parent holder.
101
-        if (isset($parentID)) {
102
-            $items = $items->filter(['ParentID'=>$parentID]);
103
-        }
104
-
105
-        // Filter down to a single tag.
106
-        if (isset($tagID)) {
107
-            $taxonomy = DataObject::getSchema()->tableName(TaxonomyTerm::class);
108
-            $tableName = DataObject::getSchema()->tableName($className);
109
-
110
-            $items = $items->innerJoin(
111
-                'BasePage_Terms',
112
-                sprintf('"%s"."ID" = "BasePage_Terms"."BasePageID"', $tableName)
113
-            )->innerJoin(
114
-                $taxonomy,
115
-                sprintf(
116
-                    '"BasePage_Terms"."TaxonomyTermID" = "%s"."ID" AND "TaxonomyTerm"."ID" = \'%d\'',
117
-                    $taxonomy,
118
-                    $tagID
119
-                )
120
-            );
121
-        }
122
-
123
-        // Filter by date
124
-        if (isset($dateFrom)) {
125
-            if (!isset($dateTo)) {
126
-                $dateTo = $dateFrom;
127
-            }
128
-
129
-            $items = $items->where([
130
-                sprintf('"%s"."Date" >= \'%s\'', $dbTableName, Convert::raw2sql("$dateFrom 00:00:00")),
131
-                sprintf('"%s"."Date" <= \'%s\'', $dbTableName, Convert::raw2sql("$dateTo 23:59:59"))
132
-            ]);
133
-        }
134
-
135
-        // Filter down to single month.
136
-        if (isset($year) && isset($monthNumber)) {
137
-            $year = (int)$year;
138
-            $monthNumber = (int)$monthNumber;
139
-
140
-            $beginDate = sprintf("%04d-%02d-01 00:00:00", $year, $monthNumber);
141
-            $endDate = date('Y-m-d H:i:s', strtotime("{$beginDate} +1 month"));
142
-
143
-            $items = $items->where(array(
144
-                sprintf('"%s"."Date" >= \'%s\'', $dbTableName, Convert::raw2sql($beginDate)),
145
-                sprintf('"%s"."Date" < \'%s\'', $dbTableName, Convert::raw2sql($endDate))
146
-            ));
147
-        }
148
-
149
-        // Unpaginated DataList.
150
-        return $items;
151
-    }
152
-
153
-    /**
154
-     * Produce an ArrayList of available months out of the updates contained in the DataList.
155
-     *
156
-     * Here is an example of the returned structure:
157
-     * ArrayList:
158
-     *   ArrayData:
159
-     *     YearName => 2013
160
-     *     Months => ArrayList:
161
-     *       MonthName => Jan
162
-     *       MonthNumber => 1
163
-     *       MonthLink => (page URL)year=2012&month=1
164
-     *       Active => true
165
-     *   ArrayData:
166
-     *     YearName => 2012
167
-     *     Months => ArrayList:
168
-     *     ...
169
-     *
170
-     * @param DataList $updates DataList DataList to extract months from.
171
-     * @param string $link Link used as abase to construct the MonthLink.
172
-     * @param int $currentYear Currently selected year, for computing the link active state.
173
-     * @param int $currentMonthNumber Currently selected month, for computing the link active state.
174
-     *
175
-     * @returns ArrayList
176
-     */
177
-    public static function ExtractMonths(
178
-        DataList $updates,
179
-        $link = null,
180
-        $currentYear = null,
181
-        $currentMonthNumber = null
182
-    ) {
183
-        // Set the link to current URL in the same way the HTTP::setGetVar does it.
184
-        if (!isset($link)) {
185
-            $link = Director::makeRelative($_SERVER['REQUEST_URI']);
186
-        }
187
-
188
-        $dates = $updates->dataQuery()
189
-            ->groupby('YEAR("Date")')
190
-            ->groupby('MONTH("Date")')
191
-            ->query()
192
-            ->setSelect([
193
-                'Year' => 'YEAR("Date")',
194
-                'Month' => 'MONTH("Date")',
195
-            ])
196
-            ->addWhere('"Date" IS NOT NULL')
197
-            ->setOrderBy([
198
-                'YEAR("Date")' => 'DESC',
199
-                'MONTH("Date")' => 'DESC',
200
-            ])
201
-            ->execute();
202
-
203
-        $years = [];
204
-        foreach ($dates as $date) {
205
-            $monthNumber = $date['Month'];
206
-            $year = $date['Year'];
207
-            $dateObj = new DateTime(implode('-', [$year, $monthNumber, 1]));
208
-            $monthName = $dateObj->Format('M');
209
-
210
-            // Set up the relevant year array, if not yet available.
211
-            if (!isset($years[$year])) {
212
-                $years[$year] = ['YearName'=>$year, 'Months' => []];
213
-            }
214
-
215
-            // Check if the currently processed month is the one that is selected via GET params.
216
-            $active = false;
217
-            if (isset($year) && isset($monthNumber)) {
218
-                $active = (((int)$currentYear)==$year && ((int)$currentMonthNumber)==$monthNumber);
219
-            }
220
-
221
-            // Build the link - keep the tag and date filter, but reset the pagination.
222
-            if ($active) {
223
-                // Allow clicking to deselect the month.
224
-                $link = HTTP::setGetVar('month', null, $link, '&');
225
-                $link = HTTP::setGetVar('year', null, $link, '&');
226
-            } else {
227
-                $link = HTTP::setGetVar('month', $monthNumber, $link, '&');
228
-                $link = HTTP::setGetVar('year', $year, $link, '&');
229
-            }
230
-            $link = HTTP::setGetVar('start', null, $link, '&');
231
-
232
-            $years[$year]['Months'][$monthNumber] = array(
233
-                'MonthName'=>$monthName,
234
-                'MonthNumber'=>$monthNumber,
235
-                'MonthLink'=>$link,
236
-                'Active'=>$active
237
-            );
238
-        }
239
-
240
-        // ArrayList will not recursively walk through the supplied array, so manually build nested ArrayLists.
241
-        foreach ($years as &$year) {
242
-            $year['Months'] = new ArrayList($year['Months']);
243
-        }
244
-
245
-        // Reverse the list so the most recent years appear first.
246
-        return new ArrayList($years);
247
-    }
248
-
249
-    public function getDefaultRSSLink()
250
-    {
251
-        return $this->Link('rss');
252
-    }
253
-
254
-    public function getDefaultAtomLink()
255
-    {
256
-        return $this->Link('atom');
257
-    }
258
-
259
-    public function getSubscriptionTitle()
260
-    {
261
-        return $this->Title;
262
-    }
20
+	/**
21
+	 * Meant as an abstract base class.
22
+	 *
23
+	 * {@inheritDoc}
24
+	 */
25
+	private static $hide_ancestor = DatedUpdateHolder::class;
26
+
27
+	private static $update_name = 'Updates';
28
+
29
+	private static $update_class = DatedUpdatePage::class;
30
+
31
+	private static $singular_name = 'Dated Update Holder';
32
+
33
+	private static $plural_name = 'Dated Update Holders';
34
+
35
+	private static $table_name = 'DatedUpdateHolder';
36
+
37
+	/**
38
+	 * Find all distinct tags (TaxonomyTerms) associated with the DatedUpdatePages under this holder.
39
+	 */
40
+	public function UpdateTags()
41
+	{
42
+		$siteTree = DataObject::getSchema()->tableName(SiteTree::class);
43
+		$taxonomy = DataObject::getSchema()->tableName(TaxonomyTerm::class);
44
+
45
+		$tags = TaxonomyTerm::get()
46
+			->innerJoin('BasePage_Terms', sprintf('"%s"."ID"="BasePage_Terms"."TaxonomyTermID"', $taxonomy))
47
+			->innerJoin(
48
+				$siteTree,
49
+				sprintf(
50
+					'"%s"."ID" = "BasePage_Terms"."BasePageID" AND "%s"."ParentID" = \'%d\'',
51
+					$siteTree,
52
+					$siteTree,
53
+					$this->ID
54
+				)
55
+			)
56
+			->sort('Name');
57
+
58
+		return $tags;
59
+	}
60
+
61
+	/**
62
+	 * Wrapper to find all updates belonging to this holder, based on some filters.
63
+	 */
64
+	public function Updates($tagID = null, $dateFrom = null, $dateTo = null, $year = null, $monthNumber = null)
65
+	{
66
+		$className = Config::inst()->get($this->ClassName, 'update_class');
67
+		return static::AllUpdates($className, $this->ID, $tagID, $dateFrom, $dateTo, $year, $monthNumber);
68
+	}
69
+
70
+	/**
71
+	 * Find all site's updates, based on some filters.
72
+	 * Omitting parameters will prevent relevant filters from being applied. The filters are ANDed together.
73
+	 *
74
+	 * @param string $className The name of the class to fetch.
75
+	 * @param int|null $parentID The ID of the holder to extract the updates from.
76
+	 * @param int|null $tagID The ID of the tag to filter the updates by.
77
+	 * @param string|null $dateFrom The beginning of a date filter range.
78
+	 * @param string|null $dateTo The end of the date filter range. If empty, only one day will be searched for.
79
+	 * @param int|null $year Numeric value of the year to show.
80
+	 * @param int|null $monthNumber Numeric value of the month to show.
81
+	 *
82
+	 * @returns DataList | PaginatedList
83
+	 */
84
+	public static function AllUpdates(
85
+		$className = DatedUpdatePage::class,
86
+		$parentID = null,
87
+		$tagID = null,
88
+		$dateFrom = null,
89
+		$dateTo = null,
90
+		$year = null,
91
+		$monthNumber = null
92
+	) {
93
+
94
+		$items = $className::get();
95
+		$dbTableName = DataObject::getSchema()->tableForField($className, 'Date');
96
+		if (!$dbTableName) {
97
+			$dbTableName = DatedUpdatePage::class;
98
+		}
99
+
100
+		// Filter by parent holder.
101
+		if (isset($parentID)) {
102
+			$items = $items->filter(['ParentID'=>$parentID]);
103
+		}
104
+
105
+		// Filter down to a single tag.
106
+		if (isset($tagID)) {
107
+			$taxonomy = DataObject::getSchema()->tableName(TaxonomyTerm::class);
108
+			$tableName = DataObject::getSchema()->tableName($className);
109
+
110
+			$items = $items->innerJoin(
111
+				'BasePage_Terms',
112
+				sprintf('"%s"."ID" = "BasePage_Terms"."BasePageID"', $tableName)
113
+			)->innerJoin(
114
+				$taxonomy,
115
+				sprintf(
116
+					'"BasePage_Terms"."TaxonomyTermID" = "%s"."ID" AND "TaxonomyTerm"."ID" = \'%d\'',
117
+					$taxonomy,
118
+					$tagID
119
+				)
120
+			);
121
+		}
122
+
123
+		// Filter by date
124
+		if (isset($dateFrom)) {
125
+			if (!isset($dateTo)) {
126
+				$dateTo = $dateFrom;
127
+			}
128
+
129
+			$items = $items->where([
130
+				sprintf('"%s"."Date" >= \'%s\'', $dbTableName, Convert::raw2sql("$dateFrom 00:00:00")),
131
+				sprintf('"%s"."Date" <= \'%s\'', $dbTableName, Convert::raw2sql("$dateTo 23:59:59"))
132
+			]);
133
+		}
134
+
135
+		// Filter down to single month.
136
+		if (isset($year) && isset($monthNumber)) {
137
+			$year = (int)$year;
138
+			$monthNumber = (int)$monthNumber;
139
+
140
+			$beginDate = sprintf("%04d-%02d-01 00:00:00", $year, $monthNumber);
141
+			$endDate = date('Y-m-d H:i:s', strtotime("{$beginDate} +1 month"));
142
+
143
+			$items = $items->where(array(
144
+				sprintf('"%s"."Date" >= \'%s\'', $dbTableName, Convert::raw2sql($beginDate)),
145
+				sprintf('"%s"."Date" < \'%s\'', $dbTableName, Convert::raw2sql($endDate))
146
+			));
147
+		}
148
+
149
+		// Unpaginated DataList.
150
+		return $items;
151
+	}
152
+
153
+	/**
154
+	 * Produce an ArrayList of available months out of the updates contained in the DataList.
155
+	 *
156
+	 * Here is an example of the returned structure:
157
+	 * ArrayList:
158
+	 *   ArrayData:
159
+	 *     YearName => 2013
160
+	 *     Months => ArrayList:
161
+	 *       MonthName => Jan
162
+	 *       MonthNumber => 1
163
+	 *       MonthLink => (page URL)year=2012&month=1
164
+	 *       Active => true
165
+	 *   ArrayData:
166
+	 *     YearName => 2012
167
+	 *     Months => ArrayList:
168
+	 *     ...
169
+	 *
170
+	 * @param DataList $updates DataList DataList to extract months from.
171
+	 * @param string $link Link used as abase to construct the MonthLink.
172
+	 * @param int $currentYear Currently selected year, for computing the link active state.
173
+	 * @param int $currentMonthNumber Currently selected month, for computing the link active state.
174
+	 *
175
+	 * @returns ArrayList
176
+	 */
177
+	public static function ExtractMonths(
178
+		DataList $updates,
179
+		$link = null,
180
+		$currentYear = null,
181
+		$currentMonthNumber = null
182
+	) {
183
+		// Set the link to current URL in the same way the HTTP::setGetVar does it.
184
+		if (!isset($link)) {
185
+			$link = Director::makeRelative($_SERVER['REQUEST_URI']);
186
+		}
187
+
188
+		$dates = $updates->dataQuery()
189
+			->groupby('YEAR("Date")')
190
+			->groupby('MONTH("Date")')
191
+			->query()
192
+			->setSelect([
193
+				'Year' => 'YEAR("Date")',
194
+				'Month' => 'MONTH("Date")',
195
+			])
196
+			->addWhere('"Date" IS NOT NULL')
197
+			->setOrderBy([
198
+				'YEAR("Date")' => 'DESC',
199
+				'MONTH("Date")' => 'DESC',
200
+			])
201
+			->execute();
202
+
203
+		$years = [];
204
+		foreach ($dates as $date) {
205
+			$monthNumber = $date['Month'];
206
+			$year = $date['Year'];
207
+			$dateObj = new DateTime(implode('-', [$year, $monthNumber, 1]));
208
+			$monthName = $dateObj->Format('M');
209
+
210
+			// Set up the relevant year array, if not yet available.
211
+			if (!isset($years[$year])) {
212
+				$years[$year] = ['YearName'=>$year, 'Months' => []];
213
+			}
214
+
215
+			// Check if the currently processed month is the one that is selected via GET params.
216
+			$active = false;
217
+			if (isset($year) && isset($monthNumber)) {
218
+				$active = (((int)$currentYear)==$year && ((int)$currentMonthNumber)==$monthNumber);
219
+			}
220
+
221
+			// Build the link - keep the tag and date filter, but reset the pagination.
222
+			if ($active) {
223
+				// Allow clicking to deselect the month.
224
+				$link = HTTP::setGetVar('month', null, $link, '&');
225
+				$link = HTTP::setGetVar('year', null, $link, '&');
226
+			} else {
227
+				$link = HTTP::setGetVar('month', $monthNumber, $link, '&');
228
+				$link = HTTP::setGetVar('year', $year, $link, '&');
229
+			}
230
+			$link = HTTP::setGetVar('start', null, $link, '&');
231
+
232
+			$years[$year]['Months'][$monthNumber] = array(
233
+				'MonthName'=>$monthName,
234
+				'MonthNumber'=>$monthNumber,
235
+				'MonthLink'=>$link,
236
+				'Active'=>$active
237
+			);
238
+		}
239
+
240
+		// ArrayList will not recursively walk through the supplied array, so manually build nested ArrayLists.
241
+		foreach ($years as &$year) {
242
+			$year['Months'] = new ArrayList($year['Months']);
243
+		}
244
+
245
+		// Reverse the list so the most recent years appear first.
246
+		return new ArrayList($years);
247
+	}
248
+
249
+	public function getDefaultRSSLink()
250
+	{
251
+		return $this->Link('rss');
252
+	}
253
+
254
+	public function getDefaultAtomLink()
255
+	{
256
+		return $this->Link('atom');
257
+	}
258
+
259
+	public function getSubscriptionTitle()
260
+	{
261
+		return $this->Title;
262
+	}
263 263
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -134,8 +134,8 @@  discard block
 block discarded – undo
134 134
 
135 135
         // Filter down to single month.
136 136
         if (isset($year) && isset($monthNumber)) {
137
-            $year = (int)$year;
138
-            $monthNumber = (int)$monthNumber;
137
+            $year = (int) $year;
138
+            $monthNumber = (int) $monthNumber;
139 139
 
140 140
             $beginDate = sprintf("%04d-%02d-01 00:00:00", $year, $monthNumber);
141 141
             $endDate = date('Y-m-d H:i:s', strtotime("{$beginDate} +1 month"));
@@ -215,7 +215,7 @@  discard block
 block discarded – undo
215 215
             // Check if the currently processed month is the one that is selected via GET params.
216 216
             $active = false;
217 217
             if (isset($year) && isset($monthNumber)) {
218
-                $active = (((int)$currentYear)==$year && ((int)$currentMonthNumber)==$monthNumber);
218
+                $active = (((int) $currentYear) == $year && ((int) $currentMonthNumber) == $monthNumber);
219 219
             }
220 220
 
221 221
             // Build the link - keep the tag and date filter, but reset the pagination.
Please login to merge, or discard this patch.
src/PageTypes/SitemapPageController.php 1 patch
Indentation   +47 added lines, -47 removed lines patch added patch discarded remove patch
@@ -9,51 +9,51 @@
 block discarded – undo
9 9
 
10 10
 class SitemapPageController extends PageController
11 11
 {
12
-    private static $allowed_actions = [
13
-        'showpage',
14
-    ];
15
-
16
-    private static $url_handlers = [
17
-        'page/$ID' => 'showpage',
18
-    ];
19
-
20
-    public function Page($link)
21
-    {
22
-        if ($link instanceof HTTPRequest) {
23
-            Deprecation::notice('2.0', 'Using page() as a url handler is deprecated. Use showpage() action instead');
24
-            return $this->showpage($link);
25
-        }
26
-        return parent::Page($link);
27
-    }
28
-
29
-    public function showpage($request)
30
-    {
31
-        $id = (int) $request->param('ID');
32
-        if (!$id) {
33
-            return false;
34
-        }
35
-        $page = SiteTree::get()->byId($id);
36
-
37
-        // does the page exist?
38
-        if (!($page && $page->exists())) {
39
-            return $this->httpError(404);
40
-        }
41
-
42
-        // can the page be viewed?
43
-        if (!$page->canView()) {
44
-            return $this->httpError(403);
45
-        }
46
-
47
-        $viewer = $this->customise([
48
-            'IsAjax' => $request->isAjax(),
49
-            'SelectedPage' => $page,
50
-            'Children' => $page->Children(),
51
-        ]);
52
-
53
-        if ($request->isAjax()) {
54
-            return $viewer->renderWith('SitemapNodeChildren');
55
-        }
56
-
57
-        return $viewer;
58
-    }
12
+	private static $allowed_actions = [
13
+		'showpage',
14
+	];
15
+
16
+	private static $url_handlers = [
17
+		'page/$ID' => 'showpage',
18
+	];
19
+
20
+	public function Page($link)
21
+	{
22
+		if ($link instanceof HTTPRequest) {
23
+			Deprecation::notice('2.0', 'Using page() as a url handler is deprecated. Use showpage() action instead');
24
+			return $this->showpage($link);
25
+		}
26
+		return parent::Page($link);
27
+	}
28
+
29
+	public function showpage($request)
30
+	{
31
+		$id = (int) $request->param('ID');
32
+		if (!$id) {
33
+			return false;
34
+		}
35
+		$page = SiteTree::get()->byId($id);
36
+
37
+		// does the page exist?
38
+		if (!($page && $page->exists())) {
39
+			return $this->httpError(404);
40
+		}
41
+
42
+		// can the page be viewed?
43
+		if (!$page->canView()) {
44
+			return $this->httpError(403);
45
+		}
46
+
47
+		$viewer = $this->customise([
48
+			'IsAjax' => $request->isAjax(),
49
+			'SelectedPage' => $page,
50
+			'Children' => $page->Children(),
51
+		]);
52
+
53
+		if ($request->isAjax()) {
54
+			return $viewer->renderWith('SitemapNodeChildren');
55
+		}
56
+
57
+		return $viewer;
58
+	}
59 59
 }
Please login to merge, or discard this patch.
src/PageTypes/EventHolder.php 1 patch
Indentation   +45 added lines, -45 removed lines patch added patch discarded remove patch
@@ -7,59 +7,59 @@
 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';
10
+	private static $description = 'Container page for Event Pages, provides event filtering and pagination';
11 11
 
12
-    private static $allowed_children = [
13
-        EventPage::class,
14
-    ];
12
+	private static $allowed_children = [
13
+		EventPage::class,
14
+	];
15 15
 
16
-    private static $default_child = EventPage::class;
16
+	private static $default_child = EventPage::class;
17 17
 
18
-    private static $update_name = 'Events';
18
+	private static $update_name = 'Events';
19 19
 
20
-    private static $update_class = EventPage::class;
20
+	private static $update_class = EventPage::class;
21 21
 
22
-    private static $icon = 'cwp/images/icons/sitetree_images/event_holder.png';
22
+	private static $icon = 'cwp/images/icons/sitetree_images/event_holder.png';
23 23
 
24
-    public $pageIcon = 'images/icons/sitetree_images/event_holder.png';
24
+	public $pageIcon = 'images/icons/sitetree_images/event_holder.png';
25 25
 
26
-    private static $singular_name = 'Event Holder';
26
+	private static $singular_name = 'Event Holder';
27 27
 
28
-    private static $plural_name = 'Event Holders';
28
+	private static $plural_name = 'Event Holders';
29 29
 
30
-    private static $table_name = 'EventHolder';
30
+	private static $table_name = 'EventHolder';
31 31
 
32
-    /**
33
-     * Find all site's news items, based on some filters.
34
-     * Omitting parameters will prevent relevant filters from being applied. The filters are ANDed together.
35
-     *
36
-     * @param string $className The name of the class to fetch.
37
-     * @param int $parentID The ID of the holder to extract the news items from.
38
-     * @param int $tagID The ID of the tag to filter the news items by.
39
-     * @param string $dateFrom The beginning of a date filter range.
40
-     * @param string $dateTo The end of the date filter range. If empty, only one day will be searched for.
41
-     * @param int $year Numeric value of the year to show.
42
-     * @param int $monthNumber Numeric value of the month to show.
43
-     *
44
-     * @returns DataList|PaginatedList
45
-     */
46
-    public static function AllUpdates(
47
-        $className = 'Events',
48
-        $parentID = null,
49
-        $tagID = null,
50
-        $dateFrom = null,
51
-        $dateTo = null,
52
-        $year = null,
53
-        $monthNumber = null
54
-    ) {
55
-        return parent::AllUpdates(
56
-            $className,
57
-            $parentID,
58
-            $tagID,
59
-            $dateFrom,
60
-            $dateTo,
61
-            $year,
62
-            $monthNumber
63
-        )->Sort('Date', 'ASC');
64
-    }
32
+	/**
33
+	 * Find all site's news items, based on some filters.
34
+	 * Omitting parameters will prevent relevant filters from being applied. The filters are ANDed together.
35
+	 *
36
+	 * @param string $className The name of the class to fetch.
37
+	 * @param int $parentID The ID of the holder to extract the news items from.
38
+	 * @param int $tagID The ID of the tag to filter the news items by.
39
+	 * @param string $dateFrom The beginning of a date filter range.
40
+	 * @param string $dateTo The end of the date filter range. If empty, only one day will be searched for.
41
+	 * @param int $year Numeric value of the year to show.
42
+	 * @param int $monthNumber Numeric value of the month to show.
43
+	 *
44
+	 * @returns DataList|PaginatedList
45
+	 */
46
+	public static function AllUpdates(
47
+		$className = 'Events',
48
+		$parentID = null,
49
+		$tagID = null,
50
+		$dateFrom = null,
51
+		$dateTo = null,
52
+		$year = null,
53
+		$monthNumber = null
54
+	) {
55
+		return parent::AllUpdates(
56
+			$className,
57
+			$parentID,
58
+			$tagID,
59
+			$dateFrom,
60
+			$dateTo,
61
+			$year,
62
+			$monthNumber
63
+		)->Sort('Date', 'ASC');
64
+	}
65 65
 }
Please login to merge, or discard this patch.
src/Tasks/CleanupGeneratedPdfDailyTask.php 1 patch
Indentation   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -7,9 +7,9 @@
 block discarded – undo
7 7
 // @todo replace with QueuedJobs
8 8
 class CleanupGeneratedPdfDailyTask // extends DailyTask
9 9
 {
10
-    public function process()
11
-    {
12
-        $task = new CleanupGeneratedPdfBuildTask();
13
-        $task->run(null);
14
-    }
10
+	public function process()
11
+	{
12
+		$task = new CleanupGeneratedPdfBuildTask();
13
+		$task->run(null);
14
+	}
15 15
 }
Please login to merge, or discard this patch.
src/Tasks/PopulateThemeSampleDataTask.php 1 patch
Indentation   +126 added lines, -126 removed lines patch added patch discarded remove patch
@@ -17,130 +17,130 @@
 block discarded – undo
17 17
  */
18 18
 class PopulateThemeSampleDataTask extends BuildTask
19 19
 {
20
-    protected $title = 'Populate sample data for theme demo';
21
-
22
-    protected $description = 'Populates some sample data for showcasing the functionality of the '
23
-        . 'starter and Wātea themes';
24
-
25
-    /**
26
-     * A series of method calls to create sample data
27
-     *
28
-     * @param HTTPRequest $request
29
-     */
30
-    public function run($request)
31
-    {
32
-        $this->handleContactForm();
33
-    }
34
-
35
-    /**
36
-     * Decide whether to create a contact user defined form, and call it to be be created if so
37
-     *
38
-     * @return $this
39
-     */
40
-    protected function handleContactForm()
41
-    {
42
-        if (!$this->getContactFormExists()) {
43
-            $this->createContactForm();
44
-        }
45
-        return $this;
46
-    }
47
-
48
-    /**
49
-     * Determine whether a "contact us" userform exists yet
50
-     *
51
-     * @return bool
52
-     */
53
-    protected function getContactFormExists()
54
-    {
55
-        $exists = false;
56
-        foreach (UserDefinedForm::get()->column('ID') as $formId) {
57
-            $count = Versioned::get_all_versions(UserDefinedForm::class, $formId)
58
-                ->filter('URLSegment', 'contact')
59
-                ->count();
60
-
61
-            if ($count >= 1) {
62
-                $exists = true;
63
-                break;
64
-            }
65
-        }
66
-        return $exists;
67
-    }
68
-
69
-    /**
70
-     * Create a "contact us" userform. Please note that this form does not have any recipients by default, so
71
-     * no emails will be sent. To add recipients - edit the page in the CMS and add a recipient via the "Recipients"
72
-     * tab.
73
-     *
74
-     * @return $this
75
-     */
76
-    protected function createContactForm()
77
-    {
78
-        $form = UserDefinedForm::create(array(
79
-            'Title' => 'Contact',
80
-            'URLSegment' => 'contact',
81
-            'Content' => '<p>$UserDefinedForm</p>',
82
-            'SubmitButtonText' => 'Submit',
83
-            'ClearButtonText' => 'Clear',
84
-            'OnCompleteMessage' => "<p>Thanks, we've received your submission and will be in touch shortly.</p>",
85
-            'EnableLiveValidation' => true
86
-        ));
87
-
88
-        $form->write();
89
-
90
-        // Add form fields
91
-        $fields = array(
92
-            EditableFormStep::create(array(
93
-                'Title' => _t('EditableFormStep.TITLE_FIRST', 'First Page')
94
-            )),
95
-            EditableTextField::create(array(
96
-                'Title' => 'Name',
97
-                'Required' => true,
98
-                'RightTitle' => 'Please enter your first and last name'
99
-            )),
100
-            EditableEmailField::create(array(
101
-                'Title' => Email::class,
102
-                'Required' => true,
103
-                'Placeholder' => '[email protected]'
104
-            )),
105
-            EditableTextField::create(array(
106
-                'Title' => 'Subject'
107
-            )),
108
-            EditableTextField::create(array(
109
-                'Title' => 'Message',
110
-                'Required' => true,
111
-                'Rows' => 5
112
-            ))
113
-        );
114
-
115
-        foreach ($fields as $field) {
116
-            $field->write();
117
-            $form->Fields()->add($field);
118
-            $field->publish('Stage', 'Live');
119
-        }
120
-
121
-        $form->publish('Stage', 'Live');
122
-        $form->flushCache();
123
-
124
-        $this->output(' + Created "contact" UserDefinedForm page');
125
-
126
-        return $this;
127
-    }
128
-
129
-    /**
130
-     * Output a message either to the console or browser
131
-     *
132
-     * @param  string $message
133
-     * @return $this
134
-     */
135
-    protected function output($message)
136
-    {
137
-        if (Director::is_cli()) {
138
-            $message .= PHP_EOL;
139
-        } else {
140
-            $message = sprintf('<p>%s</p>', $message);
141
-        }
142
-        echo $message;
143
-
144
-        return $this;
145
-    }
20
+	protected $title = 'Populate sample data for theme demo';
21
+
22
+	protected $description = 'Populates some sample data for showcasing the functionality of the '
23
+		. 'starter and Wātea themes';
24
+
25
+	/**
26
+	 * A series of method calls to create sample data
27
+	 *
28
+	 * @param HTTPRequest $request
29
+	 */
30
+	public function run($request)
31
+	{
32
+		$this->handleContactForm();
33
+	}
34
+
35
+	/**
36
+	 * Decide whether to create a contact user defined form, and call it to be be created if so
37
+	 *
38
+	 * @return $this
39
+	 */
40
+	protected function handleContactForm()
41
+	{
42
+		if (!$this->getContactFormExists()) {
43
+			$this->createContactForm();
44
+		}
45
+		return $this;
46
+	}
47
+
48
+	/**
49
+	 * Determine whether a "contact us" userform exists yet
50
+	 *
51
+	 * @return bool
52
+	 */
53
+	protected function getContactFormExists()
54
+	{
55
+		$exists = false;
56
+		foreach (UserDefinedForm::get()->column('ID') as $formId) {
57
+			$count = Versioned::get_all_versions(UserDefinedForm::class, $formId)
58
+				->filter('URLSegment', 'contact')
59
+				->count();
60
+
61
+			if ($count >= 1) {
62
+				$exists = true;
63
+				break;
64
+			}
65
+		}
66
+		return $exists;
67
+	}
68
+
69
+	/**
70
+	 * Create a "contact us" userform. Please note that this form does not have any recipients by default, so
71
+	 * no emails will be sent. To add recipients - edit the page in the CMS and add a recipient via the "Recipients"
72
+	 * tab.
73
+	 *
74
+	 * @return $this
75
+	 */
76
+	protected function createContactForm()
77
+	{
78
+		$form = UserDefinedForm::create(array(
79
+			'Title' => 'Contact',
80
+			'URLSegment' => 'contact',
81
+			'Content' => '<p>$UserDefinedForm</p>',
82
+			'SubmitButtonText' => 'Submit',
83
+			'ClearButtonText' => 'Clear',
84
+			'OnCompleteMessage' => "<p>Thanks, we've received your submission and will be in touch shortly.</p>",
85
+			'EnableLiveValidation' => true
86
+		));
87
+
88
+		$form->write();
89
+
90
+		// Add form fields
91
+		$fields = array(
92
+			EditableFormStep::create(array(
93
+				'Title' => _t('EditableFormStep.TITLE_FIRST', 'First Page')
94
+			)),
95
+			EditableTextField::create(array(
96
+				'Title' => 'Name',
97
+				'Required' => true,
98
+				'RightTitle' => 'Please enter your first and last name'
99
+			)),
100
+			EditableEmailField::create(array(
101
+				'Title' => Email::class,
102
+				'Required' => true,
103
+				'Placeholder' => '[email protected]'
104
+			)),
105
+			EditableTextField::create(array(
106
+				'Title' => 'Subject'
107
+			)),
108
+			EditableTextField::create(array(
109
+				'Title' => 'Message',
110
+				'Required' => true,
111
+				'Rows' => 5
112
+			))
113
+		);
114
+
115
+		foreach ($fields as $field) {
116
+			$field->write();
117
+			$form->Fields()->add($field);
118
+			$field->publish('Stage', 'Live');
119
+		}
120
+
121
+		$form->publish('Stage', 'Live');
122
+		$form->flushCache();
123
+
124
+		$this->output(' + Created "contact" UserDefinedForm page');
125
+
126
+		return $this;
127
+	}
128
+
129
+	/**
130
+	 * Output a message either to the console or browser
131
+	 *
132
+	 * @param  string $message
133
+	 * @return $this
134
+	 */
135
+	protected function output($message)
136
+	{
137
+		if (Director::is_cli()) {
138
+			$message .= PHP_EOL;
139
+		} else {
140
+			$message = sprintf('<p>%s</p>', $message);
141
+		}
142
+		echo $message;
143
+
144
+		return $this;
145
+	}
146 146
 }
Please login to merge, or discard this patch.