Droptica: How to Perform a Drupal Security Audit? Overview of the Modules and Libraries

.

A security audit is the process of identifying security threats that can lead to unauthorised access to content, data leaks, bypassing the security, and other dangers. In the first part of the series on conducting a security audit, we’ll focus on the overview of the Drupal module versions that we use at Droptica for this purpose, as well as on PHP and JavaScript libraries.

Drupal security audit

At Droptica, we make every effort to ensure that the solutions we provide are as safe as possible. We use the tools provided by the Drupal community, such as the Security Review module, to optimize the process of detecting the most popular security errors. We also use the Security Kit to make the project we’re working on more resistant to attacks. You can learn more about the functionality of these modules in the linked posts, and the information on their operation will be useful in the following parts, in which we’ll talk about the Drupal configuration review and code analysis.

Checking the versions of the installed Drupal modules

Updating modules and libraries is the simplest activity that we can perform to improve the security of our application. Drupal provides a view listing all the modules, which additionally indicates whether a given module is up-to-date, and if it isn’t – whether the update contains security fixes.

To check if the modules are up-to-date, go to /admin/modules/update
Checking the versions of Drupal modules as part of security audit

In the screenshot above, you can see that some of the modules need updating. Of course, in such cases we always recommend that you update all possible modules. If any of the modules contain a security fix, the update is required to ensure a high level of security for the application.

In the case of Drupal, the information about whether a given module has a security flaw is made available to the public when the author of the module releases its patched version. Module authors usually try to hide which code has been changed to patch a security flaw, but this always means that the attacker just needs more time to find a way to cause the bug and exploit it. Time is important, so you should keep track of security updates regularly, not only during a Drupal security audit. As we mentioned earlier, this is one of the simplest steps we can take to ensure a higher level of security for our application.

Patches review

When updating the Drupal modules, you should also check if a patch has been applied to a given module. If so, we proceed as follows:

  1. We check whether the patch was created by the community and if it concerns a specific issue on drupal.org. If so, we look for the issue that the patch is from. It’s possible that the patch has been applied to one of the newer versions of the module. In such a case, we recommend updating the module and removing the patch with the information that the code that fixes the bug or adds a given functionality has been applied to the official, newer version of the module. If the patch hasn’t yet been applied to the newer version of the module, we still recommend updating and testing if the latest version of the patch serves its purpose.
  2. If the patch wasn’t created by the Drupal community, but is the result of working on the project, we still recommend updating the module. In this case, however, ensuring the correct operation of the patch lies with the people responsible for the custom code of the project. After updating, you should check whether the patch works as intended. If not, we recommend introducing appropriate fixes to the patch which will ensure its correct operation on the latest version of the module.

PHP libraries review

The next step will be reviewing the used PHP libraries. To list them, we can use the composer show command or the local-php-security-checker package. We recommend the latter solution because it significantly speeds up the process.

Result of the composer show command during the review of the used PHP libraries

Result of the composer show command.

If you choose to install the local-php-security-checker package, follow the guidelines in the README.md file.

Result of the scan using local-php-security-checker during a Drupal security audit

Result of the scan using local-php-security-checker.

There’s also the little-known Drupal Composer Security Checker module that uses the security-checker package. Currently, this module doesn’t fulfill its task and the security-checker package itself isn’t actively developed (since January 2021), therefore we’ll focus on the local-php-security-checker package itself. If you find a security risk, our recommendation will be to update the library, of course – as in any case. An audit of the PHP libraries should be carried out regularly, the same as in the case of the Drupal modules.

JavaScript libraries review

The next step will be to check if the used JavaScript libraries are up-to-date and if they contain security fixes. To do this, you should review the library directory and the used package.json files.

In the case of the library directory, you need to check the version manually. In the case of package.json, we use the npm-audit command.

Result of the npm-audit command checking the package.json during the JavaScript libraries review

Result of the npm-audit command

The npm-audit command will list all known vulnerabilities, determine the threat level, package, dependencies, package path, and show a link with information about the vulnerability.

The npm-audit command shows all vulnerabilities in the JavaScript libraries

If you find a vulnerability, as always we recommend the update. JS library scans should be performed routinely, more often than a comprehensive security audit.

Improving the Drupal security – further steps

In this part of the Drupal security audit cycle, we’ve learned how to check whether the used versions of the modules and libraries are up-to-date and don’t contain known security bugs. We also understand how to proceed if there is a patch available for a module – both when the patch comes from the Drupal community and when it was prepared by the developer working on the application.

Acquiring the knowledge provided in this post is the easiest way to improve the security of your application. Checking the versions of the used solutions is the first step that we perform during a security audit – our Drupal support team recommends periodic checking for updates. In the event that an update containing security fixes is released, we recommend that you perform an update as soon as possible.

In the next part of this series of articles, we’ll get to learn more about the Drupal configuration aimed at increasing the security of our application. We’ll also learn how to reduce the number of attack vectors and we’ll find out more about the modules that’ll help us with this.


Go to Source
Author:

Envato Tuts+: Intro to Drupal: Build a Simple CMS

