diff --git a/.gitignore b/.gitignore index 59b6207b..2faf5af4 100644 --- a/.gitignore +++ b/.gitignore @@ -9,30 +9,6 @@ sites/*/private sites/*/translations # Ignore default text files -robots.txt -/CHANGELOG.txt -/COPYRIGHT.txt -/INSTALL*.txt -/LICENSE.txt -/MAINTAINERS.txt -/UPGRADE.txt -/README.txt -sites/README.txt -sites/all/libraries/README.txt -sites/all/modules/README.txt -sites/all/themes/README.txt # Ignore everything but the "sites" folder ( for non core developer ) .htaccess -web.config -authorize.php -cron.php -index.php -install.php -update.php -xmlrpc.php -/includes -/misc -/modules -/profiles -/scripts diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 00000000..d159169d --- /dev/null +++ b/LICENSE.txt @@ -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. + + + Copyright (C) + + 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. + + , 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. diff --git a/README.txt b/README.txt new file mode 100644 index 00000000..0bafcc1b --- /dev/null +++ b/README.txt @@ -0,0 +1,139 @@ + +CONTENTS OF THIS FILE +--------------------- + + * About Drupal + * Configuration and features + * Installation profiles + * Appearance + * Developing for Drupal + * More information + +ABOUT DRUPAL +------------ + +Drupal is an open source content management platform supporting a variety of +websites ranging from personal weblogs to large community-driven websites. For +more information, see the Drupal website at https://www.drupal.org, and join +the Drupal community at https://www.drupal.org/community. + +Legal information about Drupal: + * Know your rights when using Drupal: + See LICENSE.txt in the "core" directory. + * Learn about the Drupal trademark and logo policy: + https://www.drupal.com/trademark + +CONFIGURATION AND FEATURES +-------------------------- + +Drupal core (what you get when you download and extract a drupal-x.y.tar.gz or +drupal-x.y.zip file from https://www.drupal.org/project/drupal) has what you +need to get started with your website. It includes several modules (extensions +that add functionality) for common website features, such as managing content, +user accounts, image uploading, and search. Core comes with many options that +allow site-specific configuration. In addition to the core modules, there are +thousands of contributed modules (for functionality not included with Drupal +core) available for download. + +More about configuration: + * Install, update, and maintain Drupal: + See INSTALL.txt and UPDATE.txt in the "core" directory. + * Learn about how to use Drupal to create your site: + https://www.drupal.org/documentation + * Follow best practices: + https://www.drupal.org/best-practices + * Download contributed modules to /modules to extend Drupal's functionality: + https://www.drupal.org/project/modules + * See also: "Developing for Drupal" for writing your own modules, below. + + +INSTALLATION PROFILES +--------------------- + +Installation profiles define additional steps (such as enabling modules, +defining content types, etc.) that run after the base installation provided +by core when Drupal is first installed. There are two basic installation +profiles provided with Drupal core. + +Installation profiles from the Drupal community modify the installation process +to provide a website for a specific use case, such as a CMS for media +publishers, a web-based project tracking tool, or a full-fledged CRM for +non-profit organizations raising money and accepting donations. They can be +distributed as bare installation profiles or as "distributions". Distributions +include Drupal core, the installation profile, and all other required +extensions, such as contributed and custom modules, themes, and third-party +libraries. Bare installation profiles require you to download Drupal Core and +the required extensions separately; place the downloaded profile in the +/profiles directory before you start the installation process. + +More about installation profiles and distributions: + * Read about the difference between installation profiles and distributions: + https://www.drupal.org/node/1089736 + * Download contributed installation profiles and distributions: + https://www.drupal.org/project/distributions + * Develop your own installation profile or distribution: + https://www.drupal.org/developing/distributions + + +APPEARANCE +---------- + +In Drupal, the appearance of your site is set by the theme (themes are +extensions that set fonts, colors, and layout). Drupal core comes with several +themes. More themes are available for download, and you can also create your own +custom theme. + +More about themes: + * Download contributed themes to /themes to modify Drupal's appearance: + https://www.drupal.org/project/themes + * Develop your own theme: + https://www.drupal.org/documentation/theme + +DEVELOPING FOR DRUPAL +--------------------- + +Drupal contains an extensive API that allows you to add to and modify the +functionality of your site. The API consists of "hooks", which allow modules to +react to system events and customize Drupal's behavior, and functions that +standardize common operations such as database queries and form generation. The +flexible hook architecture means that you should never need to directly modify +the files that come with Drupal core to achieve the functionality you want; +instead, functionality modifications take the form of modules. + +When you need new functionality for your Drupal site, search for existing +contributed modules. If you find a module that matches except for a bug or an +additional needed feature, change the module and contribute your improvements +back to the project in the form of a "patch". Create new custom modules only +when nothing existing comes close to what you need. + +More about developing: + * Search for existing contributed modules: + https://www.drupal.org/project/modules + * Contribute a patch: + https://www.drupal.org/patch/submit + * Develop your own module: + https://www.drupal.org/developing/modules + * Follow programming best practices: + https://www.drupal.org/developing/best-practices + * Refer to the API documentation: + https://api.drupal.org/api/drupal/8 + * Learn from documented Drupal API examples: + https://www.drupal.org/project/examples + +MORE INFORMATION +---------------- + + * See the Drupal.org online documentation: + https://www.drupal.org/documentation + + * For a list of security announcements, see the "Security advisories" page at + https://www.drupal.org/security (available as an RSS feed). This page also + describes how to subscribe to these announcements via email. + + * For information about the Drupal security process, or to find out how to + report a potential security issue to the Drupal security team, see the + "Security team" page at https://www.drupal.org/security-team + + * For information about the wide range of available support options, visit + https://www.drupal.org and click on Community and Support in the top or + bottom navigation. diff --git a/core/authorize.php b/core/authorize.php new file mode 100644 index 00000000..a72e0ac6 --- /dev/null +++ b/core/authorize.php @@ -0,0 +1,198 @@ +authenticate($request); + if ($account) { + \Drupal::currentUser()->setAccount($account); + } + return Settings::get('allow_authorize_operations', TRUE) && \Drupal::currentUser()->hasPermission('administer software updates'); +} + +try { + $request = Request::createFromGlobals(); + $kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod'); + $kernel->prepareLegacyRequest($request); +} +catch (HttpExceptionInterface $e) { + $response = new Response('', $e->getStatusCode()); + $response->prepare($request)->send(); + exit; +} + +// We have to enable the user and system modules, even to check access and +// display errors via the maintenance theme. +\Drupal::moduleHandler()->addModule('system', 'core/modules/system'); +\Drupal::moduleHandler()->addModule('user', 'core/modules/user'); +\Drupal::moduleHandler()->load('system'); +\Drupal::moduleHandler()->load('user'); + +// Initialize the maintenance theme for this administrative script. +drupal_maintenance_theme(); + +$content = []; +$show_messages = TRUE; + +$is_allowed = authorize_access_allowed($request); + +// Build content. +if ($is_allowed) { + // Load both the Form API and Batch API. + require_once __DIR__ . '/includes/form.inc'; + require_once __DIR__ . '/includes/batch.inc'; + + if (isset($_SESSION['authorize_page_title'])) { + $page_title = $_SESSION['authorize_page_title']; + } + else { + $page_title = t('Authorize file system changes'); + } + + // See if we've run the operation and need to display a report. + if (isset($_SESSION['authorize_results']) && $results = $_SESSION['authorize_results']) { + + // Clear the session out. + unset($_SESSION['authorize_results']); + unset($_SESSION['authorize_operation']); + unset($_SESSION['authorize_filetransfer_info']); + + if (!empty($results['page_title'])) { + $page_title = $results['page_title']; + } + if (!empty($results['page_message'])) { + drupal_set_message($results['page_message']['message'], $results['page_message']['type']); + } + + $content['authorize_report'] = [ + '#theme' => 'authorize_report', + '#messages' => $results['messages'], + ]; + + if (is_array($results['tasks'])) { + $links = $results['tasks']; + } + else { + // Since this is being called outsite of the primary front controller, + // the base_url needs to be set explicitly to ensure that links are + // relative to the site root. + // @todo Simplify with https://www.drupal.org/node/2548095 + $default_options = [ + '#type' => 'link', + '#options' => [ + 'absolute' => TRUE, + 'base_url' => $GLOBALS['base_url'], + ], + ]; + $links = [ + $default_options + [ + '#url' => Url::fromRoute('system.admin'), + '#title' => t('Administration pages'), + ], + $default_options + [ + '#url' => Url::fromRoute(''), + '#title' => t('Front page'), + ], + ]; + } + + $content['next_steps'] = [ + '#theme' => 'item_list', + '#items' => $links, + '#title' => t('Next steps'), + ]; + } + // If a batch is running, let it run. + elseif ($request->query->has('batch')) { + $content = _batch_page($request); + // If _batch_page() returns a response object (likely a JsonResponse for + // JavaScript-based batch processing), send it immediately. + if ($content instanceof Response) { + $content->send(); + exit; + } + } + else { + if (empty($_SESSION['authorize_operation']) || empty($_SESSION['authorize_filetransfer_info'])) { + $content = ['#markup' => t('It appears you have reached this page in error.')]; + } + elseif (!$batch = batch_get()) { + // We have a batch to process, show the filetransfer form. + try { + $content = \Drupal::formBuilder()->getForm('Drupal\Core\FileTransfer\Form\FileTransferAuthorizeForm'); + } + catch (EnforcedResponseException $e) { + $e->getResponse()->send(); + exit; + } + } + } + // We defer the display of messages until all operations are done. + $show_messages = !(($batch = batch_get()) && isset($batch['running'])); +} +else { + \Drupal::logger('access denied')->warning('authorize.php'); + $page_title = t('Access denied'); + $content = ['#markup' => t('You are not allowed to access this page.')]; +} + +$bare_html_page_renderer = \Drupal::service('bare_html_page_renderer'); +$response = $bare_html_page_renderer->renderBarePage($content, $page_title, 'maintenance_page', [ + '#show_messages' => $show_messages, +]); +if (!$is_allowed) { + $response->setStatusCode(403); +} +$response->send(); diff --git a/core/install.php b/core/install.php new file mode 100644 index 00000000..6bdd6f8c --- /dev/null +++ b/core/install.php @@ -0,0 +1,44 @@ +system requirements page for more information.'; + exit; +} + +// Initialize the autoloader. +$class_loader = require_once $root_path . '/autoload.php'; + +// If OPCache is in use, ensure opcache.save_comments is enabled. +if (OpCodeCache::isEnabled() && !ini_get('opcache.save_comments')) { + print 'Systems with OPcache installed must have opcache.save_comments enabled.'; + exit(); +} + +// Start the installer. +require_once $root_path . '/core/includes/install.core.inc'; +install_drupal($class_loader); diff --git a/index.php b/index.php new file mode 100644 index 00000000..750dc282 --- /dev/null +++ b/index.php @@ -0,0 +1,22 @@ +handle($request); +$response->send(); + +$kernel->terminate($request, $response); diff --git a/modules/README.txt b/modules/README.txt new file mode 100644 index 00000000..529c31b2 --- /dev/null +++ b/modules/README.txt @@ -0,0 +1,42 @@ +Modules extend your site functionality beyond Drupal core. + +WHAT TO PLACE IN THIS DIRECTORY? +-------------------------------- + +Placing downloaded and custom modules in this directory separates downloaded and +custom modules from Drupal core's modules. This allows Drupal core to be updated +without overwriting these files. + +DOWNLOAD ADDITIONAL MODULES +--------------------------- + +Contributed modules from the Drupal community may be downloaded at +https://www.drupal.org/project/project_module. + +ORGANIZING MODULES IN THIS DIRECTORY +------------------------------------ + +You may create subdirectories in this directory, to organize your added modules, +without breaking the site. Some common subdirectories include "contrib" for +contributed modules, and "custom" for custom modules. Note that if you move a +module to a subdirectory after it has been enabled, you may need to clear the +Drupal cache so it can be found. + +There are number of directories that are ignored when looking for modules. These +are 'src', 'lib', 'vendor', 'assets', 'css', 'files', 'images', 'js', 'misc', +'templates', 'includes', 'fixtures' and 'Drupal'. + +MULTISITE CONFIGURATION +----------------------- + +In multisite configurations, modules found in this directory are available to +all sites. You may also put modules in the sites/all/modules directory, and the +versions in sites/all/modules will take precedence over versions of the same +module that are here. Alternatively, the sites/your_site_name/modules directory +pattern may be used to restrict modules to a specific site instance. + +MORE INFORMATION +---------------- + +Refer to the “Developing for Drupal” section of the README.txt in the Drupal +root directory for further information on extending Drupal with custom modules. diff --git a/modules/addtocalendar/LICENSE b/modules/addtocalendar/LICENSE new file mode 100644 index 00000000..d0de3ef9 --- /dev/null +++ b/modules/addtocalendar/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2016 Purushotam Rai + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/modules/addtocalendar/LICENSE.txt b/modules/addtocalendar/LICENSE.txt new file mode 100644 index 00000000..d159169d --- /dev/null +++ b/modules/addtocalendar/LICENSE.txt @@ -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. + + + Copyright (C) + + 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. + + , 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. diff --git a/modules/addtocalendar/README.md b/modules/addtocalendar/README.md new file mode 100644 index 00000000..ac730466 --- /dev/null +++ b/modules/addtocalendar/README.md @@ -0,0 +1,83 @@ +CONTENTS OF THIS FILE +--------------------- + + * Introduction + * Module Details + * Recommended modules + * Configuration + * Troubleshooting + * FAQ + * Maintainers + + +INTRODUCTION +------------ +Add to Calendar Module integrates 'Add to Calendar' button provided by +addtocalendar.com which supports iCalender, Google Calendar, Outlook, +Outlook Online and Yahoo Calendar. It's basically a thirdparty field +formatter setting available for datetime field formatters. + +MODULE DETAILS +-------------- +Add to Calendar Module makes use of ADDTOCALENDAR.COM's service which +provides free button for event page on website and email. Button +supports all modern browsers and platforms: iOS, iPad, iPhone, Android, +Windows, Blackberry. Provides handful of configuration for a really +flexible experience. + +Module internally extends Datetime field formatters using third party +settings to append the "Add to Calendar" button besides date field. +When clicked on this button, the event is exported to the corresponding +website with proper information in the next tab where user can add the +event to their calendar. + +External CSS and JS files are provided by Addtocalendar.com + +SIMILAR MODULES +--------------- +* Addtocal (https://www.drupal.org/project/addtocal) + A field formatter providing a widget for exporting events to: + Google Calendar + Yahoo! Calendar + iCal + Outlook + + +CONFIGURATION +------------- +* Style: As of now 3 styles are available (Blue, Glow Orange and Basic). + +* Display Text: Text to be displayed on the button. + +* Title, Description, Location, Organizer, Organizer Email, End Date: + These are for collecting event information, which can be configured to + be collected from other fields, direct static data or tokens. + +* Private: Use public for free access to event information from any + places. User private if the event is closed to public access. + +* Security Level: Use https to protect your users. + +* List of calenders to show in button list. + +TROUBLESHOOTING +--------------- +As of now, Add to calendar Module uses Addtocalandar.com service and +css, js files. In case the module is not working properly, you may try: +* Rebuilding the cache +* Reinstalling the module. +* Try different style. + + +MAINTAINERS +----------- +Current maintainers: + + * Purushotam Rai (https://drupal.org/user/3193859) + + +This project has been sponsored by: + * QED42 + QED42 is a web development agency focussed on helping organisations and + individuals reach their potential, most of our work is in the space of + publishing, e-commerce, social and enterprise. diff --git a/modules/addtocalendar/addtocalendar.info.yml b/modules/addtocalendar/addtocalendar.info.yml new file mode 100644 index 00000000..df146e2e --- /dev/null +++ b/modules/addtocalendar/addtocalendar.info.yml @@ -0,0 +1,13 @@ +name: Add To Calendar +type: module +description: 'Add to calendar button to be used for event page.' +# version: VERSION +# core: 8.x +dependencies: + - datetime + +# Information added by Drupal.org packaging script on 2017-04-26 +version: '8.x-2.0' +core: '8.x' +project: 'addtocalendar' +datestamp: 1493189646 diff --git a/modules/addtocalendar/addtocalendar.libraries.yml b/modules/addtocalendar/addtocalendar.libraries.yml new file mode 100644 index 00000000..e57d6ea5 --- /dev/null +++ b/modules/addtocalendar/addtocalendar.libraries.yml @@ -0,0 +1,16 @@ +base: + css: + component: + '//addtocalendar.com/atc/1.5/atc-base.css': {type: external} + js: + '//addtocalendar.com/atc/1.5/atc.min.js': { type: external, minified: true } + +glow_orange: + css: + component: + '//addtocalendar.com/atc/1.5/atc-style-glow-orange.css': {type: external} + +blue: + css: + component: + '//addtocalendar.com/atc/1.5/atc-style-blue.css': {type: external} diff --git a/modules/addtocalendar/addtocalendar.module b/modules/addtocalendar/addtocalendar.module new file mode 100644 index 00000000..88739a44 --- /dev/null +++ b/modules/addtocalendar/addtocalendar.module @@ -0,0 +1,54 @@ +getPluginDefinition()['field_types']))) { + $settings = $plugin->getThirdPartySettings('addtocalendar'); + $element = _addtocalendar_build_form($settings, $field_definition); + } + return $element; +} + +/** + * Implements hook_field_formatter_settings_summary_alter(). + */ +function addtocalendar_field_formatter_settings_summary_alter(&$summary, $context) { + if (count(array_intersect(['datetime', 'daterange'], $context['formatter']->getPluginDefinition()['field_types']))) { + if ($context['formatter']->getThirdPartySetting('addtocalendar', 'addtocalendar_show')) { + $summary[] = t('Add to calendar enabled'); + } + } +} + +/** + * Implements hook_preprocess_field(). + */ +function addtocalendar_preprocess_field(&$variables) { + if ($variables['field_type'] == 'datetime' || $variables['field_type'] == 'daterange') { + _addtocalendar_preprocess_field($variables); + } +} diff --git a/modules/addtocalendar/includes/addtocalendar.build.inc b/modules/addtocalendar/includes/addtocalendar.build.inc new file mode 100644 index 00000000..4a1110c2 --- /dev/null +++ b/modules/addtocalendar/includes/addtocalendar.build.inc @@ -0,0 +1,196 @@ +getComponent($field_name); + + if (!empty($field_display['third_party_settings']['addtocalendar'])) { + $build['addtocalendar'] = []; + $settings = $field_display['third_party_settings']['addtocalendar']; + $style = []; + if ($settings['addtocalendar_show']) { + $token_service = \Drupal::token(); + $token_options = ['langcode' => $entity->language()->getId(), 'callback' => '', 'clear' => TRUE]; + $timeZone = date_default_timezone_get(); + $values = $entity->{$field_name}->getValue(); + $delta = !empty($settings['addtocalendar_settings']['delta']) ? $settings['addtocalendar_settings']['delta'] : 0; + if (empty($values[$delta]['value'])) { + return; + } + + // Unsetting values other than delta if single value is selected. + if ($settings['addtocalendar_settings']['multiple_value'] == 1) { + $temp = $values[$delta]; + unset($values); + $values = array($delta => $temp); + unset($temp); + } + foreach ($values as $index => $date_val) { + $date = new DrupalDateTime(preg_replace('/T/', ' ', $values[$index]['value']), 'UTC'); + if (!empty($values[$index]['end_value']) && isset($values[$index]['end_value'])) { + $end_date = new DrupalDateTime(preg_replace('/T/', ' ', $values[$index]['end_value']), 'UTC'); + } + + $build['addtocalendar'][$index]['atc_date_start'] = [ + '#type' => 'html_tag', + '#tag' => 'var', + '#value' => $date->format('Y-m-d H:i:s', ['timezone' => $timeZone]), + '#attributes' => [ + 'class' => 'atc_date_start', + ], + ]; + $info = [ + 'atc_date_end', + 'atc_title', + 'atc_description', + 'atc_location', + 'atc_organizer', + 'atc_organizer_email', + ]; + foreach ($info as $value) { + switch ($settings['addtocalendar_settings'][$value]['field']) { + case 'token': + $class_value = $settings['addtocalendar_settings'][$value]['tokenized']; + $class_value = $token_service->replace($class_value, array('node' => $entity), $token_options); + break; + + case 'title': + $class_value = $entity->getTitle(); + break; + + default: + $field = $settings['addtocalendar_settings'][$value]['field']; + if (strip_tags($entity->{$field}->getFieldDefinition() + ->getType()) == 'daterange' + ) { + $class_value = strip_tags($entity->{$field}->end_value); + } + else { + $class_value = strip_tags($entity->{$field}->value); + } + break; + } + $build['addtocalendar'][$index][$value] = [ + '#type' => 'html_tag', + '#tag' => 'var', + '#value' => $class_value, + '#attributes' => [ + 'class' => $value, + ], + ]; + } + + // Assign end date the value of start date if no end date is present and its not a daterange field. + if (empty($end_date)) { + $build['addtocalendar'][$index]['atc_date_end']['#value'] = (!empty($build['addtocalendar'][$index]['atc_date_end']['#value'])) ? $build['addtocalendar'][$index]['atc_date_end']['#value'] : $build['addtocalendar'][$index]['atc_date_start']['#value']; + $build['addtocalendar'][$index]['atc_date_end']['#value'] = (!empty($build['addtocalendar'][$index]['atc_date_end']['#value'])) ? $build['addtocalendar'][$index]['atc_date_start']['#value'] : $date->format('Y-m-d H:i:s', ['timezone' => $timeZone]); + } + // Assign end date the value of end date if no end date is present and its a daterange field. + else { + $end_date_val = $end_date->__toString(); + $build['addtocalendar'][$index]['atc_date_end']['#value'] = (!empty($build['addtocalendar'][$index]['atc_date_end']['#value'])) ? $build['addtocalendar'][$index]['atc_date_end']['#value'] : $end_date_val; + $build['addtocalendar'][$index]['atc_date_end']['#value'] = $end_date->format('Y-m-d H:i:s', ['timezone' => $timeZone]); + } + + $build['addtocalendar'][$index]['atc_timezone'] = [ + '#type' => 'html_tag', + '#tag' => 'var', + '#value' => $timeZone, + '#attributes' => [ + 'class' => 'atc_timezone', + ], + ]; + + $build['addtocalendar'][$index]['atc_privacy'] = [ + '#type' => 'html_tag', + '#tag' => 'var', + '#value' => $settings['addtocalendar_settings']['atc_privacy'], + '#attributes' => [ + 'class' => 'atc_privacy', + ], + ]; + + $build['addtocalendar'][$index] = [ + '#type' => 'html_tag', + '#tag' => 'span', + '#value' => '' . render($build['addtocalendar'][$index]) . '', + '#attributes' => [ + 'class' => [ + 'addtocalendar', + ], + ], + ]; + + if ($settings['addtocalendar_settings']['data_calendars']) { + $value = ''; + foreach ($settings['addtocalendar_settings']['data_calendars'] as $key => $set) { + if ($set) { + $value .= $key . ', '; + } + } + if ($value) { + $build['addtocalendar'][$index]['#attributes']['data-calendars'] = $value; + } + } + + $build['addtocalendar'][$index]['#attributes']['data-secure'] = $settings['addtocalendar_settings']['data_secure']; + // Styling. + switch ($settings['addtocalendar_settings']['style']) { + case 'blue': + $style['class'] = 'atc-style-blue'; + $style['library'] = 'addtocalendar/blue'; + break; + + case 'glow_orange': + $style['class'] = 'atc-style-glow-orange'; + $style['library'] = 'addtocalendar/glow_orange'; + break; + } + if (!empty($style)) { + $build['addtocalendar'][$index]['#attributes']['class'][] = $style['class']; + $variables['#attached']['library'][] = $style['library']; + } + } + } + // Setting #markup for all the date or daterange fields if multivalue is selected. + if ($settings['addtocalendar_settings']['multiple_value'] == 2) { + foreach ($variables['items'] as $k => $content) { + if (isset($variables['items'][$k]['content']['#markup'])) { + $variables['items'][$k]['content']['#markup'] .= render($build['addtocalendar'][$k]); + } + elseif (isset($variables['items'][$k]['content'])) { + unset($variables['items'][$k]['content']['#theme']); + $variables['items'][$k]['content']['#markup'] = $variables['items'][$k]['content']['#text'] . render($build['addtocalendar'][$k]); + } + $variables['#attached']['library'][] = 'addtocalendar/base'; + } + } + // Setting #markup for all the date or daterange fields if single value is selected. + else { + if (isset($variables['items'][$delta]['content']['#markup'])) { + $variables['items'][$delta]['content']['#markup'] .= render($build['addtocalendar']); + } + elseif (isset($variables['items'][$delta]['content'])) { + unset($variables['items'][$delta]['content']['#theme']); + $variables['items'][$delta]['content']['#markup'] = $variables['items'][$delta]['content']['#text'] . render($build['addtocalendar']); + } + $variables['#attached']['library'][] = 'addtocalendar/base'; + } + } +} diff --git a/modules/addtocalendar/includes/addtocalendar.form.inc b/modules/addtocalendar/includes/addtocalendar.form.inc new file mode 100644 index 00000000..cb1cb070 --- /dev/null +++ b/modules/addtocalendar/includes/addtocalendar.form.inc @@ -0,0 +1,183 @@ + 'checkbox', + '#title' => t('Show Add to Calendar'), + '#default_value' => !empty($settings['addtocalendar_show']) ? $settings['addtocalendar_show'] : 0, + ]; + + $element['addtocalendar_settings'] = [ + '#type' => 'fieldset', + '#title' => t('Add to Calendar Settings'), + '#states' => [ + 'visible' => [ + 'input[name*="addtocalendar_show"]' => ['checked' => TRUE], + ], + ], + ]; + + $element['addtocalendar_settings']['style'] = [ + '#type' => 'select', + '#title' => t('Select Style'), + '#options' => [ + 0 => t('No Styling'), + 'blue' => t('Blue'), + 'glow_orange' => t('Glow Orange'), + ], + '#default_value' => !empty($settings['addtocalendar_settings']['style']) ? $settings['addtocalendar_settings']['style'] : 'blue', + ]; + + $element['addtocalendar_settings']['display_text'] = [ + '#type' => 'textfield', + '#title' => t('Display Text'), + '#default_value' => !empty($settings['addtocalendar_settings']['display_text']) ? $settings['addtocalendar_settings']['display_text'] : t('Add to Calender'), + ]; + + // Fetching site name and site email id. + $config = \Drupal::config('system.site'); + $site_name = $config->get('name'); + $site_mail = $config->get('mail'); + + $info = [ + 'atc_title' => [ + 'label' => t('Title'), + 'sample_data' => 'Title', + ], + 'atc_description' => [ + 'label' => t('Description'), + 'sample_data' => 'Description', + ], + 'atc_location' => [ + 'label' => t('Location'), + 'sample_data' => 'Location', + ], + 'atc_organizer' => [ + 'label' => t('Organizer'), + 'sample_data' => $site_name, + ], + 'atc_organizer_email' => [ + 'label' => t('Organizer'), + 'sample_data' => $site_mail, + ], + 'atc_date_end' => [ + 'label' => t('End Date'), + 'sample_data' => '', + ], + ]; + + $fields = Drupal::service('entity_field.manager')->getFieldDefinitions($field_definition->get('entity_type'), $field_definition->get('bundle')); + $field_options = []; + foreach ($fields as $id => $field) { + if (is_a($field, 'Drupal\field\Entity\FieldConfig')) { + $field_options[$id] = $field->getLabel(); + } + } + + $field_options = array_merge( + ['token' => t('Use Token/Static Content')], + ['title' => t('Title')], + $field_options + ); + + if (\Drupal::moduleHandler()->moduleExists('token')) { + $element['addtocalendar_settings']['token_help'] = [ + '#type' => 'markup', + '#token_types' => array('node'), + '#theme' => 'token_tree_link', + ]; + } + + foreach ($info as $id => $data) { + $element['addtocalendar_settings'][$id]['field'] = [ + '#type' => 'select', + '#title' => $data['label'] . t(': field'), + '#options' => $field_options, + '#description' => t('Select field to be used as @label for calendar events', array('@label' => $data['label'])), + '#default_value' => !empty($settings['addtocalendar_settings'][$id]['field']) ? $settings['addtocalendar_settings'][$id]['field'] : '', + ]; + $element['addtocalendar_settings'][$id]['tokenized'] = [ + '#type' => 'textfield', + '#title' => $data['label'] . t(': Static/Tokenized Content'), + '#default_value' => !empty($settings['addtocalendar_settings'][$id]['tokenized']) ? $settings['addtocalendar_settings'][$id]['tokenized'] : $data['sample_data'], + ]; + } + + $element['addtocalendar_settings']['atc_privacy'] = [ + '#type' => 'select', + '#title' => t('Privacy'), + '#options' => [ + 'public' => t('Public'), + 'private' => t('Private'), + ], + '#description' => t('Use public for free access to event information from any places. User private if the event is closed to public access.'), + '#default_value' => !empty($settings['addtocalendar_settings']['atc_privacy']) ? $settings['addtocalendar_settings']['atc_privacy'] : '', + ]; + $element['addtocalendar_settings']['data_secure'] = [ + '#type' => 'select', + '#title' => t('Security level'), + '#options' => [ + 'auto' => t('Auto'), + 'true' => t('Use https only'), + 'false' => t('Use http only'), + ], + '#default_value' => !empty($settings['addtocalendar_settings']['data_secure']) ? $settings['addtocalendar_settings']['data_secure'] : '', + ]; + $element['addtocalendar_settings']['data_calendars'] = [ + '#type' => 'checkboxes', + '#options' => [ + 'iCalendar' => t('iCalendar'), + 'Google Calendar' => t('Google Calendar'), + 'Outlook' => t('Outlook'), + 'Outlook Online' => t('Outlook Online'), + 'Yahoo! Calendar' => t('Yahoo! Calendar'), + ], + '#default_value' => !empty($settings['addtocalendar_settings']['data_calendars']) ? $settings['addtocalendar_settings']['data_calendars'] : '', + '#title' => t('List of calendars to show in button list.'), + ]; + + $cardinality = $field_definition->getFieldStorageDefinition()->getCardinality(); + + if ($cardinality != 1) { + $element['addtocalendar_settings']['multiple_value'] = [ + '#type' => 'select', + '#title' => t('AddToCalendar button visibility'), + '#options' => [ + 1 => t('Single'), + 2 => t('All'), + ], + '#default_value' => !empty($settings['addtocalendar_settings']['multiple_value']) ? $settings['addtocalendar_settings']['multiple_value'] : 1, + ]; + $element['addtocalendar_settings']['delta'] = [ + '#type' => 'textfield', + '#title' => t('Delta'), + '#description' => 'AddToCalendar button visibility for a particular date field (default starts with 0).', + '#states' => [ + 'visible' => [ + ':input[name="fields[' . $field_definition->get('field_name') . '][settings_edit_form][third_party_settings][addtocalendar][addtocalendar_settings][multiple_value]"]' => [ + 'value' => 1, + ], + ], + ], + '#default_value' => !empty($settings['addtocalendar_settings']['delta']) ? $settings['addtocalendar_settings']['delta'] : 0, + ]; + } + return $element; +} diff --git a/modules/colorbox/LICENSE.txt b/modules/colorbox/LICENSE.txt new file mode 100644 index 00000000..d159169d --- /dev/null +++ b/modules/colorbox/LICENSE.txt @@ -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. + + + Copyright (C) + + 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. + + , 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. diff --git a/modules/colorbox/README.txt b/modules/colorbox/README.txt new file mode 100644 index 00000000..1aa465e8 --- /dev/null +++ b/modules/colorbox/README.txt @@ -0,0 +1,117 @@ +CONTENTS OF THIS FILE +--------------------- + + * Introduction + * Features + * Requirements + * Installation + * Configuration + * Maintainers + + +INTRODUCTION +------------ + +Colorbox is a light-weight, customizable lightbox plugin for jQuery 1.4.3+. +This module allows for integration of Colorbox into Drupal. +The jQuery library is a part of Drupal since version 5+. + +* jQuery - http://jquery.com/ +* Colorbox - http://www.jacklmoore.com/colorbox/ + + +FEATURES: +--------- + +The Colorbox module: + +* Works as a Formatter in entities and in views. +* Excellent integration with core image field and image styles and the Insert + module +* Choose between a default style and a number of other styles that are included. +* Style the Colorbox with a custom Colorbox style in your theme. +* Drush command, drush colorbox-plugin, to download and install the Colorbox + plugin in "libraries/". + +The Colorbox plugin: + +* Compatible with: jQuery 1.3.2+ in Firefox, Safari, Chrome, Opera, Internet + Explorer 7+ +* Supports photos, grouping, slideshow, ajax, inline, and iframed content. +* Lightweight: 10KB of JavaScript (less than 5KBs gzipped). +* Appearance is controlled through CSS so it can be restyled. +* Can be extended with callbacks & event-hooks without altering the source + files. +* Completely unobtrusive, options are set in the JS and require no changes to + existing HTML. +* Preloads upcoming images in a photo group. +* Currently used on more than 2 million websites. +* Released under the MIT License. + + +REQUIREMENTS +------------ + +Just Colorbox plugin in "libraries". + + +INSTALLATION +------------ + +1. Install the module as normal, see link for instructions. + Link: https://www.drupal.org/documentation/install/modules-themes/modules-8 + +2. Download and unpack the Colorbox plugin in "libraries". + Make sure the path to the plugin file becomes: + "libraries/colorbox/jquery.colorbox-min.js" + Link: https://github.com/jackmoore/colorbox/archive/master.zip + Drush users can use the command "drush colorbox-plugin". + +3. Go to "Administer" -> "Extend" and enable the Colorbox module. + + +CONFIGURATION +------------- + + * Go to "Configuration" -> "Media" -> "Colorbox" to find all the configuration + options. + +Add a custom Colorbox style to your theme: +---------------------------------------- +The easiest way is to start with either the default style or one of the example +styles included in the Colorbox JS library download. Simply copy the entire +style folder to your theme and rename it to something logical like "mycolorbox". +Inside that folder are both a .css and .js file, rename both of those as well to +match your folder name: i.e. "colorbox_mycolorbox.css" and +"colorbox_mycolorbox.js" + +Add entries in your theme's .info file for the Colorbox CSS/JS files: + +stylesheets[all][] = mycolorbox/colorbox_mycolorbox.css +scripts[] = mycolorbox/colorbox_mycolorbox.js + +Go to "Configuration" -> "Media" -> "Colorbox" and select "None" under +"Styles and Options". This will leave the styling of Colorbox up to your theme. +Make any CSS adjustments to your "colorbox_mycolorbox.css" file. + + +Drush: +------ +A Drush command is provides for easy installation of the Colorbox plugin itself. + +% drush colorbox-plugin + +The command will download the plugin and unpack it in "libraries/". +It is possible to add another path as an option to the command, but not +recommended unless you know what you are doing. + + +MAINTAINERS +----------- + +Current maintainers: + + * Fredrik Jonsson (frjo) - https://www.drupal.org/user/5546 + +Requires - Drupal 8 +License - GPL (see LICENSE) diff --git a/modules/colorbox/colorbox.api.php b/modules/colorbox/colorbox.api.php new file mode 100644 index 00000000..44efba27 --- /dev/null +++ b/modules/colorbox/colorbox.api.php @@ -0,0 +1,29 @@ +getLibraryByName('colorbox', 'colorbox'); + $library_exists = file_exists(DRUPAL_ROOT . '/' . $library['js'][0]['data']); + + return [ + 'colorbox_library_downloaded' => [ + 'title' => t('Colorbox library'), + 'value' => $library_exists ? t('Installed') : t('Not installed'), + 'description' => $library_exists ? '' : t('The Colorbox library needs to be downloaded and extracted into the /libraries/colorbox folder in your Drupal installation directory.', ['@url' => 'https://github.com/jackmoore/colorbox/archive/master.zip']), + 'severity' => $library_exists ? REQUIREMENT_OK : REQUIREMENT_ERROR, + ], + ]; +} diff --git a/modules/colorbox/colorbox.libraries.yml b/modules/colorbox/colorbox.libraries.yml new file mode 100644 index 00000000..2a9eb55e --- /dev/null +++ b/modules/colorbox/colorbox.libraries.yml @@ -0,0 +1,101 @@ +colorbox: + remote: http://github.com/jackmoore/colorbox + version: VERSION + license: + name: MIT + gpl-compatible: false + js: + /libraries/colorbox/jquery.colorbox-min.js: { minified: true } + dependencies: + - core/jquery + - core/jquery.once + +colorbox-dev: + remote: http://github.com/jackmoore/colorbox + version: VERSION + license: + name: MIT + gpl-compatible: false + js: + /libraries/colorbox/jquery.colorbox.js: { } + dependencies: + - core/jquery + - core/jquery.once + +init: + version: VERSION + js: + js/colorbox.js: {} + dependencies: + - core/jquery + - core/drupal + +plain: + version: VERSION + js: + styles/plain/colorbox_style.js: {} + css: + theme: + styles/plain/colorbox_style.css: {} + dependencies: + - colorbox/init + +stockholmsyndrome: + version: VERSION + js: + styles/stockholmsyndrome/colorbox_style.js: {} + css: + theme: + styles/stockholmsyndrome/colorbox_style.css: {} + dependencies: + - colorbox/init + +default: + version: VERSION + js: + styles/default/colorbox_style.js: {} + css: + theme: + styles/default/colorbox_style.css: {} + dependencies: + - colorbox/init + +example1: + version: VERSION + css: + theme: + /libraries/colorbox/example1/colorbox.css: {} + dependencies: + - colorbox/init + +example2: + version: VERSION + css: + theme: + /libraries/colorbox/example2/colorbox.css: {} + dependencies: + - colorbox/init + +example3: + version: VERSION + css: + theme: + /libraries/colorbox/example3/colorbox.css: {} + dependencies: + - colorbox/init + +example4: + version: VERSION + css: + theme: + /libraries/colorbox/example4/colorbox.css: {} + dependencies: + - colorbox/init + +example4: + version: VERSION + css: + theme: + /libraries/colorbox/example5/colorbox.css: {} + dependencies: + - colorbox/init diff --git a/modules/colorbox/colorbox.links.menu.yml b/modules/colorbox/colorbox.links.menu.yml new file mode 100644 index 00000000..e03938c8 --- /dev/null +++ b/modules/colorbox/colorbox.links.menu.yml @@ -0,0 +1,5 @@ +colorbox.admin_settings: + title: 'Colorbox settings' + description: 'Configure the Colorbox settings.' + parent: system.admin_config_media + route_name: colorbox.admin_settings diff --git a/modules/colorbox/colorbox.module b/modules/colorbox/colorbox.module new file mode 100644 index 00000000..4b3b1074 --- /dev/null +++ b/modules/colorbox/colorbox.module @@ -0,0 +1,47 @@ +' . t('About') . ''; + $output .= '

' . t('Colorbox is a light-weight, customizable lightbox plugin for jQuery 1.4.3+. This module allows for integration of Colorbox into Drupal.
The jQuery library is a part of Drupal since version 5+.') . '

'; + $output .= '

' . t('Configuration') . '

'; + $output .= '

' . t('Go to "Configuration" -> "Media" -> "Colorbox" to find all the configuration options.') . '

'; + $output .= '

' . t('Add a custom Colorbox style to your theme') . '

'; + $output .= '

' . t('The easiest way is to start with either the default style or one of the example styles included in the Colorbox JS library download. Simply copy the entire style folder to your theme and rename it to something logical like "mycolorbox". Inside that folder are both a .css and .js file, rename both of those as well to match +your folder name: i.e. "colorbox_mycolorbox.css" and "colorbox_mycolorbox.js"') . '

'; + $output .= '

' . t("Add entries in your theme's .info file for the Colorbox CSS/JS files:") . '

'; + $output .= '

' . t('stylesheets[all][] = mycolorbox/colorbox_mycolorbox.css
scripts[] = mycolorbox/colorbox_mycolorbox.js') . '

'; + $output .= '

' . t('Go to "Configuration" -> "Media" -> "Colorbox" and select "None" under "Styles and Options". This will leave the styling of Colorbox up to your theme.
Make any CSS adjustments to your "colorbox_mycolorbox.css" file.') . '

'; + return $output; + } +} + + +/** + * Implements hook_theme(). + */ +function colorbox_theme() { + return array( + 'colorbox_formatter' => array( + 'variables' => array( + 'item' => NULL, + 'item_attributes' => NULL, + 'entity' => NULL, + 'settings' => NULL, + ), + 'file' => 'colorbox.theme.inc', + ), + ); +} diff --git a/modules/colorbox/colorbox.post_update.php b/modules/colorbox/colorbox.post_update.php new file mode 100644 index 00000000..a4815432 --- /dev/null +++ b/modules/colorbox/colorbox.post_update.php @@ -0,0 +1,22 @@ +save(); + } +} diff --git a/modules/colorbox/colorbox.routing.yml b/modules/colorbox/colorbox.routing.yml new file mode 100644 index 00000000..4932b48c --- /dev/null +++ b/modules/colorbox/colorbox.routing.yml @@ -0,0 +1,7 @@ +colorbox.admin_settings: + path: '/admin/config/media/colorbox' + defaults: + _form: '\Drupal\colorbox\Form\ColorboxSettingsForm' + _title: 'Colorbox settings' + requirements: + _permission: 'administer site configuration' diff --git a/modules/colorbox/colorbox.services.yml b/modules/colorbox/colorbox.services.yml new file mode 100644 index 00000000..1fce9d0c --- /dev/null +++ b/modules/colorbox/colorbox.services.yml @@ -0,0 +1,7 @@ +services: + colorbox.activation_check: + class: Drupal\colorbox\ActivationCheck + arguments: ['@config.factory', '@request_stack'] + colorbox.attachment: + class: Drupal\colorbox\ColorboxAttachment + arguments: ['@colorbox.activation_check', '@module_handler', '@config.factory'] diff --git a/modules/colorbox/colorbox.theme.inc b/modules/colorbox/colorbox.theme.inc new file mode 100644 index 00000000..629d66ff --- /dev/null +++ b/modules/colorbox/colorbox.theme.inc @@ -0,0 +1,199 @@ +entity->getFileUri(); + $classes_array = ['colorbox']; + $data_cbox_img_attrs = []; + + // Build the caption. + $entity_title = $entity->label(); + $entity_type = $entity->getEntityTypeId(); + $entity_bundle = $entity->bundle(); + + switch ($settings['colorbox_caption']) { + case 'auto': + // If the title is empty use alt or the entity title in that order. + if (!empty($item->title)) { + $caption = $item->title; + } + elseif (!empty($item->alt)) { + $caption = $item->alt; + } + elseif (!empty($entity_title)) { + $caption = $entity_title; + } + else { + $caption = ''; + } + break; + + case 'title': + $caption = $item->title; + break; + + case 'alt': + $caption = $item->alt; + break; + + case 'entity_title': + $caption = $entity_title; + break; + + case 'custom': + $token_service = \Drupal::token(); + $caption = $token_service->replace($settings['colorbox_caption_custom'], [$entity_type => $entity, 'file' => $item], ['clear' => TRUE]); + break; + + default: + $caption = ''; + } + + // Shorten the caption for the example styles or when caption + // shortening is active. + $config = \Drupal::config('colorbox.settings'); + $colorbox_style = $config->get('colorbox_style'); + $trim_length = $config->get('colorbox_caption_trim_length'); + if (((strpos($colorbox_style, 'colorbox/example') !== FALSE) || $config->get('colorbox_caption_trim')) && (Unicode::strlen($caption) > $trim_length)) { + $caption = Unicode::substr($caption, 0, $trim_length - 5) . '...'; + } + + // Build the gallery id. + $id = $entity->id(); + $entity_id = !empty($id) ? $entity_bundle . '-' . $id : 'entity-id'; + $field_name = $item->getParent()->getName(); + + switch ($settings['colorbox_gallery']) { + case 'post': + $gallery_id = 'gallery-' . $entity_id; + break; + + case 'page': + $gallery_id = 'gallery-all'; + break; + + case 'field_post': + $gallery_id = 'gallery-' . $entity_id . '-' . $field_name; + break; + + case 'field_page': + $gallery_id = 'gallery-' . $field_name; + break; + + case 'custom': + $token_service = \Drupal::token(); + $gallery_id = $token_service->replace($settings['colorbox_gallery_custom'], [$entity_type => $entity, 'file' => $item], ['clear' => TRUE]); + break; + + default: + $gallery_id = ''; + } + + // If gallery id is not empty add unique per-request token to avoid + // images being added manually to galleries. + if (!empty($gallery_id) && $config->get('advanced.unique_token')) { + // Check if gallery token has already been set, we need to reuse + // the token for the whole request. + if (is_null($gallery_token)) { + // We use a short token since randomness is not critical. + $gallery_token = Crypt::randomBytesBase64(8); + } + $gallery_id = $gallery_id . '-' . $gallery_token; + } + + // Set up the $variables['image'] parameter. + if ($settings['style_name'] == 'hide') { + $variables['image'] = []; + $classes_array[] = 'js-hide'; + } + elseif (!empty($settings['style_name'])) { + $variables['image'] = [ + '#theme' => 'image_style', + '#style_name' => $settings['style_name'], + ]; + } + else { + $variables['image'] = [ + '#theme' => 'image', + ]; + } + + if (!empty($variables['image'])) { + $variables['image']['#attributes'] = $item_attributes; + + // Do not output an empty 'title' attribute. + if (Unicode::strlen($item->title) != 0) { + $variables['image']['#title'] = $item->title; + $data_cbox_img_attrs['title'] = '"title":"' . $item->title . '"'; + } + + foreach (['width', 'height', 'alt'] as $key) { + $variables['image']["#$key"] = $item->$key; + if ($key == 'alt') { + $data_cbox_img_attrs['alt'] = '"alt":"' . $item->alt . '"'; + } + } + + $variables['image']['#uri'] = empty($item->uri) ? $image_uri : $item->uri; + } + + if (!empty($settings['colorbox_image_style'])) { + $style = ImageStyle::load($settings['colorbox_image_style']); + $variables['url'] = $style->buildUrl($image_uri); + } + else { + $variables['url'] = file_create_url($image_uri); + } + + // If File Entity module is enabled, load attribute values from file entity. + if (\Drupal::moduleHandler()->moduleExists('file_entity')) { + // File id of the save file. + $fid = $item->target_id; + // Load file object. + $file_obj = File::load($fid); + $file_array = $file_obj->toArray(); + // Populate the image title. + if (!empty($file_array['field_image_title_text'][0]['value']) && empty($item->title) && $settings['colorbox_caption'] == 'title') { + $caption = $file_array['field_image_title_text'][0]['value']; + } + // Populate the image alt text. + if (!empty($file_array['field_image_alt_text'][0]['value']) && empty($item->alt) && $settings['colorbox_caption'] == 'alt') { + $caption = $file_array['field_image_alt_text'][0]['value']; + } + } + + $variables['attributes']['title'] = $caption; + $variables['attributes']['data-colorbox-gallery'] = $gallery_id; + $variables['attributes']['class'] = $classes_array; + if (!empty($data_cbox_img_attrs)) { + $variables['attributes']['data-cbox-img-attrs'] = '{' . implode(',', $data_cbox_img_attrs) . '}'; + } +} diff --git a/modules/colorbox/composer.json b/modules/colorbox/composer.json new file mode 100644 index 00000000..467a7d76 --- /dev/null +++ b/modules/colorbox/composer.json @@ -0,0 +1,12 @@ +{ + "name": "drupal/colorbox", + "description": "A light-weight, customizable lightbox plugin for jQuery.", + "type": "drupal-module", + "homepage": "https://www.drupal.org/project/colorbox", + "support": { + "issues": "https://www.drupal.org/project/colorbox", + "source": "https://cgit.drupalcode.org/colorbox" + }, + "license": "GPL-2.0+", + "minimum-stability": "dev" +} diff --git a/modules/colorbox/config/install/colorbox.settings.yml b/modules/colorbox/config/install/colorbox.settings.yml new file mode 100644 index 00000000..c25fff31 --- /dev/null +++ b/modules/colorbox/config/install/colorbox.settings.yml @@ -0,0 +1,31 @@ +custom: + style: 'default' + activate: 0 + transition_type: 'elastic' + transition_speed: 350 + opacity: 0.85 + text_current: '{current} of {total}' + text_previous: '« Prev' + text_next: 'Next »' + text_close: 'Close' + maxwidth: '98%' + maxheight: '98%' + initialwidth: '300' + initialheight: '250' + overlayclose: TRUE + returnfocus: TRUE + fixed: TRUE + scrolling: TRUE + slideshow: + slideshow: 0 + auto: TRUE + speed: 2500 + text_start: 'start slideshow' + text_stop: 'stop slideshow' +advanced: + unique_token: 1 + mobile_detect: 1 + mobile_device_width: '480px' + caption_trim: 0 + caption_trim_length: 75 + compression_type: 'minified' diff --git a/modules/colorbox/config/schema/colorbox.schema.yml b/modules/colorbox/config/schema/colorbox.schema.yml new file mode 100644 index 00000000..ab9a7b1a --- /dev/null +++ b/modules/colorbox/config/schema/colorbox.schema.yml @@ -0,0 +1,126 @@ +field.formatter.settings.colorbox: + type: mapping + label: 'Entity reference field formatter settings.' + mapping: + colorbox_node_style: + type: string + label: 'Node Style' + colorbox_node_style_first: + type: string + label: 'Node style first' + colorbox_image_style: + type: string + label: 'Image style' + colorbox_gallery: + type: string + label: 'Gallery' + colorbox_gallery_custom: + type: string + label: 'Gallery custom' + colorbox_caption: + type: string + label: 'Caption' + colorbox_caption_custom: + type: string + label: 'Caption custom' + +colorbox.settings: + type: config_object + label: 'Colorbox settings' + mapping: + custom: + type: mapping + label: Custom Settings + mapping: + style: + type: string + label: 'Style' + activate: + type: integer + label: 'Options' + transition_type: + type: string + label: 'Transition type' + transition_speed: + type: integer + label: 'Transition speed' + opacity: + type: float + label: 'Opacity' + text_current: + type: text + label: 'Current' + text_previous: + type: text + label: 'Previous' + text_next: + type: text + label: 'Next' + text_close: + type: text + label: 'Close' + maxwidth: + type: text + label: 'Max width' + maxheight: + type: text + label: 'Max height' + initialwidth: + type: text + label: 'Initial width' + initialheight: + type: text + label: 'Initial height' + overlayclose: + type: boolean + label: 'Overlay close' + returnfocus: + type: boolean + label: 'Return focus' + fixed: + type: boolean + label: 'Fixed' + scrolling: + type: boolean + label: 'Scrollbars' + slideshow: + type: mapping + label: 'Slideshow' + mapping: + slideshow: + type: integer + label: 'Slideshow' + auto: + type: boolean + label: 'Slideshow autostart' + speed: + type: integer + label: 'Slideshow speed' + text_start: + type: text + label: 'Start slideshow' + text_stop: + type: text + label: 'Stop slideshow' + advanced: + type: mapping + label: 'Advanced settings' + mapping: + unique_token: + type: integer + label: 'Unique per-request gallery token' + mobile_detect: + type: integer + label: 'Mobile detection' + mobile_device_width: + type: 'string' + label: 'Device width' + caption_trim: + type: integer + label: 'Caption shortening' + caption_trim_length: + type: integer + label: 'Caption max length' + compression_type: + type: string + label: 'Colorbox compression level' diff --git a/modules/colorbox/drush/colorbox.drush.inc b/modules/colorbox/drush/colorbox.drush.inc new file mode 100644 index 00000000..e802b9c9 --- /dev/null +++ b/modules/colorbox/drush/colorbox.drush.inc @@ -0,0 +1,101 @@ + 'drush_colorbox_plugin', + 'description' => dt('Download and install the Colorbox plugin.'), + // No bootstrap. + 'bootstrap' => DRUSH_BOOTSTRAP_DRUSH, + 'arguments' => array( + 'path' => dt('Optional. A path where to install the Colorbox plugin. If omitted Drush will use the default location.'), + ), + 'aliases' => array('colorboxplugin'), + ); + + return $items; +} + +/** + * Implements hook_drush_help(). + * + * This function is called whenever a drush user calls + * 'drush help ' + */ +function colorbox_drush_help($section) { + switch ($section) { + case 'drush:colorbox-plugin': + return dt('Download and install the Colorbox plugin from jacklmoore.com/colorbox, default location is the libraries directory.'); + } +} + +/** + * Command to download the Colorbox plugin. + */ +function drush_colorbox_plugin() { + $args = func_get_args(); + if (!empty($args[0])) { + $path = $args[0]; + } + else { + $path = 'libraries'; + } + + // Create the path if it does not exist. + if (!is_dir($path)) { + drush_op('mkdir', $path); + drush_log(dt('Directory @path was created', array('@path' => $path)), 'notice'); + } + + // Set the directory to the download location. + $olddir = getcwd(); + chdir($path); + + // Download the zip archive. + if ($filepath = drush_download_file(COLORBOX_DOWNLOAD_URI)) { + $filename = basename($filepath); + $dirname = COLORBOX_DOWNLOAD_PREFIX . basename($filepath, '.zip'); + + // Remove any existing Colorbox plugin directory. + if (is_dir($dirname) || is_dir('colorbox')) { + drush_delete_dir($dirname, TRUE); + drush_delete_dir('colorbox', TRUE); + drush_log(dt('A existing Colorbox plugin was deleted from @path', array('@path' => $path)), 'notice'); + } + + // Decompress the zip archive. + drush_tarball_extract($filename); + + // Change the directory name to "colorbox" if needed. + if ($dirname != 'colorbox') { + drush_move_dir($dirname, 'colorbox', TRUE); + $dirname = 'colorbox'; + } + } + + if (is_dir($dirname)) { + drush_log(dt('Colorbox plugin has been installed in @path', array('@path' => $path)), 'success'); + } + else { + drush_log(dt('Drush was unable to install the Colorbox plugin to @path', array('@path' => $path)), 'error'); + } + + // Set working directory back to the previous working directory. + chdir($olddir); +} diff --git a/modules/colorbox/images/controls.png b/modules/colorbox/images/controls.png new file mode 100644 index 00000000..22389727 Binary files /dev/null and b/modules/colorbox/images/controls.png differ diff --git a/modules/colorbox/images/loading_animation.gif b/modules/colorbox/images/loading_animation.gif new file mode 100644 index 00000000..f864d5fd Binary files /dev/null and b/modules/colorbox/images/loading_animation.gif differ diff --git a/modules/colorbox/images/loading_background.png b/modules/colorbox/images/loading_background.png new file mode 100644 index 00000000..9de11f46 Binary files /dev/null and b/modules/colorbox/images/loading_background.png differ diff --git a/modules/colorbox/js/colorbox.js b/modules/colorbox/js/colorbox.js new file mode 100644 index 00000000..a8c4c873 --- /dev/null +++ b/modules/colorbox/js/colorbox.js @@ -0,0 +1,29 @@ +(function ($, Drupal) { + + 'use strict'; + + Drupal.behaviors.initColorbox = { + attach: function (context, settings) { + if (!$.isFunction($.colorbox) || typeof settings.colorbox === 'undefined') { + return; + } + + if (settings.colorbox.mobiledetect && window.matchMedia) { + // Disable Colorbox for small screens. + var mq = window.matchMedia('(max-device-width: ' + settings.colorbox.mobiledevicewidth + ')'); + if (mq.matches) { + return; + } + } + + settings.colorbox.rel = function () { + return $(this).data('colorbox-gallery') + }; + + $('.colorbox', context) + .once('init-colorbox') + .colorbox(settings.colorbox); + } + }; + +})(jQuery, Drupal); diff --git a/modules/colorbox/src/ActivationCheck.php b/modules/colorbox/src/ActivationCheck.php new file mode 100644 index 00000000..15ae847a --- /dev/null +++ b/modules/colorbox/src/ActivationCheck.php @@ -0,0 +1,42 @@ +settings = $config->get('colorbox.settings'); + $this->request = $request->getCurrentRequest(); + } + + /** + * {@inheritdoc} + */ + public function isActive() { + return $this->request->get('colorbox') !== 'no'; + } + +} diff --git a/modules/colorbox/src/ActivationCheckInterface.php b/modules/colorbox/src/ActivationCheckInterface.php new file mode 100644 index 00000000..9a9e773d --- /dev/null +++ b/modules/colorbox/src/ActivationCheckInterface.php @@ -0,0 +1,18 @@ +activation = $activation; + $this->moduleHandler = $module_handler; + $this->settings = $config->get('colorbox.settings'); + } + + /** + * {@inheritdoc} + */ + public function isApplicable() { + return !drupal_installation_attempted() && $this->activation->isActive(); + } + + /** + * {@inheritdoc} + */ + public function attach(array &$page) { + if ($this->settings->get('custom.activate')) { + $js_settings = array( + 'transition' => $this->settings->get('custom.transition_type'), + 'speed' => $this->settings->get('custom.transition_speed'), + 'opacity' => $this->settings->get('custom.opacity'), + 'slideshow' => $this->settings->get('custom.slideshow.slideshow') ? TRUE : FALSE, + 'slideshowAuto' => $this->settings->get('custom.slideshow.auto') ? TRUE : FALSE, + 'slideshowSpeed' => $this->settings->get('custom.slideshow.speed'), + 'slideshowStart' => $this->settings->get('custom.slideshow.text_start'), + 'slideshowStop' => $this->settings->get('custom.slideshow.text_stop'), + 'current' => $this->settings->get('custom.text_current'), + 'previous' => $this->settings->get('custom.text_previous'), + 'next' => $this->settings->get('custom.text_next'), + 'close' => $this->settings->get('custom.text_close'), + 'overlayClose' => $this->settings->get('custom.overlayclose') ? TRUE : FALSE, + 'returnFocus' => $this->settings->get('custom.returnfocus') ? TRUE : FALSE, + 'maxWidth' => $this->settings->get('custom.maxwidth'), + 'maxHeight' => $this->settings->get('custom.maxheight'), + 'initialWidth' => $this->settings->get('custom.initialwidth'), + 'initialHeight' => $this->settings->get('custom.initialheight'), + 'fixed' => $this->settings->get('custom.fixed') ? TRUE : FALSE, + 'scrolling' => $this->settings->get('custom.scrolling') ? TRUE : FALSE, + 'mobiledetect' => $this->settings->get('advanced.mobile_detect') ? TRUE : FALSE, + 'mobiledevicewidth' => $this->settings->get('advanced.mobile_device_width'), + ); + } + else { + $js_settings = array( + 'opacity' => '0.85', + 'current' => $this->t('{current} of {total}'), + 'previous' => $this->t('« Prev'), + 'next' => $this->t('Next »'), + 'close' => $this->t('Close'), + 'maxWidth' => '98%', + 'maxHeight' => '98%', + 'fixed' => TRUE, + 'mobiledetect' => $this->settings->get('advanced.mobile_detect') ? TRUE : FALSE, + 'mobiledevicewidth' => $this->settings->get('advanced.mobile_device_width'), + ); + } + + $style = $this->settings->get('custom.style'); + + // Give other modules the possibility to override Colorbox + // settings and style. + $this->moduleHandler->alter('colorbox_settings', $js_settings, $style); + + // Add colorbox js settings. + $page['#attached']['drupalSettings']['colorbox'] = $js_settings; + + // Add and initialise the Colorbox plugin. + if ($this->settings->get('advanced.compression_type') == 'minified') { + $page['#attached']['library'][] = 'colorbox/colorbox'; + } + else { + $page['#attached']['library'][] = 'colorbox/colorbox-dev'; + } + + // Add JS and CSS based on selected style. + if ($style != 'none') { + $page['#attached']['library'][] = "colorbox/$style"; + } + } + +} diff --git a/modules/colorbox/src/ElementAttachmentInterface.php b/modules/colorbox/src/ElementAttachmentInterface.php new file mode 100644 index 00000000..56cfabb9 --- /dev/null +++ b/modules/colorbox/src/ElementAttachmentInterface.php @@ -0,0 +1,26 @@ +configFactory->get('colorbox.settings'); + + $form['colorbox_custom_settings'] = [ + '#type' => 'details', + '#title' => $this->t('Styles and options'), + '#open' => TRUE, + ]; + $colorbox_styles = [ + 'default' => $this->t('Default'), + 'plain' => $this->t('Plain (mainly for images)'), + 'stockholmsyndrome' => $this->t('Stockholm Syndrome'), + 'example1' => $this->t('Example 1'), + 'example2' => $this->t('Example 2'), + 'example3' => $this->t('Example 3'), + 'example4' => $this->t('Example 4'), + 'example5' => $this->t('Example 5'), + 'none' => $this->t('None'), + ]; + $form['colorbox_custom_settings']['colorbox_style'] = [ + '#type' => 'select', + '#title' => $this->t('Style'), + '#options' => $colorbox_styles, + '#default_value' => $config->get('custom.style'), + '#description' => $this->t('Select the style to use for the Colorbox. The example styles are the ones that come with the Colorbox plugin. Select "None" if you have added Colorbox styles to your theme.'), + ]; + $form['colorbox_custom_settings']['colorbox_custom_settings_activate'] = [ + '#type' => 'radios', + '#title' => $this->t('Options'), + '#options' => [0 => $this->t('Default'), 1 => $this->t('Custom')], + '#default_value' => $config->get('custom.activate'), + '#description' => $this->t('Use the default or custom options for Colorbox.'), + ]; + $form['colorbox_custom_settings']['colorbox_transition_type'] = [ + '#type' => 'radios', + '#title' => $this->t('Transition type'), + '#options' => [ + 'elastic' => $this->t('Elastic'), + 'fade' => $this->t('Fade'), + 'none' => $this->t('None'), + ], + '#default_value' => $config->get('custom.transition_type'), + '#description' => $this->t('The transition type.'), + '#states' => $this->getState(static::STATE_CUSTOM_SETTINGS), + ]; + $form['colorbox_custom_settings']['colorbox_transition_speed'] = [ + '#type' => 'select', + '#title' => $this->t('Transition speed'), + '#options' => $this->optionsRange(100, 600, 50), + '#default_value' => $config->get('custom.transition_speed'), + '#description' => $this->t('Sets the speed of the fade and elastic transitions, in milliseconds.'), + '#states' => $this->getState(static::STATE_CUSTOM_SETTINGS), + ]; + $form['colorbox_custom_settings']['colorbox_opacity'] = [ + '#type' => 'select', + '#title' => $this->t('Opacity'), + '#options' => $this->optionsRange(0, 1, 0.05), + '#default_value' => $config->get('custom.opacity'), + '#description' => $this->t('The overlay opacity level. Range: 0 to 1.'), + '#states' => $this->getState(static::STATE_CUSTOM_SETTINGS), + ]; + $form['colorbox_custom_settings']['colorbox_text_current'] = [ + '#type' => 'textfield', + '#title' => $this->t('Current'), + '#default_value' => $config->get('custom.text_current'), + '#size' => 30, + '#description' => $this->t('Text format for the content group / gallery count. {current} and {total} are detected and replaced with actual numbers while Colorbox runs.'), + '#states' => $this->getState(static::STATE_CUSTOM_SETTINGS), + ]; + $form['colorbox_custom_settings']['colorbox_text_previous'] = [ + '#type' => 'textfield', + '#title' => $this->t('Previous'), + '#default_value' => $config->get('custom.text_previous'), + '#size' => 30, + '#description' => $this->t('Text for the previous button in a shared relation group.'), + '#states' => $this->getState(static::STATE_CUSTOM_SETTINGS), + ]; + $form['colorbox_custom_settings']['colorbox_text_next'] = [ + '#type' => 'textfield', + '#title' => $this->t('Next'), + '#default_value' => $config->get('custom.text_next'), + '#size' => 30, + '#description' => $this->t('Text for the next button in a shared relation group.'), + '#states' => $this->getState(static::STATE_CUSTOM_SETTINGS), + ]; + $form['colorbox_custom_settings']['colorbox_text_close'] = [ + '#type' => 'textfield', + '#title' => $this->t('Close'), + '#default_value' => $config->get('custom.text_close'), + '#size' => 30, + '#description' => $this->t('Text for the close button. The "Esc" key will also close Colorbox.'), + '#states' => $this->getState(static::STATE_CUSTOM_SETTINGS), + ]; + $form['colorbox_custom_settings']['colorbox_maxwidth'] = [ + '#type' => 'textfield', + '#title' => $this->t('Max width'), + '#default_value' => $config->get('custom.maxwidth'), + '#size' => 30, + '#description' => $this->t('Set a maximum width for loaded content. Example: "100%", 500, "500px".'), + '#states' => $this->getState(static::STATE_CUSTOM_SETTINGS), + ]; + $form['colorbox_custom_settings']['colorbox_maxheight'] = [ + '#type' => 'textfield', + '#title' => $this->t('Max height'), + '#default_value' => $config->get('custom.maxheight'), + '#size' => 30, + '#description' => $this->t('Set a maximum height for loaded content. Example: "100%", 500, "500px".'), + '#states' => $this->getState(static::STATE_CUSTOM_SETTINGS), + ]; + $form['colorbox_custom_settings']['colorbox_initialwidth'] = [ + '#type' => 'textfield', + '#title' => $this->t('Initial width'), + '#default_value' => $config->get('custom.initialwidth'), + '#size' => 30, + '#description' => $this->t('Set the initial width, prior to any content being loaded. Example: "100%", 500, "500px".'), + '#states' => $this->getState(static::STATE_CUSTOM_SETTINGS), + ]; + $form['colorbox_custom_settings']['colorbox_initialheight'] = [ + '#type' => 'textfield', + '#title' => $this->t('Initial height'), + '#default_value' => $config->get('custom.initialheight'), + '#size' => 30, + '#description' => $this->t('Set the initial height, prior to any content being loaded. Example: "100%", 500, "500px".'), + '#states' => $this->getState(static::STATE_CUSTOM_SETTINGS), + ]; + $form['colorbox_custom_settings']['colorbox_overlayclose'] = [ + '#type' => 'checkbox', + '#title' => $this->t('Overlay close'), + '#default_value' => $config->get('custom.overlayclose'), + '#description' => $this->t('Enable closing Colorbox by clicking on the background overlay.'), + '#states' => $this->getState(static::STATE_CUSTOM_SETTINGS), + ]; + $form['colorbox_custom_settings']['colorbox_returnfocus'] = [ + '#type' => 'checkbox', + '#title' => $this->t('Return focus'), + '#default_value' => $config->get('custom.returnfocus'), + '#description' => $this->t('Return focus when Colorbox exits to the element it was launched from.'), + '#states' => $this->getState(static::STATE_CUSTOM_SETTINGS), + ]; + $form['colorbox_custom_settings']['colorbox_fixed'] = [ + '#type' => 'checkbox', + '#title' => $this->t('Fixed'), + '#default_value' => $config->get('custom.fixed'), + '#description' => $this->t("If the Colorbox should be displayed in a fixed position within the visitor's viewport or relative to the document."), + '#states' => $this->getState(static::STATE_CUSTOM_SETTINGS), + ]; + $form['colorbox_custom_settings']['colorbox_scrolling'] = [ + '#type' => 'checkbox', + '#title' => $this->t('Scrollbars'), + '#default_value' => $config->get('custom.scrolling'), + '#description' => $this->t('If unchecked, Colorbox will hide scrollbars for overflowing content. This could be used on conjunction with the resize method for a smoother transition if you are appending content to an already open instance of Colorbox.'), + '#states' => $this->getState(static::STATE_CUSTOM_SETTINGS), + ]; + + $form['colorbox_custom_settings']['colorbox_slideshow_settings'] = [ + '#type' => 'details', + '#title' => $this->t('Slideshow settings'), + '#collapsible' => TRUE, + '#collapsed' => TRUE, + '#states' => $this->getState(static::STATE_CUSTOM_SETTINGS), + ]; + $form['colorbox_custom_settings']['colorbox_slideshow_settings']['colorbox_slideshow'] = [ + '#type' => 'radios', + '#title' => $this->t('Slideshow'), + '#options' => [0 => $this->t('Off'), 1 => $this->t('On')], + '#default_value' => $config->get('custom.slideshow.slideshow'), + '#description' => $this->t('An automatic slideshow to a content group / gallery.'), + ]; + $form['colorbox_custom_settings']['colorbox_slideshow_settings']['colorbox_slideshowauto'] = [ + '#type' => 'checkbox', + '#title' => $this->t('Slideshow autostart'), + '#default_value' => $config->get('custom.slideshow.auto'), + '#description' => $this->t('If the slideshow should automatically start to play.'), + '#states' => $this->getState(static::STATE_SLIDESHOW_ENABLED), + ]; + $form['colorbox_custom_settings']['colorbox_slideshow_settings']['colorbox_slideshowspeed'] = [ + '#type' => 'select', + '#title' => $this->t('Slideshow speed'), + '#options' => $this->optionsRange(1000, 6000, 500), + '#default_value' => $config->get('custom.slideshow.speed'), + '#description' => $this->t('Sets the speed of the slideshow, in milliseconds.'), + '#states' => $this->getState(static::STATE_SLIDESHOW_ENABLED), + ]; + $form['colorbox_custom_settings']['colorbox_slideshow_settings']['colorbox_text_start'] = [ + '#type' => 'textfield', + '#title' => $this->t('Start slideshow'), + '#default_value' => $config->get('custom.slideshow.text_start'), + '#size' => 30, + '#description' => $this->t('Text for the slideshow start button.'), + '#states' => $this->getState(static::STATE_SLIDESHOW_ENABLED), + ]; + $form['colorbox_custom_settings']['colorbox_slideshow_settings']['colorbox_text_stop'] = [ + '#type' => 'textfield', + '#title' => $this->t('Stop slideshow'), + '#default_value' => $config->get('custom.slideshow.text_stop'), + '#size' => 30, + '#description' => $this->t('Text for the slideshow stop button.'), + '#states' => $this->getState(static::STATE_SLIDESHOW_ENABLED), + ]; + + $form['colorbox_advanced_settings'] = [ + '#type' => 'details', + '#title' => $this->t('Advanced settings'), + ]; + $form['colorbox_advanced_settings']['colorbox_unique_token'] = [ + '#type' => 'radios', + '#title' => $this->t('Unique per-request gallery token'), + '#options' => [1 => $this->t('On'), 0 => $this->t('Off')], + '#default_value' => $config->get('advanced.unique_token'), + '#description' => $this->t('If On (default), Colorbox will add a unique per-request token to the gallery id to avoid images being added manually to galleries. The token was added as a security fix but some see the old behavoiur as an feature and this settings makes it possible to remove the token.'), + ]; + $form['colorbox_advanced_settings']['colorbox_mobile_detect'] = [ + '#type' => 'radios', + '#title' => $this->t('Mobile detection'), + '#options' => [1 => $this->t('On'), 0 => $this->t('Off')], + '#default_value' => $config->get('advanced.mobile_detect'), + '#description' => $this->t('If on (default) Colorbox will not be active for devices with the max width set below.'), + ]; + $form['colorbox_advanced_settings']['colorbox_mobile_device_width'] = [ + '#type' => 'textfield', + '#title' => $this->t('Device width'), + '#default_value' => $config->get('advanced.mobile_device_width'), + '#size' => 30, + '#description' => $this->t('Set the mobile device max width. Default: 480px.'), + '#states' => [ + 'visible' => [ + ':input[name="colorbox_mobile_detect"]' => ['value' => '1'], + ], + ], + ]; + $form['colorbox_advanced_settings']['colorbox_caption_trim'] = [ + '#type' => 'radios', + '#title' => $this->t('Caption shortening'), + '#options' => [0 => $this->t('Default'), 1 => $this->t('Yes')], + '#default_value' => $config->get('advanced.caption_trim'), + '#description' => $this->t('If the caption should be made shorter in the Colorbox to avoid layout problems. The default is to shorten for the example styles, they need it, but not for other styles.'), + ]; + $form['colorbox_advanced_settings']['colorbox_caption_trim_length'] = [ + '#type' => 'select', + '#title' => $this->t('Caption max length'), + '#options' => $this->optionsRange(40, 120, 5), + '#default_value' => $config->get('advanced.caption_trim_length'), + '#states' => [ + 'visible' => [ + ':input[name="colorbox_caption_trim"]' => ['value' => '1'], + ], + ], + ]; + $form['colorbox_advanced_settings']['colorbox_compression_type'] = [ + '#type' => 'radios', + '#title' => $this->t('Choose Colorbox compression level'), + '#options' => [ + 'minified' => $this->t('Production (Minified)'), + 'source' => $this->t('Development (Uncompressed Code)'), + ], + '#default_value' => $config->get('advanced.compression_type'), + ]; + + return parent::buildForm($form, $form_state); + } + + /** + * {@inheritdoc} + */ + public function submitForm(array &$form, FormStateInterface $form_state) { + + $config = $this->configFactory->getEditable('colorbox.settings'); + + $config + ->set('custom.style', $form_state->getValue('colorbox_style')) + ->set('custom.activate', $form_state->getValue('colorbox_custom_settings_activate')) + ->set('custom.transition_type', $form_state->getValue('colorbox_transition_type')) + ->set('custom.transition_speed', $form_state->getValue('colorbox_transition_speed')) + ->set('custom.opacity', $form_state->getValue('colorbox_opacity')) + ->set('custom.text_current', $form_state->getValue('colorbox_text_current')) + ->set('custom.text_previous', $form_state->getValue('colorbox_text_previous')) + ->set('custom.text_next', $form_state->getValue('colorbox_text_next')) + ->set('custom.text_close', $form_state->getValue('colorbox_text_close')) + ->set('custom.overlayclose', $form_state->getValue('colorbox_overlayclose')) + ->set('custom.returnfocus', $form_state->getValue('colorbox_returnfocus')) + ->set('custom.maxwidth', $form_state->getValue('colorbox_maxwidth')) + ->set('custom.maxheight', $form_state->getValue('colorbox_maxheight')) + ->set('custom.initialwidth', $form_state->getValue('colorbox_initialwidth')) + ->set('custom.initialheight', $form_state->getValue('colorbox_initialheight')) + ->set('custom.fixed', $form_state->getValue('colorbox_fixed')) + ->set('custom.scrolling', $form_state->getValue('colorbox_scrolling')) + ->set('custom.slideshow.slideshow', $form_state->getValue('colorbox_slideshow')) + ->set('custom.slideshow.auto', $form_state->getValue('colorbox_slideshowauto')) + ->set('custom.slideshow.speed', $form_state->getValue('colorbox_slideshowspeed')) + ->set('custom.slideshow.text_start', $form_state->getValue('colorbox_text_start')) + ->set('custom.slideshow.text_stop', $form_state->getValue('colorbox_text_stop')) + ->set('advanced.unique_token', $form_state->getValue('colorbox_unique_token')) + ->set('advanced.mobile_detect', $form_state->getValue('colorbox_mobile_detect')) + ->set('advanced.mobile_device_width', $form_state->getValue('colorbox_mobile_device_width')) + ->set('advanced.caption_trim', $form_state->getValue('colorbox_caption_trim')) + ->set('advanced.caption_trim_length', $form_state->getValue('colorbox_caption_trim_length')) + ->set('advanced.compression_type', $form_state->getValue('colorbox_compression_type')); + + if ($form_state->getValue('colorbox_image_style')) { + $config->set('insert.image_style', $form_state->getValue('colorbox_image_style')); + } + + if ($form_state->getValue('colorbox_insert_gallery')) { + $config->set('insert.insert_gallery', $form_state->getValue('colorbox_insert_gallery')); + } + + $config->save(); + + parent::submitForm($form, $form_state); + } + + /** + * Get one of the pre-defined states used in this form. + * + * @param string $state + * The state to get that matches one of the state class constants. + * + * @return array + * A corresponding form API state. + */ + protected function getState($state) { + $states = [ + static::STATE_CUSTOM_SETTINGS => [ + 'visible' => [ + ':input[name="colorbox_custom_settings_activate"]' => ['value' => '1'], + ], + ], + static::STATE_SLIDESHOW_ENABLED => [ + 'visible' => [ + ':input[name="colorbox_slideshow"]' => ['value' => '1'], + ], + ], + ]; + return $states[$state]; + } + + /** + * Create a range for a series of options. + * + * @param int $start + * The start of the range. + * @param int $end + * The end of the range. + * @param int $step + * The interval between elements. + * + * @return array + * An options array for the given range. + */ + protected function optionsRange($start, $end, $step) { + $range = range($start, $end, $step); + return array_combine($range, $range); + } + +} diff --git a/modules/colorbox/src/Plugin/Field/FieldFormatter/ColorboxFormatter.php b/modules/colorbox/src/Plugin/Field/FieldFormatter/ColorboxFormatter.php new file mode 100644 index 00000000..f4d696cc --- /dev/null +++ b/modules/colorbox/src/Plugin/Field/FieldFormatter/ColorboxFormatter.php @@ -0,0 +1,435 @@ +currentUser = $current_user; + $this->imageStyleStorage = $image_style_storage; + $this->attachment = $attachment; + } + + /** + * {@inheritdoc} + */ + public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) { + return new static( + $plugin_id, + $plugin_definition, + $configuration['field_definition'], + $configuration['settings'], + $configuration['label'], + $configuration['view_mode'], + $configuration['third_party_settings'], + $container->get('current_user'), + $container->get('entity.manager')->getStorage('image_style'), + $container->get('colorbox.attachment') + ); + } + + /** + * {@inheritdoc} + */ + public static function defaultSettings() { + return [ + 'colorbox_node_style' => '', + 'colorbox_node_style_first' => '', + 'colorbox_image_style' => '', + 'colorbox_gallery' => 'post', + 'colorbox_gallery_custom' => '', + 'colorbox_caption' => 'auto', + 'colorbox_caption_custom' => '', + ] + parent::defaultSettings(); + } + + /** + * {@inheritdoc} + */ + public function settingsForm(array $form, FormStateInterface $form_state) { + $image_styles = image_style_options(FALSE); + $image_styles_hide = $image_styles; + $image_styles_hide['hide'] = $this->t('Hide (do not display image)'); + $description_link = Link::fromTextAndUrl( + $this->t('Configure Image Styles'), + Url::fromRoute('entity.image_style.collection') + ); + + $element['colorbox_node_style'] = [ + '#title' => $this->t('Image style for content'), + '#type' => 'select', + '#default_value' => $this->getSetting('colorbox_node_style'), + '#empty_option' => $this->t('None (original image)'), + '#options' => $image_styles_hide, + '#description' => $description_link->toRenderable() + [ + '#access' => $this->currentUser->hasPermission('administer image styles'), + ], + ]; + $element['colorbox_node_style_first'] = [ + '#title' => $this->t('Image style for first image in content'), + '#type' => 'select', + '#default_value' => $this->getSetting('colorbox_node_style_first'), + '#empty_option' => $this->t('No special style.'), + '#options' => $image_styles, + '#description' => $description_link->toRenderable() + [ + '#access' => $this->currentUser->hasPermission('administer image styles'), + ], + ]; + $element['colorbox_image_style'] = [ + '#title' => $this->t('Image style for Colorbox'), + '#type' => 'select', + '#default_value' => $this->getSetting('colorbox_image_style'), + '#empty_option' => $this->t('None (original image)'), + '#options' => $image_styles, + '#description' => $description_link->toRenderable() + [ + '#access' => $this->currentUser->hasPermission('administer image styles'), + ], + ]; + + $gallery = [ + 'post' => $this->t('Per post gallery'), + 'page' => $this->t('Per page gallery'), + 'field_post' => $this->t('Per field in post gallery'), + 'field_page' => $this->t('Per field in page gallery'), + 'custom' => $this->t('Custom (with tokens)'), + 'none' => $this->t('No gallery'), + ]; + $element['colorbox_gallery'] = [ + '#title' => $this->t('Gallery (image grouping)'), + '#type' => 'select', + '#default_value' => $this->getSetting('colorbox_gallery'), + '#options' => $gallery, + '#description' => $this->t('How Colorbox should group the image galleries.'), + ]; + $element['colorbox_gallery_custom'] = [ + '#title' => $this->t('Custom gallery'), + '#type' => 'textfield', + '#default_value' => $this->getSetting('colorbox_gallery_custom'), + '#description' => $this->t('All images on a page with the same gallery value (rel attribute) will be grouped together. It must only contain lowercase letters, numbers, and underscores.'), + '#required' => FALSE, + '#states' => [ + 'visible' => [ + ':input[name$="[settings_edit_form][settings][colorbox_gallery]"]' => ['value' => 'custom'], + ], + ], + ]; + if (\Drupal::moduleHandler()->moduleExists('token')) { + $element['colorbox_token_gallery'] = [ + '#type' => 'fieldset', + '#title' => t('Replacement patterns'), + '#theme' => 'token_tree_link', + '#token_types' => [$form['#entity_type'], 'file'], + '#states' => [ + 'visible' => [ + ':input[name$="[settings_edit_form][settings][colorbox_gallery]"]' => ['value' => 'custom'], + ], + ], + ]; + } + else { + $element['colorbox_token_gallery'] = [ + '#type' => 'fieldset', + '#title' => $this->t('Replacement patterns'), + '#description' => '' . $this->t('For token support the token module must be installed.', ['@token_url' => 'http://drupal.org/project/token']) . '', + '#states' => [ + 'visible' => [ + ':input[name$="[settings_edit_form][settings][colorbox_gallery]"]' => ['value' => 'custom'], + ], + ], + ]; + } + + $caption = [ + 'auto' => $this->t('Automatic'), + 'title' => $this->t('Title text'), + 'alt' => $this->t('Alt text'), + 'entity_title' => $this->t('Content title'), + 'custom' => $this->t('Custom (with tokens)'), + 'none' => $this->t('None'), + ]; + $element['colorbox_caption'] = [ + '#title' => $this->t('Caption'), + '#type' => 'select', + '#default_value' => $this->getSetting('colorbox_caption'), + '#options' => $caption, + '#description' => $this->t('Automatic will use the first non-empty value out of the title, the alt text and the content title.'), + ]; + $element['colorbox_caption_custom'] = [ + '#title' => $this->t('Custom caption'), + '#type' => 'textfield', + '#default_value' => $this->getSetting('colorbox_caption_custom'), + '#states' => [ + 'visible' => [ + ':input[name$="[settings_edit_form][settings][colorbox_caption]"]' => ['value' => 'custom'], + ], + ], + ]; + if (\Drupal::moduleHandler()->moduleExists('token')) { + $element['colorbox_token_caption'] = [ + '#type' => 'fieldset', + '#title' => t('Replacement patterns'), + '#theme' => 'token_tree_link', + '#token_types' => [$form['#entity_type'], 'file'], + '#states' => [ + 'visible' => [ + ':input[name$="[settings_edit_form][settings][colorbox_caption]"]' => ['value' => 'custom'], + ], + ], + ]; + } + else { + $element['colorbox_token_caption'] = [ + '#type' => 'fieldset', + '#title' => $this->t('Replacement patterns'), + '#description' => '' . $this->t('For token support the token module must be installed.', ['@token_url' => 'http://drupal.org/project/token']) . '', + '#states' => [ + 'visible' => [ + ':input[name$="[settings_edit_form][settings][colorbox_caption]"]' => ['value' => 'custom'], + ], + ], + ]; + } + + return $element; + } + + /** + * {@inheritdoc} + */ + public function settingsSummary() { + $summary = []; + + $image_styles = image_style_options(FALSE); + // Unset possible 'No defined styles' option. + unset($image_styles['']); + // Styles could be lost because of enabled/disabled modules that defines + // their styles in code. + if (isset($image_styles[$this->getSetting('colorbox_node_style')])) { + $summary[] = $this->t('Content image style: @style', ['@style' => $image_styles[$this->getSetting('colorbox_node_style')]]); + } + elseif ($this->getSetting('colorbox_node_style') == 'hide') { + $summary[] = $this->t('Content image style: Hide'); + } + else { + $summary[] = $this->t('Content image style: Original image'); + } + + if (isset($image_styles[$this->getSetting('colorbox_node_style_first')])) { + $summary[] = $this->t('Content image style of first image: @style', ['@style' => $image_styles[$this->getSetting('colorbox_node_style_first')]]); + } + + if (isset($image_styles[$this->getSetting('colorbox_image_style')])) { + $summary[] = $this->t('Colorbox image style: @style', ['@style' => $image_styles[$this->getSetting('colorbox_image_style')]]); + } + else { + $summary[] = $this->t('Colorbox image style: Original image'); + } + + $gallery = [ + 'post' => $this->t('Per post gallery'), + 'page' => $this->t('Per page gallery'), + 'field_post' => $this->t('Per field in post gallery'), + 'field_page' => $this->t('Per field in page gallery'), + 'custom' => $this->t('Custom (with tokens)'), + 'none' => $this->t('No gallery'), + ]; + if ($this->getSetting('colorbox_gallery')) { + $summary[] = $this->t('Colorbox gallery type: @type', ['@type' => $gallery[$this->getSetting('colorbox_gallery')]]) . ($this->getSetting('colorbox_gallery') == 'custom' ? ' (' . $this->getSetting('colorbox_gallery_custom') . ')' : ''); + } + + $caption = [ + 'auto' => $this->t('Automatic'), + 'title' => $this->t('Title text'), + 'alt' => $this->t('Alt text'), + 'entity_title' => $this->t('Content title'), + 'custom' => $this->t('Custom (with tokens)'), + 'none' => $this->t('None'), + ]; + + if ($this->getSetting('colorbox_caption')) { + $summary[] = $this->t('Colorbox caption: @type', ['@type' => $caption[$this->getSetting('colorbox_caption')]]); + } + + return $summary; + } + + /** + * {@inheritdoc} + */ + public function viewElements(FieldItemListInterface $items, $langcode) { + $elements = []; + $settings = $this->getSettings(); + $files = $this->getEntitiesToView($items, $langcode); + + // Early opt-out if the field is empty. + if (empty($files)) { + return $elements; + } + + // Collect cache tags to be added for each item in the field. + $cache_tags = []; + if (!empty($settings['colorbox_node_style']) && $settings['colorbox_node_style'] != 'hide') { + $image_style = $this->imageStyleStorage->load($settings['colorbox_node_style']); + $cache_tags = $image_style->getCacheTags(); + } + $cache_tags_first = []; + if (!empty($settings['colorbox_node_style_first'])) { + $image_style_first = $this->imageStyleStorage->load($settings['colorbox_node_style_first']); + $cache_tags_first = $image_style_first->getCacheTags(); + } + + foreach ($files as $delta => $file) { + // Check if first image should have separate image style. + if ($delta == 0 && !empty($settings['colorbox_node_style_first'])) { + $settings['style_first'] = TRUE; + $settings['style_name'] = $settings['colorbox_node_style_first']; + $cache_tags = Cache::mergeTags($cache_tags_first, $file->getCacheTags()); + } + else { + $settings['style_first'] = FALSE; + $settings['style_name'] = $settings['colorbox_node_style']; + $cache_tags = Cache::mergeTags($cache_tags, $file->getCacheTags()); + } + + // Extract field item attributes for the theme function, and unset them + // from the $item so that the field template does not re-render them. + $item = $file->_referringItem; + $item_attributes = $item->_attributes; + unset($item->_attributes); + + $elements[$delta] = [ + '#theme' => 'colorbox_formatter', + '#item' => $item, + '#item_attributes' => $item_attributes, + '#entity' => $items->getEntity(), + '#settings' => $settings, + '#cache' => [ + 'tags' => $cache_tags, + ], + ]; + } + + // Attach the Colorbox JS and CSS. + if ($this->attachment->isApplicable()) { + $this->attachment->attach($elements); + } + + return $elements; + } + + /** + * {@inheritdoc} + */ + public function calculateDependencies() { + $dependencies = parent::calculateDependencies(); + $style_ids = []; + $style_ids[] = $this->getSetting('colorbox_node_style'); + if (!empty($this->getSetting('colorbox_node_style_first'))) { + $style_ids[] = $this->getSetting('colorbox_node_style_first'); + } + $style_ids[] = $this->getSetting('colorbox_image_style'); + /** @var \Drupal\image\ImageStyleInterface $style */ + foreach ($style_ids as $style_id) { + if ($style_id && $style = ImageStyle::load($style_id)) { + // If this formatter uses a valid image style to display the image, add + // the image style configuration entity as dependency of this formatter. + $dependencies[$style->getConfigDependencyKey()][] = $style->getConfigDependencyName(); + } + } + return $dependencies; + } + + /** + * {@inheritdoc} + */ + public function onDependencyRemoval(array $dependencies) { + $changed = parent::onDependencyRemoval($dependencies); + $style_ids = []; + $style_ids['colorbox_node_style'] = $this->getSetting('colorbox_node_style'); + if (!empty($this->getSetting('colorbox_node_style_first'))) { + $style_ids['colorbox_node_style_first'] = $this->getSetting('colorbox_node_style_first'); + } + $style_ids['colorbox_image_style'] = $this->getSetting('colorbox_image_style'); + /** @var \Drupal\image\ImageStyleInterface $style */ + foreach ($style_ids as $name => $style_id) { + if ($style_id && $style = ImageStyle::load($style_id)) { + if (!empty($dependencies[$style->getConfigDependencyKey()][$style->getConfigDependencyName()])) { + $replacement_id = $this->imageStyleStorage->getReplacementId($style_id); + // If a valid replacement has been provided in the storage, + // replace the image style with the replacement and signal + // that the formatter plugin. + // Settings were updated. + if ($replacement_id && ImageStyle::load($replacement_id)) { + $this->setSetting($name, $replacement_id); + $changed = TRUE; + } + } + } + } + return $changed; + } + +} diff --git a/modules/colorbox/styles/default/colorbox_style.css b/modules/colorbox/styles/default/colorbox_style.css new file mode 100644 index 00000000..2517c7f3 --- /dev/null +++ b/modules/colorbox/styles/default/colorbox_style.css @@ -0,0 +1,216 @@ +/** + * Colorbox Core Style: + * The following CSS is consistent between example themes and should not be altered. + */ +#colorbox, #cboxOverlay, #cboxWrapper { + position: absolute; + top: 0; + left: 0; + z-index: 9999; + overflow: hidden; +} +#cboxOverlay { + position: fixed; + width: 100%; + height: 100%; +} +#cboxMiddleLeft, #cboxBottomLeft { + clear: left; +} +#cboxContent { + position: relative; +} +#cboxLoadedContent { + overflow: auto; + -webkit-overflow-scrolling: touch; +} +#cboxTitle { + margin: 0; +} +#cboxLoadingOverlay, #cboxLoadingGraphic { + position: absolute; + top: 0; + left: 0; + width: 100%; + height: 100%; +} +/** + * These elements are buttons, and may need to have additional + * styles reset to avoid unwanted base styles. + */ +#cboxPrevious, #cboxNext, #cboxClose, #cboxSlideshow { + border: 0; + padding: 0; + margin: 0; + overflow: visible; + width: auto; + background: none; + cursor: pointer; +} +/** + * Avoid outlines on :active (mouseclick), + * but preserve outlines on :focus (tabbed navigating) + */ +#cboxPrevious:active, #cboxNext:active, #cboxClose:active, #cboxSlideshow:active { + outline: 0; +} +.cboxPhoto { + float: left; + margin: auto; + border: 0; + display: block; + max-width: none; +} +.cboxIframe { + width: 100%; + height: 100%; + display: block; + border: 0; +} +/* Reset box sizing to content-box if theme is using border-box. */ +#colorbox, #cboxContent, #cboxLoadedContent { + -moz-box-sizing: content-box; + -webkit-box-sizing: content-box; + box-sizing: content-box; +} + +/** + * Colorbox module default style: + * The styles are ordered & tabbed in a way that represents + * the nesting of the generated HTML. + */ +#cboxOverlay { + background: #000; +} +#colorbox { + outline: 0; +} + #cboxWrapper { + background: #fff; + -moz-border-radius: 5px; + -webkit-border-radius: 5px; + border-radius: 5px; + } + #cboxTopLeft { + width: 15px; + height: 15px; + } + #cboxTopCenter { + height: 15px; + } + #cboxTopRight { + width: 15px; + height: 15px; + } + #cboxBottomLeft { + width: 15px; + height: 10px; + } + #cboxBottomCenter { + height: 10px; + } + #cboxBottomRight { + width: 15px; + height: 10px; + } + #cboxMiddleLeft { + width: 15px; + } + #cboxMiddleRight { + width: 15px; + } + #cboxContent { + background: #fff; + overflow: hidden; + } + #cboxError { + padding: 50px; + border: 1px solid #ccc; + } + #cboxLoadedContent { + margin-bottom: 28px; + } + #cboxTitle { + position: absolute; + background: rgba(255, 255, 255, 0.7); + bottom: 28px; + left: 0; + color: #535353; + width: 100%; + padding: 4px 6px; + -moz-box-sizing: border-box; + -webkit-box-sizing: border-box; + box-sizing: border-box; + } + #cboxCurrent { + position: absolute; + bottom: 4px; + left: 60px; + color: #949494; + } + .cboxSlideshow_on #cboxSlideshow { + position: absolute; + bottom: 0px; + right: 30px; + background: url(images/controls.png) no-repeat -75px -50px; + width: 25px; + height: 25px; + text-indent: -9999px; + } + .cboxSlideshow_on #cboxSlideshow:hover { + background-position: -101px -50px; + } + .cboxSlideshow_off #cboxSlideshow { + position: absolute; + bottom: 0px; + right: 30px; + background: url(images/controls.png) no-repeat -25px -50px; + width: 25px; + height: 25px; + text-indent: -9999px; + } + .cboxSlideshow_off #cboxSlideshow:hover { + background-position: -49px -50px; + } + #cboxPrevious { + position: absolute; + bottom: 0; + left: 0; + background: url(images/controls.png) no-repeat -75px 0px; + width: 25px; + height: 25px; + text-indent: -9999px; + } + #cboxPrevious:hover { + background-position: -75px -25px; + } + #cboxNext { + position: absolute; + bottom: 0; + left: 27px; + background: url(images/controls.png) no-repeat -50px 0px; + width: 25px; + height: 25px; + text-indent: -9999px; + } + #cboxNext:hover { + background-position: -50px -25px; + } + #cboxLoadingOverlay { + background: #fff; + } + #cboxLoadingGraphic { + background: url(images/loading_animation.gif) no-repeat center center; + } + #cboxClose { + position: absolute; + bottom: 0; + right: 0; + background: url(images/controls.png) no-repeat -25px 0px; + width: 25px; + height: 25px; + text-indent: -9999px; + } + #cboxClose:hover { + background-position: -25px -25px; + } diff --git a/modules/colorbox/styles/default/colorbox_style.js b/modules/colorbox/styles/default/colorbox_style.js new file mode 100644 index 00000000..47875ffd --- /dev/null +++ b/modules/colorbox/styles/default/colorbox_style.js @@ -0,0 +1,22 @@ +(function ($) { + +Drupal.behaviors.initColorboxDefaultStyle = { + attach: function (context, settings) { + $(context).bind('cbox_complete', function () { + // Only run if there is a title. + if ($('#cboxTitle:empty', context).length == false) { + $('#cboxLoadedContent img', context).bind('mouseover', function () { + $('#cboxTitle', context).slideDown(); + }); + $('#cboxOverlay', context).bind('mouseover', function () { + $('#cboxTitle', context).slideUp(); + }); + } + else { + $('#cboxTitle', context).hide(); + } + }); + } +}; + +})(jQuery); diff --git a/modules/colorbox/styles/default/images/controls.png b/modules/colorbox/styles/default/images/controls.png new file mode 100644 index 00000000..22389727 Binary files /dev/null and b/modules/colorbox/styles/default/images/controls.png differ diff --git a/modules/colorbox/styles/default/images/loading_animation.gif b/modules/colorbox/styles/default/images/loading_animation.gif new file mode 100644 index 00000000..f864d5fd Binary files /dev/null and b/modules/colorbox/styles/default/images/loading_animation.gif differ diff --git a/modules/colorbox/styles/default/images/loading_background.png b/modules/colorbox/styles/default/images/loading_background.png new file mode 100644 index 00000000..9de11f46 Binary files /dev/null and b/modules/colorbox/styles/default/images/loading_background.png differ diff --git a/modules/colorbox/styles/plain/colorbox_style.css b/modules/colorbox/styles/plain/colorbox_style.css new file mode 100644 index 00000000..0b500daf --- /dev/null +++ b/modules/colorbox/styles/plain/colorbox_style.css @@ -0,0 +1,144 @@ +/** + * Colorbox Core Style: + * The following CSS is consistent between example themes and should not be altered. + */ +#colorbox, #cboxOverlay, #cboxWrapper { + position: absolute; + top: 0; + left: 0; + z-index: 9999; + overflow: hidden; +} +#cboxOverlay { + position: fixed; + width: 100%; + height: 100%; +} +#cboxMiddleLeft, #cboxBottomLeft { + clear: left; +} +#cboxContent { + position: relative; +} +#cboxLoadedContent { + overflow: auto; + -webkit-overflow-scrolling: touch; +} +#cboxTitle { + margin: 0; +} +#cboxLoadingOverlay, #cboxLoadingGraphic { + position: absolute; + top: 0; + left: 0; + width: 100%; + height: 100%; +} +/** + * These elements are buttons, and may need to have additional + * styles reset to avoid unwanted base styles. + */ +#cboxPrevious, #cboxNext, #cboxClose, #cboxSlideshow { + border: 0; + padding: 0; + margin: 0; + overflow: visible; + width: auto; + background: none; + cursor: pointer; +} +/** + * Avoid outlines on :active (mouseclick), + * but preserve outlines on :focus (tabbed navigating) + */ +#cboxPrevious:active, #cboxNext:active, #cboxClose:active, #cboxSlideshow:active { + outline: 0; +} +.cboxPhoto { + float: left; + margin: auto; + border: 0; + display: block; + max-width: none; +} +.cboxIframe { + width: 100%; + height: 100%; + display: block; + border: 0; +} +/* Reset box sizing to content-box if theme is using border-box. */ +#colorbox, #cboxContent, #cboxLoadedContent { + -moz-box-sizing: content-box; + -webkit-box-sizing: content-box; + box-sizing: content-box; +} + +/** + * Colorbox module plain style: + * The styles are ordered & tabbed in a way that represents + * the nesting of the generated HTML. + */ +#cboxOverlay { + background: #000; +} +#colorbox { + outline: 0; +} + #cboxWrapper {} + #cboxContent { + overflow: hidden; + } + #cboxContent, .cboxPhoto { + -webkit-border-radius: 5px; + -moz-border-radius: 5px; + border-radius: 5px; + } + #cboxError { + padding: 50px; + border: 1px solid #ccc; + } + #cboxTitle { + position: absolute; + background: rgba(255, 255, 255, 0.7); + bottom: 0; + left: 0; + color: #535353; + width: 100%; + padding: 4px 6px; + -moz-box-sizing: border-box; + -webkit-box-sizing: border-box; + box-sizing: border-box; + -webkit-border-bottom-right-radius: 5px; + -webkit-border-bottom-left-radius: 5px; + -moz-border-radius-bottomright: 5px; + -moz-border-radius-bottomleft: 5px; + border-bottom-right-radius: 5px; + border-bottom-left-radius: 5px; + } + + #cboxLoadingOverlay { + background: #fff; + } + #cboxLoadingGraphic { + background: url(images/loading_animation.gif) no-repeat center center; + } + #cboxClose.cbox-close-plain { + position: absolute; + font-size: 20px; + line-height: 18px; + text-align: center; + color: rgba(255, 255, 255, 0.7); + background: rgba(0, 0, 0, 0.5); + top: 4px; + right: 4px; + width: 20px; + height: 20px; + -webkit-border-radius: 10px; + -moz-border-radius: 10px; + border-radius: 10px; + } + .cbox-close-plain:hover { + color: rgba(255, 255, 255, 0.9); + background: rgba(0, 0, 0, 0.8); + } diff --git a/modules/colorbox/styles/plain/colorbox_style.js b/modules/colorbox/styles/plain/colorbox_style.js new file mode 100644 index 00000000..83e54e1f --- /dev/null +++ b/modules/colorbox/styles/plain/colorbox_style.js @@ -0,0 +1,35 @@ +(function ($, Drupal) { + + "use strict"; + + Drupal.behaviors.initColorboxPlainStyle = { + attach: function (context, settings) { + $(context).bind('cbox_complete', function () { + // Make all the controls invisible. + $('#cboxCurrent, #cboxSlideshow, #cboxPrevious, #cboxNext', context).addClass('element-invisible'); + // Replace "Close" with "×" and show. + $('#cboxClose', context).html('\u00d7').addClass('cbox-close-plain'); + // Hide empty title. + if ($('#cboxTitle:empty', context).length == true) { + $('#cboxTitle', context).hide(); + } + $('#cboxLoadedContent', context).bind('mouseover', function () { + $('#cboxClose', context).animate({opacity: 1}, {queue: false, duration: "fast"}); + if ($('#cboxTitle:empty', context).length == false) { + $('#cboxTitle', context).slideDown(); + } + }); + $('#cboxOverlay', context).bind('mouseover', function () { + $('#cboxClose', context).animate({opacity: 0}, {queue: false, duration: "fast"}); + if ($('#cboxTitle:empty', context).length == false) { + $('#cboxTitle', context).slideUp(); + } + }); + }); + $(context).bind('cbox_closed', function () { + $('#cboxClose', context).removeClass('cbox-close-plain'); + }); + } + }; + +})(jQuery, Drupal); diff --git a/modules/colorbox/styles/plain/images/controls.png b/modules/colorbox/styles/plain/images/controls.png new file mode 100644 index 00000000..22389727 Binary files /dev/null and b/modules/colorbox/styles/plain/images/controls.png differ diff --git a/modules/colorbox/styles/plain/images/loading_animation.gif b/modules/colorbox/styles/plain/images/loading_animation.gif new file mode 100644 index 00000000..f864d5fd Binary files /dev/null and b/modules/colorbox/styles/plain/images/loading_animation.gif differ diff --git a/modules/colorbox/styles/plain/images/loading_background.png b/modules/colorbox/styles/plain/images/loading_background.png new file mode 100644 index 00000000..9de11f46 Binary files /dev/null and b/modules/colorbox/styles/plain/images/loading_background.png differ diff --git a/modules/colorbox/styles/stockholmsyndrome/colorbox_stockholmsyndrome_screen.png b/modules/colorbox/styles/stockholmsyndrome/colorbox_stockholmsyndrome_screen.png new file mode 100644 index 00000000..3ff1269b Binary files /dev/null and b/modules/colorbox/styles/stockholmsyndrome/colorbox_stockholmsyndrome_screen.png differ diff --git a/modules/colorbox/styles/stockholmsyndrome/colorbox_style.css b/modules/colorbox/styles/stockholmsyndrome/colorbox_style.css new file mode 100644 index 00000000..6cdfa33c --- /dev/null +++ b/modules/colorbox/styles/stockholmsyndrome/colorbox_style.css @@ -0,0 +1,219 @@ +/** + * Colorbox Core Style: + * The following CSS is consistent between example themes and should not be altered. + */ +#colorbox, #cboxOverlay, #cboxWrapper { + position: absolute; + top: 0; + left: 0; + z-index: 9999; + overflow: hidden; +} +#cboxOverlay { + position: fixed; + width: 100%; + height: 100%; +} +#cboxMiddleLeft, #cboxBottomLeft { + clear: left; +} +#cboxContent { + position: relative; +} +#cboxLoadedContent { + overflow: auto; + -webkit-overflow-scrolling: touch; +} +#cboxTitle { + margin: 0; +} +#cboxLoadingOverlay, #cboxLoadingGraphic { + position: absolute; + top: 0; + left: 0; + width: 100%; + height: 100%; +} +/** + * These elements are buttons, and may need to have additional + * styles reset to avoid unwanted base styles. + */ +#cboxPrevious, #cboxNext, #cboxClose, #cboxSlideshow { + border: 0; + padding: 0; + margin: 0; + overflow: visible; + width: auto; + background: none; + cursor: pointer; +} +/** + * Avoid outlines on :active (mouseclick), + * but preserve outlines on :focus (tabbed navigating) + */ +#cboxPrevious:active, #cboxNext:active, #cboxClose:active, #cboxSlideshow:active { + outline: 0; +} +.cboxPhoto { + float: left; + margin: auto; + border: 0; + display: block; + max-width: none; +} +.cboxIframe { + width: 100%; + height: 100%; + display: block; + border: 0; +} +/* Reset box sizing to content-box if theme is using border-box. */ +#colorbox, #cboxContent, #cboxLoadedContent { + -moz-box-sizing: content-box; + -webkit-box-sizing: content-box; + box-sizing: content-box; +} + +/** + * Colorbox module Stockholm syndrome style: + * The styles are ordered & tabbed in a way that represents + * the nesting of the generated HTML. + */ +#cboxOverlay { + background: #000; +} + +#colorbox { + background: #fff url(images/bg_tab.png) center bottom repeat-x; + -moz-box-shadow: 3px 3px 16px #333; + -webkit-box-shadow: 3px 3px 16px #333; + box-shadow: 3px 3px 16px #333; + -moz-border-radius-bottomleft: 9px; + -moz-border-radius-bottomright: 9px; + -webkit-border-bottom-left-radius: 9px; + -webkit-border-bottom-right-radius: 9px; + border-bottom-left-radius: 9px; + border-bottom-right-radius: 9px; + outline: 0; +} +#colorbox, #colorbox div { + overflow: visible; /* Required by the close button. */ +} + #cboxWrapper { + -moz-border-radius-bottomleft: 9px; + -moz-border-radius-bottomright: 9px; + -webkit-border-bottom-left-radius: 9px; + -webkit-border-bottom-right-radius: 9px; + border-bottom-left-radius: 9px; + border-bottom-right-radius: 9px; + } + #cboxTopLeft { + width: 0; + height: 0; + } + #cboxTopCenter { + height: 0; + } + #cboxTopRight { + width: 0; + height: 0; + } + #cboxBottomLeft { + width: 15px; + height: 10px; + } + #cboxBottomCenter { + height: 10px; + } + #cboxBottomRight { + width: 15px; + height: 10px; + } + #cboxMiddleLeft { + width: 0; + } + #cboxMiddleRight { + width: 0; + } + #cboxContent { + background: #fff; + overflow: hidden; + margin-bottom: 28px; + } + #cboxError { + padding: 50px; + border: 1px solid #ccc; + } + #cboxLoadedContent { + } + #cboxTitle { + left: 0; + height: 38px; + color: #313131; + padding: 0 140px 0 15px; + display: table-cell !important; + vertical-align: middle; + float: none !important; + } + #cboxCurrent { + position: absolute; + bottom: -26px; + right: 80px; + color: #313131; + border-left: 1px solid #313131; + padding: 0 0 0 15px; + } + /* Slideshow not implemented. */ + .cboxSlideshow_on #cboxSlideshow { + display: none; + } + .cboxSlideshow_on #cboxSlideshow:hover { + } + .cboxSlideshow_off #cboxSlideshow { + display: none; + } + .cboxSlideshow_off #cboxSlideshow:hover { + } + #cboxPrevious { + position: absolute; + bottom: -26px; + right: 45px; + background: url(images/controls.png) no-repeat 0 -48px; + width: 21px; + height: 15px; + text-indent: -9999px; + } + #cboxPrevious:hover { + background-position: 0 -111px; + } + #cboxNext { + position: absolute; + bottom: -26px; + right: 15px; + background: url(images/controls.png) no-repeat 0 -29px; + width: 21px; + height: 15px; + text-indent: -9999px; + } + #cboxNext:hover { + background-position: 0 -92px; + } + #cboxLoadingOverlay { + background: #e6e6e6; + } + #cboxLoadingGraphic { + background: url(images/loading_animation.gif) no-repeat center center; + } + #cboxClose { + position: absolute; + top: -10px; + right: -10px; + background: url(images/controls.png) no-repeat 0px 0px; + width: 25px; + height: 25px; + text-indent: -9999px; + opacity: 0; + } + #cboxClose:hover { + background-position: 0 -63px; + } diff --git a/modules/colorbox/styles/stockholmsyndrome/colorbox_style.js b/modules/colorbox/styles/stockholmsyndrome/colorbox_style.js new file mode 100644 index 00000000..db3ab3ef --- /dev/null +++ b/modules/colorbox/styles/stockholmsyndrome/colorbox_style.js @@ -0,0 +1,20 @@ +(function ($) { + +Drupal.behaviors.initColorboxStockholmsyndromeStyle = { + attach: function (context, settings) { + $(context).bind('cbox_open', function () { + // Hide close button initially. + $('#cboxClose', context).css('opacity', 0); + }); + $(context).bind('cbox_load', function () { + // Hide close button. (It doesn't handle the load animation well.) + $('#cboxClose', context).css('opacity', 0); + }); + $(context).bind('cbox_complete', function () { + // Show close button with a delay. + $('#cboxClose', context).fadeTo('fast', 0, function () {$(this).css('opacity', 1)}); + }); + } +}; + +})(jQuery); diff --git a/modules/colorbox/styles/stockholmsyndrome/images/bg_tab.png b/modules/colorbox/styles/stockholmsyndrome/images/bg_tab.png new file mode 100644 index 00000000..03064d92 Binary files /dev/null and b/modules/colorbox/styles/stockholmsyndrome/images/bg_tab.png differ diff --git a/modules/colorbox/styles/stockholmsyndrome/images/controls.png b/modules/colorbox/styles/stockholmsyndrome/images/controls.png new file mode 100644 index 00000000..6745faa2 Binary files /dev/null and b/modules/colorbox/styles/stockholmsyndrome/images/controls.png differ diff --git a/modules/colorbox/styles/stockholmsyndrome/images/loading_animation.gif b/modules/colorbox/styles/stockholmsyndrome/images/loading_animation.gif new file mode 100644 index 00000000..f864d5fd Binary files /dev/null and b/modules/colorbox/styles/stockholmsyndrome/images/loading_animation.gif differ diff --git a/modules/colorbox/templates/colorbox-formatter.html.twig b/modules/colorbox/templates/colorbox-formatter.html.twig new file mode 100644 index 00000000..b282c1b8 --- /dev/null +++ b/modules/colorbox/templates/colorbox-formatter.html.twig @@ -0,0 +1,16 @@ +{# +/** + * @file + * Default theme implementation to display a formatted colorbox image field. + * + * Available variables: + * - image: A collection of image data. + * - url: An URL the image can be linked to. + * - attributes: Link attributes. + * + * @see template_preprocess_colorbox_formatter() + * + * @ingroup themeable + */ +#} +{{ image }} diff --git a/modules/colorbox/tests/modules/colorbox_library_test/colorbox_library_test.info.yml b/modules/colorbox/tests/modules/colorbox_library_test/colorbox_library_test.info.yml new file mode 100644 index 00000000..a95d8272 --- /dev/null +++ b/modules/colorbox/tests/modules/colorbox_library_test/colorbox_library_test.info.yml @@ -0,0 +1,12 @@ +name: Colorbox Library Test +description: Ensure colorbox can be tested properly with the downloaded library. +type: module +hidden: true +package: Testing +# core: 8.x + +# Information added by Drupal.org packaging script on 2017-04-24 +version: '8.x-1.4' +core: '8.x' +project: 'colorbox' +datestamp: 1493051361 diff --git a/modules/colorbox/tests/modules/colorbox_library_test/colorbox_library_test.install b/modules/colorbox/tests/modules/colorbox_library_test/colorbox_library_test.install new file mode 100644 index 00000000..dc0bb9aa --- /dev/null +++ b/modules/colorbox/tests/modules/colorbox_library_test/colorbox_library_test.install @@ -0,0 +1,26 @@ +open($zip_file); + $zip->extractTo($library_folder); + rename($library_folder . '/colorbox-master', $colorbox_folder); +} diff --git a/modules/colorbox/tests/modules/colorbox_library_test/colorbox_library_test.module b/modules/colorbox/tests/modules/colorbox_library_test/colorbox_library_test.module new file mode 100644 index 00000000..f62de99d --- /dev/null +++ b/modules/colorbox/tests/modules/colorbox_library_test/colorbox_library_test.module @@ -0,0 +1,21 @@ + $library) { + $libraries['colorbox']['js']['/' . Settings::get('file_public_path') . $key] = $library; + unset($libraries['colorbox']['js'][$key]); + } +} diff --git a/modules/colorbox/tests/src/FunctionalJavascript/ColorboxJavascriptTest.php b/modules/colorbox/tests/src/FunctionalJavascript/ColorboxJavascriptTest.php new file mode 100644 index 00000000..a72deb3f --- /dev/null +++ b/modules/colorbox/tests/src/FunctionalJavascript/ColorboxJavascriptTest.php @@ -0,0 +1,191 @@ +drupalGet('node/' . $this->node->id()); + $this->getSession()->getPage()->find('css', 'img')->click(); + $this->getSession()->wait(static::COLORBOX_WAIT_TIMEOUT); + $this->assertSession()->elementContains('css', '#colorbox', 'test.png'); + } + + /** + * Test the gallery works. + */ + public function testColorboxGallery() { + $this->drupalGet('node/' . $this->node->id()); + + // Click and launch the gallery. + $this->getSession()->getPage()->find('css', 'img')->click(); + $this->getSession()->wait(static::COLORBOX_WAIT_TIMEOUT); + $this->assertSession()->elementContains('css', '#cboxTitle', 'Image title 1'); + $this->assertSession()->elementContains('css', '#colorbox', 'test.png'); + + // Click on the next image and assert the second image is visible. + $this->assertSession()->elementExists('css', '#cboxNext')->click(); + $this->getSession()->wait(static::COLORBOX_WAIT_TIMEOUT); + $this->assertSession()->elementContains('css', '#cboxTitle', 'Image title 2'); + $this->assertSession()->elementContains('css', '#colorbox', 'test.png'); + + // Use alt captions. + \Drupal::entityTypeManager() + ->getStorage('entity_view_display') + ->load('node.page.default') + ->setComponent('field_test_image', [ + 'type' => 'colorbox', + 'settings' => ['colorbox_caption' => 'alt'], + 'status' => TRUE, + ]) + ->save(); + drupal_flush_all_caches(); + + // Ensure the caption being used is the alt text. + $this->drupalGet('node/' . $this->node->id()); + $this->getSession()->getPage()->find('css', 'img')->click(); + $this->getSession()->wait(static::COLORBOX_WAIT_TIMEOUT); + $this->assertSession()->elementContains('css', '#cboxTitle', 'Image alt 1'); + } + + /** + * Test the mobile detection. + */ + public function testMobileDetection() { + $this->changeSetting('advanced.mobile_detect', TRUE); + $this->changeSetting('advanced.mobile_detect_width', '1200px'); + $this->getSession()->resizeWindow(200, 200); + $this->drupalGet('node/' . $this->node->id()); + $this->assertSession()->elementAttributeContains('css', '#colorbox', 'style', 'display: none;'); + } + + /** + * Test the admin form. + */ + public function testAdminForm() { + $this->drupalLogin($this->drupalCreateUser([ + 'administer site configuration', + ])); + $this->drupalGet('admin/config/media/colorbox'); + $this->assertFalse($this->getSession()->getPage()->find('css', '.form-item-colorbox-transition-speed')->isVisible()); + $this->assertSession()->fieldExists('colorbox_custom_settings_activate')->setValue(TRUE); + $this->assertTrue($this->getSession()->getPage()->find('css', '.form-item-colorbox-transition-speed')->isVisible()); + $this->assertSession()->fieldExists('colorbox_overlayclose')->setValue(FALSE); + $this->getSession()->getPage()->find('css', '.form-submit')->click(); + $this->assertSession()->pageTextContains('The configuration options have been saved.'); + } + + /** + * Change a colorbox setting. + * + * @param string $setting + * The name of the setting. + * @param string $value + * The value. + */ + protected function changeSetting($setting, $value) { + \Drupal::configFactory() + ->getEditable('colorbox.settings') + ->set($setting, $value) + ->save(); + } + + /** + * {@inheritdoc} + */ + protected function setUp() { + parent::setUp(); + $this->createContentType(['type' => 'page']); + FieldStorageConfig::create(array( + 'field_name' => 'field_test_image', + 'entity_type' => 'node', + 'type' => 'image', + 'settings' => [], + 'cardinality' => 3, + ))->save(); + $field_config = FieldConfig::create([ + 'field_name' => 'field_test_image', + 'label' => 'Colorbox Field', + 'entity_type' => 'node', + 'bundle' => 'page', + 'required' => TRUE, + 'settings' => [], + ]); + $field_config->save(); + \Drupal::entityTypeManager() + ->getStorage('entity_view_display') + ->load('node.page.default') + ->setComponent('field_test_image', [ + 'type' => 'colorbox', + 'settings' => [], + 'status' => TRUE, + ]) + ->save(); + file_unmanaged_copy(DRUPAL_ROOT . '/core/modules/simpletest/files/image-1.png', 'public://test.png'); + $file_a = File::create([ + 'uri' => 'public://test.png', + 'filename' => 'test.png', + ]); + $file_a->save(); + $file_b = File::create([ + 'uri' => 'public://test.png', + 'filename' => 'test.png', + ]); + $file_b->save(); + $this->node = $this->createNode([ + 'type' => 'page', + 'field_test_image' => [ + [ + 'target_id' => $file_a->id(), + 'alt' => 'Image alt 1', + 'title' => 'Image title 1', + ], + [ + 'target_id' => $file_b->id(), + 'alt' => 'Image alt 2', + 'title' => 'Image title 2', + ], + ], + ]); + } + +} diff --git a/modules/colorbox_inline/LICENSE.txt b/modules/colorbox_inline/LICENSE.txt new file mode 100644 index 00000000..d159169d --- /dev/null +++ b/modules/colorbox_inline/LICENSE.txt @@ -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. + + + Copyright (C) + + 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. + + , 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. diff --git a/modules/colorbox_inline/README.txt b/modules/colorbox_inline/README.txt new file mode 100644 index 00000000..30cd32dc --- /dev/null +++ b/modules/colorbox_inline/README.txt @@ -0,0 +1,57 @@ +CONTENTS OF THIS FILE +--------------------- + + * Introduction + * Requirements + * Installation + * Configuration + * Maintainers + + +INTRODUCTION +------------ + +Colorbox Inline allows you to open content already on the page within a +colorbox. If you would like to load content via AJAX, you can use colorbox_load. + + +REQUIREMENTS +------------ + +Requires the following modules: + + * Colorbox (https://drupal.org/project/colorbox) + +To create an element which opens the colorbox on click: + +Add a the attribute data-colorbox-inline to an element and make it's value a +selector for the content you wish to open. +Eg, User Login. +Optional extra configuration you can add: + + - `data-width` and `data-height` to the anchor to control the size of the + modal window. + - `data-class` to add a class to the colorbox wrapper. + + +INSTALLATION +------------ + +Install as you would normally install a contributed Drupal module. See: +https://drupal.org/documentation/install/modules-themes/modules-8 for further +information. + + +CONFIGURATION +------------- + +No special requirements + + +MAINTAINERS +----------- + +Current maintainers: + * Sam Becker (Sam152) - https://www.drupal.org/user/1485048 + * Renato Gonçalves (RenatoG) - https://www.drupal.org/user/3326031 + * Nick Wilde (NickWilde) - https://www.drupal.org/u/nickwilde diff --git a/modules/colorbox_inline/colorbox_inline.info.yml b/modules/colorbox_inline/colorbox_inline.info.yml new file mode 100644 index 00000000..34f72b6e --- /dev/null +++ b/modules/colorbox_inline/colorbox_inline.info.yml @@ -0,0 +1,14 @@ +name: Colorbox Inline +type: module +description: Enabled the "colorbox inline" functionality for Drupal 8. +package: Media +# core: 8.x + +dependencies: + - drupal:colorbox + +# Information added by Drupal.org packaging script on 2017-11-01 +version: '8.x-1.0' +core: '8.x' +project: 'colorbox_inline' +datestamp: 1509503290 diff --git a/modules/colorbox_inline/colorbox_inline.libraries.yml b/modules/colorbox_inline/colorbox_inline.libraries.yml new file mode 100644 index 00000000..2957b118 --- /dev/null +++ b/modules/colorbox_inline/colorbox_inline.libraries.yml @@ -0,0 +1,5 @@ +colorbox_inline: + js: + js/colorbox_inline.js: {} + dependencies: + - colorbox/colorbox diff --git a/modules/colorbox_inline/colorbox_inline.module b/modules/colorbox_inline/colorbox_inline.module new file mode 100644 index 00000000..ca9ebf02 --- /dev/null +++ b/modules/colorbox_inline/colorbox_inline.module @@ -0,0 +1,14 @@ +attach($page); + $page['#attached']['library'][] = 'colorbox_inline/colorbox_inline'; +} diff --git a/modules/colorbox_inline/js/colorbox_inline.js b/modules/colorbox_inline/js/colorbox_inline.js new file mode 100644 index 00000000..01965e3e --- /dev/null +++ b/modules/colorbox_inline/js/colorbox_inline.js @@ -0,0 +1,23 @@ +(function ($) { + "use strict"; + /** + * Enable the colorbox inline functionality. + */ + Drupal.behaviors.colorboxInline = { + attach: function (context, drupalSettings) { + $('[data-colorbox-inline]', context).once().click(function () { + var $link = $(this); + var settings = $.extend({}, drupalSettings.colorbox, { + href: false, + inline: true + }, { + className: $link.data('class'), + href: $link.data('colorbox-inline'), + width: $link.data('width'), + height: $link.data('height') + }); + $link.colorbox(settings); + }); + } + }; +})(jQuery); diff --git a/modules/colorbox_load/LICENSE.txt b/modules/colorbox_load/LICENSE.txt new file mode 100644 index 00000000..d159169d --- /dev/null +++ b/modules/colorbox_load/LICENSE.txt @@ -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. + + + Copyright (C) + + 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. + + , 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. diff --git a/modules/colorbox_load/colorbox_load.info.yml b/modules/colorbox_load/colorbox_load.info.yml new file mode 100644 index 00000000..98227b2d --- /dev/null +++ b/modules/colorbox_load/colorbox_load.info.yml @@ -0,0 +1,16 @@ +name: Colorbox Load +type: module +description: 'Allow you to load any content in a colorbox.' +package: Media +# core: 8.x +configure: ng_lightbox.settings + +dependencies: + - colorbox + - ng_lightbox + +# Information added by Drupal.org packaging script on 2016-07-07 +version: '8.x-1.0-rc2' +core: '8.x' +project: 'colorbox_load' +datestamp: 1467852845 diff --git a/modules/colorbox_load/colorbox_load.install b/modules/colorbox_load/colorbox_load.install new file mode 100644 index 00000000..5382c031 --- /dev/null +++ b/modules/colorbox_load/colorbox_load.install @@ -0,0 +1,24 @@ +getEditable('ng_lightbox.settings'); + $config->set('renderer', 'drupal_colorbox'); + $config->save(); +} + +/** + * Implements hook_uninstall(). + */ +function colorbox_load_uninstall() { + $config = \Drupal::configFactory()->getEditable('ng_lightbox.settings'); + $config->set('renderer', NULL); + $config->save(); +} diff --git a/modules/colorbox_load/colorbox_load.libraries.yml b/modules/colorbox_load/colorbox_load.libraries.yml new file mode 100644 index 00000000..039e2175 --- /dev/null +++ b/modules/colorbox_load/colorbox_load.libraries.yml @@ -0,0 +1,6 @@ +colorbox_load: + js: + js/colorbox_load.js: {} + dependencies: + - core/drupal.ajax + - colorbox/colorbox diff --git a/modules/colorbox_load/colorbox_load.module b/modules/colorbox_load/colorbox_load.module new file mode 100644 index 00000000..559b365c --- /dev/null +++ b/modules/colorbox_load/colorbox_load.module @@ -0,0 +1,14 @@ +attach($page); + $page['#attached']['library'][] = 'colorbox_load/colorbox_load'; +} diff --git a/modules/colorbox_load/colorbox_load.services.yml b/modules/colorbox_load/colorbox_load.services.yml new file mode 100644 index 00000000..2cfb234e --- /dev/null +++ b/modules/colorbox_load/colorbox_load.services.yml @@ -0,0 +1,5 @@ +services: + colorbox_load.renderer: + class: Drupal\colorbox_load\Renderer + tags: + - { name: render.main_content_renderer, format: drupal_colorbox, ng_lightbox: Colorbox } diff --git a/modules/colorbox_load/js/colorbox_load.js b/modules/colorbox_load/js/colorbox_load.js new file mode 100644 index 00000000..0fc2cf2f --- /dev/null +++ b/modules/colorbox_load/js/colorbox_load.js @@ -0,0 +1,11 @@ +(function ($) { + "use strict"; + Drupal.AjaxCommands.prototype.colorboxLoadOpen = function (ajax, response) { + $.colorbox($.extend(drupalSettings.colorbox, { + html: response.data, + width: '90%', + height: '90%' + })); + Drupal.attachBehaviors(response.data); + }; +})(jQuery); diff --git a/modules/colorbox_load/src/OpenCommand.php b/modules/colorbox_load/src/OpenCommand.php new file mode 100644 index 00000000..327c21fe --- /dev/null +++ b/modules/colorbox_load/src/OpenCommand.php @@ -0,0 +1,44 @@ +content = $content; + } + + /** + * {@inheritdoc{ + */ + public function render() { + return [ + 'command' => 'colorboxLoadOpen', + 'data' => $this->content, + ]; + } + +} diff --git a/modules/colorbox_load/src/Renderer.php b/modules/colorbox_load/src/Renderer.php new file mode 100644 index 00000000..080eb122 --- /dev/null +++ b/modules/colorbox_load/src/Renderer.php @@ -0,0 +1,31 @@ +setAttachments($main_content['#attached']); + $response->addCommand(new OpenCommand($content)); + return $response; + } + +} diff --git a/modules/field_group/LICENSE.txt b/modules/field_group/LICENSE.txt new file mode 100644 index 00000000..d159169d --- /dev/null +++ b/modules/field_group/LICENSE.txt @@ -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. + + + Copyright (C) + + 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. + + , 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. diff --git a/modules/field_group/README.txt b/modules/field_group/README.txt new file mode 100644 index 00000000..2eb008f5 --- /dev/null +++ b/modules/field_group/README.txt @@ -0,0 +1,50 @@ +History: + Field_group was originally written when drupal 7 was released. For drupal 6, the module is + located in the CCK module (http://drupal.org/project/cck). + As drupal core has a fields API drupal > 6, the field_group module + is considered a contribution. + +Description: + field_group is a module that will group a set of fields. In Drupal8, + with fields, one means all fields that come from fieldable entities. + You can add fieldgroups in several types with their own format settings. + field_group uses plugins to add your own formatter and rendering for + it. + One of the biggest improvements to previous versions, is that fieldgroups + have unlimited nesting, better display control. + Note that field_group will only group fields, it can not be used to hide + certain fields since this a permission matter. + +Module project page: + http://drupal.org/project/field_group + +Documentation page (D7 version): + http://drupal.org/node/1017838 + http://drupal.org/node/1017962 + +Available group types: + - Html element + - Fieldsets + - Tabs (horizontal and vertical) + - Accordions + - Details (Use this if you want collapsible fieldsets) + +To submit bug reports and feature suggestions, or to track changes: + http://drupal.org/project/issues/field_group + +-- Configuration -- +1. You can configure the field groups for different displays like, in managed_form_display and managed_display of the entity type. +2. You can create different field groups under managed_form_display by adding a new group under "Add new group" label and the format the grouping using the desired formatter for displaying the same. +3. Same thing can be done in managed_display. +4. The field grouping done in managed display will be reflected on the view detail page of the entity, while that done in the managed_form_display will be +reflected in the add/edit form of the entity. + +-- MAINTAINERS -- + +stalski - http://drupal.org/user/322618 +zuuperman - http://drupal.org/user/361625 +swentel - http://drupal.org/user/107403 + +-- INSPIRATORS -- + +yched - http://drupal.org/user/39567 \ No newline at end of file diff --git a/modules/field_group/composer.json b/modules/field_group/composer.json new file mode 100644 index 00000000..82d09318 --- /dev/null +++ b/modules/field_group/composer.json @@ -0,0 +1,8 @@ +{ + "name": "drupal/field_group", + "description": "Provides the field_group module.", + "type": "drupal-module", + "license": "GPL-2.0+", + "minimum-stability": "dev", + "require": {} +} diff --git a/modules/field_group/config/schema/field_group.entity_display.schema.yml b/modules/field_group/config/schema/field_group.entity_display.schema.yml new file mode 100644 index 00000000..c47e7847 --- /dev/null +++ b/modules/field_group/config/schema/field_group.entity_display.schema.yml @@ -0,0 +1,55 @@ +core.entity_view_display.*.*.*.third_party.field_group: + type: sequence + label: 'Field group settings on entity view' + sequence: + - type: mapping + label: A field group + mapping: + children: + type: sequence + label: 'The fields belonging to the group' + sequence: + - type: string + label: 'The field name' + label: + type: string + label: Readable name of the group + parent_name: + type: string + label: 'The parent group of this group' + weight: + type: integer + label: 'The weight of the group' + format_type: + type: string + label: 'The formatter of the group' + format_settings: + type: field_group.field_group_formatter_plugin.[%parent.format_type] + +core.entity_form_display.*.*.*.third_party.field_group: + type: sequence + label: 'Field group settings on entity form' + sequence: + - type: mapping + label: A field group + mapping: + children: + type: sequence + label: 'The fields belonging to the group' + sequence: + - type: string + label: 'The field name' + label: + type: string + label: Readable name of the group + parent_name: + type: string + label: 'The parent group of this group' + weight: + type: integer + label: 'The weight of the group' + format_type: + type: string + label: 'The formatter of the group' + format_settings: + type: field_group.field_group_formatter_plugin.[%parent.format_type] diff --git a/modules/field_group/config/schema/field_group.field_group_formatter_plugin.schema.yml b/modules/field_group/config/schema/field_group.field_group_formatter_plugin.schema.yml new file mode 100644 index 00000000..82b8f274 --- /dev/null +++ b/modules/field_group/config/schema/field_group.field_group_formatter_plugin.schema.yml @@ -0,0 +1,105 @@ +field_group.field_group_formatter_plugin.accordion: + type: field_group.field_group_formatter_plugin.base + label: 'Mapping for the accordion formatter settings' + mapping: + effect: + type: string + label: 'Effect on the accordion' + +field_group.field_group_formatter_plugin.accordion_item: + type: field_group.field_group_formatter_plugin.base + label: 'Mapping for the accordion item formatter settings' + mapping: + formatter: + type: string + label: 'Formatting of the item' + description: + type: string + label: 'description of the item' + required_fields: + type: boolean + label: 'Mark for required fields' + +field_group.field_group_formatter_plugin.details: + type: field_group.field_group_formatter_plugin.base + label: 'Mapping for the details formatter settings' + mapping: + open: + type: boolean + label: 'Display element open by default.' + required_fields: + type: boolean + label: 'Mark for required fields' + +field_group.field_group_formatter_plugin.fieldset: + type: field_group.field_group_formatter_plugin.base + label: 'Mapping for the fieldset formatter settings' + mapping: + description: + type: string + label: 'description of the item' + required_fields: + type: boolean + label: 'Mark for required fields' + +field_group.field_group_formatter_plugin.html_element: + type: field_group.field_group_formatter_plugin.base + label: 'Mapping for the html element formatter settings' + mapping: + element: + type: string + label: 'html element tag to be used' + show_label: + type: boolean + label: 'show the label' + label_element: + type: string + label: 'html element tag to be used for the label' + attributes: + type: string + label: 'html attributes for the element' + effect: + type: string + label: 'effect on the element' + speed: + type: string + label: 'speed of the effect' + required_fields: + type: boolean + label: 'Mark for required fields' + +field_group.field_group_formatter_plugin.tab: + type: field_group.field_group_formatter_plugin.base + label: 'Mapping for the tab formatter settings' + mapping: + formatter: + type: string + label: 'default state for the tab' + description: + type: string + label: 'description of the tab' + required_fields: + type: boolean + label: 'Mark for required fields' + +field_group.field_group_formatter_plugin.tabs: + type: field_group.field_group_formatter_plugin.base + label: 'Mapping for the tab formatter settings' + mapping: + direction: + type: string + label: 'Direction of the tabs' + +field_group.field_group_formatter_plugin.base: + type: mapping + label: 'Mapping for the base formatter settings' + mapping: + label: + type: string + label: 'Label of the fieldgroup' + classes: + type: string + label: 'Classes of the fieldgroup' + id: + type: string + label: 'Html id of the fieldgroup' \ No newline at end of file diff --git a/modules/field_group/contrib/field_group_migrate/field_group_migrate.info.yml b/modules/field_group/contrib/field_group_migrate/field_group_migrate.info.yml new file mode 100644 index 00000000..b9c0a03c --- /dev/null +++ b/modules/field_group/contrib/field_group_migrate/field_group_migrate.info.yml @@ -0,0 +1,14 @@ +name: 'Field Group Migrate' +type: module +description: 'Provides the ability to migrate field groups from D6/D7 to D8.' +package: Migrate +# version: VERSION +# core: 8.x +dependencies: + - field_group:field_group + +# Information added by Drupal.org packaging script on 2016-11-28 +version: '8.x-1.0-rc6' +core: '8.x' +project: 'field_group' +datestamp: 1480365490 diff --git a/modules/field_group/contrib/field_group_migrate/migration_templates/d6_field_group_entity_form_display.yml b/modules/field_group/contrib/field_group_migrate/migration_templates/d6_field_group_entity_form_display.yml new file mode 100644 index 00000000..01edd68b --- /dev/null +++ b/modules/field_group/contrib/field_group_migrate/migration_templates/d6_field_group_entity_form_display.yml @@ -0,0 +1,41 @@ +langcode: en +status: true +dependencies: + config: + - migrate.migration.d6_field_instance + module: + - field_group_migrate + - node +id: d6_field_group_entity_form_display +migration_tags: + - 'Drupal 6' +label: 'Field groups' +source: + plugin: d6_field_group + constants: + mode: entity_form_display + entity_type: node + form_mode: default + third_party_settings: { } +process: + mode: constants/mode + entity_type: constants/entity_type + bundle: type_name + form_mode: constants/form_mode + id: + plugin: concat + source: + - group_name + delimiter: . + field_group/label: label + field_group/weight: weight + field_group/children: children + field_group/format_type: converted_settings/format_type + field_group/format_settings: converted_settings/format_settings +destination: + plugin: field_group_entity_form_display +template: d6_field_instance_widget_settings +migration_dependencies: + required: + - d6_field_instance +migration_group: null diff --git a/modules/field_group/contrib/field_group_migrate/migration_templates/d6_field_group_entity_view_display.yml b/modules/field_group/contrib/field_group_migrate/migration_templates/d6_field_group_entity_view_display.yml new file mode 100644 index 00000000..92adcc16 --- /dev/null +++ b/modules/field_group/contrib/field_group_migrate/migration_templates/d6_field_group_entity_view_display.yml @@ -0,0 +1,39 @@ +langcode: en +status: true +dependencies: + config: + - migrate.migration.d6_field_instance + module: + - field_group_migrate + - node +id: d6_field_group_entity_view_display +migration_tags: + - 'Drupal 6' +label: 'Field groups' +source: + plugin: d6_field_group + constants: + mode: entity_view_display + entity_type: node + third_party_settings: { } +process: + mode: constants/mode + entity_type: constants/entity_type + bundle: type_name + id: + plugin: concat + source: + - group_name + delimiter: . + field_group/label: label + field_group/weight: weight + field_group/children: children + field_group/format_type: converted_settings/format_type + field_group/format_settings: converted_settings/format_settings +destination: + plugin: field_group_entity_view_display +template: d6_field_instance_widget_settings +migration_dependencies: + required: + - d6_field_instance +migration_group: null diff --git a/modules/field_group/contrib/field_group_migrate/migration_templates/d7_field_group.yml b/modules/field_group/contrib/field_group_migrate/migration_templates/d7_field_group.yml new file mode 100644 index 00000000..bf80db70 --- /dev/null +++ b/modules/field_group/contrib/field_group_migrate/migration_templates/d7_field_group.yml @@ -0,0 +1,28 @@ +id: d7_field_group +label: Field groups +migration_tags: + - Drupal 7 +source: + plugin: d7_field_group +process: + entity_type: entity_type + bundle: bundle + mode: + plugin: static_map + source: mode + bypass: true + map: + form: default + type: + plugin: static_map + source: mode + default_value: entity_view_display + map: + form: entity_form_display + group_name: group_name + settings: settings +destination: + plugin: d7_field_group +migration_dependencies: + required: + - d7_field_formatter_settings diff --git a/modules/field_group/contrib/field_group_migrate/src/Plugin/migrate/destination/FieldGroupEntityFormDisplay.php b/modules/field_group/contrib/field_group_migrate/src/Plugin/migrate/destination/FieldGroupEntityFormDisplay.php new file mode 100644 index 00000000..f0b4f3bf --- /dev/null +++ b/modules/field_group/contrib/field_group_migrate/src/Plugin/migrate/destination/FieldGroupEntityFormDisplay.php @@ -0,0 +1,39 @@ +getIds()) as $id) { + $values[$id] = $row->getDestinationProperty($id); + } + $entity = $this->getEntity($values['entity_type'], $values['bundle'], $values[static::MODE_NAME]); + if (!$entity->isNew()) { + $settings = $row->getDestinationProperty('field_group'); + $entity->setThirdPartySetting('field_group', $row->getDestinationProperty('id'), $settings); + if (isset($settings['format_type']) && ($settings['format_type'] == 'no_style' || $settings['format_type'] == 'hidden')) { + $entity->unsetThirdPartySetting('field_group', $row->getDestinationProperty('id')); + } + $entity->save(); + } + return array_values($values); + } + +} diff --git a/modules/field_group/contrib/field_group_migrate/src/Plugin/migrate/destination/FieldGroupEntityViewDisplay.php b/modules/field_group/contrib/field_group_migrate/src/Plugin/migrate/destination/FieldGroupEntityViewDisplay.php new file mode 100644 index 00000000..2ef0a5d8 --- /dev/null +++ b/modules/field_group/contrib/field_group_migrate/src/Plugin/migrate/destination/FieldGroupEntityViewDisplay.php @@ -0,0 +1,43 @@ +getIds()) as $id) { + $values[$id] = $row->getDestinationProperty($id); + } + + foreach ($row->getSourceProperty('view_modes') as $view_mode => $settings) { + $entity = $this->getEntity($values['entity_type'], $values['bundle'], $view_mode); + if (!$entity->isNew()) { + $settings = array_merge($row->getDestinationProperty('field_group'), $settings); + $entity->setThirdPartySetting('field_group', $row->getDestinationProperty('id'), $settings); + if (isset($settings['format_type']) && ($settings['format_type'] == 'no_style' || $settings['format_type'] == 'hidden')) { + $entity->unsetThirdPartySetting('field_group', $row->getDestinationProperty('id')); + } + $entity->save(); + } + } + + return array_values($values); + } + +} diff --git a/modules/field_group/contrib/field_group_migrate/src/Plugin/migrate/destination/d7/FieldGroup.php b/modules/field_group/contrib/field_group_migrate/src/Plugin/migrate/destination/d7/FieldGroup.php new file mode 100644 index 00000000..1110f188 --- /dev/null +++ b/modules/field_group/contrib/field_group_migrate/src/Plugin/migrate/destination/d7/FieldGroup.php @@ -0,0 +1,97 @@ +getIds()) as $id) { + $values[$id] = $row->getDestinationProperty($id); + } + + $entity = $this->getEntity($values['entity_type'], $values['bundle'], $values['mode'], $values['type']); + if (!$entity->isNew()) { + $settings = $row->getDestinationProperty('settings'); + $entity->setThirdPartySetting('field_group', $row->getDestinationProperty('group_name'), $settings); + if (isset($settings['format_type']) && ($settings['format_type'] == 'hidden')) { + $entity->unsetThirdPartySetting('field_group', $row->getDestinationProperty('group_name')); + } + $entity->save(); + } + + return array_values($values); + } + + /** + * {@inheritdoc} + */ + public function getIds() { + $ids['entity_type']['type'] = 'string'; + $ids['bundle']['type'] = 'string'; + $ids['mode']['type'] = 'string'; + $ids['type']['type'] = 'string'; + $ids['group_name']['type'] = 'string'; + return $ids; + } + + /** + * {@inheritdoc} + */ + public function rollback(array $destination_identifier) { + $entity = $this->getEntity($destination_identifier['entity_type'], $destination_identifier['bundle'], $destination_identifier['mode'], $destination_identifier['type']); + if (!$entity->isNew()) { + $entity->unsetThirdPartySetting('field_group', $destination_identifier['group_name']); + $entity->save(); + } + } + + /** + * {@inheritdoc} + */ + public function fields(MigrationInterface $migration = NULL) { + // This is intentionally left empty. + } + + /** + * Gets the entity. + * + * @param string $entity_type + * The entity type to retrieve. + * @param string $bundle + * The entity bundle. + * @param string $mode + * The display mode. + * @param string $type + * The destination type. + * + * @return \Drupal\Core\Entity\Display\EntityDisplayInterface + * The entity display object. + */ + protected function getEntity($entity_type, $bundle, $mode, $type) { + $function = $type == 'entity_form_display' ? 'entity_get_form_display' : 'entity_get_display'; + return $function($entity_type, $bundle, $mode); + } + +} diff --git a/modules/field_group/contrib/field_group_migrate/src/Plugin/migrate/source/d6/FieldGroup.php b/modules/field_group/contrib/field_group_migrate/src/Plugin/migrate/source/d6/FieldGroup.php new file mode 100644 index 00000000..ef53935f --- /dev/null +++ b/modules/field_group/contrib/field_group_migrate/src/Plugin/migrate/source/d6/FieldGroup.php @@ -0,0 +1,188 @@ +select('content_group', 'g') + ->fields('g', [ + 'group_type', + 'type_name', + 'group_name', + 'label', + 'settings', + 'weight', + ]); + return $query; + } + + /** + * {@inheritdoc} + */ + public function prepareRow(Row $row) { + $query = $this->select('content_group_fields', 'f'); + $query->fields('f', ['field_name']) + ->condition('type_name', $row->getSourceProperty('type_name')) + ->condition('group_name', $row->getSourceProperty('group_name')); + $fields = $query->execute()->fetchCol(); + $row->setSourceProperty('children', $fields); + $row->setSourceProperty('settings', unserialize($row->getSourceProperty('settings'))); + + switch ($row->getSourceProperty('constants/mode')) { + case 'entity_form_display': + $this->transformEntityFormDisplaySettings($row); + break; + + case 'entity_view_display': + $this->transformEntityViewDisplaySettings($row); + break; + } + + return parent::prepareRow($row); + } + + protected function transformEntityFormDisplaySettings(Row $row) { + $row->setSourceProperty('extracted_settings', $row->getSourceProperty('settings/form')); + $source_settings = $row->getSourceProperty('extracted_settings'); + $settings = [ + 'format_type' => 'details', + 'format_settings' => [], + ]; + + switch ($source_settings['style']) { + case 'no_style': + $settings['format_type'] = 'no_style'; + break; + + case 'simple': + $settings['format_type'] = 'html_element'; + $settings['format_settings']['element'] = 'div'; + $settings['format_settings']['label_element'] = 'h2'; + break; + + case 'fieldset': + $settings['format_type'] = 'fieldset'; + break; + + case 'fieldset_collapsible': + $settings['format_type'] = 'details'; + $settings['format_settings']['open'] = TRUE; + break; + + case 'fieldset_collapsed': + $settings['format_type'] = 'details'; + $settings['format_settings']['open'] = FALSE; + break; + + case 'hidden': + $settings['format_type'] = 'hidden'; + break; + } + + $row->setSourceProperty('converted_settings', $settings); + } + + protected function transformEntityViewDisplaySettings(Row $row) { + $row->setSourceProperty('extracted_settings', $row->getSourceProperty('settings/display')); + $view_modes = array_diff(array_keys($row->getSourceProperty('extracted_settings')), ['label', 'description', 'weight']); + $view_modes = array_filter($view_modes, function ($value) { + return !is_numeric($value); + }); + $row->setSourceProperty('view_mode_keys', $view_modes); + $view_modes = []; + + foreach ($row->getSourceProperty('view_mode_keys') as $view_mode) { + $source_settings = $row->getSourceProperty('extracted_settings/' . $view_mode); + $row->setSourceProperty('view_modes', []); + $settings = [ + 'format_type' => 'details', + 'format_settings' => [], + ]; + + switch ($source_settings['format']) { + case 'no_style': + $settings['format_type'] = 'no_style'; + break; + + case 'simple': + $settings['format_type'] = 'html_element'; + $settings['format_settings']['element'] = 'div'; + $settings['format_settings']['label_element'] = 'h2'; + break; + + case 'fieldset': + $settings['format_type'] = 'fieldset'; + break; + + case 'fieldset_collapsible': + $settings['format_type'] = 'details'; + $settings['format_settings']['open'] = TRUE; + break; + + case 'fieldset_collapsed': + $settings['format_type'] = 'details'; + $settings['format_settings']['open'] = FALSE; + break; + + case 'hidden': + $settings['format_type'] = 'hidden'; + break; + } + + /** + * @todo: ? + */ + if ($view_mode == 'full') { + $view_mode = 'default'; + } + + // $row->setSourceProperty('view_modes/' . $view_mode, $settings); + $view_modes[$view_mode] = $settings; + } + + $row->setSourceProperty('view_modes', $view_modes); + } + + /** + * {@inheritdoc} + */ + public function getIds() { + $ids['type_name']['type'] = 'string'; + $ids['type_name']['alias'] = 'g'; + + $ids['group_name']['type'] = 'string'; + $ids['group_name']['alias'] = 'g'; + + return $ids; + } + + /** + * {@inheritdoc} + */ + public function fields() { + $fields = [ + 'group_type', + 'type_name', + 'group_name', + 'label', + 'settings', + 'weight' + ]; + return array_combine($fields, $fields); + } + +} diff --git a/modules/field_group/contrib/field_group_migrate/src/Plugin/migrate/source/d7/FieldGroup.php b/modules/field_group/contrib/field_group_migrate/src/Plugin/migrate/source/d7/FieldGroup.php new file mode 100644 index 00000000..dc69ec2b --- /dev/null +++ b/modules/field_group/contrib/field_group_migrate/src/Plugin/migrate/source/d7/FieldGroup.php @@ -0,0 +1,104 @@ +select('field_group', 'f')->fields('f'); + } + + /** + * {@inheritdoc} + */ + public function prepareRow(Row $row) { + $data = unserialize($row->getSourceProperty('data')); + $format_settings = $data['format_settings'] + $data['format_settings']['instance_settings']; + unset($format_settings['instance_settings']); + $settings = array( + 'children' => $data['children'], + 'parent_name' => $row->getSourceProperty('parent_name'), + 'weight' => $data['weight'], + 'label' => $data['label'], + 'format_settings' => $format_settings, + 'format_type' => $data['format_type'], + ); + switch ($data['format_type']) { + case 'div': + $settings['format_type'] = 'html_element'; + $settings['format_settings']['element'] = 'div'; + break; + + case 'tabs': + $settings['format_type'] = 'tabs'; + $settings['format_settings']['direction'] = 'vertical'; + break; + + case 'htabs': + $settings['format_type'] = 'tabs'; + $settings['format_settings']['direction'] = 'horizontal'; + break; + + case 'htab': + $settings['format_type'] = 'tab'; + break; + + case 'multipage-group': + // @todo Check if there is a better way to deal with this format type. + $settings['format_type'] = 'tabs'; + break; + + case 'multipage': + // @todo Check if there is a better way to deal with this format type. + $settings['format_type'] = 'tab'; + break; + + } + $row->setSourceProperty('settings', $settings); + return parent::prepareRow($row); + } + + /** + * {@inheritdoc} + */ + public function getIds() { + $ids['id']['type'] = 'integer'; + return $ids; + } + + /** + * {@inheritdoc} + */ + public function fields() { + $fields = array( + 'id' => $this->t('ID'), + 'identifier' => $this->t('Identifier'), + 'group_name' => $this->t('Group name'), + 'entity_type' => $this->t('Entity type'), + 'bundle' => $this->t('Bundle'), + 'mode' => $this->t('View mode'), + 'parent_name' => $this->t('Parent name'), + 'data' => $this->t('Data'), + ); + return $fields; + } + +} diff --git a/modules/field_group/contrib/field_group_migrate/tests/fixtures/drupal7.php b/modules/field_group/contrib/field_group_migrate/tests/fixtures/drupal7.php new file mode 100644 index 00000000..f418f173 --- /dev/null +++ b/modules/field_group/contrib/field_group_migrate/tests/fixtures/drupal7.php @@ -0,0 +1,147 @@ +schema()->createTable('field_group', array( + 'fields' => array( + 'id' => array( + 'type' => 'serial', + 'not null' => TRUE, + 'size' => 'normal', + ), + 'identifier' => array( + 'type' => 'varchar', + 'not null' => TRUE, + 'length' => '255', + 'default' => '', + ), + 'group_name' => array( + 'type' => 'varchar', + 'not null' => TRUE, + 'length' => '32', + 'default' => '', + ), + 'entity_type' => array( + 'type' => 'varchar', + 'not null' => TRUE, + 'length' => '32', + 'default' => '', + ), + 'bundle' => array( + 'type' => 'varchar', + 'not null' => TRUE, + 'length' => '128', + 'default' => '', + ), + 'mode' => array( + 'type' => 'varchar', + 'not null' => TRUE, + 'length' => '128', + 'default' => '', + ), + 'parent_name' => array( + 'type' => 'varchar', + 'not null' => TRUE, + 'length' => '32', + 'default' => '', + ), + 'data' => array( + 'type' => 'blob', + 'not null' => TRUE, + 'size' => 'big', + ), + ), + 'primary key' => array( + 'id', + ), + 'unique keys' => array( + 'identifier' => array( + 'identifier', + ), + ), + 'indexes' => array( + 'group_name' => array( + 'group_name', + ), + ), + 'mysql_character_set' => 'utf8', +)); + +$connection->insert('field_group') +->fields(array( + 'id', + 'identifier', + 'group_name', + 'entity_type', + 'bundle', + 'mode', + 'parent_name', + 'data', +)) +->values(array( + 'id' => '1', + 'identifier' => 'group_page|node|page|default', + 'group_name' => 'group_page', + 'entity_type' => 'node', + 'bundle' => 'page', + 'mode' => 'default', + 'parent_name' => '', + 'data' => 'a:5:{s:5:"label";s:10:"Node group";s:6:"weight";i:0;s:8:"children";a:0:{}s:11:"format_type";s:5:"htabs";s:15:"format_settings";a:1:{s:17:"instance_settings";a:0:{}}}', +)) +->values(array( + 'id' => '2', + 'identifier' => 'group_user|user|user|default', + 'group_name' => 'group_user', + 'entity_type' => 'user', + 'bundle' => 'user', + 'mode' => 'default', + 'parent_name' => '', + 'data' => 'a:5:{s:5:"label";s:17:"User group parent";s:6:"weight";i:1;s:8:"children";a:0:{}s:11:"format_type";s:3:"div";s:15:"format_settings";a:1:{s:17:"instance_settings";a:0:{}}}', +)) +->values(array( + 'id' => '3', + 'identifier' => 'group_user_child|user|user|default', + 'group_name' => 'group_user_child', + 'entity_type' => 'user', + 'bundle' => 'user', + 'mode' => 'default', + 'parent_name' => 'group_user', + 'data' => 'a:5:{s:5:"label";s:16:"User group child";s:6:"weight";i:99;s:8:"children";a:1:{i:0;s:12:"user_picture";}s:11:"format_type";s:4:"tabs";s:15:"format_settings";a:2:{s:5:"label";s:16:"User group child";s:17:"instance_settings";a:2:{s:7:"classes";s:16:"user-group-child";s:2:"id";s:33:"group_article_node_article_teaser";}}}', +)) +->values(array( + 'id' => '4', + 'identifier' => 'group_article|node|article|teaser', + 'group_name' => 'group_article', + 'entity_type' => 'node', + 'bundle' => 'article', + 'mode' => 'teaser', + 'parent_name' => '', + 'data' => 'a:5:{s:5:"label";s:10:"htab group";s:6:"weight";i:2;s:8:"children";a:1:{i:0;s:11:"field_image";}s:11:"format_type";s:4:"htab";s:15:"format_settings";a:1:{s:17:"instance_settings";a:1:{s:7:"classes";s:10:"htab-group";}}}', +)) +->values(array( + 'id' => '5', + 'identifier' => 'group_page|node|page|form', + 'group_name' => 'group_page', + 'entity_type' => 'node', + 'bundle' => 'page', + 'mode' => 'form', + 'parent_name' => '', + 'data' => 'a:5:{s:5:"label";s:15:"Node form group";s:6:"weight";i:0;s:8:"children";a:0:{}s:11:"format_type";s:5:"htabs";s:15:"format_settings";a:1:{s:17:"instance_settings";a:0:{}}}', +)) +->values(array( + 'id' => '6', + 'identifier' => 'group_article|node|article|form', + 'group_name' => 'group_article', + 'entity_type' => 'node', + 'bundle' => 'article', + 'mode' => 'form', + 'parent_name' => '', + 'data' => 'a:5:{s:5:"label";s:15:"htab form group";s:6:"weight";i:2;s:8:"children";a:1:{i:0;s:11:"field_image";}s:11:"format_type";s:4:"htab";s:15:"format_settings";a:1:{s:17:"instance_settings";a:0:{}}}', +)) +->execute(); diff --git a/modules/field_group/contrib/field_group_migrate/tests/src/Kernel/Migrate/d7/MigrateFieldGroupTest.php b/modules/field_group/contrib/field_group_migrate/tests/src/Kernel/Migrate/d7/MigrateFieldGroupTest.php new file mode 100644 index 00000000..9a9cbfc1 --- /dev/null +++ b/modules/field_group/contrib/field_group_migrate/tests/src/Kernel/Migrate/d7/MigrateFieldGroupTest.php @@ -0,0 +1,114 @@ +loadFixture(__DIR__ . '/../../../../fixtures/drupal7.php'); + + $this->installConfig(static::$modules); + + $this->executeMigrations([ + 'd7_node_type', + 'd7_comment_type', + 'd7_view_modes', + 'd7_field', + 'd7_field_instance', + 'd7_field_formatter_settings', + 'd7_field_group', + ]); + } + + /** + * Asserts various aspects of a migrated field group. + * + * @param $id + * The id of the entity display to which the field group applies. + * @param $type + * The destination type. + * @param $group_name + * The name of the field group. + * @param $expected_label + * The expected label. + * @param int $expected_weight + * The expected label. + * @param array $expected_format_settings + * The expected format settings. + * @param string $expected_format_type + * The expected format type. + * @param array $expected_children + * The expected children. + * @param string $expected_parent_name + * The expected parent name. + */ + protected function assertEntity($id, $type, $group_name, $expected_label, $expected_weight = 0, $expected_format_settings = [], $expected_format_type = 'tabs', $expected_children = [], $expected_parent_name = '') { + /** @var EntityDisplayInterface $entity */ + $entity = \Drupal::entityTypeManager() + ->getStorage($type) + ->load($id); + $field_group_settings = $entity->getThirdPartySettings('field_group'); + $this->assertNotEmpty($field_group_settings); + $this->assertArrayHasKey($group_name, $field_group_settings); + $field_group = $field_group_settings[$group_name]; + $this->assertEquals($expected_label, $field_group['label']); + $this->assertEquals($expected_format_settings, $field_group['format_settings']); + $this->assertEquals($expected_children, $field_group['children']); + $this->assertEquals($expected_parent_name, $field_group['parent_name']); + $this->assertEquals($expected_weight, $field_group['weight']); + $this->assertEquals($expected_format_type, $field_group['format_type']); + } + + /** + * Test field group migration from Drupal 7 to 8. + */ + public function testFieldGroup() { + $this->assertEntity('node.page.default', 'entity_view_display', 'group_page', 'Node group', 0, ['direction' => 'horizontal']); + $this->assertEntity('user.user.default', 'entity_view_display', 'group_user', 'User group parent', 1, ['element' => 'div'], 'html_element'); + $this->assertEntity('user.user.default', 'entity_view_display', 'group_user_child', 'User group child', 99, ['direction' => 'vertical', 'label' => 'User group child', 'classes' => 'user-group-child', 'id' => 'group_article_node_article_teaser'], 'tabs', ['user_picture'], 'group_user'); + $this->assertEntity('node.article.teaser', 'entity_view_display', 'group_article', 'htab group', 2, ['classes' => 'htab-group'], 'tab', ['field_image']); + + // Check an entity_view_display without a field group. + /** @var EntityDisplayInterface $entity */ + $entity = \Drupal::entityTypeManager() + ->getStorage('entity_view_display') + ->load('node.page.teaser'); + $field_group_settings = $entity->getThirdPartySettings('field_group'); + $this->assertEmpty($field_group_settings); + + $this->assertEntity('node.page.default', 'entity_form_display', 'group_page', 'Node form group', 0, ['direction' => 'horizontal']); + $this->assertEntity('node.article.default', 'entity_form_display', 'group_article', 'htab form group', 2, [], 'tab', ['field_image']); + + // Check an entity_form_display without a field group. + $entity = \Drupal::entityTypeManager() + ->getStorage('entity_form_display') + ->load('node.blog.default'); + $field_group_settings = $entity->getThirdPartySettings('field_group'); + $this->assertEmpty($field_group_settings); + } +} diff --git a/modules/field_group/contrib/field_group_migrate/tests/src/Unit/Migrate/d7/FieldGroupTest.php b/modules/field_group/contrib/field_group_migrate/tests/src/Unit/Migrate/d7/FieldGroupTest.php new file mode 100644 index 00000000..34449fbd --- /dev/null +++ b/modules/field_group/contrib/field_group_migrate/tests/src/Unit/Migrate/d7/FieldGroupTest.php @@ -0,0 +1,94 @@ + 'test', + 'source' => [ + 'plugin' => 'd7_field_group', + ], + ]; + + protected $expectedResults = [ + [ + 'id' => '1', + 'identifier' => 'group_page|node|page|default', + 'group_name' => 'group_page', + 'entity_type' => 'node', + 'bundle' => 'page', + 'mode' => 'default', + 'parent_name' => '', + 'data' => 'a:5:{s:5:"label";s:10:"Node group";s:6:"weight";i:0;s:8:"children";a:0:{}s:11:"format_type";s:5:"htabs";s:15:"format_settings";a:1:{s:17:"instance_settings";a:0:{}}}', + ], + [ + 'id' => '2', + 'identifier' => 'group_user|user|user|default', + 'group_name' => 'group_user', + 'entity_type' => 'user', + 'bundle' => 'user', + 'mode' => 'default', + 'parent_name' => '', + 'data' => 'a:5:{s:5:"label";s:17:"User group parent";s:6:"weight";i:1;s:8:"children";a:0:{}s:11:"format_type";s:3:"div";s:15:"format_settings";a:1:{s:17:"instance_settings";a:0:{}}}', + ], + [ + 'id' => '3', + 'identifier' => 'group_user_child|user|user|default', + 'group_name' => 'group_user_child', + 'entity_type' => 'user', + 'bundle' => 'user', + 'mode' => 'default', + 'parent_name' => 'group_user', + 'data' => 'a:5:{s:5:"label";s:16:"User group child";s:6:"weight";i:99;s:8:"children";a:1:{i:0;s:12:"user_picture";}s:11:"format_type";s:4:"tabs";s:15:"format_settings";a:2:{s:5:"label";s:16:"User group child";s:17:"instance_settings";a:2:{s:7:"classes";s:16:"user-group-child";s:2:"id";s:33:"group_article_node_article_teaser";}}}', + ], + [ + 'id' => '4', + 'identifier' => 'group_article|node|article|teaser', + 'group_name' => 'group_article', + 'entity_type' => 'node', + 'bundle' => 'article', + 'mode' => 'teaser', + 'parent_name' => '', + 'data' => 'a:5:{s:5:"label";s:10:"htab group";s:6:"weight";i:2;s:8:"children";a:1:{i:0;s:11:"field_image";}s:11:"format_type";s:4:"htab";s:15:"format_settings";a:1:{s:17:"instance_settings";a:1:{s:7:"classes";s:10:"htab-group";}}}', + ], + [ + 'id' => '5', + 'identifier' => 'group_page|node|page|form', + 'group_name' => 'group_page', + 'entity_type' => 'node', + 'bundle' => 'page', + 'mode' => 'form', + 'parent_name' => '', + 'data' => 'a:5:{s:5:"label";s:15:"Node form group";s:6:"weight";i:0;s:8:"children";a:0:{}s:11:"format_type";s:5:"htabs";s:15:"format_settings";a:1:{s:17:"instance_settings";a:0:{}}}', + ], + [ + 'id' => '6', + 'identifier' => 'group_article|node|article|form', + 'group_name' => 'group_article', + 'entity_type' => 'node', + 'bundle' => 'article', + 'mode' => 'form', + 'parent_name' => '', + 'data' => 'a:5:{s:5:"label";s:15:"htab form group";s:6:"weight";i:2;s:8:"children";a:1:{i:0;s:11:"field_image";}s:11:"format_type";s:4:"htab";s:15:"format_settings";a:1:{s:17:"instance_settings";a:0:{}}}', + ], + ]; + + /** + * {@inheritdoc} + */ + protected function setUp() { + $this->databaseContents['field_group'] = $this->expectedResults; + parent::setUp(); + } + +} diff --git a/modules/field_group/css/field_group.field_ui.css b/modules/field_group/css/field_group.field_ui.css new file mode 100644 index 00000000..7584e99e --- /dev/null +++ b/modules/field_group/css/field_group.field_ui.css @@ -0,0 +1,14 @@ + +#field-overview tr.field-group .group-label, +#field-display-overview tr.field-group .group-label { + font-weight: bold; +} + +#field-overview tr.static-region, +#field-display-overview tr.static-region { + background-color: #ddd; +} + +#edit-refresh { + display:none; +} \ No newline at end of file diff --git a/modules/field_group/field_group.info.yml b/modules/field_group/field_group.info.yml new file mode 100644 index 00000000..e747db2d --- /dev/null +++ b/modules/field_group/field_group.info.yml @@ -0,0 +1,13 @@ +name: 'Field Group' +type: module +description: 'Provides the ability to group your fields on both form and display.' +package : Fields +# core: 8.x +dependencies: + - drupal:field + +# Information added by Drupal.org packaging script on 2016-11-28 +version: '8.x-1.0-rc6' +core: '8.x' +project: 'field_group' +datestamp: 1480365490 diff --git a/modules/field_group/field_group.libraries.yml b/modules/field_group/field_group.libraries.yml new file mode 100644 index 00000000..01f43f6a --- /dev/null +++ b/modules/field_group/field_group.libraries.yml @@ -0,0 +1,60 @@ +field_ui: + version: VERSION + js: + js/field_group.field_ui.js: {} + css: + component: + css/field_group.field_ui.css: {} + dependencies: + - core/jquery + - core/jquery.once + - core/drupal + - core/drupalSettings + +core: + version: VERSION + js: + js/field_group.js: {} + dependencies: + - core/jquery + - core/jquery.once + - core/drupal + - core/drupalSettings + +formatter.accordion: + version: VERSION + js: + formatters/accordion/accordion.js: {} + dependencies: + - core/jquery.ui.accordion + +formatter.html_element: + version: VERSION + js: + formatters/html_element/html-element.js: {} + +formatter.fieldset: + version: VERSION + js: + formatters/fieldset/fieldset.js: {} + +formatter.details: + version: VERSION + js: + formatters/details/details.js: {} + +formatter.tabs: + version: VERSION + js: + formatters/tabs/tabs.js: {} + +element.horizontal_tabs: + version: VERSION + js: + # Load before field_group/core. + formatters/tabs/horizontal-tabs.js: {weight: -1} + css: + component: + formatters/tabs/horizontal-tabs.css: {} + dependencies: + - core/drupal.collapse diff --git a/modules/field_group/field_group.links.action.yml b/modules/field_group/field_group.links.action.yml new file mode 100644 index 00000000..bc988ab6 --- /dev/null +++ b/modules/field_group/field_group.links.action.yml @@ -0,0 +1,3 @@ +field_group.field_group_add: + class: \Drupal\Core\Menu\LocalActionDefault + deriver: \Drupal\field_group\Plugin\Derivative\FieldGroupLocalAction diff --git a/modules/field_group/field_group.module b/modules/field_group/field_group.module new file mode 100644 index 00000000..fdf4c6d6 --- /dev/null +++ b/modules/field_group/field_group.module @@ -0,0 +1,786 @@ +getDefinitions(); + $entity_types = array(); + foreach ($entity_info as $entity_type_id => $entity_type) { + if ($route_name = $entity_type->get('field_ui_base_route')) { + $entity_types[] = $entity_type_id; + } + } + + foreach ($theme_registry as $theme_hook => $info) { + if (in_array($theme_hook, $entity_types) || (!empty($info['base hook']) && in_array($info['base hook'], $entity_types))) { + $theme_registry[$theme_hook]['preprocess functions'][] = 'field_group_build_entity_groups'; + } + } + + // ECK does not use the eck as theme function. + if (isset($theme_registry['eck_entity'])) { + $theme_registry['eck_entity']['preprocess functions'][] = 'field_group_build_entity_groups'; + } + +} + +/** + * Implements hook_theme(). + */ +function field_group_theme() { + return array( + 'horizontal_tabs' => array( + 'render element' => 'element', + 'template' => 'horizontal-tabs', + 'file' => 'templates/theme.inc', + ), + 'field_group_accordion_item' => array( + 'render element' => 'element', + 'template' => 'field-group-accordion-item', + 'file' => 'templates/theme.inc', + ), + 'field_group_accordion' => array( + 'render element' => 'element', + 'template' => 'field-group-accordion', + 'file' => 'templates/theme.inc', + ), + 'field_group_html_element' => array( + 'render element' => 'element', + 'template' => 'field-group-html-element', + 'file' => 'templates/theme.inc', + ), + ); +} + +/** + * Implements hook_theme_suggestions_alter(). + * + * @param array $suggestions + * @param array $variables + * @param $hook + */ +function field_group_theme_suggestions_alter(array &$suggestions, array $variables, $hook) { + switch ($hook) { + case 'horizontal_tabs': + case 'field_group_accordion_item': + case 'field_group_accordion': + case 'field_group_html_element': + $element = $variables['element']; + + $name = $element['#group_name']; + $entity_type = $element['#entity_type']; + $bundle = $element['#bundle']; + + $wrapper = ''; + if (isset($element['#wrapper_element'])) { + $wrapper = $element['#wrapper_element']; + $suggestions[] = $hook . '__' . $wrapper; + } + + $suggestions[] = $hook . '__' . $entity_type; + $suggestions[] = $hook . '__' . $bundle; + $suggestions[] = $hook . '__' . $name; + + if ($wrapper) { + $suggestions[] = $hook . '__' . $entity_type . '__' . $wrapper; + } + + $suggestions[] = $hook . '__' . $entity_type . '__' . $bundle; + $suggestions[] = $hook . '__' . $entity_type . '__' . $name; + + if ($wrapper) { + $suggestions[] = $hook . '__' . $entity_type . '__' . $bundle . '__' . $wrapper; + } + $suggestions[] = $hook . '__' . $entity_type . '__' . $bundle . '__' . $name; + break; + } + +} + +/** + * Implements hook_form_FORM_ID_alter(). + * Using hook_form_field_ui_form_display_overview_form_alter. + */ +function field_group_form_entity_form_display_edit_form_alter(&$form, FormStateInterface $form_state) { + $form_state->loadInclude('field_group', 'inc', 'includes/field_ui'); + field_group_field_ui_display_form_alter($form, $form_state); +} + +/** + * Implements hook_form_FORM_ID_alter(). + * Using hook_form_field_ui_display_overview_form_alter. + */ +function field_group_form_entity_view_display_edit_form_alter(&$form, FormStateInterface $form_state) { + $form_state->loadInclude('field_group', 'inc', 'includes/field_ui'); + field_group_field_ui_display_form_alter($form, $form_state); +} + +/** + * Implements hook_field_info_max_weight(). + */ +function field_group_field_info_max_weight($entity_type, $bundle, $context, $context_mode) { + + $groups = field_group_info_groups($entity_type, $bundle, $context, $context_mode); + + $weights = array(); + foreach ($groups as $group) { + $weights[] = $group->weight; + } + return $weights ? max($weights) : NULL; +} + +/** + * Implements hook_form_alter(). + */ +function field_group_form_alter(array &$form, FormStateInterface $form_state) { + + if ($form_state->getFormObject() instanceof ContentEntityFormInterface && !$form_state->getFormObject() instanceof ConfirmFormInterface) { + + /** + * @var EntityFormDisplayInterface $form_display + */ + if ($form_display = $form_state->getStorage()['form_display']) { + $entity = $form_state->getFormObject()->getEntity(); + + $context = array( + 'entity_type' => $entity->getEntityTypeId(), + 'bundle' => $entity->bundle(), + 'entity' => $entity, + 'context' => 'form', + 'display_context' => 'form', + 'mode' => $form_display->getMode(), + ); + + field_group_attach_groups($form, $context); + $form['#pre_render'][] = 'field_group_form_pre_render'; + } + } + +} + +/** + * Implements hook_inline_entity_form_entity_form_alter(). + */ +function field_group_inline_entity_form_entity_form_alter(&$entity_form, FormStateInterface $form_state) { + + // Attach the fieldgroups to current entity form. + $context = [ + 'entity_type' => $entity_form['#entity']->getEntityTypeId(), + 'bundle' => $entity_form['#entity']->bundle(), + 'entity' => $entity_form['#entity'], + 'display_context' => 'form', + 'mode' => 'default', + ]; + + field_group_attach_groups($entity_form, $context); + $entity_form['#pre_render'][] = 'field_group_form_pre_render'; +} + +/** + * Implements hook_entity_view_alter(). + */ +function field_group_entity_view_alter(&$build, EntityInterface $entity, EntityDisplayInterface $display) { + + $context = array( + 'entity_type' => $display->getTargetEntityTypeId(), + 'bundle' => $entity->bundle(), + 'entity' => $entity, + 'display_context' => 'view', + 'mode' => $display->getMode(), + ); + + field_group_attach_groups($build, $context); + + // If no theme hook, we have no theme hook to preprocess. + // Add a prerender. + if (empty($build['#theme'])) { + + $ds_enabled = false; + if (Drupal::moduleHandler()->moduleExists('ds')) { + // Check if DS is enabled for this display. + if ($display->getThirdPartySetting('ds', 'layout') && !Drupal\ds\Ds::isDisabled()) { + $ds_enabled = true; + } + } + + // If DS is enabled, no pre render is needed (DS adds fieldgroup preprocessing). + if (!$ds_enabled) { + $build['#pre_render'][] = 'field_group_entity_view_pre_render'; + } + } +} + +/** + * Pre render callback for rendering groups. + * @see field_group_field_attach_form + * @param $element Form that is being rendered. + */ +function field_group_form_pre_render($element) { + if (empty($element['#field_group_form_pre_render'])) { + $element['#field_group_form_pre_render'] = TRUE; + field_group_build_entity_groups($element, 'form'); + } + return $element; +} + +/** + * Pre render callback for rendering groups on entities without theme hook. + * @param $element + * Entity being rendered. + */ +function field_group_entity_view_pre_render($element) { + field_group_build_entity_groups($element, 'view'); + return $element; +} + +/** + * Implements hook_field_group_pre_render(). + * + * @param Array $element + * Group beïng rendered. + * @param Object $group + * The Field group info. + * @param $rendering_object + * The entity / form beïng rendered + */ +function field_group_field_group_pre_render(&$element, &$group, &$rendering_object) { + + // Add all field_group format types to the js settings. + $element['#attached']['drupalSettings']['field_group'] = array( + $group->format_type => [ + 'mode' => $group->mode, + 'context' => $group->context, + 'settings' => $group->format_settings, + ], + ); + + $element['#weight'] = $group->weight; + + // Call the pre render function for the format type. + $manager = Drupal::service('plugin.manager.field_group.formatters'); + $plugin = $manager->getInstance(array( + 'format_type' => $group->format_type, + 'configuration' => array('label' => $group->label, 'settings' => $group->format_settings), + 'group' => $group, + )); + $plugin->preRender($element, $rendering_object); + +} + +/** + * Implements hook_field_group_build_pre_render_alter(). + * @param Array $elements by address. + */ +function field_group_field_group_build_pre_render_alter(& $element) { + + // Someone is doing a node view, in a node view. Reset content. + if (isset($element['#node']->content) && count($element['#node']->content) > 0) { + $element['#node']->content = array(); + } + + $display = isset($element['#view_mode']); + $groups = array_keys($element['#fieldgroups']); + + // Dish the fieldgroups with no fields for non-forms. + if ($display) { + field_group_remove_empty_display_groups($element, $groups); + } + else { + // Fix the problem on forms with additional settings. + field_group_remove_empty_form_groups('form', $element, $groups, $element['#fieldgroups'], $element['#entity_type']); + } + +} + +/** + * Attach groups to the (form) build. + * + * @param Array $element + * The part of the form. + * @param Array $context + * The contextual information. + */ +function field_group_attach_groups(&$element, $context) { + + $entity_type = $context['entity_type']; + $bundle = $context['bundle']; + $mode = $context['mode']; + $display_context = $context['display_context']; + + $element['#fieldgroups'] = field_group_info_groups($entity_type, $bundle, $display_context, $mode); + + // Create a lookup array. + $group_children = array(); + foreach ($element['#fieldgroups'] as $group_name => $group) { + foreach ($group->children as $child) { + $group_children[$child] = $group_name; + } + } + $element['#group_children'] = $group_children; + $element['#entity_type'] = $entity_type; + +} + +/** + * Preprocess/ Pre-render callback. + * + * @see field_group_form_pre_render() + * @see field_group_theme_registry_alter + * @see field_group_fields_nest() + * @param $vars preprocess vars or form element + * @param $context The display context (form or view) + * @return $element Array with re-arranged fields in groups. + */ +function field_group_build_entity_groups(&$vars, $context = 'view') { + + if ($context == 'form') { + $element = &$vars; + $nest_vars = NULL; + } + else { + if (isset($vars['elements'])) { + $element = &$vars['elements']; + } + elseif (isset($vars['content'])) { + $element = &$vars['content']; + } + else { + + if ($context === 'eck_entity') { + $element = &$vars['entity']; + } + else { + $element = &$vars; + } + } + + $nest_vars = &$vars; + } + + // No groups on the entity. + if (empty($element['#fieldgroups'])) { + return $element; + } + + // Nest the fields in the corresponding field groups. + field_group_fields_nest($element, $nest_vars); + + // Allow others to alter the pre_rendered build. + Drupal::moduleHandler()->alter('field_group_build_pre_render', $element); + + // Return the element on forms. + if ($context == 'form') { + return $element; + } + + // No groups on the entity. Prerender removed empty field groups. + if (empty($element['#fieldgroups'])) { + return $element; + } + + // Put groups inside content if we are rendering an entity_view. + foreach ($element['#fieldgroups'] as $group) { + if (!empty($element[$group->group_name])) { + if (isset($vars['content'])) { + $vars['content'][$group->group_name] = $element[$group->group_name]; + } + elseif (isset($vars['user_profile'])) { + $vars['user_profile'][$group->group_name] = $element[$group->group_name]; + } + } + } + +} + +/** + * Recursive function to nest fields in the field groups. + * + * This function will take out all the elements in the form and + * place them in the correct container element, a fieldgroup. + * The current group element in the loop is passed recursively so we can + * stash fields and groups in it while we go deeper in the array. + * @param Array $element + * The current element to analyse for grouping. + * @param Array $vars + * Rendering vars from the entity being viewed. + */ +function field_group_fields_nest(&$element, &$vars = NULL) { + + // Create all groups and keep a flat list of references to these groups. + $group_references = array(); + foreach ($element['#fieldgroups'] as $group_name => $group) { + // Construct own weight, as some fields (for example preprocess fields) don't have weight set. + $element[$group_name] = array(); + $group_references[$group_name] = &$element[$group_name]; + } + + // Loop through all form children looking for those that are supposed to be + // in groups, and insert placeholder element for the new group field in the + // correct location within the form structure. + $element_clone = array(); + foreach (Element::children($element) as $child_name) { + $element_clone[$child_name] = $element[$child_name]; + // If this element is in a group, create the placeholder element. + if (isset($element['#group_children'][$child_name])) { + $element_clone[$element['#group_children'][$child_name]] = array(); + } + } + $element = array_merge($element_clone, $element); + + // Move all children to their parents. Use the flat list of references for + // direct access as we don't know where in the root_element hierarchy the + // parent currently is situated. + foreach ($element['#group_children'] as $child_name => $parent_name) { + + // Entity being viewed + if ($vars) { + // If not a group, check vars['content'] for empty field. + if (!isset($element['#fieldgroups'][$child_name]) && isset($vars['content'][$child_name])) { + $group_references[$parent_name][$child_name] = $vars['content'][$child_name]; + unset($vars['content'][$child_name]); + } + elseif (!isset($element['#fieldgroups'][$child_name]) && isset($vars['user_profile'][$child_name])) { + $group_references[$parent_name][$child_name] = $vars['user_profile'][$child_name]; + unset($vars['user_profile'][$child_name]); + } + // If this is a group, we have to use a reference to keep the reference + // list intact (but if it is a field we don't mind). + else { + $group_references[$parent_name][$child_name] = &$element[$child_name]; + unset($element[$child_name]); + } + } + // Form being viewed + else { + // Block denied fields (#access) before they are put in groups. + // Fields (not groups) that don't have children (like field_permissions) are removed + // in field_group_field_group_build_pre_render_alter. + if (isset($element[$child_name]) && (!isset($element[$child_name]['#access']) || $element[$child_name]['#access'])) { + // If this is a group, we have to use a reference to keep the reference + // list intact (but if it is a field we don't mind). + $group_references[$parent_name][$child_name] = &$element[$child_name]; + $group_references[$parent_name]['#weight'] = $element['#fieldgroups'][$parent_name]->weight; + } + + // The child has been copied to its parent: remove it from the root element. + unset($element[$child_name]); + } + + } + + // Bring extra element wrappers to achieve a grouping of fields. + // This will mainly be prefix and suffix altering. + foreach ($element['#fieldgroups'] as $group_name => $group) { + field_group_pre_render($group_references[$group_name], $group, $element); + } + +} + +/** + * Function to pre render the field group element. + * + * @see field_group_fields_nest() + * + * @param $element + * Render array of group element that needs to be created. + * @param $group + * Object with the group information. + * @param $rendering_object + * The entity / form beïng rendered. + */ +function field_group_pre_render(& $element, $group, & $rendering_object) { + + // Only run the pre_render function if the group has elements. + // $group->group_name + if ($element == array()) { + return; + } + + // Let modules define their wrapping element. + // Note that the group element has no properties, only elements. + foreach (Drupal::moduleHandler()->getImplementations('field_group_pre_render') as $module) { + // The intention here is to have the opportunity to alter the + // elements, as defined in hook_field_group_formatter_info. + // Note, implement $element by reference! + $function = $module . '_field_group_pre_render'; + $function($element, $group, $rendering_object); + } + + // Allow others to alter the pre_render. + Drupal::moduleHandler()->alter('field_group_pre_render', $element, $group, $rendering_object); + +} + +/** + * Saves a group definition. + * This function is called by ctools export when calls are made + * through ctools_export_crud_save(). + * + * @param $group + * A group definition. + * @param $display + * The display to update if known. + * @return EntityDisplayInterface || NULL + */ +function field_group_group_save($group, $display = NULL) { + if ($display === NULL) { + if ($group->context == 'form') { + $display = EntityFormDisplay::load($group->entity_type . '.' . $group->bundle . '.' . $group->mode); + } + elseif ($group->context == 'view') { + $display = EntityViewDisplay::load($group->entity_type . '.' . $group->bundle . '.' . $group->mode); + } + } + + // If no display was found. It doesn't exist yet, create it. + if (!isset($display)) { + + if ($group->context == 'form') { + $display = EntityFormDisplay::create(array( + 'targetEntityType' => $group->entity_type, + 'bundle' => $group->bundle, + 'mode' => $group->mode, + ))->setStatus(TRUE); + } + elseif ($group->context == 'view') { + $display = EntityViewDisplay::create(array( + 'targetEntityType' => $group->entity_type, + 'bundle' => $group->bundle, + 'mode' => $group->mode, + ))->setStatus(TRUE); + } + + } + + /** + * @var $display \Drupal\Core\Entity\Display\EntityDisplayInterface + */ + if (isset($display)) { + $data = (array) $group; + unset($data['group_name'], $data['entity_type'], $data['bundle'], $data['mode'], $data['form'], $data['context']); + $display->setThirdPartySetting('field_group', $group->group_name, $data); + $display->save(); + } + + return $display; +} + +/** + * Delete a field group. + * + * @param $group + * A group definition. + */ +function field_group_group_delete($group) { + if ($group->context == 'form') { + $display = EntityFormDisplay::load($group->entity_type . '.' . $group->bundle . '.' . $group->mode); + } + elseif ($group->context == 'view') { + $display = EntityViewDisplay::load($group->entity_type . '.' . $group->bundle . '.' . $group->mode); + } + + /** + * @var $display \Drupal\Core\Entity\Display\EntityDisplayInterface + */ + if (isset($display)) { + $display->unsetThirdPartySetting('field_group', $group->group_name); + $display->save(); + } + + Drupal::moduleHandler()->invokeAll('field_group_delete_field_group', array($group)); +} + +/** + * Get all groups. + * + * @param $entity_type + * The name of the entity. + * @param $bundle + * The name of the bundle. + * @param $context + * The context of the view mode (form or view) + * @param $mode + * The view mode. + */ +function field_group_info_groups($entity_type, $bundle, $context, $mode) { + if ($context == 'form') { + $display = EntityFormDisplay::load($entity_type . '.' . $bundle . '.' . $mode); + if (!$display) { + return array(); + } + $data = $display->getThirdPartySettings('field_group'); + } + if ($context == 'view') { + $display = EntityViewDisplay::load($entity_type . '.' . $bundle . '.' . $mode); + if (!$display) { + return array(); + } + $data = $display->getThirdPartySettings('field_group'); + } + $groups = array(); + if (isset($data)) { + foreach ($data as $group_name => $definition) { + $definition += array( + 'group_name' => $group_name, + 'entity_type' => $entity_type, + 'bundle' => $bundle, + 'context' => $context, + 'mode' => $mode, + ); + $groups[$group_name] = (object) $definition; + } + } + return $groups; +} + +/** + * Loads a group definition. + * + * @param $group_name + * The name of the group. + * @param $entity_type + * The name of the entity. + * @param $bundle + * The name of the bundle. + * @param $context + * The context of the view mode (form or view) + * @param $mode + * The view mode to load. + */ +function field_group_load_field_group($group_name, $entity_type, $bundle, $context, $mode) { + $groups = field_group_info_groups($entity_type, $bundle, $context, $mode); + if (isset($groups[$group_name])) { + return $groups[$group_name]; + } +} + +/** + * Checks if a field_group exists in required context. + * + * @param String $group_name + * The name of the group. + * @param String $entity_type + * The name of the entity. + * @param String $bundle + * The bundle for the entity. + * @param $context + * The context of the view mode (form or view) + * @param String $mode + * The view mode context the group will be rendered. + */ +function field_group_exists($group_name, $entity_type, $bundle, $context, $mode) { + return (bool) field_group_load_field_group($group_name, $entity_type, $bundle, $context, $mode); +} + +/** + * Remove empty groups on forms. + * + * @param String $parent_name + * The name of the element. + * @param array $element + * The element to check the empty state. + * @param array $groups + * Array of group objects. + */ +function field_group_remove_empty_form_groups($name, & $element, $groups, &$form_groups, $entity) { + + $exceptions = array('user__account', 'comment__author'); + + $children = Element::children($element); + + $hasChildren = FALSE; + if (count($children)) { + foreach ($children as $childname) { + + if (in_array($childname, $groups)) { + field_group_remove_empty_form_groups($childname, $element[$childname], $groups, $form_groups, $entity); + } + $exception = $entity . '__' . $childname; + $hasChildren = $hasChildren ? TRUE : (isset($element[$childname]['#type']) || isset($element[$childname]['#markup']) || in_array($exception, $exceptions)); + + } + } + + if (!$hasChildren) { + + // Remove empty elements from the #fieldgroups. + if (empty($element) && isset($form_groups[$name]) && !is_array($form_groups[$name])) { + foreach ($form_groups as $group_name => $group) { + if (isset($group->children)) { + $group_children = array_flip($group->children); + if (isset($group_children[$name])) { + unset($form_groups[$group_name]->children[$group_children[$name]]); + } + } + } + } + + $element['#access'] = FALSE; + + } + +} + +/** + * Remove empty groups on entity display. + * + * @param array $element + * The element to check the empty state. + * @param array $groups + * Array of group objects. + */ +function field_group_remove_empty_display_groups(& $element, $groups) { + + $empty_child = TRUE; + $empty_group = TRUE; + + // Loop through the visible children for current element. + foreach (Element::getVisibleChildren($element) as $name) { + + // Descend if the child is a group. + if (in_array($name, $groups)) { + $empty_child = field_group_remove_empty_display_groups($element[$name], $groups); + if (!$empty_child) { + $empty_group = FALSE; + } + } + // Child is a field or a renderable array and the element is not empty. + elseif (!empty($element[$name])) { + $clone_element = $element[$name]; + // Weight parameter can make empty element seen as not empty. + unset($clone_element['#weight']); + if (!Element::isEmpty($clone_element)) { + $empty_group = FALSE; + } + } + + } + + // Reset an empty group. + if ($empty_group) { + $element = []; + } + + return $empty_group; + +} diff --git a/modules/field_group/field_group.services.yml b/modules/field_group/field_group.services.yml new file mode 100644 index 00000000..b7528819 --- /dev/null +++ b/modules/field_group/field_group.services.yml @@ -0,0 +1,13 @@ +services: + plugin.manager.field_group.formatters: + class: Drupal\field_group\FieldGroupFormatterPluginManager + parent: default_plugin_manager + field_group.subscriber: + class: Drupal\field_group\Routing\RouteSubscriber + arguments: ['@entity.manager'] + tags: + - { name: event_subscriber } + field_group.param_converter: + class: Drupal\field_group\Routing\FieldGroupConverter + tags: + - { name: paramconverter } \ No newline at end of file diff --git a/modules/field_group/formatters/accordion/accordion.js b/modules/field_group/formatters/accordion/accordion.js new file mode 100644 index 00000000..d4a141fb --- /dev/null +++ b/modules/field_group/formatters/accordion/accordion.js @@ -0,0 +1,68 @@ +(function ($) { + + 'use strict'; + + Drupal.FieldGroup = Drupal.FieldGroup || {}; + Drupal.FieldGroup.Effects = Drupal.FieldGroup.Effects || {}; + + /** + * Implements Drupal.FieldGroup.processHook(). + */ + Drupal.FieldGroup.Effects.processAccordion = { + execute: function (context, settings, group_info) { + $('div.field-group-accordion-wrapper', context).once('fieldgroup-effects').each(function () { + var wrapper = $(this); + + // Get the index to set active. + var active_index = false; + wrapper.find('.accordion-item').each(function (i) { + if ($(this).hasClass('field-group-accordion-active')) { + active_index = i; + } + }); + + wrapper.accordion({ + heightStyle: 'content', + active: active_index, + collapsible: true, + changestart: function (event, ui) { + if ($(this).hasClass('effect-none')) { + ui.options.animated = false; + } + else { + ui.options.animated = 'slide'; + } + } + }); + + if (group_info.context === 'form') { + + var $firstErrorItem = false; + + // Add required fields mark to any element containing required fields + wrapper.find('div.field-group-accordion-item').each(function (i) { + + var $this = $(this); + if ($this.is('.required-fields') && ($this.find('[required]').length > 0 || $this.find('.form-required').length > 0)) { + $('h3.ui-accordion-header a').eq(i).addClass('form-required'); + } + if ($('.error', $this).length) { + // Save first error item, for focussing it. + if (!$firstErrorItem) { + $firstErrorItem = $this.parent().accordion('activate', i); + } + $('h3.ui-accordion-header').eq(i).addClass('error'); + } + }); + + // Save first error item, for focussing it. + if (!$firstErrorItem) { + $('.ui-accordion-content-active', $firstErrorItem).css({height: 'auto', width: 'auto', display: 'block'}); + } + + } + }); + } + }; + +})(jQuery); diff --git a/modules/field_group/formatters/details/details.js b/modules/field_group/formatters/details/details.js new file mode 100644 index 00000000..c3d87b8b --- /dev/null +++ b/modules/field_group/formatters/details/details.js @@ -0,0 +1,23 @@ +(function ($) { + + 'use strict'; + + Drupal.FieldGroup = Drupal.FieldGroup || {}; + Drupal.FieldGroup.Effects = Drupal.FieldGroup.Effects || {}; + + /** + * This script adds the required and error classes to the details wrapper. + */ + Drupal.behaviors.fieldGroupDetails = { + attach: function (context) { + $(context).find('.field-group-details').once('field-group-details').each(function () { + var $this = $(this); + + if ($this.is('.required-fields') && ($this.find('[required]').length > 0 || $this.find('.form-required').length > 0)) { + $('summary', $this).first().addClass('form-required'); + } + }); + } + }; + +})(jQuery); diff --git a/modules/field_group/formatters/fieldset/fieldset.js b/modules/field_group/formatters/fieldset/fieldset.js new file mode 100644 index 00000000..f52e9dd5 --- /dev/null +++ b/modules/field_group/formatters/fieldset/fieldset.js @@ -0,0 +1,24 @@ +(function ($) { + + 'use strict'; + + Drupal.FieldGroup = Drupal.FieldGroup || {}; + Drupal.FieldGroup.Effects = Drupal.FieldGroup.Effects || {}; + + /** + * This script adds the required and error classes to the fieldset wrapper. + */ + Drupal.behaviors.fieldGroupDFieldset = { + attach: function (context) { + + $(context).find('.field-group-fieldset').once('field-group-fieldset').each(function () { + var $this = $(this); + + if ($this.is('.required-fields') && ($this.find('[required]').length > 0 || $this.find('.form-required').length > 0)) { + $('legend', $this).first().addClass('form-required'); + } + }); + } + }; + +})(jQuery); diff --git a/modules/field_group/formatters/html_element/html-element.js b/modules/field_group/formatters/html_element/html-element.js new file mode 100644 index 00000000..07060674 --- /dev/null +++ b/modules/field_group/formatters/html_element/html-element.js @@ -0,0 +1,70 @@ +(function ($) { + + 'use strict'; + + Drupal.FieldGroup = Drupal.FieldGroup || {}; + Drupal.FieldGroup.Effects = Drupal.FieldGroup.Effects || {}; + + /** + * Implements Drupal.FieldGroup.processHook(). + */ + Drupal.FieldGroup.Effects.processHtml_element = { + execute: function (context, settings, group_info) { + + $('.field-group-html-element', context).once('fieldgroup-effects').each(function () { + var $wrapper = $(this); + + if ($wrapper.hasClass('fieldgroup-collapsible')) { + Drupal.FieldGroup.Effects.processHtml_element.renderCollapsible($wrapper); + } + else { + + // Add required field markers if needed + if (group_info.settings.show_label && $wrapper.is('.required-fields') && ($wrapper.find('[required]').length > 0 || $wrapper.find('.form-required').length > 0)) { + $wrapper.find(group_info.settings.label_element + ':first').addClass('form-required'); + } + } + + }); + }, + renderCollapsible: function($wrapper) { + + // Turn the legend into a clickable link, but retain span.field-group-format-toggler + // for CSS positioning. + + var $toggler = $('.field-group-toggler:first', $wrapper); + var $link = $(''); + $link.prepend($toggler.contents()); + + // Add required field markers if needed + if ($wrapper.is('.required-fields') && ($wrapper.find('[required]').length > 0 || $wrapper.find('.form-required').length > 0)) { + $link.addClass('form-required'); + } + + $link.appendTo($toggler); + + // .wrapInner() does not retain bound events. + $link.click(function () { + var wrapper = $wrapper.get(0); + // Don't animate multiple times. + if (!wrapper.animating) { + wrapper.animating = true; + var speed = $wrapper.hasClass('speed-fast') ? 300 : 1000; + if ($wrapper.hasClass('effect-none') && $wrapper.hasClass('speed-none')) { + $('> .field-group-wrapper', wrapper).toggle(); + } + else if ($wrapper.hasClass('effect-blind')) { + $('> .field-group-wrapper', wrapper).toggle('blind', {}, speed); + } + else { + $('> .field-group-wrapper', wrapper).toggle(speed); + } + wrapper.animating = false; + } + $wrapper.toggleClass('collapsed'); + return false; + }); + } + }; + +})(jQuery); diff --git a/modules/field_group/formatters/tabs/horizontal-tabs.css b/modules/field_group/formatters/tabs/horizontal-tabs.css new file mode 100644 index 00000000..088e59ed --- /dev/null +++ b/modules/field_group/formatters/tabs/horizontal-tabs.css @@ -0,0 +1,129 @@ +.horizontal-tabs { + margin: 0 0 1em 0; /* LTR */ + padding: 0; + border: 1px solid #ccc; + position: relative; /* IE6/7 */ +} + +[dir="rtl"] .horizontal-tabs { + margin: 0 0 1em 0; +} + +.horizontal-tabs .horizontal-tabs-list { + display: inline-block; + margin: 0; + border: 0; + padding: 0px; + list-style: none; + background-color: #dedede; + border-right: 1px solid #dedede; /* LTR */ + width: 100%; + height: auto; + clear: both; +} + +[dir="rtl"] .horizontal-tabs .horizontal-tabs-list { + border-right: 0; + border-left: 1px solid #dedede; +} + +.horizontal-tabs-pane { + padding: 0 1em; + border: 0; +} + +.horizontal-tabs-pane > summary { + display: none; +} + +/* Layout of each tab */ +.horizontal-tabs .horizontal-tab-button { + background: #eee; + border-right: 1px solid #ccc; /* LTR */ + padding: 1px; + padding-top: 0; + margin: 0; + min-width: 5em; /* IE7 */ + float: left; /* LTR */ +} + +[dir="rtl"] .horizontal-tabs .horizontal-tab-button { + border-right: 0; + border-left: 1px solid #ccc; + float: right; +} + +.horizontal-tabs .horizontal-tab-button a { + display: block; + text-decoration: none; + padding: 0.5em 0.6em; +} + +.horizontal-tabs .horizontal-tab-button a:hover { + outline: none; + background-color: #ededdd; +} + +.horizontal-tabs .horizontal-tab-button li:hover, +.horizontal-tabs .horizontal-tab-button li:focus { + background-color: #ddd; +} + +.horizontal-tabs ul.horizontal-tabs-list :focus { + outline: none; +} + +.horizontal-tab-button a:focus strong, +.horizontal-tab-button a:active strong, +.horizontal-tab-button a:hover strong { + text-decoration: none; + outline: none; +} + +.horizontal-tab-button.selected { + background-color: #fff; + padding: 0 0 1px 0; +} + +[dir="rtl"] .horizontal-tab-button.selected { + border-left-width: 0; + border-right-width: 1px; +} + +.horizontal-tabs ul.horizontal-tabs-list li a, +.horizontal-tabs ul.horizontal-tabs-list li.selected a { + display: block; + text-decoration: none; + padding: 0.5em 0.6em 0.3em 0.6em; + position:relative; + top: 0px; +} + +.horizontal-tab-button .selected strong { + color: #000; +} + +.horizontal-tab-button .summary { + display: block; +} + +.horizontal-tab-button .summary { + line-height: normal; + margin-bottom: 0; +} + +/** + * tab content + */ +div.field-group-htabs-wrapper .field-group-format-wrapper { + clear: both; + padding: 0 0 0.6em; +} + +/*hide*/ +.horizontal-tabs .horizontal-tab-hidden { + display: block; + position: absolute; + top: -100000px; + width: 100%; +} diff --git a/modules/field_group/formatters/tabs/horizontal-tabs.js b/modules/field_group/formatters/tabs/horizontal-tabs.js new file mode 100644 index 00000000..acf08f37 --- /dev/null +++ b/modules/field_group/formatters/tabs/horizontal-tabs.js @@ -0,0 +1,248 @@ +(function ($) { + + 'use strict'; + + Drupal.FieldGroup = Drupal.FieldGroup || {}; + Drupal.FieldGroup.Effects = Drupal.FieldGroup.Effects || {}; + + /** + * This script transforms a set of fieldsets into a stack of horizontal + * tabs. Another tab pane can be selected by clicking on the respective + * tab. + * + * Each tab may have a summary which can be updated by another + * script. For that to work, each fieldset has an associated + * 'horizontalTabCallback' (with jQuery.data() attached to the fieldset), + * which is called every time the user performs an update to a form + * element inside the tab pane. + */ + Drupal.behaviors.horizontalTabs = { + attach: function (context) { + + var width = drupalSettings.widthBreakpoint || 640; + var mq = '(max-width: ' + width + 'px)'; + + if (window.matchMedia(mq).matches) { + return; + } + + $(context).find('[data-horizontal-tabs-panes]').once('horizontal-tabs').each(function () { + + var $this = $(this).addClass('horizontal-tabs-panes'); + var focusID = $(':hidden.horizontal-tabs-active-tab', this).val(); + var tab_focus; + + // Check if there are some details that can be converted to horizontal-tabs + var $details = $this.find('> details'); + if ($details.length === 0) { + return; + } + + // If collapse.js did not do his work yet, call it directly. + if (!$($details[0]).hasClass('.collapse-processed')) { + Drupal.behaviors.collapse.attach(context); + } + + // Create the tab column. + var tab_list = $('
    '); + $(this).wrap('
    ').before(tab_list); + + // Transform each details into a tab. + $details.each(function (i) { + var $this = $(this); + var summaryElement = $this.find('> summary .details-title'); + + if (!summaryElement.length) { + summaryElement = $this.find('> summary'); + } + + var summary = summaryElement.clone().children().remove().end().text(); + var horizontal_tab = new Drupal.horizontalTab({ + title: $.trim(summary), + details: $this + }); + horizontal_tab.item.addClass('horizontal-tab-button-' + i); + tab_list.append(horizontal_tab.item); + $this + .removeClass('collapsed') + // prop() can't be used on browsers not supporting details element, + // the style won't apply to them if prop() is used. + .attr('open', true) + .addClass('horizontal-tabs-pane') + .data('horizontalTab', horizontal_tab); + if (this.id === focusID) { + tab_focus = $this; + } + }); + + $(tab_list).find('> li:first').addClass('first'); + $(tab_list).find('> li:last').addClass('last'); + + if (!tab_focus) { + // If the current URL has a fragment and one of the tabs contains an + // element that matches the URL fragment, activate that tab. + var hash = window.location.hash.replace(/[=%;,\/]/g, ''); + if (hash !== '#' && $(hash, this).length) { + tab_focus = $(window.location.hash, this).closest('.horizontal-tabs-pane'); + } + else { + tab_focus = $this.find('> .horizontal-tabs-pane:first'); + } + } + if (tab_focus.length) { + tab_focus.data('horizontalTab').focus(); + } + }); + } + }; + + /** + * The horizontal tab object represents a single tab within a tab group. + * + * @param {object} settings + * An object with the following keys: + * - title: The name of the tab. + * - details: The jQuery object of the details element that is the tab pane. + */ + Drupal.horizontalTab = function (settings) { + var self = this; + $.extend(this, settings, Drupal.theme('horizontalTab', settings)); + + this.link.attr('href', '#' + settings.details.attr('id')); + + this.link.on('click', function (e) { + e.preventDefault(); + self.focus(); + }); + + // Keyboard events added: + // Pressing the Enter key will open the tab pane. + this.link.on('keydown', function (event) { + event.preventDefault(); + if (event.keyCode === 13) { + self.focus(); + // Set focus on the first input field of the visible details/tab pane. + $('.horizontal-tabs-pane :input:visible:enabled:first').trigger('focus'); + } + }); + + // Only bind update summary on forms. + if (this.details.drupalGetSummary) { + this.details + .on('summaryUpdated', function () { + self.updateSummary(); + }) + .trigger('summaryUpdated'); + } + + }; + + Drupal.horizontalTab.prototype = { + + /** + * Displays the tab's content pane. + */ + focus: function () { + this.details + .removeClass('horizontal-tab-hidden') + .siblings('.horizontal-tabs-pane') + .each(function () { + var tab = $(this).data('horizontalTab'); + tab.details.addClass('horizontal-tab-hidden'); + tab.item.removeClass('selected'); + }) + .end() + .siblings(':hidden.horizontal-tabs-active-tab') + .val(this.details.attr('id')); + this.item.addClass('selected'); + // Mark the active tab for screen readers. + $('#active-horizontal-tab').remove(); + this.link.append('' + Drupal.t('(active tab)') + ''); + }, + + /** + * Updates the tab's summary. + */ + updateSummary: function () { + this.summary.html(this.details.drupalGetSummary()); + }, + + /** + * Shows a horizontal tab pane. + * + * @return {Drupal.horizontalTab} The current horizontal tab. + */ + tabShow: function () { + // Display the tab. + this.item.removeClass('horizontal-tab-hidden'); + // Update .first marker for items. We need recurse from parent to retain the + // actual DOM element order as jQuery implements sortOrder, but not as public + // method. + this.item.parent().children('.horizontal-tab-button').removeClass('first') + .filter(':visible:first').addClass('first'); + // Display the details element. + this.details.removeClass('horizontal-tab-hidden'); + // Focus this tab. + this.focus(); + return this; + }, + + /** + * Hides a horizontal tab pane. + * + * @return {Drupal.horizontalTab} The current horizontal tab. + */ + tabHide: function () { + // Hide this tab. + this.item.addClass('horizontal-tab-hidden'); + // Update .first marker for items. We need recurse from parent to retain the + // actual DOM element order as jQuery implements sortOrder, but not as public + // method. + this.item.parent().children('.horizontal-tab-button').removeClass('first') + .filter(':visible:first').addClass('first'); + // Hide the details element. + this.details.addClass('horizontal-tab-hidden'); + // Focus the first visible tab (if there is one). + var $firstTab = this.details.siblings('.horizontal-tabs-pane:not(.horizontal-tab-hidden):first'); + if ($firstTab.length) { + $firstTab.data('horizontalTab').focus(); + } + else { + // Hide the vertical tabs (if no tabs remain). + this.item.closest('.form-type-horizontal-tabs').hide(); + } + return this; + } + }; + + /** + * Theme function for a horizontal tab. + * + * @param {object} settings + * An object with the following keys: + * - title: The name of the tab. + * @return {object} + * This function has to return an object with at least these keys: + * - item: The root tab jQuery element + * - link: The anchor tag that acts as the clickable area of the tab + * (jQuery version) + * - summary: The jQuery element that contains the tab summary + */ + Drupal.theme.horizontalTab = function (settings) { + var tab = {}; + var idAttr = settings.details.attr('id'); + + tab.item = $('
  • ') + .append(tab.link = $('') + .append(tab.title = $('').text(settings.title)) + ); + + // No need to add summary on frontend. + if (settings.details.drupalGetSummary) { + tab.link.append(tab.summary = $('')); + } + + return tab; + }; + +})(jQuery, Modernizr); diff --git a/modules/field_group/formatters/tabs/tabs.js b/modules/field_group/formatters/tabs/tabs.js new file mode 100644 index 00000000..c2c5b5d3 --- /dev/null +++ b/modules/field_group/formatters/tabs/tabs.js @@ -0,0 +1,39 @@ +(function ($) { + + 'use strict'; + + Drupal.FieldGroup = Drupal.FieldGroup || {}; + Drupal.FieldGroup.Effects = Drupal.FieldGroup.Effects || {}; + + /** + * Implements Drupal.FieldGroup.processHook(). + */ + Drupal.FieldGroup.Effects.processTabs = { + execute: function (context, settings, group_info) { + + if (group_info.context === 'form') { + + // Add required fields mark to any element containing required fields + var direction = group_info.settings.direction; + $(context).find('[data-' + direction + '-tabs-panes] details').once('fieldgroup-effects').each(function () { + + var $this = $(this); + if (typeof $(this).data(direction + 'Tab') !== 'undefined') { + + if ($this.is('.required-fields') && ($this.find('[required]').length > 0 || $this.find('.form-required').length > 0)) { + $this.data(direction + 'Tab').link.find('strong:first').addClass('form-required'); + } + + if ($('.error', $this).length) { + $this.data(direction + 'Tab').link.parent().addClass('error'); + Drupal.FieldGroup.setGroupWithfocus($this); + $this.data(direction + 'Tab').focus(); + } + } + }); + + } + } + }; + +})(jQuery, Modernizr); diff --git a/modules/field_group/includes/field_ui.inc b/modules/field_group/includes/field_ui.inc new file mode 100644 index 00000000..6a3cf76a --- /dev/null +++ b/modules/field_group/includes/field_ui.inc @@ -0,0 +1,579 @@ +entity_type = $display->getTargetEntityTypeId(); + $params->bundle = $display->getTargetBundle(); + $params->region_callback = 'field_group_display_overview_row_region'; + $params->mode = $display->getMode(); + $params->context = field_group_get_context_from_display($display); + + $params->groups = array(); + $params->groups = field_group_info_groups($params->entity_type, $params->bundle, $params->context, $params->mode); + + // Gather parenting data. + $params->parents = array(); + foreach ($params->groups as $name => $group) { + foreach ($group->children as $child) { + $params->parents[$child] = $name; + } + } + + return $params; +} + +/** + * Helper function to get context from entity display. + * + * @param \Drupal\Core\Entity\EntityDisplayBase $display + * + * @return string + */ +function field_group_get_context_from_display(\Drupal\Core\Entity\EntityDisplayBase $display) { + if ($display instanceof \Drupal\Core\Entity\Display\EntityFormDisplayInterface) { + return 'form'; + } + elseif ($display instanceof \Drupal\Core\Entity\Display\EntityViewDisplayInterface) { + return 'view'; + } + + throw new LogicException('Unknown display object.'); +} + +/** + * Function to alter the display overview screens. + */ +function field_group_field_ui_display_form_alter(&$form, FormStateInterface $form_state) { + // Only start altering the form if we need to. + if (empty($form['#fields']) && empty($form['#extra'])) { + return; + } + + $callback_object = $form_state->getBuildInfo()['callback_object']; + if (!$callback_object instanceof EntityDisplayFormBase) { + throw new InvalidArgumentException('Unkown callback object.'); + } + + $display = $callback_object->getEntity(); + + $params = field_group_field_ui_form_params($form, $display); + $form['#fieldgroups'] = array_keys($params->groups); + $form['#context'] = $display; + + $table = &$form['fields']; + $form_state_values = $form_state->getValues(); + $field_group_form_state = $form_state->get('field_group'); + + if ($field_group_form_state == NULL) { + $field_group_form_state = $params->groups; + } + + $table['#parent_options'] = []; + + // Extend available parenting options. + foreach ($field_group_form_state as $name => $group) { + $table['#parent_options'][$name] = $group->label; + } + + // Update existing rows accordingly to the parents. + foreach (Element::children($table) as $name) { + $table[$name]['parent_wrapper']['parent']['#options'] = $table['#parent_options']; + // Inherit the value of the parent when default value is empty. + if (empty($table[$name]['parent_wrapper']['parent']['#default_value'])) { + $table[$name]['parent_wrapper']['parent']['#default_value'] = isset($params->parents[$name]) ? $params->parents[$name] : ''; + } + } + + $formatter_options = field_group_field_formatter_options($params->context); + + $refresh_rows = isset($form_state_values['refresh_rows']) ? $form_state_values['refresh_rows'] : (isset($form_state->getUserInput()['refresh_rows']) ? $form_state->getUserInput()['refresh_rows'] : NULL); + // Create the group rows and check actions. + foreach ($form['#fieldgroups'] as $name) { + $group = &$field_group_form_state[$name]; + + // Check the currently selected formatter, and merge persisted values for + // formatter settings for the group. + // This needs to be done first, so all fields are updated before creating form elements. + if (isset($refresh_rows) && $refresh_rows == $name) { + $settings = isset($form_state_values['fields'][$name]) ? $form_state_values['fields'][$name] : (isset($form_state->getUserInput()['fields'][$name]) ? $form_state->getUserInput()['fields'][$name] : NULL); + if (array_key_exists('settings_edit', $settings)) { + $group = $field_group_form_state[$name]; + } + field_group_formatter_row_update($group, $settings); + } + + // Save the group when the configuration is submitted. + if (!empty($form_state_values[$name . '_plugin_settings_update'])) { + field_group_formatter_settings_update($group, $form_state_values['fields'][$name]); + } + // After all updates are finished, let the form_state know. + $field_group_form_state[$name] = $group; + + $settings = field_group_format_settings_form($group, $form, $form_state); + + $id = strtr($name, '_', '-'); + $js_rows_data[$id] = array('type' => 'group', 'name' => $name); + // A group cannot be selected as its own parent. + $parent_options = $table['#parent_options']; + unset($parent_options[$name]); + $table[$name] = array( + '#attributes' => array('class' => array('draggable', 'field-group'), 'id' => $id), + '#row_type' => 'group', + '#region_callback' => $params->region_callback, + '#js_settings' => array('rowHandler' => 'group'), + 'human_name' => array( + '#markup' => Html::escape(t($group->label)), + '#prefix' => '', + '#suffix' => '', + ), + 'weight' => array( + '#type' => 'textfield', + '#default_value' => $group->weight, + '#size' => 3, + '#attributes' => array('class' => array('field-weight')), + ), + 'parent_wrapper' => array( + 'parent' => array( + '#type' => 'select', + '#options' => $parent_options, + '#empty_value' => '', + '#default_value' => isset($params->parents[$name]) ? $params->parents[$name] : '', + '#attributes' => array('class' => array('field-parent')), + '#parents' => array('fields', $name, 'parent'), + ), + 'hidden_name' => array( + '#type' => 'hidden', + '#default_value' => $name, + '#attributes' => array('class' => array('field-name')), + ), + ), + ); + + // For view settings. Add a spacer cell. We can't use colspan because of the javascript . + if ($params->context == 'view') { + $table[$name] += array( + 'spacer' => array( + '#markup' => ' ' + ) + ); + } + + $table[$name] += array( + 'format' => array( + 'type' => array( + '#type' => 'select', + '#options' => $formatter_options, + '#default_value' => $group->format_type, + '#attributes' => array('class' => array('field-group-type')), + ), + ), + ); + + $base_button = array( + '#submit' => array( + array($form_state->getBuildInfo()['callback_object'], 'multistepSubmit') + ), + '#ajax' => array( + 'callback' => array($form_state->getBuildInfo()['callback_object'], 'multistepAjax'), + 'wrapper' => 'field-display-overview-wrapper', + 'effect' => 'fade', + ), + '#field_name' => $name, + ); + + if ($form_state->get('plugin_settings_edit') == $name) { + $table[$name]['format']['#cell_attributes'] = array('colspan' => 2); + $table[$name]['format']['format_settings'] = array( + '#type' => 'container', + '#attributes' => array('class' => array('field-plugin-settings-edit-form')), + '#parents' => array('fields', $name, 'settings_edit_form'), + '#weight' => -5, + 'label' => array( + '#markup' => t('Field group format:') . ' ' . $group->format_type . '', + ), + // Create a settings form where hooks can pick in. + 'settings' => $settings, + 'actions' => array( + '#type' => 'actions', + 'save_settings' => $base_button + array( + '#type' => 'submit', + '#name' => $name . '_plugin_settings_update', + '#value' => t('Update'), + '#op' => 'update', + ), + 'cancel_settings' => $base_button + array( + '#type' => 'submit', + '#name' => $name . '_plugin_settings_cancel', + '#value' => t('Cancel'), + '#op' => 'cancel', + // Do not check errors for the 'Cancel' button. + '#limit_validation_errors' => array(), + ), + ), + ); + $table[$name]['#attributes']['class'][] = 'field-formatter-settings-editing'; + $table[$name]['format']['type']['#attributes']['class'] = array('visually-hidden'); + } + else { + // After saving, the settings are updated here aswell. First we create + // the element for the table cell. + $table[$name]['settings_summary'] = array('#markup' => ''); + if (!empty($group->format_settings)) { + $table[$name]['settings_summary'] = field_group_format_settings_summary($name, $group); + } + // Add the configure button. + $table[$name]['settings_edit'] = $base_button + array( + '#type' => 'image_button', + '#name' => $name . '_group_settings_edit', + '#src' => 'core/misc/icons/787878/cog.svg', + '#attributes' => array('class' => array('field-plugin-settings-edit'), 'alt' => t('Edit')), + '#op' => 'edit', + // Do not check errors for the 'Edit' button, but make sure we get + // the value of the 'plugin type' select. + '#limit_validation_errors' => array(array('fields', $name, 'type')), + '#prefix' => '
    ', + '#suffix' => '
    ', + ); + + $delete_route = \Drupal\field_group\FieldgroupUi::getDeleteRoute($group); + + $table[$name]['settings_edit']['#suffix'] .= Drupal::l(t('delete'), $delete_route); + } + + $form_state->set('field_group', $field_group_form_state); + + } + + // Additional row: add new group. + $parent_options = $table['#parent_options']; + + $form['#attached']['library'][] = 'field_group/field_ui'; + + array_unshift($form['actions']['submit']['#submit'], 'field_group_field_overview_submit'); + + // Create the settings for fieldgroup as vertical tabs (merged with DS). + field_group_field_ui_create_vertical_tabs($form, $form_state, $params); + + // Show a warning if the user has not set up required containers + if ($form['#fieldgroups']) { + + $parent_requirements = array( + 'accordion-item' => array( + 'parent' => 'accordion', + 'message' => 'Each Accordion item element needs to have a parent Accordion group element.', + ), + ); + + // On display overview tabs need to be checked. + if (field_group_get_context_from_display($display) == 'view') { + $parent_requirements['tab'] = array( + 'parent' => 'tabs', + 'message' => 'Each tab element needs to have a parent tabs group element.', + ); + } + + foreach ($form['#fieldgroups'] as $group_name) { + $group_check = field_group_load_field_group($group_name, $params->entity_type, $params->bundle, $params->context, $params->mode); + if (isset($parent_requirements[$group_check->format_type])) { + if (!$group_check->parent_name || field_group_load_field_group($group_check->parent_name, $params->entity_type, $params->bundle, $params->context, $params->mode)->format_type != $parent_requirements[$group_check->format_type]['parent']) { + drupal_set_message(t($parent_requirements[$group_check->format_type]['message']), 'warning', FALSE); + } + } + } + } +} + +/** + * Create vertical tabs. + */ +function field_group_field_ui_create_vertical_tabs(&$form, &$form_state, $params) { + + $form_state->set('field_group_params', $params); + + $existing_group_config = \Drupal::configFactory()->listAll('field_group.' . $params->entity_type . '.' . $params->bundle); + $displays = array(); + foreach ($existing_group_config as $config) { + $group = \Drupal::config($config)->get(); + if ($group['context'] == $params->context && $group['mode'] == $params->mode) { + continue; + } + $displays[$group['context'] . '.' . $group['mode']] = $group['context'] . ':' . $group['mode']; + } + + // No displays to clone. + if (empty($displays)) { + return; + } + + // Add additional settings vertical tab. + if (!isset($form['additional_settings'])) { + $form['additional_settings'] = array( + '#type' => 'vertical_tabs', + '#theme_wrappers' => array('vertical_tabs'), + '#prefix' => '
    ', + '#suffix' => '
    ', + '#tree' => TRUE, + ); + } + + // Add extra guidelines for webmaster. + $form['field_group'] = array( + '#type' => 'details', + '#group' => 'additional_settings', + '#title' => t('Fieldgroups'), + '#description' => t('

    Fields can be dragged into groups with unlimited nesting. Each fieldgroup format comes with a configuration form, specific for that format type.
    Note that some formats come in pair. These types have a html wrapper to nest its fieldgroup children. E.g. Place accordion items into the accordion, vertical tabs in vertical tab group and horizontal tabs in the horizontal tab group. There is one exception to this rule, you can use a vertical tab without a wrapper when the additional settings tabs are available. E.g. node forms.

    '), + '#collapsible' => TRUE, + '#open' => TRUE, + ); + $form['field_group']['fieldgroup_clone'] = array( + '#title' => t('Select source display'), + '#description' => t('Clone fieldgroups from selected display to the current display'), + '#type' => 'select', + '#options' => $displays, + '#default_value' => 'none' + ); + $form['field_group']['fieldgroup_submit'] = array( + '#type' => 'submit', + '#value' => t('Clone'), + '#validate' => array('field_group_field_ui_clone_field_groups_validate'), + '#submit' => array('field_group_field_ui_clone_field_groups') + ); + +} + +/** + * Returns the region to which a row in the 'Manage display' screen belongs. + * @param Array $row A field or field_group row + * @return String the current region. + */ +function field_group_display_overview_row_region($row) { + switch ($row['#row_type']) { + case 'group': + return ($row['format']['type']['#value'] == 'hidden' ? 'hidden' : 'content'); + } +} + +/** + * Submit handler for the overview screens. + * @param Array $form The complete form. + * @param FormStateInterface $form_state The state of the form. + */ +function field_group_field_overview_submit($form, FormStateInterface $form_state) { + $form_values = $form_state->getValue('fields'); + $fields_added = $form_state->getValue('fields_added'); + + /** + * @var \Drupal\Core\Entity\EntityDisplayBase $display + */ + $display = $form['#context']; + + $entity_type = $display->get('targetEntityType'); + $bundle = $display->get('bundle'); + $mode = $display->get('mode'); + $context = field_group_get_context_from_display($display); + + // Collect children. + $children = array_fill_keys($form['#fieldgroups'], array()); + foreach ($form_values as $name => $value) { + if (!empty($value['parent'])) { + $children[$value['parent']][$name] = $name; + } + } + + // Update existing groups. + $groups = field_group_info_groups($entity_type, $bundle, $context, $mode, TRUE); + $field_group_form_state = $form_state->get('field_group'); + if (!empty($field_group_form_state)) { + foreach ($form['#fieldgroups'] as $group_name) { + + // Only save updated groups. + if (!isset($field_group_form_state[$group_name])) { + continue; + } + + $group = $groups[$group_name]; + $group->label = $field_group_form_state[$group_name]->label; + $group->children = array_keys($children[$group_name]); + $group->parent_name = $form_values[$group_name]['parent']; + $group->weight = $form_values[$group_name]['weight']; + + $old_format_type = $group->format_type; + $group->format_type = isset($form_values[$group_name]['format']['type']) ? $form_values[$group_name]['format']['type'] : 'visible'; + if (isset($field_group_form_state[$group_name]->format_settings)) { + $group->format_settings = $field_group_form_state[$group_name]->format_settings; + } + + // If the format type is changed, make sure we have all required format settings. + if ($group->format_type != $old_format_type) { + $default_formatter_settings = _field_group_get_default_formatter_settings($group->format_type, $context); + $group->format_settings += $default_formatter_settings; + } + + /** @var EntityFormInterface $entity_form */ + $entity_form = $form_state->getFormObject(); + + /** @var EntityDisplayInterface $display */ + $display = $entity_form->getEntity(); + + field_group_group_save($group, $display); + } + } + + \Drupal::cache()->invalidate('field_groups'); +} + +/** + * Creates a form for field_group formatters. + * @param Object $group The FieldGroup object. + */ +function field_group_format_settings_form(&$group, $form, $form_state) { + $manager = \Drupal::service('plugin.manager.field_group.formatters'); + $plugin = $manager->getInstance(array( + 'format_type' => $group->format_type, + 'configuration' => array('label' => $group->label, 'settings' => $group->format_settings), + 'group' => $group, + )); + + return $plugin->settingsForm($form, $form_state); +} + +/** + * Update the row so that the group variables are updated. + * The rendering of the elements needs the updated defaults. + * @param Object $group + * @param array $settings + */ +function field_group_formatter_row_update(& $group, $settings) { + // if the row has changed formatter type, update the group object + if (!empty($settings['format']['type']) && $settings['format']['type'] != $group->format_type) { + $group->format_type = $settings['format']['type']; + field_group_formatter_settings_update($group, $settings); + } +} + +/** + * Update handler for field_group configuration settings. + * @param Object $group The group object + * @param Array $settings Configuration settings + */ +function field_group_formatter_settings_update(& $group, $settings) { + + // for format changes we load the defaults. + if (empty($settings['settings_edit_form']['settings'])) { + $group->format_settings = _field_group_get_default_formatter_settings($group->format_type, $group->context); + } + else { + $group->format_type = $settings['format']['type']; + $group->label = $settings['settings_edit_form']['settings']['label']; + $group->format_settings = $settings['settings_edit_form']['settings']; + } +} + +/** + * Creates a summary for the field format configuration summary. + * @param String $group_name The name of the group + * @param Object $group The group object + * @return Array ready to be rendered. + */ +function field_group_format_settings_summary($group_name, $group) { + + $manager = \Drupal::service('plugin.manager.field_group.formatters'); + $plugin = $manager->getInstance(array( + 'format_type' => $group->format_type, + 'configuration' => array('label' => $group->label, 'settings' => $group->format_settings), + 'group' => $group, + )); + + $summary = $plugin->settingsSummary(); + + return array( + '#markup' => '
    ' . implode('
    ', $summary) . '
    ', + '#cell_attributes' => array('class' => array('field-plugin-summary-cell')), + ); +} + +/** + * Validate handler to validate saving existing fieldgroups from one view mode or form to another. + */ +function field_group_field_ui_clone_field_groups_validate($form, FormStateInterface $form_state) { + + $form_state_values = $form_state->getValues(); + $field_group_params = $form_state->get('field_group_params'); + + list($context, $mode) = explode('.', $form_state_values['fieldgroup_clone']); + $source_groups = field_group_info_groups($field_group_params->entity_type, $field_group_params->bundle, $context, $mode); + + // Check for types are not known in current mode. + if ($field_group_params->context != 'form') { + $non_existing_types = []; + } + else { + $non_existing_types = ['html_element']; + } + + foreach ($source_groups as $key => $group) { + if (in_array($group->format_type, $non_existing_types)) { + unset($source_groups[$key]); + drupal_set_message(t('Skipping @group because this type does not exist in current mode', array('@group' => $group->label)), 'warning'); + } + } + + if (empty($source_groups)) { + // Report error found with selection. + $form_state->setErrorByName('additional_settings][fieldgroup_clone', t('No field groups were found in selected view mode.')); + return; + } + + $form_state->set('#source_groups', $source_groups); + +} + +/** + * Submit handler to save existing fieldgroups from one view mode or form to another. + */ +function field_group_field_ui_clone_field_groups($form, FormStateInterface $form_state) { + + $fields = array_keys($form_state->getValue('fields')); + $source_groups = $form_state->get('#source_groups'); + if ($source_groups) { + + $field_group_params = $form_state->get('field_group_params'); + foreach ($source_groups as $source_group) { + if (in_array($source_group->group_name, $fields)) { + drupal_set_message(t('Fieldgroup @group is not cloned since a group already exists with the same name.', array('@group' => $source_group->group_name)), 'warning'); + continue; + } + + $source_group->context = $field_group_params->context; + $source_group->mode = $field_group_params->mode; + $source_group->children = array(); + field_group_group_save($source_group); + + drupal_set_message(t('Fieldgroup @group cloned successfully.', array('@group' => $source_group->group_name))); + + } + } + +} diff --git a/modules/field_group/includes/helpers.inc b/modules/field_group/includes/helpers.inc new file mode 100644 index 00000000..7d3b1b7c --- /dev/null +++ b/modules/field_group/includes/helpers.inc @@ -0,0 +1,64 @@ +getDefaultSettings($format_type, $context); +} + +/** + * Return an array of field_group_formatter options. + */ +function field_group_field_formatter_options($type) { + $options = &drupal_static(__FUNCTION__); + + if (!isset($options)) { + $options = array(); + + $manager = Drupal::service('plugin.manager.field_group.formatters'); + $formatters = $manager->getDefinitions(); + + foreach ($formatters as $formatter) { + if (in_array($type, $formatter['supported_contexts'])) { + $options[$formatter['id']] = $formatter['label']; + } + } + } + + return $options; +} + +/** + * Validate the entered css class from the submitted format settings. + * @param Array $element The validated element + * @param FormStateInterface $form_state The state of the form. + */ +function field_group_validate_css_class($element, FormStateInterface $form_state) { + $form_state_values = $form_state->getValues(); + $plugin_name = $form_state->get('plugin_settings_edit'); + if (!empty($form_state_values['fields'][$plugin_name]['settings_edit_form']['settings']['classes']) && !preg_match('!^[A-Za-z0-9-_ ]+$!', $form_state_values['fields'][$plugin_name]['settings_edit_form']['settings']['classes'])) { + Drupal::formBuilder()->setError($element, $form_state, t('The css class must include only letters, numbers, underscores and dashes.')); + } +} + +/** + * Validate the entered id attribute from the submitted format settings. + * @param Array $element The validated element + * @param FormStateInterface $form_state The state of the form. + */ +function field_group_validate_id($element, FormStateInterface $form_state) { + $form_state_values = $form_state->getValues(); + $plugin_name = $form_state->get('plugin_settings_edit'); + if (!empty($form_state_values['fields'][$plugin_name]['settings_edit_form']['settings']['id']) && !preg_match('!^[A-Za-z0-9-_]+$!', $form_state_values['fields'][$plugin_name]['settings_edit_form']['settings']['id'])) { + Drupal::formBuilder()->setError($element, $form_state, t('The id must include only letters, numbers, underscores and dashes.')); + } +} \ No newline at end of file diff --git a/modules/field_group/js/field_group.field_ui.js b/modules/field_group/js/field_group.field_ui.js new file mode 100644 index 00000000..b23a5123 --- /dev/null +++ b/modules/field_group/js/field_group.field_ui.js @@ -0,0 +1,138 @@ +(function ($) { + + 'use strict'; + Drupal.behaviors.fieldUIFieldsOverview = { + attach: function (context, settings) { + $('table#field-overview', context).once('field-field-overview', function () { + Drupal.fieldUIOverview.attach(this, settings.fieldUIRowsData, Drupal.fieldUIFieldOverview); + }); + } + }; + + /** + * Row handlers for the 'Manage fields' screen. + */ + Drupal.fieldUIFieldOverview = Drupal.fieldUIFieldOverview || {}; + + Drupal.fieldUIFieldOverview.group = function (row, data) { + this.row = row; + this.name = data.name; + this.region = data.region; + this.tableDrag = data.tableDrag; + + // Attach change listener to the 'group format' select. + this.$formatSelect = $('select.field-group-type', row); + this.$formatSelect.change(Drupal.fieldUIOverview.onChange); + + return this; + }; + + Drupal.fieldUIFieldOverview.group.prototype = { + getRegion: function () { + return 'main'; + }, + + regionChange: function (region, recurse) { + return {}; + }, + + regionChangeFields: function (region, element, refreshRows) { + + // Create a new tabledrag rowObject, that will compute the group's child + // rows for us. + var tableDrag = element.tableDrag; + var rowObject = new tableDrag.row(element.row, 'mouse', true); + // Skip the main row, we handled it above. + rowObject.group.shift(); + + // Let child rows handlers deal with the region change - without recursing + // on nested group rows, we are handling them all here. + $.each(rowObject.group, function () { + var childRow = this; + var childRowHandler = $(childRow).data('fieldUIRowHandler'); + $.extend(refreshRows, childRowHandler.regionChange(region, false)); + }); + } + }; + + + /** + * Row handlers for the 'Manage display' screen. + */ + Drupal.fieldUIDisplayOverview = Drupal.fieldUIDisplayOverview || {}; + + Drupal.fieldUIDisplayOverview.group = function (row, data) { + this.row = row; + this.name = data.name; + this.region = data.region; + this.tableDrag = data.tableDrag; + + // Attach change listener to the 'group format' select. + this.$formatSelect = $('select.field-group-type', row); + this.$formatSelect.change(Drupal.fieldUIOverview.onChange); + + return this; + }; + + Drupal.fieldUIDisplayOverview.group.prototype = { + getRegion: function () { + return (this.$formatSelect.val() === 'hidden') ? 'hidden' : 'content'; + }, + + regionChange: function (region, recurse) { + + // Default recurse to true. + recurse = (typeof recurse === 'undefined') || recurse; + + // When triggered by a row drag, the 'format' select needs to be adjusted to + // the new region. + var currentValue = this.$formatSelect.val(); + var value; + switch (region) { + case 'visible': + if (currentValue === 'hidden') { + // Restore the group format back to 'fieldset'. + value = 'fieldset'; + } + break; + + default: + value = 'hidden'; + break; + } + if (typeof value !== 'undefined') { + this.$formatSelect.val(value); + } + + var refreshRows = {}; + refreshRows[this.name] = this.$formatSelect.get(0); + + if (recurse) { + this.regionChangeFields(region, this, refreshRows); + } + + return refreshRows; + }, + + regionChangeFields: function (region, element, refreshRows) { + + // Create a new tabledrag rowObject, that will compute the group's child + // rows for us. + var tableDrag = element.tableDrag; + var rowObject = new tableDrag.row(element.row, 'mouse', true); + // Skip the main row, we handled it above. + rowObject.group.shift(); + + // Let child rows handlers deal with the region change - without recursing + // on nested group rows, we are handling them all here. + $.each(rowObject.group, function () { + var childRow = this; + var childRowHandler = $(childRow).data('fieldUIRowHandler'); + $.extend(refreshRows, childRowHandler.regionChange(region, false)); + }); + + } + + }; + +})(jQuery); diff --git a/modules/field_group/js/field_group.js b/modules/field_group/js/field_group.js new file mode 100644 index 00000000..8933dc65 --- /dev/null +++ b/modules/field_group/js/field_group.js @@ -0,0 +1,58 @@ +(function ($) { + + 'use strict'; + + /** + * Drupal FieldGroup object. + */ + Drupal.FieldGroup = Drupal.FieldGroup || {}; + Drupal.FieldGroup.Effects = Drupal.FieldGroup.Effects || {}; + Drupal.FieldGroup.groupWithfocus = null; + + Drupal.FieldGroup.setGroupWithfocus = function (element) { + element.css({display: 'block'}); + Drupal.FieldGroup.groupWithfocus = element; + }; + + /** + * Behaviors. + */ + Drupal.behaviors.fieldGroup = { + attach: function (context, settings) { + + settings.field_group = settings.field_group || drupalSettings.field_group; + if (typeof settings.field_group === 'undefined') { + return; + } + + // Execute all of them. + $.each(Drupal.FieldGroup.Effects, function (func) { + // We check for a wrapper function in Drupal.field_group as + // alternative for dynamic string function calls. + var type = func.toLowerCase().replace('process', ''); + if (typeof settings.field_group[type] !== 'undefined' && $.isFunction(this.execute)) { + this.execute(context, settings, settings.field_group[type]); + } + }); + + // Add a new ID to each fieldset. + $('.group-wrapper fieldset').each(function () { + // Tats bad, but we have to keep the actual id to prevent layouts to break. + var fieldgroupID = 'field_group-' + $(this).attr('id') + ' ' + $(this).attr('id'); + $(this).attr('id', fieldgroupID); + }); + + // Set the hash in url to remember last userselection. + $('.group-wrapper ul li').each(function () { + var fieldGroupNavigationListIndex = $(this).index(); + $(this).children('a').click(function () { + var fieldset = $('.group-wrapper fieldset').get(fieldGroupNavigationListIndex); + // Grab the first id, holding the wanted hashurl. + var hashUrl = $(fieldset).attr('id').replace(/^field_group-/, '').split(' ')[0]; + window.location.hash = hashUrl; + }); + }); + } + }; + +})(jQuery); diff --git a/modules/field_group/src/Annotation/FieldGroupFormatter.php b/modules/field_group/src/Annotation/FieldGroupFormatter.php new file mode 100644 index 00000000..0e3752d8 --- /dev/null +++ b/modules/field_group/src/Annotation/FieldGroupFormatter.php @@ -0,0 +1,80 @@ + array( + array($class, 'processAccordion'), + ), + '#theme_wrappers' => array('field_group_accordion'), + ); + } + + /** + * Process the accordion item. + * + * @param array $element + * An associative array containing the properties and children of the + * details element. + * @param \Drupal\Core\Form\FormStateInterface $form_state + * The current state of the form. + * + * @return array + * The processed element. + */ + public static function processAccordion(&$element, FormStateInterface $form_state) { + + // Add the jQuery UI accordion. + $element['#attached']['library'][] = 'field_group/formatter.accordion'; + + // Add the effect class. + if (isset($element['#effect'])) { + if (!isset($element['#attributes']['class'])) { + $element['#attributes']['class'] = array(); + } + $element['#attributes']['class'][] = 'effect-' . $element['#effect']; + } + + return $element; + } + +} diff --git a/modules/field_group/src/Element/AccordionItem.php b/modules/field_group/src/Element/AccordionItem.php new file mode 100644 index 00000000..8d6dfe45 --- /dev/null +++ b/modules/field_group/src/Element/AccordionItem.php @@ -0,0 +1,24 @@ + TRUE, + '#theme_wrappers' => array('field_group_accordion_item'), + ); + } + +} diff --git a/modules/field_group/src/Element/HorizontalTabs.php b/modules/field_group/src/Element/HorizontalTabs.php new file mode 100644 index 00000000..f1ee96fe --- /dev/null +++ b/modules/field_group/src/Element/HorizontalTabs.php @@ -0,0 +1,88 @@ + '', + '#process' => array( + array($class, 'processHorizontalTabs'), + ), + '#theme_wrappers' => array('horizontal_tabs'), + ); + } + + /** + * Creates a group formatted as horizontal tabs. + * + * @param array $element + * An associative array containing the properties and children of the + * details element. + * @param \Drupal\Core\Form\FormStateInterface $form_state + * The current state of the form. + * @param bool $on_form + * Are the tabs rendered on a form or not. + * + * @return array + * The processed element. + */ + public static function processHorizontalTabs(&$element, FormStateInterface $form_state, $on_form = TRUE) { + + // Inject a new details as child, so that form_process_details() processes + // this details element like any other details. + $element['group'] = array( + '#type' => 'details', + '#theme_wrappers' => array(), + '#parents' => $element['#parents'], + ); + + // Add an invisible label for accessibility. + if (!isset($element['#title'])) { + $element['#title'] = t('Horizontal Tabs'); + $element['#title_display'] = 'invisible'; + } + + // Add required JavaScript and Stylesheet. + $element['#attached']['library'][] = 'field_group/element.horizontal_tabs'; + + // Only add forms library on forms. + if ($on_form) { + $element['#attached']['library'][] = 'core/drupal.form'; + } + + // The JavaScript stores the currently selected tab in this hidden + // field so that the active tab can be restored the next time the + // form is rendered, e.g. on preview pages or when form validation + // fails. + $name = implode('__', $element['#parents']); + if ($form_state->hasValue($name . '__active_tab')){ + $element['#default_tab'] = $form_state->getValue($name . '__active_tab'); + } + $element[$name . '__active_tab'] = array( + '#type' => 'hidden', + '#default_value' => $element['#default_tab'], + '#attributes' => array('class' => array('horizontal-tabs-active-tab')), + ); + + return $element; + } + +} diff --git a/modules/field_group/src/Element/HtmlElement.php b/modules/field_group/src/Element/HtmlElement.php new file mode 100644 index 00000000..43f34ab5 --- /dev/null +++ b/modules/field_group/src/Element/HtmlElement.php @@ -0,0 +1,65 @@ + array( + array($class, 'processHtmlElement'), + ), + '#theme_wrappers' => array('field_group_html_element'), + ); + } + + /** + * Process a html element + * + * @param array $element + * An associative array containing the properties and children of the + * details element. + * @param FormStateInterface $form_state + * The current state of the form. + * + * @return array + * The processed element. + */ + public static function processHtmlElement(&$element, FormStateInterface $form_state) { + + // If an effect is set, we need to load extra js. + if (!empty($element['#effect']) && $element['#effect'] !== 'none') { + + $element['#attached']['library'][] = 'field_group/formatter.html_element'; + + // Add the required classes for the js. + $element['#attributes']['class'][] = 'fieldgroup-collapsible'; + $element['#attributes']['class'][] = 'effect-' . $element['#effect']; + if (!empty($element['#speed'])) { + $element['#attributes']['class'][] = 'speed-' . $element['#speed']; + } + + // Add jquery ui effects library for the blind effect. + if ($element['#effect'] == 'blind') { + $element['#attached']['library'][] = 'core/jquery.ui.effects.blind'; + } + + } + + return $element; + } + +} diff --git a/modules/field_group/src/FieldGroupFormatterBase.php b/modules/field_group/src/FieldGroupFormatterBase.php new file mode 100644 index 00000000..b9028c9b --- /dev/null +++ b/modules/field_group/src/FieldGroupFormatterBase.php @@ -0,0 +1,179 @@ +group = $group; + $this->settings = $settings; + $this->label = $label; + $this->context = $group->context; + } + + /** + * Get the current label. + * @return string + */ + public function getLabel() { + return $this->label; + } + + /** + * {@inheritdoc} + */ + public function settingsForm() { + + $form = array(); + $form['label'] = array( + '#type' => 'textfield', + '#title' => t('Field group label'), + '#default_value' => $this->label, + '#weight' => -5, + ); + + $form['id'] = array( + '#title' => t('ID'), + '#type' => 'textfield', + '#default_value' => $this->getSetting('id'), + '#weight' => 10, + '#element_validate' => array('field_group_validate_id'), + ); + + $form['classes'] = array( + '#title' => t('Extra CSS classes'), + '#type' => 'textfield', + '#default_value' => $this->getSetting('classes'), + '#weight' => 11, + '#element_validate' => array('field_group_validate_css_class'), + ); + + return $form; + + } + + /** + * {@inheritdoc} + */ + public function settingsSummary() { + + $summary = array(); + + if ($this->getSetting('formatter')) { + $summary[] = $this->pluginDefinition['label'] . ': ' . $this->getSetting('formatter'); + } + + if ($this->getSetting('id')) { + $summary[] = $this->t('Id: @id', array('@id' => $this->getSetting('id'))); + } + + if ($this->getSetting('classes')) { + $summary[] = \Drupal::translation()->translate('Extra CSS classes: @classes', array('@classes' => $this->getSetting('classes'))); + } + + return $summary; + } + + /** + * {@inheritdoc} + */ + public static function defaultSettings() { + return self::defaultContextSettings('view'); + } + + /** + * {@inheritdoc} + */ + public static function defaultContextSettings($context) { + return array( + 'classes' => '', + 'id' => '', + ); + } + + /** + * Get the classes to add to the group. + */ + protected function getClasses() { + + $classes = array(); + // Add a required-fields class to trigger the js. + if ($this->getSetting('required_fields')) { + $classes[] = 'required-fields'; + $classes[] = 'field-group-' . str_replace('_', '-', $this->getBaseId()); + } + + if ($this->getSetting('classes')) { + $classes = array_merge($classes, explode(' ', trim($this->getSetting('classes')))); + } + + return $classes; + } + + /** + * {@inheritdoc} + */ + public function preRender(&$element, $rendering_object) { + $element['#group_name'] = $this->group->group_name; + $element['#entity_type'] = $this->group->entity_type; + $element['#bundle'] = $this->group->bundle; + } + +} diff --git a/modules/field_group/src/FieldGroupFormatterInterface.php b/modules/field_group/src/FieldGroupFormatterInterface.php new file mode 100644 index 00000000..538e8007 --- /dev/null +++ b/modules/field_group/src/FieldGroupFormatterInterface.php @@ -0,0 +1,58 @@ +alterInfo('field_group_formatter_info'); + $this->setCacheBackend($cache_backend, 'field_group_formatter_info'); + } + + /** + * {@inheritdoc} + */ + public function createInstance($plugin_id, array $configuration = array()) { + $plugin_definition = $this->getDefinition($plugin_id); + $plugin_class = DefaultFactory::getPluginClass($plugin_id, $plugin_definition); + + // If the plugin provides a factory method, pass the container to it. + if (is_subclass_of($plugin_class, 'Drupal\Core\Plugin\ContainerFactoryPluginInterface')) { + return $plugin_class::create(\Drupal::getContainer(), $configuration, $plugin_id, $plugin_definition); + } + + return new $plugin_class($plugin_id, $plugin_definition, $configuration['group'], $configuration['settings'], $configuration['label']); + } + + /** + * Overrides PluginManagerBase::getInstance(). + * + * @param array $options + * An array with the following key/value pairs: + * - format_type: The current format type. + * - group: The current group. + * - prepare: (bool, optional) Whether default values should get merged in + * the 'configuration' array. Defaults to TRUE. + * - configuration: (array) the configuration for the formatter. The + * following key value pairs are allowed, and are all optional if + * 'prepare' is TRUE: + * - label: (string) Position of the label. The default 'field' theme + * implementation supports the values 'inline', 'above' and 'hidden'. + * Defaults to 'above'. + * - settings: (array) Settings specific to the formatter. Each setting + * defaults to the default value specified in the formatter definition. + * + * @return \Drupal\field_group\FieldGroupFormatterInterface|null + * A formatter object or NULL when plugin is not found. + */ + public function getInstance(array $options) { + $configuration = $options['configuration']; + $format_type = $options['format_type']; + $context = $options['group']->context; + + // Fill in default configuration if needed. + if (!isset($options['prepare']) || $options['prepare'] == TRUE) { + $configuration = $this->prepareConfiguration($format_type, $context, $configuration); + } + + $plugin_id = $format_type; + + // Validate if plugin exists and it's allowed for current context. + $definition = $this->getDefinition($format_type, FALSE); + if (!isset($definition['class']) || !in_array($context, $definition['supported_contexts'])) { + return NULL; + } + + $configuration += array( + 'group' => $options['group'], + ); + + return $this->createInstance($plugin_id, $configuration); + } + + /** + * Merges default values for formatter configuration. + * + * @param string $format_type + * The format type + * @param string $context + * The context to prepare configuration for. + * @param array $properties + * An array of formatter configuration. + * + * @return array + * The display properties with defaults added. + */ + public function prepareConfiguration($format_type, $context, array $configuration) { + // Fill in defaults for missing properties. + $configuration += array( + 'label' => '', + 'settings' => array(), + ); + + // Fill in default settings values for the formatter. + $configuration['settings'] += $this->getDefaultSettings($format_type, $context); + + return $configuration; + } + + /** + * Returns the default settings of a field_group formatter. + * + * @param string $type + * A formatter type name. + * @param string $context + * The context to get default values for. + * + * @return array + * The formatter type's default settings, as provided by the plugin + * definition, or an empty array if type or settings are undefined. + */ + public function getDefaultSettings($type, $context) { + $plugin_definition = $this->getDefinition($type, FALSE); + if (!empty($plugin_definition['class'])) { + $plugin_class = DefaultFactory::getPluginClass($type, $plugin_definition); + return $plugin_class::defaultContextSettings($context); + } + return array(); + } + +} diff --git a/modules/field_group/src/FieldgroupUi.php b/modules/field_group/src/FieldgroupUi.php new file mode 100644 index 00000000..fa9514a6 --- /dev/null +++ b/modules/field_group/src/FieldgroupUi.php @@ -0,0 +1,97 @@ +getDefinition($group->entity_type); + if ($entity_type->get('field_ui_base_route')) { + + $context_route_name = ""; + $mode_route_name = "default"; + $route_parameters = FieldUI::getRouteBundleParameter($entity_type, $group->bundle); + + // Get correct route name based on context and mode. + if ($group->context == 'form') { + $context_route_name = 'entity_form_display'; + + if ($group->mode != 'default') { + $mode_route_name = 'form_mode'; + $route_parameters['form_mode_name'] = $group->mode; + } + + } + else { + $context_route_name = 'entity_view_display'; + + if ($group->mode != 'default') { + $mode_route_name = 'view_mode'; + $route_parameters['view_mode_name'] = $group->mode; + } + + } + + return new Url("entity.{$context_route_name}.{$group->entity_type}.{$mode_route_name}", $route_parameters); + } + } + + /** + * Get the field group delete route for a given group. + * @param \stdClass $group + * + * @return \Drupal\Core\Url + * A URL object. + */ + public static function getDeleteRoute($group) { + + $entity_type_id = $group->entity_type; + $entity_type = \Drupal::entityTypeManager()->getDefinition($entity_type_id); + if ($entity_type->get('field_ui_base_route')) { + + $mode_route_name = ''; + $route_parameters = FieldUI::getRouteBundleParameter($entity_type, $group->bundle); + $route_parameters['field_group_name'] = $group->group_name; + + // Get correct route name based on context and mode. + if ($group->context == 'form') { + + $context_route_name = 'form_display'; + if ($group->mode != 'default') { + $mode_route_name = '.form_mode'; + $route_parameters['form_mode_name'] = $group->mode; + } + + } + else { + + $context_route_name = 'display'; + if ($group->mode != 'default') { + $mode_route_name = '.view_mode'; + $route_parameters['view_mode_name'] = $group->mode; + } + + } + + return new Url('field_ui.field_group_delete_' . $entity_type_id . '.' . $context_route_name . $mode_route_name, $route_parameters); + } + + throw new \InvalidArgumentException('The given group is not a valid.'); + + } + +} \ No newline at end of file diff --git a/modules/field_group/src/Form/FieldGroupAddForm.php b/modules/field_group/src/Form/FieldGroupAddForm.php new file mode 100644 index 00000000..de37914c --- /dev/null +++ b/modules/field_group/src/Form/FieldGroupAddForm.php @@ -0,0 +1,290 @@ +mode = \Drupal::request()->get('form_mode_name'); + } + else { + $this->mode = \Drupal::request()->get('view_mode_name'); + } + + if (empty($this->mode)) { + $this->mode = 'default'; + } + + if (!$form_state->get('context')) { + $form_state->set('context', $context); + } + if (!$form_state->get('entity_type_id')) { + $form_state->set('entity_type_id', $entity_type_id); + } + if (!$form_state->get('bundle')) { + $form_state->set('bundle', $bundle); + } + if (!$form_state->get('step')) { + $form_state->set('step', 'formatter'); + } + + $this->entityTypeId = $form_state->get('entity_type_id'); + $this->bundle = $form_state->get('bundle'); + $this->context = $form_state->get('context'); + $this->currentStep = $form_state->get('step'); + + if ($this->currentStep == 'formatter') { + $this->buildFormatterSelectionForm($form, $form_state); + } + else { + $this->buildConfigurationForm($form, $form_state); + } + + return $form; + + } + + /** + * Build the formatter selection step. + */ + function buildFormatterSelectionForm(array &$form, FormStateInterface $form_state) { + + // Gather group formatters. + $formatter_options = \field_group_field_formatter_options($form_state->get('context')); + $form['add'] = array( + '#type' => 'container', + '#attributes' => array('class' => array('form--inline', 'clearfix')), + ); + + $form['add']['group_formatter'] = array( + '#type' => 'select', + '#title' => $this->t('Add a new group'), + '#options' => $formatter_options, + '#empty_option' => $this->t('- Select a group type -'), + '#required' => TRUE, + ); + + // Field label and field_name. + $form['new_group_wrapper'] = array( + '#type' => 'container', + '#states' => array( + '!visible' => array( + ':input[name="group_formatter"]' => array('value' => ''), + ), + ), + ); + $form['new_group_wrapper']['label'] = array( + '#type' => 'textfield', + '#title' => $this->t('Label'), + '#size' => 15, + '#required' => TRUE, + ); + + $form['new_group_wrapper']['group_name'] = array( + '#type' => 'machine_name', + '#size' => 15, + // This field should stay LTR even for RTL languages. + '#field_prefix' => '' . self::GROUP_PREFIX, + '#field_suffix' => '‎', + '#description' => $this->t('A unique machine-readable name containing letters, numbers, and underscores.'), + '#maxlength' => FieldStorageConfig::NAME_MAX_LENGTH - strlen(self::GROUP_PREFIX), + '#machine_name' => array( + 'source' => array('new_group_wrapper', 'label'), + 'exists' => array($this, 'groupNameExists'), + ), + '#required' => TRUE, + ); + + $form['actions'] = array('#type' => 'actions'); + $form['actions']['submit'] = array( + '#type' => 'submit', + '#value' => $this->t('Save and continue'), + '#button_type' => 'primary', + '#validate' => array( + array($this, 'validateFormatterSelection') + ), + ); + + $form['#attached']['library'][] = 'field_ui/drupal.field_ui'; + } + + /** + * Build the formatter configuration form. + */ + function buildConfigurationForm(array &$form, FormStateInterface $form_state) { + + $group = new \stdClass(); + $group->context = $this->context; + $group->entity_type = $this->entityTypeId; + $group->bundle = $this->bundle; + $group->mode = $this->mode; + + $manager = \Drupal::service('plugin.manager.field_group.formatters'); + $plugin = $manager->getInstance(array( + 'format_type' => $form_state->getValue('group_formatter'), + 'configuration' => [ + 'label' => $form_state->getValue('label'), + ], + 'group' => $group, + )); + + $form['format_settings'] = array( + '#type' => 'container', + '#tree' => TRUE, + ); + + $form['format_settings'] += $plugin->settingsForm(); + + $form['actions'] = array('#type' => 'actions'); + $form['actions']['submit'] = array( + '#type' => 'submit', + '#value' => $this->t('Create group'), + '#button_type' => 'primary', + ); + + } + + /** + * Validate the formatter selection step. + */ + public function validateFormatterSelection(array &$form, FormStateInterface $form_state) { + + $group_name = self::GROUP_PREFIX . $form_state->getValue('group_name'); + + // Add the prefix. + $form_state->setValueForElement($form['new_group_wrapper']['group_name'], $group_name); + } + + /** + * {@inheritdoc} + */ + public function submitForm(array &$form, FormStateInterface $form_state) { + + if ($form_state->get('step') == 'formatter') { + $form_state->set('step', 'configuration'); + $form_state->set('group_label', $form_state->getValue('label')); + $form_state->set('group_name', $form_state->getValue('group_name')); + $form_state->set('group_formatter', $form_state->getValue('group_formatter')); + $form_state->setRebuild(); + } + else { + + $new_group = (object) array( + 'group_name' => $form_state->get('group_name'), + 'entity_type' => $this->entityTypeId, + 'bundle' => $this->bundle, + 'mode' => $this->mode, + 'context' => $this->context, + 'children' =>[], + 'parent_name' => '', + 'weight' => 20, + 'format_type' => $form_state->get('group_formatter'), + ); + + $new_group->format_settings = $form_state->getValue('format_settings'); + $new_group->label = $new_group->format_settings['label']; + unset($new_group->format_settings['label']); + $new_group->format_settings += _field_group_get_default_formatter_settings($form_state->get('group_formatter'), $this->context); + + field_group_group_save($new_group); + + // Store new group information for any additional submit handlers. + $groups_added = $form_state->get('groups_added'); + $groups_added['_add_new_group'] = $new_group->group_name; + drupal_set_message(t('New group %label successfully created.', array('%label' => $new_group->label))); + + $form_state->setRedirectUrl(FieldgroupUi::getFieldUiRoute($new_group)); + \Drupal::cache()->invalidate('field_groups'); + + } + + } + + /** + * Checks if a group machine name is taken. + * + * @param string $value + * The machine name, not prefixed. + * @param array $element + * An array containing the structure of the 'group_name' element. + * @param FormStateInterface $form_state + * The current state of the form. + * + * @return bool + * Whether or not the group machine name is taken. + */ + public function groupNameExists($value, $element, FormStateInterface $form_state) { + + // Add the prefix. + $group_name = self::GROUP_PREFIX . $value; + $entity_type = $form_state->get('entity_type_id'); + $bundle = $form_state->get('bundle'); + $context = $form_state->get('context'); + $mode = $form_state->get('mode'); + + return field_group_exists($group_name, $entity_type, $bundle, $context, $mode); + } + +} diff --git a/modules/field_group/src/Form/FieldGroupDeleteForm.php b/modules/field_group/src/Form/FieldGroupDeleteForm.php new file mode 100644 index 00000000..1b827292 --- /dev/null +++ b/modules/field_group/src/Form/FieldGroupDeleteForm.php @@ -0,0 +1,82 @@ +getRequest()->attributes->get('form_mode_name'); + } + else { + $mode = $this->getRequest()->attributes->get('view_mode_name'); + } + + if (empty($mode)) { + $mode = 'default'; + } + + $this->fieldGroup = field_group_load_field_group($field_group_name, $entity_type_id, $bundle, $context, $mode); + return parent::buildForm($form, $form_state); + } + + /** + * {@inheritdoc} + */ + public function submitForm(array &$form, FormStateInterface $form_state) { + $bundles = entity_get_bundles(); + $bundle_label = $bundles[$this->fieldGroup->entity_type][$this->fieldGroup->bundle]['label']; + + field_group_group_delete($this->fieldGroup); + + drupal_set_message(t('The group %group has been deleted from the %type content type.', array('%group' => t($this->fieldGroup->label), '%type' => $bundle_label))); + + // Redirect. + $form_state->setRedirectUrl($this->getCancelUrl()); + + } + + /** + * {@inheritdoc} + */ + public function getQuestion() { + return $this->t('Are you sure you want to delete the group %group?', array('%group' => t($this->fieldGroup->label))); + } + + /** + * {@inheritdoc} + */ + public function getConfirmText() { + return $this->t('Delete'); + } + + /** + * {@inheritdoc} + */ + public function getCancelUrl() { + return FieldgroupUi::getFieldUiRoute($this->fieldGroup); + } + +} diff --git a/modules/field_group/src/Plugin/Derivative/FieldGroupLocalAction.php b/modules/field_group/src/Plugin/Derivative/FieldGroupLocalAction.php new file mode 100644 index 00000000..96bd638b --- /dev/null +++ b/modules/field_group/src/Plugin/Derivative/FieldGroupLocalAction.php @@ -0,0 +1,106 @@ +routeProvider = $route_provider; + $this->entityTypeManager = $entity_type_manager; + } + + /** + * {@inheritdoc} + */ + public static function create(ContainerInterface $container, $base_plugin_id) { + return new static( + $container->get('router.route_provider'), + $container->get('entity_type.manager') + ); + } + + /** + * {@inheritdoc} + */ + public function getDerivativeDefinitions($base_plugin_definition) { + $this->derivatives = array(); + + foreach ($this->entityTypeManager->getDefinitions() as $entity_type_id => $entity_type) { + if ($entity_type->get('field_ui_base_route')) { + + $default_options = [ + 'title' => $this->t('Add group'), + ]; + + $this->derivatives['field_group_add_' . $entity_type_id . '_form_display'] = [ + 'route_name' => "field_ui.field_group_add_$entity_type_id.form_display", + 'appears_on' => [ + "entity.entity_form_display.{$entity_type_id}.default", + ], + ] + $default_options; + + $this->derivatives['field_group_add_' . $entity_type_id . '_form_display_form_mode'] = [ + 'route_name' => "field_ui.field_group_add_$entity_type_id.form_display.form_mode", + 'appears_on' => [ + "entity.entity_form_display.{$entity_type_id}.form_mode", + ], + ] + $default_options; + + $this->derivatives['field_group_add_' . $entity_type_id . '_display'] = [ + 'route_name' => "field_ui.field_group_add_$entity_type_id.display", + 'appears_on' => [ + "entity.entity_view_display.{$entity_type_id}.default", + ], + ] + $default_options; + + $this->derivatives['field_group_add_' . $entity_type_id . '_display_view_mode'] = [ + 'route_name' => "field_ui.field_group_add_$entity_type_id.display.view_mode", + 'appears_on' => [ + "entity.entity_view_display.{$entity_type_id}.view_mode", + ], + ] + $default_options; + } + } + + foreach ($this->derivatives as &$entry) { + $entry += $base_plugin_definition; + } + + return $this->derivatives; + } + +} diff --git a/modules/field_group/src/Plugin/field_group/FieldGroupFormatter/Accordion.php b/modules/field_group/src/Plugin/field_group/FieldGroupFormatter/Accordion.php new file mode 100644 index 00000000..378f5897 --- /dev/null +++ b/modules/field_group/src/Plugin/field_group/FieldGroupFormatter/Accordion.php @@ -0,0 +1,89 @@ + 'field_group_accordion', + '#effect' => $this->getSetting('effect'), + ); + + if ($this->getSetting('id')) { + $element['#id'] = Html::getId($this->getSetting('id')); + } + + $classes = $this->getClasses(); + if (!empty($classes)) { + $element += array('#attributes' => array('class' => $classes)); + } + + \Drupal\field_group\Element\Accordion::processAccordion($element, $form_state); + } + + /** + * {@inheritdoc} + */ + public function settingsForm() { + + $form = parent::settingsForm(); + + $form['effect'] = array( + '#title' => $this->t('Effect'), + '#type' => 'select', + '#options' => array('none' => $this->t('None'), 'bounceslide' => $this->t('Bounce slide')), + '#default_value' => $this->getSetting('effect'), + '#weight' => 2, + ); + + return $form; + } + + /** + * {@inheritdoc} + */ + public function settingsSummary() { + + $summary = array(); + $summary[] = $this->t('Effect : @effect', + array('@effect' => $this->getSetting('effect')) + ); + + return $summary; + } + + /** + * {@inheritdoc} + */ + public static function defaultContextSettings($context) { + return array( + 'effect' => 'none', + ) + parent::defaultSettings($context); + } + +} diff --git a/modules/field_group/src/Plugin/field_group/FieldGroupFormatter/AccordionItem.php b/modules/field_group/src/Plugin/field_group/FieldGroupFormatter/AccordionItem.php new file mode 100644 index 00000000..a92ee3c0 --- /dev/null +++ b/modules/field_group/src/Plugin/field_group/FieldGroupFormatter/AccordionItem.php @@ -0,0 +1,119 @@ + 'field_group_accordion_item', + '#open' => $this->getSetting('formatter') == 'open' ? TRUE : FALSE, + '#description' => $this->getSetting('description'), + '#title' => Drupal::translation()->translate($this->getLabel()), + ); + + if ($this->getSetting('id')) { + $element['#id'] = Html::getId($this->getSetting('id')); + } + + $classes = $this->getClasses(); + if (!empty($classes)) { + $element += array('#attributes' => array('class' => $classes)); + } + + if ($this->getSetting('required_fields')) { + $element['#attached']['library'][] = 'field_group/formatter.details'; + } + + } + + /** + * {@inheritdoc} + */ + public function settingsForm() { + + $form = parent::settingsForm(); + + $form['formatter'] = array( + '#title' => $this->t('Default state'), + '#type' => 'select', + '#options' => array_combine($this->pluginDefinition['format_types'], $this->pluginDefinition['format_types']), + '#default_value' => $this->getSetting('formatter'), + '#weight' => -4, + ); + + if ($this->context == 'form') { + $form['required_fields'] = array( + '#type' => 'checkbox', + '#title' => $this->t('Mark group as required if it contains required fields.'), + '#default_value' => $this->getSetting('required_fields'), + '#weight' => 2, + ); + } + + return $form; + } + + /** + * {@inheritdoc} + */ + public function settingsSummary() { + + $summary = array(); + + if ($this->getSetting('required_fields')) { + $summary[] = $this->t('Mark as required'); + } + + if ($this->getSetting('description')) { + $summary[] = $this->t('Description : @description', + array('@description' => $this->getSetting('description')) + ); + } + + return $summary; + } + + /** + * {@inheritdoc} + */ + public static function defaultContextSettings($context) { + $defaults = array( + 'formatter' => 'closed', + 'description' => '', + ) + parent::defaultSettings($context); + + if ($context == 'form') { + $defaults['required_fields'] = 1; + } + + return $defaults; + } + +} diff --git a/modules/field_group/src/Plugin/field_group/FieldGroupFormatter/Details.php b/modules/field_group/src/Plugin/field_group/FieldGroupFormatter/Details.php new file mode 100644 index 00000000..8a78c6e8 --- /dev/null +++ b/modules/field_group/src/Plugin/field_group/FieldGroupFormatter/Details.php @@ -0,0 +1,118 @@ + 'details', + '#title' => Html::escape($this->t($this->getLabel())), + '#open' => $this->getSetting('open') + ); + + if ($this->getSetting('id')) { + $element['#id'] = Html::getId($this->getSetting('id')); + } + + $classes = $this->getClasses(); + if (!empty($classes)) { + $element += array( + '#attributes' => array('class' => $classes), + ); + } + + if ($this->getSetting('description')) { + $element += array( + '#description' => $this->getSetting('description'), + ); + } + + if ($this->getSetting('required_fields')) { + $element['#attached']['library'][] = 'field_group/formatter.details'; + $element['#attached']['library'][] = 'field_group/core'; + } + } + + /** + * {@inheritdoc} + */ + public function settingsForm() { + $form = parent::settingsForm(); + + $form['open'] = array( + '#type' => 'checkbox', + '#title' => $this->t('Display element open by default.'), + '#default_value' => $this->getSetting('open'), + ); + + if ($this->context == 'form') { + $form['required_fields'] = array( + '#type' => 'checkbox', + '#title' => $this->t('Mark group as required if it contains required fields.'), + '#default_value' => $this->getSetting('required_fields'), + '#weight' => 2, + ); + } + + return $form; + } + + /** + * {@inheritdoc} + */ + public function settingsSummary() { + + $summary = array(); + if ($this->getSetting('open')) { + $summary[] = $this->t('Default state open'); + } + else { + $summary[] = $this->t('Default state closed'); + } + + if ($this->getSetting('required_fields')) { + $summary[] = $this->t('Mark as required'); + } + + return $summary; + } + + /** + * {@inheritdoc} + */ + public static function defaultContextSettings($context) { + $defaults = array( + 'open' => FALSE, + 'required_fields' => $context == 'form', + ) + parent::defaultSettings($context); + + if ($context == 'form') { + $defaults['required_fields'] = 1; + } + + return $defaults; + } + +} diff --git a/modules/field_group/src/Plugin/field_group/FieldGroupFormatter/Fieldset.php b/modules/field_group/src/Plugin/field_group/FieldGroupFormatter/Fieldset.php new file mode 100644 index 00000000..f31e9c8d --- /dev/null +++ b/modules/field_group/src/Plugin/field_group/FieldGroupFormatter/Fieldset.php @@ -0,0 +1,117 @@ + 'fieldset', + '#title' => Html::escape($this->t($this->getLabel())), + '#pre_render' => array(), + '#attributes' => array(), + ); + + if ($this->getSetting('description')) { + $element += array( + '#description' => $this->getSetting('description'), + ); + } + + if ($this->getSetting('id')) { + $element['#id'] = Html::getId($this->getSetting('id')); + } + + $classes = $this->getClasses(); + if (!empty($classes)) { + $element['#attributes'] += array('class' => $classes); + } + + if ($this->getSetting('required_fields')) { + $element['#attached']['library'][] = 'field_group/formatter.fieldset'; + $element['#attached']['library'][] = 'field_group/core'; + } + } + + /** + * {@inheritdoc} + */ + public function settingsForm() { + + $form = parent::settingsForm(); + + $form['description'] = array( + '#title' => $this->t('Description'), + '#type' => 'textarea', + '#default_value' => $this->getSetting('description'), + '#weight' => -4, + ); + + if ($this->context == 'form') { + $form['required_fields'] = array( + '#type' => 'checkbox', + '#title' => $this->t('Mark group as required if it contains required fields.'), + '#default_value' => $this->getSetting('required_fields'), + '#weight' => 2, + ); + } + + return $form; + } + + /** + * {@inheritdoc} + */ + public function settingsSummary() { + + $summary = parent::settingsSummary(); + + if ($this->getSetting('required_fields')) { + $summary[] = $this->t('Mark as required'); + } + + if ($this->getSetting('description')) { + $summary[] = $this->t('Description : @description', + array('@description' => $this->getSetting('description')) + ); + } + + return $summary; + } + + /** + * {@inheritdoc} + */ + public static function defaultContextSettings($context) { + $defaults = array( + 'description' => '', + ) + parent::defaultSettings($context); + + if ($context == 'form') { + $defaults['required_fields'] = 1; + } + + return $defaults; + } + +} diff --git a/modules/field_group/src/Plugin/field_group/FieldGroupFormatter/HtmlElement.php b/modules/field_group/src/Plugin/field_group/FieldGroupFormatter/HtmlElement.php new file mode 100644 index 00000000..bd87df1c --- /dev/null +++ b/modules/field_group/src/Plugin/field_group/FieldGroupFormatter/HtmlElement.php @@ -0,0 +1,219 @@ +getSetting('attributes')) { + + // This regex split the attributes string so that we can pass that + // later to drupal_attributes(). + preg_match_all('/([^\s=]+)="([^"]+)"/', $this->getSetting('attributes'), $matches); + + // Put the attribute and the value together. + foreach ($matches[1] as $key => $attribute) { + $element_attributes[$attribute] = $matches[2][$key]; + } + + } + + // Add the id to the attributes array. + if ($this->getSetting('id')) { + $element_attributes['id'] = Html::getId($this->getSetting('id')); + } + + // Add the classes to the attributes array. + $classes = $this->getClasses(); + if (!empty($classes)) { + if (!isset($element_attributes['class'])) { + $element_attributes['class'] = array(); + } + // If user also entered class in the attributes textfield, force it to an array. + else { + $element_attributes['class'] = array($element_attributes['class']); + } + $element_attributes['class'] = array_merge($classes, $element_attributes['class']->value()); + } + + $element['#effect'] = $this->getSetting('effect'); + $element['#speed'] = $this->getSetting('speed'); + $element['#type'] = 'field_group_html_element'; + $element['#wrapper_element'] = $this->getSetting('element'); + $element['#attributes'] = $element_attributes; + if ($this->getSetting('show_label')) { + $element['#title_element'] = $this->getSetting('label_element'); + $element['#title'] = Html::escape($this->t($this->getLabel())); + } + + $form_state = new FormState(); + \Drupal\field_group\Element\HtmlElement::processHtmlElement($element, $form_state); + + if ($this->getSetting('required_fields')) { + $element['#attached']['library'][] = 'field_group/formatter.html_element'; + $element['#attached']['library'][] = 'field_group/core'; + } + } + + /** + * {@inheritdoc} + */ + public function settingsForm() { + + $form = parent::settingsForm(); + + $form['element'] = array( + '#title' => $this->t('Element'), + '#type' => 'textfield', + '#default_value' => $this->getSetting('element'), + '#description' => $this->t('E.g. div, section, aside etc.'), + '#weight' => 1, + ); + + $form['show_label'] = array( + '#title' => $this->t('Show label'), + '#type' => 'select', + '#options' => array(0 => $this->t('No'), 1 => $this->t('Yes')), + '#default_value' => $this->getSetting('show_label'), + '#weight' => 2, + '#attributes' => array( + 'data-fieldgroup-selector' => 'show_label' + ), + ); + + $form['label_element'] = array( + '#title' => $this->t('Label element'), + '#type' => 'textfield', + '#default_value' => $this->getSetting('label_element'), + '#weight' => 3, + '#states' => array( + 'visible' => array( + ':input[data-fieldgroup-selector="show_label"]' => array('value' => 1), + ), + ), + ); + + if ($this->context == 'form') { + $form['required_fields'] = array( + '#title' => $this->t('Mark group as required if it contains required fields.'), + '#type' => 'checkbox', + '#default_value' => $this->getSetting('required_fields'), + '#weight' => 4, + ); + } + + $form['attributes'] = array( + '#title' => $this->t('Attributes'), + '#type' => 'textfield', + '#default_value' => $this->getSetting('attributes'), + '#description' => $this->t('E.g. name="anchor"'), + '#weight' => 5, + ); + + $form['effect'] = array( + '#title' => $this->t('Effect'), + '#type' => 'select', + '#options' => array( + 'none' => $this->t('None'), + 'collapsible' => $this->t('Collapsible'), + 'blind' => $this->t('Blind') + ), + '#default_value' => $this->getSetting('effect'), + '#weight' => 6, + '#attributes' => array( + 'data-fieldgroup-selector' => 'effect' + ), + ); + + $form['speed'] = array( + '#title' => $this->t('Speed'), + '#type' => 'select', + '#options' => array('slow' => $this->t('Slow'), 'fast' => $this->t('Fast')), + '#default_value' => $this->getSetting('speed'), + '#weight' => 7, + '#states' => array( + '!visible' => array( + ':input[data-fieldgroup-selector="effect"]' => array('value' => 'none'), + ), + ), + ); + + return $form; + } + + /** + * {@inheritdoc} + */ + public function settingsSummary() { + + $summary = parent::settingsSummary(); + $summary[] = $this->t('Element: @element', + array('@element' => $this->getSetting('element')) + ); + + if ($this->getSetting('show_label')) { + $summary[] = $this->t('Label element: @element', + array('@element' => $this->getSetting('label_element')) + ); + } + + if ($this->getSetting('attributes')) { + $summary[] = $this->t('Attributes: @attributes', + array('@attributes' => $this->getSetting('attributes')) + ); + } + + if ($this->getSetting('required_fields')) { + $summary[] = $this->t('Mark as required'); + } + + return $summary; + } + + /** + * {@inheritdoc} + */ + public static function defaultContextSettings($context) { + $defaults = array( + 'element' => 'div', + 'show_label' => 0, + 'label_element' => 'h3', + 'effect' => 'none', + 'speed' => 'fast', + 'attributes' => '', + ) + parent::defaultSettings($context); + + if ($context == 'form') { + $defaults['required_fields'] = 1; + } + + return $defaults; + + } + +} diff --git a/modules/field_group/src/Plugin/field_group/FieldGroupFormatter/Tab.php b/modules/field_group/src/Plugin/field_group/FieldGroupFormatter/Tab.php new file mode 100644 index 00000000..7cc8a644 --- /dev/null +++ b/modules/field_group/src/Plugin/field_group/FieldGroupFormatter/Tab.php @@ -0,0 +1,123 @@ + 'details', + '#title' => Html::escape($this->t($this->getLabel())), + '#description' => $this->getSetting('description'), + ); + + if ($this->getSetting('id')) { + $add['#id'] = Html::getId($this->getSetting('id')); + } + else { + $add['#id'] = Html::getId('edit-' . $this->group->group_name); + } + + $classes = $this->getClasses(); + if (!empty($classes)) { + $element += array( + '#attributes' => array('class' => $classes), + ); + } + + if ($this->getSetting('formatter') == 'open') { + $element['#open'] = TRUE; + } + + // Front-end and back-end on configuration will lead + // to vertical tabs nested in a separate vertical group. + if (!empty($this->group->parent_name)) { + $add['#group'] = $this->group->parent_name; + $add['#parents'] = array($add['#group']); + } + + if ($this->getSetting('required_fields')) { + $element['#attached']['library'][] = 'field_group/formatter.tabs'; + $element['#attached']['library'][] = 'field_group/core'; + } + + $element += $add; + + } + + /** + * {@inheritdoc} + */ + public function settingsForm() { + + $form = parent::settingsForm(); + + $form['formatter'] = array( + '#title' => $this->t('Default state'), + '#type' => 'select', + '#options' => array_combine($this->pluginDefinition['format_types'], $this->pluginDefinition['format_types']), + '#default_value' => $this->getSetting('formatter'), + '#weight' => -4, + ); + + $form['description'] = array( + '#title' => $this->t('Description'), + '#type' => 'textarea', + '#default_value' => $this->getSetting('description'), + '#weight' => -4, + ); + + if ($this->context == 'form') { + $form['required_fields'] = array( + '#type' => 'checkbox', + '#title' => $this->t('Mark group as required if it contains required fields.'), + '#default_value' => $this->getSetting('required_fields'), + '#weight' => 2, + ); + } + + return $form; + } + + /** + * {@inheritdoc} + */ + public static function defaultContextSettings($context) { + $defaults = array( + 'formatter' => 'closed', + 'description' => '', + ) + parent::defaultSettings($context); + + if ($context == 'form') { + $defaults['required_fields'] = 1; + } + + return $defaults; + } + +} diff --git a/modules/field_group/src/Plugin/field_group/FieldGroupFormatter/Tabs.php b/modules/field_group/src/Plugin/field_group/FieldGroupFormatter/Tabs.php new file mode 100644 index 00000000..4f49ec33 --- /dev/null +++ b/modules/field_group/src/Plugin/field_group/FieldGroupFormatter/Tabs.php @@ -0,0 +1,139 @@ + '
    ', + '#suffix' => '
    ', + '#tree' => TRUE, + '#parents' => array($this->group->group_name), + '#default_tab' => '', + ); + + if ($this->getSetting('id')) { + $element['#id'] = Html::getId($this->getSetting('id')); + } + + // By default tabs don't have titles but you can override it in the theme. + if ($this->getLabel()) { + $element['#title'] = Html::escape($this->getLabel()); + } + + $form_state = new FormState(); + + if ($this->getSetting('direction') == 'vertical') { + + $element += array( + '#type' => 'vertical_tabs', + '#theme_wrappers' => array('vertical_tabs'), + ); + $complete_form = array(); + $element = VerticalTabs::processVerticalTabs($element, $form_state, $complete_form); + } + else { + $element += array( + '#type' => 'horizontal_tabs', + '#theme_wrappers' => array('horizontal_tabs'), + ); + $on_form = $this->context == 'form'; + $element = HorizontalTabs::processHorizontalTabs($element, $form_state, $on_form); + } + + // Make sure the group has 1 child. This is needed to succeed at form_pre_render_vertical_tabs(). + // Skipping this would force us to move all child groups to this array, making it an un-nestable. + $element['group']['#groups'][$this->group->group_name] = array(0 => array()); + $element['group']['#groups'][$this->group->group_name]['#group_exists'] = TRUE; + + // Search for a tab that was marked as open. First one wins. + foreach (Element::children($element) as $tab_name) { + if (!empty($element[$tab_name]['#open'])) { + $element[$this->group->group_name . '__active_tab']['#default_value'] = $tab_name; + break; + } + } + + } + + /** + * {@inheritdoc} + */ + public function settingsForm() { + + $form = parent::settingsForm(); + + $form['direction'] = array( + '#title' => $this->t('Direction'), + '#type' => 'select', + '#options' => array( + 'vertical' => $this->t('Vertical'), + 'horizontal' => $this->t('Horizontal'), + ), + '#default_value' => $this->getSetting('direction'), + '#weight' => 1, + ); + + return $form; + } + + /** + * {@inheritdoc} + */ + public function settingsSummary() { + + $summary = parent::settingsSummary(); + $summary[] = $this->t('Direction: @direction', + array('@direction' => $this->getSetting('direction')) + ); + + return $summary; + } + + /** + * {@inheritdoc} + */ + public static function defaultContextSettings($context) { + return array( + 'direction' => 'vertical', + ) + parent::defaultContextSettings($context); + } + + /** + * {@inheritdoc} + */ + public function getClasses() { + + $classes = parent::getClasses(); + $classes[] = 'field-group-' . $this->group->format_type . '-wrapper'; + + return $classes; + } + +} diff --git a/modules/field_group/src/Routing/FieldGroupConverter.php b/modules/field_group/src/Routing/FieldGroupConverter.php new file mode 100644 index 00000000..3eb620e6 --- /dev/null +++ b/modules/field_group/src/Routing/FieldGroupConverter.php @@ -0,0 +1,32 @@ +manager = $manager; + } + + /** + * {@inheritdoc} + */ + protected function alterRoutes(RouteCollection $collection) { + + // Create fieldgroup routes for every entity. + foreach ($this->manager->getDefinitions() as $entity_type_id => $entity_type) { + $defaults = array(); + if ($route_name = $entity_type->get('field_ui_base_route')) { + // Try to get the route from the current collection. + if (!$entity_route = $collection->get($route_name)) { + continue; + } + $path = $entity_route->getPath(); + + $options = $entity_route->getOptions(); + + // Special parameter used to easily recognize all Field UI routes. + $options['_field_ui'] = TRUE; + + if (($bundle_entity_type = $entity_type->getBundleEntityType()) && $bundle_entity_type !== 'bundle') { + $options['parameters'][$entity_type->getBundleEntityType()] = array( + 'type' => 'entity:' . $entity_type->getBundleEntityType(), + ); + } + + $options['parameters']['field_group'] = array( + 'type' => 'field_group', + 'entity_type' => $entity_type->getBundleEntityType(), + ); + + $defaults_delete = [ + 'entity_type_id' => $entity_type_id, + '_form' => '\Drupal\field_group\Form\FieldGroupDeleteForm', + ]; + $defaults_add = [ + 'entity_type_id' => $entity_type_id, + '_form' => '\Drupal\field_group\Form\FieldGroupAddForm', + '_title' => 'Add group', + ]; + + // If the entity type has no bundles and it doesn't use {bundle} in its + // admin path, use the entity type. + if (strpos($path, '{bundle}') === FALSE) { + $defaults_add['bundle'] = !$entity_type->hasKey('bundle') ? $entity_type_id : ''; + $defaults_delete['bundle'] = $defaults_add['bundle']; + } + + // Routes to delete field groups. + $route = new Route( + "$path/form-display/{field_group_name}/delete", + ['context' => 'form'] + $defaults_delete, + array('_permission' => 'administer ' . $entity_type_id . ' form display'), + $options + ); + $collection->add("field_ui.field_group_delete_$entity_type_id.form_display", $route); + + $route = new Route( + "$path/form-display/{form_mode_name}/{field_group_name}/delete", + ['context' => 'form'] + $defaults_delete, + array('_permission' => 'administer ' . $entity_type_id . ' form display'), + $options + ); + $collection->add("field_ui.field_group_delete_$entity_type_id.form_display.form_mode", $route); + + $route = new Route( + "$path/display/{field_group_name}/delete", + ['context' => 'view'] + $defaults_delete, + array('_permission' => 'administer ' . $entity_type_id . ' display'), + $options + ); + $collection->add("field_ui.field_group_delete_$entity_type_id.display", $route); + + $route = new Route( + "$path/display/{view_mode_name}/{field_group_name}/delete", + ['context' => 'view'] + $defaults_delete, + array('_permission' => 'administer ' . $entity_type_id . ' display'), + $options + ); + $collection->add("field_ui.field_group_delete_$entity_type_id.display.view_mode", $route); + + // Routes to add field groups. + $route = new Route( + "$path/form-display/add-group", + ['context' => 'form'] + $defaults_add, + array('_permission' => 'administer ' . $entity_type_id . ' form display'), + $options + ); + $collection->add("field_ui.field_group_add_$entity_type_id.form_display", $route); + + $route = new Route( + "$path/form-display/{form_mode_name}/add-group", + ['context' => 'form'] + $defaults_add, + array('_permission' => 'administer ' . $entity_type_id . ' form display'), + $options + ); + $collection->add("field_ui.field_group_add_$entity_type_id.form_display.form_mode", $route); + + $route = new Route( + "$path/display/add-group", + ['context' => 'view'] + $defaults_add, + array('_permission' => 'administer ' . $entity_type_id . ' display'), + $options + ); + $collection->add("field_ui.field_group_add_$entity_type_id.display", $route); + + $route = new Route( + "$path/display/{view_mode_name}/add-group", + ['context' => 'view'] + $defaults_add, + array('_permission' => 'administer ' . $entity_type_id . ' display'), + $options + ); + $collection->add("field_ui.field_group_add_$entity_type_id.display.view_mode", $route); + + } + } + } + + /** + * {@inheritdoc} + */ + public static function getSubscribedEvents() { + //$events = parent::getSubscribedEvents(); + // Come after field_ui, config_translation. + $events[RoutingEvents::ALTER] = array('onAlterRoutes', -210); + return $events; + } + +} diff --git a/modules/field_group/src/Tests/EntityDisplayTest.php b/modules/field_group/src/Tests/EntityDisplayTest.php new file mode 100644 index 00000000..0bd204ff --- /dev/null +++ b/modules/field_group/src/Tests/EntityDisplayTest.php @@ -0,0 +1,329 @@ +drupalCreateUser(array('access content', 'administer content types', 'administer node fields', 'administer node form display', 'administer node display', 'bypass node access')); + $this->drupalLogin($admin_user); + + // Create content type, with underscores. + $type_name = strtolower($this->randomMachineName(8)) . '_test'; + $type = $this->drupalCreateContentType(array('name' => $type_name, 'type' => $type_name)); + $this->type = $type->id(); + $display = entity_get_display('node', $type_name, 'default'); + + // Create a node. + $node_values = array('type' => $type_name); + + // Create test fields. + $test_fields = array('field_test', 'field_test_2', 'field_no_access'); + foreach ($test_fields as $field_name) { + + $field_storage = FieldStorageConfig::create([ + 'field_name' => $field_name, + 'entity_type' => 'node', + 'type' => 'test_field', + ]); + $field_storage->save(); + + $instance = FieldConfig::create([ + 'field_storage' => $field_storage, + 'bundle' => $type_name, + 'label' => $this->randomMachineName(), + ]); + $instance->save(); + + // Assign a test value for the field. + $node_values[$field_name][0]['value'] = mt_rand(1, 127); + + // Set the field visible on the display object. + $display_options = array( + 'label' => 'above', + 'type' => 'field_test_default', + 'settings' => array( + 'test_formatter_setting' => $this->randomMachineName(), + ), + ); + $display->setComponent($field_name, $display_options); + } + + // Save display + create node. + $display->save(); + $this->node = $this->drupalCreateNode($node_values); + + } + + /** + * Test if an fieldgroup that only contains fields + * that has no access is not shown. + */ + function testFieldAccess() { + + $data = array( + 'label' => 'Wrapper', + 'children' => array( + 0 => 'field_no_access', + ), + 'format_type' => 'html_element', + 'format_settings' => array( + 'element' => 'div', + 'id' => 'wrapper-id', + ), + ); + + $this->createGroup('node', $this->type, 'view', 'default', $data); + $this->drupalGet('node/' . $this->node->id()); + + // Test if group is not shown. + $this->assertNoFieldByXPath("//div[contains(@id, 'wrapper-id')]", NULL, t('Div that contains fields with no access is not shown.')); + } + + /** + * Test the html element formatter. + */ + function testHtmlElement() { + + $data = array( + 'weight' => '1', + 'children' => array( + 0 => 'field_test', + 1 => 'body', + ), + 'label' => 'Link', + 'format_type' => 'html_element', + 'format_settings' => array( + 'label' => 'Link', + 'element' => 'div', + 'id' => 'wrapper-id', + 'classes' => 'test-class', + ), + ); + $group = $this->createGroup('node', $this->type, 'view', 'default', $data); + + //$groups = field_group_info_groups('node', 'article', 'view', 'default', TRUE); + $this->drupalGet('node/' . $this->node->id()); + + // Test group ids and classes. + $this->assertFieldByXPath("//div[contains(@id, 'wrapper-id')]", NULL, t('Wrapper id set on wrapper div')); + $this->assertFieldByXPath("//div[contains(@class, 'test-class')]", NULL, t('Test class set on wrapper div') . 'class="' . $group->group_name . ' test-class'); + + // Test group label. + $this->assertNoRaw('

    ' . $data['label'] . '

    ', t('Label is not shown')); + + // Set show label to true. + $group->format_settings['show_label'] = TRUE; + $group->format_settings['label_element'] = 'h3'; + field_group_group_save($group); + + $this->drupalGet('node/' . $this->node->id()); + $this->assertRaw('

    ' . $data['label'] . '

    ', t('Label is shown')); + + // Change to collapsible with blink effect. + $group->format_settings['effect'] = 'blink'; + $group->format_settings['speed'] = 'fast'; + field_group_group_save($group); + + $this->drupalGet('node/' . $this->node->id()); + $this->assertFieldByXPath("//div[contains(@class, 'speed-fast')]", NULL, t('Speed class is set')); + $this->assertFieldByXPath("//div[contains(@class, 'effect-blink')]", NULL, t('Effect class is set')); + } + + /** + * Test the fieldset formatter. + */ + function testFieldset() { + + $data = array( + 'weight' => '1', + 'children' => array( + 0 => 'field_test', + 1 => 'body', + ), + 'label' => 'Test Fieldset', + 'format_type' => 'fieldset', + 'format_settings' => array( + 'id' => 'fieldset-id', + 'classes' => 'test-class', + 'description' => 'test description', + ), + ); + $group = $this->createGroup('node', $this->type, 'view', 'default', $data); + + $this->drupalGet('node/' . $this->node->id()); + + // Test group ids and classes. + $this->assertFieldByXPath("//fieldset[contains(@id, 'fieldset-id')]", NULL, t('Correct id set on the fieldset')); + $this->assertFieldByXPath("//fieldset[contains(@class, 'test-class')]", NULL, t('Test class set on the fieldset')); + + } + + /** + * Test the tabs formatter. + */ + function testTabs() { + + $data = array( + 'label' => 'Tab 1', + 'weight' => '1', + 'children' => array( + 0 => 'field_test', + ), + 'format_type' => 'tab', + 'format_settings' => array( + 'label' => 'Tab 1', + 'classes' => 'test-class', + 'description' => '', + 'formatter' => 'open', + ), + ); + $first_tab = $this->createGroup('node', $this->type, 'view', 'default', $data); + + $data = array( + 'label' => 'Tab 2', + 'weight' => '1', + 'children' => array( + 0 => 'field_test_2', + ), + 'format_type' => 'tab', + 'format_settings' => array( + 'label' => 'Tab 1', + 'classes' => 'test-class-2', + 'description' => 'description of second tab', + 'formatter' => 'closed', + ), + ); + $second_tab = $this->createGroup('node', $this->type, 'view', 'default', $data); + + $data = array( + 'label' => 'Tabs', + 'weight' => '1', + 'children' => array( + 0 => $first_tab->group_name, + 1 => $second_tab->group_name, + ), + 'format_type' => 'tabs', + 'format_settings' => array( + 'direction' => 'vertical', + 'label' => 'Tab 1', + 'classes' => 'test-class-wrapper', + ), + ); + $tabs_group = $this->createGroup('node', $this->type, 'view', 'default', $data); + + $this->drupalGet('node/' . $this->node->id()); + + // Test properties. + $this->assertFieldByXPath("//div[contains(@class, 'test-class-wrapper')]", NULL, t('Test class set on tabs wrapper')); + $this->assertFieldByXPath("//details[contains(@class, 'test-class-2')]", NULL, t('Test class set on second tab')); + $this->assertRaw('
    description of second tab
    ', t('Description of tab is shown')); + + // Test if correctly nested. + $this->assertFieldByXPath("//div[contains(@class, 'test-class-wrapper')]//details[contains(@class, 'test-class')]", NULL, 'First tab is displayed as child of the wrapper.'); + $this->assertFieldByXPath("//div[contains(@class, 'test-class-wrapper')]//details[contains(@class, 'test-class-2')]", NULL, 'Second tab is displayed as child of the wrapper.'); + + // Test if it's a vertical tab. + $this->assertFieldByXPath('//div[@data-vertical-tabs-panes=""]', NULL, 'Tabs are shown vertical.'); + + // Switch to horizontal + $tabs_group->format_settings['direction'] = 'horizontal'; + field_group_group_save($tabs_group); + + $this->drupalGet('node/' . $this->node->id()); + + // Test if it's a horizontal tab. + $this->assertFieldByXPath('//div[@data-horizontal-tabs-panes=""]', NULL, 'Tabs are shown horizontal.'); + + } + + /** + * Test the accordion formatter. + */ + function testAccordion() { + + $data = array( + 'label' => 'Accordion item 1', + 'weight' => '1', + 'children' => array( + 0 => 'field_test', + ), + 'format_type' => 'accordion_item', + 'format_settings' => array( + 'label' => 'Accordion item 1', + 'classes' => 'test-class', + 'formatter' => 'closed', + ), + ); + $first_item = $this->createGroup('node', $this->type, 'view', 'default', $data); + $first_item_id = 'node_article_full_' . $first_item->group_name; + + $data = array( + 'label' => 'Accordion item 2', + 'weight' => '1', + 'children' => array( + 0 => 'field_test_2', + ), + 'format_type' => 'accordion_item', + 'format_settings' => array( + 'label' => 'Tab 2', + 'classes' => 'test-class-2', + 'formatter' => 'open', + ), + ); + $second_item = $this->createGroup('node', $this->type, 'view', 'default', $data); + $second_item_id = 'node_article_full_' . $second_item->group_name; + + $data = array( + 'label' => 'Accordion', + 'weight' => '1', + 'children' => array( + 0 => $first_item->group_name, + 1 => $second_item->group_name, + ), + 'format_type' => 'accordion', + 'format_settings' => array( + 'label' => 'Tab 1', + 'classes' => 'test-class-wrapper', + 'effect' => 'bounceslide' + ), + ); + $accordion = $this->createGroup('node', $this->type, 'view', 'default', $data); + + $this->drupalGet('node/' . $this->node->id()); + + // Test properties. + $this->assertFieldByXPath("//div[contains(@class, 'test-class-wrapper')]", NULL, t('Test class set on tabs wrapper')); + $this->assertFieldByXPath("//div[contains(@class, 'effect-bounceslide')]", NULL, t('Correct effect is set on the accordion')); + $this->assertFieldByXPath("//div[contains(@class, 'test-class')]", NULL, t('Accordion item with test-class is shown')); + $this->assertFieldByXPath("//div[contains(@class, 'test-class-2')]", NULL, t('Accordion item with test-class-2 is shown')); + $this->assertFieldByXPath("//h3[contains(@class, 'field-group-accordion-active')]", NULL, t('Accordion item 2 was set active')); + + // Test if correctly nested + $this->assertFieldByXPath("//div[contains(@class, 'test-class-wrapper')]//div[contains(@class, 'test-class')]", NULL, 'First item is displayed as child of the wrapper.'); + $this->assertFieldByXPath("//div[contains(@class, 'test-class-wrapper')]//div[contains(@class, 'test-class-2')]", NULL, 'Second item is displayed as child of the wrapper.'); + } + +} diff --git a/modules/field_group/src/Tests/FieldGroupTestTrait.php b/modules/field_group/src/Tests/FieldGroupTestTrait.php new file mode 100644 index 00000000..7feb1566 --- /dev/null +++ b/modules/field_group/src/Tests/FieldGroupTestTrait.php @@ -0,0 +1,46 @@ +randomMachineName()); + + $field_group = (object) array( + 'group_name' => $group_name, + 'entity_type' => $entity_type, + 'bundle' => $bundle, + 'mode' => $mode, + 'context' => $context, + 'children' => isset($data['children']) ? $data['children'] : array(), + 'parent_name' => isset($data['parent']) ? $data['parent'] : '', + 'weight' => isset($data['weight']) ? $data['weight'] : 0, + 'label' => isset($data['label']) ? $data['label'] : $this->randomString(8), + 'format_type' => $data['format_type'], + 'format_settings' => $data['format_settings'], + ); + + field_group_group_save($field_group); + + return $field_group; + } + +} diff --git a/modules/field_group/src/Tests/FieldGroupWithoutFieldUiTest.php b/modules/field_group/src/Tests/FieldGroupWithoutFieldUiTest.php new file mode 100644 index 00000000..f9bd3b1f --- /dev/null +++ b/modules/field_group/src/Tests/FieldGroupWithoutFieldUiTest.php @@ -0,0 +1,24 @@ +placeBlock('local_actions_block', ['id' => 'local_actions_block']); + $this->drupalGet(Url::fromRoute('user.login')); + } + +} diff --git a/modules/field_group/src/Tests/ManageDisplayTest.php b/modules/field_group/src/Tests/ManageDisplayTest.php new file mode 100644 index 00000000..8e6155cd --- /dev/null +++ b/modules/field_group/src/Tests/ManageDisplayTest.php @@ -0,0 +1,148 @@ +drupalCreateUser(array('access content', 'administer content types', 'administer node fields', 'administer node form display', 'administer node display', 'bypass node access')); + $this->drupalLogin($admin_user); + + // Create content type, with underscores. + $type_name = Unicode::strtolower($this->randomMachineName(8)) . '_test'; + $type = $this->drupalCreateContentType(array('name' => $type_name, 'type' => $type_name)); + $this->type = $type->id(); + + } + + /** + * Test the creation a group on the article content type. + */ + function testCreateGroup() { + + // Create random group name. + $this->group_label = $this->randomString(8); + $this->group_name_input = Unicode::strtolower($this->randomMachineName()); + $this->group_name = 'group_' . $this->group_name_input; + $this->group_formatter = 'details'; + + // Setup new group. + $group = array( + 'group_formatter' => $this->group_formatter, + 'label' => $this->group_label, + ); + + $this->drupalPostForm('admin/structure/types/manage/' . $this->type . '/form-display/add-group', $group, t('Save and continue')); + $this->assertText('Machine-readable name field is required.'); + + // Setup new group. + $group = array( + 'group_formatter' => $this->group_formatter, + 'label' => $this->group_label, + 'group_name' => $this->group_name_input, + ); + + // Add new group on the 'Manage form display' page. + $this->drupalPostForm('admin/structure/types/manage/' . $this->type . '/form-display/add-group', $group, t('Save and continue')); + $this->drupalPostForm(NULL, [], t('Create group')); + + $this->assertRaw(t('New group %label successfully created.', array('%label' => $this->group_label)), t('Group message displayed on screen.')); + + // Test if group is in the $groups array. + $this->group = field_group_load_field_group($this->group_name, 'node', $this->type, 'form', 'default'); + $this->assertNotNull($this->group, t('Group was loaded')); + + // Add new group on the 'Manage display' page. + $this->drupalPostForm('admin/structure/types/manage/' . $this->type . '/display/add-group', $group, t('Save and continue')); + $this->drupalPostForm(NULL, [], t('Create group')); + + $this->assertRaw(t('New group %label successfully created.', array('%label' => $this->group_label)), t('Group message displayed on screen.')); + + // Test if group is in the $groups array. + $loaded_group = field_group_load_field_group($this->group_name, 'node', $this->type, 'view', 'default'); + $this->assertNotNull($loaded_group, t('Group was loaded')); + } + + /** + * Delete a group. + */ + function testDeleteGroup() { + + $data = array( + 'format_type' => 'fieldset', + 'label' => 'testing', + ); + + $group = $this->createGroup('node', $this->type, 'form', 'default', $data); + + $this->drupalPostForm('admin/structure/types/manage/' . $this->type . '/form-display/' . $group->group_name . '/delete', array(), t('Delete')); + $this->assertRaw(t('The group %label has been deleted from the %type content type.', array('%label' => $group->label, '%type' => $this->type)), t('Group removal message displayed on screen.')); + + $display = EntityFormDisplay::load($group->entity_type . '.' . $group->bundle . '.' . $group->mode); + $data = $display->getThirdPartySettings('field_group'); + + // Test that group is not in the $groups array. + \Drupal::entityTypeManager()->getStorage('entity_form_display')->resetCache(); + $loaded_group = field_group_load_field_group($group->group_name, 'node', $this->type, 'form', 'default'); + $this->assertNull($loaded_group, t('Group not found after deleting')); + + $data = array( + 'format_type' => 'fieldset', + 'label' => 'testing', + ); + + $group = $this->createGroup('node', $this->type, 'view', 'default', $data); + + $this->drupalPostForm('admin/structure/types/manage/' . $this->type . '/display/' . $group->group_name . '/delete', array(), t('Delete')); + $this->assertRaw(t('The group %label has been deleted from the %type content type.', array('%label' => $group->label, '%type' => $this->type)), t('Group removal message displayed on screen.')); + + // Test that group is not in the $groups array. + \Drupal::entityTypeManager()->getStorage('entity_view_display')->resetCache(); + $loaded_group = field_group_load_field_group($group->group_name, 'node', $this->type, 'view', 'default'); + $this->assertNull($loaded_group, t('Group not found after deleting')); + } + + /** + * Nest a field underneath a group. + */ + function testNestField() { + + $data = array( + 'format_type' => 'fieldset', + ); + + $group = $this->createGroup('node', $this->type, 'form', 'default', $data); + + $edit = array( + 'fields[body][parent]' => $group->group_name, + ); + $this->drupalPostForm('admin/structure/types/manage/' . $this->type . '/form-display', $edit, t('Save')); + $this->assertRaw(t('Your settings have been saved.'), t('Settings saved')); + + $group = field_group_load_field_group($group->group_name, 'node', $this->type, 'form', 'default'); + $this->assertTrue(in_array('body', $group->children), t('Body is a child of %group', array('%group' => $group->group_name))); + } + +} diff --git a/modules/field_group/templates/field-group-accordion-item.html.twig b/modules/field_group/templates/field-group-accordion-item.html.twig new file mode 100644 index 00000000..a19a87d0 --- /dev/null +++ b/modules/field_group/templates/field-group-accordion-item.html.twig @@ -0,0 +1,39 @@ +{# +/** + * @file + * Default theme implementation for a fieldgroup accordion item. + * + * Available variables: + * - title: Title of the group. + * - children: The children of the group. + * - label_attributes: A list of HTML attributes for the label. + * - attributes: A list of HTML attributes for the group wrapper. + * + * @see template_preprocess_field_group_accordion() + * + * @ingroup themeable + */ +#} +{% + + set label_classes = [ + 'field-group-format-toggler', + 'accordion-item', + open ? 'field-group-accordion-active', + ] + +%} + +{% + set classes = [ + 'field-group-format-wrapper', + ] +%} + +

    + {{ title }} +

    +
    + {% if description %}
    {% endif %} + {{children}} +
    \ No newline at end of file diff --git a/modules/field_group/templates/field-group-accordion.html.twig b/modules/field_group/templates/field-group-accordion.html.twig new file mode 100644 index 00000000..c21b692e --- /dev/null +++ b/modules/field_group/templates/field-group-accordion.html.twig @@ -0,0 +1,21 @@ +{# +/** + * @file + * Default theme implementation for a fieldgroup accordion item. + * + * Available variables: + * - children: The children of the group. + * - attributes: A list of HTML attributes for the group wrapper. + * + * @see template_preprocess_field_group_accordion() + * + * @ingroup themeable + */ +#} +{% + set classes = [ + 'field-group-accordion-wrapper', + ] +%} + +
    {{ children }}
    diff --git a/modules/field_group/templates/field-group-html-element.html.twig b/modules/field_group/templates/field-group-html-element.html.twig new file mode 100644 index 00000000..73072fcc --- /dev/null +++ b/modules/field_group/templates/field-group-html-element.html.twig @@ -0,0 +1,30 @@ +{# +/** + * @file + * Default theme implementation for a fieldgroup html element. + * + * Available variables: + * - title: Title of the group. + * - title_element: Element to wrap the title. + * - children: The children of the group. + * - wrapper_element: The html element to use + * - attributes: A list of HTML attributes for the group wrapper. + * + * @see template_preprocess_field_group_html_element() + * + * @ingroup themeable + */ +#} + +<{{ wrapper_element }} {{ attributes }}> + {% if title %} + <{{ title_element }}{% if collapsible %} class="field-group-toggler"{% endif %}>{{ title }} + {% endif %} + {% if collapsible %} +
    + {% endif %} + {{children}} + {% if collapsible %} +
    + {% endif %} + \ No newline at end of file diff --git a/modules/field_group/templates/horizontal-tabs.html.twig b/modules/field_group/templates/horizontal-tabs.html.twig new file mode 100644 index 00000000..9ed2a3a1 --- /dev/null +++ b/modules/field_group/templates/horizontal-tabs.html.twig @@ -0,0 +1,15 @@ +{# +/** + * @file + * Default theme implementation for horizontal tabs. + * + * Available variables + * - attributes: A list of HTML attributes for the wrapper element. + * - children: The rendered children. + * + * @see template_preprocess_horizontal_tabs() + * + * @ingroup themeable + */ +#} +
    {{ children }}
    diff --git a/modules/field_group/templates/theme.inc b/modules/field_group/templates/theme.inc new file mode 100644 index 00000000..2f0d20a9 --- /dev/null +++ b/modules/field_group/templates/theme.inc @@ -0,0 +1,94 @@ +getName() == 'field_no_access') { + return AccessResult::forbidden(); + } + + return AccessResult::neutral(); + +} + diff --git a/modules/field_group/tests/src/FunctionalJavascript/FieldGroupUiTest.php b/modules/field_group/tests/src/FunctionalJavascript/FieldGroupUiTest.php new file mode 100644 index 00000000..13d7e620 --- /dev/null +++ b/modules/field_group/tests/src/FunctionalJavascript/FieldGroupUiTest.php @@ -0,0 +1,96 @@ +drupalCreateUser(array('access content', 'administer content types', 'administer node fields', 'administer node form display', 'administer node display', 'bypass node access')); + $this->drupalLogin($admin_user); + + // Create content type, with underscores. + $type_name = Unicode::strtolower($this->randomMachineName(8)) . '_test'; + $type = NodeType::create([ + 'name' => $type_name, + 'type' => $type_name, + ]); + $type->save(); + $this->nodeType = $type->id(); + } + + public function testCreateAndEdit() { + foreach (['test_1', 'test_2'] as $name) { + $group = array( + 'group_formatter' => 'details', + 'label' => 'Test 1', + 'group_name' => $name, + ); + + // Add new group on the 'Manage form display' page. + $this->drupalPostForm('admin/structure/types/manage/' . $this->nodeType . '/form-display/add-group', $group, t('Save and continue')); + $this->drupalPostForm(NULL, [], t('Create group')); + } + + // Update title in group 1 + $page = $this->getSession()->getPage(); + $page->pressButton('group_test_1_group_settings_edit'); + $this->assertSession()->assertWaitOnAjaxRequest(); + $page->fillField('fields[group_test_1][settings_edit_form][settings][label]', 'Test 1 - Update'); + $page->pressButton('Update'); + $this->assertSession()->assertWaitOnAjaxRequest(); + + // Update title in group 2 + $page->pressButton('group_test_2_group_settings_edit'); + $this->assertSession()->assertWaitOnAjaxRequest(); + $page->fillField('fields[group_test_2][settings_edit_form][settings][label]', 'Test 2 - Update'); + $page->pressButton('Update'); + $this->assertSession()->assertWaitOnAjaxRequest(); + + // Open group 1 again + $page->pressButton('group_test_1_group_settings_edit'); + $this->assertSession()->assertWaitOnAjaxRequest(); + $this->assertSession()->fieldValueEquals('fields[group_test_1][settings_edit_form][settings][label]', 'Test 1 - Update'); + $page->pressButton('Cancel'); + $this->assertSession()->assertWaitOnAjaxRequest(); + + $page->pressButton('Save'); + + /** @var EntityFormDisplayInterface $display */ + $display = EntityFormDisplay::load("node.{$this->nodeType}.default"); + $this->assertSame('Test 1 - Update', $display->getThirdPartySetting('field_group', 'group_test_1')['label']); + $this->assertSame('Test 1 - Update', $display->getThirdPartySetting('field_group', 'group_test_1')['format_settings']['label']); + + $this->assertSame('Test 2 - Update', $display->getThirdPartySetting('field_group', 'group_test_2')['label']); + $this->assertSame('Test 2 - Update', $display->getThirdPartySetting('field_group', 'group_test_2')['format_settings']['label']); + } + +} diff --git a/modules/login_destination/LICENSE.txt b/modules/login_destination/LICENSE.txt new file mode 100644 index 00000000..d159169d --- /dev/null +++ b/modules/login_destination/LICENSE.txt @@ -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. + + + Copyright (C) + + 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. + + , 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. diff --git a/modules/login_destination/README.txt b/modules/login_destination/README.txt new file mode 100644 index 00000000..f83ee80d --- /dev/null +++ b/modules/login_destination/README.txt @@ -0,0 +1,31 @@ +The Login Destination module provides a way to customize the destination that a +user is redirected to after logging in, registering to the site, using a +one-time login link or logging out. + +The configuration consists of specifying so called login destination rules that +are evaluated when the login or logout takes place. Those rules are evaluated +against certain conditions and the user is taken to the destination specified +by the first matching rule. If the destination is empty, no redirect is +performed aka user is taken to the default destination. You can define pages +from which a user logs in/out to be a matching criterion. You can also select +certain user roles that are matched against those of a user. Note that only one +role has to match in order for the redirect to take place. If no roles are +selected the redirect is performed regardless of user roles. + +The destination you specify can be an internal page or an external URL. +Remember to precede the url with http://. You can also use the tag to +redirect to the front page. In case of +login/register form the page from which the user entered the form is treated as +the current page. Note that if you provide your own login/logout links you have +to add the 'current' GET parameter to them so Login Destination knows where +your users come from. + +It also possible to set some advanced parameters on the setting page. Every +time in Drupal you can specify the 'destination' GET parameter in url to +redirect the user to a custom page. If you check the option +'Preserve the destination parameter' Login Destination will give priority to +this parameter over its own module settings. However with this option enabled +the redirect from the login block will not work. In some rare cases you can +also redirect the user just after using the one-time login link, before given +the possibility to change their password. Do this by checking the +'Redirect immediately after using one-time login link' option. diff --git a/modules/login_destination/composer.json b/modules/login_destination/composer.json new file mode 100644 index 00000000..339bfbab --- /dev/null +++ b/modules/login_destination/composer.json @@ -0,0 +1,5 @@ +{ + "name": "drupal/login_destination", + "description": "The Login Destination module add possibility customize the destination that the user is redirected to after login.", + "type": "drupal-module" +} diff --git a/modules/login_destination/config/install/login_destination.settings.yml b/modules/login_destination/config/install/login_destination.settings.yml new file mode 100644 index 00000000..8083316c --- /dev/null +++ b/modules/login_destination/config/install/login_destination.settings.yml @@ -0,0 +1,2 @@ +preserve_destination: FALSE +immediate_redirect: FALSE diff --git a/modules/login_destination/config/schema/login_destination.schema.yml b/modules/login_destination/config/schema/login_destination.schema.yml new file mode 100644 index 00000000..0bf05a87 --- /dev/null +++ b/modules/login_destination/config/schema/login_destination.schema.yml @@ -0,0 +1,34 @@ +login_destination.destination.*: + type: config_entity + label: 'Login destination configuration entity' + mapping: + name: + type: string + label: 'Login destination rule machine name' + label: + type: string + label: 'Short description of the rule' + triggers: + type: array + label: 'Triggers' + destination_path: + type: string + label: 'Destination' + pages_type: + type: integer + label: 'Pages type' + pages: + type: string + label: 'Pages' + roles: + type: array + label: 'Roles' + weight: + type: integer + label: 'Weight' + enabled: + type: boolean + label: 'Enabled' + uuid: + type: string + label: 'UUID' diff --git a/modules/login_destination/config/schema/login_destination.settings.yml b/modules/login_destination/config/schema/login_destination.settings.yml new file mode 100644 index 00000000..cf22ec35 --- /dev/null +++ b/modules/login_destination/config/schema/login_destination.settings.yml @@ -0,0 +1,10 @@ +login_destination.settings: + type: config_object + label: 'Login destination settings' + mapping: + preserve_destination: + type: boolean + label: 'Preserve the destination parameter' + immediate_redirect: + type: boolean + label: 'Redirect immediately after using one-time login link' diff --git a/modules/login_destination/login_destination.info.yml b/modules/login_destination/login_destination.info.yml new file mode 100644 index 00000000..b2276b94 --- /dev/null +++ b/modules/login_destination/login_destination.info.yml @@ -0,0 +1,12 @@ +name: Login Destination +type: module +description: Add possibility customize the destination that the user is redirected to after login. +package: User +# core: 8.x +configure: login_destination.settings + +# Information added by Drupal.org packaging script on 2017-05-10 +version: '8.x-1.x-dev' +core: '8.x' +project: 'login_destination' +datestamp: 1494452588 diff --git a/modules/login_destination/login_destination.links.action.yml b/modules/login_destination/login_destination.links.action.yml new file mode 100644 index 00000000..f471bac5 --- /dev/null +++ b/modules/login_destination/login_destination.links.action.yml @@ -0,0 +1,5 @@ +login_destination.add: + route_name: login_destination.add + title: 'Add Login Destination' + appears_on: + - login_destination.list diff --git a/modules/login_destination/login_destination.links.menu.yml b/modules/login_destination/login_destination.links.menu.yml new file mode 100644 index 00000000..ea72d542 --- /dev/null +++ b/modules/login_destination/login_destination.links.menu.yml @@ -0,0 +1,6 @@ +login_destination.list: + title: 'Login destinations' + parent: user.admin_index + description: 'Customize the destination that the user is redirected to after login.' + weight: -5 + route_name: login_destination.list diff --git a/modules/login_destination/login_destination.links.task.yml b/modules/login_destination/login_destination.links.task.yml new file mode 100644 index 00000000..1f10816f --- /dev/null +++ b/modules/login_destination/login_destination.links.task.yml @@ -0,0 +1,9 @@ +login_destination.list: + title: 'Login destinations' + route_name: login_destination.list + base_route: login_destination.list + +login_destination.settings: + title: 'Settings' + route_name: login_destination.settings + base_route: login_destination.list diff --git a/modules/login_destination/login_destination.module b/modules/login_destination/login_destination.module new file mode 100644 index 00000000..27ed7da7 --- /dev/null +++ b/modules/login_destination/login_destination.module @@ -0,0 +1,124 @@ +' . t('About') . ''; + $output .= '

    ' . t('The Login Destination module allows you to customize the destination that the user is redirected to after logging in, registering to the site, using a one-time login link or logging out. The destination can be an internal page or an external URL. You may specify certain conditions like pages or user roles and make the destination depend upon them.') . '

    '; + $output .= '

    ' . t('Uses') . '

    '; + $output .= '
    '; + $output .= '
    ' . t('Creating login destinations') . '
    '; + $output .= '
    ' . t('Users with sufficient permissions can create login destination through the !link. The page listing the login destinations provides an interface to add, edit and delete them', [ + '!link' => (string) \Drupal::l('Login destination page', Url::fromRoute('login_destination.list')), + ]) . '
    '; + $output .= '
    ' . t('Assigning destinations') . '
    '; + $output .= '
    ' . t('You can add login destinations and specify the page where the user will be redirected when it logs in or logs out. You can also configure specific pages where the destination can work or not and select for what user roles the login destination applies') . '
    '; + $output .= '
    '; + return $output; + + case 'login_destination.list': + $output = '

    ' . t('Login destination rules are evaluated each time a user logs in, registers to the site, uses a one-time login link or logs out. Each rule consists of the destination, path conditions and user roles conditions. First matching rule gets executed.') . '

    '; + return $output; + } +} + +/** + * Implements hook_user_login(). + */ +function login_destination_user_login(AccountInterface $account) { + if (isset($account->user_is_new) && $account->user_is_new) { + // User is just registered. + login_destination_perform_redirect('registration', $account); + } + elseif (\Drupal::service('current_route_match')->getRouteName() === 'user.reset.login') { + // User is used a one-time login link. + login_destination_perform_redirect('one-time-login', $account); + } + else { + login_destination_perform_redirect('login', $account); + } +} + +/** + * Implements hook_user_logout(). + */ +function login_destination_user_logout(AccountInterface $account) { + login_destination_perform_redirect('logout', $account); +} + +/** + * Implements hook_toolbar_alter(). + */ +function login_destination_toolbar_alter(&$items) { + if (empty($items['user']['tray']['user_links'])) { + return; + } + // Disable cache for user links in toolbar, to be able set current param. + $items['user']['tray']['user_links']['#cache']['context'] = []; + $items['user']['tray']['user_links']['#cache']['max-age'] = 0; + + if (\Drupal::currentUser()->isAnonymous()) { + $url = &$items['user']['tray']['user_links']['#links']['login']['url']; + // Change route name, since route "user.page" always redirects to "user.login". + $url = Url::fromRoute('user.login'); + } + else { + $url = &$items['user']['tray']['user_links']['#links']['logout']['url']; + } + // Get current path. + $current = \Drupal::service('path.current')->getPath(); + + // Add current param to be able to evaluate previous page. + $url->setOptions(['query' => ['current' => $current]]); +} + +/** + * Implements hook_entity_presave(). + */ +function login_destination_entity_presave(EntityInterface $entity) { + // Verify that entity is a user entity, and this is new entity. + if (!$entity instanceof UserInterface || !$entity->isNew()) { + return; + } + // Save parameter to user entity, which will allow us understand that user + // is just created. Do not need to save parameter, when needs verification + // by administrator. + $needs_verification = \Drupal::config('user.settings')->get('verify_mail'); + if ($needs_verification || !$entity->isActive()) { + return; + } + $entity->user_is_new = TRUE; +} + +/** + * Evaluate rules and perform redirect. + * + * This function is intended to be used by external modules. + * + * @param string $trigger + * Action of login destination rule. + * @param \Drupal\Core\Session\AccountInterface $account + * User Account. + */ +function login_destination_perform_redirect($trigger, AccountInterface $account) { + /** @var Drupal\login_destination\LoginDestinationManager $service */ + $service = \Drupal::service('login_destination.manager'); + $destination = $service->findDestination($trigger, $account); + if ($destination) { + $service->prepareDestination($destination); + } +} diff --git a/modules/login_destination/login_destination.permissions.yml b/modules/login_destination/login_destination.permissions.yml new file mode 100644 index 00000000..03d6971a --- /dev/null +++ b/modules/login_destination/login_destination.permissions.yml @@ -0,0 +1,2 @@ +administer login destination settings: + title: 'Administer Login Destination settings' diff --git a/modules/login_destination/login_destination.routing.yml b/modules/login_destination/login_destination.routing.yml new file mode 100644 index 00000000..ef926fe2 --- /dev/null +++ b/modules/login_destination/login_destination.routing.yml @@ -0,0 +1,40 @@ +login_destination.settings: + path: '/admin/config/people/login-destination/settings' + defaults: + _form: '\Drupal\login_destination\Form\LoginDestinationSettingsForm' + _title: 'Login destination Settings' + requirements: + _permission: 'administer login destination settings' + +login_destination.list: + path: '/admin/config/people/login-destination' + defaults: + _content: '\Drupal\Core\Entity\Controller\EntityListController::listing' + _entity_list: 'login_destination' + _title: 'Login destinations' + requirements: + _permission: 'administer login destination settings' + +login_destination.add: + path: '/admin/config/people/login-destination/add' + defaults: + _entity_form: login_destination.add + _title: 'Add login destination rule' + requirements: + _permission: 'administer login destination settings' + +entity.login_destination.edit_form: + path: '/admin/config/people/login-destination/{login_destination}/edit' + defaults: + _entity_form: login_destination.edit + _title: 'Edit login destination rule' + requirements: + _permission: 'administer login destination settings' + +entity.login_destination.delete_form: + path: '/admin/config/people/login-destination/{login_destination}/delete' + defaults: + _entity_form: login_destination.delete + _title: 'Delete login destination rule' + requirements: + _permission: 'administer login destination settings' diff --git a/modules/login_destination/login_destination.services.yml b/modules/login_destination/login_destination.services.yml new file mode 100644 index 00000000..9e495323 --- /dev/null +++ b/modules/login_destination/login_destination.services.yml @@ -0,0 +1,4 @@ +services: + login_destination.manager: + class: Drupal\login_destination\LoginDestinationManager + arguments: ['@entity_type.manager', '@path.alias_manager', '@path.matcher', '@path.current', '@redirect.destination', '@config.factory', '@request_stack'] diff --git a/modules/login_destination/src/Controller/LoginDestinationListBuilder.php b/modules/login_destination/src/Controller/LoginDestinationListBuilder.php new file mode 100644 index 00000000..1523ad16 --- /dev/null +++ b/modules/login_destination/src/Controller/LoginDestinationListBuilder.php @@ -0,0 +1,84 @@ + $this->t('Label'), + 'destination' => $this->t('Destination'), + 'triggers' => $this->t('Triggers'), + 'pages' => $this->t('Pages'), + 'roles' => $this->t('Roles'), + 'enabled' => $this->t('Enabled'), + ]; + return $header + parent::buildHeader(); + } + + /** + * {@inheritdoc} + */ + public function buildRow(EntityInterface $entity) { + /** @var LoginDestination $entity */ + $row['label'] = $entity->getLabel(); + $row['destination'] = [ + '#type' => 'link', + '#title' => $entity->viewDestination(), + '#url' => Url::fromUri($entity->getDestination()), + ]; + $row['triggers'] = [ + '#markup' => $entity->viewTriggers(), + ]; + $row['pages'] = [ + '#markup' => $entity->viewPages(), + ]; + $row['roles'] = [ + '#markup' => $entity->viewRoles(), + ]; + $row['enabled'] = [ + '#type' => 'checkbox', + '#default_value' => $entity->isEnabled(), + ]; + return $row + parent::buildRow($entity); + } + + /** + * {@inheritdoc} + */ + public function submitForm(array &$form, FormStateInterface $form_state) { + parent::submitForm($form, $form_state); + foreach ($form_state->getValue($this->entitiesKey) as $id => $value) { + // Save entity only when its weight was changed. + $this->entities[$id]->set('enabled', $value['enabled']); + $this->entities[$id]->save(); + } + } + +} diff --git a/modules/login_destination/src/Entity/LoginDestination.php b/modules/login_destination/src/Entity/LoginDestination.php new file mode 100644 index 00000000..adeda688 --- /dev/null +++ b/modules/login_destination/src/Entity/LoginDestination.php @@ -0,0 +1,333 @@ +name; + } + + /** + * @inheritdoc + */ + public function getLabel() { + return $this->label; + } + + /** + * @inheritdoc + */ + public function getMachineName() { + return $this->name; + } + + /** + * @inheritdoc + */ + public function getTriggers() { + return $this->triggers; + } + + /** + * @inheritdoc + */ + public function getDestination() { + return $this->destination_path; + } + + /** + * @inheritdoc + */ + public function getPagesType() { + return $this->pages_type; + } + + /** + * @inheritdoc + */ + public function getPages() { + return $this->pages; + } + + /** + * @inheritdoc + */ + public function getRoles() { + return $this->roles; + } + + /** + * @inheritdoc + */ + public function getWeight() { + return $this->weight; + } + + /** + * {@inheritdoc} + */ + public function viewTriggers() { + $items = []; + foreach ($this->triggers as $trigger) { + if (empty($trigger)) { + continue; + } + switch ($trigger) { + case LoginDestination::TRIGGER_REGISTRATION: + $items[] = t('Registration'); + break; + + case LoginDestination::TRIGGER_LOGIN: + $items[] = t('Login'); + break; + + case LoginDestination::TRIGGER_ONE_TIME_LOGIN: + $items[] = t('One-time login link'); + break; + + case LoginDestination::TRIGGER_LOGOUT: + $items[] = t('Logout'); + break; + } + } + return $this->renderItemList($items, t('All triggers')); + } + + /** + * {@inheritdoc} + */ + public function viewRoles() { + $roles = $this->getAllSystemRoles(); + $items = array_values(array_intersect_key($roles, $this->roles)); + return $this->renderItemList($items, t('All roles')); + } + + /** + * {@inheritdoc} + */ + public function viewPages() { + $type = $this->pages_type; + $pages = trim($this->pages); + + if (empty($pages)) { + if ($type == self::REDIRECT_NOT_LISTED) { + return t('All pages'); + } + return t('No pages'); + } + + $pages = explode("\n", preg_replace('/\r/', '', $this->pages)); + $items = []; + foreach ($pages as $page) { + $items[] = $type == self::REDIRECT_NOT_LISTED ? '~ ' . $page : $page; + } + + return $this->renderItemList($items, t('Empty')); + } + + /** + * {@inheritdoc} + */ + public function viewDestination() { + $url = Url::fromUri($this->destination_path); + $label = $this->destination_path; + if ($url->isExternal()) { + return Html::escape($label); + } + $scheme = parse_url($this->destination_path, PHP_URL_SCHEME); + if ($scheme === 'internal') { + return t('Internal destination'); + } + if ($scheme === 'entity') { + $params = $url->getRouteParameters(); + $entity = \Drupal::entityTypeManager() + ->getStorage('node') + ->load(reset($params)); + return $entity->get('title')->value; + } + + return Html::escape($this->destination_path); + } + + /** + * Render item list. + * + * @param array $array + * List of items. + * @param string $empty_message + * Default empty message. + * + * @return string|\Drupal\Core\Render\Markup + * List of items or empty message. + */ + protected function renderItemList(array $array, $empty_message) { + $items = []; + foreach ($array as $value) { + if (!empty($value)) { + $items[] = Html::escape($value); + } + } + + if (count($items) === 0) { + return $empty_message; + } + + $item_list = [ + '#theme' => 'item_list', + '#items' => $items, + '#list_type' => 'ul', + ]; + return \Drupal::service('renderer')->render($item_list); + } + + /** + * Get all roles in the system. + * + * @return array + * List of system roles. + */ + public function getAllSystemRoles() { + $role_options = []; + foreach (user_roles(TRUE) as $role) { + $role_options[$role->id()] = $role->label(); + } + return $role_options; + } + + /** + * {@inheritdoc} + */ + public function isEnabled() { + return $this->enabled; + } + +} diff --git a/modules/login_destination/src/Form/LoginDestinationDeleteRuleForm.php b/modules/login_destination/src/Form/LoginDestinationDeleteRuleForm.php new file mode 100644 index 00000000..0305fa19 --- /dev/null +++ b/modules/login_destination/src/Form/LoginDestinationDeleteRuleForm.php @@ -0,0 +1,52 @@ +entity; + return $this->t('Are you sure you want to delete the login destination "@destination"?', [ + '@destination' => $login_destination->getLabel(), + ]); + } + + /** + * {@inheritdoc} + */ + public function getCancelUrl() { + return new Url('login_destination.list'); + } + + /** + * {@inheritdoc} + */ + public function getConfirmText() { + return $this->t('Delete'); + } + + /** + * {@inheritdoc} + */ + public function submitForm(array &$form, FormStateInterface $form_state) { + /** @var $login_destination \Drupal\login_destination\Entity\LoginDestination */ + $login_destination = $this->entity; + $login_destination->delete(); + drupal_set_message($this->t('The login destination %destination has been deleted.', [ + '%destination' => $login_destination->getLabel(), + ])); + $form_state->setRedirectUrl($this->getCancelUrl()); + } + +} diff --git a/modules/login_destination/src/Form/LoginDestinationRuleForm.php b/modules/login_destination/src/Form/LoginDestinationRuleForm.php new file mode 100644 index 00000000..aba4a659 --- /dev/null +++ b/modules/login_destination/src/Form/LoginDestinationRuleForm.php @@ -0,0 +1,299 @@ +loginDestinationStorage = $login_destination_storage; + } + + /** + * {@inheritdoc} + */ + public static function create(ContainerInterface $container) { + return new static($container->get('entity_type.manager') + ->getStorage('login_destination')); + } + + /** + * {@inheritdoc} + */ + public function form(array $form, FormStateInterface $form_state) { + /** @var $login_destination LoginDestination */ + $login_destination = $this->entity; + + $form['label'] = [ + '#type' => 'textfield', + '#title' => $this->t('Label'), + '#default_value' => $login_destination->getLabel(), + '#description' => $this->t('A short description of this login destination rule.'), + '#required' => TRUE, + ]; + + $form['name'] = [ + '#type' => 'machine_name', + '#machine_name' => [ + 'exists' => [$this->loginDestinationStorage, 'load'], + ], + '#disabled' => !$login_destination->isNew(), + '#default_value' => $login_destination->id(), + '#required' => TRUE, + '#description' => $this->t('A unique machine-readable name for this login destination rule.'), + ]; + + $form['triggers'] = [ + '#type' => 'checkboxes', + '#title' => $this->t('Redirect upon triggers'), + '#options' => [ + LoginDestination::TRIGGER_REGISTRATION => $this->t('Registration'), + LoginDestination::TRIGGER_LOGIN => $this->t('Login'), + LoginDestination::TRIGGER_ONE_TIME_LOGIN => $this->t('One-time login link'), + LoginDestination::TRIGGER_LOGOUT => $this->t('Logout'), + ], + '#required' => TRUE, + '#default_value' => !empty($login_destination->triggers) ? $login_destination->getTriggers() : [], + '#description' => $this->t('Redirect only upon selected trigger(s).'), + ]; + + $form['destination_path'] = [ + '#type' => 'entity_autocomplete', + '#target_type' => 'node', + '#placeholder' => '', + '#attributes' => [ + 'data-autocomplete-first-character-blacklist' => '/#?', + ], + '#title' => $this->t('Redirect destination'), + '#default_value' => $this->getUriAsDisplayableString($login_destination->getDestination()), + '#element_validate' => [[$this, 'validateUriElement']], + '#maxlength' => 2048, + '#required' => TRUE, + '#process_default_value' => FALSE, + '#description' => $this->t('Start typing the title of a piece of content to select it. You can also enter an internal path such as %add-node or an external URL such as %url. Enter %front to link to the front page.', [ + '%front' => '', + '%add-node' => '/node/add', + '%url' => 'http://example.com', + ]), + ]; + + $form['pages_type'] = [ + '#type' => 'radios', + '#title' => $this->t('Redirect from specific pages'), + '#default_value' => $login_destination->getPagesType(), + '#options' => [ + $login_destination::REDIRECT_NOT_LISTED => $this->t('All pages except those listed'), + $login_destination::REDIRECT_LISTED => $this->t('Only the listed pages'), + ], + ]; + + $form['pages'] = [ + '#type' => 'textarea', + '#default_value' => $login_destination->getPages(), + '#description' => $this->t('Specify pages by using their paths. Enter one path per line. The \'*\' character is a wildcard. Example paths are %blog for the blog page and %blog-wildcard for every personal blog. %front is the front page. %login is the login form. %register is the registration form. %reset is the one-time login (e-mail validation).', [ + '%blog' => 'blog', + '%blog-wildcard' => '/blog/*', + '%front' => '', + '%login' => '/user', + '%register' => '/user/register', + '%reset' => '/user/*/edit', + ]), + ]; + + $form['roles'] = [ + '#type' => 'checkboxes', + '#title' => $this->t('Redirect users with roles'), + '#options' => $login_destination->getAllSystemRoles(), + '#default_value' => $login_destination->getRoles(), + '#description' => $this->t('Redirect only the selected role(s). If you select no roles, all users will be redirected.'), + ]; + + $form['uuid'] = [ + '#type' => 'value', + '#value' => $login_destination->get('uuid'), + ]; + + return parent::form($form, $form_state); + } + + /** + * {@inheritdoc} + */ + public function validateForm(array &$form, FormStateInterface $form_state) { + parent::validateForm($form, $form_state); + // Get selected roles. + $roles = array_filter($form_state->getValue('roles')); + + // Set filtered values. + $form_state->setValue('roles', $roles); + $form_state->setValue('triggers', array_filter($form_state->getValue('triggers'))); + + // Get entered by user destination path. + $destination = $form_state->getValue('destination_path'); + // @todo verify that selected role has access to entered path. + // @todo verify entered paths to specific pages. + } + + /** + * {@inheritdoc} + */ + public function save(array $form, FormStateInterface $form_state) { + /** @var $login_destination \Drupal\login_destination\Entity\LoginDestination */ + $login_destination = $this->entity; + + if ($login_destination->save()) { + drupal_set_message($this->t('Saved the %label login destination.', [ + '%label' => $login_destination->getLabel(), + ])); + } + else { + drupal_set_message($this->t('The %label login destination was not saved.', [ + '%label' => $login_destination->getLabel(), + ])); + } + $form_state->setRedirect('login_destination.list'); + } + + /** + * Form element validation handler for the 'uri' element. + * + * Disallows saving inaccessible or untrusted URLs. + * + * @see LinkWidget::validateUriElement() + */ + public function validateUriElement($element, FormStateInterface $form_state, $form) { + $uri = $this->getUserEnteredStringAsUri($element['#value']); + $form_state->setValueForElement($element, $uri); + + // If getUserEnteredStringAsUri() mapped the entered value to a 'internal:' + // URI , ensure the raw value begins with '/', '?' or '#'. + // @todo '' is valid input for BC reasons, may be removed by + // https://www.drupal.org/node/2421941 + if (parse_url($uri, PHP_URL_SCHEME) === 'internal' && !in_array($element['#value'][0], [ + '/', + '?', + '#', + ], TRUE) && substr($element['#value'], 0, 7) !== '' + ) { + $form_state->setError($element, t('Manually entered paths should start with /, ? or #.')); + return; + } + } + + /** + * Gets the URI without the 'internal:' or 'entity:' scheme. + * + * The following two forms of URIs are transformed: + * - 'entity:' URIs: to entity autocomplete ("label (entity id)") strings; + * - 'internal:' URIs: the scheme is stripped. + * + * This method is the inverse of ::getUserEnteredStringAsUri(). + * + * @param string $uri + * The URI to get the displayable string for. + * + * @return string + * + * @see LinkWidget::getUriAsDisplayableString() + */ + protected function getUriAsDisplayableString($uri) { + $scheme = parse_url($uri, PHP_URL_SCHEME); + + // By default, the displayable string is the URI. + $displayable_string = $uri; + + // A different displayable string may be chosen in case of the 'internal:' + // or 'entity:' built-in schemes. + if ($scheme === 'internal') { + $uri_reference = explode(':', $uri, 2)[1]; + + // @todo '' is valid input for BC reasons, may be removed by + // https://www.drupal.org/node/2421941 + $path = parse_url($uri, PHP_URL_PATH); + if ($path === '/') { + $uri_reference = '' . substr($uri_reference, 1); + } + + $displayable_string = $uri_reference; + } + elseif ($scheme === 'entity') { + list($entity_type, $entity_id) = explode('/', substr($uri, 7), 2); + // Show the 'entity:' URI as the entity autocomplete would. + $entity_manager = \Drupal::entityTypeManager(); + if ($entity_manager->getDefinition($entity_type, FALSE) && $entity = \Drupal::entityTypeManager() + ->getStorage($entity_type) + ->load($entity_id) + ) { + $displayable_string = EntityAutocomplete::getEntityLabels(array($entity)); + } + } + + return $displayable_string; + } + + /** + * Gets the user-entered string as a URI. + * + * The following two forms of input are mapped to URIs: + * - entity autocomplete ("label (entity id)") strings: to 'entity:' URIs; + * - strings without a detectable scheme: to 'internal:' URIs. + * + * This method is the inverse of ::getUriAsDisplayableString(). + * + * @param string $string + * The user-entered string. + * + * @return string + * The URI, if a non-empty $uri was passed. + * + * @see LinkWidget::getUserEnteredStringAsUri() + */ + protected function getUserEnteredStringAsUri($string) { + // By default, assume the entered string is an URI. + $uri = $string; + + // Detect entity autocomplete string, map to 'entity:' URI. + $entity_id = EntityAutocomplete::extractEntityIdFromAutocompleteInput($string); + if ($entity_id !== NULL) { + // @todo Support entity types other than 'node'. Will be fixed in + // https://www.drupal.org/node/2423093. + $uri = 'entity:node/' . $entity_id; + } + // Detect a schemeless string, map to 'internal:' URI. + elseif (!empty($string) && parse_url($string, PHP_URL_SCHEME) === NULL) { + // @todo '' is valid input for BC reasons, may be removed by + // https://www.drupal.org/node/2421941 + // - '' -> '/' + // - '#foo' -> '/#foo' + if (strpos($string, '') === 0) { + $string = '/' . substr($string, strlen('')); + } + $uri = 'internal:' . $string; + } + + return $uri; + } + +} diff --git a/modules/login_destination/src/Form/LoginDestinationSettingsForm.php b/modules/login_destination/src/Form/LoginDestinationSettingsForm.php new file mode 100644 index 00000000..1b9cfad7 --- /dev/null +++ b/modules/login_destination/src/Form/LoginDestinationSettingsForm.php @@ -0,0 +1,60 @@ +config('login_destination.settings'); + $form['settings']['preserve_destination'] = [ + '#type' => 'checkbox', + '#default_value' => $config->get('preserve_destination'), + '#title' => t('Preserve the destination parameter'), + '#description' => t("The 'destination' GET parameter will have priority over the settings of this module. With this setting enabled, redirect from the user login block will not work."), + ]; + $form['settings']['immediate_redirect'] = [ + '#type' => 'checkbox', + '#default_value' => $config->get('immediate_redirect'), + '#title' => t('Redirect immediately after using one-time login link'), + '#description' => t('User will be redirected before given the possibility to change their password.'), + ]; + + return parent::buildForm($form, $form_state); + } + + /** + * @inheritdoc + */ + public function submitForm(array &$form, FormStateInterface $form_state) { + $config = $this->config('login_destination.settings'); + $config->set('preserve_destination', $form_state->getValue('preserve_destination')); + $config->set('immediate_redirect', $form_state->getValue('immediate_redirect')); + $config->save(); + + parent::submitForm($form, $form_state); + } + +} diff --git a/modules/login_destination/src/LoginDestinationInterface.php b/modules/login_destination/src/LoginDestinationInterface.php new file mode 100644 index 00000000..6bacf176 --- /dev/null +++ b/modules/login_destination/src/LoginDestinationInterface.php @@ -0,0 +1,117 @@ +entityTypeManager = $entity_type_manager; + $this->aliasManager = $alias_manager; + $this->pathMatcher = $path_matcher; + $this->currentPath = $current_path; + $this->redirectDestination = $redirect_destination; + $this->configFactory = $config_factory; + $this->requestStack = $request_stack; + } + + /** + * {@inheritdoc} + */ + public function findDestination($trigger, AccountInterface $account) { + $destinations = $this->entityTypeManager->getStorage('login_destination') + ->loadMultiple(); + uasort($destinations, '\Drupal\login_destination\Entity\LoginDestination::sort'); + + $path = $this->getCurrentPath(); + $path_alias = Unicode::strtolower($this->aliasManager->getAliasByPath($path)); + + // Get user roles. + $user_roles = $account->getRoles(); + + /** @var LoginDestination $destination */ + foreach ($destinations as $destination) { + if (!$destination->isEnabled()) { + continue; + } + + // Determine if the trigger matches that of the login destination rule. + $destination_triggers = $destination->getTriggers(); + if (!in_array($trigger, $destination_triggers)) { + continue; + } + $destination_roles = $destination->getRoles(); + + $role_match = array_intersect($user_roles, $destination_roles); + // Ensure the user logging in has a role allowed by the login destination rule. + // Or Login Destination Rule does not have any selected roles. + if (empty($role_match) && !empty($destination_roles)) { + continue; + } + + $pages = Unicode::strtolower($destination->getPages()); + if (!empty($pages)) { + $type = $destination->getPagesType(); + $page_match = $this->pathMatcher->matchPath($path_alias, $pages) || $this->pathMatcher->matchPath($path, $pages); + + // Make sure the page matches(or does not match if the rule specifies that). + if (($page_match && $type == $destination::REDIRECT_LISTED) || (!$page_match && $type == $destination::REDIRECT_NOT_LISTED)) { + + return $destination; + } + continue; + } + + return $destination; + } + + return FALSE; + } + + /** + * {@inheritdoc} + */ + public function prepareDestination(LoginDestination $destination) { + // Get config with settings. + $config = $this->configFactory->get('login_destination.settings'); + // Get current destination value. + $drupal_destination = $this->redirectDestination->getAsArray(); + + // Determine if a destination exist in the URL. + if (!empty($drupal_destination['destination']) && $config->get('preserve_destination')) { + return; + } + + // Prepare destination path. + $path = $destination->getDestination(); + $path_destination = Url::fromUri($path)->toString(); + + // Set destination to current request. + $this->requestStack->getCurrentRequest()->query->set('destination', $path_destination); + } + + /** + * Get current path. + * + * @return string + */ + protected function getCurrentPath() { + $current = $this->requestStack->getCurrentRequest()->get('current', ''); + if (empty($current)) { + $current = $this->currentPath->getPath(); + } + return $current; + } + +} diff --git a/modules/login_destination/src/LoginDestinationManagerInterface.php b/modules/login_destination/src/LoginDestinationManagerInterface.php new file mode 100644 index 00000000..46c1b797 --- /dev/null +++ b/modules/login_destination/src/LoginDestinationManagerInterface.php @@ -0,0 +1,33 @@ + + Copyright (C) + + 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. + + , 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. diff --git a/modules/ng_lightbox/README.txt b/modules/ng_lightbox/README.txt new file mode 100644 index 00000000..e7bf686a --- /dev/null +++ b/modules/ng_lightbox/README.txt @@ -0,0 +1,17 @@ +## Setup + +Go to example.com/admin/config/media/ng-lightbox and configure the paths you would +like to be auto-lightboxed. + +Anything that runs through theme_link() and mentioned on the admin page is lightboxed, if you +want to manually apply the lightbox to a link, simply add the "ng-lightbox" class to the anchor. + +## Rebuilding SASS + +If you're contributing to ng_lightbox you can re-generate the css with the +following command from within the ng_lightbox folder. + + compass compile --no-sourcemap --no-debug-info --force -e production sass/lightbox.scss + +If you're simply using the ng_lightbox module and want to have your own theme you can copy the +sass file into your theme and begin customising from there. diff --git a/modules/ng_lightbox/config/install/ng_lightbox.settings.yml b/modules/ng_lightbox/config/install/ng_lightbox.settings.yml new file mode 100644 index 00000000..9240be8c --- /dev/null +++ b/modules/ng_lightbox/config/install/ng_lightbox.settings.yml @@ -0,0 +1,5 @@ +patterns: '' +default_width: 700 +lightbox_class: '' +skip_admin_paths: true +renderer: 'drupal_modal' diff --git a/modules/ng_lightbox/config/schema/ng_lightbox.schema.yml b/modules/ng_lightbox/config/schema/ng_lightbox.schema.yml new file mode 100755 index 00000000..7318a143 --- /dev/null +++ b/modules/ng_lightbox/config/schema/ng_lightbox.schema.yml @@ -0,0 +1,19 @@ +ng_lightbox.settings: + type: config_object + label: 'NG Lightbox settings.' + mapping: + patterns: + type: string + label: 'The path patterns to try match.' + default_width: + type: integer + label: 'The default width of the lightbox.' + lightbox_class: + type: string + label: 'The custom class of the lightbox.' + skip_admin_paths: + type: boolean + label: 'Whether to disable the lightbox on admin pages.' + renderer: + type: string + label: 'The renderer used to launch a the lightbox.' diff --git a/modules/ng_lightbox/ng_lightbox.info.yml b/modules/ng_lightbox/ng_lightbox.info.yml new file mode 100644 index 00000000..43867763 --- /dev/null +++ b/modules/ng_lightbox/ng_lightbox.info.yml @@ -0,0 +1,15 @@ +name: NG Lightbox +description: A path based lightbox solution using CSS 3 properties. +type: module +# core: 8.x +package: NG +configure: ng_lightbox.settings + +files: + - ng_lightbox.test + +# Information added by Drupal.org packaging script on 2017-03-06 +version: '8.x-1.0-beta3' +core: '8.x' +project: 'ng_lightbox' +datestamp: 1488844686 diff --git a/modules/ng_lightbox/ng_lightbox.libraries.yml b/modules/ng_lightbox/ng_lightbox.libraries.yml new file mode 100644 index 00000000..dbc2cd3b --- /dev/null +++ b/modules/ng_lightbox/ng_lightbox.libraries.yml @@ -0,0 +1,5 @@ +ng_lightbox: + version: VERSION + js: {} + dependencies: + - core/drupal.ajax diff --git a/modules/ng_lightbox/ng_lightbox.links.menu.yml b/modules/ng_lightbox/ng_lightbox.links.menu.yml new file mode 100644 index 00000000..daebdfad --- /dev/null +++ b/modules/ng_lightbox/ng_lightbox.links.menu.yml @@ -0,0 +1,5 @@ +ng_lightbox.settings: + title: NG Lightbox + description: 'Configure the NG Lightbox settings.' + route_name: ng_lightbox.settings + parent: system.admin_config_media diff --git a/modules/ng_lightbox/ng_lightbox.module b/modules/ng_lightbox/ng_lightbox.module new file mode 100644 index 00000000..8cd87463 --- /dev/null +++ b/modules/ng_lightbox/ng_lightbox.module @@ -0,0 +1,37 @@ +isNgLightboxEnabledPath($vars['url'])) { + $lightbox->addLightbox($vars); + } + elseif (!empty($vars['options']['attributes']['class'])) { + // We have to normalize to an array because many places incorrectly set + // class to a string. + $vars['options']['attributes']['class'] = (array) $vars['options']['attributes']['class']; + + if (in_array('ng-lightbox', $vars['options']['attributes']['class'])) { + $lightbox->addLightbox($vars); + } + } + + // If you've enabled/disabled the modal for admin paths this allows you to + // override it for one off paths. + \Drupal::moduleHandler()->alter('ng_lightbox_ajax_path', $vars); +} + +/** + * Implements hook_page_attachments(). + */ +function ng_lightbox_page_attachments(array &$attachments) { + $attachments['#attached']['library'][] = 'ng_lightbox/ng_lightbox'; +} diff --git a/modules/ng_lightbox/ng_lightbox.permissions.yml b/modules/ng_lightbox/ng_lightbox.permissions.yml new file mode 100644 index 00000000..46b0ae08 --- /dev/null +++ b/modules/ng_lightbox/ng_lightbox.permissions.yml @@ -0,0 +1,4 @@ +administer ng lightbox: + title: 'Administer NG Lightbox' + description: 'Allow users to administer the NG Lightbox settings.' + restrict access: true diff --git a/modules/ng_lightbox/ng_lightbox.routing.yml b/modules/ng_lightbox/ng_lightbox.routing.yml new file mode 100644 index 00000000..df4f933a --- /dev/null +++ b/modules/ng_lightbox/ng_lightbox.routing.yml @@ -0,0 +1,7 @@ +ng_lightbox.settings: + path: '/admin/config/media/ng-lightbox' + defaults: + _form: '\Drupal\ng_lightbox\Form\NgLightboxSettingsForm' + _title: 'NG Lightbox' + requirements: + _permission: 'administer ng lightbox' diff --git a/modules/ng_lightbox/ng_lightbox.services.yml b/modules/ng_lightbox/ng_lightbox.services.yml new file mode 100644 index 00000000..96b15649 --- /dev/null +++ b/modules/ng_lightbox/ng_lightbox.services.yml @@ -0,0 +1,4 @@ +services: + ng_lightbox: + class: Drupal\ng_lightbox\NgLightbox + arguments: ['@path.matcher', '@path.alias_manager', '@config.factory', '@router.admin_context'] diff --git a/modules/ng_lightbox/src/Form/NgLightboxSettingsForm.php b/modules/ng_lightbox/src/Form/NgLightboxSettingsForm.php new file mode 100644 index 00000000..a3796509 --- /dev/null +++ b/modules/ng_lightbox/src/Form/NgLightboxSettingsForm.php @@ -0,0 +1,116 @@ +renderers = $lightbox_renderers; + } + + /** + * {@inheritdoc} + */ + public static function create(ContainerInterface $container) { + return new static( + $container->get('config.factory'), + $container->getParameter('ng_lightbox_renderers') + ); + } + + /** + * {@inheritdoc} + */ + public function buildForm(array $form, FormStateInterface $form_state) { + $this->config = $this->configFactory()->getEditable('ng_lightbox.settings'); + + $form['container']['patterns'] = array( + '#type' => 'textarea', + '#title' => $this->t('Paths'), + '#default_value' => $this->config->get('patterns'), + '#description' => $this->t('New line separated paths that must start with a leading slash. Wildcard character is *. E.g. /comment/*/reply.'), + ); + $form['container']['default_width'] = array( + '#type' => 'textfield', + '#title' => $this->t('Default Width'), + '#default_value' => $this->config->get('default_width'), + '#description' => $this->t('The default width for modals opened with NG Lightbox.'), + ); + $form['container']['lightbox_class'] = array( + '#type' => 'textfield', + '#title' => $this->t('Lightbox Class'), + '#default_value' => $this->config->get('lightbox_class'), + '#description' => $this->t('The css custom class for modals opened with NG Lightbox.'), + ); + $form['container']['skip_admin_paths'] = array( + '#title' => $this->t('Skip all admin paths'), + '#type' => 'checkbox', + '#default_value' => $this->config->get('skip_admin_paths'), + '#description' => $this->t('This will exclude all admin paths from the lightbox. If you want some paths, see hook_ng_lightbox_ajax_path_alter().'), + ); + $form['container']['renderer'] = array( + '#title' => $this->t('Renderer'), + '#type' => 'select', + '#default_value' => $this->config->get('renderer') ?: NgLightbox::DEFAULT_MODAL, + '#description' => $this->t('Select which renderer should be used for the lightbox.'), + '#options' => $this->renderers, + ); + + return parent::buildForm($form, $form_state); + } + + /** + * {@inheritdoc} + */ + public function submitForm(array &$form, FormStateInterface $form_state) { + $values = $form_state->getValues(); + $this->config + ->set('patterns', $values['patterns']) + ->set('default_width', $values['default_width']) + ->set('lightbox_class', $values['lightbox_class']) + ->set('skip_admin_paths', $values['skip_admin_paths']) + ->set('renderer', $values['renderer']) + ->save(); + } + + /** + * {@inheritdoc} + */ + public function getFormId() { + return 'ng_lightbox_settings'; + } + + /** + * {@inheritdoc} + */ + protected function getEditableConfigNames() { + return []; + } + +} diff --git a/modules/ng_lightbox/src/NgLightbox.php b/modules/ng_lightbox/src/NgLightbox.php new file mode 100644 index 00000000..65ae0815 --- /dev/null +++ b/modules/ng_lightbox/src/NgLightbox.php @@ -0,0 +1,152 @@ +pathMatcher = $path_matcher; + $this->aliasManager = $alias_manager; + $this->config = $config_factory->get('ng_lightbox.settings'); + $this->adminContext = $admin_context; + } + + /** + * Checks whether a give path matches the ng-lightbox path rules. + * This function checks both internal paths and aliased paths. + * + * @param \Drupal\Core\Url $url + * The Url object. + * + * @return bool + * TRUE if it matches the given rules. + */ + public function isNgLightboxEnabledPath(Url $url) { + + // No lightbox on external Urls. + if ($url->isExternal()) { + return FALSE; + } + + // If we don't want to enable the Lightbox on admin pages. + if ($this->config->get('skip_admin_paths') && $this->adminContext->isAdminRoute()) { + return FALSE; + } + + // @TODO, decide whether we want to try and support paths or to adopt routes + // like core is trying to force us into. + $path = strtolower($url->toString()); + + // We filter out empty paths because some modules (such as Media) use + // theme_link() to generate links with empty paths and we filter out paths + // that do not start with a /, such as #hash-only URLs. + if (empty($path) || $path[0] !== '/') { + return FALSE; + } + + // Remove the base path. + if ($base_path = \Drupal::request()->getBasePath()) { + $path = substr($path, strlen($base_path)); + } + + // Check the cache, see if we've handled this before. + if (isset($this->matches[$path])) { + return $this->matches[$path]; + } + + // Normalise the patterns as well so they match the normalised paths. + $patterns = strtolower($this->config->get('patterns')); + + // Check for internal paths first which is much quicker than the alias lookup. + if ($this->pathMatcher->matchPath($path, $patterns)) { + $this->matches[$path] = TRUE; + } + else { + // Now check for aliases paths. + $aliased_path = strtolower($this->aliasManager->getAliasByPath($path)); + if ($path != $aliased_path && $this->pathMatcher->matchPath($aliased_path, $patterns)) { + $this->matches[$path] = TRUE; + } + else { + // No match. + $this->matches[$path] = FALSE; + } + } + + return $this->matches[$path]; + } + + /** + * Adds a lightbox to a link. + * + * @param array $link + * The link we want to add the lightbox to. + */ + public function addLightbox(array &$link) { + // Safety check if class isn't an array. + if (!isset($link['options']['attributes']['class'])) { + $link['options']['attributes']['class'] = array(); + } + + // Add our lightbox class. + $link['options']['attributes']['class'][] = 'use-ajax'; + $link['options']['attributes']['data-dialog-type'] = str_replace('drupal_', '', $this->config->get('renderer') ?: static::DEFAULT_MODAL); + $data = [ + 'width' => $this->config->get('default_width'), + 'dialogClass' => $this->config->get('lightbox_class'), + ]; + + $link['options']['attributes']['data-dialog-options'] = json_encode($data); + } + +} diff --git a/modules/ng_lightbox/src/NgLightboxPass.php b/modules/ng_lightbox/src/NgLightboxPass.php new file mode 100644 index 00000000..7dca32e3 --- /dev/null +++ b/modules/ng_lightbox/src/NgLightboxPass.php @@ -0,0 +1,34 @@ +findTaggedServiceIds('render.main_content_renderer') as $id => $attributes_list) { + foreach ($attributes_list as $attributes) { + if (!empty($attributes['ng_lightbox'])) { + $format = $attributes['format']; + $lightbox_renderers[$format] = $attributes['ng_lightbox']; + } + } + } + $container->setParameter('ng_lightbox_renderers', $lightbox_renderers); + } + +} diff --git a/modules/ng_lightbox/src/NgLightboxServiceProvider.php b/modules/ng_lightbox/src/NgLightboxServiceProvider.php new file mode 100644 index 00000000..cb12d587 --- /dev/null +++ b/modules/ng_lightbox/src/NgLightboxServiceProvider.php @@ -0,0 +1,53 @@ +addCompilerPass(new NgLightboxPass()); + } + + /** + * {@inheritdoc} + */ + public function alter(ContainerBuilder $container) { + $this->addLightbox($container, 'main_content_renderer.dialog', 'Core Dialog'); + $this->addLightbox($container, 'main_content_renderer.modal', 'Core Modal'); + } + + /** + * @param \Drupal\Core\DependencyInjection\ContainerBuilder $container + * @param $id + * @param $title + */ + protected function addLightbox(ContainerBuilder $container, $id, $title) { + $definition = $container->getDefinition($id); + $tags = $definition->getTags(); + + foreach ($tags as $delta => &$tag) { + if ($delta === 'render.main_content_renderer') { + foreach ($tag as &$attribute) { + $attribute['ng_lightbox'] = $title; + } + } + } + + $definition->setTags($tags); + } + +} diff --git a/modules/ng_lightbox/src/Tests/NgLightboxTest.php b/modules/ng_lightbox/src/Tests/NgLightboxTest.php new file mode 100644 index 00000000..fb94c82a --- /dev/null +++ b/modules/ng_lightbox/src/Tests/NgLightboxTest.php @@ -0,0 +1,131 @@ +installSchema('system', ['router', 'url_alias']); + \Drupal::service('router.builder')->rebuild(); + + $this->installEntitySchema('node'); + $this->installEntitySchema('user'); + $this->installSchema('node', ['node_access']); + $this->installConfig(['ng_lightbox']); + + // Create the node type. + NodeType::create(['type' => 'page'])->save(); + } + + /** + * Test the pattern matching for link paths. + */ + public function testPatternMatching() { + + // Test the patterns are enabled on links as expected. + $node = Node::create(['type' => 'page', 'title' => $this->randomString()]); + $node->save(); + $config = \Drupal::configFactory()->getEditable('ng_lightbox.settings'); + $config->set('patterns', $node->url())->save(); + $this->assertLightboxEnabled(\Drupal::l('Normal Path', $node->urlInfo())); + + // Create a second node and make sure it doesn't get lightboxed. + $node = Node::create(['type' => 'page', 'title' => $this->randomString()]); + $node->save(); + $this->assertLightboxNotEnabled(\Drupal::l('Normal Path', $node->urlInfo())); + + + // @TODO, these were in D7 but in D8, I can't see how you can even generate + // a link with such a format so maybe it isn't needed at all? + // The uppercase path should still be matched for a lightbox. + // $this->assertLightboxNotEnabled(\Drupal::l('Uppercase Path', 'NODE/1')); + // $this->assertLightboxNotEnabled(\Drupal::l('Alaised Path', $alias)); + // $this->assertLightboxNotEnabled(\Drupal::l('Empty Path', '')); + } + + /** + * Asserts the lightbox was enabled for the generated link. + * + * @param string $link + * The rendered link. + */ + protected function assertLightboxEnabled($link) { + $this->assertContains('use-ajax', $link); + $this->assertContains('data-dialog-type', $link); + } + + /** + * Asserts the lightbox was not enabled for the generated link. + * + * @param string $link + * The rendered link. + */ + protected function assertLightboxNotEnabled($link) { + $this->assertNotContains('use-ajax', $link); + $this->assertNotContains('data-dialog-type', $link); + } + + /** + * Asserts a string does exist in the haystack. + * + * @param string $needle + * The string to search for. + * @param string $haystack + * The string to search within. + * @param string $message + * The message to log. + * + * @return bool + * TRUE if it was found otherwise FALSE. + */ + protected function assertContains($needle, $haystack, $message = '') { + if (empty($message)) { + $message = t('%needle was found within %haystack', array('%needle' => $needle, '%haystack' => $haystack)); + } + return $this->assertTrue(stripos($haystack, $needle) !== FALSE, $message); + } + + /** + * Asserts a string does not exist in the haystack. + * + * @param string $needle + * The string to search for. + * @param string $haystack + * The string to search within. + * @param string $message + * The message to log. + * + * @return bool + * TRUE if it was not found otherwise FALSE. + */ + protected function assertNotContains($needle, $haystack, $message = '') { + if (empty($message)) { + $message = t('%needle was not found within %haystack', array('%needle' => $needle, '%haystack' => $haystack)); + } + return $this->assertTrue(stripos($haystack, $needle) === FALSE, $message); + } + +} diff --git a/modules/ng_lightbox/src/Tests/NgLightboxWebTest.php b/modules/ng_lightbox/src/Tests/NgLightboxWebTest.php new file mode 100644 index 00000000..ec989bcc --- /dev/null +++ b/modules/ng_lightbox/src/Tests/NgLightboxWebTest.php @@ -0,0 +1,48 @@ +getEditable('ng_lightbox.settings'); + $this->createContentType(['type' => 'page']); + $node = $this->drupalCreateNode(); + $config->set('patterns', '/node/' . $node->id()); + $config->save(); + } + + /** + * Test that we can render a modal even before selecting one from the admin. + */ + public function testDefaultModal() { + $this->drupalGet('/node'); + $this->assertRaw('data-dialog-type="modal"'); + } + +} diff --git a/modules/ng_lightbox/tests/src/Kernel/NgLightboxTest.php b/modules/ng_lightbox/tests/src/Kernel/NgLightboxTest.php new file mode 100644 index 00000000..f01a890e --- /dev/null +++ b/modules/ng_lightbox/tests/src/Kernel/NgLightboxTest.php @@ -0,0 +1,28 @@ +assertFalse($this->container->get('ng_lightbox')->isNgLightboxEnabledPath($url)); + } + +} diff --git a/modules/ng_lightbox/tests/src/Unit/NgLightboxTest.php b/modules/ng_lightbox/tests/src/Unit/NgLightboxTest.php new file mode 100644 index 00000000..eaa5d8be --- /dev/null +++ b/modules/ng_lightbox/tests/src/Unit/NgLightboxTest.php @@ -0,0 +1,84 @@ +getLightbox(); + $this->assertEquals(FALSE, $lightbox->isNgLightboxEnabledPath($this->getUrlMock(TRUE)->reveal())); + } + + /** + * Test the admin_skip_path settings. + */ + public function testAdminSkipPaths() { + // Admin skip paths enabled and admin route. + $lightbox = $this->getLightbox(); + $this->assertEquals(FALSE, $lightbox->isNgLightboxEnabledPath($this->getUrlMock()->reveal())); + } + + /** + * Test with an empty path. + */ + public function testEmptyPath() { + $lightbox = $this->getLightbox(FALSE); + $url = $this->getUrlMock(); + $url->toString()->willReturn(''); + $this->assertEquals(FALSE, $lightbox->isNgLightboxEnabledPath($url->reveal())); + } + + /** + * Helper to create Url mocks. + * + * @param bool|FALSE $is_external + * TRUE if this URL is external otherwise FALSE. + * + * @return \Prophecy\Prophecy\ObjectProphecy + * The url prophecy for testing. + */ + protected function getUrlMock($is_external = FALSE) { + $url = $this->prophesize('Drupal\Core\Url'); + $url->isExternal()->willReturn($is_external); + return $url; + } + + /** + * Get the lightbox service setup for testing. + * + * @return \Drupal\ng_lightbox\NgLightbox + * The lightbox service. + */ + protected function getLightbox($skip_admin_paths = TRUE, $is_admin_route = TRUE) { + + $path_matcher = $this->prophesize('Drupal\Core\Path\PathMatcherInterface'); + $alias_manager = $this->prophesize('Drupal\Core\Path\AliasManagerInterface'); + $config_factory = $this->prophesize('Drupal\Core\Config\ConfigFactoryInterface'); + $config = $this->prophesize('Drupal\Core\Config\ImmutableConfig'); + $config->get(Argument::exact('skip_admin_paths'))->willReturn($skip_admin_paths); + $config_factory->get(Argument::exact('ng_lightbox.settings'))->willReturn($config); + $admin_context = $this->prophesize('Drupal\Core\Routing\AdminContext'); + $admin_context->isAdminRoute()->willReturn($is_admin_route); + + $lightbox = new NgLightbox($path_matcher->reveal(), $alias_manager->reveal(), $config_factory->reveal(), $admin_context->reveal()); + + return $lightbox; + } + +} diff --git a/profiles/README.txt b/profiles/README.txt new file mode 100644 index 00000000..b0f0c0ba --- /dev/null +++ b/profiles/README.txt @@ -0,0 +1,28 @@ +Installation profiles define additional steps that run after the base +installation of Drupal is completed. They may also offer additional +functionality and change the behavior of the site. + +WHAT TO PLACE IN THIS DIRECTORY? +-------------------------------- + +Place downloaded and custom installation profiles in this directory. +Note that installation profiles are generally provided as part of a Drupal +distribution. + +DOWNLOAD ADDITIONAL DISTRIBUTIONS +--------------------------------- + +Contributed distributions from the Drupal community may be downloaded at +https://www.drupal.org/project/project_distribution. + +MULTISITE CONFIGURATION +----------------------- + +In multisite configurations, installation profiles found in this directory are +available to all sites during their initial site installation. + +MORE INFORMATION +---------------- + +Refer to the "Installation profiles" section of the README.txt in the Drupal +root directory for further information on extending Drupal with custom profiles. diff --git a/robots.txt b/robots.txt new file mode 100644 index 00000000..13483a81 --- /dev/null +++ b/robots.txt @@ -0,0 +1,61 @@ +# +# robots.txt +# +# This file is to prevent the crawling and indexing of certain parts +# of your site by web crawlers and spiders run by sites like Yahoo! +# and Google. By telling these "robots" where not to go on your site, +# you save bandwidth and server resources. +# +# This file will be ignored unless it is at the root of your host: +# Used: http://example.com/robots.txt +# Ignored: http://example.com/site/robots.txt +# +# For more information about the robots.txt standard, see: +# http://www.robotstxt.org/robotstxt.html + +User-agent: * +# CSS, JS, Images +Allow: /core/*.css$ +Allow: /core/*.css? +Allow: /core/*.js$ +Allow: /core/*.js? +Allow: /core/*.gif +Allow: /core/*.jpg +Allow: /core/*.jpeg +Allow: /core/*.png +Allow: /core/*.svg +Allow: /profiles/*.css$ +Allow: /profiles/*.css? +Allow: /profiles/*.js$ +Allow: /profiles/*.js? +Allow: /profiles/*.gif +Allow: /profiles/*.jpg +Allow: /profiles/*.jpeg +Allow: /profiles/*.png +Allow: /profiles/*.svg +# Directories +Disallow: /core/ +Disallow: /profiles/ +# Files +Disallow: /README.txt +Disallow: /web.config +# Paths (clean URLs) +Disallow: /admin/ +Disallow: /comment/reply/ +Disallow: /filter/tips/ +Disallow: /node/add/ +Disallow: /search/ +Disallow: /user/register/ +Disallow: /user/password/ +Disallow: /user/login/ +Disallow: /user/logout/ +# Paths (no clean URLs) +Disallow: /index.php/admin/ +Disallow: /index.php/comment/reply/ +Disallow: /index.php/filter/tips/ +Disallow: /index.php/node/add/ +Disallow: /index.php/search/ +Disallow: /index.php/user/password/ +Disallow: /index.php/user/register/ +Disallow: /index.php/user/login/ +Disallow: /index.php/user/logout/ diff --git a/sites/README.txt b/sites/README.txt new file mode 100644 index 00000000..0372902f --- /dev/null +++ b/sites/README.txt @@ -0,0 +1,10 @@ +This directory structure contains the settings and configuration files specific +to your site or sites and is an integral part of multisite configurations. + +It is now recommended to place your custom and downloaded extensions in the +/modules, /themes, and /profiles directories located in the Drupal root. The +sites/all/ subdirectory structure, which was recommended in previous versions +of Drupal, is still supported. + +See core/INSTALL.txt for information about single-site installation or +multisite configuration. diff --git a/update.php b/update.php new file mode 100644 index 00000000..59e808ed --- /dev/null +++ b/update.php @@ -0,0 +1,31 @@ +handle($request); +$response->send(); + +$kernel->terminate($request, $response); diff --git a/vendor/web.config b/vendor/web.config new file mode 100644 index 00000000..2e065e26 --- /dev/null +++ b/vendor/web.config @@ -0,0 +1,7 @@ + + + + + + + diff --git a/web.config b/web.config new file mode 100644 index 00000000..3fc5b10a --- /dev/null +++ b/web.config @@ -0,0 +1,103 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +