Compare commits
43
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bf32cbaee8 | ||
|
|
916911e1d6 | ||
|
|
168e1009e8 | ||
|
|
b4c613c9a4 | ||
|
|
1eb3163ad6 | ||
|
|
b6dfcd4485 | ||
|
|
c0837f799e | ||
|
|
9e64c092d4 | ||
|
|
c9b30d9046 | ||
|
|
9cf2dd32d8 | ||
|
|
7a02d86270 | ||
|
|
61261ea35b | ||
|
|
265670ec89 | ||
|
|
13e1af6f8e | ||
|
|
03a6d00061 | ||
|
|
8b0a0ea705 | ||
|
|
bd68707e61 | ||
|
|
e2b0c1c59a | ||
|
|
d3eea03e7d | ||
|
|
225e5c5929 | ||
|
|
79b253c350 | ||
|
|
b1ebaf63c0 | ||
|
|
32d2c3709a | ||
|
|
4659728d34 | ||
|
|
aa55ae2e35 | ||
|
|
551ff35344 | ||
|
|
4e1a5c59b5 | ||
|
|
780a55fb00 | ||
|
|
7cbdba45da | ||
|
|
aebcee71b1 | ||
|
|
28b23dcfbc | ||
|
|
50f0d72e62 | ||
|
|
956d8fb1ec | ||
|
|
781d3d5230 | ||
|
|
b7229d0c02 | ||
|
|
6a09dbd486 | ||
|
|
fff698433f | ||
|
|
2004adee70 | ||
|
|
761659ddf0 | ||
|
|
6f7463ad93 | ||
|
|
3e43f73411 | ||
|
|
cfaa928600 | ||
|
|
b98a63475e |
Generated
+23
-22
@@ -124,16 +124,16 @@
|
||||
},
|
||||
{
|
||||
"name": "chi-teck/drupal-code-generator",
|
||||
"version": "1.23.2",
|
||||
"version": "1.24.0",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/Chi-teck/drupal-code-generator.git",
|
||||
"reference": "b157b38c8c148c67d5b80c7c349b1a446115ea0e"
|
||||
"reference": "20682ec4acc92e9671ba7b9bd0e972978c3a08f2"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/Chi-teck/drupal-code-generator/zipball/b157b38c8c148c67d5b80c7c349b1a446115ea0e",
|
||||
"reference": "b157b38c8c148c67d5b80c7c349b1a446115ea0e",
|
||||
"url": "https://api.github.com/repos/Chi-teck/drupal-code-generator/zipball/20682ec4acc92e9671ba7b9bd0e972978c3a08f2",
|
||||
"reference": "20682ec4acc92e9671ba7b9bd0e972978c3a08f2",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
@@ -159,7 +159,7 @@
|
||||
"GPL-2.0-or-later"
|
||||
],
|
||||
"description": "Drupal code generator",
|
||||
"time": "2018-03-03T04:17:26+00:00"
|
||||
"time": "2018-04-25T17:35:50+00:00"
|
||||
},
|
||||
{
|
||||
"name": "composer/installers",
|
||||
@@ -1524,16 +1524,16 @@
|
||||
},
|
||||
{
|
||||
"name": "drupal/core",
|
||||
"version": "8.5.2",
|
||||
"version": "8.5.3",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/drupal/core.git",
|
||||
"reference": "bc21760d4be4ad117851809183c8d18880ab275a"
|
||||
"reference": "b012f0ae51504880e920f2c6efdbdf03b6fe2129"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/drupal/core/zipball/bc21760d4be4ad117851809183c8d18880ab275a",
|
||||
"reference": "bc21760d4be4ad117851809183c8d18880ab275a",
|
||||
"url": "https://api.github.com/repos/drupal/core/zipball/b012f0ae51504880e920f2c6efdbdf03b6fe2129",
|
||||
"reference": "b012f0ae51504880e920f2c6efdbdf03b6fe2129",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
@@ -1755,7 +1755,7 @@
|
||||
"GPL-2.0-or-later"
|
||||
],
|
||||
"description": "Drupal is an open source content management platform powering millions of websites and applications.",
|
||||
"time": "2018-04-18T17:00:56+00:00"
|
||||
"time": "2018-04-25T15:39:01+00:00"
|
||||
},
|
||||
{
|
||||
"name": "drush/drush",
|
||||
@@ -4727,30 +4727,30 @@
|
||||
},
|
||||
{
|
||||
"name": "zendframework/zend-escaper",
|
||||
"version": "2.5.2",
|
||||
"version": "2.6.0",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/zendframework/zend-escaper.git",
|
||||
"reference": "2dcd14b61a72d8b8e27d579c6344e12c26141d4e"
|
||||
"reference": "31d8aafae982f9568287cb4dce987e6aff8fd074"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/zendframework/zend-escaper/zipball/2dcd14b61a72d8b8e27d579c6344e12c26141d4e",
|
||||
"reference": "2dcd14b61a72d8b8e27d579c6344e12c26141d4e",
|
||||
"url": "https://api.github.com/repos/zendframework/zend-escaper/zipball/31d8aafae982f9568287cb4dce987e6aff8fd074",
|
||||
"reference": "31d8aafae982f9568287cb4dce987e6aff8fd074",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
"php": ">=5.5"
|
||||
"php": "^5.6 || ^7.0"
|
||||
},
|
||||
"require-dev": {
|
||||
"fabpot/php-cs-fixer": "1.7.*",
|
||||
"phpunit/phpunit": "~4.0"
|
||||
"phpunit/phpunit": "^5.7.27 || ^6.5.8 || ^7.1.2",
|
||||
"zendframework/zend-coding-standard": "~1.0.0"
|
||||
},
|
||||
"type": "library",
|
||||
"extra": {
|
||||
"branch-alias": {
|
||||
"dev-master": "2.5-dev",
|
||||
"dev-develop": "2.6-dev"
|
||||
"dev-master": "2.6.x-dev",
|
||||
"dev-develop": "2.7.x-dev"
|
||||
}
|
||||
},
|
||||
"autoload": {
|
||||
@@ -4762,12 +4762,13 @@
|
||||
"license": [
|
||||
"BSD-3-Clause"
|
||||
],
|
||||
"homepage": "https://github.com/zendframework/zend-escaper",
|
||||
"description": "Securely and safely escape HTML, HTML attributes, JavaScript, CSS, and URLs",
|
||||
"keywords": [
|
||||
"ZendFramework",
|
||||
"escaper",
|
||||
"zf2"
|
||||
"zf"
|
||||
],
|
||||
"time": "2016-06-30T19:48:38+00:00"
|
||||
"time": "2018-04-25T15:48:53+00:00"
|
||||
},
|
||||
{
|
||||
"name": "zendframework/zend-feed",
|
||||
|
||||
+1
-1
@@ -82,7 +82,7 @@ class Drupal {
|
||||
/**
|
||||
* The current system version.
|
||||
*/
|
||||
const VERSION = '8.5.2';
|
||||
const VERSION = '8.5.3';
|
||||
|
||||
/**
|
||||
* Core API compatibility.
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
namespace Drupal\Core\Security;
|
||||
|
||||
use Drupal\Component\Utility\UrlHelper;
|
||||
use Symfony\Component\HttpFoundation\ParameterBag;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
|
||||
/**
|
||||
@@ -39,28 +41,18 @@ class RequestSanitizer {
|
||||
*/
|
||||
public static function sanitize(Request $request, $whitelist, $log_sanitized_keys = FALSE) {
|
||||
if (!$request->attributes->get(self::SANITIZED, FALSE)) {
|
||||
// Process query string parameters.
|
||||
$get_sanitized_keys = [];
|
||||
$request->query->replace(static::stripDangerousValues($request->query->all(), $whitelist, $get_sanitized_keys));
|
||||
if ($log_sanitized_keys && !empty($get_sanitized_keys)) {
|
||||
trigger_error(sprintf('Potentially unsafe keys removed from query string parameters (GET): %s', implode(', ', $get_sanitized_keys)));
|
||||
$update_globals = FALSE;
|
||||
$bags = [
|
||||
'query' => 'Potentially unsafe keys removed from query string parameters (GET): %s',
|
||||
'request' => 'Potentially unsafe keys removed from request body parameters (POST): %s',
|
||||
'cookies' => 'Potentially unsafe keys removed from cookie parameters: %s',
|
||||
];
|
||||
foreach ($bags as $bag => $message) {
|
||||
if (static::processParameterBag($request->$bag, $whitelist, $log_sanitized_keys, $bag, $message)) {
|
||||
$update_globals = TRUE;
|
||||
}
|
||||
}
|
||||
|
||||
// Request body parameters.
|
||||
$post_sanitized_keys = [];
|
||||
$request->request->replace(static::stripDangerousValues($request->request->all(), $whitelist, $post_sanitized_keys));
|
||||
if ($log_sanitized_keys && !empty($post_sanitized_keys)) {
|
||||
trigger_error(sprintf('Potentially unsafe keys removed from request body parameters (POST): %s', implode(', ', $post_sanitized_keys)));
|
||||
}
|
||||
|
||||
// Cookie parameters.
|
||||
$cookie_sanitized_keys = [];
|
||||
$request->cookies->replace(static::stripDangerousValues($request->cookies->all(), $whitelist, $cookie_sanitized_keys));
|
||||
if ($log_sanitized_keys && !empty($cookie_sanitized_keys)) {
|
||||
trigger_error(sprintf('Potentially unsafe keys removed from cookie parameters: %s', implode(', ', $cookie_sanitized_keys)));
|
||||
}
|
||||
|
||||
if (!empty($get_sanitized_keys) || !empty($post_sanitized_keys) || !empty($cookie_sanitized_keys)) {
|
||||
if ($update_globals) {
|
||||
$request->overrideGlobals();
|
||||
}
|
||||
$request->attributes->set(self::SANITIZED, TRUE);
|
||||
@@ -68,6 +60,72 @@ class RequestSanitizer {
|
||||
return $request;
|
||||
}
|
||||
|
||||
/**
|
||||
* Processes a request parameter bag.
|
||||
*
|
||||
* @param \Symfony\Component\HttpFoundation\ParameterBag $bag
|
||||
* The parameter bag to process.
|
||||
* @param string[] $whitelist
|
||||
* An array of keys to whitelist as safe.
|
||||
* @param bool $log_sanitized_keys
|
||||
* Set to TRUE to log keys that are sanitized.
|
||||
* @param string $bag_name
|
||||
* The request parameter bag name. Either 'query', 'request' or 'cookies'.
|
||||
* @param string $message
|
||||
* The message to log if the parameter bag contains keys that are removed.
|
||||
* If the message contains %s that is replaced by a list of removed keys.
|
||||
*
|
||||
* @return bool
|
||||
* TRUE if the parameter bag has been sanitized, FALSE if not.
|
||||
*/
|
||||
protected static function processParameterBag(ParameterBag $bag, $whitelist, $log_sanitized_keys, $bag_name, $message) {
|
||||
$sanitized = FALSE;
|
||||
$sanitized_keys = [];
|
||||
$bag->replace(static::stripDangerousValues($bag->all(), $whitelist, $sanitized_keys));
|
||||
if (!empty($sanitized_keys)) {
|
||||
$sanitized = TRUE;
|
||||
if ($log_sanitized_keys) {
|
||||
trigger_error(sprintf($message, implode(', ', $sanitized_keys)));
|
||||
}
|
||||
}
|
||||
|
||||
if ($bag->has('destination')) {
|
||||
$destination_dangerous_keys = static::checkDestination($bag->get('destination'), $whitelist);
|
||||
if (!empty($destination_dangerous_keys)) {
|
||||
// The destination is removed rather than sanitized because the URL
|
||||
// generator service is not available and this method is called very
|
||||
// early in the bootstrap.
|
||||
$bag->remove('destination');
|
||||
$sanitized = TRUE;
|
||||
if ($log_sanitized_keys) {
|
||||
trigger_error(sprintf('Potentially unsafe destination removed from %s parameter bag because it contained the following keys: %s', $bag_name, implode(', ', $destination_dangerous_keys)));
|
||||
}
|
||||
}
|
||||
}
|
||||
return $sanitized;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks a destination string to see if it is dangerous.
|
||||
*
|
||||
* @param string $destination
|
||||
* The destination string to check.
|
||||
* @param array $whitelist
|
||||
* An array of keys to whitelist as safe.
|
||||
*
|
||||
* @return array
|
||||
* The dangerous keys found in the destination parameter.
|
||||
*/
|
||||
protected static function checkDestination($destination, array $whitelist) {
|
||||
$dangerous_keys = [];
|
||||
$parts = UrlHelper::parse($destination);
|
||||
// If there is a query string, check its query parameters.
|
||||
if (!empty($parts['query'])) {
|
||||
static::stripDangerousValues($parts['query'], $whitelist, $dangerous_keys);
|
||||
}
|
||||
return $dangerous_keys;
|
||||
}
|
||||
|
||||
/**
|
||||
* Strips dangerous keys from $input.
|
||||
*
|
||||
|
||||
@@ -8,6 +8,7 @@ use Drupal\Component\Utility\NestedArray;
|
||||
use Drupal\Core\Ajax\AjaxResponse;
|
||||
use Drupal\Core\Ajax\ReplaceCommand;
|
||||
use Drupal\Core\Form\FormStateInterface;
|
||||
use Drupal\Core\Render\Element;
|
||||
use Drupal\Core\Render\Element\FormElement;
|
||||
use Drupal\Core\Site\Settings;
|
||||
use Drupal\Core\Url;
|
||||
@@ -175,6 +176,9 @@ class ManagedFile extends FormElement {
|
||||
|
||||
$form_parents = explode('/', $request->query->get('element_parents'));
|
||||
|
||||
// Sanitize form parents before using them.
|
||||
$form_parents = array_filter($form_parents, [Element::class, 'child']);
|
||||
|
||||
// Retrieve the element to be rendered.
|
||||
$form = NestedArray::getValue($form, $form_parents);
|
||||
|
||||
|
||||
@@ -0,0 +1,339 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 2, June 1991
|
||||
|
||||
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
|
||||
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The licenses for most software are designed to take away your
|
||||
freedom to share and change it. By contrast, the GNU General Public
|
||||
License is intended to guarantee your freedom to share and change free
|
||||
software--to make sure the software is free for all its users. This
|
||||
General Public License applies to most of the Free Software
|
||||
Foundation's software and to any other program whose authors commit to
|
||||
using it. (Some other Free Software Foundation software is covered by
|
||||
the GNU Lesser General Public License instead.) You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
this service if you wish), that you receive source code or can get it
|
||||
if you want it, that you can change the software or use pieces of it
|
||||
in new free programs; and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to make restrictions that forbid
|
||||
anyone to deny you these rights or to ask you to surrender the rights.
|
||||
These restrictions translate to certain responsibilities for you if you
|
||||
distribute copies of the software, or if you modify it.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must give the recipients all the rights that
|
||||
you have. You must make sure that they, too, receive or can get the
|
||||
source code. And you must show them these terms so they know their
|
||||
rights.
|
||||
|
||||
We protect your rights with two steps: (1) copyright the software, and
|
||||
(2) offer you this license which gives you legal permission to copy,
|
||||
distribute and/or modify the software.
|
||||
|
||||
Also, for each author's protection and ours, we want to make certain
|
||||
that everyone understands that there is no warranty for this free
|
||||
software. If the software is modified by someone else and passed on, we
|
||||
want its recipients to know that what they have is not the original, so
|
||||
that any problems introduced by others will not reflect on the original
|
||||
authors' reputations.
|
||||
|
||||
Finally, any free program is threatened constantly by software
|
||||
patents. We wish to avoid the danger that redistributors of a free
|
||||
program will individually obtain patent licenses, in effect making the
|
||||
program proprietary. To prevent this, we have made it clear that any
|
||||
patent must be licensed for everyone's free use or not licensed at all.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
|
||||
|
||||
0. This License applies to any program or other work which contains
|
||||
a notice placed by the copyright holder saying it may be distributed
|
||||
under the terms of this General Public License. The "Program", below,
|
||||
refers to any such program or work, and a "work based on the Program"
|
||||
means either the Program or any derivative work under copyright law:
|
||||
that is to say, a work containing the Program or a portion of it,
|
||||
either verbatim or with modifications and/or translated into another
|
||||
language. (Hereinafter, translation is included without limitation in
|
||||
the term "modification".) Each licensee is addressed as "you".
|
||||
|
||||
Activities other than copying, distribution and modification are not
|
||||
covered by this License; they are outside its scope. The act of
|
||||
running the Program is not restricted, and the output from the Program
|
||||
is covered only if its contents constitute a work based on the
|
||||
Program (independent of having been made by running the Program).
|
||||
Whether that is true depends on what the Program does.
|
||||
|
||||
1. You may copy and distribute verbatim copies of the Program's
|
||||
source code as you receive it, in any medium, provided that you
|
||||
conspicuously and appropriately publish on each copy an appropriate
|
||||
copyright notice and disclaimer of warranty; keep intact all the
|
||||
notices that refer to this License and to the absence of any warranty;
|
||||
and give any other recipients of the Program a copy of this License
|
||||
along with the Program.
|
||||
|
||||
You may charge a fee for the physical act of transferring a copy, and
|
||||
you may at your option offer warranty protection in exchange for a fee.
|
||||
|
||||
2. You may modify your copy or copies of the Program or any portion
|
||||
of it, thus forming a work based on the Program, and copy and
|
||||
distribute such modifications or work under the terms of Section 1
|
||||
above, provided that you also meet all of these conditions:
|
||||
|
||||
a) You must cause the modified files to carry prominent notices
|
||||
stating that you changed the files and the date of any change.
|
||||
|
||||
b) You must cause any work that you distribute or publish, that in
|
||||
whole or in part contains or is derived from the Program or any
|
||||
part thereof, to be licensed as a whole at no charge to all third
|
||||
parties under the terms of this License.
|
||||
|
||||
c) If the modified program normally reads commands interactively
|
||||
when run, you must cause it, when started running for such
|
||||
interactive use in the most ordinary way, to print or display an
|
||||
announcement including an appropriate copyright notice and a
|
||||
notice that there is no warranty (or else, saying that you provide
|
||||
a warranty) and that users may redistribute the program under
|
||||
these conditions, and telling the user how to view a copy of this
|
||||
License. (Exception: if the Program itself is interactive but
|
||||
does not normally print such an announcement, your work based on
|
||||
the Program is not required to print an announcement.)
|
||||
|
||||
These requirements apply to the modified work as a whole. If
|
||||
identifiable sections of that work are not derived from the Program,
|
||||
and can be reasonably considered independent and separate works in
|
||||
themselves, then this License, and its terms, do not apply to those
|
||||
sections when you distribute them as separate works. But when you
|
||||
distribute the same sections as part of a whole which is a work based
|
||||
on the Program, the distribution of the whole must be on the terms of
|
||||
this License, whose permissions for other licensees extend to the
|
||||
entire whole, and thus to each and every part regardless of who wrote it.
|
||||
|
||||
Thus, it is not the intent of this section to claim rights or contest
|
||||
your rights to work written entirely by you; rather, the intent is to
|
||||
exercise the right to control the distribution of derivative or
|
||||
collective works based on the Program.
|
||||
|
||||
In addition, mere aggregation of another work not based on the Program
|
||||
with the Program (or with a work based on the Program) on a volume of
|
||||
a storage or distribution medium does not bring the other work under
|
||||
the scope of this License.
|
||||
|
||||
3. You may copy and distribute the Program (or a work based on it,
|
||||
under Section 2) in object code or executable form under the terms of
|
||||
Sections 1 and 2 above provided that you also do one of the following:
|
||||
|
||||
a) Accompany it with the complete corresponding machine-readable
|
||||
source code, which must be distributed under the terms of Sections
|
||||
1 and 2 above on a medium customarily used for software interchange; or,
|
||||
|
||||
b) Accompany it with a written offer, valid for at least three
|
||||
years, to give any third party, for a charge no more than your
|
||||
cost of physically performing source distribution, a complete
|
||||
machine-readable copy of the corresponding source code, to be
|
||||
distributed under the terms of Sections 1 and 2 above on a medium
|
||||
customarily used for software interchange; or,
|
||||
|
||||
c) Accompany it with the information you received as to the offer
|
||||
to distribute corresponding source code. (This alternative is
|
||||
allowed only for noncommercial distribution and only if you
|
||||
received the program in object code or executable form with such
|
||||
an offer, in accord with Subsection b above.)
|
||||
|
||||
The source code for a work means the preferred form of the work for
|
||||
making modifications to it. For an executable work, complete source
|
||||
code means all the source code for all modules it contains, plus any
|
||||
associated interface definition files, plus the scripts used to
|
||||
control compilation and installation of the executable. However, as a
|
||||
special exception, the source code distributed need not include
|
||||
anything that is normally distributed (in either source or binary
|
||||
form) with the major components (compiler, kernel, and so on) of the
|
||||
operating system on which the executable runs, unless that component
|
||||
itself accompanies the executable.
|
||||
|
||||
If distribution of executable or object code is made by offering
|
||||
access to copy from a designated place, then offering equivalent
|
||||
access to copy the source code from the same place counts as
|
||||
distribution of the source code, even though third parties are not
|
||||
compelled to copy the source along with the object code.
|
||||
|
||||
4. You may not copy, modify, sublicense, or distribute the Program
|
||||
except as expressly provided under this License. Any attempt
|
||||
otherwise to copy, modify, sublicense or distribute the Program is
|
||||
void, and will automatically terminate your rights under this License.
|
||||
However, parties who have received copies, or rights, from you under
|
||||
this License will not have their licenses terminated so long as such
|
||||
parties remain in full compliance.
|
||||
|
||||
5. You are not required to accept this License, since you have not
|
||||
signed it. However, nothing else grants you permission to modify or
|
||||
distribute the Program or its derivative works. These actions are
|
||||
prohibited by law if you do not accept this License. Therefore, by
|
||||
modifying or distributing the Program (or any work based on the
|
||||
Program), you indicate your acceptance of this License to do so, and
|
||||
all its terms and conditions for copying, distributing or modifying
|
||||
the Program or works based on it.
|
||||
|
||||
6. Each time you redistribute the Program (or any work based on the
|
||||
Program), the recipient automatically receives a license from the
|
||||
original licensor to copy, distribute or modify the Program subject to
|
||||
these terms and conditions. You may not impose any further
|
||||
restrictions on the recipients' exercise of the rights granted herein.
|
||||
You are not responsible for enforcing compliance by third parties to
|
||||
this License.
|
||||
|
||||
7. If, as a consequence of a court judgment or allegation of patent
|
||||
infringement or for any other reason (not limited to patent issues),
|
||||
conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot
|
||||
distribute so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you
|
||||
may not distribute the Program at all. For example, if a patent
|
||||
license would not permit royalty-free redistribution of the Program by
|
||||
all those who receive copies directly or indirectly through you, then
|
||||
the only way you could satisfy both it and this License would be to
|
||||
refrain entirely from distribution of the Program.
|
||||
|
||||
If any portion of this section is held invalid or unenforceable under
|
||||
any particular circumstance, the balance of the section is intended to
|
||||
apply and the section as a whole is intended to apply in other
|
||||
circumstances.
|
||||
|
||||
It is not the purpose of this section to induce you to infringe any
|
||||
patents or other property right claims or to contest validity of any
|
||||
such claims; this section has the sole purpose of protecting the
|
||||
integrity of the free software distribution system, which is
|
||||
implemented by public license practices. Many people have made
|
||||
generous contributions to the wide range of software distributed
|
||||
through that system in reliance on consistent application of that
|
||||
system; it is up to the author/donor to decide if he or she is willing
|
||||
to distribute software through any other system and a licensee cannot
|
||||
impose that choice.
|
||||
|
||||
This section is intended to make thoroughly clear what is believed to
|
||||
be a consequence of the rest of this License.
|
||||
|
||||
8. If the distribution and/or use of the Program is restricted in
|
||||
certain countries either by patents or by copyrighted interfaces, the
|
||||
original copyright holder who places the Program under this License
|
||||
may add an explicit geographical distribution limitation excluding
|
||||
those countries, so that distribution is permitted only in or among
|
||||
countries not thus excluded. In such case, this License incorporates
|
||||
the limitation as if written in the body of this License.
|
||||
|
||||
9. The Free Software Foundation may publish revised and/or new versions
|
||||
of the General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the Program
|
||||
specifies a version number of this License which applies to it and "any
|
||||
later version", you have the option of following the terms and conditions
|
||||
either of that version or of any later version published by the Free
|
||||
Software Foundation. If the Program does not specify a version number of
|
||||
this License, you may choose any version ever published by the Free Software
|
||||
Foundation.
|
||||
|
||||
10. If you wish to incorporate parts of the Program into other free
|
||||
programs whose distribution conditions are different, write to the author
|
||||
to ask for permission. For software which is copyrighted by the Free
|
||||
Software Foundation, write to the Free Software Foundation; we sometimes
|
||||
make exceptions for this. Our decision will be guided by the two goals
|
||||
of preserving the free status of all derivatives of our free software and
|
||||
of promoting the sharing and reuse of software generally.
|
||||
|
||||
NO WARRANTY
|
||||
|
||||
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
|
||||
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
|
||||
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
|
||||
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
|
||||
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
|
||||
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
|
||||
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
|
||||
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
|
||||
REPAIR OR CORRECTION.
|
||||
|
||||
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
|
||||
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
|
||||
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
|
||||
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
|
||||
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
|
||||
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
|
||||
POSSIBILITY OF SUCH DAMAGES.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
convey the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software; you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation; either version 2 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License along
|
||||
with this program; if not, write to the Free Software Foundation, Inc.,
|
||||
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program is interactive, make it output a short notice like this
|
||||
when it starts in an interactive mode:
|
||||
|
||||
Gnomovision version 69, Copyright (C) year name of author
|
||||
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, the commands you use may
|
||||
be called something other than `show w' and `show c'; they could even be
|
||||
mouse-clicks or menu items--whatever suits your program.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or your
|
||||
school, if any, to sign a "copyright disclaimer" for the program, if
|
||||
necessary. Here is a sample; alter the names:
|
||||
|
||||
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
|
||||
`Gnomovision' (which makes passes at compilers) written by James Hacker.
|
||||
|
||||
<signature of Ty Coon>, 1 April 1989
|
||||
Ty Coon, President of Vice
|
||||
|
||||
This General Public License does not permit incorporating your program into
|
||||
proprietary programs. If your program is a subroutine library, you may
|
||||
consider it more useful to permit linking proprietary applications with the
|
||||
library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License.
|
||||
@@ -0,0 +1,12 @@
|
||||
name: Better Messages
|
||||
type: module
|
||||
description: This module adds simple functions to make Drupal messages look and act better.
|
||||
package: User interface
|
||||
# core: 8.x
|
||||
configure: better_messages.settings_form
|
||||
|
||||
# Information added by Drupal.org packaging script on 2018-02-03
|
||||
version: '8.x-1.0-alpha2'
|
||||
core: '8.x'
|
||||
project: 'better_messages'
|
||||
datestamp: 1517663884
|
||||
@@ -0,0 +1,14 @@
|
||||
better_messages:
|
||||
version: 1.x
|
||||
css:
|
||||
theme:
|
||||
css/better_messages.css: {}
|
||||
js:
|
||||
js/better_messages.js: {}
|
||||
dependencies:
|
||||
- core/jquery
|
||||
- core/jquery.once
|
||||
- core/jquery.ui.draggable
|
||||
- core/jquery.ui.resizable
|
||||
- core/drupal
|
||||
- core/drupalSettings
|
||||
@@ -0,0 +1,5 @@
|
||||
better_messages.settings_form:
|
||||
title: 'Better Messages settings'
|
||||
description: 'Better handling of Drupal messages UI'
|
||||
route_name: better_messages.settings_form
|
||||
parent: system.admin_config_ui
|
||||
@@ -0,0 +1,138 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Implements hook_theme().
|
||||
*/
|
||||
function better_messages_theme() {
|
||||
return [
|
||||
'better_messages_wrapper' => [
|
||||
'render element' => 'element',
|
||||
'variables' => [
|
||||
'children' => '',
|
||||
'message_list' => [],
|
||||
],
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements hook_element_info_alter().
|
||||
*/
|
||||
function better_messages_element_info_alter(array &$info) {
|
||||
// Replace the default pre_render for status_messages with our custom one.
|
||||
$info['status_messages']['#pre_render'][0] = 'better_messages_status_messages_pre_render';
|
||||
}
|
||||
|
||||
/**
|
||||
* Pre render callback for 'status_messages' render element.
|
||||
*/
|
||||
function better_messages_status_messages_pre_render(array $element) {
|
||||
// The code below is heavily copied from StatusMessages::renderMessages().
|
||||
$element = [
|
||||
'#lazy_builder' => ['better_messages_status_messages_lazy_builder', [$element['#display']]],
|
||||
'#create_placeholder' => TRUE,
|
||||
];
|
||||
|
||||
// Directly create a placeholder as we need this to be placeholdered
|
||||
// regardless if this is a POST or GET request.
|
||||
// @todo remove this when https://www.drupal.org/node/2367555 lands.
|
||||
return \Drupal::service('render_placeholder_generator')->createPlaceholder($element);
|
||||
}
|
||||
|
||||
/**
|
||||
* Lazy builder for 'status_messages'.
|
||||
*
|
||||
* Improved version of StatusMessages::renderMessages() that additionally wraps
|
||||
* the output into an overlay markup whenever necessary.
|
||||
*
|
||||
* @param string|null $type
|
||||
* Limit the messages returned by type. Defaults to NULL, meaning all types.
|
||||
* Passed on to drupal_get_messages(). These values are supported:
|
||||
* - NULL
|
||||
* - 'status'
|
||||
* - 'warning'
|
||||
* - 'error'
|
||||
*
|
||||
* @return array
|
||||
* A renderable array containing the messages.
|
||||
*/
|
||||
function better_messages_status_messages_lazy_builder($type) {
|
||||
$render = \Drupal\Core\Render\Element\StatusMessages::renderMessages($type);
|
||||
if (!empty($render)) {
|
||||
$render['#theme_wrappers'][] = 'better_messages_wrapper';
|
||||
$render['#attached']['library'][] = 'better_messages/better_messages';
|
||||
$render['#attached']['drupalSettings']['better_messages'] = \Drupal::config('better_messages.settings')->get();
|
||||
}
|
||||
|
||||
return $render;
|
||||
}
|
||||
|
||||
/**
|
||||
* Preprocess for 'better_messages_wrapper' theme hook.
|
||||
*/
|
||||
function template_preprocess_better_messages_wrapper(&$variables) {
|
||||
$settings = \Drupal::config('better_messages.settings');
|
||||
$cache = \Drupal\Core\Cache\CacheableMetadata::createFromRenderArray($variables);
|
||||
$cache->addCacheTags($settings->getCacheTags());
|
||||
$cache->addCacheContexts($settings->getCacheContexts());
|
||||
$cache->mergeCacheMaxAge($settings->getCacheMaxAge());
|
||||
|
||||
// Inject the messages from $variables into our "better_messages" context
|
||||
// since now we have crossed beyond the point where "current" messages are
|
||||
// retrievable via drupal_get_messages().
|
||||
\Drupal::service('better_messages.context')->setMessages($variables['message_list']);
|
||||
|
||||
/** @var \Drupal\Core\Condition\ConditionManager $condition_manager */
|
||||
$condition_manager = \Drupal::service('plugin.manager.condition');
|
||||
/** @var \Drupal\Core\Plugin\Context\ContextRepositoryInterface $context_repository */
|
||||
$context_repository = \Drupal::service('context.repository');
|
||||
/** @var \Drupal\Core\Plugin\Context\ContextHandlerInterface $context_handler */
|
||||
$context_handler = \Drupal::service('context.handler');
|
||||
|
||||
$pass = TRUE;
|
||||
foreach ($settings->get('visibility') as $condition_id => $condition) {
|
||||
$condition = $condition_manager->createInstance($condition_id, $condition);
|
||||
if ($condition instanceof \Drupal\Core\Plugin\ContextAwarePluginInterface) {
|
||||
try {
|
||||
$contexts = $context_repository->getRuntimeContexts(array_values($condition->getContextMapping()));
|
||||
$context_handler->applyContextMapping($condition, $contexts);
|
||||
}
|
||||
catch (\Drupal\Component\Plugin\Exception\ContextException $e) {
|
||||
// We couldn't initialize the condition, so it just cannot participate.
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
$pass = $condition->execute();
|
||||
}
|
||||
catch (\Drupal\Component\Plugin\Exception\ContextException $e) {
|
||||
// Condition couldn't evaluate itself. Let's skip it.
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($condition instanceof \Drupal\Core\Cache\CacheableDependencyInterface) {
|
||||
$cache->addCacheTags($condition->getCacheTags());
|
||||
$cache->addCacheContexts($condition->getCacheContexts());
|
||||
$cache->mergeCacheMaxAge($condition->getCacheMaxAge());
|
||||
}
|
||||
|
||||
if (!$pass) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
$cache->applyTo($variables);
|
||||
|
||||
if ($pass && !empty($variables['message_list'])) {
|
||||
$variables['attributes']['class'][] = 'better-messages-overlay';
|
||||
|
||||
if (\Drupal::config('better_messages.settings')->get('fixed')) {
|
||||
$variables['attributes']['class'][] = 'better-messages-position-fixed';
|
||||
}
|
||||
|
||||
if (isset($variables['message_list']['error'])) {
|
||||
$variables['attributes']['class'][] = 'better-messages-has-errors';
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
configure better messages:
|
||||
title: 'Configure better messages'
|
||||
description: 'Configure settings of the Better Messages module.'
|
||||
@@ -0,0 +1,7 @@
|
||||
better_messages.settings_form:
|
||||
path: /admin/config/user-interface/better-messages
|
||||
defaults:
|
||||
_form: 'Drupal\better_messages\Form\BetterMessagesSettingsForm'
|
||||
_title: 'Better Message settings'
|
||||
requirements:
|
||||
_permission: 'configure better messages'
|
||||
@@ -0,0 +1,5 @@
|
||||
services:
|
||||
better_messages.context:
|
||||
class: Drupal\better_messages\ContextProvider\MessagesContext
|
||||
tags:
|
||||
- { name: 'context_provider' }
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"name": "drupal/better_messages",
|
||||
"description": "Better Messages module for Drupal 8.",
|
||||
"type": "drupal-module"
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
position: 'center'
|
||||
vertical: 0
|
||||
horizontal: 10
|
||||
fixed: 1
|
||||
width: '400px'
|
||||
autoclose: 0
|
||||
opendelay: 0.3
|
||||
disable_autoclose: 0
|
||||
show_countdown: 1
|
||||
hover_autoclose: 1
|
||||
popin:
|
||||
effect: 'fadeIn'
|
||||
duration: 'slow'
|
||||
popout:
|
||||
effect: 'fadeOut'
|
||||
duration: 'slow'
|
||||
jquery_ui:
|
||||
draggable: 1
|
||||
resizable: 0
|
||||
visibility: []
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
better_messages.settings:
|
||||
type: config_entity
|
||||
label: 'Better Messages settings'
|
||||
mapping:
|
||||
position:
|
||||
type: string
|
||||
label: 'Position'
|
||||
vertical:
|
||||
type: integer
|
||||
label: 'Vertical'
|
||||
horizontal:
|
||||
type: integer
|
||||
label: 'Horizontal'
|
||||
fixed:
|
||||
type: integer
|
||||
label: 'Fixed'
|
||||
width:
|
||||
type: string
|
||||
label: 'Width'
|
||||
autoclose:
|
||||
type: integer
|
||||
label: 'autoclose'
|
||||
opendelay:
|
||||
type: float
|
||||
label: 'Opendelay'
|
||||
disable_autoclose:
|
||||
type: integer
|
||||
label: 'Disable autoclose'
|
||||
show_countdown:
|
||||
type: integer
|
||||
label: 'Show countdown'
|
||||
hover_autoclose:
|
||||
type: integer
|
||||
label: 'Hover autoclose'
|
||||
popin:
|
||||
type: mapping
|
||||
label: 'Popin effect'
|
||||
mapping:
|
||||
effect:
|
||||
type: string
|
||||
label: 'Effect'
|
||||
duration:
|
||||
type: string
|
||||
label: 'Duration'
|
||||
popout:
|
||||
type: mapping
|
||||
label: 'Popout effect'
|
||||
mapping:
|
||||
effect:
|
||||
type: string
|
||||
label: 'Effect'
|
||||
duration:
|
||||
type: string
|
||||
label: 'Duration'
|
||||
jquery_ui:
|
||||
type: mapping
|
||||
label: 'jQuery UI enhancement'
|
||||
mapping:
|
||||
draggable:
|
||||
type: integer
|
||||
label: 'Draggable'
|
||||
resizable :
|
||||
type: integer
|
||||
label: 'Resizable'
|
||||
visibility:
|
||||
type: sequence
|
||||
label: 'Visibility Conditions'
|
||||
sequence:
|
||||
type: condition.plugin.[id]
|
||||
label: 'Visibility Condition'
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
condition.plugin.message_type:
|
||||
type: condition.plugin
|
||||
mapping:
|
||||
message_types:
|
||||
type: sequence
|
||||
label: 'Allowed message types'
|
||||
sequence:
|
||||
type: string
|
||||
label: 'Message type'
|
||||
@@ -0,0 +1,7 @@
|
||||
#better-messages-default .better-messages-close {
|
||||
float: left;
|
||||
}
|
||||
|
||||
#better-messages-default .better-messages-timer {
|
||||
float: right;
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
/** We want the admin toolbar to be on top of our overlay when it's
|
||||
horizontal. */
|
||||
.toolbar-horizontal #toolbar-administration {
|
||||
z-index: 520;
|
||||
}
|
||||
|
||||
/** Hide the messages if we have JS support */
|
||||
.js #better-messages-default.better-messages-overlay {
|
||||
display: none;
|
||||
}
|
||||
|
||||
#better-messages-default.better-messages-overlay {
|
||||
z-index: 510;
|
||||
position: absolute;
|
||||
background: #FFFFFF;
|
||||
padding: 1em;
|
||||
-webkit-box-shadow: 0 2px 10px #000000;
|
||||
-moz-box-shadow: 0 2px 10px #000000;
|
||||
box-shadow: 0 2px 10px #000000;
|
||||
-webkit-border-radius: 1em;
|
||||
-moz-border-radius: 1em;
|
||||
border-radius: 1em;
|
||||
}
|
||||
|
||||
#better-messages-default.better-messages-overlay.better-messages-position-fixed {
|
||||
position: fixed;
|
||||
}
|
||||
|
||||
#better-messages-default.better-messages-overlay .better-messages-footer {
|
||||
border-top: 1px solid #DDDDDD;
|
||||
margin-top: 10px;
|
||||
padding-top: 5px;
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
#better-messages-default.better-messages-overlay .better-messages-close {
|
||||
display: block;
|
||||
float: right;
|
||||
color: #676767;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
#better-messages-default.better-messages-overlay .better-messages-close span {
|
||||
background: transparent url(../images/closelabel.gif) no-repeat;
|
||||
display: block;
|
||||
float: right;
|
||||
height: 22px;
|
||||
width: 22px;
|
||||
}
|
||||
|
||||
#better-messages-default.better-messages-overlay .better-messages-timer {
|
||||
float: left;
|
||||
line-height: 22px;
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 687 B |
@@ -0,0 +1,124 @@
|
||||
|
||||
(function ($) {
|
||||
|
||||
'use strict';
|
||||
|
||||
Drupal.behaviors.betterMessages = {
|
||||
attach: function (context, settings) {
|
||||
|
||||
var betterMessages = settings.better_messages;
|
||||
var message_box = $('#better-messages-default.better-messages-overlay', context).once('better-messages');
|
||||
|
||||
if (message_box.length > 0) {
|
||||
/* jQuery UI Enhancements */
|
||||
if (betterMessages.jquery_ui.draggable == '1') {
|
||||
message_box.draggable();
|
||||
}
|
||||
if (betterMessages.jquery_ui.resizable == '1') {
|
||||
message_box.resizable();
|
||||
}
|
||||
|
||||
/* Functions to determine the popin/popout animation */
|
||||
betterMessages.open = function () {
|
||||
var method = 'fadeIn';
|
||||
switch (betterMessages.popin.effect) {
|
||||
case 'fadeIn':
|
||||
case 'slideDown':
|
||||
method = betterMessages.popin.effect;
|
||||
break;
|
||||
}
|
||||
message_box[method](betterMessages.popin.duration);
|
||||
};
|
||||
betterMessages.close = function () {
|
||||
var method = 'fadeOut';
|
||||
switch (betterMessages.popout.effect) {
|
||||
case 'fadeOut':
|
||||
break;
|
||||
case 'slideUp':
|
||||
method = betterMessages.popout.effect;
|
||||
break;
|
||||
}
|
||||
message_box[method](betterMessages.popout.duration);
|
||||
};
|
||||
|
||||
/* Function to determine closing count */
|
||||
betterMessages.countDownClose = function (seconds) {
|
||||
if (!message_box.hasClass('better-messages-has-errors') || !betterMessages.disable_autoclose) {
|
||||
if (seconds > 0) {
|
||||
seconds--;
|
||||
if (betterMessages.show_countdown == '1') {
|
||||
$('.better-messages-timer', message_box).text(Drupal.t('Closing in !seconds seconds', {'!seconds': seconds}));
|
||||
}
|
||||
if (seconds > 0) {
|
||||
betterMessages.countDown = setTimeout(function () {
|
||||
betterMessages.countDownClose(seconds);
|
||||
}, 1000);
|
||||
}
|
||||
else {
|
||||
betterMessages.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if (betterMessages.width) {
|
||||
message_box.css('width', betterMessages.width);
|
||||
}
|
||||
|
||||
/* Determine Popup Message position */
|
||||
var vertical = betterMessages.vertical;
|
||||
var horizontal = betterMessages.horizontal;
|
||||
var cssPosition = {};
|
||||
switch (betterMessages.position) {
|
||||
case 'center':
|
||||
vertical = ($(window).height() - message_box.height()) / 2;
|
||||
horizontal = ($(window).width() - message_box.width()) / 2;
|
||||
cssPosition = {top: vertical + 'px', left: horizontal + 'px'};
|
||||
break;
|
||||
case 'tl':
|
||||
cssPosition = {top: vertical + 'px', left: horizontal + 'px'};
|
||||
break;
|
||||
case 'tr':
|
||||
cssPosition = {top: vertical + 'px', right: horizontal + 'px'};
|
||||
break;
|
||||
case 'bl':
|
||||
cssPosition = {bottom: vertical + 'px', left: horizontal + 'px'};
|
||||
break;
|
||||
case 'br':
|
||||
cssPosition = {bottom: vertical + 'px', right: horizontal + 'px'};
|
||||
break;
|
||||
}
|
||||
message_box.css(cssPosition);
|
||||
|
||||
/* Here we control closing and opening effects and controls */
|
||||
setTimeout(function () {
|
||||
betterMessages.open();
|
||||
}, betterMessages.opendelay * 1000);
|
||||
|
||||
if (betterMessages.autoclose != 0) {
|
||||
betterMessages.countDownClose(betterMessages.autoclose);
|
||||
}
|
||||
if (betterMessages.hover_autoclose == '1') {
|
||||
message_box.hover(function () {
|
||||
clearTimeout(betterMessages.countDown);
|
||||
$('.better-messages-timer', message_box).fadeOut('slow');
|
||||
});
|
||||
}
|
||||
$('.better-messages-close', message_box).click(function (event) {
|
||||
betterMessages.close();
|
||||
event.preventDefault();
|
||||
});
|
||||
|
||||
/* Esc key handler for closing the message. This doesn't work on Safari or Chrome
|
||||
See the issue here: http://code.google.com/p/chromium/issues/detail?id=14635
|
||||
*/
|
||||
$(document).keypress(function (e) {
|
||||
if (e.keyCode == 27) {
|
||||
betterMessages.close();
|
||||
return e.preventDefault();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
})(jQuery);
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\better_messages\ContextProvider;
|
||||
|
||||
use Drupal\Core\Cache\CacheableMetadata;
|
||||
use Drupal\Core\Plugin\Context\Context;
|
||||
use Drupal\Core\Plugin\Context\ContextDefinition;
|
||||
use Drupal\Core\Plugin\Context\ContextProviderInterface;
|
||||
use Drupal\Core\StringTranslation\StringTranslationTrait;
|
||||
|
||||
/**
|
||||
* Provides current Drupal status messages as a context.
|
||||
*/
|
||||
class MessagesContext implements ContextProviderInterface {
|
||||
|
||||
use StringTranslationTrait;
|
||||
|
||||
/**
|
||||
* Current status messages.
|
||||
*
|
||||
* If this property is NULL, it means we haven't hit the rendering yet and
|
||||
* current messages can be queried from Drupal core. Otherwise the currently
|
||||
* rendered messages will be stored in here.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $messages = NULL;
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function getRuntimeContexts(array $unqualified_context_ids) {
|
||||
$result = [];
|
||||
|
||||
$context_definition = new ContextDefinition('map', NULL, FALSE);
|
||||
$context = new Context($context_definition, $this->getMessages());
|
||||
|
||||
$cacheability = new CacheableMetadata();
|
||||
// We cannot cache this context as literally a few lines below some message
|
||||
// might be added.
|
||||
$cacheability->setCacheMaxAge(0);
|
||||
// Since messages are stored in session, we must vary by it.
|
||||
$cacheability->addCacheContexts(['session']);
|
||||
$context->addCacheableDependency($cacheability);
|
||||
|
||||
$result['better_messages'] = $context;
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function getAvailableContexts() {
|
||||
$context = new Context(new ContextDefinition('map', $this->t('Current status messages')));
|
||||
return ['better_messages' => $context];
|
||||
}
|
||||
|
||||
/**
|
||||
* Store currently rendered status messages.
|
||||
*
|
||||
* @param array $messages
|
||||
* Messages array to store (supposedly it should be the currently rendered
|
||||
* ones)
|
||||
*/
|
||||
public function setMessages(array $messages) {
|
||||
$this->messages = $messages;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve current status messages.
|
||||
*
|
||||
* @return array
|
||||
* Array of current messages. It will either be a result of
|
||||
* drupal_get_messages() or $this->messages should we already be beyond the
|
||||
* phase of rendering status messages on the current page request
|
||||
*/
|
||||
protected function getMessages() {
|
||||
return is_null($this->messages) ? drupal_get_messages(NULL, FALSE) : $this->messages;
|
||||
}
|
||||
|
||||
}
|
||||
+356
@@ -0,0 +1,356 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\better_messages\Form;
|
||||
|
||||
use Drupal\Core\Condition\ConditionManager;
|
||||
use Drupal\Core\Config\ConfigFactoryInterface;
|
||||
use Drupal\Core\Form\ConfigFormBase;
|
||||
use Drupal\Core\Form\FormStateInterface;
|
||||
use Drupal\Core\Form\SubformState;
|
||||
use Drupal\Core\Plugin\Context\ContextRepositoryInterface;
|
||||
use Symfony\Component\DependencyInjection\ContainerInterface;
|
||||
|
||||
/**
|
||||
* Admin settings form of the module.
|
||||
*/
|
||||
class BetterMessagesSettingsForm extends ConfigFormBase {
|
||||
|
||||
/**
|
||||
* The condition plugin manager.
|
||||
*
|
||||
* @var \Drupal\Core\Condition\ConditionManager
|
||||
*/
|
||||
protected $conditionManager;
|
||||
|
||||
/**
|
||||
* The context repository service.
|
||||
*
|
||||
* @var \Drupal\Core\Plugin\Context\ContextRepositoryInterface
|
||||
*/
|
||||
protected $contextRepository;
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public static function create(ContainerInterface $container) {
|
||||
return new static(
|
||||
$container->get('config.factory'),
|
||||
$container->get('plugin.manager.condition'),
|
||||
$container->get('context.repository')
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* BetterMessagesSettingsForm constructor.
|
||||
*/
|
||||
public function __construct(ConfigFactoryInterface $config_factory, ConditionManager $condition_manager, ContextRepositoryInterface $context_repository) {
|
||||
parent::__construct($config_factory);
|
||||
|
||||
$this->conditionManager = $condition_manager;
|
||||
$this->contextRepository = $context_repository;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function getFormId() {
|
||||
return 'better_messages_settings_form';
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function getEditableConfigNames() {
|
||||
return ['better_messages.settings'];
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function buildForm(array $form, FormStateInterface $form_state) {
|
||||
$config = $this->config('better_messages.settings');
|
||||
|
||||
$form_state->setTemporaryValue('gathered_contexts', $this->contextRepository->getAvailableContexts());
|
||||
|
||||
$settings = $config->get();
|
||||
|
||||
$form['position'] = array(
|
||||
'#type' => 'details',
|
||||
'#title' => $this->t('Messages positions and basic properties'),
|
||||
'#weight' => -5,
|
||||
'#open' => TRUE
|
||||
);
|
||||
|
||||
$form['position']['pos'] = array(
|
||||
'#type' => 'radios',
|
||||
'#title' => $this->t('Set position of Message'),
|
||||
'#default_value' => $settings['position'],
|
||||
'#description' => $this->t('Position of message relative to screen'),
|
||||
'#attributes' => array('class' => array('better-messages-admin-radios')),
|
||||
'#options' => array(
|
||||
'center' => $this->t('Center screen'),
|
||||
'tl' => $this->t('Top left'),
|
||||
'tr' => $this->t('Top right'),
|
||||
'bl' => $this->t('Bottom left'),
|
||||
'br' => $this->t('Bottom right'),
|
||||
),
|
||||
);
|
||||
|
||||
$form['position']['fixed'] = array(
|
||||
'#type' => 'checkbox',
|
||||
'#default_value' => $settings['fixed'],
|
||||
'#title' => $this->t('Keep fixed position of message as you scroll.'),
|
||||
);
|
||||
|
||||
$form['position']['width'] = array(
|
||||
'#type' => 'textfield',
|
||||
'#title' => $this->t('Custom width'),
|
||||
'#description' => $this->t('Width in pixel (e.g. 400px) or percentage (e.g. 100%). Leave empty if you prefer your theme to control the width.'),
|
||||
'#default_value' => $settings['width'],
|
||||
'#size' => 20,
|
||||
'#maxlength' => 20,
|
||||
);
|
||||
|
||||
$form['position']['horizontal'] = array(
|
||||
'#type' => 'textfield',
|
||||
'#title' => $this->t('Left/Right spacing'),
|
||||
'#default_value' => $settings['horizontal'],
|
||||
'#size' => 20,
|
||||
'#maxlength' => 20,
|
||||
'#required' => TRUE,
|
||||
'#field_suffix' => $this->t('px'),
|
||||
'#states' => [
|
||||
'invisible' => [
|
||||
':input[name="pos"]' => ['value' => 'center'],
|
||||
],
|
||||
],
|
||||
);
|
||||
|
||||
$form['position']['vertical'] = array(
|
||||
'#type' => 'textfield',
|
||||
'#title' => $this->t('Top/Down spacing'),
|
||||
'#default_value' => $settings['vertical'],
|
||||
'#size' => 20,
|
||||
'#maxlength' => 20,
|
||||
'#required' => TRUE,
|
||||
'#field_suffix' => $this->t('px'),
|
||||
'#states' => [
|
||||
'invisible' => [
|
||||
':input[name="pos"]' => ['value' => 'center'],
|
||||
],
|
||||
],
|
||||
);
|
||||
|
||||
$form['animation'] = array(
|
||||
'#type' => 'details',
|
||||
'#title' => $this->t('Messages animation settings'),
|
||||
'#weight' => -3,
|
||||
'#open' => TRUE,
|
||||
);
|
||||
|
||||
$form['animation']['popin_effect'] = array(
|
||||
'#type' => 'select',
|
||||
'#title' => $this->t('Pop-in (show) message box effect'),
|
||||
'#default_value' => $settings['popin']['effect'],
|
||||
'#options' => array(
|
||||
'fadeIn' => $this->t('Fade in'),
|
||||
'slideDown' => $this->t('Slide down'),
|
||||
),
|
||||
);
|
||||
|
||||
$form['animation']['popin_duration'] = array(
|
||||
'#type' => 'textfield',
|
||||
'#title' => $this->t('Duration of (show) effect'),
|
||||
'#description' => $this->t('A string representing one of the three predefined speeds ("slow", "normal", or "fast").<br />Or the number of milliseconds to run the animation (e.g. 1000).'),
|
||||
'#default_value' => $settings['popin']['duration'],
|
||||
'#size' => 20,
|
||||
'#maxlength' => 20,
|
||||
);
|
||||
|
||||
$form['animation']['popout_effect'] = array(
|
||||
'#type' => 'select',
|
||||
'#title' => $this->t('Pop-out (close) message box effect'),
|
||||
'#default_value' => $settings['popout']['effect'],
|
||||
'#options' => array(
|
||||
'fadeIn' => $this->t('Fade out'),
|
||||
'slideUp' => $this->t('Slide Up'),
|
||||
),
|
||||
);
|
||||
|
||||
$form['animation']['popout_duration'] = array(
|
||||
'#type' => 'textfield',
|
||||
'#title' => $this->t('Duration of (close) effect'),
|
||||
'#description' => $this->t('A string representing one of the three predefined speeds ("slow", "normal", or "fast").<br />Or the number of milliseconds to run the animation (e.g. 1000).'),
|
||||
'#default_value' => $settings['popout']['duration'],
|
||||
'#size' => 20,
|
||||
'#maxlength' => 20,
|
||||
);
|
||||
|
||||
$form['animation']['autoclose'] = array(
|
||||
'#type' => 'textfield',
|
||||
'#title' => $this->t('Number of seconds to auto close after the page has loaded'),
|
||||
'#description' => $this->t('0 for never. You can set it as 0.25 for quarter second'),
|
||||
'#default_value' => $settings['autoclose'],
|
||||
'#size' => 20,
|
||||
'#maxlength' => 20,
|
||||
);
|
||||
|
||||
$form['animation']['disable_autoclose'] = array(
|
||||
'#type' => 'checkbox',
|
||||
'#title' => $this->t('Disable auto close if messages include an error message'),
|
||||
'#default_value' => $settings['disable_autoclose'],
|
||||
);
|
||||
|
||||
$form['animation']['show_countdown'] = array(
|
||||
'#type' => 'checkbox',
|
||||
'#title' => $this->t('Show countdown timer'),
|
||||
'#default_value' => $settings['show_countdown'],
|
||||
);
|
||||
|
||||
$form['animation']['hover_autoclose'] = array(
|
||||
'#type' => 'checkbox',
|
||||
'#title' => $this->t('Stop auto close timer when hover'),
|
||||
'#default_value' => $settings['hover_autoclose'],
|
||||
);
|
||||
|
||||
$form['animation']['open_delay'] = array(
|
||||
'#type' => 'textfield',
|
||||
'#title' => $this->t('Number of seconds to delay message after the page has loaded'),
|
||||
'#description' => $this->t('0 for never. You can set it as 0.25 for quarter second'),
|
||||
'#default_value' => $settings['opendelay'],
|
||||
'#size' => 20,
|
||||
'#maxlength' => 20,
|
||||
);
|
||||
|
||||
$form['jquery_ui'] = array(
|
||||
'#type' => 'details',
|
||||
'#title' => $this->t('jQuery UI enhancements'),
|
||||
'#weight' => 10,
|
||||
'#description' => $this->t('These settings require jQuery UI.'),
|
||||
'#open' => TRUE,
|
||||
);
|
||||
|
||||
$form['jquery_ui']['draggable'] = array(
|
||||
'#type' => 'checkbox',
|
||||
'#title' => $this->t('Make Better Messages draggable'),
|
||||
'#default_value' => $settings['jquery_ui']['draggable'],
|
||||
);
|
||||
$form['jquery_ui']['resizable'] = array(
|
||||
'#type' => 'checkbox',
|
||||
'#title' => $this->t('Make Better Messages resizable'),
|
||||
'#default_value' => $settings['jquery_ui']['resizable'],
|
||||
);
|
||||
|
||||
$form['visibility'] = $this->buildVisibility([], $form_state);
|
||||
|
||||
return parent::buildForm($form, $form_state);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function validateForm(array &$form, FormStateInterface $form_state) {
|
||||
parent::validateForm($form, $form_state);
|
||||
|
||||
foreach ($form_state->getValue('visibility') as $condition_id => $values) {
|
||||
// All condition plugins use 'negate' as a Boolean in their schema.
|
||||
// However, certain form elements may return it as 0/1. Cast here to
|
||||
// ensure the data is in the expected type.
|
||||
if (array_key_exists('negate', $values)) {
|
||||
$form_state->setValue(['visibility', $condition_id, 'negate'], (bool) $values['negate']);
|
||||
}
|
||||
|
||||
// Allow the condition to validate the form.
|
||||
$condition = $form_state->get(['conditions', $condition_id]);
|
||||
$condition->validateConfigurationForm($form['visibility'][$condition_id], SubformState::createForSubform($form['visibility'][$condition_id], $form, $form_state));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function submitForm(array &$form, FormStateInterface $form_state) {
|
||||
$config = $this->config('better_messages.settings');
|
||||
$config->set('position', $form_state->getValue('pos'))
|
||||
->set('fixed', $form_state->getValue('fixed'))
|
||||
->set('width', $form_state->getValue('width'))
|
||||
->set('horizontal', intval($form_state->getValue('horizontal')))
|
||||
->set('vertical', intval($form_state->getValue('vertical')))
|
||||
->set('popin.effect', $form_state->getValue('popin_effect'))
|
||||
->set('popin.duration', $form_state->getValue('popin_duration'))
|
||||
->set('popout.effect', $form_state->getValue('popout_effect'))
|
||||
->set('popout.duration', $form_state->getValue('popout_duration'))
|
||||
->set('autoclose', $form_state->getValue('autoclose'))
|
||||
->set('disable_autoclose', $form_state->getValue('disable_autoclose'))
|
||||
->set('show_countdown', $form_state->getValue('show_countdown'))
|
||||
->set('hover_autoclose', $form_state->getValue('hover_autoclose'))
|
||||
->set('opendelay', $form_state->getValue('open_delay'))
|
||||
->set('jquery_ui.draggable', $form_state->getValue('draggable'))
|
||||
->set('jquery_ui.resizable', $form_state->getValue('resizable'))
|
||||
->set('visibility', []);
|
||||
|
||||
foreach ($form_state->getValue('visibility') as $condition_id => $values) {
|
||||
// Allow the condition to submit the form.
|
||||
$condition = $form_state->get(['conditions', $condition_id]);
|
||||
$condition->submitConfigurationForm($form['visibility'][$condition_id], SubformState::createForSubform($form['visibility'][$condition_id], $form, $form_state));
|
||||
$config->set('visibility.' . $condition_id, $condition->getConfiguration());
|
||||
}
|
||||
|
||||
$config->save();
|
||||
|
||||
parent::submitForm($form, $form_state);
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate form elements for visibility controls.
|
||||
*
|
||||
* @param array $form
|
||||
* Form array chunk where the genreated visibility controls will be embedded
|
||||
* @param \Drupal\Core\Form\FormStateInterface $form_state
|
||||
* Form state that corresponds to $form
|
||||
*
|
||||
* @return array
|
||||
* Form elements for visibility controls
|
||||
*/
|
||||
protected function buildVisibility($form, FormStateInterface $form_state) {
|
||||
$form['#tree'] = TRUE;
|
||||
|
||||
$form['visibility_tabs'] = [
|
||||
'#type' => 'vertical_tabs',
|
||||
'#title' => $this->t('Visibility'),
|
||||
'#parents' => ['visibility_tabs'],
|
||||
];
|
||||
|
||||
$visibility = $this->config($this->getEditableConfigNames()[0])->get('visibility');
|
||||
foreach ($this->conditionManager->getDefinitionsForContexts($form_state->getTemporaryValue('gathered_contexts')) as $condition_id => $definition) {
|
||||
/** @var \Drupal\Core\Condition\ConditionInterface $condition */
|
||||
$condition = $this->conditionManager->createInstance($condition_id, isset($visibility[$condition_id]) ? $visibility[$condition_id] : []);
|
||||
$form_state->set(['conditions', $condition_id], $condition);
|
||||
$condition_form = $condition->buildConfigurationForm([], $form_state);
|
||||
$condition_form['#type'] = 'details';
|
||||
$condition_form['#title'] = $condition->getPluginDefinition()['label'];
|
||||
$condition_form['#group'] = 'visibility_tabs';
|
||||
$form[$condition_id] = $condition_form;
|
||||
}
|
||||
|
||||
// The "current_theme" condition is very raw, and has bugs:
|
||||
// https://www.drupal.org/node/2787529 and
|
||||
// https://www.drupal.org/node/2787529
|
||||
// so we prefer to ditch it.
|
||||
unset($form['current_theme']);
|
||||
|
||||
if (isset($form['request_path'])) {
|
||||
$form['request_path']['#title'] = $this->t('Pages');
|
||||
$form['request_path']['negate']['#type'] = 'radios';
|
||||
$form['request_path']['negate']['#default_value'] = (int) $form['request_path']['negate']['#default_value'];
|
||||
$form['request_path']['negate']['#title_display'] = 'invisible';
|
||||
$form['request_path']['negate']['#options'] = [
|
||||
$this->t('Show for the listed pages'),
|
||||
$this->t('Hide for the listed pages'),
|
||||
];
|
||||
}
|
||||
|
||||
return $form;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\better_messages\Plugin\Condition;
|
||||
|
||||
use Drupal\Component\Utility\Unicode;
|
||||
use Drupal\Core\Condition\ConditionPluginBase;
|
||||
use Drupal\Core\Form\FormStateInterface;
|
||||
use Drupal\Core\Path\AliasManagerInterface;
|
||||
use Drupal\Core\Path\CurrentPathStack;
|
||||
use Drupal\Core\Path\PathMatcherInterface;
|
||||
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
|
||||
use Drupal\Core\Plugin\ContextAwarePluginInterface;
|
||||
use Symfony\Component\DependencyInjection\ContainerInterface;
|
||||
use Symfony\Component\HttpFoundation\RequestStack;
|
||||
|
||||
/**
|
||||
* Provides a 'Message type' condition.
|
||||
*
|
||||
* @Condition(
|
||||
* id = "message_type",
|
||||
* label = @Translation("Message type"),
|
||||
* context = {
|
||||
* "better_messages" = @ContextDefinition("map",
|
||||
* label = @Translation("Current better messages")
|
||||
* )
|
||||
* }
|
||||
* )
|
||||
*/
|
||||
class MessageType extends ConditionPluginBase {
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function defaultConfiguration() {
|
||||
return ['message_types' => []] + parent::defaultConfiguration();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
|
||||
$form['message_types'] = [
|
||||
'#type' => 'checkboxes',
|
||||
'#title' => $this->t('Message types'),
|
||||
'#default_value' => $this->configuration['message_types'],
|
||||
'#options' => $this->messageTypeOptions(),
|
||||
'#description' => $this->t('Specify for which message types to active the condition. Leaving empty means for all message types.'),
|
||||
];
|
||||
return parent::buildConfigurationForm($form, $form_state);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
|
||||
$this->configuration['message_types'] = array_values(array_filter($form_state->getValue('message_types')));
|
||||
parent::submitConfigurationForm($form, $form_state);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function summary() {
|
||||
$message_labels = array_intersect_key($this->messageTypeOptions(), array_combine($this->configuration['message_types'], $this->configuration['message_types']));
|
||||
return implode(', ', $message_labels);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function evaluate() {
|
||||
$messages = $this->getContextValue('better_messages');
|
||||
$intersect = array_intersect($this->configuration['message_types'], array_keys($messages));
|
||||
return empty($this->configuration['message_types']) || !empty($intersect);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve a list of known message types.
|
||||
*
|
||||
* @return array
|
||||
* Array of known message types. Keys are their machine names whereas values
|
||||
* are the corresponding human friendly labels
|
||||
*/
|
||||
protected function messageTypeOptions() {
|
||||
return [
|
||||
'status' => $this->t('Status'),
|
||||
'warning' => $this->t('Warning'),
|
||||
'error' => $this->t('Error'),
|
||||
];
|
||||
}
|
||||
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
{#
|
||||
/**
|
||||
* @file
|
||||
* Default theme for better_messages_wrapper theme hook.
|
||||
*
|
||||
* Wrap the system messages into additional markup required for presenting the
|
||||
* messages in an overlay.
|
||||
*
|
||||
* Available variables:
|
||||
* - children: The system messages
|
||||
*/
|
||||
#}
|
||||
<div{{ attributes.setAttribute('id', 'better-messages-default') }}>
|
||||
<div id="better-messages-inner">
|
||||
{%block children%}
|
||||
<div class="better-messages-content">
|
||||
{{ children }}
|
||||
</div>
|
||||
{% if attributes.hasClass('better-messages-overlay') %}
|
||||
<div class="better-messages-footer"><span class="better-messages-timer"></span><a class="better-messages-close" href="#">{{ 'Close' | t }}<span></span></a></div>
|
||||
{% endif %}
|
||||
{%endblock%}
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,339 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 2, June 1991
|
||||
|
||||
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
|
||||
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The licenses for most software are designed to take away your
|
||||
freedom to share and change it. By contrast, the GNU General Public
|
||||
License is intended to guarantee your freedom to share and change free
|
||||
software--to make sure the software is free for all its users. This
|
||||
General Public License applies to most of the Free Software
|
||||
Foundation's software and to any other program whose authors commit to
|
||||
using it. (Some other Free Software Foundation software is covered by
|
||||
the GNU Lesser General Public License instead.) You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
this service if you wish), that you receive source code or can get it
|
||||
if you want it, that you can change the software or use pieces of it
|
||||
in new free programs; and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to make restrictions that forbid
|
||||
anyone to deny you these rights or to ask you to surrender the rights.
|
||||
These restrictions translate to certain responsibilities for you if you
|
||||
distribute copies of the software, or if you modify it.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must give the recipients all the rights that
|
||||
you have. You must make sure that they, too, receive or can get the
|
||||
source code. And you must show them these terms so they know their
|
||||
rights.
|
||||
|
||||
We protect your rights with two steps: (1) copyright the software, and
|
||||
(2) offer you this license which gives you legal permission to copy,
|
||||
distribute and/or modify the software.
|
||||
|
||||
Also, for each author's protection and ours, we want to make certain
|
||||
that everyone understands that there is no warranty for this free
|
||||
software. If the software is modified by someone else and passed on, we
|
||||
want its recipients to know that what they have is not the original, so
|
||||
that any problems introduced by others will not reflect on the original
|
||||
authors' reputations.
|
||||
|
||||
Finally, any free program is threatened constantly by software
|
||||
patents. We wish to avoid the danger that redistributors of a free
|
||||
program will individually obtain patent licenses, in effect making the
|
||||
program proprietary. To prevent this, we have made it clear that any
|
||||
patent must be licensed for everyone's free use or not licensed at all.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
|
||||
|
||||
0. This License applies to any program or other work which contains
|
||||
a notice placed by the copyright holder saying it may be distributed
|
||||
under the terms of this General Public License. The "Program", below,
|
||||
refers to any such program or work, and a "work based on the Program"
|
||||
means either the Program or any derivative work under copyright law:
|
||||
that is to say, a work containing the Program or a portion of it,
|
||||
either verbatim or with modifications and/or translated into another
|
||||
language. (Hereinafter, translation is included without limitation in
|
||||
the term "modification".) Each licensee is addressed as "you".
|
||||
|
||||
Activities other than copying, distribution and modification are not
|
||||
covered by this License; they are outside its scope. The act of
|
||||
running the Program is not restricted, and the output from the Program
|
||||
is covered only if its contents constitute a work based on the
|
||||
Program (independent of having been made by running the Program).
|
||||
Whether that is true depends on what the Program does.
|
||||
|
||||
1. You may copy and distribute verbatim copies of the Program's
|
||||
source code as you receive it, in any medium, provided that you
|
||||
conspicuously and appropriately publish on each copy an appropriate
|
||||
copyright notice and disclaimer of warranty; keep intact all the
|
||||
notices that refer to this License and to the absence of any warranty;
|
||||
and give any other recipients of the Program a copy of this License
|
||||
along with the Program.
|
||||
|
||||
You may charge a fee for the physical act of transferring a copy, and
|
||||
you may at your option offer warranty protection in exchange for a fee.
|
||||
|
||||
2. You may modify your copy or copies of the Program or any portion
|
||||
of it, thus forming a work based on the Program, and copy and
|
||||
distribute such modifications or work under the terms of Section 1
|
||||
above, provided that you also meet all of these conditions:
|
||||
|
||||
a) You must cause the modified files to carry prominent notices
|
||||
stating that you changed the files and the date of any change.
|
||||
|
||||
b) You must cause any work that you distribute or publish, that in
|
||||
whole or in part contains or is derived from the Program or any
|
||||
part thereof, to be licensed as a whole at no charge to all third
|
||||
parties under the terms of this License.
|
||||
|
||||
c) If the modified program normally reads commands interactively
|
||||
when run, you must cause it, when started running for such
|
||||
interactive use in the most ordinary way, to print or display an
|
||||
announcement including an appropriate copyright notice and a
|
||||
notice that there is no warranty (or else, saying that you provide
|
||||
a warranty) and that users may redistribute the program under
|
||||
these conditions, and telling the user how to view a copy of this
|
||||
License. (Exception: if the Program itself is interactive but
|
||||
does not normally print such an announcement, your work based on
|
||||
the Program is not required to print an announcement.)
|
||||
|
||||
These requirements apply to the modified work as a whole. If
|
||||
identifiable sections of that work are not derived from the Program,
|
||||
and can be reasonably considered independent and separate works in
|
||||
themselves, then this License, and its terms, do not apply to those
|
||||
sections when you distribute them as separate works. But when you
|
||||
distribute the same sections as part of a whole which is a work based
|
||||
on the Program, the distribution of the whole must be on the terms of
|
||||
this License, whose permissions for other licensees extend to the
|
||||
entire whole, and thus to each and every part regardless of who wrote it.
|
||||
|
||||
Thus, it is not the intent of this section to claim rights or contest
|
||||
your rights to work written entirely by you; rather, the intent is to
|
||||
exercise the right to control the distribution of derivative or
|
||||
collective works based on the Program.
|
||||
|
||||
In addition, mere aggregation of another work not based on the Program
|
||||
with the Program (or with a work based on the Program) on a volume of
|
||||
a storage or distribution medium does not bring the other work under
|
||||
the scope of this License.
|
||||
|
||||
3. You may copy and distribute the Program (or a work based on it,
|
||||
under Section 2) in object code or executable form under the terms of
|
||||
Sections 1 and 2 above provided that you also do one of the following:
|
||||
|
||||
a) Accompany it with the complete corresponding machine-readable
|
||||
source code, which must be distributed under the terms of Sections
|
||||
1 and 2 above on a medium customarily used for software interchange; or,
|
||||
|
||||
b) Accompany it with a written offer, valid for at least three
|
||||
years, to give any third party, for a charge no more than your
|
||||
cost of physically performing source distribution, a complete
|
||||
machine-readable copy of the corresponding source code, to be
|
||||
distributed under the terms of Sections 1 and 2 above on a medium
|
||||
customarily used for software interchange; or,
|
||||
|
||||
c) Accompany it with the information you received as to the offer
|
||||
to distribute corresponding source code. (This alternative is
|
||||
allowed only for noncommercial distribution and only if you
|
||||
received the program in object code or executable form with such
|
||||
an offer, in accord with Subsection b above.)
|
||||
|
||||
The source code for a work means the preferred form of the work for
|
||||
making modifications to it. For an executable work, complete source
|
||||
code means all the source code for all modules it contains, plus any
|
||||
associated interface definition files, plus the scripts used to
|
||||
control compilation and installation of the executable. However, as a
|
||||
special exception, the source code distributed need not include
|
||||
anything that is normally distributed (in either source or binary
|
||||
form) with the major components (compiler, kernel, and so on) of the
|
||||
operating system on which the executable runs, unless that component
|
||||
itself accompanies the executable.
|
||||
|
||||
If distribution of executable or object code is made by offering
|
||||
access to copy from a designated place, then offering equivalent
|
||||
access to copy the source code from the same place counts as
|
||||
distribution of the source code, even though third parties are not
|
||||
compelled to copy the source along with the object code.
|
||||
|
||||
4. You may not copy, modify, sublicense, or distribute the Program
|
||||
except as expressly provided under this License. Any attempt
|
||||
otherwise to copy, modify, sublicense or distribute the Program is
|
||||
void, and will automatically terminate your rights under this License.
|
||||
However, parties who have received copies, or rights, from you under
|
||||
this License will not have their licenses terminated so long as such
|
||||
parties remain in full compliance.
|
||||
|
||||
5. You are not required to accept this License, since you have not
|
||||
signed it. However, nothing else grants you permission to modify or
|
||||
distribute the Program or its derivative works. These actions are
|
||||
prohibited by law if you do not accept this License. Therefore, by
|
||||
modifying or distributing the Program (or any work based on the
|
||||
Program), you indicate your acceptance of this License to do so, and
|
||||
all its terms and conditions for copying, distributing or modifying
|
||||
the Program or works based on it.
|
||||
|
||||
6. Each time you redistribute the Program (or any work based on the
|
||||
Program), the recipient automatically receives a license from the
|
||||
original licensor to copy, distribute or modify the Program subject to
|
||||
these terms and conditions. You may not impose any further
|
||||
restrictions on the recipients' exercise of the rights granted herein.
|
||||
You are not responsible for enforcing compliance by third parties to
|
||||
this License.
|
||||
|
||||
7. If, as a consequence of a court judgment or allegation of patent
|
||||
infringement or for any other reason (not limited to patent issues),
|
||||
conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot
|
||||
distribute so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you
|
||||
may not distribute the Program at all. For example, if a patent
|
||||
license would not permit royalty-free redistribution of the Program by
|
||||
all those who receive copies directly or indirectly through you, then
|
||||
the only way you could satisfy both it and this License would be to
|
||||
refrain entirely from distribution of the Program.
|
||||
|
||||
If any portion of this section is held invalid or unenforceable under
|
||||
any particular circumstance, the balance of the section is intended to
|
||||
apply and the section as a whole is intended to apply in other
|
||||
circumstances.
|
||||
|
||||
It is not the purpose of this section to induce you to infringe any
|
||||
patents or other property right claims or to contest validity of any
|
||||
such claims; this section has the sole purpose of protecting the
|
||||
integrity of the free software distribution system, which is
|
||||
implemented by public license practices. Many people have made
|
||||
generous contributions to the wide range of software distributed
|
||||
through that system in reliance on consistent application of that
|
||||
system; it is up to the author/donor to decide if he or she is willing
|
||||
to distribute software through any other system and a licensee cannot
|
||||
impose that choice.
|
||||
|
||||
This section is intended to make thoroughly clear what is believed to
|
||||
be a consequence of the rest of this License.
|
||||
|
||||
8. If the distribution and/or use of the Program is restricted in
|
||||
certain countries either by patents or by copyrighted interfaces, the
|
||||
original copyright holder who places the Program under this License
|
||||
may add an explicit geographical distribution limitation excluding
|
||||
those countries, so that distribution is permitted only in or among
|
||||
countries not thus excluded. In such case, this License incorporates
|
||||
the limitation as if written in the body of this License.
|
||||
|
||||
9. The Free Software Foundation may publish revised and/or new versions
|
||||
of the General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the Program
|
||||
specifies a version number of this License which applies to it and "any
|
||||
later version", you have the option of following the terms and conditions
|
||||
either of that version or of any later version published by the Free
|
||||
Software Foundation. If the Program does not specify a version number of
|
||||
this License, you may choose any version ever published by the Free Software
|
||||
Foundation.
|
||||
|
||||
10. If you wish to incorporate parts of the Program into other free
|
||||
programs whose distribution conditions are different, write to the author
|
||||
to ask for permission. For software which is copyrighted by the Free
|
||||
Software Foundation, write to the Free Software Foundation; we sometimes
|
||||
make exceptions for this. Our decision will be guided by the two goals
|
||||
of preserving the free status of all derivatives of our free software and
|
||||
of promoting the sharing and reuse of software generally.
|
||||
|
||||
NO WARRANTY
|
||||
|
||||
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
|
||||
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
|
||||
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
|
||||
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
|
||||
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
|
||||
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
|
||||
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
|
||||
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
|
||||
REPAIR OR CORRECTION.
|
||||
|
||||
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
|
||||
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
|
||||
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
|
||||
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
|
||||
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
|
||||
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
|
||||
POSSIBILITY OF SUCH DAMAGES.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
convey the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software; you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation; either version 2 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License along
|
||||
with this program; if not, write to the Free Software Foundation, Inc.,
|
||||
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program is interactive, make it output a short notice like this
|
||||
when it starts in an interactive mode:
|
||||
|
||||
Gnomovision version 69, Copyright (C) year name of author
|
||||
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, the commands you use may
|
||||
be called something other than `show w' and `show c'; they could even be
|
||||
mouse-clicks or menu items--whatever suits your program.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or your
|
||||
school, if any, to sign a "copyright disclaimer" for the program, if
|
||||
necessary. Here is a sample; alter the names:
|
||||
|
||||
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
|
||||
`Gnomovision' (which makes passes at compilers) written by James Hacker.
|
||||
|
||||
<signature of Ty Coon>, 1 April 1989
|
||||
Ty Coon, President of Vice
|
||||
|
||||
This General Public License does not permit incorporating your program into
|
||||
proprietary programs. If your program is a subroutine library, you may
|
||||
consider it more useful to permit linking proprietary applications with the
|
||||
library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License.
|
||||
@@ -0,0 +1,14 @@
|
||||
This is a simple module that adds a JS in the HTML head to perform a redirect
|
||||
from a desktop site URL to a mobile one or the other way around. This is
|
||||
useful when Varnish or any other reverse proxy cache is being used to cache
|
||||
your site and keep a mobile vs desktop redirect working.
|
||||
|
||||
Install this module like any other module and set the "Desktop site URL" and
|
||||
"Mobile site URL" for this to work.
|
||||
|
||||
To be able to access the administrative area or avoid redirection at any point,
|
||||
use the query string below:
|
||||
|
||||
?stopredirect=true
|
||||
|
||||
URL settings - /admin/config/system/mobile_js_redirect
|
||||
@@ -0,0 +1,46 @@
|
||||
/**
|
||||
* @file
|
||||
* Client-side Javascript routine for Mobile JS Redirect module.
|
||||
*/
|
||||
|
||||
var mobile_pattern = new RegExp(mobile_js_redirect_devices_regexp, 'i');
|
||||
var mobile = (mobile_pattern.test(navigator.userAgent.toLowerCase()));
|
||||
|
||||
// Both of these variables have to be set for this mechanism to work.
|
||||
// If this plugin is being used by a Drupal Gardens site, we can simply
|
||||
// set these variables manually and upload this file to the site.
|
||||
var target_url = mobile_js_redirect_target_url;
|
||||
var mobile_url = mobile_js_redirect_mobile_url;
|
||||
var desktop_url = mobile_js_redirect_desktop_url;
|
||||
|
||||
// Check whether the noRedirect flag is set.
|
||||
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
|
||||
var no_redirect = false;
|
||||
var secure = (window.location.protocol == "https:") ? true : false;
|
||||
for (var i = 0; i < hashes.length; i++) {
|
||||
var hash = hashes[i].split('=');
|
||||
if (hash[0] != null && hash[0] == 'stopredirect' && hash[1] != null && hash[1] == 'true') {
|
||||
no_redirect = true;
|
||||
// Add session cookie to stop future redirect.
|
||||
jQuery.cookie('mobile_js_redirect.stopredirect', 1, { path: '/', secure: secure });
|
||||
break;
|
||||
}
|
||||
else if (jQuery.cookie('mobile_js_redirect.stopredirect') == 1) {
|
||||
no_redirect = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (mobile_url != null && desktop_url != null && !no_redirect) {
|
||||
// Remove protocol and path.
|
||||
var regex = /[\/:?#]/;
|
||||
var url_parts = target_url.replace('http://', '').replace('https://', '').split(regex);
|
||||
|
||||
if (mobile && window.location.hostname == url_parts[0]) {
|
||||
// The device is mobile but the URL is desktop, so redirect.
|
||||
document.location = mobile_url;
|
||||
}
|
||||
else if (!mobile && window.location.hostname == url_parts[0]) {
|
||||
// The device is desktop but the URL is mobile, so redirect.
|
||||
document.location = desktop_url;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
name: 'Mobile JS Redirect'
|
||||
type: module
|
||||
description: 'Client-side redirect based on the user-agent string.'
|
||||
# core: 8.x
|
||||
configure: 'admin/config/system/mobile_js_redirect'
|
||||
|
||||
# Information added by Drupal.org packaging script on 2016-11-30
|
||||
version: '8.x-1.0-beta1'
|
||||
core: '8.x'
|
||||
project: 'mobile_js_redirect'
|
||||
datestamp: 1480536188
|
||||
@@ -0,0 +1,7 @@
|
||||
mobile-js-redirect-js:
|
||||
version: 1.x
|
||||
js:
|
||||
js/mobile_js_redirect.js: {}
|
||||
dependencies:
|
||||
- core/jquery
|
||||
- core/jquery.cookie
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
system.mobile_js_redirect_admin:
|
||||
title: 'Mobile JS Redirect'
|
||||
parent: system.admin_config_system
|
||||
description: 'Manage the Mobile JS Redirect Settings.'
|
||||
route_name: mobile_js_redirect.admin_form
|
||||
weight: 30
|
||||
@@ -0,0 +1,90 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* @file
|
||||
* Client-side redirect based on the user-agent string.
|
||||
*/
|
||||
|
||||
use Drupal\Component\Utility\Html;
|
||||
|
||||
/**
|
||||
* Default value for devices list option.
|
||||
*/
|
||||
const MOBILE_JS_REDIRECT_REGEXP_DEVICES_LIST = 'iphone|ipad|ipod|android|blackberry|mini|windowssce|iemobile|palm';
|
||||
|
||||
/**
|
||||
* Implements hook_page_attachments().
|
||||
*/
|
||||
function mobile_js_redirect_page_attachments(array &$attachments) {
|
||||
$attachments['#attached']['library'][] = 'mobile_js_redirect/mobile-js-redirect-js';
|
||||
$attachments['#attached']['html_head'][] = [
|
||||
[
|
||||
'#type' => 'html_tag',
|
||||
'#tag' => 'script',
|
||||
'#value' => mobile_js_get_urls(),
|
||||
],
|
||||
'mobile-js-redirect-js',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get URLs for use on JS file.
|
||||
*/
|
||||
function mobile_js_get_urls() {
|
||||
|
||||
global $base_root;
|
||||
$urls = \Drupal::config('mobile_js_redirect.settings')->get('mobile_js_redirect_urls');
|
||||
$current_url = $base_root . \Drupal::request()->getRequestUri();
|
||||
$current_devices_list = (!empty(\Drupal::config('mobile_js_redirect.settings')->get('mobile_js_redirect_regexp_devices_list'))) ? \Drupal::config('mobile_js_redirect.settings')->get('mobile_js_redirect_regexp_devices_list') : MOBILE_JS_REDIRECT_REGEXP_DEVICES_LIST;
|
||||
$devices_list = Html::escape($current_devices_list);
|
||||
|
||||
// Set default values.
|
||||
$javascript = "var mobile_js_redirect_target_url = '';";
|
||||
$javascript .= "var mobile_js_redirect_desktop_url = '';";
|
||||
$javascript .= "var mobile_js_redirect_mobile_url = '';";
|
||||
|
||||
$urls_arr = explode(PHP_EOL, $urls);
|
||||
|
||||
foreach ($urls_arr as $value) {
|
||||
|
||||
$url_line = explode('|', $value);
|
||||
$last_char = substr($url_line[0], -1);
|
||||
|
||||
if ($last_char == '*') {
|
||||
$trated_url = substr($url_line[0], 0, -1);
|
||||
if (strpos($current_url, $trated_url) !== FALSE) {
|
||||
$javascript = mobile_js_update_urls($url_line);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if ($url_line[0] == $current_url || $url_line[0] . '/' == $current_url) {
|
||||
$javascript = mobile_js_update_urls($url_line);
|
||||
break;
|
||||
}
|
||||
}
|
||||
$javascript .= "var mobile_js_redirect_devices_regexp = '$devices_list';";
|
||||
|
||||
return $javascript;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update URL values.
|
||||
*/
|
||||
function mobile_js_update_urls($url_array) {
|
||||
$target_url = (!empty($url_array[0])) ? $url_array[0] : '';
|
||||
$last_char = substr($url_array[0], -1);
|
||||
|
||||
if ($last_char == '*') {
|
||||
$target_url = substr($url_array[0], 0, -1);
|
||||
}
|
||||
|
||||
$url_desktop = (!empty($url_array[1])) ? $url_array[1] : '';
|
||||
$url_mobile = (!empty($url_array[2])) ? $url_array[2] : '';
|
||||
|
||||
$javascript = "var mobile_js_redirect_target_url = '$target_url';";
|
||||
$javascript .= "var mobile_js_redirect_desktop_url = '$url_desktop';";
|
||||
$javascript .= "var mobile_js_redirect_mobile_url = '$url_mobile';";
|
||||
|
||||
return $javascript;
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
mobile_js_redirect.admin_form:
|
||||
path: '/admin/config/system/mobile_js_redirect'
|
||||
defaults:
|
||||
_title: 'Mobile JS Redirect Settings'
|
||||
_form: '\Drupal\mobile_js_redirect\Form\MobileJsRedirectAdminForm'
|
||||
requirements:
|
||||
_permission: 'administer site configuration'
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\mobile_js_redirect\Form;
|
||||
|
||||
use Drupal\Core\Form\ConfigFormBase;
|
||||
use Drupal\Core\Form\FormStateInterface;
|
||||
|
||||
/**
|
||||
* Implements an MobileJsRedirectAdminForm form.
|
||||
*/
|
||||
class MobileJsRedirectAdminForm extends ConfigFormBase {
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function getFormId() {
|
||||
return 'mobile_js_redirect_form';
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function getEditableConfigNames() {
|
||||
return ['mobile_js_redirect.settings'];
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function buildForm(array $form, FormStateInterface $form_state) {
|
||||
$config = $this->config('mobile_js_redirect.settings');
|
||||
$form['site_urls'] = array(
|
||||
'#type' => 'fieldset',
|
||||
'#title' => t('Site URLs'),
|
||||
'#description' => t('Mobile and Desktop sites URLs - Please read the instructions below the textarea.'),
|
||||
);
|
||||
|
||||
$form['site_urls']['mobile_js_redirect_urls'] = array(
|
||||
'#type' => 'textarea',
|
||||
'#description' => t('- Put each group of urls on a line separated by | character (pipe) without spaces like: TARGET URL|DESKTOP URL|MOBILE URL.<br>- You can use the * character (asterisk) as a wildcard on target url.<br>- If you wont redirect one of these (desktop or mobile) leave blank.<br>- The redirect occurrs on the first "true" match.'),
|
||||
'#default_value' => $config->get('mobile_js_redirect_urls'),
|
||||
'#attributes' => array('placeholder' => array('Target URL|Desktop URL|Mobile URL')),
|
||||
'#size' => 10,
|
||||
'#resizable' => FALSE,
|
||||
);
|
||||
|
||||
$form['devices_list'] = array(
|
||||
'#type' => 'fieldset',
|
||||
'#title' => t('Devices List'),
|
||||
'#description' => t('Enter list of User Agent device names which should be recognized as mobile devices.<br>The default list Devices List is: iphone|ipad|ipod|android|blackberry|mini|windowssce|iemobile|palm'),
|
||||
);
|
||||
|
||||
$form['devices_list']['mobile_js_redirect_regexp_devices_list'] = array(
|
||||
'#type' => 'textfield',
|
||||
'#description' => t('Use | for separation.'),
|
||||
'#default_value' => (!empty($config->get('mobile_js_redirect_regexp_devices_list'))) ? $config->get('mobile_js_redirect_regexp_devices_list') : MOBILE_JS_REDIRECT_REGEXP_DEVICES_LIST,
|
||||
);
|
||||
|
||||
return parent::buildForm($form, $form_state);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function validateForm(array &$form, FormStateInterface $form_state) {
|
||||
if (empty($form_state->getValue('mobile_js_redirect_regexp_devices_list'))) {
|
||||
$form_state->setErrorByName('mobile_js_redirect_regexp_devices_list', $this->t('The device list is empty. Please fill the Device list to continue.'));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function submitForm(array &$form, FormStateInterface $form_state) {
|
||||
$config = $this->config('mobile_js_redirect.settings');
|
||||
foreach ($form_state->getValues() as $key => $value) {
|
||||
if (strpos($key, 'mobile_js_redirect_') !== FALSE) {
|
||||
$config->set($key, $value);
|
||||
}
|
||||
}
|
||||
|
||||
$config->save();
|
||||
|
||||
drupal_set_message($this->t('Mobile Js Redirect configuration has been saved.'));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\mobile_js_redirect\Tests;
|
||||
|
||||
use Drupal\simpletest\WebTestBase;
|
||||
|
||||
/**
|
||||
* Tests for the Mobile JS Redirect module.
|
||||
*
|
||||
* @group Mobile Js Redirect
|
||||
*/
|
||||
class MobileJsRedirectTests extends WebTestBase {
|
||||
|
||||
protected $strictConfigSchema = FALSE;
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public static $modules = array('mobile_js_redirect');
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
private $user;
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function setUp() {
|
||||
|
||||
parent::setUp();
|
||||
$this->user = $this->DrupalCreateUser(array(
|
||||
'administer site configuration',
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function testMobileJsRedirectPageExists() {
|
||||
|
||||
$this->drupalLogin($this->user);
|
||||
|
||||
// Generator test:
|
||||
$this->drupalGet('admin/config/system/mobile_js_redirect');
|
||||
$this->assertResponse(200);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function testConfigForm() {
|
||||
|
||||
// Test form structure.
|
||||
$this->drupalLogin($this->user);
|
||||
$this->drupalGet('admin/config/system/mobile_js_redirect');
|
||||
$this->assertResponse(200);
|
||||
$config = $this->config('mobile_js_redirect.settings');
|
||||
$this->assertFieldByName(
|
||||
'mobile_js_redirect_urls',
|
||||
$config->get('mobile_js_redirect_urls'),
|
||||
'Page title field has the default value'
|
||||
);
|
||||
$this->assertFieldByName(
|
||||
'mobile_js_redirect_regexp_devices_list',
|
||||
$config->get('mobile_js_redirect_regexp_devices_list'),
|
||||
'Page title field has the default value'
|
||||
);
|
||||
|
||||
$this->drupalPostForm(NULL, array(
|
||||
'mobile_js_redirect_urls' => 'targetexample|desktopredirect|mobileredirect',
|
||||
'mobile_js_redirect_regexp_devices_list' => 'iphone|ipad|ipod|android|blackberry|mini|windowssce|iemobile|palm',
|
||||
), t('Save configuration'));
|
||||
|
||||
$this->drupalGet('admin/config/system/mobile_js_redirect');
|
||||
$this->assertResponse(200);
|
||||
$this->assertFieldByName(
|
||||
'mobile_js_redirect_urls',
|
||||
'targetexample|desktopredirect|mobileredirect',
|
||||
'URLs text is OK.'
|
||||
);
|
||||
$this->assertFieldByName(
|
||||
'mobile_js_redirect_regexp_devices_list',
|
||||
'iphone|ipad|ipod|android|blackberry|mini|windowssce|iemobile|palm',
|
||||
'Devices List text is OK.'
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,339 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 2, June 1991
|
||||
|
||||
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
|
||||
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The licenses for most software are designed to take away your
|
||||
freedom to share and change it. By contrast, the GNU General Public
|
||||
License is intended to guarantee your freedom to share and change free
|
||||
software--to make sure the software is free for all its users. This
|
||||
General Public License applies to most of the Free Software
|
||||
Foundation's software and to any other program whose authors commit to
|
||||
using it. (Some other Free Software Foundation software is covered by
|
||||
the GNU Lesser General Public License instead.) You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
this service if you wish), that you receive source code or can get it
|
||||
if you want it, that you can change the software or use pieces of it
|
||||
in new free programs; and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to make restrictions that forbid
|
||||
anyone to deny you these rights or to ask you to surrender the rights.
|
||||
These restrictions translate to certain responsibilities for you if you
|
||||
distribute copies of the software, or if you modify it.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must give the recipients all the rights that
|
||||
you have. You must make sure that they, too, receive or can get the
|
||||
source code. And you must show them these terms so they know their
|
||||
rights.
|
||||
|
||||
We protect your rights with two steps: (1) copyright the software, and
|
||||
(2) offer you this license which gives you legal permission to copy,
|
||||
distribute and/or modify the software.
|
||||
|
||||
Also, for each author's protection and ours, we want to make certain
|
||||
that everyone understands that there is no warranty for this free
|
||||
software. If the software is modified by someone else and passed on, we
|
||||
want its recipients to know that what they have is not the original, so
|
||||
that any problems introduced by others will not reflect on the original
|
||||
authors' reputations.
|
||||
|
||||
Finally, any free program is threatened constantly by software
|
||||
patents. We wish to avoid the danger that redistributors of a free
|
||||
program will individually obtain patent licenses, in effect making the
|
||||
program proprietary. To prevent this, we have made it clear that any
|
||||
patent must be licensed for everyone's free use or not licensed at all.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
|
||||
|
||||
0. This License applies to any program or other work which contains
|
||||
a notice placed by the copyright holder saying it may be distributed
|
||||
under the terms of this General Public License. The "Program", below,
|
||||
refers to any such program or work, and a "work based on the Program"
|
||||
means either the Program or any derivative work under copyright law:
|
||||
that is to say, a work containing the Program or a portion of it,
|
||||
either verbatim or with modifications and/or translated into another
|
||||
language. (Hereinafter, translation is included without limitation in
|
||||
the term "modification".) Each licensee is addressed as "you".
|
||||
|
||||
Activities other than copying, distribution and modification are not
|
||||
covered by this License; they are outside its scope. The act of
|
||||
running the Program is not restricted, and the output from the Program
|
||||
is covered only if its contents constitute a work based on the
|
||||
Program (independent of having been made by running the Program).
|
||||
Whether that is true depends on what the Program does.
|
||||
|
||||
1. You may copy and distribute verbatim copies of the Program's
|
||||
source code as you receive it, in any medium, provided that you
|
||||
conspicuously and appropriately publish on each copy an appropriate
|
||||
copyright notice and disclaimer of warranty; keep intact all the
|
||||
notices that refer to this License and to the absence of any warranty;
|
||||
and give any other recipients of the Program a copy of this License
|
||||
along with the Program.
|
||||
|
||||
You may charge a fee for the physical act of transferring a copy, and
|
||||
you may at your option offer warranty protection in exchange for a fee.
|
||||
|
||||
2. You may modify your copy or copies of the Program or any portion
|
||||
of it, thus forming a work based on the Program, and copy and
|
||||
distribute such modifications or work under the terms of Section 1
|
||||
above, provided that you also meet all of these conditions:
|
||||
|
||||
a) You must cause the modified files to carry prominent notices
|
||||
stating that you changed the files and the date of any change.
|
||||
|
||||
b) You must cause any work that you distribute or publish, that in
|
||||
whole or in part contains or is derived from the Program or any
|
||||
part thereof, to be licensed as a whole at no charge to all third
|
||||
parties under the terms of this License.
|
||||
|
||||
c) If the modified program normally reads commands interactively
|
||||
when run, you must cause it, when started running for such
|
||||
interactive use in the most ordinary way, to print or display an
|
||||
announcement including an appropriate copyright notice and a
|
||||
notice that there is no warranty (or else, saying that you provide
|
||||
a warranty) and that users may redistribute the program under
|
||||
these conditions, and telling the user how to view a copy of this
|
||||
License. (Exception: if the Program itself is interactive but
|
||||
does not normally print such an announcement, your work based on
|
||||
the Program is not required to print an announcement.)
|
||||
|
||||
These requirements apply to the modified work as a whole. If
|
||||
identifiable sections of that work are not derived from the Program,
|
||||
and can be reasonably considered independent and separate works in
|
||||
themselves, then this License, and its terms, do not apply to those
|
||||
sections when you distribute them as separate works. But when you
|
||||
distribute the same sections as part of a whole which is a work based
|
||||
on the Program, the distribution of the whole must be on the terms of
|
||||
this License, whose permissions for other licensees extend to the
|
||||
entire whole, and thus to each and every part regardless of who wrote it.
|
||||
|
||||
Thus, it is not the intent of this section to claim rights or contest
|
||||
your rights to work written entirely by you; rather, the intent is to
|
||||
exercise the right to control the distribution of derivative or
|
||||
collective works based on the Program.
|
||||
|
||||
In addition, mere aggregation of another work not based on the Program
|
||||
with the Program (or with a work based on the Program) on a volume of
|
||||
a storage or distribution medium does not bring the other work under
|
||||
the scope of this License.
|
||||
|
||||
3. You may copy and distribute the Program (or a work based on it,
|
||||
under Section 2) in object code or executable form under the terms of
|
||||
Sections 1 and 2 above provided that you also do one of the following:
|
||||
|
||||
a) Accompany it with the complete corresponding machine-readable
|
||||
source code, which must be distributed under the terms of Sections
|
||||
1 and 2 above on a medium customarily used for software interchange; or,
|
||||
|
||||
b) Accompany it with a written offer, valid for at least three
|
||||
years, to give any third party, for a charge no more than your
|
||||
cost of physically performing source distribution, a complete
|
||||
machine-readable copy of the corresponding source code, to be
|
||||
distributed under the terms of Sections 1 and 2 above on a medium
|
||||
customarily used for software interchange; or,
|
||||
|
||||
c) Accompany it with the information you received as to the offer
|
||||
to distribute corresponding source code. (This alternative is
|
||||
allowed only for noncommercial distribution and only if you
|
||||
received the program in object code or executable form with such
|
||||
an offer, in accord with Subsection b above.)
|
||||
|
||||
The source code for a work means the preferred form of the work for
|
||||
making modifications to it. For an executable work, complete source
|
||||
code means all the source code for all modules it contains, plus any
|
||||
associated interface definition files, plus the scripts used to
|
||||
control compilation and installation of the executable. However, as a
|
||||
special exception, the source code distributed need not include
|
||||
anything that is normally distributed (in either source or binary
|
||||
form) with the major components (compiler, kernel, and so on) of the
|
||||
operating system on which the executable runs, unless that component
|
||||
itself accompanies the executable.
|
||||
|
||||
If distribution of executable or object code is made by offering
|
||||
access to copy from a designated place, then offering equivalent
|
||||
access to copy the source code from the same place counts as
|
||||
distribution of the source code, even though third parties are not
|
||||
compelled to copy the source along with the object code.
|
||||
|
||||
4. You may not copy, modify, sublicense, or distribute the Program
|
||||
except as expressly provided under this License. Any attempt
|
||||
otherwise to copy, modify, sublicense or distribute the Program is
|
||||
void, and will automatically terminate your rights under this License.
|
||||
However, parties who have received copies, or rights, from you under
|
||||
this License will not have their licenses terminated so long as such
|
||||
parties remain in full compliance.
|
||||
|
||||
5. You are not required to accept this License, since you have not
|
||||
signed it. However, nothing else grants you permission to modify or
|
||||
distribute the Program or its derivative works. These actions are
|
||||
prohibited by law if you do not accept this License. Therefore, by
|
||||
modifying or distributing the Program (or any work based on the
|
||||
Program), you indicate your acceptance of this License to do so, and
|
||||
all its terms and conditions for copying, distributing or modifying
|
||||
the Program or works based on it.
|
||||
|
||||
6. Each time you redistribute the Program (or any work based on the
|
||||
Program), the recipient automatically receives a license from the
|
||||
original licensor to copy, distribute or modify the Program subject to
|
||||
these terms and conditions. You may not impose any further
|
||||
restrictions on the recipients' exercise of the rights granted herein.
|
||||
You are not responsible for enforcing compliance by third parties to
|
||||
this License.
|
||||
|
||||
7. If, as a consequence of a court judgment or allegation of patent
|
||||
infringement or for any other reason (not limited to patent issues),
|
||||
conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot
|
||||
distribute so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you
|
||||
may not distribute the Program at all. For example, if a patent
|
||||
license would not permit royalty-free redistribution of the Program by
|
||||
all those who receive copies directly or indirectly through you, then
|
||||
the only way you could satisfy both it and this License would be to
|
||||
refrain entirely from distribution of the Program.
|
||||
|
||||
If any portion of this section is held invalid or unenforceable under
|
||||
any particular circumstance, the balance of the section is intended to
|
||||
apply and the section as a whole is intended to apply in other
|
||||
circumstances.
|
||||
|
||||
It is not the purpose of this section to induce you to infringe any
|
||||
patents or other property right claims or to contest validity of any
|
||||
such claims; this section has the sole purpose of protecting the
|
||||
integrity of the free software distribution system, which is
|
||||
implemented by public license practices. Many people have made
|
||||
generous contributions to the wide range of software distributed
|
||||
through that system in reliance on consistent application of that
|
||||
system; it is up to the author/donor to decide if he or she is willing
|
||||
to distribute software through any other system and a licensee cannot
|
||||
impose that choice.
|
||||
|
||||
This section is intended to make thoroughly clear what is believed to
|
||||
be a consequence of the rest of this License.
|
||||
|
||||
8. If the distribution and/or use of the Program is restricted in
|
||||
certain countries either by patents or by copyrighted interfaces, the
|
||||
original copyright holder who places the Program under this License
|
||||
may add an explicit geographical distribution limitation excluding
|
||||
those countries, so that distribution is permitted only in or among
|
||||
countries not thus excluded. In such case, this License incorporates
|
||||
the limitation as if written in the body of this License.
|
||||
|
||||
9. The Free Software Foundation may publish revised and/or new versions
|
||||
of the General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the Program
|
||||
specifies a version number of this License which applies to it and "any
|
||||
later version", you have the option of following the terms and conditions
|
||||
either of that version or of any later version published by the Free
|
||||
Software Foundation. If the Program does not specify a version number of
|
||||
this License, you may choose any version ever published by the Free Software
|
||||
Foundation.
|
||||
|
||||
10. If you wish to incorporate parts of the Program into other free
|
||||
programs whose distribution conditions are different, write to the author
|
||||
to ask for permission. For software which is copyrighted by the Free
|
||||
Software Foundation, write to the Free Software Foundation; we sometimes
|
||||
make exceptions for this. Our decision will be guided by the two goals
|
||||
of preserving the free status of all derivatives of our free software and
|
||||
of promoting the sharing and reuse of software generally.
|
||||
|
||||
NO WARRANTY
|
||||
|
||||
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
|
||||
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
|
||||
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
|
||||
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
|
||||
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
|
||||
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
|
||||
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
|
||||
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
|
||||
REPAIR OR CORRECTION.
|
||||
|
||||
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
|
||||
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
|
||||
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
|
||||
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
|
||||
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
|
||||
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
|
||||
POSSIBILITY OF SUCH DAMAGES.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
convey the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software; you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation; either version 2 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License along
|
||||
with this program; if not, write to the Free Software Foundation, Inc.,
|
||||
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program is interactive, make it output a short notice like this
|
||||
when it starts in an interactive mode:
|
||||
|
||||
Gnomovision version 69, Copyright (C) year name of author
|
||||
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, the commands you use may
|
||||
be called something other than `show w' and `show c'; they could even be
|
||||
mouse-clicks or menu items--whatever suits your program.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or your
|
||||
school, if any, to sign a "copyright disclaimer" for the program, if
|
||||
necessary. Here is a sample; alter the names:
|
||||
|
||||
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
|
||||
`Gnomovision' (which makes passes at compilers) written by James Hacker.
|
||||
|
||||
<signature of Ty Coon>, 1 April 1989
|
||||
Ty Coon, President of Vice
|
||||
|
||||
This General Public License does not permit incorporating your program into
|
||||
proprietary programs. If your program is a subroutine library, you may
|
||||
consider it more useful to permit linking proprietary applications with the
|
||||
library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License.
|
||||
@@ -0,0 +1,53 @@
|
||||
|
||||
CONTENTS OF THIS FILE
|
||||
---------------------
|
||||
|
||||
* Introduction
|
||||
* Configuration
|
||||
* Features
|
||||
* More information
|
||||
|
||||
INTRODUCTION
|
||||
------------
|
||||
|
||||
The AddToAny module provides share buttons for Drupal. Sharing icons and
|
||||
features are maintained by AddToAny, the universal sharing platform.
|
||||
|
||||
By default, the module places share buttons below node content.
|
||||
|
||||
CONFIGURATION
|
||||
-------------
|
||||
|
||||
To configure AddToAny, go to:
|
||||
Administration > Configuration > Web services > AddToAny.
|
||||
|
||||
Explore AddToAny's documentation for the Drupal module:
|
||||
https://www.addtoany.com/buttons/customize/drupal
|
||||
|
||||
FEATURES
|
||||
--------
|
||||
|
||||
The module strives to remain lightweight & efficient while integrating with
|
||||
core Drupal features and major contributed modules such as:
|
||||
|
||||
* Blocks
|
||||
* Views
|
||||
* Display Suite (contributed)
|
||||
|
||||
AddToAny core is optimized to load asynchronously, and many sharing and social
|
||||
media features come from AddToAny core including:
|
||||
|
||||
* Universal share menus
|
||||
* Share counters
|
||||
* Share templates
|
||||
* Custom icons
|
||||
* Automatic Google Analytics integration
|
||||
* Event tracking (useful for integration with other analytics software)
|
||||
* Link tracking using bit.ly, goo.gl, and custom URL shorteners
|
||||
* Automatic localization (over 50 languages)
|
||||
|
||||
MORE INFORMATION
|
||||
----------------
|
||||
|
||||
* AddToAny's official website:
|
||||
https://www.addtoany.com/
|
||||
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* @file
|
||||
* Hooks specific to the AddToAny module.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Alter the entity types that the AddToAny pseudo-field is available for.
|
||||
*
|
||||
* @param array $types
|
||||
* The entity types.
|
||||
*/
|
||||
function hook_addtoany_entity_types_alter(&$types) {
|
||||
// Add the "taxonomy_term" entity type.
|
||||
$types[] = 'taxonomy_term';
|
||||
}
|
||||
|
||||
/**
|
||||
* @} End of "addtogroup addtoany".
|
||||
*/
|
||||
@@ -0,0 +1,5 @@
|
||||
addtoany.settings:
|
||||
title: 'AddToAny Settings'
|
||||
base_route_name: addtoany.admin_settings
|
||||
names:
|
||||
- addtoany.settings
|
||||
@@ -0,0 +1,14 @@
|
||||
name: AddToAny
|
||||
type: module
|
||||
description: 'Share buttons by AddToAny, including the AddToAny universal sharing button, Facebook, Twitter, Google+, Pinterest, and over 100 more on the <a href="https://www.addtoany.com/" target="_blank">AddToAny</a> platform.'
|
||||
package: Other
|
||||
# core: 8.x
|
||||
dependencies:
|
||||
- drupal:node
|
||||
configure: addtoany.admin_settings
|
||||
|
||||
# Information added by Drupal.org packaging script on 2018-03-07
|
||||
version: '8.x-1.9'
|
||||
core: '8.x'
|
||||
project: 'addtoany'
|
||||
datestamp: 1520385667
|
||||
@@ -0,0 +1,132 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* @file
|
||||
* Install, update and uninstall functions for the AddToAny module.
|
||||
*/
|
||||
|
||||
use Drupal\Core\Entity\Entity\EntityViewDisplay;
|
||||
use Drupal\node\Entity\NodeType;
|
||||
|
||||
/**
|
||||
* Implements hook_install().
|
||||
*/
|
||||
function addtoany_install() {
|
||||
// Build a structured list of node bundles and view modes that have AddToAny
|
||||
// enabled by default.
|
||||
$node_enable_by_default = [
|
||||
'article' => ['default', 'teaser'],
|
||||
'page' => ['default', 'teaser'],
|
||||
];
|
||||
// Get the config entity storage handler.
|
||||
$storage = \Drupal::entityTypeManager()->getStorage('entity_view_display');
|
||||
foreach ($node_enable_by_default as $bundle => $viewmodes) {
|
||||
// Set a default weight per node type.
|
||||
$display_weight = ($bundle == 'article') ? 5 : 101;
|
||||
|
||||
foreach ($viewmodes as $viewmode) {
|
||||
// Get the config entity for this bundle and view mode.
|
||||
$display = $storage->load('node.' . $bundle . '.' . $viewmode);
|
||||
// Enable the AddToAny extra field and save the config.
|
||||
if (!empty($display)) {
|
||||
$display->setComponent('addtoany', ['weight' => $display_weight])->save();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Migrate global placement settings to settings per view mode.
|
||||
*/
|
||||
function addtoany_update_8101(&$sandbox) {
|
||||
$config_factory = \Drupal::configFactory();
|
||||
|
||||
// Gather the settings we need to migrate.
|
||||
$addtoany_settings = $config_factory->getEditable('addtoany.settings');
|
||||
$node_types = $addtoany_settings->getOriginal('nodetypes');
|
||||
$display_in_teasers = $addtoany_settings->getOriginal('display_in_teasers');
|
||||
$display_in_nodecont = $addtoany_settings->getOriginal('display_in_nodecont');
|
||||
$display_weight = $addtoany_settings->getOriginal('display_weight');
|
||||
$new_display_weight = $display_weight;
|
||||
|
||||
// The entity display repository stores which view modes are enabled.
|
||||
$entity_display_repository = \Drupal::getContainer()->get('entity_display.repository');
|
||||
|
||||
// Check if AddToAny is currently shown on at least one node type.
|
||||
if (!empty($node_types) && $display_in_nodecont) {
|
||||
|
||||
// Loop over the AddToAny-enabled node types.
|
||||
foreach ($node_types as $bundle) {
|
||||
// Get enabled view modes.
|
||||
$view_modes = $entity_display_repository->getViewModeOptionsByBundle('node', $bundle);
|
||||
|
||||
// If the teaser view mode is enabled but the old settings excluded it,
|
||||
// take it out.
|
||||
if (!empty($view_modes['teaser']) && $display_in_teasers == FALSE) {
|
||||
unset($view_modes['teaser']);
|
||||
}
|
||||
|
||||
// Check if the old default weight was set.
|
||||
if ($display_weight == 10) {
|
||||
// Set the new default weight per node type.
|
||||
$new_display_weight = ($bundle == 'article') ? 5 : 101;
|
||||
}
|
||||
|
||||
// Loop over the view modes and apply new settings to match the old.
|
||||
foreach ($view_modes as $view_mode => $view_mode_info) {
|
||||
$display = EntityViewDisplay::load('node.' . $bundle . '.' . $view_mode);
|
||||
$display->setComponent('addtoany', ['weight' => $new_display_weight])->save();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Convert Display Suite fields to regular "extra fields".
|
||||
if (\Drupal::moduleHandler()->moduleExists('ds')) {
|
||||
// The DsField implementation only supported node entities.
|
||||
$all_node_types = NodeType::loadMultiple();
|
||||
|
||||
foreach ($all_node_types as $node_type) {
|
||||
// Get enabled view modes.
|
||||
$view_modes = $entity_display_repository->getViewModeOptionsByBundle('node', $node_type->id());
|
||||
|
||||
// Loop over the view modes and apply new settings to match the old.
|
||||
foreach ($view_modes as $view_mode => $view_mode_info) {
|
||||
// Get the entity view display config entity.
|
||||
$display = EntityViewDisplay::load('node.' . $node_type->id() . '.' . $view_mode);
|
||||
|
||||
// Check if this view mode uses Display Suite fields and if the Display
|
||||
// Suite AddToAny field ("addtoany_field") was enabled.
|
||||
$ds_fields = $display->getThirdPartySetting('ds', 'fields');
|
||||
if (!empty($ds_fields) && isset($ds_fields['addtoany_field'])) {
|
||||
// Remove the DS field, add the extra field.
|
||||
unset($ds_fields['addtoany_field']);
|
||||
$display->setComponent('addtoany');
|
||||
// Keep the rest of the DS fields.
|
||||
$display->setThirdPartySetting('ds', 'fields', $ds_fields);
|
||||
|
||||
// Find where the DS field was placed and put the AddToAny extra field
|
||||
// in its place.
|
||||
$ds_regions = $display->getThirdPartySetting('ds', 'regions');
|
||||
foreach ($ds_regions as $label => $ds_region_fields) {
|
||||
$key = array_search('addtoany_field', $ds_region_fields);
|
||||
if ($key !== FALSE) {
|
||||
$ds_regions[$label][$key] = 'addtoany';
|
||||
}
|
||||
}
|
||||
// Apply the altered region settings.
|
||||
$display->setThirdPartySetting('ds', 'regions', $ds_regions);
|
||||
|
||||
// Save the view mode.
|
||||
$display->save();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Finally, clean up no longer used settings.
|
||||
$addtoany_settings->clear('nodetypes')
|
||||
->clear('display_in_teasers')
|
||||
->clear('display_in_nodecont')
|
||||
->clear('display_weight')
|
||||
->save();
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
addtoany:
|
||||
version: VERSION
|
||||
js:
|
||||
https://static.addtoany.com/menu/page.js: { attributes: { async: true }, type: external, minified: true }
|
||||
js/addtoany.js: {}
|
||||
css:
|
||||
theme:
|
||||
css/addtoany.css: {}
|
||||
dependencies:
|
||||
- core/drupal
|
||||
|
||||
addtoany.admin:
|
||||
version: VERSION
|
||||
js:
|
||||
js/addtoany.admin.js: {}
|
||||
css:
|
||||
theme:
|
||||
css/addtoany.admin.css: {}
|
||||
dependencies:
|
||||
- core/jquery
|
||||
- core/drupal
|
||||
@@ -0,0 +1,5 @@
|
||||
addtoany.admin_settings:
|
||||
title: 'AddToAny'
|
||||
parent: system.admin_config_services
|
||||
description: 'Configure AddToAny share buttons.'
|
||||
route_name: addtoany.admin_settings
|
||||
@@ -0,0 +1,4 @@
|
||||
addtoany.admin_settings_tab:
|
||||
route_name: addtoany.admin_settings
|
||||
title: Settings
|
||||
base_route: addtoany.admin_settings
|
||||
@@ -0,0 +1,270 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* @file
|
||||
* Handle AddToAny integration.
|
||||
*/
|
||||
|
||||
use Drupal\Core\Entity\EntityInterface;
|
||||
use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
|
||||
use Drupal\Core\Render\Markup;
|
||||
use Drupal\Core\Url;
|
||||
use Drupal\Component\Utility\UrlHelper;
|
||||
use Drupal\node\Entity\Node;
|
||||
|
||||
/**
|
||||
* Implements hook_theme().
|
||||
*/
|
||||
function addtoany_theme() {
|
||||
return [
|
||||
'addtoany_standard' => [
|
||||
'variables' => [
|
||||
'addtoany_html' => FALSE,
|
||||
'link_url' => FALSE,
|
||||
'link_title' => FALSE,
|
||||
'buttons_size' => FALSE,
|
||||
'button_setting' => FALSE,
|
||||
'button_image' => FALSE,
|
||||
'universal_button_placement' => FALSE,
|
||||
'entity_type' => '',
|
||||
'bundle' => '',
|
||||
],
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements hook_theme_suggestions_HOOK().
|
||||
*/
|
||||
function addtoany_theme_suggestions_addtoany_standard(array $variables) {
|
||||
$suggestion = 'addtoany_standard__';
|
||||
$suggestions = [];
|
||||
|
||||
if (!empty($variables['entity_type'])) {
|
||||
$suggestion .= $variables['entity_type'];
|
||||
$suggestions[] = $suggestion;
|
||||
}
|
||||
|
||||
if (!empty($variables['entity_type']) && !empty($variables['bundle'])) {
|
||||
$suggestion .= '__' . $variables['bundle'];
|
||||
$suggestions[] = $suggestion;
|
||||
}
|
||||
|
||||
return $suggestions;
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements hook_entity_extra_field_info().
|
||||
*/
|
||||
function addtoany_entity_extra_field_info() {
|
||||
$extra = [];
|
||||
$types = ['node', 'comment', 'media'];
|
||||
|
||||
// Allow modules to alter the entity types.
|
||||
\Drupal::moduleHandler()->alter('addtoany_entity_types', $types);
|
||||
|
||||
foreach ($types as $type) {
|
||||
$bundles = Drupal::service('entity_type.bundle.info')->getBundleInfo($type);
|
||||
foreach ($bundles as $bundle => $bundle_data) {
|
||||
$extra[$type][$bundle]['display']['addtoany'] = [
|
||||
'label' => t('AddToAny'),
|
||||
'description' => t('Share buttons by AddToAny'),
|
||||
'weight' => 5,
|
||||
'visible' => FALSE,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
return $extra;
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements hook_ENTITY_TYPE_view().
|
||||
*/
|
||||
function addtoany_entity_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) {
|
||||
if ($display->getComponent('addtoany')) {
|
||||
$data = addtoany_create_entity_data($entity);
|
||||
$build['addtoany'] = [
|
||||
'#addtoany_html' => \Drupal::token()->replace($data['addtoany_html'], ['node' => $entity]),
|
||||
'#link_url' => $data['link_url'],
|
||||
'#link_title' => $data['link_title'],
|
||||
'#button_setting' => $data['button_setting'],
|
||||
'#button_image' => $data['button_image'],
|
||||
'#universal_button_placement' => $data['universal_button_placement'],
|
||||
'#buttons_size' => $data['buttons_size'],
|
||||
'#entity_type' => $entity->getEntityType()->id(),
|
||||
'#bundle' => $entity->bundle(),
|
||||
'#theme' => 'addtoany_standard',
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements hook_page_attachments().
|
||||
*/
|
||||
function addtoany_page_attachments(&$page) {
|
||||
$config = \Drupal::config('addtoany.settings');
|
||||
|
||||
// Initial JavaScript.
|
||||
$additional_js = $config->get('additional_js');
|
||||
|
||||
if (\Drupal::moduleHandler()->moduleExists('token')) {
|
||||
$node = \Drupal::routeMatch()->getParameter('node');
|
||||
$data = [];
|
||||
if ($node) {
|
||||
if (is_numeric($node)) {
|
||||
$node = Node::load($node);
|
||||
}
|
||||
$data = ['node' => $node];
|
||||
$additional_js = \Drupal::token()->replace($additional_js, $data);
|
||||
}
|
||||
}
|
||||
|
||||
$javascript_header = 'window.a2a_config=window.a2a_config||{};'
|
||||
. 'a2a_config.callbacks=[];a2a_config.overlays=[];'
|
||||
. 'a2a_config.templates={};'
|
||||
. (($config->get('no_3p')) ? 'a2a_config.no_3p=1;' : '')
|
||||
. $additional_js;
|
||||
|
||||
// Add AddToAny initial JS config.
|
||||
$page['#attached']['html_head'][] = [
|
||||
// The data.
|
||||
[
|
||||
// Add a <script> tag.
|
||||
'#tag' => 'script',
|
||||
// Add JavaScript to the <script> tag.
|
||||
'#value' => Markup::create($javascript_header),
|
||||
// Give weight so it appears after meta tags, etc.
|
||||
'#weight' => 10,
|
||||
],
|
||||
// Assign a key to reference this HTML <HEAD> element when altering.
|
||||
'addtoany-js',
|
||||
];
|
||||
|
||||
// Custom CSS.
|
||||
$css = $config->get('additional_css');
|
||||
if (!empty($css)) {
|
||||
// Add AddToAny custom CSS.
|
||||
$page['#attached']['html_head'][] = [
|
||||
// The data.
|
||||
[
|
||||
// Add a <style> tag.
|
||||
'#tag' => 'style',
|
||||
// Add CSS to the <style> tag.
|
||||
'#value' => $css,
|
||||
// Give weight so it appears after meta tags, etc.
|
||||
'#weight' => 10,
|
||||
],
|
||||
// Assign a key to reference this HTML <HEAD> element when altering.
|
||||
'addtoany-css',
|
||||
];
|
||||
}
|
||||
|
||||
// Add module's main library, which includes external AddToAny core JS,
|
||||
// and the module's CSS.
|
||||
$page['#attached']['library'][] = 'addtoany/addtoany';
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate data for AddToAny buttons for a node.
|
||||
*
|
||||
* @param object $node
|
||||
* The node object to create the buttons for.
|
||||
* @param object $config
|
||||
* If present this will be used as custom config data. Use NULL for default
|
||||
* config data.
|
||||
*
|
||||
* @return array
|
||||
* The array with url, title, additional_html that will be send to Twig.
|
||||
*/
|
||||
function addtoany_create_entity_data($node, $config = NULL) {
|
||||
$url = isset($node) ? $node->url('canonical', ['absolute' => TRUE]) : NULL;
|
||||
$title = isset($node) ? $node->label() : NULL;
|
||||
return addtoany_create_data($url, $title, $config);
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate data for AddToAny buttons.
|
||||
*
|
||||
* @param string $url
|
||||
* If present this will be used as the URL.
|
||||
* @param string $title
|
||||
* If present this will be used as the title. Use an empty string for no title
|
||||
* or NULL to use the current page title.
|
||||
* @param object $config
|
||||
* If present this will be used as custom config data. Use NULL for default
|
||||
* config data.
|
||||
*
|
||||
* @return array
|
||||
* The array with url, title, additional_html that will be send to Twig.
|
||||
*/
|
||||
function addtoany_create_data($url = NULL, $title = NULL, $config = NULL) {
|
||||
if (is_null($config)) {
|
||||
$config = \Drupal::config('addtoany.settings');
|
||||
}
|
||||
|
||||
$additional_html = rtrim($config->get('additional_html'));
|
||||
$universal_button_placement = $config->get('universal_button_placement');
|
||||
|
||||
$is_front = \Drupal::service('path.matcher')->isFrontPage();
|
||||
|
||||
// Default to <front> or the current path.
|
||||
if (!isset($url)) {
|
||||
// Use <front> for the front page to avoid '/node' as the final URL,
|
||||
// otherwise use current path.
|
||||
$url = ($is_front) ? Url::fromRoute('<front>')
|
||||
->setAbsolute()
|
||||
->toString() : Url::fromRoute('<current>')->setAbsolute()->toString();
|
||||
}
|
||||
else {
|
||||
// Sanitize and encode URL for HTML output.
|
||||
$url = UrlHelper::stripDangerousProtocols($url);
|
||||
}
|
||||
|
||||
// Default to the current title if available, otherwise use the site name.
|
||||
if (!isset($title)) {
|
||||
$site_name = \Drupal::config('system.site')->get('name');
|
||||
|
||||
if ($is_front) {
|
||||
$title = $site_name;
|
||||
}
|
||||
else {
|
||||
$request = \Drupal::request();
|
||||
$route_match = \Drupal::routeMatch();
|
||||
$title = \Drupal::service('title_resolver')
|
||||
->getTitle($request, $route_match->getRouteObject());
|
||||
// Expecting array|string|null from getTitle.
|
||||
if (is_array($title)) {
|
||||
$title['#allowed_tags'] = [];
|
||||
$title = \Drupal::service('renderer')->renderPlain($title);
|
||||
}
|
||||
}
|
||||
|
||||
$title = (empty($title)) ? $site_name : $title;
|
||||
}
|
||||
|
||||
$buttons_size = $config->get('buttons_size');
|
||||
// Must be a 3 digit positive integer.
|
||||
$buttons_size = (
|
||||
$buttons_size !== '32' && strlen($buttons_size) <= 3 && $buttons_size !== ''
|
||||
&& is_numeric($buttons_size) && intval($buttons_size) == $buttons_size && $buttons_size > 0
|
||||
) ? $buttons_size : '32';
|
||||
|
||||
$button_setting = $config->get('universal_button');
|
||||
|
||||
if ($button_setting == 'custom') {
|
||||
$button_image = UrlHelper::stripDangerousProtocols($config->get('custom_universal_button'));
|
||||
}
|
||||
|
||||
$info = [
|
||||
'link_url' => $url,
|
||||
'link_title' => $title,
|
||||
'buttons_size' => $buttons_size,
|
||||
'button_setting' => $button_setting,
|
||||
'button_image' => isset($button_image) ? $button_image : '',
|
||||
'universal_button_placement' => $universal_button_placement,
|
||||
'addtoany_html' => $additional_html,
|
||||
];
|
||||
|
||||
return $info;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
# Permissions for the addtoany module
|
||||
'administer addtoany':
|
||||
title: 'Administer AddToAny'
|
||||
description: 'Perform administration tasks for the AddToAny module.'
|
||||
@@ -0,0 +1,7 @@
|
||||
addtoany.admin_settings:
|
||||
path: '/admin/config/services/addtoany'
|
||||
defaults:
|
||||
_form: '\Drupal\addtoany\Form\AddToAnySettingsForm'
|
||||
_title: 'AddToAny'
|
||||
requirements:
|
||||
_permission: 'administer addtoany'
|
||||
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* @file
|
||||
* Views integration for AddToAny.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Implements hook_views_data_alter().
|
||||
*/
|
||||
function addtoany_views_data_alter(array &$data) {
|
||||
// Add the addtoany link to the node fields.
|
||||
$data['node']['addtoany_share'] = [
|
||||
'title' => t('AddToAny share buttons'),
|
||||
'field' => [
|
||||
'title' => t('AddToAny share buttons'),
|
||||
'help' => t('Provide share buttons for sharing the content.'),
|
||||
'id' => 'node_addtoany_share',
|
||||
],
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
buttons_size: 32
|
||||
additional_html: |
|
||||
<a class="a2a_button_facebook"></a>
|
||||
<a class="a2a_button_twitter"></a>
|
||||
<a class="a2a_button_google_plus"></a>
|
||||
additional_css: ''
|
||||
additional_js: ''
|
||||
universal_button: default
|
||||
custom_universal_button: ''
|
||||
universal_button_placement: before
|
||||
no_3p: false
|
||||
@@ -0,0 +1,28 @@
|
||||
# Schema file for the configuration files of the addtoany module.
|
||||
addtoany.settings:
|
||||
type: config_object
|
||||
label: 'AddToAny Settings'
|
||||
mapping:
|
||||
buttons_size:
|
||||
type: integer
|
||||
additional_html:
|
||||
type: text
|
||||
label: 'Additional HTML'
|
||||
additional_css:
|
||||
type: string
|
||||
label: 'Additional CSS'
|
||||
additional_js:
|
||||
type: string
|
||||
label: 'Additional JS'
|
||||
universal_button:
|
||||
type: string
|
||||
label: 'Universal Button Type'
|
||||
custom_universal_button:
|
||||
type: uri
|
||||
lable: 'Custom button URL'
|
||||
universal_button_placement:
|
||||
type: string
|
||||
label: 'Universal Button Placement'
|
||||
no_3p:
|
||||
type: boolean
|
||||
label: 'Disable 3rd Party Cookies'
|
||||
@@ -0,0 +1,7 @@
|
||||
.addtoany-round-icon {
|
||||
border-radius: 14%;
|
||||
}
|
||||
|
||||
.addtoany-universal-button-option img {
|
||||
vertical-align: middle;
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
.addtoany {
|
||||
display: inline;
|
||||
}
|
||||
.addtoany_list {
|
||||
display: inline;
|
||||
line-height: 16px;
|
||||
}
|
||||
.addtoany_list > a,
|
||||
.addtoany_list a img,
|
||||
.addtoany_list a > span {
|
||||
vertical-align: middle;
|
||||
}
|
||||
.addtoany_list > a {
|
||||
border: 0;
|
||||
display: inline-block;
|
||||
font-size: 16px;
|
||||
padding: 0 4px;
|
||||
}
|
||||
.addtoany_list.a2a_kit_size_32 > a {
|
||||
font-size: 32px;
|
||||
}
|
||||
.addtoany_list .a2a_counter img {
|
||||
float: left;
|
||||
}
|
||||
.addtoany_list a span.a2a_img {
|
||||
display: inline-block;
|
||||
height: 16px;
|
||||
opacity: 1;
|
||||
overflow: hidden;
|
||||
width: 16px;
|
||||
}
|
||||
.addtoany_list a span {
|
||||
display: inline-block;
|
||||
float: none;
|
||||
}
|
||||
.addtoany_list.a2a_kit_size_32 a > span {
|
||||
border-radius: 4px;
|
||||
height: 32px;
|
||||
line-height: 32px;
|
||||
opacity: 1;
|
||||
width: 32px;
|
||||
}
|
||||
.addtoany_list a:hover:hover img,
|
||||
.addtoany_list a:hover span {
|
||||
opacity: .7;
|
||||
}
|
||||
.addtoany_list a.addtoany_share_save img {
|
||||
border: 0;
|
||||
width: auto;
|
||||
height: auto;
|
||||
}
|
||||
.addtoany_list a .a2a_count {
|
||||
position: relative;
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 104 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32"><path fill="#0166FF" d="M0 0h32v32H0z"/><g fill="#FFF"><path d="M14 7h4v18h-4z"/><path d="M7 14h18v4H7z"/></g></svg>
|
||||
|
After Width: | Height: | Size: 179 B |
@@ -0,0 +1,33 @@
|
||||
(function ($) {
|
||||
'use strict';
|
||||
Drupal.behaviors.addtoany = {
|
||||
attach: function (context, settings) {
|
||||
|
||||
|
||||
// Initial page setup
|
||||
|
||||
var addtoany_icon = $('input[name="addtoany_universal_button"]').next('label').find('img:first');
|
||||
var initial_icon_size_int = parseInt($('input[name="addtoany_buttons_size"]').val());
|
||||
|
||||
// Set the A2A icon's size to match selected Icon Size
|
||||
addtoany_icon.height(initial_icon_size_int).width(initial_icon_size_int);
|
||||
|
||||
|
||||
// Bring attention to large A2A icon option
|
||||
// because the universal button will likely be changed to match the other icons
|
||||
// (Drupal #states can't handle this)
|
||||
$('input[name="addtoany_buttons_size"]').change(function () {
|
||||
|
||||
var icon_size = $(this).val();
|
||||
var icon_size_int = parseInt(icon_size);
|
||||
|
||||
// Set the A2A icon's size to match selected Icon Size
|
||||
addtoany_icon.height(icon_size_int).width(icon_size_int);
|
||||
|
||||
});
|
||||
|
||||
|
||||
}
|
||||
};
|
||||
|
||||
}(jQuery));
|
||||
@@ -0,0 +1,14 @@
|
||||
/* global a2a*/
|
||||
(function (Drupal) {
|
||||
'use strict';
|
||||
|
||||
Drupal.behaviors.addToAny = {
|
||||
attach: function (context, settings) {
|
||||
// If not the full document (it's probably AJAX), and window.a2a exists
|
||||
if (context !== document && window.a2a) {
|
||||
a2a.init_all('page'); // Init all uninitiated AddToAny instances
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
})(Drupal);
|
||||
@@ -0,0 +1,216 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\addtoany\Form;
|
||||
|
||||
use Drupal\Core\Form\ConfigFormBase;
|
||||
use Drupal\Core\Form\FormStateInterface;
|
||||
use Drupal\Core\Extension\ModuleHandler;
|
||||
use Symfony\Component\DependencyInjection\ContainerInterface;
|
||||
|
||||
/**
|
||||
* Configure AddToAny settings for this site.
|
||||
*/
|
||||
class AddToAnySettingsForm extends ConfigFormBase {
|
||||
/**
|
||||
* Drupal\Core\Extension\ModuleHandler definition.
|
||||
*
|
||||
* @var Drupal\Core\Extension\ModuleHandler
|
||||
*/
|
||||
protected $moduleHandler;
|
||||
|
||||
/**
|
||||
* Constructs a AddToAnySettingsForm object.
|
||||
*
|
||||
* @param \Drupal\Core\Extension\ModuleHandler $module_handler
|
||||
* The factory for configuration objects.
|
||||
*/
|
||||
public function __construct(ModuleHandler $module_handler) {
|
||||
$this->moduleHandler = $module_handler;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public static function create(ContainerInterface $container) {
|
||||
return new static(
|
||||
$container->get('module_handler')
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function getFormId() {
|
||||
return 'addtoany_settings_form';
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function getEditableConfigNames() {
|
||||
return [
|
||||
'addtoany.settings',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function buildForm(array $form, FormStateInterface $form_state) {
|
||||
|
||||
global $base_path;
|
||||
|
||||
$addtoany_settings = $this->config('addtoany.settings');
|
||||
|
||||
$button_img = '<img src="' . $base_path . drupal_get_path('module', 'addtoany') . '/images/%s" width="%d" height="%d"%s />';
|
||||
|
||||
$button_options = [
|
||||
'default' => sprintf($button_img, 'a2a_32_32.svg', 32, 32, ' class="addtoany-round-icon"'),
|
||||
'custom' => $this->t('Custom button'),
|
||||
'none' => $this->t('None'),
|
||||
];
|
||||
|
||||
$attributes_for_code = [
|
||||
'autocapitalize' => ['off'],
|
||||
'autocomplete' => ['off'],
|
||||
'autocorrect' => ['off'],
|
||||
'spellcheck' => ['false'],
|
||||
];
|
||||
|
||||
// Attach CSS and JS.
|
||||
$form['#attached']['library'][] = 'addtoany/addtoany.admin';
|
||||
|
||||
$form['addtoany_button_settings'] = [
|
||||
'#type' => 'details',
|
||||
'#title' => $this->t('Buttons'),
|
||||
'#open' => TRUE,
|
||||
];
|
||||
$form['addtoany_button_settings']['addtoany_buttons_size'] = [
|
||||
'#type' => 'number',
|
||||
'#title' => $this->t('Icon size'),
|
||||
'#field_suffix' => ' ' . $this->t('pixels'),
|
||||
'#default_value' => $addtoany_settings->get('buttons_size'),
|
||||
'#size' => 10,
|
||||
'#maxlength' => 3,
|
||||
'#min' => 8,
|
||||
'#max' => 999,
|
||||
'#required' => TRUE,
|
||||
];
|
||||
$form['addtoany_button_settings']['addtoany_service_button_settings'] = [
|
||||
'#type' => 'details',
|
||||
'#title' => $this->t('Service Buttons'),
|
||||
'#collapsible' => TRUE,
|
||||
'#collapsed' => TRUE,
|
||||
];
|
||||
$form['addtoany_button_settings']['addtoany_service_button_settings']['addtoany_additional_html'] = [
|
||||
'#type' => 'textarea',
|
||||
'#title' => $this->t('Service Buttons HTML code'),
|
||||
'#default_value' => $addtoany_settings->get('additional_html'),
|
||||
'#description' => $this->t('You can add HTML code to display customized <a href="https://www.addtoany.com/buttons/customize/drupal/standalone_services" target="_blank">standalone service buttons</a> next to each universal share button. For example: <br /> <code><a class="a2a_button_facebook"></a><br /><a class="a2a_button_twitter"></a><br /><a class="a2a_button_pinterest"></a></code>
|
||||
'),
|
||||
'#attributes' => $attributes_for_code,
|
||||
];
|
||||
$form['addtoany_button_settings']['universal_button'] = [
|
||||
'#type' => 'details',
|
||||
'#title' => $this->t('Universal Button'),
|
||||
'#collapsible' => TRUE,
|
||||
'#collapsed' => TRUE,
|
||||
/* #states workaround in addtoany.admin.js */
|
||||
];
|
||||
$form['addtoany_button_settings']['universal_button']['addtoany_universal_button'] = [
|
||||
'#type' => 'radios',
|
||||
'#title' => $this->t('Button'),
|
||||
'#default_value' => $addtoany_settings->get('universal_button'),
|
||||
'#attributes' => ['class' => ['addtoany-universal-button-option']],
|
||||
'#options' => $button_options,
|
||||
];
|
||||
$form['addtoany_button_settings']['universal_button']['addtoany_custom_universal_button'] = [
|
||||
'#type' => 'textfield',
|
||||
'#title' => $this->t('Custom button URL'),
|
||||
'#default_value' => $addtoany_settings->get('custom_universal_button'),
|
||||
'#description' => $this->t('URL of the button image. Example: http://example.com/share.png'),
|
||||
'#states' => [
|
||||
// Show only if custom button is selected.
|
||||
'visible' => [
|
||||
':input[name="addtoany_universal_button"]' => ['value' => 'custom'],
|
||||
],
|
||||
],
|
||||
];
|
||||
$form['addtoany_button_settings']['universal_button']['addtoany_universal_button_placement'] = [
|
||||
'#type' => 'radios',
|
||||
'#title' => $this->t('Button placement'),
|
||||
'#default_value' => $addtoany_settings->get('universal_button_placement'),
|
||||
'#options' => [
|
||||
'after' => $this->t('After the service buttons'),
|
||||
'before' => $this->t('Before the service buttons'),
|
||||
],
|
||||
'#states' => [
|
||||
// Hide when universal sharing is disabled.
|
||||
'invisible' => [
|
||||
':input[name="addtoany_universal_button"]' => ['value' => 'none'],
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
$form['addtoany_additional_settings'] = [
|
||||
'#type' => 'details',
|
||||
'#title' => $this->t('Additional options'),
|
||||
'#collapsible' => TRUE,
|
||||
'#collapsed' => TRUE,
|
||||
];
|
||||
$form['addtoany_additional_settings']['addtoany_additional_js'] = [
|
||||
'#type' => 'textarea',
|
||||
'#title' => $this->t('Additional JavaScript'),
|
||||
'#default_value' => $addtoany_settings->get('additional_js'),
|
||||
'#description' => $this->t('You can add special JavaScript code for AddToAny. See <a href="https://www.addtoany.com/buttons/customize/drupal" target="_blank">AddToAny documentation</a>.'),
|
||||
'#attributes' => $attributes_for_code,
|
||||
];
|
||||
$form['addtoany_additional_settings']['addtoany_additional_css'] = [
|
||||
'#type' => 'textarea',
|
||||
'#title' => $this->t('Additional CSS'),
|
||||
'#default_value' => $addtoany_settings->get('additional_css'),
|
||||
'#description' => $this->t('You can add special CSS code for AddToAny. See <a href="https://www.addtoany.com/buttons/customize/drupal" target="_blank">AddToAny documentation</a>.'),
|
||||
'#attributes' => $attributes_for_code,
|
||||
];
|
||||
$form['addtoany_additional_settings']['addtoany_no_3p'] = [
|
||||
'#type' => 'checkbox',
|
||||
'#title' => $this->t('Disable 3rd party cookies'),
|
||||
'#default_value' => $addtoany_settings->get('no_3p'),
|
||||
'#description' => $this->t('Disabling may affect analytics and limit some functionality.'),
|
||||
];
|
||||
|
||||
if ($this->moduleHandler->moduleExists('token')) {
|
||||
$form['tokens'] = [
|
||||
'#theme' => 'token_tree_link',
|
||||
'#token_types' => ['node'],
|
||||
'#global_types' => TRUE,
|
||||
'#click_insert' => TRUE,
|
||||
'#show_restricted' => FALSE,
|
||||
'#recursion_limit' => 3,
|
||||
'#text' => $this->t('Browse available tokens'),
|
||||
];
|
||||
}
|
||||
|
||||
return parent::buildForm($form, $form_state);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function submitForm(array &$form, FormStateInterface $form_state) {
|
||||
$values = $form_state->getValues();
|
||||
$this->config('addtoany.settings')
|
||||
->set('additional_css', $values['addtoany_additional_css'])
|
||||
->set('additional_html', $values['addtoany_additional_html'])
|
||||
->set('additional_js', $values['addtoany_additional_js'])
|
||||
->set('buttons_size', $values['addtoany_buttons_size'])
|
||||
->set('custom_universal_button', $values['addtoany_custom_universal_button'])
|
||||
->set('universal_button', $values['addtoany_universal_button'])
|
||||
->set('universal_button_placement', $values['addtoany_universal_button_placement'])
|
||||
->set('no_3p', $values['addtoany_no_3p'])
|
||||
->save();
|
||||
|
||||
parent::submitForm($form, $form_state);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\addtoany\Plugin\Block;
|
||||
|
||||
use Drupal\Core\Block\BlockBase;
|
||||
use Drupal\node\Entity\Node;
|
||||
|
||||
/**
|
||||
* Provides an 'AddToAny' block.
|
||||
*
|
||||
* @Block(
|
||||
* id = "addtoany_block",
|
||||
* admin_label = @Translation("AddToAny buttons"),
|
||||
* )
|
||||
*/
|
||||
class AddToAnyBlock extends BlockBase {
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function build() {
|
||||
$node = \Drupal::routeMatch()->getParameter('node');
|
||||
if (is_numeric($node)) {
|
||||
$node = Node::load($node);
|
||||
}
|
||||
$data = addtoany_create_entity_data($node);
|
||||
return [
|
||||
'#addtoany_html' => \Drupal::token()->replace($data['addtoany_html'], ['node' => $node]),
|
||||
'#link_url' => $data['link_url'],
|
||||
'#link_title' => $data['link_title'],
|
||||
'#button_setting' => $data['button_setting'],
|
||||
'#button_image' => $data['button_image'],
|
||||
'#universal_button_placement' => $data['universal_button_placement'],
|
||||
'#buttons_size' => $data['buttons_size'],
|
||||
'#theme' => 'addtoany_standard',
|
||||
'#cache' => [
|
||||
'contexts' => ['url'],
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\addtoany\Plugin\views\field;
|
||||
|
||||
use Drupal\views\Plugin\views\field\FieldPluginBase;
|
||||
use Drupal\views\ResultRow;
|
||||
|
||||
/**
|
||||
* Field handler to flag the node type.
|
||||
*
|
||||
* @ingroup views_field_handlers
|
||||
*
|
||||
* @ViewsField("node_addtoany_share")
|
||||
*/
|
||||
class NodeAddToAnyShare extends FieldPluginBase {
|
||||
|
||||
/**
|
||||
* @{inheritdoc}
|
||||
*/
|
||||
public function query() {
|
||||
// Leave empty to avoid a query on this field.
|
||||
}
|
||||
|
||||
/**
|
||||
* @{inheritdoc}
|
||||
*/
|
||||
public function render(ResultRow $values) {
|
||||
$entity = $values->_entity;
|
||||
if ($entity->access('view')) {
|
||||
$data = addtoany_create_entity_data($entity);
|
||||
return [
|
||||
'#addtoany_html' => \Drupal::token()->replace($data['addtoany_html'], ['node' => $entity]),
|
||||
'#link_url' => $data['link_url'],
|
||||
'#link_title' => $data['link_title'],
|
||||
'#button_setting' => $data['button_setting'],
|
||||
'#button_image' => $data['button_image'],
|
||||
'#universal_button_placement' => $data['universal_button_placement'],
|
||||
'#buttons_size' => $data['buttons_size'],
|
||||
'#theme' => 'addtoany_standard',
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
{#
|
||||
/**
|
||||
* @file
|
||||
* Default theme implementation to standard AddToAny buttons.
|
||||
*
|
||||
* Available variables:
|
||||
* - addtoany_html: HTML for AddToAny buttons.
|
||||
* - button_image: URL for universal button.
|
||||
* - button_setting: Setting of button.
|
||||
* - button_size: Size of buttons.
|
||||
* - universal_button_placement: Value of 'before' or 'after' to place button.
|
||||
* - link_url: Value of URL to share.
|
||||
* - link_title: Value of page title to share.
|
||||
*
|
||||
* @ingroup themeable
|
||||
*/
|
||||
#}
|
||||
{# Remove whitespace between tags for even spacing between buttons. #}
|
||||
{% spaceless %}
|
||||
|
||||
{% if button_setting != 'none' %}
|
||||
{% set universal_button %}
|
||||
<a class="a2a_dd addtoany_share" href="https://www.addtoany.com/share#url={{ link_url|url_encode }}&title={{ link_title|url_encode }}">
|
||||
{% if button_image %}
|
||||
<img src="{{ button_image }}">
|
||||
{% endif %}
|
||||
</a>
|
||||
{% endset %}
|
||||
{% endif %}
|
||||
|
||||
<span class="a2a_kit a2a_kit_size_{{ buttons_size }} addtoany_list" data-a2a-url="{{ link_url }}" data-a2a-title="{{ link_title }}">
|
||||
{% if universal_button_placement == 'before' %}
|
||||
{{ universal_button }}
|
||||
{% endif %}
|
||||
|
||||
{% if addtoany_html %}
|
||||
{{ addtoany_html|raw }}
|
||||
{% endif %}
|
||||
|
||||
{% if universal_button_placement == 'after' %}
|
||||
{{ universal_button }}
|
||||
{% endif %}
|
||||
</span>
|
||||
|
||||
{% endspaceless %}
|
||||
@@ -0,0 +1,40 @@
|
||||
---
|
||||
language: php
|
||||
php: '7.1'
|
||||
services: docker
|
||||
|
||||
env:
|
||||
DOCKER_COMPOSE_VERSION: 1.13.0
|
||||
|
||||
before_install:
|
||||
# List available docker-engine versions.
|
||||
- apt-cache madison docker-engine
|
||||
|
||||
# Upgrade docker.
|
||||
- curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
|
||||
- sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"
|
||||
- sudo apt-get update
|
||||
- sudo apt-get -y install docker-ce
|
||||
|
||||
# Upgrade docker-compose.
|
||||
- sudo rm /usr/local/bin/docker-compose
|
||||
- curl -L https://github.com/docker/compose/releases/download/${DOCKER_COMPOSE_VERSION}/docker-compose-`uname -s`-`uname -m` > docker-compose
|
||||
- chmod +x docker-compose
|
||||
- sudo mv docker-compose /usr/local/bin
|
||||
|
||||
# Pull container.
|
||||
- docker pull geerlingguy/drupal-vm:latest
|
||||
|
||||
script:
|
||||
# Build environment and install Honeypot.
|
||||
- docker-compose up -d
|
||||
- docker exec honeypot install-drupal
|
||||
- docker exec honeypot ln -s /opt/honeypot/ /var/www/drupalvm/drupal/web/modules/honeypot
|
||||
- docker exec honeypot bash -c 'cd /var/www/drupalvm/drupal/web; drush en -y honeypot simpletest'
|
||||
|
||||
# Fix permissions on the simpletest directories.
|
||||
- docker exec honeypot chown -R www-data:www-data /var/www/drupalvm/drupal/web/sites/simpletest
|
||||
- docker exec honeypot chown -R www-data:www-data /var/www/drupalvm/drupal/web/sites/default/files
|
||||
|
||||
# Run module tests.
|
||||
- docker exec honeypot bash -c 'sudo -u www-data php /var/www/drupalvm/drupal/web/core/scripts/run-tests.sh --verbose --module honeypot --url http://local.drupalhoneypot.com/'
|
||||
@@ -0,0 +1,339 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 2, June 1991
|
||||
|
||||
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
|
||||
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The licenses for most software are designed to take away your
|
||||
freedom to share and change it. By contrast, the GNU General Public
|
||||
License is intended to guarantee your freedom to share and change free
|
||||
software--to make sure the software is free for all its users. This
|
||||
General Public License applies to most of the Free Software
|
||||
Foundation's software and to any other program whose authors commit to
|
||||
using it. (Some other Free Software Foundation software is covered by
|
||||
the GNU Lesser General Public License instead.) You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
this service if you wish), that you receive source code or can get it
|
||||
if you want it, that you can change the software or use pieces of it
|
||||
in new free programs; and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to make restrictions that forbid
|
||||
anyone to deny you these rights or to ask you to surrender the rights.
|
||||
These restrictions translate to certain responsibilities for you if you
|
||||
distribute copies of the software, or if you modify it.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must give the recipients all the rights that
|
||||
you have. You must make sure that they, too, receive or can get the
|
||||
source code. And you must show them these terms so they know their
|
||||
rights.
|
||||
|
||||
We protect your rights with two steps: (1) copyright the software, and
|
||||
(2) offer you this license which gives you legal permission to copy,
|
||||
distribute and/or modify the software.
|
||||
|
||||
Also, for each author's protection and ours, we want to make certain
|
||||
that everyone understands that there is no warranty for this free
|
||||
software. If the software is modified by someone else and passed on, we
|
||||
want its recipients to know that what they have is not the original, so
|
||||
that any problems introduced by others will not reflect on the original
|
||||
authors' reputations.
|
||||
|
||||
Finally, any free program is threatened constantly by software
|
||||
patents. We wish to avoid the danger that redistributors of a free
|
||||
program will individually obtain patent licenses, in effect making the
|
||||
program proprietary. To prevent this, we have made it clear that any
|
||||
patent must be licensed for everyone's free use or not licensed at all.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
|
||||
|
||||
0. This License applies to any program or other work which contains
|
||||
a notice placed by the copyright holder saying it may be distributed
|
||||
under the terms of this General Public License. The "Program", below,
|
||||
refers to any such program or work, and a "work based on the Program"
|
||||
means either the Program or any derivative work under copyright law:
|
||||
that is to say, a work containing the Program or a portion of it,
|
||||
either verbatim or with modifications and/or translated into another
|
||||
language. (Hereinafter, translation is included without limitation in
|
||||
the term "modification".) Each licensee is addressed as "you".
|
||||
|
||||
Activities other than copying, distribution and modification are not
|
||||
covered by this License; they are outside its scope. The act of
|
||||
running the Program is not restricted, and the output from the Program
|
||||
is covered only if its contents constitute a work based on the
|
||||
Program (independent of having been made by running the Program).
|
||||
Whether that is true depends on what the Program does.
|
||||
|
||||
1. You may copy and distribute verbatim copies of the Program's
|
||||
source code as you receive it, in any medium, provided that you
|
||||
conspicuously and appropriately publish on each copy an appropriate
|
||||
copyright notice and disclaimer of warranty; keep intact all the
|
||||
notices that refer to this License and to the absence of any warranty;
|
||||
and give any other recipients of the Program a copy of this License
|
||||
along with the Program.
|
||||
|
||||
You may charge a fee for the physical act of transferring a copy, and
|
||||
you may at your option offer warranty protection in exchange for a fee.
|
||||
|
||||
2. You may modify your copy or copies of the Program or any portion
|
||||
of it, thus forming a work based on the Program, and copy and
|
||||
distribute such modifications or work under the terms of Section 1
|
||||
above, provided that you also meet all of these conditions:
|
||||
|
||||
a) You must cause the modified files to carry prominent notices
|
||||
stating that you changed the files and the date of any change.
|
||||
|
||||
b) You must cause any work that you distribute or publish, that in
|
||||
whole or in part contains or is derived from the Program or any
|
||||
part thereof, to be licensed as a whole at no charge to all third
|
||||
parties under the terms of this License.
|
||||
|
||||
c) If the modified program normally reads commands interactively
|
||||
when run, you must cause it, when started running for such
|
||||
interactive use in the most ordinary way, to print or display an
|
||||
announcement including an appropriate copyright notice and a
|
||||
notice that there is no warranty (or else, saying that you provide
|
||||
a warranty) and that users may redistribute the program under
|
||||
these conditions, and telling the user how to view a copy of this
|
||||
License. (Exception: if the Program itself is interactive but
|
||||
does not normally print such an announcement, your work based on
|
||||
the Program is not required to print an announcement.)
|
||||
|
||||
These requirements apply to the modified work as a whole. If
|
||||
identifiable sections of that work are not derived from the Program,
|
||||
and can be reasonably considered independent and separate works in
|
||||
themselves, then this License, and its terms, do not apply to those
|
||||
sections when you distribute them as separate works. But when you
|
||||
distribute the same sections as part of a whole which is a work based
|
||||
on the Program, the distribution of the whole must be on the terms of
|
||||
this License, whose permissions for other licensees extend to the
|
||||
entire whole, and thus to each and every part regardless of who wrote it.
|
||||
|
||||
Thus, it is not the intent of this section to claim rights or contest
|
||||
your rights to work written entirely by you; rather, the intent is to
|
||||
exercise the right to control the distribution of derivative or
|
||||
collective works based on the Program.
|
||||
|
||||
In addition, mere aggregation of another work not based on the Program
|
||||
with the Program (or with a work based on the Program) on a volume of
|
||||
a storage or distribution medium does not bring the other work under
|
||||
the scope of this License.
|
||||
|
||||
3. You may copy and distribute the Program (or a work based on it,
|
||||
under Section 2) in object code or executable form under the terms of
|
||||
Sections 1 and 2 above provided that you also do one of the following:
|
||||
|
||||
a) Accompany it with the complete corresponding machine-readable
|
||||
source code, which must be distributed under the terms of Sections
|
||||
1 and 2 above on a medium customarily used for software interchange; or,
|
||||
|
||||
b) Accompany it with a written offer, valid for at least three
|
||||
years, to give any third party, for a charge no more than your
|
||||
cost of physically performing source distribution, a complete
|
||||
machine-readable copy of the corresponding source code, to be
|
||||
distributed under the terms of Sections 1 and 2 above on a medium
|
||||
customarily used for software interchange; or,
|
||||
|
||||
c) Accompany it with the information you received as to the offer
|
||||
to distribute corresponding source code. (This alternative is
|
||||
allowed only for noncommercial distribution and only if you
|
||||
received the program in object code or executable form with such
|
||||
an offer, in accord with Subsection b above.)
|
||||
|
||||
The source code for a work means the preferred form of the work for
|
||||
making modifications to it. For an executable work, complete source
|
||||
code means all the source code for all modules it contains, plus any
|
||||
associated interface definition files, plus the scripts used to
|
||||
control compilation and installation of the executable. However, as a
|
||||
special exception, the source code distributed need not include
|
||||
anything that is normally distributed (in either source or binary
|
||||
form) with the major components (compiler, kernel, and so on) of the
|
||||
operating system on which the executable runs, unless that component
|
||||
itself accompanies the executable.
|
||||
|
||||
If distribution of executable or object code is made by offering
|
||||
access to copy from a designated place, then offering equivalent
|
||||
access to copy the source code from the same place counts as
|
||||
distribution of the source code, even though third parties are not
|
||||
compelled to copy the source along with the object code.
|
||||
|
||||
4. You may not copy, modify, sublicense, or distribute the Program
|
||||
except as expressly provided under this License. Any attempt
|
||||
otherwise to copy, modify, sublicense or distribute the Program is
|
||||
void, and will automatically terminate your rights under this License.
|
||||
However, parties who have received copies, or rights, from you under
|
||||
this License will not have their licenses terminated so long as such
|
||||
parties remain in full compliance.
|
||||
|
||||
5. You are not required to accept this License, since you have not
|
||||
signed it. However, nothing else grants you permission to modify or
|
||||
distribute the Program or its derivative works. These actions are
|
||||
prohibited by law if you do not accept this License. Therefore, by
|
||||
modifying or distributing the Program (or any work based on the
|
||||
Program), you indicate your acceptance of this License to do so, and
|
||||
all its terms and conditions for copying, distributing or modifying
|
||||
the Program or works based on it.
|
||||
|
||||
6. Each time you redistribute the Program (or any work based on the
|
||||
Program), the recipient automatically receives a license from the
|
||||
original licensor to copy, distribute or modify the Program subject to
|
||||
these terms and conditions. You may not impose any further
|
||||
restrictions on the recipients' exercise of the rights granted herein.
|
||||
You are not responsible for enforcing compliance by third parties to
|
||||
this License.
|
||||
|
||||
7. If, as a consequence of a court judgment or allegation of patent
|
||||
infringement or for any other reason (not limited to patent issues),
|
||||
conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot
|
||||
distribute so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you
|
||||
may not distribute the Program at all. For example, if a patent
|
||||
license would not permit royalty-free redistribution of the Program by
|
||||
all those who receive copies directly or indirectly through you, then
|
||||
the only way you could satisfy both it and this License would be to
|
||||
refrain entirely from distribution of the Program.
|
||||
|
||||
If any portion of this section is held invalid or unenforceable under
|
||||
any particular circumstance, the balance of the section is intended to
|
||||
apply and the section as a whole is intended to apply in other
|
||||
circumstances.
|
||||
|
||||
It is not the purpose of this section to induce you to infringe any
|
||||
patents or other property right claims or to contest validity of any
|
||||
such claims; this section has the sole purpose of protecting the
|
||||
integrity of the free software distribution system, which is
|
||||
implemented by public license practices. Many people have made
|
||||
generous contributions to the wide range of software distributed
|
||||
through that system in reliance on consistent application of that
|
||||
system; it is up to the author/donor to decide if he or she is willing
|
||||
to distribute software through any other system and a licensee cannot
|
||||
impose that choice.
|
||||
|
||||
This section is intended to make thoroughly clear what is believed to
|
||||
be a consequence of the rest of this License.
|
||||
|
||||
8. If the distribution and/or use of the Program is restricted in
|
||||
certain countries either by patents or by copyrighted interfaces, the
|
||||
original copyright holder who places the Program under this License
|
||||
may add an explicit geographical distribution limitation excluding
|
||||
those countries, so that distribution is permitted only in or among
|
||||
countries not thus excluded. In such case, this License incorporates
|
||||
the limitation as if written in the body of this License.
|
||||
|
||||
9. The Free Software Foundation may publish revised and/or new versions
|
||||
of the General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the Program
|
||||
specifies a version number of this License which applies to it and "any
|
||||
later version", you have the option of following the terms and conditions
|
||||
either of that version or of any later version published by the Free
|
||||
Software Foundation. If the Program does not specify a version number of
|
||||
this License, you may choose any version ever published by the Free Software
|
||||
Foundation.
|
||||
|
||||
10. If you wish to incorporate parts of the Program into other free
|
||||
programs whose distribution conditions are different, write to the author
|
||||
to ask for permission. For software which is copyrighted by the Free
|
||||
Software Foundation, write to the Free Software Foundation; we sometimes
|
||||
make exceptions for this. Our decision will be guided by the two goals
|
||||
of preserving the free status of all derivatives of our free software and
|
||||
of promoting the sharing and reuse of software generally.
|
||||
|
||||
NO WARRANTY
|
||||
|
||||
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
|
||||
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
|
||||
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
|
||||
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
|
||||
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
|
||||
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
|
||||
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
|
||||
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
|
||||
REPAIR OR CORRECTION.
|
||||
|
||||
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
|
||||
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
|
||||
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
|
||||
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
|
||||
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
|
||||
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
|
||||
POSSIBILITY OF SUCH DAMAGES.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
convey the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software; you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation; either version 2 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License along
|
||||
with this program; if not, write to the Free Software Foundation, Inc.,
|
||||
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program is interactive, make it output a short notice like this
|
||||
when it starts in an interactive mode:
|
||||
|
||||
Gnomovision version 69, Copyright (C) year name of author
|
||||
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, the commands you use may
|
||||
be called something other than `show w' and `show c'; they could even be
|
||||
mouse-clicks or menu items--whatever suits your program.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or your
|
||||
school, if any, to sign a "copyright disclaimer" for the program, if
|
||||
necessary. Here is a sample; alter the names:
|
||||
|
||||
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
|
||||
`Gnomovision' (which makes passes at compilers) written by James Hacker.
|
||||
|
||||
<signature of Ty Coon>, 1 April 1989
|
||||
Ty Coon, President of Vice
|
||||
|
||||
This General Public License does not permit incorporating your program into
|
||||
proprietary programs. If your program is a subroutine library, you may
|
||||
consider it more useful to permit linking proprietary applications with the
|
||||
library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License.
|
||||
@@ -0,0 +1,56 @@
|
||||
|
||||
# Honeypot
|
||||
|
||||
[](https://travis-ci.org/geerlingguy/drupal-honeypot)
|
||||
|
||||
|
||||
## Installation
|
||||
|
||||
To install this module, `composer require` it, or place it in your modules
|
||||
folder and enable it on the modules page.
|
||||
|
||||
|
||||
## Configuration
|
||||
|
||||
All settings for this module are on the Honeypot configuration page, under the
|
||||
Configuration section, in the Content authoring settings. You can visit the
|
||||
configuration page directly at admin/config/content/honeypot.
|
||||
|
||||
Note that, when testing Honeypot on your website, make sure you're not logged in
|
||||
as an administrative user or user 1; Honeypot allows administrative users to
|
||||
bypass Honeypot protection, so by default, Honeypot will not be added to forms
|
||||
accessed by site administrators.
|
||||
|
||||
|
||||
## Use in Your Own Forms
|
||||
|
||||
If you want to add honeypot to your own forms, or to any form through your own
|
||||
module's hook_form_alter's, you can simply place the following function call
|
||||
inside your form builder function (or inside a hook_form_alter):
|
||||
|
||||
honeypot_add_form_protection(
|
||||
$form,
|
||||
$form_state,
|
||||
['honeypot', 'time_restriction']
|
||||
);
|
||||
|
||||
Note that you can enable or disable either the honeypot field, or the time
|
||||
restriction on the form by including or not including the option in the array.
|
||||
|
||||
|
||||
## Testing
|
||||
|
||||
Honeypot includes a `docker-compose.yml` file that can be used for testing purposes. To build a Drupal 8 environment for local testing, do the following:
|
||||
|
||||
1. Make sure you have Docker for Mac (or for whatever OS you're using) installed.
|
||||
2. Add the following entry to your `/etc/hosts` file: `192.168.22.33 local.drupalhoneypot.com`
|
||||
3. Run `docker-compose up -d` in this directory.
|
||||
4. Install Drupal: `docker exec honeypot install-drupal` (optionally provide a version after `install-drupal`).
|
||||
5. Link the honeypot module directory into the Drupal modules directory: `docker exec honeypot ln -s /opt/honeypot/ /var/www/drupalvm/drupal/web/modules/honeypot`
|
||||
6. Visit `http://local.drupalhoneypot.com/user` and log in using the admin credentials Drush displayed.
|
||||
|
||||
|
||||
## Credit
|
||||
|
||||
The Honeypot module was originally developed by Jeff Geerling of Midwestern Mac,
|
||||
LLC (midwesternmac.com), and sponsored by Flocknote (flocknote.com).
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"name": "drupal/honeypot",
|
||||
"description": "Mitigates spam form submissions using the honeypot method.",
|
||||
"type": "drupal-module",
|
||||
"license": "GPL-2.0+",
|
||||
"keywords": ["spam", "php", "form", "honeypot", "honeytrap", "deterrent"],
|
||||
"homepage": "https://www.drupal.org/project/honeypot",
|
||||
"minimum-stability": "dev",
|
||||
"authors": [
|
||||
{
|
||||
"name": "Jeff Geerling",
|
||||
"email": "geerlingguy@mac.com"
|
||||
}
|
||||
],
|
||||
"require": { }
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
unprotected_forms:
|
||||
- 'user_login_form'
|
||||
- 'search_form'
|
||||
- 'search_block_form'
|
||||
- 'views_exposed_form'
|
||||
- 'honeypot_settings_form'
|
||||
protect_all_forms: false
|
||||
log: false
|
||||
element_name: 'url'
|
||||
time_limit: 5
|
||||
expire: 300
|
||||
form_settings:
|
||||
user_register_form: false
|
||||
user_pass: false
|
||||
feedback_contact_message_form: false
|
||||
_contact_message_form: false
|
||||
@@ -0,0 +1,59 @@
|
||||
id: honeypot
|
||||
module: honeypot
|
||||
label: Honeypot
|
||||
langcode: en
|
||||
routes:
|
||||
- route_name: honeypot.config
|
||||
tips:
|
||||
honeypot-configuration:
|
||||
id: honeypot-configuration
|
||||
plugin: text
|
||||
label: Honeypot
|
||||
weight: -10
|
||||
body: "Congratulations on installing Honeypot on your site! With just a few clicks, you can have your site well-protected against automated spam bots.\r\n\r\nClick Next to be guided through this configuration page."
|
||||
location: top
|
||||
protect-all-forms:
|
||||
id: protect-all-forms
|
||||
plugin: text
|
||||
label: 'Protect all forms'
|
||||
weight: -9
|
||||
attributes:
|
||||
data-id: edit-protect-all-forms
|
||||
body: "Protecting all the forms is the easiest way to quickly cut down on spam on your site, but doing this disables Drupal's caching for every page where a form is displayed.\r\n\r\nNote: If you have the honeypot time limit enabled, this option may cause issues with Drupal Commerce product forms or similarly-sparse forms that are able to be completed in a very short time."
|
||||
location: bottom
|
||||
log-blocked-form-submissions:
|
||||
id: log-blocked-form-submissions
|
||||
plugin: text
|
||||
label: 'Log blocked form submissions'
|
||||
weight: -8
|
||||
attributes:
|
||||
data-id: edit-log
|
||||
body: 'Check this box to log every form submission using watchdog. If you have Database Logging enabled, you can view these log entries in the Recent log messages page under Reports.'
|
||||
location: bottom
|
||||
honeypot-element-name:
|
||||
id: honeypot-element-name
|
||||
plugin: text
|
||||
label: 'Honeypot Element Name'
|
||||
weight: -7
|
||||
attributes:
|
||||
data-id: edit-element-name
|
||||
body: 'Spam bots typically fill out any field they believe will help get links back to their site, so tempting them with a field named something like ''url'', ''homepage'', or ''link'' makes it hard for them to resist filling in the field—and easy to catch them in the trap and reject their submissions!'
|
||||
location: top
|
||||
honeypot-time-limit:
|
||||
id: honeypot-time-limit
|
||||
plugin: text
|
||||
label: 'Honeypot Time Limit'
|
||||
weight: -6
|
||||
attributes:
|
||||
data-id: edit-time-limit
|
||||
body: 'If you enter a positive value, Honeypot will require that all protected forms take at least that many seconds long to fill out. Most forms take at least 5-10 seconds to complete (if you''re a human), so setting this to a value < 5 will help protect against spam bots. Set to 0 to disable.'
|
||||
location: top
|
||||
honeypot-form-specific-settings:
|
||||
id: honeypot-form-specific-settings
|
||||
plugin: text
|
||||
label: 'Honeypot form-specific settings'
|
||||
weight: -5
|
||||
attributes:
|
||||
data-id: edit-form-settings
|
||||
body: 'If you would like to choose particular forms to be protected by Honeypot, check the forms you wish to protect in this section. Most common types of forms are available for protection.'
|
||||
location: top
|
||||
@@ -0,0 +1,28 @@
|
||||
honeypot.settings:
|
||||
type: config_object
|
||||
mapping:
|
||||
protect_all_forms:
|
||||
type: boolean
|
||||
label: 'Protect all forms'
|
||||
unprotected_forms:
|
||||
type: sequence
|
||||
label: 'Unprotected forms'
|
||||
sequence:
|
||||
type: string
|
||||
label: 'Unprotected form'
|
||||
log:
|
||||
type: boolean
|
||||
label: 'Log blocked form submissions'
|
||||
element_name:
|
||||
type: string
|
||||
label: 'Honeypot element name'
|
||||
time_limit:
|
||||
type: integer
|
||||
label: 'Honeypot time limit'
|
||||
expire:
|
||||
type: integer
|
||||
label: 'Expiration'
|
||||
form_settings:
|
||||
type: sequence
|
||||
sequence:
|
||||
type: boolean
|
||||
@@ -0,0 +1,34 @@
|
||||
version: "3"
|
||||
|
||||
services:
|
||||
|
||||
honeypot:
|
||||
image: geerlingguy/drupal-vm
|
||||
container_name: honeypot
|
||||
ports:
|
||||
- 80:80
|
||||
- 443:443
|
||||
privileged: true
|
||||
extra_hosts:
|
||||
local.drupalhoneypot.com: 127.0.0.1
|
||||
dns:
|
||||
- 8.8.8.8
|
||||
- 8.8.4.4
|
||||
volumes:
|
||||
# Switch to the commented line once Docker CE stable has the feature.
|
||||
- ./:/opt/honeypot/:rw
|
||||
# - ./:/opt/honeypot/:rw,delegated
|
||||
command: /lib/systemd/systemd
|
||||
networks:
|
||||
honeypot:
|
||||
ipv4_address: 192.168.22.33
|
||||
|
||||
networks:
|
||||
|
||||
honeypot:
|
||||
driver: bridge
|
||||
driver_opts:
|
||||
ip: 192.168.22.1
|
||||
ipam:
|
||||
config:
|
||||
- subnet: "192.168.22.0/16"
|
||||
@@ -0,0 +1,100 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* @file
|
||||
* API Functionality for Honeypot module.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @addtogroup hooks
|
||||
* @{
|
||||
*/
|
||||
|
||||
/**
|
||||
* Alter the honeypot protections added to a particular form.
|
||||
*
|
||||
* @param array $options
|
||||
* Protections that will be applied to the form. May be empty, or may include
|
||||
* 'honeypot' and/or 'time_restriction'.
|
||||
* @param array $form
|
||||
* The Form API form to which protections will be added.
|
||||
*/
|
||||
function hook_honeypot_form_protections_alter(array &$options, array $form) {
|
||||
// Add 'time_restriction' protection to 'mymodule-form' if it's not set.
|
||||
if ($form['form_id']['#value'] == 'mymodule_form' && !in_array('time_restriction', $options)) {
|
||||
$options[] = 'time_restriction';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* React to an addition of honeypot form protections for a given form_id.
|
||||
*
|
||||
* After honeypot has added its protections to a form, this hook will be called.
|
||||
* You can use this hook to track when and how many times certain protected
|
||||
* forms are displayed to certain users, or for other tracking purposes.
|
||||
*
|
||||
* @param array $options
|
||||
* Protections that were applied to the form. Includes 'honeypot' and/or
|
||||
* 'time_restriction'.
|
||||
* @param array $form
|
||||
* The Form API form to which protections were added.
|
||||
*/
|
||||
function hook_honeypot_add_form_protection(array $options, array $form) {
|
||||
if ($form['form_id']['#value'] == 'mymodule_form') {
|
||||
// Do something...
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* React to the rejection of a form submission.
|
||||
*
|
||||
* When honeypot rejects a form submission, it calls this hook with the form ID,
|
||||
* the user ID (0 if anonymous) of the user that was disallowed from submitting
|
||||
* the form, and the reason (type) for the rejection of the form submission.
|
||||
*
|
||||
* @param string $form_id
|
||||
* Form ID of the form the user was disallowed from submitting.
|
||||
* @param int $uid
|
||||
* 0 for anonymous users, otherwise the user ID of the user.
|
||||
* @param string $type
|
||||
* String indicating the reason the submission was blocked. Allowed values:
|
||||
* - honeypot: If honeypot field was filled in.
|
||||
* - honeypot_time: If form was completed before the configured time limit.
|
||||
*/
|
||||
function hook_honeypot_reject($form_id, $uid, $type) {
|
||||
if ($form_id == 'mymodule_form') {
|
||||
// Do something...
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Add time to the Honeypot time limit.
|
||||
*
|
||||
* In certain circumstances (for example, on forms routinely targeted by
|
||||
* spammers), you may want to add an additional time delay. You can use this
|
||||
* hook to return additional time (in seconds) to honeypot when it is calculates
|
||||
* the time limit for a particular form.
|
||||
*
|
||||
* @param int $honeypot_time_limit
|
||||
* The current honeypot time limit (in seconds), to which any additions you
|
||||
* return will be added.
|
||||
* @param array $form_values
|
||||
* Array of form values (may be empty).
|
||||
* @param int $number
|
||||
* Number of times the current user has already fallen into the honeypot trap.
|
||||
*
|
||||
* @return int
|
||||
* Additional time to add to the honeypot_time_limit, in seconds (integer).
|
||||
*/
|
||||
function hook_honeypot_time_limit($honeypot_time_limit, array $form_values, $number) {
|
||||
$additions = 0;
|
||||
// If 'some_interesting_value' is set in your form, add 10 seconds to limit.
|
||||
if (!empty($form_values['some_interesting_value']) && $form_values['some_interesting_value']) {
|
||||
$additions = 10;
|
||||
}
|
||||
return $additions;
|
||||
}
|
||||
|
||||
/**
|
||||
* @} End of "addtogroup hooks".
|
||||
*/
|
||||
@@ -0,0 +1,13 @@
|
||||
name: Honeypot
|
||||
type: module
|
||||
description: 'Mitigates spam form submissions using the honeypot method.'
|
||||
package: "Spam control"
|
||||
# core: 8.x
|
||||
configure: honeypot.config
|
||||
hidden: false
|
||||
|
||||
# Information added by Drupal.org packaging script on 2017-07-12
|
||||
version: '8.x-1.27'
|
||||
core: '8.x'
|
||||
project: 'honeypot'
|
||||
datestamp: 1499867346
|
||||
@@ -0,0 +1,74 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* @file
|
||||
* Contains install and update functions for Honeypot.
|
||||
*/
|
||||
|
||||
use Drupal\Core\Url;
|
||||
use Drupal\Core\Link;
|
||||
|
||||
/**
|
||||
* Implements hook_schema().
|
||||
*/
|
||||
function honeypot_schema() {
|
||||
$schema['honeypot_user'] = [
|
||||
'description' => 'Table that stores failed attempts to submit a form.',
|
||||
'fields' => [
|
||||
'uid' => [
|
||||
'description' => 'Foreign key to {users}.uid; uniquely identifies a Drupal user to whom this ACL data applies.',
|
||||
'type' => 'int',
|
||||
'unsigned' => TRUE,
|
||||
'not null' => TRUE,
|
||||
],
|
||||
'hostname' => [
|
||||
'type' => 'varchar',
|
||||
'length' => 128,
|
||||
'not null' => TRUE,
|
||||
'description' => 'Hostname of user that that triggered honeypot.',
|
||||
],
|
||||
'timestamp' => [
|
||||
'description' => 'Date/time when the form submission failed, as Unix timestamp.',
|
||||
'type' => 'int',
|
||||
'unsigned' => TRUE,
|
||||
'not null' => TRUE,
|
||||
],
|
||||
],
|
||||
'indexes' => [
|
||||
'uid' => ['uid'],
|
||||
'timestamp' => ['timestamp'],
|
||||
],
|
||||
];
|
||||
return $schema;
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements hook_install().
|
||||
*/
|
||||
function honeypot_install() {
|
||||
if (PHP_SAPI !== 'cli') {
|
||||
$config_url = Url::fromUri('base://admin/config/content/honeypot');
|
||||
drupal_set_message(t(
|
||||
'Honeypot installed successfully. Please <a href=":url">configure Honeypot</a> to protect your forms from spam bots.',
|
||||
[':url' => $config_url->toString()]
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements hook_uninstall().
|
||||
*/
|
||||
function honeypot_uninstall() {
|
||||
// Clear the bootstrap cache.
|
||||
\Drupal::cache('bootstrap')->deleteAll();
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds the 'hostname' column to the {honeypot_user} table.
|
||||
*/
|
||||
function honeypot_update_8100() {
|
||||
$schema = honeypot_schema();
|
||||
$spec = $schema['honeypot_user']['fields']['hostname'];
|
||||
$spec['initial'] = '';
|
||||
\Drupal::database()->schema()->addField('honeypot_user', 'hostname', $spec);
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
honeypot.config:
|
||||
title: Honeypot configuration
|
||||
description: 'Configure Honeypot spam prevention and the forms on which Honeypot will be used.'
|
||||
parent: system.admin_config_content
|
||||
route_name: honeypot.config
|
||||
@@ -0,0 +1,316 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* @file
|
||||
* Honeypot module, for deterring spam bots from completing Drupal forms.
|
||||
*/
|
||||
|
||||
use Drupal\Core\Form\FormStateInterface;
|
||||
use Drupal\Component\Utility\Crypt;
|
||||
|
||||
/**
|
||||
* Implements hook_cron().
|
||||
*/
|
||||
function honeypot_cron() {
|
||||
// Delete {honeypot_user} entries older than the value of honeypot_expire.
|
||||
$expire_limit = \Drupal::config('honeypot.settings')->get('expire');
|
||||
\Drupal::database()->delete('honeypot_user')
|
||||
->condition('timestamp', REQUEST_TIME - $expire_limit, '<')
|
||||
->execute();
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements hook_form_alter().
|
||||
*
|
||||
* Add Honeypot features to forms enabled in the Honeypot admin interface.
|
||||
*/
|
||||
function honeypot_form_alter(&$form, FormStateInterface $form_state, $form_id) {
|
||||
// Don't use for maintenance mode forms (install, update, etc.).
|
||||
if (defined('MAINTENANCE_MODE')) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Add a tag to all forms, so that if they are cached and honeypot
|
||||
// configuration is changed, the cached forms are invalidated and honeypot
|
||||
// protection can be re-evaluated.
|
||||
$form['#cache']['tags'][] = 'config:honeypot.settings';
|
||||
|
||||
// Get list of unprotected forms and setting for whether to protect all forms.
|
||||
$unprotected_forms = \Drupal::config('honeypot.settings')->get('unprotected_forms');
|
||||
$protect_all_forms = \Drupal::config('honeypot.settings')->get('protect_all_forms');
|
||||
|
||||
// If configured to protect all forms, add protection to every form.
|
||||
if ($protect_all_forms && !in_array($form_id, $unprotected_forms)) {
|
||||
// Don't protect system forms - only admins should have access, and system
|
||||
// forms may be programmatically submitted by drush and other modules.
|
||||
if (strpos($form_id, 'system_') === FALSE && strpos($form_id, 'search_') === FALSE && strpos($form_id, 'views_exposed_form_') === FALSE) {
|
||||
honeypot_add_form_protection($form, $form_state, ['honeypot', 'time_restriction']);
|
||||
}
|
||||
}
|
||||
|
||||
// Otherwise add form protection to admin-configured forms.
|
||||
elseif ($forms_to_protect = honeypot_get_protected_forms()) {
|
||||
foreach ($forms_to_protect as $protect_form_id) {
|
||||
// For most forms, do a straight check on the form ID.
|
||||
if ($form_id == $protect_form_id) {
|
||||
honeypot_add_form_protection($form, $form_state, ['honeypot', 'time_restriction']);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Build an array of all the protected forms on the site, by form_id.
|
||||
*/
|
||||
function honeypot_get_protected_forms() {
|
||||
$forms = &drupal_static(__FUNCTION__);
|
||||
|
||||
// If the data isn't already in memory, get from cache or look it up fresh.
|
||||
if (!isset($forms)) {
|
||||
if ($cache = \Drupal::cache()->get('honeypot_protected_forms')) {
|
||||
$forms = $cache->data;
|
||||
}
|
||||
else {
|
||||
$form_settings = \Drupal::config('honeypot.settings')->get('form_settings');
|
||||
if (!empty($form_settings)) {
|
||||
// Add each form that's enabled to the $forms array.
|
||||
foreach ($form_settings as $form_id => $enabled) {
|
||||
if ($enabled) {
|
||||
$forms[] = $form_id;
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
$forms = [];
|
||||
}
|
||||
|
||||
// Save the cached data.
|
||||
\Drupal::cache()->set('honeypot_protected_forms', $forms);
|
||||
}
|
||||
}
|
||||
|
||||
return $forms;
|
||||
}
|
||||
|
||||
/**
|
||||
* Form builder function to add different types of protection to forms.
|
||||
*
|
||||
* @param array $options
|
||||
* Array of options to be added to form. Currently accepts 'honeypot' and
|
||||
* 'time_restriction'.
|
||||
*/
|
||||
function honeypot_add_form_protection(&$form, FormStateInterface $form_state, array $options = []) {
|
||||
$account = \Drupal::currentUser();
|
||||
|
||||
// Allow other modules to alter the protections applied to this form.
|
||||
\Drupal::moduleHandler()->alter('honeypot_form_protections', $options, $form);
|
||||
|
||||
// Don't add any protections if the user can bypass the Honeypot.
|
||||
if ($account->hasPermission('bypass honeypot protection')) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Build the honeypot element.
|
||||
if (in_array('honeypot', $options)) {
|
||||
// Get the element name (default is generic 'url').
|
||||
$honeypot_element = \Drupal::config('honeypot.settings')->get('element_name');
|
||||
|
||||
// Build the honeypot element.
|
||||
$honeypot_class = $honeypot_element . '-textfield';
|
||||
$form[$honeypot_element] = [
|
||||
'#theme_wrappers' => [
|
||||
'container' => [
|
||||
'#id' => NULL,
|
||||
'#attributes' => [
|
||||
'class' => [
|
||||
$honeypot_class,
|
||||
],
|
||||
'style' => [
|
||||
'display: none !important;',
|
||||
],
|
||||
],
|
||||
],
|
||||
],
|
||||
'#type' => 'textfield',
|
||||
'#title' => t('Leave this field blank'),
|
||||
'#size' => 20,
|
||||
'#weight' => 100,
|
||||
'#attributes' => ['autocomplete' => 'off'],
|
||||
'#element_validate' => ['_honeypot_honeypot_validate'],
|
||||
];
|
||||
|
||||
}
|
||||
|
||||
// Set the time restriction for this form (if it's not disabled).
|
||||
if (in_array('time_restriction', $options) && \Drupal::config('honeypot.settings')->get('time_limit') != 0) {
|
||||
// Set the current time in a hidden value to be checked later.
|
||||
$input = $form_state->getUserInput();
|
||||
if (empty($input['honeypot_time'])) {
|
||||
$identifier = Crypt::randomBytesBase64();
|
||||
\Drupal::service('keyvalue.expirable')->get('honeypot_time_restriction')->set($identifier, time(), 3600*24);
|
||||
}
|
||||
else {
|
||||
$identifier = $input['honeypot_time'];
|
||||
}
|
||||
$form['honeypot_time'] = [
|
||||
'#type' => 'hidden',
|
||||
'#title' => t('Timestamp'),
|
||||
'#default_value' => $identifier,
|
||||
'#element_validate' => ['_honeypot_time_restriction_validate'],
|
||||
'#cache' => [
|
||||
'max-age' => 0,
|
||||
],
|
||||
];
|
||||
|
||||
// Disable page caching to make sure timestamp isn't cached.
|
||||
$account = \Drupal::currentUser();
|
||||
if ($account->id() == 0) {
|
||||
// TODO D8 - Use DIC? See: http://drupal.org/node/1539454
|
||||
// Should this now set 'omit_vary_cookie' instead?
|
||||
Drupal::service('page_cache_kill_switch')->trigger();
|
||||
}
|
||||
}
|
||||
|
||||
// Allow other modules to react to addition of form protection.
|
||||
if (!empty($options)) {
|
||||
\Drupal::moduleHandler()->invokeAll('honeypot_add_form_protection', [$options, $form]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate honeypot field.
|
||||
*/
|
||||
function _honeypot_honeypot_validate($element, FormStateInterface $form_state) {
|
||||
// Get the honeypot field value.
|
||||
$honeypot_value = $element['#value'];
|
||||
|
||||
// Make sure it's empty.
|
||||
if (!empty($honeypot_value)) {
|
||||
_honeypot_log($form_state->getValue('form_id'), 'honeypot');
|
||||
$form_state->setErrorByName('', t('There was a problem with your form submission. Please refresh the page and try again.'));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate honeypot's time restriction field.
|
||||
*/
|
||||
function _honeypot_time_restriction_validate($element, FormStateInterface $form_state) {
|
||||
if ($form_state->isProgrammed()) {
|
||||
// Don't do anything if the form was submitted programmatically.
|
||||
return;
|
||||
}
|
||||
|
||||
$triggering_element = $form_state->getTriggeringElement();
|
||||
// Don't do anything if the triggering element is a preview button.
|
||||
if ($triggering_element['#value'] == t('Preview')) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Get the time value.
|
||||
$identifier = $form_state->getValue('honeypot_time', FALSE);
|
||||
$honeypot_time = \Drupal::service('keyvalue.expirable')->get('honeypot_time_restriction')->get($identifier, 0);
|
||||
|
||||
// Get the honeypot_time_limit.
|
||||
$time_limit = honeypot_get_time_limit($form_state->getValues());
|
||||
|
||||
// Make sure current time - (time_limit + form time value) is greater than 0.
|
||||
// If not, throw an error.
|
||||
if (!$honeypot_time || REQUEST_TIME < ($honeypot_time + $time_limit)) {
|
||||
_honeypot_log($form_state->getValue('form_id'), 'honeypot_time');
|
||||
$time_limit = honeypot_get_time_limit();
|
||||
\Drupal::service('keyvalue.expirable')->get('honeypot_time_restriction')->set($identifier, REQUEST_TIME, 3600*24);
|
||||
$form_state->setErrorByName('', t('There was a problem with your form submission. Please wait @limit seconds and try again.', ['@limit' => $time_limit]));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Log blocked form submissions.
|
||||
*
|
||||
* @param string $form_id
|
||||
* Form ID for the form on which submission was blocked.
|
||||
* @param string $type
|
||||
* String indicating the reason the submission was blocked. Allowed values:
|
||||
* - honeypot: If honeypot field was filled in.
|
||||
* - honeypot_time: If form was completed before the configured time limit.
|
||||
*/
|
||||
function _honeypot_log($form_id, $type) {
|
||||
honeypot_log_failure($form_id, $type);
|
||||
if (\Drupal::config('honeypot.settings')->get('log')) {
|
||||
$variables = [
|
||||
'%form' => $form_id,
|
||||
'@cause' => ($type == 'honeypot') ? t('submission of a value in the honeypot field') : t('submission of the form in less than minimum required time'),
|
||||
];
|
||||
\Drupal::logger('honeypot')->notice(t('Blocked submission of %form due to @cause.', $variables));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Look up the time limit for the current user.
|
||||
*
|
||||
* @param array $form_values
|
||||
* Array of form values (optional).
|
||||
*/
|
||||
function honeypot_get_time_limit(array $form_values = []) {
|
||||
$account = \Drupal::currentUser();
|
||||
$honeypot_time_limit = \Drupal::config('honeypot.settings')->get('time_limit');
|
||||
|
||||
// Only calculate time limit if honeypot_time_limit has a value > 0.
|
||||
if ($honeypot_time_limit) {
|
||||
$expire_time = \Drupal::config('honeypot.settings')->get('expire');
|
||||
|
||||
// Query the {honeypot_user} table to determine the number of failed
|
||||
// submissions for the current user.
|
||||
$uid = $account->id();
|
||||
$query = \Drupal::database()->select('honeypot_user', 'hu')
|
||||
->condition('uid', $uid)
|
||||
->condition('timestamp', REQUEST_TIME - $expire_time, '>');
|
||||
|
||||
// For anonymous users, take the hostname into account.
|
||||
if ($uid === 0) {
|
||||
$hostname = \Drupal::request()->getClientIp();
|
||||
$query->condition('hostname', $hostname);
|
||||
}
|
||||
$number = $query->countQuery()->execute()->fetchField();
|
||||
|
||||
// Don't add more than 30 days' worth of extra time.
|
||||
$honeypot_time_limit = (int) min($honeypot_time_limit + exp($number) - 1, 2592000);
|
||||
// TODO - Only accepts two args.
|
||||
$additions = \Drupal::moduleHandler()->invokeAll('honeypot_time_limit', [
|
||||
$honeypot_time_limit,
|
||||
$form_values,
|
||||
$number,
|
||||
]);
|
||||
if (count($additions)) {
|
||||
$honeypot_time_limit += array_sum($additions);
|
||||
}
|
||||
}
|
||||
return $honeypot_time_limit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Log the failed submission with timestamp and hostname.
|
||||
*
|
||||
* @param string $form_id
|
||||
* Form ID for the rejected form submission.
|
||||
* @param string $type
|
||||
* String indicating the reason the submission was blocked. Allowed values:
|
||||
* - honeypot: If honeypot field was filled in.
|
||||
* - honeypot_time: If form was completed before the configured time limit.
|
||||
*/
|
||||
function honeypot_log_failure($form_id, $type) {
|
||||
$account = \Drupal::currentUser();
|
||||
$uid = $account->id();
|
||||
|
||||
// Log failed submissions.
|
||||
\Drupal::database()->insert('honeypot_user')
|
||||
->fields([
|
||||
'uid' => $uid,
|
||||
'hostname' => Drupal::request()->getClientIp(),
|
||||
'timestamp' => REQUEST_TIME,
|
||||
])
|
||||
->execute();
|
||||
|
||||
// Allow other modules to react to honeypot rejections.
|
||||
// TODO - Only accepts two args.
|
||||
\Drupal::moduleHandler()->invokeAll('honeypot_reject', [$form_id, $uid, $type]);
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
'administer honeypot':
|
||||
title: 'Administer Honeypot'
|
||||
description: 'Administer Honeypot-protected forms and settings.'
|
||||
|
||||
'bypass honeypot protection':
|
||||
title: 'Bypass Honeypot protection'
|
||||
description: 'Bypass Honeypot form protection.'
|
||||
@@ -0,0 +1,7 @@
|
||||
honeypot.config:
|
||||
path: '/admin/config/content/honeypot'
|
||||
defaults:
|
||||
_form: '\Drupal\honeypot\Controller\HoneypotSettingsController'
|
||||
_title: 'Honeypot configuration'
|
||||
requirements:
|
||||
_permission: 'administer honeypot'
|
||||
+329
@@ -0,0 +1,329 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\honeypot\Controller;
|
||||
|
||||
use Drupal\Component\Utility\Html;
|
||||
use Drupal\Core\Form\ConfigFormBase;
|
||||
use Drupal\Core\Config\ConfigFactoryInterface;
|
||||
use Drupal\Core\Form\FormStateInterface;
|
||||
use Drupal\node\Entity\NodeType;
|
||||
use Drupal\comment\Entity\CommentType;
|
||||
use Drupal\Core\Extension\ModuleHandlerInterface;
|
||||
use Drupal\Core\Entity\EntityTypeManagerInterface;
|
||||
use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
|
||||
use Drupal\Core\Cache\CacheBackendInterface;
|
||||
use Symfony\Component\DependencyInjection\ContainerInterface;
|
||||
|
||||
/**
|
||||
* Returns responses for Honeypot module routes.
|
||||
*/
|
||||
class HoneypotSettingsController extends ConfigFormBase {
|
||||
|
||||
/**
|
||||
* The module handler service.
|
||||
*
|
||||
* @var \Drupal\Core\Extension\ModuleHandlerInterface
|
||||
*/
|
||||
protected $moduleHandler;
|
||||
|
||||
/**
|
||||
* The entity type manager.
|
||||
*
|
||||
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
|
||||
*/
|
||||
protected $entityTypeManager;
|
||||
|
||||
/**
|
||||
* The entity type bundle info service.
|
||||
*
|
||||
* @var \Drupal\Core\Entity\EntityTypeBundleInfoInterface
|
||||
*/
|
||||
protected $entityTypeBundleInfo;
|
||||
|
||||
/**
|
||||
* A cache backend interface.
|
||||
*
|
||||
* @var \Drupal\Core\Cache\CacheBackendInterface
|
||||
*/
|
||||
protected $cache;
|
||||
|
||||
/**
|
||||
* Constructs a settings controller.
|
||||
*
|
||||
* @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
|
||||
* The factory for configuration objects.
|
||||
* @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
|
||||
* The module handler.
|
||||
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
|
||||
* The entity type manager.
|
||||
* @param \Drupal\Core\Entity\EntityTypeBundleInfoInterface $entity_type_bundle_info
|
||||
* The entity type bundle info service.
|
||||
* @param \Drupal\Core\Cache\CacheBackendInterface $cache_backend
|
||||
* The cache backend interface.
|
||||
*/
|
||||
public function __construct(ConfigFactoryInterface $config_factory, ModuleHandlerInterface $module_handler, EntityTypeManagerInterface $entity_type_manager, EntityTypeBundleInfoInterface $entity_type_bundle_info, CacheBackendInterface $cache_backend) {
|
||||
parent::__construct($config_factory);
|
||||
$this->moduleHandler = $module_handler;
|
||||
$this->entityTypeManager = $entity_type_manager;
|
||||
$this->entityTypeBundleInfo = $entity_type_bundle_info;
|
||||
$this->cache = $cache_backend;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public static function create(ContainerInterface $container) {
|
||||
return new static(
|
||||
$container->get('config.factory'),
|
||||
$container->get('module_handler'),
|
||||
$container->get('entity_type.manager'),
|
||||
$container->get('entity_type.bundle.info'),
|
||||
$container->get('cache.default')
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a value from the retrieved form settings array.
|
||||
*/
|
||||
public function getFormSettingsValue($form_settings, $form_id) {
|
||||
// If there are settings in the array and the form ID already has a setting,
|
||||
// return the saved setting for the form ID.
|
||||
if (!empty($form_settings) && isset($form_settings[$form_id])) {
|
||||
return $form_settings[$form_id];
|
||||
}
|
||||
// Default to false.
|
||||
else {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function getEditableConfigNames() {
|
||||
return ['honeypot.settings'];
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function getFormId() {
|
||||
return 'honeypot_settings_form';
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function buildForm(array $form, FormStateInterface $form_state) {
|
||||
// Honeypot Configuration.
|
||||
$form['configuration'] = [
|
||||
'#type' => 'fieldset',
|
||||
'#title' => $this->t('Honeypot Configuration'),
|
||||
'#collapsible' => TRUE,
|
||||
'#collapsed' => FALSE,
|
||||
];
|
||||
$form['configuration']['protect_all_forms'] = [
|
||||
'#type' => 'checkbox',
|
||||
'#title' => $this->t('Protect all forms with Honeypot'),
|
||||
'#description' => $this->t('Enable Honeypot protection for ALL forms on this site (it is best to only enable Honeypot for the forms you need below).'),
|
||||
'#default_value' => $this->config('honeypot.settings')->get('protect_all_forms'),
|
||||
];
|
||||
$form['configuration']['protect_all_forms']['#description'] .= '<br />' . $this->t('<strong>Page caching will be disabled on any page where a form is present if the Honeypot time limit is not set to 0.</strong>');
|
||||
$form['configuration']['log'] = [
|
||||
'#type' => 'checkbox',
|
||||
'#title' => $this->t('Log blocked form submissions'),
|
||||
'#description' => $this->t('Log submissions that are blocked due to Honeypot protection.'),
|
||||
'#default_value' => $this->config('honeypot.settings')->get('log'),
|
||||
];
|
||||
$form['configuration']['element_name'] = [
|
||||
'#type' => 'textfield',
|
||||
'#title' => $this->t('Honeypot element name'),
|
||||
'#description' => $this->t("The name of the Honeypot form field. It's usually most effective to use a generic name like email, homepage, or link, but this should be changed if it interferes with fields that are already in your forms. Must not contain spaces or special characters."),
|
||||
'#default_value' => $this->config('honeypot.settings')->get('element_name'),
|
||||
'#required' => TRUE,
|
||||
'#size' => 30,
|
||||
];
|
||||
$form['configuration']['time_limit'] = [
|
||||
'#type' => 'textfield',
|
||||
'#title' => $this->t('Honeypot time limit'),
|
||||
'#description' => $this->t('Minimum time required before form should be considered entered by a human instead of a bot. Set to 0 to disable.'),
|
||||
'#default_value' => $this->config('honeypot.settings')->get('time_limit'),
|
||||
'#required' => TRUE,
|
||||
'#size' => 5,
|
||||
'#field_suffix' => $this->t('seconds'),
|
||||
];
|
||||
$form['configuration']['time_limit']['#description'] .= '<br />' . $this->t('<strong>Page caching will be disabled if there is a form protected by time limit on the page.</strong>');
|
||||
|
||||
// Honeypot Enabled forms.
|
||||
$form_settings = $this->config('honeypot.settings')->get('form_settings');
|
||||
$form['form_settings'] = [
|
||||
'#type' => 'fieldset',
|
||||
'#title' => $this->t('Honeypot Enabled Forms'),
|
||||
'#description' => $this->t("Check the boxes next to individual forms on which you'd like Honeypot protection enabled."),
|
||||
'#collapsible' => TRUE,
|
||||
'#collapsed' => FALSE,
|
||||
'#tree' => TRUE,
|
||||
'#states' => [
|
||||
// Hide this fieldset when all forms are protected.
|
||||
'invisible' => [
|
||||
'input[name="protect_all_forms"]' => ['checked' => TRUE],
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
// Generic forms.
|
||||
$form['form_settings']['general_forms'] = ['#markup' => '<h5>' . $this->t('General Forms') . '</h5>'];
|
||||
// User register form.
|
||||
$form['form_settings']['user_register_form'] = [
|
||||
'#type' => 'checkbox',
|
||||
'#title' => $this->t('User Registration form'),
|
||||
'#default_value' => $this->getFormSettingsValue($form_settings, 'user_register_form'),
|
||||
];
|
||||
// User password form.
|
||||
$form['form_settings']['user_pass'] = [
|
||||
'#type' => 'checkbox',
|
||||
'#title' => $this->t('User Password Reset form'),
|
||||
'#default_value' => $this->getFormSettingsValue($form_settings, 'user_pass'),
|
||||
];
|
||||
|
||||
// If contact.module enabled, add contact forms.
|
||||
if ($this->moduleHandler->moduleExists('contact')) {
|
||||
$form['form_settings']['contact_forms'] = ['#markup' => '<h5>' . $this->t('Contact Forms') . '</h5>'];
|
||||
|
||||
$bundles = $this->entityTypeBundleInfo->getBundleInfo('contact_message');
|
||||
$formController = $this->entityTypeManager->getFormObject('contact_message', 'default');
|
||||
|
||||
foreach ($bundles as $bundle_key => $bundle) {
|
||||
$stub = $this->entityTypeManager->getStorage('contact_message')->create([
|
||||
'contact_form' => $bundle_key,
|
||||
]);
|
||||
$formController->setEntity($stub);
|
||||
$form_id = $formController->getFormId();
|
||||
|
||||
$form['form_settings'][$form_id] = [
|
||||
'#type' => 'checkbox',
|
||||
'#title' => Html::escape($bundle['label']),
|
||||
'#default_value' => $this->getFormSettingsValue($form_settings, $form_id),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
// Node types for node forms.
|
||||
if ($this->moduleHandler->moduleExists('node')) {
|
||||
$types = NodeType::loadMultiple();
|
||||
if (!empty($types)) {
|
||||
// Node forms.
|
||||
$form['form_settings']['node_forms'] = ['#markup' => '<h5>' . $this->t('Node Forms') . '</h5>'];
|
||||
foreach ($types as $type) {
|
||||
$id = 'node_' . $type->get('type') . '_form';
|
||||
$form['form_settings'][$id] = [
|
||||
'#type' => 'checkbox',
|
||||
'#title' => $this->t('@name node form', ['@name' => $type->label()]),
|
||||
'#default_value' => $this->getFormSettingsValue($form_settings, $id),
|
||||
];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Comment types for comment forms.
|
||||
if ($this->moduleHandler->moduleExists('comment')) {
|
||||
$types = CommentType::loadMultiple();
|
||||
if (!empty($types)) {
|
||||
$form['form_settings']['comment_forms'] = ['#markup' => '<h5>' . $this->t('Comment Forms') . '</h5>'];
|
||||
foreach ($types as $type) {
|
||||
$id = 'comment_' . $type->id() . '_form';
|
||||
$form['form_settings'][$id] = [
|
||||
'#type' => 'checkbox',
|
||||
'#title' => $this->t('@name comment form', ['@name' => $type->label()]),
|
||||
'#default_value' => $this->getFormSettingsValue($form_settings, $id),
|
||||
];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Store the keys we want to save in configuration when form is submitted.
|
||||
$keys_to_save = array_keys($form['configuration']);
|
||||
foreach ($keys_to_save as $key => $key_to_save) {
|
||||
if (strpos($key_to_save, '#') !== FALSE) {
|
||||
unset($keys_to_save[$key]);
|
||||
}
|
||||
}
|
||||
$form_state->setStorage(['keys' => $keys_to_save]);
|
||||
|
||||
// For now, manually add submit button. Hopefully, by the time D8 is
|
||||
// released, there will be something like system_settings_form() in D7.
|
||||
$form['actions']['#type'] = 'container';
|
||||
$form['actions']['submit'] = [
|
||||
'#type' => 'submit',
|
||||
'#value' => $this->t('Save configuration'),
|
||||
];
|
||||
|
||||
return $form;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function validateForm(array &$form, FormStateInterface $form_state) {
|
||||
// Make sure the time limit is a positive integer or 0.
|
||||
$time_limit = $form_state->getValue('time_limit');
|
||||
if ((is_numeric($time_limit) && $time_limit > 0) || $time_limit === '0') {
|
||||
if (ctype_digit($time_limit)) {
|
||||
// Good to go.
|
||||
}
|
||||
else {
|
||||
$form_state->setErrorByName('time_limit', $this->t("The time limit must be a positive integer or 0."));
|
||||
}
|
||||
}
|
||||
else {
|
||||
$form_state->setErrorByName('time_limit', $this->t("The time limit must be a positive integer or 0."));
|
||||
}
|
||||
|
||||
// Make sure Honeypot element name only contains A-Z, 0-9.
|
||||
if (!preg_match("/^[-_a-zA-Z0-9]+$/", $form_state->getValue('element_name'))) {
|
||||
$form_state->setErrorByName('element_name', $this->t("The element name cannot contain spaces or other special characters."));
|
||||
}
|
||||
|
||||
// Make sure Honeypot element name starts with a letter.
|
||||
if (!preg_match("/^[a-zA-Z].+$/", $form_state->getValue('element_name'))) {
|
||||
$form_state->setErrorByName('element_name', $this->t("The element name must start with a letter."));
|
||||
}
|
||||
|
||||
// Make sure Honeypot element name isn't one of the reserved names.
|
||||
$reserved_element_names = [
|
||||
'name',
|
||||
'pass',
|
||||
'website',
|
||||
];
|
||||
if (in_array($form_state->getValue('element_name'), $reserved_element_names)) {
|
||||
$form_state->setErrorByName('element_name', $this->t("The element name cannot match one of the common Drupal form field names (e.g. @names).", ['@names' => implode(', ', $reserved_element_names)]));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function submitForm(array &$form, FormStateInterface $form_state) {
|
||||
$config = $this->config('honeypot.settings');
|
||||
$storage = $form_state->getStorage();
|
||||
|
||||
// Save all the Honeypot configuration items from $form_state.
|
||||
foreach ($form_state->getValues() as $key => $value) {
|
||||
if (in_array($key, $storage['keys'])) {
|
||||
$config->set($key, $value);
|
||||
}
|
||||
}
|
||||
|
||||
// Save the honeypot forms from $form_state into a 'form_settings' array.
|
||||
$config->set('form_settings', $form_state->getValue('form_settings'));
|
||||
|
||||
$config->save();
|
||||
|
||||
// Clear the honeypot protected forms cache.
|
||||
$this->cache->delete('honeypot_protected_forms');
|
||||
|
||||
// Tell the user the settings have been saved.
|
||||
drupal_set_message($this->t('The configuration options have been saved.'));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\honeypot\Tests;
|
||||
|
||||
use Drupal\simpletest\WebTestBase;
|
||||
|
||||
/**
|
||||
* Test Honeypot spam protection admin form functionality.
|
||||
*
|
||||
* @group honeypot
|
||||
*/
|
||||
class HoneypotAdminFormTest extends WebTestBase {
|
||||
|
||||
protected $adminUser;
|
||||
|
||||
/**
|
||||
* Modules to enable.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = ['honeypot'];
|
||||
|
||||
/**
|
||||
* Setup before test.
|
||||
*/
|
||||
public function setUp() {
|
||||
// Enable modules required for this test.
|
||||
parent::setUp();
|
||||
|
||||
// Set up admin user.
|
||||
$this->adminUser = $this->drupalCreateUser([
|
||||
'administer honeypot',
|
||||
'bypass honeypot protection',
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test a valid element name.
|
||||
*/
|
||||
public function testElementNameUpdateSuccess() {
|
||||
// Log in the admin user.
|
||||
$this->drupalLogin($this->adminUser);
|
||||
|
||||
// Set up form and submit it.
|
||||
$edit['element_name'] = "test";
|
||||
$this->drupalPostForm('admin/config/content/honeypot', $edit, t('Save configuration'));
|
||||
|
||||
// Form should have been submitted successfully.
|
||||
$this->assertText(t('The configuration options have been saved.'), 'Honeypot element name assertion works for valid names.');
|
||||
|
||||
// Set up form and submit it.
|
||||
$edit['element_name'] = "test-1";
|
||||
$this->drupalPostForm('admin/config/content/honeypot', $edit, t('Save configuration'));
|
||||
|
||||
// Form should have been submitted successfully.
|
||||
$this->assertText(t('The configuration options have been saved.'), 'Honeypot element name assertion works for valid names with dashes and numbers.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Test an invalid element name (invalid first character).
|
||||
*/
|
||||
public function testElementNameUpdateFirstCharacterFail() {
|
||||
// Log in the admin user.
|
||||
$this->drupalLogin($this->adminUser);
|
||||
|
||||
// Set up form and submit it.
|
||||
$edit['element_name'] = "1test";
|
||||
$this->drupalPostForm('admin/config/content/honeypot', $edit, t('Save configuration'));
|
||||
|
||||
// Form submission should fail.
|
||||
$this->assertText(t('The element name must start with a letter.'), 'Honeypot element name assertion works for invalid names.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Test an invalid element name (invalid character in name).
|
||||
*/
|
||||
public function testElementNameUpdateInvalidCharacterFail() {
|
||||
// Log in the admin user.
|
||||
$this->drupalLogin($this->adminUser);
|
||||
|
||||
// Set up form and submit it.
|
||||
$edit['element_name'] = "special-character-&";
|
||||
$this->drupalPostForm('admin/config/content/honeypot', $edit, t('Save configuration'));
|
||||
|
||||
// Form submission should fail.
|
||||
$this->assertText(t('The element name cannot contain spaces or other special characters.'), 'Honeypot element name assertion works for invalid names with special characters.');
|
||||
|
||||
// Set up form and submit it.
|
||||
$edit['element_name'] = "space in name";
|
||||
$this->drupalPostForm('admin/config/content/honeypot', $edit, t('Save configuration'));
|
||||
|
||||
// Form submission should fail.
|
||||
$this->assertText(t('The element name cannot contain spaces or other special characters.'), 'Honeypot element name assertion works for invalid names with spaces.');
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\honeypot\Tests;
|
||||
|
||||
use Drupal\comment\Tests\CommentTestTrait;
|
||||
use Drupal\comment\Plugin\Field\FieldType\CommentItemInterface;
|
||||
use Drupal\contact\Entity\ContactForm;
|
||||
use Drupal\simpletest\WebTestBase;
|
||||
use Drupal\user\Entity\Role;
|
||||
use Drupal\user\RoleInterface;
|
||||
|
||||
/**
|
||||
* Tests page caching on Honeypot protected forms.
|
||||
*
|
||||
* @group honeypot
|
||||
*/
|
||||
class HoneypotFormCacheTest extends WebTestBase {
|
||||
|
||||
use CommentTestTrait;
|
||||
/**
|
||||
* Modules to enable.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = ['honeypot', 'node', 'comment', 'contact'];
|
||||
|
||||
protected $node;
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function setUp() {
|
||||
parent::setUp();
|
||||
|
||||
// Set up required Honeypot configuration.
|
||||
$honeypot_config = \Drupal::configFactory()->getEditable('honeypot.settings');
|
||||
$honeypot_config->set('element_name', 'url');
|
||||
// Enable time_limit protection.
|
||||
$honeypot_config->set('time_limit', 5);
|
||||
// Test protecting all forms.
|
||||
$honeypot_config->set('protect_all_forms', TRUE);
|
||||
$honeypot_config->set('log', FALSE);
|
||||
$honeypot_config->save();
|
||||
|
||||
// Set up other required configuration.
|
||||
$user_config = \Drupal::configFactory()->getEditable('user.settings');
|
||||
$user_config->set('verify_mail', TRUE);
|
||||
$user_config->set('register', USER_REGISTER_VISITORS);
|
||||
$user_config->save();
|
||||
|
||||
// Create an Article node type.
|
||||
if ($this->profile != 'standard') {
|
||||
$this->drupalCreateContentType(['type' => 'article', 'name' => 'Article']);
|
||||
// Create comment field on article.
|
||||
$this->addDefaultCommentField('node', 'article');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Test enabling and disabling of page cache based on time limit settings.
|
||||
*/
|
||||
public function testCacheContactForm() {
|
||||
// Create a Website feedback contact form.
|
||||
$feedback_form = ContactForm::create([
|
||||
'id' => 'feedback',
|
||||
'label' => 'Website feedback',
|
||||
'recipients' => [],
|
||||
'reply' => '',
|
||||
'weight' => 0,
|
||||
]);
|
||||
$feedback_form->save();
|
||||
$contact_settings = \Drupal::configFactory()->getEditable('contact.settings');
|
||||
$contact_settings->set('default_form', 'feedback')->save();
|
||||
|
||||
// Give anonymous users permission to view contact form.
|
||||
Role::load(RoleInterface::ANONYMOUS_ID)
|
||||
->grantPermission('access site-wide contact form')
|
||||
->save();
|
||||
|
||||
// Prime the cache.
|
||||
$this->drupalGet('contact/feedback');
|
||||
|
||||
// Test on cache header with time limit enabled, cache should miss.
|
||||
$this->drupalGet('contact/feedback');
|
||||
$this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), '', 'Page was not cached.');
|
||||
|
||||
// Disable time limit.
|
||||
\Drupal::configFactory()->getEditable('honeypot.settings')->set('time_limit', 0)->save();
|
||||
|
||||
// Prime the cache.
|
||||
$this->drupalGet('contact/feedback');
|
||||
// Test on cache header with time limit disabled, cache should hit.
|
||||
$this->drupalGet('contact/feedback');
|
||||
$this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT', 'Page was cached.');
|
||||
|
||||
// Re-enable the time limit, we should not be seeing the cached version.
|
||||
\Drupal::configFactory()->getEditable('honeypot.settings')->set('time_limit', 5)->save();
|
||||
$this->drupalGet('contact/feedback');
|
||||
$this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), '', 'Page was not cached.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Test enabling and disabling of page cache based on time limit settings.
|
||||
*/
|
||||
public function testCacheCommentForm() {
|
||||
// Set up example node.
|
||||
$this->node = $this->drupalCreateNode([
|
||||
'type' => 'article',
|
||||
'comment' => CommentItemInterface::OPEN,
|
||||
]);
|
||||
|
||||
// Give anonymous users permission to post comments.
|
||||
Role::load(RoleInterface::ANONYMOUS_ID)
|
||||
->grantPermission('post comments')
|
||||
->grantPermission('access comments')
|
||||
->save();
|
||||
|
||||
// Prime the cache.
|
||||
$this->drupalGet('node/' . $this->node->id());
|
||||
|
||||
// Test on cache header with time limit enabled, cache should miss.
|
||||
$this->drupalGet('node/' . $this->node->id());
|
||||
$this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), '', 'Page was not cached.');
|
||||
|
||||
// Disable time limit.
|
||||
\Drupal::configFactory()->getEditable('honeypot.settings')->set('time_limit', 0)->save();
|
||||
|
||||
// Prime the cache.
|
||||
$this->drupalGet('node/' . $this->node->id());
|
||||
|
||||
// Test on cache header with time limit disabled, cache should hit.
|
||||
$this->drupalGet('node/' . $this->node->id());
|
||||
$this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT', 'Page was cached.');
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\honeypot\Tests;
|
||||
|
||||
use Drupal\simpletest\WebTestBase;
|
||||
|
||||
/**
|
||||
* Test programmatic submission of forms protected by Honeypot.
|
||||
*
|
||||
* @group honeypot
|
||||
*/
|
||||
class HoneypotFormProgrammaticSubmissionTest extends WebTestBase {
|
||||
|
||||
/**
|
||||
* Modules to enable.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = ['honeypot', 'honeypot_test', 'user'];
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function setUp() {
|
||||
parent::setUp();
|
||||
|
||||
// Set up required Honeypot configuration.
|
||||
$honeypot_config = \Drupal::configFactory()->getEditable('honeypot.settings');
|
||||
$honeypot_config->set('element_name', 'url');
|
||||
$honeypot_config->set('time_limit', 5);
|
||||
$honeypot_config->set('protect_all_forms', TRUE);
|
||||
$honeypot_config->set('log', FALSE);
|
||||
$honeypot_config->save();
|
||||
|
||||
$this->drupalCreateUser([], 'robo-user');
|
||||
}
|
||||
|
||||
/**
|
||||
* Trigger a programmatic form submission and verify the validation errors.
|
||||
*/
|
||||
public function testProgrammaticFormSubmission() {
|
||||
$result = $this->drupalGet('/honeypot_test/submit_form');
|
||||
$form_errors = (array) json_decode($result);
|
||||
$this->assertNoRaw('There was a problem with your form submission. Please wait 6 seconds and try again.');
|
||||
$this->assertFalse($form_errors, 'The were no validation errors when submitting the form.');
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,254 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\honeypot\Tests;
|
||||
|
||||
use Drupal\simpletest\WebTestBase;
|
||||
use Drupal\comment\Tests\CommentTestTrait;
|
||||
use Drupal\comment\Plugin\Field\FieldType\CommentItemInterface;
|
||||
use Drupal\contact\Entity\ContactForm;
|
||||
|
||||
/**
|
||||
* Test Honeypot spam protection functionality.
|
||||
*
|
||||
* @group honeypot
|
||||
*/
|
||||
class HoneypotFormTest extends WebTestBase {
|
||||
|
||||
use CommentTestTrait;
|
||||
|
||||
protected $adminUser;
|
||||
protected $webUser;
|
||||
protected $node;
|
||||
|
||||
/**
|
||||
* Modules to enable.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = ['honeypot', 'node', 'comment', 'contact'];
|
||||
|
||||
/**
|
||||
* Setup before test.
|
||||
*/
|
||||
public function setUp() {
|
||||
// Enable modules required for this test.
|
||||
parent::setUp();
|
||||
|
||||
// Set up required Honeypot configuration.
|
||||
$honeypot_config = \Drupal::configFactory()->getEditable('honeypot.settings');
|
||||
$honeypot_config->set('element_name', 'url');
|
||||
// Disable time_limit protection.
|
||||
$honeypot_config->set('time_limit', 0);
|
||||
// Test protecting all forms.
|
||||
$honeypot_config->set('protect_all_forms', TRUE);
|
||||
$honeypot_config->set('log', FALSE);
|
||||
$honeypot_config->save();
|
||||
|
||||
// Set up other required configuration.
|
||||
$user_config = \Drupal::configFactory()->getEditable('user.settings');
|
||||
$user_config->set('verify_mail', TRUE);
|
||||
$user_config->set('register', USER_REGISTER_VISITORS);
|
||||
$user_config->save();
|
||||
|
||||
// Create an Article node type.
|
||||
if ($this->profile != 'standard') {
|
||||
$this->drupalCreateContentType(['type' => 'article', 'name' => 'Article']);
|
||||
// Create comment field on article.
|
||||
$this->addDefaultCommentField('node', 'article');
|
||||
}
|
||||
|
||||
// Set up admin user.
|
||||
$this->adminUser = $this->drupalCreateUser([
|
||||
'administer honeypot',
|
||||
'bypass honeypot protection',
|
||||
'administer content types',
|
||||
'administer users',
|
||||
'access comments',
|
||||
'post comments',
|
||||
'skip comment approval',
|
||||
'administer comments',
|
||||
]);
|
||||
|
||||
// Set up web user.
|
||||
$this->webUser = $this->drupalCreateUser([
|
||||
'access comments',
|
||||
'post comments',
|
||||
'create article content',
|
||||
'access site-wide contact form',
|
||||
]);
|
||||
|
||||
// Set up example node.
|
||||
$this->node = $this->drupalCreateNode([
|
||||
'type' => 'article',
|
||||
'comment' => CommentItemInterface::OPEN,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Make sure user login form is not protected.
|
||||
*/
|
||||
public function testUserLoginNotProtected() {
|
||||
$this->drupalGet('user');
|
||||
$this->assertNoText('id="edit-url" name="url"', 'Honeypot not enabled on user login form.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Test user registration (anonymous users).
|
||||
*/
|
||||
public function testProtectRegisterUserNormal() {
|
||||
// Set up form and submit it.
|
||||
$edit['name'] = $this->randomMachineName();
|
||||
$edit['mail'] = $edit['name'] . '@example.com';
|
||||
$this->drupalPostForm('user/register', $edit, t('Create new account'));
|
||||
|
||||
// Form should have been submitted successfully.
|
||||
$this->assertText(t('A welcome message with further instructions has been sent to your email address.'), 'User registered successfully.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Test for user register honeypot filled.
|
||||
*/
|
||||
public function testProtectUserRegisterHoneypotFilled() {
|
||||
// Set up form and submit it.
|
||||
$edit['name'] = $this->randomMachineName();
|
||||
$edit['mail'] = $edit['name'] . '@example.com';
|
||||
$edit['url'] = 'http://www.example.com/';
|
||||
$this->drupalPostForm('user/register', $edit, t('Create new account'));
|
||||
|
||||
// Form should have error message.
|
||||
$this->assertText(t('There was a problem with your form submission. Please refresh the page and try again.'), 'Registration form protected by honeypot.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Test for user register too fast.
|
||||
*/
|
||||
public function testProtectRegisterUserTooFast() {
|
||||
\Drupal::configFactory()->getEditable('honeypot.settings')->set('time_limit', 1)->save();
|
||||
|
||||
// First attempt a submission that does not trigger honeypot.
|
||||
$edit['name'] = $this->randomMachineName();
|
||||
$edit['mail'] = $edit['name'] . '@example.com';
|
||||
$this->drupalGet('user/register');
|
||||
sleep(2);
|
||||
$this->drupalPostForm(NULL, $edit, t('Create new account'));
|
||||
$this->assertNoText(t('There was a problem with your form submission.'));
|
||||
|
||||
// Set the time limit a bit higher so we can trigger honeypot.
|
||||
\Drupal::configFactory()->getEditable('honeypot.settings')->set('time_limit', 5)->save();
|
||||
|
||||
// Set up form and submit it.
|
||||
$edit['name'] = $this->randomMachineName();
|
||||
$edit['mail'] = $edit['name'] . '@example.com';
|
||||
$this->drupalPostForm('user/register', $edit, t('Create new account'));
|
||||
|
||||
// Form should have error message.
|
||||
$this->assertText(t('There was a problem with your form submission. Please wait 6 seconds and try again.'), 'Registration form protected by time limit.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Test comment form protection.
|
||||
*/
|
||||
public function testProtectCommentFormNormal() {
|
||||
$comment = 'Test comment.';
|
||||
|
||||
// Disable time limit for honeypot.
|
||||
\Drupal::configFactory()->getEditable('honeypot.settings')->set('time_limit', 0)->save();
|
||||
|
||||
// Log in the web user.
|
||||
$this->drupalLogin($this->webUser);
|
||||
|
||||
// Set up form and submit it.
|
||||
$edit["comment_body[0][value]"] = $comment;
|
||||
$this->drupalPostForm('comment/reply/node/' . $this->node->id() . '/comment', $edit, t('Save'));
|
||||
$this->assertText(t('Your comment has been queued for review'), 'Comment posted successfully.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Test for comment form honeypot filled.
|
||||
*/
|
||||
public function testProtectCommentFormHoneypotFilled() {
|
||||
$comment = 'Test comment.';
|
||||
|
||||
// Log in the web user.
|
||||
$this->drupalLogin($this->webUser);
|
||||
|
||||
// Set up form and submit it.
|
||||
$edit["comment_body[0][value]"] = $comment;
|
||||
$edit['url'] = 'http://www.example.com/';
|
||||
$this->drupalPostForm('comment/reply/node/' . $this->node->id() . '/comment', $edit, t('Save'));
|
||||
$this->assertText(t('There was a problem with your form submission. Please refresh the page and try again.'), 'Comment posted successfully.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Test for comment form honeypot bypass.
|
||||
*/
|
||||
public function testProtectCommentFormHoneypotBypass() {
|
||||
// Log in the admin user.
|
||||
$this->drupalLogin($this->adminUser);
|
||||
|
||||
// Get the comment reply form and ensure there's no 'url' field.
|
||||
$this->drupalGet('comment/reply/node/' . $this->node->id() . '/comment');
|
||||
$this->assertNoText('id="edit-url" name="url"', 'Honeypot home page field not shown.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Test node form protection.
|
||||
*/
|
||||
public function testProtectNodeFormTooFast() {
|
||||
// Log in the admin user.
|
||||
$this->drupalLogin($this->webUser);
|
||||
|
||||
// Reset the time limit to 5 seconds.
|
||||
\Drupal::configFactory()->getEditable('honeypot.settings')->set('time_limit', 5)->save();
|
||||
|
||||
// Set up the form and submit it.
|
||||
$edit["title[0][value]"] = 'Test Page';
|
||||
$this->drupalPostForm('node/add/article', $edit, t('Save'));
|
||||
$this->assertText(t('There was a problem with your form submission.'), 'Honeypot node form timestamp protection works.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Test node form protection.
|
||||
*/
|
||||
public function testProtectNodeFormPreviewPassthru() {
|
||||
// Log in the admin user.
|
||||
$this->drupalLogin($this->webUser);
|
||||
|
||||
// Post a node form using the 'Preview' button and make sure it's allowed.
|
||||
$edit["title[0][value]"] = 'Test Page';
|
||||
$this->drupalPostForm('node/add/article', $edit, t('Preview'));
|
||||
$this->assertNoText(t('There was a problem with your form submission.'), 'Honeypot not blocking node form previews.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Test protection on the Contact form.
|
||||
*/
|
||||
public function testProtectContactForm() {
|
||||
$this->drupalLogin($this->adminUser);
|
||||
|
||||
// Disable 'protect_all_forms'.
|
||||
\Drupal::configFactory()->getEditable('honeypot.settings')->set('protect_all_forms', FALSE)->save();
|
||||
|
||||
// Create a Website feedback contact form.
|
||||
$feedback_form = ContactForm::create([
|
||||
'id' => 'feedback',
|
||||
'label' => 'Website feedback',
|
||||
'recipients' => [],
|
||||
'reply' => '',
|
||||
'weight' => 0,
|
||||
]);
|
||||
$feedback_form->save();
|
||||
$contact_settings = \Drupal::configFactory()->getEditable('contact.settings');
|
||||
$contact_settings->set('default_form', 'feedback')->save();
|
||||
|
||||
// Submit the admin form so we can verify the right forms are displayed.
|
||||
$this->drupalPostForm('admin/config/content/honeypot', [
|
||||
'form_settings[contact_message_feedback_form]' => TRUE,
|
||||
], t('Save configuration'));
|
||||
|
||||
$this->drupalLogin($this->webUser);
|
||||
$this->drupalGet('contact/feedback');
|
||||
$this->assertField('url', 'Honeypot field is added to Contact form.');
|
||||
}
|
||||
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
name: honeypot_test
|
||||
type: module
|
||||
description: Support module for Honeypot internal testing purposes.
|
||||
# core: 8.x
|
||||
package: Testing
|
||||
hidden: true
|
||||
|
||||
# Information added by Drupal.org packaging script on 2017-07-12
|
||||
version: '8.x-1.27'
|
||||
core: '8.x'
|
||||
project: 'honeypot'
|
||||
datestamp: 1499867346
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
honeypot_test.submit_form:
|
||||
path: '/honeypot_test/submit_form'
|
||||
defaults:
|
||||
_title: 'Test programmatic form submission'
|
||||
_controller: '\Drupal\honeypot_test\Controller\HoneypotTestController::submitFormPage'
|
||||
requirements:
|
||||
# This is a test form, we don't need to worry about access.
|
||||
_access: 'TRUE'
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\honeypot_test\Controller;
|
||||
|
||||
use Drupal\Core\Form\FormState;
|
||||
use Symfony\Component\HttpFoundation\JsonResponse;
|
||||
|
||||
/**
|
||||
* Controller for honeypot_test routes.
|
||||
*/
|
||||
class HoneypotTestController {
|
||||
|
||||
/**
|
||||
* Page that triggers a programmatic form submission.
|
||||
*
|
||||
* Returns the validation errors triggered by the form submission as json.
|
||||
*/
|
||||
public function submitFormPage() {
|
||||
$form_state = new FormState();
|
||||
$values = [
|
||||
'name' => 'robo-user',
|
||||
'mail' => 'robouser@example.com',
|
||||
'op' => t('Submit'),
|
||||
];
|
||||
$form_state->setValues($values);
|
||||
\Drupal::formBuilder()->submitForm('\Drupal\user\Form\UserPasswordForm', $form_state);
|
||||
|
||||
return new JsonResponse($form_state->getErrors());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,339 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 2, June 1991
|
||||
|
||||
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
|
||||
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The licenses for most software are designed to take away your
|
||||
freedom to share and change it. By contrast, the GNU General Public
|
||||
License is intended to guarantee your freedom to share and change free
|
||||
software--to make sure the software is free for all its users. This
|
||||
General Public License applies to most of the Free Software
|
||||
Foundation's software and to any other program whose authors commit to
|
||||
using it. (Some other Free Software Foundation software is covered by
|
||||
the GNU Lesser General Public License instead.) You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
this service if you wish), that you receive source code or can get it
|
||||
if you want it, that you can change the software or use pieces of it
|
||||
in new free programs; and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to make restrictions that forbid
|
||||
anyone to deny you these rights or to ask you to surrender the rights.
|
||||
These restrictions translate to certain responsibilities for you if you
|
||||
distribute copies of the software, or if you modify it.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must give the recipients all the rights that
|
||||
you have. You must make sure that they, too, receive or can get the
|
||||
source code. And you must show them these terms so they know their
|
||||
rights.
|
||||
|
||||
We protect your rights with two steps: (1) copyright the software, and
|
||||
(2) offer you this license which gives you legal permission to copy,
|
||||
distribute and/or modify the software.
|
||||
|
||||
Also, for each author's protection and ours, we want to make certain
|
||||
that everyone understands that there is no warranty for this free
|
||||
software. If the software is modified by someone else and passed on, we
|
||||
want its recipients to know that what they have is not the original, so
|
||||
that any problems introduced by others will not reflect on the original
|
||||
authors' reputations.
|
||||
|
||||
Finally, any free program is threatened constantly by software
|
||||
patents. We wish to avoid the danger that redistributors of a free
|
||||
program will individually obtain patent licenses, in effect making the
|
||||
program proprietary. To prevent this, we have made it clear that any
|
||||
patent must be licensed for everyone's free use or not licensed at all.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
|
||||
|
||||
0. This License applies to any program or other work which contains
|
||||
a notice placed by the copyright holder saying it may be distributed
|
||||
under the terms of this General Public License. The "Program", below,
|
||||
refers to any such program or work, and a "work based on the Program"
|
||||
means either the Program or any derivative work under copyright law:
|
||||
that is to say, a work containing the Program or a portion of it,
|
||||
either verbatim or with modifications and/or translated into another
|
||||
language. (Hereinafter, translation is included without limitation in
|
||||
the term "modification".) Each licensee is addressed as "you".
|
||||
|
||||
Activities other than copying, distribution and modification are not
|
||||
covered by this License; they are outside its scope. The act of
|
||||
running the Program is not restricted, and the output from the Program
|
||||
is covered only if its contents constitute a work based on the
|
||||
Program (independent of having been made by running the Program).
|
||||
Whether that is true depends on what the Program does.
|
||||
|
||||
1. You may copy and distribute verbatim copies of the Program's
|
||||
source code as you receive it, in any medium, provided that you
|
||||
conspicuously and appropriately publish on each copy an appropriate
|
||||
copyright notice and disclaimer of warranty; keep intact all the
|
||||
notices that refer to this License and to the absence of any warranty;
|
||||
and give any other recipients of the Program a copy of this License
|
||||
along with the Program.
|
||||
|
||||
You may charge a fee for the physical act of transferring a copy, and
|
||||
you may at your option offer warranty protection in exchange for a fee.
|
||||
|
||||
2. You may modify your copy or copies of the Program or any portion
|
||||
of it, thus forming a work based on the Program, and copy and
|
||||
distribute such modifications or work under the terms of Section 1
|
||||
above, provided that you also meet all of these conditions:
|
||||
|
||||
a) You must cause the modified files to carry prominent notices
|
||||
stating that you changed the files and the date of any change.
|
||||
|
||||
b) You must cause any work that you distribute or publish, that in
|
||||
whole or in part contains or is derived from the Program or any
|
||||
part thereof, to be licensed as a whole at no charge to all third
|
||||
parties under the terms of this License.
|
||||
|
||||
c) If the modified program normally reads commands interactively
|
||||
when run, you must cause it, when started running for such
|
||||
interactive use in the most ordinary way, to print or display an
|
||||
announcement including an appropriate copyright notice and a
|
||||
notice that there is no warranty (or else, saying that you provide
|
||||
a warranty) and that users may redistribute the program under
|
||||
these conditions, and telling the user how to view a copy of this
|
||||
License. (Exception: if the Program itself is interactive but
|
||||
does not normally print such an announcement, your work based on
|
||||
the Program is not required to print an announcement.)
|
||||
|
||||
These requirements apply to the modified work as a whole. If
|
||||
identifiable sections of that work are not derived from the Program,
|
||||
and can be reasonably considered independent and separate works in
|
||||
themselves, then this License, and its terms, do not apply to those
|
||||
sections when you distribute them as separate works. But when you
|
||||
distribute the same sections as part of a whole which is a work based
|
||||
on the Program, the distribution of the whole must be on the terms of
|
||||
this License, whose permissions for other licensees extend to the
|
||||
entire whole, and thus to each and every part regardless of who wrote it.
|
||||
|
||||
Thus, it is not the intent of this section to claim rights or contest
|
||||
your rights to work written entirely by you; rather, the intent is to
|
||||
exercise the right to control the distribution of derivative or
|
||||
collective works based on the Program.
|
||||
|
||||
In addition, mere aggregation of another work not based on the Program
|
||||
with the Program (or with a work based on the Program) on a volume of
|
||||
a storage or distribution medium does not bring the other work under
|
||||
the scope of this License.
|
||||
|
||||
3. You may copy and distribute the Program (or a work based on it,
|
||||
under Section 2) in object code or executable form under the terms of
|
||||
Sections 1 and 2 above provided that you also do one of the following:
|
||||
|
||||
a) Accompany it with the complete corresponding machine-readable
|
||||
source code, which must be distributed under the terms of Sections
|
||||
1 and 2 above on a medium customarily used for software interchange; or,
|
||||
|
||||
b) Accompany it with a written offer, valid for at least three
|
||||
years, to give any third party, for a charge no more than your
|
||||
cost of physically performing source distribution, a complete
|
||||
machine-readable copy of the corresponding source code, to be
|
||||
distributed under the terms of Sections 1 and 2 above on a medium
|
||||
customarily used for software interchange; or,
|
||||
|
||||
c) Accompany it with the information you received as to the offer
|
||||
to distribute corresponding source code. (This alternative is
|
||||
allowed only for noncommercial distribution and only if you
|
||||
received the program in object code or executable form with such
|
||||
an offer, in accord with Subsection b above.)
|
||||
|
||||
The source code for a work means the preferred form of the work for
|
||||
making modifications to it. For an executable work, complete source
|
||||
code means all the source code for all modules it contains, plus any
|
||||
associated interface definition files, plus the scripts used to
|
||||
control compilation and installation of the executable. However, as a
|
||||
special exception, the source code distributed need not include
|
||||
anything that is normally distributed (in either source or binary
|
||||
form) with the major components (compiler, kernel, and so on) of the
|
||||
operating system on which the executable runs, unless that component
|
||||
itself accompanies the executable.
|
||||
|
||||
If distribution of executable or object code is made by offering
|
||||
access to copy from a designated place, then offering equivalent
|
||||
access to copy the source code from the same place counts as
|
||||
distribution of the source code, even though third parties are not
|
||||
compelled to copy the source along with the object code.
|
||||
|
||||
4. You may not copy, modify, sublicense, or distribute the Program
|
||||
except as expressly provided under this License. Any attempt
|
||||
otherwise to copy, modify, sublicense or distribute the Program is
|
||||
void, and will automatically terminate your rights under this License.
|
||||
However, parties who have received copies, or rights, from you under
|
||||
this License will not have their licenses terminated so long as such
|
||||
parties remain in full compliance.
|
||||
|
||||
5. You are not required to accept this License, since you have not
|
||||
signed it. However, nothing else grants you permission to modify or
|
||||
distribute the Program or its derivative works. These actions are
|
||||
prohibited by law if you do not accept this License. Therefore, by
|
||||
modifying or distributing the Program (or any work based on the
|
||||
Program), you indicate your acceptance of this License to do so, and
|
||||
all its terms and conditions for copying, distributing or modifying
|
||||
the Program or works based on it.
|
||||
|
||||
6. Each time you redistribute the Program (or any work based on the
|
||||
Program), the recipient automatically receives a license from the
|
||||
original licensor to copy, distribute or modify the Program subject to
|
||||
these terms and conditions. You may not impose any further
|
||||
restrictions on the recipients' exercise of the rights granted herein.
|
||||
You are not responsible for enforcing compliance by third parties to
|
||||
this License.
|
||||
|
||||
7. If, as a consequence of a court judgment or allegation of patent
|
||||
infringement or for any other reason (not limited to patent issues),
|
||||
conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot
|
||||
distribute so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you
|
||||
may not distribute the Program at all. For example, if a patent
|
||||
license would not permit royalty-free redistribution of the Program by
|
||||
all those who receive copies directly or indirectly through you, then
|
||||
the only way you could satisfy both it and this License would be to
|
||||
refrain entirely from distribution of the Program.
|
||||
|
||||
If any portion of this section is held invalid or unenforceable under
|
||||
any particular circumstance, the balance of the section is intended to
|
||||
apply and the section as a whole is intended to apply in other
|
||||
circumstances.
|
||||
|
||||
It is not the purpose of this section to induce you to infringe any
|
||||
patents or other property right claims or to contest validity of any
|
||||
such claims; this section has the sole purpose of protecting the
|
||||
integrity of the free software distribution system, which is
|
||||
implemented by public license practices. Many people have made
|
||||
generous contributions to the wide range of software distributed
|
||||
through that system in reliance on consistent application of that
|
||||
system; it is up to the author/donor to decide if he or she is willing
|
||||
to distribute software through any other system and a licensee cannot
|
||||
impose that choice.
|
||||
|
||||
This section is intended to make thoroughly clear what is believed to
|
||||
be a consequence of the rest of this License.
|
||||
|
||||
8. If the distribution and/or use of the Program is restricted in
|
||||
certain countries either by patents or by copyrighted interfaces, the
|
||||
original copyright holder who places the Program under this License
|
||||
may add an explicit geographical distribution limitation excluding
|
||||
those countries, so that distribution is permitted only in or among
|
||||
countries not thus excluded. In such case, this License incorporates
|
||||
the limitation as if written in the body of this License.
|
||||
|
||||
9. The Free Software Foundation may publish revised and/or new versions
|
||||
of the General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the Program
|
||||
specifies a version number of this License which applies to it and "any
|
||||
later version", you have the option of following the terms and conditions
|
||||
either of that version or of any later version published by the Free
|
||||
Software Foundation. If the Program does not specify a version number of
|
||||
this License, you may choose any version ever published by the Free Software
|
||||
Foundation.
|
||||
|
||||
10. If you wish to incorporate parts of the Program into other free
|
||||
programs whose distribution conditions are different, write to the author
|
||||
to ask for permission. For software which is copyrighted by the Free
|
||||
Software Foundation, write to the Free Software Foundation; we sometimes
|
||||
make exceptions for this. Our decision will be guided by the two goals
|
||||
of preserving the free status of all derivatives of our free software and
|
||||
of promoting the sharing and reuse of software generally.
|
||||
|
||||
NO WARRANTY
|
||||
|
||||
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
|
||||
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
|
||||
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
|
||||
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
|
||||
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
|
||||
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
|
||||
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
|
||||
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
|
||||
REPAIR OR CORRECTION.
|
||||
|
||||
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
|
||||
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
|
||||
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
|
||||
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
|
||||
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
|
||||
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
|
||||
POSSIBILITY OF SUCH DAMAGES.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
convey the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software; you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation; either version 2 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License along
|
||||
with this program; if not, write to the Free Software Foundation, Inc.,
|
||||
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program is interactive, make it output a short notice like this
|
||||
when it starts in an interactive mode:
|
||||
|
||||
Gnomovision version 69, Copyright (C) year name of author
|
||||
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, the commands you use may
|
||||
be called something other than `show w' and `show c'; they could even be
|
||||
mouse-clicks or menu items--whatever suits your program.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or your
|
||||
school, if any, to sign a "copyright disclaimer" for the program, if
|
||||
necessary. Here is a sample; alter the names:
|
||||
|
||||
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
|
||||
`Gnomovision' (which makes passes at compilers) written by James Hacker.
|
||||
|
||||
<signature of Ty Coon>, 1 April 1989
|
||||
Ty Coon, President of Vice
|
||||
|
||||
This General Public License does not permit incorporating your program into
|
||||
proprietary programs. If your program is a subroutine library, you may
|
||||
consider it more useful to permit linking proprietary applications with the
|
||||
library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License.
|
||||
@@ -0,0 +1,54 @@
|
||||
CONTENTS OF THIS FILE
|
||||
---------------------
|
||||
* Introduction
|
||||
* Requirements
|
||||
* Recommended Modules
|
||||
* Installation
|
||||
* Configuration
|
||||
|
||||
INTRODUCTION
|
||||
------------
|
||||
After a given timeout has passed, users are given a configurable session
|
||||
expiration prompt. They can reset the timeout, logout, or ignore it, in which
|
||||
case they'll be logged out after the padding time is elapsed. This is all backed
|
||||
up by a server side logout if JS is disabled or bypassed.
|
||||
|
||||
REQUIREMENTS
|
||||
------------
|
||||
None.
|
||||
|
||||
RECOMMENDED MODULES
|
||||
-------------------
|
||||
* Session Limit (https://www.drupal.org/project/session_limit)
|
||||
* Password Policy (https://www.drupal.org/project/password_policy)
|
||||
|
||||
INSTALLATION
|
||||
------------
|
||||
* Install as usual:
|
||||
See https://www.drupal.org/documentation/install/modules-themes/modules-8
|
||||
for further information.
|
||||
|
||||
CONFIGURATION
|
||||
-------------
|
||||
* Configure permissions : Home >> Administration >> People
|
||||
(/admin/people/permissions)
|
||||
* Configure Automated logout : Home >> Administration >> Configuration >> People
|
||||
(/admin/config/people/autologout)
|
||||
* Configurable "Global timeout" and "Timeout padding".
|
||||
The latter determines how much time a user has to respond to the prompt
|
||||
and when the server side timeout will occur.
|
||||
* Configurable messaging.
|
||||
* Configurable "Redirect URL" with the destination automatically appended.
|
||||
* Configure which roles will be automatically logged out.
|
||||
* Configure if a logout will occur on admin pages.
|
||||
* Integration with ui.dialog if available.
|
||||
This makes for attractive and more functional dialogs.
|
||||
* Configurable timeout based on user.
|
||||
* Configurable maximum timeout.
|
||||
Primarily used when a user has permission to change their timeout value,
|
||||
this will be a cap or maximum value they can use.
|
||||
* Order of precedence is : user timeout -> lowest role timeout -> global
|
||||
timeout.
|
||||
* So if a user has a user timeout set, that is their timeout threshold,
|
||||
if none is set the lowest timeout value based on all the roles the user
|
||||
belongs to is used, if none is set the global timeout is used.
|
||||
@@ -0,0 +1,49 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* @file
|
||||
* Describe hooks provided by the autologout module.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Prevent autologout logging a user out.
|
||||
*
|
||||
* This allows other modules to indicate that a page should not be included
|
||||
* in the autologout checks. This works in the same way as not ticking the
|
||||
* enforce on admin pages option for autologout which stops a user being logged
|
||||
* out of admin pages.
|
||||
*
|
||||
* @return bool
|
||||
* Return TRUE if you do not want the user to be logged out.
|
||||
* Return FALSE (or nothing) if you want to leave the autologout
|
||||
* process alone.
|
||||
*/
|
||||
function hook_autologout_prevent() {
|
||||
// Don't include autologout JS checks on ajax callbacks.
|
||||
$path_args = explode('/', current_path());
|
||||
$blacklist = [
|
||||
'ajax',
|
||||
'autologout_ahah_logout',
|
||||
'autologout_ahah_set_last',
|
||||
];
|
||||
|
||||
if (in_array($path_args[0], $blacklist)) {
|
||||
return TRUE;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Keep a login alive whilst the user is on a particular page.
|
||||
*
|
||||
* @return bool
|
||||
* By returning TRUE from this function the JS which talks to autologout
|
||||
* module is included in the current page request and periodically dials back
|
||||
* to the server to keep the login alive.
|
||||
* Return FALSE (or nothing) to just use the standard behaviour.
|
||||
*/
|
||||
function hook_autologout_refresh_only() {
|
||||
// Check to see if an open admin page will keep login alive.
|
||||
if (\Drupal::service('router.admin_context')->isAdminRoute(routeMatch()->getRouteObject()) && !\Drupal::config('autologout.settings')->get('enforce_admin')) {
|
||||
return TRUE;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
name: Automated Logout
|
||||
type: module
|
||||
description: 'Adds automated timed logout.'
|
||||
# core: 8.x
|
||||
configure: autologout.set_admin
|
||||
|
||||
# Information added by Drupal.org packaging script on 2017-05-08
|
||||
version: '8.x-1.0'
|
||||
core: '8.x'
|
||||
project: 'autologout'
|
||||
datestamp: 1494237191
|
||||
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
use Drupal\Core\Database\Database;
|
||||
/**
|
||||
* Transfer logouts time settings from configs to states.
|
||||
*/
|
||||
function autologout_update_8001(&$sandbox) {
|
||||
$result = Database::getConnection()
|
||||
->select('config', 'c')
|
||||
->fields('c', ['name', 'data'])
|
||||
->condition('name', 'autologout.user.%', 'LIKE')
|
||||
->execute()->fetchAll();
|
||||
if (!isset($sandbox['current'])) {
|
||||
$sandbox['current'] = 0;
|
||||
$sandbox['max'] = count($result);
|
||||
}
|
||||
$limit = 5;
|
||||
$result = array_slice($result, $sandbox['current'], $limit);
|
||||
foreach ($result as $row) {
|
||||
$key = $row->name;
|
||||
// User uid is a part of the key after. E.g. autologout.user.1 for user 1.
|
||||
$user_id = (substr($key, 16));
|
||||
$data = unserialize($row->data);
|
||||
\Drupal::service('user.data')->set('autologout', $user_id, 'timeout', $data['timeout']);
|
||||
\Drupal::service('user.data')->set('autologout', $user_id, 'enabled', $data['enabled']);
|
||||
$sandbox['current']++;
|
||||
}
|
||||
$sandbox['#finished'] = empty($sandbox['max']) ? 1 : ($sandbox['current'] / $sandbox['max']);
|
||||
if ($sandbox['#finished'] >= 1) {
|
||||
return t('Autologout settings are successfully updated. Updated @users', ["@users" => $sandbox['max']]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
drupal.autologout:
|
||||
version: VERSION
|
||||
js:
|
||||
js/autologout.js: { weight: -2 }
|
||||
|
||||
dependencies:
|
||||
- core/drupal.dialog
|
||||
- core/drupal.ajax
|
||||
- core/drupalSettings
|
||||
@@ -0,0 +1,6 @@
|
||||
autologout.set_admin:
|
||||
title: 'Automated logout settings'
|
||||
parent: user.admin_index
|
||||
description: 'Configure default automated logout settings.'
|
||||
weight: -10
|
||||
route_name: autologout.set_admin
|
||||
@@ -0,0 +1,236 @@
|
||||
<?php
|
||||
|
||||
use Drupal\Core\Url;
|
||||
use Drupal\Core\Form\FormStateInterface;
|
||||
use Drupal\Core\Routing\RouteMatchInterface;
|
||||
|
||||
/**
|
||||
* Implements hook_help().
|
||||
*/
|
||||
function autologout_help($route_name, RouteMatchInterface $route_match) {
|
||||
switch ($route_name) {
|
||||
case 'help.page.autologout':
|
||||
$seconds = \Drupal::service('autologout.manager')->getUserTimeout();
|
||||
$output = '';
|
||||
$output .= '<h3>' . t('About') . '</h3>';
|
||||
$output .= '<p>' . t("This module allows you to force site users to be logged out after a given amount of time due to inactivity after first being presented with a confirmation dialog. Your current logout threshold is %seconds seconds.", ['%seconds' => $seconds]) . '</p>';
|
||||
return $output;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements hook_form_FORM_ID_alter().
|
||||
*
|
||||
* Adds a field to user/edit to change that users logout.
|
||||
*/
|
||||
function autologout_form_user_form_alter(&$form, FormStateInterface $form_state) {
|
||||
$user = \Drupal::currentUser();
|
||||
$account = $form_state->getFormObject()->getEntity();
|
||||
$user_id = $account->id();
|
||||
$access = FALSE;
|
||||
|
||||
// If user has access to change, and they are changing their own and only
|
||||
// their own timeout. Or they are an admin.
|
||||
if (!\Drupal::currentUser()->isAnonymous() && (($user->hasPermission('change own logout threshold') && $user->id() == $user_id) || $user->hasPermission('administer autologout'))) {
|
||||
$access = TRUE;
|
||||
$autologout_data = \Drupal::service('user.data')->get('autologout', $user_id, 'timeout');
|
||||
}
|
||||
|
||||
if ($access) {
|
||||
$form['user_' . $user_id] = [
|
||||
'#type' => 'textfield',
|
||||
'#title' => t('Your current logout threshold'),
|
||||
'#default_value' => isset($autologout_data) ? $autologout_data : '',
|
||||
'#size' => 8,
|
||||
'#description' => t('How many seconds to give a user to respond to the logout dialog before ending their session.'),
|
||||
'#element_validate' => ['_autologout_user_uid_timeout_validate'],
|
||||
];
|
||||
|
||||
$form['actions']['submit']['#submit'][] = 'autologout_user_profile_submit';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Form validation.
|
||||
*/
|
||||
function _autologout_user_uid_timeout_validate($element, FormStateInterface $form_state) {
|
||||
$max_timeout = \Drupal::config('autologout.settings')->get('max_timeout');
|
||||
$timeout = $element['#value'];
|
||||
|
||||
// Set error if timeout isn't strictly a number between 60 and max.
|
||||
if ($timeout != "" && ($timeout < 10 || ($timeout > 0 && $timeout < 60) || $timeout > $max_timeout || !is_numeric($timeout))) {
|
||||
$form_state->setError($element, t('The timeout must be an integer greater than 60, and less then %max.', ['%max' => $max_timeout]));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle submission of timeout threshold in user/edit.
|
||||
*/
|
||||
function autologout_user_profile_submit(&$form, FormStateInterface $form_state) {
|
||||
$user_id = $form_state->getFormObject()->getEntity()->id();
|
||||
|
||||
$timeout = $form_state->getValue('user_' . $user_id);
|
||||
$enabled = ($timeout != '') ? TRUE : FALSE;
|
||||
|
||||
\Drupal::service('user.data')->set('autologout', $user_id, 'timeout', $timeout);
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements hook_autologout_prevent().
|
||||
*/
|
||||
function autologout_autologout_prevent() {
|
||||
$user = \Drupal::currentUser();
|
||||
|
||||
// Don't include autologout JS checks on ajax callbacks.
|
||||
$paths = [
|
||||
'system',
|
||||
'autologout_ajax_get_time_left',
|
||||
'autologout_ahah_logout',
|
||||
'autologout_ahah_set_last',
|
||||
];
|
||||
// getPath is used because Url::fromRoute('<current>')->toString() doesn't
|
||||
// give correct path for XHR request.
|
||||
$url = \Drupal::service('path.current')->getPath();
|
||||
$path_args = explode('/', $url);
|
||||
if (in_array($path_args[1], $paths)) {
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
// If user is anonymous or has no timeout set.
|
||||
if ($user->id() == 0 || (!\Drupal::service('autologout.manager')->getUserTimeout())) {
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
// If the user has checked remember_me via the remember_me module.
|
||||
$remember_me = \Drupal::service('user.data')->get('remember_me', $user->id(), 'remember_me');
|
||||
if (!empty($remember_me)) {
|
||||
return TRUE;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements hook_autologout_refresh_only().
|
||||
*/
|
||||
function autologout_autologout_refresh_only() {
|
||||
if (!\Drupal::config('autologout.settings')->get('enforce_admin') && \Drupal::service('router.admin_context')->isAdminRoute(\Drupal::routeMatch()->getRouteObject())) {
|
||||
return TRUE;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements hook_page_attachments().
|
||||
*
|
||||
* Add a form element to every page which is used to detect if the page was
|
||||
* loaded from browser cache. This happens when the browser's back button is
|
||||
* pressed for example. The JS will set the value of the hidden input element
|
||||
* to 1 after initial load. If this is 1 on subsequent loads, the page was
|
||||
* loaded from cache and an autologout timeout refresh needs to be triggered.
|
||||
*/
|
||||
function autologout_page_attachments(array &$page) {
|
||||
$autologout_manager = \Drupal::service('autologout.manager');
|
||||
|
||||
// Check if JS should be included on this request.
|
||||
if ($autologout_manager->preventJs()) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if anything wants to be refresh only. This URL would include the
|
||||
// javascript but will keep the login alive whilst that page is opened.
|
||||
$refresh_only = $autologout_manager->refreshOnly();
|
||||
|
||||
$settings = \Drupal::config('autologout.settings');
|
||||
|
||||
$timeout = $autologout_manager->getUserTimeout();
|
||||
$timeout_padding = $settings->get('padding');
|
||||
$redirect_url = $settings->get('redirect_url');
|
||||
$redirect_query = \Drupal::service('redirect.destination')->getAsArray() + ['autologout_timeout' => 1];
|
||||
$no_dialog = $settings->get('no_dialog');
|
||||
$use_alt_logout_method = $settings->get('use_alt_logout_method');
|
||||
|
||||
// Get all settings JS will need for dialog.
|
||||
$msg = t('@msg', ['@msg' => $settings->get('message')]);
|
||||
$settings = [
|
||||
'timeout' => $refresh_only ? ($timeout * 500) : ($timeout * 1000),
|
||||
'timeout_padding' => $timeout_padding * 1000,
|
||||
'message' => t('@msg', ['@msg' => $msg]),
|
||||
'redirect_url' => Url::fromUserInput($redirect_url, ['query' => $redirect_query])->toString(),
|
||||
'title' => t('@name Alert', ['@name' => \Drupal::config('system.site')->get('name')]),
|
||||
'refresh_only' => $refresh_only,
|
||||
'no_dialog' => $no_dialog,
|
||||
'use_alt_logout_method' => $use_alt_logout_method,
|
||||
];
|
||||
// If this is an AJAX request, then the logout redirect url should still be
|
||||
// referring to the page that generated this request.
|
||||
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
|
||||
global $base_url;
|
||||
$relative_url = str_replace($base_url . '/', '', $_SERVER['HTTP_REFERER']);
|
||||
$settings['redirect_url'] = Url::fromUserInput($redirect_url, [
|
||||
'query' => ['destination' => urlencode($relative_url)],
|
||||
'autologout_timeout' => 1,
|
||||
]);
|
||||
}
|
||||
|
||||
autologout_attach_js($page, $settings, TRUE);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements hook_page_bottom().
|
||||
*/
|
||||
function autologout_page_bottom() {
|
||||
if (!\Drupal::service('autologout.manager')->preventJs()) {
|
||||
$page_bottom['autologout'] = [
|
||||
'#markup' => '<form id="autologout-cache-check"><input type="hidden" id="autologout-cache-check-bit" value="0" /></form>',
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds the necessary js and libraries.
|
||||
*
|
||||
* @param array $element
|
||||
* The renderable array element to #attach the js to.
|
||||
* @param array $settings
|
||||
* The JS Settings.
|
||||
*/
|
||||
function autologout_attach_js(&$element, $settings) {
|
||||
$element['#attached']['drupalSettings']['autologout'] = $settings;
|
||||
$element['#attached']['library'][] = 'autologout/drupal.autologout';
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements hook_user_login().
|
||||
*
|
||||
* Delete stale sessions for the user on login. This stops
|
||||
* session_limit module thinking the user has reached their
|
||||
* session limit.
|
||||
*/
|
||||
function autologout_user_login($account) {
|
||||
// Cleanup old sessions.
|
||||
$timeout = \Drupal::service('autologout.manager')->getUserTimeout($account->id());
|
||||
|
||||
if (empty($timeout)) {
|
||||
// Users that don't get logged have their sessions left.
|
||||
return;
|
||||
}
|
||||
|
||||
$timeout_padding = \Drupal::config('autologout.settings')->get('padding');
|
||||
$timestamp = REQUEST_TIME - ($timeout + $timeout_padding);
|
||||
|
||||
// Find all stale sessions.
|
||||
$database = \Drupal::database();
|
||||
$sids = $database->select('sessions', 's')
|
||||
->fields('s', ['sid'])
|
||||
->condition('uid', $account->id())
|
||||
->condition('timestamp', $timestamp, '<')
|
||||
->orderBy('timestamp', 'DESC')
|
||||
->execute()
|
||||
->fetchCol();
|
||||
|
||||
if (!empty($sids)) {
|
||||
// Delete stale sessions at login.
|
||||
$database->delete('sessions')
|
||||
->condition('sid', $sids, 'IN')
|
||||
->execute();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
change own logout threshold:
|
||||
title: 'Change own logout threshold'
|
||||
administer autologout:
|
||||
title: 'Administer Autologout'
|
||||
@@ -0,0 +1,34 @@
|
||||
autologout.set_admin:
|
||||
path: '/admin/config/people/autologout'
|
||||
defaults:
|
||||
_form: '\Drupal\autologout\Form\AutologoutSettingsForm'
|
||||
_title: 'Automated logout settings'
|
||||
requirements:
|
||||
_permission: 'administer autologout'
|
||||
|
||||
autologout.ahah_logout:
|
||||
path: '/autologout_ahah_logout'
|
||||
defaults:
|
||||
_controller: '\Drupal\autologout\Controller\AutologoutController::ahahLogout'
|
||||
options:
|
||||
_theme: ajax_base_page
|
||||
requirements:
|
||||
_user_is_logged_in: 'TRUE'
|
||||
|
||||
autologout.ahah_set_last:
|
||||
path: '/autologout_ahah_set_last'
|
||||
defaults:
|
||||
_controller: '\Drupal\autologout\Controller\AutologoutController::ahahSetLast'
|
||||
options:
|
||||
_theme: ajax_base_page
|
||||
requirements:
|
||||
_user_is_logged_in: 'TRUE'
|
||||
|
||||
autologout.ajax_get_time_left:
|
||||
path: '/autologout_ajax_get_time_left'
|
||||
defaults:
|
||||
_controller: '\Drupal\autologout\Controller\AutologoutController::ahahGetRemainingTime'
|
||||
options:
|
||||
_theme: ajax_base_page
|
||||
requirements:
|
||||
_user_is_logged_in: 'TRUE'
|
||||
@@ -0,0 +1,12 @@
|
||||
services:
|
||||
autologout_event_subscriber:
|
||||
class: Drupal\autologout\EventSubscriber\AutologoutSubscriber
|
||||
tags:
|
||||
- {name: event_subscriber}
|
||||
arguments: ['@autologout.manager']
|
||||
|
||||
autologout.manager:
|
||||
class: Drupal\autologout\AutologoutManager
|
||||
tags:
|
||||
- {name: autologout_manager}
|
||||
arguments: ['@module_handler', '@config.factory']
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"name": "drupal/autologout",
|
||||
"description": "Adds automated timed logout.",
|
||||
"type": "drupal-module",
|
||||
"homepage": "http://drupal.org/project/autologout",
|
||||
"license": "GPL-2.0+"
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
timeout: 1800
|
||||
max_timeout: 172800
|
||||
padding: 20
|
||||
role_logout: false
|
||||
redirect_url: /user/login
|
||||
no_dialog: false
|
||||
message: 'Your session is about to expire. Do you want to reset it?'
|
||||
inactivity_message: 'You have been logged out due to inactivity.'
|
||||
enforce_admin: false
|
||||
jstimer_format: '%hours%:%mins%:%secs%'
|
||||
jstimer_js_load_option: false
|
||||
use_alt_logout_method: false
|
||||
use_watchdog: true
|
||||
@@ -0,0 +1,64 @@
|
||||
autologout.settings:
|
||||
type: config_object
|
||||
mapping:
|
||||
timeout:
|
||||
type: integer
|
||||
label: 'Timeout value'
|
||||
max_timeout:
|
||||
type: integer
|
||||
label: 'Max timeout value'
|
||||
padding:
|
||||
type: integer
|
||||
label: 'Seconds to give a user to respond'
|
||||
role_logout:
|
||||
type: boolean
|
||||
label: 'Enable role timeout'
|
||||
redirect_url:
|
||||
type: string
|
||||
label: 'Redirect url'
|
||||
no_dialog:
|
||||
type: boolean
|
||||
label: 'Integer label'
|
||||
message:
|
||||
type: string
|
||||
label: 'Message to display'
|
||||
inactivity_message:
|
||||
type: string
|
||||
label: 'Message displayed after logging out'
|
||||
enforce_admin:
|
||||
type: boolean
|
||||
label: 'Enable admin logout'
|
||||
jstimer_format:
|
||||
type: string
|
||||
label: 'JS timer format'
|
||||
jstimer_js_load_option:
|
||||
type: boolean
|
||||
label: 'JS timer load'
|
||||
use_alt_logout_method:
|
||||
type: boolean
|
||||
label: 'Use alternate logout methode'
|
||||
use_watchdog:
|
||||
type: boolean
|
||||
label: 'Use watchdog'
|
||||
|
||||
autologout.role.*:
|
||||
type: config_object
|
||||
label: 'Role Settings'
|
||||
mapping:
|
||||
enabled:
|
||||
type: boolean
|
||||
label: 'Enabled'
|
||||
timeout:
|
||||
type: integer
|
||||
label: 'Timeout'
|
||||
|
||||
autologout.user.*:
|
||||
type: config_object
|
||||
label: 'User Settings'
|
||||
mapping:
|
||||
enabled:
|
||||
type: boolean
|
||||
label: 'Enabled'
|
||||
timeout:
|
||||
type: integer
|
||||
label: 'Timeout'
|
||||
@@ -0,0 +1,313 @@
|
||||
/**
|
||||
* @file
|
||||
* JavaScript for autologout.
|
||||
*/
|
||||
|
||||
(function ($, Drupal) {
|
||||
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Attaches the batch behavior for autologout.
|
||||
*
|
||||
* @type {Drupal~behavior}
|
||||
*/
|
||||
Drupal.behaviors.autologout = {
|
||||
attach: function (context, settings) {
|
||||
if (context !== document) {
|
||||
return;
|
||||
}
|
||||
|
||||
var paddingTimer;
|
||||
var theDialog;
|
||||
var t;
|
||||
var localSettings;
|
||||
|
||||
// Activity is a boolean used to detect a user has
|
||||
// interacted with the page.
|
||||
var activity;
|
||||
|
||||
// Timer to keep track of activity resets.
|
||||
var activityResetTimer;
|
||||
|
||||
// Prevent settings being overridden by ajax callbacks by cloning it.
|
||||
localSettings = jQuery.extend(true, {}, settings.autologout);
|
||||
|
||||
// Add timer element to prevent detach of all behaviours.
|
||||
var timerMarkup = $('<div id="timer"></div>').hide();
|
||||
$('body').append(timerMarkup);
|
||||
|
||||
if (localSettings.refresh_only) {
|
||||
// On pages where user shouldn't be logged out, don't set the timer.
|
||||
t = setTimeout(keepAlive, localSettings.timeout);
|
||||
}
|
||||
else {
|
||||
// Set no activity to start with.
|
||||
activity = false;
|
||||
|
||||
// Bind formUpdated events to preventAutoLogout event.
|
||||
$('body').bind('formUpdated', function (event) {
|
||||
$(event.target).trigger('preventAutologout');
|
||||
});
|
||||
|
||||
// Bind formUpdated events to preventAutoLogout event.
|
||||
$('body').bind('mousemove', function (event) {
|
||||
$(event.target).trigger('preventAutologout');
|
||||
});
|
||||
|
||||
// Support for CKEditor.
|
||||
if (typeof CKEDITOR !== 'undefined') {
|
||||
CKEDITOR.on('instanceCreated', function (e) {
|
||||
e.editor.on('contentDom', function () {
|
||||
e.editor.document.on('keyup', function (event) {
|
||||
// Keyup event in ckeditor should prevent autologout.
|
||||
$(e.editor.element.$).trigger('preventAutologout');
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
$('body').bind('preventAutologout', function (event) {
|
||||
// When the preventAutologout event fires, we set activity to true.
|
||||
activity = true;
|
||||
|
||||
// Clear timer if one exists.
|
||||
clearTimeout(activityResetTimer);
|
||||
|
||||
// Set a timer that goes off and resets this activity indicator after
|
||||
// a minute, otherwise sessions never timeout.
|
||||
activityResetTimer = setTimeout(function () {
|
||||
activity = false;
|
||||
}, 60000);
|
||||
});
|
||||
|
||||
// On pages where the user should be logged out, set the timer to popup
|
||||
// and log them out.
|
||||
t = setTimeout(init, localSettings.timeout);
|
||||
}
|
||||
|
||||
function init() {
|
||||
var noDialog = settings.autologout.no_dialog;
|
||||
if (activity) {
|
||||
// The user has been active on the page.
|
||||
activity = false;
|
||||
refresh();
|
||||
}
|
||||
else {
|
||||
// The user has not been active, ask them if they want to stay logged
|
||||
// in and start the logout timer.
|
||||
paddingTimer = setTimeout(confirmLogout, localSettings.timeout_padding);
|
||||
// While the countdown timer is going, lookup the remaining time. If
|
||||
// there is more time remaining (i.e. a user is navigating in another
|
||||
// tab), then reset the timer for opening the dialog.
|
||||
Drupal.Ajax['autologout.getTimeLeft'].autologoutGetTimeLeft(function (time) {
|
||||
if (time > 0) {
|
||||
clearTimeout(paddingTimer);
|
||||
t = setTimeout(init, time);
|
||||
}
|
||||
else {
|
||||
// Logout user right away without displaying a confirmation dialog.
|
||||
if (noDialog) {
|
||||
logout();
|
||||
return;
|
||||
}
|
||||
theDialog = dialog();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function dialog() {
|
||||
var buttons = {};
|
||||
buttons[Drupal.t('Yes')] = function () {
|
||||
$(this).dialog("destroy");
|
||||
clearTimeout(paddingTimer);
|
||||
refresh();
|
||||
};
|
||||
|
||||
buttons[Drupal.t('No')] = function () {
|
||||
$(this).dialog("destroy");
|
||||
logout();
|
||||
};
|
||||
|
||||
return $('<div id="autologout-confirm">' + localSettings.message + '</div>').dialog({
|
||||
modal: true,
|
||||
closeOnEscape: false,
|
||||
width: "auto",
|
||||
dialogClass: 'autologout-dialog',
|
||||
title: localSettings.title,
|
||||
buttons: buttons,
|
||||
close: function (event, ui) {
|
||||
logout();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// A user could have used the reset button on the tab/window they're
|
||||
// actively using, so we need to double check before actually logging out.
|
||||
function confirmLogout() {
|
||||
$(theDialog).dialog('destroy');
|
||||
|
||||
Drupal.Ajax['autologout.getTimeLeft'].autologoutGetTimeLeft(function (time) {
|
||||
if (time > 0) {
|
||||
t = setTimeout(init, time);
|
||||
}
|
||||
else {
|
||||
logout();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function logout() {
|
||||
if (localSettings.use_alt_logout_method) {
|
||||
window.location = drupalSettings.path.baseUrl + "autologout_ahah_logout";
|
||||
}
|
||||
else {
|
||||
$.ajax({
|
||||
url: drupalSettings.path.baseUrl + "autologout_ahah_logout",
|
||||
type: "POST",
|
||||
beforeSend: function (xhr) {
|
||||
xhr.setRequestHeader('X-Requested-With', {
|
||||
toString: function (){
|
||||
return '';
|
||||
}
|
||||
});
|
||||
},
|
||||
success: function () {
|
||||
window.location = localSettings.redirect_url;
|
||||
},
|
||||
error: function (XMLHttpRequest, textStatus) {
|
||||
if (XMLHttpRequest.status === 403 || XMLHttpRequest.status === 404) {
|
||||
window.location = localSettings.redirect_url;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the remaining time.
|
||||
*
|
||||
* Use the Drupal ajax library to handle get time remaining events
|
||||
* because if using the JS Timer, the return will update it.
|
||||
*
|
||||
* @param function callback(time)
|
||||
* The function to run when ajax is successful. The time parameter
|
||||
* is the time remaining for the current user in ms.
|
||||
*/
|
||||
Drupal.Ajax.prototype.autologoutGetTimeLeft = function (callback) {
|
||||
var ajax = this;
|
||||
|
||||
if (ajax.ajaxing) {
|
||||
return false;
|
||||
}
|
||||
ajax.options.success = function (response, status) {
|
||||
if (typeof response == 'string') {
|
||||
response = $.parseJSON(response);
|
||||
}
|
||||
if (typeof response[0].command === 'string' && response[0].command === 'alert') {
|
||||
// In the event of an error, we can assume user has been logged out.
|
||||
window.location = localSettings.redirect_url;
|
||||
}
|
||||
|
||||
callback(response[1].settings.time);
|
||||
|
||||
response[0].data = '<div id="timer" style="display: none;">' + response[0].data + '</div>';
|
||||
|
||||
// Let Drupal.ajax handle the JSON response.
|
||||
return ajax.success(response, status);
|
||||
};
|
||||
|
||||
try {
|
||||
$.ajax(ajax.options);
|
||||
}
|
||||
catch (e) {
|
||||
ajax.ajaxing = false;
|
||||
}
|
||||
};
|
||||
|
||||
Drupal.Ajax['autologout.getTimeLeft'] = Drupal.ajax({
|
||||
base: null,
|
||||
element: document.body,
|
||||
url: drupalSettings.path.baseUrl + 'autologout_ajax_get_time_left',
|
||||
event: 'autologout.getTimeLeft',
|
||||
error: function (XMLHttpRequest, textStatus) {
|
||||
// Disable error reporting to the screen.
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* Handle refresh event.
|
||||
*
|
||||
* Use the Drupal ajax library to handle refresh events because if using
|
||||
* the JS Timer, the return will update it.
|
||||
*
|
||||
* @param function timerFunction
|
||||
* The function to tell the timer to run after its been restarted.
|
||||
*/
|
||||
Drupal.Ajax.prototype.autologoutRefresh = function (timerfunction) {
|
||||
var ajax = this;
|
||||
|
||||
if (ajax.ajaxing) {
|
||||
return false;
|
||||
}
|
||||
|
||||
ajax.options.success = function (response, status) {
|
||||
if (typeof response === 'string') {
|
||||
response = $.parseJSON(response);
|
||||
}
|
||||
if (typeof response[0].command === 'string' && response[0].command === 'alert') {
|
||||
// In the event of an error, we can assume the user has been logged out.
|
||||
window.location = localSettings.redirect_url;
|
||||
}
|
||||
|
||||
t = setTimeout(timerfunction, localSettings.timeout);
|
||||
activity = false;
|
||||
|
||||
// Wrap response data in timer markup to prevent detach of all behaviors.
|
||||
response[0].data = '<div id="timer" style="display: none;">' + response[0].data + '</div>';
|
||||
|
||||
// Let Drupal.ajax handle the JSON response.
|
||||
return ajax.success(response, status);
|
||||
};
|
||||
|
||||
try {
|
||||
$.ajax(ajax.options);
|
||||
}
|
||||
catch (e) {
|
||||
ajax.ajaxing = false;
|
||||
}
|
||||
};
|
||||
|
||||
Drupal.Ajax['autologout.refresh'] = Drupal.ajax({
|
||||
base: null,
|
||||
element: document.body,
|
||||
url: drupalSettings.path.baseUrl + 'autologout_ahah_set_last',
|
||||
event: 'autologout.refresh',
|
||||
error: function (XMLHttpRequest, textStatus) {
|
||||
// Disable error reporting to the screen.
|
||||
}
|
||||
});
|
||||
|
||||
function keepAlive() {
|
||||
Drupal.Ajax['autologout.refresh'].autologoutRefresh(keepAlive);
|
||||
}
|
||||
|
||||
function refresh() {
|
||||
Drupal.Ajax['autologout.refresh'].autologoutRefresh(init);
|
||||
}
|
||||
|
||||
// Check if the page was loaded via a back button click.
|
||||
var $dirty_bit = $('#autologout-cache-check-bit');
|
||||
if ($dirty_bit.length !== 0) {
|
||||
if ($dirty_bit.val() === '1') {
|
||||
// Page was loaded via back button click, we should refresh the timer.
|
||||
refresh();
|
||||
}
|
||||
|
||||
$dirty_bit.val('1');
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
})(jQuery, Drupal);
|
||||
@@ -0,0 +1,195 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\autologout;
|
||||
|
||||
use Drupal\Core\Config\ConfigFactoryInterface;
|
||||
use Drupal\Core\Extension\ModuleHandlerInterface;
|
||||
use Drupal\user\Entity\User;
|
||||
use Drupal\Core\Session\AnonymousUserSession;
|
||||
|
||||
/**
|
||||
* Defines an AutologoutManager service.
|
||||
*/
|
||||
class AutologoutManager implements AutologoutManagerInterface {
|
||||
|
||||
/**
|
||||
* The module manager service.
|
||||
*
|
||||
* @var \Drupal\Core\Extension\ModuleHandlerInterface
|
||||
*/
|
||||
protected $moduleHandler;
|
||||
|
||||
/**
|
||||
* The config object for 'autologout.settings'.
|
||||
*
|
||||
* @var \Drupal\Core\Config\Config
|
||||
*/
|
||||
protected $autoLogoutSettings;
|
||||
|
||||
/**
|
||||
* The config factory service.
|
||||
*
|
||||
* @var \Drupal\Core\Config\ConfigFactoryInterface
|
||||
*/
|
||||
protected $configFactory;
|
||||
|
||||
/**
|
||||
* Constructs an AutologoutManager object.
|
||||
*
|
||||
* @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
|
||||
* The module handler.
|
||||
*/
|
||||
public function __construct(ModuleHandlerInterface $module_handler, ConfigFactoryInterface $config_factory) {
|
||||
$this->moduleHandler = $module_handler;
|
||||
$this->autoLogoutSettings = $config_factory->get('autologout.settings');
|
||||
$this->configFactory = $config_factory;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function preventJs() {
|
||||
foreach ($this->moduleHandler->invokeAll('autologout_prevent') as $prevent) {
|
||||
if (!empty($prevent)) {
|
||||
return TRUE;
|
||||
}
|
||||
}
|
||||
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function refreshOnly() {
|
||||
foreach ($this->moduleHandler->invokeAll('autologout_refresh_only') as $module_refresh_only) {
|
||||
if (!empty($module_refresh_only)) {
|
||||
return TRUE;
|
||||
}
|
||||
}
|
||||
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function inactivityMessage() {
|
||||
$message = $this->autoLogoutSettings->get('inactivity_message');
|
||||
if (!empty($message)) {
|
||||
drupal_set_message($message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function logout() {
|
||||
$user = \Drupal::currentUser();
|
||||
|
||||
if ($this->autoLogoutSettings->get('use_watchdog')) {
|
||||
\Drupal::logger('user')->info('Session automatically closed for %name by autologout.', ['%name' => $user->getAccountName()]);
|
||||
}
|
||||
|
||||
// Destroy the current session.
|
||||
$this->moduleHandler->invokeAll('user_logout', [$user]);
|
||||
\Drupal::service('session_manager')->destroy();
|
||||
$user->setAccount(new AnonymousUserSession());
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function getRoleTimeout() {
|
||||
$roles = user_roles(TRUE);
|
||||
$role_timeout = [];
|
||||
|
||||
// Go through roles, get timeouts for each and return as array.
|
||||
foreach ($roles as $name => $role) {
|
||||
$role_settings = $this->configFactory->get('autologout.role.' . $name);
|
||||
if ($role_settings->get('enabled')) {
|
||||
$timeout_role = $role_settings->get('timeout');
|
||||
$role_timeout[$name] = $timeout_role;
|
||||
}
|
||||
}
|
||||
return $role_timeout;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function getRemainingTime() {
|
||||
$timeout = $this->getUserTimeout();
|
||||
$time_passed = isset($_SESSION['autologout_last']) ? REQUEST_TIME - $_SESSION['autologout_last'] : 0;
|
||||
return $timeout - $time_passed;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function createTimer() {
|
||||
return $this->getRemainingTime();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function getUserTimeout($uid = NULL) {
|
||||
if (is_null($uid)) {
|
||||
// If $uid is not provided, use the logged in user.
|
||||
$user = \Drupal::currentUser();
|
||||
}
|
||||
else {
|
||||
$user = User::load($uid);
|
||||
}
|
||||
|
||||
if ($user->id() == 0) {
|
||||
// Anonymous doesn't get logged out.
|
||||
return 0;
|
||||
}
|
||||
$user_timeout = \Drupal::service('user.data')->get('autologout', $user->id(), 'timeout');
|
||||
|
||||
if (is_numeric($user_timeout)) {
|
||||
// User timeout takes precedence.
|
||||
return $user_timeout;
|
||||
}
|
||||
|
||||
// Get role timeouts for user.
|
||||
if ($this->autoLogoutSettings->get('role_logout')) {
|
||||
$user_roles = $user->getRoles();
|
||||
$output = [];
|
||||
$timeouts = $this->getRoleTimeout();
|
||||
foreach ($user_roles as $rid => $role) {
|
||||
if (isset($timeouts[$role])) {
|
||||
$output[$rid] = $timeouts[$role];
|
||||
}
|
||||
}
|
||||
|
||||
// Assign the lowest timeout value to be session timeout value.
|
||||
if (!empty($output)) {
|
||||
// If one of the user's roles has a unique timeout, use this.
|
||||
return min($output);
|
||||
}
|
||||
}
|
||||
|
||||
// If no user or role override exists, return the default timeout.
|
||||
return $this->autoLogoutSettings->get('timeout');
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function logoutRole($user) {
|
||||
if ($this->autoLogoutSettings->get('role_logout')) {
|
||||
foreach ($user->roles as $name => $role) {
|
||||
if ($this->configFactory->get('autologout.role.' . $name . '.enabled')) {
|
||||
return TRUE;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\autologout;
|
||||
|
||||
/**
|
||||
* Interface for AutologoutManager.
|
||||
*/
|
||||
interface AutologoutManagerInterface {
|
||||
|
||||
/**
|
||||
* Get the timer HTML markup.
|
||||
*
|
||||
* @return string
|
||||
* HTML to insert a countdown timer.
|
||||
*/
|
||||
public function createTimer();
|
||||
|
||||
/**
|
||||
* Get the time remaining before logout.
|
||||
*
|
||||
* @return int
|
||||
* Number of seconds remaining.
|
||||
*/
|
||||
public function getRemainingTime();
|
||||
|
||||
/**
|
||||
* Go through every role to get timeout value, default is the global timeout.
|
||||
*
|
||||
* @return int
|
||||
* Number of seconds timeout set for the user role.
|
||||
*/
|
||||
public function getRoleTimeout();
|
||||
|
||||
/**
|
||||
* Get a user's timeout in seconds.
|
||||
*
|
||||
* @param int $uid
|
||||
* (Optional) Provide a user's uid to get the timeout for.
|
||||
* Default is the logged in user.
|
||||
*
|
||||
* @return int
|
||||
* The number of seconds the user can be idle for before being logged out.
|
||||
* A value of 0 means no timeout.
|
||||
*/
|
||||
public function getUserTimeout($uid = NULL);
|
||||
|
||||
/**
|
||||
* Perform Logout.
|
||||
*
|
||||
* Helper to perform the actual logout. Destroys the session of the logged
|
||||
* in user.
|
||||
*/
|
||||
public function logout();
|
||||
|
||||
/**
|
||||
* Helper to determine if a given user should be autologged out.
|
||||
*/
|
||||
public function logoutRole($user);
|
||||
|
||||
/**
|
||||
* Display the inactivity message if required when the user is logged out.
|
||||
*/
|
||||
public function inactivityMessage();
|
||||
|
||||
/**
|
||||
* Determine if autologout should be prevented.
|
||||
*
|
||||
* @return bool
|
||||
* TRUE if there is a reason not to autologout
|
||||
* the current user on the current page.
|
||||
*/
|
||||
public function preventJs();
|
||||
|
||||
/**
|
||||
* Determine if connection should be refreshed.
|
||||
*
|
||||
* @return bool
|
||||
* TRUE if something about the current context should keep the connection
|
||||
* open. FALSE and the standard countdown to autologout applies.
|
||||
*/
|
||||
public function refreshOnly();
|
||||
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user