Drupal’s popularity has lately been rising. It’s a great platform for setting up content management systems and community driven sites. Here, I’ll give a general overview of Drupal and build a simple site for a fake client. We’ll begin with outlining the client’s needs, installing and configuring a few modules, creating user roles and assigning permissions, and finally we’ll add in some content. We won’t go into theming, as it’s a bit out of the scope of this article.

Continue reading “Envato Tuts+: Intro to Drupal: Build a Simple CMS”

Envato Tuts+: Top 10 Most Usable Content Management Systems

There are plenty of options when it comes to picking a content management system for a development project. Depending on how advanced you need the CMS to be, what language it’s built in, and who is going to be using it, it can be a nightmare trying to find the “perfect” CMS for a project.

However, some CMSs have a slight edge over the rest of the competition because of the usability of the software. Some are just easier to install, use and extend, thanks to some thoughtful planning by the lead developers. 

We have a number of themes and resources to support these top content management systems. If you’re looking for WordPress Themes, Drupal Themes, or Joomla Themes we have you covered on Envato Market

We support a number of additional popular CMS systems. And a gallery of WordPress Plugins, Drupal Plugins, Joomla plugins and more. Visit our ThemeForest or CodeCanyon marketplaces to browse through a ton of professional options.  

Here are 10 of the most usable CMSs on the web to use in your next project, so you can choose the one that fits your needs best.

1. WordPress

WordPress

What is there left to say about WordPress that hasn’t already been said? The PHP blogging platform is far and away the most popular CMS for blogging, and probably the most popular CMS overall. It’s a great platform for beginners, thanks to their excellent documentation

and super-quick installation wizard. Five minutes to a running CMS is pretty good. Not to mention the fact that the newest versions auto-update the core and plugins from within the backend, without having to download a single file.

For those users not familiar with HTML or other markup language, a WYSIWYG editor is provided straight out of the box. The backend layout is streamlined and intuitive, and a new user should be able to easily find their way around the administration section. Wordpres also comes with built-in image and multimedia uploading support.

For developers, the theming language is fairly simple and straightforward, as well the Plugin API.

The WordPress Community is a faithful and zealous bunch. WordPress probably has the widest base of plugins and themes to choose from. We have thousands of professional WordPress Themes and WordPress Plugins available for sale on Envato Market, with a full suite of styles and options to choose from. 

A great part about the WordPress community is the amount of help and documentation online you can find on nearly every aspect of customizing WordPress. If you can dream it, chances are it’s already been done with WordPress and documented somewhere.

If you need help with anything from installing a theme to optimizing the speed of your WordPress site, you can find plenty of experienced WordPress developers to help you on Envato Studio.

2. Drupal

Drupal

Drupal is another CMS that has a very large, active community. Instead of focusing on blogging as a platform, Drupal is more of a pure CMS. A plain installation comes with a ton of optional modules that can add lots of interesting features like forums, user blogs, OpenID, profiles and more. It’s trivial to create a site with social features with a simple install of Drupal. In fact, with a few 3rd party modules you can create some interesting site clones with little effort.

One of Drupal’s most popular features is the Taxonomy module, a feature that allows for multiple levels and types of categories for content types. And you can find plenty of professional Drupal Themes, which are ready to be customized and worked with. You can also grab Drupal Plugins.

Drupal also has a very active community powering it, and has excellent support for plugins and other general questions. 

You can also hire a developer to complete a range of tasks for your Drupal site for a reasonable fixed fee.

3. Joomla!

Joomla

Joomla is a very advanced CMS in terms of functionality. That said, getting started with Joomla is fairly easy, thanks to Joomla’s installer. Joomla’s installer is meant to work on common shared hosting packages, and is a very straightforward considering how configurable the software is.

Joomla is very similar to Drupal in that it’s a complete CMS, and might be a bit much for a simple portfolio site. It comes with an attractive administration interface, complete with intuitive drop-down menus and other features. The CMS also has great support for access control protocols like LDAP, OpenID and even Gmail.com.

The Joomla site hosts more than 3,200 extensions, so you know the developer community behind the popular CMS is alive and kicking. Like WordPress, you can add just about any needed functionality with an extension. However, the Joomla theme and extension community relies more on paid resources, so if you’re looking for customizations, be ready to pull out your wallet. You can also grab Joomla plugins, or hire Joomla developers to help you get your store set up right.

4. ExpressionEngine

EE

ExpressionEngine (EE) is an elegant, flexible CMS solution for any type of project. Designed to be extensible and easy to modify, EE sets itself apart in how clean and intuitive their user administration area is. It takes only a matter of minutes to understand the layout of the backend and to start creating content or modify the look. It’s fantastic for creating websites for less-than-savvy clients that need to use the backend without getting confused.

ExpressionEngine is packed with helpful features like the ability to have multiple sites with one installation of software. For designers, EE has a powerful templating engine that has custom global variables, custom SQL queries and a built in versioning system. Template caching, query caching and tag caching keep the site running quickly too.

