Pro Drupal 7 Development, 3rd Edition
Pro Drupal 7 Development
Third Edition
■ ■ ■ ToddTomlinson JohnK.VanDyk
ProDrupal7Development:ThirdEdition
Copyright©2010byToddTomlinsonandJohnK.VanDyk Allrightsreserved.Nopartofthisworkmaybereproducedortransmittedinanyformorbyanymeans, electronicormechanical,includingphotocopying,recording,orbyanyinformationstorageorretrieval system,withoutthepriorwrittenpermissionofthecopyrightownerandthepublisher.
ISBN-13(pbk):978-1-4302-2838-7
ISBN-13(electronic):978-1-4302-2839-4 PrintedandboundintheUnitedStatesofAmerica987654321 Trademarkednames,logos,andimagesmayappearinthisbook.Ratherthanuseatrademarksymbol witheveryoccurrenceofatrademarkedname,logo,orimageweusethenames,logos,andimagesonly inaneditorialfashionandtothebenefitofthetrademarkowner,withnointentionofinfringementof thetrademark. Theuseinthispublicationoftradenames,trademarks,servicemarks,andsimilarterms,eveniftheyare notidentifiedassuch,isnottobetakenasanexpressionofopinionastowhetherornottheyaresubject toproprietaryrights.
PresidentandPublisher:PaulManning LeadEditor:MichelleLowman TechnicalReviewers:JoshuaBrauer,RobertDouglass,PeterM.Wolanin EditorialBoard:SteveAnglin,MarkBeckner,EwanBuckingham,GaryCornell,JonathanGennick,
JonathanHassell,MichelleLowman,MatthewMoodie,DuncanParkes,JeffreyPepper,Frank Pohlmann,DouglasPundick,BenRenow-Clarke,DominicShakeshaft,MattWade,TomWelsh
CoordinatingEditor:AnitaCastro CopyEditor:MaryAnnFugate ProductionSupport:PatrickCunningham Indexer:BIMIndexing&ProofreadingServices Artist:AprilMilne CoverDesigner:AnnaIshchenko
DistributedtothebooktradeworldwidebySpringerScience+BusinessMedia,LLC., 233SpringStreet,6thFloor,NewYork,NY10013.Phone1-800-SPRINGER,fax(201)348-4505, e-mail Forinformationontranslations ApressandfriendsofEDbooksmaybepurchasedinbulkforacademic,corporate,orpromotionaluse. eBookversionsandlicensesarealsoavailableformosttitles.Formoreinformation,referenceour SpecialBulkSales–eBookLicensingwebpageat Theinformationinthisbookisdistributedonan“asis”basis,withoutwarranty.Althoughevery precautionhasbeentakeninthepreparationofthiswork,neithertheauthor(s)norApressshallhave anyliabilitytoanypersonorentitywithrespecttoanylossordamagecausedorallegedtobecaused directlyorindirectlybytheinformationcontainedinthiswork.
Contents at a Glance
Foreword...........................................................................................
AbouttheTechnicalReviewers......................................................................
Introduction.......................................................................................
■
Chapter2:WritingaModule........................................................................
■
Chapter3:Hooks,Actions,andTriggers............................................................
■
Chapter4:TheMenuSystem.........................................................................
■
Chapter5:WorkingwithDatabases..................................................................
■
Chapter6:WorkingwithUsers......................................................................
■
Chapter7:WorkingwithNodes......................................................................
■
Chapter8:WorkingwithFields.....................................................................
■
Chapter9:TheThemeSystem........................................................................
■
Chapter10:WorkingwithBlocks....................................................................
■
Chapter11:TheFormAPI...........................................................................
■
Chapter12:ManipulatingUserInput:TheFilterSystem
■
Chapter13:SearchingandIndexingContent
■
Chapter14:WorkingwithFiles.....................................................................
■■ Chapter15:WorkingwithTaxonomy..................................................................
■ Chapter16:Caching................................................................................
■ Chapter17:Sessions...............................................................................
■ Chapter18:UsingjQuery...........................................................................
■ Chapter10:LocalizationandTranslation...........................................................
■ Chapter20:XML-RPC................................................................................
■ Chapter21:WritingSecureCode....................................................................
■ Chapter22:DevelopmentBestPractices
■ Chapter23:OptimizingDrupal......................................................................
■ Chapter24:InstallationProfiles..................................................................
■ Chapter25:Testing................................................................................
■ AppendixA:DatabaseTableReference...............................................................
■ AppendixB:Resources..............................................................................
Index..............................................................................................
Contents
Foreword...........................................................................................
AbouttheTechnicalReviewers......................................................................
Introduction.......................................................................................
■
WhatIsDrupal?...............................................................................................................
Core..........................................................................................................................
Modules.......................................................................................................................
Themes........................................................................................................................
Fields........................................................................................................................
FileLayout...................................................................................................................
TheWebServer’sRole.........................................................................................................
ProcessingaRequest.......................................................................................................... Summary.......................................................................................................................
■ Chapter2:WritingaModule........................................................................
ImplementingaHook................................................................................ DefiningYourOwnAdministrationSection........................................................... ValidatingUser-SubmittedSettings.................................................................
UsingDrupal’svariablesTable................................................................................................ FurtherSteps.................................................................................................................
■ Chapter3:Hooks,Actions,andTriggers............................................................
UnderstandingActions.............................................................................. TheTriggerUserInterface.................................................................................................... AssigningtheAction..........................................................................................................
UsingtheContextinActions............................................................................................45
HowtheTriggerModulePreparestheContext................................................................................... EstablishingtheContext......................................................................................................
HowActionsAreStored............................................................................. TheactionsTable.............................................................................................................
CallinganActionDirectlywithactions_do()....................................................... AddingTriggerstoExistingHooks..................................................................
Chapter4:TheMenuSystem......................................................................... ■
CallbackMapping................................................................................... CreatingaMenuItem............................................................................... PageCallbacksinOtherFiles...................................................................... MenuNesting.................................................................................................................. TitleLocalizationandCustomization...............................................................
WildcardsinMenuItems.................................................................................................74
BasicWildcards............................................................................................................... UsingtheValueofaWildcard................................................................................................. PassingAdditionalArgumentstotheLoadFunction............................................................................. BuildingPathsfromWildcardsUsingto_arg()Functions.............................................
AlteringMenuItemsfromOtherModules............................................................. KindsofMenuItems................................................................................
AssigningCallbacksWithoutAddingaLinktotheMenu HidingExistingMenuItems.................................................................................................... CommonMistakes...............................................................................................................
Summary....................................................................................................................... ■
DefiningDatabaseParameters....................................................................... ConnectingtotheDatabase......................................................................... RetrievingQueryResults...........................................................................
GettingaSingleValue........................................................................................................ UsingtheQueryBuilderandQueryObjects..................................................................................... GettingResultsforPagedDisplay.............................................................................................
InsertsandUpdateswithdrupal_write_record().............................................................98 TheSchemaAPI...............................................................................................................99
UsingModule.installFiles................................................................................................... UsingtheSchemaModule.......................................................................................................
DeclaringaSpecificColumnTypewithmysql_type................................................... DeletingTablesonUninstall..................................................................................................
ModifyingOtherModules’Querieswithhook_query_alter() UsingaTemporaryTable............................................................................ Summary.......................................................................................................................
■ The$userObject................................................................................... Introductiontouserhooks.........................................................................
Understandinghook_user_view($account,$view_mode)................................................. TheUserRegistrationProcess...................................................................... TheLoginProcess..................................................................................
AddingDatatothe$userObjectatLoadTime.................................................................................. ExternalLogin................................................................................................................
Chapter7:WorkingwithNodes...................................................................... ■
SoWhatExactlyIsaNode?......................................................................... CreatingaNodeModule.............................................................................
Creatingthe.installFile....................................................................................................
Creatingthe.moduleFile..................................................................................................................... ModifyingtheMenuCallback...............................................................................................................
LimitingAccesstoaNodeTypewithhook__node_access(). ............................................................. ValidatingFieldswithhook_validate().................................................................................................. KeepingDataCurrentwithhook_update()........................................................................................... ModifyingNodesofOurTypewithhook_load()....................................................................................
ManipulatingNodesThatAreNotOurTypewithhook_node_xxxxx(). ................................................ HowNodesAreStored.................................................................................................. RestrictingAccesstoNodes.........................................................................................
DefiningNodeGrants............................................................................................................................ Summary.......................................................................................................................161 Chapter8:WorkingwithFields. .........................................................................
■ CreatingContentTypes................................................................................................. CreatingaCustomField................................................................................................ Summary.......................................................................................................................183
Chapter9:TheThemeSystem........................................................................ ■
Themes........................................................................................................................ InstallinganOff-the-ShelfTheme.............................................................................................
The.infoFile................................................................................................................ AddingRegionstoYourTheme.................................................................................................. AddingJavaScriptFiles.......................................................................................................
UnderstandingTemplateFiles....................................................................... TheBigPicture............................................................................................................... OverridingTemplateFiles..................................................................................................... OverridingThemableItems..................................................................................................... AddingandManipulatingTemplateVariables....................................................................................
Summary....................................................................................................................... ■
WhatIsaBlock?................................................................................... BlockPlacement............................................................................................................... UsingtheBlockHooks.........................................................................................................
BuildingaBlock...................................................................................
BlockVisibilityExamples.......................................................................... DisplayingaBlocktoLogged-InUsersOnly....................................................................................
Summary....................................................................................................................... ■
UnderstandingFormProcessing....................................................................................239
InitializingtheProcess...................................................................................................... SettinganID................................................................................................................. LookingforaValidationFunction............................................................................................. AllowingModulestoAltertheFormBeforeIt’sBuilt.......................................................................... AllowingFunctionstoAltertheFormAfterIt’sBuilt......................................................................... FindingaThemeFunctionfortheForm......................................................................................... RenderingtheForm............................................................................................................ SubmittingtheForm...........................................................................................................
CreatingBasicForms.....................................................................................................247
FormProperties............................................................................................................... Fieldsets..................................................................................................................... SpecifyingValidationandSubmissionFunctionswithhook_forms()
WritingaValidationFunction................................................................................................. WritingaSubmitFunction..................................................................................................... SubmittingFormsProgrammaticallywithdrupal_form_submit()
FormAPIProperties................................................................................ PropertiesfortheRootoftheForm........................................................................................... PropertiesAllowedinAllElements............................................................................................
Summary....................................................................................................................... ■
Filters....................................................................................................................... InstallingaFilter...........................................................................................................
CreatingaCustomFilter........................................................................... Implementinghook_filter_info()............................................................................................... HelperFunction...............................................................................................................
Summary....................................................................................................................... ■
BuildingaCustomSearchPage....................................................................................307
TheDefaultSearchForm....................................................................................................... AddingtotheSearchForm.....................................................................................................
UsingtheSearchHTMLIndexer...................................................................... WhentoUsetheIndexer.......................................................................................................
Summary....................................................................................................................... ■
Chapter14:WorkingwithFiles..................................................................... ManagedandUnmanagedDrupalAPIs..................................................................
PublicFiles.................................................................................................................. PHPSettings..................................................................................................................
UploadField.................................................................................................................. FileAPI......................................................................................................................
DatabaseSchema............................................................................................................... AuthenticationHooksforDownloading..........................................................................................
Summary....................................................................................................................... ■
Chapter15:WorkingwithTaxonomy.................................................................. CreatingaVocabulary..............................................................................
AssigningaVocabularytoaContentType.....................................................................344 KindsofTaxonomy........................................................................................................345
Flat......................................................................................................................... MultipleHierarchical.........................................................................................................
ViewingContentbyTerm............................................................................ UsingANDandORinURLs...................................................................................................... AutomaticRSSFeeds...........................................................................................................
StoringTaxonomies................................................................................. CreatingaModule-BasedVocabulary............................................................................................
CommonTasks....................................................................................... DisplayingTaxonomyTermsAssociatedwithaNode................................................... Usingtaxonomy_select_nodes().................................................................................................
TaxonomyFunctions................................................................................. RetrievingInformationAboutVocabularies..................................................................................... RetrievingInformationAboutTerms............................................................................................ RetrievingInformationAboutTermHierarchy...................................................................................
AdditionalResources............................................................................... Chapter16:Caching................................................................................
■ KnowingWhentoCache..............................................................................
HowCachingIsUsedWithinDrupalCore......................................................................368
MenuSystem................................................................................................................... AdministrationVariablesandModuleSettings..................................................................................
Blocks........................................................................................................................ Summary.......................................................................................................................
■ Chapter17:Sessions...............................................................................
Usage........................................................................................................................ In.htaccess.................................................................................................................. Inbootstrap.inc..............................................................................................................
Storage....................................................................................................................... SessionConversations..............................................................................
FirstVisit................................................................................................................... UserwithanAccount..........................................................................................................
CommonTasks....................................................................................... ChangingtheLengthofTimeBeforeaCookie StoringDataintheSession...................................................................................................
Summary....................................................................................................................... ■
Chapter18:UsingjQuery........................................................................... TheOldWay...................................................................................................................
HowjQueryWorks................................................................................... UsingaCSSIDSelector....................................................................................................... jQueryWithinDrupal...............................................................................
YourFirstjQueryCode........................................................................................................ MethodChaining............................................................................................................... WrappingExistingElements.................................................................................................... WheretoPutJavaScript.......................................................................................................
BuildingajQueryVotingWidget.................................................................... BuildingtheModule........................................................................................................... WaystoExtendThisModule....................................................................................................
NextSteps.................................................................................................................... Chapter19:LocalizationandTranslation...........................................................
■
EnablingtheLocaleModule...........................................................................................417 UserInterfaceTranslation.............................................................................................417
Strings....................................................................................................................... ReplacingBuilt-InStringswithCustomStrings................................................................................
StartingaNewTranslation......................................................................... Generating.potFileswithTranslationTemplateExtractor.......................................... Creating.potFilesforanEntireSite........................................................................................
InstallingaLanguageTranslation.................................................................. SettingUpaTranslationatInstallTime......................................................................................
Right-to-LeftLanguageSupport..................................................................... Default....................................................................................................................... PathPrefixwithLanguageFallback............................................................................................
ContentTranslation................................................................................. IntroducingtheContentTranslationModule.................................................................................... MultilingualSupportwithTranslation.........................................................................................
Localization-andTranslation-RelatedFiles........................................................ Summary.......................................................................................................................
■ WhatIsXML-RPC?...................................................................................
XML-RPCClients............................................................................................................452
XML-RPCClientExample:GettingtheTime......................................................................................
XML-RPCClientExample:GettingtheNameofaState................................................
ASimpleXML-RPCServer............................................................................ MappingYourMethodwithhook_xmlrpc()........................................................................................
Built-InXML-RPCMethods........................................................................... system.listMethods............................................................................................................ system.methodHelp............................................................................................................. system.multiCall..............................................................................................................
Summary....................................................................................................................... ■
HandlingUserInput................................................................................ ThinkingAboutDataTypes..................................................................................................... Usingfilter_xss()toPreventCross-SiteScriptingAttacks.........................................
HandlingURLsSecurely............................................................................. KeepingPrivateDataPrivatewithhook_query_alter()............................................... PermissionsandPageCallbacks..................................................................... FileSecurity.................................................................................................................
FilePermissions.............................................................................................................. FileUploads..................................................................................................................
EncodingMailHeaders..............................................................................
FilesforProductionEnvironments................................................................................ Stand-AlonePHP. ......................................................................................................... FormAPISecurity. ........................................................................................................ Summary. .....................................................................................................................
■ CodingStandards. ........................................................................................................
LineIndentionandWhitespace............................................................................................................ Casting. .........................................................................................................................
FunctionCalls. ..................................................................................................................................... FunctionNames. .................................................................................................................................. Arrays...................................................................................................................................................
StringConcatenators............................................................................................................................
Comments.....................................................................................................................491
DocumentationExamples..................................................................................................................... DocumentingFunctions. ...................................................................................................................... IncludingCode......................................................................................................................................
Semicolons. ....................................................................................................
ExampleURLs.................................................................................................................. NamingConventions................................................................................. FindingYourWayAroundCodewithgrep.............................................................
■ Chapter23:OptimizingDrupal......................................................................
OptimizingPHP..................................................................................... SettingPHPOpcodeCacheFileto/dev/zero....................................................................................
TuningApache...................................................................................... mod_expires................................................................................................................... MPMPreforkvs.ApacheMPMWorker............................................................................................. DecreasingApacheTimeout.....................................................................................................
UsingNginxInsteadofApache...................................................................... Varnish......................................................................................................................
NormalizingincomingrequestsforbetterVarnishhits.............................................. Boost........................................................................................................................
LinuxSystemTuningforHighTrafficServers....................................................... DedicatedServersvs.VirtualServers.............................................................. DecreasingServerTimeouts.........................................................................
EnablingMySQL’sQueryCache.................................................................................................. DrupalPerformance.................................................................................
Eliminating404Errors........................................................................................................ Drupal-SpecificOptimizations......................................................................
PageCaching.................................................................................................................. PruningtheSessionsTable.................................................................................................... Runningcron..................................................................................................................
Architectures................................................................................................................. SingleServer................................................................................................................. SeparateDatabaseServerandaWebServerCluster..................................................
FindingtheBottleneck.............................................................................
■ Chapter24:InstallationProfiles..................................................................
Theenhanced.infoFile........................................................................................................ Theenhanced.installFile.....................................................................................................
Usinghook_install_tasksandhook_install_tasks_alter ■
Chapter25:Testing................................................................................ HowTestsAreDefined.............................................................................. TestAssertions....................................................................................
■ AppendixA:DatabaseTableReference...............................................................
■ AppendixB:Resources..............................................................................
TheDrupalSourceCodeRepositoryonGIT...................................................................................... DrupalAPIReference.......................................................................................................... UpdatingModules..............................................................................................................
Handbooks..........................................................................................
MailingLists................................................................................................................. Development.................................................................................................................. Translations..................................................................................................................
UserGroupsandInterestGroups.................................................................... NorthAmerica................................................................................................................. Asia.........................................................................................................................
Oceania................................................................................................................................................629 Africa....................................................................................................................................................629
Videocasts.................................................................................................................... Conferences........................................................................................
Index..............................................................................................
Foreword
Fouryearsago,Iwrotetheforewordforthefirsteditionofthisbook.Whatwasmissingatthattimewas adeveloperbookforDrupal.Sincethen,ProDrupalDevelopmenthasmadeanincrediblecontribution toDrupal’ssteadygrowth.Idon’tthinkIknowasingleDrupaldeveloperwhodoesn’townacopyofthe
ProDrupalDevelopmentbook.