Compare commits

...
21 Commits
Author SHA1 Message Date
bachir 551ff35344 core security update 8.5.3 2018-04-25 20:08:51 +02:00
bachir 4e1a5c59b5 added autologout module 2018-04-25 20:08:02 +02:00
bachir 780a55fb00 bug fix 2018-04-25 16:24:03 +02:00
bachir 7cbdba45da 5 next events on home page 2018-04-25 16:08:46 +02:00
bachir aebcee71b1 mignified assets for prod 2018-04-25 15:54:40 +02:00
bachir 28b23dcfbc added, designed and configured better_messages module 2018-04-25 15:54:14 +02:00
bachir 50f0d72e62 better registration form and accompt creation 2018-04-25 15:38:49 +02:00
bachir 956d8fb1ec better register form display 2018-04-25 15:37:24 +02:00
bachir 781d3d5230 final color set for corpus map, ho yeh! 2018-04-25 15:16:08 +02:00
bachir b7229d0c02 mignified assets for prod 2018-04-25 14:56:50 +02:00
bachir 6a09dbd486 fix pointer-event:none; on none .col element : other pages than front 2018-04-25 12:20:13 +02:00
bachir fff698433f fixed audio player with safari 2018-04-25 12:14:31 +02:00
bachir 2004adee70 fix chutier help popup 2018-04-24 22:37:21 +02:00
bachir 761659ddf0 production sound are now playable 2018-04-24 22:33:49 +02:00
bachir 6f7463ad93 production masonry hide block not fully visible 2018-04-24 21:54:22 +02:00
bachir 3e43f73411 fixed page without edlp_theme beahaviours not booted 2018-04-24 20:59:31 +02:00
bachir cfaa928600 imporved entree index display 2018-04-24 20:52:11 +02:00
bachir b98a63475e removed day name frome events display 2018-04-24 20:44:06 +02:00
bachir 799c739999 mignified assets for prod 2018-04-24 13:53:09 +02:00
bachir a4cdf3cfd2 new colors 2018-04-24 13:52:16 +02:00
bachir 1e52fb821c date is now good 2018-04-24 13:49:46 +02:00
127 changed files with 8464 additions and 4667 deletions
Generated
+23 -22
View File
@@ -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
View File
@@ -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"
}
@@ -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: []
@@ -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'
@@ -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);
@@ -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;
}
}
@@ -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'),
];
}
}
@@ -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,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
[![Build Status](https://travis-ci.org/geerlingguy/drupal-honeypot.svg?branch=8.x-1.x)](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'
@@ -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.');
}
}
@@ -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.');
}
}
@@ -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
@@ -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'
@@ -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;
}
}
@@ -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);
}
}
@@ -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.');
}
}
@@ -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
@@ -0,0 +1 @@
login_with_username: FALSE
@@ -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();
}
@@ -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());
}
}
@@ -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));
}
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -1,71 +1 @@
canvas#corpus-map {
position: absolute;
-webkit-box-sizing: border-box;
box-sizing: border-box;
top: 0;
left: 0;
z-index: 0; }
canvas#corpus-map.de-activated {
background-color: #f4f4f4; }
div.node-popup {
z-index: 10;
position: absolute;
-webkit-box-sizing: content-box;
box-sizing: content-box;
width: 300px;
min-height: 30px;
pointer-events: none;
top: 60%;
left: 30%;
pointer-events: none; }
div.node-popup .inner {
padding: 0.6em;
outline: 1px solid red;
background-color: white; }
div.node-popup:before {
content: "";
position: absolute;
width: 60px;
height: 0;
border-top: 1px solid red; }
div.node-popup[pos="bottom-right"] {
-webkit-transform: translateY(42px) translateX(42px);
transform: translateY(42px) translateX(42px); }
div.node-popup[pos="bottom-right"]:before {
top: -1px;
left: -61px;
-webkit-transform-origin: bottom right;
transform-origin: bottom right;
-webkit-transform: rotateZ(45deg);
transform: rotateZ(45deg); }
div.node-popup[pos="bottom-left"] {
-webkit-transform: translateX(-100%) translateY(42px) translateX(-42px);
transform: translateX(-100%) translateY(42px) translateX(-42px); }
div.node-popup[pos="bottom-left"]:before {
top: calc(100% +1px);
left: 100%;
-webkit-transform-origin: top left;
transform-origin: top left;
-webkit-transform: rotateZ(-45deg);
transform: rotateZ(-45deg); }
div.node-popup[pos="top-left"] {
-webkit-transform: translateY(-100%) translateX(-100%) translateY(-42px) translateX(-42px);
transform: translateY(-100%) translateX(-100%) translateY(-42px) translateX(-42px); }
div.node-popup[pos="top-left"]:before {
bottom: 0;
left: 100%;
-webkit-transform-origin: top left;
transform-origin: top left;
-webkit-transform: rotateZ(45deg);
transform: rotateZ(45deg); }
div.node-popup[pos="top-right"] {
-webkit-transform: translateY(-100%) translateY(-42px) translateX(42px);
transform: translateY(-100%) translateY(-42px) translateX(42px); }
div.node-popup[pos="top-right"]:before {
top: calc(100% + 1px);
left: -61px;
-webkit-transform-origin: top right;
transform-origin: top right;
-webkit-transform: rotateZ(-45deg);
transform: rotateZ(-45deg); }
canvas#corpus-map{position:absolute;-webkit-box-sizing:border-box;box-sizing:border-box;top:0;left:0;z-index:0}canvas#corpus-map.de-activated{background-color:#f4f4f4}div.node-popup{z-index:10;position:absolute;-webkit-box-sizing:content-box;box-sizing:content-box;width:300px;min-height:30px;top:60%;left:30%;pointer-events:none}div.node-popup .inner{padding:.6em;outline:red solid 1px;background-color:#fff}div.node-popup:before{content:"";position:absolute;width:60px;height:0;border-top:1px solid red}div.node-popup[pos=bottom-right]{-webkit-transform:translateY(42px) translateX(42px);transform:translateY(42px) translateX(42px)}div.node-popup[pos=bottom-right]:before{top:-1px;left:-61px;-webkit-transform-origin:bottom right;transform-origin:bottom right;-webkit-transform:rotateZ(45deg);transform:rotateZ(45deg)}div.node-popup[pos=bottom-left]{-webkit-transform:translateX(-100%) translateY(42px) translateX(-42px);transform:translateX(-100%) translateY(42px) translateX(-42px)}div.node-popup[pos=bottom-left]:before{top:calc(100% +1px);left:100%;-webkit-transform-origin:top left;transform-origin:top left;-webkit-transform:rotateZ(-45deg);transform:rotateZ(-45deg)}div.node-popup[pos=top-left]{-webkit-transform:translateY(-100%) translateX(-100%) translateY(-42px) translateX(-42px);transform:translateY(-100%) translateX(-100%) translateY(-42px) translateX(-42px)}div.node-popup[pos=top-left]:before{bottom:0;left:100%;-webkit-transform-origin:top left;transform-origin:top left;-webkit-transform:rotateZ(45deg);transform:rotateZ(45deg)}div.node-popup[pos=top-right]{-webkit-transform:translateY(-100%) translateY(-42px) translateX(42px);transform:translateY(-100%) translateY(-42px) translateX(42px)}div.node-popup[pos=top-right]:before{top:calc(100% + 1px);left:-61px;-webkit-transform-origin:top right;transform-origin:top right;-webkit-transform:rotateZ(-45deg);transform:rotateZ(-45deg)}
@@ -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();
@@ -1,125 +1,4 @@
(function ($, Drupal, drupalSettings) {
var settings = drupalSettings.edlp_search;
var _$body = $('body');
var _$container;
var _$form;
function init(){
// console.log('EdlpSearch Init', settings);
initEvents();
initAjax();
};
function initEvents(){
$('body')
.on('new-content-ajax-loaded', initAjax)
.on('edlp_search_search_form-col-closed', onSearchClosed);
};
function initAjax(){
_$form = $('#edlp-search-form:not(.ajax-enabled)');
if(!_$form.length) return false;
//console.log('EdlpSearch initAjaxForm()');
_$form = $('#edlp-search-form:not(.ajax-enabled)')
.on('submit', onSubmitForm)
.addClass('ajax-enabled');
_$container = _$form.parents('.row');
if(!_$container.length){
_$container = _$form.parent();
}
};
function onSubmitForm(e){
e.preventDefault();
// console.log('onSubmitForm',e);
var args = {};
// search for key words
args.keys = $('input[type="search"]', this).val();
// entries filter
args.entries = [];
$('input[type="checkbox"]:checked', '#edit-entries').each(function(index, el) {
args.entries.push($(this).val());
});
// langues
args.langues = $('input[name="language"]', this).val();
// genres
args.genres = $('input[name="genres"]', this).val();
//console.log('EdlpSearch onSubmitForm() : args',args);
loadResults(args);
return false;
};
function loadResults(args){
//console.log('EdlpSearch loadResults() : args', args);
_$form.addClass('ajax-loading');
_$body.addClass('ajax-loading');
$('[theme="edlp_search_results"]', _$container).addClass('ajax-loading');
var path = window.location.origin + drupalSettings.path.baseUrl +settings.results_ajax_url;
$.getJSON(path, args)
.done(function(data){
onResultsLoaded(data);
})
.fail(function(jqxhr, textStatus, error){
onResultsLoadFail(jqxhr, textStatus, error);
});
};
function onResultsLoaded(data){
// console.log('EdlpSearch onResultsLoaded()', data);
_$form.removeClass('ajax-loading');
_$body.removeClass('ajax-loading');
// insert results col
$prev_results = $('[theme="edlp_search_results"]', _$container);
if($prev_results.length){
$prev_results.replaceWith(data.rendered);
}else{
_$container.append(data.rendered);
}
// trigger event
_$body.trigger({
'type':'search-results-loaded',
'results':data.results_nids
});
// piwik
if(typeof _paq !== 'undefined'){
// page tracking
// https://matomo.org/blog/2017/02/how-to-track-single-page-websites-using-piwik-analytics/
// _paq.push(['setCustomUrl', state.url]);
// _paq.push(['setDocumentTitle', data.title]);
// _paq.push(['trackPageView']);
// trackEvent(category, action, [name], [value])
var search_name = data.keys+';'+data.langues+';'+data.genres+';'+data.entry_names.join(',');
// _paq.push(['trackEvent', 'AjaxSearch', 'Results', search_name, data.results_nids.length]);
// piwik track searches
// trackSiteSearch(keyword, [category], [resultsCount])
_paq.push(['trackSiteSearch', search_name, 'search', data.results_nids.length]);
}
};
function onResultsLoadFail(jqxhr, textStatus, error){
console.warn('EdlpSearch : search results ajax load failed : '+error, jqxhr.responseText);
};
function onSearchClosed(e){
// console.log('Edlp Search onSearchClosed()');
$('div[theme="edlp_search_results"]').remove();
// trigger event
_$body.trigger({'type':'search-closed'});
}
init();
})(jQuery, Drupal, drupalSettings);
(function($,Drupal,drupalSettings){var settings=drupalSettings.edlp_search;var _$body=$('body');var _$container;var _$form;function init(){initEvents();initAjax();};function initEvents(){$('body').on('new-content-ajax-loaded',initAjax).on('edlp_search_search_form-col-closed',onSearchClosed);};function initAjax(){_$form=$('#edlp-search-form:not(.ajax-enabled)');if(!_$form.length)return false;_$form=$('#edlp-search-form:not(.ajax-enabled)').on('submit',onSubmitForm).addClass('ajax-enabled');_$container=_$form.parents('.row');if(!_$container.length){_$container=_$form.parent();}};function onSubmitForm(e){e.preventDefault();var args={};args.keys=$('input[type="search"]',this).val();args.entries=[];$('input[type="checkbox"]:checked','#edit-entries').each(function(index,el){args.entries.push($(this).val());});args.langues=$('input[name="language"]',this).val();args.genres=$('input[name="genres"]',this).val();loadResults(args);return false;};function loadResults(args){_$form.addClass('ajax-loading');_$body.addClass('ajax-loading');$('[theme="edlp_search_results"]',_$container).addClass('ajax-loading');var path=window.location.origin+drupalSettings.path.baseUrl+settings.results_ajax_url;$.getJSON(path,args).done(function(data){onResultsLoaded(data);}).fail(function(jqxhr,textStatus,error){onResultsLoadFail(jqxhr,textStatus,error);});};function onResultsLoaded(data){_$form.removeClass('ajax-loading');_$body.removeClass('ajax-loading');$prev_results=$('[theme="edlp_search_results"]',_$container);if($prev_results.length){$prev_results.replaceWith(data.rendered);}else{_$container.append(data.rendered);}
_$body.trigger({'type':'search-results-loaded','results':data.results_nids});if(typeof _paq!=='undefined'){var search_name=data.keys+';'+data.langues+';'+data.genres+';'+data.entry_names.join(',');_paq.push(['trackSiteSearch',search_name,'search',data.results_nids.length]);}};function onResultsLoadFail(jqxhr,textStatus,error){void 0;};function onSearchClosed(e){$('div[theme="edlp_search_results"]').remove();_$body.trigger({'type':'search-closed'});}
init();})(jQuery,Drupal,drupalSettings);
@@ -1,408 +1,10 @@
(function ($, Drupal, drupalSettings) {
var _settings = drupalSettings.edlp_studio;
var $composer;
// audio play is handled by edlp_theme
function init(){
// console.log('Studio Init');
initEvents();
initStudio();
};
function initEvents(){
$('body')
.on('new-audio-cartel-loaded', initAjaxChutierLinks)
.on('new-content-ajax-loaded', initStudio)
.on('all-modal-closed', initStudio);
};
function initStudio(){
if($('#studio-ui').length){
$composer = $('.composition_ui .composer', '#studio-ui');
initAjaxChutierLinks();
initAjaxCompoLinks();
initDragAndDropUI();
$('body').trigger({'type':'studio-initialized'});
}else{
$('body').trigger({'type':'studio-not-active'});
}
}
// ___ _ _ _ _ _ _ _ _ _
// / __| |_ _ _| |_(_)___ _ _ | \| |___ __| |___ | | (_)_ _ | |__ ___
// | (__| ' \ || | _| / -_) '_| | .` / _ \/ _` / -_) | |__| | ' \| / /(_-<
// \___|_||_\_,_|\__|_\___|_| |_|\_\___/\__,_\___| |____|_|_||_|_\_\/__/
function initAjaxChutierLinks(){
//console.log('studio initAjaxChutierLinks');
$('.chutier-ajax-link:not(.ajax-enabled)')
.addClass('ajax-enabled')
.on('click', onClickChutierAjaxLink);
};
function onClickChutierAjaxLink(e){
//console.log('studio onClickAjaxLink chutier');
e.preventDefault();
addRemoveToChutier($(this));
return false;
};
function addRemoveToChutier($link){
// var ajax_path = 'edlp_studio/ajax/chutier/add/'+id; // + '/' +cid;
var ajax_path = $link.attr('data-drupal-link-system-path');
var path = window.location.origin + drupalSettings.path.baseUrl + ajax_path;
$link.addClass('ajax-loading');
$.getJSON(path, {})
.done(function(data){
onActionToChutierDone($link, data);
})
.fail(function(jqxhr, textStatus, error){
onErrorActionToChutier(jqxhr, textStatus, error, $link);
});
};
function onActionToChutierDone($link, data){
//console.log('onActionToChutierDone',data);
$('body').trigger({
'type':'chutier-action-done',
'action_done':data.action_done,
'new_action':data.action_done == 'add' ? 'remove' : 'add',
'target_id':$link.attr('target_id'),
});
$link.replaceWith(data.new_link);
initAjaxChutierLinks();
// reload Studio chutier_ui's documents list
updateStudioChutier();
};
function onErrorActionToChutier(jqxhr, textStatus, error, $link){
console.warn('action to chuttier load failed : '+error, jqxhr.responseText);
};
// ___ _ _ _
// / __|___ _ __ _ __ ___ __(_) |_(_)___ _ _ ___
// | (__/ _ \ ' \| '_ \/ _ (_-< | _| / _ \ ' \(_-<
// \___\___/_|_|_| .__/\___/__/_|\__|_\___/_||_/__/
// |_|
function initAjaxCompoLinks(){
//console.log('studio initAjaxCompoLinks');
$('.new-composition-link:not(.ajax-enabled)')
.on('click', onClickNewCompoLink)
.addClass('ajax-enabled');
$('.composition-link:not(.ajax-enabled)')
.on('click', onClickCompoLink)
.addClass('ajax-enabled');
$('.delete-composition-link:not(.ajax-enabled)')
.on('click', onClickDeleteCompoLink)
.addClass('ajax-enabled');
};
// ___ ___
// / _ \ _ __ ___ _ _ / __|___ _ __ _ __ ___
// | (_) | '_ \/ -_) ' \ | (__/ _ \ ' \| '_ \/ _ \
// \___/| .__/\___|_||_| \___\___/_|_|_| .__/\___/
// |_| |_|
function onClickCompoLink(e){
e.preventDefault();
//console.log('onClickCompoLink');
openCompo($(this));
return false;
};
function openCompo($link){
var cid = $link.attr('cid');
var ajax_path = _settings.open_compo_ajax_url+'/'+cid;
var path = window.location.origin + Drupal.url(ajax_path);
$link.addClass('ajax-loading');
$composer.addClass('ajax-loading');
$.getJSON(path, {})
.done(function(data){
onOpenCompoDone(data, $link);
})
.fail(function(jqxhr, textStatus, error){
onErrorOpenCompo(jqxhr, textStatus, error, $link);
});
};
function onOpenCompoDone(data, $link){
//console.log('onActionToCompoDone',data);
$('.composition-link').removeClass('is-active');
$link.removeClass('ajax-loading').addClass('is-active');
if($('.composition', $composer).length){
$('.composition', $composer).replaceWith(data.compo);
}else{
$('header', $composer).after(data.compo);
}
$composer.removeClass('ajax-loading');
initDragAndDropUI();
$('body').trigger({
'type':'on-studio-compo-opened'
});
};
function onErrorOpenCompo(jqxhr, textStatus, error, $link){
$link.removeClass('ajax-loading');
console.warn('open compo load failed : '+error, jqxhr.responseText);
};
// _ _ _____ __ __ __ ___ _ __ _ __ ___
// | ' \/ -_) V V / / _/ _ \ ' \| '_ \/ _ \
// |_||_\___|\_/\_/ \__\___/_|_|_| .__/\___/
// |_|
function onClickNewCompoLink(e){
e.preventDefault();
setInputForNewCompoName($(this));
return false;
};
function setInputForNewCompoName($link){
var $form = $('<form>').addClass('new-compo-form')
.append($('<input>').attr('type', 'text').attr('placeholder', 'new name'))
.append($('<button>').attr('type', 'submit').html('+'))
.submit(function(e){
onNewCompoFormSubmit(e, $link, $(this));
});
$link
.after($form)
.addClass('folded');
$form.children('input[type="text"]').focus();
};
function onNewCompoFormSubmit(e, $link, $form){
var name = $('input[type="text"]',$form).val();
//console.log('onNewCompoFormSubmit', name);
if(name != ''){
$form.addClass('ajax-loading').children('*').attr('disabled', 'disabled');
createNewCompo(name, $link, $form);
}
e.preventDefault();
};
function createNewCompo(name,$link, $form){
var ajax_path = $link.attr('data-drupal-link-system-path');
var path = window.location.origin + drupalSettings.path.baseUrl + ajax_path;
// $link.addClass('ajax-loading');
$.getJSON(path, {
'new_name':name
})
.done(function(data){
onCreateCompoDone(data, $link, $form);
})
.fail(function(jqxhr, textStatus, error){
onErrorCreateCompo(jqxhr, textStatus, error, $link);
});
};
function onCreateCompoDone(data, $link, $form){
//console.log('onActionToCompoDone',data);
var $new_link = $(data.new_link);
var $delete_link = $(data.delete_link);
$link
.removeClass('folded')
.parents('li')
.before($('<li>').append($new_link).append($delete_link));
$form.remove();
// open new composition to composer
initAjaxCompoLinks();
openCompo($new_link);
};
function onErrorCreateCompo(jqxhr, textStatus, error, $link){
console.warn('action to compo load failed : '+error, jqxhr.responseText);
};
// ___ _ _
// | \ ___| |___| |_ ___ __ ___ _ __ _ __ ___
// | |) / -_) / -_) _/ -_) / _/ _ \ ' \| '_ \/ _ \
// |___/\___|_\___|\__\___| \__\___/_|_|_| .__/\___/
// |_|
function onClickDeleteCompoLink(e){
e.preventDefault();
// TODO: confirm compo deletion
deleteCompo($(this));
return false;
};
function deleteCompo($link){
var ajax_path = $link.attr('data-drupal-link-system-path');
var path = window.location.origin + Drupal.url(ajax_path);
$link.parents('li').addClass('ajax-loading');
$.getJSON(path, {})
.done(function(data){
onDeleteCompoDone(data, $link);
})
.fail(function(jqxhr, textStatus, error){
onErrorDeleteCompo(jqxhr, textStatus, error, $link);
});
};
function onDeleteCompoDone(data, $link, $form){
//console.log('onDeleteCompoDone',data);
if(data.status == "ok"){
$link.parents('li').remove();
//console.log("$('.composition-link').length", $('.composition-link').length);
if($('.composition-link').length){
openCompo($('.composition-link').eq(0));
}else{
$('.composition', $composer).html();
}
}else{
console.warn(data.message);
}
};
function onErrorDeleteCompo(jqxhr, textStatus, error, $link){
$link.parents('li').removeClass('ajax-loading');
console.warn('delete compo load failed : '+error, jqxhr.responseText);
};
// ___ _ _ _ _
// / __| |_ _ _ __| (_)___ ___ _ _(_)
// \__ \ _| || / _` | / _ \___| || | |
// |___/\__|\_,_\__,_|_\___/ \_,_|_|
// this seems dirty
function updateStudioChutier(){
$studioChutier = $('#studio-ui .chutier_ui');
if($studioChutier.length){
var ajax_path = _settings.chutier_ui_ajax;
var path = window.location.origin + drupalSettings.path.baseUrl + ajax_path;
$studioChutier.addClass('loading');
$.getJSON(path, {})
.done(function(data){
onLoadedChutier($studioChutier, data);
})
.fail(function(jqxhr, textStatus, error){
onLoadChutierError(jqxhr, textStatus, error, $studioChutier);
});
}
};
function onLoadedChutier($studioChutier, data){
$studioChutier.replaceWith(data.rendered);
initAjaxChutierLinks();
// set chutier element draggable again
setChutierDraggable();
$('body').trigger({
'type':'on-studio-chutier-updated'
});
}
function onLoadChutierError(jqxhr, textStatus, error, $studioChutier){
console.warn('Chutier load failed', jqxhr.responseText);
$studioChutier.removeClass('loading');
}
// ___ __ ___ _ _ ___
// | \ _ _ __ _ __ _ / _|___ | \ _ _ ___ _ __ | | | |_ _|
// | |) | '_/ _` / _` | > _|_ _| | |) | '_/ _ \ '_ \ | |_| || |
// |___/|_| \__,_\__, | \_____| |___/|_| \___/ .__/ \___/|___|
// |___/ |_|
function initDragAndDropUI(){
// check if field--name-documents exists
if (!$('.composition_ui .composer .composition .field--name-documents').length) {
// if not create it
$field_documents = $('<div>')
.addClass('field').addClass('field--name-documents')
.appendTo('.composition_ui .composer .composition');
}else{
// add real dom square element to handle sorting
$field_documents = $('.composition_ui .composer .composition .field--name-documents'); $('.field__item', $field_documents).each(function(i){
$(this).prepend($('<span>').addClass('handler'));
});
}
// create remove dropzone
var $remove_zone = $('<div>').addClass('remove-drop-zone')
.appendTo('.composition_ui .composer .composition')
.droppable({
tolerance:'pointer',
// scope:'composition_ui',
over:function(e,ui){
// console.log('on over remove : ui', ui);
ui.draggable.addClass('ready-to-remove');
},
out:function(e,ui){
// console.log('on over remove : ui', ui);
ui.draggable.removeClass('ready-to-remove');
},
drop:function(e,ui){
// console.log('on drop remove : ui', ui);
ui.draggable.remove();
// onOrderChanged(ui);
}
});
// create sortable
$field_documents.sortable({
revert:false,
handle: ".handler",
receive:function(e, ui){
$('.field__item', this).attr('style', '');
// TODO: trigger event to enable new audiolink player
},
update:function(e, ui){
onOrderChanged(e, ui);
},
connectWith : $remove_zone,
});
// set chutier element draggable
setChutierDraggable();
};
function setChutierDraggable(){
$('.chutier_ui .item-list li>div').draggable({
containment:$('#studio-ui'),
scroll:false,
helper:function(e){
// we reproduce here the irem structure of destination sortable elements
// var $audio_link = $('.audio-link',this);
return $('<div>').addClass('field__item')
.append(
$('<article>').addClass('node').append(
$('<h2>').addClass('node-title').append(
// $('<a>')
// .attr('nid', $audio_link.attr('nid'))
// .html($audio_link.html())
$('.audio-link',this).clone().removeClass('ajax-enable')
)
)
)
.prepend($('<span>').addClass('handler'));
},
// cursor:'grab',
cursorAt:{bottom:10,left:10},
zIndex:999,
revert:true,
revertDuration:0,
connectToSortable:$('.composition_ui .composer .composition .field--name-documents'),
});
}
function onOrderChanged(e, ui){
//console.log('onOrderChanged : e', e);
var cid = $(e.target).parents('.composition').attr('cid');
var documents = {};
$('a', e.target).each(function(i) {
// console.log(this);
documents[i] = $(this).attr('nid');
});
// console.log(documents);
recordCompoList(cid, documents);
};
function recordCompoList(cid, docs){
//console.log('recordCompoList '+cid, docs);
var ajax_path = _settings.save_compo_ajax_url+'/'+cid;
var path = window.location.origin + Drupal.url(ajax_path);
//console.log('path', path);
$.getJSON(path, {
documents:docs
})
.done(function(data){
onRecordCompoDone(data);
})
.fail(function(jqxhr, textStatus, error){
onErrorRecordCompo(jqxhr, textStatus, error);
});
$('body').trigger({
'type':'on-studio-compo-updated'
});
}
function onRecordCompoDone(data){
//console.log('onDeleteCompoDone',data);
if(data.status == "ok"){
}else{
console.warn(data.message);
}
};
function onErrorRecordCompo(jqxhr, textStatus, error){
console.warn('record compo failed : '+error, jqxhr.responseText);
};
init();
})(jQuery, Drupal, drupalSettings);
(function($,Drupal,drupalSettings){var _settings=drupalSettings.edlp_studio;var $composer;function init(){initEvents();initStudio();};function initEvents(){$('body').on('new-audio-cartel-loaded',initAjaxChutierLinks).on('new-content-ajax-loaded',initStudio).on('all-modal-closed',initStudio);};function initStudio(){if($('#studio-ui').length){$composer=$('.composition_ui .composer','#studio-ui');initAjaxChutierLinks();initAjaxCompoLinks();initDragAndDropUI();$('body').trigger({'type':'studio-initialized'});}else{$('body').trigger({'type':'studio-not-active'});}}
function initAjaxChutierLinks(){$('.chutier-ajax-link:not(.ajax-enabled)').addClass('ajax-enabled').on('click',onClickChutierAjaxLink);};function onClickChutierAjaxLink(e){e.preventDefault();addRemoveToChutier($(this));return false;};function addRemoveToChutier($link){var ajax_path=$link.attr('data-drupal-link-system-path');var path=window.location.origin+drupalSettings.path.baseUrl+ajax_path;$link.addClass('ajax-loading');$.getJSON(path,{}).done(function(data){onActionToChutierDone($link,data);}).fail(function(jqxhr,textStatus,error){onErrorActionToChutier(jqxhr,textStatus,error,$link);});};function onActionToChutierDone($link,data){$('body').trigger({'type':'chutier-action-done','action_done':data.action_done,'new_action':data.action_done=='add'?'remove':'add','target_id':$link.attr('target_id'),});$link.replaceWith(data.new_link);initAjaxChutierLinks();updateStudioChutier();};function onErrorActionToChutier(jqxhr,textStatus,error,$link){void 0;};function initAjaxCompoLinks(){$('.new-composition-link:not(.ajax-enabled)').on('click',onClickNewCompoLink).addClass('ajax-enabled');$('.composition-link:not(.ajax-enabled)').on('click',onClickCompoLink).addClass('ajax-enabled');$('.delete-composition-link:not(.ajax-enabled)').on('click',onClickDeleteCompoLink).addClass('ajax-enabled');};function onClickCompoLink(e){e.preventDefault();openCompo($(this));return false;};function openCompo($link){var cid=$link.attr('cid');var ajax_path=_settings.open_compo_ajax_url+'/'+cid;var path=window.location.origin+Drupal.url(ajax_path);$link.addClass('ajax-loading');$composer.addClass('ajax-loading');$.getJSON(path,{}).done(function(data){onOpenCompoDone(data,$link);}).fail(function(jqxhr,textStatus,error){onErrorOpenCompo(jqxhr,textStatus,error,$link);});};function onOpenCompoDone(data,$link){$('.composition-link').removeClass('is-active');$link.removeClass('ajax-loading').addClass('is-active');if($('.composition',$composer).length){$('.composition',$composer).replaceWith(data.compo);}else{$('header',$composer).after(data.compo);}
$composer.removeClass('ajax-loading');initDragAndDropUI();$('body').trigger({'type':'on-studio-compo-opened'});};function onErrorOpenCompo(jqxhr,textStatus,error,$link){$link.removeClass('ajax-loading');void 0;};function onClickNewCompoLink(e){e.preventDefault();setInputForNewCompoName($(this));return false;};function setInputForNewCompoName($link){var $form=$('<form>').addClass('new-compo-form').append($('<input>').attr('type','text').attr('placeholder','new name')).append($('<button>').attr('type','submit').html('+')).submit(function(e){onNewCompoFormSubmit(e,$link,$(this));});$link.after($form).addClass('folded');$form.children('input[type="text"]').focus();};function onNewCompoFormSubmit(e,$link,$form){var name=$('input[type="text"]',$form).val();if(name!=''){$form.addClass('ajax-loading').children('*').attr('disabled','disabled');createNewCompo(name,$link,$form);}
e.preventDefault();};function createNewCompo(name,$link,$form){var ajax_path=$link.attr('data-drupal-link-system-path');var path=window.location.origin+drupalSettings.path.baseUrl+ajax_path;$.getJSON(path,{'new_name':name}).done(function(data){onCreateCompoDone(data,$link,$form);}).fail(function(jqxhr,textStatus,error){onErrorCreateCompo(jqxhr,textStatus,error,$link);});};function onCreateCompoDone(data,$link,$form){var $new_link=$(data.new_link);var $delete_link=$(data.delete_link);$link.removeClass('folded').parents('li').before($('<li>').append($new_link).append($delete_link));$form.remove();initAjaxCompoLinks();openCompo($new_link);};function onErrorCreateCompo(jqxhr,textStatus,error,$link){void 0;};function onClickDeleteCompoLink(e){e.preventDefault();deleteCompo($(this));return false;};function deleteCompo($link){var ajax_path=$link.attr('data-drupal-link-system-path');var path=window.location.origin+Drupal.url(ajax_path);$link.parents('li').addClass('ajax-loading');$.getJSON(path,{}).done(function(data){onDeleteCompoDone(data,$link);}).fail(function(jqxhr,textStatus,error){onErrorDeleteCompo(jqxhr,textStatus,error,$link);});};function onDeleteCompoDone(data,$link,$form){if(data.status=="ok"){$link.parents('li').remove();if($('.composition-link').length){openCompo($('.composition-link').eq(0));}else{$('.composition',$composer).html();}}else{void 0;}};function onErrorDeleteCompo(jqxhr,textStatus,error,$link){$link.parents('li').removeClass('ajax-loading');void 0;};function updateStudioChutier(){$studioChutier=$('#studio-ui .chutier_ui');if($studioChutier.length){var ajax_path=_settings.chutier_ui_ajax;var path=window.location.origin+drupalSettings.path.baseUrl+ajax_path;$studioChutier.addClass('loading');$.getJSON(path,{}).done(function(data){onLoadedChutier($studioChutier,data);}).fail(function(jqxhr,textStatus,error){onLoadChutierError(jqxhr,textStatus,error,$studioChutier);});}};function onLoadedChutier($studioChutier,data){$studioChutier.replaceWith(data.rendered);initAjaxChutierLinks();setChutierDraggable();$('body').trigger({'type':'on-studio-chutier-updated'});}
function onLoadChutierError(jqxhr,textStatus,error,$studioChutier){void 0;$studioChutier.removeClass('loading');}
function initDragAndDropUI(){if(!$('.composition_ui .composer .composition .field--name-documents').length){$field_documents=$('<div>').addClass('field').addClass('field--name-documents').appendTo('.composition_ui .composer .composition');}else{$field_documents=$('.composition_ui .composer .composition .field--name-documents');$('.field__item',$field_documents).each(function(i){$(this).prepend($('<span>').addClass('handler'));});}
var $remove_zone=$('<div>').addClass('remove-drop-zone').appendTo('.composition_ui .composer .composition').droppable({tolerance:'pointer',over:function(e,ui){ui.draggable.addClass('ready-to-remove');},out:function(e,ui){ui.draggable.removeClass('ready-to-remove');},drop:function(e,ui){ui.draggable.remove();}});$field_documents.sortable({revert:false,handle:".handler",receive:function(e,ui){$('.field__item',this).attr('style','');},update:function(e,ui){onOrderChanged(e,ui);},connectWith:$remove_zone,});setChutierDraggable();};function setChutierDraggable(){$('.chutier_ui .item-list li>div').draggable({containment:$('#studio-ui'),scroll:false,helper:function(e){return $('<div>').addClass('field__item').append($('<article>').addClass('node').append($('<h2>').addClass('node-title').append($('.audio-link',this).clone().removeClass('ajax-enable')))).prepend($('<span>').addClass('handler'));},cursorAt:{bottom:10,left:10},zIndex:999,revert:true,revertDuration:0,connectToSortable:$('.composition_ui .composer .composition .field--name-documents'),});}
function onOrderChanged(e,ui){var cid=$(e.target).parents('.composition').attr('cid');var documents={};$('a',e.target).each(function(i){documents[i]=$(this).attr('nid');});recordCompoList(cid,documents);};function recordCompoList(cid,docs){var ajax_path=_settings.save_compo_ajax_url+'/'+cid;var path=window.location.origin+Drupal.url(ajax_path);$.getJSON(path,{documents:docs}).done(function(data){onRecordCompoDone(data);}).fail(function(jqxhr,textStatus,error){onErrorRecordCompo(jqxhr,textStatus,error);});$('body').trigger({'type':'on-studio-compo-updated'});}
function onRecordCompoDone(data){if(data.status=="ok"){}else{void 0;}};function onErrorRecordCompo(jqxhr,textStatus,error){void 0;};init();})(jQuery,Drupal,drupalSettings);
@@ -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>'
@@ -1,20 +1,2 @@
console.log('EDLP THEME HISTORY.js');
// var edlp is provided by edlp_ajax.module file
if(edlp.redirect){
console.log('history redirect', edlp);
console.log('window.location', window.location);
// window.localStorage.setItem('edlp_origin_path', edlp.sys_path.replace(/^\//, ''));
edlp.sys_path = edlp.sys_path.replace(/^\//, '');
// window.localStorage.setItem('edlp_origin_url', window.location.pathname);
edlp.url = window.location.pathname;
// window.localStorage.setItem('edlp_origin_hash', window.location.hash);
edlp.hash = window.location.hash;
window.localStorage.setItem('edlp_origin', JSON.stringify(edlp));
// redirect to home
window.location.replace(window.location.origin+'/'+edlp.lang_code);
}else{
console.log('history do not redirect');
}
void 0;if(edlp.redirect){void 0;void 0;edlp.sys_path=edlp.sys_path.replace(/^\//,'');edlp.url=window.location.pathname;edlp.hash=window.location.hash;window.localStorage.setItem('edlp_origin',JSON.stringify(edlp));window.location.replace(window.location.origin+'/'+edlp.lang_code);}else{void 0;}
File diff suppressed because it is too large Load Diff
@@ -1027,7 +1027,7 @@ main[role="main"] {
width: 100%;
height: 100%;
overflow: hidden; }
main[role="main"] .layout-content > * {
main[role="main"] .layout-content .row > *:not(.col):not(.grid) {
pointer-events: auto; }
body.toolbar-horizontal.toolbar-themes.toolbar-no-tabs main[role="main"] {
@@ -1222,6 +1222,12 @@ main[role="main"] article.node.node--type-enregistrement.node--view-mode-article
text-transform: none;
margin: 0.9em 0 0 0; }
main[role="main"] article.node.node--type-enregistrement.node--view-mode-index, main[role="main"] article.node.node--type-enregistrement.node--view-mode-index p {
margin: 0; }
main[role="main"] article.node.node--type-enregistrement.node--view-mode-index h2.node-title {
margin-top: 0.2em; }
html.js main[role="main"] article.node.node--type-enregistrement.node--view-mode-transcript h3.sur-title {
display: none; }
@@ -1283,22 +1289,28 @@ main[role="main"] .agenda {
font-weight: normal;
line-height: 1.4; }
main[role="main"] article.node--type-evenement.node--view-mode-teaser .field--name-field-page-liee {
main[role="main"] article.node--type-evenement .field--name-field-page-liee {
font-size: 0.82em;
font-weight: 600;
line-height: 1.6;
text-transform: none; }
main[role="main"] article.node--type-evenement.node--view-mode-teaser .field--name-field-date {
main[role="main"] article.node--type-evenement .field--name-field-date {
font-size: 0.82em;
font-weight: normal;
line-height: 1.4; }
main[role="main"] article.node--type-evenement.node--view-mode-teaser .field--name-title {
main[role="main"] article.node--type-evenement .field--name-title {
font-size: 0.82em;
font-weight: normal;
line-height: 1.4; }
main[role="main"] article.node--type-evenement.node--view-mode-aside .field--name-field-date {
font-size: 0.82em;
font-weight: 600;
line-height: 1.6;
text-transform: none; }
main[role="main"] div.taxonomy-term > h2 {
font-size: 0.82em;
font-weight: 600;
@@ -2243,8 +2255,17 @@ body.path-agenda main .col > .wrapper {
body.path-frontpage .layout-content .row, body.path-productions .layout-content .row {
white-space: normal;
min-height: 100%; }
body.path-frontpage .layout-content .row .grid, body.path-productions .layout-content .row .grid {
position: relative;
min-height: 100%;
max-height: 100%; }
body.path-frontpage .layout-content .row .col, body.path-productions .layout-content .row .col {
height: auto; }
height: auto;
opacity: 1;
-webkit-transition: opacity 0.5s ease-in-out;
transition: opacity 0.5s ease-in-out; }
body.path-frontpage .layout-content .row .col.offfield, body.path-productions .layout-content .row .col.offfield {
opacity: 0; }
body.path-frontpage .layout-content .row .col.col-2:last-child, body.path-productions .layout-content .row .col.col-2:last-child {
padding-left: 0em;
padding-right: 1em; }
@@ -2823,3 +2844,50 @@ footer {
.url-to-video-container span.url-to-video-player .play-button {
z-index: 5;
top: 50%; }
#user-register-form {
width: 29em; }
#user-register-form input {
font-size: 0.82em;
font-weight: normal;
line-height: 1.4; }
#user-register-form label {
font-size: 0.82em;
font-weight: 600;
line-height: 1.6;
text-transform: none;
display: inline-block;
width: 16em;
white-space: normal; }
#user-register-form .form-item {
white-space: nowrap; }
#user-register-form .description {
font-size: 0.756em;
font-weight: normal;
line-height: 1.4;
max-width: 100%;
white-space: normal; }
#user-register-form input[type='email'], #user-register-form input[type='password'] {
width: 17em; }
#user-register-form .password-strength, #user-register-form .password-strength__meter {
width: 98%; }
#user-register-form .password-strength__title, #user-register-form .password-confirm {
font-size: 0.82em;
font-weight: normal;
line-height: 1.4; }
#better-messages-default.better-messages-overlay {
border-radius: 0;
padding: 0.8em;
-webkit-box-shadow: 0 2px 10px #716f6f;
box-shadow: 0 2px 10px #716f6f; }
#better-messages-default.better-messages-overlay .better-messages-footer {
border-top: none; }
#better-messages-default.better-messages-overlay .better-messages-footer .better-messages-close {
font-size: 0.82em;
font-weight: normal;
line-height: 1.4; }
#better-messages-default.better-messages-overlay .better-messages-footer .better-messages-close span {
height: 15px;
width: 15px;
background-size: contain; }
@@ -572,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)')
@@ -582,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');
}
});
@@ -607,6 +609,14 @@
return false;
}
// 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
@@ -739,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">');
@@ -883,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),
@@ -896,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){
@@ -1400,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,
});
@@ -1421,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');
}
}
}
}
// ___ _ _ _
// | __|_ _ _ _ ___ __ _(_)__| |_ _ _ ___ _ __ ___ _ _| |_
// | _|| ' \| '_/ -_) _` | (_-< _| '_/ -_) ' \/ -_) ' \ _|
@@ -1527,30 +1591,14 @@
}
};
// _ _ _
// | || |___| |_ __ ___ _ _ ___
// | __ / -_) | '_ \/ -_) '_(_-<
// |_||_\___|_| .__/\___|_| /__/
// |_|
// 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;}
@@ -350,7 +354,7 @@ main[role="main"]{
}
}
article.node--type-evenement.node--view-mode-teaser{
article.node--type-evenement{
.field--name-field-page-liee{
@include content_subtitles;
}
@@ -362,6 +366,11 @@ main[role="main"]{
}
// .field--name-body{}
}
article.node--type-evenement.node--view-mode-aside{
.field--name-field-date{
@include content_subtitles;
}
}
div.taxonomy-term{
>h2{
@@ -1300,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;
@@ -2000,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;
}
}

Some files were not shown because too many files have changed in this diff Show More