One of my favorite features of EE that is the global search and replace functionality. Anyone who’s ever managed a site or blog knows how useful it is to change lots of data without having to manually search and open each page or post to modify it.

ExpressionEngine is quite different than other previously-mentioned CMS in that it’s paid software. The personal license costs $99.95, and the commercial license costs $249.99. You can also get help with ExpressionEngine on Envato Studio.

5. TextPattern

Textpattern

Textpattern is a popular choice for designers because of its simple elegance. Textpattern isn’t a CMS that throws in every feature it can think of. The code base is svelte and minimal. The main goal of Textpattern is to provide an excellent CMS that creates well-structured, standards-compliant pages. Instead of providing a WYSIWYG editor, Textpattern uses textile markup in the textareas to create HTML elements within the pages. The pages that are generated are extremely lightweight and fast-loading.

Even though Textpattern is deliberately simple in design, the backend is surprisingly easy to use and intuitive. New users should be able to find their way around the administration section easily.

While Textpattern may be very minimal at the core level, you can always extend the functionality by 3rd party extensions, mods or plugins. Textpattern has an active developer community with lots of help and resources at their Textpattern.org site.

6. Radiant CMS

Radiant

The content management systems that we’ve listed so far are all PHP programs. PHP is the most popular language for web development, but that doesn’t mean we should overlook other popular web languages like Ruby. Radiant CMS is a fast, minimal CMS that might be compared to Textpattern. Radiant is built on the popular Ruby framework Rails, and the developers behind Radiant have done their best to make the software as simple and elegant as possible, with just the right amount of functionality. Like Textpattern, Radiant doesn’t come with a WYSIWYG editor and relies on Textile markup to create rich HTML. Radiant also has it’s own templating language Radius which is very similar to HTML for intuitive template creation.

7. Cushy CMS

Cushy CMS

Cushy CMS is a different type of CMS altogether. Sure, it has all the basic functionality of a regular content management system, but it doesn’t rely on a specific language. In fact, the CMS is a hosted solution. There are no downloads or future upgrades to worry about.

How Cushy works is it takes FTP info and uploads content on to the server, which in turn the developer or the designer can modify the layout, as well as the posting fields in the backend, just by changing the style classes of the styles. Very, very simple.

Cushy CMS is free for anyone, even for professional use. There is an option to upgrade to a pro account to use your own logo and color scheme, as well as other fine-grain customizations in the way Cushy CMS functions.

8. SilverStripe

SilverStripe

SilverStripe is another PHP CMS that behaves much like WordPress, except has many more configurable options and is tailored towards content management, and not blogging. SilverStripe is unique because it was built upon its very own PHP framework Saphire. It also provides its own templating language to help with the design process.

SilverStripe also has some interesting features built in to the base, like content version control and native SEO support. What’s really unique with SilverStripe is that developers and designers can customize the administration area for their clients, if need be. While the development community isn’t as large as other projects there are some modules, themes and widgets to add functionality. Also, you’ll want to modify the theme for each site, as SilverStripe doesn’t provide much in terms of style, to give the designer more freedom.

9. Alfresco

Alfresco

Alfresco is a JSP is a beefy enterprise content management solution that is surprisingly easy to install. A really useful feature of Alfresco is the ability to drop files into folders and turn them into web documents. Alfresco might be a little bit more work than some of the other CMS and isn’t as beginner-friendly, it certainly is quite usable given the massive power of the system. The administration backend is clean and well-designed.

While Alfresco might not be a great choice for most simple sites, it’s an excellent choice for enterprise needs.

10. TYPOlight

TYPOlight

TYPOlight seems to have the perfect balance of features built into the CMS. In terms of functionality, TYPOlight ranks with Drupal and ExpressionEngine, and even offers some unique bundled modules like newsletters and calendars. Developers can save time with the built-in CSS generator, and there are plenty of resources for learning more about the CMS.

If there is a downside to TYPOlight, it’s that it has so many features and configurable options. Even though the backend is thoughtfully organized, there are still a lot of options to consider. But if you’re wanting to build a site with advanced functionality and little extra programming, TYPOlight could be a great fit.


Go to Source
Author:

Envato Tuts+: Using and Extending the Drupal 8 Mail API: Part 1

In this two part series we are going to explore the Mail API in Drupal 8. In doing so, we are going to cover two main aspects: how to use it programatically for sending emails and how to extend it for using an external service like Mandrill.

To demonstrate this, in the first part we will create a custom email template that gets used for sending emails to the current user when s/he saves a new Article node. Additionally, we will see how others can alter that template in order to allow for HTML rendering of the email body instead of the default plain text.

In the second part we are going to look at extending the mail system and integrating an external API for email delivery. For this, we will use Mandrill and its PHP library that provides a good foundation for interacting with its API.

All the work we go through can be found in this Git repository as part of a custom Drupal 8 module that we will start writing here. So feel free to check that out if you want to follow along. Let’s get started.

The first prerequisite of this module is its .info file:

d8mail.info.yml:

With this out of the way, we can already enable the module on our site if we want.

How Do We Send an Email?

