Passed
Pull Request — master (#27)
by Robbie
02:35
created
src/PageTypes/DatedUpdateHolderController.php 2 patches
Indentation   +356 added lines, -356 removed lines patch added patch discarded remove patch
@@ -34,360 +34,360 @@
 block discarded – undo
34 34
  */
35 35
 class DatedUpdateHolderController extends PageController
36 36
 {
37
-    private static $allowed_actions = [
38
-        'rss',
39
-        'atom',
40
-        'DateRangeForm',
41
-    ];
42
-
43
-    private static $casting = [
44
-        'MetaTitle' => 'Text',
45
-        'FilterDescription' => 'Text',
46
-    ];
47
-
48
-    /**
49
-     * The session key for storing temporary form messages
50
-     *
51
-     * @var string
52
-     */
53
-    const TEMP_FORM_MESSAGE = __CLASS__ . '.TempFormMessage';
54
-
55
-    /**
56
-     * Get the meta title for the current action
57
-     *
58
-     * @return string
59
-     */
60
-    public function getMetaTitle()
61
-    {
62
-        $title = $this->data()->getTitle();
63
-        $filter = $this->FilterDescription();
64
-        if ($filter) {
65
-            $title = "{$title} - {$filter}";
66
-        }
67
-
68
-        $this->extend('updateMetaTitle', $title);
69
-        return $title;
70
-    }
71
-
72
-    /**
73
-     * Returns a description of the current filter
74
-     *
75
-     * @return string
76
-     */
77
-    public function FilterDescription()
78
-    {
79
-        $params = $this->parseParams();
80
-
81
-        $filters = array();
82
-        if ($params['tag']) {
83
-            $term = TaxonomyTerm::get_by_id(TaxonomyTerm::class, $params['tag']);
84
-            if ($term) {
85
-                $filters[] = _t(
86
-                    'CWP\\CWP\\PageTypes\\DatedUpdateHolder.FILTER_WITHIN',
87
-                    'within'
88
-                ) . ' "' . $term->Name . '"';
89
-            }
90
-        }
91
-
92
-        if ($params['from'] || $params['to']) {
93
-            if ($params['from']) {
94
-                $from = strtotime($params['from']);
95
-                if ($params['to']) {
96
-                    $to = strtotime($params['to']);
97
-                    $filters[] = _t('CWP\\CWP\\PageTypes\\DatedUpdateHolder.FILTER_BETWEEN', 'between') . ' '
98
-                        . date('j/m/Y', $from) . ' and ' . date('j/m/Y', $to);
99
-                } else {
100
-                    $filters[] = _t('CWP\\CWP\\PageTypes\\DatedUpdateHolder.FILTER_ON', 'on')
101
-                        . ' ' . date('j/m/Y', $from);
102
-                }
103
-            } else {
104
-                $to = strtotime($params['to']);
105
-                $filters[] = _t('CWP\\CWP\\PageTypes\\DatedUpdateHolder.FILTER_ON', 'on')
106
-                    . ' ' . date('j/m/Y', $to);
107
-            }
108
-        }
109
-
110
-        if ($params['year'] && $params['month']) {
111
-            $timestamp = mktime(1, 1, 1, $params['month'], 1, $params['year']);
112
-            $filters[] = _t('CWP\\CWP\\PageTypes\\DatedUpdateHolder.FILTER_IN', 'in')
113
-                . ' ' . date('F', $timestamp) . ' ' . $params['year'];
114
-        }
115
-
116
-        if ($filters) {
117
-            return $this->getUpdateName() . ' ' . implode(' ', $filters);
118
-        }
119
-    }
120
-
121
-    public function getUpdateName()
122
-    {
123
-        return Config::inst()->get($this->data()->ClassName, 'update_name');
124
-    }
125
-
126
-    protected function init()
127
-    {
128
-        parent::init();
129
-        RSSFeed::linkToFeed($this->Link() . 'rss', $this->getSubscriptionTitle());
130
-    }
131
-
132
-    /**
133
-     * Parse URL parameters.
134
-     *
135
-     * @param bool $produceErrorMessages Set to false to omit session messages.
136
-     */
137
-    public function parseParams($produceErrorMessages = true)
138
-    {
139
-        $tag = $this->request->getVar('tag');
140
-        $from = $this->request->getVar('from');
141
-        $to = $this->request->getVar('to');
142
-        $year = $this->request->getVar('year');
143
-        $month = $this->request->getVar('month');
144
-
145
-        if ($tag == '') {
146
-            $tag = null;
147
-        }
148
-        if ($from == '') {
149
-            $from = null;
150
-        }
151
-        if ($to == '') {
152
-            $to = null;
153
-        }
154
-        if ($year == '') {
155
-            $year = null;
156
-        }
157
-        if ($month == '') {
158
-            $month = null;
159
-        }
160
-
161
-        if (isset($tag)) {
162
-            $tag = (int)$tag;
163
-        }
164
-        if (isset($from)) {
165
-            $from = urldecode($from);
166
-            $parser = DBDatetime::create();
167
-            $parser->setValue($from);
168
-            $from = $parser->Format('y-MM-dd');
169
-        }
170
-        if (isset($to)) {
171
-            $to = urldecode($to);
172
-            $parser = DBDatetime::create();
173
-            $parser->setValue($to);
174
-            $to = $parser->Format('y-MM-dd');
175
-        }
176
-        if (isset($year)) {
177
-            $year = (int)$year;
178
-        }
179
-        if (isset($month)) {
180
-            $month = (int)$month;
181
-        }
182
-
183
-        // If only "To" has been provided filter by single date. Normalise by swapping with "From".
184
-        if (isset($to) && !isset($from)) {
185
-            list($to, $from) = [$from, $to];
186
-        }
187
-
188
-        // Flip the dates if the order is wrong.
189
-        if (isset($to) && isset($from) && strtotime($from) > strtotime($to)) {
190
-            list($to, $from) = [$from, $to];
191
-
192
-            if ($produceErrorMessages) {
193
-                $this->getRequest()->getSession()->set(self::TEMP_FORM_MESSAGE, _t(
194
-                    __CLASS__ . '.FilterAppliedMessage',
195
-                    'Filter has been applied with the dates reversed.'
196
-                ));
197
-            }
198
-        }
199
-
200
-        // Notify the user that filtering by single date is taking place.
201
-        if (isset($from) && !isset($to)) {
202
-            if ($produceErrorMessages) {
203
-                $this->getRequest()->getSession()->set(self::TEMP_FORM_MESSAGE, _t(
204
-                    __CLASS__ . '.DateRangeFilterMessage', 'Filtered by a single date.'
205
-                ));
206
-            }
207
-        }
208
-
209
-        return [
210
-            'tag' => $tag,
211
-            'from' => $from,
212
-            'to' => $to,
213
-            'year' => $year,
214
-            'month' => $month,
215
-        ];
216
-    }
217
-
218
-    /**
219
-     * Build the link - keep the date range, reset the rest.
220
-     */
221
-    public function AllTagsLink()
222
-    {
223
-        $link = HTTP::setGetVar('tag', null, null, '&');
224
-        $link = HTTP::setGetVar('month', null, $link, '&');
225
-        $link = HTTP::setGetVar('year', null, $link, '&');
226
-        $link = HTTP::setGetVar('start', null, $link, '&');
227
-
228
-        return $link;
229
-    }
230
-
231
-    /**
232
-     * List tags and attach links.
233
-     */
234
-    public function UpdateTagsWithLinks()
235
-    {
236
-        $tags = $this->UpdateTags();
237
-
238
-        $processed = ArrayList::create();
239
-
240
-        foreach ($tags as $tag) {
241
-            // Build the link - keep the tag, and date range, but reset month, year and pagination.
242
-            $link = HTTP::setGetVar('tag', $tag->ID, null, '&');
243
-            $link = HTTP::setGetVar('month', null, $link, '&');
244
-            $link = HTTP::setGetVar('year', null, $link, '&');
245
-            $link = HTTP::setGetVar('start', null, $link, '&');
246
-
247
-            $tag->Link = $link;
248
-            $processed->push($tag);
249
-        }
250
-
251
-        return $processed;
252
-    }
253
-
254
-    /**
255
-     * Get the TaxonomyTerm related to the current tag GET parameter.
256
-     */
257
-    public function CurrentTag()
258
-    {
259
-        $tagID = $this->request->getVar('tag');
260
-
261
-        if (isset($tagID)) {
262
-            return TaxonomyTerm::get_by_id(TaxonomyTerm::class, (int)$tagID);
263
-        }
264
-    }
265
-
266
-    /**
267
-     * Extract the available months based on the current query.
268
-     * Only tag is respected. Pagination and months are ignored.
269
-     */
270
-    public function AvailableMonths()
271
-    {
272
-        $params = $this->parseParams();
273
-
274
-        return DatedUpdateHolder::ExtractMonths(
275
-            $this->Updates($params['tag'], $params['from'], $params['to']),
276
-            Director::makeRelative($_SERVER['REQUEST_URI']),
277
-            $params['year'],
278
-            $params['month']
279
-        );
280
-    }
281
-
282
-    /**
283
-     * Get the updates based on the current query.
284
-     */
285
-    public function FilteredUpdates($pageSize = 20)
286
-    {
287
-        $params = $this->parseParams();
288
-
289
-        $items = $this->Updates(
290
-            $params['tag'],
291
-            $params['from'],
292
-            $params['to'],
293
-            $params['year'],
294
-            $params['month']
295
-        );
296
-
297
-        // Apply pagination
298
-        $list = PaginatedList::create($items, $this->getRequest());
299
-        $list->setPageLength($pageSize);
300
-        return $list;
301
-    }
302
-
303
-    /**
304
-     * @return Form
305
-     */
306
-    public function DateRangeForm()
307
-    {
308
-        $dateFromTitle = DBField::create_field('HTMLText', sprintf(
309
-            '%s <span class="field-note">%s</span>',
310
-            _t('CWP\\CWP\\PageTypes\\DatedUpdateHolder.FROM_DATE', 'From date'),
311
-            _t('CWP\\CWP\\PageTypes\\DatedUpdateHolder.DATE_EXAMPLE', '(example: 2017/12/30)')
312
-        ));
313
-        $dateToTitle = DBField::create_field('HTMLText', sprintf(
314
-            '%s <span class="field-note">%s</span>',
315
-            _t('CWP\\CWP\\PageTypes\\DatedUpdateHolder.TO_DATE', 'To date'),
316
-            _t('CWP\\CWP\\PageTypes\\DatedUpdateHolder.DATE_EXAMPLE', '(example: 2017/12/30)')
317
-        ));
318
-
319
-        $fields = FieldList::create(
320
-            DateField::create('from', $dateFromTitle),
321
-            DateField::create('to', $dateToTitle),
322
-            HiddenField::create('tag')
323
-        );
324
-
325
-        $actions = FieldList::create(
326
-            FormAction::create("doDateFilter")
327
-                ->setTitle(_t(__CLASS__ . '.Filter', 'Filter'))
328
-                ->addExtraClass('btn btn-primary primary'),
329
-            FormAction::create("doDateReset")
330
-                ->setTitle(_t(__CLASS__ . '.Clear', 'Clear'))
331
-                ->addExtraClass('btn')
332
-        );
333
-
334
-        $form = Form::create($this, 'DateRangeForm', $fields, $actions);
335
-        $form->loadDataFrom($this->request->getVars());
336
-        $form->setFormMethod('get');
337
-
338
-        // Add any locally stored form messages before returning
339
-        if ($formMessage = $this->getRequest()->getSession()->get(self::TEMP_FORM_MESSAGE)) {
340
-            $form->setMessage($formMessage, ValidationResult::TYPE_WARNING);
341
-            $this->getRequest()->getSession()->clear(self::TEMP_FORM_MESSAGE);
342
-        }
343
-
344
-        return $form;
345
-    }
346
-
347
-    public function doDateFilter()
348
-    {
349
-        $params = $this->parseParams();
350
-
351
-        // Build the link - keep the tag, but reset month, year and pagination.
352
-        $link = HTTP::setGetVar('from', $params['from'], $this->AbsoluteLink(), '&');
353
-        $link = HTTP::setGetVar('to', $params['to'], $link, '&');
354
-        if (isset($params['tag'])) {
355
-            $link = HTTP::setGetVar('tag', $params['tag'], $link, '&');
356
-        }
357
-
358
-        $this->redirect($link);
359
-    }
360
-
361
-    public function doDateReset()
362
-    {
363
-        $params = $this->parseParams(false);
364
-
365
-        // Reset the link - only include the tag.
366
-        $link = $this->AbsoluteLink();
367
-        if (isset($params['tag'])) {
368
-            $link = HTTP::setGetVar('tag', $params['tag'], $link, '&');
369
-        }
370
-
371
-        $this->redirect($link);
372
-    }
373
-
374
-    public function rss()
375
-    {
376
-        $rss = RSSFeed::create(
377
-            $this->Updates()->sort('Created DESC')->limit(20),
378
-            $this->Link('rss'),
379
-            $this->getSubscriptionTitle()
380
-        );
381
-        return $rss->outputToBrowser();
382
-    }
383
-
384
-    public function atom()
385
-    {
386
-        $atom = CwpAtomFeed::create(
387
-            $this->Updates()->sort('Created DESC')->limit(20),
388
-            $this->Link('atom'),
389
-            $this->getSubscriptionTitle()
390
-        );
391
-        return $atom->outputToBrowser();
392
-    }
37
+	private static $allowed_actions = [
38
+		'rss',
39
+		'atom',
40
+		'DateRangeForm',
41
+	];
42
+
43
+	private static $casting = [
44
+		'MetaTitle' => 'Text',
45
+		'FilterDescription' => 'Text',
46
+	];
47
+
48
+	/**
49
+	 * The session key for storing temporary form messages
50
+	 *
51
+	 * @var string
52
+	 */
53
+	const TEMP_FORM_MESSAGE = __CLASS__ . '.TempFormMessage';
54
+
55
+	/**
56
+	 * Get the meta title for the current action
57
+	 *
58
+	 * @return string
59
+	 */
60
+	public function getMetaTitle()
61
+	{
62
+		$title = $this->data()->getTitle();
63
+		$filter = $this->FilterDescription();
64
+		if ($filter) {
65
+			$title = "{$title} - {$filter}";
66
+		}
67
+
68
+		$this->extend('updateMetaTitle', $title);
69
+		return $title;
70
+	}
71
+
72
+	/**
73
+	 * Returns a description of the current filter
74
+	 *
75
+	 * @return string
76
+	 */
77
+	public function FilterDescription()
78
+	{
79
+		$params = $this->parseParams();
80
+
81
+		$filters = array();
82
+		if ($params['tag']) {
83
+			$term = TaxonomyTerm::get_by_id(TaxonomyTerm::class, $params['tag']);
84
+			if ($term) {
85
+				$filters[] = _t(
86
+					'CWP\\CWP\\PageTypes\\DatedUpdateHolder.FILTER_WITHIN',
87
+					'within'
88
+				) . ' "' . $term->Name . '"';
89
+			}
90
+		}
91
+
92
+		if ($params['from'] || $params['to']) {
93
+			if ($params['from']) {
94
+				$from = strtotime($params['from']);
95
+				if ($params['to']) {
96
+					$to = strtotime($params['to']);
97
+					$filters[] = _t('CWP\\CWP\\PageTypes\\DatedUpdateHolder.FILTER_BETWEEN', 'between') . ' '
98
+						. date('j/m/Y', $from) . ' and ' . date('j/m/Y', $to);
99
+				} else {
100
+					$filters[] = _t('CWP\\CWP\\PageTypes\\DatedUpdateHolder.FILTER_ON', 'on')
101
+						. ' ' . date('j/m/Y', $from);
102
+				}
103
+			} else {
104
+				$to = strtotime($params['to']);
105
+				$filters[] = _t('CWP\\CWP\\PageTypes\\DatedUpdateHolder.FILTER_ON', 'on')
106
+					. ' ' . date('j/m/Y', $to);
107
+			}
108
+		}
109
+
110
+		if ($params['year'] && $params['month']) {
111
+			$timestamp = mktime(1, 1, 1, $params['month'], 1, $params['year']);
112
+			$filters[] = _t('CWP\\CWP\\PageTypes\\DatedUpdateHolder.FILTER_IN', 'in')
113
+				. ' ' . date('F', $timestamp) . ' ' . $params['year'];
114
+		}
115
+
116
+		if ($filters) {
117
+			return $this->getUpdateName() . ' ' . implode(' ', $filters);
118
+		}
119
+	}
120
+
121
+	public function getUpdateName()
122
+	{
123
+		return Config::inst()->get($this->data()->ClassName, 'update_name');
124
+	}
125
+
126
+	protected function init()
127
+	{
128
+		parent::init();
129
+		RSSFeed::linkToFeed($this->Link() . 'rss', $this->getSubscriptionTitle());
130
+	}
131
+
132
+	/**
133
+	 * Parse URL parameters.
134
+	 *
135
+	 * @param bool $produceErrorMessages Set to false to omit session messages.
136
+	 */
137
+	public function parseParams($produceErrorMessages = true)
138
+	{
139
+		$tag = $this->request->getVar('tag');
140
+		$from = $this->request->getVar('from');
141
+		$to = $this->request->getVar('to');
142
+		$year = $this->request->getVar('year');
143
+		$month = $this->request->getVar('month');
144
+
145
+		if ($tag == '') {
146
+			$tag = null;
147
+		}
148
+		if ($from == '') {
149
+			$from = null;
150
+		}
151
+		if ($to == '') {
152
+			$to = null;
153
+		}
154
+		if ($year == '') {
155
+			$year = null;
156
+		}
157
+		if ($month == '') {
158
+			$month = null;
159
+		}
160
+
161
+		if (isset($tag)) {
162
+			$tag = (int)$tag;
163
+		}
164
+		if (isset($from)) {
165
+			$from = urldecode($from);
166
+			$parser = DBDatetime::create();
167
+			$parser->setValue($from);
168
+			$from = $parser->Format('y-MM-dd');
169
+		}
170
+		if (isset($to)) {
171
+			$to = urldecode($to);
172
+			$parser = DBDatetime::create();
173
+			$parser->setValue($to);
174
+			$to = $parser->Format('y-MM-dd');
175
+		}
176
+		if (isset($year)) {
177
+			$year = (int)$year;
178
+		}
179
+		if (isset($month)) {
180
+			$month = (int)$month;
181
+		}
182
+
183
+		// If only "To" has been provided filter by single date. Normalise by swapping with "From".
184
+		if (isset($to) && !isset($from)) {
185
+			list($to, $from) = [$from, $to];
186
+		}
187
+
188
+		// Flip the dates if the order is wrong.
189
+		if (isset($to) && isset($from) && strtotime($from) > strtotime($to)) {
190
+			list($to, $from) = [$from, $to];
191
+
192
+			if ($produceErrorMessages) {
193
+				$this->getRequest()->getSession()->set(self::TEMP_FORM_MESSAGE, _t(
194
+					__CLASS__ . '.FilterAppliedMessage',
195
+					'Filter has been applied with the dates reversed.'
196
+				));
197
+			}
198
+		}
199
+
200
+		// Notify the user that filtering by single date is taking place.
201
+		if (isset($from) && !isset($to)) {
202
+			if ($produceErrorMessages) {
203
+				$this->getRequest()->getSession()->set(self::TEMP_FORM_MESSAGE, _t(
204
+					__CLASS__ . '.DateRangeFilterMessage', 'Filtered by a single date.'
205
+				));
206
+			}
207
+		}
208
+
209
+		return [
210
+			'tag' => $tag,
211
+			'from' => $from,
212
+			'to' => $to,
213
+			'year' => $year,
214
+			'month' => $month,
215
+		];
216
+	}
217
+
218
+	/**
219
+	 * Build the link - keep the date range, reset the rest.
220
+	 */
221
+	public function AllTagsLink()
222
+	{
223
+		$link = HTTP::setGetVar('tag', null, null, '&');
224
+		$link = HTTP::setGetVar('month', null, $link, '&');
225
+		$link = HTTP::setGetVar('year', null, $link, '&');
226
+		$link = HTTP::setGetVar('start', null, $link, '&');
227
+
228
+		return $link;
229
+	}
230
+
231
+	/**
232
+	 * List tags and attach links.
233
+	 */
234
+	public function UpdateTagsWithLinks()
235
+	{
236
+		$tags = $this->UpdateTags();
237
+
238
+		$processed = ArrayList::create();
239
+
240
+		foreach ($tags as $tag) {
241
+			// Build the link - keep the tag, and date range, but reset month, year and pagination.
242
+			$link = HTTP::setGetVar('tag', $tag->ID, null, '&');
243
+			$link = HTTP::setGetVar('month', null, $link, '&');
244
+			$link = HTTP::setGetVar('year', null, $link, '&');
245
+			$link = HTTP::setGetVar('start', null, $link, '&');
246
+
247
+			$tag->Link = $link;
248
+			$processed->push($tag);
249
+		}
250
+
251
+		return $processed;
252
+	}
253
+
254
+	/**
255
+	 * Get the TaxonomyTerm related to the current tag GET parameter.
256
+	 */
257
+	public function CurrentTag()
258
+	{
259
+		$tagID = $this->request->getVar('tag');
260
+
261
+		if (isset($tagID)) {
262
+			return TaxonomyTerm::get_by_id(TaxonomyTerm::class, (int)$tagID);
263
+		}
264
+	}
265
+
266
+	/**
267
+	 * Extract the available months based on the current query.
268
+	 * Only tag is respected. Pagination and months are ignored.
269
+	 */
270
+	public function AvailableMonths()
271
+	{
272
+		$params = $this->parseParams();
273
+
274
+		return DatedUpdateHolder::ExtractMonths(
275
+			$this->Updates($params['tag'], $params['from'], $params['to']),
276
+			Director::makeRelative($_SERVER['REQUEST_URI']),
277
+			$params['year'],
278
+			$params['month']
279
+		);
280
+	}
281
+
282
+	/**
283
+	 * Get the updates based on the current query.
284
+	 */
285
+	public function FilteredUpdates($pageSize = 20)
286
+	{
287
+		$params = $this->parseParams();
288
+
289
+		$items = $this->Updates(
290
+			$params['tag'],
291
+			$params['from'],
292
+			$params['to'],
293
+			$params['year'],
294
+			$params['month']
295
+		);
296
+
297
+		// Apply pagination
298
+		$list = PaginatedList::create($items, $this->getRequest());
299
+		$list->setPageLength($pageSize);
300
+		return $list;
301
+	}
302
+
303
+	/**
304
+	 * @return Form
305
+	 */
306
+	public function DateRangeForm()
307
+	{
308
+		$dateFromTitle = DBField::create_field('HTMLText', sprintf(
309
+			'%s <span class="field-note">%s</span>',
310
+			_t('CWP\\CWP\\PageTypes\\DatedUpdateHolder.FROM_DATE', 'From date'),
311
+			_t('CWP\\CWP\\PageTypes\\DatedUpdateHolder.DATE_EXAMPLE', '(example: 2017/12/30)')
312
+		));
313
+		$dateToTitle = DBField::create_field('HTMLText', sprintf(
314
+			'%s <span class="field-note">%s</span>',
315
+			_t('CWP\\CWP\\PageTypes\\DatedUpdateHolder.TO_DATE', 'To date'),
316
+			_t('CWP\\CWP\\PageTypes\\DatedUpdateHolder.DATE_EXAMPLE', '(example: 2017/12/30)')
317
+		));
318
+
319
+		$fields = FieldList::create(
320
+			DateField::create('from', $dateFromTitle),
321
+			DateField::create('to', $dateToTitle),
322
+			HiddenField::create('tag')
323
+		);
324
+
325
+		$actions = FieldList::create(
326
+			FormAction::create("doDateFilter")
327
+				->setTitle(_t(__CLASS__ . '.Filter', 'Filter'))
328
+				->addExtraClass('btn btn-primary primary'),
329
+			FormAction::create("doDateReset")
330
+				->setTitle(_t(__CLASS__ . '.Clear', 'Clear'))
331
+				->addExtraClass('btn')
332
+		);
333
+
334
+		$form = Form::create($this, 'DateRangeForm', $fields, $actions);
335
+		$form->loadDataFrom($this->request->getVars());
336
+		$form->setFormMethod('get');
337
+
338
+		// Add any locally stored form messages before returning
339
+		if ($formMessage = $this->getRequest()->getSession()->get(self::TEMP_FORM_MESSAGE)) {
340
+			$form->setMessage($formMessage, ValidationResult::TYPE_WARNING);
341
+			$this->getRequest()->getSession()->clear(self::TEMP_FORM_MESSAGE);
342
+		}
343
+
344
+		return $form;
345
+	}
346
+
347
+	public function doDateFilter()
348
+	{
349
+		$params = $this->parseParams();
350
+
351
+		// Build the link - keep the tag, but reset month, year and pagination.
352
+		$link = HTTP::setGetVar('from', $params['from'], $this->AbsoluteLink(), '&');
353
+		$link = HTTP::setGetVar('to', $params['to'], $link, '&');
354
+		if (isset($params['tag'])) {
355
+			$link = HTTP::setGetVar('tag', $params['tag'], $link, '&');
356
+		}
357
+
358
+		$this->redirect($link);
359
+	}
360
+
361
+	public function doDateReset()
362
+	{
363
+		$params = $this->parseParams(false);
364
+
365
+		// Reset the link - only include the tag.
366
+		$link = $this->AbsoluteLink();
367
+		if (isset($params['tag'])) {
368
+			$link = HTTP::setGetVar('tag', $params['tag'], $link, '&');
369
+		}
370
+
371
+		$this->redirect($link);
372
+	}
373
+
374
+	public function rss()
375
+	{
376
+		$rss = RSSFeed::create(
377
+			$this->Updates()->sort('Created DESC')->limit(20),
378
+			$this->Link('rss'),
379
+			$this->getSubscriptionTitle()
380
+		);
381
+		return $rss->outputToBrowser();
382
+	}
383
+
384
+	public function atom()
385
+	{
386
+		$atom = CwpAtomFeed::create(
387
+			$this->Updates()->sort('Created DESC')->limit(20),
388
+			$this->Link('atom'),
389
+			$this->getSubscriptionTitle()
390
+		);
391
+		return $atom->outputToBrowser();
392
+	}
393 393
 }
Please login to merge, or discard this patch.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -159,7 +159,7 @@  discard block
 block discarded – undo
159 159
         }
