and making sure you are familiar with all the material in it. If you have neverinstalled Drupal at all or tried to use it, you should definitely also do that now (there areinstallation instructions in theINSTALL.txtfile that comes with Drupal, or athttp://drupal.org/documentation/install).After that, you should be ready to start looking at some Drupal programming examples,so I would suggest that you download theExamples for Developersproject fromhttp://drupal.org/project/examples, which is a comprehensive set of programming examplescoveringDrupal core(the base Drupal system, not including add-on modules). TheExamples project is maintained by many contributors within the Drupal community,and it is an excellent resource; its existence has allowed this book to concentrate on thebackground information you will need to become a Drupal programming expert andon giving examples that are beyond the scope of the Examples project.The next step I’d suggest would be to install one or two of the example modules fromthe Examples project, try them out, and then look through their code (check theREADME.txtfile for installation instructions). If there’s a programming topic that you’reparticularly interested in, you could choose an example module on that basis; I wouldparticularly recommend the Block and Page example modules as good general startingpoints. Keep in mind when you are reviewing the code that the official Drupal APIreference site,http://api.drupal.org, is the best place to go to find documentation onparticular Drupal API functions.That should give you a little bit of experience looking at Drupal code, at which point Iwould suggest returning to this book and readingChapter 2andChapter 3carefully, tolearn about the dos and don’ts of Drupal programming. At that point, you should havevi | Prefacewww.it-ebooks.infothe necessary background for the special topics and examples of Chapter 4, and to returnto the Examples for Developers project and look at examples there of interest; skim themso you know what’s there, and then come back to individual topics and examples whenyou need them.Finally, Chapter 5 offers a few closing tips and suggestions, and many sections of thisbook have suggestions for further reading.Drupal VersionsEvery few years, the Drupal project releases a new major version of Drupal (Drupal 6,Drupal 7, and so on). Each major version of Drupal brings large, incompatible changesto the architecture and API, and generally, programming that you do for one majorversion cannot be used without modification in other major versions. Contributed mod‐ules (additional modules downloaded from drupal.org) also make large, incompatiblearchitectural and API changes with their releases (Views 6.x-2.x versus 6.x-3.x, for in‐stance).The code samples in this book are compatible with Drupal 7, and with particular Drupal7 versions of contributed modules as noted in their sections. The descriptive sectionsof this book are also written primarily with Drupal 7 in mind, with notes about changesexpected in Drupal 8 (which was still in development as of this writing).Where to Find More InformationDrupal Site Building and General Drupal InformationWhen I started using and programming with Drupal, there weren’t really any booksavailable on using Drupal to build websites, so I don’t have any specific general Drupalbook recommendations; the Drupal project maintains a list of current books aboutDrupal at http://drupal.org/books.Here is a list of online resources on site building and the Drupal project in general:http://drupal.org/documentationThe Drupal Community Documentation, a wiki-like compendium of pages aboutnearly everything in Drupal (installation, site building, programming, etc.). It hasa lot of coverage, but since it is open to editing by all members of the Drupal com‐munity, it is of varying quality and only somewhat organized. Within this docu‐mentation, the “Developing for Drupal” section and the “Theming” section are ofmost use to programmers; other sections are aimed at setting up sites with Drupal,configuring modules, and the like.Preface | viiwww.it-ebooks.infohttp://drupal.org/planetDrupal Planet, which is an aggregated feed composed of many Drupal-related blogs.Subscribe to keep up-to-date on new developments in Drupal and to read blog postson programming topics.http://groups.drupal.orgCentral place to find topical and geographical Drupal groups, each of which has aforum. Many of them also have meetings and events (online or in-person) that youcan attend.http://drupal.org/ircThe Drupal community uses IRC for online chatting, and this section of the Drupalwebsite contains a channel list and background information.http://association.drupal.orgWebsite of the Drupal Association, the nonprofit organization behind the Drupalproject.http://drupal.org/project/modules and http://drupal.org/project/themesSearch for downloads of contributed Drupal modules and themes here.Drupal Programming Reference and BackgroundThe Drupal API changes often enough that if someone tried to write an API referencebook, it would probably be outdated before it was published. So, the following onlineresources are recommended (in addition, some of the general Drupal resources of theprevious section have programming information):http://api.drupal.orgThe API reference site for Drupal. As of this writing, this site only includes Drupalcore and a few contributed modules; http://drupalcontrib.org is a similar referencesite that includes all of the Drupal contributed modules. Use one of these sites tofind documentation about a specific Drupal function, class, or constant whose nameyou know. See “Using api.drupal.org” (page 97) for more information.http://drupal.org/developing/apiTutorials and conceptual explanations for the various Drupal APIs. Use this refer‐ence if you do not know what function you need to use, or if you need more back‐ground information.http://drupal.org/project/examplesThe Examples for Developers project, which is a set of well-documented examplemodules that aim to illustrate all of the core Drupal APIs. There has been somediscussion about distributing these examples as part of the Drupal core download,but as of this writing, they are still a separate project.viii | Prefacewww.it-ebooks.infohttp://drupal.org/writing-secure-codeDocumentation about writing secure code in Drupal. Also, Greg James Knaddison,one of the prominent members of the Drupal Security Team, has written CrackingDrupal: A Drop in the Bucket (John Wiley and Sons), which is widely considered tobe the definitive reference for Drupal security.http://drupal.org/coding-standardsThe coding standards for the Drupal project.http://drupal.org/new-contributorsA list of tasks for people with a variety of skill sets, with step-by-step instructions,suitable for people who are new to contributing to the Drupal project.http://drupal.org/noviceDetailed instructions on how to contribute patches (code fixes) to Drupal.PHP ResourcesThere are hundreds of books about PHP, and everyone should be able to find one thatsuits their needs, background, and style preferences. For an experienced programmerwho is new to PHP, I recommend:•PHP in a Nutshell by Paul Hudson (O’Reilly) to learn the PHP language.•Web Database Applications with PHP and MySQL by Hugh E. Williams and DavidLane (O’Reilly) to learn the basics of web applications with PHP, including securityconcerns and how all the pieces fit together.•For reference information about specific PHP functions, http://php.net (that is al‐ways the most up-to-date reference; you can also download the entire reference forlocal or offline access).Database ResourcesDrupal can run on a variety of databases; most commonly, people use either MySQL, aMySQL clone such as MariaDB, or PostgreSQL. If you program with Drupal, you willneed to use the Drupal Database API for maximum portability rather than writingMySQL or other database queries directly. Because of this, websites and references aimedat specific databases are of limited use to Drupal programmers. Instead, I recommend:•Web Database Applications with PHP and MySQL (previously mentioned) as a goodstarting point for learning the basics of queries useful for web programming.•SQL Pocket Guide by Jonathan Gennick (O’Reilly), which highlights the similaritiesand differences between the various databases’ query syntax and capabilities.Preface | ixwww.it-ebooks.infoOther Web Technology ResourcesAgain, Web Database Applications with PHP and MySQL is a good starting point forlearning about how the web server, PHP scripting language, database, and browser in‐teract in web applications in general. For reference on HTML, CSS, and JavaScript, Irecommend:•http://www.w3schools.com has a great online reference for HTML and CSS.•If you prefer a book format, the O’Reilly pocket references are handy: CSS PocketReference by Eric A. Meyer and HTML & XHTML Pocket Reference by JenniferNiederst Robbins.•For JavaScript, I am continually pulling out my well-worn copy of JavaScript: TheDefinitive Guide (O’Reilly), which contains both the basics of JavaScript program‐ming and an API reference.•Drupal makes extensive use of the jQuery JavaScript library, which has a compre‐hensive online API reference at http://docs.jquery.com.Conventions Used in This BookThe following terminology conventions are used in this book:•While on some operating systems directories are called “folders,” this book alwaysrefers to them as “directories.”•Sample site URLs use “example.com” as the base site URL.•Sample modules have machine name 'mymodule', and sample themes have ma‐chine name 'mytheme'.The following typographical conventions are used in this book:ItalicIndicates new terms, URLs, email addresses, filenames, and file extensions.Constant widthUsed for program listings, as well as within paragraphs to refer to program elementssuch as variable or function names, databases, data types, environment variables,statements, and keywords.Constant width boldShows commands or other text that should be typed literally by the user.Constant width italicShows text that should be replaced with user-supplied values or by values deter‐mined by context.x | Prefacewww.it-ebooks.infoThis icon signifies a tip, suggestion, or general note.This icon indicates a warning or caution.Using Code ExamplesThis book is here to help you get your job done. In general, if this book includes codeexamples, you may use the code in this book in your programs and documentation. Youdo not need to contact us for permission unless you’re reproducing a significant portionof the code. For example, writing a program that uses several chunks of code from thisbook does not require permission. Selling or distributing a CD-ROM of examples fromO’Reilly books does require permission. Answering a question by citing this book andquoting example code does not require permission. Incorporating a significant amountof example code from this book into your product’s documentation does requirepermission.We appreciate, but do not require, attribution. An attribution usually includes the title,author, publisher, and ISBN. For example: “Programmer’s Guide to Drupalby JenniferHodgdon (O’Reilly). Copyright 2013 Poplar Productivityware, LLC.,978-1-449-34331-6.”If you feel your use of code examples falls outside fair use or the permission given above,feel free to contact us atpermissions@oreilly.com.Safari® Books OnlineSafari Books Online

is an on-demand digital library that delivers ex‐pertcontentin both book and video form from the world’s leadingauthors in technology and business.Technology professionals, software developers, web designers, and business and creativeprofessionals use Safari Books Online as their primary resource for research, problemsolving, learning, and certification training.Safari Books Online offers a range ofproduct mixes

and pricing programs fororgani‐zations,government agencies, andindividuals. Subscribers have access to thousands ofbooks, training videos, and prepublication manuscripts in one fully searchable databasefrom publishers like O’Reilly Media, Prentice Hall Professional, Addison-Wesley Pro‐fessional, Microsoft Press, Sams, Que, Peachpit Press, Focal Press, Cisco Press, JohnPreface | xiwww.it-ebooks.infoWiley & Sons, Syngress, Morgan Kaufmann, IBM Redbooks, Packt, Adobe Press, FTPress, Apress, Manning, New Riders, McGraw-Hill, Jones & Bartlett, Course Technol‐ogy, and dozens more. For more information about Safari Books Online, please visit usonline.How to Contact UsPlease address comments and questions concerning this book to the publisher:O’Reilly Media, Inc.1005 Gravenstein Highway NorthSebastopol, CA 95472800-998-9938 (in the United States or Canada)707-829-0515 (international or local)707-829-0104 (fax)We have a web page for this book, where we list errata, examples, and any additionalinformation. You can access this page at http://oreil.ly/Prog_Guide_Drupal.To comment or ask technical questions about this book, send email to bookquestions@oreilly.com.For more information about our books, courses, conferences, and news, see our websiteat http://www.oreilly.com.Find us on Facebook: http://facebook.com/oreillyFollow us on Twitter: http://twitter.com/oreillymediaWatch us on YouTube: http://www.youtube.com/oreillymediaAcknowledgmentsWriting this book would not have been possible without the world-wide Drupal open-source project community, and I would especially like to acknowledge the support ofthe women of Drupal and the members of the Seattle and Spokane Drupal Groups.Without their help and encouragement, I would never have even gotten in touch withO’Reilly (thanks Angie!), much less decided to write this book. The daily cheerleadingof my partner, Zach Carter, was also a great help in completing it. And all of the con‐tributors to the Examples for Developers project made it possible for this book to con‐centrate on principles and pitfalls, without the need for it to include as many examplesin its pages.I would also like to thank Will Hartmann (PapaGrande), Michelle Williamson (micnap),Melissa Anderson (eliza411), Katherine Senzee (ksenzee), and Michael J. Ross (mjross)for providing technical reviews of this book.xii | Prefacewww.it-ebooks.infoAnd finally, I would like to thank my editor at O’Reilly, Meghan Blanchette, for manyvaluable suggestions, and for patiently guiding me through the publishing process.Preface | xiiiwww.it-ebooks.infowww.it-ebooks.infoCHAPTER 1Overview of DrupalWhat Is Drupal?Depending on who you talk to, you’ll hear Drupal called a Content Management Sys‐tem (CMS) or a Content Management Framework (CMF, a platform that you can use tobuild a custom CMS)--and both are accurate. It can be called a basic CMS because afterinstalling only the base Drupal software, you can create a website with forums, staticpages, and/or a blog, and manage the content online. On the other hand, it can be calleda flexible CMF because most people choose to add additional modules to Drupal inorder to build more complicated websites with more features, and Drupal also allowsyou to create fully custom modules.Drupal is free and open-source software (FOSS), governed by the GNU General PublicLicense (GPL) version 2 (or, at your option, any later version). If you have never readthe GPL and plan to use Drupal, you would be well advised to do so (even more so ifyou plan to do any Drupal programming, for yourself or others). The GPL governs notonly what you can do with Drupal software itself, but also what you can do with anyadd-ons you download from drupal.org, code you find on drupal.org documentationpages, and any derivative work (work that contains GPL-licensed work, verbatim or withmodifications) that you or others create. It’s also written in plain English and is quite agood read (for programmer-types anyway); you can find it in the LICENSE.txt file dis‐tributed with Drupal core, or at http://gnu.org.And finally, Drupal is also a project and a community. Unlike some FOSS software thatis developed primarily by one company that later releases the source code to the public,Drupal is continually evolving due to the efforts of a world wide community of indi‐viduals and companies who donate their time and money to create and test Drupalsoftware, write the documentation, translate it into other languages, answer supportquestions, keep the drupal.org web servers running, and organize get-togethers on alocal and world wide scale.1www.it-ebooks.infoDrupal CoreDrupal core is what you get when you download Drupal from http://drupal.org/project/drupal, consisting of a set of PHP scripts (some with embedded HTML mark-up), Java‐Script, CSS, and other files. This software interacts with a web server (typically, Apache),a database (MySQL, PostgreSQL, and SQLite are supported by Drupal core version 7,and others are supported by add-on modules), and a web browser to provide the basicsof a CMS:•A URL request dispatch system•A user account management system with flexible permissions and roles•Online content editing•A theme (template) system, which lets you override how everything from a buttonto an entire page is displayed•A block system that allows you to place chunks of content in various regions of asite’s pages (this system will be quite different in Drupal 8, and more flexible).•A navigation menu builder•A flexible taxonomy system that supports categories, tags, and user-definedtaxonomy vocabularies•Optional modules supporting commenting, content fields, RSS aggregation, search,and site features such as forums and polls (depending on the Drupal version, someof these may require downloading add-on modules instead of being part of Drupalcore)•The ability to set up a site in different languages and translate content (dependingon the Drupal version, some add-on modules may be required to make a multi-lingual or non-English site)•Logging of system events and errors•An API for Drupal programmersDrupal Add-Ons: Modules, Themes, Distributions, and TranslationsDrupal is modular software, meaning that you can turn site features and functionalityon and off by enabling and disabling modules. Drupal core comes with a few requiredmodules and several optional modules; you can download thousands of additionalcontributed modules from http://drupal.org/project/modules. Most modules have con‐figuration options that you can modify from the Drupal administration interface, by2 | Chapter 1: Overview of Drupalwww.it-ebooks.infologging in to the Drupal-based site using an account that has been given appropriatepermissions. The permission system is flexible: you can define named roles, which aregranted specific permissions (the permissions are defined by modules), and you canassign one or more roles to each user account.Drupal uses a theme system to separate the content from the specific HTML markupand styling. This means that if you want to redesign the site’s layout or styling, you cando so by downloading a new theme from http://drupal.org/project/themes, purchasinga commercially available theme, or creating one yourself—once installed and enabled,it takes effect immediately to change the look of your site without the necessity of editingyour content pages. The theme system allows you to use the default display for whateveryou are happy with and override the parts you want to change; the overrides can be atanything from the lowest level (for example, the presentation of buttons) to the full page.You can also download Drupal in a distribution, which consists of Drupal core and acollection of contributed modules and themes that work together to provide a morefunctional site for a specific purpose. Distributions are available at http://drupal.org/project/distributions for e-commerce, government, non-profits, and many otherpurposes.And finally, you can download translations for Drupal and its contributed modules,themes, and distributions from http://localize.drupal.org. As of Drupal version 7, this isunfortunately more complicated than installing a module or theme, even more so if youwant to set up a multilingual site. It should be improved in Drupal 8.Finding Drupal add-onsHere are the main ways to find Drupal add-ons (modules, themes, or distributions):•To find a specific add-on that you know the name of, visit http://drupal.org and typethe name into the search box.•If it’s not in the first few results, try restricting the search to modules or themes,using the filters in the right sidebar (there is no way to restrict to distributions asof this writing).•Alternatively, start by navigating to http://drupal.org/project/modules, http://drupal.org/project/themes, or http://drupal.org/project/distributions, and searchingfrom there.•You can try guessing the URL, which is always drupal.org/project/, followed by themachine name of the project. The machine name is composed of lowercase letters,numbers, and underscores, but as the machine names are chosen by developers,some are hard to guess and they may take a couple of tries. For example, the Viewsmodule is at http://drupal.org/project/views; the Pixture Reloaded theme is at http://drupal.org/project/pixture_reloaded; the XML Sitemap module is at http://drupal.org/project/xmlsitemap.What Is Drupal? | 3www.it-ebooks.info• If you don’t know the name, you can search from http://drupal.org/project/modules, http://drupal.org/project/themes, or http://drupal.org/project/distributionsby keyword, Drupal version compatibility, or category (for modules only).How Drupal Handles URL RequestsWhen Drupal is installed properly and the web server receives an HTTP request thatcorresponds to the Drupal site, the main Drupal index.php file is loaded and executedby the server to handle the request. It is important for Drupal programmers to under‐stand how Drupal handles such requests; here is an overview (see also Figure 1-1):1.Drupal determines which settings.php file to use for the HTTP request (you can setup Drupal to serve multiple sites, each with its own settings.php file), and this fileis loaded and executed.2.If a URL request is coming from an anonymous user (a site visitor who is not loggedin), the page cache is checked to see if output has previously been cached for thesame requested URL. If so, the cached output is returned to the web server, andDrupal is done. Drupal page caching does not apply to authenticated (logged-in)users.3.The database connection, configuration/variable system, and PHP session variablesare initialized.4.The language system is initialized, and various files are loaded and executed (coreinclude files and enabled modules’ .module files).5.Drupal determines whether the site is offline (also known as being in maintenancemode) or online.6.If the site is offline, Drupal retrieves the offline message stored by an administratoras the page content. Other functions are called to generate some sections of the pagecontent.7.If the site is online, or if an authorized user is accessing a page while the site is offline,Drupal determines which functions need to be called to generate the content forthe request, and calls these functions. They ideally return raw, prerendered content,but they could also return rendered or partially rendered content.8.Drupal determines what delivery method to use for the page, and calls the appro‐priate delivery function.9.For HTML page requests, the default page delivery function prints HTTP headers,uses the theme to render the raw content into HTML, prints the HTML output4 | Chapter 1: Overview of Drupalwww.it-ebooks.info(which effectively sends it to the web server), saves user session information to thedatabase, and exits. The AJAX request delivery function is similar, but it rendersinto JSON output instead of using the theme system to render to HTML. Modulescan also define custom page delivery methods.Figure 1-1. Overview of Drupal HTTP request handlingRelated topics:•“The Drupal Cache” (page 6)•“Providing Page and Block Output” (page 55)•“Where to Find More Information” (page vii) (web technology section—to findresources for learning about how web servers process requests in general)Drupal 8In Drupal 8, some of this high-level overview will still apply, althoughthe details behind the steps will be changing significantly. In particular,fewer files will get loaded, and philosophically, Drupal will be orientedtowards responding to generic HTTP requests containing session vari‐ables and other context information, rather than returning HTML pagesgiven a URL.How Drupal Handles URL Requests | 5www.it-ebooks.infoThe Drupal CacheDrupal has a cache system, which allows modules to precalculate data or output andstore it in the database so that the next time it is needed it doesn’t have to be calculatedagain. This can save a lot of time on page loads, at the expense of some added complexity:any module that uses caching needs to take care to clear its cached data whenever thedata is invalidated due to changes in dependent data. The Drupal 7 cache system has afairly simple API, consisting of functions cache_set() and cache_get() (with a fewvariations), as well as cache_clear_all() to clear all database caches, includingmodule-specific caches. Modules can register to have their caches cleared by imple‐menting a hook (hooks are module entry points to altering Drupal) calledhook_flush_caches().Both Drupal core and add-on modules cache information using this system. Here are afew examples:•Page output for anonymous users (page caching can be turned off from the Perfor‐mance configuration page)•Block output (block caching can also be turned off from the Performance page)•Menu routing (URL) information, block registration information, and other infor‐mation collected from modules•Theme information, including the list of theme regions and theme-related infor‐mation from modules and themes•Form arraysProgrammers and site builders new to Drupal quickly learn that the first thing to try, ifthey are having trouble with a site or if programming changes they have recently madeare not being recognized, is to clear the cache. You can clear the cache by visiting thePerformance configuration page and clicking the cache clear button, or by using Drush.Related topics, examples, and references:•See “Principle: Drupal Is Alterable” (page 9) to learn more about hooks in general,including theme hooks•See http://api.drupal.org to find full documentation of the cache functions men‐tioned here•For more information on Drush, see “Drupal Development Tools” (page 95)•The Cache example from the Examples for Developers project (http://drupal.org/project/examples) illustrates how to use the Cache API•Cache in menu routing: “Registering for a URL” (page 51) and the Page example fromExamples for Developers6 | Chapter 1: Overview of Drupalwww.it-ebooks.info•Cache in block registration: “Registering a Block” (page 54) and the Block examplefrom Examples for Developers•Views cache: “Creating Views Module Add-Ons” (page 80)•Theme cache: “Defining Theme Regions for Block Placement” (page 40) and “Mak‐ing Your Output Themeable” (page 13)•Forms: “Generating Forms with the Form API” (page 59) and the Form examplefrom Examples for DevelopersDrupal 8The cache API functions are different in Drupal 8 because it uses classesto manage caching.The Drupal Cache | 7www.it-ebooks.infowww.it-ebooks.infoCHAPTER 2Drupal Programming PrinciplesExperienced programmers learn, from training and experience, a set of principles andbest practices to apply whenever they approach a problem they want to solve with pro‐gramming. These include general practices such as “Comment your code” and “Chooseclear variable names,” which apply to all programming languages and situations, andsome that are specific to a particular domain. Drupal has its own set of programmingprinciples (covered in this chapter); learning them and following them should help yoube a more effective Drupal programmer.If you are completely new to Drupal programming, you might find ituseful to download the Examples for Developers project from http://drupal.org/project/examples before reading this chapter. Try out thePage and Block examples, and take a look at their source code. Thencome back and you’ll have a little more context for learning theseprinciples.Principle: Drupal Is AlterableSince Drupal is intended to be used as a platform for building web applications, one ofits fundamental principles is that nearly everything about it needs to be customizable,and it needs to be customizable without having to edit its base source code. Since you’renot supposed to need to edit the base code to build any type of web application withDrupal, both Drupal core and contributed modules are (ideally) fully alterable, meaningthat they provide hooks that you can use to customize their behavior and output.The term “hook” is used in a similar manner in several CMS projects, to mean an entrypoint where an add-on module or plugin can act to alter the behavior or output of thebase CMS. In Drupal specifically, there are several somewhat overlapping types of hooks:9www.it-ebooks.info•Generic hooks, which allow modules to define additions to Drupal behavior.•Alter hooks, which allow modules to make modifications to existing Drupalbehavior.•Theme hooks, which allow themes to modify the output that is sent to the browser.•Theme hooks come with theme preprocessing and processing hooks, which modulescan use to alter the information that is sent to the theme for output.Why Not Just Hack (Edit) the Code?Unlike in some other programming communities, the word “hack” in the Drupal com‐munity has definite negative connotations: hacking specifically means editing code thatyou downloaded from Drupal.org, in order to make a change that you need for a site.Hacking is highly discouraged; “hacking core,” or editing the Drupal core files, is con‐sidered to be the worst offense. There are several reasons:•Hacking is usually unnecessary, since there should be a hook available that will letyou accomplish your goal without hacking.•If you have hacked Drupal core or other downloaded code, updates will be muchmore difficult, because you will need to re-apply your hack after downloading anew version of the code. All downloaded code is at least occasionally updated withsecurity fixes, bug fixes, and new features.•If you program with hooks instead of hacking, you can turn off your changes bydisabling the module containing the hooks. If you hack code, you will need to “un-hack” it to turn off your changes.•If you find that the hook you need does not exist, or if you are tempted to hack inorder to fix a bug or add a new feature to a module, turn your hack into a patch andit becomes a benefit to you and the Drupal community if it is added to the moduleor to Drupal core.Further reading:•The “Hooks” topic on http://api.drupal.org lists all Drupal core generic and alterhooks, and the “Default theme implementations” topic lists all Drupal core themehooks.•Patches: “Reporting Issues and Contributing Code to the Drupal Community”(page 46)10 | Chapter 2: Drupal Programming Principleswww.it-ebooks.infoDrupal 8Drupal version 8 will certainly also be alterable, but it will use a com‐bination of hooks and a new plugin system.Programming with Hooks in Modules and ThemesFundamentally (at least, from the point of view of a Drupal programmer and in versionsup through Drupal 7), modules are mostly collections of hook implementations (PHPfunctions that define the hook’s output or behavior), and themes are mostly collectionsof theme hook overrides (PHP functions or template files that define how output ispresented); both themes and modules may also contain supporting code, CSS, Java‐Script, images, and other files. When your objective is to alter Drupal, generally youshould override theme hooks in a theme if your aim is to change the presentation ofdata, such as the exact HTML markup and CSS, and you should implement hooks in amodule if your aim is to change the way Drupal behaves or what data is being output.If you need to do both, you will probably need to set up both a theme and a module.To set up a module or theme and implement or override hooks, follow these steps:1.Pick a machine name or short name for the module or theme. This is usually asequence of letters and underscores, sometimes with numbers, that must followPHP’s function-naming conventions, since it will be used as a function prefix (usethe machine name as a prefix for all functions you define in your module or theme).Pick a name that is not already in use by a project on drupal.org, to avoid laterconflicts. Throughout this book, the convention is that you are creating a modulecalled 'mymodule' or a theme called 'mytheme'.2.Create a directory for your theme or module. See the “Where to Put Modules andThemes” (page 13) sidebar to figure out where to put this directory.3.Create a file called mymodule.info or mytheme.info inside your directory, which isa plain text file that contains information about the module or theme. The exactsyntax of this file tends to vary from version to version of Drupal and is slightlydifferent for modules and themes, so check the online documentation, or copy afile from a module or theme provided in Drupal core or the Examples for Developersproject to use as a starting point. Here’s a minimal example for a Drupal 7 module(the syntax of this much is the same for themes):; Comments start with a semicolon.; The name displayed on the Modules or Themes list.name = My Module; The longer description displayed on the Modules or Themes list.description = Longer description of this module.; The Drupal core version this module or theme is compatible with.core = 7.xPrinciple: Drupal Is Alterable | 11www.it-ebooks.info4.For theme and module hook functions, inside the same directory create a PHP filefor your hook implementation or override functions (skip this step for theme tem‐plates). For theme hook functions, this file is called template.php. For most genericmodule hook functions, this file is called mymodule.module, but there are a fewhook implementations that belong in other files. For instance, implementations ofinstall-related hooks such as hook_schema() and hook_update_N() go into themymodule.install file, and the contributed Views module uses two separate files forits hooks. Always read the reference documentation for the hook you are imple‐menting to find out where its implementation belongs.5.Within your module or theme file, define a function to implement the hook oroverride the theme function (skip this step for theme templates). For a hook calledhook_foo(), the function must be named mymodule_foo(). For a theme hook func‐tion called theme_foo(), the function must be called mytheme_foo(). For the func‐tion body, often there is a good starting point in the hook documentation or thetheme hook function you are overriding.6.To override a theme hook template file, copy the template file you are overriding toyour theme directory, keeping the same file name.7.Edit the function or file to make the desired changes.8.Enable your module or theme.9.As you are programming and testing, if you add a new hook implementation ortheme override to an enabled module or theme, you will need to clear the Drupalcache so that Drupal will recognize your change. For some informational hooks,you will also need to clear the cache when you make a change to the function body,to force Drupal to re-run your hook and read the new information. In general, it’salways a good idea while you are developing to clear the cache after any change.There has been some discussion about changing the hook implemen‐tation function naming convention to mymodule__foo() (two under‐scores instead of one) for Drupal 8 or some later Drupal version, becausemany modules and many hooks have underscores in their names, andhaving a double underscore as the separator would make the distinctionclearer. However, as of this writing, this has not yet been adopted.Further reading, references, and examples:•Documentation of .info file syntax for modules: http://bit.ly/U0SuhH•Documentation of .info file syntax for themes: http://bit.ly/Tol9P7•“The Drupal Cache” (page 6)12 | Chapter 2: Drupal Programming Principleswww.it-ebooks.info•Individual hook documentation can be found by searching for the hook functionor template file name, such as hook_block_info, theme_table, or block.tpl.php, onhttp://api.drupal.org. Hook documentation pages give you documentation aboutthe purpose of the hook, parameters, return value, which file the hook should belocated in, a list of places where the hook is invoked (that is, which Drupal systemwill call your hook implementation function), and a list of other implementationsin Drupal core. The function body for a hook function is a sample implementation.Theme hook pages tell you where the theme hook is used and document the vari‐ables you can use in your output.•Database schema and installation hooks: “Setting Up Database Tables: Schema APIand hook_update_N()” (page 22)•Views hooks: “Creating Views Module Add-Ons” (page 80)•Check if a proposed machine name for your module or theme is already in use bytrying the URL drupal.org/project/your_proposed_nameWhere to Put Modules and ThemesIn Drupal 7 and earlier versions, modules and themes that you download or createshould generally go into the sites/all/modules and sites/all/themes directories. Each mod‐ule or theme project should be in its own subdirectory, such as sites/all/modules/viewsfor the Views project. You can also organize modules into subdirectories; for example,you could create sites/all/modules/contrib and sites/all/modules/custom directories fordownloaded (“contributed”) modules and custom modules, respectively.If you have a multisite installation and want a module or theme to be available to onlyone of the sites, you can put it in sites/specific_site/modules or sites/specific_site/themes.See http://drupal.org/documentation/install/multi-site for more information on thistopic.In Drupal 8, all of the Drupal core code (include files, modules, themes, and so on) hasbeen moved to the directory core, and while you can still put your downloaded andcustom modules into sites/all, there are also top-level modules and themes directoriesavailable. The use of these top-level directories is recommended, except for site-specificmodules and themes in a multisite installation.Making Your Output ThemeableDrupal’s theme system is designed to separate the data and content from the styling andpresentation: the module has control over the data and content, and the theme that isin use should have full control over styling and presentation, including rendering datainto HTML. The basic principle that makes this work is that all data that is renderedPrinciple: Drupal Is Alterable | 13www.it-ebooks.infointo HTML should be passed through the Drupal theme() function. For instance,whenever a block from the core Block module is rendered, a call is made totheme('block', $block_data), rather than having the Block module simply outputan HTML <div> containing the data. This allows your theme to override the defaultblock.tpl.php theme template file, replacing the default <div> with different HTML ifdesired. The first argument to the theme() function is the theme hook name('block' in this example), and the second argument is an array containing the data andattributes needed by the theme hook for rendering.Theme functions versus render arraysThere is often confusion around the relationship between theme func‐tions and render arrays (which are arrays containing the data to be out‐put). The basic idea is that each element in a render array is rendered(converted into an HTML string) by a theme function or theme tem‐plate, and rendering should be done as late as possible in the page-generating process. So, you should generally return render arrays fromyour functions that provide block and page output, and define themefunctions or templates as needed (as described in this section), to renderthe elements of the output render arrays.Modules that you write should follow the same principle: if your module outputs dataas HTML, it should use the Drupal theme system to render the output instead of creatingthe HTML directly. Here is an outline of the steps; you might want to pull up the Themingexample from Examples for Developers and follow along:1.See if there is already a theme hook for the type of output you are generating. Forinstance, if you are generating an HTML table, you should use the Drupal core'table' theme hook instead of defining your own hook.2.If there is not already an appropriate theme hook, define a custom theme hook byimplementing hook_theme() in your mymodule.module file. Example:function mymodule_theme($existing, $type, $theme, $path) {return array(// The array keys are names of the theme hooks you are defining.'mymodule_hookname' => array(// Input variables.'variables' => array(// These are passed as an array to theme(), which passes them on// to your theme function or template. Here, provide default values.'input1' => '',),// If you want to use a template, include this line; for a theme// function, leave it out.14 | Chapter 2: Drupal Programming Principleswww.it-ebooks.info

?></div>4.If you are using a theme template, declare it in yourmymodule.info

file with afiles[] = mymodule-hookname.tpl.phpline.5.Try to keep the programming in your theme function or template file to aminimum—it should just be putting the output inside some HTML markup. Anyprogramminglogic should instead be put into a function calledtemplate_preprocess_mymodule_hookname(), defined in yourmymodule.mod‐ule

file. This function will automatically be called to preprocess the input data intothe variables that can be printed by the template file.6.Calltheme('mymodule_hookname', $data)

lists all Drupalcore theme functions and template files. Each theme function or template page lists“theme calls” (places in Drupal core that calltheme('hook_name')to use that themehook).Principle: Drupal Is Alterable | 15www.it-ebooks.infoDrupal 8In Drupal 8, theme template files will be using the Twig templatingsystem, with Twig files like block.html.twig replacing PHP template fileslike block.tpl.php from previous versions of Drupal; theme functionswill also be replaced by Twig files.Principle: Drupal Is InternationalDrupal core and Drupal contributed modules and themes are ideally constructed so thattheir user interface elements use English by default, but can be translated into otherlanguages. Less universally (but still ideally), modules and themes should also be con‐structed so that any user-entered text for settings or content can be translated. If bothof these principles are followed:•You can build an English-language site.•You can build a site whose language is not English.•You can build a multilingual site.•You can use the translation mechanism to change the default English user interfacetext supplied by a module (for instance, changing the text on a button or link),without altering the module code.When you program for Drupal, even if you don’t think you will ever need to translateyour site, it is still a good idea to follow this principle, because:•The world is getting more global, and you might eventually need to translate yoursite.•You might decide to contribute the module on drupal.org so that others can use it.•It’s a good Drupal coding habit to get into, in case you ever want to contribute codeto the Drupal project.•At least for built-in user interface text, it’s not very difficult anyway.Unicode stringsWhen programming with an international audience in mind, it is im‐portant to remember that not all text is ASCII—character sets for muchof the world are instead multibyte Unicode characters. Some of thestandard PHP string functions, such as strlen(), strtolower(), etc.,do not take this into consideration and are not safe to use for multibytecharacters. Instead, you can use Drupal’s multibyte-safe equivalentfunctions (drupal_strlen(), and so on).16 | Chapter 2: Drupal Programming Principleswww.it-ebooks.infoInternationalizing User Interface TextThe basic tool for internationalizing user interface text in the modules and themes youcreate is Drupal’s t() function. Any text that will be shown to an administrative user ora site visitor should be enclosed in t(); before the text is printed, Drupal will translateit to the appropriate language. For instance:// Bad:$button_text = 'Save';// Good:$button_text = t('Save');For translation to work properly, the first argument of t() must always be a literal string—it cannot contain variables. (This is because the first arguments to t() are extractedfrom code to build the database of strings that need translation.) If you need to substitutevariable information into your string, t() has a mechanism:// Bad:$message_string = t("Hello $user_name");// Good:$message_string = t('Hello @user_name', array('@user_name' => $user_name));As you can see, it doesn’t really take much effort to make basic module-defined or theme-defined user interface text translatable. There are additional Drupal functions you canuse to internationalize numbers, dates, and JavaScript text; these are collectively knownas the Drupal Localization API. There is also a Drupal.t() function that is the equivalentto t() for use in JavaScript code, and an st() function for use in contexts where the fullDrupal localization system is not available (such as during installation).Further reading and references:•Find Drupal localization functions on http://api.drupal.org listed in the “Format‐ting” and “Sanitization” topics.•Read more about the Localization API at http://drupal.org/developing/api/localizationDrupal 8The t() function is not expected to change in Drupal 8.Principle: Drupal Is International | 17www.it-ebooks.infoInternationalizing User-Entered TextIf you are building a module that has user-entered settings or user-entered text that isthen displayed to other users and you want your module to be fully internationalizedso that it can be used on a multilingual site, you need to provide a way for the user-entered text to be translated. The t() function only works for literal text strings, so itcannot be used for this purpose.Unfortunately, as of Drupal version 7, there is no Drupal core API for translating user-entered text in a uniform way. This situation will be remedied in Drupal version 8, sincethere is a major internationalization development effort underway (as of this writing).Meanwhile, in Drupal 7, if you do want your module’s user-entered text to be interna‐tionalized and translatable, do one or more of the following:•Store user-entered text in individual Drupal variables, using the variable_get()and variable_set() functions. If each string of user-entered text is stored in itsown variable, and the variables are declared using the contributed Variable module’shook_variable_info(), site builders can use the contributed Internationalizationmodule to translate this text. This is most appropriate if you just have a fewadministrator-entered text strings that need to be translated.•For settings that form a list, use a Drupal core taxonomy vocabulary to manage thelist instead of managing it in your own module. The taxonomy terms can then betranslated using the contributed Internationalization module. To set up a vocabu‐lary, you will need to add the following code to your module’s hook_enable()implementation in the mymodule.install file:// Create the vocabulary if it doesn't already exist.$vocabulary = taxonomy_vocabulary_load(variable_get('mymodule_vocabulary', 0));if (!$vocabulary) {$vocabulary = (object) array('name' => t('Some appropriate name'),'machine_name' => 'mymodule_appropriate_name','description' => t('Some appropriate description'),'module' => 'mymodule',);taxonomy_vocabulary_save($vocabulary);variable_set('mymodule_vocabulary', $vocabulary->vid);}•For more complicated collections of settings, define a Drupal entity with fields tostore your settings. The collections of settings can then be translated using the EntityTranslation module, which is expected to be added to Drupal core version 8.18 | Chapter 2: Drupal Programming Principleswww.it-ebooks.infoFurther reading and references:•General information about programming with hooks: “Programming with Hooksin Modules and Themes” (page 11)•Define an entity with fields: “Defining an Entity Type” (page 68)•Internationalization module: http://drupal.org/project/i18n•Variable module: http://drupal.org/project/variable•Entity Translation module: http://drupal.org/project/entity_translationDrupal 8The variable_get() and variable_set() functions will be replacedin Drupal 8 with a new Configuration API, which will be internation‐alized in Drupal 8. The programming behind the taxonomy and entitysystems will also be updated for Drupal 8 somewhat (more object-oriented), but the data storage and internationalization will be similar.Principle: Drupal Is Accessible and UsableThe World Wide Web Consortium (W3C) defines accessibility as meaning that peoplewith disabilities can perceive, understand, interact with, and contribute to a website,and their Web Accessibility Initiative (WAI) has many resources for learning aboutaccessibility and testing websites for accessibility. The Drupal project has an active ac‐cessibility team, and one of Drupal’s guiding principles is that its administrative backendand its visitor-facing output should both be as accessible as possible. The Drupal acces‐sibility team has helped to improve the accessibility of Drupal by maintaining docu‐mentation on accessibility, testing Drupal for accessibility problems, and pushing theDrupal project to adopt industry-wide accessibility standards.Another principle that ideally guides web design is usability: the idea that websites’ userinterfaces should be easy to use and learn. The Drupal project has an active usabilityteam, and a commitment to high usability of the Drupal administrative interface is oneof Drupal’s guiding principles. The Drupal usability team has done usability studies andproposed changes that have greatly improved the usability of Drupal—there was a largeusability push for Drupal version 7, and this is expected to continue through futureversions of Drupal.At times, usability and accessibility can be at odds. For instance, usability studies mightshow that a drag-and-drop interface for ordering menu items is much faster and moreintuitive than an interface where you assign numerical weights to define the order, butblind users and users who have mobility limitations that preclude use of a mouse cannotuse drag-and-drop interfaces, so the drag-and-drop interface has accessibility problems.Principle: Drupal Is Accessible and Usable | 19www.it-ebooks.infoTo satisfy both usability and accessibility principles, you can supply the drag-and-dropinterface along with a link that lets users switch to the numerical weight interface ifneeded. Also, usability can sometimes be at odds with itself: for instance, an interfacethat provides more information when you hover your mouse over an area might be quiteusable for someone using a mouse on a standard computer, but how do you “hover” ona mobile phone interface?So, instead of thinking that usability and accessibility are incompatible, the guidingprinciple of combining usability and accessibility should be to make the user interfacefor a task as easy to use and learn as possible for users without mobility, sight, or otherlimitations, while providing alternatives that allow users with these limitations to beable to accomplish the task. In addition, when thinking about and testing for usability,different types of devices and browsers should be considered. Drupal aims to followthese principles, and you should also try to adopt them in your own programming. Hereare some things you can do to improve accessibility and usability in your programming:•Familiarize yourself with the usability and accessibility guidelines of the Drupalproject.•When providing a user interface in your own module, use the same user interfacepatterns as Drupal core (they have already been tested for usability and accessibility,and uniformity also means easier learning).•When adding an administrative page for your module, put it in an appropriatesection of the existing administrative user interface hierarchy of Drupal core, sopeople can find it easily.•Test your user interfaces and theme for accessibility.•Make sure that all information you present is available in text format (not just inimages or diagrams), so screen reader users can access it. Search engines also onlyindex text information, so making your site accessible in this way will also help itsvisibility in search engines.•Make your theme and user interface designs adaptable to different screen sizes andmagnifications. This will help with both usability on mobile devices and accessi‐bility for people who need to magnify their screens.Further reading and references:•World Wide Web Consortium (W3C): http://w3.org•Web Accessibility Initiative (WAI)—includes resources for accessibility testing andworld wide standards: http://www.w3.org/WAI/•Drupal accessibility team: http://groups.drupal.org/accessibility•Drupal accessibility guidelines and resources: http://drupal.org/about/accessibility•Drupal usability team: http://groups.drupal.org/usability20 | Chapter 2: Drupal Programming Principleswww.it-ebooks.info•Drupal usability guidelines: http://drupal.org/ui-standardsPrinciple: Drupal Is Database IndependentAlthough most Drupal sites use MySQL (or a compatible clone) as the database backend,Drupal version 7 (and later versions) can be used with a variety of databases: Drupalcore supports PostgreSQL and SQLite, and contributed modules add support for otherdatabases. Drupal core also provides several database-related customizations, such asthe ability to prefix database table names with a string, or different strings for differenttables, and to fall back to a different database if the default database is not available. Inorder to facilitate this portability, Drupal provides a Schema API and a Database API,which work together as a framework for defining and querying database tables.Since Drupal is written in PHP, it is possible in your own programming to avoid usingthe Drupal Schema and Database APIs and instead use the PHP database functions youmay be familiar with to query the database directly. But this is not a good idea, because:•Using the Database API helps make your queries more secure from SQL injectionbugs.•The Schema API is actually easier to use for creating and modifying tables thanwriting your own SQL queries, and the code is easier to read and maintain. TheDatabase API takes an effort similar to writing your own SQL queries.•You might sometime want to switch to a different database for performance reasons.•You might sometime want to use different site set-up choices, such as setting updevelopment and staging sites with different database options.•You might want to contribute your module on drupal.org so that others can use it.•It’s a good habit to get into, in case you ever want to contribute code to the Drupalproject.It should be noted that one of the best ways to make sure to stay independent of thedatabase is to avoid direct use of the database entirely. For instance, instead of creatinga module to store information in its own custom database table, consider whether youcan use Drupal’s taxonomy, node, or entity system instead. Or perhaps you can use acontributed module, along with a custom plugin.Further reading and references:•The rest of this section has more details on the Database and Schema APIs.•Avoiding database programming entirely: “Mistake: Programming Too Much”(page 35)•Security concerns: “Principle: Drupal Is Secure; User Input Is Insecure” (page 27)Principle: Drupal Is Database Independent | 21www.it-ebooks.info•Drupal Schema API:http://drupal.org/developing/api/schema•Drupal Database API:http://drupal.org/developing/api/database•Modules providing alternative database integration: MongoDB (http://drupal.org/project/mongodb), Microsoft SQL Server (http://drupal.org/project/sqlsrv), Oracle(http://drupal.org/project/oracle)•Group for people interested in enterprise applications (including database integra‐tion):http://groups.drupal.org/enterpriseDrupal 8The Database and Schema APIs are not expected to change significantlyin Drupal 8, except that the PHP classes that the Database API uses arenamespaced in Drupal 8, are found in different files, and may haveslightly different names in the Drupal source code. This should notsignificantly affect programming with databases.Setting Up Database Tables: Schema API and hook_update_N()If your module really does need to set up its own database tables, create them by im‐plementinghook_schema()in yourmymodule.install

file. Drupal will then take care ofcreating the tables when your module is enabled, as well as deleting them when yourmodule is uninstalled. For example, to define a database table called'mymodule_foo'with fields'bar'and'baz':function

mymodule_schema()

{

$schema

=

array();

$schema['mymodule_foo']

=

array(

'description'

=>

'Untranslated description of this table',

'fields'

=>

array(

'bar'

=>

array(

'description'

=>

'Untranslated description of this field',

'type'

=>

'varchar',

'length'

=>

50,

'default'

=>

'',

),

'baz'

=>

array(

'description'

=>

'Untranslated description of this field',

'type'

=>

'int',

'unsigned'

=>

TRUE,

'default'

=>

0,

),

),

'primary key'

=>

array('baz'),

);

return

$schema;}22 | Chapter 2: Drupal Programming Principleswww.it-ebooks.infoThe Schema API is flexible enough to define all aspects of databasetables, including fields of different types, indexes, and so on. See theSchema API documentation for details.Once you have enabled a module and its database tables are created, you may find thatyou need to make a change, such as adding a field, deleting a field, adding a new databasetable, and so on, to correspond to a new feature you have added to your module. TheSchema API provides a standard way to do this:1.Add a hook_update_N() implementation (also known as an update function) toyour mymodule.install file, which will update the database using functions such asdb_add_field(), db_create_table(), etc. Update functions are named sequen‐tially, and each builds upon the previous schema and updates. The comment directlybefore the function is shown on the Pending Updates page when you run the ex‐ample.com/update.php script, so make this comment coherent and descriptive. Forexample, this function would change the length of the 'bar' field to 150 characters,and also add a new field 'bay':/*** Make one field wider and add a new field in the mymodule_foo table.*/function mymodule_update_7001() {db_change_field('mymodule_foo', 'bar', 'bar', array('description' => 'Untranslated description of this field','type' => 'varchar','length' => 150,'default' => '',));db_add_field('mymodule_foo', 'bay', array('description' => 'Untranslated description of this field','type' => 'varchar','length' => 50,'default' => '',));}2.Edit your original hook_schema() implementation function, making correspond‐ing changes to the schema.3.Make changes in your module code to use the new schema.4.If this is for a site you manage, run the update script by visiting example.com/update.php. You will be presented with a list of pending updates, which shouldinclude the update function you just created and show the description from thefunction comment.Principle: Drupal Is Database Independent | 23www.it-ebooks.infoDo not attempt to call Drupal Database API functions such as drupal_write_record() that rely on the schema from an update function,because the schema will be in an unknown state while the update func‐tion is running.Correspondingly, never reference your hook_schema() implementationin an update function—always write out the full array values in yourcalls to db_change_field() and similar functions. The reason is that ifyou ever decide to share your module with someone else, you will nothave control over when the updates are run, so you don’t know at themoment of running a particular update function what the state of theschema in hook_schema() might be.Further reading, examples, and references:•General information about programming with hooks: “Programming with Hooksin Modules and Themes” (page 11)•Drupal Schema API: http://drupal.org/developing/api/schema•The DBTNG example from Examples for Developers: http://drupal.org/project/examples (DBTNG is the nickname for the Database API that originated in Drupal7, and stands for “Database: The Next Generation”)•Look up hook_schema and hook_update_N on http://api.drupal.org for full detailsof their return values.•The functions that update database tables, such as db_change_field(), can befound in the database.inc include file (at least in Drupal 7). You can look this fileup on http://api.drupal.org to find a list of all its functions.Querying the Database with the Database APIIf your module needs to query the Drupal database directly, whether querying its owntables or tables provided by Drupal core or another module, you will need to use theDrupal Database API to ensure that your queries are secure and portable. The DatabaseAPI provides the db_query() function, which you can use to make simple queries, anda dynamic API that can be used for arbitrarily complex queries.Very simple queriesFor the simplest SELECT queries, you can use the Drupal db_query() function:$result = db_query('SELECT * FROM {users} u WHERE u.status = :status',array(':status' => $desired_status));foreach ($result as $record) {24 | Chapter 2: Drupal Programming Principleswww.it-ebooks.info// $record will be a PHP object with fields corresponding to the table fields.$user_name = $record->name;// ...}Notes:•The name of the database table being queried must be enclosed in {}. When Drupalruns the query, this table name will be prefixed as necessary.•Variable inputs to the query use placeholders, which start with : and should containonly letters (numbers, underscores, and so on will not work in all cases). The secondargument to db_query() is an array giving the values of the placeholders. Neverput variable inputs directly into your query strings, especially if they originate ininsecure user input.•If a placeholder is a string, do not enclose it in quotes in the query—the variablesubstitution will take care of adding the quotes as necessary. For instance:// Bad:"WHERE u.name = ':name'"// Good:"WHERE u.name = :name"•Only use db_query() for SELECT queries on a single database table, and only if SQLfunctions such as LIKE and grouping are not involved. The reason is that insertqueries, delete queries, update queries, table joins, grouping, and some SQL func‐tions are different across database engines, so to ensure portability, you will needto use the dynamic query Database API functions for these queries.•Some Drupal database tables have permission implications (for instance, the Nodemodule has a rich permission system for restricting access to certain content bycertain users or roles). When querying such tables, do not use db_query(), becausethe query will need to be modified by Drupal to enforce the correct permissions.Use the dynamic query Database API functions instead.•Drupal also has a built-in pager system that greatly simplifies making multiple-pagequeries. You will need to use the dynamic query functions to use this system.Dynamic queriesFor queries that involve more than one database table, paging, SQL functions such asLIKE, grouping, tables with access restrictions, or anything other than a SELECT, youwill need to use Drupal’s dynamic query functions instead of the simple db_query()function. These functions allow you to build up a query in a database-independent way,and then execute it to get the same type of result set returned by db_query().Principle: Drupal Is Database Independent | 25www.it-ebooks.infoFor example:// Equivalent to:// SELECT title, nid, created FROM {node} n WHERE n.status = 1// with node access enforced.$result = db_select('node', 'n')->addTag('node_access') // Enforce node access permissions.->fields('n', array('title', 'nid', 'created')) // Fields to return.->condition('n.status', 1) // WHERE condition.->execute();foreach ($result as $node) {// $node will be a PHP object with fields corresponding to the table fields.$title = $node->title;// ...}Notes:•Unlike when using the simple db_query(), do not enclose table names in {}.•The addTag() method is used when you are querying a table with permissionsconsiderations. For instance, the Node module has a complex permissions system,which is enforced for you in database queries if you add the 'node_access' tag toyour query.•Some query methods allow chaining, as illustrated in the previous example, becausethey alter the query in place and return the altered query object. Some do not;notably addField() and the join methods. If you use a non-chaining method, usesyntax like this:// Equivalent to:// SELECT n.changed AS last_updated, n.title, n.nid, u.name FROM// {node} n INNER JOIN {users} u ON u.uid = n.nid WHERE// n.status = 1// with a pager, 20 items per page, and node access enforced.$query = db_select('node', 'n');$query->addField('n', 'changed', 'last_updated'); // Field with an alias.$query->innerJoin('users', 'u', 'u.uid = n.uid'); // Join.$query = $query->extend('PagerDefault'); // Paging.$result = $query->fields('n', array('title', 'nid'))->fields('u', array('name'))->addTag('node_access')->condition('n.status', 1)->limit(20) // Number of items per page.->execute();•When using a PagerDefault query, as in the previous example, add a standard pagerto your output by calling theme('pager'). This will let Drupal handle all the detailsof getting the right items on each page.26 | Chapter 2: Drupal Programming Principleswww.it-ebooks.infoFurther reading, examples, and references:•Avoiding database programming entirely: “Mistake: Programming Too Much”(page 35)•Security concerns: “Principle: Drupal Is Secure; User Input Is Insecure” (page 27)•Paged queries and output: “Generating paged output” (page 57)•Drupal Database API: http://drupal.org/developing/api/database•The DBTNG example from Examples for Developers: http://drupal.org/project/examples (DBTNG is the nickname for the Database API that originated in Drupal7, and stands for “Database: The Next Generation”)•The database query functions, such as db_select(), can be found in the data‐base.inc include file (at least in Drupal 7). You can look this file up on http://api.drupal.org to find a list of all its functions.Principle: Drupal Is Secure; User Input Is InsecureWhen programming for the web, you always need to think about security. The basicprinciple to follow is to consider all user-provided input to be insecure, whether it isprovided by a trusted user such as a site administrator (who could be the target ofhacking), a semi-trusted user such as someone with a generic user account on your site,or an anonymous site visitor. With that in mind, whatever you do in your Drupal pro‐gramming that involves user-provided input, that input will first need to be cleansed orchecked in some way to make it more secure.Besides this basic principle, which applies to all web programming, Drupal has an ad‐ditional security concern: your programming needs to respect Drupal’s permission sys‐tem. For instance, although a module you write can run arbitrary database queries, onlyinformation from the database that a particular user has permission to view should beshown to them. And although a module you write can technically call any Drupal APIfunction at any time, you should not call functions without checking that the user haspermission to perform their actions.Both Drupal core and Drupal’s contributed modules and themes ideally follow theseprinciples of cleansing user input and checking Drupal permissions: the Drupal projecthas a volunteer security team, which handles reports of security violations, and everycontributor’s first module or theme is reviewed before it is allowed to be promoted to“full project” status on drupal.org. Your Drupal programming should also follow theseprinciples, and the following sections will give you an introduction to making yourDrupal code more secure. You will also need to make sure your site permissions arereasonable and take other measures to set up a secure site.Principle: Drupal Is Secure; User Input Is Insecure | 27www.it-ebooks.infoFurther reading and resources:•Securing a Drupal site:http://drupal.org/security/secure-configuration•The Drupal site building section of“Where to Find More Information”(page vii)lists additional resources•“Mistake: Saving PHP Code in the Database” (page 43)Cleansing and Checking User-Provided InputThe philosophy used in Drupal for ensuring security with user-provided input is to storewhatever the user typed in the database without alteration, and then cleanse it prior todisplay. Both of these steps must be done carefully.In the database storage step, you need to be concerned aboutSQL injection

attacks—malicious users could attempt to provide input that would, for instance, end the queryyou were using to add the data to the database, and run a query of their choice. If youuse the Drupal database API correctly, however, all user-provided input will either beput into the query using placeholders or as arguments to safe methods such ascondition(), and the integrity of your database will be protected.In the output step, the Drupal API provides functions you can use to cleanse data tomake it safe for HTML output. For instance, if you are outputting data that is supposedto be plain text (without HTML tags), you should pass it through thecheck_plain()function. If you are outputting data that is supposed to contain HTML tags (whichshould be limited for untrusted users), you should pass it through thecheck_markup()function. If you are outputting a user-provided URL, you should pass it throughcheck_url(). However, note that some Drupal API functions, such asl()(for makinglinks), cleanse input themselves, so read the function documentation and don’t double-cleanse. Examples:// Bad:print

'<p>'

.

$text

.

'</p>';print

'<a href="'

.

$url

.

'">'

.

$text

.

'</a>';print

l(check_plain($text),

check_url($url));// Good:print

'<p>'

.

check_plain($text)

.

'</p>';print

l($text,

$url);Further reading, examples, and references:•Drupal database API:“Querying the Database with the Database API” (page 24)•Drupal functions that cleanse data can be found onhttp://api.drupal.orgunder the“Sanitization” topic.•More about writing secure code:http://drupal.org/writing-secure-code28 | Chapter 2: Drupal Programming Principleswww.it-ebooks.info•“Mistake: Saving PHP Code in the Database” (page 43)Checking Drupal PermissionsDrupal has a rich permission system, which your modules need to interact with properlyto ensure that users, including anonymous site visitors, are only allowed to see infor‐mation and perform actions that they have permission for. There are several systems