-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathMaintenanceMode.module
More file actions
282 lines (255 loc) · 12.6 KB
/
MaintenanceMode.module
File metadata and controls
282 lines (255 loc) · 12.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
<?php
class MaintenanceMode extends WireData implements Module, ConfigurableModule
{
/**
* Basic information about module
*/
public static function getModuleInfo()
{
return array(
'title' => 'Maintenance Mode',
'summary' => 'Allows you to put your site into maintenance mode so that users who are not logged in are taken to the login screen and a message is displayed accordingly.',
'href' => 'https://processwire.com/talk/topic/382-module-maintenance-mode/',
'version' => 111,
'permanent' => false,
'autoload' => true,
'singular' => true,
);
}
/**
* Default configuration for module
*
* This is based on Ryan's examples [used also in @apeisa's AdminBar, for instance]
*/
static public function getDefaultData()
{
return array(
'inMaintenance' => 0,
'showPage' => 0,
'showURL' => '',
'bypassRoles' => '',
'allowPages' => 0,
'showFrontendNotice' => 1
);
}
/**
* Populate the default config data
*
*/
public function __construct()
{
foreach (self::getDefaultData() as $key => $value) {
$this->$key = $value;
}
}
/**
* Initialize the module and setup hooks
*/
public function init()
{
// hook before the page has been loaded to see if we're in maintenance mode and redirect if neccessary
$this->addHookBefore('Page::render', $this, 'maintenanceCheck');
$this->addHookAfter('Page::render', $this, 'maintenanceMessage');
}
/**
* Ready hook to show admin notices
*/
public function ready()
{
$user = $this->fuel('user');
$page = $this->fuel('page');
if ($user->isLoggedin() && $user->isSuperuser() && $page->template == 'admin' && !$this->config->ajax && !$this->input->requestMethod('POST')) {
// Show persistent admin notice for maintenance mode
if ($this->inMaintenance) {
// Remove any leftover maintenance warnings from session to prevent duplicates
foreach ($this->wire('notices') as $notice) {
if ($notice instanceof NoticeWarning && $notice->class === $this->className()) {
$this->wire('notices')->remove($notice);
}
}
$warning = __("Site is currently in maintenance mode");
if ($this->modules->isInstalled('ProCache')) {
$procache = $this->modules->get('ProCache');
if ($procache && $procache->cacheOn) {
$warning .= '. ' . __("**Warning:** ProCache is enabled - cached pages may still be served to visitors during maintenance mode");
}
}
$this->warning($warning, Notice::allowMarkdown);
}
}
}
static public function getModuleConfigInputfields(array $data)
{
// this is a container for fields, basically like a fieldset
$fields = new InputfieldWrapper();
// since this is a static function, we can't use $this->modules, so get them from the global wire() function
$modules = wire('modules');
// Populate $data with the default config, because if they've never configured this module before,
// the $data provided to this function will be empty. Or, if you add new config items in a new version,
// $data won't have it until they configure it. Best bet is to merge defaults with custom, where
// custom overwrites the defaults (array_merge).
$data = array_merge(self::getDefaultData(), $data);
// Populate the $fieldsModel with data for each checkbox
$fieldsModel = array(
'inMaintenance' => array(
'label' => "Put site into maintenance mode?",
'desc' => "Will redirect any visitors who are not logged in to your site to the login page with an appropriate message.",
'type' => "_createCheckbox"),
'bypassRoles' => array(
'label' => "Allow specific roles to bypass maintenance mode",
'desc' => "Optionally allow certain user roles eg. site editors/staff to see the side whilst in maintenance mode (superuser will always be allowed regardless of this setting)",
'type' => "_createInputfieldASMSelect"),
'showPage' => array(
'label' => "Redirect to another page instead of the login page?",
'desc' => "Alternatively shows a specific page instead of the login page - for added security.",
'type' => "_createInputfieldPageListSelect"),
'showURL' => array(
'label' => "Redirect to another URL?",
'desc' => "Allows you to send visitors who are not logged in to another URL including other sites.",
'type' => "_createInputfieldURL"),
'allowPages' => array(
'label' => "Allowed Pages",
'desc' => "These pages will always be accessible in maintenance mode",
'type' => "_createInputfieldPageListSelectMultiple"),
'showFrontendNotice' => array(
'label' => "Show frontend maintenance notice?",
'desc' => "Display a maintenance mode notice on the frontend for logged-in superusers",
'type' => "_createCheckbox")
);
// Now use $data and $fieldsModel loop to create all checkboxes
foreach ($fieldsModel as $f => $fM) {
$fields->add(
call_user_func(array(static::class, $fM['type']), $f, $fM['label'], $data[$f], $fM['desc'])
);
}
return $fields;
}
/**
* Checks if we're in maintenance mode and performs any neccessary redirects
*
* @param HookEvent $event
*/
public function maintenanceCheck(HookEvent $event)
{
$page = $event->object;
$user = $this->fuel('user');
// If we're in maintenance mode
if ($this->inMaintenance) {
// Check to make sure we're not a superuser and our role isn't in the list of allowed roles to access the site in maintenance mode
if (!$user->isSuperuser() && !array_intersect(explode('|', $user->roles), $this->bypassRoles)) {
$this->message("This site is currently in maintenance mode. If you are a site administrator, you may log in below and view the site as normal.");
// Redirect only if current page is not in array of allowed pages
if (!in_array($page->id, $this->allowPages)) {
// If we have a different URL to redirect to then do a temp. redirect to that URL...
if ($this->showURL && ($page->name != 'login')) {
$this->session->redirect($this->showURL, false);
// If we have a specific page to redirect to then do it
} elseif ($this->showPage && ($page->id != $this->showPage) && ($page->name != 'login')) {
$this->session->redirect($this->fuel('pages')->get($this->showPage)->url, false);
// Else redirect to the login page
} elseif (!$this->showPage && $page->name != 'login') {
$this->session->redirect($this->config->urls->admin, false);
}
}
}
// Else if we're not in maintenance mode and we're not an administrator, make sure the maintenance page redirects to the homepage
} elseif (!$this->inMaintenance && $this->showPage && ($page->id == $this->showPage) && !$user->isSuperuser()) {
$this->session->redirect($this->config->urls->root, false);
}
}
public function maintenanceMessage(HookEvent $event)
{
if ($this->inMaintenance && $this->showFrontendNotice) {
$user = $this->fuel('user');
if ($user->isLoggedin() && $user->isSuperuser()) {
$page = $event->object;
// Show notice on frontend if enabled
if ($page->template != 'admin') {
$out = $event->return;
// Check to see if the edit link is visible (it is in the default template at least when viewing pages in the front-end). If so, move message to the right of it.
$indent = strpos($out, 'editpage') !== false ? '60px;' : '0';
$code = "<div style='font-family: Arial; font-size: 12px; padding: 5px 6px; line-height: 14px; margin-left: {$indent}; background-color: #87A71B; color: #fff; z-index:99999; position: fixed; text-align: center;'>Site is in maintenance mode</div>";
$out = preg_replace('/(<body[^>]*>)/i', '$1' . $code, $out);
$event->return = $out;
}
}
}
}
/**
* @param string $chName – name of the field this ties to
* @param string $chTitle – title of the field
* @param boolean $chChecked – is the checkbox checked? (default: true)
* @param string $chDesc – description (KISS) (default: empty)
* @return InputfieldCheckbox – created checkbox
*/
private static function _createCheckbox($chName, $chTitle, $chChecked = true, $chDesc = '')
{
$field = wire('modules')->get("InputfieldCheckbox");
$field->name = $chName;
$field->label = $chTitle;
$field->description = $chDesc;
$field->value = 1;
$field->attr('checked', $chChecked ? 'checked' : '');
return $field;
}
/**
* @param string $ipName – name of the field this ties to
* @param string $ipTitle – title of the field
* @param boolean $ipValue – the value of the field (default: empty, i.e. no page selected)
* @param string $ipDesc – description (KISS) (default: empty)
* @return InputfieldPageListSelect – created page list select
*/
private static function _createInputfieldPageListSelect($ipName, $ipTitle, $ipValue = '', $ipDesc = '')
{
$field = wire('modules')->get("InputfieldPageListSelect");
$field->name = $ipName;
$field->label = $ipTitle;
$field->required = false;
$field->description = $ipDesc;
$field->attr('value', $ipValue);
$field->set('unselectLabel', 'Unselect');
if ($ipValue == 0) $field->collapsed = Inputfield::collapsedYes;
return $field;
}
private static function _createInputfieldURL($name, $title, $value = '', $desc = '')
{
$field = wire('modules')->get("InputfieldURL");
$field->name = $name;
$field->label = $title;
$field->required = false;
$field->attr('value', $value);
$field->description = $desc;
$field->notes = "Example: http://another.place.com/index.html";
if (!(int)ini_get('allow_url_fopen')) $field->error("Your PHP doesn't have 'allow_url_fopen' enabled, so the redirect to external URL option won't work.");
if ('' === $value) $field->collapsed = Inputfield::collapsedYes;
return $field;
}
private static function _createInputfieldASMSelect($aName, $aTitle, $aValue, $aDesc = '', $aOptions = '', $aNotes = '', $aWidth = 100)
{
if (!isset($aValue) || !is_array($aValue)) $aValue = '';
$modules = Wire::getFuel('modules');
$field = $modules->get("InputfieldAsmSelect");
$field->attr('name', $aName);
foreach (wire('roles') as $role) {
$field->addOption($role->id, $role->name);
}
$field->attr('value', $aValue);
$field->label = $aTitle;
$field->description = $aDesc;
$field->columnWidth = $aWidth;
if (empty($aValue)) $field->collapsed = Inputfield::collapsedYes;
return $field;
}
private static function _createInputfieldPageListSelectMultiple($ipName, $ipTitle, $ipValue = '', $ipDesc = '')
{
$field = wire('modules')->get("InputfieldPageListSelectMultiple");
$field->name = $ipName;
$field->label = $ipTitle;
$field->required = false;
$field->description = $ipDesc;
$field->attr('value', $ipValue);
$field->set('unselectLabel', 'Unselect');
if ($ipValue == 0) $field->collapsed = Inputfield::collapsedYes;
return $field;
}
}