160 160
 
161 161
         if (isset($tag)) {
162
-            $tag = (int)$tag;
162
+            $tag = (int) $tag;
163 163
         }
164 164
         if (isset($from)) {
165 165
             $from = urldecode($from);
@@ -174,10 +174,10 @@  discard block
 block discarded – undo
174 174
             $to = $parser->Format('y-MM-dd');
175 175
         }
176 176
         if (isset($year)) {
177
-            $year = (int)$year;
177
+            $year = (int) $year;
178 178
         }
179 179
         if (isset($month)) {
180
-            $month = (int)$month;
180
+            $month = (int) $month;
181 181
         }
182 182
 
183 183
         // If only "To" has been provided filter by single date. Normalise by swapping with "From".
@@ -259,7 +259,7 @@  discard block
 block discarded – undo
259 259
         $tagID = $this->request->getVar('tag');
260 260
 
261 261
         if (isset($tagID)) {
262
-            return TaxonomyTerm::get_by_id(TaxonomyTerm::class, (int)$tagID);
262
+            return TaxonomyTerm::get_by_id(TaxonomyTerm::class, (int) $tagID);
263 263
         }
264 264
     }
265 265
 
Please login to merge, or discard this patch.
src/PageTypes/BasePage.php 2 patches
Indentation   +236 added lines, -236 removed lines patch added patch discarded remove patch
@@ -28,240 +28,240 @@
 block discarded – undo