There are two main steps needed to send an email programatically with Drupal 8. We first need to implement hook_mail() in order to define one or more email templates. The second step is to use the mail manager to send emails using one of these templates.

Although called a hook, hook_mail() is not a typical hook but more of a regular function that generally gets called only by the same module that implements it. In other words, when you send an email programatically, you need to specify the module name implementing hook_mail() and the template id you want to use and that is defined by this hook. But we’ll see that in a minute. First, how do we implement it?

d8mail.module:

This is a very simple implementation that defines one template identified as node_insert (the $key). The other two function arguments are:

  • $message: passed by reference, and inside which we add as much boilerplate about our email as we need 
  • $params: an array of extra data that needs to go in the email and that is passed from the mail manager when we try to send the email

As you can see, we are building up the $message array with values we want this email to include in all the calls. We are setting a default from value that is retrieved from the configuration system and that represents the main site email address. We set a boilerplate email subject that lets the recipient know a new node was created, followed by the name of the node (which will be passed in through the $params array). The subject is also translatable into the language that gets passed from the caller. 

Lastly, we run the message body through the string sanitiser because the text may contain HTML and it might get truncated if we don’t encode the HTML elements. And since we are using the SafeMarkup class, we need to use it at the top:

Additionally, the message body is an array that will later be imploded into a string. And obviously there are many other parameters we can set, such as headers, but this will suffice for this example.

And that’s all for the hook_mail() implementation. Now let’s turn to the code which gets run every time a new node is created, hook_entity_insert():

This hook gets triggered after every node save, and all we have to do is make sure we are targeting the correct node and include our logic.

After checking that the node entity is of the type article, we load the Drupal mail manager service and start setting some values for the email. We need the following information:

  • the module name that implements hook_mail() and defines our template (what I mentioned above)
  • the template id (the $key)
  • the recipient email address (the one found on the current user account)
  • the language ($langcode) which goes inside the $params array and which will be used to translate the subject message
  • the node title that will get added to the email subject
  • the email body, which in our case will be the value of the node’s body field
  • the boolean value indicating whether the email should be actually sent

We then pass all these values to the mail() method of the mail manager. The latter is responsible for building the email (calling the right hook_mail() implementation being one aspect of this) and finally delegating the actual delivery to the responsible plugin. By default, this will be PHPMail, which uses the default mail() function that comes with PHP.

If the mail manager is successful in sending the email (actual delivery is not taken into account but rather a successful PHP action), the mail() method will return an array containing a result key with whatever the mail plugin returns. Checking for that value, we can learn whether the email action was successful and inform the user that we have notified them of their action. Otherwise, we print and log an error message.

And that’s about it. Clearing the cache and creating an article node should land an email in your inbox. If you are not getting anything and there are no error signs on your screen, make sure you check your server logs and mail queue to verify that emails are being sent out.

Before moving on, I would like to make a quick note regarding this hook implementation. In this example, I placed all the logic inside it directly. Additionally, I used an early return at the top, which essentially means no other logic can be added but the one specific to the article nodes. In real applications I recommend refactoring the mailing logic into a separate function or class and deferring to that. Moreover, you should not use early returns inside hook implementations but instead call other functions if the conditions are met. 

How Do We Alter an Email?

Once all of this is in place, we have another tool at our disposal that allows us to alter such an existing setup: hook_mail_alter(). This hook is called from within the mail manager before the responsible mail plugin sends the email. The purpose is to allow other modules to perform final alterations to an existent email being sent out.

Although this can be used by other modules as well, we will illustrate an example implementation from within the same module we’ve been working with. To this end, we will alter the email by changing one of its default headers in order to transform it from plain text to HTML. And this is how we can do this:

As you can see, this is a simple alteration of the Content-Type header that transforms the email into HTML. This way plain text HTML entities will be parsed as HTML by mail clients. And using the switch case, we make sure this only happens for the email template we defined earlier.

One thing to note here is that the alter hook gets called after the relevant hook_mail() implementation. So after this, the only processing that happens on the email is done inside the format() method of the mail plugin (enforced by its interface).

Conclusion

And that is pretty much all there is to sending emails programatically using Drupal 8. We’ve seen the steps required to programatically set up email templates that get hydrated by the mail manager whenever we want it. We’ve also mentioned the default mail delivery plugin which is used to send emails in Drupal 8. And lastly, we’ve seen how other modules can now alter our email by adding new headers, changing the subject, concatenating values to the mail body, etc.

In the next article we are going to look at replacing the default PHPMail plugin with our own custom implementation. We will set up a mailer that uses Mandrill with the help of its PHP library. The goal is to allow our own module to use this mailer while the rest of the application continues to use the default PHPMailer.


Go to Source
Author:

Envato Tuts+: Using and Extending the Drupal 8 Mail API: Part 2

In the previous article we looked at how we can send emails programatically in Drupal 8. We also saw how other modules can alter these outgoing mails. Today, we are going to look at how we can use the Mail API to extend this default behaviour. The purpose is to use an external service as a means for email delivery. 

