Did you know? DZone has great portals for Python, Cloud, NoSQL, and HTML5!

PHP

  • submit to reddit

Getting Started with Drupal

By Matt Vance

14,184 Downloads · Refcard 59 of 151 (see them all)

Download
FREE PDF


The Essential Drupal Cheat Sheet

Drupal is an open source content management system and framework written in PHP. Drupal is used to power many of today’s high-profile sites, such as Popular Science, Ubuntu and the Electronic Frontier Foundation. This DZone Refcard will provide useful information to help you perform three of the most common roles associated with setting up a new Drupal site: site building, theming, and development. Youll also enjoy these other related Refcardz from our DZone Refcardz library: Essential MySQL and PHP.
HTML Preview
Getting Started with Drupal

Getting Started with Drupal

By Matt Vance

about drupal

Drupal is an open source content management system and content management framework written in PHP. Drupal is used to power a variety of high-profile web sites, including sites for Popular Science (http://www.popsci.com/), Ubuntu (http://www.ubuntu.com/), and the Electronic Frontier Foundation (http://www.eff.org/).

Drupal is designed to be modular, with a number of optional modules included in the default “core” Drupal package. These modules serve to extend and enhance the capabilities of Drupal core. In addition, thousands of contributed modules are available for download from the central Drupal community website, Drupal.org.

Drupal is most often run on a LAMP server stack (an acronym for Linux, Apache, MySQL, and PHP). However, Drupal is not limited to a single architecture and can be run under Apple’s OS X or Microsoft Windows. Alternative web servers supported by Drupal include Microsoft IIS and lighttpd. In addition to MySQL, Drupal can also be run using PostgreSQL for database storage.

Hot Tip

For a more thorough PHP reference, see the PHP Refcard (http://refcardz.dzone.com/refcardz/php). Drupal also includes the open source jQuery JavaScript library to simplify the creation of dynamic behavior within a user’s browser. For help using jQuery, check out the jQuery Selectors Refcard. (http://refcardz.dzone.com/refcardz/jquery-selectors).

This Drupal Refcard will provide useful information to help you perform three of the common roles associated with setting up a new Drupal site: site building, theming, and development. This Refcard focuses on Drupal 6, the latest major release available as of this writing.

Drupal site building

Drupal can be used to create just about any type of website, from simple single-author blogs to multi-user social networking communities. Along with Drupal’s flexibility comes a steep learning curve. First time site builders can quickly become overwhelmed by the thousands of available contributed modules.

While the Drupal community strives to work together to create user friendly modules that combine together well, not all modules are created equal. Since developers can’t be expected to test their modules in combination with every other available module, there are bound to be incompatibilities. It is important, especially for first time site builders, to evaluate modules on a test site before installing them on a production site.

Not all Drupal modules are ready for prime time, but some modules have been around long enough and are useful for enough applications to warrant being on a site builder’s short list.

Hot Tip

Sign up for an account on Drupal.org. Some areas and tools on the site are only available to logged in users, plus it is an important first step toward getting involved in the “community” that develops, supports, and steers the Drupal project. Get involved on the forums; both asking and answering questions can help you get up-to-speed more quickly.

CCK

The Content Construction Kit module, also known as CCK (http://drupal.org/project/cck), allows site builders to extend beyond the default content types that are included with Drupal. Not only can the default page and story content types (sometimes called “node” types) be rearranged or customized with additional fields, but completely new content types can also be created. CCK includes several sub-modules for adding a variety of custom field types such as select boxes, check boxes, text boxes, and more. In addition, other contributed modules, such as Date (http://drupal.org/project/date), FileField (http://drupal.org/project/filefield), and ImageField

refcardzad

(http://drupal.org/project/imagefield), can be downloaded separately to add more complex fields to your custom content types.

Views

The Views module (http://drupal.org/project/views) allows site builders a great deal of control and flexibility in presenting lists of content, also called “views”, on a site. The Views module provides a graphical user interface that can output nodes, users, comments, and more. Views can be presented as pages, as RSS feeds, or “blocks” (the often small pieces of content that are typically reused on various pages in sidebars, headers, and footers). The individual items that make up a view can be customized in terms of sort order, fields displayed, and the format of the list (such as unordered lists or tables).

Views Module

The Views module interface can take some time to master, but it is worth the investment. The flexibility of Views can be useful not just to site builders but also to developers, since views can be exported and bundled with modules.

Add on modules such as the Views Bonus Pack (http://drupal.org/project/view_bonus) can extend the Views module even more to present content as CSV files, Microsoft Word DOC files, or as XML.

Hot Tip

When installing new contributed modules and themes, resist the temptation to place the files in the default /modules or /themes directories. To make future upgrades of Drupal easier, create a /sites/all/ modules and /sites/all/themes directory instead. Contributed and custom modules and themes should then be placed in their own respective subdirectories.

Administration menu

The Administration Menu module (http://drupal.org/project/admin_menu) provides administrators with a small drop-down menu at the top of every page to allow easy access to the various administration pages that must be configured when building a new Drupal site.

Pathauto

The Pathauto module (http://drupal.org/project/pathauto) extends Drupal’s core Path module by automating the process of creating more user friendly and search engine friendly URL aliases for a site’s content. Pathauto requires and works in conjunction with the Token module (http://drupal.org/project/token).

Wysiwyg API

Drupal does not include a WYSIWIG editor by default; however, a wide variety of WYSIWYG and other client-side editors can be made to work with Drupal. The WYSIWYG API module (http://drupal.org/project/wysiwyg) provides Drupal integration for a variety of add-on editors, including: TinyMCE, FCKeditor, the YUI Rich Text Editor. Other modules provide support for individual editors, but it is likely that more will opt to integrate with the WYSIWYG API module going forward, in order to avoid duplicating development effort.

Hot Tip

With thousands of contributed modules, there is inevitably overlap in the functionality provided by some modules. Rather than installing each overlapping module to compare functionality, first check the “Comparisons of contributed modules” section of the Drupal handbooks (http://drupal.org/node/266179) to see if someone else has already documented their comparison. Example comparisons include WYSIWYG modules, node access modules, and content rotator modules.

Drupal theming

Drupal provides a flexible theming layer to allow a site’s design to be highly customized. While Drupal can be used in conjunction with a variety of “theme engines” such as Smarty or PHPTAL, most users will want to become familiar with Drupal’s default theme engine format, PHPTemplate.

Depending on the needs of your site, you may choose to create a completely custom theme or use one of Drupal’s “starter themes” as the basis for a new site design. Starter themes such as Zen, Blueprint, or Framework strive to provide a basic foundation that can be customized to provide the look and feel your site requires.

To create your own custom theme from scratch, start by creating a new directory for the theme under the /sites/all/ themes directory. For example, to create a new theme called “Beautiful”, start by creating a new /sites/all/themes/beautiful directory.

Hot Tip

Drupal’s default theme, Garland, was not designed to be a “starter theme.” When looking to transform an existing theme to match a specific design, avoid using Garland. Instead, start from scratch or look to themes such as Zen, Framework, or Basic. For a detailed comparison of starter themes, see http://adaptivethemes.com/starter-themecomparison. html

.info file

Typically a theme directory contains a number of files that work together to make up the theme. At the very least, a [themename] .info file is required in order for Drupal to recognize a theme. Building on the example above, a minimal beautiful.info file might start with the following:


name = Beautiful
description = A example theme created for educational purposes.
core = 6.x
engine = phptemplate

A number of optional keys such as regions, stylesheets, and scripts can also be defined in order to override the defaults Drupal provides. More details can be found in the Drupal handbooks(http://drupal.org/node/171205).

Drupal themes typically contain a number of template files such as page.tpl.php or node.tpl.php. Each template file specifies how a particular portion of the site is to be presented. The various core modules provide default template files that can be copied into your theme directory and edited to customize them to suit the needs of a particular site.

Template files (.tpl.php)

The base template file found in most themes is the page.tpl. php file which acts as a wrapper around most of the other template files. When building a new theme, the default page. tpl.php theme file found in the /modules/system directory can provide a good starting point. You can copy that file into your theme’s directory and customize it as needed.

Hot Tip

Drupal uses a theme registry to cache information about a theme. In order for Drupal to recognize changes to a theme such as adding files or changing the .info file, it is important to clear the theme registry. To clear the theme registry, go to the Performance page (Administer > Site configuration > Performance) and click on the “Clear cached data” button.

Additional template files can be used to customize the presentation of the various smaller elements of a Drupal site such as blocks, comments, polls, and more.

Template file Purpose
page.tpl.php the main container template file, which acts as a wrapper for the other template files below; see the following page for a list of available variables within the page.tpl.php file: http://api.drupal.org/api/file/modules/system/page.tpl.php
page-front.tpl.php can be used to specify a custom front page
node.tpl.php controls how the various content types or “nodes” are displayed; see the following page for a list of available variables within the node.tpl.php file: http://api.drupal.org/api/file/modules/node/node.tpl.php/6
node-[nodetype].tpl.php optional template files used to target and customize nodes of a specific content type
block.tpl.php contains the code used to display reuseable “block” content that may appear in multiple places within a site
block-[region].tpl.php optional template files to customize how blocks in specific block “regions” will appear; regions are the areas specified in the theme’s .info file where blocks can be designated to appear (such as headers, sidebars, etc)
comment.tpl.php controls the formatting of user comments

Template files can be targeted to customize specific content of a site by naming the files according to specific “suggestions.” For example, to customize the front page of a site, create a copy of the page.tpl.php file named page-front.tpl.php and customize the new front page template as needed. See the Drupal handbooks (http://drupal.org/node/190815) for more details about the various core template files and how to use and customize the suggestion options.

Hot Tip

When creating your own theme from scratch, be sure to output the $closure variable, just before the closing tag in the page.tpl.php file. The $closure variable is easy to overlook, but it is important because it outputs some final markup, which may cause some modules to fail, if it is missing.

template.php

The template.php file is an optional file used as a container for conditional processing and overriding of theme functions. In addition to overriding theme output using the template file method outlined above, Drupal also allows theme functions (any function beginning with “theme_”) to be overridden inside the template.php file. Those more familiar with programming in PHP may prefer to use template functions to override Drupal’s defaults in order to gain more flexibility and performance. A list of Drupal’s default theme functions can be found on the Drupal API site
(http://drupal.org/api/group/themeable).

Hot Tip

For help tracking down the particular function that controls the content you want to customize, install the Devel module (http://drupal.org/project/devel) and enable the Theme developer module that comes with it. The Theme developer module provides a graphical tool that can be used to select specific portions of a page and display the theme function or template file responsible for generating it.

style.css

Drupal will automatically recognize a style.css file as a theme’s primary cascading style sheet file. Additional CSS files can be specified in the .info file using the “stylesheets” key.

screenshot.png

The screenshot.png file is a thumbnail sized image of the theme presented on Drupal’s theme administration page to provide users with a preview of how a theme will look.

Drupal development

Drupal has a reputation as being created by developers for developers. While it has made great strides recently at becoming more user friendly, Drupal still has a lot to offer developers. Drupal has been designed with flexibility in mind. Developers can customize the vast majority of Drupal’s functionality through Drupal’s system of hook functions.

Novice users should not be dissuaded from creating their own custom modules. Even a simple single-function module can be useful for things such as customizing how Drupal presents a particular piece of content or form.

Hot Tip

Resist the temptation to modify the core of Drupal. “Hacking core” is discouraged, in favor of creating modules that modify Drupal’s behavior instead. Creating modules avoids having to maintain and apply patches to Drupal as updates get released
.

To develop a new custom module, start by creating a new directory for the module under the /sites/all/modules directory. For example, to create a new module called “Functional”, start by creating a new /sites/all/modules/functional directory.

Hot Tip

Before sitting down to develop a new custom module, take the time to browse or search the contributed modules available on Drupal.org. The thousands of modules available there are typically developed to be reusable in a variety of environments. You may not find a module that does exactly what you are looking for, you may find one that can be adapted to suit your needs. If you make improvements to an existing module, consider contributing your code back in the module’s issue queue, in the form of a patch. In addition to helping others, if the patch gets accepted, it will make future upgrades of the module on your own site easier.

.info file

As with themes, each Drupal module must include at least a .info file in order to be recognized. An example functional.info file might consist of the following:


; $Id$
name = Functional module
description = “A simple example module created for educational
purposes.”
core = 6.x

See the Drupal handbooks (http://drupal.org/node/231036) for details on the other keys that can be specified in the module’s .info file.

Once the .info file has been created, a module can be enabled on the Module administration page (Site building > Modules). However, until the .module file has been created, the module won’t provide any new functionality.

.module file

The .module file typically contains the majority of the code for a module. Modules interact with the core of Drupal by implementing various hook functions that get called as Drupal carries out various tasks. Certain specific hook functions will need to be implemented depending on what functionality or customization a particular module needs to provide. A list of available hook functions can be found on the Drupal API Reference site (http://api.drupal.org/api/group/hooks).

For our example functional.module file, we will implement the hook_nodeapi function. By implementing hook_nodeapi, a module can act on the node object used as a container for the majority of content within Drupal.

To implement a particular hook function within a module, replace the word hook within the functions name with the name of the module. For example, in a module called functional, the hook_nodeapi function is implemented as functional_nodeapi:


<?php
  function functional_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
   switch ($op) {
    case ‘view’:
     $node->content[‘body’][‘#value’] .= “<br><br>Brought to you
by RefCardz”;
     break;
  }
}

Once the “functional” module is enabled, all nodes within the site will appear with a “Brought to you by RefCardz” notice at the bottom.

Hot Tip

To quickly dump variables to the screen for debugging purposes, you can take advantage of the message area typically found at the top of the page in most themes, by using the following function: drupal_set_message(‘<pre>’ . print_r($variable, TRUE) . ‘</pre>’);
If you have the Devel module enabled, you can take advantage of more cleanly formatted output by using the following instead: dpm($variable);

By implementing hook_form_alter, modules can use Drupal’s Form API to add, remove, or change forms. For example, some sites use the Views module or Panels module to customize the site’s front page, so the “Promoted to front page” publishing option may need to be removed to avoid confusion. The following code will remove the checkbox used to promote content to the front page.


function functional_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == ‘page_node_form’) {
    unset($form[‘options’][‘promote’]);
  }
}

For a more detailed introduction to the Forms API, see the “Forms API Quickstart Guide” (http://api.drupal.org/api/file/ developer/topics/forums_api.html)

Useful Hook Functions (for a complete listing of hook functions, see
http://api.drupal.org/api/group/hooks/)
Description
hook_block
http://api.drupal.org/api/function/hook_block/
Declare a block or set of blocks
hook_cron
http://api.drupal.org/api/function/hook_cron/
Perform periodic actions
hook_db_rewrite_sql
http://api.drupal.org/api/function/hook_db_rewrite_sql/
Rewrite database queries, usually for access control
hook_enable
http://api.drupal.org/api/function/hook_enable/
Perform necessary actions after module is enabled
hook_form_alter
http://api.drupal.org/api/function/hook_form_alter/
Perform alterations before a form is rendered
hook_mail_alter
http://api.drupal.org/api/function/hook_mail_alter/
Alter any aspect of the emails sent by Drupal
hook_mail
http://api.drupal.org/api/function/hook_mail/
Prepare an email message based on parameters
hook_menu
http://api.drupal.org/api/function/hook_menu/
Define menu items and page callbacks
hook_perm
http://api.drupal.org/api/function/hook_perm/
Define user permissions
hook_user
http://api.drupal.org/api/function/hook_user/
Act on user account actions
hook_watchdog
http://api.drupal.org/api/function/hook_watchdog/
Log an event message

.install file

Another file commonly found in Drupal modules is the .install file. The .install file is used to store code that is run when a module is installed or uninstalled, such as the hook_schema and hook_install functions.

Common .install File Functions Description
hook_install
http://api.drupal.org/api/function/hook_install/
Install the current version of the database schema, and any other setup tasks.
hook_schema
http://api.drupal.org/api/function/hook_schema/
Define the current version of the atabase schema.
hook_uninstall
http://api.drupal.org/api/function/hook_uninstall
Remove any tables or variables that the module sets.

Modules for developers

Modules for Developers

Several of the contributed modules for Drupal provide tools useful to module developers.

Deadwood

As new versions of Drupal get released, it can take a while for existing modules to get upgraded. The Deadwood module (http://drupal.org/project/deadwood) helps speed up the process of upgrading Drupal modules by automating some of the code updates.

Devel module

The Devel module (http://drupal.org/project/devel) provides tools for clearing Drupal’s cache, for generating dummy content, for debugging access issues, for performance logging, and much more.

Devel Mode

The Devel module also includes an open source debugging tool called Krumo that can display a structured representation of any PHP variable. Devel adds “Dev load” and “Dev render” tabs to nodes which output the Node object through Krumo. With Devel enabled, you can output your own variables through Krumo using Devel’s print message function, dpm().

Coder module

Since the Deadwood module doesn’t completely automate the process of upgrading modules from one version of Drupal to the next, there is usually some manual coding to be performed after running Deadwood. That is where the Coder module (http://drupal.org/project/coder) comes in handy. The Coder module does not modify code, but it provides an automated code review that can pinpoint areas of code that need to be updated.

Coder Module

The Coder module can also help enforce coding standards by pinpointing sloppy coding and suggesting ways to clean it up. The Coder module can be especially helpful to run before contributing code back to the community at Drupal.org. Schema

The Schema module (http://drupal.org/project/schema)

provides tools for working with Drupal’s database Schema API. If you’ve already manually created the tables required by a module, the schema module can provide the corresponding schema data structure to be added to your module’s .install file, making it easier to replicate the same tables on another Drupal installation.

Cache Disable

Drupal’s caching system can be a source of confusion and productivity loss, if you are not careful. Rather than having to remember each of the various tasks that require the cache to be flushed, install and enable the Cache Disable module (http://drupal.org/project/cache_disable) when doing development on a new site. Just remember to turn the module off, once you have completed your development work.

API

The API module (http://drupal.org/project/api) is used to generate the hyperlinked documentation found at api.drupal. org. The same module can be used to provide a local version of Drupal’s API documentation. In addition to providing documentation on Drupal’s core modules, the API module can also generate documentation pages for installed modules that follow Drupal’s coding standards. If you prefer not to set up your own API site, you can still browse the documentation for many of the contributed modules, courtesy of Drupal consulting company Lullabot (http://api.lullabot.com/)

Other API Modules

Though Drupal does provide a full-fledged development framework, it doesn’t include everything one might need for every possible coding task. Thankfully, the repository of contibuted modules on drupal.org includes quite a few API modules. Many of the API modules provide no functionality on their own, but provide API code that other modules and module developers can build on. Example API modules include the Voting API (http://drupal.org/project/feedapi), Chart API (http://drupal.org/project/chart), and the Import/ Export API (http://drupal.org/project/importexportapi).

Resources

URL Reference
http://api.drupal.org/ Documentation of Drupal’s API
http://drupal.org/handbooks The Drupal community maintains several handbooks including documentation for beginners, themers, and developers
http://drupalcodesearch.com/ Drupal Code Search allows users to search much of Drupal’s contributed code, though the index may not reflect the latest up-to-the-minute changes
http://cvs.drupal.org/ A web interface to browse the code in the Drupal.org CVS repository, from the start of the project to the latest in contributed modules
http://drupalmodules.com/ Drupal Modules allows users to rate modules. Ratings can be handy when choosing modules to use on a site
http://drupal.org/planet Drupal Planet aggregates a number of blogs that post regularly about Drupal
http://groups.drupal.org/ Groups.Drupal is a gathering place for niche groups within the Drupal community. Try searching for a user group near you or a group focused on your specific area of interest
http://drupal.org/irc Learn how to connect to Drupals IRC channels and connect with a world-wide community of developers at all hours of the day
http://drupal.org/mailing-list Drupal.org provides a number of mailing lists to keep the community up-to-date. Anyone running a public Drupal site should subscribe to the security announcements mailing list
http://association.drupal.org/ The Drupal Association is a not-for-profit association charged with providing support to the Drupal project
http://drupal.org/getting-involved The Drupal project thrives largely due to a strong community of contributors. Read the “Getting Involved” handbook to learn how you too can contribute
http://ww.lullabot.com/podcast Several Drupal podcasts exist, both in audio and video formats, but the Lullabot podcasts are longest-running and arguably the most in-depth

About The Author

Photo of Matt Vance

Matt Vance

is a Web developer, technology consultant, and freelance writer living in Austin, Texas. He has written for Macworld magazine and Lifehacker.com. He can be contacted through his website, http://minezone.org/

Recommended Book

Drupal

Newcomers will find a thorough introduction to the framework, while experienced Drupal developers will learn best practices for building powerful websites. With Using Drupal, you’ll find concrete and creative solutions for developing the exact community website you have in mind.


Share this Refcard with
your friends & followers...

DZone greatly appreciates your support.


Your download should begin immediately.
If it doesn't, click here.

Daily Dose - PHP 5.3.5 and 5.2.17 Fix Cruicial "Floating-Point Bug"

The floating-point bug is an error in the way that PHP converts numbers that may cause system resource problems.  This error opens up a system to a DoS attack on 32-bit systems.  You can find a PHP script that determines whether your system is affected by...

0 replies - 16028 views - 01/10/11 by Mitchell Pronsc... in Daily Dose

Daily Dose - Chromium OS on the iPad

A developer who provides nightly Chromium builds has managed to port Google's Chromium OS to the iPad.  He posted a picture of the iPad's web page running in a Chrome browser on the iPad.  However, he's planning to post on the "few catches"...

0 replies - 18170 views - 09/30/10 by Mitchell Pronsc... in Daily Dose

Adobe ColdFusion Web Services for PHP Programmers

By Marco Tabini

3,799 Downloads · Refcard 116 of 151 (see them all)

Download
FREE PDF


The Essential ColdFusion Web Services Cheat Sheet

ColdFusion Web Services can be deployed using a variety of standard protocols like SOAP or plain XML, you can easily take advantage of them from your PHP 5 scripts using nothing more than the standard web service facilities of the language. This DZone Refcard will introduce you to features that allow PHP Programmers to take advantage of the ColdFusion platform. Specifically, youll find out how to access and discover exposed web services and services from PHP, how to generate documents and charts, and how to manipulate PDFs and images.
HTML Preview
Adobe® ColdFusion Web Services for PHP Programmers

Adobe® ColdFusion Web Services: for PHP Programmers

By Marco Tabini

INTRODUCTION

Adobe® ColdFusion 9 (CF9) is a technology platform that allows developers to create web-based applications of any complexity using a set of easy-to-use tools.

In addition to being a standalone server-side technology, ColdFusion also provides a number of facilities that allow you to perform tasks like manipulating PDF or Microsoft Office files, sending e-mail, creating charts, and much more—all tasks that often require expensive dedicated solutions that must be developed in-house.

Because ColdFusion services can be deployed using a variety of standard protocols like SOAP or plain XML, you can easily take advantage of them from your PHP 5 scripts using nothing more than the standard web service facilities of the language. In fact, you can take advantage of CF9’s “Exposed Services” without even writing a single line of CFML code!

Obtaining and Installing CF9

Much like PHP, ColdFusion is a cross-platform product that is capable of running on a variety of platforms, including Windows, Mac OS X and any variety of Linux on which you can install a Java runtime environment.

CF9 comes in two different editions: Standard and Enterprise. The latter provides a number of scalability and monitoring facilities designed for large deployments, while the former is targeted at simpler needs. Outside of these differences, however, both editions offer a comparable set of core features, which means that your CF9 server setup can grow organically without having to sacrifice any functionality—which CF9 edition you choose will be primarily dictated by the amount of traffic that you need to serve, rather than by the type of task that you need to perform.

Hot Tip

You can find a feature-by-feature comparison of each CF9 edition at http://www.adobe.com/products/ coldfusion/pdfs/cf9_feature_comparison_matrix_ue.pdf

While CF9 is a commercial product that requires the purchase of a license in order to be used in a production environment, Adobe makes a Developer Edition of the platform available free of charge. Its only limitation is that it allows no more than two concurrent connections—perfect for developing locally on your machine.

You can download the Developer Edition of CF9 directly from the Adobe website at http://www.adobe.com/products/coldfusion/; like the commercial versions of CF9, the Developer Edition is available for every platform supported by the product. Once you have downloaded and launched the installer, the setup process will ask you a number of questions, including whether you want to install OpenOffice, which CF9 uses to manipulate Microsoft Office documents, and whether to enable the Remote Development Service, which you should do in a development environment if you plan on taking advantage of CF9’s debugging features.

Configuration and Settings

At the end of the setup process, the installer will launch the Configuration and Settings Wizard, a web-based application that completes your server’s configuration and eventually grants you access to the ColdFusion Administrator, from which you can control and manipulate all your server-side settings.

ACCESSING EXPOSED WEB SERVICES

You don’t need to know how to develop ColdFusion applications in order to take advantage of the Exposed Services that are part of the platform.

In fact, CF9 makes a number of its features available directly through a SOAP-based interface, allowing you to:

  • Generate and manipulate PDF files
  • Manipulate images
  • Generate Micr osoft Office documents
  • Send and r eceive e-mail

Access Control

In order to access any of the exposed CF9 services, you need to first define the appropriate set of access controls. You can do so by creating a user by opening the Administrator and clicking on the “User Manager” item under the “Security” menu. Click on the “Add User” button, and then fill the user authentication form with the appropriate information.

authentication

At this point, you can define which Exposed Services the user has access to by selecting them in the “Prohibited Services” list and transferring them to the ”Allowed Services” list. Exposed Services

To finish, click on the “Add User” button and you’re all set!

Enabling Client Access

By default, to ensure the security of your server, CF9 precludes any client from accessing Exposed Services.

You can change this setting by clicking on the “Allowed IP Addresses” item under the “Security Menu,” where you can add one or more IPs (or IP ranges) to the server’s whitelist for Exposed Services.

Security Menu

Hot Tip

The examples in this Refcard assume that you are running the Developer Edition of CF9 on your local machine. For deployment, you will need to alter your settings according to the make-up of your specific production environment.

Configuring Services

Some services must be configured before they can be used. For example, the Mail service requires you to specify an SMTP server before it can be used to send messages, while the Document service requires you to specify the location of OpenOffice, and so on.

In all cases, you can view and modify the settings for the services exposed by your server directly from the Administrator.

DISCOVERING EXPOSED SERVICES FROM PHP

Exposed Services are made available through a specific location on your server; typically, if you have installed your copy of CF9 using the standard settings, this will be at http://127.0.0.1:8500/CFIDE/services/. If you point your browser to that URL, you will be greeted with a list of all the service entry points available.

Clicking on a specific file will cause CF9 to output a help page that describes all the functionality provided by the service and all the available remote method calls.

remote method calls

Hot Tip

Complete documentation for all the Exposed Services can be found on the Adobe Help site at http://help.adobe.com/en_US/ColdFusion/9.0/CFMLRef/ index.html both in a “live” web-based version and in PDF format.

Accessing a Service’s WSDL Specification

Since your PHP scripts will be accessing Exposed Services through SOAP, you need access to the WSDL specification for the services you want to interface with.

Luckily, CF9 supports the built-in generation of WSDL documents, so all you need to do is add a special query string to the end of the URL of its entry point. For example, the WSDL for the Mail service can be accessed at this URL: http://127.0.0.1:8500/CFIDE/services/mail.cfc?WSDL

Using SOAP

PHP 5’s web service libraries make accessing web services of any kind very easy.

Once you have access to the WSDL, you can call any of the services directly from a PHP 5.x script by using the SOAPClient class. SOAPClient encapsulates a SOAP service and provides the means for introspecting its methods and data types, as well as performing calls against it.

For example, having obtained the URL of the WSDL document for the Mail service, you can find out which method calls it supports by running this simple script:


$service = new SOAPClient(‘http://127.0.0.1:8500/CFIDE/services/mail.
cfc?WSDL’);
var_dump($service->__getFunctions());

This will produce the following output:


array(1) {
  [0]=>
  string(35) “sendResponse send(send $parameters)”
}

This indicates that the service supports a method called send() that takes a single parameter of type “send” in input and returns a value of type “sendResponse” in output.

Much like the __getFunctions() method of SOAPClient can be used to retrieve the names of all the remote procedure calls provided by a service, __getTypes() can be used to retrieve a description of all the compound data types defined by it. In this case, the output will contain a description of both the “send” and “sendResponse” data types, which we can then use to issue a call to the service:


<?php
$service = new SOAPClient(‘http://127.0.0.1:8500/CFIDE/services/mail.
cfc?WSDL’);
$payload = array(
‘serviceusername’ => ‘johndoe’,
‘servicepassword’ => ‘johndoepassword’,
‘server’ => ‘smtp.example.com’,
‘port’ => ‘25’,
‘username’ => ‘smptuser’,
‘password’ => ‘smptpassword’,
‘from’ => ‘marco@example.com’,
‘to’ => ‘marco@example.com’,
‘bcc’ => ‘’,
‘cc’ => ‘’,
‘subject’ => ‘Test’,
‘content’ => ‘This is a test e-mail!’,
‘type’ => ‘’,
‘charset’ => ‘’,
‘failto’ => ‘’,
‘mailerid’ => ‘’,
‘mimeattach’ => ‘’,
‘priority’ => ‘’,
‘replyto’ => ‘’,
‘timeout’ => ‘’,
‘useSSL’ => ‘’,
‘useTLS’ => ‘’,
‘wraptext’ => ‘’,
‘attachments’ => ‘’,
‘mailparts’ => ‘’,
);

As you can see, you can leave those fields that are not required blank by setting them to an empty string; however, you must include them in the payload, and they cannot be set to NULL.

Hot Tip

If you use an IDE to edit your PHP code, you may be able to take advantage of advanced SOAP functionality such as code completion or service proxying. Check your IDE’s documentation for more information.

You have probably noticed the serviceusername and servicepassword properties at the beginning of the payload: these are the credentials of the user that you defined earlier in the Administrator.

Dealing with Failure

Occasionally, any code can fail. It is, therefore, essential to be able to manage failure in a predictable and safe way.

When a service call fails, SOAPClient throws an exception of the appropriate kind, which, generally, includes some information about the error and provides useful clues on how to address it. For example:


PHP Fatal error: Uncaught SoapFault exception: [soapenv:Server.
userException] coldfusion.xml.rpc.CFCInvocationException: [coldfusion.
servicelayer.ServicelayerExceptions$UserNotAuthorizedException : User
johndoe is not authorized to invoke mail service]
Stack trace:
[...]

In this particular case, you can plainly see that the failure is caused by the fact that the password provided for the service user was incorrect.

Hot Tip

In a production environment, you should always encapsulate your service calls in a try... catch code block and handle failures appropriately.

GENERATING DOCUMENTS

The Document Exposed Service can be used to generate documents based on existing templates, or even on the contents of a web page.

You can find the WSDL for the Document service at this URL: http://127.0.0.1:8500/CFIDE/services/document.cfc?wsdl

As you can see by introspecting the WSDL descriptor or reading the documentation for the service, Document supports a method called generate() that requires a long list of parameters. However, you only need a couple of them to create a PDF out of a web page:


<?php

$service = new SOAPClient(‘http://127.0.0.1:8500/CFIDE/services/document.
cfc?wsdl’);

$payload = array(
	‘serviceusername’ => ‘johndoe’,
	‘servicepassword’ => johndoepassword’,
	‘format’ => ‘pdf’,
	‘content’ => ‘’,
	‘authpassword’ => ‘’,
	‘authuser’ => ‘’,
	‘backgroundvisible’ => ‘’,
	‘bookmark’ => ‘’,
	‘encryption’ => ‘’,
	‘fontembed’ => ‘’,
	‘marginbottom’ => ‘’,
	‘marginleft’ => ‘’,
	‘marginright’ => ‘’,
	‘margintop’ => ‘’,
	‘mimetype’ => ‘’,
	‘orientation’ => ‘’,
	‘ownerpassword’ => ‘’,
	‘pageheight’ => ‘’,
	‘pagetype’ => ‘’,
	‘pagewidth’ => ‘’,
	‘permissions’ => ‘’,
	‘proxyhost’ => ‘’,
	‘proxypassword’ => ‘’,
	‘proxyport’ => ‘’,
	‘proxyuser’ => ‘’,
	‘src’ => ‘http://google.com’,
	‘scale’ => ‘’,
	‘unit’ => ‘’,
	‘useragent’ => ‘’,
	‘userpassword’ => ‘’,
	‘documentsection’ => ‘’,
	‘documentitem’ => ‘’,
);

$result = $service->generate($payload);

$pdfUrl = $result->generateReturn;


As you can see, the service returns a structure that contains the URL to the PDF file that was generated from the URL you provided in input. You can either redirect your client to that URL, or read the file and output it directly from your PHP file if the CF9 server is not directly reachable to the client that invoked your PHP script.

Hot Tip

The Trial and Developer edition of CF9 will place a watermark on all generated files. Licensed versions of CF9 do not have this limitation.

While the example above is a bit contrived, there are many practical scenarios in which being able to create PDF files can be useful to a web project—think, for example, of e-commerce systems that must deliver receipts to their customers.

MANIPULATING PDF FILES

The PDF service, as its name implies, makes it possible for you to manipulate PDF files. You can perform tasks like add watermarks, add, delete and extract pages from a document, merge documents together and modify their security features. The PDF service can be accessed through this WSDL file: http://127.0.0.1:8500/CFIDE/services/pdf.cfc?WSDL

Retrieving Information About a PDF File

The getinfo() method of the service allows you to retrieve a wealth of information from a PDF file—from the name of the application that was used to create it to the number of pages it contains:


<?php

$service = new SOAPClient(‘http://127.0.0.1:8500/CFIDE/services/pdf.
cfc?wsdl’);

// var_dump($service->__getTypes());

$payload = array(
	‘serviceusername’ => ‘johndoe’,
	‘servicepassword’ => ‘johndoepassword’,
	‘source’ => ‘http://example.com/example.pdf’,
	‘password’ => ‘’,
);

$result = $service->getinfo($payload);

echo $result->application;
echo $result->totalPages;

As you can see, the service expects you to pass a URL to the PDF file that needs to be inspected—clearly, this location must be accessible to your CF9 installation.

Hot Tip

You can examine and manipulate protected PDF files by providing a value for the password parameter of most PDF service calls. Note that using the document’s user password will limit you to the functionality that has been enabled by the creator. For more information on the PDF security model, visit http://createpdf.adobe.com/cgi-feeder.pl/help_security

Generating Thumbnail Views

Another useful feature of the PDF service is the ability to generate thumbnail images of a document’s pages:


<?php

$service = new SOAPClient(‘http://127.0.0.1:8500/CFIDE/services/pdf.
cfc?wsdl’);

$payload = array(
	‘serviceusername’ => ‘johndoe’,
	‘servicepassword’ => ‘johndoepassword’,
	‘source’ => ‘http://example.com/example.pdf’,
	‘format’ => ‘jpg’,
	‘imageprefix’ => ‘img’,
	‘password’ => ‘’,
	‘pages’ => ‘’,
	‘resolution’ => ‘high’,
	‘scale’ => ‘’,
	‘transparent’ => ‘’,
);

$result = $service->thumbnail($payload);

foreach ($result->thumbnailReturn as $thumbnail) {

	echo $thumbnail->value;
}


Upon a successful execution, this method returns a collection of objects that provide URLs for each of the thumbnails generated. As you can see, you can specify a number of different options: the output format (JPEG in this case, but PNG and TIFF are also supported), the resolution (high or low), the scale (a percentage between 1 and 100), and so on.

Password-protect and Encrypt PDF Documents

It is sometimes convenient to be able to dynamically password-protect a PDF document—for example to provide each user with a customized version that can only be opened using his or her password.

This can be easily accomplished by calling the protect() method:


<?php
$service = new SOAPClient(‘http://127.0.0.1:8500/CFIDE/services/pdf.
cfc?wsdl’);

$payload = array(
	‘serviceusername’ => ‘johndoe’,
	‘servicepassword’ => ‘johndoepassword’,
	‘source’ => ‘http://example.com/example.pdf’,
	‘newUserPassword’ => ‘userpass’,
	‘newOwnerPassword’ => ‘ownerpass’,
	‘permissions’ => ‘AllowPrinting,AllowScreenReaders’,
	‘encrypt’ => ‘RC4_128M’,
	‘password’ => ‘’,
);

$result = $service->protect($payload);

echo $result->protectReturn;

The result of the call will contain the URL to the newly protected document in a property called protectedReturn.

Note that the service call allows you to specify both an owner and client password (http://createpdf.adobe.com/cgi-feeder.pl/help_security for more information on the Adobe PDF security model) as well as specific permissions that users are allowed to take advantage of. All these options are explained in the CF9 documentation.

Merging PDF Files

The ability to merge one or more PDF files can be handy in a number of different scenarios. Imagine, for example, compiling several reports into a single document, or dynamically creating PDF books for your customers based on specific chapters that they decide to buy.

CF9 makes this task very easy to accomplish:


<?php

error_reporting(E_ALL | E_STRICT);

$service = new SOAPClient(‘http://127.0.0.1:8500/CFIDE/services/pdf.
cfc?wsdl’);

$payload = array(
	‘serviceusername’ => ‘johndoe’,
	‘servicepassword’ => ‘johndoepassword’,
	‘source’ => ‘http://example.com/example.pdf, http://example.com/
example2.pdf’,
	‘keepbookmark’ => ‘1’
);

$result = $service->mergeFiles($payload);

echo $result->mergeFilesReturn;

The merge operation can be performed on an arbitrary number of files (greater than or equal to two). The keepbookmark parameter allows you to maintain all the existing bookmarks from your source PDFs into the final result.

MANIPULATING IMAGES

While PHP has some powerful image manipulation functions provided by the GD Library, the latter does have some limitations. It is sometimes difficult to install, and the process of creating and manipulating the images can require multiple complex steps.

If you happen to also have access to an instance of CF9, however, you can take advantage of its Image services for a set of easy-to-use manipulation functions that, while not as rich as the ones provided by GD, require much less effort, especially for simple tasks.

The Image service’s WSDL can be accessed at this URL: http://127.0.0.1:8500/CFIDE/services/image.cfc?WSDL

Obtaining Information About an Image

For example, you can obtain a wealth of information on an image through a simple call to the Info method of the Image service:


<?php

$service = new SOAPClient(‘http://127.0.0.1:8500/CFIDE/services/image.
cfc?wsdl’);

$payload = array(
	‘serviceusername’ => ‘johndoe’,
	‘servicepassword’ => ‘johndoepassword’,
	‘source’ => ‘http://example.com/logo.png’,
);
$result = $service->info($payload);
foreach ($result->InfoReturn as $info) {
	echo $info->key, ‘ => ‘, $info->value, “\n”;
}


The result of the method call is a long list of data on the image:


source => _cf5341945594648670180.png
height => 126
width => 103
colormodel.pixel_size => 32
colormodel.bits_component_1 => 8
colormodel.bits_component_2 => 8
colormodel.alpha_channel_support => YES
colormodel.colormodel_type => ComponentColorModel
colormodel.colorspace => Any of the family of RGB color spaces
colormodel.alpha_premultiplied => NO
colormodel.transparency => TRANSLUCENT
colormodel.num_color_components => 3
colormodel.bits_component_3 => 8
colormodel.num_components => 4
colormodel.bits_component_4 => 8

As you can see, we can now determine the width and height of the image, as well as gather lots of information about its color model.

Resizing an Image

Another typical operation that is performed on images is resizing them; in this case, the functionality provided by CF9 is much simpler than its GD equivalent:


<?php

$service = new SOAPClient(‘http://127.0.0.1:8500/CFIDE/services/image.
cfc?wsdl’);

$payload = array(
	‘serviceusername’ => ‘johndoe’,
	‘servicepassword’ => ‘johndoepassword’,
	‘source’ => ‘http://example.com/logo.png’,
	‘width’ => 100,
	‘height’ => 100,
	‘interpolation’ => ‘highestquality’,
	‘blurfactor’ => 1,
);

$result = $service->resize($payload)->ResizeReturn;

As you can see, the process is fairly simple. All you need to do is specify a location for the image, its new dimensions, an interpolation algorithm and a blur factor; the latter is used to reduce resizing artifacts when the final image has a larger size than the original.

Compared to the GD method of resizing images, the CF9 approach has several advantages. First, it’s a one-step operation, whereas GD requires multiple separate steps. Second, CF9 takes care of caching the output image for you, thus making caching repeated resize operations easier.

CHARTING

While there are numerous open source libraries and free web services that can be used to generate charts, CF9 provides a truly powerful service whose functionality is hard to beat.

For example, in addition to creating charts in a multitude of different varieties, the Chart service allows you to output in several formats, including as an interactive file in the form of an Adobe® Flash® movie that features mouse-over effects and animations.

The WSDL for the Chart service can be found at this URL: http://127.0.0.1:8500/CFIDE/services/chart.cfc?WSDL

Generating Charts

The functionality provided by the Chart service is rich and complex, but can all be accessed through a single call to the generate() method. As a result, the latter has a signature that looks a little intimidating at first, but that is, in reality, very easy to grasp once you get through the basics. Here’s an example:


<?php

$service = new SOAPClient(‘http://127.0.0.1:8500/CFIDE/services/chart.
cfc?wsdl’);

$payload = array(
		‘serviceusername’ => ‘johndoe’,
		‘servicepassword’ => ‘johndoepassword’,
		‘backgroundcolor’ => ‘’,
		‘chartheight’ => ‘’,
		‘chartwidth’ => ‘’,
		‘databackgroundcolor’ => ‘’,
		‘font’ => ‘’,
		‘fontbold’ => ‘’,
		‘fontitalic’ => ‘’,
		‘fontsize’ => ‘’,
		‘foregroundcolor’ => ‘’,
		‘format’ => ‘flash’,
		‘gridlines’ => ‘’,
		‘labelformat’ => ‘’,
		‘markersize’ => ‘’,
		‘pieslicestyle’ => ‘’,
		‘scalefrom’ => ‘’,
		‘scaleto’ => ‘’,
		‘seriesplacement’ => ‘’,
		‘show3d’ => ‘’,
		‘showborder’ => ‘’,
		‘showlegend’ => ‘’,
		‘showmarkers’ => ‘’,
		‘showxgridlines’ => ‘’,
		‘showygridlines’ => ‘’,
		‘sortxaxis’ => ‘’,
		‘tipbgcolor’ => ‘’,
		‘tipstyle’ => ‘’,
		‘title’ => ‘’,
		‘url’ => ‘’,
		‘xaxistitle’ => ‘’,
		‘xaxistype’ => ‘’,
		‘xoffset’ => ‘’,
		‘yaxistitle’ => ‘’,
		‘yaxistype’ => ‘’,
		‘yoffset’ => ‘’,
		‘chartseries’ => array (
				‘chartdata’ => array (
					0 => array (
						‘item’ => ‘Sales’,
						‘value’ => ‘90000’
					),
					1 => array (
						‘item’ => ‘Revenue’,
						‘value’ => ‘150000’
						)
			),
			‘colorlist’ => ‘red,green’,
			‘datalabelstyle’ => ‘’,
			‘paintstyle’ => ‘’,
			‘seriescolor’ => ‘’,
			‘serieslabel’ => ‘’,
			‘type’ => ‘bar’,
		)
);
$result = $service->generate($payload)->generateReturn;

As you can see, despite the long list of parameters, all you really need to provide is one or more “chartseries” values, which are nothing more than a collection of data points in item/value format and a few specs on how those data points should be represented. The remaining parameters can be used to further tweak the chart’s appearance and manipulate items like its title, font characteristics, the visibility of grid-lines, and so on.

Chart

This last example barely scratches the surface of CF9’s charting service has to offer. For example, you can actually create 3-D charts, or combine multiple graphs into a single image. Depending on the complexity of your project, CF9 can greatly enhance the look of your application, and provide your users with helpful visuals.

LEARN MORE ABOUT CF9 WEB SERVICES

There is a lot more to CF9’s Web Services offerings than what can be covered in this Refcard — for example, there is an entire service dedicated to e-mail. Luckily, Adobe maintains a comprehensive set of documentation for developers at http://help.adobe.com/en_US/ColdFusion/9.0/Developing/index.html.

About The Authors

Photo of author By Marco Tabini

MANIK SURTANI

Marco Tabini is the co-founder, with Arbi Arzoumani, of php|architect, the world’s largest PHP magazine in the English language, currently distributed in over 145 countries. He is also the co-founder, with Keith Casey, of Blue Parabola, LLC, a consulting firm that specializes in information architecture, code and security auditing, largescale deployments and optimization.

An accomplished author on the subject of PHP and the business of web development, Marco is also a frequent speaker at PHP and OSS conferences throughout the world.

Recommended Book

Adobe Coldfusion 9

Written by the best known and most trusted name in the ColdFusion community, Ben Forta, The ColdFusion Web Application Construction Kit is the best-selling ColdFusion series of all time - the books that most ColdFusion developers used to learn the product. This Getting Started volume starts with Web and Internet fundamentals and database concepts and design, and then progresses to topics including creating data-driven pages, building complete applications, implementing security mechanisms, integrating with e-mail, building reusable functions and components, generating data-driven reports and graphs, building Ajaxpowered user interfaces, and much more. Complete coverage of ColdFusion 9 continues in “Volume 2, Application Development” (ISBN:0321679199) and “Volume 3, Advanced Application Development” (ISBN:0321679202).


Share this Refcard with
your friends & followers...

DZone greatly appreciates your support.


Your download should begin immediately.
If it doesn't, click here.

DZone Daily Dose - WebKit Gains MathML Support

Writing mathematical formulas on web pages just got easier if your page is being read by a WebKit browser such as Chrome or Safari.  The WebKit developers are now releasing nightly builds that support the MathML XML language, which allows you to type in...

1 replies - 19664 views - 08/23/10 by Mitchell Pronsc... in Daily Dose

Daily Dose - Firefox 4 Getting Auto-Updates

Tucked away in a tiny corner of the Firefox discussion forum is a quote from Alex Faaborg, a principal designer on Firefox.  The posting says that Firefox 4 will begin to include automatic updates for minor releases.  Only major updates (e.g. 4, 4.5, or 5)...

0 replies - 17439 views - 08/09/10 by Mitchell Pronsc... in Daily Dose

Daily Dose - Check Out the EJB on That JBoss AS

The fourth JBoss Application Server 6.0 milestone was released this week.  It is the first to include support for EJB 3.1 Timer Service and EJB 3.1 Asynchronous invocations. M4 also comes with a different default JBossWS stack that uses Apache CXF.  With...

1 replies - 11848 views - 07/30/10 by Mitchell Pronsc... in Daily Dose

Daily Dose - PHP Language Update

The next version of PHP 5 has been released with over 100 bugfixes, some of which are security related.  PHP 5.3.3 may owe some of these bugfixes to the PHP Month of Security in May, which has been run by Stefan Esser for three years.  In PHP 5.3.3, methods...

0 replies - 10195 views - 07/23/10 by Mitchell Pronsc... in Daily Dose

Daily Dose - Can We Stop Talking About the iPhone Antenna Now?

In this week's edition of 'Media Frenzy Over Basically Nothing,' Apple finally called a press conference to end all the crazy talk about possible recalls and "Antennagate".  Apple CEO Steve Jobs threw up some stats during their presentation showing...

0 replies - 16985 views - 07/16/10 by Mitchell Pronsc... in Daily Dose

Daily Dose - iPhone 4 on Sale, Droid X Unveiled

Some big iPhone and Android news broke today - first, there was the iPhone 4 release, which may have reached record-breaking sales levels.  However, there were a few problems with the phone that users noticed today as they brought home their pretty new...

0 replies - 11728 views - 06/25/10 by Mitchell Pronsc... in Daily Dose

Daily Dose - GNOME 3.0: Which Modules Made the Cut?

Project release manager Vincent Untz posted a synopsis of the new modules that will be included in GNOME 3.0.  The GNOME Activity Journal didn't make the cut and neither did the Clutter GUI, but the GNOME Shell did.  So did the GNOME Color Manager and the...

0 replies - 11978 views - 06/10/10 by Mitchell Pronsc... in Daily Dose