28 28
 
29 29
 class BasePage extends SiteTree
30 30
 {
31
-    private static $icon = 'cwp/cwp:images/icons/sitetree_images/page.png';
32
-
33
-    /**
34
-     * Hide this page type from the CMS. hide_ancestor is slightly misnamed, should really be just "hide"
35
-     *
36
-     * {@inheritDoc}
37
-     */
38
-    private static $hide_ancestor = BasePage::class;
39
-
40
-    /**
41
-     * @config
42
-     * @var bool
43
-     */
44
-    private static $pdf_export = false;
45
-
46
-    /**
47
-     * Domain to generate PDF's from, DOES not include protocol
48
-     * i.e. google.com not http://google.com
49
-     * @config
50
-     * @var string
51
-     */
52
-    private static $pdf_base_url = "";
53
-
54
-    /**
55
-     * Allow custom overriding of the path to the WKHTMLTOPDF binary, in cases
56
-     * where multiple versions of the binary are available to choose from. This
57
-     * should be the full path to the binary (e.g. /usr/local/bin/wkhtmltopdf)
58
-     * @see BasePage_Controller::generatePDF();
59
-     *
60
-     * @config
61
-     * @var string|null
62
-     */
63
-    private static $wkhtmltopdf_binary = null;
64
-
65
-    /**
66
-     * Where to store generated PDF files
67
-     *
68
-     * @config
69
-     * @var string
70
-     */
71
-    private static $generated_pdf_path = 'assets/_generated_pdfs';
72
-
73
-    private static $api_access = [
74
-        'view' => [
75
-            'Locale', 'URLSegment', 'Title', 'MenuTitle', 'Content', 'MetaDescription',
76
-            'ExtraMenu', 'Sort', 'Version', 'ParentID', 'ID'
77
-        ],
78
-        'edit' => [
79
-            'Locale', 'URLSegment', 'Title', 'MenuTitle', 'Content', 'MetaDescription',
80
-            'ExtraMenu', 'Sort', 'Version', 'ParentID', 'ID'
81
-        ],
82
-    ];
83
-
84
-    private static $table_name = 'BasePage';
85
-
86
-    /**
87
-     * @config
88
-     * @var string
89
-     */
90
-    private static $related_pages_title = 'Related pages';
91
-
92
-    private static $many_many = [
93
-        'Terms' => TaxonomyTerm::class,
94
-        'RelatedPages' => BasePage::class,
95
-    ];
96
-
97
-    private static $many_many_extraFields = [
98
-        'RelatedPages' => [
99
-            'SortOrder' => 'Int',
100
-        ],
101
-    ];
102
-
103
-    private static $plural_name = 'Base Pages';
104
-
105
-    /**
106
-     * Get the footer holder.
107
-     */
108
-    public function getFooter()
109
-    {
110
-        return FooterHolder::get_one(FooterHolder::class);
111
-    }
112
-
113
-    /**
114
-     * Return the full filename of the pdf file, including path & extension
115
-     */
116
-    public function getPdfFilename()
117
-    {
118
-        $baseName = sprintf('%s-%s', $this->URLSegment, $this->ID);
119
-
120
-        $folderPath = $this->config()->get('generated_pdf_path');
121
-        if ($folderPath[0] != '/') {
122
-            $folderPath = BASE_PATH . '/' . $folderPath;
123
-        }
124
-
125
-        return sprintf('%s/%s.pdf', $folderPath, $baseName);
126
-    }
127
-
128
-    /**
129
-     * Build pdf link for template.
130
-     */
131
-    public function PdfLink()
132
-    {
133
-        if (!$this->config()->get('pdf_export')) {
134
-            return false;
135
-        }
136
-
137
-        $path = $this->getPdfFilename();
138
-
139
-        if ((Versioned::get_stage() === Versioned::LIVE) && file_exists($path)) {
140
-            return Director::baseURL() . preg_replace('#^/#', '', Director::makeRelative($path));
141
-        }
142
-        return $this->Link('downloadpdf');
143
-    }
144
-
145
-    public function RelatedPages()
146
-    {
147
-        return $this->getManyManyComponents('RelatedPages')->sort('SortOrder');
148
-    }
149
-
150
-    public function RelatedPagesTitle()
151
-    {
152
-        return $this->config()->get('related_pages_title');
153
-    }
154
-
155
-    /**
156
-     * Remove linked pdf when publishing the page,
157
-     * as it would be out of date.
158
-     */
159
-    public function onAfterPublish()
160
-    {
161
-        $filepath = $this->getPdfFilename();
162
-        if (file_exists($filepath)) {
163
-            unlink($filepath);
164
-        }
165
-    }
166
-
167
-    /**
168
-     * Remove linked pdf when unpublishing the page,
169
-     * so it's no longer valid.
170
-     *
171
-     * @return boolean
172
-     */
173
-    public function doUnpublish()
174
-    {
175
-        if (!parent::doUnpublish()) {
176
-            return false;
177
-        }
178
-
179
-        $filepath = $this->getPdfFilename();
180
-        if (file_exists($filepath)) {
181
-            unlink($filepath);
182
-        }
183
-
184
-        return true;
185
-    }
186
-
187
-    public function getCMSFields()
188
-    {
189
-        $this->beforeUpdateCMSFields(function (FieldList $fields) {
190
-            // Related Pages
191
-            $components = GridFieldConfig_RelationEditor::create();
192
-            $components->removeComponentsByType(GridFieldAddNewButton::class);
193
-            $components->removeComponentsByType(GridFieldEditButton::class);
194
-            $components->removeComponentsByType(GridFieldFilterHeader::class);
195
-            $components->addComponent(new GridFieldSortableRows('SortOrder'));
196
-
197
-            /** @var GridFieldDataColumns $dataColumns */
198
-            $dataColumns = $components->getComponentByType(GridFieldDataColumns::class);
199
-            $dataColumns->setDisplayFields([
200
-                'Title' => _t(__CLASS__ . '.ColumnTitle', 'Title'),
201
-                'ClassName' => _t(__CLASS__ . '.ColumnPageType', 'Page Type')
202
-            ]);
203
-
204
-            $fields->findOrMakeTab(
205
-                'Root.RelatedPages',
206
-                _t(__CLASS__ . '.RelatedPages', 'Related pages')
207
-            );
208
-            $fields->addFieldToTab(
209
-                'Root.RelatedPages',
210
-                GridField::create(
211
-                    'RelatedPages',
212
-                    _t(__CLASS__ . '.RelatedPages', 'Related pages'),
213
-                    $this->RelatedPages(),
214
-                    $components
215
-                )
216
-            );
217
-
218
-            // Taxonomies - Unless they have their own 'Tags' field (such as in Blog, etc)
219
-            $hasMany = $this->hasMany();
220
-            $manyMany = $this->manyMany();
221
-            if (!isset($hasMany['Tags']) && !isset($manyMany['Tags'])) {
222
-                $components = GridFieldConfig_RelationEditor::create();
223
-                $components->removeComponentsByType(GridFieldAddNewButton::class);
224
-                $components->removeComponentsByType(GridFieldEditButton::class);
225
-
226
-                /** @var GridFieldAddExistingAutocompleter $autoCompleter */
227
-                $autoCompleter = $components->getComponentByType(GridFieldAddExistingAutocompleter::class);
228
-                $autoCompleter->setResultsFormat('$Name ($TaxonomyName)');
229
-
230
-                /** @var GridFieldDataColumns $dataColumns */
231
-                $dataColumns = $components->getComponentByType(GridFieldDataColumns::class);
232
-                $dataColumns->setDisplayFields([
233
-                    'Name' => _t(__CLASS__ . '.Term', 'Term'),
234
-                    'TaxonomyName' => _t(__CLASS__ . '.Taxonomy', 'Taxonomy')
235
-                ]);
236
-
237
-                $fields->findOrMakeTab('Root.Tags', _t(__CLASS__ . '.TagsTabTitle', 'Tags'));
238
-                $fields->addFieldToTab(
239
-                    'Root.Tags',
240
-                    TreeMultiselectField::create(
241
-                        'Terms',
242
-                        _t(__CLASS__ . '.Terms', 'Terms'),
243
-                        TaxonomyTerm::class
244
-                    )->setDescription(_t(__CLASS__ . '.TermsDescription', 'Click to search for additional terms'))
245
-                );
246
-            }
247
-        });
248
-        return parent::getCMSFields();
249
-    }
250
-
251
-    /**
252
-     * Returns the native language name for the selected locale/language, empty string if Fluent is not available
253
-     *
254
-     * @return string
255
-     */
256
-    public function getSelectedLanguage()
257
-    {
258
-        if (!class_exists(Locale::class) || !$this->hasMethod('Locales')) {
259
-            return '';
260
-        }
261
-
262
-        /** @var ArrayData $information */
263
-        $information = $this->LocaleInformation(FluentState::singleton()->getLocale());
264
-
265
-        return $information->LanguageNative;
266
-    }
31
+	private static $icon = 'cwp/cwp:images/icons/sitetree_images/page.png';
32
+
33
+	/**
34
+	 * Hide this page type from the CMS. hide_ancestor is slightly misnamed, should really be just "hide"
35
+	 *
36
+	 * {@inheritDoc}
37
+	 */
38
+	private static $hide_ancestor = BasePage::class;
39
+
40
+	/**
41
+	 * @config
42
+	 * @var bool
43
+	 */
44
+	private static $pdf_export = false;
45
+
46
+	/**
47
+	 * Domain to generate PDF's from, DOES not include protocol
48
+	 * i.e. google.com not http://google.com
49
+	 * @config
50
+	 * @var string
51
+	 */
52
+	private static $pdf_base_url = "";
53
+
54
+	/**
55
+	 * Allow custom overriding of the path to the WKHTMLTOPDF binary, in cases
56
+	 * where multiple versions of the binary are available to choose from. This
57
+	 * should be the full path to the binary (e.g. /usr/local/bin/wkhtmltopdf)
58
+	 * @see BasePage_Controller::generatePDF();
59
+	 *
60
+	 * @config
61
+	 * @var string|null
62
+	 */
63
+	private static $wkhtmltopdf_binary = null;
64
+
65
+	/**
66
+	 * Where to store generated PDF files
67
+	 *
68
+	 * @config
69
+	 * @var string
70
+	 */
71
+	private static $generated_pdf_path = 'assets/_generated_pdfs';
72
+
73
+	private static $api_access = [
74
+		'view' => [
75
+			'Locale', 'URLSegment', 'Title', 'MenuTitle', 'Content', 'MetaDescription',
76
+			'ExtraMenu', 'Sort', 'Version', 'ParentID', 'ID'
77
+		],
78
+		'edit' => [
79
+			'Locale', 'URLSegment', 'Title', 'MenuTitle', 'Content', 'MetaDescription',
80
+			'ExtraMenu', 'Sort', 'Version', 'ParentID', 'ID'
81
+		],
82
+	];
83
+
84
+	private static $table_name = 'BasePage';
85
+
86
+	/**
87
+	 * @config
88
+	 * @var string
89
+	 */
90
+	private static $related_pages_title = 'Related pages';
91
+
92
+	private static $many_many = [
93
+		'Terms' => TaxonomyTerm::class,
94
+		'RelatedPages' => BasePage::class,
95
+	];
96
+
97
+	private static $many_many_extraFields = [
98
+		'RelatedPages' => [
99
+			'SortOrder' => 'Int',
100
+		],
101
+	];
102
+
103
+	private static $plural_name = 'Base Pages';
104
+
105
+	/**
106
+	 * Get the footer holder.
107
+	 */
108
+	public function getFooter()
109
+	{
110
+		return FooterHolder::get_one(FooterHolder::class);
111
+	}
112
+
113
+	/**
114
+	 * Return the full filename of the pdf file, including path & extension
115
+	 */
116
+	public function getPdfFilename()
117
+	{
118
+		$baseName = sprintf('%s-%s', $this->URLSegment, $this->ID);
119
+
120
+		$folderPath = $this->config()->get('generated_pdf_path');
121
+		if ($folderPath[0] != '/') {
122
+			$folderPath = BASE_PATH . '/' . $folderPath;
123
+		}
124
+
125
+		return sprintf('%s/%s.pdf', $folderPath, $baseName);
126
+	}
127
+
128
+	/**
129
+	 * Build pdf link for template.
130
+	 */
131
+	public function PdfLink()
132
+	{
133
+		if (!$this->config()->get('pdf_export')) {
134
+			return false;
135
+		}
136
+
137
+		$path = $this->getPdfFilename();
138
+
139
+		if ((Versioned::get_stage() === Versioned::LIVE) && file_exists($path)) {
140
+			return Director::baseURL() . preg_replace('#^/#', '', Director::makeRelative($path));
141
+		}
142
+		return $this->Link('downloadpdf');
143
+	}
144
+
145
+	public function RelatedPages()
146
+	{
147
+		return $this->getManyManyComponents('RelatedPages')->sort('SortOrder');
148
+	}
149
+
150
+	public function RelatedPagesTitle()
151
+	{
152
+		return $this->config()->get('related_pages_title');
153
+	}
154
+
155
+	/**
156
+	 * Remove linked pdf when publishing the page,
157
+	 * as it would be out of date.
158
+	 */
159
+	public function onAfterPublish()
160
+	{
161
+		$filepath = $this->getPdfFilename();
162
+		if (file_exists($filepath)) {
163
+			unlink($filepath);
164
+		}
165
+	}
166
+
167
+	/**
168
+	 * Remove linked pdf when unpublishing the page,
169
+	 * so it's no longer valid.
170
+	 *
171
+	 * @return boolean
172
+	 */
173
+	public function doUnpublish()
174
+	{
175
+		if (!parent::doUnpublish()) {
176
+			return false;
177
+		}
178
+
179
+		$filepath = $this->getPdfFilename();
180
+		if (file_exists($filepath)) {
181
+			unlink($filepath);
182
+		}
183
+
184
+		return true;
185
+	}
186
+
187
+	public function getCMSFields()
188
+	{
189
+		$this->beforeUpdateCMSFields(function (FieldList $fields) {
190
+			// Related Pages
191
+			$components = GridFieldConfig_RelationEditor::create();
192
+			$components->removeComponentsByType(GridFieldAddNewButton::class);
193
+			$components->removeComponentsByType(GridFieldEditButton::class);
194
+			$components->removeComponentsByType(GridFieldFilterHeader::class);
195
+			$components->addComponent(new GridFieldSortableRows('SortOrder'));
196
+
197
+			/** @var GridFieldDataColumns $dataColumns */
198
+			$dataColumns = $components->getComponentByType(GridFieldDataColumns::class);
199
+			$dataColumns->setDisplayFields([
200
+				'Title' => _t(__CLASS__ . '.ColumnTitle', 'Title'),
201
+				'ClassName' => _t(__CLASS__ . '.ColumnPageType', 'Page Type')
202
+			]);
203
+
204
+			$fields->findOrMakeTab(
205
+				'Root.RelatedPages',
206
+				_t(__CLASS__ . '.RelatedPages', 'Related pages')
207
+			);
208
+			$fields->addFieldToTab(
209
+				'Root.RelatedPages',
210
+				GridField::create(
211
+					'RelatedPages',
212
+					_t(__CLASS__ . '.RelatedPages', 'Related pages'),
213
+					$this->RelatedPages(),
214
+					$components
215
+				)
216
+			);
217
+
218
+			// Taxonomies - Unless they have their own 'Tags' field (such as in Blog, etc)
219
+			$hasMany = $this->hasMany();
220
+			$manyMany = $this->manyMany();
221
+			if (!isset($hasMany['Tags']) && !isset($manyMany['Tags'])) {
222
+				$components = GridFieldConfig_RelationEditor::create();
223
+				$components->removeComponentsByType(GridFieldAddNewButton::class);
224
+				$components->removeComponentsByType(GridFieldEditButton::class);
225
+
226
+				/** @var GridFieldAddExistingAutocompleter $autoCompleter */
227
+				$autoCompleter = $components->getComponentByType(GridFieldAddExistingAutocompleter::class);
228
+				$autoCompleter->setResultsFormat('$Name ($TaxonomyName)');
229
+
230
+				/** @var GridFieldDataColumns $dataColumns */
231
+				$dataColumns = $components->getComponentByType(GridFieldDataColumns::class);
232
+				$dataColumns->setDisplayFields([
233
+					'Name' => _t(__CLASS__ . '.Term', 'Term'),
234
+					'TaxonomyName' => _t(__CLASS__ . '.Taxonomy', 'Taxonomy')
235
+				]);
236
+
237
+				$fields->findOrMakeTab('Root.Tags', _t(__CLASS__ . '.TagsTabTitle', 'Tags'));
238
+				$fields->addFieldToTab(
239
+					'Root.Tags',
240
+					TreeMultiselectField::create(
241
+						'Terms',
242
+						_t(__CLASS__ . '.Terms', 'Terms'),
243
+						TaxonomyTerm::class
244
+					)->setDescription(_t(__CLASS__ . '.TermsDescription', 'Click to search for additional terms'))
245
+				);
246
+			}
247
+		});
248
+		return parent::getCMSFields();
249
+	}
250
+
251
+	/**
252
+	 * Returns the native language name for the selected locale/language, empty string if Fluent is not available
253
+	 *
254
+	 * @return string
255
+	 */
256
+	public function getSelectedLanguage()
257
+	{
258
+		if (!class_exists(Locale::class) || !$this->hasMethod('Locales')) {
259
+			return '';
260
+		}
261
+
262
+		/** @var ArrayData $information */
263
+		$information = $this->LocaleInformation(FluentState::singleton()->getLocale());
264
+
265
+		return $information->LanguageNative;
266
+	}
267 267
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -186,7 +186,7 @@
 block discarded – undo
186 186
 
187 187
     public function getCMSFields()
188 188
     {
189
-        $this->beforeUpdateCMSFields(function (FieldList $fields) {
189
+        $this->beforeUpdateCMSFields(function(FieldList $fields) {
190 190
             // Related Pages
191 191
             $components = GridFieldConfig_RelationEditor::create();
192 192
             $components->removeComponentsByType(GridFieldAddNewButton::class);
Please login to merge, or discard this patch.
src/PageTypes/BasePageController.php 2 patches
Indentation   +153 added lines, -153 removed lines patch added patch discarded remove patch
@@ -13,163 +13,163 @@
 block discarded – undo
13 13
 
14 14
 class BasePageController extends ContentController
15 15
 {
16
-    private static $allowed_actions = [
17
-        'downloadpdf',
18
-    ];
19
-
20
-    /**
21
-     * Serve the page rendered as PDF.
22
-     */
23
-    public function downloadpdf()
24
-    {
25
-        if (!Config::inst()->get(BasePage::class, 'pdf_export')) {
26
-            return false;
27
-        }
28
-
29
-        // We only allow producing live pdf. There is no way to secure the draft files.
30
-        Versioned::set_stage(Versioned::LIVE);
31
-
32
-        $path = $this->dataRecord->getPdfFilename();
33
-        if (!file_exists($path)) {
34
-            $this->generatePDF();
35
-        }
36
-
37
-        return HTTPRequest::send_file(file_get_contents($path), basename($path), 'application/pdf');
38
-    }
39
-
40
-    /*
16
+	private static $allowed_actions = [
17
+		'downloadpdf',
18
+	];
19
+
20
+	/**
21
+	 * Serve the page rendered as PDF.
22
+	 */
23
+	public function downloadpdf()
24
+	{
25
+		if (!Config::inst()->get(BasePage::class, 'pdf_export')) {
26
+			return false;
27
+		}
28
+
29
+		// We only allow producing live pdf. There is no way to secure the draft files.
30
+		Versioned::set_stage(Versioned::LIVE);
31
+
32
+		$path = $this->dataRecord->getPdfFilename();
33
+		if (!file_exists($path)) {
34
+			$this->generatePDF();
35
+		}
36
+
37
+		return HTTPRequest::send_file(file_get_contents($path), basename($path), 'application/pdf');
38
+	}
39
+
40
+	/*
41 41
     * This will return either pdf_base_url from YML, CWP_SECURE_DOMAIN
42 42
     * from _ss_environment, or blank. In that order of importance.
43 43
     */
44
-    public function getPDFBaseURL()
45
-    {
46
-        //if base url YML is defined in YML, use that
47
-        if (Config::inst()->get(BasePage::class, 'pdf_base_url')) {
48
-            $pdfBaseUrl = Config::inst()->get(BasePage::class, 'pdf_base_url').'/';
49
-            //otherwise, if we are CWP use the secure domain
50
-        } elseif (Environment::getEnv('CWP_SECURE_DOMAIN')) {
51
-            $pdfBaseUrl = Environment::getEnv('CWP_SECURE_DOMAIN') . '/';
52
-            //or if neither, leave blank
53
-        } else {
54
-            $pdfBaseUrl = '';
55
-        }
56
-        return $pdfBaseUrl;
57
-    }
58
-
59
-    /*
44
+	public function getPDFBaseURL()
45
+	{
46
+		//if base url YML is defined in YML, use that
47
+		if (Config::inst()->get(BasePage::class, 'pdf_base_url')) {
48
+			$pdfBaseUrl = Config::inst()->get(BasePage::class, 'pdf_base_url').'/';
49
+			//otherwise, if we are CWP use the secure domain
50
+		} elseif (Environment::getEnv('CWP_SECURE_DOMAIN')) {
51
+			$pdfBaseUrl = Environment::getEnv('CWP_SECURE_DOMAIN') . '/';
52
+			//or if neither, leave blank
53
+		} else {
54
+			$pdfBaseUrl = '';
55
+		}
56
+		return $pdfBaseUrl;
57
+	}
58
+
59
+	/*
60 60
     * Don't use the proxy if the pdf domain is the CWP secure domain
61 61
     * Or if we aren't on a CWP server
62 62
     */
63
-    public function getPDFProxy($pdfBaseUrl)
64
-    {
65
-        if (!Environment::getEnv('CWP_SECURE_DOMAIN')
66
-            || $pdfBaseUrl == Environment::getEnv('CWP_SECURE_DOMAIN') . '/'
67
-        ) {
68
-            $proxy = '';
69
-        } else {
70
-            $proxy = ' --proxy ' . Environment::getEnv('SS_OUTBOUND_PROXY')
71
-                . ':' . Environment::getEnv('SS_OUTBOUND_PROXY_PORT');
72
-        }
73
-        return $proxy;
74
-    }
75
-
76
-    /**
77
-     * Render the page as PDF using wkhtmltopdf.
78
-     */
79
-    public function generatePDF()
80
-    {
81
-        if (!Config::inst()->get(BasePage::class, 'pdf_export')) {
82
-            return false;
83
-        }
84
-
85
-        $binaryPath = Config::inst()->get(BasePage::class, 'wkhtmltopdf_binary');
86
-        if (!$binaryPath || !is_executable($binaryPath)) {
87
-            if (Environment::getEnv('WKHTMLTOPDF_BINARY')
88
-                && is_executable(Environment::getEnv('WKHTMLTOPDF_BINARY'))
89
-            ) {
90
-                $binaryPath = Environment::getEnv('WKHTMLTOPDF_BINARY');
91
-            }
92
-        }
93
-
94
-        if (!$binaryPath) {
95
-            user_error('Neither WKHTMLTOPDF_BINARY nor BasePage.wkhtmltopdf_binary are defined', E_USER_ERROR);
96
-        }
97
-
98
-        if (Versioned::get_reading_mode() == 'Stage.Stage') {
99
-            user_error('Generating PDFs on draft is not supported', E_USER_ERROR);
100
-        }
101
-
102
-        set_time_limit(60);
103
-
104
-        // prepare the paths
105
-        $pdfFile = $this->dataRecord->getPdfFilename();
106
-        $bodyFile = str_replace('.pdf', '_pdf.html', $pdfFile);
107
-        $footerFile = str_replace('.pdf', '_pdffooter.html', $pdfFile);
108
-
109
-        // make sure the work directory exists
110
-        if (!file_exists(dirname($pdfFile))) {
111
-            Filesystem::makeFolder(dirname($pdfFile));
112
-        }
113
-
114
-        //decide the domain to use in generation
115
-        $pdfBaseUrl = $this->getPDFBaseURL();
116
-
117
-        // Force http protocol on CWP - fetching from localhost without using the proxy, SSL terminates on gateway.
118
-        if (Environment::getEnv('CWP_ENVIRONMENT')) {
119
-            Config::modify()->set(Director::class, 'alternate_protocol', 'http');
120
-            //only set alternate protocol if CWP_SECURE_DOMAIN is defined OR pdf_base_url is
121
-            if ($pdfBaseUrl) {
122
-                Config::modify()->set(Director::class, 'alternate_base_url', 'http://' . $pdfBaseUrl);
123
-            }
124
-        }
125
-
126
-        $bodyViewer = $this->getViewer('pdf');
127
-
128
-        // write the output of this page to HTML, ready for conversion to PDF
129
-        file_put_contents($bodyFile, $bodyViewer->process($this));
130
-
131
-        // get the viewer for the current template with _pdffooter
132
-        $footerViewer = $this->getViewer('pdffooter');
133
-
134
-        // write the output of the footer template to HTML, ready for conversion to PDF
135
-        file_put_contents($footerFile, $footerViewer->process($this));
136
-
137
-        //decide what the proxy should look like
138
-        $proxy = $this->getPDFProxy($pdfBaseUrl);
139
-
140
-        // finally, generate the PDF
141
-        $command = $binaryPath . $proxy . ' --outline -B 40pt -L 20pt -R 20pt -T 20pt --encoding utf-8 '
142
-            . '--orientation Portrait --disable-javascript --quiet --print-media-type ';
143
-        $retVal = 0;
144
-        $output = array();
145
-        exec(
146
-            $command . " --footer-html \"$footerFile\" \"$bodyFile\" \"$pdfFile\" &> /dev/stdout",
147
-            $output,
148
-            $retVal
149
-        );
150
-
151
-        // remove temporary file
152
-        unlink($bodyFile);
153
-        unlink($footerFile);
154
-
155
-        // output any errors
156
-        if ($retVal != 0) {
157
-            user_error('wkhtmltopdf failed: ' . implode("\n", $output), E_USER_ERROR);
158
-        }
159
-
160
-        // serve the generated file
161
-        return HTTPRequest::send_file(file_get_contents($pdfFile), basename($pdfFile), 'application/pdf');
162
-    }
163
-
164
-    /**
165
-     * Provide current year.
166
-     */
167
-    public function CurrentDatetime()
168
-    {
169
-        return DBDatetime::now();
170
-    }
171
-
172
-    public function getRSSLink()
173
-    {
174
-    }
63
+	public function getPDFProxy($pdfBaseUrl)
64
+	{
65
+		if (!Environment::getEnv('CWP_SECURE_DOMAIN')
66
+			|| $pdfBaseUrl == Environment::getEnv('CWP_SECURE_DOMAIN') . '/'
67
+		) {
68
+			$proxy = '';
69
+		} else {
70
+			$proxy = ' --proxy ' . Environment::getEnv('SS_OUTBOUND_PROXY')
71
+				. ':' . Environment::getEnv('SS_OUTBOUND_PROXY_PORT');
72
+		}
73
+		return $proxy;
74
+	}
75
+
76
+	/**
77
+	 * Render the page as PDF using wkhtmltopdf.
78
+	 */
79
+	public function generatePDF()
80
+	{
81
+		if (!Config::inst()->get(BasePage::class, 'pdf_export')) {
82
+			return false;
83
+		}
84
+
85
+		$binaryPath = Config::inst()->get(BasePage::class, 'wkhtmltopdf_binary');
86
+		if (!$binaryPath || !is_executable($binaryPath)) {
87
+			if (Environment::getEnv('WKHTMLTOPDF_BINARY')
88
+				&& is_executable(Environment::getEnv('WKHTMLTOPDF_BINARY'))
89
+			) {
90
+				$binaryPath = Environment::getEnv('WKHTMLTOPDF_BINARY');
91
+			}
92
+		}
93
+
94
+		if (!$binaryPath) {
95
+			user_error('Neither WKHTMLTOPDF_BINARY nor BasePage.wkhtmltopdf_binary are defined', E_USER_ERROR);
96
+		}
97
+
98
+		if (Versioned::get_reading_mode() == 'Stage.Stage') {
99
+			user_error('Generating PDFs on draft is not supported', E_USER_ERROR);
100
+		}
101
+
102
+		set_time_limit(60);
103
+
104
+		// prepare the paths
105
+		$pdfFile = $this->dataRecord->getPdfFilename();
106
+		$bodyFile = str_replace('.pdf', '_pdf.html', $pdfFile);
107
+		$footerFile = str_replace('.pdf', '_pdffooter.html', $pdfFile);
108
+
109
+		// make sure the work directory exists
110
+		if (!file_exists(dirname($pdfFile))) {
111
+			Filesystem::makeFolder(dirname($pdfFile));
112
+		}
113
+
114
+		//decide the domain to use in generation
115
+		$pdfBaseUrl = $this->getPDFBaseURL();
116
+
117
+		// Force http protocol on CWP - fetching from localhost without using the proxy, SSL terminates on gateway.
118
+		if (Environment::getEnv('CWP_ENVIRONMENT')) {
119
+			Config::modify()->set(Director::class, 'alternate_protocol', 'http');
120
+			//only set alternate protocol if CWP_SECURE_DOMAIN is defined OR pdf_base_url is
121
+			if ($pdfBaseUrl) {
122
+				Config::modify()->set(Director::class, 'alternate_base_url', 'http://' . $pdfBaseUrl);
123
+			}
124
+		}
125
+
126
+		$bodyViewer = $this->getViewer('pdf');
127
+
128
+		// write the output of this page to HTML, ready for conversion to PDF
129
+		file_put_contents($bodyFile, $bodyViewer->process($this));
130
+
131
+		// get the viewer for the current template with _pdffooter
132
+		$footerViewer = $this->getViewer('pdffooter');
133
+
134
+		// write the output of the footer template to HTML, ready for conversion to PDF
135
+		file_put_contents($footerFile, $footerViewer->process($this));
136
+
137
+		//decide what the proxy should look like
138
+		$proxy = $this->getPDFProxy($pdfBaseUrl);
139
+
140
+		// finally, generate the PDF
141
+		$command = $binaryPath . $proxy . ' --outline -B 40pt -L 20pt -R 20pt -T 20pt --encoding utf-8 '
142
+			. '--orientation Portrait --disable-javascript --quiet --print-media-type ';
143
+		$retVal = 0;
144
+		$output = array();
145
+		exec(
146
+			$command . " --footer-html \"$footerFile\" \"$bodyFile\" \"$pdfFile\" &> /dev/stdout",
147
+			$output,
148
+			$retVal
149
+		);
150
+
151
+		// remove temporary file
152
+		unlink($bodyFile);
153
+		unlink($footerFile);
154
+
155
+		// output any errors
156
+		if ($retVal != 0) {
157
+			user_error('wkhtmltopdf failed: ' . implode("\n", $output), E_USER_ERROR);
158
+		}
159
+
160
+		// serve the generated file
161
+		return HTTPRequest::send_file(file_get_contents($pdfFile), basename($pdfFile), 'application/pdf');
162
+	}
163
+
164
+	/**
165
+	 * Provide current year.
166
+	 */
167
+	public function CurrentDatetime()
168
+	{
169
+		return DBDatetime::now();
170
+	}
171
+
172
+	public function getRSSLink()
173
+	{
174
+	}
175 175
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -45,7 +45,7 @@
 block discarded – undo
45 45
     {
46 46
         //if base url YML is defined in YML, use that
47 47
         if (Config::inst()->get(BasePage::class, 'pdf_base_url')) {
48
-            $pdfBaseUrl = Config::inst()->get(BasePage::class, 'pdf_base_url').'/';
48
+            $pdfBaseUrl = Config::inst()->get(BasePage::class, 'pdf_base_url') . '/';
49 49
             //otherwise, if we are CWP use the secure domain
50 50
         } elseif (Environment::getEnv('CWP_SECURE_DOMAIN')) {
51 51
             $pdfBaseUrl = Environment::getEnv('CWP_SECURE_DOMAIN') . '/';
Please login to merge, or discard this patch.