For this, we will use Mandrill, although the focus of the article will not be its API or how to work with it, but rather the Drupal side of things. And remember, the working module can be found in this Git repository.

As we’ve seen in the previous article, sending an email in Drupal 8 happens by requesting the mail manager, passing some parameters to its mail() method, and setting up a template inside a hook_mail() implementation. What the mail manager does internally is load up the appropriate mail plugin, construct the email, and then delegate to the mail() method of whatever plugin was loaded.

But who does it actually delegate to?

Plugin Selection

An important thing to understand before writing our own plugin is the selection process of the mail manager for loading plugins. In other words, how do we know which plugin it will load, and how can we make it load our own?

The system.mail.interface configuration array holds all the answers. It contains the ids of the available plugins, keyed by the context they are used in. By default, all we have inside this configuration is default => phpmail. This means that the plugin with the id phpmail (the PHPMail class) is used as fallback for all contexts that are not otherwise specified, i.e. the default.

If we want to write our own plugin, we need to add another element into that array with the plugin id as its value. The key for this value can be one of two things: the machine name of our module (to load the plugin whenever our module sends emails) or a combination of module name and email template key (to load the plugin whenever our module sends an email using that specific key). 

An example of the latter construct is d8mail_node_insert, where d8mail is our module name we started building in the previous article, and node_insert is the email template key we defined.

So now that we know how the mail plugin selection happens, we need to make sure this config array contains the necessary information so that emails sent with our d8mail module use the new plugin we will build. We can do this inside a hook_install() implementation that gets triggered only once when the module gets installed:

d8mail.install:

Not super complicated what happens above. We load the editable config object representing the system.mail configuration, and add a new element to the interface array: d8mail => mandrill_mail. We will soon create a mail plugin with the id of mandrill_mail which will be used for all emails sent by the d8mail module. And that’s it.

But before we move on, we need to make sure this change is reverted when the module is uninstalled. For this, we can use the counterpart hook_uninstall() that gets called when a module gets uninstalled (there is no more module disabling in Drupal 8).

Inside the same file:

With the hook_uninstall() implementation we do the opposite of before: we remove our plugin id if it is set.

The install/uninstall scenario is just one way to go. You can also create an administration form that allows users to select the plugin they want and under which context. But you still need to make sure that when you disable the module defining a particular plugin, the configuration will no longer keep a reference to that plugin. Otherwise the mail manager may try to use a non-existent class and throw all kinds of errors.

Mandrill

As I mentioned before, we will work with the Mandrill API in order to illustrate our task. So let’s load up Mandrill’s PHP Library and make it available in our environment. There are three steps we need to do for this.

First, we need to actually get the library inside Drupal. At the time of writing, this basically means adding the "mandrill/mandrill": "1.0.*" dependency to the root composer.json file and running composer install. Keep in mind, though, that this will also clear the Drupal installation from inside the core/ folder and download the latest stable release instead. Then, you’ll need to edit the root index.php file and change the path to the autoloader as per these instructions. Hopefully this last action won’t be necessary soon, and I encourage you to follow the discussions around the future of Composer in Drupal 8 for managing external libraries.

Second, we need to get an API key from Mandrill. Luckily, this we can easily generate from their administration pages. Once we have that, we can store it inside a new file created on our server, at either location:

We can also pass the key as a constructor parameter to the main Mandrill class, but this way we won’t have to hardcode it in our code. 

Thirdly, we need to create a service so that we can use dependency injection for passing the Mandrill class into our plugin:

d8mail.services.yml:

Depending on how you have loaded the Mandrill class into your application, you’ll need to change the value after class. By using the composer.json approach, this will suffice.

The Mail Plugin

It’s finally time to create our plugin. In Drupal 8, plugin classes go inside the src/Plugin folder of our module. Depending on their type, however, they are placed further down within other directories (in our case Mail). Let’s write our class that will depend on the Mandrill API library to send emails:

src/Plugin/Mail/MandrillMail.php:

There are a couple of things to note before getting into what the class does.

First, the annotations above the class. This is just the most common plugin discovery mechanism for Drupal 8. The id key matches the value we added to the system.mail.interface configuration array earlier, while the rest are basic plugin definition elements.

Second, the implementation of the ContainerFactoryPluginInterface interface by which we define the create() method. The latter is part of the dependency injection process by which we can load up the Mandrill service we defined in the services.yml file earlier. This makes testing much easier and it’s considered best practice.

As I mentioned, the mail plugins need to implement the MailInterface interface which enforces the existence of the format() and mail() methods. In our case, the first does exactly the same thing as the PHPMail plugin: a bit of processing of the message body. So you can add your own logic here if you want. The latter method, on the other hand, is responsible for sending the mail out, in our case, using the Mandrill API itself.

As the Mandrill documentation instructs, we construct an email message inside the $vars array using values passed from the mail manager through the $message parameter. These will be already filtered through hook_mail(), hook_mail_alter() and the plugin’s own format() method. All that’s left is to actually send the email. I won’t go into the details of using the Mandrill API as you can consult the documentation for all the options you can use.

