Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
551ff35344 | ||
|
|
4e1a5c59b5 | ||
|
|
780a55fb00 | ||
|
|
7cbdba45da | ||
|
|
aebcee71b1 | ||
|
|
28b23dcfbc | ||
|
|
50f0d72e62 | ||
|
|
956d8fb1ec | ||
|
|
781d3d5230 | ||
|
|
b7229d0c02 | ||
|
|
6a09dbd486 | ||
|
|
fff698433f | ||
|
|
2004adee70 | ||
|
|
761659ddf0 | ||
|
|
6f7463ad93 | ||
|
|
3e43f73411 | ||
|
|
cfaa928600 | ||
|
|
b98a63475e | ||
|
|
799c739999 | ||
|
|
a4cdf3cfd2 | ||
|
|
1e52fb821c | ||
|
|
41717783ac | ||
|
|
bf0dade005 |
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,12 @@
|
||||
name: 'Date range formatter'
|
||||
type: module
|
||||
description: 'Formats date ranges.'
|
||||
package: Date/Time
|
||||
# core: 8.x
|
||||
dependencies:
|
||||
- datetime_range
|
||||
# Information added by Drupal.org packaging script on 2017-08-11
|
||||
version: '8.x-3.1'
|
||||
core: '8.x'
|
||||
project: 'date_range_formatter'
|
||||
datestamp: 1502454546
|
||||
@@ -0,0 +1 @@
|
||||
<?php
|
||||
+150
@@ -0,0 +1,150 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\date_range_formatter\Plugin\Field\FieldFormatter;
|
||||
|
||||
use Drupal\Core\Field\FieldItemListInterface;
|
||||
use Drupal\Core\Form\FormStateInterface;
|
||||
use Drupal\datetime\Plugin\Field\FieldFormatter\DateTimeCustomFormatter;
|
||||
use Drupal\datetime_range\DateTimeRangeTrait;
|
||||
|
||||
/**
|
||||
* Plugin implementation of the 'Custom' formatter for 'daterange' fields.
|
||||
*
|
||||
* This formatter renders the data range as plain text, with a fully
|
||||
* configurable date format using the PHP date syntax and separator.
|
||||
*
|
||||
* @FieldFormatter(
|
||||
* id = "date_range_without_time",
|
||||
* label = @Translation("Date range (without time)"),
|
||||
* field_types = {
|
||||
* "daterange"
|
||||
* }
|
||||
* )
|
||||
*/
|
||||
class DateRangeFormatterRangeFormatter extends DateTimeCustomFormatter {
|
||||
|
||||
use DateTimeRangeTrait;
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public static function defaultSettings() {
|
||||
return [
|
||||
'separator' => '-',
|
||||
'single' => 'd F Y',
|
||||
'single_all_day' => 'd F Y',
|
||||
'one_day' => 'd F Y',
|
||||
'one_month' => 'd - {d} F Y',
|
||||
'several_months' => 'd F - {d} {F} Y',
|
||||
'several_years' => 'd F Y - {d} {F} {Y}',
|
||||
] + parent::defaultSettings();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function viewElements(FieldItemListInterface $items, $langcode) {
|
||||
$elements = [];
|
||||
|
||||
foreach ($items as $delta => $item) {
|
||||
if (!empty($item->start_date) && !empty($item->end_date)) {
|
||||
/** @var \Drupal\Core\Datetime\DrupalDateTime $start_date */
|
||||
$start_date = $item->start_date->getTimestamp();
|
||||
/** @var \Drupal\Core\Datetime\DrupalDateTime $end_date */
|
||||
$end_date = $item->end_date->getTimestamp();
|
||||
if ($start_date !== $end_date) {
|
||||
$format = $this->getSetting('several_years');
|
||||
if (date('Y', $start_date) === date('Y', $end_date)) {
|
||||
$format = $this->getSetting('several_months');
|
||||
}
|
||||
if (date('m.Y', $start_date) === date('m.Y', $end_date)) {
|
||||
$format = $this->getSetting('one_month');
|
||||
}
|
||||
if (date('d.m.Y', $start_date) === date('d.m.Y', $end_date)) {
|
||||
$format = $this->getSetting('one_day');
|
||||
}
|
||||
|
||||
$date_str = format_date($start_date, 'custom', preg_replace('/\{([a-zA-Z])\}/', '{\\\$1}', t($format)));
|
||||
$matches = array();
|
||||
if (preg_match_all('/\{([a-zA-Z])\}/', $date_str, $matches)) {
|
||||
foreach ($matches[1] as $match) {
|
||||
$date_str = preg_replace('/\{' . $match . '\}/', format_date($end_date, 'custom', $match), $date_str);
|
||||
}
|
||||
}
|
||||
$elements[$delta] = ['#markup' => '<span class="date-display-range">' . $date_str . '</span>',];
|
||||
|
||||
}
|
||||
else {
|
||||
$elements[$delta] = ['#markup' => date($this->getSetting('one_day'), $start_date)];
|
||||
}
|
||||
}
|
||||
}
|
||||
return $elements;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function settingsForm(array $form, FormStateInterface $form_state) {
|
||||
$form = parent::settingsForm($form, $form_state);
|
||||
unset($form['date_format']);
|
||||
$form['single'] = [
|
||||
'#type' => 'textfield',
|
||||
'#title' => t('Date format for single date'),
|
||||
'#default_value' => $this->getSetting('single') ? : 'd F Y',
|
||||
];
|
||||
$form['single_all_day'] = [
|
||||
'#type' => 'textfield',
|
||||
'#title' => t('Date format for the single date if the date is "all day"'),
|
||||
'#default_value' => $this->getSetting('single_all_day') ? : 'd F Y',
|
||||
];
|
||||
$form['one_day'] = [
|
||||
'#type' => 'textfield',
|
||||
'#title' => t('Date format for the single day date range'),
|
||||
'#default_value' => $this->getSetting('one_day') ? : 'd F Y',
|
||||
];
|
||||
$form['one_month'] = [
|
||||
'#type' => 'textfield',
|
||||
'#title' => t('Date format for the single month date range'),
|
||||
'#default_value' => $this->getSetting('one_month') ? : 'd - {d} F Y',
|
||||
];
|
||||
$form['several_months'] = [
|
||||
'#type' => 'textfield',
|
||||
'#title' => t('Date format for the single year date range'),
|
||||
'#default_value' => $this->getSetting('several_months') ? : 'd F - {d} {F} Y',
|
||||
];
|
||||
$form['several_years'] = [
|
||||
'#type' => 'textfield',
|
||||
'#title' => t('Date format for multiple years date range'),
|
||||
'#default_value' => $this->getSetting('several_years') ? : 'd F Y - {d} {F} {Y}',
|
||||
];
|
||||
$form['help'] = [
|
||||
'#type' => 'markup',
|
||||
'#markup' => t('A user-defined date format. See the <a href="@url">PHP manual</a> for available options.', ['@url' => 'http://php.net/manual/function.date.php']) .
|
||||
'<br />' . t('Use letters in braces for end date elements, for example, {d} means the day of the end date.') .
|
||||
'<br />' . t('These format values are translated, for example, t("d F Y") instead of "d F Y" will be used as the actual date format.'),
|
||||
];
|
||||
|
||||
return $form;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function settingsSummary() {
|
||||
$summary = parent::settingsSummary();
|
||||
$summary[] = $this->t('Display date range using formats: @single, @single_all_day, @one_day, @one_month, @several_months, @several_years',
|
||||
array(
|
||||
'@single' => $this->getSetting('single') ? : 'd F Y',
|
||||
'@single_all_day' => $this->getSetting('single_all_day') ? : 'd F Y',
|
||||
'@one_day' => $this->getSetting('one_day') ? : 'd F Y',
|
||||
'@one_month' => $this->getSetting('one_month') ? : 'd - {d} F Y',
|
||||
'@several_months' => $this->getSetting('several_months') ? : 'd F - {d} {F} Y',
|
||||
'@several_years' => $this->getSetting('several_years') ? : 'd F Y - {d} {F} {Y}',
|
||||
)
|
||||
);
|
||||
|
||||
return $summary;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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();
|
||||
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\autologout\Controller;
|
||||
|
||||
use Drupal\autologout\AutologoutManagerInterface;
|
||||
use Symfony\Component\DependencyInjection\ContainerInterface;
|
||||
use Drupal\Core\Ajax;
|
||||
use Drupal\Core\Ajax\AjaxResponse;
|
||||
use Drupal\Core\Controller\ControllerBase;
|
||||
|
||||
/**
|
||||
* Returns responses for autologout module routes.
|
||||
*/
|
||||
class AutologoutController extends ControllerBase {
|
||||
|
||||
/**
|
||||
* The autologout manager service.
|
||||
*
|
||||
* @var \Drupal\autologout\AutologoutManagerInterface
|
||||
*/
|
||||
protected $autoLogoutManager;
|
||||
|
||||
/**
|
||||
* Constructs an AutologoutSubscriber object.
|
||||
*
|
||||
* @param \Drupal\autologout\AutologoutManagerInterface $autologout
|
||||
* The autologout manager service.
|
||||
*/
|
||||
public function __construct(AutologoutManagerInterface $autologout) {
|
||||
$this->autoLogoutManager = $autologout;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public static function create(ContainerInterface $container) {
|
||||
return new static(
|
||||
$container->get('autologout.manager')
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* AJAX callback that performs the actual logout and redirects the user.
|
||||
*/
|
||||
public function ahahLogout() {
|
||||
$this->autoLogoutManager->logout();
|
||||
$response = new AjaxResponse();
|
||||
$response->setStatusCode(200);
|
||||
return $response;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ajax callback to reset the last access session variable.
|
||||
*/
|
||||
public function ahahSetLast() {
|
||||
$_SESSION['autologout_last'] = REQUEST_TIME;
|
||||
|
||||
// Reset the timer.
|
||||
$response = new AjaxResponse();
|
||||
$markup = $this->autoLogoutManager->createTimer();
|
||||
$response->addCommand(new Ajax\ReplaceCommand('#timer', $markup));
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
/**
|
||||
* AJAX callback that returns the time remaining for this user is logged out.
|
||||
*/
|
||||
public function ahahGetRemainingTime() {
|
||||
$time_remaining_ms = $this->autoLogoutManager->getRemainingTime() * 1000;
|
||||
|
||||
// Reset the timer.
|
||||
$response = new AjaxResponse();
|
||||
$markup = $this->autoLogoutManager->createTimer();
|
||||
|
||||
$response->addCommand(new Ajax\ReplaceCommand('#timer', $markup));
|
||||
$response->addCommand(new Ajax\SettingsCommand(['time' => $time_remaining_ms]));
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
}
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\autologout\EventSubscriber;
|
||||
|
||||
use Drupal\autologout\AutologoutManagerInterface;
|
||||
use Symfony\Component\HttpKernel\KernelEvents;
|
||||
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
|
||||
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
|
||||
|
||||
/**
|
||||
* Defines autologout Subscriber.
|
||||
*/
|
||||
class AutologoutSubscriber implements EventSubscriberInterface {
|
||||
|
||||
/**
|
||||
* The autologout manager service.
|
||||
*
|
||||
* @var \Drupal\autologout\AutologoutManagerInterface
|
||||
*/
|
||||
protected $autoLogoutManager;
|
||||
|
||||
/**
|
||||
* Constructs an AutologoutSubscriber object.
|
||||
*
|
||||
* @param \Drupal\autologout\AutologoutManagerInterface $autologout
|
||||
* The autologout manager service.
|
||||
*/
|
||||
public function __construct(AutologoutManagerInterface $autologout) {
|
||||
$this->autoLogoutManager = $autologout;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check for autologout JS.
|
||||
*
|
||||
* @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event
|
||||
* The request event.
|
||||
*/
|
||||
public function onRequest(GetResponseEvent $event) {
|
||||
$autologout_manager = \Drupal::service('autologout.manager');
|
||||
|
||||
$uid = \Drupal::currentUser()->id();
|
||||
|
||||
if ($uid == 0) {
|
||||
if (!empty($_GET['autologout_timeout']) && $_GET['autologout_timeout'] == 1 && empty($_POST)) {
|
||||
$autologout_manager->inactivityMessage();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if ($this->autoLogoutManager->preventJs()) {
|
||||
return;
|
||||
}
|
||||
|
||||
$now = REQUEST_TIME;
|
||||
// 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');
|
||||
|
||||
// We need a backup plan if JS is disabled.
|
||||
if (!$refresh_only && isset($_SESSION['autologout_last'])) {
|
||||
// If time since last access is > timeout + padding, log them out.
|
||||
$diff = $now - $_SESSION['autologout_last'];
|
||||
if ($diff >= ($timeout + (int) $timeout_padding)) {
|
||||
$autologout_manager->logout();
|
||||
// User has changed so force Drupal to remake decisions based on user.
|
||||
global $theme, $theme_key;
|
||||
drupal_static_reset();
|
||||
$theme = NULL;
|
||||
$theme_key = NULL;
|
||||
\Drupal::theme()->getActiveTheme();
|
||||
$autologout_manager->inactivityMessage();
|
||||
}
|
||||
else {
|
||||
$_SESSION['autologout_last'] = $now;
|
||||
}
|
||||
}
|
||||
else {
|
||||
$_SESSION['autologout_last'] = $now;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public static function getSubscribedEvents() {
|
||||
$events[KernelEvents::REQUEST][] = ['onRequest', 100];
|
||||
return $events;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\autologout\Form;
|
||||
|
||||
use Drupal\autologout\AutologoutManagerInterface;
|
||||
use Drupal\Core\Form\FormBase;
|
||||
use Drupal\Core\Form\FormStateInterface;
|
||||
use Symfony\Component\DependencyInjection\ContainerInterface;
|
||||
|
||||
/**
|
||||
* Provides a settings for autologout module.
|
||||
*/
|
||||
class AutologoutBlockForm extends FormBase {
|
||||
|
||||
/**
|
||||
* The autologout manager service.
|
||||
*
|
||||
* @var \Drupal\autologout\AutologoutManagerInterface
|
||||
*/
|
||||
protected $autoLogoutManager;
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function getFormId() {
|
||||
return 'autologout_block_settings';
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs an AutologoutBlockForm object.
|
||||
*
|
||||
* @param \Drupal\autologout\AutologoutManagerInterface $autologout
|
||||
* The autologout manager service.
|
||||
*/
|
||||
public function __construct(AutologoutManagerInterface $autologout) {
|
||||
$this->autoLogoutManager = $autologout;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public static function create(ContainerInterface $container) {
|
||||
return new static(
|
||||
$container->get('autologout.manager')
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function buildForm(array $form, FormStateInterface $form_state) {
|
||||
$form['reset'] = [
|
||||
'#type' => 'button',
|
||||
'#value' => t('Reset Timeout'),
|
||||
'#weight' => 1,
|
||||
'#limit_validation_errors' => FALSE,
|
||||
'#executes_submit_callback' => FALSE,
|
||||
'#ajax' => [
|
||||
'callback' => 'autologout_ahah_set_last',
|
||||
],
|
||||
];
|
||||
|
||||
$form['timer'] = [
|
||||
'#markup' => $this->autoLogoutManager->createTimer(),
|
||||
];
|
||||
|
||||
return parent::buildForm($form, $form_state);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function submitForm(array &$form, FormStateInterface $form_state) {
|
||||
// Submits on block form.
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,315 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\autologout\Form;
|
||||
|
||||
use Drupal\Core\Config\ConfigFactoryInterface;
|
||||
use Drupal\Core\Form\ConfigFormBase;
|
||||
use Drupal\Core\Form\FormStateInterface;
|
||||
use Drupal\Core\Extension\ModuleHandlerInterface;
|
||||
use Symfony\Component\DependencyInjection\ContainerInterface;
|
||||
|
||||
/**
|
||||
* Provides settings for autologout module.
|
||||
*/
|
||||
class AutologoutSettingsForm extends ConfigFormBase {
|
||||
|
||||
/**
|
||||
* The module manager service.
|
||||
*
|
||||
* @var \Drupal\Core\Extension\ModuleHandlerInterface
|
||||
*/
|
||||
protected $moduleHandler;
|
||||
|
||||
/**
|
||||
* Constructs an AutologoutSettingsForm object.
|
||||
*
|
||||
* @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
|
||||
* The factory for configuration objects.
|
||||
* @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
|
||||
* The module manager service.
|
||||
*/
|
||||
public function __construct(ConfigFactoryInterface $config_factory, ModuleHandlerInterface $module_handler) {
|
||||
parent::__construct($config_factory);
|
||||
$this->moduleHandler = $module_handler;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public static function create(ContainerInterface $container) {
|
||||
return new static(
|
||||
$container->get('config.factory'),
|
||||
$container->get('module_handler')
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function getEditableConfigNames() {
|
||||
return ['autologout.settings'];
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function getFormId() {
|
||||
return 'autologout_settings';
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function buildForm(array $form, FormStateInterface $form_state) {
|
||||
$config = $this->config('autologout.settings');
|
||||
$form['timeout'] = [
|
||||
'#type' => 'textfield',
|
||||
'#title' => $this->t('Timeout value in seconds'),
|
||||
'#default_value' => $config->get('timeout'),
|
||||
'#size' => 8,
|
||||
'#weight' => -10,
|
||||
'#description' => $this->t('The length of inactivity time, in seconds, before automated log out. Must be 60 seconds or greater. Will not be used if role timeout is activated.'),
|
||||
];
|
||||
|
||||
$form['max_timeout'] = [
|
||||
'#type' => 'textfield',
|
||||
'#title' => $this->t('Max timeout setting'),
|
||||
'#default_value' => $config->get('max_timeout'),
|
||||
'#size' => 10,
|
||||
'#maxlength' => 12,
|
||||
'#weight' => -8,
|
||||
'#description' => $this->t('The maximum logout threshold time that can be set by users who have the permission to set user level timeouts.'),
|
||||
];
|
||||
|
||||
$form['padding'] = [
|
||||
'#type' => 'textfield',
|
||||
'#title' => $this->t('Timeout padding'),
|
||||
'#default_value' => $config->get('padding'),
|
||||
'#size' => 8,
|
||||
'#weight' => -6,
|
||||
'#description' => $this->t('How many seconds to give a user to respond to the logout dialog before ending their session.'),
|
||||
];
|
||||
|
||||
$form['role_logout'] = [
|
||||
'#type' => 'checkbox',
|
||||
'#title' => $this->t('Role Timeout'),
|
||||
'#default_value' => $config->get('role_logout'),
|
||||
'#weight' => -4,
|
||||
'#description' => $this->t('Enable each role to have its own timeout threshold, a refresh maybe required for changes to take effect. Any role not ticked will use the default timeout value. Any role can have a value of 0 which means that they will never be logged out.'),
|
||||
];
|
||||
|
||||
$form['redirect_url'] = [
|
||||
'#type' => 'textfield',
|
||||
'#title' => $this->t('Redirect URL at logout'),
|
||||
'#default_value' => $config->get('redirect_url'),
|
||||
'#size' => 40,
|
||||
'#description' => $this->t('Send users to this internal page when they are logged out.'),
|
||||
];
|
||||
|
||||
$form['no_dialog'] = [
|
||||
'#type' => 'checkbox',
|
||||
'#title' => $this->t('Do not display the logout dialog'),
|
||||
'#default_value' => $config->get('no_dialog'),
|
||||
'#description' => $this->t('Enable this if you want users to logout right away and skip displaying the logout dialog.'),
|
||||
];
|
||||
|
||||
$form['use_alt_logout_method'] = [
|
||||
'#type' => 'checkbox',
|
||||
'#title' => $this->t('Use alternate logout method'),
|
||||
'#default_value' => $config->get('use_alt_logout_method'),
|
||||
'#description' => $this->t('Normally when auto logout is triggered, it is done via an AJAX service call. Sites that use an SSO provider, such as CAS, are likely to see this request fail with the error "Origin is not allowed by Access-Control-Allow-Origin". The alternate approach is to have the auto logout trigger a page redirect to initiate the logout process instead.'),
|
||||
];
|
||||
|
||||
$form['message'] = [
|
||||
'#type' => 'textarea',
|
||||
'#title' => $this->t('Message to display in the logout dialog'),
|
||||
'#default_value' => $config->get('message'),
|
||||
'#size' => 40,
|
||||
'#description' => $this->t('This message must be plain text as it might appear in a JavaScript confirm dialog.'),
|
||||
];
|
||||
|
||||
$form['inactivity_message'] = [
|
||||
'#type' => 'textarea',
|
||||
'#title' => $this->t('Message to display to the user after they are logged out.'),
|
||||
'#default_value' => $config->get('inactivity_message'),
|
||||
'#size' => 40,
|
||||
'#description' => $this->t('This message is displayed after the user was logged out due to inactivity. You can leave this blank to show no message to the user.'),
|
||||
];
|
||||
|
||||
$form['use_watchdog'] = [
|
||||
'#type' => 'checkbox',
|
||||
'#title' => $this->t('Enable watchdog Automated Logout logging'),
|
||||
'#default_value' => $config->get('use_watchdog'),
|
||||
'#description' => $this->t('Enable logging of automatically logged out users'),
|
||||
];
|
||||
|
||||
$form['enforce_admin'] = [
|
||||
'#type' => 'checkbox',
|
||||
'#title' => $this->t('Enforce auto logout on admin pages'),
|
||||
'#default_value' => $config->get('enforce_admin'),
|
||||
'#description' => $this->t('If checked, then users will be automatically logged out when administering the site.'),
|
||||
];
|
||||
|
||||
if ($this->moduleHandler->moduleExists('jstimer') && $this->moduleHandler->moduleExists('jst_timer')) {
|
||||
$form['jstimer_format'] = [
|
||||
'#type' => 'textfield',
|
||||
'#title' => $this->t('Autologout block time format'),
|
||||
'#default_value' => $config->get('jstimer_format'),
|
||||
'#description' => $this->t('Change the display of the dynamic timer. Available replacement values are: %day%, %month%, %year%, %dow%, %moy%, %years%, %ydays%, %days%, %hours%, %mins%, and %secs%.'),
|
||||
];
|
||||
}
|
||||
|
||||
$form['table'] = [
|
||||
'#type' => 'table',
|
||||
'#weight' => -2,
|
||||
'#header' => [
|
||||
'enable' => $this->t('Enable'),
|
||||
'name' => $this->t('Role Name'),
|
||||
'timeout' => $this->t('Timeout (seconds)'),
|
||||
],
|
||||
'#title' => $this->t('If Enabled every user in role will be logged out based on that roles timeout, unless the user has an individual timeout set.'),
|
||||
'#states' => [
|
||||
'visible' => [
|
||||
// Only show this field when the 'role_logout' checkbox is enabled.
|
||||
':input[name="role_logout"]' => ['checked' => TRUE],
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
foreach (user_roles(TRUE) as $key => $role) {
|
||||
$form['table'][$key] = [
|
||||
'enabled' => [
|
||||
'#type' => 'checkbox',
|
||||
'#default_value' => $this->config('autologout.role.' . $key)->get('enabled'),
|
||||
],
|
||||
'role' => [
|
||||
'#type' => 'item',
|
||||
'#value' => $key,
|
||||
'#markup' => $key,
|
||||
],
|
||||
'timeout' => [
|
||||
'#type' => 'textfield',
|
||||
'#default_value' => $this->config('autologout.role.' . $key)->get('timeout'),
|
||||
'#size' => 8,
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
return parent::buildForm($form, $form_state);
|
||||
}
|
||||
/**
|
||||
* Validate timeout range.
|
||||
*
|
||||
* Checks to see if timeout threshold is outside max/min values. Done here
|
||||
* to centralize and stop repeated code. Hard coded min, configurable max.
|
||||
*
|
||||
* @param int $timeout
|
||||
* The timeout value in seconds to validate.
|
||||
* @param int $max_timeout
|
||||
* (optional) Maximum value of timeout. If not set, system default is used.
|
||||
*
|
||||
* @return bool
|
||||
* Return TRUE or FALSE
|
||||
*/
|
||||
public function timeoutValidate($timeout, $max_timeout = NULL) {
|
||||
$validate = TRUE;
|
||||
if (is_null($max_timeout)) {
|
||||
$max_timeout = $this->config('autologout.settings')->get('max_timeout');
|
||||
}
|
||||
|
||||
if (!is_numeric($timeout) || $timeout < 0 || ($timeout > 0 && $timeout < 60) || $timeout > $max_timeout) {
|
||||
// Less than 60, greater than max_timeout and is numeric.
|
||||
// 0 is allowed now as this means no timeout.
|
||||
$validate = FALSE;
|
||||
}
|
||||
return $validate;
|
||||
}
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function validateForm(array &$form, FormStateInterface $form_state) {
|
||||
$values = $form_state->getValues();
|
||||
$new_stack = [];
|
||||
foreach ($values['table'] as $key => $pair) {
|
||||
if (is_array($pair)) {
|
||||
foreach ($pair as $pairkey => $pairvalue) {
|
||||
$new_stack[$key][$pairkey] = $pairvalue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$max_timeout = $values['max_timeout'];
|
||||
|
||||
if ($values['role_logout']) {
|
||||
// Validate timeouts for each role.
|
||||
foreach (array_keys(user_roles(TRUE)) as $role) {
|
||||
if (empty($new_stack[$role]) || $new_stack[$role]['enabled'] == 0) {
|
||||
// Don't validate role timeouts for non enabled roles.
|
||||
continue;
|
||||
}
|
||||
|
||||
$timeout = $new_stack[$role]['timeout'];
|
||||
$validate = $this->timeoutValidate($timeout, $max_timeout);
|
||||
if (!$validate) {
|
||||
$form_state->setErrorByName('table][' . $role . '][timeout', $this->t('%role role timeout must be an integer greater than 60, less then %max or 0 to disable autologout for that role.', ['%role' => $role, '%max' => $max_timeout]));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$timeout = $values['timeout'];
|
||||
// Validate timeout.
|
||||
if ($timeout < 60) {
|
||||
$form_state->setErrorByName('timeout', $this->t('The timeout value must be an integer 60 seconds or greater.'));
|
||||
}
|
||||
elseif ($max_timeout <= 60) {
|
||||
$form_state->setErrorByName('max_timeout', $this->t('The max timeout must be an integer greater than 60.'));
|
||||
}
|
||||
elseif (!is_numeric($timeout) || ((int) $timeout != $timeout) || $timeout < 60 || $timeout > $max_timeout) {
|
||||
$form_state->setErrorByName('timeout', $this->t('The timeout must be an integer greater than 60 and less then %max.', ['%max' => $max_timeout]));
|
||||
}
|
||||
|
||||
$redirect_url = $values['redirect_url'];
|
||||
|
||||
// Validate redirect url.
|
||||
if (strpos($redirect_url, '/') !== 0) {
|
||||
$form_state->setErrorByName('redirect_url', $this->t("The user-entered string :redirect_url must begin with a '/'", [':redirect_url' => $redirect_url]));
|
||||
}
|
||||
|
||||
parent::validateForm($form, $form_state);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function submitForm(array &$form, FormStateInterface $form_state) {
|
||||
$values = $form_state->getValues();
|
||||
$autologout_settings = $this->config('autologout.settings');
|
||||
|
||||
$autologout_settings->set('timeout', $values['timeout'])
|
||||
->set('max_timeout', $values['max_timeout'])
|
||||
->set('padding', $values['padding'])
|
||||
->set('role_logout', $values['role_logout'])
|
||||
->set('redirect_url', $values['redirect_url'])
|
||||
->set('no_dialog', $values['no_dialog'])
|
||||
->set('message', $values['message'])
|
||||
->set('inactivity_message', $values['inactivity_message'])
|
||||
->set('enforce_admin', $values['enforce_admin'])
|
||||
->set('use_alt_logout_method', $values['use_alt_logout_method'])
|
||||
->set('use_watchdog', $values['use_watchdog'])
|
||||
->save();
|
||||
|
||||
foreach ($values['table'] as $user) {
|
||||
$this->configFactory()->getEditable('autologout.role.' . $user['role'])
|
||||
->set('enabled', $user['enabled'])
|
||||
->set('timeout', $user['timeout'])
|
||||
->save();
|
||||
}
|
||||
|
||||
if (isset($values['jstimer_format'])) {
|
||||
$autologout_settings->set('jstimer_format', $values['jstimer_format'])->save();
|
||||
}
|
||||
|
||||
parent::submitForm($form, $form_state);
|
||||
}
|
||||
|
||||
}
|
||||
+129
@@ -0,0 +1,129 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\autologout\Plugin\Block;
|
||||
|
||||
use Drupal\Core\Block\BlockBase;
|
||||
use Drupal\Core\Config\Config;
|
||||
use Drupal\Core\Datetime\DateFormatterInterface;
|
||||
use Drupal\Core\Extension\ModuleHandlerInterface;
|
||||
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
|
||||
use Symfony\Component\DependencyInjection\ContainerInterface;
|
||||
|
||||
/**
|
||||
* Provides an 'Automated Logout info' block.
|
||||
*
|
||||
* @Block(
|
||||
* id = "autologout_warning_block",
|
||||
* admin_label = @Translation("Automated logout info"),
|
||||
* category = @Translation("User"),
|
||||
* )
|
||||
*/
|
||||
class AutologoutWarningBlock extends BlockBase implements ContainerFactoryPluginInterface {
|
||||
|
||||
/**
|
||||
* The module manager service.
|
||||
*
|
||||
* @var \Drupal\Core\Extension\ModuleHandlerInterface
|
||||
*/
|
||||
protected $moduleHandler;
|
||||
|
||||
/**
|
||||
* The date formatter service.
|
||||
*
|
||||
* @var \Drupal\Core\Datetime\DateFormatterInterface
|
||||
*/
|
||||
protected $dateFormatter;
|
||||
|
||||
/**
|
||||
* The config object for 'autologout.settings'.
|
||||
*
|
||||
* @var \Drupal\Core\Config\Config
|
||||
*/
|
||||
protected $autoLogoutSettings;
|
||||
|
||||
/**
|
||||
* Constructs an AutologoutWarningBlock object.
|
||||
*
|
||||
* @param array $configuration
|
||||
* A configuration array containing information about the plugin instance.
|
||||
* @param string $plugin_id
|
||||
* The plugin_id for the plugin instance.
|
||||
* @param mixed $plugin_definition
|
||||
* The plugin implementation definition.
|
||||
* @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
|
||||
* The module manager service.
|
||||
* @param \Drupal\Core\Datetime\DateFormatterInterface $date_formatter
|
||||
* The date formatter service.
|
||||
* @param \Drupal\Core\Config\Config $autologout_settings
|
||||
* The config object for 'autologout.settings'.
|
||||
*/
|
||||
public function __construct(array $configuration, $plugin_id, $plugin_definition, ModuleHandlerInterface $module_handler, DateFormatterInterface $date_formatter, Config $autologout_settings) {
|
||||
parent::__construct($configuration, $plugin_id, $plugin_definition);
|
||||
$this->moduleHandler = $module_handler;
|
||||
$this->dateFormatter = $date_formatter;
|
||||
$this->autoLogoutSettings = $autologout_settings;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
|
||||
return new static(
|
||||
$configuration,
|
||||
$plugin_id,
|
||||
$plugin_definition,
|
||||
$container->get('module_handler'),
|
||||
$container->get('date.formatter'),
|
||||
$container->get('config.factory')->get('autologout.settings')
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function defaultConfiguration() {
|
||||
// @todo: This is not the place where we should be doing this.
|
||||
$return = [];
|
||||
//if ($this->moduleHandler->moduleExists('jstimer')) {
|
||||
// if (!$this->moduleHandler->moduleExists(('jst_timer'))) {
|
||||
// drupal_set_message($this->t('The "Widget: timer" module must also be enabled for the dynamic countdown to work in the automated logout block.'), 'error');
|
||||
// }
|
||||
|
||||
// if ($this->autoLogoutSettings->get('jstimer_js_load_option') != 1) {
|
||||
// drupal_set_message($this->t("The Javascript timer module's 'Javascript load options' setting should be set to 'Every page' for the dynamic countdown to work in the automated logout block."), 'error');
|
||||
// }
|
||||
//}
|
||||
return $return;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function build() {
|
||||
$autologout_manager = \Drupal::service('autologout.manager');
|
||||
if ($autologout_manager->preventJs()) {
|
||||
|
||||
// Don't display the block if the user is not going
|
||||
// to be logged out on this page.
|
||||
return [];
|
||||
}
|
||||
|
||||
if ($autologout_manager->refreshOnly()) {
|
||||
$markup = $this->t('Autologout does not apply on the current page,
|
||||
you will be kept logged in whilst this page remains open.');
|
||||
}
|
||||
elseif ($this->moduleHandler->moduleExists('jstimer') && $this->moduleHandler->moduleExists('jst_timer')) {
|
||||
return \Drupal::formBuilder()->getForm('Drupal\autologout\Form\AutologoutBlockForm');
|
||||
}
|
||||
else {
|
||||
$timeout = (int) $this->autoLogoutSettings->get('timeout');
|
||||
$markup = $this->t('You will be logged out in @time if this page is not refreshed before then.', ['@time' => $this->dateFormatter->formatInterval($timeout)]);
|
||||
}
|
||||
|
||||
return [
|
||||
'#type' => 'markup',
|
||||
'#markup' => $markup,
|
||||
];
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\autologout\Tests;
|
||||
|
||||
use Drupal\simpletest\WebTestBase;
|
||||
|
||||
/**
|
||||
* Test the Autologout ajax endpoints.
|
||||
*
|
||||
* @description Ensure the AJAX endpoints work as expected
|
||||
*
|
||||
* @group Autologout
|
||||
*/
|
||||
class AutologoutAjaxTest extends WebTestBase {
|
||||
/**
|
||||
* Modules to enable.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = [
|
||||
'node',
|
||||
'system_test',
|
||||
'views',
|
||||
'user',
|
||||
'autologout',
|
||||
'menu_ui',
|
||||
'block',
|
||||
];
|
||||
|
||||
/**
|
||||
* User with admin rights.
|
||||
*/
|
||||
protected $privilegedUser;
|
||||
|
||||
/**
|
||||
* SetUp() performs any pre-requisite tasks that need to happen.
|
||||
*/
|
||||
public function setUp() {
|
||||
parent::setUp();
|
||||
// Create and log in our privileged user.
|
||||
$this->privilegedUser = $this->drupalCreateUser([
|
||||
'access content',
|
||||
'administer site configuration',
|
||||
'access site reports',
|
||||
'access administration pages',
|
||||
'bypass node access',
|
||||
'administer content types',
|
||||
'administer nodes',
|
||||
'administer autologout',
|
||||
'change own logout threshold',
|
||||
]);
|
||||
$this->drupalLogin($this->privilegedUser);
|
||||
|
||||
// Make node page default.
|
||||
$this->config('system.site')->set('page.front', 'node')->save();
|
||||
// Place the User login block on the home page to verify Log out text.
|
||||
$this->drupalPlaceBlock('system_menu_block:account');
|
||||
}
|
||||
|
||||
/**
|
||||
* Test ajax logout callbacks work as expected.
|
||||
*/
|
||||
public function testAutologoutByAjax() {
|
||||
|
||||
$config = \Drupal::configFactory()->getEditable('autologout.settings');
|
||||
$config->set('timeout', 100)
|
||||
->set('padding', 10)
|
||||
->save();
|
||||
|
||||
// Check that the user can access the page after login.
|
||||
$this->drupalGet('node');
|
||||
$this->assertResponse(200, 'Homepage is accessible');
|
||||
$this->assertText(t('Log out'), 'User is still logged in.');
|
||||
|
||||
// Test the time remaining callback works as expected.
|
||||
$result = $this->drupalGetAjax('autologout_ajax_get_time_left');
|
||||
$this->assertResponse(200, 'autologout_ajax_get_time_left is accessible when logged in');
|
||||
$this->assertEqual('insert', $result[0]['command'], 'autologout_ajax_get_time_left returns an insert command for adding the jstimer onto the page');
|
||||
$this->assertEqual('#timer', $result[0]['selector'], 'autologout_ajax_get_time_left specifies the #timer selector.');
|
||||
$this->assert(!empty($result[1]['settings']['time']) && is_int($result[1]['settings']['time']) && $result[1]['settings']['time'] > 0, 'autologout_ajax_get_time_left returns the remaining time as a positive integer');
|
||||
|
||||
// Test that ajax logout works as expected.
|
||||
$this->drupalGet('autologout_ahah_logout');
|
||||
$this->assertResponse(200, 'autologout_ahah_logout is accessible when logged in');
|
||||
|
||||
// Check we are now logged out.
|
||||
$this->drupalGet('node');
|
||||
$this->assertResponse(200, 'Homepage is accessible');
|
||||
$this->assertNoText(t('Log out'), 'User is no longer logged in.');
|
||||
|
||||
// Check further get time remaining requests return access denied.
|
||||
$this->drupalGet('autologout_ajax_get_time_left');
|
||||
$this->assertResponse(403, 'autologout_ajax_get_time_left is not accessible when logged out.');
|
||||
|
||||
// Check further logout requests result in access denied.
|
||||
$this->drupalGet('autologout_ahah_logout');
|
||||
$this->assertResponse(403, 'autologout_ahah_logout is not accessible when logged out.');
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Test ajax stay logged in callbacks work as expected.
|
||||
*/
|
||||
public function testStayloggedInByAjax() {
|
||||
$config = \Drupal::configFactory()->getEditable('autologout.settings');
|
||||
$config->set('timeout', 20)
|
||||
->set('padding', 5)
|
||||
->save();
|
||||
|
||||
// Check that the user can access the page after login.
|
||||
$this->drupalGet('node');
|
||||
$this->assertResponse(200, 'Homepage is accessible');
|
||||
$this->assertText(t('Log out'), 'User is still logged in.');
|
||||
|
||||
// Sleep for half the timeout.
|
||||
sleep(14);
|
||||
|
||||
// Test that ajax stay logged in works.
|
||||
$result = $this->drupalGetAjax('autologout_ahah_set_last');
|
||||
$this->assertResponse(200, 'autologout_ahah_set_last is accessible when logged in.');
|
||||
$this->assertEqual('insert', $result[0]['command'], 'autologout_ajax_set_last returns an insert command for adding the jstimer onto the page');
|
||||
$this->assertEqual('#timer', $result[0]['selector'], 'autologout_ajax_set_last specifies the #timer selector.');
|
||||
|
||||
// Sleep for half the timeout again.
|
||||
sleep(14);
|
||||
|
||||
// Check we are still logged in.
|
||||
$this->drupalGet('node');
|
||||
$this->assertResponse(200, t('Homepage is accessible'));
|
||||
$this->assertText(t('Log out'), t('User is still logged in.'));
|
||||
|
||||
// Logout.
|
||||
$this->drupalGet('autologout_ahah_logout');
|
||||
$this->assertResponse(200, 'autologout_ahah_logout is accessible when logged in.');
|
||||
|
||||
// Check further requests to set last result in 403.
|
||||
$result = $this->drupalGetAjax('autologout_ahah_set_last');
|
||||
$this->assertResponse(403, 'autologout_ahah_set_last is not accessible when logged out.');
|
||||
}
|
||||
|
||||
}
|
||||
+188
@@ -0,0 +1,188 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\autologout\Tests;
|
||||
use Drupal\simpletest\WebTestBase;
|
||||
|
||||
/**
|
||||
* Test session cleanup on login.
|
||||
*
|
||||
* @description Ensure that the autologout module cleans up stale sessions at login
|
||||
*
|
||||
* @group Autologout
|
||||
*/
|
||||
class AutologoutSessionCleanupOnLoginTest extends WebTestBase {
|
||||
/**
|
||||
* Modules to enable.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = ['autologout', 'node'];
|
||||
/**
|
||||
* A store references to different sessions.
|
||||
*/
|
||||
protected $curlHandles = [];
|
||||
protected $loggedInUsers = [];
|
||||
protected $privilegedUser;
|
||||
protected $database;
|
||||
|
||||
/**
|
||||
* SetUp() performs any pre-requisite tasks that need to happen.
|
||||
*/
|
||||
public function setUp() {
|
||||
parent::setUp();
|
||||
// Create and log in our privileged user.
|
||||
$this->privilegedUser = $this->drupalCreateUser(['access content overview',
|
||||
'administer site configuration',
|
||||
'access site reports',
|
||||
'access administration pages',
|
||||
'bypass node access',
|
||||
'administer content types',
|
||||
'administer nodes',
|
||||
'administer autologout',
|
||||
'change own logout threshold',
|
||||
]);
|
||||
$this->database = $this->container->get('database');
|
||||
}
|
||||
|
||||
/**
|
||||
* Test that stale sessions are cleaned up at login.
|
||||
*/
|
||||
public function testSessionCleanupAtLogin() {
|
||||
// For the purposes of the test, set the timeout periods to 5 seconds.
|
||||
$config = \Drupal::configFactory()->getEditable('autologout.settings');
|
||||
$config->set('timeout', 5)
|
||||
->set('padding', 0)
|
||||
->save();
|
||||
|
||||
// Login in session 1.
|
||||
$this->drupalLogin($this->privilegedUser);
|
||||
// Check one active session.
|
||||
$sessions = $this->getSessions($this->privilegedUser);
|
||||
$this->assertEqual(1, count($sessions), 'After initial login there is one active session');
|
||||
|
||||
// Switch sessions.
|
||||
$session1 = $this->stashSession();
|
||||
|
||||
// Login to session 2.
|
||||
$this->drupalLogin($this->privilegedUser);
|
||||
|
||||
// Check two active sessions.
|
||||
$sessions = $this->getSessions($this->privilegedUser);
|
||||
$this->assertEqual(2, count($sessions), 'After second login there is now two active session');
|
||||
|
||||
$this->stashSession();
|
||||
|
||||
// Switch sessions.
|
||||
// Wait for sessions to expire.
|
||||
sleep(6);
|
||||
|
||||
// Login to session 3.
|
||||
$this->drupalLogin($this->privilegedUser);
|
||||
|
||||
// Check one active session.
|
||||
$sessions = $this->getSessions($this->privilegedUser);
|
||||
$this->assertEqual(1, count($sessions), 'After third login, there is 1 active session, two stale sessions were cleaned up.');
|
||||
|
||||
// Switch back to session 1 and check no longer logged in.
|
||||
$this->restoreSession($session1);
|
||||
$this->drupalGet('node');
|
||||
$this->assertNoText(t('Log out'), 'User is no longer logged in on session 1.');
|
||||
|
||||
$this->closeAllSessions();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get active sessions for given user.
|
||||
*/
|
||||
public function getSessions($account) {
|
||||
// Check there is one session in the sessions table.
|
||||
$result = $this->database->select('sessions', 's')
|
||||
->fields('s')
|
||||
->condition('uid', $account->id())
|
||||
->orderBy('timestamp', 'DESC')
|
||||
->execute();
|
||||
$sessions = [];
|
||||
foreach ($result as $session) {
|
||||
$sessions[] = $session;
|
||||
}
|
||||
|
||||
return $sessions;
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialise a new unique session.
|
||||
*
|
||||
* @return string
|
||||
* Unique identifier for the session just stored.
|
||||
* It is the cookiefile name.
|
||||
*/
|
||||
public function stashSession() {
|
||||
if (empty($this->cookieFile)) {
|
||||
// No session to stash.
|
||||
return 0;
|
||||
}
|
||||
|
||||
// The session_id is the current cookieFile.
|
||||
$session_id = $this->cookieFile;
|
||||
|
||||
$this->curlHandles[$session_id] = $this->curlHandle;
|
||||
$this->loggedInUsers[$session_id] = $this->loggedInUser;
|
||||
|
||||
// Reset Curl.
|
||||
unset($this->curlHandle);
|
||||
$this->loggedInUser = FALSE;
|
||||
|
||||
// Set a new unique cookie filename.
|
||||
do {
|
||||
$this->cookieFile = $this->originalFileDirectory . '/' . $this->randomMachineName() . '.jar';
|
||||
} while (isset($this->curlHandles[$this->cookieFile]));
|
||||
|
||||
return $session_id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Restore a previously stashed session.
|
||||
*
|
||||
* @param string $session_id
|
||||
* The session to restore as returned by stashSession();
|
||||
* This is also the path to the cookie file.
|
||||
*
|
||||
* @return string
|
||||
* The old session id that was replaced.
|
||||
*/
|
||||
public function restoreSession($session_id) {
|
||||
$old_session_id = NULL;
|
||||
|
||||
if (isset($this->curlHandle)) {
|
||||
$old_session_id = $this->stashSession();
|
||||
}
|
||||
|
||||
// Restore the specified session.
|
||||
$this->curlHandle = $this->curlHandles[$session_id];
|
||||
$this->cookieFile = $session_id;
|
||||
$this->loggedInUser = $this->loggedInUsers[$session_id];
|
||||
|
||||
return $old_session_id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Close all stashed sessions and the current session.
|
||||
*/
|
||||
public function closeAllSessions() {
|
||||
foreach ($this->curlHandles as $curl_handle) {
|
||||
if (isset($curl_handle)) {
|
||||
curl_close($curl_handle);
|
||||
}
|
||||
}
|
||||
|
||||
// Make the server forget all sessions.
|
||||
$this->database->truncate('sessions')->execute();
|
||||
|
||||
$this->curlHandles = [];
|
||||
$this->loggedInUsers = [];
|
||||
$this->loggedInUser = FALSE;
|
||||
$this->cookieFile = $this->originalFileDirectory . '/' . $this->randomMachineName() . '.jar';
|
||||
unset($this->curlHandle);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,395 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\autologout\Tests;
|
||||
|
||||
use Drupal\simpletest\WebTestBase;
|
||||
|
||||
/**
|
||||
* Tests the autologout's features.
|
||||
*
|
||||
* @description Ensure that the autologout module functions as expected
|
||||
*
|
||||
* @group Autologout
|
||||
*/
|
||||
class AutologoutTest extends WebTestBase {
|
||||
/**
|
||||
* Modules to enable.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = [
|
||||
'node',
|
||||
'system',
|
||||
'system_test',
|
||||
'views',
|
||||
'user',
|
||||
'autologout',
|
||||
'menu_ui',
|
||||
'block',
|
||||
];
|
||||
|
||||
/**
|
||||
* Use the Standard profile to test help implementations of many core modules.
|
||||
*/
|
||||
protected $profile = 'standard';
|
||||
|
||||
/**
|
||||
* User with admin rights.
|
||||
*/
|
||||
protected $privilegedUser;
|
||||
|
||||
/**
|
||||
* The config factory service.
|
||||
*
|
||||
* @var \Drupal\Core\Config\ConfigFactoryInterface
|
||||
*/
|
||||
protected $configFactory;
|
||||
|
||||
/**
|
||||
* Stores the user data service used by the test.
|
||||
*
|
||||
* @var \Drupal\user\UserDataInterface
|
||||
*/
|
||||
public $userData;
|
||||
|
||||
/**
|
||||
* SetUp() performs any pre-requisite tasks that need to happen.
|
||||
*/
|
||||
public function setUp() {
|
||||
parent::setUp();
|
||||
// Create and log in our privileged user.
|
||||
$this->privilegedUser = $this->drupalCreateUser([
|
||||
'access content',
|
||||
'administer site configuration',
|
||||
'access site reports',
|
||||
'access administration pages',
|
||||
'bypass node access',
|
||||
'administer content types',
|
||||
'administer nodes',
|
||||
'administer autologout',
|
||||
'change own logout threshold',
|
||||
'access site reports',
|
||||
'view the administration theme',
|
||||
]);
|
||||
$this->drupalLogin($this->privilegedUser);
|
||||
|
||||
$this->configFactory = $this->container->get('config.factory');
|
||||
$this->userData = $this->container->get('user.data');
|
||||
|
||||
$config = $this->configFactory->getEditable('autologout.settings');
|
||||
// For the purposes of the test, set the timeout periods to 10 seconds.
|
||||
$config->set('timeout', 10)
|
||||
->save();
|
||||
|
||||
$this->drupalLogin($this->privilegedUser);
|
||||
|
||||
// Make node page default.
|
||||
$this->configFactory->getEditable('system.site')->set('page.front', 'node')->save();
|
||||
// Place the User login block on the home page to verify Log out text.
|
||||
$this->drupalPlaceBlock('system_menu_block:account');
|
||||
}
|
||||
|
||||
/**
|
||||
* Test the precedence of the timeouts.
|
||||
*
|
||||
* This tests the following function:
|
||||
* _autologout_get_user_timeout();
|
||||
*/
|
||||
public function testAutologoutTimeoutPrecedence() {
|
||||
$autologout_settings = $this->configFactory->getEditable('autologout.settings');
|
||||
$autologout_role_settings = $this->configFactory->getEditable('autologout.role.authenticated');
|
||||
$uid = $this->privilegedUser->id();
|
||||
$autologout_user_settings = \Drupal::service('user.data');
|
||||
|
||||
// Default used if no role is specified.
|
||||
$autologout_settings->set('timeout', 100)
|
||||
->set('role_logout', FALSE)
|
||||
->save();
|
||||
$autologout_role_settings->set('enabled', FALSE)
|
||||
->set('timeout', 200)
|
||||
->save();
|
||||
$this->assertAutotimeout($uid, 100, 'User timeout uses default if no other option set');
|
||||
|
||||
// Default used if role selected but no user's role is selected.
|
||||
$autologout_settings->set('role_logout', TRUE)
|
||||
->save();
|
||||
$autologout_role_settings->set('enabled', FALSE)
|
||||
->set('timeout', 200)
|
||||
->save();
|
||||
$this->assertAutotimeout($uid, 100, 'User timeout uses default if role timeouts are used but not one of the current user.');
|
||||
|
||||
// Role timeout is used if user's role is selected.
|
||||
$autologout_settings->set('role_logout', TRUE)
|
||||
->save();
|
||||
$autologout_role_settings->set('enabled', TRUE)
|
||||
->set('timeout', 200)
|
||||
->save();
|
||||
$this->assertAutotimeout($uid, 200, 'User timeout uses role value');
|
||||
|
||||
// Role timeout is used if user's role is selected.
|
||||
$autologout_settings->set('role_logout', TRUE)
|
||||
->save();
|
||||
$autologout_role_settings->set('enabled', TRUE)
|
||||
->set('timeout', 0)
|
||||
->save();
|
||||
$this->assertAutotimeout($uid, 0, 'User timeout uses role value of 0 if set for one of the user roles.');
|
||||
|
||||
// Role timeout used if personal timeout is empty string.
|
||||
$autologout_settings->set('role_logout', TRUE)
|
||||
->save();
|
||||
$autologout_role_settings->set('enabled', TRUE)
|
||||
->set('timeout', 200)
|
||||
->save();
|
||||
$autologout_user_settings->set('autologout', $uid, 'timeout', '');
|
||||
$autologout_user_settings->set('autologout', $uid, 'enabled', FALSE);
|
||||
$this->assertAutotimeout($uid, 200, 'User timeout uses role value if personal value is the empty string.');
|
||||
|
||||
// Default timeout used if personal timeout is empty string.
|
||||
$autologout_settings->set('role_logout', TRUE)
|
||||
->save();
|
||||
$autologout_role_settings->set('enabled', FALSE)
|
||||
->set('timeout', 200)
|
||||
->save();
|
||||
$autologout_user_settings->set('autologout', $uid, 'timeout', '');
|
||||
$autologout_user_settings->set('autologout', $uid, 'enabled', FALSE);
|
||||
$this->assertAutotimeout($uid, 100, 'User timeout uses default value if personal value is the empty string and no role timeout is specified.');
|
||||
|
||||
// Personal timeout used if set.
|
||||
$autologout_settings->set('role_logout', TRUE)
|
||||
->save();
|
||||
$autologout_role_settings->set('enabled', FALSE)
|
||||
->set('timeout', 200)
|
||||
->save();
|
||||
$autologout_user_settings->set('autologout', $uid, 'timeout', 300);
|
||||
$autologout_user_settings->set('autologout', $uid, 'enabled', TRUE);
|
||||
$this->assertAutotimeout($uid, 300, 'User timeout uses default value if personal value is the empty string and no role timeout is specified.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Test a user is logged out after the default timeout period.
|
||||
*/
|
||||
public function testAutologoutDefaultTimeout() {
|
||||
// Check that the user can access the page after login.
|
||||
$this->drupalGet('node');
|
||||
$this->assertResponse(200, 'Homepage is accessible');
|
||||
$this->assertText('Log out', 'User is still logged in.');
|
||||
|
||||
// Wait for timeout period to elapse.
|
||||
sleep(30);
|
||||
|
||||
// Check we are now logged out.
|
||||
$this->drupalGet('node');
|
||||
$this->assertResponse(200, 'Homepage is accessible');
|
||||
$this->assertNoRaw(t('Log out'), 'User is no longer logged in.');
|
||||
$this->assertText(t('You have been logged out due to inactivity.'), 'User sees inactivity message.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Test a user is not logged out within the default timeout period.
|
||||
*/
|
||||
public function testAutologoutNoLogoutInsideTimeout() {
|
||||
// Check that the user can access the page after login.
|
||||
$this->drupalGet('node');
|
||||
$this->assertResponse(200, 'Homepage is accessible');
|
||||
$this->assertText(t('Log out'), 'User is still logged in.');
|
||||
|
||||
// Wait within the timeout period.
|
||||
sleep(10);
|
||||
|
||||
// Check we are still logged in.
|
||||
$this->drupalGet('node');
|
||||
$this->assertResponse(200, 'Homepage is accessible');
|
||||
$this->assertText(t('Log out'), 'User is still logged in.');
|
||||
$this->assertNoText(t('You have been logged out due to inactivity.'), 'User does not see inactivity message.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Test the behaviour of the settings for submission.
|
||||
*/
|
||||
public function testAutologoutSettingsForm() {
|
||||
$edit = [];
|
||||
$autologout_settings = $this->configFactory->getEditable('autologout.settings');
|
||||
$autologout_settings->set('max_timeout', 1000)
|
||||
->save();
|
||||
|
||||
$roles = user_roles(TRUE);
|
||||
// Unset authenticated, as it will be used to add manual value later.
|
||||
unset($roles['authenticated']);
|
||||
|
||||
// Test that it is possible to set a value above the max_timeout
|
||||
// threshold.
|
||||
$edit['timeout'] = 1500;
|
||||
$edit['max_timeout'] = 2000;
|
||||
$edit['padding'] = 60;
|
||||
$edit['role_logout'] = TRUE;
|
||||
$edit['table[authenticated][enabled]'] = TRUE;
|
||||
$edit['table[authenticated][timeout]'] = 1200;
|
||||
foreach ($roles as $key => $role) {
|
||||
$edit['table[' . $key . '][enabled]'] = TRUE;
|
||||
$edit['table[' . $key . '][timeout]'] = 1200;
|
||||
}
|
||||
$edit['redirect_url'] = '/user/login';
|
||||
|
||||
$this->drupalPostForm('admin/config/people/autologout', $edit, t('Save configuration'));
|
||||
$this->assertText(t('The configuration options have been saved.'), 'Unable to save autologout config when modifying the max timeout.');
|
||||
|
||||
// Test that out of range values are picked up.
|
||||
$edit['timeout'] = 2500;
|
||||
$edit['max_timeout'] = 2000;
|
||||
$edit['padding'] = 60;
|
||||
$edit['role_logout'] = TRUE;
|
||||
$edit['table[authenticated][enabled]'] = TRUE;
|
||||
$edit['table[authenticated][timeout]'] = 1200;
|
||||
foreach ($roles as $key => $role) {
|
||||
$edit['table[' . $key . '][enabled]'] = TRUE;
|
||||
$edit['table[' . $key . '][timeout]'] = 1200;
|
||||
}
|
||||
$edit['redirect_url'] = '/user/login';
|
||||
$this->drupalPostForm('admin/config/people/autologout', $edit, t('Save configuration'));
|
||||
$this->assertNoText(t('The configuration options have been saved.'), 'Saved configuration despite the autologout_timeout being too large.');
|
||||
|
||||
// Test that out of range values are picked up.
|
||||
$edit['timeout'] = 1500;
|
||||
$edit['max_timeout'] = 2000;
|
||||
$edit['padding'] = 60;
|
||||
$edit['role_logout'] = TRUE;
|
||||
$edit['table[authenticated][enabled]'] = TRUE;
|
||||
$edit['table[authenticated][timeout]'] = 2500;
|
||||
foreach ($roles as $key => $role) {
|
||||
$edit['table[' . $key . '][enabled]'] = TRUE;
|
||||
$edit['table[' . $key . '][timeout]'] = 1200;
|
||||
}
|
||||
$edit['redirect_url'] = '/user/login';
|
||||
$this->drupalPostForm('admin/config/people/autologout', $edit, t('Save configuration'));
|
||||
$this->assertNoText(t('The configuration options have been saved.'), 'Saved configuration despite a role timeout being too large.');
|
||||
|
||||
// Test that role timeouts are not validated for disabled roles.
|
||||
$edit['timeout'] = 1500;
|
||||
$edit['max_timeout'] = 2000;
|
||||
$edit['padding'] = 60;
|
||||
$edit['role_logout'] = TRUE;
|
||||
$edit['table[authenticated][enabled]'] = FALSE;
|
||||
$edit['table[authenticated][timeout]'] = 4000;
|
||||
foreach ($roles as $key => $role) {
|
||||
$edit['table[' . $key . '][enabled]'] = FALSE;
|
||||
$edit['table[' . $key . '][timeout]'] = 1200;
|
||||
}
|
||||
$edit['redirect_url'] = '/user/login';
|
||||
|
||||
$this->drupalPostForm('admin/config/people/autologout', $edit, t('Save configuration'));
|
||||
$this->assertText(t('The configuration options have been saved.'), 'Unable to save autologout due to out of range role timeout for a role which is not enabled..');
|
||||
}
|
||||
|
||||
/**
|
||||
* Test a user is logged out and denied access to admin pages.
|
||||
*/
|
||||
public function testAutologoutDefaultTimeoutAccessDeniedToAdmin() {
|
||||
$autologout_settings = $this->configFactory->getEditable('autologout.settings');
|
||||
// Enforce auto logout of admin pages.
|
||||
$autologout_settings->set('enforce_admin', FALSE)
|
||||
->save();
|
||||
|
||||
// Check that the user can access the page after login.
|
||||
$this->drupalGet('admin/reports/status');
|
||||
$this->assertResponse(200, 'Admin page is accessible');
|
||||
$this->assertText(t("Here you can find a short overview of your site's parameters as well as any problems detected with your installation."), 'User can access elements of the admin page.');
|
||||
|
||||
// Wait for timeout period to elapse.
|
||||
sleep(30);
|
||||
|
||||
// Check we are now logged out.
|
||||
$this->drupalGet('admin/reports/status');
|
||||
$this->assertResponse(403, 'Admin page returns 403 access denied.');
|
||||
$this->assertNoText(t('Log out'), 'User is no longer logged in.');
|
||||
$this->assertNoText(t("Here you can find a short overview of your site's parameters as well as any problems detected with your installation."), 'User cannot access elements of the admin page.');
|
||||
$this->assertText(t('You have been logged out due to inactivity.'), 'User sees inactivity message.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Test integration with the remember me module.
|
||||
*
|
||||
* Users who checked remember_me on login should never be logged out.
|
||||
*/
|
||||
public function testNoAutologoutWithRememberMe() {
|
||||
// Set the remember_me module data bit to TRUE.
|
||||
$this->userData->set('remember_me', $this->privilegedUser->id(), 'remember_me', TRUE);
|
||||
|
||||
// Check that the user can access the page after login.
|
||||
$this->drupalGet('node');
|
||||
$this->assertResponse(200, 'Homepage is accessible');
|
||||
$this->assertText(t('Log out'), 'User is still logged in.');
|
||||
|
||||
// Wait for timeout period to elapse.
|
||||
sleep(30);
|
||||
|
||||
// Check we are still logged in.
|
||||
$this->drupalGet('node');
|
||||
$this->assertResponse(200, 'Homepage is accessible');
|
||||
$this->assertText(t('Log out'), 'User is still logged in after timeout with remember_me on.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Test the behaviour of custom message displayed on autologout.
|
||||
*/
|
||||
public function testCustomMessage() {
|
||||
$autologout_settings = $this->configFactory->getEditable('autologout.settings');
|
||||
$inactivity_message = 'Custom message for test';
|
||||
|
||||
// Update message string in configuration.
|
||||
$autologout_settings->set('inactivity_message', $inactivity_message)
|
||||
->save();
|
||||
|
||||
// Set time out for 10 seconds.
|
||||
$autologout_settings->set('timeout', 10)
|
||||
->save();
|
||||
|
||||
// Wait for 20 seconds for timeout.
|
||||
sleep(30);
|
||||
|
||||
// Access the admin page and verify user is logged out and custom message
|
||||
// is displayed.
|
||||
$this->drupalGet('admin/reports/status');
|
||||
$this->assertText($inactivity_message, 'User sees custom message');
|
||||
}
|
||||
|
||||
/**
|
||||
* Test the behaviour of application when Autologout is enabled for admin.
|
||||
*/
|
||||
public function testAutologoutAdminPages() {
|
||||
|
||||
$autologout_settings = $this->configFactory->getEditable('autologout.settings');
|
||||
// Enforce auto logout of admin pages.
|
||||
$autologout_settings->set('enforce_admin', TRUE)
|
||||
->save();
|
||||
// Set time out as 10 seconds.
|
||||
$autologout_settings->set('timeout', 10)
|
||||
->save();
|
||||
// Verify admin should not be logged out.
|
||||
$this->drupalGet('admin/reports/status');
|
||||
$this->assertResponse('200', 'Admin pages are accessible');
|
||||
|
||||
// Wait until timeout.
|
||||
sleep(30);
|
||||
|
||||
// Verify admin should be logged out.
|
||||
$this->drupalGet('admin/reports/status');
|
||||
$this->assertText(t('You have been logged out due to inactivity.'), 'User sees inactivity message.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Assert the timeout for a particular user.
|
||||
*
|
||||
* @param int $uid
|
||||
* User uid to assert the timeout for.
|
||||
* @param int $expected_timeout
|
||||
* The expected timeout.
|
||||
* @param string $message
|
||||
* The test message.
|
||||
* @param string $group
|
||||
* The test grouping.
|
||||
*/
|
||||
public function assertAutotimeout($uid, $expected_timeout, $message = '', $group = '') {
|
||||
return $this->assertEqual(\Drupal::service('autologout.manager')->getUserTimeout($uid), $expected_timeout, $message, $group);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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,44 @@
|
||||
Email Registration allows users to register and login with their e-mail address
|
||||
instead of using a separate username in addition to the e-mail address. It will
|
||||
automatically generate a username based on the e-mail address but that behavior
|
||||
can be overridden with a custom hook implementation in a site specific module.
|
||||
|
||||
INSTALLATION
|
||||
============
|
||||
|
||||
Required step:
|
||||
|
||||
1. Enable the module as you normally would.
|
||||
|
||||
|
||||
Optional steps:
|
||||
|
||||
2. You will probably want to change the welcome e-mail
|
||||
(Administer -> User Management -> User Settings) and replace instances of
|
||||
the token !username with !mailto
|
||||
|
||||
3. This automatically generated username is still displayed name for posts,
|
||||
comments, etc. You can allow your users to change their username by
|
||||
going to: (Administer -> User Management -> Access Control) and granting
|
||||
the permission to "change own username"
|
||||
This privilege allows a user to change their username in "My Account".
|
||||
|
||||
4. If a user enters an invalid email or password they will see a message:
|
||||
"Sorry, unrecognized username or password. Have you forgotten your password?"
|
||||
That message is confusing because it mentions username when all other
|
||||
language on the page mentions entering their E-mail. This can be easily
|
||||
overridden in your settings.php file with an entry like this:
|
||||
|
||||
$conf['locale_custom_strings_en'][''] = array(
|
||||
'Sorry, unrecognized username or password. <a href="@password">Have you forgotten your password?</a>' => 'Sorry, unrecognized e-mail or password. <a href="@password">Have you forgotten your password?</a>',
|
||||
);
|
||||
|
||||
|
||||
|
||||
|
||||
BUGS, FEATURES, QUESTIONS
|
||||
=========================
|
||||
Post any bugs, features or questions to the issue queue:
|
||||
|
||||
http://drupal.org/project/issues/email_registration
|
||||
|
||||
+1
@@ -0,0 +1 @@
|
||||
login_with_username: FALSE
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
email_registration.settings:
|
||||
type: config_object
|
||||
label: 'Email registration config'
|
||||
mapping:
|
||||
login_with_username:
|
||||
type: boolean
|
||||
label: 'Allow users to log in with e-mail or username.'
|
||||
@@ -0,0 +1,37 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* @file
|
||||
* Documentation for email_registration module API.
|
||||
*/
|
||||
|
||||
use Drupal\user\UserInterface;
|
||||
|
||||
/**
|
||||
* @addtogroup hooks
|
||||
* @{
|
||||
*/
|
||||
|
||||
/**
|
||||
* Implement this hook to generate a username for email_registration module.
|
||||
*
|
||||
* Other modules may implement hook_email_registration_name($account)
|
||||
* to generate a username (return a string to be used as the username, NULL
|
||||
* to have email_registration generate it).
|
||||
*
|
||||
* @param \Drupal\user\UserInterface $account
|
||||
* The user object on which the operation is being performed.
|
||||
*
|
||||
* @return string
|
||||
* A string defining a generated username.
|
||||
*/
|
||||
function hook_email_registration_name(UserInterface $account) {
|
||||
// Your hook implementation should ensure that the resulting string
|
||||
// works as a username. You can use email_registration_cleanup_username($name)
|
||||
// to clean up the name.
|
||||
return email_registration_cleanup_username('u' . $account->id());
|
||||
}
|
||||
|
||||
/**
|
||||
* @} End of "addtogroup hooks".
|
||||
*/
|
||||
@@ -0,0 +1,12 @@
|
||||
name: Email Registration
|
||||
type: module
|
||||
description: 'Allows users to register with an e-mail address as their username.'
|
||||
# core: 8.x
|
||||
dependencies:
|
||||
- drupal:user
|
||||
|
||||
# Information added by Drupal.org packaging script on 2017-04-04
|
||||
version: '8.x-1.0-rc5'
|
||||
core: '8.x'
|
||||
project: 'email_registration'
|
||||
datestamp: 1491318185
|
||||
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* @file
|
||||
* Update and installation requirement hooks for the Email Registration module.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Implements hook_requirements().
|
||||
*/
|
||||
function email_registration_requirements() {
|
||||
$requirements = array();
|
||||
|
||||
// @todo Get rid of variable_get() and check is this conflict still valid.
|
||||
if (\Drupal::moduleHandler()->moduleExists('logintoboggan') && \Drupal::config('logintoboggan.settings')->get('login_with_email')) {
|
||||
$requirements['email_registration'] = array(
|
||||
'title' => t('Email Registration / LoginToboggan Conflict'),
|
||||
'value' => t('Conflict'),
|
||||
'description' => t('There is a conflict between %email_registration and %logintoboggan. You should disable the "Allow users to login using their e-mail address" option from %logintoboggan.', array('%email_registration' => 'Email registration', '%logintoboggan' => 'Login Toboggan')),
|
||||
'severity' => REQUIREMENT_ERROR,
|
||||
);
|
||||
}
|
||||
|
||||
return $requirements;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add an option to log in with the username as well as the e-mail address.
|
||||
*/
|
||||
function email_registration_update_8100() {
|
||||
$config_factory = \Drupal::configFactory();
|
||||
$email_registration = $config_factory->getEditable('email_registration.settings');
|
||||
$email_registration->set('login_with_username', FALSE);
|
||||
$email_registration->save();
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* @file
|
||||
* Allows users to register with an e-mail address as their username.
|
||||
*/
|
||||
|
||||
use Drupal\Component\Utility\Unicode;
|
||||
use Drupal\user\UserInterface;
|
||||
use Drupal\Core\Render\Element\Email;
|
||||
use Drupal\Core\Form\FormStateInterface;
|
||||
use Drupal\Core\Url;
|
||||
|
||||
/**
|
||||
* Implements hook_ENTITY_TYPE_insert().
|
||||
*
|
||||
* Alter the user name (after entity being stored).
|
||||
*/
|
||||
function email_registration_user_insert(UserInterface $account) {
|
||||
// Don't create a new username if one is already set.
|
||||
$name = $account->getAccountName();
|
||||
if (!empty($name) && strpos($name, 'email_registration_') !== 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Other modules may implement hook_email_registration_name($edit, $account)
|
||||
// to generate a username (return a string to be used as the username, NULL
|
||||
// to have email_registration generate it).
|
||||
$names = Drupal::moduleHandler()->invokeAll('email_registration_name', array($account));
|
||||
// Remove any empty entries.
|
||||
$names = array_filter($names);
|
||||
|
||||
if (empty($names)) {
|
||||
// Strip off everything after the @ sign.
|
||||
$new_name = preg_replace('/@.*$/', '', $account->getEmail());
|
||||
// Clean up the username.
|
||||
$new_name = email_registration_cleanup_username($new_name);
|
||||
}
|
||||
else {
|
||||
// One would expect a single implementation of the hook, but if there
|
||||
// are multiples out there use the last one.
|
||||
$new_name = array_pop($names);
|
||||
}
|
||||
|
||||
// Ensure whatever name we have is unique.
|
||||
$new_name = email_registration_unique_username($new_name, $account->id());
|
||||
|
||||
$account->setUsername($new_name);
|
||||
if ($account->isValidationRequired() && !$account->validate()) {
|
||||
\Drupal::logger('email_registration')->error('Email registration failed setting the new name on user @id.', ['@id' => $account->id()]);
|
||||
return;
|
||||
}
|
||||
$account->save();
|
||||
}
|
||||
|
||||
/**
|
||||
* Makes the username unique.
|
||||
*
|
||||
* Given a starting point for a Drupal username (e.g. the name portion of an
|
||||
* email address) return a legal, unique Drupal username. This function is
|
||||
* designed to work on the results of the /user/register or /admin/people/create
|
||||
* forms which have already called user_validate_name, valid_email_address
|
||||
* or a similar function. If your custom code is creating users, you should
|
||||
* ensure that the email/name is already validated using something like that.
|
||||
*
|
||||
* @param string $name
|
||||
* A name from which to base the final user name.
|
||||
* May contain illegal characters; these will be stripped.
|
||||
* @param int $uid
|
||||
* (optional) Uid to ignore when searching for unique user
|
||||
* (e.g. if we update the username after the {users} row is inserted).
|
||||
*
|
||||
* @return string
|
||||
* A unique user name based on $name.
|
||||
*
|
||||
* @see user_validate_name()
|
||||
*/
|
||||
function email_registration_unique_username($name, $uid = 0) {
|
||||
// Iterate until we find a unique name.
|
||||
$i = 0;
|
||||
$database = \Drupal::database();
|
||||
do {
|
||||
$new_name = empty($i) ? $name : $name . '_' . $i;
|
||||
$found = $database->queryRange("SELECT uid from {users_field_data} WHERE uid <> :uid AND name = :name", 0, 1, array(':uid' => $uid, ':name' => $new_name))->fetchAssoc();
|
||||
$i++;
|
||||
} while (!empty($found));
|
||||
|
||||
return $new_name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cleans up username.
|
||||
*
|
||||
* Run username sanitation, e.g.:
|
||||
* Replace two or more spaces with a single underscore
|
||||
* Strip illegal characters.
|
||||
*
|
||||
* @param string $name
|
||||
* The username to be cleaned up.
|
||||
*
|
||||
* @return string
|
||||
* Cleaned up username.
|
||||
*/
|
||||
function email_registration_cleanup_username($name) {
|
||||
// Strip illegal characters.
|
||||
$name = preg_replace('/[^\x{80}-\x{F7} a-zA-Z0-9@_.\'-]/', '', $name);
|
||||
|
||||
// Strip leading and trailing spaces.
|
||||
$name = trim($name);
|
||||
|
||||
// Convert any other series of spaces to a single underscore.
|
||||
$name = preg_replace('/\s+/', '_', $name);
|
||||
|
||||
// If there's nothing left use a default.
|
||||
$name = ('' === $name) ? t('user') : $name;
|
||||
|
||||
// Truncate to a reasonable size.
|
||||
$name = (Unicode::strlen($name) > (USERNAME_MAX_LENGTH - 10)) ? Unicode::substr($name, 0, USERNAME_MAX_LENGTH - 11) : $name;
|
||||
return $name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements hook_form_FORM_ID_alter().
|
||||
*/
|
||||
function email_registration_form_user_register_form_alter(&$form, FormStateInterface $form_state) {
|
||||
$form['account']['name']['#type'] = 'value';
|
||||
$form['account']['name']['#value'] = 'email_registration_' . user_password();
|
||||
$form['account']['mail']['#title'] = t('E-mail');
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements hook_form_FORM_ID_alter().
|
||||
*/
|
||||
function email_registration_form_user_pass_alter(&$form, FormStateInterface $form_state) {
|
||||
$form['name']['#title'] = t('E-mail');
|
||||
// Allow client side validation of input format.
|
||||
$form['name']['#type'] = 'email';
|
||||
$form['name']['#maxlength'] = Email::EMAIL_MAX_LENGTH;
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements hook_form_FORM_ID_alter().
|
||||
*/
|
||||
function email_registration_form_user_login_form_alter(&$form, FormStateInterface $form_state) {
|
||||
$config = \Drupal::config('email_registration.settings');
|
||||
$login_with_username = $config->get('login_with_username');
|
||||
$form['name']['#title'] = $login_with_username ? t('E-mail or username') : t('E-mail');
|
||||
$form['name']['#description'] = $login_with_username ? t('Enter your e-mail address or username.') : t('Enter your e-mail address.');
|
||||
$form['name']['#element_validate'][] = 'email_registration_user_login_validate';
|
||||
$form['pass']['#description'] = t('Enter the password that accompanies your e-mail.');
|
||||
// Allow client side validation of input format.
|
||||
$form['name']['#type'] = $login_with_username ? 'textfield' : 'email';
|
||||
$form['name']['#maxlength'] = Email::EMAIL_MAX_LENGTH;
|
||||
// Make sure the login form cache is invalidated when the setting changes.
|
||||
$form['#cache']['tags'][] = 'config:email_registration.settings';
|
||||
}
|
||||
|
||||
/**
|
||||
* Form element validation handler for the user login form.
|
||||
*
|
||||
* Allows users to authenticate by email, which is our preferred method.
|
||||
*/
|
||||
function email_registration_user_login_validate($form, FormStateInterface $form_state) {
|
||||
$mail = $form_state->getValue('name');
|
||||
if (!empty($mail)) {
|
||||
$config = \Drupal::config('email_registration.settings');
|
||||
if ($user = user_load_by_mail($mail)) {
|
||||
$form_state->setValue('name', $user->getAccountName());
|
||||
}
|
||||
elseif (!$config->get('login_with_username')) {
|
||||
$user_input = $form_state->getUserInput();
|
||||
$query = isset($user_input['name']) ? ['name' => $user_input['name']] : [];
|
||||
$form_state->setErrorByName('name', t('Unrecognized e-mail address or password. <a href=":password">Forgot your password?</a>', [':password' => Url::fromRoute('user.pass', [], ['query' => $query])->toString()]));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements hook_form_FORM_ID_alter().
|
||||
*/
|
||||
function email_registration_form_user_form_alter(&$form, FormStateInterface $form_state) {
|
||||
$form['account']['name']['#title'] = t('Display name');
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements hook_form_FORM_ID_alter().
|
||||
*/
|
||||
function email_registration_form_user_admin_settings_alter(&$form, FormStateInterface $form_state) {
|
||||
$config = \Drupal::config('email_registration.settings');
|
||||
$form['registration_cancellation']['login_with_username'] = [
|
||||
'#type' => 'checkbox',
|
||||
'#title' => t('Allow to log in with e-mail or username.'),
|
||||
'#description' => t('Allow users to log in with either their username or their e-mail address.'),
|
||||
'#default_value' => $config->get('login_with_username'),
|
||||
];
|
||||
$form['#submit'][] = 'email_registration_form_user_admin_settings_submit';
|
||||
}
|
||||
|
||||
/**
|
||||
* Submit function for user_admin_settings to save our variable.
|
||||
*
|
||||
* @see email_registration_form_user_admin_settings_alter().
|
||||
*/
|
||||
function email_registration_form_user_admin_settings_submit(array &$form, FormStateInterface $form_state) {
|
||||
$config = \Drupal::configFactory()->getEditable('email_registration.settings');
|
||||
$config->set('login_with_username', $form_state->getValue('login_with_username'))->save();
|
||||
}
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\Tests\email_registration\Functional;
|
||||
|
||||
use Drupal\Tests\BrowserTestBase;
|
||||
|
||||
/**
|
||||
* Tests the email registration module.
|
||||
*
|
||||
* @group email_registration
|
||||
*/
|
||||
class EmailRegistrationTestCase extends BrowserTestBase {
|
||||
|
||||
/**
|
||||
* Modules to enable.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = array('email_registration');
|
||||
|
||||
/**
|
||||
* Test various behaviors for anonymous users.
|
||||
*/
|
||||
public function testRegistration() {
|
||||
$user_config = $this->container->get('config.factory')->getEditable('user.settings');
|
||||
$email_registration_config = $this->container->get('config.factory')->getEditable('email_registration.settings');
|
||||
$user_config
|
||||
->set('verify_mail', FALSE)
|
||||
->set('register', USER_REGISTER_VISITORS)
|
||||
->save();
|
||||
// Try to register a user.
|
||||
$name = $this->randomMachineName();
|
||||
$pass = $this->randomString(10);
|
||||
$register = array(
|
||||
'mail' => $name . '@example.com',
|
||||
'pass[pass1]' => $pass,
|
||||
'pass[pass2]' => $pass,
|
||||
);
|
||||
$this->drupalPostForm('/user/register', $register, t('Create new account'));
|
||||
$this->drupalLogout();
|
||||
|
||||
$login = array(
|
||||
'name' => $name . '@example.com',
|
||||
'pass' => $pass,
|
||||
);
|
||||
$this->drupalPostForm('user/login', $login, t('Log in'));
|
||||
|
||||
// Really basic confirmation that the user was created and logged in.
|
||||
$this->assertRaw('<title>' . $name . ' | Drupal</title>', t('User properly created, logged in.'));
|
||||
|
||||
// Now try the immediate login.
|
||||
$this->drupalLogout();
|
||||
|
||||
// Try to login with just username, should fail by default.
|
||||
$this->drupalGet('user/login');
|
||||
$this->assertText('Enter your e-mail address.');
|
||||
$this->assertText('E-mail');
|
||||
$this->assertNoText('E-mail or username');
|
||||
$login = array(
|
||||
'name' => $name,
|
||||
'pass' => $pass,
|
||||
);
|
||||
$this->drupalPostForm('user/login', $login, t('Log in'));
|
||||
$error_message = $this->xpath('//div[contains(@class, "error")]');
|
||||
$this->assertTrue(!empty($error_message), t('When login_with_username is false, a user cannot login with just their username.'));
|
||||
|
||||
// Set login_with_username to TRUE and try to login with just username.
|
||||
$email_registration_config->set('login_with_username', TRUE)->save();
|
||||
$this->drupalGet('user/login');
|
||||
$this->assertText('Enter your e-mail address or username.');
|
||||
$this->assertText('E-mail or username');
|
||||
$this->drupalPostForm('user/login', $login, t('Log in'));
|
||||
$this->assertRaw('<title>' . $name . ' | Drupal</title>', t('When login_with_username is true, a user can login with just their username.'));
|
||||
$this->drupalLogout();
|
||||
|
||||
$user_config
|
||||
->set('verify_mail', FALSE)
|
||||
->save();
|
||||
$name = $this->randomMachineName();
|
||||
$pass = $this->randomString(10);
|
||||
$register = array(
|
||||
'mail' => $name . '@example.com',
|
||||
'pass[pass1]' => $pass,
|
||||
'pass[pass2]' => $pass,
|
||||
);
|
||||
$this->drupalPostForm('/user/register', $register, t('Create new account'));
|
||||
$this->assertRaw('Registration successful. You are now logged in.', t('User properly created, immediately logged in.'));
|
||||
|
||||
// Test email_registration_unique_username().
|
||||
$this->drupalLogout();
|
||||
$user_config
|
||||
->set('verify_mail', FALSE)
|
||||
->set('register', USER_REGISTER_VISITORS)
|
||||
->save();
|
||||
$name = $this->randomMachineName(32);
|
||||
$pass = $this->randomString(10);
|
||||
|
||||
$this->createUser(array(), $name);
|
||||
$next_unique_name = email_registration_unique_username($name);
|
||||
|
||||
$register = array(
|
||||
'mail' => $name . '@example2.com',
|
||||
'pass[pass1]' => $pass,
|
||||
'pass[pass2]' => $pass,
|
||||
);
|
||||
$this->drupalPostForm('/user/register', $register, t('Create new account'));
|
||||
$account = user_load_by_mail($register['mail']);
|
||||
$this->assertTrue($next_unique_name === $account->getAccountName());
|
||||
}
|
||||
|
||||
}
|
||||
+125
@@ -0,0 +1,125 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\edlp_ajax\Plugin\Field\FieldFormatter;
|
||||
|
||||
use Drupal\Component\Utility\Html;
|
||||
use Drupal\Core\Field\FieldItemInterface;
|
||||
use Drupal\Core\Field\FieldItemListInterface;
|
||||
use Drupal\Core\Field\FormatterBase;
|
||||
use Drupal\Core\Form\FormStateInterface;
|
||||
use Drupal\Core\Field\Plugin\Field\FieldFormatter\EntityReferenceLabelFormatter;
|
||||
/**
|
||||
* Plugin implementation of the 'entity_reference_label_formatter_ajax' formatter.
|
||||
*
|
||||
* @FieldFormatter(
|
||||
* id = "entity_reference_label_formatter_ajax",
|
||||
* label = @Translation("Label link ajax ready"),
|
||||
* field_types = {
|
||||
* "entity_reference"
|
||||
* }
|
||||
* )
|
||||
*/
|
||||
class EntityReferenceLabelFormatterAjax extends EntityReferenceLabelFormatter {
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public static function defaultSettings() {
|
||||
return [
|
||||
// Implement default settings.
|
||||
] + parent::defaultSettings();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function settingsForm(array $form, FormStateInterface $form_state) {
|
||||
return [
|
||||
// Implement settings form.
|
||||
] + parent::settingsForm($form, $form_state);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
// public function settingsSummary() {
|
||||
// $summary = [];
|
||||
// // Implement settings summary.
|
||||
//
|
||||
// return $summary;
|
||||
// }
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function viewElements(FieldItemListInterface $items, $langcode) {
|
||||
$elements = [];
|
||||
$output_as_link = $this->getSetting('link');
|
||||
|
||||
foreach ($this->getEntitiesToView($items, $langcode) as $delta => $entity) {
|
||||
$label = $entity->label();
|
||||
// If the link is to be displayed and the entity has a uri, display a
|
||||
// link.
|
||||
if ($output_as_link && !$entity->isNew()) {
|
||||
try {
|
||||
$uri = $entity->urlInfo();
|
||||
$options = $uri->getOptions();
|
||||
$options += array(
|
||||
'attributes' => array(
|
||||
'class' => ['ajax-link'],
|
||||
'nid'=>$entity->id(),
|
||||
'data-drupal-link-system-path' => $uri->getInternalPath()
|
||||
)
|
||||
);
|
||||
$uri->setOptions($options);
|
||||
}
|
||||
catch (UndefinedLinkTemplateException $e) {
|
||||
// This exception is thrown by \Drupal\Core\Entity\Entity::urlInfo()
|
||||
// and it means that the entity type doesn't have a link template nor
|
||||
// a valid "uri_callback", so don't bother trying to output a link for
|
||||
// the rest of the referenced entities.
|
||||
$output_as_link = FALSE;
|
||||
}
|
||||
}
|
||||
|
||||
if ($output_as_link && isset($uri) && !$entity->isNew()) {
|
||||
$elements[$delta] = [
|
||||
'#type' => 'link',
|
||||
'#title' => $label,
|
||||
'#url' => $uri,
|
||||
'#options' => $uri->getOptions(),
|
||||
];
|
||||
|
||||
if (!empty($items[$delta]->_attributes)) {
|
||||
$elements[$delta]['#options'] += ['attributes' => []];
|
||||
$elements[$delta]['#options']['attributes'] += $items[$delta]->_attributes;
|
||||
// Unset field item attributes since they have been included in the
|
||||
// formatter output and shouldn't be rendered in the field template.
|
||||
unset($items[$delta]->_attributes);
|
||||
}
|
||||
}
|
||||
else {
|
||||
$elements[$delta] = ['#plain_text' => $label];
|
||||
}
|
||||
$elements[$delta]['#cache']['tags'] = $entity->getCacheTags();
|
||||
}
|
||||
|
||||
return $elements;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate the output appropriate for one field item.
|
||||
*
|
||||
* @param \Drupal\Core\Field\FieldItemInterface $item
|
||||
* One field item.
|
||||
*
|
||||
* @return string
|
||||
* The textual output generated.
|
||||
*/
|
||||
protected function viewValue(FieldItemInterface $item) {
|
||||
// The text value has no text format assigned to it, so the user input
|
||||
// should equal the output, including newlines.
|
||||
return nl2br(Html::escape($item->value));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
|
||||
(function($,Drupal,drupalSettings){EdlpCorpus=function(){var _activated=true;var _$body=$('body');var _$container=_$body;var _$canvas=$('<canvas id="corpus-map">').appendTo(_$container);var _canvas=_$canvas[0];var _ctx=_canvas.getContext('2d');var _dpi=window.devicePixelRatio;var _scene_props={width:0,height:0,'margin_top':75,'margin_right':0,'margin_bottom':65,'margin_left':0};var _physics=new Physics();var _nodes=[];var _articles_nodes=[];var _no_articles_nodes=[];var _articles_filter_on=false;var _nodes_by_entries={};var _nodes_by_nid={};var _nodes_Nid_Id={};var _nodes_centered=[];var _nodes_centered_attractions=[];var _loaded=false;var _playlist=[];var _p_velocity_factor=0.5;var _mouse_in=true;var _m_pos={x:0,y:0};var _node_hover_id=-1;var _node_opened_id=-1;var _$entrees_block=$('#block-edlpentreesblock');var _$entrees_block_termlinks=$('a.term-link',_$entrees_block);var _$articles_link;var _node_pop_up;var _settings=drupalSettings.edlp_corpus;var _ecolors=_settings.colors;var _attracter;var check_parts_colid_frq=2;var check_parts_colid_tick=1;function init(){initCanvas();if(_activated){loadCorpus();}else{_$canvas.addClass('de-activated');}};function initCanvas(){window.addEventListener('resize',onResizeCanvas,false);onResizeCanvas();};function onResizeCanvas(){_scene_props.width=window.innerWidth;_scene_props.height=window.innerHeight;_canvas.style.width=_scene_props.width+'px';_canvas.style.height=_scene_props.height+'px';_canvas.width=_scene_props.width*_dpi;_canvas.height=_scene_props.height*_dpi;_ctx.scale(_dpi,_dpi);if(_loaded){for(var i=0;i<_nodes.length;i++){_nodes[i].onResizeCanvas();}
|
||||
resizePhysics();}};function loadCorpus(){var ajax_path=_settings.load_corpus_ajax_url;var path=window.location.origin+Drupal.url(ajax_path);$.getJSON(path,{}).done(function(data){onCorpusLoaded(data);}).fail(function(jqxhr,textStatus,error){onCorpusLoadError(jqxhr,textStatus,error);});};function onCorpusLoadError(jqxhr,textStatus,error){void 0;};function onCorpusLoaded(data){initPhysics();buildNodes(data.nodes);initArtilesLink();initNodePopup();initEvents();checkPreOpenedEntry();startAnime();_loaded=true;};function initPhysics(){_attracter=_physics.makeParticle(1000);_attracter.fixed=true;resizePhysics();};function resizePhysics(){_attracter.position={x:_scene_props.width/2,y:_scene_props.height/2};};function buildNodes(nodes){var d;for(var i in nodes){d=i<1?true:false;new Node(i,nodes[i],d);_playlist.push({'id':i,'nid':nodes[i].nid,'audio_url':nodes[i].audio_url});}};function Node(i,node,d){this.id=i;for(key in node)
|
||||
(function($,Drupal,drupalSettings){EdlpCorpus=function(){var _activated=true;var _$body=$('body');var _$container=_$body;var _$canvas=$('<canvas id="corpus-map">').appendTo(_$container);var _canvas=_$canvas[0];var _ctx=_canvas.getContext('2d');var _dpi=window.devicePixelRatio;var _scene_props={width:window.innerWidth,height:window.innerHeight,'margin_top':75,'margin_right':0,'margin_bottom':65,'margin_left':0};var _evolution_zone={left:_scene_props.width/4,right:_scene_props.width-_scene_props.width/4,center:_scene_props.width/2,};var _physics=new Physics();var _nodes=[];var _articles_nodes=[];var _no_articles_nodes=[];var _articles_filter_on=false;var _nodes_by_entries={};var _nodes_by_nid={};var _nodes_Nid_Id={};var _nodes_centered=[];var _nodes_centered_attractions=[];var _loaded=false;var _playlist=[];var _p_velocity_factor=0.5;var _mouse_in=true;var _m_pos={x:0,y:0};var _node_hover_id=-1;var _node_opened_id=-1;var _$entrees_block=$('#block-edlpentreesblock');var _$entrees_block_termlinks=$('a.term-link',_$entrees_block);var _$articles_link;var _node_pop_up;var _settings=drupalSettings.edlp_corpus;var _ecolors=_settings.colors;var _attracter;var check_parts_colid_frq=2;var check_parts_colid_tick=1;function init(){initCanvas();if(_activated){loadCorpus();}else{_$canvas.addClass('de-activated');}};function initCanvas(){window.addEventListener('resize',onResizeCanvas,false);onResizeCanvas();};function onResizeCanvas(){_scene_props.width=window.innerWidth;_scene_props.height=window.innerHeight;_canvas.style.width=_scene_props.width+'px';_canvas.style.height=_scene_props.height+'px';_canvas.width=_scene_props.width*_dpi;_canvas.height=_scene_props.height*_dpi;_ctx.scale(_dpi,_dpi);moveEvolutionZone();if(_loaded){for(var i=0;i<_nodes.length;i++){_nodes[i].onResizeCanvas();}}};function loadCorpus(){var ajax_path=_settings.load_corpus_ajax_url;var path=window.location.origin+Drupal.url(ajax_path);$.getJSON(path,{}).done(function(data){onCorpusLoaded(data);}).fail(function(jqxhr,textStatus,error){onCorpusLoadError(jqxhr,textStatus,error);});};function onCorpusLoadError(jqxhr,textStatus,error){void 0;};function onCorpusLoaded(data){initPhysics();buildNodes(data.nodes);initArtilesLink();initNodePopup();initEvents();checkPreOpenedEntry();startAnime();_loaded=true;};function initPhysics(){_attracter=_physics.makeParticle(1000);_attracter.fixed=true;resizePhysics();};function resizePhysics(){if(typeof _attracter!='undefined'){_attracter.position={x:_evolution_zone.center,y:_scene_props.height/2};}};function buildNodes(nodes){var d;for(var i in nodes){d=i<1?true:false;new Node(i,nodes[i],d);_playlist.push({'id':i,'nid':nodes[i].nid,'audio_url':nodes[i].audio_url});}};function Node(i,node,d){this.id=i;for(key in node)
|
||||
this[key]=node[key];_nodes.push(this);_nodes_by_nid[this.nid]=this;_nodes_Nid_Id[this.nid]=this.id;if(this.has_article==1){_articles_nodes.push(this);}else{_no_articles_nodes.push(this);}
|
||||
for(var j=0;j<this.entrees.length;j++){if(typeof _nodes_by_entries[this.entrees[j]]=='undefined')
|
||||
_nodes_by_entries[this.entrees[j]]=[];_nodes_by_entries[this.entrees[j]].push(this);}
|
||||
@@ -11,7 +10,7 @@ if(_mouse_in&&!this.aside&&!this.faded)
|
||||
this.checkMouse();this.redraw();};Node.prototype.checkVelocityThreshold=function(){if(!this.centered||!this.aside){if(Math.abs(this.p.velocity.x)<this.velocity_threshold&&Math.abs(this.p.velocity.y)<this.velocity_threshold){this.p.velocity.multiplyScalar(0);}}};Node.prototype.checkWallBouncing=function(){switch(true){case this.x<this.wall_limits.left&&this.p.velocity.x<0:this.p.position.x=this.wall_limits.left;this.p.velocity.multiplyScalarXY(-1,1).multiplyScalar(this.wall_bouncing_elasticity);break;case this.x>this.wall_limits.right&&this.p.velocity.x>0:this.p.position.x=this.wall_limits.right;this.p.velocity.multiplyScalarXY(-1,1).multiplyScalar(this.wall_bouncing_elasticity);break;case this.y<this.wall_limits.top&&this.p.velocity.y<0:this.p.position.y=this.wall_limits.top;this.p.velocity.multiplyScalarXY(1,-1).multiplyScalar(this.wall_bouncing_elasticity);break;case this.y>this.wall_limits.bottom&&this.p.velocity.y>0:this.p.position.y=this.wall_limits.bottom;this.p.velocity.multiplyScalarXY(1,-1).multiplyScalar(this.wall_bouncing_elasticity);break;}};Node.prototype.updatePos=function(){this.x=this.p.position.x;this.y=this.p.position.y;};Node.prototype.checkMouse=function(){if(_m_pos.x>this.x-this.r&&_m_pos.x<this.x+this.r&&_m_pos.y>this.y-this.r&&_m_pos.y<this.y+this.r){if(_node_hover_id==-1||_node_hover_id!==this.id){this.setHover();}}else{this.unsetHover();}};Node.prototype.setHover=function(){this.hover=true;_node_hover_id=this.id;_node_pop_up.setNode(this);};Node.prototype.unsetHover=function(){this.hover=false;if(_node_hover_id==this.id){_node_hover_id=-1;_node_pop_up.removeNode();}};Node.prototype.open=function(){this.opened=true;_node_opened_id=this.id;};Node.prototype.close=function(){this.opened=false;};Node.prototype.fade=function(){this.faded=true;};Node.prototype.unFade=function(){this.faded=false;};Node.prototype.setCenteredOnEntree=function(tid){this.e_color='e_col_'+tid;this.setCentered();};Node.prototype.setCentered=function(){this.center=true;this.stopScrambling();this.unsetAside();this.attract.on=true;}
|
||||
Node.prototype.unsetCentered=function(){this.center=false;this.attract.on=false;}
|
||||
Node.prototype.limitEvolutionZone=function(){this.dist_to_attracter=this.p.distanceTo(_attracter);if(this.dist_to_attracter<_scene_props.width/4){if(this.p.velocity.length()>0.4){this.p.velocity.multiplyScalar(0.99);}}
|
||||
if(Math.abs(_attracter.position.x-this.x)>_scene_props.width/4||Math.abs(_attracter.position.y-this.y)>_scene_props.height/4){this.attract.on=true;}else{this.attract.on=false;}}
|
||||
if(this.x<_evolution_zone.left||this.x>_evolution_zone.right||Math.abs(_attracter.position.y-this.y)>_scene_props.height/4){this.attract.on=true;}else{this.attract.on=false;}}
|
||||
Node.prototype.setAside=function(){this.aside=true;this.stopScrambling();this.unsetCentered();this.ori_p.position.x=this.x<_scene_props.width/2?this.wall_limits.left:this.wall_limits.right;this.ori_p_attract.on=true;this.wall_bouncing_elasticity=0.15;}
|
||||
Node.prototype.unsetAside=function(){this.aside=false;this.ori_p_attract.on=false;this.ori_p.position.x=this.ori_pos.x;this.wall_bouncing_elasticity=0.75;}
|
||||
Node.prototype.resolveNormalPos=function(){switch(true){case this.center:this.unsetCentered();break;case this.aside:this.unsetAside();break;}};Node.prototype.scramble=function(){this.scrambling=true;this.unsetCentered();this.unsetAside();this.ori_p.position.x=this.ori_pos.x;this.ori_p.position.y=this.ori_pos.y;this.ori_p_attract.on=true;}
|
||||
@@ -26,7 +25,8 @@ newVelY1=(ma-mb)/Smamb*na.p.velocity.y+2*mb/Smamb*nb.p.velocity.y;newVelY2=(mb-m
|
||||
newVelX1=(ma-mb)/Smamb*na.p.velocity.x+2*mb/Smamb*nb.p.velocity.x;newVelX2=(mb-ma)/Smamb*nb.p.velocity.x+2*ma/Smamb*na.p.velocity.x;na.p.velocity.x=newVelX1;nb.p.velocity.x=newVelX2;}
|
||||
na.p.velocity.multiplyScalar(0.90);nb.p.velocity.multiplyScalar(0.90);}}};function openNodeByNid(nid){closeNode();if(typeof _nodes_Nid_Id[nid]!='undefined'){_node_opened_id=_nodes_Nid_Id[nid];_nodes[_nodes_Nid_Id[nid]].open();}}
|
||||
function closeNode(){if(_node_opened_id!=-1){_nodes[_node_opened_id].close();_node_opened_id=-1;}}
|
||||
function createNodesRepulsions(){purgeNodesRepulsions();for(var n=0;n<_nodes_centered.length;n++){for(var q=n+1;q<_nodes_centered.length;q++){_physics.makeAttraction(_nodes_centered[n].p,_nodes_centered[q].p,-0.4,10);}}};function purgeNodesRepulsions(){for(var a=_physics.attractions.length-1;a>=0;a--){if(Math.abs(_physics.attractions[a].constant)<1){_physics.attractions.splice(a,1);}else{break;}}};function updateRandomPlaylist(p){_$canvas.trigger({type:'update-random-playlist',playlist:p})};function toggleEntree(tid,bubbling){var $link=_$entrees_block_termlinks.filter('[tid="'+tid+'"]');var $li=$link.parents('li');var sys_path=$link.attr('data-drupal-link-system-path');var url=$link.attr('href');var title=$link.text();if(!$li.is('.opened')){_$entrees_block_termlinks.parents('li').removeClass('opened');$li.addClass('opened');$li.parents('.item-list').addClass('opened')
|
||||
function createNodesRepulsions(){purgeNodesRepulsions();for(var n=0;n<_nodes_centered.length;n++){for(var q=n+1;q<_nodes_centered.length;q++){_physics.makeAttraction(_nodes_centered[n].p,_nodes_centered[q].p,-0.4,10);}}};function purgeNodesRepulsions(){for(var a=_physics.attractions.length-1;a>=0;a--){if(Math.abs(_physics.attractions[a].constant)<1){_physics.attractions.splice(a,1);}else{break;}}};function moveEvolutionZone(l,r){var left=l||0;var right=r||0;_evolution_zone.left=Math.max(_scene_props.width/5,left+20);_evolution_zone.right=Math.min(_scene_props.width-_scene_props.width/5,_scene_props.width-right+20);_evolution_zone.center=_evolution_zone.left+(_evolution_zone.right-_evolution_zone.left)/2;resizePhysics();}
|
||||
function updateRandomPlaylist(p){_$canvas.trigger({type:'update-random-playlist',playlist:p})};function toggleEntree(tid,bubbling){var $link=_$entrees_block_termlinks.filter('[tid="'+tid+'"]');var $li=$link.parents('li');var sys_path=$link.attr('data-drupal-link-system-path');var url=$link.attr('href');var title=$link.text();if(!$li.is('.opened')){_$entrees_block_termlinks.parents('li').removeClass('opened');$li.addClass('opened');$li.parents('.item-list').addClass('opened')
|
||||
filterEntree(tid);if(bubbling){_$body.trigger({'type':'open_entree','tid':tid,'url':url,'sys_path':sys_path,'title':title});}}else if(bubbling){$li.removeClass('opened');$li.parents('.item-list').removeClass('opened')
|
||||
scrambleCollection();_$body.trigger({'type':'close_entree','tid':tid});}};function filterEntree(t){shutDownArticles();_nodes_centered=[];for(var n=0;n<_nodes.length;n++){if(_nodes[n].entrees.indexOf(t)==-1){_nodes[n].setAside();}else{_nodes[n].setCenteredOnEntree(t);_nodes_centered.push(_nodes[n]);}}
|
||||
updateRandomPlaylist(_nodes_centered);createNodesRepulsions();};function highlightEntries(){_$entrees_block_termlinks.parents('li').removeClass('highlighted').parents('.item-list').removeClass('highlighted');var id=-1;if(_node_hover_id!=-1){id=_node_hover_id;}else if(_node_opened_id!=-1){id=_node_opened_id;}
|
||||
@@ -36,7 +36,7 @@ updateRandomPlaylist(_playlist);};function closeAllEntries(){_$entrees_block_ter
|
||||
return false;};function activateArticlesFilter(){_articles_filter_on=true;for(var i=0;i<_no_articles_nodes.length;i++){_no_articles_nodes[i].fade();}
|
||||
updateRandomPlaylist(_articles_nodes);if(typeof _paq!=='undefined'){_paq.push(['trackEvent','Corpus Articles','on']);}};function deactivateArticlesFilter(){_articles_filter_on=false;for(var i=0;i<_no_articles_nodes.length;i++){_no_articles_nodes[i].unFade();}
|
||||
updateRandomPlaylist(_playlist);if(typeof _paq!=='undefined'){_paq.push(['trackEvent','Corpus Articles','off']);}};function shutDownArticles(){if(_$articles_link.is('.is-active'))
|
||||
_$articles_link.trigger('click');};function initEvents(){void 0;_$canvas.on('mousemove',function(event){event.preventDefault();_m_pos.x=event.originalEvent.clientX;_m_pos.y=event.originalEvent.clientY;}).on('mouseenter',function(event){_mouse_in=true;}).on('mouseout',function(event){_mouse_in=false;_node_pop_up.removeNode();}).on('click',function(event){if(event.target.tagName!="A"&&event.target.tagName!="INPUT"){event.preventDefault();if(_node_hover_id!=-1){var event={'type':'corpus-cliked-on-node','target_node':_nodes[_node_hover_id],'article':_articles_filter_on};_$canvas.trigger(event);}else{_$canvas.trigger('corpus-cliked-on-map');shutDownArticles();}}}).on('mouseover-audio-link',function(e){void 0;_nodes_by_nid[e.nid].setHover();}).on('mouseout-audio-link',function(e){void 0;_nodes_by_nid[e.nid].unsetHover();}).on('audio-node-opened',function(e){openNodeByNid(e.nid);}).on('audio-node-closed',function(e){closeNode();}).on('open-entree',function(e){toggleEntree(e.tid);}).on('close-all-entree',function(e){closeAllEntries();}).on('scramble-collection',function(e){void 0;scrambleCollection();});_$entrees_block_termlinks.on('click',function(event){event.preventDefault();toggleEntree($(this).attr('tid'),true);return false;});_$body.on('chutier-action-done',function(e){_nodes_by_nid[e.target_id].chutier_action=e.new_action;}).on('ajax-node-loaded-linked-documents',function(e){void 0;filterByNids(e.nids);}).on('search-results-loaded',function(e){filterByNids(e.results);}).on('search-closed',function(e){scrambleCollection();}).on('new-content-not-entree-ajax-loaded',function(e){if(_$entrees_block_termlinks.parents('li.opened').length){_$entrees_block_termlinks.parents('li').removeClass('opened').parents('.item-list').removeClass('opened');scrambleCollection();}});};function checkPreOpenedEntry(){_$entrees_block.find('li.entree').each(function(index,el){var $li=$(this);if($('a.is-active',$li).length){$li.addClass('opened').parents('.item-list').addClass('opened');filterEntree($li.attr('tid'));return false;}});};function initNodePopup(){_node_pop_up=new NodePopUp();};function NodePopUp(){this.visible=false;this.node;this.$dom=$('<div>').addClass('node-popup').attr('pos','top-right').appendTo('body');this.$content=$('<div>').addClass('inner').appendTo(this.$dom);if(typeof NodePopUp.initialized=="undefined"){NodePopUp.prototype.setNode=function(n){this.node=n;this.setPositioning();this.setContent();};NodePopUp.prototype.setPositioning=function(){switch(true){case this.node.x>this.node.wall_limits.right-350&&this.node.y<this.node.wall_limits.top+200:this.$dom.attr('pos','bottom-left');break;case this.node.x>this.node.wall_limits.right-350:this.$dom.attr('pos','top-left');break;case this.node.y<this.node.wall_limits.top+200:this.$dom.attr('pos','bottom-right');break;default:this.$dom.attr('pos','top-right');}};NodePopUp.prototype.setContent=function(){this.$content.html('');var $entrees=$('<div>').addClass('entrees');for(var i=0;i<this.node.entrees.length;i++){var tid=this.node.entrees[i];$entrees.append($('<span>').addClass('entree').attr('tid',tid));}
|
||||
_$articles_link.trigger('click');};function initEvents(){void 0;_$canvas.on('mousemove',function(event){event.preventDefault();_m_pos.x=event.originalEvent.clientX;_m_pos.y=event.originalEvent.clientY;}).on('mouseenter',function(event){_mouse_in=true;}).on('mouseout',function(event){_mouse_in=false;_node_pop_up.removeNode();}).on('click',function(event){if(event.target.tagName!="A"&&event.target.tagName!="INPUT"){event.preventDefault();if(_node_hover_id!=-1){var event={'type':'corpus-cliked-on-node','target_node':_nodes[_node_hover_id],'article':_articles_filter_on};_$canvas.trigger(event);}else{_$canvas.trigger('corpus-cliked-on-map');shutDownArticles();}}}).on('mouseover-audio-link',function(e){void 0;_nodes_by_nid[e.nid].setHover();}).on('mouseout-audio-link',function(e){void 0;_nodes_by_nid[e.nid].unsetHover();}).on('audio-node-opened',function(e){openNodeByNid(e.nid);}).on('audio-node-closed',function(e){closeNode();}).on('open-entree',function(e){toggleEntree(e.tid);}).on('close-all-entree',function(e){closeAllEntries();}).on('scramble-collection',function(e){void 0;scrambleCollection();});_$entrees_block_termlinks.on('click',function(event){event.preventDefault();toggleEntree($(this).attr('tid'),true);return false;});_$body.on('chutier-action-done',function(e){_nodes_by_nid[e.target_id].chutier_action=e.new_action;}).on('ajax-node-loaded-linked-documents',function(e){void 0;filterByNids(e.nids);}).on('search-results-loaded',function(e){filterByNids(e.results);}).on('search-closed',function(e){scrambleCollection();}).on('new-content-not-entree-ajax-loaded',function(e){if(_$entrees_block_termlinks.parents('li.opened').length){_$entrees_block_termlinks.parents('li').removeClass('opened').parents('.item-list').removeClass('opened');scrambleCollection();}}).on('visible-space-changed',function(e){moveEvolutionZone(e.left_limit,e.right_limit);});};function checkPreOpenedEntry(){_$entrees_block.find('li.entree').each(function(index,el){var $li=$(this);if($('a.is-active',$li).length){$li.addClass('opened').parents('.item-list').addClass('opened');filterEntree($li.attr('tid'));return false;}});};function initNodePopup(){_node_pop_up=new NodePopUp();};function NodePopUp(){this.visible=false;this.node;this.$dom=$('<div>').addClass('node-popup').attr('pos','top-right').appendTo('body');this.$content=$('<div>').addClass('inner').appendTo(this.$dom);if(typeof NodePopUp.initialized=="undefined"){NodePopUp.prototype.setNode=function(n){this.node=n;this.setPositioning();this.setContent();};NodePopUp.prototype.setPositioning=function(){switch(true){case this.node.x>this.node.wall_limits.right-350&&this.node.y<this.node.wall_limits.top+200:this.$dom.attr('pos','bottom-left');break;case this.node.x>this.node.wall_limits.right-350:this.$dom.attr('pos','top-left');break;case this.node.y<this.node.wall_limits.top+200:this.$dom.attr('pos','bottom-right');break;default:this.$dom.attr('pos','top-right');}};NodePopUp.prototype.setContent=function(){this.$content.html('');var $entrees=$('<div>').addClass('entrees');for(var i=0;i<this.node.entrees.length;i++){var tid=this.node.entrees[i];$entrees.append($('<span>').addClass('entree').attr('tid',tid));}
|
||||
var $chutier_action=$('<span>').addClass('chutier-icon').attr('action',this.node.chutier_action);this.$content.append($entrees).append('<h2 class="title">'+this.node.title+'</h2>').append('<section class="description">'+this.node.description+'</section>').append($chutier_action);};NodePopUp.prototype.removeNode=function(){this.node=false;};NodePopUp.prototype.draw=function(){if(this.node){this.$dom.css({'display':"block",'left':this.node.x+"px",'top':this.node.y+"px",});}else{this.$dom.css({'display':"none",});}};NodePopUp.initialized=true;}}
|
||||
function render(){_ctx.clearRect(0,0,_scene_props.width,_scene_props.height);checkParticulesCollisions();for(var i=0;i<_nodes.length;i++){_nodes[i].onUpdate();}
|
||||
_node_pop_up.draw();if(_node_hover_id!=-1){_canvas.style.cursor='pointer';}else{_canvas.style.cursor='auto';}
|
||||
|
||||
@@ -26,8 +26,8 @@
|
||||
var _ctx = _canvas.getContext('2d');
|
||||
var _dpi = window.devicePixelRatio;
|
||||
var _scene_props = {
|
||||
width:0,
|
||||
height:0,
|
||||
width:window.innerWidth,
|
||||
height:window.innerHeight,
|
||||
// 'margin_top':90, // with red border on head
|
||||
'margin_top':75, // without red border on head
|
||||
// 'margin_top':0,
|
||||
@@ -36,6 +36,12 @@
|
||||
// 'margin_bottom':0,
|
||||
'margin_left':0
|
||||
};
|
||||
var _evolution_zone = {
|
||||
left:_scene_props.width/4,
|
||||
right:_scene_props.width - _scene_props.width/4,
|
||||
center:_scene_props.width/2,
|
||||
};
|
||||
|
||||
var _physics = new Physics();
|
||||
var _nodes = [];
|
||||
var _articles_nodes = [];
|
||||
@@ -102,12 +108,15 @@
|
||||
_canvas.height = _scene_props.height*_dpi;
|
||||
_ctx.scale(_dpi, _dpi);
|
||||
|
||||
moveEvolutionZone();
|
||||
|
||||
if(_loaded){
|
||||
for (var i = 0; i < _nodes.length; i++) {
|
||||
_nodes[i].onResizeCanvas();
|
||||
}
|
||||
// move _attracter and _repulser to their right places again
|
||||
resizePhysics();
|
||||
// moveEvolutionZone() will trigger resizePhysics()
|
||||
// resizePhysics();
|
||||
}
|
||||
|
||||
};
|
||||
@@ -161,7 +170,9 @@
|
||||
};
|
||||
function resizePhysics(){
|
||||
// attracters
|
||||
_attracter.position = {x:_scene_props.width/2, y:_scene_props.height/2};
|
||||
if(typeof _attracter != 'undefined'){
|
||||
_attracter.position = {x:_evolution_zone.center, y:_scene_props.height/2};
|
||||
}
|
||||
};
|
||||
|
||||
// _ _ _
|
||||
@@ -479,7 +490,10 @@
|
||||
this.p.velocity.multiplyScalar(0.99); // 0.995
|
||||
}
|
||||
}
|
||||
if( Math.abs(_attracter.position.x - this.x) > _scene_props.width/4
|
||||
// limit evolution zone
|
||||
// if( Math.abs(_attracter.position.x - this.x) > _scene_props.width/4
|
||||
// || Math.abs(_attracter.position.y - this.y) > _scene_props.height/4){
|
||||
if( this.x < _evolution_zone.left || this.x > _evolution_zone.right
|
||||
|| Math.abs(_attracter.position.y - this.y) > _scene_props.height/4){
|
||||
this.attract.on = true;
|
||||
}else{
|
||||
@@ -731,6 +745,23 @@
|
||||
// console.log('_physics.attractions.length', _physics.attractions.length);
|
||||
};
|
||||
|
||||
|
||||
|
||||
|
||||
// ___ _ _ _ ____
|
||||
// | __|_ _____| |_ _| |_(_)___ _ _ |_ /___ _ _ ___
|
||||
// | _|\ V / _ \ | || | _| / _ \ ' \ / // _ \ ' \/ -_)
|
||||
// |___|\_/\___/_|\_,_|\__|_\___/_||_| /___\___/_||_\___|
|
||||
function moveEvolutionZone(l, r){
|
||||
var left = l || 0;
|
||||
var right = r || 0;
|
||||
_evolution_zone.left = Math.max(_scene_props.width/5, left+20);
|
||||
_evolution_zone.right = Math.min(_scene_props.width - _scene_props.width/5, _scene_props.width-right+20);
|
||||
_evolution_zone.center = _evolution_zone.left + (_evolution_zone.right - _evolution_zone.left)/2;
|
||||
// move _attracter to the center of the zone
|
||||
resizePhysics();
|
||||
}
|
||||
|
||||
// ___ _ ___ _ _ _ _
|
||||
// | _ \__ _ _ _ __| |___ _ __ | _ \ |__ _ _ _| (_)__| |_
|
||||
// | / _` | ' \/ _` / _ \ ' \ | _/ / _` | || | | (_-< _|
|
||||
@@ -1050,6 +1081,10 @@
|
||||
.parents('.item-list').removeClass('opened');
|
||||
scrambleCollection();
|
||||
}
|
||||
})
|
||||
.on('visible-space-changed', function(e){
|
||||
// limits are absolute distance from each side (not positions from left)
|
||||
moveEvolutionZone(e.left_limit, e.right_limit);
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
@@ -78,7 +78,7 @@ class HomeController extends ControllerBase {
|
||||
->condition('status', 1)
|
||||
->condition('type', 'evenement')
|
||||
->condition('field_date', $now->format(DATETIME_DATETIME_STORAGE_FORMAT), '>=')
|
||||
->range(0,3)
|
||||
->range(0,5)
|
||||
->sort('field_date');
|
||||
|
||||
$events = $query->execute();
|
||||
|
||||
@@ -156,13 +156,13 @@ function edlp_studio_node_view(array &$build, \Drupal\Core\Entity\EntityInterfac
|
||||
'#attributes' => array(
|
||||
'class' => array('inner')
|
||||
),
|
||||
'text'=>array(
|
||||
'description'=>array(
|
||||
'#prefix'=>'<p>',
|
||||
'#markup'=>t('Le Studio rassemble vos documents favoris. Il permet de les sauvegarder et de les agencer en compositions.'),
|
||||
'#suffix'=>'</p>'
|
||||
),
|
||||
// TODO: ajouter le login form
|
||||
'links'=>array(
|
||||
'register'=>array(
|
||||
'#prefix'=>'<p>',
|
||||
'register'=> array(
|
||||
'#type' => 'link',
|
||||
@@ -176,7 +176,7 @@ function edlp_studio_node_view(array &$build, \Drupal\Core\Entity\EntityInterfac
|
||||
),
|
||||
'#suffix'=>'</p>'
|
||||
),
|
||||
'text'=>array(
|
||||
'login'=>array(
|
||||
'#prefix'=>'<p>',
|
||||
'#markup'=>t("Ou connectez vous en survolant l'icone du studio en bas a droite de la page"),
|
||||
'#suffix'=>'</p>'
|
||||
|
||||
@@ -14,27 +14,28 @@ if(state.sys_path=="productions"){initProductions();}else{addCloseModalBtnToCols
|
||||
if(data.entity_type=="node"&&data.bundle=="enregistrement"&&data.view_mode=="transcript"){initEnregistrementTranscript();}
|
||||
if(typeof data.translations_links!='undefined'){void 0;var lang_code=drupalSettings.path.currentLanguage;var $links=$(data.translations_links);$links.find('li[hreflang="'+lang_code+'"]').addClass('is-active').find('a').addClass('is-active');if(state.view_mode){$links.find('a').each(function(i,e){var $a=$(this);$a.attr('href',$a.attr('href')+'#'+state.view_mode);});}
|
||||
$('ul','.block.language-switcher-language-url').replaceWith($links);}
|
||||
initAjaxLinks();_$body.trigger({'type':'new-content-ajax-loaded'});Drupal.attachBehaviors(_$row[0]);_$body.attr('booted','booted');_$body.removeClass('ajax-loading');if(state.url){history.pushState(state,null,state.url);if(typeof _paq!=='undefined'){_paq.push(['setCustomUrl',state.url]);_paq.push(['setDocumentTitle',data.title]);_ajax_timing.end=performance.now();_paq.push(['setGenerationTimeMs',_ajax_timing.end-_ajax_timing.start]);_paq.push(['trackPageView']);}}};function initAudioLinksInContent(){_$row.find('a.audio-link').on('mouseover',function(event){event.preventDefault();if(_corpus_ready){_$corpus_canvas.trigger({type:'mouseover-audio-link',nid:$(this).attr('nid')});}}).on('mouseout',function(event){event.preventDefault();if(_corpus_ready){_$corpus_canvas.trigger({type:'mouseout-audio-link',nid:$(this).attr('nid')});}});};function addCloseModalBtnToCols(){$('.col',_$row).each(function(index,el){if($('span.close-col-btn',this).length)
|
||||
initAjaxLinks();checkVisibleCorpusMapSpace();_$body.trigger({'type':'new-content-ajax-loaded'});Drupal.attachBehaviors(_$row[0]);_$body.attr('booted','booted');_$body.removeClass('ajax-loading');if(state.url){history.pushState(state,null,state.url);if(typeof _paq!=='undefined'){_paq.push(['setCustomUrl',state.url]);_paq.push(['setDocumentTitle',data.title]);_ajax_timing.end=performance.now();_paq.push(['setGenerationTimeMs',_ajax_timing.end-_ajax_timing.start]);_paq.push(['trackPageView']);}}};function initAudioLinksInContent(){_$row.find('a.audio-link').on('mouseover',function(event){event.preventDefault();if(_corpus_ready){_$corpus_canvas.trigger({type:'mouseover-audio-link',nid:$(this).attr('nid')});}}).on('mouseout',function(event){event.preventDefault();if(_corpus_ready){_$corpus_canvas.trigger({type:'mouseout-audio-link',nid:$(this).attr('nid')});}});};function addCloseModalBtnToCols(){$('.col',_$row).each(function(index,el){if($('span.close-col-btn',this).length)
|
||||
return true;$(this).children('.wrapper').prepend($('<span>').addClass('close-col-btn').on('click',onCloseModal));});};function onCloseModal(e){var $col=$(this).parents('.col');var theme=$col.attr('theme');if(theme!=''){_$body.trigger({'type':theme+'-col-closed'});}
|
||||
$col.remove();checkRowEmpty();};function refreshAllBlocks(){var path=window.location.origin+Drupal.url(_ajax_settings.blocksjson_path);$.getJSON(path,{}).done(function(data){onAjaxBlockLoaded(data);}).fail(function(jqxhr,textStatus,error){onAjaxBlockLoadError(jqxhr,textStatus,error);});};function onAjaxBlockLoadError(jqxhr,textStatus,error){void 0;};function onAjaxBlockLoaded(data){void 0;for(var blockname in data.blocks){var block=data.blocks[blockname];void 0;$(block.id).replaceWith(block.rendered);}};function initHistory(){initFirstLoad();window.addEventListener('popstate',onHistoryPopState);};function initFirstLoad(){void 0;var edlp_origin=JSON.parse(window.localStorage.getItem('edlp_origin'));void 0;if(edlp_origin!=null&&edlp_origin.sys_path){var view_mode=edlp_origin.hash.replace('#','');var state=getSysPathState(edlp_origin.sys_path,view_mode);if(edlp_origin.entity_type=="taxonomy_term"&&edlp_origin.entity_bundle=="entrees"&&view_mode){state.selector='entree-'+view_mode+'-link-'+edlp_origin.entity_id;if(_corpus_ready){_$corpus_canvas.trigger({type:'open-entree',tid:edlp_origin.entity_id});}else{$('li.entree[tid="'+edlp_origin.entity_id+'"] a.term-link').addClass('is-active');}}
|
||||
$col.remove();checkRowEmpty();checkVisibleCorpusMapSpace();};function refreshAllBlocks(){var path=window.location.origin+Drupal.url(_ajax_settings.blocksjson_path);$.getJSON(path,{}).done(function(data){onAjaxBlockLoaded(data);}).fail(function(jqxhr,textStatus,error){onAjaxBlockLoadError(jqxhr,textStatus,error);});};function onAjaxBlockLoadError(jqxhr,textStatus,error){void 0;};function onAjaxBlockLoaded(data){void 0;for(var blockname in data.blocks){var block=data.blocks[blockname];void 0;$(block.id).replaceWith(block.rendered);}};function initHistory(){initFirstLoad();window.addEventListener('popstate',onHistoryPopState);};function initFirstLoad(){void 0;var edlp_origin=JSON.parse(window.localStorage.getItem('edlp_origin'));void 0;if(edlp_origin!=null&&edlp_origin.sys_path){var view_mode=edlp_origin.hash.replace('#','');var state=getSysPathState(edlp_origin.sys_path,view_mode);if(edlp_origin.entity_type=="taxonomy_term"&&edlp_origin.entity_bundle=="entrees"&&view_mode){state.selector='entree-'+view_mode+'-link-'+edlp_origin.entity_id;if(_corpus_ready){_$corpus_canvas.trigger({type:'open-entree',tid:edlp_origin.entity_id});}else{$('li.entree[tid="'+edlp_origin.entity_id+'"] a.term-link').addClass('is-active');}}
|
||||
if(edlp_origin.audio_url){var node={nid:edlp_origin.entity_id,audio_url:edlp_origin.audio_url};_audioPlayer.openDocument(node,'history_first_load');if(view_mode==""){state.audio=true;state.node=node;_$body.attr('booted','booted');}else{ajaxLoadContent(state);}}
|
||||
else if(state.ajax_path){ajaxLoadContent(state);}
|
||||
if(state.entree_tid){openEntree(state.entree_tid);}
|
||||
history.replaceState(state,null,edlp_origin.url+edlp_origin.hash);window.localStorage.removeItem("edlp_origin");}else{history.replaceState({home:true},null,window.location.pathname);_$body.attr('booted','booted');}};function onHistoryPopState(e){void 0;if(e.state.home){backToFrontPage(true);}
|
||||
else if(e.state.audio){_audioPlayer.openDocument(e.state.node,'popstate',e.state.historic_index);}
|
||||
else{if(e.state.entree_tid){openEntree(e.state.entree_tid);}
|
||||
if(e.state.ajax_path){e.state.url=null;ajaxLoadContent(e.state);}}};function initAjaxLinks(){$('a.site-name','#block-edlptheme-branding').add('a','#block-mainnavigation').add('a','#block-footer.menu--footer').add('a','#block-productions').add('a','article.node:not(.node--type-enregistrement) h2.node-title').add('a','.productions-subtree').add('a','.productions-parent').addClass('ajax-link');_$ajaxLinks=$('.ajax-link:not(.ajax-enabled)').each(function(i,e){var $this=$(this);if($this.is('.ajax-enable'))return;if($this.attr('data-drupal-link-system-path')){$this.on('click',onClickAjaxLink).addClass('ajax-enable');}});};function onClickAjaxLink(e){e.preventDefault();var $link=$(this);if($link.is('.is-active'))
|
||||
if(e.state.ajax_path){e.state.url=null;ajaxLoadContent(e.state);}}};function initAjaxLinks(){$('a.site-name','#block-edlptheme-branding').add('a','#block-mainnavigation').add('a','#block-footer.menu--footer').add('a','#block-productions').add('a','article.node:not(.node--type-enregistrement) h2.node-title').add('a','.productions-subtree').add('a','.productions-parent').add('a','.field--name-field-son').addClass('ajax-link');_$ajaxLinks=$('.ajax-link:not(.ajax-enabled)').each(function(i,e){var $this=$(this);if($this.is('.ajax-enable'))return;if($this.attr('data-drupal-link-system-path')||$this.is('[type^="audio"]')){$this.on('click',onClickAjaxLink).addClass('ajax-enable');}});};function onClickAjaxLink(e){e.preventDefault();var $link=$(this);if($link.is('.is-active'))
|
||||
return false;if($link.is('.audio-link')){_audioPlayer.emmit('stop-shuffle').openDocument({nid:$link.attr('nid'),audio_url:$link.attr('audio_url'),title:$link.find('.field--name-title').html()});return false;}
|
||||
if($link.is('[type^="audio"]')){_audioPlayer.emmit('stop-shuffle').openSound($link.attr('href'),$link.html());return false;}
|
||||
var sys_path=$(this).attr('data-drupal-link-system-path');if(sys_path=='<front>'){backToFrontPage();return false;}
|
||||
var view_mode=$link.attr('viewmode');var state=getSysPathState(sys_path,view_mode);state.url=$(this).attr('href');if(view_mode){state.url+="#"+view_mode;}
|
||||
if($link.is('[selector]')){state.selector=$link.attr('selector');}
|
||||
$link.addClass('ajax-loading');ajaxLoadContent(state);return false;};function onCorpusMapReady(e){_corpus_ready=true;_$corpus_canvas=$('canvas#corpus-map');_$corpus_canvas.on('corpus-cliked-on-map',function(e){backToFrontPage();}).on('corpus-cliked-on-node',function(e){_audioPlayer.emmit('stop-shuffle').setAutoOpenArticle(e.article).openDocument(e.target_node);});_randomPlayer=new RandomPlayer(e.playlist);_$body.attr('corpus-map','ready');}
|
||||
function openEntree(tid){if(tid){closeAllModals();_$body.removeClass();if(_corpus_ready){_$corpus_canvas.trigger({type:'open-entree',tid:tid});}else{$('li.entree[tid="'+tid+'"] a.term-link').addClass('is-active');}}};function AudioPlayer(){var that=this;this.fid;this.audio=new Audio();this.audio_events=["loadedmetadata","canplay","playing","pause","timeupdate","ended","error"];this.$container=$('<div id="audio-player">');this.$btns=$('<div>').addClass('btns').appendTo(this.$container);this.$previous=$('<div>').addClass('previous').appendTo(this.$btns);this.$playpause=$('<div>').addClass('play-pause').appendTo(this.$btns);this.$next=$('<div>').addClass('next').appendTo(this.$btns);this.$timelinecont=$('<div>').addClass('time-line-container').appendTo(this.$container);this.$timeline=$('<div>').addClass('time-line').appendTo(this.$timelinecont);this.$loader=$('<div>').addClass('loader').appendTo(this.$timeline);this.$cursor=$('<div>').addClass('cursor').appendTo(this.$timeline);this.$time=$('<div>').addClass('time').appendTo(this.$container);this.$currentTime=$('<div>').addClass('current-time').html('00:00').appendTo(this.$time);this.$duration=$('<div>').addClass('duration').html('00:00').appendTo(this.$time);this.$fav=$('<div>').addClass('favoris').appendTo(this.$container);this.$cartel=$('<div>').addClass('cartel').appendTo(this.$container);this.hideTimer=false;this.hideTimeMS=10000;this.currentHistoricIndex=null;this.historic=[];this.shuffle_is_active=false;this.auto_open_article=false;this.event_handlers={'audio-open-document':[],'audio-play':[],'audio-pause':[],'audio-play-next':[],'audio-ended':[],'stop-shuffle':[]};this.init();};AudioPlayer.prototype={init(){this.$container_parent=$('header[role="banner"] .region-header');this.$container.appendTo(this.$container_parent);this.timeline_w=parseInt(this.$timeline.width());var fn='';for(var i=0;i<this.audio_events.length;i++){fn=this.audio_events[i];fn='on'+fn.charAt(0).toUpperCase()+fn.slice(1);this.audio.addEventListener(this.audio_events[i],this[fn].bind(this),true);}
|
||||
function openEntree(tid){if(tid){closeAllModals();_$body.removeClass();if(_corpus_ready){_$corpus_canvas.trigger({type:'open-entree',tid:tid});}else{$('li.entree[tid="'+tid+'"] a.term-link').addClass('is-active');}}};function checkVisibleCorpusMapSpace(){var left_limit=0,right_limit=0;_$row.find('.col').each(function(i,e){var $col=$(this);var offset=$col.offset();switch(true){case $col.is('.float-right'):right_limit=Math.max(right_limit,Math.abs(offset.left-window.innerWidth));break;default:left_limit=Math.max(left_limit,offset.left+$col.width());break;}});void 0;if(_corpus_ready){_$body.trigger({type:'visible-space-changed',left_limit:left_limit,right_limit:right_limit});}else{_corpus_promise.done(function(){_$body.trigger({type:'visible-space-changed',left_limit:left_limit,right_limit:right_limit});});}};function AudioPlayer(){var that=this;this.fid;this.audio=new Audio();this.audio_events=["loadedmetadata","playing","pause","timeupdate","ended","error"];this.$container=$('<div id="audio-player">');this.$btns=$('<div>').addClass('btns').appendTo(this.$container);this.$previous=$('<div>').addClass('previous').appendTo(this.$btns);this.$playpause=$('<div>').addClass('play-pause').appendTo(this.$btns);this.$next=$('<div>').addClass('next').appendTo(this.$btns);this.$timelinecont=$('<div>').addClass('time-line-container').appendTo(this.$container);this.$timeline=$('<div>').addClass('time-line').appendTo(this.$timelinecont);this.$loader=$('<div>').addClass('loader').appendTo(this.$timeline);this.$cursor=$('<div>').addClass('cursor').appendTo(this.$timeline);this.$time=$('<div>').addClass('time').appendTo(this.$container);this.$currentTime=$('<div>').addClass('current-time').html('00:00').appendTo(this.$time);this.$duration=$('<div>').addClass('duration').html('00:00').appendTo(this.$time);this.$fav=$('<div>').addClass('favoris').appendTo(this.$container);this.$cartel=$('<div>').addClass('cartel').appendTo(this.$container);this.hideTimer=false;this.hideTimeMS=10000;this.currentHistoricIndex=null;this.historic=[];this.shuffle_is_active=false;this.auto_open_article=false;this.event_handlers={'audio-open-document':[],'audio-play':[],'audio-pause':[],'audio-play-next':[],'audio-ended':[],'stop-shuffle':[]};this.init();};AudioPlayer.prototype={init(){this.$container_parent=$('header[role="banner"] .region-header');this.$container.appendTo(this.$container_parent);this.timeline_w=parseInt(this.$timeline.width());var fn='';for(var i=0;i<this.audio_events.length;i++){fn=this.audio_events[i];fn='on'+fn.charAt(0).toUpperCase()+fn.slice(1);this.audio.addEventListener(this.audio_events[i],this[fn].bind(this),true);}
|
||||
this.$previous.on('click',this.playPrevious.bind(this));this.$playpause.on('click',this.togglePlayPause.bind(this));this.$next.on('click',this.playNext.bind(this));},openDocument(node,caller,historic_index){if(typeof node=='undefined'||typeof node.nid=='undefined'||typeof node.audio_url=='undfined'||typeof node.document_url=='undfined'){void 0;return false;}
|
||||
if(typeof caller=='undefined'||caller!='popstate'){this.historic.push(node);this.currentHistoricIndex=this.historic.length-1;if(caller!="history_first_load"){var state={audio:true,node:{nid:node.nid,audio_url:node.audio_url,document_url:node.document_url,title:node.title||null,},historic_index:this.currentHistoricIndex,};history.pushState(state,null,node.document_url);}}else{this.currentHistoricIndex=historic_index;}
|
||||
this.emmit('audio-open-document',{caller:caller});if(typeof _paq!=='undefined'){if(typeof node.title!='undefined'){_paq.push(['trackEvent','Audio','play',node.title]);}}
|
||||
this.launch();},launch(){this.clearTimeOutToHide();this.setSRC(this.historic[this.currentHistoricIndex].audio_url);this.loadNode(this.historic[this.currentHistoricIndex].nid);try{_$corpus_canvas.trigger({'type':'audio-node-opened','nid':this.historic[this.currentHistoricIndex].nid});}catch(e){void 0;}
|
||||
this.showHidePreviousBtn();this.showHideNextBtn();this.show();},setSRC(url){void 0;this.audio.src=url;},onLoadedmetadata(){var rem=parseInt(this.audio.duration,10),mins=Math.floor(rem/60,10),secs=rem-mins*60;this.$duration.html('<span>'+(mins<10?'0':'')+mins+':'+(secs<10?'0':'')+secs+'</span>');this.updateLoadingBar();},updateLoadingBar(){if(this.audio.buffered.length>0){this.$loader.css({'width':parseInt((100*this.audio.buffered.end(0)/this.audio.duration),10)+'%'});if(this.audio.buffered.end(0)<this.audio.duration){var that=this;window.requestAnimationFrame(that.updateLoadingBar.bind(that));}else{}}},onCanplay(){this.play();},onError(){void 0;},play(){this.clearTimeOutToHide();this.audio.play();},playPrevious(){if(this.currentHistoricIndex>0){this.currentHistoricIndex-=1;this.launch();}},playNext(){if(this.currentHistoricIndex<this.historic.length-1){this.currentHistoricIndex+=1;this.launch();}else{this.emmit('audio-play-next');}},togglePlayPause(e){if(this.audio.paused){this.audio.play();}else{this.audio.pause();}},stop(){this.audio.pause();if(!(_$body.is('.path-node-'+this.historic[this.currentHistoricIndex].nid)&&(_$body.is('.view-mode-article')||_$body.is('.view-mode-transcript')))){this.timeOutToHide();}},onPlaying(){this.$btns.addClass('is-playing');this.emmit('audio-play');},onPause(){this.$btns.removeClass('is-playing');this.emmit('audio-pause');},onTimeupdate(){this.$cursor.css({'left':(this.audio.currentTime/this.audio.duration*this.timeline_w)+"px"});var rem=parseInt(this.audio.currentTime,10),mins=Math.floor(rem/60,10),secs=rem-mins*60;this.$currentTime.html('<span>'+(mins<10?'0':'')+mins+':'+(secs<10?'0':'')+secs+'</span>');},onEnded(){void 0;this.emmit('audio-ended');this.stop();},loadNode(nid){this.$cartel.addClass('loading');var vm='player_cartel';var ajax_path=_ajax_settings.entityjson_path+'/node/'+nid+'/'+vm;var path=window.location.origin+Drupal.url(ajax_path);$.getJSON(path,{}).done(this.onNodeLoaded.bind(this)).fail(this.onNodeLoadFail.bind(this));},onNodeLoaded(data){this.$cartel.html(data.rendered).removeClass('loading');_$body.trigger({'type':'new-audio-cartel-loaded'});initAjaxLinks();if(this.auto_open_article){this.$cartel.find('a.link-article').trigger('click');this.auto_open_article=false;}},onNodeLoadFail(jqxhr,textStatus,error){void 0;this.$cartel.removeClass('loading').html('');},setAutoOpenArticle(art){this.auto_open_article=art;return this;},show(){this.$container_parent.addClass('audio-player-visible');this.$container.addClass('visible');},showHidePreviousBtn(){if(this.historic.length>1&&this.currentHistoricIndex>0){this.$previous.addClass('is-active');}else{this.$previous.removeClass('is-active');}},showHideNextBtn(){if(this.currentHistoricIndex<this.historic.length-1||this.shuffle_is_active){this.$next.addClass('is-active');}else{this.$next.removeClass('is-active');}},timeOutToHide(){this.clearTimeOutToHide();this.hideTimer=setTimeout(this.hide.bind(this),this.hideTimeMS);},clearTimeOutToHide(){if(this.hideTimer){clearTimeout(this.hideTimer);this.hideTimer=false;}},hide(){this.$container_parent.removeClass('audio-player-visible');this.$container.removeClass('visible');try{_$corpus_canvas.trigger('audio-node-closed');}catch(e){void 0;}},on(event_name,handler){if(typeof this.event_handlers[event_name]=='undefined'){void 0;}
|
||||
this.showHidePreviousBtn();this.showHideNextBtn();this.show();},openSound(url,title){this.hide();this.clearTimeOutToHide();this.$cartel.html("");this.setSRC(url);this.show();if(typeof _paq!=='undefined'){_paq.push(['trackEvent','Audio','play',url]);}},setSRC(url){void 0;this.audio.src=url;this.play();},onLoadedmetadata(){var rem=parseInt(this.audio.duration,10),mins=Math.floor(rem/60,10),secs=rem-mins*60;this.$duration.html('<span>'+(mins<10?'0':'')+mins+':'+(secs<10?'0':'')+secs+'</span>');this.updateLoadingBar();},updateLoadingBar(){void 0;if(this.audio.buffered.length>0){this.$loader.css({'width':parseInt((100*this.audio.buffered.end(0)/this.audio.duration),10)+'%'});if(this.audio.buffered.end(0)<this.audio.duration){window.requestAnimationFrame(this.updateLoadingBar.bind(this));}else{void 0;}}else{window.requestAnimationFrame(this.updateLoadingBar.bind(this));}},onError(){void 0;},play(){this.clearTimeOutToHide();var promise=this.audio.play();if(promise!==undefined){promise.catch(error=>{void 0;}).then(()=>{void 0;});}},playPrevious(){if(this.currentHistoricIndex>0){this.currentHistoricIndex-=1;this.launch();}},playNext(){if(this.currentHistoricIndex<this.historic.length-1){this.currentHistoricIndex+=1;this.launch();}else{this.emmit('audio-play-next');}},togglePlayPause(e){if(this.audio.paused){this.audio.play();}else{this.audio.pause();}},stop(){this.audio.pause();if(!(_$body.is('.path-node-'+this.historic[this.currentHistoricIndex].nid)&&(_$body.is('.view-mode-article')||_$body.is('.view-mode-transcript')))){this.timeOutToHide();}},onPlaying(){this.$btns.addClass('is-playing');this.emmit('audio-play');},onPause(){this.$btns.removeClass('is-playing');this.emmit('audio-pause');},onTimeupdate(){this.$cursor.css({'left':(this.audio.currentTime/this.audio.duration*this.timeline_w)+"px"});var rem=parseInt(this.audio.currentTime,10),mins=Math.floor(rem/60,10),secs=rem-mins*60;this.$currentTime.html('<span>'+(mins<10?'0':'')+mins+':'+(secs<10?'0':'')+secs+'</span>');},onEnded(){void 0;this.emmit('audio-ended');this.stop();},loadNode(nid){this.$cartel.addClass('loading');var vm='player_cartel';var ajax_path=_ajax_settings.entityjson_path+'/node/'+nid+'/'+vm;var path=window.location.origin+Drupal.url(ajax_path);$.getJSON(path,{}).done(this.onNodeLoaded.bind(this)).fail(this.onNodeLoadFail.bind(this));},onNodeLoaded(data){this.$cartel.html(data.rendered).removeClass('loading');_$body.trigger({'type':'new-audio-cartel-loaded'});initAjaxLinks();if(this.auto_open_article){this.$cartel.find('a.link-article').trigger('click');this.auto_open_article=false;}},onNodeLoadFail(jqxhr,textStatus,error){void 0;this.$cartel.removeClass('loading').html('');},setAutoOpenArticle(art){this.auto_open_article=art;return this;},show(){this.$container_parent.addClass('audio-player-visible');this.$container.addClass('visible');},showHidePreviousBtn(){if(this.historic.length>1&&this.currentHistoricIndex>0){this.$previous.addClass('is-active');}else{this.$previous.removeClass('is-active');}},showHideNextBtn(){if(this.currentHistoricIndex<this.historic.length-1||this.shuffle_is_active){this.$next.addClass('is-active');}else{this.$next.removeClass('is-active');}},timeOutToHide(){this.clearTimeOutToHide();this.hideTimer=setTimeout(this.hide.bind(this),this.hideTimeMS);},clearTimeOutToHide(){if(this.hideTimer){clearTimeout(this.hideTimer);this.hideTimer=false;}},hide(){this.$container_parent.removeClass('audio-player-visible');this.$container.removeClass('visible');try{_$corpus_canvas.trigger('audio-node-closed');}catch(e){void 0;}},on(event_name,handler){if(typeof this.event_handlers[event_name]=='undefined'){void 0;}
|
||||
this.event_handlers[event_name].push(handler);return this;},emmit(event_name,args){var handler;var args=args||{};for(var i=this.event_handlers[event_name].length-1;i>=0;i--){handler=this.event_handlers[event_name][i];setTimeout(function(){handler(args);},0);}
|
||||
return this;},}
|
||||
function RandomPlayer(playlist){this.active=false;this.playlist=playlist;this.$btn=$('<a>').html('Shuffle').addClass('random-player-btn');this.init();};RandomPlayer.prototype={init(){$('<div>').addClass('block random-player').append(this.$btn).prependTo('.region-footer-right');this.$btn.on('click',this.toggleActive.bind(this));_audioPlayer.on('audio-ended',this.onAudioPlayerEnded.bind(this)).on('audio-play-next',this.onAudioPlayNext.bind(this)).on('stop-shuffle',this.stop.bind(this));_$corpus_canvas.on('update-random-playlist',this.updatePlaylist.bind(this));},updatePlaylist(e){this.playlist=e.playlist;this.shuffle();},shuffle(){var tempPLaylist=[];for(var i=this.playlist.length-1;i>=0;i--){tempPLaylist.push(this.playlist[i]);}
|
||||
@@ -47,7 +48,8 @@ return this;},showHideControls(){if(this.$controls){if(this.playing&&!this.pause
|
||||
if(this.$playpause){if(this.playlist.length>0){this.$playpause.addClass('is-active');}else{this.$playpause.removeClass('is-active');}}
|
||||
if(this.$next){if(this.playing&&this.playlist.length>1&&this.current_index<this.playlist.length-1){this.$next.addClass('is-active');}else{this.$next.removeClass('is-active');}}
|
||||
if(this.$previous){if(this.playing&&this.playlist.length>1&&this.current_index>0){this.$previous.addClass('is-active');}else{this.$previous.removeClass('is-active');}}
|
||||
return this;},deactivate(){this.stop();this.active=false;},onAudioOpenDocument(args){if(args.caller!==this){this.reset();}},onAudioPlayerPlay(){if(this.playing&&this.paused){this.paused=false;this.showHideControls();}},onAudioPlayerPause(){if(this.playing&&!this.paused){this.paused=true;this.showHideControls();}},onAudioPlayerEnded(){this.next();},};function initProductions(){var $grid=$('.grid',_$row).masonry({itemSelector:'.col',columnWidth:'.col-2',horizontalOrder:true,containerStyle:null,});$grid.imagesLoaded().progress(function(){$grid.masonry('layout');});$grid.imagesLoaded(function(){$grid.masonry('layout');});};function initEnregistrementTranscript(){void 0;var $node=_$row.find('article.node--type-enregistrement.node--view-mode-transcript');var $nav=$('<nav>').prependTo($node);$node.find('.field--name-field-transcript-vo').addClass('visible').find('.field__label').clone().appendTo($nav).addClass('is-active').attr('field_target','.field--name-field-transcript-vo');$node.find('.field--name-field-transcript-trad').find('.field__label').clone().appendTo($nav).attr('field_target','.field--name-field-transcript-trad');$nav.find('.field__label').on('click',function(){var $this=$(this).addClass('is-active');$this.siblings('.is-active').removeClass('is-active');$this.parents('article.node').find('.field.visible').removeClass('visible');$this.parents('article.node').find($this.attr('field_target')).addClass('visible');});};function backToFrontPage(pop_state){void 0;closeAllModals();$('body').removeClass().addClass('path-frontpage');$('a[data-drupal-link-system-path="<front>"]').addClass('is-active');_$corpus_canvas.trigger({'type':'close-all-entree'});_$corpus_canvas.trigger({'type':'scramble-collection'});if(typeof pop_state=="undefined"||!pop_state){void 0;history.pushState({home:true},null,drupalSettings.path.baseUrl+drupalSettings.path.currentLanguage);}}
|
||||
return this;},deactivate(){this.stop();this.active=false;},onAudioOpenDocument(args){if(args.caller!==this){this.reset();}},onAudioPlayerPlay(){if(this.playing&&this.paused){this.paused=false;this.showHideControls();}},onAudioPlayerPause(){if(this.playing&&!this.paused){this.paused=true;this.showHideControls();}},onAudioPlayerEnded(){this.next();},};function initProductions(){void 0;_$row.find('.col').addClass('offfield');var $grid=$('.grid',_$row).masonry({itemSelector:'.col',columnWidth:'.col-2',horizontalOrder:true,containerStyle:null,transitionDuration:0,});$grid.imagesLoaded().progress(function(){$grid.masonry('layout');});$grid.imagesLoaded(function(){$grid.masonry('layout');});$grid.on('layoutComplete',checkProductionBlockVisible);};function checkProductionBlockVisible(e,items){void 0;for(var i in items){if(!items[i].isTransitioning){if(items[i].position.y+items[i].size.outerHeight<_$row.height()){$(items[i].element).removeClass('offfield');}else{$(items[i].element).addClass('offfield');}}}}
|
||||
function initEnregistrementTranscript(){void 0;var $node=_$row.find('article.node--type-enregistrement.node--view-mode-transcript');var $nav=$('<nav>').prependTo($node);$node.find('.field--name-field-transcript-vo').addClass('visible').find('.field__label').clone().appendTo($nav).addClass('is-active').attr('field_target','.field--name-field-transcript-vo');$node.find('.field--name-field-transcript-trad').find('.field__label').clone().appendTo($nav).attr('field_target','.field--name-field-transcript-trad');$nav.find('.field__label').on('click',function(){var $this=$(this).addClass('is-active');$this.siblings('.is-active').removeClass('is-active');$this.parents('article.node').find('.field.visible').removeClass('visible');$this.parents('article.node').find($this.attr('field_target')).addClass('visible');});};function backToFrontPage(pop_state){void 0;closeAllModals();$('body').removeClass().addClass('path-frontpage');$('a[data-drupal-link-system-path="<front>"]').addClass('is-active');_$corpus_canvas.trigger({'type':'close-all-entree'});_$corpus_canvas.trigger({'type':'scramble-collection'});if(typeof pop_state=="undefined"||!pop_state){void 0;history.pushState({home:true},null,drupalSettings.path.baseUrl+drupalSettings.path.currentLanguage);}}
|
||||
function initHome(){addCloseModalBtnToCols();var $grid=$('.grid',_$row).masonry({itemSelector:'.col',columnWidth:'.col-2',horizontalOrder:true,containerStyle:null,});$grid.imagesLoaded().progress(function(){$grid.masonry('layout');});$grid.imagesLoaded(function(){$grid.masonry('layout');});}
|
||||
function closeAllModals(){_$row.html('');_$ajaxLinks.removeClass('is-active');_$body.trigger({'type':'all-modal-closed'});};function checkRowEmpty(){if(!$('.col',_$row).length&&!_$body.is('.entity-type-taxonomy_term.bundle-entrees')){if(!_$body.is('.entity-type-node.bundle-page')){backToFrontPage();}else{_$corpus_canvas.trigger({'type':'scramble-collection'});}}};init();}
|
||||
$(document).ready(function($){if(drupalSettings.path.isFront){var edlptheme=new EdlpTheme();}});})(jQuery,Drupal,drupalSettings);
|
||||
function closeAllModals(){_$row.html('');_$ajaxLinks.removeClass('is-active');_$body.trigger({'type':'all-modal-closed'});};function checkRowEmpty(){if(!$('.col',_$row).length){if(!_$body.is('.entity-type-taxonomy_term.bundle-entrees')){if(!_$body.is('.entity-type-node.bundle-page')){backToFrontPage();}else{_$corpus_canvas.trigger({'type':'scramble-collection'});}}else{$('.entree-content a.is-active').removeClass('is-active');}}};init();}
|
||||
$(document).ready(function($){if(drupalSettings.path.isFront){var edlptheme=new EdlpTheme();}else{$('body').attr('booted','booted');}});})(jQuery,Drupal,drupalSettings);
|
||||
+2893
-1
File diff suppressed because one or more lines are too long
@@ -323,6 +323,8 @@
|
||||
|
||||
initAjaxLinks();
|
||||
|
||||
checkVisibleCorpusMapSpace();
|
||||
|
||||
// trigger other modules behaviours
|
||||
_$body.trigger({'type':'new-content-ajax-loaded'});
|
||||
|
||||
@@ -407,6 +409,7 @@
|
||||
// remove the col
|
||||
$col.remove();
|
||||
checkRowEmpty();
|
||||
checkVisibleCorpusMapSpace();
|
||||
};
|
||||
|
||||
// _ _ ___ _ _
|
||||
@@ -569,9 +572,11 @@
|
||||
.add('a', '#block-footer.menu--footer')
|
||||
.add('a', '#block-productions')
|
||||
.add('a', 'article.node:not(.node--type-enregistrement) h2.node-title')
|
||||
// .add('a', 'article.node--type-evenement.node--view-mode-teaser .field--name-field-page-liee')
|
||||
.add('a', '.productions-subtree')
|
||||
.add('a', '.productions-parent')
|
||||
// .add('a.index-link, a.notice-link', '#block-edlpentreesblock')
|
||||
.add('a', '.field--name-field-son')
|
||||
.addClass('ajax-link');
|
||||
|
||||
_$ajaxLinks = $('.ajax-link:not(.ajax-enabled)')
|
||||
@@ -579,7 +584,7 @@
|
||||
var $this = $(this);
|
||||
// avoid already ajaxified links
|
||||
if($this.is('.ajax-enable')) return;
|
||||
if($this.attr('data-drupal-link-system-path')){
|
||||
if($this.attr('data-drupal-link-system-path') || $this.is('[type^="audio"]')){
|
||||
$this.on('click', onClickAjaxLink).addClass('ajax-enable');
|
||||
}
|
||||
});
|
||||
@@ -604,7 +609,15 @@
|
||||
return false;
|
||||
}
|
||||
|
||||
// NOT USED (YET)
|
||||
// other sounds playing
|
||||
if($link.is('[type^="audio"]')){
|
||||
_audioPlayer
|
||||
.emmit('stop-shuffle')
|
||||
.openSound($link.attr('href'), $link.html());
|
||||
return false;
|
||||
}
|
||||
|
||||
// NOT USED ( YET ? )
|
||||
// if($link.is('.language-link')){
|
||||
// TODO: change global site current language
|
||||
// load all blocks translated (exepted language switcher) ... :/
|
||||
@@ -648,7 +661,6 @@
|
||||
// | (__/ _ \ '_| '_ \ || (_-<
|
||||
// \___\___/_| | .__/\_,_/__/
|
||||
// |_|
|
||||
|
||||
function onCorpusMapReady(e){
|
||||
//console.log('theme : onCorpusReady', e);
|
||||
_corpus_ready = true;
|
||||
@@ -690,6 +702,40 @@
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
function checkVisibleCorpusMapSpace(){
|
||||
var left_limit = 0, right_limit = 0;
|
||||
_$row.find('.col').each(function(i,e){
|
||||
var $col = $(this);
|
||||
var offset = $col.offset();
|
||||
switch(true){
|
||||
case $col.is('.float-right'):
|
||||
right_limit = Math.max(right_limit, Math.abs(offset.left-window.innerWidth));
|
||||
break;
|
||||
default:
|
||||
left_limit = Math.max(left_limit, offset.left+$col.width());
|
||||
break;
|
||||
}
|
||||
});
|
||||
console.log('checkVisibleCorpusMapSpace left_limit:'+left_limit+" right_limit:"+right_limit);
|
||||
|
||||
if(_corpus_ready){
|
||||
_$body.trigger({
|
||||
type:'visible-space-changed',
|
||||
left_limit:left_limit,
|
||||
right_limit:right_limit
|
||||
});
|
||||
}else{
|
||||
_corpus_promise.done(function(){
|
||||
_$body.trigger({
|
||||
type:'visible-space-changed',
|
||||
left_limit:left_limit,
|
||||
right_limit:right_limit
|
||||
});
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// _ _ _
|
||||
// /_\ _ _ __| (_)___
|
||||
// / _ \ || / _` | / _ \
|
||||
@@ -703,7 +749,7 @@
|
||||
this.fid;
|
||||
this.audio = new Audio();
|
||||
// audio events
|
||||
this.audio_events = ["loadedmetadata","canplay","playing","pause","timeupdate","ended","error"];
|
||||
this.audio_events = ["loadedmetadata","playing","pause","timeupdate","ended","error"]; // ,"canplay"
|
||||
|
||||
// UI dom objects
|
||||
this.$container = $('<div id="audio-player">');
|
||||
@@ -847,10 +893,22 @@
|
||||
this.showHideNextBtn();
|
||||
this.show();
|
||||
},
|
||||
openSound(url, title){
|
||||
this.hide();
|
||||
this.clearTimeOutToHide();
|
||||
this.$cartel.html("");
|
||||
this.setSRC(url);
|
||||
this.show();
|
||||
if(typeof _paq !== 'undefined'){
|
||||
_paq.push(['trackEvent', 'Audio', 'play', url]);
|
||||
}
|
||||
},
|
||||
// audio functions
|
||||
setSRC(url){
|
||||
console.log('AudioPlayer setSRC : url', url);
|
||||
this.audio.src = url;
|
||||
// need to trigger play right now to prevent safari blocking auto-play
|
||||
this.play();
|
||||
},
|
||||
onLoadedmetadata(){
|
||||
var rem = parseInt(this.audio.duration, 10),
|
||||
@@ -860,29 +918,50 @@
|
||||
this.updateLoadingBar();
|
||||
},
|
||||
updateLoadingBar(){
|
||||
console.log("updateLoadingBar");
|
||||
|
||||
// var that = this;
|
||||
// if (this.audio.readyState === 4){
|
||||
if(this.audio.buffered.length>0){
|
||||
// debugger;
|
||||
this.$loader.css({
|
||||
'width':parseInt((100 * this.audio.buffered.end(0) / this.audio.duration), 10)+'%'
|
||||
});
|
||||
if( this.audio.buffered.end(0) < this.audio.duration ){
|
||||
// loop through this function until file is fully loaded
|
||||
var that = this;
|
||||
window.requestAnimationFrame(that.updateLoadingBar.bind(that));
|
||||
window.requestAnimationFrame(this.updateLoadingBar.bind(this));
|
||||
}else{
|
||||
//console.log('Audio fully loaded');
|
||||
console.log('Audio fully loaded');
|
||||
}
|
||||
}else{
|
||||
// as audio buffer is not ready, recall updateLoadingBar in next frame
|
||||
window.requestAnimationFrame(this.updateLoadingBar.bind(this));
|
||||
}
|
||||
},
|
||||
onCanplay(){
|
||||
this.play();
|
||||
},
|
||||
// onCanplay(){
|
||||
// // this.play();
|
||||
// },
|
||||
onError(){
|
||||
console.warn("Audio Error " + this.audio.error.code + "; details: " + this.audio.error.message);
|
||||
},
|
||||
play(){
|
||||
this.clearTimeOutToHide();
|
||||
this.audio.play();
|
||||
// this.audio.play();
|
||||
|
||||
// Not really needed has we trigger play right after setting the source https://stackoverflow.com/questions/47431439/mp4-video-safari-showing-unhandled-promise-rejection-object-domerror-in-c
|
||||
var promise = this.audio.play();
|
||||
// console.log('promise', promise);
|
||||
if (promise !== undefined) {
|
||||
promise.catch(error => {
|
||||
// Auto-play was prevented
|
||||
// Show a UI element to let the user manually start playback
|
||||
console.warn('autoplay failed, ask for playing', error);
|
||||
|
||||
}).then(() => {
|
||||
// Auto-play started
|
||||
console.log('autoplay succeed');
|
||||
});
|
||||
}
|
||||
},
|
||||
playPrevious(){
|
||||
if(this.currentHistoricIndex > 0){
|
||||
@@ -1364,12 +1443,17 @@
|
||||
// | _/ '_/ _ \/ _` | || / _| _| / _ \ ' \(_-<
|
||||
// |_| |_| \___/\__,_|\_,_\__|\__|_\___/_||_/__/
|
||||
function initProductions(){
|
||||
// console.log('theme : initProductions');
|
||||
console.log('theme : initProductions');
|
||||
|
||||
_$row.find('.col').addClass('offfield');
|
||||
|
||||
var $grid = $('.grid',_$row).masonry({
|
||||
itemSelector:'.col',
|
||||
columnWidth:'.col-2',
|
||||
horizontalOrder: true,
|
||||
containerStyle: null,
|
||||
transitionDuration:0,//'0.2s',
|
||||
// stagger:30,
|
||||
// disable initial layout
|
||||
// initLayout: false,
|
||||
});
|
||||
@@ -1385,9 +1469,25 @@
|
||||
|
||||
$grid.imagesLoaded(function(){
|
||||
$grid.masonry('layout');
|
||||
// checkProductionBlockVisible();
|
||||
});
|
||||
|
||||
$grid.on('layoutComplete', checkProductionBlockVisible);
|
||||
};
|
||||
|
||||
function checkProductionBlockVisible(e,items){
|
||||
console.log('checkProductionBlockVisible', e, items);
|
||||
for (var i in items) {
|
||||
if(!items[i].isTransitioning){
|
||||
if(items[i].position.y+items[i].size.outerHeight < _$row.height()){
|
||||
$(items[i].element).removeClass('offfield');
|
||||
}else{
|
||||
$(items[i].element).addClass('offfield');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ___ _ _ _
|
||||
// | __|_ _ _ _ ___ __ _(_)__| |_ _ _ ___ _ __ ___ _ _| |_
|
||||
// | _|| ' \| '_/ -_) _` | (_-< _| '_/ -_) ' \/ -_) ' \ _|
|
||||
@@ -1473,43 +1573,32 @@
|
||||
};
|
||||
|
||||
function checkRowEmpty(){
|
||||
// TODO: remove is-active class from index or notice entree links
|
||||
// if row is empty and we are not in productions or entree notice|index call closeAllModals()
|
||||
if(!$('.col', _$row).length && !_$body.is('.entity-type-taxonomy_term.bundle-entrees')){
|
||||
if(!_$body.is('.entity-type-node.bundle-page')){
|
||||
// we weren't on production or entree, so go back to front page
|
||||
backToFrontPage();
|
||||
if(!$('.col', _$row).length){
|
||||
if(!_$body.is('.entity-type-taxonomy_term.bundle-entrees')){
|
||||
if(!_$body.is('.entity-type-node.bundle-page')){
|
||||
// we weren't on production or entree, so go back to front page
|
||||
backToFrontPage();
|
||||
}else{
|
||||
// if we were on production page just scramble collection in case of map was filtered
|
||||
_$corpus_canvas.trigger({'type':'scramble-collection'});
|
||||
}
|
||||
}else{
|
||||
// if we were on production page just scramble collection in case of map was filtered
|
||||
_$corpus_canvas.trigger({'type':'scramble-collection'});
|
||||
// remove is-active class from index or notice entree links
|
||||
$('.entree-content a.is-active').removeClass('is-active');
|
||||
// TODO: remove the hash index or notice
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// _ _ _
|
||||
// | || |___| |_ __ ___ _ _ ___
|
||||
// | __ / -_) | '_ \/ -_) '_(_-<
|
||||
// |_||_\___|_| .__/\___|_| /__/
|
||||
// |_|
|
||||
|
||||
// https://plainjs.com/javascript/utilities/set-cookie-get-cookie-and-delete-cookie-5/
|
||||
// function getCookie(name) {
|
||||
// var v = document.cookie.match('(^|;) ?' + name + '=([^;]*)(;|$)');
|
||||
// return v ? v[2] : null;
|
||||
// }
|
||||
// function setCookie(name, value, days) {
|
||||
// var d = new Date;
|
||||
// d.setTime(d.getTime() + 24*60*60*1000*days);
|
||||
// document.cookie = name + "=" + value + ";path=/;expires=" + d.toGMTString();
|
||||
// }
|
||||
// function deleteCookie(name) { setCookie(name, '', -1); }
|
||||
|
||||
init();
|
||||
} // end EdlpTheme()
|
||||
|
||||
$(document).ready(function($) {
|
||||
if(drupalSettings.path.isFront){
|
||||
var edlptheme = new EdlpTheme();
|
||||
}else{
|
||||
$('body').attr('booted', 'booted');
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -282,6 +282,10 @@ main[role="main"]{
|
||||
margin:0.9em 0 0 0;
|
||||
}
|
||||
}
|
||||
article.node.node--type-enregistrement.node--view-mode-index{
|
||||
&,p{margin:0}
|
||||
h2.node-title{margin-top: 0.2em;}
|
||||
}
|
||||
article.node.node--type-enregistrement.node--view-mode-transcript{
|
||||
html.js &{
|
||||
h3.sur-title{display:none;}
|
||||
@@ -348,7 +352,24 @@ main[role="main"]{
|
||||
@include content_courant;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
article.node--type-evenement{
|
||||
.field--name-field-page-liee{
|
||||
@include content_subtitles;
|
||||
}
|
||||
.field--name-field-date{
|
||||
@include content_courant;
|
||||
}
|
||||
.field--name-title{
|
||||
@include content_courant;
|
||||
}
|
||||
// .field--name-body{}
|
||||
}
|
||||
article.node--type-evenement.node--view-mode-aside{
|
||||
.field--name-field-date{
|
||||
@include content_subtitles;
|
||||
}
|
||||
}
|
||||
|
||||
div.taxonomy-term{
|
||||
@@ -439,6 +460,8 @@ main[role="main"]{
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
img{
|
||||
max-width: 100%;
|
||||
height: auto;
|
||||
@@ -1286,8 +1309,17 @@ body.path-frontpage, body.path-productions{
|
||||
.layout-content .row{
|
||||
white-space: normal;
|
||||
min-height: 100%;
|
||||
.grid{
|
||||
position: relative;
|
||||
min-height: 100%; max-height: 100%;
|
||||
}
|
||||
.col{
|
||||
height:auto;
|
||||
opacity:1;
|
||||
transition: opacity 0.5s ease-in-out;
|
||||
&.offfield{
|
||||
opacity: 0;
|
||||
}
|
||||
&.col-2:last-child{
|
||||
padding-left: 0em;
|
||||
padding-right: 1em;
|
||||
@@ -1986,3 +2018,53 @@ footer{
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#user-register-form{
|
||||
width:29em;
|
||||
input{
|
||||
@include content_courant;
|
||||
}
|
||||
label{
|
||||
@include content_subtitles;
|
||||
display: inline-block;
|
||||
width: 16em;
|
||||
white-space: normal;
|
||||
}
|
||||
.form-item{
|
||||
white-space: nowrap;
|
||||
}
|
||||
.description{
|
||||
@include content_petit;
|
||||
max-width: 100%;
|
||||
white-space: normal;
|
||||
}
|
||||
input[type='email'], input[type='password']{
|
||||
width:17em;
|
||||
}
|
||||
.password-strength, .password-strength__meter{
|
||||
width:98%;
|
||||
}
|
||||
.password-strength__title, .password-confirm{
|
||||
@include content_courant;
|
||||
}
|
||||
}
|
||||
|
||||
#better-messages-default.better-messages-overlay{
|
||||
border-radius: 0;
|
||||
padding:0.8em;
|
||||
box-shadow: 0 2px 10px #716f6f;
|
||||
.better-messages-content{
|
||||
|
||||
}
|
||||
.better-messages-footer{
|
||||
border-top: none;
|
||||
.better-messages-close{
|
||||
@include content_courant;
|
||||
span{
|
||||
height:15px; width:15px;
|
||||
background-size: contain;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -34,3 +34,9 @@
|
||||
font-weight: normal;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
@mixin content_petit {
|
||||
font-size: 0.756em;
|
||||
font-weight: normal;
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
@@ -63,7 +63,7 @@ main[role="main"]{
|
||||
.layout-content{
|
||||
width: 100%; height:100%;
|
||||
overflow:hidden;
|
||||
&>*{
|
||||
.row>*:not(.col):not(.grid){
|
||||
pointer-events: auto;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -248,3 +248,7 @@ function edlptheme_preprocess_links__language_block(&$vars){
|
||||
$vars['links'][$lang_code]['link']['#title'] = $lang_code;
|
||||
}
|
||||
}
|
||||
|
||||
function edlptheme_preprocess_file_link(&$vars){
|
||||
|
||||
}
|
||||
|
||||
@@ -1,15 +1,8 @@
|
||||
<div class="col small-col-12 med-col-4 large-col-3 ">
|
||||
<div class="col small-col-12 med-col-4 large-col-3 float-right">
|
||||
<div class="wrapper">
|
||||
<div class="agenda">
|
||||
{{ coming_events }}
|
||||
{{ past_events }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col small-col-12 med-col-8 large-col-5 event float-right">
|
||||
<div class="wrapper">
|
||||
<div class="agenda">
|
||||
{{ next_event }}
|
||||
{{ coming_events }}
|
||||
{{ past_events }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
<div class="col small-col-12 med-col-4 large-col-4">
|
||||
<div class="col small-col-12 med-col-6 large-col-6">
|
||||
<div class="wrapper">
|
||||
{{ content }}
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
{#
|
||||
/**
|
||||
* @file
|
||||
* Default theme implementation for a link to a file.
|
||||
*
|
||||
* Available variables:
|
||||
* - attributes: The HTML attributes for the containing element.
|
||||
* - link: A link to the file.
|
||||
*
|
||||
* @see template_preprocess_file_link()
|
||||
*
|
||||
* @ingroup themeable
|
||||
*/
|
||||
#}
|
||||
<span{{ attributes }}>{{ link }}</span>
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user