Passed
Pull Request — master (#22)
by Robbie
03:03
created
src/Extensions/SynonymValidator.php 1 patch
Indentation   +150 added lines, -150 removed lines patch added patch discarded remove patch
@@ -6,154 +6,154 @@
 block discarded – undo
6 6
 
7 7
 class SynonymValidator extends Validator
8 8
 {
9
-    /**
10
-     * @var array
11
-     */
12
-    protected $fieldNames;
13
-
14
-    /**
15
-     * @inheritdoc
16
-     *
17
-     * @param array $fieldNames
18
-     */
19
-    public function __construct(array $fieldNames)
20
-    {
21
-        $this->fieldNames = $fieldNames;
22
-
23
-        parent::__construct();
24
-    }
25
-
26
-    /**
27
-     * @inheritdoc
28
-     *
29
-     * @param array $data
30
-     *
31
-     * @return mixed
32
-     */
33
-    public function php($data)
34
-    {
35
-        foreach ($this->fieldNames as $fieldName) {
36
-            if (empty($data[$fieldName])) {
37
-                return;
38
-            }
39
-
40
-            $this->validateField($fieldName, $data[$fieldName]);
41
-        }
42
-    }
43
-
44
-    /**
45
-     * Validate field values, raising errors if the values are invalid.
46
-     *
47
-     * @param string $fieldName
48
-     * @param mixed $value
49
-     */
50
-    protected function validateField($fieldName, $value)
51
-    {
52
-        if (!$this->validateValue($value)) {
53
-            $this->validationError(
54
-                $fieldName,
55
-                _t(
56
-                    __CLASS__ . '.InvalidValue',
57
-                    'Synonyms cannot contain words separated by spaces'
58
-                )
59
-            );
60
-        }
61
-    }
62
-
63
-    /**
64
-     * Check field values to see that they doesn't contain spaces between words.
65
-     *
66
-     * @param mixed $value
67
-     *
68
-     * @return bool
69
-     */
70
-    protected function validateValue($value)
71
-    {
72
-        // strip empty lines
73
-        $lines = array_filter(
74
-            explode("\n", $value)
75
-        );
76
-
77
-        // strip comments (lines beginning with "#")
78
-        $lines = array_filter($lines, function ($line) {
79
-            $line = trim($line);
80
-
81
-            return !empty($line) && $line[0] !== '#';
82
-        });
83
-
84
-        // validate each line
85
-        foreach ($lines as $line) {
86
-            if (!$this->validateLine($line)) {
87
-                return false;
88
-            }
89
-        }
90
-
91
-        return true;
92
-    }
93
-
94
-    /**
95
-     * Check each line to see that it doesn't contain spaces between words.
96
-     *
97
-     * @param string $line
98
-     *
99
-     * @return bool
100
-     */
101
-    protected function validateLine($line)
102
-    {
103
-        $line = trim($line);
104
-
105
-        $parts = explode(',', $line);
106
-        $parts = array_filter($parts);
107
-
108
-        foreach ($parts as $part) {
109
-            if (!$this->validatePart($part)) {
110
-                return false;
111
-            }
112
-        }
113
-
114
-        return true;
115
-    }
116
-
117
-    /**
118
-     * Check each part of the line doesn't contain spaces between words.
119
-     *
120
-     * @param string $part
121
-     *
122
-     * @return bool
123
-     */
124
-    protected function validatePart($part)
125
-    {
126
-        if (strpos($part, '=>') !== false) {
127
-            $subs = explode('=>', $part);
128
-            $subs = array_filter($subs);
129
-
130
-            foreach ($subs as $sub) {
131
-                if (!$this->validateNoSpaces($sub)) {
132
-                    return false;
133
-                }
134
-            }
135
-
136
-            return true;
137
-        }
138
-
139
-        return $this->validateNoSpaces($part);
140
-    }
141
-
142
-    /**
143
-     * @param string $value
144
-     *
145
-     * @return bool
146
-     */
147
-    protected function validateNoSpaces($value)
148
-    {
149
-        // allow spaces at the beginning and end of the value
150
-        $value = trim($value);
151
-
152
-        // does the value contain 1 or more whitespace characters?
153
-        if (preg_match('/\s+/', $value)) {
154
-            return false;
155
-        }
156
-
157
-        return true;
158
-    }
9
+	/**
10
+	 * @var array
11
+	 */
12
+	protected $fieldNames;
13
+
14
+	/**
15
+	 * @inheritdoc
16
+	 *
17
+	 * @param array $fieldNames
18
+	 */
19
+	public function __construct(array $fieldNames)
20
+	{
21
+		$this->fieldNames = $fieldNames;
22
+
23
+		parent::__construct();
24
+	}
25
+
26
+	/**
27
+	 * @inheritdoc
28
+	 *
29
+	 * @param array $data
30
+	 *
31
+	 * @return mixed
32
+	 */
33
+	public function php($data)
34
+	{
35
+		foreach ($this->fieldNames as $fieldName) {
36
+			if (empty($data[$fieldName])) {
37
+				return;
38
+			}
39
+
40
+			$this->validateField($fieldName, $data[$fieldName]);
41
+		}
42
+	}
43
+
44
+	/**
45
+	 * Validate field values, raising errors if the values are invalid.
46
+	 *
47
+	 * @param string $fieldName
48
+	 * @param mixed $value
49
+	 */
50
+	protected function validateField($fieldName, $value)
51
+	{
52
+		if (!$this->validateValue($value)) {
53
+			$this->validationError(
54
+				$fieldName,
55
+				_t(
56
+					__CLASS__ . '.InvalidValue',
57
+					'Synonyms cannot contain words separated by spaces'
58
+				)
59
+			);
60
+		}
61
+	}
62
+
63
+	/**
64
+	 * Check field values to see that they doesn't contain spaces between words.
65
+	 *
66
+	 * @param mixed $value
67
+	 *
68
+	 * @return bool
69
+	 */
70
+	protected function validateValue($value)
71
+	{
72
+		// strip empty lines
73
+		$lines = array_filter(
74
+			explode("\n", $value)
75
+		);
76
+
77
+		// strip comments (lines beginning with "#")
78
+		$lines = array_filter($lines, function ($line) {
79
+			$line = trim($line);
80
+
81
+			return !empty($line) && $line[0] !== '#';
82
+		});
83
+
84
+		// validate each line
85
+		foreach ($lines as $line) {
86
+			if (!$this->validateLine($line)) {
87
+				return false;
88
+			}
89
+		}
90
+
91
+		return true;
92
+	}
93
+
94
+	/**
95
+	 * Check each line to see that it doesn't contain spaces between words.
96
+	 *
97
+	 * @param string $line
98
+	 *
99
+	 * @return bool
100
+	 */
101
+	protected function validateLine($line)
102
+	{
103
+		$line = trim($line);
104
+
105
+		$parts = explode(',', $line);
106
+		$parts = array_filter($parts);
107
+
108
+		foreach ($parts as $part) {
109
+			if (!$this->validatePart($part)) {
110
+				return false;
111
+			}
112
+		}
113
+
114
+		return true;
115
+	}
116
+
117
+	/**
118
+	 * Check each part of the line doesn't contain spaces between words.
119
+	 *
120
+	 * @param string $part
121
+	 *
122
+	 * @return bool
123
+	 */
124
+	protected function validatePart($part)
125
+	{
126
+		if (strpos($part, '=>') !== false) {
127
+			$subs = explode('=>', $part);
128
+			$subs = array_filter($subs);
129
+
130
+			foreach ($subs as $sub) {
131
+				if (!$this->validateNoSpaces($sub)) {
132
+					return false;
133
+				}
134
+			}
135
+
136
+			return true;
137
+		}
138
+
139
+		return $this->validateNoSpaces($part);
140
+	}
141
+
142
+	/**
143
+	 * @param string $value
144
+	 *
145
+	 * @return bool
146
+	 */
147
+	protected function validateNoSpaces($value)
148
+	{
149
+		// allow spaces at the beginning and end of the value
150
+		$value = trim($value);
151
+
152
+		// does the value contain 1 or more whitespace characters?
153
+		if (preg_match('/\s+/', $value)) {
154
+			return false;
155
+		}
156
+
157
+		return true;
158
+	}
159 159
 }
Please login to merge, or discard this patch.
src/Extensions/CwpSiteTreeFileExtension.php 1 patch
Indentation   +49 added lines, -49 removed lines patch added patch discarded remove patch
@@ -11,53 +11,53 @@
 block discarded – undo
11 11
 class CwpSiteTreeFileExtension extends DataExtension
12 12
 {
13 13
 
14
-    public function updateCMSFields(FieldList $fields)
15
-    {
16
-        Requirements::css('cwp/cwp:css/fieldDescriptionToggle.css');
17
-        Requirements::javascript('cwp/cwp:javascript/fieldDescriptionToggle.js');
18
-
19
-        $fields->insertAfter(
20
-            'LastEdited',
21
-            ReadonlyField::create(
22
-                'BackLinkCount',
23
-                _t('SilverStripe\\CMS\\Model\\SiteTreeFileExtension.BACKLINKCOUNT', 'Used on:'),
24
-                $this->owner->BackLinkTracking()->Count() . ' '
25
-                    . _t('SilverStripe\\CMS\\Model\\SiteTreeFileExtension.PAGES', 'page(s)')
26
-            )
27
-            ->addExtraClass('cms-description-toggle')
28
-            ->setDescription($this->BackLinkHTMLList())
29
-        );
30
-    }
31
-
32
-    /**
33
-     * Generate an HTML list which provides links to where a file is used.
34
-     *
35
-     * @return string
36
-     */
37
-    public function BackLinkHTMLList()
38
-    {
39
-        $html = '<em>' . _t(
40
-            __CLASS__ . '.BACKLINK_LIST_DESCRIPTION',
41
-            'This list shows all pages where the file has been added through a WYSIWYG editor.'
42
-        ) . '</em>';
43
-        $html .= '<ul>';
44
-
45
-        foreach ($this->owner->BackLinkTracking() as $backLink) {
46
-            $listItem = '<li>';
47
-
48
-            // Add the page link
49
-            $listItem .= '<a href="' . $backLink->Link() . '" target="_blank">'
50
-                . Convert::raw2xml($backLink->MenuTitle) . '</a> &ndash; ';
51
-
52
-            // Add the CMS link
53
-            $listItem .= '<a href="' . $backLink->CMSEditLink() . '">'
54
-                . _t(__CLASS__ . '.EDIT', 'Edit') . '</a>';
55
-
56
-            $html .= $listItem . '</li>';
57
-        }
58
-
59
-        $html .= '</ul>';
60
-
61
-        return $html;
62
-    }
14
+	public function updateCMSFields(FieldList $fields)
15
+	{
16
+		Requirements::css('cwp/cwp:css/fieldDescriptionToggle.css');
17
+		Requirements::javascript('cwp/cwp:javascript/fieldDescriptionToggle.js');
18
+
19
+		$fields->insertAfter(
20
+			'LastEdited',
21
+			ReadonlyField::create(
22
+				'BackLinkCount',
23
+				_t('SilverStripe\\CMS\\Model\\SiteTreeFileExtension.BACKLINKCOUNT', 'Used on:'),
24
+				$this->owner->BackLinkTracking()->Count() . ' '
25
+					. _t('SilverStripe\\CMS\\Model\\SiteTreeFileExtension.PAGES', 'page(s)')
26
+			)
27
+			->addExtraClass('cms-description-toggle')
28
+			->setDescription($this->BackLinkHTMLList())
29
+		);
30
+	}
31
+
32
+	/**
33
+	 * Generate an HTML list which provides links to where a file is used.
34
+	 *
35
+	 * @return string
36
+	 */
37
+	public function BackLinkHTMLList()
38
+	{
39
+		$html = '<em>' . _t(
40
+			__CLASS__ . '.BACKLINK_LIST_DESCRIPTION',
41
+			'This list shows all pages where the file has been added through a WYSIWYG editor.'
42
+		) . '</em>';
43
+		$html .= '<ul>';
44
+
45
+		foreach ($this->owner->BackLinkTracking() as $backLink) {
46
+			$listItem = '<li>';
47
+
48
+			// Add the page link
49
+			$listItem .= '<a href="' . $backLink->Link() . '" target="_blank">'
50
+				. Convert::raw2xml($backLink->MenuTitle) . '</a> &ndash; ';
51
+
52
+			// Add the CMS link
53
+			$listItem .= '<a href="' . $backLink->CMSEditLink() . '">'
54
+				. _t(__CLASS__ . '.EDIT', 'Edit') . '</a>';
55
+
56
+			$html .= $listItem . '</li>';
57
+		}
58
+
59
+		$html .= '</ul>';
60
+
61
+		return $html;
62
+	}
63 63
 }
Please login to merge, or discard this patch.
src/Extensions/CwpSiteTreeExtension.php 1 patch
Indentation   +31 added lines, -31 removed lines patch added patch discarded remove patch
@@ -9,39 +9,39 @@
 block discarded – undo
9 9
 
10 10
 class CwpSiteTreeExtension extends DataExtension
11 11
 {
12
-    private static $db = array(
13
-        'ShowPageUtilities' => 'Boolean(1)'
14
-    );
12
+	private static $db = array(
13
+		'ShowPageUtilities' => 'Boolean(1)'
14
+	);
15 15
 
16
-    private static $defaults = array(
17
-        'ShowPageUtilities' => true
18
-    );
16
+	private static $defaults = array(
17
+		'ShowPageUtilities' => true
18
+	);
19 19
 
20
-    /**
21
-     * Modify the settings for a SiteTree
22
-     *
23
-     * {@inheritDoc}
24
-     *
25
-     * @param FieldList $fields
26
-     */
27
-    public function updateSettingsFields(FieldList $fields)
28
-    {
29
-        $helpText = _t(
30
-            __CLASS__ . '.SHOW_PAGE_UTILITIES_HELP',
31
-            'You can disable page utilities (print, share, etc) for this page'
32
-        );
20
+	/**
21
+	 * Modify the settings for a SiteTree
22
+	 *
23
+	 * {@inheritDoc}
24
+	 *
25
+	 * @param FieldList $fields
26
+	 */
27
+	public function updateSettingsFields(FieldList $fields)
28
+	{
29
+		$helpText = _t(
30
+			__CLASS__ . '.SHOW_PAGE_UTILITIES_HELP',
31
+			'You can disable page utilities (print, share, etc) for this page'
32
+		);
33 33
 
34
-        $fields->addFieldsToTab(
35
-            'Root.Settings',
36
-            array(
37
-                LiteralField::create('PageUtilitiesHelp', $helpText),
38
-                CheckboxField::create('ShowPageUtilities', $this->owner->fieldLabel('ShowPageUtilities'))
39
-            )
40
-        );
41
-    }
34
+		$fields->addFieldsToTab(
35
+			'Root.Settings',
36
+			array(
37
+				LiteralField::create('PageUtilitiesHelp', $helpText),
38
+				CheckboxField::create('ShowPageUtilities', $this->owner->fieldLabel('ShowPageUtilities'))
39
+			)
40
+		);
41
+	}
42 42
 
43
-    public function updateFieldLabels(&$labels)
44
-    {
45
-        $labels['ShowPageUtilities'] = _t(__CLASS__ . '.SHOW_PAGE_UTILITIES', 'Show page utilities?');
46
-    }
43
+	public function updateFieldLabels(&$labels)
44
+	{
45
+		$labels['ShowPageUtilities'] = _t(__CLASS__ . '.SHOW_PAGE_UTILITIES', 'Show page utilities?');
46
+	}
47 47
 }
Please login to merge, or discard this patch.
src/Extensions/SynonymsSiteConfig.php 1 patch
Indentation   +42 added lines, -42 removed lines patch added patch discarded remove patch
@@ -16,52 +16,52 @@
 block discarded – undo
16 16
 class SynonymsSiteConfig extends DataExtension
17 17
 {
18 18
 
19
-    private static $db = array(
20
-        'SearchSynonyms' => 'Text', // fulltextsearch synonyms.txt content
21
-    );
19
+	private static $db = array(
20
+		'SearchSynonyms' => 'Text', // fulltextsearch synonyms.txt content
21
+	);
22 22
 
23
-    public function updateCMSFields(FieldList $fields)
24
-    {
25
-        // Don't show this field if you're not an admin
26
-        if (!Permission::check('ADMIN')) {
27
-            return;
28
-        }
23
+	public function updateCMSFields(FieldList $fields)
24
+	{
25
+		// Don't show this field if you're not an admin
26
+		if (!Permission::check('ADMIN')) {
27
+			return;
28
+		}
29 29
 
30
-        // Search synonyms
31
-        $fields->addFieldToTab(
32
-            'Root.FulltextSearch',
33
-            TextareaField::create('SearchSynonyms', _t(__CLASS__ . '.SearchSynonyms', 'Search Synonyms'))
34
-                ->setDescription(_t(
35
-                    __CLASS__ . '.SearchSynonyms_Description',
36
-                    'Enter as many comma separated synonyms as you wish, where '.
37
-                    'each line represents a group of synonyms.<br /> ' .
38
-                    'You will need to run <a rel="external" target="_blank" href="dev/tasks/Solr_Configure">'
39
-                    . 'Solr_Configure</a> if you make any changes'
40
-                ))
41
-        );
42
-    }
30
+		// Search synonyms
31
+		$fields->addFieldToTab(
32
+			'Root.FulltextSearch',
33
+			TextareaField::create('SearchSynonyms', _t(__CLASS__ . '.SearchSynonyms', 'Search Synonyms'))
34
+				->setDescription(_t(
35
+					__CLASS__ . '.SearchSynonyms_Description',
36
+					'Enter as many comma separated synonyms as you wish, where '.
37
+					'each line represents a group of synonyms.<br /> ' .
38
+					'You will need to run <a rel="external" target="_blank" href="dev/tasks/Solr_Configure">'
39
+					. 'Solr_Configure</a> if you make any changes'
40
+				))
41
+		);
42
+	}
43 43
 
44
-    /**
45
-     * @inheritdoc
46
-     *
47
-     * @param ValidationResult $validationResult
48
-     */
49
-    public function validate(ValidationResult $validationResult)
50
-    {
51
-        $validator = new SynonymValidator(array(
52
-            'SearchSynonyms',
53
-        ));
44
+	/**
45
+	 * @inheritdoc
46
+	 *
47
+	 * @param ValidationResult $validationResult
48
+	 */
49
+	public function validate(ValidationResult $validationResult)
50
+	{
51
+		$validator = new SynonymValidator(array(
52
+			'SearchSynonyms',
53
+		));
54 54
 
55
-        $validator->php(array(
56
-            'SearchSynonyms' => $this->owner->SearchSynonyms
57
-        ));
55
+		$validator->php(array(
56
+			'SearchSynonyms' => $this->owner->SearchSynonyms
57
+		));
58 58
 
59
-        $errors = $validator->getErrors();
59
+		$errors = $validator->getErrors();
60 60
 
61
-        if (is_array($errors) || $errors instanceof Traversable) {
62
-            foreach ($errors as $error) {
63
-                $validationResult->addError($error['message']);
64
-            }
65
-        }
66
-    }
61
+		if (is_array($errors) || $errors instanceof Traversable) {
62
+			foreach ($errors as $error) {
63
+				$validationResult->addError($error['message']);
64
+			}
65
+		}
66
+	}
67 67
 }
Please login to merge, or discard this patch.
src/Search/CwpSearchPageController.php 1 patch
Indentation   +20 added lines, -20 removed lines patch added patch discarded remove patch
@@ -11,25 +11,25 @@
 block discarded – undo
11 11
  */
12 12
 class CwpSearchPageController extends PageController
13 13
 {
14
-    /**
15
-     * Create the dummy search record for this page
16
-     *
17
-     * @return CwpSearchPage
18
-     */
19
-    protected function generateSearchRecord()
20
-    {
21
-        $searchPage = CwpSearchPage::create();
22
-        $searchPage->URLSegment = 'search';
23
-        $searchPage->Title = _t('SilverStripe\\CMS\\Search\\SearchForm.SearchResults', 'Search Results');
24
-        $searchPage->ID = -1;
25
-        return $searchPage;
26
-    }
14
+	/**
15
+	 * Create the dummy search record for this page
16
+	 *
17
+	 * @return CwpSearchPage
18
+	 */
19
+	protected function generateSearchRecord()
20
+	{
21
+		$searchPage = CwpSearchPage::create();
22
+		$searchPage->URLSegment = 'search';
23
+		$searchPage->Title = _t('SilverStripe\\CMS\\Search\\SearchForm.SearchResults', 'Search Results');
24
+		$searchPage->ID = -1;
25
+		return $searchPage;
26
+	}
27 27
 
28
-    public function __construct($dataRecord = null)
29
-    {
30
-        if (!$dataRecord) {
31
-            $dataRecord = $this->generateSearchRecord();
32
-        }
33
-        parent::__construct($dataRecord);
34
-    }
28
+	public function __construct($dataRecord = null)
29
+	{
30
+		if (!$dataRecord) {
31
+			$dataRecord = $this->generateSearchRecord();
32
+		}
33
+		parent::__construct($dataRecord);
34
+	}
35 35
 }
Please login to merge, or discard this patch.
src/Tasks/PopulateThemeSampleDataTask.php 1 patch
Indentation   +129 added lines, -129 removed lines patch added patch discarded remove patch
@@ -17,133 +17,133 @@
 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([
93
-                'Title' => _t(
94
-                    'SilverStripe\\UserForms\\Model\\EditableFormField\\EditableFormStep.TITLE_FIRST',
95
-                    'First Page'
96
-                )
97
-            ]),
98
-            EditableTextField::create([
99
-                'Title' => 'Name',
100
-                'Required' => true,
101
-                'RightTitle' => 'Please enter your first and last name'
102
-            ]),
103
-            EditableEmailField::create([
104
-                'Title' => Email::class,
105
-                'Required' => true,
106
-                'Placeholder' => '[email protected]'
107
-            ]),
108
-            EditableTextField::create([
109
-                'Title' => 'Subject'
110
-            ]),
111
-            EditableTextField::create([
112
-                'Title' => 'Message',
113
-                'Required' => true,
114
-                'Rows' => 5
115
-            ])
116
-        );
117
-
118
-        foreach ($fields as $field) {
119
-            $field->write();
120
-            $form->Fields()->add($field);
121
-            $field->copyVersionToStage(Versioned::DRAFT, Versioned::LIVE);
122
-        }
123
-
124
-        $form->copyVersionToStage(Versioned::DRAFT, Versioned::LIVE);
125
-        $form->flushCache();
126
-
127
-        $this->output(' + Created "contact" UserDefinedForm page');
128
-
129
-        return $this;
130
-    }
131
-
132
-    /**
133
-     * Output a message either to the console or browser
134
-     *
135
-     * @param  string $message
136
-     * @return $this
137
-     */
138
-    protected function output($message)
139
-    {
140
-        if (Director::is_cli()) {
141
-            $message .= PHP_EOL;
142
-        } else {
143
-            $message = sprintf('<p>%s</p>', $message);
144
-        }
145
-        echo $message;
146
-
147
-        return $this;
148
-    }
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([
93
+				'Title' => _t(
94
+					'SilverStripe\\UserForms\\Model\\EditableFormField\\EditableFormStep.TITLE_FIRST',
95
+					'First Page'
96
+				)
97
+			]),
98
+			EditableTextField::create([
99
+				'Title' => 'Name',
100
+				'Required' => true,
101
+				'RightTitle' => 'Please enter your first and last name'
102
+			]),
103
+			EditableEmailField::create([
104
+				'Title' => Email::class,
105
+				'Required' => true,
106
+				'Placeholder' => '[email protected]'
107
+			]),
108
+			EditableTextField::create([
109
+				'Title' => 'Subject'
110
+			]),
111
+			EditableTextField::create([
112
+				'Title' => 'Message',
113
+				'Required' => true,
114
+				'Rows' => 5
115
+			])
116
+		);
117
+
118
+		foreach ($fields as $field) {
119
+			$field->write();
120
+			$form->Fields()->add($field);
121
+			$field->copyVersionToStage(Versioned::DRAFT, Versioned::LIVE);
122
+		}
123
+
124
+		$form->copyVersionToStage(Versioned::DRAFT, Versioned::LIVE);
125
+		$form->flushCache();
126
+
127
+		$this->output(' + Created "contact" UserDefinedForm page');
128
+
129
+		return $this;
130
+	}
131
+
132
+	/**
133
+	 * Output a message either to the console or browser
134
+	 *
135
+	 * @param  string $message
136
+	 * @return $this
137
+	 */
138
+	protected function output($message)
139
+	{
140
+		if (Director::is_cli()) {
141
+			$message .= PHP_EOL;
142
+		} else {
143
+			$message = sprintf('<p>%s</p>', $message);
144
+		}
145
+		echo $message;
146
+
147
+		return $this;
148
+	}
149 149
 }
Please login to merge, or discard this patch.
src/PageTypes/DatedUpdatePage.php 1 patch
Indentation   +55 added lines, -55 removed lines patch added patch discarded remove patch
@@ -10,70 +10,70 @@
 block discarded – undo
10 10
 
11 11
 class DatedUpdatePage extends Page
12 12
 {
13
-    /**
14
-     * Meant as an abstract base class.
15
-     *
16
-     * {@inheritDoc}
17
-     */
18
-    private static $hide_ancestor = DatedUpdatePage::class;
13
+	/**
14
+	 * Meant as an abstract base class.
15
+	 *
16
+	 * {@inheritDoc}
17
+	 */
18
+	private static $hide_ancestor = DatedUpdatePage::class;
19 19
 
20
-    private static $singular_name = 'Dated Update Page';
20
+	private static $singular_name = 'Dated Update Page';
21 21
 
22
-    private static $plural_name = 'Dated Update Pages';
22
+	private static $plural_name = 'Dated Update Pages';
23 23
 
24
-    private static $table_name = 'DatedUpdatePage';
24
+	private static $table_name = 'DatedUpdatePage';
25 25
 
26
-    private static $defaults = [
27
-        'ShowInMenus' => false,
28
-    ];
26
+	private static $defaults = [
27
+		'ShowInMenus' => false,
28
+	];
29 29
 
30
-    private static $db = [
31
-        'Abstract' => 'Text',
32
-        'Date' => 'Datetime',
33
-    ];
30
+	private static $db = [
31
+		'Abstract' => 'Text',
32
+		'Date' => 'Datetime',
33
+	];
34 34
 
35
-    /**
36
-     * Add the default for the Date being the current day.
37
-     */
38
-    public function populateDefaults()
39
-    {
40
-        parent::populateDefaults();
35
+	/**
36
+	 * Add the default for the Date being the current day.
37
+	 */
38
+	public function populateDefaults()
39
+	{
40
+		parent::populateDefaults();
41 41
 
42
-        if (!isset($this->Date) || $this->Date === null) {
43
-            $this->Date = DBDatetime::now()->Format('y-MM-dd 09:00:00');
44
-        }
45
-    }
42
+		if (!isset($this->Date) || $this->Date === null) {
43
+			$this->Date = DBDatetime::now()->Format('y-MM-dd 09:00:00');
44
+		}
45
+	}
46 46
 
47
-    public function fieldLabels($includerelations = true)
48
-    {
49
-        $labels = parent::fieldLabels($includerelations);
50
-        $labels['Date'] = _t(__CLASS__ . '.DateLabel', 'Date');
51
-        $labels['Abstract'] = _t(__CLASS__ . '.AbstractTextFieldLabel', 'Abstract');
47
+	public function fieldLabels($includerelations = true)
48
+	{
49
+		$labels = parent::fieldLabels($includerelations);
50
+		$labels['Date'] = _t(__CLASS__ . '.DateLabel', 'Date');
51
+		$labels['Abstract'] = _t(__CLASS__ . '.AbstractTextFieldLabel', 'Abstract');
52 52
 
53
-        return $labels;
54
-    }
53
+		return $labels;
54
+	}
55 55
 
56
-    public function getCMSFields()
57
-    {
58
-        $this->beforeUpdateCMSFields(function (FieldList $fields) {
59
-            $fields->addFieldToTab(
60
-                'Root.Main',
61
-                $dateTimeField = DatetimeField::create('Date', $this->fieldLabel('Date')),
62
-                'Content'
63
-            );
56
+	public function getCMSFields()
57
+	{
58
+		$this->beforeUpdateCMSFields(function (FieldList $fields) {
59
+			$fields->addFieldToTab(
60
+				'Root.Main',
61
+				$dateTimeField = DatetimeField::create('Date', $this->fieldLabel('Date')),
62
+				'Content'
63
+			);
64 64
 
65
-            $fields->addfieldToTab(
66
-                'Root.Main',
67
-                $abstractField = TextareaField::create('Abstract', $this->fieldLabel('Abstract')),
68
-                'Content'
69
-            );
70
-            $abstractField->setAttribute('maxlength', '160');
71
-            $abstractField->setRightTitle(_t(
72
-                __CLASS__ . '.AbstractDesc',
73
-                'The abstract is used as a summary on the listing pages. It is limited to 160 characters.'
74
-            ));
75
-            $abstractField->setRows(6);
76
-        });
77
-        return parent::getCMSFields();
78
-    }
65
+			$fields->addfieldToTab(
66
+				'Root.Main',
67
+				$abstractField = TextareaField::create('Abstract', $this->fieldLabel('Abstract')),
68
+				'Content'
69
+			);
70
+			$abstractField->setAttribute('maxlength', '160');
71
+			$abstractField->setRightTitle(_t(
72
+				__CLASS__ . '.AbstractDesc',
73
+				'The abstract is used as a summary on the listing pages. It is limited to 160 characters.'
74
+			));
75
+			$abstractField->setRows(6);
76
+		});
77
+		return parent::getCMSFields();
78
+	}
79 79
 }