After sending the email and getting back from Mandrill a sent status, we return the entire response array, which contains some more information. This array then gets added by the mail manager to its own return array keyed as result. If Mandrill has a problem, rejects the email or throws an exception, we return false. This will make the mail manager handle this situation by logging the incident and printing a status message.

And that is pretty much it. We can clear the cache and try creating another article node. This time, the notification email should be sent by Mandrill instead of PHP’s mail(). With this in place, though, the hook_mail_alter() implementation has become superfluous as there are no headers we are actually sending through to Mandrill (and the text is HTML already). And for that matter quite a lot of the work of the mail manager is not used, as we are not passing that on to Mandrill. But this is just meant to illustrate the process of how you can go about setting this up. The details of the implementation remain up to you and your needs.

Conclusion

And there we have it. We have implemented our own mail plugin to be used by the d8module we started in the previous article. And due to the extensible nature of Drupal 8, it didn’t even take too much effort. 

What’s left for you to do is to perfect the mail sending logic and adapt it to your circumstances. This can mean further integration between Mandrill and your Drupal instance, constructing nice templates or what have you. Additionally, an important remaining task is writing automated tests for this functionality. And Drupal 8 offers quite the toolkit for that as well.


Go to Source
Author:

Envato Tuts+: What Is Drupal?

Drupal is a popular open-source content management system written in PHP. Having been created in the early 2000s by a Belgian student, it now powers some of the most prominent websites on the web (WhiteHouse.gov, Weather.com, etc.). It is often regarded as a competitor of CMSs such as WordPress and Joomla.

One of the most important components of the Drupal project is its community of supporters (contributors, developers, evangelists, business owners, etc.). Prominent within this community stands the Drupal Association, responsible for “fostering and supporting the Drupal software project, the community and its growth”.

A giant leap from its predecessor, the 8th major release of the Drupal project has just hit the shelves. It brought about a serious modernisation of its code, practices and mentality. Many regard this shift as a real move away from the traditional notion of a CMS to more of a Content Management Framework (CMF) that provides a great platform for building complex applications.

In this article, I’m going to answer some of the more frequent questions people have about Drupal when starting up for the first time or considering doing so:

  • Is it right for me? Who is it aimed at?
  • How can it be installed, and where can I host it?
  • How can I start working with it as a developer?
  • What options do I have for extending functionality or styling it?

Who Is Drupal Aimed At?

Since the beginning of the project, Drupal has evolved from being mainly a tool for building smaller sites to one that can now power enterprise-level platforms. Especially with Drupal 8, site builders and developers can easily scale up from small websites to large platforms with many integrations. For example, the adoption of Composer allows you not only to bring external libraries into a Drupal project, but also to use Drupal as part of a bigger project of applications and libraries. It’s safe to say that Drupal is flexible enough to meet the needs of a wide range of projects.

When it comes to development, Drupal has always had a relatively closed community—not because people are unfriendly, quite the contrary, but mainly because of the code typically being written in a Drupal way (resulting in what sometimes is referred to as Drupalisms). This has meant a learning curve for any developer starting up, but also less interest from developers of other PHP projects to jump in and contribute.

This is no longer the case. Especially with the release of Drupal 8, the community now promotes a new mentality of code reusability and best practice across different open-source projects. Active participation in the PHP Framework Interoperability Group is part of this effort, and using a number of popular Symfony components in Drupal 8 core is a testament to this commitment. 

With this move, the Drupal community has gotten richer by welcoming many developers from other communities and projects, and it is sure to grow even further. So if you are a Laravel developer, looking at Drupal code will no longer be so daunting.

How Can I Install Drupal, and Where Can I Host It?

Traditionally, Drupal has had a relatively easy installation process, particularly for people who at least knew their way around a Linux environment. The project simply needs to be dropped into a folder your web server can run (which needs to be using PHP and have a MySQL or MariaDB database). Then pointing your browser to the /install.php file and following the steps takes care of the rest. The most important screen you’ll see is the one in which you select a specific database to use.

In terms of requirements, the LAMP stack (Linux, Apache, MySQL and PHP) environment has always been a favourite for Drupal to run in. However, it is in no way restricted to it. Solutions exist for installing it straight on Windows or Mac (e.g. using the Acquia Dev Desktop) but also on a Linux system that runs other web servers.

The easiest approach, if you go with your own setup, is to use a LAMP server for hosting. For a bit more performance you can replace Apache with Nginx, but you’ll then have to take care of some specific configuration that otherwise is handled in the .htaccess file Drupal ships with.

However, if you don’t want the hassle of maintaining your own hosting server, there are three main providers of specialised Drupal managed hosting: Acquia, Pantheon, and Platform.sh. These also provide a workflow for easy updates and development flow. Past that, you are looking at fully managed hosting with a Drupal development company.

How Can I Get Started Developing for It?

Developing Drupal websites has typically been the kind of thing you either liked a lot or didn’t like at all. This is because when you were first introduced to Drupal, you encountered very many specificities that you didn’t see in other projects. So if those tickled your fancy, you loved it forever.