Please login to merge, or discard this patch.
src/PageTypes/BasePage.php 1 patch
Indentation   +287 added lines, -287 removed lines patch added patch discarded remove patch
@@ -29,297 +29,297 @@
 block discarded – undo
29 29
 
30 30
 class BasePage extends SiteTree
31 31
 {
32
-    private static $icon = 'cwp/cwp:images/icons/sitetree_images/page.png';
32
+	private static $icon = 'cwp/cwp:images/icons/sitetree_images/page.png';
33 33
 
34
-    /**
35
-     * Hide this page type from the CMS. hide_ancestor is slightly misnamed, should really be just "hide"
36
-     *
37
-     * {@inheritDoc}
38
-     */
39
-    private static $hide_ancestor = BasePage::class;
34
+	/**
35
+	 * Hide this page type from the CMS. hide_ancestor is slightly misnamed, should really be just "hide"
36
+	 *
37
+	 * {@inheritDoc}
38
+	 */
39
+	private static $hide_ancestor = BasePage::class;
40 40
 
41
-    private static $pdf_export = false;
41
+	private static $pdf_export = false;
42 42
 
43
-    /*
43
+	/*
44 44
     *Domain to generate PDF's from, DOES not include protocol
45 45
     *i.e. google.com not http://google.com
46 46
     */
47
-    private static $pdf_base_url = "";
48
-
49
-    /**
50
-     * Allow custom overriding of the path to the WKHTMLTOPDF binary, in cases
51
-     * where multiple versions of the binary are available to choose from. This
52
-     * should be the full path to the binary (e.g. /usr/local/bin/wkhtmltopdf)
53
-     * @see BasePage_Controller::generatePDF();
54
-     */
55
-    private static $wkhtmltopdf_binary = null;
56
-
57
-    private static $generated_pdf_path = 'assets/_generated_pdfs';
58
-
59
-    private static $api_access = [
60
-        'view' => [
61
-            'Locale', 'URLSegment', 'Title', 'MenuTitle', 'Content', 'MetaDescription',
62
-            'ExtraMenu', 'Sort', 'Version', 'ParentID', 'ID'
63
-        ],
64
-        'edit' => [
65
-            'Locale', 'URLSegment', 'Title', 'MenuTitle', 'Content', 'MetaDescription',
66
-            'ExtraMenu', 'Sort', 'Version', 'ParentID', 'ID'
67
-        ],
68
-    ];
69
-
70
-    private static $table_name = 'BasePage';
71
-
72
-    public static $related_pages_title = 'Related pages';
73
-
74
-    private static $many_many = [
75
-        'Terms' => TaxonomyTerm::class,
76
-        'RelatedPages' => BasePage::class,
77
-    ];
78
-
79
-    private static $many_many_extraFields = [
80
-        'RelatedPages' => [
81
-            'SortOrder' => 'Int',
82
-        ],
83
-    ];
84
-
85
-    private static $plural_name = 'Base Pages';
86
-
87
-    /**
88
-     * Get the footer holder.
89
-     */
90
-    public function getFooter()
91
-    {
92
-        return FooterHolder::get_one(FooterHolder::class);
93
-    }
94
-
95
-    /**
96
-     * Return the full filename of the pdf file, including path & extension
97
-     */
98
-    public function getPdfFilename()
99
-    {
100
-        $baseName = sprintf('%s-%s', $this->URLSegment, $this->ID);
101
-
102
-        $folderPath = Config::inst()->get(BasePage::class, 'generated_pdf_path');
103
-        if ($folderPath[0] != '/') {
104
-            $folderPath = BASE_PATH . '/' . $folderPath;
105
-        }
106
-
107
-        return sprintf('%s/%s.pdf', $folderPath, $baseName);
108
-    }
109
-
110
-    /**
111
-     * Build pdf link for template.
112
-     */
113
-    public function PdfLink()
114
-    {
115
-        if (!Config::inst()->get(BasePage::class, 'pdf_export')) {
116
-            return false;
117
-        }
118
-
119
-        $path = $this->getPdfFilename();
120
-
121
-        if ((Versioned::get_stage() === Versioned::LIVE) && file_exists($path)) {
122
-            return Director::baseURL() . preg_replace('#^/#', '', Director::makeRelative($path));
123
-        }
124
-        return $this->Link('downloadpdf');
125
-    }
126
-
127
-    public function RelatedPages()
128
-    {
129
-        return $this->getManyManyComponents('RelatedPages')->sort('SortOrder');
130
-    }
131
-
132
-    public function RelatedPagesTitle()
133
-    {
134
-        return $this->stat('related_pages_title');
135
-    }
136
-
137
-    /**
138
-     * Remove linked pdf when publishing the page,
139
-     * as it would be out of date.
140
-     */
141
-    public function onAfterPublish()
142
-    {
143
-        $filepath = $this->getPdfFilename();
144
-        if (file_exists($filepath)) {
145
-            unlink($filepath);
146
-        }
147
-    }
148
-
149
-    /**
150
-     * Remove linked pdf when unpublishing the page,
151
-     * so it's no longer valid.
152
-     *
153
-     * @return boolean
154
-     */
155
-    public function doUnpublish()
156
-    {
157
-        if (!parent::doUnpublish()) {
158
-            return false;
159
-        }
160
-
161
-        $filepath = $this->getPdfFilename();
162
-        if (file_exists($filepath)) {
163
-            unlink($filepath);
164
-        }
165
-
166
-        return true;
167
-    }
168
-
169
-    /**
170
-     * @deprecated 2.0.0 remove with other deprecations
171
-     * @todo Remove once CWP moves to 3.3 core (which includes this in SiteTree)
172
-     * @return self
173
-     */
174
-    public function doRestoreToStage()
175
-    {
176
-        $this->invokeWithExtensions('onBeforeRestoreToStage', $this);
177
-        $result = parent::doRestoreToStage();
178
-        $this->invokeWithExtensions('onAfterRestoreToStage', $this);
179
-
180
-        return $result;
181
-    }
182
-
183
-    public function getCMSFields()
184
-    {
185
-        $this->beforeUpdateCMSFields(function (FieldList $fields) {
186
-            // Related Pages
187
-            $components = GridFieldConfig_RelationEditor::create();
188
-            $components->removeComponentsByType(GridFieldAddNewButton::class);
189
-            $components->removeComponentsByType(GridFieldEditButton::class);
190
-            $components->removeComponentsByType(GridFieldFilterHeader::class);
191
-            $components->addComponent(new GridFieldSortableRows('SortOrder'));
192
-
193
-            /** @var GridFieldDataColumns $dataColumns */
194
-            $dataColumns = $components->getComponentByType(GridFieldDataColumns::class);
195
-            $dataColumns->setDisplayFields([
196
-                'Title' => _t(__CLASS__ . '.ColumnTitle', 'Title'),
197
-                'ClassName' => _t(__CLASS__ . '.ColumnPageType', 'Page Type')
198
-            ]);
199
-
200
-            $fields->findOrMakeTab(
201
-                'Root.RelatedPages',
202
-                _t(__CLASS__ . '.RelatedPages', 'Related pages')
203
-            );
204
-            $fields->addFieldToTab(
205
-                'Root.RelatedPages',
206
-                GridField::create(
207
-                    'RelatedPages',
208
-                    _t(__CLASS__ . '.RelatedPages', 'Related pages'),
209
-                    $this->RelatedPages(),
210
-                    $components
211
-                )
212
-            );
213
-
214
-            // Taxonomies - Unless they have their own 'Tags' field (such as in Blog, etc)
215
-            $hasMany = $this->hasMany();
216
-            $manyMany = $this->manyMany();
217
-            if (!isset($hasMany['Tags']) && !isset($manyMany['Tags'])) {
218
-                $components = GridFieldConfig_RelationEditor::create();
219
-                $components->removeComponentsByType(GridFieldAddNewButton::class);
220
-                $components->removeComponentsByType(GridFieldEditButton::class);
221
-
222
-                /** @var GridFieldAddExistingAutocompleter $autoCompleter */
223
-                $autoCompleter = $components->getComponentByType(GridFieldAddExistingAutocompleter::class);
224
-                $autoCompleter->setResultsFormat('$Name ($TaxonomyName)');
225
-
226
-                /** @var GridFieldDataColumns $dataColumns */
227
-                $dataColumns = $components->getComponentByType(GridFieldDataColumns::class);
228
-                $dataColumns->setDisplayFields([
229
-                    'Name' => _t(__CLASS__ . '.Term', 'Term'),
230
-                    'TaxonomyName' => _t(__CLASS__ . '.Taxonomy', 'Taxonomy')
231
-                ]);
232
-
233
-                $fields->findOrMakeTab('Root.Tags', _t(__CLASS__ . '.TagsTabTitle', 'Tags'));
234
-                $fields->addFieldToTab(
235
-                    'Root.Tags',
236
-                    TreeMultiselectField::create(
237
-                        'Terms',
238
-                        _t(__CLASS__ . '.Terms', 'Terms'),
239
-                        TaxonomyTerm::class
240
-                    )->setDescription(_t(__CLASS__ . '.TermsDescription', 'Click to search for additional terms'))
241
-                );
242
-            }
243
-        });
244
-        return parent::getCMSFields();
245
-    }
246
-
247
-    /**
248
-     * Provides data for translation navigation.
249
-     * Collects all site translations, marks the current one, and redirects
250
-     * to the translated home page if a. there is a translated homepage and b. the
251
-     * translation of the specific page is not available.
252
-     * @todo re-implement with Fluent
253
-     */
254
-    public function getAvailableTranslations()
255
-    {
256
-        if (!class_exists('Translatable')) {
257
-            return false;
258
-        }
259
-
260
-        $translations = new ArrayList();
261
-        $globalTranslations = Translatable::get_existing_content_languages();
262
-
263
-        foreach ($globalTranslations as $loc => $langName) {
264
-            // Find out the language name in native language.
265
-            $nativeLangName = i18n::get_language_name($loc, true);
266
-            if (!$nativeLangName) {
267
-                $nativeLangName = i18n::get_language_name(i18n::get_lang_from_locale($loc), true);
268
-            }
269
-            if (!$nativeLangName) {
270
-                // Fall back to the locale name.
271
-                $nativeLangName = $langName;
272
-            }
273
-
274
-            // Eliminate the part in brackets (e.g. [mandarin])
275
-            $nativeLangName = preg_replace('/ *[\(\[].*$/', '', $nativeLangName);
276
-
277
-            // Find out the link to the translated page.
278
-            $link = null;
279
-            $page = $this->getTranslation($loc);
280
-            if ($page) {
281
-                $link = $page->Link();
282
-            }
283
-            if (!$link) {
284
-                // Fall back to the home page
285
-                $link = Translatable::get_homepage_link_by_locale($loc);
286
-            }
287
-            if (!$link) {
288
-                continue;
289
-            }
290
-
291
-            // Assemble the table for the switcher.
292
-            $translations->push(new ArrayData(array(
293
-                'Locale' => i18n::convert_rfc1766($loc),
294
-                'LangName' => $nativeLangName,
295
-                'Link' => $link,
296
-                'Current' => (Translatable::get_current_locale()==$loc)
297
-            )));
298
-        }
299
-
300
-        if ($translations->count()>1) {
301
-            return $translations;
302
-        } else {
303
-            return null;
304
-        }
305
-    }
306
-
307
-    /**
308
-     * Returns the native language name for the selected locale/language, empty string if Translatable is not available
309
-     *
310
-     * @return string
311
-     * @todo re-implement with Fluent
312
-     */
313
-    public function getSelectedLanguage()
314
-    {
315
-        if (!class_exists('Translatable')) {
316
-            return '';
317
-        }
318
-
319
-        $language = explode('_', Translatable::get_current_locale());
320
-        $languageCode = array_shift($language);
321
-        $nativeName = i18n::get_language_name($languageCode, true);
322
-
323
-        return $nativeName;
324
-    }
47
+	private static $pdf_base_url = "";
48
+
49
+	/**
50
+	 * Allow custom overriding of the path to the WKHTMLTOPDF binary, in cases
51
+	 * where multiple versions of the binary are available to choose from. This
52
+	 * should be the full path to the binary (e.g. /usr/local/bin/wkhtmltopdf)
53
+	 * @see BasePage_Controller::generatePDF();
54
+	 */
55
+	private static $wkhtmltopdf_binary = null;
56
+
57
+	private static $generated_pdf_path = 'assets/_generated_pdfs';
58
+
59
+	private static $api_access = [
60
+		'view' => [
61
+			'Locale', 'URLSegment', 'Title', 'MenuTitle', 'Content', 'MetaDescription',
62
+			'ExtraMenu', 'Sort', 'Version', 'ParentID', 'ID'
63
+		],
64
+		'edit' => [
65
+			'Locale', 'URLSegment', 'Title', 'MenuTitle', 'Content', 'MetaDescription',
66
+			'ExtraMenu', 'Sort', 'Version', 'ParentID', 'ID'
67
+		],
68
+	];
69
+
70
+	private static $table_name = 'BasePage';
71
+
72
+	public static $related_pages_title = 'Related pages';
73
+
74
+	private static $many_many = [
75
+		'Terms' => TaxonomyTerm::class,
76
+		'RelatedPages' => BasePage::class,
77
+	];
78
+
79
+	private static $many_many_extraFields = [
80
+		'RelatedPages' => [
81
+			'SortOrder' => 'Int',
82
+		],
83
+	];
84
+
85
+	private static $plural_name = 'Base Pages';
86
+
87
+	/**
88
+	 * Get the footer holder.
89
+	 */
90
+	public function getFooter()
91
+	{
92
+		return FooterHolder::get_one(FooterHolder::class);
93
+	}
94
+
95
+	/**
96
+	 * Return the full filename of the pdf file, including path & extension
97
+	 */
98
+	public function getPdfFilename()
99
+	{
100
+		$baseName = sprintf('%s-%s', $this->URLSegment, $this->ID);
101
+
102
+		$folderPath = Config::inst()->get(BasePage::class, 'generated_pdf_path');
103
+		if ($folderPath[0] != '/') {
104
+			$folderPath = BASE_PATH . '/' . $folderPath;
105
+		}
106
+
107
+		return sprintf('%s/%s.pdf', $folderPath, $baseName);
108
+	}
109
+
110
+	/**
111
+	 * Build pdf link for template.
112
+	 */
113
+	public function PdfLink()
114
+	{
115
+		if (!Config::inst()->get(BasePage::class, 'pdf_export')) {
116
+			return false;
117
+		}
118
+
119
+		$path = $this->getPdfFilename();
120
+
121
+		if ((Versioned::get_stage() === Versioned::LIVE) && file_exists($path)) {
122
+			return Director::baseURL() . preg_replace('#^/#', '', Director::makeRelative($path));
123
+		}
124
+		return $this->Link('downloadpdf');
125
+	}
126
+
127
+	public function RelatedPages()
128
+	{
129
+		return $this->getManyManyComponents('RelatedPages')->sort('SortOrder');
130
+	}
131
+
132
+	public function RelatedPagesTitle()
133
+	{
134
+		return $this->stat('related_pages_title');
135
+	}
136
+
137
+	/**
138
+	 * Remove linked pdf when publishing the page,
139
+	 * as it would be out of date.
140
+	 */
141
+	public function onAfterPublish()
142
+	{
143
+		$filepath = $this->getPdfFilename();
144
+		if (file_exists($filepath)) {
145
+			unlink($filepath);
146
+		}
147
+	}
148
+
149
+	/**
150
+	 * Remove linked pdf when unpublishing the page,
151
+	 * so it's no longer valid.
152
+	 *
153
+	 * @return boolean
154
+	 */
155
+	public function doUnpublish()
156
+	{
157
+		if (!parent::doUnpublish()) {
158
+			return false;
159
+		}
160
+
161
+		$filepath = $this->getPdfFilename();
162
+		if (file_exists($filepath)) {
163
+			unlink($filepath);
164
+		}
165
+
166
+		return true;
167
+	}
168
+
169
+	/**
170
+	 * @deprecated 2.0.0 remove with other deprecations
171
+	 * @todo Remove once CWP moves to 3.3 core (which includes this in SiteTree)
172
+	 * @return self
173
+	 */
174
+	public function doRestoreToStage()
175
+	{
176
+		$this->invokeWithExtensions('onBeforeRestoreToStage', $this);
177
+		$result = parent::doRestoreToStage();
178
+		$this->invokeWithExtensions('onAfterRestoreToStage', $this);
179
+
180
+		return $result;
181
+	}
182
+
183
+	public function getCMSFields()
184
+	{
185
+		$this->beforeUpdateCMSFields(function (FieldList $fields) {
186
+			// Related Pages
187
+			$components = GridFieldConfig_RelationEditor::create();
188
+			$components->removeComponentsByType(GridFieldAddNewButton::class);
189
+			$components->removeComponentsByType(GridFieldEditButton::class);
190
+			$components->removeComponentsByType(GridFieldFilterHeader::class);
191
+			$components->addComponent(new GridFieldSortableRows('SortOrder'));
192
+
193
+			/** @var GridFieldDataColumns $dataColumns */
194
+			$dataColumns = $components->getComponentByType(GridFieldDataColumns::class);
195
+			$dataColumns->setDisplayFields([
196
+				'Title' => _t(__CLASS__ . '.ColumnTitle', 'Title'),
197
+				'ClassName' => _t(__CLASS__ . '.ColumnPageType', 'Page Type')
198
+			]);
199
+
200
+			$fields->findOrMakeTab(
201
+				'Root.RelatedPages',
202
+				_t(__CLASS__ . '.RelatedPages', 'Related pages')
203
+			);
204
+			$fields->addFieldToTab(
205
+				'Root.RelatedPages',
206
+				GridField::create(
207
+					'RelatedPages',
208
+					_t(__CLASS__ . '.RelatedPages', 'Related pages'),
209
+					$this->RelatedPages(),
210
+					$components
211
+				)
212
+			);
213
+
214
+			// Taxonomies - Unless they have their own 'Tags' field (such as in Blog, etc)
215
+			$hasMany = $this->hasMany();
216
+			$manyMany = $this->manyMany();
217
+			if (!isset($hasMany['Tags']) && !isset($manyMany['Tags'])) {
218
+				$components = GridFieldConfig_RelationEditor::create();
219
+				$components->removeComponentsByType(GridFieldAddNewButton::class);
220
+				$components->removeComponentsByType(GridFieldEditButton::class);
221
+
222
+				/** @var GridFieldAddExistingAutocompleter $autoCompleter */
223
+				$autoCompleter = $components->getComponentByType(GridFieldAddExistingAutocompleter::class);
224
+				$autoCompleter->setResultsFormat('$Name ($TaxonomyName)');
225
+
226
+				/** @var GridFieldDataColumns $dataColumns */
227
+				$dataColumns = $components->getComponentByType(GridFieldDataColumns::class);
228
+				$dataColumns->setDisplayFields([
229
+					'Name' => _t(__CLASS__ . '.Term', 'Term'),
230
+					'TaxonomyName' => _t(__CLASS__ . '.Taxonomy', 'Taxonomy')
231
+				]);
232
+
233
+				$fields->findOrMakeTab('Root.Tags', _t(__CLASS__ . '.TagsTabTitle', 'Tags'));
234
+				$fields->addFieldToTab(
235
+					'Root.Tags',
236
+					TreeMultiselectField::create(
237
+						'Terms',
238
+						_t(__CLASS__ . '.Terms', 'Terms'),
239
+						TaxonomyTerm::class
240
+					)->setDescription(_t(__CLASS__ . '.TermsDescription', 'Click to search for additional terms'))
241
+				);
242
+			}
243
+		});
244
+		return parent::getCMSFields();
245
+	}
246
+
247
+	/**
248
+	 * Provides data for translation navigation.
249
+	 * Collects all site translations, marks the current one, and redirects
250
+	 * to the translated home page if a. there is a translated homepage and b. the
251
+	 * translation of the specific page is not available.
252
+	 * @todo re-implement with Fluent
253
+	 */
254
+	public function getAvailableTranslations()
255
+	{
256
+		if (!class_exists('Translatable')) {
257
+			return false;
258
+		}
259
+
260
+		$translations = new ArrayList();
261
+		$globalTranslations = Translatable::get_existing_content_languages();
262
+
263
+		foreach ($globalTranslations as $loc => $langName) {
264
+			// Find out the language name in native language.
265
+			$nativeLangName = i18n::get_language_name($loc, true);
266
+			if (!$nativeLangName) {
267
+				$nativeLangName = i18n::get_language_name(i18n::get_lang_from_locale($loc), true);
268
+			}
269
+			if (!$nativeLangName) {
270
+				// Fall back to the locale name.
271
+				$nativeLangName = $langName;
272
+			}
273
+
274
+			// Eliminate the part in brackets (e.g. [mandarin])
275
+			$nativeLangName = preg_replace('/ *[\(\[].*$/', '', $nativeLangName);
276
+
277
+			// Find out the link to the translated page.
278
+			$link = null;
279
+			$page = $this->getTranslation($loc);
280
+			if ($page) {
281
+				$link = $page->Link();
282
+			}
283
+			if (!$link) {
284
+				// Fall back to the home page
285
+				$link = Translatable::get_homepage_link_by_locale($loc);
286
+			}
287
+			if (!$link) {
288
+				continue;
289
+			}
290
+
291
+			// Assemble the table for the switcher.
292
+			$translations->push(new ArrayData(array(
293
+				'Locale' => i18n::convert_rfc1766($loc),
294
+				'LangName' => $nativeLangName,
295
+				'Link' => $link,
296
+				'Current' => (Translatable::get_current_locale()==$loc)
297
+			)));
298
+		}
299
+
300
+		if ($translations->count()>1) {
301
+			return $translations;
302
+		} else {
303
+			return null;
304
+		}
305
+	}
306
+
307
+	/**
308
+	 * Returns the native language name for the selected locale/language, empty string if Translatable is not available
309
+	 *
310
+	 * @return string
311
+	 * @todo re-implement with Fluent
312
+	 */
313
+	public function getSelectedLanguage()
314
+	{
315
+		if (!class_exists('Translatable')) {
316
+			return '';
317
+		}
318
+
319
+		$language = explode('_', Translatable::get_current_locale());
320
+		$languageCode = array_shift($language);
321
+		$nativeName = i18n::get_language_name($languageCode, true);
322
+
323
+		return $nativeName;
324
+	}
325 325
 }
Please login to merge, or discard this patch.
src/PageTypes/BasePageController.php 1 patch
Indentation   +345 added lines, -345 removed lines patch added patch discarded remove patch
@@ -23,355 +23,355 @@
 block discarded – undo
23 23
 
24 24
 class BasePageController extends ContentController
25 25
 {
26
-    private static $allowed_actions = [
27
-        'downloadpdf',
28
-        'SearchForm',
29
-        'results',
30
-    ];
31
-
32
-    /**
33
-     * How many search results should be shown per-page?
34
-     * @var int
35
-     */
36
-    public static $results_per_page = 10;
37
-
38
-    public static $search_index_class = CwpSolrIndex::class;
39
-
40
-    /**
41
-     * If spelling suggestions for searches are given, enable
42
-     * suggested searches to be followed immediately
43
-     *
44
-     * @config
45
-     * @var bool
46
-     */
47
-    private static $search_follow_suggestions = true;
48
-
49
-    /**
50
-     * Which classes should be queried when searching?
51
-     * @var array
52
-     */
53
-    public static $classes_to_search = [
54
-        [
55
-            'class' => 'Page',
56
-            'includeSubclasses' => true,
57
-        ]
58
-    ];
59
-
60
-    /**
61
-     * Serve the page rendered as PDF.
62
-     */
63
-    public function downloadpdf()
64
-    {
65
-        if (!Config::inst()->get(BasePage::class, 'pdf_export')) {
66
-            return false;
67
-        }
68
-
69
-        // We only allow producing live pdf. There is no way to secure the draft files.
70
-        Versioned::set_stage(Versioned::LIVE);
71
-
72
-        $path = $this->dataRecord->getPdfFilename();
73
-        if (!file_exists($path)) {
74
-            $this->generatePDF();
75
-        }
76
-
77
-        return HTTPRequest::send_file(file_get_contents($path), basename($path), 'application/pdf');
78
-    }
79
-
80
-    /*
26
+	private static $allowed_actions = [
27
+		'downloadpdf',
28
+		'SearchForm',
29
+		'results',
30
+	];
31
+
32
+	/**
33
+	 * How many search results should be shown per-page?
34
+	 * @var int
35
+	 */
36
+	public static $results_per_page = 10;
37
+
38
+	public static $search_index_class = CwpSolrIndex::class;
39
+
40
+	/**
41
+	 * If spelling suggestions for searches are given, enable
42
+	 * suggested searches to be followed immediately
43
+	 *
44
+	 * @config
45
+	 * @var bool
46
+	 */
47
+	private static $search_follow_suggestions = true;
48
+
49
+	/**
50
+	 * Which classes should be queried when searching?
51
+	 * @var array
52
+	 */
53
+	public static $classes_to_search = [
54
+		[
55
+			'class' => 'Page',
56
+			'includeSubclasses' => true,
57
+		]
58
+	];
59
+
60
+	/**
61
+	 * Serve the page rendered as PDF.
62
+	 */
63
+	public function downloadpdf()
64
+	{
65
+		if (!Config::inst()->get(BasePage::class, 'pdf_export')) {
66
+			return false;
67
+		}
68
+
69
+		// We only allow producing live pdf. There is no way to secure the draft files.
70
+		Versioned::set_stage(Versioned::LIVE);
71
+
72
+		$path = $this->dataRecord->getPdfFilename();
73
+		if (!file_exists($path)) {
74
+			$this->generatePDF();
75
+		}
76
+
77
+		return HTTPRequest::send_file(file_get_contents($path), basename($path), 'application/pdf');
78
+	}
79
+
80
+	/*
81 81
     * This will return either pdf_base_url from YML, CWP_SECURE_DOMAIN
82 82
     * from _ss_environment, or blank. In that order of importance.
83 83
     */
84
-    public function getPDFBaseURL()
85
-    {
86
-        //if base url YML is defined in YML, use that
87
-        if (Config::inst()->get(BasePage::class, 'pdf_base_url')) {
88
-            $pdfBaseUrl = Config::inst()->get(BasePage::class, 'pdf_base_url').'/';
89
-            //otherwise, if we are CWP use the secure domain
90
-        } elseif (Environment::getEnv('CWP_SECURE_DOMAIN')) {
91
-            $pdfBaseUrl = Environment::getEnv('CWP_SECURE_DOMAIN') . '/';
92
-            //or if neither, leave blank
93
-        } else {
94
-            $pdfBaseUrl = '';
95
-        }
96
-        return $pdfBaseUrl;
97
-    }
98
-
99
-    /*
84
+	public function getPDFBaseURL()
85
+	{
86
+		//if base url YML is defined in YML, use that
87
+		if (Config::inst()->get(BasePage::class, 'pdf_base_url')) {
88
+			$pdfBaseUrl = Config::inst()->get(BasePage::class, 'pdf_base_url').'/';
89
+			//otherwise, if we are CWP use the secure domain
90
+		} elseif (Environment::getEnv('CWP_SECURE_DOMAIN')) {
91
+			$pdfBaseUrl = Environment::getEnv('CWP_SECURE_DOMAIN') . '/';
92
+			//or if neither, leave blank
93
+		} else {
94
+			$pdfBaseUrl = '';
95
+		}
96
+		return $pdfBaseUrl;
97
+	}
98
+
99
+	/*
100 100
     * Don't use the proxy if the pdf domain is the CWP secure domain
101 101
     * Or if we aren't on a CWP server
102 102
     */
103
-    public function getPDFProxy($pdfBaseUrl)
104
-    {
105
-        if (!Environment::getEnv('CWP_SECURE_DOMAIN')
106
-            || $pdfBaseUrl == Environment::getEnv('CWP_SECURE_DOMAIN') . '/'
107
-        ) {
108
-            $proxy = '';
109
-        } else {
110
-            $proxy = ' --proxy ' . Environment::getEnv('SS_OUTBOUND_PROXY')
111
-                . ':' . Environment::getEnv('SS_OUTBOUND_PROXY_PORT');
112
-        }
113
-        return $proxy;
114
-    }
115
-
116
-    /**
117
-     * Render the page as PDF using wkhtmltopdf.
118
-     */
119
-    public function generatePDF()
120
-    {
121
-        if (!Config::inst()->get(BasePage::class, 'pdf_export')) {
122
-            return false;
123
-        }
124
-
125
-        $binaryPath = Config::inst()->get(BasePage::class, 'wkhtmltopdf_binary');
126
-        if (!$binaryPath || !is_executable($binaryPath)) {
127
-            if (Environment::getEnv('WKHTMLTOPDF_BINARY')
128
-                && is_executable(Environment::getEnv('WKHTMLTOPDF_BINARY'))
129
-            ) {
130
-                $binaryPath = Environment::getEnv('WKHTMLTOPDF_BINARY');
131
-            }
132
-        }
133
-
134
-        if (!$binaryPath) {
135
-            user_error('Neither WKHTMLTOPDF_BINARY nor BasePage.wkhtmltopdf_binary are defined', E_USER_ERROR);
136
-        }
137
-
138
-        if (Versioned::get_reading_mode() == 'Stage.Stage') {
139
-            user_error('Generating PDFs on draft is not supported', E_USER_ERROR);
140
-        }
141
-
142
-        set_time_limit(60);
143
-
144
-        // prepare the paths
145
-        $pdfFile = $this->dataRecord->getPdfFilename();
146
-        $bodyFile = str_replace('.pdf', '_pdf.html', $pdfFile);
147
-        $footerFile = str_replace('.pdf', '_pdffooter.html', $pdfFile);
148
-
149
-        // make sure the work directory exists
150
-        if (!file_exists(dirname($pdfFile))) {
151
-            Filesystem::makeFolder(dirname($pdfFile));
152
-        }
153
-
154
-        //decide the domain to use in generation
155
-        $pdfBaseUrl = $this->getPDFBaseURL();
156
-
157
-        // Force http protocol on CWP - fetching from localhost without using the proxy, SSL terminates on gateway.
158
-        if (Environment::getEnv('CWP_ENVIRONMENT')) {
159
-            Config::modify()->set(Director::class, 'alternate_protocol', 'http');
160
-            //only set alternate protocol if CWP_SECURE_DOMAIN is defined OR pdf_base_url is
161
-            if ($pdfBaseUrl) {
162
-                Config::modify()->set(Director::class, 'alternate_base_url', 'http://' . $pdfBaseUrl);
163
-            }
164
-        }
165
-
166
-        $bodyViewer = $this->getViewer('pdf');
167
-
168
-        // write the output of this page to HTML, ready for conversion to PDF
169
-        file_put_contents($bodyFile, $bodyViewer->process($this));
170
-
171
-        // get the viewer for the current template with _pdffooter
172
-        $footerViewer = $this->getViewer('pdffooter');
173
-
174
-        // write the output of the footer template to HTML, ready for conversion to PDF
175
-        file_put_contents($footerFile, $footerViewer->process($this));
176
-
177
-        //decide what the proxy should look like
178
-        $proxy = $this->getPDFProxy($pdfBaseUrl);
179
-
180
-        // finally, generate the PDF
181
-        $command = $binaryPath . $proxy . ' --outline -B 40pt -L 20pt -R 20pt -T 20pt --encoding utf-8 '
182
-            . '--orientation Portrait --disable-javascript --quiet --print-media-type ';
183
-        $retVal = 0;
184
-        $output = array();
185
-        exec(
186
-            $command . " --footer-html \"$footerFile\" \"$bodyFile\" \"$pdfFile\" &> /dev/stdout",
187
-            $output,
188
-            $retVal
189
-        );
190
-
191
-        // remove temporary file
192
-        unlink($bodyFile);
193
-        unlink($footerFile);
194
-
195
-        // output any errors
196
-        if ($retVal != 0) {
197
-            user_error('wkhtmltopdf failed: ' . implode("\n", $output), E_USER_ERROR);
198
-        }
199
-
200
-        // serve the generated file
201
-        return HTTPRequest::send_file(file_get_contents($pdfFile), basename($pdfFile), 'application/pdf');
202
-    }
203
-
204
-    /**
205
-     * Site search form
206
-     */
207
-    public function SearchForm()
208
-    {
209
-        $searchText = $this->getRequest()->getVar('Search');
210
-
211
-        $fields = FieldList::create(
212
-            TextField::create('Search', false, $searchText)
213
-        );
214
-        $actions = FieldList::create(
215
-            FormAction::create('results', _t('SilverStripe\\CMS\\Search\\SearchForm.GO', 'Go'))
216
-        );
217
-
218
-        $form = SearchForm::create($this, SearchForm::class, $fields, $actions);
219
-        $form->setFormAction('search/SearchForm');
220
-
221
-        return $form;
222
-    }
223
-
224
-    /**
225
-     * Get search form with _header suffix
226
-     *
227
-     * @return SearchForm
228
-     */
229
-    public function HeaderSearchForm()
230
-    {
231
-        return $this->SearchForm()->setTemplate('SearchForm_header');
232
-    }
233
-
234
-    /**
235
-     * Process and render search results.
236
-     *
237
-     * @param array $data The raw request data submitted by user
238
-     * @param SearchForm $form The form instance that was submitted
239
-     * @param HTTPRequest $request Request generated for this action
240
-     * @return DBHTMLText
241
-     */
242
-    public function results($data, $form, $request)
243
-    {
244
-        // Check parameters for terms, pagination, and if we should follow suggestions
245
-        $keywords = empty($data['Search']) ? '' : $data['Search'];
246
-        $start = isset($data['start']) ? $data['start'] : 0;
247
-        $suggestions = isset($data['suggestions'])
248
-            ? $data['suggestions']
249
-            : $this->config()->search_follow_suggestions;
250
-
251
-        $results = CwpSearchEngine::create()
252
-            ->search(
253
-                $keywords,
254
-                $this->getClassesToSearch(),
255
-                $this->getSearchIndex(),
256
-                $this->getSearchPageSize(),
257
-                $start,
258
-                $suggestions
259
-            );
260
-
261
-        // Customise content with these results
262
-        $properties = [
263
-            'MetaTitle' => _t(__CLASS__ . '.MetaTitle', 'Search {keywords}', ['keywords' => $keywords]),
264
-            'NoSearchResults' => _t(__CLASS__ . '.NoResult', 'Sorry, your search query did not return any results.'),
265
-            'EmptySearch' => _t(__CLASS__ . '.EmptySearch', 'Search field empty, please enter your search query.'),
266
-            'PdfLink' => '',
267
-            'Title' => _t('SilverStripe\\CMS\\Search\\SearchForm.SearchResults', 'Search Results'),
268
-        ];
269
-        $this->extend('updateSearchResults', $results, $properties);
270
-
271
-        // Customise page
272
-        $response = $this->customise($properties);
273
-        if ($results) {
274
-            $response = $response
275
-                ->customise($results)
276
-                ->customise(array( 'Results' => $results->getResults() ));
277
-        }
278
-
279
-        // Render
280
-        $templates = $this->getResultsTemplate($request);
281
-        return $response->renderWith($templates);
282
-    }
283
-
284
-    /**
285
-     * Select the template to render search results with
286
-     *
287
-     * @param HTTPRequest $request
288
-     * @return array
289
-     */
290
-    protected function getResultsTemplate($request)
291
-    {
292
-        $templates = [Page::class . '_results', Page::class];
293
-        if ($request->getVar('format') == 'rss') {
294
-            array_unshift($templates, 'Page_results_rss');
295
-        }
296
-        if ($request->getVar('format') == 'atom') {
297
-            array_unshift($templates, 'Page_results_atom');
298
-        }
299
-        return $templates;
300
-    }
301
-
302
-    /**
303
-     * Provide scripts as needed by the *default* theme.
304
-     * Override this function if you are using a custom theme based on the *default*.
305
-     *
306
-     * @deprecated 1.6..2.0 Use "starter" theme instead
307
-     */
308
-    public function getBaseScripts()
309
-    {
310
-        $scripts = array();
311
-        $this->extend('updateBaseScripts', $scripts);
312
-        return $scripts;
313
-    }
314
-
315
-    /**
316
-     * Provide stylesheets, as needed by the *default* theme assumed by this recipe.
317
-     * Override this function if you are using a custom theme based on the *default*.
318
-     *
319
-     * @deprecated 1.6..2.0 Use "starter" theme instead
320
-     */
321
-    public function getBaseStyles()
322
-    {
323
-        $styles = array();
324
-        $this->extend('updateBaseStyles', $styles);
325
-        return $styles;
326
-    }
327
-
328
-    /**
329
-     * Provide current year.
330
-     */
331
-    public function CurrentDatetime()
332
-    {
333
-        return DBDatetime::now();
334
-    }
335
-
336
-    public function getRSSLink()
337
-    {
338
-    }
339
-
340
-    /**
341
-     * Get the search index registered for this application
342
-     *
343
-     * @return CwpSearchIndex
344
-     */
345
-    protected function getSearchIndex()
346
-    {
347
-        // Will be a service name in 2.0 and returned via injector
348
-        /** @var CwpSearchIndex $index */
349
-        $index = null;
350
-        if (self::$search_index_class) {
351
-            $index = Injector::inst()->get(self::$search_index_class);
352
-        }
353
-        return $index;
354
-    }
355
-
356
-    /**
357
-     * Gets the list of configured classes to search
358
-     *
359
-     * @return array
360
-     */
361
-    protected function getClassesToSearch()
362
-    {
363
-        // Will be private static config in 2.0
364
-        return self::$classes_to_search;
365
-    }
366
-
367
-    /**
368
-     * Get page size for search
369
-     *
370
-     * @return int
371
-     */
372
-    protected function getSearchPageSize()
373
-    {
374
-        // Will be private static config in 2.0
375
-        return self::$results_per_page;
376
-    }
103
+	public function getPDFProxy($pdfBaseUrl)
104
+	{
105
+		if (!Environment::getEnv('CWP_SECURE_DOMAIN')
106
+			|| $pdfBaseUrl == Environment::getEnv('CWP_SECURE_DOMAIN') . '/'
107
+		) {
108
+			$proxy = '';
109
+		} else {
110
+			$proxy = ' --proxy ' . Environment::getEnv('SS_OUTBOUND_PROXY')
111
+				. ':' . Environment::getEnv('SS_OUTBOUND_PROXY_PORT');
112
+		}
113
+		return $proxy;
114
+	}
115
+
116
+	/**
117
+	 * Render the page as PDF using wkhtmltopdf.
118
+	 */
119
+	public function generatePDF()
120
+	{
121
+		if (!Config::inst()->get(BasePage::class, 'pdf_export')) {
122
+			return false;
123
+		}
124
+
125
+		$binaryPath = Config::inst()->get(BasePage::class, 'wkhtmltopdf_binary');
126
+		if (!$binaryPath || !is_executable($binaryPath)) {
127
+			if (Environment::getEnv('WKHTMLTOPDF_BINARY')
128
+				&& is_executable(Environment::getEnv('WKHTMLTOPDF_BINARY'))
129
+			) {
130
+				$binaryPath = Environment::getEnv('WKHTMLTOPDF_BINARY');
131
+			}
132
+		}
133
+
134
+		if (!$binaryPath) {
135
+			user_error('Neither WKHTMLTOPDF_BINARY nor BasePage.wkhtmltopdf_binary are defined', E_USER_ERROR);
136
+		}
137
+
138
+		if (Versioned::get_reading_mode() == 'Stage.Stage') {
139
+			user_error('Generating PDFs on draft is not supported', E_USER_ERROR);
140
+		}
141
+
142
+		set_time_limit(60);
143
+
144
+		// prepare the paths
145
+		$pdfFile = $this->dataRecord->getPdfFilename();
146
+		$bodyFile = str_replace('.pdf', '_pdf.html', $pdfFile);
147
+		$footerFile = str_replace('.pdf', '_pdffooter.html', $pdfFile);
148
+
149
+		// make sure the work directory exists
150
+		if (!file_exists(dirname($pdfFile))) {
151
+			Filesystem::makeFolder(dirname($pdfFile));
152
+		}
153
+
154
+		//decide the domain to use in generation
155
+		$pdfBaseUrl = $this->getPDFBaseURL();
156
+
157
+		// Force http protocol on CWP - fetching from localhost without using the proxy, SSL terminates on gateway.
158
+		if (Environment::getEnv('CWP_ENVIRONMENT')) {
159
+			Config::modify()->set(Director::class, 'alternate_protocol', 'http');
160
+			//only set alternate protocol if CWP_SECURE_DOMAIN is defined OR pdf_base_url is
161
+			if ($pdfBaseUrl) {
162
+				Config::modify()->set(Director::class, 'alternate_base_url', 'http://' . $pdfBaseUrl);
163
+			}
164
+		}
165
+
166
+		$bodyViewer = $this->getViewer('pdf');
167
+
168
+		// write the output of this page to HTML, ready for conversion to PDF
169
+		file_put_contents($bodyFile, $bodyViewer->process($this));
170
+
171
+		// get the viewer for the current template with _pdffooter
172
+		$footerViewer = $this->getViewer('pdffooter');
173
+
174
+		// write the output of the footer template to HTML, ready for conversion to PDF
175
+		file_put_contents($footerFile, $footerViewer->process($this));
176
+
177
+		//decide what the proxy should look like
178
+		$proxy = $this->getPDFProxy($pdfBaseUrl);
179
+
180
+		// finally, generate the PDF
181
+		$command = $binaryPath . $proxy . ' --outline -B 40pt -L 20pt -R 20pt -T 20pt --encoding utf-8 '
182
+			. '--orientation Portrait --disable-javascript --quiet --print-media-type ';
183
+		$retVal = 0;
184
+		$output = array();
185
+		exec(
186
+			$command . " --footer-html \"$footerFile\" \"$bodyFile\" \"$pdfFile\" &> /dev/stdout",
187
+			$output,
188
+			$retVal
189
+		);
190
+
191
+		// remove temporary file
192
+		unlink($bodyFile);
193
+		unlink($footerFile);
194
+
195
+		// output any errors
196
+		if ($retVal != 0) {
197
+			user_error('wkhtmltopdf failed: ' . implode("\n", $output), E_USER_ERROR);
198
+		}
199
+
200
+		// serve the generated file
201
+		return HTTPRequest::send_file(file_get_contents($pdfFile), basename($pdfFile), 'application/pdf');
202
+	}
203
+
204
+	/**
205
+	 * Site search form
206
+	 */
207
+	public function SearchForm()
208
+	{
209
+		$searchText = $this->getRequest()->getVar('Search');
210
+
211
+		$fields = FieldList::create(
212
+			TextField::create('Search', false, $searchText)
213
+		);
214
+		$actions = FieldList::create(
215
+			FormAction::create('results', _t('SilverStripe\\CMS\\Search\\SearchForm.GO', 'Go'))
216
+		);
217
+
218
+		$form = SearchForm::create($this, SearchForm::class, $fields, $actions);
219
+		$form->setFormAction('search/SearchForm');
220
+
221
+		return $form;
222
+	}
223
+
224
+	/**
225
+	 * Get search form with _header suffix
226
+	 *
227
+	 * @return SearchForm
228
+	 */
229
+	public function HeaderSearchForm()
230
+	{
231
+		return $this->SearchForm()->setTemplate('SearchForm_header');
232
+	}
233
+
234
+	/**
235
+	 * Process and render search results.
236
+	 *
237
+	 * @param array $data The raw request data submitted by user
238
+	 * @param SearchForm $form The form instance that was submitted
239
+	 * @param HTTPRequest $request Request generated for this action
240
+	 * @return DBHTMLText
241
+	 */
242
+	public function results($data, $form, $request)
243
+	{
244
+		// Check parameters for terms, pagination, and if we should follow suggestions
245
+		$keywords = empty($data['Search']) ? '' : $data['Search'];
246
+		$start = isset($data['start']) ? $data['start'] : 0;
247
+		$suggestions = isset($data['suggestions'])
248
+			? $data['suggestions']
249
+			: $this->config()->search_follow_suggestions;
250
+
251
+		$results = CwpSearchEngine::create()
252
+			->search(
253
+				$keywords,
254
+				$this->getClassesToSearch(),
255
+				$this->getSearchIndex(),
256
+				$this->getSearchPageSize(),
257
+				$start,
258
+				$suggestions
259
+			);
260
+
261
+		// Customise content with these results
262
+		$properties = [
263
+			'MetaTitle' => _t(__CLASS__ . '.MetaTitle', 'Search {keywords}', ['keywords' => $keywords]),
264
+			'NoSearchResults' => _t(__CLASS__ . '.NoResult', 'Sorry, your search query did not return any results.'),
265
+			'EmptySearch' => _t(__CLASS__ . '.EmptySearch', 'Search field empty, please enter your search query.'),
266
+			'PdfLink' => '',
267
+			'Title' => _t('SilverStripe\\CMS\\Search\\SearchForm.SearchResults', 'Search Results'),
268
+		];
269
+		$this->extend('updateSearchResults', $results, $properties);
270
+
271
+		// Customise page
272
+		$response = $this->customise($properties);
273
+		if ($results) {
274
+			$response = $response
275
+				->customise($results)
276
+				->customise(array( 'Results' => $results->getResults() ));
277
+		}
278
+
279
+		// Render
280
+		$templates = $this->getResultsTemplate($request);
281
+		return $response->renderWith($templates);
282
+	}
283
+
284
+	/**
285
+	 * Select the template to render search results with
286
+	 *
287
+	 * @param HTTPRequest $request
288
+	 * @return array
289
+	 */
290
+	protected function getResultsTemplate($request)
291
+	{
292
+		$templates = [Page::class . '_results', Page::class];
293
+		if ($request->getVar('format') == 'rss') {
294
+			array_unshift($templates, 'Page_results_rss');
295
+		}
296
+		if ($request->getVar('format') == 'atom') {
297
+			array_unshift($templates, 'Page_results_atom');
298
+		}
299
+		return $templates;
300
+	}
301
+
302
+	/**
303
+	 * Provide scripts as needed by the *default* theme.
304
+	 * Override this function if you are using a custom theme based on the *default*.
305
+	 *
306
+	 * @deprecated 1.6..2.0 Use "starter" theme instead
307
+	 */
308
+	public function getBaseScripts()
309
+	{
310
+		$scripts = array();
311
+		$this->extend('updateBaseScripts', $scripts);
312
+		return $scripts;
313
+	}
314
+
315
+	/**
316
+	 * Provide stylesheets, as needed by the *default* theme assumed by this recipe.
317
+	 * Override this function if you are using a custom theme based on the *default*.
318
+	 *
319
+	 * @deprecated 1.6..2.0 Use "starter" theme instead
320
+	 */
321
+	public function getBaseStyles()
322
+	{
323
+		$styles = array();
324
+		$this->extend('updateBaseStyles', $styles);
325
+		return $styles;
326
+	}
327
+
328
+	/**
329
+	 * Provide current year.
330
+	 */
331
+	public function CurrentDatetime()
332
+	{
333
+		return DBDatetime::now();
334
+	}
335
+
336
+	public function getRSSLink()
337
+	{
338
+	}
339
+
340
+	/**
341
+	 * Get the search index registered for this application
342
+	 *
343
+	 * @return CwpSearchIndex
344
+	 */
345
+	protected function getSearchIndex()
346
+	{
347
+		// Will be a service name in 2.0 and returned via injector
348
+		/** @var CwpSearchIndex $index */
349
+		$index = null;
350
+		if (self::$search_index_class) {
351
+			$index = Injector::inst()->get(self::$search_index_class);
352
+		}
353
+		return $index;
354
+	}
355
+
356
+	/**
357
+	 * Gets the list of configured classes to search
358
+	 *
359
+	 * @return array
360
+	 */
361
+	protected function getClassesToSearch()
362
+	{
363
+		// Will be private static config in 2.0
364
+		return self::$classes_to_search;
365
+	}
366
+
367
+	/**
368
+	 * Get page size for search
369
+	 *
370
+	 * @return int
371
+	 */
372
+	protected function getSearchPageSize()
373
+	{
374
+		// Will be private static config in 2.0
375
+		return self::$results_per_page;
376
+	}
377 377
 }
Please login to merge, or discard this patch.