With getting off this island in Drupal 8, this is no longer the case as much. You still have plenty of Drupalisms left that you can love or hate, but you now also have external components like Symfony or Guzzle and, most importantly, a more modern way of writing code in general (OOP, design patterns, reusable components, etc.). So your PHP skills from building websites with Zend will come in handy.

A good way of getting into Drupal development is to follow some online video courses. There are a couple of resources that are excellent for this purpose, most notably Drupalize.me. If, however, video is not your favourite medium, there are also many written tutorials and guides available to get you started. Check out the following links for some of the first steps you can take:

Since Drupal 8 is brand new, you’ll find significantly more learning content for Drupal 7. Nevertheless, the focus in the community has been shifting recently towards Drupal 8, so you can expect more and more of these resources to crop up. And if you have no experience with any version of Drupal, it’s best to focus exclusively on Drupal 8 as the changes between the two are big and perhaps you’d be facing unnecessary challenges.

How Can I Extend Drupal?

The main extension point of a core Drupal installation is its module system. 

Modules are used to encapsulate bigger chunks of reusable functionality that can/should work on different sites. Aside from the core modules, there are a large number of contributed ones, available for installation. 

Granted, most are still only for Drupal 6 and 7, but the community is catching up also for the newest version. This problem is also mitigated by the incorporation in Drupal 8 of a few popular contributed modules as well as extending the scope of what core can do out of the box (compared to Drupal 7). 

Lastly, custom modules (the ones that you write yourself) are the primary way you can add any functionality that you want and that is not available via a contributed module.

Installing modules can allow you to plug in various pieces of functionality, but you should not treat this as a green light for adding too many. It’s always better to stick to the ones you actually need, and don’t be afraid to be critical in this respect. You can also work on finding a good balance between contributed code and the custom one you write yourself. 

Additionally, since we are talking about open-source software, you should always evaluate the modules you install. The following indicators are good examples to pay attention to: number of downloads and usage, commit frequency, maintainer engagement, state of the issue queue.

And do keep security in mind as well. It’s highly recommended you keep both Drupal core and any contributed modules up to date as this will significantly help you keep your site and server secure (though it doesn’t ensure it).

What About Styling?

The styling layer of a Drupal site is handled (in large part) by its theme. Themes are similar to modules in that they are an extension point, but they have different responsibilities. They contain the styles, front-end libraries and in most cases template files that are used to output data.

There has been great progress in Drupal 8 compared to the previous version: the popular Twig engine has been adopted for templating, theming has been limited to Twig template files, debugging and overriding templates has been made much easier, etc. Similar to the advances in back-end development experience (DX), the theming layer has been made more appealing to the non-Drupal crowd. Front-end developers can now easily work with Drupal themes without having to understand the ins and outs of the back end.

Drupal core comes with a number of themes that can provide you with examples but also which you can extend from. There are also contributed themes similar to how there are modules. Popular front-end frameworks such as Bootstrap or Zurb Foundation have mature Drupal theme implementations for Drupal 7, which are also readying for Drupal 8. These work very well as base themes but also for quickly scaffolding a website and making it look decent.

Paid themes are also available to try out. Usually they are very cheap and quick to set up. The problem with them is that they are worth exactly as much as you pay for them and usually have gaping holes in their flexibility. As a beginner, these themes can seem like a great way to set up a site, and they very well may be. However, as you progress, you’ll learn to avoid them and build your own, based on external designs or even plain HTML/CSS/JS templates.

Conclusion

Drupal is a powerful tool for building websites and platforms of any kind. With each new major release, Drupal has shown a commitment to better itself, become more robust and flexible, and embrace outside communities as well.


Go to Source
Author:

Envato Tuts+: Drupal 8: Properly Injecting Dependencies Using DI

As I am sure you know by now, dependency injection (DI) and the Symfony service container are important new development features of Drupal 8. However, even though they are starting to be better understood in the Drupal development community, there is still some lack of clarity about how exactly to inject services into Drupal 8 classes.

Many examples talk about services, but most cover only the static way of loading them:

This is understandable as the proper injection approach is more verbose, and if you know it already, rather boilerplate. However, the static approach in real life should only be used in two cases:

  • in the .module file (outside of a class context)
  • those rare occasions within a class context where the class is being loaded without service container awareness

Other than that, injecting services is the best practice as it ensures decoupled code and eases testing.

In Drupal 8 there are some specificities about dependency injection that you will not be able to understand solely from a pure Symfony approach. So in this article we are going to look at some examples of proper constructor injection in Drupal 8. To this end, but also to cover all the basics, we will look at three types of examples, in order of complexity:

  • injecting services into another of your own services
  • injecting services into non-service classes
  • injecting services into plugin classes

Going forward, the assumption is that you know already what DI is, what purpose it serves and how the service container supports it. If not, I recommend checking out this article first.

Services

Injecting services into your own service is very easy. Since you are the one defining the service, all you have to do is pass it as an argument to the service you want to inject. Imagine the following service definitions:

Here we define two services where the second one takes the first one as a constructor argument. So all we have to do now in the AnotherDemoService class is store it as a local variable:

And that is pretty much it. It’s also important to mention that this approach is exactly the same as in Symfony, so no change here.

Non-Service Classes

Now let’s take a look at classes that we often interact with but that are not our own services. To understand how this injection takes place, you need to understand how the classes are resolved and how they are instantiated. But we will see that in practice soon.

Controllers

Controller classes are mostly used for mapping routing paths to business logic. They are supposed to stay thin and delegate heavier business logic to services. Many extend the ControllerBase class and get some helper methods to retrieve common services from the container. However, these are returned statically.

When a controller object is being created (ControllerResolver::createController), the ClassResolver is used to get an instance of the controller class definition. The resolver is container aware and returns an instance of the controller if the container already has it. Conversely, it instantiates a new one and returns that. 

And here is where our injection takes place: if the class being resolved implements the ContainerAwareInterface, the instantiation takes place by using the static create() method on that class which receives the entire container. And our ControllerBase class also implements the ContainerAwareInterface.

So let’s take a look at an example controller which properly injects services using this approach (instead of requesting them statically):

The EntityListController class doesn’t do anything for our purposes here, so just imagine that BlockListController directly extends the ControllerBase class, which in turn implements the ContainerInjectionInterface.

As we said, when this controller is instantiated, the static create() method is called. Its purpose is to instantiate this class and pass whatever parameters it wants to the class constructor. And since the container is passed to create(), it can choose which services to request and pass along to the constructor. 

Then, the constructor simply has to receive the services and store them locally. Do keep in mind that it’s bad practice to inject the entire container into your class, and you should always limit the services you inject to the ones you need. And if you need too many, you are likely doing something wrong.

We used this controller example to go a bit deeper into the Drupal dependency injection approach and understand how constructor injection works. There are also setter injection possibilities by making classes container aware, but we won’t cover that here. Let’s instead look at other examples of classes you may interact with and in which you should inject services.

Forms

Forms are another great example of classes where you need to inject services. Usually you either extend the FormBase or ConfigFormBase classes which already implement the ContainerInjectionInterface. In this case, if you override the create() and constructor methods, you can inject whatever you want. If you don’t want to extend these classes, all you have to do is implement this interface yourself and follow the same steps we saw above with the controller.

As an example, let’s take a look at the SiteInformationForm which extends the ConfigFormBase and see how it injects services on top of the config.factory its parent needs:

As before, the create() method is used for the instantiation, which passes to the constructor the service required by the parent class as well as some extra ones it needs on top.

And this is pretty much how the basic constructor injection works in Drupal 8. It’s available in almost all class contexts, save for a few in which the instantiation part was not yet solved in this manner (e.g. FieldType plugins). Additionally, there is an important subsystem which has some differences but is crucially important to understand: plugins.

Plugins

The plugin system is a very important Drupal 8 component that powers a lot of functionality. So let’s see how dependency injection works with plugin classes.

The most important difference in how injection is handled with plugins is the interface plugin classes need to implement: ContainerFactoryPluginInterface. The reason is that plugins are not resolved but are managed by a plugin manager. So when this manager needs to instantiate one of its plugins, it will do so using a factory. And usually, this factory is the ContainerFactory (or a similar variation of it). 

So if we look at ContainerFactory::createInstance(), we see that aside from the container being passed to the usual create() method, the $configuration, $plugin_id, and $plugin_definition variables are passed as well (which are the three basic parameters each plugin comes with).

So let’s see two examples of such plugins that inject services. First, the core UserLoginBlock plugin (@Block):

As you can see, it implements the ContainerFactoryPluginInterface and the create() method receives those three extra parameters. These are then passed in the right order to the class constructor, and from the container a service is requested and passed as well. This is the most basic, yet commonly used, example of injecting services into plugin classes.

Another interesting example is the FileWidget plugin (@FieldWidget):

As you can see, the create() method receives the same parameters, but the class constructor expects extra ones that are specific to this plugin type. This is not a problem. They can usually be found inside the $configuration array of that particular plugin and passed from there.

So these are the main differences when it comes to injecting services into plugin classes. There’s a different interface to implement and some extra parameters in the create() method.

Conclusion

As we’ve seen in this article, there are a number of ways we can get our hands on services in Drupal 8. Sometimes we have to statically request them. However, most of the time we shouldn’t. And we’ve seen some typical examples of when and how we should inject them into our classes instead. We’ve also seen the two main interfaces the classes need to implement in order to be instantiated with the container and be ready for injection, as well as the difference between them.

If you are working in a class context and you are unsure of how to inject services, start looking at other classes of that type. If they are plugins, check if any of the parents implement the ContainerFactoryPluginInterface. If not, do it yourself for your class and make sure the constructor receives what it expects. Also check out the plugin manager class responsible and see what factory it uses. 

In other cases, such as with TypedData classes like the FieldType, take a look at other examples in core. If you see others using statically loaded services, it’s most likely not yet ready for injection so you’ll have to do the same. But keep an eye out, because this might change in the future.


Go to Source
Author: