summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorDave Reid2011-04-08 16:06:09 (GMT)
committer Dave Reid2011-04-08 16:06:09 (GMT)
commit15a6a95d15b6c6aa17f65889951b65e931ed6b49 (patch)
treeb2da3073732344855a0cf4e361d2b9c8a41cbd97
parentbfc0e2c2d045b7921f3d40cfc873de6e5978c080 (diff)
Removed files from master branch. Clone 7.x-1.x or create named branches from here on out.master
-rw-r--r--README.txt14
-rw-r--r--action_example/CHANGELOG.txt1
-rw-r--r--action_example/action_example.info6
-rw-r--r--action_example/action_example.module360
-rw-r--r--action_example/action_example.test83
-rw-r--r--ajax_example/ajax_example.css20
-rw-r--r--ajax_example/ajax_example.info5
-rw-r--r--ajax_example/ajax_example.js31
-rw-r--r--ajax_example/ajax_example.module549
-rw-r--r--ajax_example/ajax_example_advanced.inc388
-rw-r--r--ajax_example/ajax_example_graceful_degradation.inc640
-rw-r--r--ajax_example/ajax_example_misc.inc108
-rw-r--r--batch_example/batch_example.info6
-rw-r--r--batch_example/batch_example.install79
-rw-r--r--batch_example/batch_example.module264
-rw-r--r--batch_example/batch_example.test53
-rw-r--r--block_example/block_example.info6
-rw-r--r--block_example/block_example.install13
-rwxr-xr-xblock_example/block_example.module217
-rw-r--r--block_example/block_example.test92
-rw-r--r--dbtng_example/dbtng_example.info6
-rw-r--r--dbtng_example/dbtng_example.install115
-rw-r--r--dbtng_example/dbtng_example.module571
-rw-r--r--dbtng_example/dbtng_example.test181
-rwxr-xr-xemail_example/CHANGELOG.txt2
-rw-r--r--email_example/email_example.info6
-rw-r--r--email_example/email_example.module201
-rw-r--r--email_example/email_example.test98
-rw-r--r--examples.index.php31
-rw-r--r--field_example/field_example.css9
-rw-r--r--field_example/field_example.info6
-rw-r--r--field_example/field_example.install31
-rw-r--r--field_example/field_example.js26
-rw-r--r--field_example/field_example.module320
-rw-r--r--field_example/field_example.test144
-rw-r--r--file_example/file_example.info6
-rw-r--r--file_example/file_example.module522
-rw-r--r--file_example/file_example.test123
-rw-r--r--file_example/file_example_session_streams.inc678
-rwxr-xr-xfilter_example/filter_example.info6
-rwxr-xr-xfilter_example/filter_example.module176
-rw-r--r--filter_example/filter_example.test97
-rw-r--r--form_example/form_example.info6
-rw-r--r--form_example/form_example.module153
-rw-r--r--form_example/form_example.test176
-rw-r--r--form_example/form_example_states.inc266
-rw-r--r--form_example/form_example_tutorial.inc756
-rw-r--r--form_example/form_example_wizard.inc283
-rw-r--r--image_example/image_example.info8
-rw-r--r--image_example/image_example.install46
-rw-r--r--image_example/image_example.module372
-rw-r--r--image_example/image_example.pages.inc147
-rw-r--r--image_example/image_example.test103
-rw-r--r--js_example/accordion.tpl.php54
-rw-r--r--js_example/css/jsweights.css5
-rw-r--r--js_example/js/ajaxy.js6
-rw-r--r--js_example/js/black.js8
-rw-r--r--js_example/js/blue.js8
-rw-r--r--js_example/js/brown.js8
-rw-r--r--js_example/js/green.js8
-rw-r--r--js_example/js/purple.js8
-rw-r--r--js_example/js/red.js8
-rw-r--r--js_example/js_example.info5
-rwxr-xr-xjs_example/js_example.module67
-rw-r--r--menu_example/menu_example.info6
-rw-r--r--menu_example/menu_example.module467
-rw-r--r--menu_example/menu_example.test148
-rw-r--r--node_access_example/node_access_example.info6
-rw-r--r--node_access_example/node_access_example.install29
-rwxr-xr-xnode_access_example/node_access_example.module342
-rw-r--r--node_access_example/node_access_example.test196
-rwxr-xr-xnode_example/node_example.info7
-rwxr-xr-xnode_example/node_example.install217
-rwxr-xr-xnode_example/node_example.module167
-rw-r--r--node_example/node_example.test55
-rw-r--r--nodeapi_example/nodeapi_example.info6
-rw-r--r--nodeapi_example/nodeapi_example.install60
-rwxr-xr-xnodeapi_example/nodeapi_example.module283
-rw-r--r--nodeapi_example/nodeapi_example.test211
-rw-r--r--page_example/page_example.info6
-rwxr-xr-xpage_example/page_example.module167
-rw-r--r--page_example/page_example.test119
-rw-r--r--queue_example/queue_example.css4
-rw-r--r--queue_example/queue_example.info6
-rw-r--r--queue_example/queue_example.module275
-rw-r--r--queue_example/queue_example.test66
-rw-r--r--render_example/render_example.css21
-rw-r--r--render_example/render_example.info7
-rw-r--r--render_example/render_example.install16
-rw-r--r--render_example/render_example.module498
-rw-r--r--render_example/render_example.test138
-rw-r--r--simpletest_example/simpletest_example.info7
-rw-r--r--simpletest_example/simpletest_example.install29
-rw-r--r--simpletest_example/simpletest_example.module112
-rw-r--r--simpletest_example/simpletest_example.test79
-rw-r--r--token_example/token_example.info7
-rw-r--r--token_example/token_example.module195
-rw-r--r--token_example/token_example.test63
-rw-r--r--token_example/token_example.tokens.inc129
-rw-r--r--trigger_example/CHANGELOG.txt2
-rw-r--r--trigger_example/trigger_example.info7
-rw-r--r--trigger_example/trigger_example.module312
-rw-r--r--trigger_example/trigger_example.test78
-rw-r--r--vertical_tabs_example/vertical_tabs_example.info4
-rw-r--r--vertical_tabs_example/vertical_tabs_example.js24
-rw-r--r--vertical_tabs_example/vertical_tabs_example.module89
-rw-r--r--xmlrpc_example/xmlrpc_example.info6
-rw-r--r--xmlrpc_example/xmlrpc_example.module647
-rw-r--r--xmlrpc_example/xmlrpc_example.test128
109 files changed, 3 insertions, 14229 deletions
diff --git a/README.txt b/README.txt
index 358d8ca..56d3e5e 100644
--- a/README.txt
+++ b/README.txt
@@ -1,11 +1,3 @@
-
-Examples modules
-
-This set of modules is intended to show how to use various Drupal features.
-It's intended only for developers.
-
-If you find a problem, bad comment, poor usage, out-of-date API usage,
-etc., please post an issue in the issue queue at
-http://drupal.org/project/examples.
-
-
+The master branch of Examples is intentionally empty. Please clone a proper
+version branch like '7.x-1.x' or '6.x-1.x'. For instructions see the project's
+Git tab at http://drupal.org/node/594964/git-instructions.
diff --git a/action_example/CHANGELOG.txt b/action_example/CHANGELOG.txt
deleted file mode 100644
index 8b13789..0000000
--- a/action_example/CHANGELOG.txt
+++ /dev/null
@@ -1 +0,0 @@
-
diff --git a/action_example/action_example.info b/action_example/action_example.info
deleted file mode 100644
index a1fa237..0000000
--- a/action_example/action_example.info
+++ /dev/null
@@ -1,6 +0,0 @@
-name = Action example
-description = Demonstrates providing actions that can be associated to triggers.
-package = Example modules
-core = 7.x
-dependencies[] = trigger
-files[] = action_example.test
diff --git a/action_example/action_example.module b/action_example/action_example.module
deleted file mode 100644
index e802cc7..0000000
--- a/action_example/action_example.module
+++ /dev/null
@@ -1,360 +0,0 @@
-<?php
-
-/**
- * @file
- * Action definition example module.
- *
- * Triggers and actions are a matched pair of Drupal features allowing some
- * Drupal programming without using PHP. Using the appropriate action in a
- * specific event, a site administrator can add new functionality.
- * Examples are:
- * - Send an email after a node is published or edited.
- * - Display a message after a user has logged in.
- * - Display a message and send an email after a node has been deleted.
- *
- * A trigger is a special function which can enqueue actions. The trigger module
- * provides the interface allowing us to associate certain actions with certain
- * triggers.
- *
- * Actions are the functions designed to be run by triggers.
- *
- * A trigger should build the appropriate context for the action to be fired.
- * Actions are very often grouped by functionality: examples are 'user', 'node',
- * 'taxonomy'. When actions are grouped it is because they expect the same
- * arguments. This way, you can enqueue as many actions understanding the 'user'
- * object as you want.
- *
- * Not all actions can be used in all triggers because they require different
- * contexts. But some actions are generic enough that they do not require
- * special objects in their contexts, and so can be used on every available
- * trigger. This 'group' type is used by actions to be available for this
- * trigger.
- *
- * What are good candidates to be triggers? Any function can be a trigger, as
- * long as it has the code to call the enqueued actions, but to make Drupal
- * more extensible, you will find hooks (from Drupal and contributed modules)
- * very good candidates. A trigger should build the arguments, ask for enqueued
- * actions and run them. You may define a function being a trigger, and run it
- * through a button in the front page, or you may prepare a trigger for a hook,
- * and everytime that hook is fired, your trigger will be.
- *
- * What are good candidates to be actions? any function is a possible action,
- * the only problem is finding a trigger able to run it.
- *
- * This module describes how to create actions for Drupal. In this
- * example we are providing three actions:
- *
- * - A generic action that can be used in any trigger, which is the most
- * basic example of an action.
- *
- * - An action which which extends the capabilities of User triggers, even if
- * associated with node or comment events.
- *
- * - An action which extends the capabilities of node triggers, but limited
- * to certain events only, and using a customizable option.
- *
- * See:
- *
- * @todo this is a drupal 6 link
- * @link http://drupal.org/node/172152 Writing Actions @endlink
- *
- * @todo this is a drupal 6 link
- * @link http://drupal.org/node/199254 Triggers and Actions in Drupal 7 @endlink
- *
- * @see hook_action_info()
- * In addition, the @link trigger_example.module Trigger Example @endlink
- * provides detailed information on how to create a trigger.
- */
-
-/**
- * Implements hook_action_info().
- *
- * We call hook_action_info when we are defining the actions we provide.
- * Actions are the actions fired by the associated triggers. In this example,
- * we are registering our three new actions, providing the unique name (using
- * Drupal's convention modulename_description_action), an easy to understand
- * description of what the action does, the 'object' expected by this action
- * (default options from core are node, user, comment and system, however other
- * trigger modules may declare new object types), which are the triggers allowed
- * to use these action, and if some customization is available. Please, note
- * that the function name is not required to finish as _action to be declared as
- * a Drupal action, and that only information provided by hook_trigger_info()
- * will be considered for valid actions creation.
- *
- * These are the actions being provided in hook_action_info()
- *
- * - action_example_basic_action: this action is a dummy function which can be
- * used by any trigger. The label describes that the action will do nothing,
- * but is enough for a basic example. Type is set to system, so users will not
- * be confused about the scope of this action (expecting a node, user, or any
- * other object). This action is not configurable, and will appear as
- * available in the list of action under the menu entry:
- * 'admin/config/system/actions.
- * - action_example_unblock_user_action: Unblocks a user.
- * - action_example_node_sticky_action: This action is a complex action that is
- * only available to Node type triggers, and can only be associated with the
- * events node presave, node insert and node update. The action does not
- * exist by default and it has to be created by user configuration. This makes
- * it an "advanced action" in Drupal, so-called because it requires
- * configuration or customization.
- * In this example action, the action will promote nodes and make them sticky
- * during presave, insert, or update, but only for particular users. As an
- * advanced action, it first needs to be created in the actions management
- * page (admin/config/system/actions). At the bottom of that page a selection
- * list shows a list of advanced actions that will includes the option
- * 'Promote to frontpage and sticky on top any content created by :'
- * Selecting this option and clicking the 'Create' button, a configuration
- * form will ask for an author name. When this action is associated to any
- * of the possible Node trigger events, it will only be effective if the
- * author of the content matches the author configured by the action.
- *
- * @return
- * An associative array of action descriptions. The keys of the array
- * are the names of the action functions, and each corresponding value
- * is an associative array with the following key-value pairs:
- * - 'type': The type of object this action acts upon. Core actions have types
- * 'node', 'user', 'comment', and 'system', but additional types can be
- * used, as long as the trigger and action agree on them.
- * - 'label': The human-readable name of the action, which should be passed
- * through the t() function for translation.
- * - 'configurable': If FALSE, then the action doesn't require any extra
- * configuration. If TRUE, then your module must define a form function with
- * the same name as the action function with '_form' appended (e.g., the
- * form for 'node_assign_owner_action' is 'node_assign_owner_action_form'.)
- * This function takes $context as its only parameter, and is paired with
- * the usual _submit function, and possibly an _validate function.
- * - 'triggers': An array of the triggers that can trigger this
- * action. For example: array('node_insert', 'user_update'). You can also
- * declare support for any trigger by returning array('any') for this value.
- * - 'behavior': (optional) A machine-readable array of behaviors of this
- * action, used to signal additionally required actions that may need to be
- * triggered. Currently recognized behaviors by Trigger module:
- * - 'changes_property': If an action with this behavior is assigned to a
- * trigger other than a "presave" hook, any save actions also assigned to
- * this trigger are moved later in the list. If no save action is present,
- * one will be added.
- * Modules that are processing actions (like Trigger module) should take
- * special care in the "presave" hook, in which case a dependent "save"
- * action should NOT be invoked.
- *
- * See hook_action_info().
- */
-function action_example_action_info() {
- return array(
- 'action_example_basic_action' => array(
- 'label' => t('Action Example: A basic example action that does nothing'),
- 'type' => 'system',
- 'configurable' => FALSE,
- 'triggers' => array('any'),
- ),
- 'action_example_unblock_user_action' => array(
- 'label' => t('Action Example: Unblock a user'),
- 'type' => 'user',
- 'configurable' => FALSE,
- 'triggers' => array('any'),
- ),
- 'action_example_node_sticky_action' => array(
- 'type' => 'node',
- 'label' => t('Action Example: Promote to frontpage and sticky on top any content created by :'),
- 'configurable' => TRUE,
- 'behavior' => array('changes_property'),
- 'triggers' => array('node_presave', 'node_insert', 'node_update'),
- ),
- );
-}
-
-
-
-/**
- * Implements hook_menu().
- *
- * Simply provide a menu entry which explains what the module does.
- */
-function action_example_menu() {
- $items['examples/action_example'] = array(
- 'title' => 'Action Example',
- 'description' => 'Provides a basic information page.',
- 'page callback' => '_action_example_page',
- 'access callback' => TRUE,
- );
- return $items;
-}
-
-
-/**
- * A simple page to explain to the developer what to do.
- */
-function _action_example_page() {
- return t("The Action Example provides three example actions which can be configured on the <a href='@actions_url'>Actions configuration page</a> and assigned to triggers on the <a href='@triggers_url'>Triggers configuration page</a>.", array('@actions_url' => url('admin/config/system/actions'), '@triggers_url' => url('admin/structure/trigger/node')));
-}
-
-/*
- * Most basic action.
- *
- * This action is not expecting any type of entity object, and can be used with
- * any trigger type or any event.
- */
-
-/**
- * Basic example action.
- *
- * @param $entity
- * An optional entity object.
- * @param array $context
- * Array with parameters for this action: depends on the trigger.
- *
- * @ingroup actions
- */
-function action_example_basic_action(&$entity, $context = array()) {
- //
- // In this case we are ignoring the entity and the context. This case of
- // action is useful when your action does not depend on the context, and
- // the function must do something regardless the scope of the trigger.
- // Simply announces that the action was executed using a messages.
-
- drupal_set_message(t('action_example_basic_action fired'));
- watchdog('action_example', 'action_example_basic_action fired.');
-}
-
-// ---------------------------------------------------------------------------
-/*
- * A complex action for different trigger types.
- *
- * This action is expecting an entity object user, node or comment. If none of
- * the above is provided (because it was not called from an user/node/comment
- * trigger event, then the action will be taken on the current logged in user.
- *
- */
-
-/**
- * Unblock an user. This action can be fired from different trigger types:
- * - User trigger: this user will be unblocked.
- * - Node/Comment trigger: the author of the node or comment will be unblocked.
- * - Other: (including system or custom defined types), current user will be
- * unblocked. (Yes, this seems like an incomprehensible use-case.)
- *
- * @param $entity
- * An optional user object (could be a user, or an author if context is
- * node or comment)
- * @param array $context
- * Array with parameters for this action: depends on the trigger. The context
- * is not used in this example.
- *
- * @ingroup actions
- */
-function action_example_unblock_user_action(&$entity, $context = array()) {
-
- // First we check that entity is a user object. If this is the case, then this
- // is a user-type trigger.
- if (isset($entity->uid)) {
- $uid = $entity->uid;
- }
- elseif (isset($context['uid'])) {
- $uid = $context['uid'];
- }
- // If neither of those are valid, then block the current user.
- else {
- $uid = $GLOBALS['user']->uid;
- }
- $account = user_load($uid);
- $account = user_save($account, array('status' => 1));
- watchdog('action_example', 'Unblocked user %name.', array('%name' => $account->name));
- drupal_set_message(t('Unblocked user %name', array('%name' => $account->name)));
-}
-
-// ---------------------------------------------------------------------------
-/*
- * A complex action using customization.
- *
- * The next action requires a configuration form to create/configure the action.
- * In Drupal these are called 'advanced actions', because they must be
- * customized to define their functionality.
- *
- * The 'action_example_node_sticky_action' allows creating rules to promote and
- * set sticky content created by selected users on certain events. A form is
- * used to configure which user is affected by this action, and this form
- * includes the stanard _validate and _submit hooks.
- */
-
-
-/**
- * Generates settings form for action_example_node_sticky_action().
- *
- * @param array $context
- * An array of options of this action (in case it is being edited)
- * @return array $form
- *
- */
-function action_example_node_sticky_action_form($context) {
- /*
- * We return a configuration form to set the requirements that will
- * match this action before being executed. This is a regular Drupal form and
- * may include any type of information you want, but all the fields of the
- * form will be saved into the $context variable.
- *
- * In this case we are promoting all content types submited by this user, but
- * it is possible to extend these conditions providing more options in the
- * settings form.
- */
- $form['author'] = array(
- '#title' => t('Author name'),
- '#type' => 'textfield',
- '#description' => t('Any content created, presaved or updated by this user will be promoted to front page and set as sticky.'),
- '#default_value' => isset($context['author']) ? $context['author'] : '',
- );
- // Verify user permissions and provide an easier way to fill this field.
- if (user_access('access user profiles')) {
- $form['author']['#autocomplete_path'] = 'user/autocomplete';
- }
- // No more options, return the form.
- return $form;
-}
-
-/**
- * Validate settings form for action_example_node_sticky_action().
- * Verify that user exists before continuing.
- */
-function action_example_node_sticky_action_validate($form, $form_state) {
- if (! $account = user_load_by_name($form_state['values']['author']) ) {
- form_set_error('author', t('Please, provide a valid username'));
- }
-}
-
-/**
- * Submit handler for action_example_node_sticky_action.
- *
- * Returns an associative array of values which will be available in the
- * $context when an action is executed.
- */
-function action_example_node_sticky_action_submit($form, $form_state) {
- return array('author' => $form_state['values']['author']);
-}
-
-/**
- * Promote and set sticky flag action. This is the special action that has been
- * customized using the configuration form.
- *
- * @param $node
- * A node object provided by the associated trigger.
- * @param $context
- * Array with the following elements:
- * - 'author': username of the author's content this function will promote and
- * set as sticky.
- *
- * @ingroup actions
- */
-function action_example_node_sticky_action($node, $context) {
- if (function_exists('dsm')) {
- dsm($node, 'action_example_node_sticky_action is firing. Here is the $node');
- dsm($context, 'action_example_node_sticky_action is firing. Here is the $context');
- }
- // Get the user configured for this special action.
- $account = user_load_by_name($context['author']);
- // Is the node created by this user? then promote and set as sticky.
- if ($account->uid == $node->uid) {
- $node->promote = NODE_PROMOTED;
- $node->sticky = NODE_STICKY;
- watchdog('action', 'Set @type %title to sticky and promoted by special action for user %username.', array('@type' => node_type_get_name($node), '%title' => $node->title, '%username' => $account->name));
- drupal_set_message(t('Set @type %title to sticky and promoted by special action for user %username.', array('@type' => node_type_get_name($node), '%title' => $node->title, '%username' => $account->name)));
- }
-}
diff --git a/action_example/action_example.test b/action_example/action_example.test
deleted file mode 100644
index 875f003..0000000
--- a/action_example/action_example.test
+++ /dev/null
@@ -1,83 +0,0 @@
-<?php
-
-/**
- * @file
- * test file for action_example module.
- */
-
-/**
- * Default test case for the action_example module.
- */
-class ActionExampleTestCase extends TriggerWebTestCase {
-
- public static function getInfo() {
- return array(
- 'name' => 'Action example',
- 'description' => 'Perform various tests on action_example module.' ,
- 'group' => 'Examples',
- );
- }
-
- function setUp() {
- parent::setUp('trigger', 'action_example');
- }
-
- /**
- * Test Action Example.
- *
- * 1. action_example_basic_action: Configure a action_example_basic_action to
- * happen when user logs in.
- * 2. action_example_unblock_user_action: When a user's profile is being
- * viewed, unblock that user.
- * 3. action_example_node_sticky_action: Create a user, configure that user
- * to always be stickied using advanced configuration. Have the user
- * create content; verify that it gets stickied.
- */
- function testActionExample() {
- // Create an administrative user.
- $admin_user = $this->drupalCreateUser(array('administer actions', 'access comments', 'access content', 'post comments', 'skip comment approval', 'create article content', 'access user profiles', 'administer users'));
- $this->drupalLogin($admin_user);
-
- // 1. Assign basic action; then logout and login user and see if it puts
- // the message on the screen.
- $hash = drupal_hash_base64('action_example_basic_action');
- $edit = array('aid' => $hash);
- $this->drupalPost('admin/structure/trigger/user', $edit, t('Assign'), array(), array(), 'trigger-user-login-assign-form');
-
- $this->drupalLogout();
- $this->drupalLogin($admin_user);
- $this->assertText(t('action_example_basic_action fired'));
-
- // 2. Unblock: When a user's profile is being viewed, unblock.
- $normal_user = $this->drupalCreateUser();
- user_save($normal_user, array('status' => 0)); // Blocked user.
- $normal_user = user_load($normal_user->uid, TRUE);
- $this->assertFalse($normal_user->status, t('Normal user status has been set to blocked'));
-
- $hash = drupal_hash_base64('action_example_unblock_user_action');
- $edit = array('aid' => $hash);
- $this->drupalPost('admin/structure/trigger/user', $edit, t('Assign'), array(), array(), 'trigger-user-view-assign-form');
-
- $this->drupalGet("user/$normal_user->uid");
- $normal_user = user_load($normal_user->uid, TRUE);
- $this->assertTrue($normal_user->status, t('Normal user status has been set to unblocked'));
- $this->assertRaw(t('Unblocked user %name', array('%name' => $normal_user->name)));
-
- // 3. Create a user whose posts are always to be stickied.
- $sticky_user = $this->drupalCreateUser(array('access comments', 'access content', 'post comments', 'skip comment approval', 'create article content'));
-
- $action_label = $this->randomName();
- $edit = array(
- 'actions_label' => $action_label,
- 'author' => $sticky_user -> name,
- );
- $aid = $this->configureAdvancedAction('action_example_node_sticky_action', $edit);
- $edit = array('aid' => drupal_hash_base64($aid));
- $this->drupalPost('admin/structure/trigger/node', $edit, t('Assign'), array(), array(), 'trigger-node-insert-assign-form');
- // Now create a node and verify that it gets stickied.
- $this->drupalLogout();
- $this->drupalLogin($sticky_user);
- $node = $this->drupalCreateNode();
- $this->assertTrue($node->sticky, t('Node was set to sticky on creation'));
- }
-}
diff --git a/ajax_example/ajax_example.css b/ajax_example/ajax_example.css
deleted file mode 100644
index 5de6e70..0000000
--- a/ajax_example/ajax_example.css
+++ /dev/null
@@ -1,20 +0,0 @@
-
-/*
- * @file ajax_example.css
- * CSS for ajax_example.
- *
- * See @link ajax_example_dependent_dropdown_degrades @endlink for
- * details on what this file does. It is not used in any other example.
- */
-
-/* hide the next button when not degrading to non-javascript browser */
-html.js .next-button {
- display: none;
-}
-
-/* Make the next/choose button align to the right of the select control */
-.form-item-dropdown-first, .form-item-question-type-select {
- display: inline-block;
-}
-
-
diff --git a/ajax_example/ajax_example.info b/ajax_example/ajax_example.info
deleted file mode 100644
index 359fe94..0000000
--- a/ajax_example/ajax_example.info
+++ /dev/null
@@ -1,5 +0,0 @@
-
-name = AJAX Example
-description = An example module showing how to use Drupal AJAX forms
-core = 7.x
-package = Example modules
diff --git a/ajax_example/ajax_example.js b/ajax_example/ajax_example.js
deleted file mode 100644
index ce5b88a..0000000
--- a/ajax_example/ajax_example.js
+++ /dev/null
@@ -1,31 +0,0 @@
-
-/*
- * @file ajax_example.js
- * JavaScript for ajax_example.
- *
- * See @link ajax_example_dependent_dropdown_degrades @endlink for
- * details on what this file does. It is not used in any other example.
- *
- */
-
-(function($) {
-
- // Re-enable form elements that are disabled for non-ajax situations.
- Drupal.behaviors.enableFormItemsForAjaxForms = {
- attach: function() {
- // If ajax is enabled.
- if (Drupal.ajax) {
- $('.enabled-for-ajax').removeAttr('disabled');
- }
-
- // Below is only for the demo case of showing with js turned off.
- // It overrides the behavior of the CSS that would normally turn off
- // the 'ok' button when JS is enabled. Here, for demonstration purposes,
- // we have AJAX disabled but JS turned on, so use this to simulate.
- if (!Drupal.ajax) {
- $('html.js .next-button').show();
- }
- }
- };
-
-})(jQuery);
diff --git a/ajax_example/ajax_example.module b/ajax_example/ajax_example.module
deleted file mode 100644
index 0b29ad0..0000000
--- a/ajax_example/ajax_example.module
+++ /dev/null
@@ -1,549 +0,0 @@
-<?php
-
-/**
- * @file
- * AJAX Examples module file with basic examples.
- *
- */
-
-/**
- * @defgroup ajax_examples AJAX Examples
- * @{
- * These examples show basic AJAX concepts.
- *
- * General documentation is available at
- * @link ajax AJAX Framework documentation @endlink and at the
- * @link http://drupal.org/node/752056 AJAX Forms handbook page @endlink.
- *
- * The several examples here demonstrate basic AJAX usage.
- * @}
-*/
-
-/**
- * Set up calls to drupal_get_form() for all our example cases.
- *
- * Implements hook_menu().
- * See @link menu_example.module Menu Example @endlink for more details on
- * hook_menu().
- */
-function ajax_example_menu() {
- $items = array();
-
- $items['examples/ajax_example'] = array(
- 'title' => 'AJAX Example',
- 'page callback' => 'ajax_example_intro',
- 'access callback' => TRUE,
- 'expanded' => TRUE,
- );
-
- // Change the description of a form element.
- $items['examples/ajax_example/simplest'] = array(
- 'title' => 'Simplest AJAX Example',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array('ajax_example_simplest'),
- 'access callback' => TRUE,
- 'weight' => 0,
- );
- // Generate a changing number of checkboxes.
- $items['examples/ajax_example/autocheckboxes'] = array(
- 'title' => 'Generate checkboxes',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array('ajax_example_autocheckboxes'),
- 'access callback' => TRUE,
- 'weight' => 1,
- );
- // Generate different textfields based on form state.
- $items['examples/ajax_example/autotextfields'] = array(
- 'title' => 'Generate textfields',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array('ajax_example_autotextfields'),
- 'access callback' => TRUE,
- 'weight' => 2,
- );
-
- // Submit a form without a page reload.
- $items['examples/ajax_example/submit_driven_ajax'] = array(
- 'title' => 'Submit-driven AJAX',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array('ajax_example_submit_driven_ajax'),
- 'access callback' => TRUE,
- 'weight' => 3,
- );
-
- // Repopulate a dropdown based on form state.
- $items['examples/ajax_example/dependent_dropdown'] = array(
- 'title' => 'Dependent dropdown',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array('ajax_example_dependent_dropdown'),
- 'access callback' => TRUE,
- 'weight' => 4,
- );
- // Repopulate a dropdown, but this time with graceful degredation.
- // See ajax_example_graceful_degradation.inc.
- $items['examples/ajax_example/dependent_dropdown_degrades'] = array(
- 'title' => 'Dependent dropdown (with graceful degradation)',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array('ajax_example_dependent_dropdown_degrades'),
- 'access callback' => TRUE,
- 'weight' => 5,
- 'file' => 'ajax_example_graceful_degradation.inc',
- );
- // The above example as it appears to users with no javascript.
- $items['examples/ajax_example/dependent_dropdown_degrades_no_js'] = array(
- 'title' => 'Dependent dropdown with javascript off',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array('ajax_example_dependent_dropdown_degrades', TRUE),
- 'access callback' => TRUE,
- 'file' => 'ajax_example_graceful_degradation.inc',
- 'weight' => 5,
- );
-
- // Populate a form section based on input in another element.
- $items['examples/ajax_example/dynamic_sections'] = array(
- 'title' => 'Dynamic Sections (with graceful degradation)',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array('ajax_example_dynamic_sections'),
- 'access callback' => TRUE,
- 'weight' => 6,
- 'file' => 'ajax_example_graceful_degradation.inc',
- );
- // The above example as it appears to users with no javascript.
- $items['ajax_example/dynamic_sections_no_js'] = array(
- 'title' => 'Dynamic Sections w/JS turned off',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array('ajax_example_dynamic_sections', TRUE),
- 'access callback' => TRUE,
- 'weight' => 6,
- 'file' => 'ajax_example_graceful_degradation.inc',
- );
-
- // A classic multi-step wizard, but with no page reloads.
- // See ajax_example_graceful_degradation.inc.
- $items['examples/ajax_example/wizard'] = array(
- 'title' => 'Wizard (with graceful degradation)',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array('ajax_example_wizard'),
- 'access callback' => TRUE,
- 'file' => 'ajax_example_graceful_degradation.inc',
- 'weight' => 7,
- );
- // The above example as it appears to users with no javascript.
- $items['examples/ajax_example/wizard_no_js'] = array(
- 'title' => 'Wizard w/JS turned off',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array('ajax_example_wizard', TRUE),
- 'access callback' => TRUE,
- 'file' => 'ajax_example_graceful_degradation.inc',
- 'weight' => 7,
- );
-
- // Add-more button that creates additional form elements.
- // See ajax_example_graceful_degradation.inc.
- $items['examples/ajax_example/add_more'] = array(
- 'title' => 'Add-more button (with graceful degradation)',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array('ajax_example_add_more'),
- 'access callback' => TRUE,
- 'file' => 'ajax_example_graceful_degradation.inc',
- 'weight' => 8,
- );
- // The above example as it appears to users with no javascript.
- $items['examples/ajax_example/add_more_no_js'] = array(
- 'title' => 'Add-more button w/JS turned off',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array('ajax_example_add_more', TRUE),
- 'access callback' => TRUE,
- 'file' => 'ajax_example_graceful_degradation.inc',
- 'weight' => 8,
- );
-
- // Use the AJAX framework outside the context of a form using the use-ajax
- // class. See ajax_example_misc.inc.
- $items['examples/ajax_example/ajax_link'] = array(
- 'title' => 'Ajax Link ("use-ajax" class)',
- 'page callback' => 'ajax_example_render_link',
- 'access callback' => TRUE,
- 'file' => 'ajax_example_misc.inc',
- 'weight' => 9,
- );
- // Use the AJAX framework outside the context of a form using a renderable
- // array of type link with the #ajax property. See ajax_example_misc.inc.
- $items['examples/ajax_example/ajax_link_renderable'] = array(
- 'title' => 'Ajax Link (Renderable Array)',
- 'page callback' => 'ajax_example_render_link_ra',
- 'access callback' => TRUE,
- 'file' => 'ajax_example_misc.inc',
- 'weight' => 9,
- );
- // A menu callback is required when using ajax outside of the Form API.
- $items['ajax_link_callback'] = array(
- 'page callback' => 'ajax_link_response',
- 'access callback' => 'user_access',
- 'access arguments' => array('access content'),
- 'type' => MENU_CALLBACK,
- 'file' => 'ajax_example_misc.inc',
- );
-
- // Use AJAX framework commands outside of the #ajax form property.
- // See ajax_example_advanced.inc.
- $items['examples/ajax_example/advanced_commands'] = array(
- 'title' => 'AJAX framework commands',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array('ajax_example_advanced_commands'),
- 'access callback' => TRUE,
- 'file' => 'ajax_example_advanced.inc',
- 'weight' => 10,
- );
-
- return $items;
-}
-
-function ajax_example_intro() {
- $markup = t('The AJAX example module provides many examples of AJAX including forms, links, and AJAX commands.');
- return $markup;
-}
-
-/**
- * @ingroup ajax_examples
- * @{
- */
-
-/**
- * Simple form whose ajax-enabled 'changethis' member causes a text change
- * in the description of the 'replace_textfield' member.
- * See @link http://drupal.org/node/262422 Form API Tutorial @endlink
- */
-function ajax_example_simplest($form, &$form_state) {
- $form = array();
- $form['changethis'] = array(
- '#title' => t("Choose something and explain why"),
- '#type' => 'select',
- '#options' => array(
- 'one' => 'one',
- 'two' => 'two',
- 'three' => 'three',
- ),
- '#ajax' => array(
- // #ajax has two required keys: callback and wrapper.
- // 'callback' is a function that will be called when this element changes.
- 'callback' => 'ajax_example_simplest_callback',
- // 'wrapper' is the HTML id of the page element that will be replaced.
- 'wrapper' => 'replace_textfield_div',
- // There are also several optional keys - see ajax_example_autocheckboxes
- // below for details on 'method', 'effect' and 'speed' and
- // ajax_example_dependent_dropdown for 'event'.
- ),
- );
-
- // This entire form element will be replaced whenever 'changethis' is updated.
- $form['replace_textfield'] = array(
- '#type' => 'textfield',
- '#title' => t("Why"),
- // The prefix/suffix provide the div that we're replacing, named by
- // #ajax['wrapper'] above.
- '#prefix' => '<div id="replace_textfield_div">',
- '#suffix' => '</div>',
- );
-
- // An AJAX request calls the form builder function for every change.
- // We can change how we build the form based on $form_state.
- if (!empty($form_state['values']['changethis'])) {
- $form['replace_textfield']['#description'] = t("Say why you chose") . " '{$form_state['values']['changethis']}'";
- }
- return $form;
-}
-
-/**
- * Callback for ajax_example_simplest.
- *
- * On an ajax submit, the form builder function is called again, then the $form
- * and $form_state are passed to this callback function so it can select which
- * portion of the form to send on to the client.
- *
- * @return renderable array (the textfield element)
- */
-function ajax_example_simplest_callback($form, $form_state) {
- // The form has already been submitted and updated. We can return the replaced
- // item as it is.
- return $form['replace_textfield'];
-}
-
-/**
- * AJAX-enabled select element causes replacement of a set of checkboxes
- * based on the selection.
- */
-function ajax_example_autocheckboxes($form, &$form_state) {
- // Since the form builder is called after every AJAX request, we rebuild
- // the form based on $form_state.
- $num_checkboxes = !empty($form_state['values']['howmany_select']) ? $form_state['values']['howmany_select'] : 1;
-
- $form['howmany_select'] = array(
- '#title' => t('How many checkboxes do you want?'),
- '#type' => 'select',
- '#options' => array(1 => 1, 2 => 2, 3 => 3, 4 => 4),
- '#default_value' => $num_checkboxes,
- '#ajax' => array(
- 'callback' => 'ajax_example_autocheckboxes_callback',
- 'wrapper' => 'checkboxes-div',
- //'method' defaults to replaceWith, but valid values also include
- // append, prepend, before and after.
- // 'method' => 'replaceWith',
- // 'effect' defaults to none. Other valid values are 'fade' and 'slide'.
- // See ajax_example_autotextfields for an example of 'fade'.
- 'effect' => 'slide',
- // 'speed' defaults to 'slow'. You can also use 'fast'
- // or a number of milliseconds for the animation to last.
- // 'speed' => 'slow',
- // Don't show any throbber...
- 'progress' => array('type' => 'none'),
- ),
- );
-
-
- $form['checkboxes_fieldset'] = array(
- '#title' => t("Generated Checkboxes"),
- // The prefix/suffix provide the div that we're replacing, named by
- // #ajax['wrapper'] above.
- '#prefix' => '<div id="checkboxes-div">',
- '#suffix' => '</div>',
- '#type' => 'fieldset',
- '#description' => t('This is where we get automatically generated checkboxes'),
- );
-
- for ($i = 1; $i <= $num_checkboxes; $i++) {
- $form['checkboxes_fieldset']["checkbox$i"] = array(
- '#type' => 'checkbox',
- '#title' => "Checkbox $i",
- );
- }
-
- $form['submit'] = array(
- '#type' => 'submit',
- '#value' => t('Submit'),
- );
-
- return $form;
-}
-
-/**
- * Callback element needs only select the portion of the form to be updated.
- * Since #ajax['callback'] return can be HTML or a renderable array (or an
- * array of commands), we can just return a piece of the form.
- * See @link ajax_example_advanced.inc AJAX Advanced Commands for more details
- * on AJAX framework commands.
- *
- * @return renderable array (the checkboxes fieldset)
- */
-function ajax_example_autocheckboxes_callback($form, $form_state) {
- return $form['checkboxes_fieldset'];
-}
-
-
-/**
- * Show/hide textfields based on AJAX-enabled checkbox clicks.
- */
-function ajax_example_autotextfields($form, &$form_state) {
-
- $form['ask_first_name'] = array(
- '#type' => 'checkbox',
- '#title' => t('Ask me my first name'),
- '#ajax' => array(
- 'callback' => 'ajax_example_autotextfields_callback',
- 'wrapper' => 'textfields',
- 'effect' => 'fade',
- )
- );
- $form['ask_last_name'] = array(
- '#type' => 'checkbox',
- '#title' => t('Ask me my last name'),
- '#ajax' => array(
- 'callback' => 'ajax_example_autotextfields_callback',
- 'wrapper' => 'textfields',
- 'effect' => 'fade',
- ),
- );
-
- $form['textfields'] = array(
- '#title' => t("Generated text fields for first and last name"),
- '#prefix' => '<div id="textfields">',
- '#suffix' => '</div>',
- '#type' => 'fieldset',
- '#description' => t('This is where we put automatically generated textfields'),
- );
-
- // Since checkboxes return TRUE or FALSE, we have to check that
- // $form_state has been filled as well as what it contains.
- if (!empty($form_state['values']['ask_first_name']) && $form_state['values']['ask_first_name']) {
- $form['textfields']['first_name'] = array(
- '#type' => 'textfield',
- '#title' => t('First Name'),
- );
- }
- if (!empty($form_state['values']['ask_last_name']) && $form_state['values']['ask_last_name']) {
- $form['textfields']['last_name'] = array(
- '#type' => 'textfield',
- '#title' => t('Last Name'),
- );
- }
-
- $form['submit'] = array(
- '#type' => 'submit',
- '#value' => t('Click Me'),
- );
-
- return $form;
-}
-
-/**
- * Selects the piece of the form we want to use as replacement text and returns
- * it as a form (renderable array).
- *
- * @return renderable array (the textfields element)
- */
-function ajax_example_autotextfields_callback($form, $form_state) {
- return $form['textfields'];
-}
-
-
-/**
- * A very basic form which with an AJAX-enabled submit.
- *
- * On submit, the markup in the #markup element is updated.
- */
-function ajax_example_submit_driven_ajax($form, &$form_state) {
- $form['box'] = array(
- '#type' => 'markup',
- '#prefix' => '<div id="box">',
- '#suffix' => '</div>',
- '#markup' => '<h1>Initial markup for box</h1>',
- );
-
- $form['submit'] = array(
- '#type' => 'submit',
- '#ajax' => array(
- 'callback' => 'ajax_example_submit_driven_callback',
- 'wrapper' => 'box',
- 'name' => 'submit1',
- ),
- '#value' => t('Submit'),
- );
-
- return $form;
-}
-
-/**
- * Select the 'box' element, change the markup in it, and return it as a
- * renderable array.
- *
- * @return renderable array (the box element)
- */
-function ajax_example_submit_driven_callback($form, $form_state) {
- // In most cases, it is recomended that you put this logic in form generation
- // rather than the callback. Submit driven forms are an exception, because
- // you may not want to return the form at all.
- $element = $form['box'];
- $element['#markup'] = "Clicked submit ({$form_state['values']['op']}): " . date('c');
- return $element;
-}
-
-
-/**
- * A form with a dropdown whose options are dependent on a
- * choice made in a previous dropdown.
- *
- * On changing the first dropdown, the options in the second
- * are updated.
- */
-function ajax_example_dependent_dropdown($form, &$form_state) {
- // Get the list of options to populate the first dropdown.
- $options_first = _ajax_example_get_first_dropdown_options();
- // If we have a value for the first dropdown from $form_state['values'] we use
- // this both as the default value for the first dropdown and also as a
- // parameter to pass to the function that retrieves the options for the
- // second dropdown.
- $selected = isset($form_state['values']['dropdown_first']) ? $form_state['values']['dropdown_first'] : key($options_first);
-
- $form['dropdown_first'] = array(
- '#type' => 'select',
- '#title' => 'Instrument Type',
- '#options' => $options_first,
- '#default_value' => $selected,
- // Bind an ajax callback to the change event (which is the default for the
- // select form type) of the first dropdown. It will replace the second
- // dropdown when rebuilt
- '#ajax' => array(
- // When 'event' occurs, Drupal will perform an ajax request in the
- // background. Usually the default value is sufficient (eg. change for
- // select elements), but valid values include any jQuery event,
- // most notably 'mousedown', 'blur', and 'submit'.
- // 'event' => 'change',
- 'callback' => 'ajax_example_dependent_dropdown_callback',
- 'wrapper' => 'dropdown-second-replace',
- ),
- );
-
- $form['dropdown_second'] = array(
- '#type' => 'select',
- '#title' => $options_first[$selected] . ' ' . t('Instruments'),
- // The entire enclosing div created here gets replaced when dropdown_first
- // is changed.
- '#prefix' => '<div id="dropdown-second-replace">',
- '#suffix' => '</div>',
- // when the form is rebuilt during ajax processing, the $selected variable
- // will now have the new value and so the options will change
- '#options' => _ajax_example_get_second_dropdown_options($selected),
- '#default_value' => isset($form_state['values']['dropdown_second']) ? $form_state['values']['dropdown_second'] : '',
- );
- $form['submit'] = array(
- '#type' => 'submit',
- '#value' => t('Submit'),
- );
- return $form;
-}
-
-/**
- * Selects just the second dropdown to be returned for re-rendering
- *
- * Since the controlling logic for populating the form is in the form builder
- * function, all we do here is select the element and return it to be updated.
- *
- * @return renderable array (the second dropdown)
- */
-function ajax_example_dependent_dropdown_callback($form, $form_state) {
- return $form['dropdown_second'];
-}
-
-/**
- * Helper function to populate the first dropdown. This would normally be
- * pulling data from the database.
- *
- * @return array of options
- */
-function _ajax_example_get_first_dropdown_options() {
- // drupal_map_assoc() just makes an array('String' => 'String'...).
- return drupal_map_assoc(array(t('String'), t('Woodwind'), t('Brass'), t('Percussion')));
-}
-
-/**
- * Helper function to populate the second dropdown. This would normally be
- * pulling data from the database.
- *
- * @param key. This will determine which set of options is returned.
- *
- * @return array of options
- */
-function _ajax_example_get_second_dropdown_options($key = '') {
- $options = array(
- t('String') => drupal_map_assoc(array(t('Violin'), t('Viola'), t('Cello'), t('Double Bass'))),
- t('Woodwind') => drupal_map_assoc(array(t('Flute'), t('Clarinet'), t('Oboe'), t('Bassoon'))),
- t('Brass') => drupal_map_assoc(array(t('Trumpet'), t('Trombone'), t('French Horn'), t('Euphonium'))),
- t('Percussion') => drupal_map_assoc(array(t('Bass Drum'), t('Timpani'), t('Snare Drum'), t('Tambourine'))),
- );
- if (isset($options[$key])) {
- return $options[$key];
- }
- else {
- return array();
- }
-}
-
diff --git a/ajax_example/ajax_example_advanced.inc b/ajax_example/ajax_example_advanced.inc
deleted file mode 100644
index 8b12c71..0000000
--- a/ajax_example/ajax_example_advanced.inc
+++ /dev/null
@@ -1,388 +0,0 @@
-<?php
-
-/**
- * @file
- * AJAX Commands examples.
- *
- * This demonstrates each of the
- * new AJAX commands. This is consolidated into a dense page because
- * it's advanced material and because it would spread itself all over creation
- * otherwise.
- *
-*/
-
-/**
- * Form to display the AJAX Commands.
- */
-function ajax_example_advanced_commands($form, &$form_state) {
- $form = array();
- $form['intro'] = array(
- '#type' => 'markup',
- '#markup' => t("<div>Demonstrates how AJAX commands can be used.</div>"),
- );
-
- // Shows the 'after' command with a callback generating commands.
- $form['after_command_example_fieldset'] = array(
- '#type' => 'fieldset',
- '#title' => t("This shows the Ajax 'after' command. Click to put something below the div that says 'Something can be inserted after this'")
- );
-
- $form['after_command_example_fieldset']['after_command_example'] = array(
- '#value' => t("AJAX 'After': Click to put something after the div"),
- '#type' => 'submit',
- '#ajax' => array(
- 'callback' => 'ajax_example_advanced_commands_after_callback',
- ),
- '#suffix' => "<div id='after_div'>Something can be inserted after this</div>
- <div id='after_status'>'After' Command Status: Unknown</div>",
- );
-
- // Shows the 'alert' command.
- $form['alert_command_example_fieldset'] = array(
- '#type' => 'fieldset',
- '#title' => t("Demonstrates the AJAX 'alert' command. Click the button."),
- );
- $form['alert_command_example_fieldset']['alert_command_example'] = array(
- '#value' => t("AJAX 'Alert': Click to alert"),
- '#type' => 'submit',
- '#ajax' => array(
- 'callback' => 'ajax_example_advanced_commands_alert_callback',
- ),
- );
-
- // Shows the 'append' command.
- $form['append_command_example_fieldset'] = array(
- '#type' => 'fieldset',
- '#title' => t("This shows the Ajax 'append' command. Click to put something below the div that says 'Something can be inserted after this'")
- );
-
- $form['append_command_example_fieldset']['append_command_example'] = array(
- '#value' => t("AJAX 'Append': Click to append something"),
- '#type' => 'submit',
- '#ajax' => array(
- 'callback' => 'ajax_example_advanced_commands_append_callback',
- ),
- '#suffix' => "<div id='append_div'>Something can be appended inside this div... </div>
- <div id='append_status'>'After' Command Status: Unknown</div>"
- );
-
-
- // Shows the 'before' command.
- $form['before_command_example_fieldset'] = array(
- '#type' => 'fieldset',
- '#title' => t("This shows the Ajax 'before' command.")
- );
-
- $form['before_command_example_fieldset']['before_command_example'] = array(
- '#value' => t("AJAX 'before': Click to put something before the div"),
- '#type' => 'submit',
- '#ajax' => array(
- 'callback' => 'ajax_example_advanced_commands_before_callback',
- ),
- '#suffix' => "<div id='before_div'>Something can be inserted before this</div>
- <div id='before_status'>'before' Command Status: Unknown</div>"
- );
-
- // Shows the 'changed' command.
- $form['changed_command_example_fieldset'] = array(
- '#type' => 'fieldset',
- '#title' => t("Demonstrates the AJAX 'changed' command. If region is 'changed', it is marked with CSS. This example also puts an asterisk by changed content."),
- );
-
- $form['changed_command_example_fieldset']['changed_command_example'] = array(
- '#title' => t("AJAX changed: If checked, div is marked as changed."),
- '#type' => 'checkbox',
- '#default_value' => FALSE,
- '#ajax' => array(
- 'callback' => 'ajax_example_advanced_commands_changed_callback',
- ),
- '#suffix' => "<div id='changed_div'> <div id='changed_div_mark_this'>This div can be marked as changed or not.</div></div>
- <div id='changed_status'>Status: Unknown</div>"
- );
-
- // Shows the AJAX 'css' command.
- $form['css_command_example_fieldset'] = array(
- '#type' => 'fieldset',
- '#title' => t("Demonstrates the AJAX 'css' command."),
- );
-
- $form['css_command_example_fieldset']['css_command_example'] = array(
- '#title' => t("AJAX CSS: Choose the color you'd like the '#box' div to be."),
- '#type' => 'select',
- // '#default_value' => 'green',
- '#options' => array('green' => 'green', 'blue' => 'blue'),
- '#ajax' => array(
- 'callback' => 'ajax_example_advanced_commands_css_callback',
- ),
- '#suffix' => "<div id='css_div' style='height: 50px; width: 50px; border: 1px solid black'> box</div>
- <div id='css_status'>Status: Unknown</div>"
- );
-
- // Shows the AJAX 'data' command. But there is no use of this information,
- // as this would require a javascript client to use the data.
- $form['data_command_example_fieldset'] = array(
- '#type' => 'fieldset',
- '#title' => t("Demonstrates the AJAX 'data' command."),
- );
-
- $form['data_command_example_fieldset']['data_command_example'] = array(
- '#title' => t("AJAX data: Set a key/value pair on a selector."),
- '#type' => 'textfield',
- '#default_value' => 'color=green',
- '#ajax' => array(
- 'callback' => 'ajax_example_advanced_commands_data_callback',
- ),
- '#suffix' => "<div id='data_div'>This div should have key='time'/value='a time string' attached.</div>
- <div id='data_status'>Status: Unknown</div>"
- );
-
- // Shows the AJAX 'html' command.
- $form['html_command_example_fieldset'] = array(
- '#type' => 'fieldset',
- '#title' => t("Demonstrates the AJAX 'html' command."),
- );
-
- $form['html_command_example_fieldset']['html_command_example'] = array(
- '#title' => t("AJAX html: Replace the HTML in a selector."),
- '#type' => 'textfield',
- '#default_value' => 'new value',
- '#ajax' => array(
- 'callback' => 'ajax_example_advanced_commands_html_callback',
- ),
- '#suffix' => "<div id='html_div'>Original contents</div>
- <div id='html_status'>Status: Unknown</div>"
- );
-
- // Shows the AJAX 'prepend' command.
- $form['prepend_command_example_fieldset'] = array(
- '#type' => 'fieldset',
- '#title' => t("This shows the AJAX 'prepend' command. Click to put something below the div that says 'Something can be inserted after this'")
- );
-
- $form['prepend_command_example_fieldset']['prepend_command_example'] = array(
- '#value' => t("AJAX 'prepend': Click to prepend something"),
- '#type' => 'submit',
- '#ajax' => array(
- 'callback' => 'ajax_example_advanced_commands_prepend_callback',
- ),
- '#suffix' => "<div id='prepend_div'>Something can be prepended to this div... </div>
- <div id='prepend_status'>'After' Command Status: Unknown</div>"
- );
-
- // Shows the AJAX 'remove' command.
- $form['remove_command_example_fieldset'] = array(
- '#type' => 'fieldset',
- '#title' => t("Shows the Ajax 'remove' command.")
- );
-
- $form['remove_command_example_fieldset']['remove_command_example'] = array(
- '#title' => t("AJAX 'remove': Check to remove text. Uncheck to add it back."),
- '#type' => 'checkbox',
- '#default_value' => FALSE,
- '#ajax' => array(
- 'callback' => 'ajax_example_advanced_commands_remove_callback',
- ),
- '#suffix' => "<div id='remove_div'><div id='remove_text'>text to be removed</div></div>
- <div id='remove_status'>'After' Command Status: Unknown</div>"
- );
-
- // Show off the AJAX 'restripe' command. Also shows classic AJAX replacement
- // on the "how many rows" processing.
- $form['restripe_command_example_fieldset'] = array(
- '#type' => 'fieldset',
- '#title' => t("Demonstrates the Ajax 'restripe' command.")
- );
-
- $form['restripe_command_example_fieldset']['restripe_num_rows'] = array(
- '#type' => 'select',
- '#default_value' => !empty($form_state['values']['restripe_num_rows']) ? $form_state['values']['restripe_num_rows'] : 1,
- '#options' => drupal_map_assoc(array(1,2,3,4,5,6,7,8,9,10)),
- '#ajax' => array(
- 'callback' => 'ajax_example_advanced_commands_restripe_num_rows',
- 'method' => 'replace',
- 'wrapper' => 'restripe_table',
- ),
- );
- $form['restripe_command_example_fieldset']['restripe_restripe'] = array(
- '#type' => 'submit',
- '#value' => t("Restripe the table"),
- '#ajax' => array(
- 'callback' => 'ajax_example_advanced_commands_restripe_callback',
- ),
- '#suffix' => "<div id='restripe_div'>
- <table id='restripe_table' style='border: 1px solid black' >
- <tr id='table-first'><td>first row</td></tr>
- </table>
- </div>
- <div id='restripe_status'>'Restripe' Command Status: Unknown</div>",
-
- );
-
- $form['submit'] = array(
- '#type' => 'submit',
- '#value' => t('Submit'),
- );
-
- return $form;
-}
-
-/**
- * 'after' callback.
- * @see ajax_command_after()
- */
-function ajax_example_advanced_commands_after_callback($form, $form_state) {
- $selector = '#after_div';
-
- $commands = array();
- $commands[] = ajax_command_after($selector, "New 'after'...");
- $commands[] = ajax_command_replace("#after_status", "<div id='after_status'>Updated after_command_example " . date('r') . "</div>");
- return array('#type' => 'ajax', '#commands' => $commands);
-}
-
-/**
- * 'alert' callback.
- * @see ajax_command_alert()
- */
-function ajax_example_advanced_commands_alert_callback($form, $form_state) {
- $commands = array();
- $commands[] = ajax_command_alert("Alert requested at " . date('r'));
- return array('#type' => 'ajax', '#commands' => $commands);
-}
-
-/**
- * 'append' callback.
- * @see ajax_command_append()
- */
-function ajax_example_advanced_commands_append_callback($form, $form_state) {
- $selector = '#append_div';
-
- $commands = array();
- $commands[] = ajax_command_append($selector, "Stuff...");
- $commands[] = ajax_command_replace("#append_status", "<div id='append_status'>Updated append_command_example " . date('r') . "</div>");
- return array('#type' => 'ajax', '#commands' => $commands);
-}
-
-/**
- * 'before' callback.
- * @see ajax_command_before()
- */
-function ajax_example_advanced_commands_before_callback($form, $form_state) {
- $selector = '#before_div';
-
- $commands = array();
- $commands[] = ajax_command_before($selector, "New 'before'...");
- $commands[] = ajax_command_replace("#before_status", "<div id='before_status'>Updated before_command_example " . date('r') . "</div>");
- return array('#type' => 'ajax', '#commands' => $commands);
-}
-
-/**
- * 'changed' callback.
- * @see ajax_command_changed()
- */
-function ajax_example_advanced_commands_changed_callback($form, $form_state) {
- $checkbox_value = $form_state['values']['changed_command_example'];
- $checkbox_value_string = $checkbox_value ? "TRUE" : "FALSE";
- $commands = array();
- if ($checkbox_value) {
- $commands[] = ajax_command_changed( '#changed_div', '#changed_div_mark_this');
- } else {
- $commands[] = ajax_command_replace('#changed_div', "<div id='changed_div'> <div id='changed_div_mark_this'>This div can be marked as changed or not.</div></div>");
- }
- $commands[] = ajax_command_replace("#changed_status", "<div id='changed_status'>Updated changed_command_example to $checkbox_value_string: " . date('r') . "</div>");
- return array('#type' => 'ajax', '#commands' => $commands);
-}
-
-/**
- * 'css' callback.
- * @see ajax_command_css()
- */
-function ajax_example_advanced_commands_css_callback($form, $form_state) {
- $selector = '#css_div';
- $color = $form_state['values']['css_command_example'];
-
- $commands = array();
- $commands[] = ajax_command_css($selector, array('background-color' => $color));
- $commands[] = ajax_command_replace("#css_status", "<div id='css_status'>Updated css_command_example to '{$color}' " . date('r') . "</div>");
- return array('#type' => 'ajax', '#commands' => $commands);
-}
-
-/**
- * 'data' callback.
- * @see ajax_command_data()
- */
-function ajax_example_advanced_commands_data_callback($form, $form_state) {
- $selector = '#data_div';
- $text = $form_state['values']['data_command_example'];
- list($key, $value) = preg_split('/=/', $text);
-
- $commands = array();
- $commands[] = ajax_command_data($selector, $key, $value);
- $commands[] = ajax_command_replace("#data_status", "<div id='data_status'>Updated data_command_example with key=$key, value=$value; " . date('r') . "</div>");
- return array('#type' => 'ajax', '#commands' => $commands);
-}
-
-/**
- * 'html' callback.
- * @see ajax_command_html()
- */
-function ajax_example_advanced_commands_html_callback($form, $form_state) {
- $text = $form_state['values']['html_command_example'];
-
- $commands = array();
- $commands[] = ajax_command_html('#html_div', $text);
- $commands[] = ajax_command_replace("#html_status", "<div id='html_status'>Updated html_command_example with text=$text; " . date('r') . "</div>");
- return array('#type' => 'ajax', '#commands' => $commands);
-}
-
-/**
- * 'prepend' callback.
- * @see ajax_command_prepend()
- */
-function ajax_example_advanced_commands_prepend_callback($form, $form_state) {
- $commands = array();
- $commands[] = ajax_command_prepend('#prepend_div', "Prepended Stuff...");
- $commands[] = ajax_command_replace("#prepend_status", "<div id='prepend_status'>Updated prepend_command_example " . date('r') . "</div>");
- return array('#type' => 'ajax', '#commands' => $commands);
-}
-
-/**
- * 'remove' callback.
- * @see ajax_command_remove()
- */
-function ajax_example_advanced_commands_remove_callback($form, $form_state) {
- $commands = array();
- $should_remove = $form_state['values']['remove_command_example'];
- $should_remove_string = $should_remove ? 'TRUE' : 'FALSE';
- if ($should_remove) {
- $commands[] = ajax_command_remove('#remove_text');
- } else {
- $commands[] = ajax_command_html('#remove_div', "<div id='remove_text'>text to be removed</div>");
- }
- $commands[] = ajax_command_replace("#remove_status", "<div id='remove_status'>Updated remove_command_example (value={$should_remove_string} " . date('r') . "</div>");
- return array('#type' => 'ajax', '#commands' => $commands);
-}
-
-/**
- * 'restripe' rows callback.
- * Rebuilds the table with the selected number of rows.
- */
-function ajax_example_advanced_commands_restripe_num_rows($form, $form_state) {
- $num_rows = $form_state['values']['restripe_num_rows'];
- $output = "<table id='restripe_table' style='border: 1px solid black'>";
- for ($i=1; $i<=$num_rows; $i++) {
- $output .= "<tr><td>Row $i</td></tr>";
- }
- $output .= "</table>";
- return $output;
-}
-
-/**
- * 'restripe' callback.
- * @see ajax_command_restripe()
- */
-function ajax_example_advanced_commands_restripe_callback($form, $form_state) {
- $commands = array();
- $commands[] = ajax_command_restripe('#restripe_table');
- $commands[] = ajax_command_replace("#restripe_status", "<div id='restripe_status'>Restriped table " . date('r') . "</div>");
- return array('#type' => 'ajax', '#commands' => $commands);
-}
diff --git a/ajax_example/ajax_example_graceful_degradation.inc b/ajax_example/ajax_example_graceful_degradation.inc
deleted file mode 100644
index 6bc0f19..0000000
--- a/ajax_example/ajax_example_graceful_degradation.inc
+++ /dev/null
@@ -1,640 +0,0 @@
-<?php
-
-/**
- * @file
- * Demonstrations of AJAX with graceful degradation.
- *
- */
-
-/**
- * @defgroup ajax_degradation_examples AJAX Degradation Examples
- * @{
- * These examples show AJAX with graceful degradation when Javascript is not
- * available.
- *
- * In each of these the key idea is that the form is rebuilt different ways
- * depending on form input. In order to accomplish that, the formbuilder function
- * is in charge of almost all logic.
- *
- * @see ajax
- *
- * @}
- */
-
-
-
-/**
- * A form with a dropdown whose options are dependent on a
- * choice made in a previous dropdown.
- *
- * On changing the first dropdown, the options in the second
- * are updated. Gracefully degrades if no javascript.
- *
- * A bit of CSS and javascript is required. The CSS hides the "add more" button
- * if javascript is not enabled. The Javascript snippet is really only used
- * to enable us to present the form in degraded mode without forcing the user
- * to turn off Javascript. Both of these are loaded by using the
- * #attached FAPI property, so it is a good example of how to use that.
- *
- * The extra argument $no_js_use is here only to allow presentation of this
- * form as if Javascript were not enabled. ajax_example_menu() provides two
- * ways to call this form, one normal ($no_js_use = FALSE) and one simulating
- * Javascript disabled ($no_js_use = TRUE).
- *
- * @ingroup ajax_examples
- * @ingroup ajax_degradation_examples
- */
-function ajax_example_dependent_dropdown_degrades($form, &$form_state, $no_js_use = FALSE) {
- // Get the list of options to populate the first dropdown.
- $options_first = _ajax_example_get_first_dropdown_options();
-
- // If we have a value for the first dropdown from $form_state['values'] we use
- // this both as the default value for the first dropdown and also as a
- // parameter to pass to the function that retrieves the options for the
- // second dropdown.
- $selected = isset($form_state['values']['dropdown_first']) ? $form_state['values']['dropdown_first'] : key($options_first);
-
- // Attach the CSS and JS we need to show this with and without javascript.
- // Without javascript we need an extra "Choose" button, and this is
- // hidden when we have javascript enabled.
- $form['#attached']['css'] = array(
- drupal_get_path('module', 'ajax_example') . '/ajax_example.css',
- );
- $form['#attached']['js'] = array(
- drupal_get_path('module', 'ajax_example') . '/ajax_example.js',
- );
-
- $form['dropdown_first_fieldset'] = array(
- '#type' => 'fieldset',
- );
- $form['dropdown_first_fieldset']['dropdown_first'] = array(
- '#type' => 'select',
- '#title' => 'Instrument Type',
- '#options' => $options_first,
- '#attributes' => array('class' => array('enabled-for-ajax')),
-
- // The '#ajax' property allows us to bind a callback to the server whenever this
- // form element changes. See ajax_example_autocheckboxes and
- // ajax_example_dependent_dropdown in ajax_example.module for more details.
- '#ajax' => array(
- 'callback' => 'ajax_example_dependent_dropdown_degrades_first_callback',
- 'wrapper' => 'dropdown-second-replace',
- ),
- );
-
- // This simply allows us to demonstrate no-javascript use without
- // actually turning off javascript in the browser. Removing the #ajax
- // element turns off AJAX behaviors on that element and as a result
- // ajax.js doesn't get loaded. This is for demonstration purposes only.
- if ($no_js_use) {
- unset($form['dropdown_first_fieldset']['dropdown_first']['#ajax']);
- }
-
- // Since we don't know if the user has js or not, we always need to output
- // this element, then hide it with with css if javascript is enabled.
- $form['dropdown_first_fieldset']['continue_to_second'] = array(
- '#type' => 'submit',
- '#value' => t('Choose'),
- '#attributes' => array('class' => array('next-button')),
- );
-
- $form['dropdown_second_fieldset'] = array(
- '#type' => 'fieldset',
- );
- $form['dropdown_second_fieldset']['dropdown_second'] = array(
- '#type' => 'select',
- '#title' => $options_first[$selected] . ' ' . t('Instruments'),
- '#prefix' => '<div id="dropdown-second-replace">',
- '#suffix' => '</div>',
- '#attributes' => array('class' => array('enabled-for-ajax')),
- // When the form is rebuilt during processing (either AJAX or multistep),
- // the $selected variable will now have the new value and so the options
- // will change.
- '#options' => _ajax_example_get_second_dropdown_options($selected),
- );
- $form['dropdown_second_fieldset']['submit'] = array(
- '#type' => 'submit',
- '#value' => t('OK'),
- // This class allows attached js file to override the disabled attribute,
- // since it's not necessary in ajax-enabled form.
- '#attributes' => array('class' => array('enabled-for-ajax')),
- );
-
- // Disable dropdown_second if a selection has not been made on dropdown_first.
- if (empty($form_state['values']['dropdown_first'])) {
- $form['dropdown_second_fieldset']['dropdown_second']['#disabled'] = TRUE;
- $form['dropdown_second_fieldset']['dropdown_second']['#description'] = t('You must make your choice on the first dropdown before changing this second one.');
- $form['dropdown_second_fieldset']['submit']['#disabled'] = TRUE;
- }
-
- return $form;
-}
-
-/**
- * Submit function for ajax_example_dependent_dropdown_degrades().
- */
-function ajax_example_dependent_dropdown_degrades_submit($form, &$form_state) {
-
- // Now handle the case of the next, previous, and submit buttons.
- // only submit will result in actual submission, all others rebuild.
- switch($form_state['triggering_element']['#value']) {
- case t('OK'): // Submit: We're done.
- drupal_set_message(t('Your values have been submitted. dropdown_first=@first, dropdown_second=@second', array('@first' => $form_state['values']['dropdown_first'], '@second' => $form_state['values']['dropdown_second'])));
- return;
- }
- // 'Choose' or anything else will cause rebuild of the form and present
- // it again.
- $form_state['rebuild'] = TRUE;
-}
-
-/**
- * Selects just the second dropdown to be returned for re-rendering
- *
- * @return renderable array (the second dropdown)
- */
-function ajax_example_dependent_dropdown_degrades_first_callback($form, $form_state) {
- return $form['dropdown_second_fieldset']['dropdown_second'];
-}
-
-
-/**
- * Example of a form with portions dynamically enabled or disabled, but
- * with graceful degradation in the case of no javascript.
- *
- * The idea here is that certain parts of the form don't need to be displayed
- * unless a given option is selected, but then they should be displayed and
- * configured.
- *
- * The third $no_js_use argument is strictly for demonstrating operation
- * without javascript, without making the user/developer turn off javascript.
- *
- * @ingroup ajax_examples
- * @ingroup ajax_degradation_examples
- */
-
-function ajax_example_dynamic_sections($form, &$form_state, $no_js_use = FALSE) {
-
- // Attach the CSS and JS we need to show this with and without javascript.
- // Without javascript we need an extra "Choose" button, and this is
- // hidden when we have javascript enabled.
- $form['#attached']['css'] = array(
- drupal_get_path('module', 'ajax_example') . '/ajax_example.css',
- );
- $form['#attached']['js'] = array(
- drupal_get_path('module', 'ajax_example') . '/ajax_example.js',
- );
- $form['description'] = array(
- '#type' => 'markup',
- '#markup' => '<div>' . t('This example demonstrates a form which dynamically creates various sections based on the configuration in the form.
- It deliberately allows graceful degradation to a non-javascript environment.
- In a javascript environment, the "Choose" button next to the select control
- if displayed; in a non-js environment it is hidden by the module CSS.
- <br/><br/>The basic idea here is that the form is built up based on
- the selection in the question_type_select field, and it is built the same
- whether we are in a javascript/AJAX environment or not.
- <br/><br/>
- Try the <a href="!ajax_link">AJAX version</a> and the <a href="!non_ajax_link">simulated-non-AJAX version</a>.
- ', array('!ajax_link' => url('ajax_example/dynamic_sections'), '!non_ajax_link' => url('ajax_example/dynamic_sections_no_js') )) . '</div>',
- );
- $form['question_type_select'] = array(
- '#type' => 'select',
- '#title' => t('Question style'),
- '#options' => drupal_map_assoc(array(t('Choose question style'), t('Multiple Choice'), t('True/False'), t('Fill-in-the-blanks'))),
- '#ajax' => array(
- 'wrapper' => 'questions-fieldset-wrapper',
- 'callback' => 'ajax_example_dynamic_sections_select_callback',
- ),
- );
- // The CSS for this module hides this next button if JS is enabled.
- $form['question_type_submit'] = array(
- '#type' => 'submit',
- '#value' => t('Choose'),
- '#attributes' => array('class' => array('next-button')),
- '#limit_validation_errors' => array(), // No need to validate when submitting this.
- '#validate' => array(),
- );
-
- // This simply allows us to demonstrate no-javascript use without
- // actually turning off javascript in the browser. Removing the #ajax
- // element turns off AJAX behaviors on that element and as a result
- // ajax.js doesn't get loaded.
- if ($no_js_use) {
- // Remove the #ajax from the above, so ajax.js won't be loaded.
- unset($form['question_type_select']['#ajax']);
- }
-
- // This fieldset just serves as a container for the part of the form
- // that gets rebuilt.
- $form['questions_fieldset'] = array(
- '#type' => 'fieldset',
- // These provide the wrapper referred to in #ajax['wrapper'] above.
- '#prefix' => '<div id="questions-fieldset-wrapper">',
- '#suffix' => '</div>',
- );
- if (!empty($form_state['values']['question_type_select'])) {
-
- $form['questions_fieldset']['question'] = array(
- '#markup' => t('Who was the first president of the U.S.?'),
- );
- $question_type = $form_state['values']['question_type_select'];
-
- switch ($question_type) {
- case t('Multiple Choice'):
- $form['questions_fieldset']['question'] = array(
- '#type' => 'radios',
- '#title' => t('Who was the first president of the United States'),
- '#options' => drupal_map_assoc(array(t('George Bush'), t('Adam McGuire'), t('Abraham Lincoln'), t('George Washington'))),
- );
- break;
-
- case t('True/False'):
- $form['questions_fieldset']['question'] = array(
- '#type' => 'radios',
- '#title' => t('Was George Washington the first president of the United States?'),
- '#options' => array(t('George Washington') => t("True"), 0 => t("False")),
- '#description' => t('Click "True" if you think George Washington was the first president of the United States.'),
- );
- break;
-
- case t('Fill-in-the-blanks'):
- $form['questions_fieldset']['question'] = array(
- '#type' => 'textfield',
- '#title' => t('Who was the first president of the United States'),
- '#description' => t('Please type the correct answer to the question.'),
- );
- break;
- }
-
- $form['questions_fieldset']['submit'] = array(
- '#type' => 'submit',
- '#value' => t('Submit your answer'),
- );
- }
- return $form;
-}
-
-/**
- * Validation function for ajax_example_dynamic_sections().
- */
-function ajax_example_dynamic_sections_validate($form, &$form_state) {
- $answer = $form_state['values']['question'];
- if ($answer !== t('George Washington')) {
- form_set_error('question', t('Wrong answer. Try again. (Hint: The right answer is "George Washington".)'));
- }
-}
-
-/**
- * Submit function for ajax_example_dynamic_sections().
- */
-function ajax_example_dynamic_sections_submit($form, &$form_state) {
- // This is only executed when a button is pressed, not when the AJAXified
- // select is changed.
- // Now handle the case of the next, previous, and submit buttons.
- // Only submit will result in actual submission, all others rebuild.
- switch($form_state['triggering_element']['#value']) {
- case t('Submit your answer'): // Submit: We're done.
- $form_state['rebuild'] = FALSE;
- $answer = $form_state['values']['question'];
-
- // Special handling for the checkbox.
- if ($answer == 1 && $form['questions_fieldset']['question']['#type'] == 'checkbox') {
- $answer = $form['questions_fieldset']['question']['#title'];
- }
- if ($answer === t('George Washington')) {
- drupal_set_message(t('You got the right answer: @answer', array('@answer' => $answer)));
- }
- else {
- drupal_set_message(t('Sorry, your answer (@answer) is wrong', array('@answer' => $answer)));
- }
- $form_state['rebuild'] = FALSE;
- return;
- }
-
- // Any other form element will cause rebuild of the form and present
- // it again.
- $form_state['rebuild'] = TRUE;
-}
-
-/**
- * Callback for the select element.
- *
- * This just selects and returns the questions_fieldset.
- */
-function ajax_example_dynamic_sections_select_callback($form, $form_state) {
- return $form['questions_fieldset'];
-}
-
-
-/**
- * This example is a classic wizard, where a different and sequential form
- * is presented on each step of the form.
- *
- * In the AJAX version, the form is replaced for each wizard section. In the
- * multistep version, it causes a new page load.
- *
- * @param $form
- * @param $form_state
- * @param $no_js_use
- * Used for this demonstration only. If true means that the form should be
- * built using a simulated no-javascript approach (ajax.js will not be
- * loaded.)
- *
- * @ingroup ajax_examples
- * @ingroup ajax_degradation_examples
- *
- */
-function ajax_example_wizard($form, &$form_state, $no_js_use = FALSE) {
-
- // Provide a wrapper around the entire form, since we'll replace the whole
- // thing with each submit.
- $form['#prefix'] = '<div id="wizard-form-wrapper">';
- $form['#suffix'] = '</div>';
- $form['#tree'] = TRUE; // We want to deal with hierarchical form values.
-
- $form['description'] = array(
- '#markup' => '<div>' . t('This example is a step-by-step wizard. The <a href="!ajax">AJAX version</a> does it without page reloads; the <a href="!multistep">multistep version</a> is the same code but simulates a non-javascript environment, showing it with page reloads.',
- array('!ajax' => url('ajax_example/wizard'), '!multistep' => url('ajax_example/wizard_no_js')))
- . '</div>',
- );
-
- // $form_state['storage'] has no specific drupal meaning, but it is
- // traditional to keep variables for multistep forms there.
- $step = empty($form_state['storage']['step']) ? 1 : $form_state['storage']['step'];
- $form_state['storage']['step'] = $step;
-
- switch ($step) {
- case 1:
- $form['step1'] = array(
- '#type' => 'fieldset',
- '#title' => t('Step 1: Personal details'),
- );
- $form['step1']['name'] = array(
- '#type' => 'textfield',
- '#title' => t('Your name'),
- '#default_value' => empty($form_state['values']['step1']['name']) ? '' : $form_state['values']['step1']['name'],
- '#required' => TRUE,
- );
- break;
-
- case 2:
- $form['step2'] = array(
- '#type' => 'fieldset',
- '#title' => t('Step 2: Street address info'),
- );
- $form['step2']['address'] = array(
- '#type' => 'textfield',
- '#title' => t('Your street address'),
- '#default_value' => empty($form_state['values']['step2']['address']) ? '' : $form_state['values']['step2']['address'],
- '#required' => TRUE,
- );
- break;
-
- case 3:
- $form['step3'] = array(
- '#type' => 'fieldset',
- '#title' => t('Step 3: City info'),
- );
- $form['step3']['city'] = array(
- '#type' => 'textfield',
- '#title' => t('Your city'),
- '#default_value' => empty($form_state['values']['step3']['city']) ? '' : $form_state['values']['step3']['city'],
- '#required' => TRUE,
- );
- break;
- }
- if ($step == 3) {
- $form['submit'] = array(
- '#type' => 'submit',
- '#value' => t("Submit your information"),
- );
- }
- if ($step < 3) {
- $form['next'] = array(
- '#type' => 'submit',
- '#value' => t('Next step'),
- '#ajax' => array(
- 'wrapper' => 'wizard-form-wrapper',
- 'callback' => 'ajax_example_wizard_callback',
- ),
- );
- }
- if ($step > 1) {
- $form['prev'] = array(
- '#type' => 'submit',
- '#value' => t("Previous step"),
-
- // Since all info will be discarded, don't validate on 'prev'.
- '#limit_validation_errors' => array(),
- // #submit is required to use #limit_validation_errors
- '#submit' => array('ajax_example_wizard_submit'),
- '#ajax' => array(
- 'wrapper' => 'wizard-form-wrapper',
- 'callback' => 'ajax_example_wizard_callback',
- ),
- );
- }
-
- // This simply allows us to demonstrate no-javascript use without
- // actually turning off javascript in the browser. Removing the #ajax
- // element turns off AJAX behaviors on that element and as a result
- // ajax.js doesn't get loaded.
- // For demonstration only! You don't need this.
- if ($no_js_use) {
- // Remove the #ajax from the above, so ajax.js won't be loaded.
- // For demonstration only.
- unset($form['next']['#ajax']);
- unset($form['prev']['#ajax']);
- }
-
- return $form;
-}
-
-function ajax_example_wizard_callback($form, $form_state) {
- return $form;
-}
-
-/**
- * Submit function for ajax_example_wizard.
- *
- * In AJAX this is only submitted when the final submit button is clicked,
- * but in the non-javascript situation, it is submitted with every
- * button click.
- *
- */
-function ajax_example_wizard_submit($form, &$form_state) {
-
- // Save away the current information.
- $current_step = 'step' . $form_state['storage']['step'];
- if (!empty($form_state['values'][$current_step])) {
- $form_state['storage']['values'][$current_step] = $form_state['values'][$current_step];
- }
-
- // Increment or decrement the step as needed. Recover values if they exist.
- if ($form_state['triggering_element']['#value'] == t('Next step')) {
- $form_state['storage']['step']++;
- // If values have already been entered for this step, recover them from
- // $form_state['storage'] to pre-populate them.
- $step_name = 'step' . $form_state['storage']['step'];
- if (!empty($form_state['storage']['values'][$step_name])) {
- $form_state['values'][$step_name] = $form_state['storage']['values'][$step_name];
- }
- }
- if ($form_state['triggering_element']['#value'] == t('Previous step')) {
- $form_state['storage']['step']--;
- // Recover our values from $form_state['storage'] to pre-populate them.
- $step_name = 'step' . $form_state['storage']['step'];
- $form_state['values'][$step_name] = $form_state['storage']['values'][$step_name];
- }
-
- // If they're done, submit.
- if ($form_state['triggering_element']['#value'] == t('Submit your information')) {
- $value_message = t("Your information has been submitted: ");
- foreach ($form_state['storage']['values'] as $step => $values) {
- $value_message .= "$step: ";
- foreach ($values as $key => $value) {
- $value_message .= "$key=$value, ";
- }
- }
- drupal_set_message($value_message);
- $form_state['rebuild'] = FALSE;
- return;
- }
-
- // Otherwise, we still have work to do.
- $form_state['rebuild'] = TRUE;
-}
-
-
-/**
- * This example shows a button to "add more" - add another textfield, and
- * the corresponding "remove" button.
- *
- * It works equivalently with javascript or not, and does the same basic steps
- * either way.
- *
- * The basic idea is that we build the form based on the setting of
- * $form_state['num_names']. The custom submit functions for the "add-one"
- * and "remove-one" buttons increment and decrement $form_state['num_names']
- * and then force a rebuild of the form.
- *
- * The $no_js_use argument is simply for demonstration: When set, it prevents
- * '#ajax' from being set, thus making the example behave as if javascript
- * were disabled in the browser.
- *
- * @ingroup ajax_examples
- * @ingroup ajax_degradation_examples
- */
-
-function ajax_example_add_more($form, &$form_state, $no_js_use = FALSE) {
- $form['description'] = array(
- '#markup' => '<div>' . t('This example shows an add-more and a remove-last button. The <a href="!ajax">AJAX version</a> does it without page reloads; the <a href="!multistep">non-js version</a> is the same code but simulates a non-javascript environment, showing it with page reloads.',
- array('!ajax' => url('examples/ajax_example/add_more'), '!multistep' => url('examples/ajax_example/add_more_no_js')))
- . '</div>',
- );
-
- // Because we have many fields with the same values, we have to set
- // #tree to be able to access them.
- $form['#tree'] = TRUE;
- $form['names_fieldset'] = array(
- '#type' => 'fieldset',
- '#title' => t('People coming to the picnic'),
- // Set up the wrapper so that AJAX will be able to replace the fieldset.
- '#prefix' => '<div id="names-fieldset-wrapper">',
- '#suffix' => '</div>',
- );
-
- // Build the fieldset with the proper number of names. We'll use
- // $form_state['num_names'] to determine the number of textfields to build.
- if (empty($form_state['num_names'])) {
- $form_state['num_names'] = 1;
- }
- for ($i = 0; $i < $form_state['num_names']; $i++) {
- $form['names_fieldset']['name'][$i] = array(
- '#type' => 'textfield',
- '#title' => t('Name'),
- );
- }
- $form['names_fieldset']['add_name'] = array(
- '#type' => 'submit',
- '#value' => t('Add one more'),
- '#submit' => array('ajax_example_add_more_add_one'),
- // See the examples in ajax_example.module for more details on the
- // properties of #ajax.
- '#ajax' => array(
- 'callback' => 'ajax_example_add_more_callback',
- 'wrapper' => 'names-fieldset-wrapper',
- ),
- );
- if ($form_state['num_names'] > 1) {
- $form['names_fieldset']['remove_name'] = array(
- '#type' => 'submit',
- '#value' => t('Remove one'),
- '#submit' => array('ajax_example_add_more_remove_one'),
- '#ajax' => array(
- 'callback' => 'ajax_example_add_more_callback',
- 'wrapper' => 'names-fieldset-wrapper',
- ),
- );
- }
- $form['submit'] = array(
- '#type' => 'submit',
- '#value' => t('Submit'),
- );
-
- // This simply allows us to demonstrate no-javascript use without
- // actually turning off javascript in the browser. Removing the #ajax
- // element turns off AJAX behaviors on that element and as a result
- // ajax.js doesn't get loaded.
- // For demonstration only! You don't need this.
- if ($no_js_use) {
- // Remove the #ajax from the above, so ajax.js won't be loaded.
- if (!empty($form['names_fieldset']['remove_name']['#ajax'])) {
- unset($form['names_fieldset']['remove_name']['#ajax']);
- }
- unset($form['names_fieldset']['add_name']['#ajax']);
- }
-
- return $form;
-}
-
-/**
- * Callback for both ajax-enabled buttons.
- *
- * This simply selects and returns the fieldset with the names in it.
- */
-function ajax_example_add_more_callback($form, $form_state) {
- return $form['names_fieldset'];
-}
-
-/**
- * Submit handler for the "add-one-more" button.
- *
- * It just increments the max counter and causes a rebuild.
- */
-function ajax_example_add_more_add_one($form, &$form_state) {
- $form_state['num_names']++;
- $form_state['rebuild'] = TRUE;
-}
-
-/**
- * Submit handler for the "remove one" button.
- *
- * Decrements the max counter and causes a form rebuild.
- */
-function ajax_example_add_more_remove_one($form, &$form_state) {
- if ($form_state['num_names'] > 1) {
- $form_state['num_names']--;
- }
- $form_state['rebuild'] = TRUE;
-}
-
-/**
- * Final submit handler.
- *
- * Reports what values were finally set.
- */
-function ajax_example_add_more_submit($form, &$form_state) {
- $output = t('These people are coming to the picnic: @names',
- array('@names' => implode(', ', $form_state['values']['names_fieldset']['name'])) );
- drupal_set_message($output);
-} \ No newline at end of file
diff --git a/ajax_example/ajax_example_misc.inc b/ajax_example/ajax_example_misc.inc
deleted file mode 100644
index e0deb07..0000000
--- a/ajax_example/ajax_example_misc.inc
+++ /dev/null
@@ -1,108 +0,0 @@
-<?php
-
-/**
- * @file
- * AJAX Miscellaneous Topics.
- *
- *
-*/
-
-/**
- * Demonstrates a clickable AJAX-enabled link using the 'use-ajax' class.
- *
- * Because of the 'use-ajax' class applied here, the link submission is done
- * without a page refresh.
- *
- * When using the AJAX framework outside the context of a form or a renderable
- * array of type 'link', you have to include ajax.js explicitly.
- * @return unknown_type
- */
-function ajax_example_render_link() {
- // drupal_add_library is invoked automatically when a form element has the
- // '#ajax' property, but since we are not rendering a form here, we have to
- // do it ourselves.
- drupal_add_library('system', 'drupal.ajax');
- $explanation = "
-The link below has the <i>use-ajax</i> class applied to it, so if
-javascript is enabled, ajax.js will try to submit it via an AJAX call instead
-of a normal page load. The URL also contains the '/nojs/' magic string, which
-is stripped if javascript is enabled, allowing the server code to tell by the
-URL whether JS was enabled or not, letting it do different things based on that.";
- $output = "<div>" . t($explanation) ."</div>";
- // The use-ajax class is special, so that the link will call without causing
- // a page reload. Note the /nojs portion of the path - if javascript is
- // enabled, this part will be stripped from the path before it is called.
- $link = l(t('Click here'), 'ajax_link_callback/nojs/', array('attributes' => array('class' => array('use-ajax'))));
- $output .= "<div id='myDiv'></div><div>$link</div>";
- return $output;
-}
-
-/**
- * Demonstrates a clickable AJAX-enabled link using a renderable array with the
- * #ajax property.
- *
- * A link that is constructed as a renderable array can have the #ajax property,
- * which ensures that the link submission is done without a page refresh. The href
- * of the link is used as the ajax callback, but it degrades gracefully without
- * JavaScript because if the 'nojs' portion of the href is not stripped out by js,
- * the callback will return content as required for a full page reload.
- *
- * The necessary JavaScript file, ajax.js, will be included on the page
- * automatically.
- * @return unknown_type
- */
-function ajax_example_render_link_ra() {
- $explanation = "
-The link below has been rendered as an element with the #ajax property, so if
-javascript is enabled, ajax.js will try to submit it via an AJAX call instead
-of a normal page load. The URL also contains the '/nojs/' magic string, which
-is stripped if javascript is enabled, allowing the server code to tell by the
-URL whether JS was enabled or not, letting it do different things based on that.";
- $build['my_div'] = array(
- '#markup' => $explanation .'<div id="myDiv"></div>',
- );
- $build['ajax_link'] = array(
- '#type' => 'link',
- '#title' => t('Click here'),
- // Note the /nojs portion of the href - if javascript is enabled,
- // this part will be stripped from the path before it is called.
- '#href' => 'ajax_link_callback/nojs/',
- '#id' => 'ajax_link',
- '#ajax' => array(
- 'wrapper' => 'myDiv',
- 'method' => 'html',
- ),
- );
-
- return $build;
-}
-
-/**
- * Callback for link example.
- *
- * Takes different logic paths based on whether Javascript was enabled.
- * If $type == 'ajax', it tells this function that ajax.js has rewritten
- * the URL and thus we are doing an AJAX and can return an array of commands.
- * @param $type
- * Either 'ajax' or 'nojs. Type is simply the normal URL argument to this
- * URL.
- * @return
- * If $type == 'ajax', returns an array of AJAX Commands.
- * Otherwise, just returns the content, which will end up being a page.
- * @see ajax
- */
-function ajax_link_response($type = 'ajax') {
- if ($type == 'ajax') {
- $output = t("This is some content delivered via AJAX");
- $commands = array();
- // See ajax_example_advanced.inc for more details on the available commands
- // and how to use them.
- $commands[] = ajax_command_append('#myDiv', $output);
- $page = array('#type' => 'ajax', '#commands' => $commands);
- ajax_deliver($page);
- }
- else {
- $output = t("This is some content delivered via a page load.");
- return $output;
- }
-}
diff --git a/batch_example/batch_example.info b/batch_example/batch_example.info
deleted file mode 100644
index 5c5ce79..0000000
--- a/batch_example/batch_example.info
+++ /dev/null
@@ -1,6 +0,0 @@
-
-name = Batch example
-description = An example outlining how a module can define batch operations.
-package = Example modules
-core = 7.x
-files[] = batch_example.test
diff --git a/batch_example/batch_example.install b/batch_example/batch_example.install
deleted file mode 100644
index ec8e60c..0000000
--- a/batch_example/batch_example.install
+++ /dev/null
@@ -1,79 +0,0 @@
-<?php
-
-/**
- * @file
- * Install/Update/Uninstall functions for batch_example module
- */
-
-/**
- * Example of batch-driven update function.
- *
- * Because some update functions may require the batch API, the $sandbox
- * provides a place to store state. When $standbox['#finished'] == TRUE,
- * calls to this update function are completed.
- *
- * The $sandbox param provides a way to store data during multiple invocations.
- * When the $sandbox['#finished'] == 1, execution is complete.
- *
- * This dummy 'update' function changes no state in the system. It simply
- * loads each node.
- *
- * To make this update function run again and again, execute the query
- * "update system set schema_version = 0 where name = 'batch_example';"
- * and then run /update.php.
- */
-function batch_example_update_7100(&$sandbox) {
- $ret = array();
-
- // Use the sandbox at your convenience to store the information needed
- // to track progression between successive calls to the function.
- if (!isset($sandbox['progress'])) {
- $sandbox['progress'] = 0; // The count of nodes visited so far.
- // Total nodes that must be visited.
- $sandbox['max'] = db_query('SELECT COUNT(DISTINCT nid) FROM {node}')->fetchField();
- // A place to store messages during the run.
- $sandbox['messages'] = array();
- $sandbox['current_node'] = -1; // Last node read via the query.
- }
-
- // Process nodes by groups of 10 (arbitrary value).
- // When a group is processed, the batch update engine determines
- // whether it should continue processing in the same request or provide
- // progress feedback to the user and wait for the next request.
- $limit = 10;
-
- // Retrieve the next group of nids.
- $result = db_select('node', 'n')
- ->fields('n', array('nid'))
- ->orderBy('n.nid', 'ASC')
- ->where('n.nid > :nid', array(':nid' => $sandbox['current_node']))
- ->extend('PagerDefault')
- ->limit($limit)
- ->execute();
- foreach ($result as $row) {
- // Here we actually perform a dummy 'update' on the current node.
- $node = db_query('SELECT nid FROM {node} WHERE nid = :nid', array(':nid' => $row->nid))->fetchField();
-
- // Update our progress information.
- $sandbox['progress']++;
- $sandbox['current_node'] = $row->nid;
- }
-
- // Set the "finished" status, to tell batch engine whether this function
- // needs to run again.
- $sandbox['#finished'] = ($sandbox['progress'] >= $sandbox['max']);
-
- // Set up a per-run message; Make a copy of $sandbox so we can change it.
- // This is simply a debugging stanza to illustrate how to capture status
- // from each pass through hook_update_N().
- $sandbox_status = $sandbox;
- unset($sandbox_status['messages']); // Don't want them in the output.
- $sandbox['messages'][] = t('$sandbox=') . print_r($sandbox_status, TRUE);
-
- if ($sandbox['#finished']) {
- // hook_update_N() may optionally return a string which will be displayed
- // to the user.
- $final_message = '<ul><li>' . implode('</li><li>', $sandbox['messages']) . "</li></ul>";
- return t('The batch_example demonstration update did what it was supposed to do: ') . $final_message;
- }
-}
diff --git a/batch_example/batch_example.module b/batch_example/batch_example.module
deleted file mode 100644
index d5752b3..0000000
--- a/batch_example/batch_example.module
+++ /dev/null
@@ -1,264 +0,0 @@
-<?php
-
-/**
- * @file
- * Outlines how a module can use the Batch API.
- *
- * Batches allow heavy processing to be spread out over several page
- * requests, ensuring that the processing does not get interrupted
- * because of a PHP timeout, while allowing the user to receive feedback
- * on the progress of the ongoing operations. It also can prevent out of memory
- * situations.
- *
- * The @link batch_example.install .install file @endlink also shows how the
- * Batch API can be used to handle long-running hook_update_N() functions.
- *
- * @see batch
- */
-
-/**
- * Two harmless batches are defined:
- * - batch 1: Load the node with the lowest nid 100 times.
- * - batch 2: Load all nodes, 20 times and uses a progressive op, loading nodes
- * by groups of 5.
- */
-
-/**
- * Implements hook_menu().
- */
-function batch_example_menu() {
- $items = array();
- $items['examples/batch_example'] = array(
- 'title' => 'Batch example',
- 'description' => t("Example of Drupal batch processing"),
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array('batch_example_simple_form'),
- 'access callback' => TRUE,
- );
-
- return $items;
-}
-
-/**
- * Form builder function to allow choice of which batch to run.
- */
-function batch_example_simple_form() {
- $form['description'] = array(
- '#type' => 'markup',
- '#markup' => t('This example offers two different batches. The first does 1000 identical operations, each completed in on run; the second does 20 operations, but each takes more than one run to operate if there are more than 5 nodes.'),
- );
- $form['batch'] = array(
- '#type' => 'select',
- '#title' => 'Choose batch',
- '#options' => array(
- 'batch_1' => t('batch 1 - 1000 operations, each loading the same node'),
- 'batch_2' => t('batch 2 - 20 operations. each one loads all nodes 5 at a time'),
- ),
- );
- $form['submit'] = array(
- '#type' => 'submit',
- '#value' => 'Go',
- );
-
- // If no nodes, prevent submission.
- // Find out if we have a node to work with. Otherwise it won't work.
- $nid = batch_example_lowest_nid();
- if (empty($nid)) {
- drupal_set_message(t("You don't currently have any nodes, and this example requires a node to work with. As a result, this form is disabled."));
- $form['submit']['#disabled'] = TRUE;
- }
- return $form;
-}
-
-function batch_example_simple_form_submit($form, &$form_state) {
- $function = 'batch_example_' . $form_state['values']['batch'];
-
- $_SESSION['http_request_count'] = 0; // reset counter for debug information.
-
- // Execute the function named batch_example_1 or batch_example_2.
- $batch = $function();
- batch_set($batch);
-}
-
-
-/**
- * @defgroup batch_definitions Example batch definitions
- * @{
- * Definitions of the batches used in this module.
- */
-
-/**
- * Batch 1 definition: Load the node with the lowest nid 1000 times.
- * This creates an operations array defining what batch 1 should do, including
- * what it should do when it's finished. In this case, each operation is the
- * same and by chance even has the same $nid to operate on, but we could have
- * a mix of different types of operations in the operations array.
- */
-function batch_example_batch_1() {
- $nid = batch_example_lowest_nid();
- $num_operations = 1000;
- drupal_set_message(t('Creating an array of @num operations', array('@num' => $num_operations)));
-
- $operations = array();
- // Set up an operations array with 1000 elements, each doing function
- // batch_example_op_1.
- // Each operation in the operations array means at least one new HTTP request,
- // running Drupal from scratch to accomplish the operation. If the operation
- // returns with $context['finished'] != TRUE, then it will be called again.
- // In this example, $context['finished'] is always TRUE.
- for ($i = 0; $i<$num_operations; $i++) {
-
- // Each operation is an array consisting of
- // - the function to call
- // - An array of arguments to that function
- $operations[] = array('batch_example_op_1', array($nid, t('(Operation @operation)', array('@operation' => $i))));
- }
- $batch = array(
- 'operations' => $operations,
- 'finished' => 'batch_example_finished',
- );
- return $batch;
-}
-
-/**
- * Batch operation for batch 1: load a node.
- * This is the function that is called on each operation in batch 1.
- */
-function batch_example_op_1($nid, $operation_details, &$context) {
- $node = node_load($nid, NULL, TRUE);
-
- // Store some result for post-processing in the finished callback.
- $context['results'][] = $node->nid . ' : ' . check_plain($node->title);
-
- // Optional message displayed under the progressbar.
- $context['message'] = t('Loading node "@title"', array('@title' => $node->title)) . ' ' . $operation_details;
-
- _batch_example_update_http_requests();
-}
-
-/**
- * Batch 2 : Prepare a batch definition that will load all nodes 20 times.
- */
-function batch_example_batch_2() {
- $num_operations = 20;
-
- // Give helpful information about how many nodes are being operated on.
- $node_count = db_query('SELECT COUNT(DISTINCT nid) FROM {node}')->fetchField();
- drupal_set_message(t('There are @node_count nodes so each of the @num operations will require @count HTTP requests.', array('@node_count' => $node_count, '@num' => $num_operations, '@count' => ceil($node_count / 5))));
-
- $operations = array();
- // 20 operations, each one loads all nodes.
- for ($i = 0; $i < $num_operations; $i++) {
- $operations[] = array('batch_example_op_2', array(t('(Operation @operation)', array('@operation' => $i))));
- }
- $batch = array(
- 'operations' => $operations,
- 'finished' => 'batch_example_finished',
- // We can define custom messages instead of the default ones.
- 'title' => t('Processing batch 2'),
- 'init_message' => t('Batch 2 is starting.'),
- 'progress_message' => t('Processed @current out of @total.'),
- 'error_message' => t('Batch 2 has encountered an error.'),
- );
- return $batch;
-}
-
-/**
- * Batch operation for batch 2 : load all nodes, 5 by five
- * After each group of 5 control is returned to the batch API for later
- * continuation.
- */
-function batch_example_op_2($operation_details, &$context) {
- // Use the $context['sandbox'] at your convenience to store the
- // information needed to track progression between successive calls.
- if (empty($context['sandbox'])) {
- $context['sandbox'] = array();
- $context['sandbox']['progress'] = 0;
- $context['sandbox']['current_node'] = 0;
-
- // Save node count for the termination message.
- $context['sandbox']['max'] = db_query('SELECT COUNT(DISTINCT nid) FROM {node}')->fetchField();
- }
-
- // Process nodes by groups of 5 (arbitrary value).
- // When a group of five is processed, the batch update engine determines
- // whether it should continue processing in the same request or provide
- // progress feedback to the user and wait for the next request.
- // That way even though we're already processing at the operation level
- // the operation itself is interruptible.
- $limit = 5;
-
- // Retrieve the next group of nids.
- $result = db_select('node', 'n')
- ->fields('n', array('nid'))
- ->orderBy('n.nid', 'ASC')
- ->where('n.nid > :nid', array(':nid' => $context['sandbox']['current_node']))
- ->extend('PagerDefault')
- ->limit($limit)
- ->execute();
- foreach ($result as $row) {
- // Here we actually perform our dummy 'processing' on the current node.
- $node = node_load($row->nid, NULL, TRUE);
-
- // Store some result for post-processing in the finished callback.
- $context['results'][] = $node->nid . ' : ' . check_plain($node->title) . ' ' . $operation_details;
-
- // Update our progress information.
- $context['sandbox']['progress']++;
- $context['sandbox']['current_node'] = $node->nid;
- $context['message'] = check_plain($node->title);
- }
-
- // Inform the batch engine that we are not finished,
- // and provide an estimation of the completion level we reached.
- if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
- $context['finished'] = ($context['sandbox']['progress'] >= $context['sandbox']['max']);
- }
- _batch_example_update_http_requests();
-}
-
-/**
- * Batch 'finished' callback used by both batch 1 and batch 2.
- */
-function batch_example_finished($success, $results, $operations) {
- if ($success) {
- // Here we could do something meaningful with the results.
- // We just display the number of nodes we processed...
- drupal_set_message(t('@count results processed in @requests HTTP requests.', array('@count' => count($results), '@requests' => _batch_example_get_http_requests())));
- drupal_set_message(t('The final result was "%final"', array('%final' => end($results))));
- }
- else {
- // An error occurred.
- // $operations contains the operations that remained unprocessed.
- $error_operation = reset($operations);
- drupal_set_message(t('An error occurred while processing @operation with arguments : @args', array('@operation' => $error_operation[0], '@args' => print_r($error_operation[0], TRUE))));
- }
-}
-
-/**
- * Utility function - simply queries and loads the lowest nid.
- * @return A nid or NULL if there are no nodes.
- */
-function batch_example_lowest_nid() {
- $select = db_select('node', 'n')
- ->fields('n', array('nid'))
- ->orderBy('n.nid', 'ASC')
- ->extend('PagerDefault')
- ->limit(1);
- $nid = $select->execute()->fetchField();
- return $nid;
-}
-/**
- * @} End of "defgroup batch_definitions".
- */
-
-/**
- * Utility function to count the HTTP requests in a session variable.
- */
-function _batch_example_update_http_requests() {
- $_SESSION['http_request_count']++;
-}
-
-function _batch_example_get_http_requests() {
- return !empty($_SESSION['http_request_count']) ? $_SESSION['http_request_count'] : 0;
-} \ No newline at end of file
diff --git a/batch_example/batch_example.test b/batch_example/batch_example.test
deleted file mode 100644
index 70198fd..0000000
--- a/batch_example/batch_example.test
+++ /dev/null
@@ -1,53 +0,0 @@
-<?php
-
-/**
- * @file
- * Test case for Testing the batch example module.
- *
- * This file contains the test cases to check if module is performing as
- * expected.
- *
- */
-class BatchExampleTestCase extends DrupalWebTestCase {
- protected $web_user;
-
- public static function getInfo() {
- return array(
- 'name' => 'Batch example functionality',
- 'description' => 'Verify the defined batches.',
- 'group' => 'Examples',
- );
- }
-
- /**
- * Enable modules and create user with specific permissions.
- */
- function setUp() {
- parent::setUp('batch_example');
- // Create user.
- $this->web_user = $this->drupalCreateUser();
- }
-
- /**
- * Login user, create 30 nodes and test both batch examples.
- */
- function testBatchExampleBasic() {
- // Login the admin user.
- $this->drupalLogin($this->web_user);
-
- // Create 30 nodes
- for ($count = 0; $count < 30; $count++) {
- $node = $this->drupalCreateNode();
- }
-
- // Launch Batch 1
- $result = $this->drupalPost('examples/batch_example', array('batch' => 'batch_1'), t('Go'));
- // Check that 1000 operations were performed.
- $this->assertText('1000 results processed');
-
- // Launch Batch 2
- $result = $this->drupalPost('examples/batch_example', array('batch' => 'batch_2'), t('Go'));
- // Check that 600 operations were performed.
- $this->assertText('600 results processed');
- }
-}
diff --git a/block_example/block_example.info b/block_example/block_example.info
deleted file mode 100644
index 44f7abf..0000000
--- a/block_example/block_example.info
+++ /dev/null
@@ -1,6 +0,0 @@
-
-name = Block Example
-description = An example outlining how a module can define blocks.
-package = Example modules
-core = 7.x
-files[] = block_example.test
diff --git a/block_example/block_example.install b/block_example/block_example.install
deleted file mode 100644
index 13a9df8..0000000
--- a/block_example/block_example.install
+++ /dev/null
@@ -1,13 +0,0 @@
-<?php
-
-/**
- * @file
- * Install, update and uninstall functions for the block_example module.
- */
-
-/**
- * Implements hook_uninstall().
- */
-function block_example_uninstall() {
- variable_del('block_example_string');
-}
diff --git a/block_example/block_example.module b/block_example/block_example.module
deleted file mode 100755
index 1a0457c..0000000
--- a/block_example/block_example.module
+++ /dev/null
@@ -1,217 +0,0 @@
-<?php
-
-/**
- * @file
- * This is an example outlining how a module can define blocks that can be
- * displayed on various pages of a site, or how to alter blocks provided by
- * other modules.
- */
-
-/**
- * Implements hook_menu().
- *
- * Provides a default page to explain what this module does.
- */
-function block_example_menu() {
- $items['examples/block_example'] = array(
- 'page callback' => 'block_example_page',
- 'access callback' => TRUE,
- 'title' => 'Block Example',
- );
- return $items;
-}
-
-/**
- * Simple page function to explain what the block example is about.
- */
-function block_example_page() {
- $page = array(
- '#type' => 'markup',
- '#markup' => t('The Block Example provides two sample blocks which demonstrate the various block APIs. To experiment with the blocks, enable and configure them on <a href="@url">the block admin page</a>.', array('@url' => url('admin/structure/block'))),
- );
- return $page;
-}
-/**
- * Implements hook_block_info().
- *
- * This hook declares what blocks are provided by the module.
- */
-function block_example_block_info() {
- // This hook returns an array, each component of which is an array of block
- // information. The array keys are the 'delta' values used in other block
- // hooks.
-
- // The required block information is a block description, which is shown
- // to the site administrator in the list of possible blocks. You can also
- // provide initial settings for block weight, status, etc.
-
- // Many options are defined in hook_block_info():
- $blocks['example_configurable_text'] = array(
- // info: The name of the block.
- 'info' => t('Example: configurable text string'),
- // Block caching options (per role, per user, etc.)
- 'cache' => DRUPAL_CACHE_PER_ROLE, // default
- );
-
- // This sample shows how to provide default settings. In this case we'll
- // enable the block in the first sidebar and make it visible only on
- // 'node/*' pages. See the hook_block_info() documentation for these.
- $blocks['example_empty'] = array(
- 'info' => t('Example: empty block'),
- 'status' => TRUE,
- 'region' => 'sidebar_first', // Not usually provided.
- 'visibility' => 1, // Not usually provided.
- 'pages' => 'node/*', // Not usually provided here.
- );
-
- return $blocks;
-}
-
-/**
- * Implements hook_block_configure().
- *
- * This hook declares configuration options for blocks provided by this module.
- */
-function block_example_block_configure($delta = '') {
- // The $delta parameter tells us which block is being configured.
- // In this example, we'll allow the administrator to customize
- // the text of the 'configurable text string' block defined in this module.
-
- $form = array();
- if ($delta == 'example_configurable_text') {
- // All we need to provide is the specific configuration options for our
- // block. Drupal will take care of the standard block configuration options
- // (block title, page visibility, etc.) and the save button.
- $form['block_example_string'] = array(
- '#type' => 'textfield',
- '#title' => t('Block contents'),
- '#size' => 60,
- '#description' => t('This text will appear in the example block.'),
- '#default_value' => variable_get('block_example_string', t('Some example content.')),
- );
- }
- return $form;
-}
-
-/**
- * Implements hook_block_save().
- *
- * This hook declares how the configured options for a block
- * provided by this module are saved.
- */
-function block_example_block_save($delta = '', $edit = array()) {
- // We need to save settings from the configuration form.
- // We need to check $delta to make sure we are saving the right block.
- if ($delta == 'example_configurable_text') {
- // Have Drupal save the string to the database.
- variable_set('block_example_string', $edit['block_example_string']);
- }
- return;
-}
-
-/**
- * Implements hook_block_view().
- *
- * This hook generates the contents of the blocks themselves.
- */
-function block_example_block_view($delta = '') {
- //The $delta parameter tells us which block is being requested.
- switch ($delta) {
- case 'example_configurable_text':
- // The subject is displayed at the top of the block. Note that it
- // should be passed through t() for translation. The title configured
- // for the block using Drupal UI supercedes this one.
- $block['subject'] = t('Title of first block (example_configurable_text)');
- // The content of the block is typically generated by calling a custom
- // function.
- $block['content'] = block_example_contents($delta);
- break;
- case 'example_empty':
- $block['subject'] = t('Title of second block (example_empty)');
- $block['content'] = block_example_contents($delta);
- break;
- }
- return $block;
-}
-
-/**
- * A module-defined block content function.
- */
-function block_example_contents($which_block) {
- switch ($which_block) {
- case 'example_configurable_text':
- // Modules would typically perform some database queries to fetch the
- // content for their blocks. Here, we'll just use the variable set in the
- // block configuration or, if none has set, a default value.
- // Block content can be returned in two formats: renderable arrays
- // (as here) are preferred though a simple string will work as well.
- return array('#markup' => variable_get('block_example_string', t('A default value. This block was created at %time', array('%time' => date('c')))));
- case 'example_empty':
- // It is possible that a block not have any content, since it is
- // probably dynamically constructed. In this case, Drupal will not display
- // the block at all. This block will not be displayed.
- return;
- }
-}
-
-/*
- * The following hooks can be used to alter blocks
- * provided by your own or other modules.
- */
-
-/**
- * Implements hook_block_list_alter().
- *
- * This hook allows you to add, remove or modify blocks in the block list. The
- * block list contains the block definitions. This example requires
- * search module and the search block enabled
- * to see how this hook implementation works.
- *
- * You may also be interested in hook_block_info_alter(), which allows changes
- * to the behavior of blocks.
- */
-function block_example_block_list_alter(&$blocks) {
- // We are going to make the search block sticky on bottom of regions. For
- // this example, we will modify the block list and append the search block at
- // the end of the list, so even if the administrator configures the block to
- // be on the top of the region, it will demote to bottom again.
- foreach ($blocks as $bid => $block) {
- if (($block->module == 'search') && ($block->delta == 'form')) {
- // Remove the block from the list and append to the end.
- unset($blocks[$bid]);
- $blocks[$bid] = $block;
- break;
- }
- }
-}
-
-/**
- * Implements hook_block_view_alter().
- *
- * This hook allows you to modify the output of any block in the system.
- *
- * In addition, instead of hook_block_view_alter(), which is called for all
- * blocks, you can also use hook_block_view_MODULE_DELTA_alter() to alter a
- * specific block.
- *
- * We are going to uppercase the title of any block if the string "magic string"
- * is encountered in the content. If we were changing only our block using
- * hook_block_view_MODULE_DELTA_alter to do this, we would have used the
- * function:
- * block_example_block_view_block_example_example_configurable_text_alter()
- *
- * To demonstrate the effect of this hook, you can use the
- * 'configurable_text_string' block created by this module and add the
- * text 'magic string' into the configuration.
- */
-function block_example_block_view_alter(&$data, $block) {
- // Verify the we have raw text content
- if (!isset($data['content']) || !is_string($data['content'])) {
- return;
- }
-
- // If the content contains the string: 'magic string', uppercase the title.
- if (strstr($data['content'], 'magic string')) {
- $data['subject'] = isset($data['subject']) ? drupal_strtoupper($data['subject']) : '';
- }
-}
diff --git a/block_example/block_example.test b/block_example/block_example.test
deleted file mode 100644
index cfbd998..0000000
--- a/block_example/block_example.test
+++ /dev/null
@@ -1,92 +0,0 @@
-<?php
-
-/**
- * @file
- * Test case for testing the block example module.
- */
-class BlockExampleTestCase extends DrupalWebTestCase {
- protected $web_user;
-
- public static function getInfo() {
- return array(
- 'name' => 'Block example functionality',
- 'description' => 'Test the configuration options and block created by Block Example module.',
- 'group' => 'Examples',
- );
- }
-
- /**
- * Enable modules and create user with specific permissions.
- */
- function setUp() {
- parent::setUp('block_example', 'search');
- // Create user. Search content permission granted for the search block to
- // be shown.
- $this->web_user = $this->drupalCreateUser(array('administer blocks', 'search content', 'access contextual links'));
- }
-
- /**
- * Login user, create an example node, and test block functionality through
- * the admin and user interfaces.
- */
- function testBlockExampleBasic() {
- // Login the admin user.
- $this->drupalLogin($this->web_user);
-
- // Find the blocks in the settings page.
- $this->drupalGet('admin/structure/block');
- $this->assertRaw(t('Example: configurable text string'), t('Block configurable-string found.'));
- $this->assertRaw(t('Example: empty block'), t('Block empty-block found.'));
-
- // Verify the default settings for block are processed.
- $this->assertFieldByName('blocks[block_example_example_empty][region]', 'sidebar_first', t('Empty block is enabled in first sidebar successfully verified.') );
- $this->assertFieldByName('blocks[block_example_example_configurable_text][region]', -1, t('Configurable text block is disabled in first sidebar successfully verified.') );
-
- // Verify that blocks are not shown
- $this->drupalGet('/');
- $this->assertNoRaw( t('Title of first block (example_configurable_text)'), t('Block configurable test not found.'));
- $this->assertNoRaw( t('Title of second block (example_empty)'), t('Block empty not found.'));
-
- // Enable the Configurable text block and verify
- $this->drupalPost('admin/structure/block', array('blocks[block_example_example_configurable_text][region]' => 'sidebar_first'), t('Save blocks'));
- $this->assertFieldByName('blocks[block_example_example_configurable_text][region]', 'sidebar_first', t('Configurable text block is enabled in first sidebar successfully verified.') );
-
- // Verify that blocks are there. Empty block will not be shown, because it is empty
- $this->drupalGet('/');
- $this->assertRaw( t('Title of first block (example_configurable_text)'), t('Block configurable text found.'));
-
- // Change content of configurable text block
- $string = $this->randomName();
- $this->drupalPost('admin/structure/block/manage/block_example/example_configurable_text/configure', array('block_example_string' => $string), t('Save block'));
-
- // Verify that new content is shown
- $this->drupalGet('/');
- $this->assertRaw( $string, t('Content of configurable text block successfully verified.'));
-
- // Verify the view_alter hook implementation. Change content of our block
- // to be 'magic string'
- $string = 'there is a magic string in content';
- $this->drupalPost('admin/structure/block/manage/block_example/example_configurable_text/configure', array('block_example_string' => $string), t('Save block'));
-
- // Verify that new content is shown and the title is uppercase
- $this->drupalGet('/');
- $this->assertRaw( $string, t('Content of configurable text block successfully verified.'));
- $this->assertText(t('Title of first block (example_configurable_text)'), t('hook_block_view_alter implementation successfully verified.'));
-
- // Verify that search block is at the bottom of the region.
-
- // Enable the search block on top of sidebar_first.
- $block_options = array(
- 'blocks[search_form][region]' => 'sidebar_first',
- 'blocks[search_form][weight]' => -9,
- );
- $this->drupalPost('admin/structure/block', $block_options, t('Save blocks'));
-
- // The first 'configure block' link should be from our configurable block,
- // the second from the Navigation menu, and the third (#2) from search block
- // if it was successfully pushed to the bottom.
- $this->drupalGet('/');
- $this->clickLink('Configure block', 2);
- $this->assertText(t("'@search' block", array('@search' => t('Search form'))), t('hook_block_info_alter successfully verified.') );
- }
-}
diff --git a/dbtng_example/dbtng_example.info b/dbtng_example/dbtng_example.info
deleted file mode 100644
index 7d7acb7..0000000
--- a/dbtng_example/dbtng_example.info
+++ /dev/null
@@ -1,6 +0,0 @@
-
-name = DBTNG example
-description = An example module showing how use the database API: DBTNG.
-package = Example modules
-core = 7.x
-files[] = dbtng_example.test
diff --git a/dbtng_example/dbtng_example.install b/dbtng_example/dbtng_example.install
deleted file mode 100644
index 5f314b3..0000000
--- a/dbtng_example/dbtng_example.install
+++ /dev/null
@@ -1,115 +0,0 @@
-<?php
-
-/**
- * @file
- * Install, update and uninstall functions for the dbtng example module.
- */
-
-/**
- * Implements hook_install().
- *
- * In Drupal 7, there is no need to install schema using this hook, the schema
- * is already installed before this hook is called.
- *
- * We will create a default entry in the database.
- *
- * @see hook_install()
- */
-function dbtng_example_install() {
- // Outside of the .install file we would use drupal_write_record() to
- // populate the database, but it cannot be used here, so we'll use
- // db_insert().
-
- // Add a default entry.
- $fields = array(
- 'name' => 'John',
- 'surname' => 'Doe',
- 'age' => 0,
- );
- db_insert('dbtng_example')
- ->fields($fields)
- ->execute();
-
- // Add another entry.
- $fields = array(
- 'name' => 'John',
- 'surname' => 'Roe',
- 'age' => 100,
- 'uid' => 1,
- );
- db_insert('dbtng_example')
- ->fields($fields)
- ->execute();
-
-}
-
-/**
- * Implements hook_uninstall().
- *
- * As in hook_install, there is no need to uninstall schema, Drupal will do it
- * for us.
- *
- * @see hook_uninstall()
- */
-function dbtng_example_uninstall() {
-}
-
-
-/**
- * Implements hook_schema().
- *
- * Define the database tables used by this module.
- * Remember that the easiest way to create the code for hook_schema is with
- * the schema module:
- * @link http://drupal.org/project/schema @endlink
- *
- * @see hook_schema()
- */
-function dbtng_example_schema() {
-
- $schema['dbtng_example'] = array(
- 'description' => 'Stores example person entries for demonstration purposes.',
- 'fields' => array(
- 'pid' => array(
- 'type' => 'serial',
- 'not null' => TRUE,
- 'description' => 'Primary Key: Unique person ID.',
- ),
- 'uid' => array(
- 'type' => 'int',
- 'not null' => TRUE,
- 'default' => 0,
- 'description' => "Creator user's {users}.uid",
- ),
- 'name' => array(
- 'type' => 'varchar',
- 'length' => 255,
- 'not null' => TRUE,
- 'default' => '',
- 'description' => 'Name of the person.',
- ),
- 'surname' => array(
- 'type' => 'varchar',
- 'length' => 255,
- 'not null' => TRUE,
- 'default' => '',
- 'description' => 'Surname of the person.',
- ),
- 'age' => array(
- 'type' => 'int',
- 'not null' => TRUE,
- 'default' => 0,
- 'size' => 'tiny',
- 'description' => 'The age of the person in years.',
- )
- ),
- 'primary key' => array('pid'),
- 'indexes' => array(
- 'name' => array('name'),
- 'surname' => array('surname'),
- 'age' => array('age'),
- ),
- );
-
- return $schema;
-}
diff --git a/dbtng_example/dbtng_example.module b/dbtng_example/dbtng_example.module
deleted file mode 100644
index 6aee7ac..0000000
--- a/dbtng_example/dbtng_example.module
+++ /dev/null
@@ -1,571 +0,0 @@
-<?php
-
-/**
- * @file
- * This is an example outlining how a module can make use of the new DBTNG
- * database API in Drupal 7.
- *
- * @todo Demonstrate transaction usage.
- *
- * General documentation is available at
- * @link database Database abstraction layer documentation @endlink and
- * at @link http://drupal.org/node/310069 @endlink.
- *
- */
-
-/**
- * @defgroup database_examples Database Examples
- * @{
- * These examples show basic database examples, including DBTNG.
- *
- * General documentation is available at
- * @link database Database abstraction layer documentation @endlink and
- * at @link http://drupal.org/node/310069 @endlink.
- *
- * The several examples here demonstrate basic database usage.
- *
- * In Drupal 6, the recommended method to save or update an entry in the
- * database was drupal_write_record() or db_query().
- *
- * In Drupal 7 and forward, the usage of db_query()
- * for INSERT, UPDATE, or DELETE is deprecated, because it is
- * database-dependent. Instead specific functions are provided to perform these
- * operations: db_insert(), db_update(), and db_delete() do the job now.
- * (Note that drupal_write_record() is also deprecated.)
- *
- * db_insert() example:
- * @code
- * // INSERT INTO {dbtng_example} (name, surname) VALUES('John, 'Doe')
- * db_insert('dbtng_example')
- * ->fields(array('name' => 'John', 'surname' => 'Doe'))
- * ->execute();
- * @endcode
- *
- * db_update() example:
- * @code
- * // UPDATE {dbtng_example} SET name = 'Jane' WHERE name = 'John'
- * db_update('dbtng_example')
- * ->fields(array('name' => 'Jane'))
- * ->condition('name', 'John')
- * ->execute();
- * @endcode
- *
- * db_delete() example:
- * @code
- * // DELETE FROM {dbtng_example} WHERE name = 'Jane'
- * db_delete('dbtng_example')
- * ->condition('name', 'Jane')
- * ->execute();
- * @endcode
- *
- * See @link database Database Abstraction Layer @endlink
- * @see db_insert()
- * @see db_update()
- * @see db_delete()
- * @see drupal_write_record()
- * @}
-*/
-
-/**
- * Save an entry in the database.
- *
- * The underlying DBTNG function is db_insert().
- *
- * In Drupal 6, this would have been:
- * @code
- * db_query(
- * "INSERT INTO {dbtng_example} (name, surname, age)
- * VALUES ('%s', '%s', '%d')",
- * $entry['name'],
- * $entry['surname'],
- * $entry['age']
- * );
- * @endcode
- *
- * Exception handling is shown in this example. It could be simplified
- * without the try/catch blocks, but since an insert will throw an exception
- * and terminate your application if the exception is not handled, it is best
- * to employ try/catch.
- *
- * @param $entry
- * An array containing all the fields of the database record.
- *
- * @ingroup database_examples
- * @see db_insert()
- */
-function dbtng_example_entry_insert($entry) {
- $return_value = NULL;
- try {
- $return_value = db_insert('dbtng_example')
- ->fields($entry)
- ->execute();
- }
- catch (Exception $e) {
- drupal_set_message(t('db_insert failed. Message = %message, query= %query',
- array('%message' => $e->getMessage(), '%query' => $e->query_string)), 'error');
- }
- return $return_value;
-}
-
-/**
- * Update an entry in the database.
- *
- * The former, deprecated techniques used db_query() or drupal_write_record():
- * @code
- * drupal_write_record('dbtng_example', $entry, $entry['pid']);
- * @endcode
- *
- * @code
- * db_query(
- * "UPDATE {dbtng_example}
- * SET name = '%s', surname = '%s', age = '%d'
- * WHERE pid = %d",
- * $entry['pid']
- * );
- * @endcode
- *
- * @param $entry
- * An array containing all the fields of the item to be updated.
- *
- * @ingroup database_examples
- * @see db_update()
- */
-function dbtng_example_entry_update($entry) {
- try {
- // db_update()...->execute() returns the number of rows updated.
- $count = db_update('dbtng_example')
- ->fields($entry)
- ->condition('pid', $entry['pid'])
- ->execute();
- }
- catch(Exception $e) {
- drupal_set_message(t('db_update failed. Message = %message, query= %query',
- array('%message' => $e->getMessage(), '%query' => $e->query_string)), 'error');
- }
- return $count;
-}
-
-/**
- * Delete an entry from the database.
- *
- * The usage of db_query is deprecated except for static queries.
- * Formerly, a deletion might have been accomplished like this:
- * @code
- * db_query("DELETE FROM {dbtng_example} WHERE pid = %d", $entry['pid]);
- * @endcode
- *
- * @param $entry
- * An array containing at least the person identifier 'pid' element of the
- * entry to delete.
- *
- * @ingroup database_examples
- * @see db_delete()
- */
-function dbtng_example_entry_delete($entry) {
- db_delete('dbtng_example')
- ->condition('pid', $entry['pid'])
- ->execute();
-
-}
-
-
-/**
- * Read from the database using a filter array.
- *
- * In Drupal 6, the standard function to perform reads was db_query(), and
- * for static queries, it still is.
- *
- * db_query() used an SQL query with placeholders and arguments as parameters.
- *
- * @code
- * // Old way
- * $query = "SELECT * FROM {dbtng_example} n WHERE n.uid = %d AND name = '%s'";
- * $result = db_query($query, $uid, $name);
- * @endcode
- *
- * Drupal 7 DBTNG provides an abstracted interface that will work with a wide
- * variety of database engines.
- *
- * db_query() is deprecated except when doing a static query. The following is
- * perfectly acceptable in Drupal 7. See
- * @link http://drupal.org/node/310072 the handbook page on static queries @endlink
- *
- * @code
- * // SELECT * FROM {dbtng_example} WHERE uid = 0 AND name = 'John'
- * db_query(
- * "SELECT * FROM {dbtng_example} WHERE uid = :uid and name = :name",
- * array(':uid' => 0, ':name' => 'John')
- * )->execute();
- * @endcode
- *
- * But for more dynamic queries, Drupal provides the db_select()
- * API method, so there are several ways to perform the same SQL query.
- * See the @link http://drupal.org/node/310075 handbook page on dynamic queries. @endlink
- *
- * @code
- * // SELECT * FROM {dbtng_example} WHERE uid = 0 AND name = 'John'
- * db_select('dbtng_example')
- * ->fields('dbtng_example')
- * ->condition('uid', 0)
- * ->condition('name', 'John')
- * ->execute();
- * @endcode
- *
- * Here is db_select with named placeholders:
- * @code
- * // SELECT * FROM {dbtng_example} WHERE uid = 0 AND name = 'John'
- * $arguments = array(':name' => 'John', ':uid' => 0);
- * db_select('dbtng_example')
- * ->fields('dbtng_example')
- * ->where('uid = :uid AND name = :name', $arguments)
- * ->execute();
- * @endcode
- *
- * Conditions are stacked and evaluated as AND and OR depending on the type of
- * query. For more information, read the conditional queries handbook page at:
- * http://drupal.org/node/310086
- *
- * The condition argument is an 'equal' evaluation by default, but this can be
- * altered:
- * @code
- * // SELECT * FROM {dbtng_example} WHERE age > 18
- * db_select('dbtng_example')
- * ->fields('dbtng_example')
- * ->condition('age', 18, '>')
- * ->execute();
- * @endcode
- *
- * @param $entry
- * An array containing all the fields used to search the entries in the table.
- * @return
- * An object containing the loaded entries if found.
- *
- * @ingroup database_examples
- * @see db_select()
- * @see db_query()
- * @see http://drupal.org/node/310072
- * @see http://drupal.org/node/310075
- *
- */
-function dbtng_example_entry_load($entry = array()) {
- // Read all fields from the dbtng_example table.
- $select = db_select('dbtng_example', 'example');
- $select->fields('example');
-
- // Add each field and value as a condition to this query.
- foreach ($entry as $field => $value) {
- $select->condition($field, $value);
- }
- // Return the result in object format.
- return $select->execute()->fetchAll();
-}
-
-/**
- * Render a filtered list of entries in the database.
- *
- * DBTNG also helps processing queries that return several rows, providing the
- * found objects in the same query execution call.
- *
- * This function queries the database using a JOIN between users table and the
- * example entries, to provide the username that created the entry, and creates
- * a table with the results, processing each row.
- *
- * SELECT
- * e.pid as pid, e.name as name, e.surname as surname, e.age as age
- * u.name as username
- * FROM
- * {dbtng_example} e
- * JOIN
- * users u ON e.uid = u.uid
- * WHERE
- * e.name = 'John' AND e.age > 18
- *
- * @see db_select()
- * @seeW http://drupal.org/node/310075
- */
-function dbtng_example_advanced_list() {
- $output = '';
-
- $select = db_select('dbtng_example', 'e');
- // Join the users table, so we can get the entry creator's username.
- $select->join('users', 'u', 'e.uid = u.uid');
- // Select these specific fields for the output.
- $select->addField('e', 'pid');
- $select->addField('u', 'name', 'username');
- $select->addField('e', 'name');
- $select->addField('e', 'surname');
- $select->addField('e', 'age');
- // Filter only persons named "John".
- $select->condition('e.name', 'John');
- // Filter only persons older than 18 years.
- $select->condition('e.age', 18, '>');
- // Make sure we only get items 0-49, for scalability reasons.
- $select->range(0, 50);
-
- // Now, loop all these entries and show them in a table. Note that there is no
- // db_fetch_* object or array function being called here. Also note that the
- // following line could have been written as
- // $entries = $select->execute()->fetchAll() which would return each selected
- // record as an object instead of an array.
- $entries = $select->execute()->fetchAll(PDO::FETCH_ASSOC);
- if (!empty($entries)) {
- $rows = array();
- foreach ($entries as $entry) {
- // Sanitize the data before handing it off to the theme layer.
- $rows[] = array_map('check_plain', $entry);
- }
- // Make a table for them.
- $header = array(t('Id'), t('Created by'), t('Name'), t('Surname'), t('Age'));
- $output .= theme('table', array('header' => $header, 'rows' => $rows));
- }
- else {
- drupal_set_message(t('No entries meet the filter criteria (Name = "John" and Age > 18).'));
- }
- return $output;
-}
-
-//// Helper functions ////
-
-/**
- * Implements hook_help().
- *
- * Show some help on each form provided by this module.
- */
-function dbtng_example_help($path) {
- $output = '';
- switch ($path) {
- case 'examples/dbtng':
- $output = t('Generate a list of all entries in the database. There is no filter in the query.');
- break;
- case 'examples/dbtng/advanced':
- $output = t('A more complex list of entries in the database. ');
- $output .= t('Only the entries with name = "John" and age older than 18 years are shown, the username of the person who created the entry is also shown.');
- break;
- case 'examples/dbtng/update':
- $output = t('Demonstrates a database update operation.');
- break;
- case 'examples/dbtng/add':
- $output = t('Add an entry to the dbtng_example table.');
- break;
- }
- return $output;
-}
-
-/**
- * Implements hook_menu().
- *
- * Set up calls to drupal_get_form() for all our example cases.
- */
-function dbtng_example_menu() {
- $items = array();
-
- $items['examples/dbtng'] = array(
- 'title' => 'DBTNG Example',
- 'page callback' => 'dbtng_example_list',
- 'access callback' => TRUE,
- );
- $items['examples/dbtng/list'] = array(
- 'title' => 'List',
- 'type' => MENU_DEFAULT_LOCAL_TASK,
- 'weight' => -10,
- );
- $items['examples/dbtng/add'] = array(
- 'title' => 'Add entry',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array('dbtng_example_form_add'),
- 'access callback' => TRUE,
- 'type' => MENU_LOCAL_TASK,
- 'weight' => -9,
- );
- $items['examples/dbtng/update'] = array(
- 'title' => 'Update entry',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array('dbtng_example_form_update'),
- 'type' => MENU_LOCAL_TASK,
- 'access callback' => TRUE,
- 'weight' => -5,
- );
- $items['examples/dbtng/advanced'] = array(
- 'title' => 'Advanced list',
- 'page callback' => 'dbtng_example_advanced_list',
- 'access callback' => TRUE,
- 'type' => MENU_LOCAL_TASK,
- );
-
- return $items;
-}
-
-/**
- * Render a list of entries in the database.
- */
-function dbtng_example_list() {
- $output = '';
-
- // Get all entries in the dbtng_example table.
- if ($entries = dbtng_example_entry_load()) {
- $rows = array();
- foreach ($entries as $entry) {
- // Sanitize the data before handing it off to the theme layer.
- $rows[] = array_map('check_plain', (array) $entry);
- }
- // Make a table for them.
- $header = array(t('Id'), t('uid'), t('Name'), t('Surname'), t('Age'));
- $output .= theme('table', array('header' => $header, 'rows' => $rows));
- }
- else {
- drupal_set_message(t('No entries have been added yet.'));
- }
- return $output;
-}
-
-/**
- * Prepare a simple form to add an entry, with all the interesting fields.
- */
-function dbtng_example_form_add($form, &$form_state) {
- $form = array();
-
- $form['add'] = array(
- '#type' => 'fieldset',
- '#title' => t('Add a person entry'),
- );
- $form['add']['name'] = array(
- '#type' => 'textfield',
- '#title' => t('Name'),
- '#size' => 15,
- );
- $form['add']['surname'] = array(
- '#type' => 'textfield',
- '#title' => t('Surname'),
- '#size' => 15,
- );
- $form['add']['age'] = array(
- '#type' => 'textfield',
- '#title' => t('Age'),
- '#size' => 5,
- '#description' => t("Values greater than 127 will cause an exception. Try it - it's a great example why exception handling is needed with DTBNG."),
- );
- $form['add']['submit'] = array(
- '#type' => 'submit',
- '#value' => t('Add'),
- );
-
- return $form;
-}
-
-/**
- * Submit handler for 'add entry' form.
- */
-function dbtng_example_form_add_submit($form, $form_state){
- global $user;
-
- // Save the submitted entry.
- $entry = array(
- 'name' => $form_state['values']['name'],
- 'surname' => $form_state['values']['surname'],
- 'age' => $form_state['values']['age'],
- 'uid' => $user->uid,
- );
- $return = dbtng_example_entry_insert($entry);
- if ($return) {
- drupal_set_message(t("Created entry @entry", array('@entry' => print_r($entry, TRUE))));
- }
-}
-
-/**
- * Sample UI to update a record.
- */
-function dbtng_example_form_update($form, &$form_state) {
- $form = array(
- '#prefix' => '<div id="updateform">',
- '#suffix' => '</div>',
- );
-
- $entries = dbtng_example_entry_load();
- $keyed_entries = array();
- if (empty($entries)) {
- $form['no_values'] = array(
- '#value' => t("No entries exist in the table dbtng_example table."),
- );
- return $form;
- }
-
- foreach ($entries as $entry) {
- $options[$entry->pid] = t("@pid: @name @surname (@age)", array('@pid' => $entry->pid, '@name' => $entry->name, '@surname' => $entry->surname, '@age' => $entry->age));
- $keyed_entries[$entry->pid] = $entry;
- }
- $default_entry = !empty($form_state['values']['pid']) ? $keyed_entries[$form_state['values']['pid']] : $entries[0];
-
- $form_state['entries'] = $keyed_entries;
-
- $form['pid'] = array(
- '#type' => 'select',
- '#options' => $options,
- '#title' => t('Choose entry to update'),
- '#default_value' => $default_entry->pid,
- '#ajax' => array(
- 'wrapper' => 'updateform',
- 'callback' => 'dbtng_example_form_update_callback',
- ),
- );
-
- $form['name'] = array(
- '#type' => 'textfield',
- '#title' => t('Updated first name'),
- '#size' => 15,
- '#default_value' => $default_entry->name,
- );
-
- $form['surname'] = array(
- '#type' => 'textfield',
- '#title' => t('Updated last name'),
- '#size' => 15,
- '#default_value' => $default_entry->surname,
- );
- $form['age'] = array(
- '#type' => 'textfield',
- '#title' => t('Updated age'),
- '#size' => 4,
- '#default_value' => $default_entry->age,
- '#description' => t("Values greater than 127 will cause an exception"),
- );
-
- $form['submit'] = array(
- '#type' => 'submit',
- '#value' => t('Update'),
- );
- return $form;
-}
-
-/**
- * AJAX callback handler for the pid select.
- *
- * When the pid changes, populates the defaults from the database in the form.
- */
-function dbtng_example_form_update_callback($form, $form_state) {
- $entry = $form_state['entries'][$form_state['values']['pid']];
- // Setting the #value of items is the only way I was able to figure out
- // to get replaced defaults on these items. #default_value will not do it
- // and shouldn't.
- foreach (array('name', 'surname', 'age') as $item) {
- $form[$item]['#value'] = $entry->$item;
- }
- return $form;
-}
-
-/**
- * Submit handler for 'update entry' form.
- */
-function dbtng_example_form_update_submit($form, $form_state){
- global $user;
-
- // Save the submitted entry.
- $entry = array(
- 'pid' => $form_state['values']['pid'],
- 'name' => $form_state['values']['name'],
- 'surname' => $form_state['values']['surname'],
- 'age' => $form_state['values']['age'],
- 'uid' => $user->uid,
- );
- $count = dbtng_example_entry_update($entry);
- drupal_set_message(t("Updated entry @entry (@count row updated)", array('@count' => $count, '@entry' => print_r($entry, TRUE))));
-}
diff --git a/dbtng_example/dbtng_example.test b/dbtng_example/dbtng_example.test
deleted file mode 100644
index ab732d3..0000000
--- a/dbtng_example/dbtng_example.test
+++ /dev/null
@@ -1,181 +0,0 @@
-<?php
-
-/**
- * @file
- * test file for dbtng_example module.
- */
-
-/**
- * Default test case for the dbtng_example module.
- */
-class DBTNGExampleUnitTestCase extends DrupalWebTestCase {
-
- public static function getInfo() {
- return array(
- 'name' => 'DBTNG example unit and UI tests',
- 'description' => 'Various unit tests on the dbtng example module.' ,
- 'group' => 'Examples',
- );
- }
-
- function setUp() {
- parent::setUp('dbtng_example');
- }
-
- /**
- * Test default module installation, two entries in the database table.
- */
- function testInstall() {
- $result = dbtng_example_entry_load();
- $this->assertEqual(
- count($result),
- 2,
- t('Found two entries in the table after installing the module.')
- );
- }
-
-
- /**
- * Test the UI.
- */
- function testUI() {
- // Test the basic list.
- $this->drupalGet('examples/dbtng');
- $this->assertPattern("/John[td\/<>\w]+Doe/", t("Text 'John Doe' found in table"));
-
- //Test the add tab.
- // Add the new entry.
- $this->drupalPost('examples/dbtng/add',
- array('name' => 'Some', 'surname' => 'Anonymous', 'age' => 33), t('Add'));
- // Now find the new entry.
- $this->drupalGet('examples/dbtng');
- $this->assertPattern("/Some[td\/<>\w]+Anonymous/", t("Text 'Some Anonymous' found in table"));
-
-
- // Try the update tab.
- // Find out the pid of our "anonymous" guy.
- $result = dbtng_example_entry_load(array('surname' => 'Anonymous'));
- $this->drupalGet("examples/dbtng");
- $this->assertEqual(
- count($result),
- 1,
- t('Found one entry in the table with surname = "Anonymous".')
- );
- $entry = $result[0];
- unset($entry->uid);
- $entry->name = 'NewFirstName';
- $this->drupalPost('examples/dbtng/update',
- (array)$entry, t('Update'));
- // Now find the new entry.
- $this->drupalGet('examples/dbtng');
- $this->assertPattern("/NewFirstName[td\/<>\w]+Anonymous/", t("Text 'NewFirstName Anonymous' found in table"));
-
- // Try the advanced tab.
- $this->drupalGet('examples/dbtng/advanced');
- $rows = $this->xpath("//*[@id='block-system-main']/div/table[1]/tbody/tr");
- $this->assertEqual(count($rows), 1, t("One row found in advanced view"));
- $this->assertFieldByXPath("//*[@id='block-system-main']/div/table[1]/tbody/tr/td[4]", "Roe", "Name 'Roe' Exists in advanced list");
- }
-
- /**
- * Test several combinations, adding entries, updating and deleting.
- */
- function testAPIExamples() {
- // Create a new entry.
- $entry = array(
- 'name' => 'James',
- 'surname' => 'Doe',
- 'age' => 23,
- );
- dbtng_example_entry_insert($entry);
-
- // Save another entry
- $entry = array(
- 'name' => 'Jane',
- 'surname' => 'NotDoe',
- 'age' => 19,
- );
- dbtng_example_entry_insert($entry);
-
- // Verify that 4 records are found in the database
- $result = dbtng_example_entry_load();
- $this->assertEqual(
- count($result),
- 4,
- t('Found a total of four entries in the table after creating two additional entries.')
- );
-
- // Verify 2 of these records have 'Doe' as surname
- $result = dbtng_example_entry_load(array('surname' => 'Doe'));
- $this->assertEqual(
- count($result),
- 2,
- t('Found two entries in the table with surname = "Doe".')
- );
-
- // Now find our not-Doe entry.
- $result = dbtng_example_entry_load(array('surname' => 'NotDoe'));
- $this->assertEqual(
- count($result),
- 1,
- t('Found one entry in the table with surname "NotDoe'));
- // Our NotDoe will be changed to "NowDoe".
- $entry = $result[0];
- $entry->surname = "NowDoe";
- dbtng_example_entry_update((array)$entry);
-
- $result = dbtng_example_entry_load(array('surname' => 'NowDoe'));
- $this->assertEqual(
- count($result),
- 1,
- t("Found renamed 'NowDoe' surname"));
-
- // Read only John Doe entry.
- $result = dbtng_example_entry_load(array('name' => 'John', 'surname' => 'Doe'));
- $this->assertEqual(
- count($result),
- 1,
- t('Found one entry for John Doe.')
- );
- // Get the entry
- $entry = (array) end($result);
- // Change age to 45
- $entry['age'] = 45;
- // Update entry in database
- dbtng_example_entry_update((array)$entry);
-
- // Find entries with age = 45
- // Read only John Doe entry.
- $result = dbtng_example_entry_load(array('surname' => 'NowDoe'));
- $this->assertEqual(
- count($result),
- 1,
- t('Found one entry with surname = Nowdoe.')
- );
-
- // Verify it is Jane NowDoe.
- $entry = (array) end($result);
- $this->assertEqual(
- $entry['name'],
- 'Jane',
- t('The name Jane is found in the entry')
- );
- $this->assertEqual(
- $entry['surname'],
- 'NowDoe',
- t('The surname NowDoe is found in the entry')
- );
-
- // Delete the entry.
- dbtng_example_entry_delete($entry);
-
- // Verify that now there are only 3 records
- $result = dbtng_example_entry_load();
- $this->assertEqual(
- count($result),
- 3,
- t('Found only three records, a record was deleted.')
- );
- }
-}
-
diff --git a/email_example/CHANGELOG.txt b/email_example/CHANGELOG.txt
deleted file mode 100755
index 0e9bee8..0000000
--- a/email_example/CHANGELOG.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-
-#730984 by rfay: Email example (D7) needs to check_plain() on user text. \ No newline at end of file
diff --git a/email_example/email_example.info b/email_example/email_example.info
deleted file mode 100644
index 4f19e4e..0000000
--- a/email_example/email_example.info
+++ /dev/null
@@ -1,6 +0,0 @@
-
-name = E-mail Example
-description = Demonstrate Drupal's e-mail APIs.
-package = Example modules
-core = 7.x
-files[] = email_example.test
diff --git a/email_example/email_example.module b/email_example/email_example.module
deleted file mode 100644
index e5ab92a..0000000
--- a/email_example/email_example.module
+++ /dev/null
@@ -1,201 +0,0 @@
-<?php
-
-/**
- * @file
- * Example of how to use Drupal's mail API.
- *
- * This example module provides two different examples of the Drupal email API.
- * - defines a simple contact form and shows how to use drupal_mail()
- * to send an e-mail (defined in hook_mail()) when the form is submitted.
- * - shows how modules can alter emails defined by other Drupal modules or
- * Core using hook_mail_alter by attaching a custom signature before
- * they are sent.
- */
-
-/**
- * Implement hook_mail().
- *
- * This hook defines a list of possible e-mail templates that this module can
- * send. Each e-mail is given a unique identifier, or 'key'.
- *
- * $message comes in with some standard properties already set: 'to' address,
- * 'from' address, and a set of default 'headers' from drupal_mail(). The goal
- * of hook_mail() is to set the message's 'subject' and 'body' properties, as
- * well as make any adjustments to the headers that are necessary.
- *
- * The $params argument is an array which can hold any additional data required
- * to build the mail subject and body; for example, user-entered form data, or
- * some context information as to where the mail request came from.
- *
- * Note that hook_mail() is not actually a hook. It is only called for a single
- * module, the module named in the first argument of drupal_mail(). So it's
- * a callback of a type, but not a hook.
- */
-function email_example_mail($key, &$message, $params) {
- global $user;
-
- // Each message is associated with a language, which may or may not be the
- // current user's selected language, depending on the type of e-mail being
- // sent. This $options array is used later in the t() calls for subject
- // and body to ensure the proper translation takes effect.
- $options = array(
- 'langcode' => $message['language']->language,
- );
-
- switch ($key) {
- // Send a simple message from the contact form.
- case 'contact_message':
- $message['subject'] = t('E-mail sent from @site-name', array('@site-name' => variable_get('site_name', 'Drupal')), $options);
- // Note that the message body is an array, not a string.
- $message['body'][] = t('@name sent you the following message:', array('@name' => $user->name), $options);
- // Because this is just user-entered text, we do not need to translate it.
-
- // Since user-entered text may have unintentional HTML entities in it like
- // '<' or '>', we need to make sure these entities are properly escaped,
- // as the body will later be transformed from HTML to text, meaning
- // that a normal use of '<' will result in truncation of the message.
- $message['body'][] = check_plain($params['message']);
- break;
- }
-}
-
-/**
- * Send an e-mail.
- *
- * @param $form_values
- * An array of values from the contact form fields that were submitted.
- * There are just two relevant items: $form_values['email'] and
- * $form_values['message'].
- */
-function email_example_mail_send($form_values) {
- // All system mails need to specify the module and template key (mirrored from
- // hook_mail()) that the message they want to send comes from.
- $module = 'email_example';
- $key = 'contact_message';
-
- // Specify 'to' and 'from' addresses.
- $to = $form_values['email'];
- $from = variable_get('site_mail', 'admin@example.com');
-
- // "params" loads in additional context for email content completion in
- // hook_mail(). In this case, we want to pass in the values the user entered
- // into the form, which include the message body in $form_values['message'].
- $params = $form_values;
-
- // The language of the e-mail. This will one of three values:
- // * user_preferred_language(): Used for sending mail to a particular website
- // user, so that the mail appears in their preferred language.
- // * global $language: Used when sending a mail back to the user currently
- // viewing the site. This will send it in the language they're currently
- // using.
- // * language_default(): Used when sending mail to a pre-existing, 'neutral'
- // address, such as the system e-mail address, or when you're unsure of the
- // language preferences of the intended recipient.
- //
- // Since in our case, we are sending a message to a random e-mail address that
- // is not necessarily tied to a user account, we will use the site's default
- // language.
- $language = language_default();
-
- // Whether or not to automatically send the mail when drupal_mail() is
- // called. This defaults to TRUE, and is normally what you want unless you
- // need to do additional processing before drupal_mail_send() is called.
- $send = TRUE;
- // Send the mail, and check for success. Note that this does not guarantee
- // message delivery; only that there were no PHP-related issues encountered
- // while sending.
- $result = drupal_mail($module, $key, $to, $language, $params, $from, $send);
- if ($result['result'] == TRUE) {
- drupal_set_message(t('Your message has been sent.'));
- }
- else {
- drupal_set_message(t('There was a problem sending your message and it was not sent.'), 'error');
- }
-
-}
-
-/**
- * Implement hook_mail_alter().
- *
- * This function is not required to send an email using Drupal's mail system.
- *
- * Hook_mail_alter() provides an interface to alter any aspect of email sent by
- * Drupal. You can use this hook to add a common site footer to all outgoing
- * email, add extra header fields, and/or modify the email in anyway. HTML-izing
- * the outgoing email is one possibility.
- */
-function email_example_mail_alter(&$message) {
- // For the purpose of this example, modify all the outgoing messages and
- // attach a site signature. The signature will be translated to the language
- // in which message was built.
- $options = array(
- 'langcode' => $message['language']->language,
- );
-
- $signature = t("\n--\nMail altered by email_example module.", array(), $options);
- if (is_array($message['body'])) {
- $message['body'][] = $signature;
- }
- else { // Some modules use the body as a string, erroneously.
- $message['body'] .= $signature;
- }
-}
-
-///// Supporting functions ////
-
-/**
- * Implement hook_menu().
- *
- * Set up a page with an e-mail contact form on it.
- */
-function email_example_menu() {
- $items['example/email_example'] = array(
- 'title' => 'E-mail Example: contact form',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array('email_example_form'),
- 'access arguments' => array('access content'),
- );
-
- return $items;
-}
-
-/**
- * The contact form.
- */
-function email_example_form() {
- $form['intro'] = array(
- '#markup' => t('Use this form to send a message to an e-mail address. No spamming!'),
- );
- $form['email'] = array(
- '#type' => 'textfield',
- '#title' => t('E-mail address'),
- '#required' => TRUE,
- );
- $form['message'] = array(
- '#type' => 'textarea',
- '#title' => t('Message'),
- '#required' => TRUE,
- );
- $form['submit'] = array(
- '#type' => 'submit',
- '#value' => t('Submit'),
- );
-
- return $form;
-}
-
-/**
- * Form validation logic for the contact form.
- */
-function email_example_form_validate($form, &$form_state) {
- if (!valid_email_address($form_state['values']['email'])) {
- form_set_error('email', t('That e-mail address is not valid.'));
- }
-}
-
-/**
- * Form submission logic for the contact form.
- */
-function email_example_form_submit($form, &$form_state) {
- email_example_mail_send($form_state['values']);
-}
diff --git a/email_example/email_example.test b/email_example/email_example.test
deleted file mode 100644
index b673670..0000000
--- a/email_example/email_example.test
+++ /dev/null
@@ -1,98 +0,0 @@
-<?php
-
-/**
- * @file
- * Simpletest case for email_example module.
- *
- * Verify example module functionality.
- */
-
-/**
- * Functionality tests for email example module.
- */
-class EmailExampleTestCase extends DrupalWebTestCase {
-
- public static function getInfo() {
- return array(
- 'name' => 'Email example',
- 'description' => 'Verify the email submission using the contact form.',
- 'group' => 'Examples',
- );
- }
-
- function setUp() {
- // Enable the email_example module.
- parent::setUp('email_example');
- }
-
- /**
- * Verify the functionality of the example module.
- */
- function testContactForm() {
- // Create and login user.
- $account = $this->drupalCreateUser();
- $this->drupalLogin($account);
-
- // Set default language for t() translations
- $t_options = array(
- 'langcode' => language_default()->language,
- );
-
- // First try to send to an invalid email address.
- $email_options = array(
- 'email' => $this->randomName(),
- 'message' => $this->randomName(128),
- );
- $result = $this->drupalPost('example/email_example', $email_options, t('Submit'));
-
- // Verify that email address is invalid and email was not sent.
- $this->assertText(t('That e-mail address is not valid.'), t('Options were validated and form submitted.'));
- $this->assertTrue(!count($this->drupalGetMails()), t('No email was sent.'));
-
- // Now try with a valid email address.
- $email_options['email'] = $this->randomName() . '@' . $this->randomName() . '.drupal';
- $result = $this->drupalPost('example/email_example', $email_options, t('Submit'));
-
- // Verify that email address is valid and email was sent.
- // $this->assertText(t('Your message has been sent.'), t('Options were validated and form submitted.'));
- $this->assertTrue(count($this->drupalGetMails()), t('An email has been sent.'));
-
- // Validate sent email.
- $email = $this->drupalGetMails();
- // Grab the first entry.
- $email = $email[0];
-
- // Verify email recipient.
- $this->assertEqual(
- $email['to'],
- $email_options['email'],
- t('Email recipient successfully verified.')
- );
-
- // Verify email subject.
- $this->assertEqual(
- $email['subject'],
- t('E-mail sent from @site-name', array('@site-name' => variable_get('site_name', 'Drupal')), $t_options),
- t('Email subject successfully verified.')
- );
-
- // Verify email body.
- $this->assertTrue(
- strstr(
- $email['body'],
- t('@name sent you the following message:', array('@name' => $account->name), $t_options)
- ),
- t('Email body successfully verified.')
- );
-
- // Verify that signature is attached.
- $this->assertTrue(
- strstr(
- $email['body'],
- t("--\nMail altered by email_example module.", array(), $t_options)
- ),
- t('Email signature successfully verified.')
- );
- }
-}
-
diff --git a/examples.index.php b/examples.index.php
deleted file mode 100644
index beab81a..0000000
--- a/examples.index.php
+++ /dev/null
@@ -1,31 +0,0 @@
-<?php
-
-/**
- * @file
- * Example modules
- *
- * - @link action_example.module Creating actions @endlink
- * - @link ajax_example.module Using AJAX forms @endlink
- * - @link batch_example.module Using the batch API @endlink
- * - @link block_example.module Defining blocks @endlink
- * - @link dbtng_example.module Database examples (DBTNG) @endlink
- * - @link email_example.module Sending e-mail @endlink
- * - @link field_example.module Defining fields in the field API @endlink
- * - @link file_example.module Demonstrates file handling @endlink
- * - @link filter_example.module Defining an input filter @endlink
- * - @link form_example.module Form API examples, including multistep forms @endlink
- * - @link image_exmaple.module Demonstrates image handling with styles and effects @endlink
- * - @link js_example.module Javascript examples @endlink
- * - @link menu_example.module Menu API examples @endlink
- * - @link nodeapi_example.module Node API demonstrations showing how a separate module can change the behavior of a node @endlink
- * - @link node_access_example.module Define custom node access fules using node access hooks @endlink
- * - @link node_example.module Creating custom node types, with fields @endlink
- * - @link page_example.module Creating a custom page @endlink
- * - @link queue_example.module Using the Queue API @endlink
- * - @link render_example.module Demonstrates the render API @endlink
- * - @link simpletest_example.module Writing tests for Drupal @endlink
- * - @link token_example.module Using tokens @endlink
- * - @link trigger_example.module Implementing triggers and actions @endlink
- * - @link vertical_tabs_example.module Using vertical tabs @endlink
- * - @link xmlrpc_example.module XML-RPC example @endlink
- */ \ No newline at end of file
diff --git a/field_example/field_example.css b/field_example/field_example.css
deleted file mode 100644
index 00a2a51..0000000
--- a/field_example/field_example.css
+++ /dev/null
@@ -1,9 +0,0 @@
-
-/**
- * @file
- * CSS for Field Example.
- */
-div.form-item table .form-type-textfield,
-div.form-item table .form-type-textfield * {
- display: inline-block;
-} \ No newline at end of file
diff --git a/field_example/field_example.info b/field_example/field_example.info
deleted file mode 100644
index bf8c96f..0000000
--- a/field_example/field_example.info
+++ /dev/null
@@ -1,6 +0,0 @@
-
-name = Field Example
-description = A trivial implementation of a field to show the Field API
-package = Example modules
-core = 7.x
-files[] = field_example.test
diff --git a/field_example/field_example.install b/field_example/field_example.install
deleted file mode 100644
index e6917b7..0000000
--- a/field_example/field_example.install
+++ /dev/null
@@ -1,31 +0,0 @@
-<?php
-
-/**
- * @file
- * Install/Update/Uninstall functions for field_example module
- */
-
-/**
- * Implements hook_field_schema().
- *
- * This defines the actual database schema of the field, using the format
- * used by the Schema API.
- *
- * The actual data we store here is just one 7-character element, even
- * though the widget presents the three portions separately.
- *
- * @see hook_field_schema()
- * @link schemaapi Schema API @endlink
- */
-function field_example_field_schema($field) {
- $columns = array(
- 'rgb' => array('type' => 'varchar', 'length' => 7, 'not null' => FALSE),
- );
- $indexes = array(
- 'rgb' => array('rgb'),
- );
- return array(
- 'columns' => $columns,
- 'indexes' => $indexes,
- );
-}
diff --git a/field_example/field_example.js b/field_example/field_example.js
deleted file mode 100644
index a03454f..0000000
--- a/field_example/field_example.js
+++ /dev/null
@@ -1,26 +0,0 @@
-
-/**
- * @file
- * Javascript for Field Example.
- */
-
-/**
- * Provide a farbtastic colorpicker for the fancier widget.
- */
-(function ($) {
- Drupal.behaviors.field_example_colorpicker = {
- attach: function(context) {
- $(".edit-field-example-colorpicker").live("focus", function(event) {
- var edit_field = this;
- var picker = $(this).closest('tr').find(".field-example-colorpicker");
-
- // Hide all color pickers except this one.
- $(".field-example-colorpicker").hide();
- $(picker).show();
- $.farbtastic(picker, function(color) {
- edit_field.value = color;
- }).setColor(edit_field.value);
- });
- }
- }
-})(jQuery);
diff --git a/field_example/field_example.module b/field_example/field_example.module
deleted file mode 100644
index 6451d0e..0000000
--- a/field_example/field_example.module
+++ /dev/null
@@ -1,320 +0,0 @@
-<?php
-
-/**
- * @file
- * An example field using the Field API.
- *
- * This is updated from Barry Jaspan's presentation at Drupalcon Paris,
- * @link http://acquia.com/community/resources/acquia-tv/intro-field-api-module-developers Video Presentation @endlink
- *
- * Providing a field requires:
- * - Defining a field
- * - hook_field_info()
- * - hook_field_schema()
- * - hook_field_validate()
- * - hook_field_is_empty()
- *
- * - Defining a formatter for the field (the portion that outputs the field for
- * display)
- * - hook_field_formatter_info()
- * - hook_field_formatter_view()
- *
- * - Defining a widget for the edit form
- * - hook_field_widget_info()
- * - hook_field_widget_form()
- *
- * *
- * See @link field_types Field Types API @endlink
- */
-
-/***************************************************************
- * Field Type API hooks
- ***************************************************************/
-
-/**
- * Implements hook_field_info().
- *
- * Provides the description of the field.
- */
-function field_example_field_info() {
- return array(
- 'field_example_rgb' => array(
- 'label' => t('Example Color RGB'),
- 'description' => t('Demonstrates a field composed of an RGB color.'),
- 'default_widget' => 'field_example_3text',
- 'default_formatter' => 'field_example_simple_text',
- ),
- );
-}
-
-/**
- * Implements hook_field_validate().
- *
- * Verifies that the RGB field as combined is valid
- * (6 hex digits with a # at the beginning).
- */
-function field_example_field_validate($entity_type, $entity, $field, $instance, $langcode, $items, &$errors) {
- foreach ($items as $delta => $item) {
- if (!empty($item['rgb'])) {
- if (! preg_match('@^#[0-9a-f]{6}$@', $item['rgb'])) {
- $errors[$field['field_name']][$langcode][$delta][] = array(
- 'error' => 'field_example_invalid',
- 'message' => t('Color must be in the HTML format #abcdef.'),
- );
- }
- }
- }
-}
-
-
-/**
- * Implements hook_field_is_empty().
- */
-function field_example_field_is_empty($item, $field) {
- return empty($item['rgb']);
-}
-
-/***********************************************************************
- * Field Type API: Formatter
- *
- * These are the api hooks that present formatted (themed) output to the
- * user.
- **********************************************************************/
-
-/**
- * Implements hook_field_formatter_info().
- */
-function field_example_field_formatter_info() {
- return array(
- // This formatter just displays the hex value in the color indicated.
- 'field_example_simple_text' => array(
- 'label' => t('Simple text-based formatter'),
- 'field types' => array('field_example_rgb'),
- ),
- // This formatter changes the background color of the content region.
- 'field_example_color_background' => array(
- 'label' => t('Change the background of the output text'),
- 'field types' => array('field_example_rgb'),
- ),
- );
-}
-
-/**
- * Implements hook_field_formatter_view().
- *
- * Two formatters are implemented.
- * - field_example_simple_text just outputs markup indicating the color that
- * was entered and uses an inline style to set the text color to that value.
- * - field_example_color_background does the same but also changes the
- * background color of div.region-content.
- */
-function field_example_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
- $element = array();
-
- switch ($display['type']) {
- // This formatter simply outputs the field as text and with a color.
- case 'field_example_simple_text':
- foreach ($items as $delta => $item) {
- $element[$delta]['#markup'] = '<p style="color: ' . $item['rgb'] . '">' . t('The color code in this field is @code', array('@code' => $item['rgb'])) . '</p>';
- }
- break;
-
- // This formatter adds css to the page changing the '.region-content' area's
- // background color. If there are many fields, the last one will win.
- case 'field_example_color_background':
- foreach ($items as $delta => $item) {
- drupal_add_css('div.region-content { background-color:' . $item['rgb'] . ';}', array('type' => 'inline') );
- $element[$delta]['#markup'] = '<p>' . t('The content area color has been changed to @code', array('@code' => $item['rgb'])) . '</p>';
- }
- break;
- }
-
- return $element;
-}
-
-
-/**************************************************************************
- * Field Type API: Widget
- *
- * The widget is the form element used to receive input from the user
- * when the field is being populated.
- **************************************************************************/
-
-/**
- * Implements hook_field_widget_info().
- *
- * Three widgets are provided.
- * - A simple text-only widget where the user enters the '#ffffff'.
- * - A 3-textfield widget that gathers the red, green, and blue values
- * separately.
- * - A farbtastic colorpicker widget that chooses the value graphically.
- */
-function field_example_field_widget_info() {
- return array(
- 'field_example_text' => array(
- 'label' => t('RGB value as #ffffff'),
- 'field types' => array('field_example_rgb'),
- ),
- 'field_example_3text' => array(
- 'label' => t('RGB text field'),
- 'field types' => array('field_example_rgb'),
- ),
- 'field_example_colorpicker' => array(
- 'label' => t('Color Picker'),
- 'field types' => array('field_example_rgb'),
- ),
- );
-}
-
-/**
- * Implements hook_field_widget_form().
- *
- * Three different forms are provided, for the three widget types.
- *
- * The 'field_example_colorpicker' and 'field_example_text' are essentially
- * the same, but field_example_colorpicker adds a javascript colorpicker
- * helper.
- *
- * field_example_3text displays three text fields, one each for red, green,
- * and blue. However, the field type defines a single text column,
- * rgb, which needs an HTML color spec. Define an element validate
- * handler that converts our r, g, and b fields into a simulated single
- * 'rgb' form element.
- */
-function field_example_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
- $value = isset($items[$delta]['rgb']) ? $items[$delta]['rgb'] : '';
- $element += array(
- '#delta' => $delta,
- );
- $element['rgb'] = array();
-
- switch ($instance['widget']['type']) {
-
- case 'field_example_colorpicker':
- $element['rgb'] += array(
- '#suffix' => '<div class="field-example-colorpicker"></div>',
- '#attributes' => array('class' => array('edit-field-example-colorpicker')),
- '#attached' => array(
- // Add Farbtastic color picker.
- 'library' => array(
- array('system', 'farbtastic'),
- ),
- // Add javascript to trigger the colorpicker.
- 'js' => array(drupal_get_path('module', 'field_example') . '/field_example.js'),
- ),
- );
-
- // DELIBERATE fall-through: From here on the field_example_text and
- // field_example_colorpicker are exactly the same.
- case 'field_example_text':
- $element['rgb'] += array(
- '#type' => 'textfield',
- '#default_value' => $value,
- // Allow a slightly larger size that the field length to allow for some
- // configurations where all characters won't fit in input field.
- '#size' => 7,
- '#maxlength' => 7,
- );
- break;
-
- case 'field_example_3text':
- // Convert rgb value into r, g, and b for #default_value.
- if (isset($items[$delta]['rgb'])) {
- preg_match_all('@..@', substr($items[$delta]['rgb'], 1), $match);
- }
- else {
- $match = array(array());
- }
-
- // A fieldset to hold the three text fields.
- $element += array(
- '#type' => 'fieldset',
- '#element_validate' => array('field_example_3text_validate'),
-
- // The following is set so that the validation function will be able
- // to access external value information which otherwise would be
- // unavailable.
- '#delta' => $delta,
- '#attached' => array(
- 'css' => array(drupal_get_path('module', 'field_example') . '/field_example.css'),
- ),
- );
-
- // Create a textfield for saturation values for Red, Green, and Blue.
- foreach (array('r' => t('Red'), 'g' => t('Green'), 'b' => t('Blue')) as $key => $title) {
- $element[$key] = array(
- '#type' => 'textfield',
- '#title' => $title,
- '#size' => 2,
- '#default_value' => array_shift($match[0]),
- '#attributes' => array('class' => array('rgb-entry')),
- // '#description' => t('The 2-digit hexadecimal representation of the @color saturation, like "a1" or "ff"', array('@color' => $title)),
- );
- }
- break;
-
- }
- return $element;
-}
-
-
-/**
- * Validate the individual fields and then convert them into a single HTML RGB
- * value as text.
- */
-function field_example_3text_validate($element, &$form_state) {
- $delta = $element['#delta']; // TODO: Isn't there a better way to find out which element?
- $field = $form_state['field'][$element['#field_name']][$element['#language']]['field'];
- $field_name = $field['field_name'];
- if (isset($form_state['values'][$field_name][$element['#language']][$delta])) {
- $values = $form_state['values'][$field_name][$element['#language']][$delta];
- foreach (array('r', 'g', 'b') as $colorfield) {
- $val = hexdec($values[$colorfield]);
- // If they left any empty, we'll set the value empty and quit.
- if (strlen($values[$colorfield]) == 0) {
- form_set_value($element, array('rgb' => NULL), $form_state);
- return;
- }
- // If they gave us anything that's not hex, reject it.
- if ( (strlen($values[$colorfield]) != 2) || $val < 0 || $val > 255) {
- form_error($element[$colorfield], t("Saturation value must be a 2-digit hexadecimal value between 00 and ff."));
- }
- }
-
- $value = sprintf('#%02s%02s%02s', $values['r'], $values['g'], $values['b']);
- form_set_value($element, array('rgb' => $value), $form_state);
- }
-}
-
-/**
- * Implements hook_field_widget_error().
- */
-function field_example_field_widget_error($element, $error, $form, &$form_state) {
- switch ($error['error']) {
- case 'field_example_invalid':
- form_error($element, $error['message']);
- break;
- }
-}
-
-
-/**
- * Implements hook_menu().
- *
- * Provides a simple user interface that tells the developer where to go.
- */
-function field_example_menu() {
- $items['examples/field_example'] = array(
- 'title' => 'Field Example',
- 'page callback' => '_field_example_page',
- 'access callback' => TRUE,
- );
- return $items;
-}
-
-/**
- * A simple page to explain to the developer what to do.
- */
-function _field_example_page() {
- return t("The Field Example provides a field composed of an HTML RGB value, like #ff00ff. To use it, add the field to a content type.");
-}
diff --git a/field_example/field_example.test b/field_example/field_example.test
deleted file mode 100644
index a138fbd..0000000
--- a/field_example/field_example.test
+++ /dev/null
@@ -1,144 +0,0 @@
-<?php
-
-/**
- * @file
- * Tests for Field Example.
- */
-
-class FieldExampleTest extends DrupalWebTestCase {
-
- public static function getInfo() {
- return array(
- 'name' => 'Field Example',
- 'description' => 'Create a content type with example_field_rgb fields, create a node, check for correct values.',
- 'group' => 'Examples',
- );
- }
- function setUp() {
- // Enable the email_example module.
- parent::setUp(array('field_ui', 'field_example'));
- }
-
- /**
- * Test basic functionality of the example field.
- *
- * - Creates a content type.
- * - Adds a single-valued field_example_rgb to it.
- * - Adds a multivalued field_example_rgb to it.
- * - Creates a node of the new type.
- * - Populates the single-valued field.
- * - Populates the multivalued field with two items.
- * - Tests the result.
- */
- function testExampleFieldBasic() {
- $content_type_friendly = $this->randomName(20);
- $content_type_machine = strtolower($this->randomName(10));
- $title = $this->randomName(20);
-
- // Create and login user.
- $account = $this->drupalCreateUser(array('administer content types'));
- $this->drupalLogin($account);
-
- $this->drupalGet('admin/structure/types');
-
- // Create the content type.
- $this->clickLink(t('Add content type'));
-
- $single_field_name_friendly = $this->randomName(20);
- $single_field_name_machine = strtolower($this->randomName(10));
-
- $edit = array (
- 'name' => $content_type_friendly,
- 'type' => $content_type_machine,
- );
- $this->drupalPost(NULL, $edit, t('Save and add fields'));
- $this->assertText(t('The content type @name has been added.', array('@name' => $content_type_friendly)));
-
- // Now add a singleton field.
- $edit = array (
- 'fields[_add_new_field][label]' => $single_field_name_friendly,
- 'fields[_add_new_field][field_name]' => $single_field_name_machine,
- 'fields[_add_new_field][type]' => 'field_example_rgb',
- 'fields[_add_new_field][widget_type]' => 'field_example_3text',
-
- );
- $this->drupalPost(NULL, $edit, t('Save'));
-
- // There are no settings for this, so just press the button.
- $this->drupalPost(NULL, array(), t('Save field settings'));
-
- // Using all the default settings, so press the button.
- $this->drupalPost(NULL, array(), t('Save settings'));
- $this->assertText(t('Saved @name configuration.', array('@name' => $single_field_name_friendly)));
-
- // Now we're back on the field-add page.
- // Now add a multivalued field.
- $multivalue_field_name_friendly = $this->randomName(20);
- $multivalue_field_name_machine = strtolower($this->randomName(10));
- $edit = array (
- 'fields[_add_new_field][label]' => $multivalue_field_name_friendly,
- 'fields[_add_new_field][field_name]' => $multivalue_field_name_machine,
- 'fields[_add_new_field][type]' => 'field_example_rgb',
- 'fields[_add_new_field][widget_type]' => 'field_example_3text',
- );
- $this->drupalPost(NULL, $edit, t('Save'));
-
- $this->drupalPost(NULL, array(), t('Save field settings'));
-
- $edit = array('field[cardinality]' => (string)(-1));
- $this->drupalPost(NULL, $edit, t('Save settings'));
-
- $this->assertText(t('Saved @name configuration.', array('@name' => $multivalue_field_name_friendly)));
-
- $this->drupalPost(NULL, array(), t('Save'));
-
- // Somehow clicking "save" isn't enough, and we have to do a
- // node_types_rebuild().
- node_types_rebuild();
- menu_rebuild();
- $type_exists = db_query('SELECT 1 FROM {node_type} WHERE type = :type', array(':type' => $content_type_machine))->fetchField();
- $this->assertTrue($type_exists, 'The new content type has been created in the database.');
-
- $permission = 'create ' . $content_type_machine . ' content';
- // Reset the permissions cache.
- $this->checkPermissions(array($permission), TRUE);
-
- // Now that we have a new content type, create a user that has privileges
- // on the content type.
- $account = $this->drupalCreateUser(array($permission));
- $this->drupalLogin($account);
-
- $this->drupalGet('node/add/' . $content_type_machine);
-
- // Add a node.
- $edit = array(
- 'title' => $title,
- 'field_' . $single_field_name_machine . '[und][0][r]' => 'ff',
- 'field_' . $single_field_name_machine . '[und][0][g]' => '00',
- 'field_' . $single_field_name_machine . '[und][0][b]' => '00',
-
- 'field_' . $multivalue_field_name_machine . '[und][0][r]' => '00',
- 'field_' . $multivalue_field_name_machine . '[und][0][g]' => 'ff',
- 'field_' . $multivalue_field_name_machine . '[und][0][b]' => '00',
-
- );
- // We want to add a 2nd item in the multivalue field, so hit "add another".
- $this->drupalPost(NULL, $edit, t('Add another item'));
-
- $edit = array(
- 'field_' . $multivalue_field_name_machine . '[und][1][r]' => '00',
- 'field_' . $multivalue_field_name_machine . '[und][1][g]' => '00',
- 'field_' . $multivalue_field_name_machine . '[und][1][b]' => 'ff',
- );
- // Now we can fill in the second item in the multivalue field and save.
- $this->drupalPost(NULL, $edit, t('Save'));
- $this->assertText(t('@content_type_friendly @title has been created', array('@content_type_friendly' => $content_type_friendly, '@title' => $title)));
-
-
- $output_strings = $this->xpath("//div[contains(@class,'field-type-field-example-rgb')]/div/div/p/text()");
-
- $this->assertEqual((string)$output_strings[0], t("The color code in this field is #ff0000"), t('Found first color code #ff0000'));
- $this->assertEqual((string)$output_strings[1], t("The color code in this field is #00ff00"), t('Found second color code #00ff00'));
- $this->assertEqual((string)$output_strings[2], t("The color code in this field is #0000ff"), t('Found third color code #0000ff'));
- }
-}
diff --git a/file_example/file_example.info b/file_example/file_example.info
deleted file mode 100644
index acdca71..0000000
--- a/file_example/file_example.info
+++ /dev/null
@@ -1,6 +0,0 @@
-name = File example
-description = Examples of using the Drupal File API and Stream Wrappers.
-package = Example modules
-core = 7.x
-files[] = file_example_session_streams.inc
-files[] = file_example.test
diff --git a/file_example/file_example.module b/file_example/file_example.module
deleted file mode 100644
index c7e0224..0000000
--- a/file_example/file_example.module
+++ /dev/null
@@ -1,522 +0,0 @@
-<?php
-
-/**
- * @file
- * Examples demonstrating the Drupal File API (and Stream Wrappers).
- *
- */
-
-/**
- * The File Example module is a part of the Examples for Developers Project
- * and provides various Drupal File API Examples. You can download and
- * experiment with this code at the
- * @link http://drupal.org/project/examples Examples for Developers project page. @endlink
- *
- * See @link http://drupal.org/node/555118 Drupal File API @endlink for handbook
- * documentation on the File API and
- * @link file File summary on api.drupal.org @endlink for the function summary.
- *
- * @defgroup file_example Examples: File Examples
- */
-
-/**
- * Implements hook_menu() to set up the URLs (menu entries) for the
- * file examples.
- */
-function file_example_menu() {
- $items = array();
- $items['examples/file_example'] = array(
- 'title' => 'File Example',
- 'page callback' => 'file_example_intro',
- 'access callback' => TRUE,
- 'expanded' => TRUE,
- );
- $items['examples/file_example/fileapi'] = array(
- 'title' => 'Use File API to read/write a file',
- 'page callback' => 'drupal_get_form',
- 'access arguments' => array('use file example'),
- 'page arguments' => array('file_example_readwrite'),
- );
- $items['examples/file_example/access_session'] = array(
- 'page callback' => 'file_example_session_contents',
- 'access arguments' => array('use file example'),
- 'type' => MENU_CALLBACK,
- );
- return $items;
-}
-
-
-/**
- * Implements hook_permission().
- */
-function file_example_permission() {
- return array(
- 'use file example' => array(
- 'title' => t('Use the examples in the File Example module'),
- ),
- );
-}
-
-
-/**
- * Form builder function for the file example readwrite and directory creation
- * example.
- *
- * A simple form that allows creation of a file, managed or unmanaged. It
- * also allows reading/deleting a file and creation of a directory.
- * @ingroup file_example
- */
-function file_example_readwrite($form, &$form_state) {
- if (empty($_SESSION['file_example_default_file'])) {
- $_SESSION['file_example_default_file'] = 'public://drupal.txt';
- }
- $default_file = $_SESSION['file_example_default_file'];
- if (empty($_SESSION['file_example_default_directory'])) {
- $_SESSION['file_example_default_directory'] = 'public://directory1';
- }
- $default_directory = $_SESSION['file_example_default_directory'];
-
- $form['write_file'] = array(
- '#type' => 'fieldset',
- '#title' => t('Write to a file'),
- );
- $form['write_file']['write_contents'] = array(
- '#type' => 'textfield',
- '#title' => t('Enter something you would like to write to a file') . ' ' . date('m'),
- '#default_value' => t('Put some text here or just use this text'),
- );
-
- $form['write_file']['destination'] = array(
- '#type' => 'textfield',
- '#default_value' => $default_file,
- '#title' => t('Optional: Enter the streamwrapper saying where it should be written'),
- '#description' => t('This may be public://some_dir/test_file.txt or private://another_dir/some_file.txt, for example. If you include a directory, it must already exist. The default is "public://". Since this example supports session://, you can also use something like session://somefile.txt.'),
- );
-
- $form['write_file']['managed_submit'] = array(
- '#type' => 'submit',
- '#value' => t('Write managed file'),
- '#submit' => array('file_example_managed_write_submit'),
- );
- $form['write_file']['unmanaged_submit'] = array(
- '#type' => 'submit',
- '#value' => t('Write unmanaged file'),
- '#submit' => array('file_example_unmanaged_write_submit'),
- );
- $form['write_file']['unmanaged_php'] = array(
- '#type' => 'submit',
- '#value' => t('Unmanaged using PHP'),
- '#submit' => array('file_example_unmanaged_php_submit'),
- );
-
- $form['fileops'] = array(
- '#type' => 'fieldset',
- '#title' => t('Read from a file'),
- );
- $form['fileops']['fileops_file'] = array(
- '#type' => 'textfield',
- '#default_value' => $default_file,
- '#title' => t('Enter the URI of a file'),
- '#description' => t('This must be a stream-type description like public://some_file.txt or http://drupal.org or private://another_file.txt or (for this example) session://yet_another_file.txt.'),
- );
- $form['fileops']['read_submit'] = array(
- '#type' => 'submit',
- '#value' => t('Read the file and store it locally'),
- '#submit' => array('file_example_read_submit'),
- );
- $form['fileops']['delete_submit'] = array(
- '#type' => 'submit',
- '#value' => t('Delete file'),
- '#submit' => array('file_example_delete_submit'),
- );
- $form['fileops']['check_submit'] = array(
- '#type' => 'submit',
- '#value' => t('Check to see if file exists'),
- '#submit' => array('file_example_file_check_exists_submit'),
- );
-
- $form['directory'] = array(
- '#type' => 'fieldset',
- '#title' => t('Create or prepare a directory'),
- );
-
- $form['directory']['directory_name'] = array(
- '#type' => 'textfield',
- '#title' => t('Directory to create/prepare/delete'),
- '#default_value' => $default_directory,
- '#description' => t('This is a directory as in public://some/directory or private://another/dir.'),
- );
- $form['directory']['create_directory'] = array(
- '#type' => 'submit',
- '#value' => t('Create directory'),
- '#submit' => array('file_example_create_directory_submit'),
- );
- $form['directory']['delete_directory'] = array(
- '#type' => 'submit',
- '#value' => t('Delete directory'),
- '#submit' => array('file_example_delete_directory_submit'),
- );
- $form['directory']['check_directory'] = array(
- '#type' => 'submit',
- '#value' => t('Check to see if directory exists'),
- '#submit' => array('file_example_check_directory_submit'),
- );
-
- $form['debug'] = array(
- '#type' => 'fieldset',
- '#title' => t('Debugging'),
- );
- $form['debug']['show_session'] = array(
- '#type' => 'submit',
- '#value' => t('Show $_SESSION contents'),
- '#submit' => array('file_example_show_session_contents_submit'),
- );
- $form['debug']['show_raw_session'] = array(
- '#type' => 'submit',
- '#value' => t('Show raw $_SESSION contents'),
- '#submit' => array('file_example_show_session_contents_submit'),
- );
-
- return $form;
-}
-
-/**
- * Submit handler to write a managed file.
- *
- * The key functions used here are:
- * - file_save_data(), which takes a buffer and saves it to a named file and
- * also creates a tracking record in the database and returns a file object.
- * In this function we use FILE_EXISTS_RENAME (the default) as the argument,
- * which means that if there's an existing file, create a new non-colliding
- * filename and use it.
- * - file_create_url(), which converts a URI in the form public://junk.txt or
- * private://something/test.txt into a URL like
- * http://example.com/sites/default/files/junk.txt.
- * @ingroup file_example
- */
-function file_example_managed_write_submit($form, &$form_state) {
- $data = $form_state['values']['write_contents'];
- $uri = !empty($form_state['values']['destination']) ? $form_state['values']['destination'] : NULL;
-
- // Managed operations work with a file object.
- $file_object = file_save_data($data, $uri, FILE_EXISTS_RENAME);
- if (!empty($file_object)) {
- $url = file_create_url($file_object->uri);
- $_SESSION['file_example_default_file'] = $file_object->uri;
- drupal_set_message(t('Saved managed file: %file to destination %destination (accessible via !url, actual uri=<span id="uri">@uri</span>)', array('%file' => print_r($file_object, TRUE), '%destination' => $uri, '@uri' => $file_object->uri, '!url' => l(t('this URL'), $url))));
- }
- else {
- drupal_set_message(t('Failed to save the managed file'), 'error');
- }
-}
-
-/**
- * Submit handler to write an unmanaged file.
- *
- * The key functions used here are:
- * - file_unmanaged_save_data(), which takes a buffer and saves it to a named
- * file, but does not create any kind of tracking record in the database.
- * This example uses FILE_EXISTS_REPLACE for the third argument, meaning
- * that if there's an existing file at this location, it should be replaced.
- * - file_create_url(), which converts a URI in the form public://junk.txt or
- * private://something/test.txt into a URL like
- * http://example.com/sites/default/files/junk.txt.
- * @ingroup file_example
- */
-
-function file_example_unmanaged_write_submit($form, &$form_state) {
- $data = $form_state['values']['write_contents'];
- $destination = !empty($form_state['values']['destination']) ? $form_state['values']['destination'] : NULL;
-
- // With the unmanaged file we just get a filename back.
- $filename = file_unmanaged_save_data($data, $destination, FILE_EXISTS_REPLACE);
- if ($filename) {
- $url = file_create_url($filename);
- $_SESSION['file_example_default_file'] = $filename;
- drupal_set_message(t('Saved file as %filename (accessible via !url, uri=<span id="uri">@uri</span>)', array('%filename' => $filename, '@uri' => $filename, '!url' => l(t('this URL'), $url))));
- }
- else {
- drupal_set_message(t('Failed to save the file'), 'error');
- }
-}
-
-
-
-/**
- * Submit handler to write an unmanaged file using plain PHP functions.
- *
- * The key functions used here are:
- * - file_unmanaged_save_data(), which takes a buffer and saves it to a named
- * file, but does not create any kind of tracking record in the database.
- * - file_create_url(), which converts a URI in the form public://junk.txt or
- * private://something/test.txt into a URL like
- * http://example.com/sites/default/files/junk.txt.
- * - drupal_tempnam() generates a temporary filename for use.
- * @ingroup file_example
- */
-
-function file_example_unmanaged_php_submit($form, &$form_state) {
- $data = $form_state['values']['write_contents'];
- $destination = !empty($form_state['values']['destination']) ? $form_state['values']['destination'] : NULL;
-
- if (empty($destination)) {
- // If no destination has been provided, use a generated name.
- $destination = drupal_tempnam('public://', 'file');
- }
-
- // With all traditional PHP functions we can use the stream wrapper notation
- // for a file as well.
- $fp = fopen($destination, 'w');
-
- // To demonstrate the fact that everything is based on streams, we'll do
- // multiple 5-character writes to put this to the file. We could easily
- // (and far more conveniently) write it in a single statement with
- // fwrite($fp, $data).
- $length = strlen($data);
- $write_size = 5;
- for ($i=0; $i < $length; $i += $write_size) {
- $result = fwrite($fp, substr($data, $i, $write_size));
- if ($result === FALSE) {
- drupal_set_message(t('Failed writing to the file; '), 'error');
- fclose($fp);
- return;
- }
- }
- $url = file_create_url($destination);
- $_SESSION['file_example_default_file'] = $destination;
- drupal_set_message(t('Saved file as %filename (accessible via !url, uri=<span id="uri">@uri</span>)', array('%filename' => $destination, '@uri' => $destination, '!url' => l(t('this URL'), $url))));
-}
-
-/**
- * Submit handler for reading a stream wrapper.
- *
- * Drupal now has full support for PHP's stream wrappers, which means that
- * instead of the traditional use of all the file functions
- * ($fp = fopen("/tmp/some_file.txt");) far more sophisticated and generalized
- * (and extensible) things can be opened as if they were files. Drupal itself
- * provides the public:// and private:// schemes for handling public and
- * private files. PHP provides file:// (the default) and http://, so that a
- * URL can be read or written (as in a POST) as if it were a file. In addition,
- * new schemes can be provided for custom applications, as will be demonstrated
- * below.
- *
- * Here we take the stream wrapper provided in the form. We grab the
- * contents with file_get_contents(). Notice that's it's as simple as that:
- * file_get_contents("http://example.com") or
- * file_get_contents("public://somefile.txt") just works. Although it's
- * not necessary, we use file_unmanaged_save_data() to save this file locally
- * and then find a local URL for it by using file_create_url().
- * @ingroup file_example
- */
-function file_example_read_submit($form, &$form_state) {
- $uri = $form_state['values']['fileops_file'];
-
- if (!is_file($uri)) {
- drupal_set_message(t('The file %uri does not exist', array('%uri' => $uri)), 'error');
- return;
- }
-
- // Make a working filename to save this by stripping off the (possible)
- // file portion of the streamwrapper. If it's an evil file extension,
- // file_munge_filename() will neuter it.
- $filename = file_munge_filename(preg_replace('@^.*/@', '', $uri), '', TRUE);
- $buffer = file_get_contents($uri);
-
- if ($buffer) {
- $sourcename = file_unmanaged_save_data($buffer, 'public://' . $filename);
- if ($sourcename) {
- $url = file_create_url($sourcename);
- $_SESSION['file_example_default_file'] = $sourcename;
- drupal_set_message(t('The file was read and copied to %filename which is accessible at !url', array('%filename' => $sourcename, '!url' => l($url, $url))));
- }
- else {
- drupal_set_message(t('Failed to save the file'));
- }
- }
- else { // We failed to get the contents of the requested file
- drupal_set_message(t('Failed to retrieve the file %file', array('%file' => $uri)));
- }
-}
-
-/**
- * Submit handler to delete a file.
- */
-function file_example_delete_submit($form, &$form_state) {
-
- $uri = $form_state['values']['fileops_file'];
-
- // Since we don't know if the file is managed or not, look in the database
- // to see. Normally, code would be working with either managed or unmanaged
- // files, so this is not a typical situation.
- $file_object = file_example_get_managed_file($uri);
-
- // If a managed file, use file_delete().
- if (!empty($file_object)) {
- $result = file_delete($file_object);
- if ($result !== TRUE) {
- drupal_set_message(t('Failed deleting managed file %uri. Result was %result', array('%uri' => $uri, '%result' => print_r($result, TRUE))), 'error');
- }
- else {
- drupal_set_message(t('Successfully deleted managed file %uri', array('%uri' => $uri)));
- $_SESSION['file_example_default_file'] = $uri;
- }
- }
- // else use file_unmanaged_delete().
- else {
- $result = file_unmanaged_delete($uri);
- if ($result !== TRUE) {
- drupal_set_message(t('Failed deleting unmanaged file %uri', array('%uri' => $uri, 'error')));
- }
- else {
- drupal_set_message(t('Successfully deleted unmanaged file %uri', array('%uri' => $uri)));
- $_SESSION['file_example_default_file'] = $uri;
- }
- }
-}
-
-/**
- * Submit handler to check existence of a file.
- */
-function file_example_file_check_exists_submit($form, &$form_state) {
- $uri = $form_state['values']['fileops_file'];
- if (is_file($uri)) {
- drupal_set_message(t('The file %uri exists.', array('%uri' => $uri)));
- }
- else {
- drupal_set_message(t('The file %uri does not exist.', array('%uri' => $uri)));
- }
-
-}
-/**
- * Submit handler for directory creation.
- * Here we create a directory and set proper permissions on it using
- * file_prepare_directory().
- * @ingroup file_example
- */
-function file_example_create_directory_submit($form, &$form_state) {
- $directory = $form_state['values']['directory_name'];
-
- // The options passed to file_prepare_directory are a bitmask, so we can
- // specify either FILE_MODIFY_PERMISSIONS (set permissions on the directory),
- // FILE_CREATE_DIRECTORY, or both together:
- // FILE_MODIFY_PERMISSIONS | FILE_CREATE_DIRECTORY.
- // FILE_MODIFY_PERMISSIONS will set the permissions of the directory by
- // by default to 0755, or to the value of the variable 'file_chmod_directory'.
- if (!file_prepare_directory($directory, FILE_MODIFY_PERMISSIONS | FILE_CREATE_DIRECTORY)) {
- drupal_set_message(t('Failed to create %directory.', array('%directory' => $directory)), 'error');
- }
- else {
- $result = is_dir($directory);
- drupal_set_message(t('Directory %directory is ready for use.', array('%directory' => $directory)));
- $_SESSION['file_example_default_directory'] = $directory;
- }
-}
-
-/**
- * Submit handler for directory deletion.
- *
- * @see file_unmanaged_delete_recursive()
- *
- * @ingroup file_example
- */
-function file_example_delete_directory_submit($form, &$form_state) {
- $directory = $form_state['values']['directory_name'];
-
- $result = file_unmanaged_delete_recursive($directory);
- if (!$result) {
- drupal_set_message(t('Failed to delete %directory.', array('%directory' => $directory)), 'error');
- }
- else {
- drupal_set_message(t('Recursively deleted directory %directory.', array('%directory' => $directory)));
- $_SESSION['file_example_default_directory'] = $directory;
- }
-}
-
-/**
- * Submit handler to test directory existence.
- * This actually just checks to see if the directory is writable
- * @param unknown_type $form
- * @param unknown_type $form_state
- */
-function file_example_check_directory_submit($form, &$form_state) {
- $directory = $form_state['values']['directory_name'];
- $result = is_dir($directory);
- if (!$result) {
- drupal_set_message(t('Directory %directory does not exist.', array('%directory' => $directory)));
- }
- else {
- drupal_set_message(t('Directory %directory exists.', array('%directory' => $directory)));
- }
-}
-
-/**
- * Utility submit function for debugging: Show $_SESSION.
- */
-function file_example_show_session_contents_submit($form, &$form_state) {
- if ($form_state['triggering_element']['#value'] == t('Show raw $_SESSION contents')) {
- drupal_set_message('<pre>' . print_r($_SESSION['file_example'], TRUE) . '</pre>');
- }
- else {
- return file_example_session_contents(NULL);
- }
-}
-
-/**
- * Utility function to check for and return a managed file.
- * In this demonstration code we don't necessarily know if a file is managed
- * or not, so often need to check to do the correct behavior. Normal code
- * would not have to do this, as it would be working with either managed or
- * unmanaged files.
- *
- * @param $uri
- * The URI of the file, like public://test.txt.
- */
-function file_example_get_managed_file($uri) {
- $fid = db_query('SELECT fid FROM {file_managed} WHERE uri = :uri', array(':uri' => $uri))->fetchField();
- if (!empty($fid)) {
- $file_object = file_load($fid);
- return $file_object;
- }
- return FALSE;
-}
-
-/**
- * Implements hook_stream_wrappers().
- * hook_stream_wrappers() is Drupal's way of exposing the class that PHP will
- * use to provide a new stream wrapper class. In this case, we'll expose the
- * 'session' scheme, so a file reference like "session://example/example.txt"
- * is readable and writable as a location in the $_SESSION variable.
- *
- * @see FileExampleSessionStreamWrapper
- *
- * defgroup streamwrapper_example Stream Wrapper Example
- */
-function file_example_stream_wrappers() {
- $wrappers = array(
- 'session' => array(
- 'name' => t('Example: $_SESSION variable storage'),
- 'class' => 'FileExampleSessionStreamWrapper',
- 'description' => t('Store files in the $_SESSION variable as an example.'),
- ),
- );
- return $wrappers;
-}
-
-/**
- * A utility function to allow us to see what is in a session "file".
- *
- * @param $session_path
- * The path, as in 'example/some/thing.txt'. This actually is a $_SESSION
- * key. example/some/thing.txt would be
- * $_SESSION['file_example']['some']['thing.txt']
- */
-function file_example_session_contents() {
- if (module_exists('devel')) {
- dsm($_SESSION['file_example'], t('Entire $_SESSION["file_example"]'));
- }
- $path_components = func_get_args();
- $session_path = join('/', $path_components);
- $content = file_get_contents('session://' . $session_path);
- return t('Contents of ') . check_plain($session_path) . ': ' . print_r($content, TRUE);
-}
-
diff --git a/file_example/file_example.test b/file_example/file_example.test
deleted file mode 100644
index b9cbcaf..0000000
--- a/file_example/file_example.test
+++ /dev/null
@@ -1,123 +0,0 @@
-<?php
-
-/**
- * @file
- * Tests for File Example.
- */
-
-class FileExampleTest extends DrupalWebTestCase {
-
- protected $privileged_user;
-
- public static function getInfo() {
- return array(
- 'name' => 'File Example Functionality',
- 'description' => 'Test File Example features and sample streamwrapper.',
- 'group' => 'Examples',
- );
- }
- function setUp() {
- parent::setUp(array('file_example'));
- $privileged_user = $this->drupalCreateUser(array('use file example'));
- $this->drupalLogin($privileged_user);
- }
-
- /**
- * Test the basic File Example UI.
- * - Create a directory to work with
- * - Foreach scheme create and read files using each of the three methods.
- */
- function testFileExampleBasic() {
-
- $expected_text = array(
- t('Write managed file') => t('Saved managed file'),
- t('Write unmanaged file') => t('Saved file as'),
- t('Unmanaged using PHP') => t('Saved file as'),
- );
- // For each of the three buttons == three write types
- foreach (array(t('Write managed file'), t('Write unmanaged file'), t('Unmanaged using PHP')) as $button) {
- // For each scheme supported by Drupal + the session:// wrapper
- foreach (array('public', 'private', 'temporary', 'session') as $scheme) {
- // Create a directory for use.
- $dirname = $scheme . '://' . $this->randomName(10);
-
- // Directory does not yet exist; assert that.
- $edit = array(
- 'directory_name' => $dirname,
- );
- $this->drupalPost('examples/file_example/fileapi', $edit, t('Check to see if directory exists'));
- $this->assertRaw(t('Directory %dirname does not exist', array('%dirname' => $dirname)), t('Verify that directory does not exist.'));
-
- $this->drupalPost('examples/file_example/fileapi', $edit, t('Create directory'));
- $this->assertRaw(t('Directory %dirname is ready for use', array('%dirname' => $dirname)));
-
- $this->drupalPost('examples/file_example/fileapi', $edit, t('Check to see if directory exists'));
- $this->assertRaw(t('Directory %dirname exists', array('%dirname' => $dirname)), t('Verify that directory now does exist.'));
-
- // Create a file in the directory we created.
- $content = $this->randomName(30);
- $filename = $dirname . '/' . $this->randomName(30) . '.txt';
-
- // Assert that the file we're about to create does not yet exist.
- $edit = array(
- 'fileops_file' => $filename,
- );
- $this->drupalPost('examples/file_example/fileapi', $edit, t('Check to see if file exists'));
- $this->assertRaw(t('The file %filename does not exist', array('%filename' => $filename)), t('Verify that file does not yet exist.'));
-
- debug(t('Processing button=%button, scheme=%scheme, dir=%dirname, file=%filename', array('%button' => $button, '%scheme' => $scheme, '%filename' => $filename, '%dirname' => $dirname)));
- $edit = array(
- 'write_contents' => $content,
- 'destination' => $filename,
- );
- $this->drupalPost('examples/file_example/fileapi', $edit, $button);
- $this->assertText($expected_text[$button]);
-
-
- // Capture the name of the output file, as it might have changed due
- // to file renaming.
- $element = $this->xpath('//span[@id="uri"]');
- $output_filename = (string)$element[0];
- debug($output_filename, 'Name of output file');
-
- // Click the link provided that is an easy way to get the data for
- // checking and make sure that the data we put in is what we get out.
- if (!in_array($scheme, array('private', 'temporary'))) {
- $this->clickLink(t('this URL'));
- $this->assertText($content);
- }
-
- // Verify that the file exists.
- $edit = array(
- 'fileops_file' => $filename,
- );
- $this->drupalPost('examples/file_example/fileapi', $edit, t('Check to see if file exists'));
- $this->assertRaw(t('The file %filename exists', array('%filename' => $filename)), t('Verify that file now exists.'));
-
- // Now read the file that got written above and verify that we can use
- // the writing tools.
- $edit = array(
- 'fileops_file' => $output_filename,
- );
- $this->drupalPost('examples/file_example/fileapi', $edit, t('Read the file and store it locally'));
-
- $this->assertText(t('The file was read and copied'));
-
- $edit = array(
- 'fileops_file' => $filename,
- );
- $this->drupalPost('examples/file_example/fileapi', $edit, t('Delete file'));
- $this->assertText(t('Successfully deleted'));
- $this->drupalPost('examples/file_example/fileapi', $edit, t('Check to see if file exists'));
- $this->assertRaw(t('The file %filename does not exist', array('%filename' => $filename)), t('Verify file has been deleted.'));
-
- $edit = array(
- 'directory_name' => $dirname,
- );
- $this->drupalPost('examples/file_example/fileapi', $edit, t('Delete directory'));
- $this->drupalPost('examples/file_example/fileapi', $edit, t('Check to see if directory exists'));
- $this->assertRaw(t('Directory %dirname does not exist', array('%dirname' => $dirname)), t('Verify that directory does not exist after deletion.'));
- }
- }
- }
-}
diff --git a/file_example/file_example_session_streams.inc b/file_example/file_example_session_streams.inc
deleted file mode 100644
index 4c2e1f6..0000000
--- a/file_example/file_example_session_streams.inc
+++ /dev/null
@@ -1,678 +0,0 @@
-<?php
-
-/**
- * @file file_example_session_streams.inc
- * Implement DrupalStreamWrapperInterface to provide a demonstration session://
- * streamwrapper. This example is nearly fully functional, but has no known
- * practical use. It's an example and demonstration only.
- */
-
-/**
- * Example stream wrapper class to handle session:// streams.
- * This is just an example, as it could have horrible results if much
- * information were placed in the $_SESSION variable. However, it does
- * demonstrate both the read and write implementation of a stream wrapper.
- *
- * A "stream" is an important Unix concept for the reading and writing of
- * files and other devices. Reading or writing a "stream" just means that you
- * open some device, file, internet site, or whatever, and you don't have to
- * know at all what it is. All the functions that deal with it are the same.
- * You can read/write more from/to the stream, seek a position in the stream,
- * or anything else without the code that does it even knowing what kind
- * of device it is talking to. This Unix idea is extended into PHP's
- * mindset.
- *
- * The idea of "stream wrapper" is that this can be extended indefinitely.
- * The classic example is HTTP: With PHP you can do a
- * file_get_contents("http://drupal.org/projects") as if it were a file,
- * because the scheme "http" is supported natively in PHP. So Drupal adds
- * the public:// and private:// schemes, and contrib modules can add any
- * scheme they want to. This example adds the session:// scheme, which allows
- * reading and writing the $_SESSION['file_example'] key as if it were a file.
- *
- * Note that because this implementation uses simple PHP arrays ($_SESSION)
- * it is limited to string values, so binary files will not work correctly.
- * Only text files can be used.
- */
-class FileExampleSessionStreamWrapper implements DrupalStreamWrapperInterface {
- /**
- * Stream context resource.
- *
- * @var Resource
- */
- public $context;
-
-
- /**
- * Instance URI (stream).
- *
- * These streams will be references as 'session://example_target'
- *
- * @var String
- */
- protected $uri;
-
- /**
- * The content of the stream.
- * Since this trivial example just uses the $_SESSION variable, this is
- * simply a reference to the contents of the related part of
- * $_SESSION['file_example'].
- */
- protected $session_content;
-
- /**
- * Pointer to where we are in a directory read.
- */
- protected $directory_pointer;
-
- /**
- * List of keys in a given directory.
- */
- protected $directory_keys;
-
- /**
- * The pointer to the next read or write within the session variable.
- */
- protected $stream_pointer;
-
- public function __construct() {
- $_SESSION['file_example']['.isadir.txt'] = TRUE;
- }
-
- /**
- * Implements setUri().
- */
- function setUri($uri) {
- $this->uri = $uri;
- }
-
- /**
- * Implements getUri().
- */
- function getUri() {
- return $this->uri;
- }
-
- /**
- * Implements getTarget().
- * The "target" is the portion of the URI to the right of the scheme.
- * So in session://example/test.txt, the target is 'example/test.txt'.
- */
- function getTarget($uri = NULL) {
- if (!isset($uri)) {
- $uri = $this->uri;
- }
-
- list($scheme, $target) = explode('://', $uri, 2);
-
- // Remove erroneous leading or trailing, forward-slashes and backslashes.
- // In the session:// scheme, there is never a leading slash on the target.
- return trim($target, '\/');
- }
-
- /**
- * Implements getMimeType().
- */
- static function getMimeType($uri, $mapping = NULL) {
- if (!isset($mapping)) {
- // The default file map, defined in file.mimetypes.inc is quite big.
- // We only load it when necessary.
- include_once DRUPAL_ROOT . '/includes/file.mimetypes.inc';
- $mapping = file_mimetype_mapping();
- }
-
- $extension = '';
- $file_parts = explode('.', basename($uri));
-
- // Remove the first part: a full filename should not match an extension.
- array_shift($file_parts);
-
- // Iterate over the file parts, trying to find a match.
- // For my.awesome.image.jpeg, we try:
- // - jpeg
- // - image.jpeg, and
- // - awesome.image.jpeg
- while ($additional_part = array_pop($file_parts)) {
- $extension = strtolower($additional_part . ($extension ? '.' . $extension : ''));
- if (isset($mapping['extensions'][$extension])) {
- return $mapping['mimetypes'][$mapping['extensions'][$extension]];
- }
- }
-
- return 'application/octet-stream';
- }
-
- /**
- * Implements getDirectoryPath().
- * In this case there is no directory string, so return an empty string.
- */
- public function getDirectoryPath() {
- return '';
- }
-
- /**
- * Overrides getExternalUrl().
- * We have set up a helper function and menu entry to provide access to this
- * key via HTTP; normally it would be accessible some other way.
- */
- function getExternalUrl() {
- $path = $this->getLocalPath();
- $url = url('examples/file_example/access_session/' . $path, array('absolute' => TRUE));
- return $url;
- }
-
- /**
- * We have no concept of chmod, so just return TRUE.
- */
- function chmod($mode) {
- return TRUE;
- }
-
- /**
- * Implements realpath().
- */
- function realpath() {
- return 'session://' . $this->getLocalPath();
- }
-
- /**
- * Returns the local path.
- * Here we aren't doing anything but stashing the "file" in a key in the
- * $_SESSION variable, so there's not much to do but to create a "path"
- * which is really just a key in the $_SESSION variable. So something
- * like 'session://one/two/three.txt' becomes
- * $_SESSION['file_example']['one']['two']['three.txt'] and the actual path
- * is "one/two/three.txt".
- *
- * @param $uri
- * Optional URI, supplied when doing a move or rename.
- */
- protected function getLocalPath($uri = NULL) {
- if (!isset($uri)) {
- $uri = $this->uri;
- }
-
- $path = str_replace('session://', '', $uri);
- $path = trim($path, '/');
- return $path;
- }
-
- /**
- * Opens a stream, as for fopen(), file_get_contents(), file_put_contents()
- *
- * @param $uri
- * A string containing the URI to the file to open.
- * @param $mode
- * The file mode ("r", "wb" etc.).
- * @param $options
- * A bit mask of STREAM_USE_PATH and STREAM_REPORT_ERRORS.
- * @param &$opened_path
- * A string containing the path actually opened.
- *
- * @return
- * Returns TRUE if file was opened successfully. (Always returns TRUE).
- *
- * @see http://php.net/manual/en/streamwrapper.stream-open.php
- */
- public function stream_open($uri, $mode, $options, &$opened_path) {
- $this->uri = $uri;
-
- // We make $session_content a reference to the appropriate key in the
- // $_SESSION variable. So if the local path were
- // /example/test.txt it $session_content would now be a
- // reference to $_SESSION['file_example']['example']['test.txt'].
- $this->session_content = &$this->uri_to_session_key($uri);
-
- // Reset the stream pointer since this is an open.
- $this->stream_pointer = 0;
- return TRUE;
- }
-
- /**
- * Return a reference to the correct $_SESSION key.
- * @param $uri
- * The uri: session://something
- * @param $create
- * If TRUE, create the key
- *
- * @return
- * TRUE if the key exists (which it will if $create was set)
- */
- protected function &uri_to_session_key($uri, $create = TRUE) {
- $path = $this->getLocalPath($uri);
- $path_components = preg_split('/\//', $path);
- $fail = FALSE;
- $var = &$_SESSION['file_example'];
- // Handle case of just session://.
- if (strlen($path) == 0) {
- return $var;
- }
- foreach ($path_components as $component) {
- if ($create || isset($var[$component])) {
- $var = &$var[$component];
- }
- else {
- return $fail;
- }
- }
- return $var;
- }
- /**
- * Support for flock().
- * The $_SESSION variable has no locking capability, so return TRUE.
- *
- * @param $operation
- * One of the following:
- * - LOCK_SH to acquire a shared lock (reader).
- * - LOCK_EX to acquire an exclusive lock (writer).
- * - LOCK_UN to release a lock (shared or exclusive).
- * - LOCK_NB if you don't want flock() to block while locking (not
- * supported on Windows).
- *
- * @return
- * Always returns TRUE at the present time. (no support)
- *
- * @see http://php.net/manual/en/streamwrapper.stream-lock.php
- */
- public function stream_lock($operation) {
- return TRUE;
- }
-
- /**
- * Support for fread(), file_get_contents() etc.
- *
- * @param $count
- * Maximum number of bytes to be read.
- *
- * @return
- * The string that was read, or FALSE in case of an error.
- *
- * @see http://php.net/manual/en/streamwrapper.stream-read.php
- */
- public function stream_read($count) {
- if (is_string($this->session_content)) {
- $remaining_chars = strlen($this->session_content) - $this->stream_pointer;
- $number_to_read = min($count, $remaining_chars);
- if ($remaining_chars > 0) {
- $buffer = substr($this->session_content, $this->stream_pointer, $number_to_read);
- $this->stream_pointer += $number_to_read;
- return $buffer;
- }
- }
- return FALSE;
- }
-
- /**
- * Support for fwrite(), file_put_contents() etc.
- *
- * @param $data
- * The string to be written.
- *
- * @return
- * The number of bytes written (integer).
- *
- * @see http://php.net/manual/en/streamwrapper.stream-write.php
- */
- public function stream_write($data) {
- // Sanitize the data in a simple way since we're putting it into the
- // session variable.
- $data = check_plain($data);
- $this->session_content = substr_replace($this->session_content, $data, $this->stream_pointer);
- $this->stream_pointer += strlen($data);
- return strlen($data);
- }
-
- /**
- * Support for feof().
- *
- * @return
- * TRUE if end-of-file has been reached.
- *
- * @see http://php.net/manual/en/streamwrapper.stream-eof.php
- */
- public function stream_eof() {
- return FALSE;
- }
-
- /**
- * Support for fseek().
- *
- * @param $offset
- * The byte offset to got to.
- * @param $whence
- * SEEK_SET, SEEK_CUR, or SEEK_END.
- *
- * @return
- * TRUE on success.
- *
- * @see http://php.net/manual/en/streamwrapper.stream-seek.php
- */
- public function stream_seek($offset, $whence) {
- if (strlen($this->session_content) >= $offset) {
- $this->stream_pointer = $offset;
- return TRUE;
- }
- return FALSE;
- }
-
- /**
- * Support for fflush().
- *
- * @return
- * TRUE if data was successfully stored (or there was no data to store).
- * This always returns TRUE, as this example provides and needs no
- * flush support.
- *
- * @see http://php.net/manual/en/streamwrapper.stream-flush.php
- */
- public function stream_flush() {
- return TRUE;
- }
-
- /**
- * Support for ftell().
- *
- * @return
- * The current offset in bytes from the beginning of file.
- *
- * @see http://php.net/manual/en/streamwrapper.stream-tell.php
- */
- public function stream_tell() {
- return $this->stream_pointer;
- }
-
- /**
- * Support for fstat().
- *
- * @return
- * An array with file status, or FALSE in case of an error - see fstat()
- * for a description of this array.
- *
- * @see http://php.net/manual/en/streamwrapper.stream-stat.php
- */
- public function stream_stat() {
- return array(
- 'size' => drupal_strlen($this->session_content),
- );
- }
-
- /**
- * Support for fclose().
- *
- * @return
- * TRUE if stream was successfully closed.
- *
- * @see http://php.net/manual/en/streamwrapper.stream-close.php
- */
- public function stream_close() {
- $this->stream_pointer = 0;
- unset($this->session_content); // Unassign the reference.
- return TRUE;
- }
-
- /**
- * Support for unlink().
- *
- * @param $uri
- * A string containing the uri to the resource to delete.
- *
- * @return
- * TRUE if resource was successfully deleted.
- *
- * @see http://php.net/manual/en/streamwrapper.unlink.php
- */
- public function unlink($uri) {
- $path = $this->getLocalPath($uri);
- $path_components = preg_split('/\//', $path);
- $fail = FALSE;
- $unset = '$_SESSION[\'file_example\']';
- foreach ($path_components as $component) {
- $unset .= '[\'' . $component . '\']';
- }
- // TODO: Is there a better way to delete from an array?
- // drupal_array_get_nested_value() doesn't work because it only returns
- // a reference; unsetting a reference only unsets the reference.
- eval("unset($unset);");
- return TRUE;
- }
-
- /**
- * Support for rename().
- *
- * @param $from_uri,
- * The uri to the file to rename.
- * @param $to_uri
- * The new uri for file.
- *
- * @return
- * TRUE if file was successfully renamed.
- *
- * @see http://php.net/manual/en/streamwrapper.rename.php
- */
- public function rename($from_uri, $to_uri) {
- $from_key = &$this->uri_to_session_key($from_uri);
- $to_key = &$this->uri_to_session_key($to_uri);
- if (is_dir($to_key) || is_file($to_key)) {
- return FALSE;
- }
- $to_key = $from_key;
- unset($from_key);
- return TRUE;
- }
-
- /**
- * Gets the name of the directory from a given path.
- *
- * @param $uri
- * A URI.
- *
- * @return
- * A string containing the directory name.
- *
- * @see drupal_dirname()
- */
- public function dirname($uri = NULL) {
- list($scheme, $target) = explode('://', $uri, 2);
- $target = $this->getTarget($uri);
- if (strpos($target, '/')) {
- $dirname = preg_replace('@/[^/]*$@', '', $target);
- }
- else
- {
- $dirname = '';
- }
- return $scheme . '://' . $dirname;
- }
-
- /**
- * Support for mkdir().
- *
- * @param $uri
- * A string containing the URI to the directory to create.
- * @param $mode
- * Permission flags - see mkdir().
- * @param $options
- * A bit mask of STREAM_REPORT_ERRORS and STREAM_MKDIR_RECURSIVE.
- *
- * @return
- * TRUE if directory was successfully created.
- *
- * @see http://php.net/manual/en/streamwrapper.mkdir.php
- */
- public function mkdir($uri, $mode, $options) {
- // If this already exists, then we can't mkdir.
- if (is_dir($uri) || is_file($uri)) {
- return FALSE;
- }
-
- // Create the key in $_SESSION;
- $this->uri_to_session_key($uri, TRUE);
-
- // Place a magic file inside it to differentiate this from an empty file.
- $marker_uri = $uri . '/.isadir.txt';
- $this->uri_to_session_key($marker_uri, TRUE);
- return TRUE;
- }
-
- /**
- * Support for rmdir().
- *
- * @param $uri
- * A string containing the URI to the directory to delete.
- * @param $options
- * A bit mask of STREAM_REPORT_ERRORS.
- *
- * @return
- * TRUE if directory was successfully removed.
- *
- * @see http://php.net/manual/en/streamwrapper.rmdir.php
- */
- public function rmdir($uri, $options) {
- $path = $this->getLocalPath($uri);
- $path_components = preg_split('/\//', $path);
- $fail = FALSE;
- $unset = '$_SESSION[\'file_example\']';
- foreach ($path_components as $component) {
- $unset .= '[\'' . $component . '\']';
- }
- // TODO: I really don't like this eval.
- debug($unset, 'array element to be unset');
- eval("unset($unset);");
-
- return TRUE;
- }
-
- /**
- * Support for stat().
- * This important function goes back to the Unix way of doing things.
- * In this example almost the entire stat array is irrelevant, but the
- * mode is very important. It tells PHP whether we have a file or a
- * directory and what the permissions are. All that is packed up in a
- * bitmask. This is not normal PHP fodder.
- *
- * @param $uri
- * A string containing the URI to get information about.
- * @param $flags
- * A bit mask of STREAM_URL_STAT_LINK and STREAM_URL_STAT_QUIET.
- *
- * @return
- * An array with file status, or FALSE in case of an error - see fstat()
- * for a description of this array.
- *
- * @see http://php.net/manual/en/streamwrapper.url-stat.php
- */
- public function url_stat($uri, $flags) {
-
- // PHP does not necessarily construct the object before all operations,
- // so here we make sure that the startup work is done.
- $this->__construct();
-
- $key = $this->uri_to_session_key($uri, FALSE);
- $return = FALSE; // Default to fail.
- $mode = 0;
-
- // We will call an array a directory and the root is always an array.
- if (is_array($key) && array_key_exists('.isadir.txt', $key)) {
- $mode = 0040000; // S_IFDIR means it's a directory.
- }
- else if ($key !== FALSE) {
- $mode = 0100000; // S_IFREG, means it's a file.
- }
-
- if ($mode) {
- $size = 0;
- if ($mode == 0100000) {
- $size = drupal_strlen($key);
- }
-
- $mode |= 0777; // There are no protections on this, so all writable.
- $return = array(
- 'dev' => 0,
- 'ino' => 0,
- 'mode' => $mode,
- 'nlink' => 0,
- 'uid' => 0,
- 'gid' => 0,
- 'rdev' => 0,
- 'size' => $size,
- 'atime' => 0,
- 'mtime' => 0,
- 'ctime' => 0,
- 'blksize' => 0,
- 'blocks' => 0,
- );
- }
- return $return;
- }
-
- /**
- * Support for opendir().
- *
- * @param $uri
- * A string containing the URI to the directory to open.
- * @param $options
- * Unknown (parameter is not documented in PHP Manual).
- *
- * @return
- * TRUE on success.
- *
- * @see http://php.net/manual/en/streamwrapper.dir-opendir.php
- */
- public function dir_opendir($uri, $options) {
- $var = &$this->uri_to_session_key($uri, FALSE);
- if ($var === FALSE || !array_key_exists('.isadir.txt', $var)) {
- return FALSE;
- }
-
- // We grab the list of key names, flip it so that .isadir.txt can easily
- // be removed, then flip it back so we can easily walk it as a list.
- $this->directory_keys = array_flip(array_keys($var));
- unset($this->directory_keys['.isadir.txt']);
- $this->directory_keys = array_keys($this->directory_keys);
- $this->directory_pointer = 0;
- return TRUE;
- }
-
- /**
- * Support for readdir().
- *
- * @return
- * The next filename, or FALSE if there are no more files in the directory.
- *
- * @see http://php.net/manual/en/streamwrapper.dir-readdir.php
- */
- public function dir_readdir() {
- if ($this->directory_pointer < count($this->directory_keys)) {
- $next = $this->directory_keys[$this->directory_pointer];
- $this->directory_pointer++;
- return $next;
- }
- return FALSE;
- }
-
- /**
- * Support for rewinddir().
- *
- * @return
- * TRUE on success.
- *
- * @see http://php.net/manual/en/streamwrapper.dir-rewinddir.php
- */
- public function dir_rewinddir() {
- $this->directory_pointer = 0;
- }
-
- /**
- * Support for closedir().
- *
- * @return
- * TRUE on success.
- *
- * @see http://php.net/manual/en/streamwrapper.dir-closedir.php
- */
- public function dir_closedir() {
- $this->directory_pointer = 0;
- unset($this->directory_keys);
- return TRUE;
- }
-}
diff --git a/filter_example/filter_example.info b/filter_example/filter_example.info
deleted file mode 100755
index 888ee73..0000000
--- a/filter_example/filter_example.info
+++ /dev/null
@@ -1,6 +0,0 @@
-
-name = Filter example
-description = An example module showing how to define a custom filter.
-package = Example modules
-core = 7.x
-files[] = filter_example.test
diff --git a/filter_example/filter_example.module b/filter_example/filter_example.module
deleted file mode 100755
index bbf0296..0000000
--- a/filter_example/filter_example.module
+++ /dev/null
@@ -1,176 +0,0 @@
-<?php
-
-/**
- * @file
- * This is an example outlining how a module can be used to define a filter
- * to be run on user-submitted content before it is output to the browser.
- *
- * To show all the capabilities of the filter system, we will define two filters
- * in this module. One will substitute the string "foo" with an administratively-
- * defined replacement string. The other will find a custom XML tag, <time />, and
- * replace it by the current time.
- */
-
-/**
- * Implements hook_menu().
- */
-function filter_example_menu() {
- $items['examples/filter_example'] = array(
- 'title' => 'Filter Example',
- 'page callback' => '_filter_example_information',
- 'access callback' => TRUE,
- );
- return $items;
-}
-
-/**
- * Implements hook_filter_info().
- *
- * Here we define the diferent filters provided by the module. For this example,
- * time_filter is a very static and simple replacement, but it requires some
- * preparation of the string because of the special html tags < and >. The
- * foo_filter is more complex, including its own settings and inline tips.
- */
-function filter_example_filter_info() {
- $filters['filter_foo'] = array(
- 'title' => t('Foo filter'),
- 'description' => t('Every instance of "foo" in the input text will be replaced with a preconfigured replacement.'),
- 'process callback' => '_filter_example_filter_foo_process',
- 'default settings' => array(
- 'filter_example_foo' => 'bar',
- ),
- 'settings callback' => '_filter_example_filter_foo_settings',
- 'tips callback' => '_filter_example_filter_foo_tips',
- );
- $filters['filter_time'] = array(
- 'title' => t('Time tag'),
- 'description' => t('Every instance of the special &lt;time /&gt; tag will be replaced with the current date and time in the user\'s specified time zone.'),
- 'prepare callback' => '_filter_example_filter_time_prepare',
- 'process callback' => '_filter_example_filter_time_process',
- 'tips callback' => '_filter_example_filter_time_tips',
- );
- return $filters;
-}
-
-/*
- * Foo filter
- *
- * Drupal has several content formats (they are not filters), and in our example
- * the foo replacement can be configured for each one of them, allowing an html
- * or php replacement, so the module includes a settings callback, with options
- * to configure that replacements. Also, a Tips callback will help showing the
- * current replacement for the content type being edited.
- */
-
-/**
- * Simply returns a little bit of information about the example.
- */
-function _filter_example_information() {
- return t(
- "There are two filters in this example. The first (foo filter) just replaces
- 'foo' with a configurable replacement. The second replaces the string
- '<time />' with the current time. To use these filters, go to !link and
- configure one of the input formats.",
- array('!link' => l("admin/config/content/formats", "admin/config/content/formats"))
- );
-}
-
-/**
- * Settings callback for foo filter
- *
- * Make use of $format to have different replacements for every input format.
- * Since we allow the administrator to define the string that gets substituted
- * when "foo" is encountered, we need to provide an interface for this kind of
- * customization. The object format is also an argument of the callback.
- *
- * The settings defined in this form are stored in database by the filter module,
- * and they will be available in the $filter argument
- */
-function _filter_example_filter_foo_settings($form, $form_state, $filter, $format, $defaults) {
- $settings['filter_example_foo'] = array(
- '#type' => 'textfield',
- '#title' => t('Substitution string'),
- '#default_value' => isset($filter->settings['filter_example_foo']) ? $filter->settings['filter_example_foo'] : $defaults['filter_example_foo'],
- '#description' => t('The string to substitute for "foo" everywhere in the text.')
- );
- return $settings;
-}
-
-/**
- * Foo filter process callback
- *
- * The actual filtering is performed here. The supplied text should be returned,
- * once any necessary substitutions have taken place. The example just replaces
- * foo with our custom defined string in the settings page.
- */
-function _filter_example_filter_foo_process($text, $filter, $format) {
- $replacement = isset($filter->settings['filter_example_foo']) ? $filter->settings['filter_example_foo'] : 'bar';
- return str_replace('foo', $replacement, $text);
-}
-
-
-/**
- * Filter tips callback for foo filter.
- *
- * The tips callback allows filters to provide help text to users during the content
- * editing process. Short tips are provided on the content editing screen, while
- * long tips are provided on a separate linked page. Short tips are optional,
- * but long tips are highly recommended.
- */
-function _filter_example_filter_foo_tips($filter, $format, $long = FALSE) {
- $replacement = isset($filter->settings['filter_example_foo']) ? $filter->settings['filter_example_foo'] : 'bar';
- if (!$long) {
- // This string will be shown in the content add/edit form
- return t('<em>foo</em> replaced with %replacement.', array('%replacement' => $replacement));
- }
- else {
- return t('Every instance of "foo" in the input text will be replaced with a configurable value. You can configure this value and put whatever you want there. The replacement value is "%replacement".', array('%replacement' => $replacement));
- }
-}
-
-/*
- * Time filter.
- *
- * This filter is a little trickier to implement than the previous one.
- * Since the input involves special HTML characters (< and >) we have to
- * run the filter before HTML is escaped/stripped by other filters. But
- * we want to use HTML in our result as well, and so if we run this filter
- * first our replacement string could be escaped or stripped. The solution
- * is to use the "prepare" operation to escape the special characters, and
- * to later replace our escaped version in the "process" step.
- */
-
-/*
- * Time filter prepare callback
- *
- * We'll use [filter-example-time] as a replacement for the time tag.
- * Note that in a more complicated filter a closing tag may also be
- * required. For more information, see "Temporary placeholders and
- * delimiters" at http://drupal.org/node/209715.
- */
-function _filter_example_filter_time_prepare($text, $filter) {
- return preg_replace('!<time ?/>!', '[filter-example-time]', $text);
-}
-
-/*
- * Time filter process callback
- *
- * Now, in the "process" step, we'll search for our escaped time tags and
- * to the real filtering: replace the xml tag with the date.
- */
-function _filter_example_filter_time_process($text, $filter) {
- return str_replace('[filter-example-time]', '<em>' . format_date(time()) . '</em>', $text);
-}
-
-
-/**
- * Filter tips callback for time filter.
- *
- * The tips callback allows filters to provide help text to users during the content
- * editing process. Short tips are provided on the content editing screen, while
- * long tips are provided on a separate linked page. Short tips are optional,
- * but long tips are highly recommended.
- */
-function _filter_example_filter_time_tips($filter, $format, $long = FALSE) {
- return t('<em>&lt;time /&gt;</em> is replaced with the current time.');
-}
diff --git a/filter_example/filter_example.test b/filter_example/filter_example.test
deleted file mode 100644
index 0768601..0000000
--- a/filter_example/filter_example.test
+++ /dev/null
@@ -1,97 +0,0 @@
-<?php
-
-/**
- * @file
- * Test case for Testing the filter example module.
- *
- * This file contains the test cases to check if module is performing as
- * expected.
- *
- */
-class FilterExampleTestCase extends DrupalWebTestCase {
- protected $web_user;
- protected $filtered_html;
- protected $full_html;
-
- public static function getInfo() {
- return array(
- 'name' => 'Filter example functionality',
- 'description' => 'Verify that content is processed by example filter.',
- 'group' => 'Examples',
- );
- }
-
- /**
- * Enable modules and create user with specific permissions.
- */
- function setUp() {
- parent::setUp('filter_example');
-
- // Load the used input formats.
- $this->filtered_html = db_query_range('SELECT * FROM {filter_format} WHERE name = :name', 0, 1, array(':name' => 'Filtered HTML'))->fetchObject();
- $this->full_html = db_query_range('SELECT * FROM {filter_format} WHERE name = :name', 0, 1, array(':name' => 'Full HTML'))->fetchObject();
-
- // Create user.
- $this->web_user = $this->drupalCreateUser(array(
- 'administer filters',
- filter_permission_name($this->filtered_html),
- filter_permission_name($this->full_html),
- 'bypass node access',
- ));
- }
-
- /**
- * Login user, create an example node, and test blog functionality through the admin and user interfaces.
- */
- function testFilterExampleBasic() {
- // Login the admin user.
- $this->drupalLogin($this->web_user);
-
- // Enable both filters in format id 1 (default format)
- $edit = array(
- 'filters[filter_time][status]' => 1,
- 'filters[filter_foo][status]' => 1,
- );
- $this->drupalPost('admin/config/content/formats/' . $this->filtered_html->format, $edit, t('Save configuration'));
-
- // Create a content type to test the filters (with default format)
- $content_type = $this->drupalCreateContentType();
-
- // Create a test node
- $langcode = LANGUAGE_NONE;
- $edit = array(
- "title" => $this->randomName(),
- "body[$langcode][0][value]" => 'What foo is it? it is <time />',
- );
- $result = $this->drupalPost('node/add/' . $content_type->type, $edit, t('Save'));
- $this->assertResponse(200);
- $time = format_date(time());
- $this->assertRaw('What bar is it? it is <em>' . $time . '</em>');
-
- // Enable foo filter in other format id 2
- $edit = array(
- 'filters[filter_foo][status]' => 1,
- );
- $this->drupalPost('admin/config/content/formats/' . $this->full_html->format, $edit, t('Save configuration'));
-
- // Change foo filter replacement with a random string in format id 2
- $replacement = $this->randomName();
- $options = array(
- 'filters[filter_foo][settings][filter_example_foo]' => $replacement,
- );
- $this->drupalPost('admin/config/content/formats/' . $this->full_html->format, $options, t('Save configuration'));
-
- // Create a test node with content format 2
- $langcode = LANGUAGE_NONE;
- $edit = array(
- "title" => $this->randomName(),
- "body[$langcode][0][value]" => 'What foo is it? it is <time />',
- "body[$langcode][0][format]" => $this->full_html->format,
- );
- $result = $this->drupalPost('node/add/' . $content_type->type, $edit, t('Save'));
- $this->assertResponse(200);
-
- // Only foo filter is enabled
- $this->assertRaw("What " . $replacement . " is it", t('Foo filter successfully verified.'));
- }
-}
diff --git a/form_example/form_example.info b/form_example/form_example.info
deleted file mode 100644
index 875fdff..0000000
--- a/form_example/form_example.info
+++ /dev/null
@@ -1,6 +0,0 @@
-
-name = Form example
-description = Examples of using the Drupal Form API.
-package = Example modules
-core = 7.x
-files[] = form_example.test
diff --git a/form_example/form_example.module b/form_example/form_example.module
deleted file mode 100644
index 46eeb50..0000000
--- a/form_example/form_example.module
+++ /dev/null
@@ -1,153 +0,0 @@
-<?php
-
-/**
- * @file
- * Examples demonstrating the Drupal Form API.
- *
- */
-
-/**
- * The Form Example module is a part of the Examples for Developers Project
- * and provides various Drupal Form API Examples. You can download and
- * experiment with this code at the
- * @link http://drupal.org/project/examples Examples for Developers project page. @endlink
- *
- * @defgroup form_example Examples: Form Examples
- */
-
-/**
- * Implements hook_menu() to set up the URLs (menu entries) for the
- * form examples.
- */
-function form_example_menu() {
- $items = array();
- $items['examples/form_example'] = array(
- 'title' => 'Form Example',
- 'page callback' => 'form_example_intro',
- 'access callback' => TRUE,
- 'expanded' => TRUE,
- );
- $items['examples/form_example/tutorial'] = array(
- 'title' => 'Form Tutorial',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array('form_example_tutorial_1'),
- 'access callback' => TRUE,
- 'description' => 'A set of ten tutorials',
- 'file' => 'form_example_tutorial.inc',
- 'type' => MENU_NORMAL_ITEM,
- );
- $items['examples/form_example/tutorial/1'] = array(
- 'title' => '#1',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array('form_example_tutorial_1'),
- 'access callback' => TRUE,
- 'description' => 'Tutorial 1: Simplest form',
- 'type' => MENU_DEFAULT_LOCAL_TASK,
- 'file' => 'form_example_tutorial.inc',
- );
- $items['examples/form_example/tutorial/2'] = array(
- 'title' => '#2',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array('form_example_tutorial_2'),
- 'access callback' => TRUE,
- 'description' => 'Tutorial 2: Form with a submit button',
- 'type' => MENU_LOCAL_TASK,
- 'file' => 'form_example_tutorial.inc',
- );
- $items['examples/form_example/tutorial/3'] = array(
- 'title' => '#3',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array('form_example_tutorial_3'),
- 'access callback' => TRUE,
- 'description' => 'Tutorial 3: Fieldsets',
- 'type' => MENU_LOCAL_TASK,
- 'file' => 'form_example_tutorial.inc',
- );
- $items['examples/form_example/tutorial/4'] = array(
- 'title' => '#4',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array('form_example_tutorial_4'),
- 'access callback' => TRUE,
- 'description' => 'Tutorial 4: Required fields',
- 'type' => MENU_LOCAL_TASK,
- 'file' => 'form_example_tutorial.inc',
- );
- $items['examples/form_example/tutorial/5'] = array(
- 'title' => '#5',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array('form_example_tutorial_5'),
- 'access callback' => TRUE,
- 'description' => 'Tutorial 5: More element attributes',
- 'type' => MENU_LOCAL_TASK,
- 'file' => 'form_example_tutorial.inc',
- );
- $items['examples/form_example/tutorial/6'] = array(
- 'title' => '#6',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array('form_example_tutorial_6'),
- 'access callback' => TRUE,
- 'description' => 'Tutorial 6: Form with a validate handler',
- 'type' => MENU_LOCAL_TASK,
- 'file' => 'form_example_tutorial.inc',
- );
- $items['examples/form_example/tutorial/7'] = array(
- 'title' => '#7',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array('form_example_tutorial_7'),
- 'access callback' => TRUE,
- 'description' => 'Tutorial 7: Form with a submit handler',
- 'type' => MENU_LOCAL_TASK,
- 'file' => 'form_example_tutorial.inc',
- );
- $items['examples/form_example/tutorial/8'] = array(
- 'title' => '#8',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array('form_example_tutorial_8'),
- 'access callback' => TRUE,
- 'description' => 'Tutorial 8: Basic multistep form',
- 'type' => MENU_LOCAL_TASK,
- 'file' => 'form_example_tutorial.inc',
- );
- $items['examples/form_example/tutorial/9'] = array(
- 'title' => '#9',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array('form_example_tutorial_9'),
- 'access callback' => TRUE,
- 'description' => 'Tutorial 9: Form with dynamically added new fields',
- 'type' => MENU_LOCAL_TASK,
- 'file' => 'form_example_tutorial.inc',
- 'weight' => 9,
- );
- $items['examples/form_example/tutorial/10'] = array(
- 'title' => '#10',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array('form_example_tutorial_10'),
- 'access callback' => TRUE,
- 'description' => t('Tutorial 11: Form with file upload'),
- 'type' => MENU_LOCAL_TASK,
- 'file' => 'form_example_tutorial.inc',
- 'weight' => 10,
- );
- $items['examples/form_example/states'] = array(
- 'title' => '#states example',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array('form_example_states_form'),
- 'access callback' => TRUE,
- 'description' => 'How to use the #states attribute in FAPI',
- 'file' => 'form_example_states.inc',
- );
- $items['examples/form_example/wizard'] = array(
- 'title' => 'Extensible wizard example',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array('form_example_wizard'),
- 'access callback' => TRUE,
- 'description' => 'A general approach to a wizard multistep form.',
- 'file' => 'form_example_wizard.inc',
- );
- return $items;
-}
-
-function form_example_intro() {
- $markup = t('The form example module provides a tutorial, extensible multistep example, and a #states example');
- return array('#markup' => $markup);
-} \ No newline at end of file
diff --git a/form_example/form_example.test b/form_example/form_example.test
deleted file mode 100644
index cf300b2..0000000
--- a/form_example/form_example.test
+++ /dev/null
@@ -1,176 +0,0 @@
-<?php
-
-/**
- * @file
- * Test file for form_example module.
- */
-
-/**
- * Default test case for the form_example module.
- */
-class FormExampleTestCase extends DrupalWebTestCase {
-
- public static function getInfo() {
- return array(
- 'name' => 'Form Example tests',
- 'description' => 'Various tests on the form example module.' ,
- 'group' => 'Examples',
- );
- }
-
- function setUp() {
- parent::setUp('form_example');
- }
-
- /**
- * Test each tutorial
- */
- function testTutorials() {
- // Tutorial #1
- $this->drupalGet('examples/form_example/tutorial');
- $this->assertText(t('#9'));
-
- // #2
- $this->drupalPost('examples/form_example/tutorial/2', array('name' => t('name')), t('Submit'));
-
- // #4
- $this->drupalPost('examples/form_example/tutorial/4',
- array('first' => t('firstname'), 'last' => t('lastname')), t('Submit'));
- $this->drupalPost('examples/form_example/tutorial/4', array(), t('Submit'));
- $this->assertText(t('First name field is required'));
- $this->assertText(t('Last name field is required'));
-
- // #5
- $this->drupalPost('examples/form_example/tutorial/5',
- array('first' => t('firstname'), 'last' => t('lastname')), t('Submit'));
- $this->assertText(t('Please enter your first name'));
- $this->drupalPost('examples/form_example/tutorial/4', array(), t('Submit'));
- $this->assertText(t('First name field is required'));
- $this->assertText(t('Last name field is required'));
-
- // #6
- $this->drupalPost('examples/form_example/tutorial/6',
- array('first' => t('firstname'), 'last' => t('lastname'), 'year_of_birth' => 1955),
- t('Submit'));
- $this->assertNoText(t('Enter a year between 1900 and 2000'));
- $this->drupalPost('examples/form_example/tutorial/6',
- array('first' => t('firstname'), 'last' => t('lastname'), 'year_of_birth' => 1855),
- t('Submit'));
-
- $this->assertText(t('Enter a year between 1900 and 2000'));
-
- // #7
- $this->drupalPost('examples/form_example/tutorial/7',
- array('first' => t('firstname'), 'last' => t('lastname'), 'year_of_birth' => 1955),
- t('Submit'));
- $this->assertText(t('The form has been submitted. name="firstname lastname", year of birth=1955'));
- $this->drupalPost('examples/form_example/tutorial/7',
- array('first' => t('firstname'), 'last' => t('lastname'), 'year_of_birth' => 1855),
- t('Submit'));
-
- $this->assertText(t('Enter a year between 1900 and 2000'));
-
- // #8
- $this->drupalPost('examples/form_example/tutorial/8',
- array('first' => t('firstname'), 'last' => t('lastname'), 'year_of_birth' => 1955),
- t('Next >>'));
-
- $this->drupalPost(NULL, array('color' => t('green')), t('<< Back'));
- $this->drupalPost(NULL, array(), t('Next >>'));
- $this->drupalPost(NULL, array('color' => t('red')), t('Submit'));
- $this->assertText(t('The form has been submitted. name="firstname lastname", year of birth=1955'));
- $this->assertText(t('And the favorite color is red'));
-
- // #9
- $url = 'examples/form_example/tutorial/9';
- for ($i = 1; $i <= 4; $i++) {
- if ($i > 1) {
- $url = NULL; // later steps of multistep form take NULL.
- }
- $this->drupalPost($url,
- array("name[$i][first]" => "firstname $i", "name[$i][last]" => "lastname $i", "name[$i][year_of_birth]" => 1950 + $i),
- t('Add another name'));
- $this->assertText(t('Name #@num', array('@num' => $i + 1)));
- }
-
- // Now remove the last name added (#5).
- $this->drupalPost(NULL, array(), t('Remove latest name'));
- $this->assertNoText("Name #5");
-
- $this->drupalPost(NULL, array(), t('Submit'));
-
- $this->assertText('Form 9 has been submitted');
- for ($i = 1; $i <= 4; $i++) {
- $this->assertText(t('@num: firstname @num lastname @num (@year)', array('@num' => $i, '@year' => 1950 + $i)));
- }
-
- // #10
- $url = 'examples/form_example/tutorial/10';
-
- $this->drupalPost($url, array(), t('Submit'));
- $this->assertText(t('No file was uploaded.'));
-
- // Get sample images.
- $images = $this->drupalGetTestFiles('image');
- foreach ($images as $image) {
- $this->drupalPost($url, array('files[file]' => drupal_realpath($image->uri)), t('Submit'));
- $this->assertText(t('The form has been submitted and the image has been saved, filename: @filename.', array('@filename' => $image->filename)));
- }
- }
-
- /**
- * Test Wizard tutorial
- * @TODO improve this using drupal_form_submit
- */
- function testWizard() {
- // Is the wizard there
- $this->drupalGet('examples/form_example/wizard');
- $this->assertText(t('Extensible wizard example'));
-
- $first_name = $this->randomName(8);
- $last_name = $this->randomName(8);
- $city = $this->randomName(8);
- $aunts_name = $this->randomName(8);
-
- // Submit the first step of the wizard
- $options = array(
- 'first_name' => $first_name,
- 'last_name' => $last_name,
- );
- $this->drupalPost('examples/form_example/wizard', $options, t('Next'));
-
- // A label city is created, and two buttons appear, Preivous and Next
- $this->assertText(t('Hint: Do not enter "San Francisco", and do not leave this out.'));
-
- // Go back to the beginning and verify that the value is there.
- $this->drupalPost(NULL, array(), t('Previous'));
- $this->assertFieldByName('first_name', $first_name);
- $this->assertFieldByName('last_name', $last_name);
-
- // Go next. We should keep our values.
- $this->drupalPost(NULL, array(), t('Next'));
- $this->assertText(t('Hint: Do not enter "San Francisco", and do not leave this out.'));
-
- // Try "San Francisco".
- $this->drupalPost(NULL, array('city' => 'San Francisco'), t('Next'));
- $this->assertText(t('You were warned not to enter "San Francisco"'));
-
- // Try the real city.
- $this->drupalPost(NULL, array('city' => $city), t('Next'));
-
- // Enter the Aunt's name, but then the previous button.
- $this->drupalPost(NULL, array('aunts_name'=> $aunts_name), t('Previous'));
- $this->assertFieldByName('city', $city);
-
- // Now go forward and then press finish; check for correct values.
- $this->drupalPost(NULL, array(), t('Next'));
- $this->drupalPost(NULL, array('aunts_name' => $aunts_name), t('Finish'));
-
- $this->assertRaw(t('[first_name] =&gt; @first_name', array('@first_name' => $first_name)));
- $this->assertRaw(t('[last_name] =&gt; @last_name', array('@last_name' => $last_name)));
- $this->assertRaw(t('[city] =&gt; @city', array('@city' => $city)));
- $this->assertRaw(t('[aunts_name] =&gt; @aunts_name', array('@aunts_name' => $aunts_name)));
- }
-
-}
-
diff --git a/form_example/form_example_states.inc b/form_example/form_example_states.inc
deleted file mode 100644
index 12ee571..0000000
--- a/form_example/form_example_states.inc
+++ /dev/null
@@ -1,266 +0,0 @@
-<?php
-
-/**
- * @file
- * An example of how to use the new #states Form API element, allowing
- * dynamic form behavior with very simple setup.
- */
-
-/**
- * This form shows off the #states system by dynamically showing parts of the
- * form based on the state of other parts.
- *
- * @ingroup form_example
- *
- * The basic idea is that you add a #states property to the element which is
- * to be changed based on some action elsewhere on the form. The #states
- * property lists a change which is to be made, and under what conditions
- * that change should be made.
- *
- * For example, in the 'tests_taken' form element below we have:
- * @code
- * '#states' => array(
- * 'visible' => array(
- * ':input[name="student_type"]' => array('value' => t('High School')),
- * ),
- * ),
- * @endcode
- * Meaning that the element is to be made visible when the condition is met.
- * The condition is a combination of a jQuery selector (which selects the
- * element we want to test) and a condition for that element. In this case,
- * the condition is whether the value of the 'student_type' element is
- * 'High School'. If it is, this element will be visible.
- *
- * So the syntax is:
- * @code
- * '#states' => array(
- * 'action_to_take_on_this_form_element' => array(
- * 'jquery_selector_for_another_element' => array('condition_type' => value),
- * ),
- * ),
- * @endcode
- *
- * If you need an action to take place only when two different conditions are
- * true, then you add both of those conditions to the action. See the
- * 'country_writein' element below for an example.
- *
- * Note that the easiest way to select a textfield, checkbox, or select is
- * with the @link http://api.jquery.com/input-selector/ ':input' jquery shortcut @endlink,
- * which selects any any of those.
- *
- * There are examples below of changing or hiding an element when a checkbox
- * is checked, when a textarea is filled, when a select has a given value.
- *
- * See drupal_process_states() for full documentation.
- *
- * See also @link http://api.drupal.org/api/drupal/developer--topics--forms_api_reference.html/7#states Form API Reference @endlink
- */
-function form_example_states_form($form, &$form_state) {
- $form['student_type'] = array(
- '#type' => 'radios',
- '#options' => drupal_map_assoc(array(t('High School'), t('Undergraduate'), t('Graduate'))),
- '#title' => t('What type of student are you?')
- );
- $form['high_school'] = array(
- '#type' => 'fieldset',
- '#title' => t('High School Information'),
- // This #states rule says that the "high school" fieldset should only
- // be shown if the "student_type" form element is set to "High School".
- '#states' => array(
- 'visible' => array(
- ':input[name="student_type"]' => array('value' => t('High School')),
- ),
- ),
- );
-
- // High school information.
- $form['high_school']['tests_taken'] = array(
- '#type' => 'checkboxes',
- '#options' => drupal_map_assoc(array(t('SAT'), t('ACT'))),
- '#title' => t('What standardized tests did you take?'),
- // This #states rule says that this checkboxes array will be visible only
- // when $form['student_type'] is set to t('High School').
- // It uses the jQuery selector :input[name=student_type] to choose the
- // element which triggers the behavior, and then defines the "High School"
- // value as the one that triggers visibility.
- '#states' => array(
- 'visible' => array( // action to take.
- ':input[name="student_type"]' => array('value' => t('High School')),
- ),
- ),
- );
-
- $form['high_school']['sat_score'] = array(
- '#type' => 'textfield',
- '#title' => t('Your SAT score:'),
- '#size' => 4,
-
- // This #states rule limits visibility to when the $form['tests_taken']
- // 'SAT' checkbox is checked."
- '#states' => array(
- 'visible' => array( // action to take.
- ':input[name="tests_taken[SAT]"]' => array('checked' => TRUE),
- ),
- ),
- );
- $form['high_school']['act_score'] = array(
- '#type' => 'textfield',
- '#title' => t('Your ACT score:'),
- '#size' => 4,
-
- // Set this element visible if the ACT checkbox above is checked.
- '#states' => array(
- 'visible' => array( // action to take.
- ':input[name="tests_taken[ACT]"]' => array('checked' => TRUE),
- ),
- ),
- );
-
- // Undergrad information.
- $form['undergraduate'] = array(
- '#type' => 'fieldset',
- '#title' => t('Undergraduate Information'),
- // This #states rule says that the "undergraduate" fieldset should only
- // be shown if the "student_type" form element is set to "Undergraduate".
- '#states' => array(
- 'visible' => array(
- ':input[name="student_type"]' => array('value' => t('Undergraduate')),
- ),
- ),
- );
-
- $form['undergraduate']['how_many_years'] = array(
- '#type' => 'select',
- '#title' => t('How many years have you completed?'),
- // The options here are integers, but since all the action here happens
- // using the DOM on the client, we will have to use strings to work with
- // them.
- '#options' => array(
- 1 => t('One'),
- 2 => t('Two'),
- 3 => t('Three'),
- 4 => t('Four'),
- 5 => t('Lots'),
- ),
- );
-
- $form['undergraduate']['comment'] = array(
- '#type' => 'item',
- '#description' => t("Wow, that's a long time."),
- '#states' => array(
- 'visible' => array(
- // Note that '5' must be used here instead of the integer 5.
- // The information is coming from the DOM as a string.
- ':input[name="how_many_years"]' => array('value' => '5'),
- ),
- ),
- );
- $form['undergraduate']['school_name'] = array(
- '#type' => 'textfield',
- '#title' => t('Your college or university:'),
- );
- $form['undergraduate']['school_country'] = array(
- '#type' => 'select',
- '#options' => drupal_map_assoc(array(t('UK'), t('Other'))),
- '#title' => t('In what country is your college or university located?'),
- );
- $form['undergraduate']['country_writein'] = array(
- '#type' => 'textfield',
- '#size' => 20,
- '#title' => t('Please enter the name of the country where your college or university is located.'),
-
- // Only show this field if school_country is set to 'Other'.
- '#states' => array(
- 'visible' => array( // Action to take: Make visible.
- ':input[name="school_country"]' => array('value' => t('Other')),
- ),
- ),
- );
-
- $form['undergraduate']['thanks'] = array(
- '#type' => 'item',
- '#description' => t('Thanks for providing both your school and your country.'),
- '#states' => array(
- // Here visibility requires that two separate conditions be true.
- 'visible' => array(
- 'input[name="school_country"]' => array('value' => t('Other')),
- 'input[name="country_writein"]' => array('filled' => TRUE),
- ),
- ),
- );
- $form['undergraduate']['go_away'] = array(
- '#type' => 'submit',
- '#value' => t('Done with form'),
- '#states' => array(
- // Here visibility requires that two separate conditions be true.
- 'visible' => array(
- 'input[name="school_country"]' => array('value' => t('Other')),
- 'input[name="country_writein"]' => array('filled' => TRUE),
- ),
- ),
- );
-
- // Graduate student information.
- $form['graduate'] = array(
- '#type' => 'fieldset',
- '#title' => t('Graduate School Information'),
- // This #states rule says that the "graduate" fieldset should only
- // be shown if the "student_type" form element is set to "Graduate".
- '#states' => array(
- 'visible' => array(
- ':input[name="student_type"]' => array('value' => t('Graduate')),
- ),
- ),
- );
- $form['graduate']['more_info'] = array(
- '#type' => 'textarea',
- '#title' => t('Please describe your graduate studies'),
- );
-
- $form['graduate']['info_provide'] = array(
- '#type' => 'checkbox',
- '#title' => t('Check here if you have provided information above'),
- '#disabled' => TRUE,
- '#states' => array(
- // Mark this checkbox checked if the "more_info" textarea has something
- // in it, if it's 'filled'.
- 'checked' => array( // Action to take: check the checkbox.
- ':input[name="more_info"]' => array('filled' => TRUE),
- ),
- ),
- );
-
- $form['expand_more_info'] = array(
- '#type' => 'checkbox',
- '#title' => t('Check here if you want to add more information.'),
- );
- $form['more_info'] = array(
- '#type' => 'fieldset',
- '#title' => t('Additional Information'),
- '#collapsible' => TRUE,
- '#collapsed' => TRUE,
-
- // Expand the expand_more_info fieldset if the box is checked.
- '#states' => array(
- 'expanded' => array(
- ':input[name="expand_more_info"]' => array('checked' => TRUE),
- ),
- ),
- );
- $form['more_info']['feedback'] = array(
- '#type' => 'textarea',
- '#title' => t('What do you have to say?'),
- );
-
- $form['submit'] = array(
- '#type' => 'submit',
- '#value' => t('Submit your information'),
- );
-
- return $form;
-}
-
-
-function form_example_states_form_submit($form, &$form_state) {
- drupal_set_message(t('Submitting values: @values', array('@values' => var_export($form_state['values'], TRUE))));
-}
diff --git a/form_example/form_example_tutorial.inc b/form_example/form_example_tutorial.inc
deleted file mode 100644
index a34b95f..0000000
--- a/form_example/form_example_tutorial.inc
+++ /dev/null
@@ -1,756 +0,0 @@
-<?php
-
-/**
- * @file
- * This is the Form API Tutorial from the handbook.
- * TODO: Update this URL, and update it in the dynamic text below.
- * @see http://drupal.org/node/262422
- *
- * It goes through nine form examples in increasing complexity to demonstrate
- * Drupal 7 Form API.
- *
- * Links are provided inline for the related handbook pages.
- */
-
-/**
- * Main Form tutorial page.
- *
- * @see form_example_tutorial_1()
- * @see form_example_tutorial_2()
- * @see form_example_tutorial_3()
- * @see form_example_tutorial_4()
- * @see form_example_tutorial_5()
- * @see form_example_tutorial_6()
- * @see form_example_tutorial_7()
- * @see form_example_tutorial_8()
- * @see form_example_tutorial_9()
- * @see form_example_tutorial_10()
- *
- */
-function form_example_tutorial() {
- return t('This is a set of nine form tutorials tied to the <a href="http://drupal.org/node/262422">Drupal handbook</a>.');
-}
-
-//////////////// Tutorial Example 1 //////////////////////
-/**
- * This first form function is from the @link http://drupal.org/node/717722 Form Tutorial handbook page @endlink
- *
- * It just creates a very basic form with a textfield.
- *
- * This function is called the "form constructor function". It builds the form.
- * It takes a two arguments, $form and $form_state, but if drupal_get_form()
- * sends additional arguments, they will be provided after $form_state.
- *
- * @ingroup form_example
- */
-function form_example_tutorial_1($form, &$form_state) {
-
- $form['description'] = array(
- '#type' => 'item',
- '#title' => t('A form with nothing but a textfield'),
- );
- // This is the first form element. It's a textfield with a label, "Name"
- $form['name'] = array(
- '#type' => 'textfield',
- '#title' => t('Name'),
- );
- return $form;
-}
-
-
-//////////////// Tutorial Example 2 //////////////////////
-
-/**
- * This is Example 2, a basic form with a submit button.
- *
- * @see http://drupal.org/node/717726
- * @ingroup form_example
- */
-function form_example_tutorial_2($form, &$form_state) {
- $form['description'] = array(
- '#type' => 'item',
- '#title' => t('A simple form with a submit button'),
- );
-
- $form['name'] = array(
- '#type' => 'textfield',
- '#title' => t('Name'),
- );
-
- // Adds a simple submit button that refreshes the form and clears its contents -- this is the default behavior for forms.
- $form['submit'] = array(
- '#type' => 'submit',
- '#value' => 'Submit',
- );
- return $form;
-}
-
-//////////////// Tutorial Example 3 //////////////////////
-
-/**
- * Example 3: A basic form with fieldsets.
- *
- * We establish a fieldset element and then place two text fields within
- * it, one for a first name and one for a last name. This helps us group
- * related content.
- *
- * Study the code below and you'll notice that we renamed the array of the first
- * and last name fields by placing them under the $form['name']
- * array. This tells Form API these fields belong to the $form['name'] fieldset.
- *
- * @ingroup form_example
- */
-function form_example_tutorial_3($form, &$form_state) {
- $form['description'] = array(
- '#type' => 'item',
- '#title' => t('A form with a fieldset'),
- );
-
- $form['name'] = array(
- '#type' => 'fieldset',
- '#title' => t('Name'),
- );
- $form['name']['first'] = array(
- '#type' => 'textfield',
- '#title' => t('First name'),
- );
- $form['name']['last'] = array(
- '#type' => 'textfield',
- '#title' => t('Last name'),
- );
-
-
- $form['submit'] = array(
- '#type' => 'submit',
- '#value' => 'Submit',
- );
- return $form;
-}
-
-
-//////////////// Tutorial Example 4 //////////////////////
-
-/**
- * Example 4: Basic form with required fields.
- *
- * @ingroup form_example
- */
-function form_example_tutorial_4($form, &$form_state) {
- $form['description'] = array(
- '#type' => 'item',
- '#title' => t('A form with validation'),
- );
-
- $form['name'] = array(
- '#type' => 'fieldset',
- '#title' => t('Name'),
- // Make the fieldset collapsible.
- '#collapsible' => TRUE, // Added
- '#collapsed' => FALSE, // Added
- );
-
- // Make these fields required.
- $form['name']['first'] = array(
- '#type' => 'textfield',
- '#title' => t('First name'),
- '#required' => TRUE, // Added
- );
- $form['name']['last'] = array(
- '#type' => 'textfield',
- '#title' => t('Last name'),
- '#required' => TRUE, // Added
- );
-
- $form['submit'] = array(
- '#type' => 'submit',
- '#value' => 'Submit',
- );
- return $form;
-}
-
-
-//////////////// Tutorial Example 5 //////////////////////
-
-/**
- * Example 5: Basic form with additional element attributes.
- *
- * This demonstrates additional attributes of text form fields.
- *
- * For a more extensive example on element types
- * @see http://drupal.org/node/751826
- *
- * See the @link http://api.drupal.org/api/file/developer/topics/forms_api.html complete form reference @endlink
- *
- * @ingroup form_example
- */
-function form_example_tutorial_5($form, &$form_state) {
- $form['description'] = array(
- '#type' => 'item',
- '#title' => t('A form with additional attributes'),
- '#description' => t('This one adds #default_value and #description'),
- );
- $form['name'] = array(
- '#type' => 'fieldset',
- '#title' => t('Name'),
- '#collapsible' => TRUE,
- '#collapsed' => FALSE,
- );
-
- $form['name']['first'] = array(
- '#type' => 'textfield',
- '#title' => t('First name'),
- '#required' => TRUE,
- '#default_value' => "First name", // added default value.
- '#description' => "Please enter your first name.", // added description
- '#size' => 20, // added
- '#maxlength' => 20, // added
- );
- $form['name']['last'] = array(
- '#type' => 'textfield',
- '#title' => t('Last name'),
- '#required' => TRUE,
- );
- $form['submit'] = array(
- '#type' => 'submit',
- '#value' => 'Submit',
- );
- return $form;
-}
-
-
-//////////////// Tutorial Example 6 //////////////////////
-
-/**
- * Example 6: A basic form with a validate handler.
- *
- * From http://drupal.org/node/717736
- * @see form_example_tutorial_6_validate()
- *
- */
-function form_example_tutorial_6($form, &$form_state) {
- $form['description'] = array(
- '#type' => 'item',
- '#title' => t('A form with a validation handler'),
- );
-
- $form['name'] = array(
- '#type' => 'fieldset',
- '#title' => t('Name'),
- '#collapsible' => TRUE,
- '#collapsed' => FALSE,
- );
- $form['name']['first'] = array(
- '#type' => 'textfield',
- '#title' => t('First name'),
- '#required' => TRUE,
- '#default_value' => "First name",
- '#description' => "Please enter your first name.",
- '#size' => 20,
- '#maxlength' => 20,
- );
- $form['name']['last'] = array(
- '#type' => 'textfield',
- '#title' => t('Last name'),
- '#required' => TRUE,
- );
-
- // New form field added to permit entry of year of birth.
- // The data entered into this field will be validated with
- // the default validation function.
- $form['year_of_birth'] = array(
- '#type' => 'textfield',
- '#title' => "Year of birth",
- '#description' => 'Format is "YYYY"',
- );
-
- $form['submit'] = array(
- '#type' => 'submit',
- '#value' => 'Submit',
- );
- return $form;
-}
-
-
-
-/**
- * Now we add a handler/function to validate the data entered into the
- * "year of birth" field to make sure it's between the values of 1900
- * and 2000. If not, it displays an error. The value report is
- * $form_state['values'] (see http://drupal.org/node/144132#form-state).
- *
- * Notice the name of the function. It is simply the name of the form
- * followed by '_validate'. This is always the name of the default validation
- * function. An alternate list of validation functions could have been provided
- * in $form['#validate'].
- *
- * @see form_example_tutorial_6()
- *
- */
-function form_example_tutorial_6_validate($form, &$form_state) {
- $year_of_birth = $form_state['values']['year_of_birth'];
- if ($year_of_birth && ($year_of_birth < 1900 || $year_of_birth > 2000)) {
- form_set_error('year_of_birth', t('Enter a year between 1900 and 2000.'));
- }
-}
-
-
-
-//////////////// Tutorial Example 7 //////////////////////
-
-/**
- * Example 7: With a submit handler.
- *
- * From the handbook page:
- * http://drupal.org/node/717740
- *
- * @see form_example_tutorial_7_validate()
- * @see form_example_tutorial_7_submit()
- * @ingroup form_example
- *
- */
-function form_example_tutorial_7($form, &$form_state) {
- $form['description'] = array(
- '#type' => 'item',
- '#title' => t('A form with a submit handler'),
- );
- $form['name'] = array(
- '#type' => 'fieldset',
- '#title' => t('Name'),
- '#collapsible' => TRUE,
- '#collapsed' => FALSE,
- );
- $form['name']['first'] = array(
- '#type' => 'textfield',
- '#title' => t('First name'),
- '#required' => TRUE,
- '#default_value' => "First name",
- '#description' => "Please enter your first name.",
- '#size' => 20,
- '#maxlength' => 20,
- );
- $form['name']['last'] = array(
- '#type' => 'textfield',
- '#title' => t('Last name'),
- '#required' => TRUE,
- );
- $form['year_of_birth'] = array(
- '#type' => 'textfield',
- '#title' => "Year of birth",
- '#description' => 'Format is "YYYY"',
- );
- $form['submit'] = array(
- '#type' => 'submit',
- '#value' => 'Submit',
- );
- return $form;
-}
-
-
-/**
- * Validation function for form_example_tutorial_7().
- *
- */
-function form_example_tutorial_7_validate($form, &$form_state) {
- $year_of_birth = $form_state['values']['year_of_birth'];
- if ($year_of_birth && ($year_of_birth < 1900 || $year_of_birth > 2000)) {
- form_set_error('year_of_birth', t('Enter a year between 1900 and 2000.'));
- }
-}
-
-/**
- * Submit function for form_example_tutorial_7().
- *
- * Adds a submit handler/function to our form to send a successful
- * completion message to the screen.
- */
-function form_example_tutorial_7_submit($form, &$form_state) {
- drupal_set_message(t('The form has been submitted. name="@first @last", year of birth=@year_of_birth',
- array('@first' => $form_state['values']['first'], '@last' => $form_state['values']['last'], '@year_of_birth' => $form_state['values']['year_of_birth'])));
-}
-
-
-//////////////// Tutorial Example 8 //////////////////////
-
-/**
- * Example 8: A simple multistep form with a Next and a Back button.
- *
- * Handbook page: http://drupal.org/node/717750.
- *
- * For more extensive multistep forms, see
- * @link form_example_wizard.inc form_example_wizard.inc @endlink
- *
- *
- * Adds logic to our form builder to give it two pages.
- * The @link ajax_example_wizard AJAX Example's Wizard Example @endlink
- * gives an AJAX version of this same idea.
- *
- * @see form_example_tutorial_8_submit()
- * @see form_example_tutorial_8_validate()
- * @see form_example_tutorial_8_page_two()
- * @see form_example_tutorial_8_page_two_submit()
- * @see form_example_tutorial_8_next_submit()
- * @see form_example_tutorial.inc
- * @ingroup form_example
- */
-function form_example_tutorial_8($form, &$form_state) {
-
- // Display page 2 if $form_state['page_num'] == 1
- if (!empty($form_state['page_num']) && $form_state['page_num'] == 2) {
- return form_example_tutorial_8_page_two($form, $form_state);
- }
-
- // Otherwise we build page 1.
- $form_state['page_num'] = 1;
-
- $form['description'] = array(
- '#type' => 'item',
- '#title' => t('A basic multistep form (page 1)'),
- );
-
- $form['first'] = array(
- '#type' => 'textfield',
- '#title' => t('First name'),
- '#description' => "Please enter your first name.",
- '#size' => 20,
- '#maxlength' => 20,
- '#required' => TRUE,
- '#default_value' => !empty($form_state['values']['first']) ? $form_state['values']['first'] : '',
- );
- $form['last'] = array(
- '#type' => 'textfield',
- '#title' => t('Last name'),
- '#default_value' => !empty($form_state['values']['last']) ? $form_state['values']['last'] : '',
- );
- $form['year_of_birth'] = array(
- '#type' => 'textfield',
- '#title' => "Year of birth",
- '#description' => 'Format is "YYYY"',
- '#default_value' => !empty($form_state['values']['year_of_birth']) ? $form_state['values']['year_of_birth'] : '',
- );
- $form['next'] = array(
- '#type' => 'submit',
- '#value' => 'Next >>',
- '#submit' => array('form_example_tutorial_8_next_submit'),
- '#validate' => array('form_example_tutorial_8_next_validate'),
- );
- return $form;
-}
-
-/**
- * Returns the form for the second page of form_example_tutorial_8().
- */
-function form_example_tutorial_8_page_two($form, &$form_state) {
- $form['description'] = array(
- '#type' => 'item',
- '#title' => t('A basic multistep form (page 2)'),
- );
-
- $form['color'] = array(
- '#type' => 'textfield',
- '#title' => t('Favorite color'),
- '#required' => TRUE,
- '#default_value' => !empty($form_state['values']['color']) ? $form_state['values']['color'] : '',
- );
- $form['submit'] = array(
- '#type' => 'submit',
- '#value' => t('Submit'),
- '#submit' => array('form_example_tutorial_8_page_two_submit'),
- );
- $form['back'] = array(
- '#type' => 'submit',
- '#value' => t('<< Back'),
- '#submit' => array('form_example_tutorial_8_page_two_back'),
- // We won't bother validating the required 'color' field, since they
- // have to come back to this page to submit anyway.
- '#limit_validation_errors' => array(),
- );
- return $form;
-}
-
-
-/**
- * Validate handler for the next button on first page.
- *
- */
-function form_example_tutorial_8_next_validate($form, &$form_state) {
- $year_of_birth = $form_state['values']['year_of_birth'];
- if ($year_of_birth && ($year_of_birth < 1900 || $year_of_birth > 2000)) {
- form_set_error('year_of_birth', t('Enter a year between 1900 and 2000.'));
- }
-}
-
-/**
- * Submit handler for form_example_tutorial_8() next button.
- *
- * Capture the values from page one and store them away so they can be used
- * at final submit time.
- *
- */
-function form_example_tutorial_8_next_submit($form, &$form_state) {
-
- // Values are saved for each page.
- // to carry forward to subsequent pages in the form.
- // and we tell FAPI to rebuild the form.
- $form_state['page_values'][1] = $form_state['values'];
-
- if (!empty($form_state['page_values'][2])) {
- $form_state['values'] = $form_state['page_values'][2];
- }
-
- // When form rebuilds, it will look at this to figure which page to build.
- $form_state['page_num'] = 2;
- $form_state['rebuild'] = TRUE;
-}
-
-/**
- * Back button handler submit handler.
- *
- * Since #limit_validation_errors = array() is set, values from page 2
- * will be discarded. We load the page 1 values instead.
- */
-function form_example_tutorial_8_page_two_back($form, &$form_state) {
- $form_state['values'] = $form_state['page_values'][1];
- $form_state['page_num'] = 1;
- $form_state['rebuild'] = TRUE;
-}
-
-/**
- * The page 2 submit handler.
- *
- * This is the final submit handler. Gather all the data together and output
- * it in a drupal_set_message().
- */
-function form_example_tutorial_8_page_two_submit($form, &$form_state) {
- // Normally, some code would go here to alter the database with the data
- // collected from the form. Instead sets a message with drupal_set_message()
- // to validate that the code worked.
- $page_one_values = $form_state['page_values'][1];
- drupal_set_message(t('The form has been submitted. name="@first @last", year of birth=@year_of_birth',
- array('@first' => $page_one_values['first'], '@last' => $page_one_values['last'], '@year_of_birth' => $page_one_values['year_of_birth'])));
-
- if (!empty($page_one_values['first2'])) {
- drupal_set_message(t('Second name: name="@first @last", year of birth=@year_of_birth',
- array('@first' => $page_one_values['first2'], '@last' => $page_one_values['last2'], '@year_of_birth' => $page_one_values['year_of_birth2'])));
- }
- drupal_set_message(t('And the favorite color is @color', array('@color' => $form_state['values']['color'])));
-
- // If we wanted to redirect on submission, set $form_state['redirect']
- // $form_state['redirect'] = 'node'; // Redirects the user to /node.
-}
-
-//////////////// Tutorial Example 9 //////////////////////
-
-/**
- * Example 9: A form with a dynamically added new fields.
- *
- * This example adds default values so that when the form is rebuilt,
- * the form will by default have the previously-entered values.
- *
- * From handbook page http://drupal.org/node/717746.
- *
- * @see form_example_tutorial_9_add_name()
- * @see form_example_tutorial_9_remove_name()
- * @see form_example_tutorial_9_submit()
- * @see form_example_tutorial_9_validate()
- * @ingroup form_example
- *
- */
-function form_example_tutorial_9($form, &$form_state) {
-
- // We will have many fields with the same name, so we need to be able to
- // access the form hierarchically.
- $form['#tree'] = TRUE;
-
- $form['description'] = array(
- '#type' => 'item',
- '#title' => t('A form with dynamically added new fields'),
- );
-
- if (empty($form_state['num_names'])) {
- $form_state['num_names'] = 1;
- }
-
- // Build the number of name fieldsets indicated by $form_state['num_names']
- for ($i = 1; $i <= $form_state['num_names']; $i++) {
- $form['name'][$i] = array(
- '#type' => 'fieldset',
- '#title' => t('Name #@num', array('@num' => $i)),
- '#collapsible' => TRUE,
- '#collapsed' => FALSE,
- );
-
- $form['name'][$i]['first'] = array(
- '#type' => 'textfield',
- '#title' => t('First name'),
- '#description' => t("Enter first name."),
- '#size' => 20,
- '#maxlength' => 20,
- '#required' => TRUE,
- );
- $form['name'][$i]['last'] = array(
- '#type' => 'textfield',
- '#title' => t('Enter Last name'),
- '#required' => TRUE,
- );
- $form['name'][$i]['year_of_birth'] = array(
- '#type' => 'textfield',
- '#title' => t("Year of birth"),
- '#description' => t('Format is "YYYY"'),
- );
- }
- $form['submit'] = array(
- '#type' => 'submit',
- '#value' => 'Submit',
- );
-
- // Adds "Add another name" button
- $form['add_name'] = array(
- '#type' => 'submit',
- '#value' => t('Add another name'),
- '#submit' => array('form_example_tutorial_9_add_name'),
- );
-
- // If we have more than one name, this button allows removal of the
- // last name.
- if ($form_state['num_names'] > 1) {
- $form['remove_name'] = array(
- '#type' => 'submit',
- '#value' => t('Remove latest name'),
- '#submit' => array('form_example_tutorial_9_remove_name'),
- // Since we are removing a name, don't validate until later.
- '#limit_validation_errors' => array(),
- );
- }
-
- return $form;
-}
-
-/**
- * Submit handler for "Add another name" button on form_example_tutorial_9().
- *
- * $form_state['num_names'] tells the form builder function how many name
- * fieldsets to build, so here we increment it.
- *
- * All elements of $form_state are persisted, so there's no need to use a
- * particular key, like the old $form_state['storage']. We can just use
- * $form_state['num_names'].
- */
-function form_example_tutorial_9_add_name($form, &$form_state) {
- // Everything in $form_state is persistent, so we'll just use
- // $form_state['add_name']
- $form_state['num_names']++;
-
- // Setting $form_state['rebuild'] = TRUE causes the form to be rebuilt again.
- $form_state['rebuild'] = TRUE;
-}
-
-
-function form_example_tutorial_9_remove_name($form, &$form_state) {
- if ($form_state['num_names'] > 1) {
- $form_state['num_names']--;
- }
-
- // Setting $form_state['rebuild'] = TRUE causes the form to be rebuilt again.
- $form_state['rebuild'] = TRUE;
-}
-
-/**
- * Validate function for form_example_tutorial_9().
- *
- * Adds logic to validate the form to check the validity of the new fields,
- * if they exist.
- */
-function form_example_tutorial_9_validate($form, &$form_state) {
-
- for ($i = 1; $i <= $form_state['num_names']; $i++) {
- $year_of_birth = $form_state['values']['name'][$i]['year_of_birth'];
-
- if ($year_of_birth && ($year_of_birth < 1900 || $year_of_birth > 2000)) {
- form_set_error("name][$i][year_of_birth", t('Enter a year between 1900 and 2000.'));
- }
- }
-}
-
-/**
- * Submit function for form_example_tutorial_9().
- */
-function form_example_tutorial_9_submit($form, &$form_state) {
- $output = t("Form 9 has been submitted. ");
- for ($i = 1; $i <= $form_state['num_names']; $i++) {
- $output .= t("@num: @first @last (@date)... ", array('@num' => $i, '@first' => $form_state['values']['name'][$i]['first'],
- '@last' => $form_state['values']['name'][$i]['last'], '@date' => $form_state['values']['name'][$i]['year_of_birth']));
- }
- drupal_set_message($output);
-}
-
-//////////////// Tutorial Example 10 //////////////////////
-
-/**
- * Example 10: A form with a file upload field.
- *
- * This example allows the user to upload a file to Drupal which is stored
- * physically and with a reference in the database.
- *
- * @see form_example_tutorial_10_submit()
- * @see form_example_tutorial_10_validate()
- * @ingroup form_example
- *
- */
-function form_example_tutorial_10($form_state) {
- // enctype="multipart/form-data" required by browsers to handle files.
- $form = array(
- '#attributes' => array('enctype' => "multipart/form-data"),
- );
-
- $form['file'] = array(
- '#type' => 'file',
- '#title' => t('Image'),
- '#description' => t('Upload a file, allowed extensions: jpg, jpeg, png, gif'),
- );
-
- $form['submit'] = array(
- '#type' => 'submit',
- '#value' => t('Submit'),
- );
-
- return $form;
-}
-
-/**
- * Validate handler for form_example_tutorial_10().
- */
-function form_example_tutorial_10_validate($form, &$form_state) {
- $file = file_save_upload('file', array(
- 'file_validate_is_image' => array(), // Validates file is really an image.
- 'file_validate_extensions' => array('png gif jpg jpeg'), // Validate extensions.
- ));
- // If the file passed validation:
- if ($file) {
- // Move the file, into the Drupal file system
- if ($file = file_move($file, 'public://')) {
- // Save the file for use in the submit handler.
- $form_state['storage']['file'] = $file;
- }
- else {
- form_set_error('file', t('Failed to write the uploaded file the site\'s file folder.'));
- }
- }
- else {
- form_set_error('file', t('No file was uploaded.'));
- }
-}
-
-/**
- * Submit handler for form_example_tutorial_10().
- */
-function form_example_tutorial_10_submit($form, &$form_state) {
- $file = $form_state['storage']['file'];
- // We are done with the file, remove it from storage.
- unset($form_state['storage']['file']);
- // Make the storage of the file permanent
- $file->status = FILE_STATUS_PERMANENT;
- // Save file status.
- file_save($file);
- // Set a response to the user.
- drupal_set_message(t('The form has been submitted and the image has been saved, filename: @filename.', array('@filename' => $file->filename)));
-}
diff --git a/form_example/form_example_wizard.inc b/form_example/form_example_wizard.inc
deleted file mode 100644
index 9c59b5b..0000000
--- a/form_example/form_example_wizard.inc
+++ /dev/null
@@ -1,283 +0,0 @@
-<?php
-
-/**
- * @file
- * Estensible wizard form example.
- *
- * This is an example of a multistep form using a wizard style. It will include
- * the 'Previous' and 'Next' buttons when required, and a 'Finish' button at the
- * last stage of the form submission.
- *
- * This example is an extensible skeleton that can include (even
- * programatically) more steps. The demonstration form includes three steps,
- * each step having its own validation functions.
- *
- * How to extend this example:
- * - Steps are defined in the _form_example_steps() function. Include or alter
- * the steps as you require.
- * - For each step, implement the corresponding 'form' function (see
- * 'form_example_wizard_personal_info' for the first step in this example.)
- * Each step is a regular form, and the wizard collects all the values of the
- * included forms.
- * - Optionally, you may include custom validation functions using the regular
- * validation hook (formname_validate). The wizard uses these validation
- * functions for each step.
- * - The most important customization sttep is to change the submit handler and
- * do whatever you want with the collected information. In this case, the
- * example just shows the collected values in the various steps.
- */
-
-/**
- * Return the list of steps and their associated forms. This has been separated
- * to clarify and easy the understanding of this example. You should edit this
- * function to include the steps your wizard/multistep form requires.
- *
- * @return $array
- */
-function _form_example_steps() {
- return array(
- 1 => array(
- 'form' => 'form_example_wizard_personal_info',
- ),
- 2 => array(
- 'form' => 'form_example_wizard_location_info',
- ),
- 3 => array(
- 'form' => 'form_example_wizard_other_info',
- ),
- );
-}
-
-/**
- * The primary formbuilder function for the wizard form. This is the form that
- * you should call with drupal_get_form() from your code, and it will include
- * the rest of the step forms defined. You are not required to change this
- * function, as this will handle all the step actions for you.
- *
- * This form has two defined submit handlers to process the different steps:
- * - Previous: handles the way to get back one step in the wizard.
- * - Next: handles each step form submission,
- *
- * The third handler, the finish button handler, is the default form _submit
- * handler used to process the information.
- *
- * You are not required to change the next or previous handlers, but you must
- * change the form_example_wizard_sbumit handler to perform the operations you
- * need on the collected information.
- */
-function form_example_wizard($form, &$form_state) {
-
- // Initialize a description of the steps for the wizard.
- if (empty($form_state['step'])) {
- $form_state['step'] = 1;
-
- // This array contains the function to be called at each step to get the
- // relevant form elements. It will also store state information for each
- // step.
- $form_state['step_information'] = _form_example_steps();
- }
- $step = &$form_state['step'];
- drupal_set_title(t('Extensible Wizard: Step @step', array('@step' => $step)));
-
- // Call the function named in $form_state['step_information'] to get the
- // form elements to display for this step.
- $form = $form_state['step_information'][$step]['form']($form, $form_state);
-
- // Show the 'previous' button if appropriate. Note that #submit is set to
- // a special submit handler, and that we use #limit_validation_errors to
- // skip all complaints about validation when using the back button. The
- // values entered will be discarded, but they will not be validated, which
- // would be annoying in a "back" button.
- if ($step > 1) {
- $form['prev'] = array(
- '#type' => 'submit',
- '#value' => t('Previous'),
- '#name' => 'prev',
- '#submit' => array('form_example_wizard_previous_submit'),
- '#limit_validation_errors' => array(),
- );
- }
-
- // Show the Next button only if there are more steps defined.
- if ($step < count($form_state['step_information'])) {
- // The Next button should be included on every step
- $form['next'] = array(
- '#type' => 'submit',
- '#value' => t('Next'),
- '#name' => 'next',
- '#submit' => array('form_example_wizard_next_submit'),
- );
- }
- else {
- // Just in case there are no more steps, we use the default submit handler of
- // the form wizard. Call this button Finish, Submit, or whatever you want to
- // show. When this button is clicked, the form_example_wizard_submit handler
- // will be called.
- $form['finish'] = array(
- '#type' => 'submit',
- '#value' => t('Finish'),
- );
- }
-
- // Include each validation function defined for the different steps.
- if (function_exists($form_state['step_information'][$step]['form'] . '_validate')) {
- $form['next']['#validate'] = array($form_state['step_information'][$step]['form'] . '_validate');
- }
-
- return $form;
-}
-
-/**
- * Submit handler for the "previous" button.
- * - Stores away $form_state['values']
- * - Decrements the step counter
- * - Replaces $form_state['values'] with the values from the previous state.
- * - Forces form rebuild.
- *
- * You are not required to change this function.
- */
-function form_example_wizard_previous_submit($form, &$form_state) {
- $current_step = &$form_state['step'];
- $form_state['step_information'][$current_step]['stored_values'] = $form_state['values'];
- if ($current_step > 1) {
- $current_step--;
- $form_state['values'] = $form_state['step_information'][$current_step]['stored_values'];
- }
- $form_state['rebuild'] = TRUE;
-}
-
-/**
- * Submit handler for the 'next' button.
- * - Saves away $form_state['values']
- * - Increments the step count.
- * - Replace $form_state['values'] from the last time we were at this page
- * or with array() if we haven't been here before.
- * - Force form rebuild.
- *
- * You are not required to change this function.
- *
- * @param unknown_type $form
- * @param unknown_type $form_state
- */
-function form_example_wizard_next_submit($form, &$form_state) {
- $current_step = &$form_state['step'];
- $form_state['step_information'][$current_step]['stored_values'] = $form_state['values'];
-
- if ($current_step < count($form_state['step_information'])) {
- $current_step++;
- if (!empty($form_state['step_information'][$current_step]['stored_values'])) {
- $form_state['values'] = $form_state['step_information'][$current_step]['stored_values'];
- }
- else {
- $form_state['values'] = array();
- }
- $form_state['rebuild'] = TRUE; // Force rebuild with next step.
- return;
- }
-}
-
-// The previous code was a 'skeleton' of a multistep wizard form. You are not
-// required to change a line on the previous code (apart from defining your own
-// steps in the _form_example_steps() function.
-//
-// All the code included from here is the content of the wizard, the steps of
-// the form.
-
-// First, let's show the defined steps for the wizard example.
-
-/**
- * Returns form elements for the 'personal info' page of the wizard. This is the
- * first step of the wizard, asking for two textfields: first name and last
- * name.
- */
-function form_example_wizard_personal_info($form, &$form_state) {
- $form = array();
- $form['first_name'] = array(
- '#type' => 'textfield',
- '#title' => t('First Name'),
- '#default_value' => !empty($form_state['values']['first_name']) ? $form_state['values']['first_name'] : '',
- );
- $form['last_name'] = array(
- '#type' => 'textfield',
- '#title' => t('Last Name'),
- '#default_value' => !empty($form_state['values']['last_name']) ? $form_state['values']['last_name'] : '',
- );
- return $form;
-}
-
-/**
- * Returns form elements for the 'location info' page of the wizard. This is the
- * second step of the wizard. This step asks for a textfield value: a City. This
- * step also includes a validation declared later.
- */
-function form_example_wizard_location_info($form, &$form_state) {
- $form = array();
- $form['city'] = array(
- '#type' => 'textfield',
- '#title' => t('City'),
- '#description' => t('Hint: Do not enter "San Francisco", and do not leave this out.'),
- '#required' => TRUE,
- '#default_value' => !empty($form_state['values']['city']) ? $form_state['values']['city'] : '',
-
- );
- return $form;
-}
-
-/**
- * Custom validation form for the 'location info' page of the wizard. This is the
- * validation function for the second step of the wizard. The city cannot be empty
- * or be "San Francisco".
- */
-function form_example_wizard_location_info_validate($form, &$form_state) {
- if ($form_state['values']['city'] == 'San Francisco') {
- form_set_error('city', t('You were warned not to enter "San Francisco"'));
- }
-}
-
-/**
- * Returns form elements for the 'other info' page of the wizard. This is the
- * thid and last step of the example wizard.
- */
-function form_example_wizard_other_info($form, &$form_state) {
- $form = array();
- $form['aunts_name'] = array(
- '#type' => 'textfield',
- '#title' => t("Your first cousin's aunt's Social Security number"),
- '#default_value' => !empty($form_state['values']['aunts_name']) ? $form_state['values']['aunts_name'] : '',
- );
- return $form;
-}
-
-// And now comes the magic of the wizard, the function that should handle all the
-// inputs from the user on each different step.
-/**
- * Wizard form submit handler.
- * - Saves away $form_state['values']
- * - Process all the form values.
- *
- * This demonstration handler just do a drupal_set_message() with the information
- * collected on each different step of the wizard.
- *
- * @param unknown_type $form
- * @param unknown_type $form_state
- */
-function form_example_wizard_submit($form, &$form_state) {
- $current_step = &$form_state['step'];
- $form_state['step_information'][$current_step]['stored_values'] = $form_state['values'];
-
- // In this case we've completed the final page of the wizard, so process the
- // submitted information.
- drupal_set_message(t('This information was collected by this wizard:'));
- foreach($form_state['step_information'] as $index => $value) {
- // Remove FAPI fields included in the values (form_token, form_id and form_build_id
- // This is not required, you may access the values using $value['stored_values']
- // but I'm removing them to make a more clear representation of the collected
- // information as the complete array will be passed through drupal_set_message().
- unset($value['stored_values']['form_id']);
- unset($value['stored_values']['form_build_id']);
- unset($value['stored_values']['form_token']);
-
- // Now show all the values.
- drupal_set_message(t('Step @num collected the following values: <pre>@result</pre>', array('@num' => $index, '@result' => print_r($value['stored_values'], TRUE))));
- }
-}
diff --git a/image_example/image_example.info b/image_example/image_example.info
deleted file mode 100644
index 29f0811..0000000
--- a/image_example/image_example.info
+++ /dev/null
@@ -1,8 +0,0 @@
-
-name = Image Example
-description = Example implementation of image.module hooks.
-package = Example modules
-core = 7.x
-core = 7.x
-dependencies[] = image
-files[] = image_example.test
diff --git a/image_example/image_example.install b/image_example/image_example.install
deleted file mode 100644
index 926d6da..0000000
--- a/image_example/image_example.install
+++ /dev/null
@@ -1,46 +0,0 @@
-<?php
-
-/**
- * @file
- * Installation and update functions for image_example.module.
- */
-
-/**
- * Implements hook_install(),
- */
-function image_example_install() {
- // Set a variable containing the name of the style to use when the module
- // outputs an image.
- variable_set('image_example_style_name', 'image_example_style');
-}
-
-/**
- * Implements hook_uninstall().
- */
-function image_example_uninstall() {
- variable_del('image_example_style_name');
- variable_del('image_example_image_fid');
-}
-
-/**
- * Implements hook_enable().
- */
-function image_example_enable() {
- // There is currently no way to manually flush an image style which causes
- // problems when installing a new module that implements
- // hook_image_styles_alter(). If the new module modifies an image style that
- // modification will not be applied to any images that have already been
- // generated unless the styles are flushed. This is one way around that.
- $styles = image_styles();
- foreach ($styles as $style) {
- image_style_flush($style);
- }
-}
-
-/**
- * Implemements hook_disable().
- */
-function image_example_disable() {
- // Solves the same problem as image_example_enable().
- image_example_enable();
-}
diff --git a/image_example/image_example.module b/image_example/image_example.module
deleted file mode 100644
index 89118b3..0000000
--- a/image_example/image_example.module
+++ /dev/null
@@ -1,372 +0,0 @@
-<?php
-
-/**
- * @file
- * Image example module demonstrates basic use of image API.
- *
- * This module demonstrates the use of Drupal 7's new image styles and effects
- * including the following topics.
- * - Define default image styles in code. Useful for modules that want to ship
- * with predefined image styles and for site developers who want their image
- * style configurations to be in version control.
- * hook_image_default_styles().
- * - Define new image effects. Demonstrates how a module can add additional
- * effects to the options available when creating image styles.
- * hook_image_effect_info().
- * - Alter existing image styles. Demonstrates the use of
- * hook_image_styles_alter() to modify existing image effects, especially
- * those defined by other modules in hook_image_default_styles() without
- * having to override the styles.
- * - Demonstrates the use of hook_image_style_save() and
- * hook_image_style_delete() to update module specific variables when an
- * image style is either re-named or deleted.
- * - Generate a form with a field of type #managed_file that allows the user
- * to upload an image and choose a style to use when displaying that image.
- * - Demonstrates the use of theme_image_style() to display images using an
- * image style.
- *
- * @see hook_image_default_styles().
- * @see hook_image_effect_info().
- * @see hook_image_style_save().
- * @see hook_image_style_delete().
- * @see theme_image_style().
- */
-
-/**
- * Implements hook_menu().
- *
- * Provide a menu item and a page to demonstrate features of this example
- * module.
- */
-function image_example_menu() {
- $items = array();
- $items['image_example/styles'] = array(
- 'title' => 'Image Example',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array('image_example_style_form'),
- 'access arguments' => array('access content'),
- 'file' => 'image_example.pages.inc',
- );
- return $items;
-}
-
-/**
- * Implements hook_help().
- */
-function image_example_help($path) {
- switch ($path) {
- case 'image_example/styles':
- $output = '<p>' . t('Use this form to upload an image and choose an Image Style to use when displaying the image. This demonstrates basic use of the Drupal 7 Image styles & effects system.') . '</p>';
- $output .= '<p>' . t('Image styles can be added/edited using the !link.', array('!link' => l(t('Image styles UI'), 'admin/config/media/image-styles'))) . '</p>';
- return $output;
- }
-}
-
-/**
- * Implements hook_image_default_styles().
- *
- * hook_image_default_styles() declares to Drupal any image styles that are
- * provided by the module. An image style is a collection of image effects that
- * are performed in a specified order, manipulating the image and generating a
- * new derivative image.
- *
- * This hook can be used to declare image styles that your module depends on or
- * allow you to define image styles in code and gain the benefits of using
- * a version control system.
- */
-function image_example_image_default_styles() {
- // This hook returns an array, each component of which describes an image
- // style. The array keys are the machine-readable image style names and
- // to avoid namespace conflicts should begin with the name of the
- // implementing module. e.g.) 'mymodule_stylename'. Styles names should
- // use only alpha-numeric characters, underscores (_), and hyphens (-).
- $styles = array();
- $styles['image_example_style'] = array();
-
- // Each style array consists of an 'effects' array that is made up of
- // sub-arrays which define the individual image effects that are combined
- // together to create the image style.
- $styles['image_example_style']['effects'] = array(
- array(
- // Name of the image effect. See image_image_effect_info() in
- // modules/image/image.effects.inc for a list of image effects available
- // in Drupal 7 core.
- 'name' => 'image_scale',
- // Arguments to pass to the effect callback function.
- // The arguments that an effect accepts are documented with each
- // individual image_EFFECT_NAME_effect function. See image_scale_effect()
- // for an example.
- 'data' => array(
- 'width' => 100,
- 'height' => 100,
- 'upscale' => 1,
- ),
- // The order in which image effects should be applied when using this
- // style.
- 'weight' => 0,
- ),
- // Add a second effect to this image style. Effects are executed in order
- // and are cummulative. When applying an image style to an image the result
- // will be the combination of all effects associated with that style.
- array(
- 'name' => 'image_example_colorize',
- 'data' => array(
- 'color' => '#FFFF66',
- ),
- 'weight' => 1,
- ),
- );
-
- return $styles;
-}
-
-/**
- * Implements hook_image_style_save().
- *
- * Allows modules to respond to updates to an image style's
- * settings.
- */
-function image_example_image_style_save($style) {
- // The $style parameter is an image style array with one notable exception.
- // When a user has choosen to replace a deleted style with another style the
- // $style['name'] property contains the name of the replacement style and
- // $style['old_name'] contains the name of the style being deleted.
-
- // Here we update a variable that contains the name of the image style that
- // the block provided by this module uses when formating images to use the
- // new user choosen style name.
- if (isset($style['old_name']) && $style['old_name'] == variable_get('image_example_style_name', '')) {
- variable_set('image_example_style_name', $style['name']);
- }
-}
-
-/**
- * Implements hook_image_style_delete().
- *
- * This hook allows modules to respond to image styles being deleted.
- *
- * @see image_example_style_save()
- */
-function image_example_image_style_delete($style) {
- // See information about $style paramater in documentation for
- // image_example_style_save().
-
- // Update the modules variable that contains the name of the image style
- // being deleted to the name of the replacement style.
- if (isset($style['old_name']) && $style['old_name'] == variable_get('image_example_style_name', '')) {
- variable_set('image_example_style_name', $style['name']);
- }
-}
-
-/**
- * Implements hook_image_style_flush().
- *
- * This hook allows modules to respond when a style is being flushed. Styles
- * are flushed any time a style is updated, an effect associated with the style
- * is updated, a new effect is added to the style, or an existing effect is
- * removed.
- *
- * Flushing removes all images generated using this style from the host. Once a
- * style has been flushed derivative images will need to be regenerated. New
- * images will be generated automatically as needed but it is worth noting that
- * on a busy site with lots of images this could have an impact on performance.
- *
- * Note: This function does not currently have any effect as the example module
- * does not use any caches. It is demonstrated here for completeness sake only.
- */
-function image_example_style_flush($style) {
- // The $style parameter is an image style array.
-
- // Empty any caches populated by our module that could contain stale data
- // after the style has been flushed. Stale data occurs because the module may
- // have cached content with a reference to the derivative image which is
- // being deleted.
- cache_clear_all('*', 'image_example', TRUE);
-}
-
-/**
- * Implements hook_image_styles_alter().
- *
- * Allows your module to modify, add, or remove image styles provided
- * by other modules. The best use of this hook is to modify default styles that
- * have not been overriden by the user. Altering styles that have been
- * overriden by the user could have an adverse affect on the user experience.
- * If you add an effect to a style through this hook and the user attempts to
- * remove the effect it will immediatly be re-applied.
- */
-function image_example_image_styles_alter(&$styles) {
- // The $styles paramater is an array of image style arrays keyed by style
- // name. You can check to see if a style has been overriden by checking the
- // $styles['stylename']['storage'] property.
-
- // Verify that the effect has not been overriden.
- if ($styles['thumbnail']['storage'] == IMAGE_STORAGE_DEFAULT) {
- // Add an additional colorize effect to the system provided thumbnail
- // effect.
- $styles['thumbnail']['effects'][] = array(
- 'label' => t('Colorize #FFFF66'),
- 'name' => 'image_example_colorize',
- 'effect callback' => 'image_example_colorize_effect',
- 'data' => array(
- 'color' => '#FFFF66',
- ),
- 'weight' => 1,
- );
- }
-}
-
-/**
- * Implements hook_image_effect_info().
- *
- * This hook allows your module to define additional image manipulation effects
- * that can be used with image styles.
- */
-function image_example_image_effect_info() {
- $effects = array();
-
- // The array is keyed on the machine-readable effect name.
- $effects['image_example_colorize'] = array(
- // Human readable name of the effect.
- 'label' => t('Colorize'),
- // (optional) Brief description of the effect that will be shown when
- // adding or configuring this image effect.
- 'help' => t('The colorize effect will first remove all color from the source image and then tint the image using the color specified.'),
- // Name of function called to perform this effect.
- 'effect callback' => 'image_example_colorize_effect',
- // (optional) Name of function that provides a $form array with options for
- // configuring the effect. Note that you only need to return the fields
- // specific to your module. Submit buttons will be added automatically, and
- // configuration options will be serailized and added to the 'data' element
- // of the effect. The function will recieve the $effect['data'] array as
- // its only parameter.
- 'form callback' => 'image_example_colorize_form',
- // (optional) Name of a theme function that will output a summary of this
- // effects configuation. Used when displaying list of effects associated
- // with an image style. In this example the function
- // theme_image_example_colorize_summary will be called via the theme()
- // function. Your module must also implement hook_theme() in order for this
- // function to work correctly. See image_example_theme() and
- // theme_image_example_colorize_summary().
- 'summary theme' => 'image_example_colorize_summary',
- );
-
- return $effects;
-}
-
-/**
- * Form Builder; Configuration settings for colorize effect.
- *
- * Create a $form array with the fields necessary for configuring the
- * image_example_colorize effect.
- *
- * Note that this is not a complete form, it only contains the portion of the
- * form for configuring the colorize options. Therefore it does not not need to
- * include metadata about the effect, nor a submit button.
- *
- * @param $data
- * The current configuration for this colorize effect.
- */
-function image_example_colorize_form($data) {
- $form = array();
- // You do not need to worry about handling saving/updating/deleting of the
- // data collected. The image module will automatically serialize and store
- // all data associated with an effect.
- $form['color'] = array(
- '#type' => 'textfield',
- '#title' => t('Color'),
- '#description' => t('The color to use when colorizing the image. Use web-style hex colors. e.g.) #FF6633.'),
- '#default_value' => isset($data['color']) ? $data['color'] : '',
- '#size' => 7,
- '#max_length' => 7,
- '#required' => TRUE,
- );
- return $form;
-}
-
-/**
- * Image effect callback; Colorize an image resource.
- *
- * @param $image
- * An image object returned by image_load().
- * @param $data
- * An array of attributes to use when performing the colorize effect with the
- * following items:
- * - "color": The web-style hex color to use when colorizing the image.
- * @return
- * TRUE on success. FALSE on failure to colorize image.
- */
-function image_example_colorize_effect(&$image, $data) {
- // Image manipulation should be done to the $image->resource, which will be
- // automatically saved as a new image once all effects have been applied.
- // If your effect makes changes to the $image->resource that relate to any
- // information stored in the $image->info array (width, height, etc.) you
- // should update that information as well. See modules/system/image.gd.inc
- // for examples of functions that perform image manipulations.
-
- // Not all GD installations are created equal. It is a good idea to check for
- // the existence of image manipulation functions before using them.
- // PHP installations using non-bundled GD do not have imagefilter(). More
- // information about image manipulation functions is available in the PHP
- // manual. http://www.php.net/manual/en/book.image.php
- if (!function_exists('imagefilter')) {
- watchdog('image', 'The image %image could not be colorized because the imagefilter() function is not available in this PHP installation.', array('%file' => $image->source));
- return FALSE;
- }
-
- // Verify that Drupal is using the PHP GD library for image manipulations
- // since this effect depends on functions in the GD library.
- if ($image->toolkit != 'gd') {
- watchdog('image', 'Image colorize failed on %path. Using non GD toolkit.', array('%path' => $image->source), WATCHDOG_ERROR);
- return FALSE;
- }
-
- // Convert short #FFF syntax to full #FFFFFF syntax.
- if (strlen($data['color']) == 4) {
- $c = $data['color'];
- $data['color'] = $c[0] . $c[1] . $c[1] . $c[2] . $c[2] . $c[3] . $c[3];
- }
-
- // Convert #FFFFFF syntax to hexadecimal colors.
- $data['color'] = hexdec(str_replace('#', '0x', $data['color']));
-
- // Convert the hexadecimal color value to a color index value.
- $rgb = array();
- for ($i = 16; $i >= 0; $i -= 8) {
- $rgb[] = (($data['color'] >> $i) & 0xFF);
- }
-
- // First desaturate the image, and then apply the new color.
- imagefilter($image->resource, IMG_FILTER_GRAYSCALE);
- imagefilter($image->resource, IMG_FILTER_COLORIZE, $rgb[0], $rgb[1], $rgb[2]);
-
- return TRUE;
-}
-
-/**
- * Implements hook_theme().
- */
-function image_example_theme() {
- return array(
- 'image_example_colorize_summary' => array(
- 'variables' => array('data' => NULL),
- ),
- 'image_example_image' => array(
- 'variables' => array('image' => NULL, 'style' => NULL),
- 'file' => 'image_example.pages.inc',
- ),
- );
-}
-
-/**
- * Formats a summary of an image colorize effect.
- *
- * @param $variables
- * An associative array containing:
- * - data: The current configuration for this colorize effect.
- *
- * @ingroup themeable
- */
-function theme_image_example_colorize_summary($variables) {
- $data = $variables['data'];
- return t('as color #@color.', array('@color' => $data['color']));
-}
diff --git a/image_example/image_example.pages.inc b/image_example/image_example.pages.inc
deleted file mode 100644
index c7206e1..0000000
--- a/image_example/image_example.pages.inc
+++ /dev/null
@@ -1,147 +0,0 @@
-<?php
-
-/**
- * @file
- * Page/form showing image styles in use.
- *
- */
-
-/**
- * Form for uploading and displaying an image using selected style.
- *
- * This page provides a form that allows the user to upload an image and choose
- * a style from the list of defined image styles to use when displaying the
- * the image. This serves as an example of integrating image styles with your
- * module and as a way to demonstrate that the styles and effects defined by
- * this module are available via Drupal's image handling system.
- *
- * @see theme_image_style().
- */
-function image_example_style_form($form, &$form_state) {
- // If there is already an uploaded image display the image here.
- if ($image_fid = variable_get('image_example_image_fid', FALSE)) {
- $image = file_load($image_fid);
- $style = variable_get('image_example_style_name', 'thumbnail');
- $form['image'] = array(
- '#markup' => theme('image_example_image', array('image' => $image, 'style' => $style)),
- );
- }
-
- // Use the #managed_file FAPI element to upload an image file.
- $form['image_example_image_fid'] = array(
- '#title' => t('Image'),
- '#type' => 'managed_file',
- '#description' => t('The uploaded image will be displayed on this page using the image style choosen below.'),
- '#default_value' => variable_get('image_example_image_fid', ''),
- '#upload_location' => 'public://image_example_images/',
- );
-
- // Provide a select field for choosing an image style to use when displaying
- // the image.
- $form['image_example_style_name'] = array(
- '#title' => t('Image style'),
- '#type' => 'select',
- '#description' => t('Choose an image style to use when displaying this image.'),
- // The image_style_options() function returns an array of all available
- // image styles both the key and the value of the array are the image
- // style's name. The fucntion takes on paramater, a boolean flag
- // signifying wether or not the array should include a <none> option.
- '#options' => image_style_options(TRUE),
- '#default_value' => variable_get('image_example_style_name', ''),
- );
-
- // Submit Button.
- $form['submit'] = array(
- '#type' => 'submit',
- '#value' => t('Save'),
- );
-
- return $form;
-}
-
-/**
- * Verify that the user supplied an image with the form..
- */
-function image_example_style_form_validate($form, &$form_state) {
- if (!isset($form_state['values']['image_example_image_fid']) || !is_numeric($form_state['values']['image_example_image_fid'])) {
- form_set_error('image_example_image_fid', t('Please select an image to upload.'));
- }
-}
-
-/**
- * Form Builder; Display a form for uploading an image.
- */
-function image_example_style_form_submit($form, &$form_state) {
- // When using the #managed_file form element the file is automatically
- // uploaded an saved to the {file} table. The value of the corresponding
- // form element is set to the {file}.fid of the new file.
-
-
- // If fid is not 0 we have a valid file.
- if ($form_state['values']['image_example_image_fid'] != 0) {
- // The new file's status is set to 0 or temporary and in order to ensure
- // that the file is not removed after 6 hours we need to change it's status
- // to 1. Save the ID of the uploaded image for later use.
- $file = file_load($form_state['values']['image_example_image_fid']);
- $file->status = FILE_STATUS_PERMANENT;
- file_save($file);
-
- // When a module is managing a file, it must manage the usage count.
- // Here we increment the usage count with file_usage_add().
- file_usage_add($file, 'image_example', 'sample_image', 1);
-
- // Save the fid of the file so that the module can reference it later.
- variable_set('image_example_image_fid', $file->fid);
- drupal_set_message(t('The image @image_name was uploaded and saved with an ID of @fid and will be displayed using the style @style.', array('@image_name' => $file->filename, '@fid' => $file->fid, '@style' => $form_state['values']['image_example_style_name'])));
- }
- // If the file was removed we need to remove the module's reference to the
- // removed file's fid, and remove the file.
- else if ($form_state['values']['image_example_image_fid'] == 0) {
- // Retrieve the old file's id.
- $fid = variable_get('image_example_image_fid', FALSE);
- $file = $fid ? file_load($fid) : FALSE;
- if ($file) {
- // When a module is managing a file, it must manage the usage count.
- // Here we decrement the usage count with file_usage_delete().
- file_usage_delete($file, 'image_example', 'sample_image', 1);
-
- // The file_delete() function takes a file object and checks to see if
- // the file is being used by any other modules. If it is the delete
- // operation is cancelled, otherwise the file is deleted.
- file_delete($file);
- }
-
- // Either way the module needs to update it's reference since even if the
- // file is in use by another module and not deleted we no longer want to
- // use it.
- variable_set('image_example_image_fid', FALSE);
- drupal_set_message(t('The image @image_name was removed.', array('@image_name' => $file->filename)));
- }
-
- // Save the name of the image style choosen by the user.
- variable_set('image_example_style_name', $form_state['values']['image_example_style_name']);
-}
-
-/**
- * Theme function displays an image rendered using the specified style.
- */
-function theme_image_example_image($variables) {
- $image = $variables['image'];
- $style = $variables['style'];
-
- // theme_image_style() is the primary method for displaying images using
- // one of the defined styles. The $variables array passed to the theme
- // contains the following two important values:
- // 'style_name': the name of the image style to use when displaying the
- // image.
- // 'path': the $file->uri of the image to display.
- // When given a style and an image path the function will first determine
- // if a derivative image already exists, in which case the existing image
- // will be displayed. If the derivative image does not already exist the
- // function returns an <img> tag with a specially crafted callback URL
- // as the src attribute for the tag. When accessed, the callback URL will
- // generate the derivative image and serve it to the browser.
- $output = theme('image_style', array('style_name' => $style, 'path' => $image->uri, 'getsize' => FALSE));
- $output .= '<p>' . t('This image is being displayed using the image style %style_name.', array('%style_name' => $style)) . '</p>';
- return $output;
-} \ No newline at end of file
diff --git a/image_example/image_example.test b/image_example/image_example.test
deleted file mode 100644
index 788f635..0000000
--- a/image_example/image_example.test
+++ /dev/null
@@ -1,103 +0,0 @@
-<?php
-
-/**
- * @file
- * Test case for testing the image example module.
- *
- * This file contains the tests cases to check if the module is performing as
- * expected.
- */
-class ImageExampleTestCase extends DrupalWebTestCase {
- protected $web_user;
-
- public static function getInfo() {
- return array(
- 'name' => 'Image example functionality',
- 'description' => 'Test functionality of the Image Example module.',
- 'group' => 'Examples',
- );
- }
-
- /**
- * Enable modules and create user with specific permissions.
- */
- function setUp() {
- parent::setUp('image_example');
- // Create user with permission to administer image styles.
- $this->web_user = $this->drupalCreateUser(array('administer image styles', 'administer blocks'));
- }
-
- /**
- * Test implementations of image API hooks.
- */
- function testImageExample() {
- // Login the admin user.
- $this->drupalLogin($this->web_user);
-
- // Verify that the default style added by
- // image_example_image_default_styles() is in the list of image styles.
- $image_styles = image_styles();
- $this->assertTrue(isset($image_styles['image_example_style']), t('The default style image_example_style is in the list of image styles.'));
-
- // Verify that the effect added to the default 'thumbnail' style by
- // image_example_image_styles_alter() is present.
- $this->assertTrue((isset($image_styles['thumbnail']['effects'][1]['name']) && $image_styles['thumbnail']['effects'][1]['name'] == 'image_example_colorize'), t('Effect added to the thumbnail style via hook_image_styles_alter() is present.'));
-
- // Create a new image style and add the effect provided by
- // image_example_effect_info().
- $new_style = array('name' => strtolower($this->randomName()));
- $new_style = image_style_save($new_style);
- $this->assertTrue(isset($new_style['isid']), t('Image style @style_name created.', array('@style_name' => $new_style['name'])));
-
- $edit = array(
- 'new' => 'image_example_colorize',
- );
- $this->drupalPost('admin/config/media/image-styles/edit/' . $new_style['name'], $edit, t('Add'));
-
- // Verify the 'color' field provided by image_example_colorize_form()
- // appears on the effect configuration page. And that we can fill it out.
- $this->assertField('data[color]', t('Color field provided by image_example_effect_colorize_form is present on effect configuration page.'));
- $edit = array(
- 'data[color]' => '#000000',
- );
- $this->drupalPost(NULL, $edit, t('Add effect'));
- $this->assertText(t('The image effect was successfully applied.'), t('Colorize effect added to @style_name.', array('@style_name' => $new_style['name'])));
-
- // Set the variable 'image_example_style_name' to the name of our new style
- // then rename the style and ensure the variable name is changed.
-
- // @todo Enable this block once http://drupal.org/node/713872 is fixed.
- if (defined('bug_713872_fixed')) {
- $style = image_style_load($new_style['name']);
- variable_set('image_example_style_name', $style['name']);
- $style['name'] = strtolower($this->randomName());
- $style = image_style_save($style);
- $variable = variable_get('image_example_style_name', '');
- $this->assertTrue(($variable == $style['name']), t('Variable image_example_style_name successfully updated when renaming image style.'));
- }
- }
-
- /**
- * Tests for image block provided by module.
- */
- function testImageExamplePage() {
- // Login the admin user.
- $this->drupalLogin($this->web_user);
- $this->drupalCreateNode(array('promote' => 1));
-
- // Upload an image to the image page.
- $images = $this->drupalGetTestFiles('image');
- $edit = array(
- 'files[image_example_image_fid]' => drupal_realpath($images[0]->uri),
- 'image_example_style_name' => 'image_example_style',
- );
- $this->drupalPost('image_example/styles', $edit, t('Save'));
- $this->assertText(t('The image @image_name was uploaded', array('@image_name' => $images[0]->filename)), t('Image uploaded to image block.'));
-
- // Verify the image is displayed.
- $this->drupalGet('image_example/styles');
- $fid = variable_get('image_example_image_fid', FALSE);
- $image = isset($fid) ? file_load($fid) : NULL;
- $this->assertRaw(file_uri_target($image->uri), t('Image is displayed'));
- }
-}
diff --git a/js_example/accordion.tpl.php b/js_example/accordion.tpl.php
deleted file mode 100644
index 6258826..0000000
--- a/js_example/accordion.tpl.php
+++ /dev/null
@@ -1,54 +0,0 @@
-<?php
-?>
-<div class="demo">
-<h2><?php print $title; ?></h2>
-<div id="accordion">
- <h3><a href="#">Section 1</a></h3>
- <div>
- <p>
- Mauris mauris ante, blandit et, ultrices a, suscipit eget, quam. Integer
- ut neque. Vivamus nisi metus, molestie vel, gravida in, condimentum sit
- amet, nunc. Nam a nibh. Donec suscipit eros. Nam mi. Proin viverra leo ut
- odio. Curabitur malesuada. Vestibulum a velit eu ante scelerisque vulputate.
- </p>
- </div>
- <h3><a href="#">Section 2</a></h3>
- <div>
- <p>
- Sed non urna. Donec et ante. Phasellus eu ligula. Vestibulum sit amet
- purus. Vivamus hendrerit, dolor at aliquet laoreet, mauris turpis porttitor
- velit, faucibus interdum tellus libero ac justo. Vivamus non quam. In
- suscipit faucibus urna.
- </p>
- </div>
- <h3><a href="#">Section 3</a></h3>
- <div>
- <p>
- Nam enim risus, molestie et, porta ac, aliquam ac, risus. Quisque lobortis.
- Phasellus pellentesque purus in massa. Aenean in pede. Phasellus ac libero
- ac tellus pellentesque semper. Sed ac felis. Sed commodo, magna quis
- lacinia ornare, quam ante aliquam nisi, eu iaculis leo purus venenatis dui.
- </p>
- <ul>
- <li>List item one</li>
- <li>List item two</li>
- <li>List item three</li>
- </ul>
- </div>
- <h3><a href="#">Section 4</a></h3>
- <div>
- <p>
- Cras dictum. Pellentesque habitant morbi tristique senectus et netus
- et malesuada fames ac turpis egestas. Vestibulum ante ipsum primis in
- faucibus orci luctus et ultrices posuere cubilia Curae; Aenean lacinia
- mauris vel est.
- </p>
- <p>
- Suspendisse eu nisl. Nullam ut libero. Integer dignissim consequat lectus.
- Class aptent taciti sociosqu ad litora torquent per conubia nostra, per
- inceptos himenaeos.
- </p>
- </div>
-</div>
-
-</div><!-- End demo -->
diff --git a/js_example/css/jsweights.css b/js_example/css/jsweights.css
deleted file mode 100644
index e2d58c0..0000000
--- a/js_example/css/jsweights.css
+++ /dev/null
@@ -1,5 +0,0 @@
-
-div#js-weights div {
- font-size: 20px;
- font-weight: bold;
-} \ No newline at end of file
diff --git a/js_example/js/ajaxy.js b/js_example/js/ajaxy.js
deleted file mode 100644
index 7e3be99..0000000
--- a/js_example/js/ajaxy.js
+++ /dev/null
@@ -1,6 +0,0 @@
-
-(function($){
-$(document).ready(function(){
- $('div#test').html('hello katherine');
-});
-})(jQuery); \ No newline at end of file
diff --git a/js_example/js/black.js b/js_example/js/black.js
deleted file mode 100644
index 2619d6e..0000000
--- a/js_example/js/black.js
+++ /dev/null
@@ -1,8 +0,0 @@
-
-(function($){
-$(document).ready(function(){
- var weight = Drupal.settings.js_weights.black;
- var newDiv = $('<div></div>').css('color', 'black').html('I have a weight of ' + weight);
- $('#js-weights').append(newDiv);
-});
-})(jQuery);
diff --git a/js_example/js/blue.js b/js_example/js/blue.js
deleted file mode 100644
index 8fdb453..0000000
--- a/js_example/js/blue.js
+++ /dev/null
@@ -1,8 +0,0 @@
-
-(function($){
-$(document).ready(function(){
- var weight = Drupal.settings.js_weights.blue;
- var newDiv = $('<div></div>').css('color', 'blue').html('I have a weight of ' + weight);
- $('#js-weights').append(newDiv);
-});
-})(jQuery);
diff --git a/js_example/js/brown.js b/js_example/js/brown.js
deleted file mode 100644
index c912293..0000000
--- a/js_example/js/brown.js
+++ /dev/null
@@ -1,8 +0,0 @@
-
-(function($){
-$(document).ready(function(){
- var weight = Drupal.settings.js_weights.brown;
- var newDiv = $('<div></div>').css('color', 'brown').html('I have a weight of ' + weight);
- $('#js-weights').append(newDiv);
-});
-})(jQuery);
diff --git a/js_example/js/green.js b/js_example/js/green.js
deleted file mode 100644
index 7ca061b..0000000
--- a/js_example/js/green.js
+++ /dev/null
@@ -1,8 +0,0 @@
-
-(function($){
-$(document).ready(function(){
- var weight = Drupal.settings.js_weights.green;
- var newDiv = $('<div></div>').css('color', 'green').html('I have a weight of ' + weight);
- $('#js-weights').append(newDiv);
-});
-})(jQuery);
diff --git a/js_example/js/purple.js b/js_example/js/purple.js
deleted file mode 100644
index bcfe3c4..0000000
--- a/js_example/js/purple.js
+++ /dev/null
@@ -1,8 +0,0 @@
-
-(function($){
-$(document).ready(function(){
- var weight = Drupal.settings.js_weights.purple;
- var newDiv = $('<div></div>').css('color', 'purple').html('I have a weight of ' + weight);
- $('#js-weights').append(newDiv);
-});
-})(jQuery);
diff --git a/js_example/js/red.js b/js_example/js/red.js
deleted file mode 100644
index d492d37..0000000
--- a/js_example/js/red.js
+++ /dev/null
@@ -1,8 +0,0 @@
-
-(function($){
-$(document).ready(function(){
- var weight = Drupal.settings.js_weights.red;
- var newDiv = $('<div></div>').css('color', 'red').html('I have a weight of ' + weight);
- $('#js-weights').append(newDiv);
-});
-})(jQuery);
diff --git a/js_example/js_example.info b/js_example/js_example.info
deleted file mode 100644
index b2f6be2..0000000
--- a/js_example/js_example.info
+++ /dev/null
@@ -1,5 +0,0 @@
-
-name = JS Example
-description = An example module showing how to use some of the new JavaScript features in Drupal 7
-core = 7.x
-package = Example modules
diff --git a/js_example/js_example.module b/js_example/js_example.module
deleted file mode 100755
index fc9950b..0000000
--- a/js_example/js_example.module
+++ /dev/null
@@ -1,67 +0,0 @@
-<?php
-
-/**
- * Implementation hook_theme().
- */
-function js_example_theme() {
- return array(
- 'my_accordion' => array(
- 'template' => 'accordion',
- 'variables' => array('title' => NULL),
- ),
- );
-}
-
-/**
- * Implements hook_menu().
- */
-function js_example_menu() {
- $items = array();
- $items['js_example/weights'] = array(
- 'title' => 'JS Example: see weighting in action',
- 'page callback' => 'js_example_js_weights',
- 'access callback' => TRUE,
- );
- $items['js_example/accordion'] = array(
- 'title' => 'JS Example: jQuery UI accordion',
- 'page callback' => 'js_example_accordion',
- 'access callback' => TRUE,
- );
- return $items;
-}
-
-
-function js_example_js_weights() {
- // add some css to show which line is output by which script
- drupal_add_css(drupal_get_path('module', 'js_example') .'/css/jsweights.css');
- //
- $weights = array(
- 'red' => 100,
- 'blue' => 23,
- 'green' => 3,
- 'brown' => 45,
- 'black' => 5,
- 'purple' => 60
- );
- drupal_add_js(array('js_weights' => $weights), array('type' => 'setting'));
- drupal_add_js(drupal_get_path('module', 'js_example') .'/js/red.js', array('weight' => $weights['red']));
- drupal_add_js(drupal_get_path('module', 'js_example') .'/js/blue.js', array('weight' => $weights['blue']));
- drupal_add_js(drupal_get_path('module', 'js_example') .'/js/green.js', array('weight' => $weights['green']));
- drupal_add_js(drupal_get_path('module', 'js_example') .'/js/brown.js', array('weight' => $weights['brown']));
- drupal_add_js(drupal_get_path('module', 'js_example') .'/js/black.js', array('weight' => $weights['black']));
- drupal_add_js(drupal_get_path('module', 'js_example') .'/js/purple.js', array('weight' => $weights['purple']));
- $output = '<div id="js-weights"></div>';
- return $output;
-}
-
-function js_example_accordion() {
- $title = t('Click sections to expand or collapse:');
- $build['myelement'] = array(
- '#theme' => 'my_accordion',
- '#title' => $title,
- );
- $build['myelement']['#attached']['library'][] = array('system', 'ui.accordion');
- $build['myelement']['#attached']['js'][] = array('data' => '(function($){$(function() { $("#accordion").accordion(); })})(jQuery);', 'type' => 'inline');
- $output = drupal_render($build);
- return $output;
-}
diff --git a/menu_example/menu_example.info b/menu_example/menu_example.info
deleted file mode 100644
index 33c7bb2..0000000
--- a/menu_example/menu_example.info
+++ /dev/null
@@ -1,6 +0,0 @@
-
-name = Menu example
-description = An example of advanced uses of the menu APIs.
-package = Example modules
-core = 7.x
-files[] = menu_example.test
diff --git a/menu_example/menu_example.module b/menu_example/menu_example.module
deleted file mode 100644
index c19b07d..0000000
--- a/menu_example/menu_example.module
+++ /dev/null
@@ -1,467 +0,0 @@
-<?php
-
-/**
- * @file
- * Demonstrates uses of the Menu APIs in Drupal, including hook_menu(),
- * hook_menu_alter(), and hook_menu_link_alter().
- */
-
-/**
- * Implementatation of hook_menu().
- */
-function menu_example_menu() {
-
- // The simplest kind of menu: A simple call to a function with a menu entry.
- // The key of the menu item (menu_example/simplest) is the path that defines
- // the menu router entry.
- $items['menu_example'] = array(
- // The menu type is not required, as we're using the default.
- // 'type' => MENU_NORMAL_ITEM,
-
- // The title - do NOT use t() as t() is called automatically.
- 'title' => 'Menu Example',
-
- // Description (hover flyover for menu link). Does NOT use t(), which is
- // called automatically.
- 'description' => 'Simplest possible menu type, and the parent menu entry for others',
-
- // Function to be called when this path is accessed.
- 'page callback' => '_menu_example_basic_instructions',
-
- // Arguments to the page callback. Here's we'll use them just to provide
- // content for our page.
- 'page arguments' => array(t('This page is displayed by the simplest (and base) menu example. Note that the title of the page is the same as the link title. You can also <a href="!link">visit a similar page with no menu link</a>', array('!link' => url('menu_example/path_only')))),
-
- // This is to be accessible to all users, so 'access callback' can be set
- // to TRUE, meaning that we should bypass all access checks.
- 'access callback' => TRUE,
-
- // If the page callback is located in another file, specify it here and
- // that file will be automatically loaded when needed.
- // 'file' => 'menu_example.module',
-
- // We can choose which menu gets the link. The default is 'navigation'.
- // 'menu_name' => 'navigation',
-
- // Show the menu link as expanded.
- 'expanded' => TRUE,
- );
-
- // Show a menu link in a menu other than the default "Navigation" menu.
- // The menu must already exist.
- $items['menu_example_alternate_menu'] = array(
- 'title' => 'Menu Example: Menu in alternate menu',
-
- // Machine name of the menu in which the link should appear.
- 'menu_name' => 'primary-links',
-
- 'page callback' => '_menu_example_menu_page',
- 'page arguments' => array(t('This will be in the Primary Links menu instead of the default Navigation menu')),
- 'access callback' => TRUE,
- );
-
- // A menu entry with simple permissions using user_access().
-
- // First, provide a courtesy menu item that mentions the existence of the
- // permissioned item.
- $items['menu_example/permissioned'] = array(
- 'title' => 'Permissioned Example',
- 'page callback' => '_menu_example_menu_page',
- 'page arguments' => array(t('A menu item that requires the "access protected menu example" permission is at <a href="!link">menu_example/permissioned/controlled</a>', array('!link' => url('menu_example/permissioned/controlled')))),
- 'access callback' => TRUE,
- 'expanded' => TRUE,
- );
-
- // Now provide the actual permissioned menu item.
- $items['menu_example/permissioned/controlled'] = array(
-
- // The title - do NOT use t() as t() is called automatically.
- 'title' => 'Permissioned Menu Item',
- 'description' => 'This menu entry will not show and the page will not be accessible without the "access protected menu example" permission.',
- 'page callback' => '_menu_example_menu_page',
- 'page arguments' => array(t('This menu entry will not show and the page will not be accessible without the "access protected menu example" permission.')),
-
- // For a permissioned menu entry, we provide an access callback which
- // determines whether the current user should have access. The default is
- // user_access(), which we'll use in this case. Since it's the default,
- // we don't even have to enter it.
- // 'access callback' => 'user_access',
-
- // The 'access arguments' are passed to the 'access callback' to help it
- // do its job. In the case of user_access(), we need to pass a permission
- // as the first argument.
- 'access arguments' => array('access protected menu example'),
-
- // The optional weight element tells how to order the submenu items.
- // Higher weights are "heavier", dropping to the bottom of the menu.
- 'weight' => 10,
- );
-
- // A menu router entry with no menu link. This could be used any time we
- // don't want the user to see a link in the menu. Otherwise, it's the same
- // as the "simplest" entry above. MENU_CALLBACK is used for all menu items
- // which don't need a visible menu link, including services and other pages
- // that may be linked to but are not intended to be accessed directly.
-
- // First, provide a courtesy link in the menu so people can find this.
- $items['menu_example/path_only'] = array(
- 'title' => 'MENU_CALLBACK example',
- 'page callback' => '_menu_example_menu_page',
- 'page arguments' => array(t('A menu entry with no menu link (MENU_CALLBACK) is at <a href="!link">!link</a>', array('!link' => url('menu_example/path_only/callback')))),
- 'access callback' => TRUE,
- 'weight' => 20,
- );
- $items['menu_example/path_only/callback'] = array(
-
- // A type of MENU_CALLBACK means leave the path completely out of the menu
- // links.
- 'type' => MENU_CALLBACK,
-
- // The title is still used for the page title, even though it's not used
- // for the menu link text, since there's no menu link.
- 'title' => 'Callback Only',
-
- 'page callback' => '_menu_example_menu_page',
- 'page arguments' => array(t('The menu entry for this page is of type MENU_CALLBACK, so it provides only a path but not a link in the menu links, but it is the same in every other way to the simplest example.')),
- 'access callback' => TRUE,
- );
-
-
- // A menu entry with tabs.
- // For tabs we need at least 3 things:
- // 1. A parent MENU_NORMAL_ITEM menu item (menu_example/tabs in this
- // example.)
- // 2. A primary tab (the one that is active when we land on the base menu).
- // This tab is of type MENU_DEFAULT_LOCAL_TASK.
- // 3. Some other menu entries for the other tabs, of type MENU_LOCAL_TASK.
- $items['menu_example/tabs'] = array(
- // 'type' => MENU_NORMAL_ITEM, // Not necessary since this is the default.
- 'title' => 'Tabs',
- 'description' => 'Shows how to create primary and secondary tabs',
- 'page callback' => '_menu_example_menu_page',
- 'page arguments' => array(t('This is the "tabs" menu entry.')),
- 'access callback' => TRUE,
- 'weight' => 30,
- );
-
- // For the default local task, we need very little configuration, as the
- // callback and other conditions are handled by the parent callback.
- $items['menu_example/tabs/default'] = array(
- 'type' => MENU_DEFAULT_LOCAL_TASK,
- 'title' => t('Default primary tab'),
- 'weight' => 1,
- );
- // Now add the rest of the tab entries.
- foreach(array(t('second') => 2, t('third') => 3, t('fourth') => 4) as $tabname => $weight) {
- $items["menu_example/tabs/$tabname"] = array(
- 'type' => MENU_LOCAL_TASK,
- 'title' => $tabname,
- 'page callback' => '_menu_example_menu_page',
- 'page arguments' => array(t('This is the tab "@tabname" in the "basic tabs" example', array('@tabname' => $tabname))),
- 'access callback' => TRUE,
-
- // The weight property overrides the default alphabetic ordering of menu
- // entries, allowing us to get our tabs in the order we want.
- 'weight' => $weight,
- );
- }
-
- // Finally, we'll add secondary tabs to the default tab of the tabs entry.
-
- // The default local task needs very little information.
- $items['menu_example/tabs/default/first'] = array(
- 'type' => MENU_DEFAULT_LOCAL_TASK,
- 'title' => t('Default secondary tab'),
- // The additional page callback and related items are handled by the
- // parent menu item.
- );
- foreach(array(t('second'), t('third')) as $tabname) {
- $items["menu_example/tabs/default/$tabname"] = array(
- 'type' => MENU_LOCAL_TASK,
- 'title' => $tabname,
- 'page callback' => '_menu_example_menu_page',
- 'page arguments' => array(t('This is the secondary tab "@tabname" in the "basic tabs" example "default" tab', array('@tabname' => $tabname))),
- 'access callback' => TRUE,
- );
- }
-
- // All the portions of the URL after the base menu are passed to the page
- // callback as separate arguments, and can be captured by the page callback
- // in its argument list. Our _menu_example_menu_page() function captures
- // arguments in its function signature and can output them.
- $items['menu_example/use_url_arguments'] = array(
- 'title' => 'Extra Arguments',
- 'description' => 'The page callback can use the arguments provided after the path used as key',
- 'page callback' => '_menu_example_menu_page',
- 'page arguments' => array(t('This page demonstrates using arguments in the path (portions of the path after "menu_example/url_arguments". For example, access it with <a href="!link1">!link1</a> or <a href="!link2">!link2</a>).', array('!link1' => url('menu_example/use_url_arguments/one/two'), '!link2' => url('menu_example/use_url_arguments/firstarg/secondarg')))),
- 'access callback' => TRUE,
- 'weight' => 40,
- );
-
- // The menu title can be dynamically created by using the 'title callback'
- // which by default is t(). Here we provide a title callback which adjusts
- // the menu title based on the current user's username.
- $items['menu_example/title_callbacks'] = array(
- 'title callback' => '_menu_example_simple_title_callback',
- 'title arguments' => array(t('Dynamic title: username=')),
- 'description' => 'The title of this menu item is dynamically generated',
- 'page callback' => '_menu_example_menu_page',
- 'page arguments' => array(t('The menu title is dynamically changed by the title callback')),
- 'access callback' => TRUE,
- 'weight' => 50,
- );
-
- // Sometimes we need to capture a specific argument within the menu path,
- // as with the menu entry 'menu_example/placeholder_argument/3333/display',
- // where we need to capture the "3333". In that case, we use a placeholder in
- // the path provided in the menu entry. The (odd) way this is done is by using
- // array(numeric_position_value) as the value for 'page arguments'. The
- // numeric_position_value is the zero-based index of the portion of the URL
- // which should be passed to the 'page callback'.
-
- // First we provide a courtesy link with information on how to access
- // an item with a placeholder.
- $items['menu_example/placeholder_argument'] = array(
- 'title' => 'Placeholder Arguments',
- 'page callback' => '_menu_example_menu_page',
- 'page arguments' => array(t('Demonstrate placeholders by visiting <a href="!link">menu_example/placeholder_argument/3343/display</a>', array('!link' => url('menu_example/placeholder_argument/3343/display')))),
- 'access callback' => TRUE,
- 'weight' => 60,
- );
-
- // Now the actual entry.
- $items['menu_example/placeholder_argument/%/display'] = array(
- 'title' => 'Placeholder Arguments',
- 'page callback' => '_menu_example_menu_page',
-
- // Pass the value of '%', which is zero-based argument 2, to the
- // 'page callback'. So if the URL is
- // 'menu_example/placeholder_argument/333/display' then the value 333
- // will be passed into the 'page callback'.
- 'page arguments' => array(2),
- 'access callback' => TRUE,
- );
-
- // Drupal provides magic placeholder processing as well, so if the placeholder
- // is '%menu_example_arg_optional', the function
- // menu_example_arg_optional_load($arg) will be called to translate the path
- // argument to a more substantial object. $arg will be the value of the
- // placeholder. Then the return value of menu_example_id_load($arg) will be
- // passed to the 'page callback'.
- // In addition, if (in this case) menu_example_arg_optional_to_arg() exists,
- // then a menu link can be created using the results of that function as a
- // default for %menu_example_arg_optional.
- $items['menu_example/default_arg/%menu_example_arg_optional'] = array(
- 'title' => 'Processed Placeholder Arguments',
- 'page callback' => '_menu_example_menu_page',
- 'page arguments' => array(2), // arg 2 (3rd arg) is the one we want.
- 'access callback' => TRUE,
- 'weight' => 70,
- );
- return $items;
-}
-
-/**
- * Page callback for the simplest introduction menu entry.
- *
- * @param $content
- * Some content passed in.
- */
-function _menu_example_basic_instructions($content = NULL) {
- $base_content = t(
- 'This is the base page of the Menu Example. There are a number of examples
- here, from the most basic (like this one) to extravagant mappings of loaded
- placeholder arguments. Enjoy!');
- return '<div>' . $base_content . '</div><div>' . $content . '</div>';
-}
-
-/**
- * Page callback for use with most of the menu entries. The arguments it
- * receives determine what it outputs.
- *
- * @param $content
- * The base content to output.
- * @param $arg1
- * First additional argument from the path used to access the menu
- * @param $arg2
- * Second additional argument.
- */
-function _menu_example_menu_page($content = NULL, $arg1 = NULL, $arg2 = NULL) {
- $output = '<div>' . $content . '</div>';
-
- if (!empty($arg1)) {
- $output .= '<div>' . t('Argument 1=%arg', array('%arg' => $arg1)) . '</div>';
- }
- if (!empty($arg2)) {
- $output .= '<div>' . t('Argument 2=%arg', array('%arg' => $arg2)) . '</div>';
- }
- return $output;
-}
-
-/**
- * Implements hook_permission() to provide a demonstration access string.
- */
-function menu_example_permission() {
- return array(
- 'access protected menu example' => array(
- 'title' => t('Access the protected menu example'),
- ),
- );
-
-}
-
-/**
- * Utility function to provide mappings from integers to some strings.
- * This would normally be some database lookup to get an object or array from
- * a key.
- *
- * @param $id
- *
- * @return
- * The string to which the integer key mapped, or NULL if it did not map.
- */
-function _menu_example_mappings($id) {
- $mapped_value = NULL;
- static $mappings = array(
- 1 => 'one',
- 2 => 'two',
- 3 => 'three',
- 99 => 'jackpot! default',
- );
- if (isset($mappings[$id])) {
- $mapped_value = $mappings[$id];
- }
- return $mapped_value;
-}
-
-/**
- * The special _load function to load menu_example.
- *
- * Given an integer $id, load the string that should be associated with it.
- * Normally this load function would return an array or object with more
- * information.
- *
- * @param $id
- * The integer to load.
- *
- * @return
- * A string loaded from the integer.
- */
-function menu_example_id_load($id) {
- // Just map a magic value here. Normally this would load some more complex
- // object from the database or other context.
- $mapped_value = _menu_example_mappings($id);
- if (!empty($mapped_value)) {
- return t('Loaded value was %loaded', array('%loaded' => $mapped_value));
- }
- else {
- return t('Sorry, the id %id was not found to be loaded', array('%id' => $id));
- }
-}
-
-/**
- * Implements hook_menu_alter().
- *
- * Changes the path 'logout' to the Spanish 'salir'.
- * Changes the title callback of the 'user/UID' menu item.
- *
- * Remember that hook_menu_alter() only runs at menu_rebuild() time, not every
- * time the page is built, so this typically happens only at cache clear time.
- *
- * @param $items
- * The complete list of menu router items ready to be written to the
- * menu_router table.
- */
-function menu_example_menu_alter(&$items) {
- // Change the path 'user/logout' to a Spanish 'user/salir'. This change will
- // prevent the menu "Log out" link from showing up. You should go to user/salir
- // manually to log out of the site.
- if (!empty($items['user/logout'])) {
- $items['user/salir'] = $items['user/logout'];
- unset($items['user/logout']);
- }
-
- // Here we will change the title callback to our own function, changing the
- // 'user' link from the traditional to always being "username's account".
- if (!empty($items['user/%user'])) {
- $items['user/%user']['title callback'] = 'menu_example_user_page_title';
- }
-}
-
-/**
- * Title callback to rewrite the '/user' menu link.
- *
- * @param $base_string
- * string to be prepended to current user's name.
- */
-function _menu_example_simple_title_callback($base_string) {
- global $user;
- $username = !empty($user->name) ? $user->name : t('anonymous');
- return $base_string . ' ' . $username;
-}
-/**
- * Title callback to rename the title dynamically, based on user_page_title().
- *
- * @param $account
- * User account related to the visited page.
- */
-function menu_example_user_page_title($account) {
- return is_object($account) ? t("@name's account", array('@name' => format_username($account))) : '';
-}
-
-/**
- * Implements hook_menu_link_alter().
- *
- * This code will get the chance to alter a menu link when it is being saved
- * in the menu interface at admin/build/menu. Whatever we do here overrides
- * anything the user/administrator might have been trying to do.
- *
- * @param $item
- * The menu item being saved.
- * @param $menu
- * The entire menu router table.
- */
-function menu_example_menu_link_alter(&$item, $menu) {
- // Force the link title to remain 'Clear Cache' no matter what the admin
- // does with the web interface.
- if ($item['link_path'] == 'devel/cache/clear') {
- $item['link_title'] = 'Clear Cache';
- };
-}
-
-/**
- * Load an item based on its $id.
- *
- * In this case we're just creating a more extensive string. In a real example
- * we would load or create some type of object.
- *
- * @param $id
- */
-function menu_example_arg_optional_load($id) {
- $mapped_value = _menu_example_mappings($id);
- if (!empty($mapped_value)) {
- return t('Loaded value was %loaded', array('%loaded' => $mapped_value));
- }
- else {
- return t('Sorry, the id %id was not found to be loaded', array('%id' => $id));
- }
-}
-
-/**
- * A to_arg() function is used to provide a default for the arg in the
- * wildcard. The purpose is to provide a menu link that will function if no
- * argument is given. For example, in the case of the menu item
- * 'menu_example/default_arg/%menu_example_arg_optional' the third argument
- * is required, and the menu system cannot make a menu link using this path
- * since it contains a placeholder. However, when the to_arg() function is
- * provided, the menu system will create a menu link pointing to the path
- * which would be created with the to_arg() function filling in the
- * %menu_example_arg_optional.
- *
- * @param $arg
- * The arg (URL fragment) to be tested.
- */
-function menu_example_arg_optional_to_arg($arg) {
- // If our argument is not provided, give a default of 99.
- return (empty($arg) || $arg == '%') ? 99 : $arg;
-} \ No newline at end of file
diff --git a/menu_example/menu_example.test b/menu_example/menu_example.test
deleted file mode 100644
index 536a97d..0000000
--- a/menu_example/menu_example.test
+++ /dev/null
@@ -1,148 +0,0 @@
-<?php
-
-/**
- * @file
- * Tests for menu example module.
- */
-class MenuExampleTestCase extends DrupalWebTestCase {
- protected $web_user;
-
- public static function getInfo() {
- return array(
- 'name' => 'Menu example functionality',
- 'description' => 'Checks behavior of Menu Example.',
- 'group' => 'Examples',
- );
- }
-
- /**
- * Enable modules and create user with specific permissions.
- */
- public function setUp() {
- parent::setUp('menu_example');
- }
-
- /**
- * Test the various menus.
- */
- function testMenuExample() {
- $this->drupalGet('');
- $this->clickLink(t('Menu Example'));
- $this->assertText(t('This is the base page of the Menu Example'));
-
- $this->clickLink(t('Permissioned Example'));
- $this->assertText(t('Permissioned Example'));
-
- $this->clickLink('menu_example/permissioned/controlled');
- $this->assertResponse(403);
-
- $this->drupalGet('menu_example');
-
- $this->clickLink(t('MENU_CALLBACK example'));
-
- $this->drupalGet('menu_example/path_only/callback');
- $this->assertText(t('The menu entry for this page is of type MENU_CALLBACK'));
-
- $this->clickLink(t('Tabs'));
- $this->assertText(t('This is the "tabs" menu entry'));
-
- $this->drupalGet('menu_example/tabs/second');
- $this->assertText(t('This is the tab "second" in the "basic tabs" example'));
-
- $this->clickLink(t('third'));
- $this->assertText(t('This is the tab "third" in the "basic tabs" example'));
-
- $this->clickLink(t('Extra Arguments'));
-
- $this->drupalGet('menu_example/use_url_arguments/one/two');
- $this->assertText(t('Argument 1=one'));
-
- $this->clickLink(t('Placeholder Arguments'));
-
- $this->clickLink(t('menu_example/placeholder_argument/3343/display'));
- $this->assertRaw('<div>3343</div>');
-
- $this->clickLink(t('Processed Placeholder Arguments'));
- $this->assertText(t('Loaded value was jackpot! default'));
-
- // Create a user with permissions to access protected menu entry.
- $web_user = $this->drupalCreateUser(array('access protected menu example'));
-
- // Use custom overridden drupalLogin function to verify the user is logged
- // in.
- $this->drupalLogin($web_user);
-
- // Check that our title callback changing /user dynamically is working.
- // Using &#039; because of the format_username function.
- $this->assertRaw(t("@name&#039;s account", array('@name' => format_username($web_user))), t('Title successfully changed to account name: %name.', array('%name' => $web_user->name)));
-
- // Now start testing other menu entries.
- $this->drupalGet('menu_example');
-
- $this->clickLink(t('Permissioned Example'));
- $this->clickLink('menu_example/permissioned/controlled');
- $this->assertResponse(200);
- $this->assertText('This menu entry will not show');
-
- // Verify that the 'logout' link has been changed to 'salir', using an
- // overridden drupalLogout function.
- $this->drupalLogout();
- }
-
- /**
- * Log in a user with the internal browser.
- *
- * This function overrides default drupalLogin function because the changes
- * made by this module to the menu entries will make default drupalLogin fail.
- *
- * @param $user
- * User object representing the user to log in.
- *
- * @see drupalCreateUser()
- */
- protected function drupalLogin(stdClass $user) {
- if ($this->loggedInUser) {
- $this->drupalLogout();
- }
-
- $edit = array(
- 'name' => $user->name,
- 'pass' => $user->pass_raw
- );
- $this->drupalPost('user', $edit, t('Log in'));
-
- // menu_example prevents "log out" link from appearing on the page, so the
- // login function must check other link to verify user has logged in
- // successfully.
- $pass = $this->assertLink(t('My account'), 0, t('User %name successfully logged in.', array('%name' => $user->name)), t('User login'));
-
- if ($pass) {
- $this->loggedInUser = $user;
- }
- }
-
- /*
- * Logs a user out of the internal browser, then check the login page to
- * confirm logout.
- *
- * This function overrides default drupalLogout function because the changes
- * made by this module to the menu entries will make default drupalLogout fail.
- *
- * When menu_example module is enabled, logout menu entry is user/salir
- *
- */
- protected function drupalLogout() {
- // Make a request to the logout page, and redirect to the user page, the
- // idea being if you were properly logged out you should be seeing a login
- // screen.
- $this->drupalGet('user/salir');
- $this->drupalGet('user');
- $pass = $this->assertField('name', t('Username field found.'), t('Logout'));
- $pass = $pass && $this->assertField('pass', t('Password field found.'), t('Logout'));
-
- if ($pass) {
- $this->loggedInUser = FALSE;
- }
- }
-
-}
diff --git a/node_access_example/node_access_example.info b/node_access_example/node_access_example.info
deleted file mode 100644
index 993e0b0..0000000
--- a/node_access_example/node_access_example.info
+++ /dev/null
@@ -1,6 +0,0 @@
-
-name = Node access example
-description = Demonstrates how a module can use Drupal's node access system
-package = Example modules
-core = 7.x
-files[] = node_access_example.test
diff --git a/node_access_example/node_access_example.install b/node_access_example/node_access_example.install
deleted file mode 100644
index cd46da1..0000000
--- a/node_access_example/node_access_example.install
+++ /dev/null
@@ -1,29 +0,0 @@
-<?php
-
-/**
- * Implements hook_install().
- */
-function node_access_example_install() {
-}
-
-/**
- * Implements hook_uninstall().
- */
-function node_access_example_uninstall() {
-}
-
-/**
- * Implements hook_schema().
- */
-function node_access_example_schema() {
- $schema['node_access_example'] = array(
- 'description' => 'Example table for node_access_example module',
- 'fields' => array(
- 'nid' => array('type' => 'int', 'unsigned' => TRUE, 'not null' => TRUE, 'default' => 0),
- 'private' => array('type' => 'int', 'not null' => TRUE, 'default' => 0),
- ),
- 'primary key' => array('nid'),
- );
-
- return $schema;
-}
diff --git a/node_access_example/node_access_example.module b/node_access_example/node_access_example.module
deleted file mode 100755
index ae82648..0000000
--- a/node_access_example/node_access_example.module
+++ /dev/null
@@ -1,342 +0,0 @@
-<?php
-
-/**
- * @file
- * This is an example illustrating how to restrict access to nodes based on
- * the node access system. It implements an additional "private" marker for
- * each node. The idea is that only the user (or specially permissioned users)
- * can access a "private" node.
- *
- * The node access system has three layers.
- * - Overall override permissions. User 1 and any user with 'bypass node access'
- * permission are automatically granted access.
- * - hook_node_access() gives each module the opportunity to approve or deny
- * access. Any module that returns NODE_ACCESS_DENY from hook_node_access()
- * will result in denial of access. If no module denies access and one or
- * more modules allow access, then access is granted.
- * - If no resolution has yet been reached, then the node_access table is used
- * along with hook_node_grants().
- *
- * In order to demonstrate hook_node_access() (see
- * node_example_module_node_access()) to deny delete access to users with an
- * even-numbered uid.
- *
- * In addition, the traditional node rights system is employed to specify
- * which users are allowed to view, edit, or delete "private" content.
- *
- * This puts a single marker on a node: 'private'. The marker is implemented
- * by a custom table which has one row per node simply indicating that the node
- * is private. If the "private" marker is set, other users are denied access.
- *
- * Additional standard permissions are defined which allow users with
- * 'access any private content' or 'edit any private content' to override
- * the node access restrictions.
- *
- * Additionally, the node author can always view, edit, and delete the node.
- * A separate access realm grants privileges to each node's author.
- *
- * There are two basic building blocks in the node access system.
- * - hook_node_access_records() provides a list of "grants" for each node.
- * - hook_node_grants() provides determines which of those grants
- * is available for a given user account.
- *
- * Note that current best practice is probably to interoperate with the
- * @link http://drupal.org/project/acl ACL module @endlink rather than directly
- * implementing node access.
- *
- * It's also critical to understand when working with node access rights that
- * normally one would only use one module granting node access. That's the
- * reason that ACL module has come to the fore, as it becomes the central
- * clearing house for granting access. The problem with node acces is that
- * it is a granting system, not a restricting system. As a result, the first
- * module that grants access wins, even though some other node access module
- * might have wanted not to grant access. So there's enormous (potential)
- * ambiguity if one tries to use more than one node access module.
- *
- * The only page provided by this module gives a rundown of how many nodes
- * are marked private, and how many of those are accessible to the current
- * user. This demonstrates the use of the 'node_access' tag in node queries,
- * preventing disclosure of information which should not be shown to a user.
- *
- * See: @link node_access Node Access Rights @endlink and
- * @link http://drupal.org/node/270000 Handbook page on Node Access module @endlink
- */
-
-
-/**
- * Implements hook_menu() to provide a description.
- */
-function node_access_example_menu() {
- $items['examples/node_access'] = array(
- 'title' => 'Node Access Example',
- 'page callback' => 'node_access_example_private_node_listing',
- 'access callback' => TRUE,
- );
- return $items;
-}
-
-/**
- * Information for the user about what nodes are marked private on the system
- * and which of those the user has access to.
- *
- * The queries showing what is accessible to the current user demonstrate the
- * use of the 'node_access' tag to make sure that we don't show inappropriate
- * information to unprivileged users.
- */
-function node_access_example_private_node_listing() {
- $content = '<div>' . t('This example shows how a module can use the Drupal node access system to allow access to specific nodes. You will need to look at the code and then experiment with it by creating nodes, marking them private, and accessing them as various users.') . '</div>';
-
- // Find out how many nodes are marked private.
- $query = db_select('node', 'n');
- $query->addExpression('COUNT(n.nid)', 'private_count');
- $query->join('node_access_example', 'nae', 'nae.nid = n.nid');
- $num_private = $query
- ->condition('nae.private', 1)->execute()->fetchField();
-
- // Find out how many nodes owned by this user are marked private.
- $query = db_select('node', 'n');
- $query->addExpression('COUNT(n.nid)', 'private_count');
- $query->join('node_access_example', 'nae', 'nae.nid = n.nid');
- $num_personal = $query
- ->condition('n.uid', $GLOBALS['user']->uid)
- ->condition('nae.private', 1)
- ->execute()->fetchfield();
-
- $content .= '<div>' . t('There are currently @num private nodes in the system @num_personal are yours.', array('@num' => $num_private, '@num_personal' => $num_personal)) . '</div>';
-
- // Use a 'node_access' tag with a query to find out how many this user has
- // access to. This will be the standard way to make lists while respecting
- // node access restrictions.
- $query = db_select('node', 'n');
- $query->addExpression('COUNT(n.nid)', 'private_count');
- $query->addTag('node_access');
- $query->join('node_access_example', 'nae', 'nae.nid = n.nid');
- $num_private_accessible = $query->condition('nae.private', 1)->execute()->fetchField();
- $content .= '<div>' . t('You have access to @num private nodes.', array('@num' => $num_private_accessible)) . '</div>';
-
- // Use the key 'node_access' tag to get the key data from the nodes this
- // has access to.
- $query = db_select('node', 'n', array('fetch' => PDO::FETCH_ASSOC));
- $query->addTag('node_access');
- $query->join('node_access_example', 'nae', 'nae.nid = n.nid');
- $query->join('users', 'u', 'u.uid = n.uid');
- $result = $query->fields('n', array('nid', 'title', 'uid'))
- ->fields('u', array('name'))
- ->condition('nae.private', 1)->execute();
-
- $rows = array();
- foreach ($result as $node) {
- $node['nid'] = l($node['nid'], 'node/' . $node['nid']);
- $rows[] = array('data' => $node, 'class' => array('accessible'));
- }
- $content .= '<div>' . t('Accessible rows:') . theme('table', array('header' => array('nid', 'title', 'uid', 'username'), 'rows' => $rows)) . '</div>';
-
- return $content;
-}
-
-
-/**
- * Implements hook_permission().
- *
- * Users with 'access any private content' have global access to content marked
- * private by other users. 'edit any private content' allows global edit
- * privileges, basically overriding the node access system.
- *
- * Note that the 'edit any * content' and 'delete any * content' permissions
- * will allow edit or delete permissions to the holder, regardless of what
- * this module does.
- */
-function node_access_example_permission() {
- return array(
- 'access any private content' => array(
- 'title' => t('Access any private content'),
- 'description' => t('May view posts of other users even though they are marked private.'),
- ),
- 'edit any private content' => array(
- 'title' => t('Edit any private content'),
- 'description' => t('May edit posts of other users even though they are marked private.'),
- ),
- );
-}
-
-/**
- * Implements hook_node_access().
- *
- * Allows view and edit access to private nodes where the account requesting
- * access has the username 'foobar'.
- */
-function node_access_example_node_access($node, $op, $account) {
- // If $node is a string, the node has not yet been created. We don't care
- // about that case.
- if (is_string($node)) {
- return NODE_ACCESS_IGNORE;
- }
- if (($op == 'view' || $op == 'update') && (!empty($account->name) && $account->name == 'foobar') && !empty($node->private)) {
- drupal_set_message(t('Access to node @nid allowed because requester name (@name) is specifically allowed', array('@name' => $node->name, '@uid' => $account->uid)));
- return NODE_ACCESS_ALLOW;
- }
- return NODE_ACCESS_IGNORE;
-}
-
-/**
- * Implements hook_node_grants().
- *
- * Tell the node access system what grant IDs the account belongs to for each
- * realm.
- *
- * Here we are providing two realms:
- * - The node_access_example_author realm grants access to a user for their
- * own content (nodes that they created). The user's grant ID is their UID.
- * - The node_access_example realm grants override access to users with specific
- * traditional permissions so that they can edit others content. This has just
- * one grant id, 1: the user is either a member or not based on the
- * permissions 'access any private content' and 'edit any private content'.
- */
-function node_access_example_node_grants($account, $op) {
- // First grant a grant to the author for own content.
- $grants['node_access_example_author'] = array($account->uid);
-
- // Then, if "access any private content" is allowed to the account,
- // grant view, update, or delete as necessary.
- if ($op == 'view' && user_access('access any private content', $account)) {
- $grants['node_access_example_view'] = array(1);
- }
-
- if (($op == 'update' || $op == 'delete') && user_access('edit any private content', $account)) {
- $grants['node_access_example_edit'] = array(1);
- }
-
- return $grants;
-}
-
-/**
- * Implements hook_node_access_records().
- *
- * All node access modules must implement this hook. If the module is
- * interested in the privacy of the node passed in, return a list
- * of node access values for each grant ID we offer. Since this
- * example module only offers 1 grant ID, we will only ever be
- * returning one record.
- */
-function node_access_example_node_access_records($node) {
- // We only care about the node if it's been marked private. If not, it is
- // treated just like any other node and we completely ignore it.
- if (!empty($node->private)) {
- $grants = array();
- $grants[] = array(
- 'realm' => 'node_access_example_view',
- 'gid' => 1,
- 'grant_view' => 1,
- 'grant_update' => 0,
- 'grant_delete' => 0,
- 'priority' => 0,
- );
- $grants[] = array(
- 'realm' => 'node_access_example_edit',
- 'gid' => 1,
- 'grant_view' => 1,
- 'grant_update' => 1,
- 'grant_delete' => 1,
- 'priority' => 0,
- );
-
- // For the example_author realm, the GID is equivalent to a UID, which
- // means there are many many groups of just 1 user.
- $grants[] = array(
- 'realm' => 'node_access_example_author',
- 'gid' => $node->uid,
- 'grant_view' => 1,
- 'grant_update' => 1,
- 'grant_delete' => 1,
- 'priority' => 0,
- );
- return $grants;
- }
-}
-
-/**
- * Implements hook_form_alter().
- *
- * This module adds a simple checkbox to the node form labeled private. If the
- * checkbox is labelled, only the node author and users with
- * 'access any private content' privileges may see it.
- */
-function node_access_example_form_alter(&$form, $form_state) {
- if (!empty($form['#node_edit_form'])) {
- $form['node_access_example'] = array(
- '#type' => 'fieldset',
- '#title' => t('Node Access Example'),
- '#collapsible' => TRUE,
- '#collapsed' => FALSE,
- '#weight' => 8,
- );
-
- $form['node_access_example']['private'] = array(
- '#type' => 'checkbox',
- '#title' => t('Private'),
- '#description' => t('Check here if this content should be set private and only shown to privileged users.'),
- '#default_value' => isset($form['#node']->private) ? $form['#node']->private : FALSE,
- );
- }
-}
-
-/**
- * Implements hook_node_load().
- */
-
-function node_access_example_node_load($nodes, $types) {
- $result = db_query('SELECT nid, private FROM {node_access_example} WHERE nid IN(:nids)', array(':nids' => array_keys($nodes)));
- foreach ($result as $record) {
- $nodes[$record->nid]->private = $record->private;
- }
-}
-
-/**
- * Implements hook_node_delete().
- *
- * Delete the node_access_example record when the node is deleted.
- */
-
-function node_access_example_node_delete($node) {
- db_delete('node_access_example')->condition('nid', $node->nid)->execute();
-}
-
-/**
- * Implements hook_node_insert().
- *
- * Insert a new access record when a node is created.
- */
-function node_access_example_node_insert($node) {
- if (isset($node->private)) {
- db_insert('node_access_example')->fields(array('nid' => $node->nid, 'private' => (int)$node->private))->execute();
- }
- drupal_set_message(t('New node @nid was created and private=@private', array('@nid' => $node->nid, '@private' => !empty($node->private) ? 1 : 0)));
-}
-
-/**
- * Implements hook_nodeapi_update().
- *
- * If the record in the node_access_example table already exists, we must
- * update it. If it doesn't exist, we create it.
- */
-function node_access_example_node_update($node) {
- // Find out if there is already a node_access_example record.
- $exists = db_query('SELECT nid FROM {node_access_example} WHERE nid = :nid', array(':nid' => $node->nid))->fetchField();
-
- // If there is already a record, update it with the new private value.
- if ($exists) {
- $num_updated = db_update('node_access_example')
- ->fields(array(
- 'nid' => $node->nid,
- 'private' => !empty($node->private) ? 1 : 0,
- ))
- ->condition('nid', $node->nid)
- ->execute();
- drupal_set_message(t("Updated node @nid to set private=@private (@num nodes actually updated)", array('@private' => $node->private, '@num' => $num_updated, '@nid' => $node->nid)));
- }
- // Otherwise, create a new record.
- else {
- node_access_example_node_insert($node);
- drupal_set_message(t('Inserted new node_access nid=@nid, private=@private', array('@nid' => $node->nid, '@private' => $node->private)));
- }
-}
diff --git a/node_access_example/node_access_example.test b/node_access_example/node_access_example.test
deleted file mode 100644
index be80dda..0000000
--- a/node_access_example/node_access_example.test
+++ /dev/null
@@ -1,196 +0,0 @@
-<?php
-
-/**
- * @file
- * Tests for Node Access example module.
- */
-class NodeAccessExampleTestCase extends DrupalWebTestCase {
-
- public static function getInfo() {
- return array(
- 'name' => 'Node Access Example functionality',
- 'description' => 'Checks behavior of Node Access Example.',
- 'group' => 'Examples',
- );
- }
-
- /**
- * Enable modules and create user with specific permissions.
- */
- public function setUp() {
- parent::setUp('node_access_example', 'search');
- node_access_rebuild();
- }
-
- /**
- * Test the "private" node access.
- *
- * - Create 3 users with "access content" and "create article" permissions.
- * - Each user creates one private and one not private article.
- * - Run cron to update search index.
- * - Test that each user can view the other user's non-private article.
- * - Test that each user cannot view the other user's private article.
- * - Test that each user finds only appropriate (non-private + own private)
- * in search results.
- * - Create another user with 'view any private content'.
- * - Test that user 4 can view all content created above.
- * - Test that user 4 can search for all content created above.
- * - Test that user 4 cannot edit private content above.
- * - Create another user with 'edit any private content'
- * - Test that user 5 can edit private content.
- * - Test that user 5 can delete private content.
- * - Test listings of nodes with 'node_access' tag on database search.
- */
- function testNodeAccessBasic() {
- $num_simple_users = 3;
- $simple_users = array();
-
- // nodes keyed by uid and nid: $nodes[$uid][$nid] = $is_private;
- $nodes_by_user = array();
- $titles = array(); // Titles keyed by nid
- $private_nodes = array(); // Array of nids marked private.
- for($i = 0; $i < $num_simple_users; $i++) {
- $simple_users[$i] = $this->drupalCreateUser(array('access content', 'create article content', 'search content'));
- }
- foreach ($simple_users as $web_user) {
- $this->drupalLogin($web_user);
- foreach(array(0 => 'Public', 1 => 'Private') as $is_private => $type) {
- $edit = array(
- 'title' => t('@private_public Article created by @user', array('@private_public' => $type, '@user' => $web_user->name)),
- );
- if ($is_private) {
- $edit['private'] = TRUE;
- $edit['body[und][0][value]'] = 'private node';
- }
- else {
- $edit['body[und][0][value]'] = 'public node';
- }
- $this->drupalPost('node/add/article', $edit, t('Save'));
- debug(t('Created article with private=@private', array('@private' => $is_private)));
- $this->assertText(t('Article @title has been created', array('@title' => $edit['title'])));
- $nid = db_query('SELECT nid FROM {node} WHERE title = :title', array(':title' => $edit['title']))->fetchField();
- $this->assertText(t('New node @nid was created and private=@private', array('@nid' => $nid, '@private' => $is_private)));
- $private_status = db_query('SELECT private FROM {node_access_example} where nid = :nid', array(':nid' => $nid))->fetchField();
- $this->assertTrue($is_private == $private_status, t('Node was properly set to private or not private in node_access_example table.'));
- if ($is_private) {
- $private_nodes[] = $nid;
- }
- $titles[$nid] = $edit['title'];
- $nodes_by_user[$web_user->uid][$nid] = $is_private;
- }
- }
- debug($nodes_by_user);
- $this->cronRun(); // Build the search index.
- foreach ($simple_users as $web_user) {
- $this->drupalLogin($web_user);
- // Check to see that we find the number of search results expected.
- $this->checkSearchResults('Private node', 1);
- // Check own nodes to see that all are readable.
- foreach(array_keys($nodes_by_user) as $uid) {
- // All of this user's nodes should be readable to same.
- if ($uid == $web_user->uid) {
- foreach($nodes_by_user[$uid] as $nid => $is_private) {
- $this->drupalGet('node/'.$nid);
- $this->assertResponse(200);
- $this->assertTitle($titles[$nid] . ' | Drupal', t('Correct title for node found'));
- }
- }
- else {
- // Otherwise, for other users, private nodes should get a 403,
- // but we should be able to read non-private nodes.
- foreach($nodes_by_user[$uid] as $nid => $is_private) {
- $this->drupalGet('node/'.$nid);
- $this->assertResponse($is_private ? 403 : 200, t('Node @nid by user @uid should get a @response for this user (@web_user_uid)', array('@nid' => $nid, '@uid' => $uid, '@response' => $is_private ? 403 : 200, '@web_user_uid' => $web_user->uid)));
- if (!$is_private) {
- $this->assertTitle($titles[$nid] . ' | Drupal', t('Correct title for node was found'));
- }
- }
- }
- }
-
- // Check to see that the correct nodes are shown on examples/node_access.
- $this->drupalGet('examples/node_access');
- $accessible = $this->xpath("//tr[contains(@class,'accessible')]");
- $this->assertEqual(count($accessible), 1, t('One private item accessible'));
- foreach ($accessible as $row) {
- $this->assertEqual($row->td[2], $web_user->uid, t('Accessible row owned by this user'));
- }
- }
-
- // Now test that a user with 'access any private content' can view content.
- $access_user = $this->drupalCreateUser(array('access content', 'create article content', 'access any private content', 'search content'));
- $this->drupalLogin($access_user);
-
- // Check to see that we find the number of search results expected.
- $this->checkSearchResults('Private node', 3);
-
- foreach($nodes_by_user as $uid => $private_status) {
- foreach ($private_status as $nid => $is_private) {
- $this->drupalGet('node/' . $nid);
- $this->assertResponse(200);
- }
- }
-
- // Check to see that the correct nodes are shown on examples/node_access.
- // This user should be able to see all 3 of them.
- $this->drupalGet('examples/node_access');
- $accessible = $this->xpath("//tr[contains(@class,'accessible')]");
- $this->assertEqual(count($accessible), 3);
-
-
- // Test that a user named 'foobar' can edit any private node due to
- // node_access_example_node_access(). Note that this user will not be
- // able to search for private nodes, and will not have available nodes
- // shown on examples/node_access, because node_access() is not called
- // for node listings, only for actual access to a node.
- $edit_user = $this->drupalCreateUser(array('access comments', 'access content', 'post comments', 'skip comment approval', 'search content'));
- // Update the name of the user to 'foobar'.
- $num_updated = db_update('users')
- ->fields(array(
- 'name' => 'foobar',
- ))
- ->condition('uid', $edit_user->uid)
- ->execute();
-
- $edit_user->name = 'foobar';
- $this->drupalLogin($edit_user);
-
- // Try to edit each of the private nodes.
- foreach($private_nodes as $nid) {
- $body = $this->randomName();
- $edit = array('body[und][0][value]' => $body);
- $this->drupalPost('node/' . $nid . '/edit', $edit, t('Save'));
- $this->assertText(t('has been updated'), t('Node was updated by "foobar" user'));
- }
-
- // Test that a privileged user can edit and delete private content.
- // This test should go last, as the nodes get deleted.
- $edit_user = $this->drupalCreateUser(array('access content', 'access any private content', 'edit any private content'));
- $this->drupalLogin($edit_user);
- foreach($private_nodes as $nid) {
- $body = $this->randomName();
- $edit = array('body[und][0][value]' => $body);
- $this->drupalPost('node/' . $nid . '/edit', $edit, t('Save'));
- $this->assertText(t('has been updated'));
- $this->drupalPost('node/' . $nid . '/edit', array(), t('Delete'));
- $this->drupalPost(NULL, array(), t('Delete'));
- $this->assertText(t('has been deleted'));
- }
-
-
- }
-
- /**
- * On the search page, search for a string and assert the expected number
- * of results.
- * @param $search_query
- * String to search for
- * @param $expected_result_count
- * Expected result count
- */
- function checkSearchResults($search_query, $expected_result_count) {
- $this->drupalPost('search/node', array('keys' => $search_query), t('Search'));
- $search_results = $this->xpath("//ol[contains(@class, 'search-results')]/li");
- $this->assertEqual(count($search_results), $expected_result_count, t('Found the expected number of search results'));
- }
-}
diff --git a/node_example/node_example.info b/node_example/node_example.info
deleted file mode 100755
index 349395b..0000000
--- a/node_example/node_example.info
+++ /dev/null
@@ -1,7 +0,0 @@
-
-name = Node example
-description = Demonstrates a custom content type and uses the field api.
-package = Example modules
-core = 7.x
-dependencies[] = image
-files[] = node_example.test
diff --git a/node_example/node_example.install b/node_example/node_example.install
deleted file mode 100755
index aaf31b8..0000000
--- a/node_example/node_example.install
+++ /dev/null
@@ -1,217 +0,0 @@
-<?php
-
-/**
- * @file
- * Install file for Node Example module.
- *
- * The definition of the fields for the module is here,
- *
- * See @link http://drupal.org/node/707832 Field API Tutorial @endlink
- *
- * See @link http://drupal.org/node/443536 Field API Handbook Page @endlink
- *
- * See @link field Field API documentation @endlink
- *
- */
-
-/**
- * Implements hook_install().
- *
- * - Add the body field.
- * - Configure the body field.
- * - Create color, quantity, and image fields.
- * - Create color, quantity, and image instances.
- *
- * @see node_type_set_defaults()
- * @see field_info_instance()
- * @see field_update_instance()
- * @see field_create_field()
- * @see field_create_instance()
- */
-function node_example_install() {
- // use get_t() to get the name of our localization function for translation
- // during install, when t() is not available.
- $t = get_t();
-
- // Define the node type.
- $node_example = array(
- 'type' => 'node_example',
- 'name' => $t('Example Node'),
- 'base' => 'node_content',
- 'description' => $t('This is an example node type with a few fields.'),
- 'body_label' => $t('Example Description')
- );
-
- // Complete the node type definition by setting any defaults not explicitly
- // declared above.
- // http://api.drupal.org/api/function/node_type_set_defaults/7
- $content_type = node_type_set_defaults($node_example);
- node_add_body_field($content_type);
-
- // Save the content type
- node_type_save($content_type);
-
-
- // Load the instance definition for our content type's body
- // http://api.drupal.org/api/function/field_info_instance/7
- $body_instance = field_info_instance('node', 'body', 'node_example');
-
- // Add our example_node_list view mode to the body instance display by
- // instructing the body to display as a summary
- $body_instance['display']['example_node_list'] = array(
- 'label' => 'hidden',
- 'type' => 'text_summary_or_trimmed',
- );
-
- // Save our changes to the body field instance.
- // http://api.drupal.org/api/function/field_update_instance/7
- field_update_instance($body_instance);
-
- // Create all the fields we are adding to our content type.
- // http://api.drupal.org/api/function/field_create_field/7
- foreach (_node_example_installed_fields() as $field) {
- field_create_field($field);
- }
-
- // Create all the instances for our fields.
- // http://api.drupal.org/api/function/field_create_instance/7
- foreach (_node_example_installed_instances() as $instance) {
- $instance['entity_type'] = 'node';
- $instance['bundle'] = $node_example['type'];
- field_create_instance($instance);
- }
-}
-
-/**
- * Return a structured array defining the fields created by this content type.
- *
- * This is packaged in a function so it can be used in both
- * node_example_install() and node_example_uninstall().
- */
-function _node_example_installed_fields() {
- $t = get_t();
- return array(
- 'node_example_color' => array(
- 'field_name' => 'node_example_color',
- 'cardinality' => 3,
- 'type' => 'text',
- 'settings' => array(
- 'max_length' => 60,
- ),
- ),
- 'node_example_quantity' => array(
- 'field_name' => 'node_example_quantity',
- 'cardinality' => 1,
- 'type' => 'text',
- ),
- 'node_example_image' => array(
- 'field_name' => 'node_example_image',
- 'type' => 'image',
- 'cardinality' => 1,
- ),
- );
-}
-
-/**
- * Return a structured array defining the instances for this content type.
- *
- * The instance lets Drupal know which widget to use to allow the user to enter
- * data and how to react in different view modes. We are going to display a
- * page that uses a custom "node_example_list" view mode. We will set a
- * cardinality of three allowing our content type to give the user three color
- * fields.
- *
- * This is provided as a function so that it can be used in both hook_install()
- * and hook_uninstall().
- */
-function _node_example_installed_instances() {
- $t = get_t();
- return array(
- 'node_example_color' => array(
- 'field_name' => 'node_example_color',
- 'label' => $t('The colors available for this object.'),
- 'widget' => array(
- 'type' => 'text_textfield',
- ),
- 'display' => array(
- 'example_node_list' => array(
- 'label' => 'hidden',
- 'type' => 'node_example_colors',
- ),
- ),
- ),
- 'node_example_quantity' => array(
- 'field_name' => 'node_example_quantity',
- 'label' => $t('Quantity required'),
- 'type' => 'text',
- 'widget' => array(
- 'type' => 'text_textfield',
- ),
- 'display' => array(
- 'example_node_list' => array(
- 'label' => 'hidden',
- 'type' => 'hidden',
- ),
- ),
- ),
- 'node_example_image' => array(
- 'field_name' => 'node_example_image',
- 'label' => $t('Upload an image:'),
- 'required' => FALSE,
- 'widget' => array(
- 'type' => 'image_image',
- 'weight' => 2.10,
- ),
- 'display' => array(
- 'example_node_list' => array(
- 'label' => 'hidden',
- 'type' => 'image_link_content__thumbnail',
- ),
- ),
- ),
- );
-}
-
-
-/**
- * Implements hook_uninstall().
- *
- */
-function node_example_uninstall() {
- // Gather all the example content that might have been created while this
- // module was enabled. Simple selects still use db_query().
- // http://api.drupal.org/api/function/db_query/7
- $sql = 'SELECT nid FROM {node} n WHERE n.type = :type';
- $result = db_query($sql, array(':type' => 'node_example'));
- $nids = array();
- foreach ($result as $row) {
- $nids[] = $row->nid;
- }
-
- // Delete all the nodes at once
- // http://api.drupal.org/api/function/node_delete_multiple/7
- node_delete_multiple($nids);
-
- // Loop over each of the fields defined by this module and delete
- // all instances of the field, their data, and the field itself.
- // http://api.drupal.org/api/function/field_delete_field/7
- foreach (array_keys(_node_example_installed_fields()) as $field) {
- field_delete_field($field);
- }
-
- // Loop over any remaining field instances attached to the node_example
- // content type (such as the body field) and delete them individually.
- // http://api.drupal.org/api/function/field_delete_field/7
- $instances = field_info_instances('node', 'node_example');
- foreach ($instances as $instance_name => $instance) {
- field_delete_instance($instance);
- }
-
- // Delete our content type
- // http://api.drupal.org/api/function/node_type_delete/7
- node_type_delete('node_example');
-
- // Purge all field infromation
- // http://api.drupal.org/api/function/field_purge_batch/7
- field_purge_batch(1000);
-}
diff --git a/node_example/node_example.module b/node_example/node_example.module
deleted file mode 100755
index b9056d4..0000000
--- a/node_example/node_example.module
+++ /dev/null
@@ -1,167 +0,0 @@
-<?php
-
-/**
- * @file
- * This is an example outlining how a module can be used to define a new
- * node type. In Drupal 7 we move most of what was once needed in this file
- * to the node_example.install file so that it can be managed efficiently.
- *
- * Our example node type will allow users to specify multiple "colors",
- * a "quantity" and an "image" for their nodes; some kind of rudimentary
- * inventory-tracking system, perhaps?
- *
- * In previous versions of Drupal, "teaser" and "page" were node view modes. In
- * Drupal 7 we can define custom view modes to let the node know how it should
- * return it's data. This module declares a custom view mode called
- * "example_node_list".
- *
- * We no longer need an extra database table to store this content type's
- * information.
- *
- * Most node types that provide fields do not require any custom code for
- * the fields, as the fields system provides storage and access.
- *
- * See @link http://drupal.org/node/707832 Field API Tutorial @endlink
- *
- * See @link http://drupal.org/node/443536 Field API Handbook Page @endlink
- *
- * See @link field Field API documentation @endlink
- *
- * See @link field_example.install field_example.install @endlink
- *
- * Remember that most node types do not require any custom code, as one
- * simply creates them using the fields UI.
- */
-
-
-/**
- * Implements hook_menu().
- *
- * We are providing a default page to illustrate the use of our custom node view
- * mode that will live at http://example.com/?q=examples/node_example
- */
-function node_example_menu() {
- $items['examples/node_example'] = array(
- 'page callback' => 'node_example_page',
- 'access arguments' => array('access content'),
- 'title' => 'Node Example',
- );
- return $items;
-}
-
-/**
- * Custom callback that builds our content and returns it to the browser.
- *
- * @return
- * a build array
- *
- */
-function node_example_page() {
- $build = array();
- $sql = 'SELECT nid FROM {node} n WHERE n.type = :type AND n.status = :status';
- $result = db_query($sql,
- array(
- ':type' => 'node_example',
- ':status' => 1,
- )
- );
-
- // Loop through each of our node_example nodes and instruct node_view
- // to use our custom "example_node_list" view.
- // http://api.drupal.org/api/function/node_load/7
- // http://api.drupal.org/api/function/node_view/7
- foreach ($result as $row) {
- $node = node_load($row->nid);
- $build['node_list'][]= node_view($node, 'example_node_list');
- }
-
- return $build;
-}
-
-/**
- * Implements hook_entity_info_alter().
- *
- * We need to modify the default node entity info by adding a new view mode to
- * be used in functions like node_view() or node_build_content().
- *
- */
-function node_example_entity_info_alter(&$entity_info) {
- $entity_info['node']['view modes']['example_node_list'] = array(
- 'label' => t('Example Node List'),
- 'custom settings' => TRUE,
- );
-}
-
-
-/**
- * Implements hook_field_formatter_info().
- */
-function node_example_field_formatter_info() {
- return array(
- 'node_example_colors' => array(
- 'label' => t('Node Example Color Handle'),
- 'field types' => array('text'),
- ),
- );
-}
-
-/**
- * Implements hook_field_formatter_view().
- *
- * @todo: We need to provide a formatter for the colors that a user is allowed to enter
- * during node creation.
- */
-function node_example_field_formatter_view($object_type, $object, $field, $instance, $langcode, $items, $display) {
- $element = array();
- switch ($display['type']) {
- case 'node_example_colors':
- foreach ($items as $delta => $item) {
- $element[$delta]['#type'] = 'markup';
- $color = $item['safe_value'];
- $element[$delta]['#markup'] = theme('example_node_color', array('color' => $color));
- }
- break;
- }
-
- return $element;
-}
-
-/**
- * Implements hook_theme().
- *
- * This lets us tell Drupal about our theme functions and their arguments.
- */
-function node_example_theme($existing, $type, $theme, $path) {
- return array(
- 'example_node_color' => array(
- 'variables' => array('color' => NULL),
- ),
- );
-}
-
-/**
- * Implements hook_help().
- */
-function node_example_help($path, $arg) {
- switch ($path) {
- case 'examples/node_example':
- return "<p>" . t(
- "The Node Example module provides a custom node type.
- You can create new nodes using the <a href='!nodeadd'>node add form</a>.
- Nodes that you create will be displayed here.",
- array('!nodeadd' => url('node/add/node-example'))
- ) . "</p>";
- }
-}
-
-/**
- * A custom theme function.
- *
- * By using this function to format our node-specific information, themes
- * can override this presentation if they wish. This is a simplifed theme
- * function purely for illustrative purposes.
- */
-function theme_example_node_color($variables) {
- $output = '<span style="background-color: #ccc; padding: 1em; margin-bottom: 1em; float: left; color: ' . $variables['color'] . '">' . $variables['color'] . '</span>';
- return $output;
-}
diff --git a/node_example/node_example.test b/node_example/node_example.test
deleted file mode 100644
index 940ff3e..0000000
--- a/node_example/node_example.test
+++ /dev/null
@@ -1,55 +0,0 @@
-<?php
-
-/**
- * @file
- * Simpletest case for node_example module.
- *
- * Verify example module functionality.
- */
-
-/**
- * Functionality tests for node example module.
- */
-class NodeExampleTestCase extends DrupalWebTestCase {
-
- public static function getInfo() {
- return array(
- 'name' => 'Node example',
- 'description' => 'Verify the custom node type creation.',
- 'group' => 'Examples',
- );
- }
-
- function setUp() {
- // Enable the module.
- parent::setUp('node_example');
- }
-
- /**
- * Verify the functionality of the example module.
- */
- function testNodeCreation() {
- // Create and login user.
- $account = $this->drupalCreateUser(array('access content', 'create node_example content'));
- $this->drupalLogin($account);
-
- // Create a new node. The image makes it more complicated, so skip it.
- $edit = array(
- 'title' => $this->randomName(),
- 'node_example_color[und][0][value]' => 'red',
- 'node_example_color[und][1][value]' => 'green',
- 'node_example_color[und][2][value]' => 'blue',
- 'node_example_quantity[und][0][value]' => 100,
- );
- $this->drupalPost('node/add/node-example', $edit, t('Save'));
- $this->assertText("Example Node " . $edit['title'] . " has been created", "Found node creation message");
- $this->assertPattern("/The colors available.*red.*green.*blue/", "Correct 'colors available' on node page");
-
- // Look on the examples page to make sure it shows up there also.
- $this->drupalGet('examples/node_example');
- $this->assertText($edit['title'], "Found random title string");
- $this->assertPattern("/red.*green.*blue/", "Correct 'colors available' on node example page");
-
- }
-}
-
diff --git a/nodeapi_example/nodeapi_example.info b/nodeapi_example/nodeapi_example.info
deleted file mode 100644
index f50e2a5..0000000
--- a/nodeapi_example/nodeapi_example.info
+++ /dev/null
@@ -1,6 +0,0 @@
-
-name = NodeAPI example
-description = Demonstrates using the hook_node_* APIs (formerly hook_nodeapi) to alter a node from a different module.
-package = Example modules
-core = 7.x
-files[] = nodeapi_example.test
diff --git a/nodeapi_example/nodeapi_example.install b/nodeapi_example/nodeapi_example.install
deleted file mode 100644
index d470be8..0000000
--- a/nodeapi_example/nodeapi_example.install
+++ /dev/null
@@ -1,60 +0,0 @@
-<?php
-
-/**
- * @file
- * Install, update and uninstall functions for the nodeapi example module.
- *
- * This file contains the functions required to perform install, update and
- * uninstall operations.
- *
- */
-
-/**
- * Implements hook_install().
- */
-function nodeapi_example_install() {
-}
-
-/**
- * Implements hook_uninstall().
- */
-function nodeapi_example_uninstall() {
-}
-
-/**
- * Implements hook_schema().
- */
-function nodeapi_example_schema() {
- $schema['nodeapi_example'] = array(
- 'description' => 'Stores information of extended content.',
- 'fields' => array(
- 'nid' => array(
- 'description' => 'Node ID that the rating is applied to.',
- 'type' => 'int',
- 'unsigned' => TRUE,
- 'not null' => TRUE,
- 'default' => 0
- ),
- 'vid' => array(
- 'description' => 'Revision ID, as we are tracking rating with node revisions',
- 'type' => 'int',
- 'unsigned' => TRUE,
- 'not null' => TRUE,
- 'default' => 0
- ),
- 'rating' => array(
- 'description' => 'The rating of the node.',
- 'type' => 'int',
- 'unsigned' => TRUE,
- 'not null' => TRUE,
- 'default' => 0
- ),
- ),
- 'primary key' => array('vid'),
- 'indexes' => array(
- 'nid' => array('nid'),
- ),
- );
-
- return $schema;
-}
diff --git a/nodeapi_example/nodeapi_example.module b/nodeapi_example/nodeapi_example.module
deleted file mode 100755
index 5a221dc..0000000
--- a/nodeapi_example/nodeapi_example.module
+++ /dev/null
@@ -1,283 +0,0 @@
-<?php
-
-/**
- * @file
- * This is an example outlining how a module can be used to extend existing
- * content types.
- *
- * We will add the ability for each node to have a "rating," which will be a
- * number from one to five. The rating will be tracked using the revision
- * system also, so every node revision may have different rating values.
- */
-
-/**
- * Implements hook_form_alter().
- *
- * By implementing this hook, we're able to modify any form. We'll only make
- * changes to two types: a node's content type configuration and edit forms.
- *
- * We need to have a way for administrators to indicate which content types
- * should have our rating field added. This is done by inserting a checkbox in
- * the node's content type configuration page.
- *
- * Changes made by this hook will be show when editing the settings of any
- * content type.
- *
- * Optionally, hook_form_FORM_ID_alter() could be used with the function name
- * nodeapi_example_form_node_type_form_alter
- */
-function nodeapi_example_form_alter(&$form, $form_state, $form_id) {
- // First, check for the node type configuration form.
- if ($form_id == 'node_type_form') {
- // Alter the node type's configuration form to add our setting. We don't
- // need to worry about saving this value back to the variable, the form
- // we're altering will do it for us.
- $form['rating'] = array(
- '#type' => 'fieldset',
- '#title' => t('Rating settings'),
- '#collapsible' => TRUE,
- '#collapsed' => TRUE,
- '#group' => 'additional_settings',
- '#weight' => -1,
- );
-
- $form['rating']['nodeapi_example'] = array(
- '#type' => 'radios',
- '#title' => t('NodeAPI Example Rating'),
- '#default_value' => variable_get('nodeapi_example_' . $form['#node_type']->type, FALSE),
- '#options' => array(FALSE => t('Disabled'), TRUE => t('Enabled')),
- '#description' => t('Should this node have a rating attached to it?'),
- );
- }
- // If the type and node field are set this may be a node edit form.
- elseif (isset($form['type']) && isset($form['#node']) && $form['type']['#value'] . '_node_form' == $form_id) {
- // If the rating is enabled for this node type, we insert our control
- // into the form.
- $node = $form['#node'];
- if (variable_get('nodeapi_example_' . $form['type']['#value'], FALSE)) {
- $form['nodeapi_example_rating'] = array(
- '#type' => 'select',
- '#title' => t('Rating'),
- '#default_value' => isset($node->nodeapi_example_rating) ? $node->nodeapi_example_rating : '',
- '#options' => array(0 => t('Unrated'), 1, 2, 3, 4, 5),
- '#required' => TRUE,
- '#weight' => 0,
- );
- }
- }
-}
-
-/**
- * hook_nodeapi() has been replaced in Drupal 7 with a set of different hooks
- * providing the same or improved functionality.
- *
- * The replacement functions providing access to events ocurred to content in
- * Drupal is listed below, and detailled in the following location:
- * http://api.drupal.org/api/group/hooks/7
- * or in the node API declaration file: modules/node/node.api.php
- *
- * hook_node_access() - Control access to a node.
- * hook_node_access_records() - Set permissions for a node to be written to the database.
- * hook_node_access_records_alter() - Alter permissions for a node before it is written to the database.
- * hook_node_build_alter() - The node content was built, the module may modify the structured content.
- * hook_node_delete() - Act on node deletion.
- * hook_node_grants() - Inform the node access system what permissions the user has.
- * hook_node_grants_alter() - Alter user access rules when trying to view, edit or delete a node.
- * hook_node_info() - Defines module-provided node types.
- * hook_node_insert() - Respond to node insertion.
- * hook_node_load() - Act on node objects when loaded.
- * hook_node_operations() - Add mass node operations.
- * hook_node_prepare() - The node is about to be shown on the add/edit form.
- * hook_node_prepare_translation() - The node is being cloned for translation.
- * hook_node_presave() - The node passed validation and is about to be saved.
- * hook_node_revision_delete() - A revision of the node is deleted.
- * hook_node_search_result() - The node is being displayed as a search result.
- * hook_node_type_delete() - Act on node type deletion.
- * hook_node_type_insert() - Act on node type creation.
- * hook_node_type_update() - Act on node type changes.
- * hook_node_update() - The node being updated.
- * hook_node_update_index() - The node is being indexed.
- * hook_node_validate() - The user has finished editing the node and is previewing or submitting it.
- * hook_node_view() - The node content is being assembled before rendering.
- *
- */
-
-/**
- * Implements hook_node_validate().
- *
- * Check that rating attribute is set in the form submission, the field is
- * required
- */
-function nodeapi_example_node_validate($node, $form) {
- if (variable_get('nodeapi_example_' . $node->type, FALSE)) {
- if (isset($node->nodeapi_example_rating) && !$node->nodeapi_example_rating) {
- form_set_error('nodeapi_example_rating', t('You must rate this content.'));
- }
- }
-}
-
-/**
- * Implements hook_node_load().
- *
- * Load the rating information if available for any of the nodes in the argument
- * list.
- */
-function nodeapi_example_node_load($nodes, $form) {
- foreach ($nodes as $node) {
- // We are using the revision id instead of node id
- if (variable_get('nodeapi_example_' . $node->type, FALSE)) {
- $vids[] = $node->vid;
- }
- }
- // Check if we should load rating for any of the nodes
- if (!isset($vids) || !count($vids)) {
- return;
- }
-
- // When we read, we don't care about the node->nid, but we look for the right
- // revision ID (node->vid)
- $result = db_select('nodeapi_example', 'e')
- ->fields('e', array(
- 'nid',
- 'vid',
- 'rating',
- ))
- ->where('e.vid IN (:vids)', array(':vids' => $vids))
- ->execute();
-
- foreach ($result as $record) {
- $nodes[$record->nid]->nodeapi_example_rating = $record->rating;
- }
-}
-
-/**
- * Implements hook_node_insert().
- *
- * As a new node is being inserted into the database, we need to do our own
- * database inserts.
- */
-function nodeapi_example_node_insert($node) {
- if (variable_get('nodeapi_example_' . $node->type, FALSE)) {
- // Notice that we are ignoring any revision information using $node->nid
- db_insert('nodeapi_example')
- ->fields(array(
- 'nid' => $node->nid,
- 'vid' => $node->vid,
- 'rating' => $node->nodeapi_example_rating,
- ))
- ->execute();
- }
-}
-
-/**
- * Implements hook_node_delete().
- *
- * When a node is deleted, we need to remove all related records from our table,
- * including all revisions. For the delete operations we use node->nid.
- */
-function nodeapi_example_node_delete($node) {
- // Notice that we're deleting even if the content type has no rating enabled.
- db_delete('nodeapi_example')
- ->condition('nid', $node->nid)
- ->execute();
-}
-
-/**
- * Implements hook_node_update().
- *
- * As an existing node is being updated in the database, we need to do our own
- * database updates.
- *
- * Update is called when an existing node has been changed. Here, we use a
- * DELETE then an INSERT rather than an UPDATE. The reason is that a node
- * created before this module was installed won't already have a rating
- * saved so there would be nothing to update.
- */
-function nodeapi_example_node_update($node) {
- if (variable_get('nodeapi_example_' . $node->type, FALSE)) {
- // If may happen that this node does not have a previous saved rating
- // value, so we can't just update it, we need to check first if this
- $rating = db_select('nodeapi_example', 'e')
- ->fields('e', array(
- 'rating',
- ))
- ->where('e.vid = (:vid)', array(':vid' => $node->vid))
- ->execute()->fetchField();
-
- if($rating) {
- // node has been rated before.
- db_update('nodeapi_example')
- ->fields(array('rating' => $node->nodeapi_example_rating))
- ->condition('vid', $node->vid)
- ->execute();
- }
- else {
- // Node was not previously rated, so insert a new rating in database.
- nodeapi_example_node_insert($node);
- }
- }
-}
-
-/**
- * Implements hook_view().
- *
- * This is a typical implementation that simply runs the node text through
- * the output filters.
- *
- * Finally, we need to take care of displaying our rating when the node is
- * viewed. This operation is called after the node has already been prepared
- * into HTML and filtered as necessary, so we know we are dealing with an
- * HTML teaser and body. We will inject our additional information at the front
- * of the node copy.
- *
- * Using node API 'hook_node_view' is more appropriate than using a filter here, because
- * filters transform user-supplied content, whereas we are extending it with
- * additional information.
- */
-function nodeapi_example_node_view($node, $build_mode = 'full') {
- if (variable_get('nodeapi_example_' . $node->type, FALSE)) {
- // Make sure to set a rating, also for nodes saved previously and not yet rated.
- $rating = isset($node->nodeapi_example_rating) ? $node->nodeapi_example_rating : 0;
- $node->content['nodeapi_example'] = array(
- '#markup' => theme('nodeapi_example_rating', array('rating' => $rating)),
- '#weight' => -1,
- );
- }
-}
-
-/**
- * Implements hook_theme().
- *
- * This lets us tell Drupal about our theme functions and their arguments.
- */
-function nodeapi_example_theme() {
- return array(
- 'nodeapi_example_rating' => array(
- 'variables' => array('rating' => NULL),
- ),
- );
-}
-
-/**
- * A custom theme function.
- *
- * By using this function to format our rating, themes can override this presentation
- * if they wish; for example, they could provide a star graphic for the rating. We
- * also wrap the default presentation in a CSS class that is prefixed by the module
- * name. This way, style sheets can modify the output without requiring theme code.
- */
-function theme_nodeapi_example_rating($variables) {
- $options = array(
- 0 => t('Unrated'),
- 1 => t('Poor'),
- 2 => t('Needs improvement'),
- 3 => t('Acceptable'),
- 4 => t('Good'),
- 5 => t('Excellent'),
- );
- $output = '<div class="nodeapi_example_rating">';
- $output .= t('Rating: %rating', array('%rating' => $options[(int) $variables['rating']]));
- $output .= '</div>';
- return $output;
-}
-
diff --git a/nodeapi_example/nodeapi_example.test b/nodeapi_example/nodeapi_example.test
deleted file mode 100644
index e16ef8e..0000000
--- a/nodeapi_example/nodeapi_example.test
+++ /dev/null
@@ -1,211 +0,0 @@
-<?php
-
-/**
- * @file
- * Test case for Testing the node API example module.
- *
- * This file contains the test cases to check if module is performing as
- * expected.
- *
- */
-class NodeApiExampleTestCase extends DrupalWebTestCase {
- /**
- * User object to perform site browsing
- * @var object
- */
- protected $web_user;
-
- /**
- * Content type to attach the rating system
- * @var string
- */
- protected $type;
-
- public static function getInfo() {
- return array(
- 'name' => 'Node API example functionality',
- 'description' => 'Demonstrate Node API hooks that allow altering a node. These are the former hook_nodeapi.',
- 'group' => 'Examples',
- );
- }
-
- /**
- * Enable modules and create user with specific permissions.
- */
- function setUp() {
- parent::setUp('nodeapi_example');
-
- // Create admin user. This module has no access control, so we can use a
- // trusted user. Revision access and revert permissions are required too.
- $this->web_user = $this->drupalCreateUser(array(
- 'administer nodes', // Required to set revision checkbox
- 'administer content types',
- 'bypass node access',
- 'view revisions',
- 'revert revisions'
- ));
- // Login the admin user.
- $this->drupalLogin($this->web_user);
- }
-
- /**
- * Login user, create an example node, and use the rating system
- */
- function testNodeExampleBasic() {
-
- // Login the user.
- $this->drupalLogin($this->web_user);
-
- // Create custom content type
- $content_type = $this->drupalCreateContentType();
- $type = $content_type->type;
-
- // Go to edit the settings of this content type
- $this->drupalGet('admin/structure/types/manage/' . $type);
- $this->assertResponse(200);
-
- // Check if the new Rating options appear in the settings page
- $this->assertText(t('NodeAPI Example Rating'), t('Rating options found in content type.'));
- $this->assertFieldByName('nodeapi_example', 1, t('Rating is Disabled by default.'));
-
- // Disable the rating for this content type: 0 for Disabled, 1 for Enabled.
- $content_settings = array(
- 'nodeapi_example' => 0,
- );
- $this->drupalPost('admin/structure/types/manage/' . $type, $content_settings, t('Save content type'));
- $this->assertResponse(200);
- $this->assertRaw(' has been updated.', t('Settings modified successfully for content type.'));
-
- // Create an example node
- $langcode = LANGUAGE_NONE;
- $edit = array(
- "title" => $this->randomName(),
- );
- $this->drupalPost('node/add/' . $type, $edit, t('Save'));
- $this->assertResponse(200);
-
- // Check that the rating is not shown, as we have not yet enabled it
- $this->assertNoRaw('Rating: <em>', t('Extended rating information is not shown.'));
-
- // Save current current url (we are viewing the new node)
- $node_url = $this->getUrl();
-
- // Enable the rating for this content type: 0 for Disabled, 1 for Enabled.
- $content_settings = array(
- 'nodeapi_example' => TRUE,
- );
- $this->drupalPost('admin/structure/types/manage/' . $type, $content_settings, t('Save content type'));
- $this->assertResponse(200);
- $this->assertRaw(' has been updated.', t('Settings modified successfully for content type.'));
-
- // Check previously create node. It should be not rated
- $this->drupalGet($node_url);
- $this->assertResponse(200);
- $this->assertRaw(t('Rating: %rating', array('%rating' => t('Unrated'))), t('Content is not rated.'));
-
- // Rate the content, 4 is for "Good"
- $rate = array(
- 'nodeapi_example_rating' => 4,
- );
- $this->drupalPost($node_url . '/edit', $rate, t('Save'));
- $this->assertResponse(200);
-
- // Check that content has been rated
- $this->assertRaw(t('Rating: %rating', array('%rating' => t('Good'))), t('Content is successfully rated.'));
-
- }
-
- /**
- * Login user, create an example node, and test rating functionality with
- * a node using revisions.
- */
- function testNodeExampleRevision() {
-
- // Login the user.
- $this->drupalLogin($this->web_user);
-
- // Create custom content type
- $content_type = $this->drupalCreateContentType();
- $type = $content_type->type;
-
- // Go to edit the settings of this content type
- $this->drupalGet('admin/structure/types/manage/' . $type);
- $this->assertResponse(200);
-
- // Check if the new Rating options appear in the settings page
- $this->assertText(t('NodeAPI Example Rating'), t('Rating options found in content type.'));
- $this->assertFieldByName('nodeapi_example', 1, t('Rating is Disabled by default.'));
-
- // Disable the rating for this content type: 0 for Disabled, 1 for Enabled.
- $content_settings = array(
- 'nodeapi_example' => 0,
- );
- $this->drupalPost('admin/structure/types/manage/' . $type, $content_settings, t('Save content type'));
- $this->assertResponse(200);
- $this->assertRaw(' has been updated.', t('Settings modified successfully for content type.'));
-
- // Create an example node
- $langcode = LANGUAGE_NONE;
- $edit = array(
- "title" => $this->randomName(),
- );
- $this->drupalPost('node/add/' . $type, $edit, t('Save'));
- $this->assertResponse(200);
-
- // Check that the rating is not shown, as we have not yet enabled it
- $this->assertNoRaw('Rating: <em>', t('Extended rating information is not shown.'));
-
- // Save current current url (we are viewing the new node)
- $node_url = $this->getUrl();
-
- // Enable the rating for this content type: 0 for Disabled, 1 for Enabled.
- $content_settings = array(
- 'nodeapi_example' => TRUE,
- );
- $this->drupalPost('admin/structure/types/manage/' . $type, $content_settings, t('Save content type'));
- $this->assertResponse(200);
- $this->assertRaw(' has been updated.', t('Settings modified successfully for content type.'));
-
- // Check previously create node. It should be not rated
- $this->drupalGet($node_url);
- $this->assertResponse(200);
- $this->assertRaw(t('Rating: %rating', array('%rating' => t('Unrated'))), t('Content is not rated.'));
-
- // Rate the content, 4 is for "Good"
- $rate = array(
- 'nodeapi_example_rating' => 4,
- );
- $this->drupalPost($node_url . '/edit', $rate, t('Save'));
- $this->assertResponse(200);
-
- // Check that content has been rated
- $this->assertRaw(t('Rating: %rating', array('%rating' => t('Good'))), t('Content is successfully rated.'));
-
- // Rate the content to poor using a new revision, 1 is for "Poor"
- $rate = array(
- 'nodeapi_example_rating' => 1,
- 'revision' => 1,
- );
- $this->drupalPost($node_url . '/edit', $rate, t('Save'));
- $this->assertResponse(200);
-
- // Check that content has been rated
- $this->assertRaw(t('Rating: %rating', array('%rating' => t('Poor'))), t('Content is successfully rated.'));
-
- //Now switch back to previous revision of the node.
- $this->drupalGet($node_url . '/revisions');
- // There is only a revision, so it must work just clicking the first link..
- $this->clickLink('revert');
- $revert_form = $this->getUrl();
- $this->drupalPost($revert_form, array(), t('Revert'));
-
- // Go back to the node page.
- $this->drupalGet($node_url);
- $this->assertResponse(200);
-
- // Check that content has been rated
- $this->assertRaw(t('Rating: %rating', array('%rating' => t('Good'))), t('Content rating matches reverted revision.'));
-
- }
-
-}
diff --git a/page_example/page_example.info b/page_example/page_example.info
deleted file mode 100644
index 3160a90..0000000
--- a/page_example/page_example.info
+++ /dev/null
@@ -1,6 +0,0 @@
-
-name = Page example
-description = An example module showing how to define a page to be displayed to the user at a given URL.
-package = Example modules
-core = 7.x
-files[] = page_example.test
diff --git a/page_example/page_example.module b/page_example/page_example.module
deleted file mode 100755
index 494ce73..0000000
--- a/page_example/page_example.module
+++ /dev/null
@@ -1,167 +0,0 @@
-<?php
-
-/**
- * @file
- * This is an example outlining how a module can be used to display a
- * custom page at a given URL.
- */
-
-/**
- * Implements hook_help().
- *
- * Throughout Drupal, hook_help() is used to display help text at the top of
- * pages. Some other parts of Drupal pages get explanatory text from these hooks
- * as well. We use it here to illustrate how to add help text to the pages your
- * module defines.
- */
-function page_example_help($path, $arg) {
- switch ($path) {
- case 'admin/help#simple':
- // Here is some help text for a custom page.
- return t('This sentence contains all the letters in the English alphabet.');
- }
-}
-
-/**
- * Implements hook_permission().
- *
- * Since the access to our new custom pages will be granted based on
- * special permissions, we need to define what those permissions are here.
- * This ensures that they are available to enable on the user role
- * administration pages.
- */
-function page_example_permission() {
- return array(
- 'access simple page' => array(
- 'title' => t('Access simple page'),
- 'description' => t('Allow users to access simple page'),
- ),
- 'access arguments page' => array(
- 'title' => t('Access page with arguments'),
- 'description' => t('Allow users to access page with arguments'),
- ),
- );
-}
-
-/**
- * Implements hook_menu().
- *
- * hook_menu() must be implemented to emit items to place in the main menu.
- * This is a required step for modules wishing to display their own pages,
- * because the process of creating the links also tells Drupal what
- * callback function to use for a given URL. The menu items returned
- * here provide this information to the menu system.
- *
- * With the below menu definitions, URLs will be interpreted as follows:
- *
- * If the user accesses http://example.com/?q=examples/page_example/simple, then
- * the menu system will first look for a menu item with that path. In this case
- * it will find a match, and execute page_example_simple().
- *
- * If the user accesses http://example.com/?q=examples/page_example/arguments,
- * no match will be found, so the system will look for 'examples/page_example',
- * which exists, and that page will be displayed.
- *
- * If the user accesses http://example.com/?q=examples/page_example/arguments,
- * the menu system will find no explicit match so will fall back to execute
- * page_example_description().
- *
- * If the user accesses
- * http://example.com/?q=examples/page_example/arguments/1/2, the menu
- * system will first look for examples/page_example/arguments/1/2. Not finding
- * a match, it will look for examples/page_example/arguments/1/%. Again not
- * finding a match, it will look for examples/page_example/arguments/%/2.
- * Yet again not finding a match, it will look for
- * examples/page_example/arguments/%/%. This time it finds a match, and so will
- * execute page_example_arguments(1, 2). Since the parameters are passed to
- * the function after the match, the function can do additional checking or
- * make use of them without resulting to the arg() function.
- *
- * The @link menu_example.module Menu Example @endlink provides extensive
- * examples for hook_menu().
- */
-function page_example_menu() {
-
- // This is the minimum information you can provide for a menu item. This menu
- // item will be created in the default menu.
- $items['examples/page_example'] = array(
- 'title' => 'Page Example',
- 'page callback' => 'page_example_description',
- 'access callback' => TRUE,
- 'expanded' => TRUE,
- );
-
- $items['examples/page_example/simple'] = array(
- 'title' => 'Simple - no arguments',
- 'page callback' => 'page_example_simple',
- 'access arguments' => array('access simple page'),
- );
-
- // By using the MENU_CALLBACK type, we can register the callback for this
- // path but do not have the item show up in the menu; the admin is not allowed
- // to enable the item in the menu, either.
- //
- // Notice that the 'page arguments' is an array of numbers. These will be
- // replaced with the corresponding parts of the menu path. In this case a 0
- // would be replaced by 'example', a 1 by 'arguments', and like wise 2 and 3 will
- // be replaced by what ever the user provides. These will be passed as
- // arguments to the page_example_arguments() function.
- $items['examples/page_example/arguments/%/%'] = array(
- 'page callback' => 'page_example_arguments',
- 'page arguments' => array(3, 4),
- 'access arguments' => array('access arguments page'),
- 'type' => MENU_CALLBACK,
- );
-
- return $items;
-}
-
-function page_example_description() {
- return array('#markup' => t('The page_example provides two pages, "simple" and "arguments". The <a href="@simple_link">simple page</a> just returns a renderable array for display. The <a href="@arguments_link">arguments page</a> takes two arguments and displays them, as in @arguments_link', array('@simple_link' => url('examples/page_example/simple', array('absolute' => TRUE)), '@arguments_link' => url('examples/page_example/arguments/23/56', array('absolute' => TRUE)))));
-}
-/**
- * A simple page callback.
- *
- * Page callbacks return a renderable array with the content area of the page.
- * The theme system will later render and surround the content in the
- * appropriate blocks, navigation, and styling.
- *
- * If you do not want to use the theme system (for example for outputting an
- * image or XML), you should print the content yourself and not return anything.
- */
-function page_example_simple() {
- return array('#markup' => '<p>' . t('Simple page: The quick brown fox jumps over the lazy dog.') . '</p>');
-}
-
-/**
- * A more complex page callback that takes arguments.
- *
- * The arguments are passed in from the page URL. The in our hook_menu
- * implementation we instructed the menu system to extract the last two
- * parameters of the path and pass them to this function as arguments.
- *
- * This function also demonstrates a more complex render array in the returned
- * values. Instead of just rendering the HTML with a theme('item_list'), the
- * list is left unrendered, and a #theme attached to it so that it can be
- * rendered as late as possible, giving more parts of the system a chance to
- * change it if necessary.
- */
-function page_example_arguments($first, $second) {
- // Make sure you don't trust the URL to be safe! Always check for exploits.
- if (!is_numeric($first) || !is_numeric($second)) {
- // We will just show a standard "access denied" page in this case.
- drupal_access_denied();
- return; // We actually don't get here.
- }
-
- $list[] = t("First number was @number.", array('@number' => $first));
- $list[] = t("Second number was @number.", array('@number' => $second));
- $list[] = t('The total was @number.', array('@number' => $first + $second));
-
- $render_array['page_example_arguments'] = array(
- '#theme' => 'item_list', // The theme function to apply to the #items
- '#items' => $list, // The list itself.
- '#title' => t('Argument Information'),
- );
- return $render_array;
-}
diff --git a/page_example/page_example.test b/page_example/page_example.test
deleted file mode 100644
index a806a43..0000000
--- a/page_example/page_example.test
+++ /dev/null
@@ -1,119 +0,0 @@
-<?php
-
-/**
- * @file
- * Test case for Testing the page example module.
- *
- * This file contains the test cases to check if module is performing as
- * expected.
- *
- */
-class PageExampleTestCase extends DrupalWebTestCase {
- protected $web_user;
-
- public static function getInfo() {
- return array(
- 'name' => 'Page example functionality',
- 'description' => 'Creates page and render the content based on the arguments passed in the URL.',
- 'group' => 'Examples',
- );
- }
-
- /**
- * Enable modules and create user with specific permissions.
- */
- function setUp() {
- parent::setUp('page_example');
- }
-
- /**
- * Generates a random string of ASCII numeric characters (values 48 to 57).
- *
- * @param $length
- * Length of random string to generate .
- * @return
- * Randomly generated string.
- */
- private static function randomNumber($length = 8) {
- $str = '';
- for ($i = 0; $i < $length; $i++) {
- $str .= chr(mt_rand(48, 57));
- }
- return $str;
- }
-
- /**
- * Verify that current user has no access to page.
- *
- * @param $url
- * URL to verify.
- */
- function pageExampleVerifyNoAccess($url) {
- // Test that page returns 403 Access Denied
- $this->drupalGet($url);
- $this->assertResponse(403);
- }
-
- /**
- * Login user, create an example node, and test blog functionality through the admin and user interfaces.
- */
- function testPageExampleBasic() {
-
- // Verify that anonymous user can't access the pages created by
- // page_example module
- $this->pageExampleVerifyNoAccess('examples/page_example/simple');
- $this->pageExampleVerifyNoAccess('examples/page_example/arguments/1/2');
-
- // Create a regular user and login.
- $this->web_user = $this->drupalCreateUser();
- $this->drupalLogin($this->web_user);
-
- // Verify that regular user can't access the pages created by
- // page_example module
- $this->pageExampleVerifyNoAccess('examples/page_example/simple');
- $this->pageExampleVerifyNoAccess('examples/page_example/arguments/1/2');
-
- // Create a user with permissions to access 'simple' page and login.
- $this->web_user = $this->drupalCreateUser(array('access simple page'));
- $this->drupalLogin($this->web_user);
-
- // Verify that user can access simple content
- $this->drupalGet('examples/page_example/simple');
- $this->assertResponse(200, t('simple content successfully accessed.'));
- $this->assertText(t('The quick brown fox jumps over the lazy dog.'), t('Simple content successfully verified.'));
-
- // Check if user can't access arguments page
- $this->pageExampleVerifyNoAccess('examples/page_example/arguments/1/2');
-
-
-
- // Create a user with permissions to access 'simple' page and login.
- $this->web_user = $this->drupalCreateUser(array('access arguments page'));
- $this->drupalLogin($this->web_user);
-
- // Verify that user can access simple content
- $first = $this->randomNumber(3);
- $second = $this->randomNumber(3);
- $this->drupalGet('examples/page_example/arguments/' . $first . '/' . $second);
- $this->assertResponse(200, t('arguments content successfully accessed.'));
- // Verify argument usage
- $this->assertRaw(t("First number was @number.", array('@number' => $first)), t('arguments first argument successfully verified.'));
- $this->assertRaw(t("Second number was @number.", array('@number' => $second)), t('arguments second argument successfully verified.'));
- $this->assertRaw(t('The total was @number.', array('@number' => $first + $second)), t('arguments content successfully verified.'));
-
- // Verify incomplete argument call to arguments content
- $this->drupalGet('examples/page_example/arguments/' . $first . '/');
- $this->assertText("provides two pages");
-
- // Verify invalid argument call to arguments content
- $this->drupalGet('examples/page_example/arguments/' . $first . '/' . $this->randomString());
- $this->assertResponse(403, t('Invalid argument for arguments content successfully verified'));
-
- // Verify invalid argument call to arguments content
- $this->drupalGet('examples/page_example/arguments/' . $this->randomString() . '/' . $second);
- $this->assertResponse(403, t('Invalid argument for arguments content successfully verified'));
-
- // Check if user can't access simple page
- $this->pageExampleVerifyNoAccess('examples/page_example/simple');
- }
-}
diff --git a/queue_example/queue_example.css b/queue_example/queue_example.css
deleted file mode 100644
index acb4565..0000000
--- a/queue_example/queue_example.css
+++ /dev/null
@@ -1,4 +0,0 @@
-
-.form-item-string-to-add, div.form-item-claim-time {
- display: inline;
-} \ No newline at end of file
diff --git a/queue_example/queue_example.info b/queue_example/queue_example.info
deleted file mode 100644
index 69b11ef..0000000
--- a/queue_example/queue_example.info
+++ /dev/null
@@ -1,6 +0,0 @@
-
-name = Queue example
-description = Examples of using the Drupal Queue API.
-package = Example modules
-core = 7.x
-files[] = queue_example.test
diff --git a/queue_example/queue_example.module b/queue_example/queue_example.module
deleted file mode 100644
index 1239f40..0000000
--- a/queue_example/queue_example.module
+++ /dev/null
@@ -1,275 +0,0 @@
-<?php
-
-/**
- * @file
- * Examples demonstrating the Drupal Queue API.
- *
- * The Queue API provides a traditional FIFO (first-in-first-out) queue,
- * but also provides the concepts of:
- * - "Creating" a queued item, which means inserting it into a queue.
- * - "Claiming" a queued item, which essentially means requesting the next item
- * from the queue and holding a lock on that item for a specified period of
- * time.
- * - "Releasing" an item, which means giving up a claim but leaving the item in
- * the queue.
- * - "Deleting" an item, which means finally removing it from the queue.
- *
- * This example demonstrates only basic queue functionality, and will use the
- * default queue implementation, which is SystemQueue, managed using
- * persistent database storage.
- *
- * Further resources include the limited @link queue @endlink documentation and
- * @link http://www.ent.iastate.edu/it/Batch_and_Queue.pdf Batch vs Queue Presentation slides by John VanDyk @endlink
- * and @link http://sf2010.drupal.org/conference/sessions/batch-vs-queue-api-smackdown session video. @endlink
- */
-
-/**
- * Implements hook_menu().
- */
-function queue_example_menu() {
- $items = array();
- $items['queue_example/insert_remove'] = array(
- 'title' => 'Queue Example: Insert and remove',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array('queue_example_add_remove_form'),
- 'access callback' => TRUE,
- );
-
- return $items;
-}
-
-/**
- * Provides an interface to add items to the queue, to retrieve (claim)
- * an item from the head of the queue, and to claim and delete. Also
- * allows the user to run cron manually, so that claimed items can be
- * released.
- */
-function queue_example_add_remove_form($form, &$form_state) {
- // Simple counter that makes it possible to put auto-incrementing default
- // string into the string to insert.
- if (empty($form_state['storage']['insert_counter'])) {
- $form_state['storage']['insert_counter'] = 1;
- }
-
- $queue_name = !empty($form_state['values']['queue_name']) ? $form_state['values']['queue_name'] : 'queue_example_first_queue';
- $items = queue_example_retrieve_queue($queue_name);
-
- // Add CSS to make the form a bit denser.
- $form['#attached']['css'] = array(drupal_get_path('module', 'queue_example') . '/queue_example.css');
-
- $form['help'] = array(
- '#type' => 'markup',
- '#markup' => '<div>' . t('This page is an interface on the Drupal queue API. You can add new items to the queue, "claim" one (retrieve the next item and keep a lock on it), and delete one (remove it from the queue). Note that claims are not expired until cron runs, so there is a special button to run cron to perform any necessary expirations.') . '</div>',
- );
-
- $form['queue_name'] = array(
- '#type' => 'select',
- '#title' => t('Choose queue'),
- '#options' => drupal_map_assoc(array('queue_example_first_queue', 'queue_example_second_queue')),
- );
- $form['insert_fieldset'] = array(
- '#type' => 'fieldset',
- '#title' => t('Insert into queue'),
- );
- $form['insert_fieldset']['string_to_add'] = array(
- '#type' => 'textfield',
- '#size' => 10,
- '#default_value' => t('item @counter', array('@counter' => $form_state['storage']['insert_counter'])),
- );
- $form['insert_fieldset']['add_item'] = array(
- '#type' => 'submit',
- '#value' => t('Insert into queue'),
- '#submit' => array('queue_example_add_remove_form_insert'),
- );
- $form['claim_fieldset'] = array(
- '#type' => 'fieldset',
- '#title' => t('Claim from queue'),
- '#collapsible' => TRUE,
- );
-
- $form['claim_fieldset']['claim_time'] = array(
- '#type' => 'radios',
- '#title' => t('Claim time, in seconds'),
- '#options' => array(0 => t('none'), 5 => t('5 seconds'), 60 => t('60 seconds')),
- '#description' => t('This time is only valid if cron runs during this time period. You can run cron manually below.'),
- '#default_value' => !empty($form_state['values']['claim_time']) ? $form_state['values']['claim_time'] : 5,
- );
- $form['claim_fieldset']['claim_item'] = array(
- '#type' => 'submit',
- '#value' => t('Claim the next item from the queue'),
- '#submit' => array('queue_example_add_remove_form_claim'),
- );
- $form['claim_fieldset']['claim_and_delete_item'] = array(
- '#type' => 'submit',
- '#value' => t('Claim the next item and delete it'),
- '#submit' => array('queue_example_add_remove_form_delete'),
- );
- $form['run_cron'] = array(
- '#type' => 'submit',
- '#value' => t('Run cron manually (to expire claimed items)'),
- '#submit' => array('queue_example_add_remove_form_run_cron'),
- );
- $form['delete_queue'] = array(
- '#type' => 'submit',
- '#value' => t('Delete the queue and items in it'),
- '#submit' => array('queue_example_add_remove_form_clear_queue'),
- );
- $form['status_fieldset'] = array(
- '#type' => 'fieldset',
- '#title' => t('Queue status'),
- '#collapsible' => TRUE,
- );
- $form['status_fieldset']['status'] = array(
- '#type' => 'markup',
- '#markup' => t('Queue status for queue @name:', array('@name' => $queue_name)) . '<br/>' . theme('queue_items', array('items' => $items)),
- );
- return $form;
-}
-
-/**
- * Submit function for the insert-into-queue button.
- */
-function queue_example_add_remove_form_insert($form, &$form_state) {
- // Get a queue (of the default type) called 'queue_example_queue'.
- // If the default queue class is SystemQueue this creates a queue that stores
- // its items in the database.
- $queue = DrupalQueue::get($form_state['values']['queue_name']);
- $queue->createQueue(); // There is no harm in trying to recreate existing.
-
- // Queue the string.
- $queue->createItem($form_state['values']['string_to_add']);
- $count = $queue->numberOfItems();
- drupal_set_message(t('Queued your string (@string_to_add). There are now @count items in the queue.', array('@count' => $count, '@string_to_add' => $form_state['values']['string_to_add'])));
- $form_state['rebuild'] = TRUE; // Allows us to keep information in $form_state.
- // Unsetting the string_to_add allows us to set the incremented default value
- // for the user so they don't have to type anything.
- unset($form_state['input']['string_to_add']);
- $form_state['storage']['insert_counter']++;
-}
-
-/**
- * Submit function for the "claim" button. Claims (retrieves) an item from
- * the queue and reports the results.
- */
-function queue_example_add_remove_form_claim($form, &$form_state) {
- $queue = DrupalQueue::get($form_state['values']['queue_name']);
- $queue->createQueue(); // There is no harm in trying to recreate existing.
- $item = $queue->claimItem($form_state['values']['claim_time']);
- $count = $queue->numberOfItems();
- if (!empty($item)) {
- drupal_set_message(t('Claimed item id=@item_id string=@string for @seconds seconds. There are @count items in the queue.', array('@count' => $count, '@item_id' => $item->item_id, '@string' => $item->data, '@seconds' => $form_state['values']['claim_time'])));
- }
- else {
- drupal_set_message(t('There were no items in the queue available to claim. There are @count items in the queue.', array('@count' => $count)));
- }
- $form_state['rebuild'] = TRUE;
-}
-
-/**
- * Submit function for "Claim and delete" button.
- */
-function queue_example_add_remove_form_delete($form, &$form_state) {
- $queue = DrupalQueue::get($form_state['values']['queue_name']);
- $queue->createQueue(); // There is no harm in trying to recreate existing.
- $count = $queue->numberOfItems();
- $item = $queue->claimItem(60);
- if (!empty($item)) {
- drupal_set_message(t('Claimed and deleted item id=@item_id string=@string for @seconds seconds. There are @count items in the queue.', array('@count' => $count, '@item_id' => $item->item_id, '@string' => $item->data, '@seconds' => $form_state['values']['claim_time'])));
- $queue->deleteItem($item);
- $count = $queue->numberOfItems();
- drupal_set_message(t('There are now @count items in the queue.', array('@count' => $count)));
- }
- else {
- $count = $queue->numberOfItems();
- drupal_set_message(t('There were no items in the queue available to claim/delete. There are currently @count items in the queue.', array('@count' => $count)));
- }
- $form_state['rebuild'] = TRUE;
-}
-
-/**
- * Submit function for "run cron" button.
- *
- * Runs cron (to release expired claims) and reports the results.
- */
-function queue_example_add_remove_form_run_cron($form, &$form_state) {
- drupal_cron_run();
- $queue = DrupalQueue::get($form_state['values']['queue_name']);
- $queue->createQueue(); // There is no harm in trying to recreate existing.
- $count = $queue->numberOfItems();
- drupal_set_message(t('Ran cron. If claimed items expired, they should be expired now. There are now @count items in the queue', array('@count' => $count)));
- $form_state['rebuild'] = TRUE;
-}
-
-/**
- * Submit handler for clearing/deleting the queue.
- */
-function queue_example_add_remove_form_clear_queue($form, &$form_state) {
- $queue = DrupalQueue::get($form_state['values']['queue_name']);
- $queue->deleteQueue();
- drupal_set_message(t('Deleted the @queue_name queue and all items in it', array('@queue_name' => $form_state['values']['queue_name'])));
-}
-
-/**
- * Retrieve the queue from the database for display purposes only.
- *
- * It is not recommended to access the database directly, and this is only here
- * so that the user interface can give a good idea of what's going on in the
- * queue.
- *
- * @param $queue_name
- * The name of the queue from which to fetch items.
- */
-function queue_example_retrieve_queue($queue_name) {
- $items = array();
- $result = db_query("SELECT item_id, data, expire, created FROM {queue} WHERE name = :name ORDER BY item_id",
- array(':name' => $queue_name),
- array('fetch' => PDO::FETCH_ASSOC));
- foreach ($result as $item) {
- $items[] = $item;
- }
- return $items;
-}
-
-/**
- * Theme the queue display.
- *
- * Again, this is not part of the demonstration of the queue API, but is here
- * just to make the user interface more understandable.
- *
- * @param $variables
- */
-function theme_queue_items($variables) {
- $items = $variables['items'];
- $rows = array();
- foreach ($items as &$item) {
- if ($item['expire'] > 0) {
- $item['expire'] = t("Claimed: expires %expire", array('%expire' => date('r', $item['expire'])));
- }
- else {
- $item['expire'] = t('Unclaimed');
- }
- $item['created'] = date('r', $item['created']);
- $item['content'] = check_plain(unserialize($item['data']));
- unset($item['data']);
- $rows[] = $item;
- }
- if (!empty($rows)) {
- $header = array(t('Item ID'), t('Claimed/Expiration'), t('Created'), t('Content/Data'));
- $output = theme('table', array('header' => $header, 'rows' => $rows));
- return $output;
- }
- else {
- return t('There are no items in the queue.');
- }
-}
-
-/**
- * Implements hook_theme().
- */
-function queue_example_theme() {
- return array(
- 'queue_items' => array(
- 'variables' => array('items' => NULL),
- ),
- );
-} \ No newline at end of file
diff --git a/queue_example/queue_example.test b/queue_example/queue_example.test
deleted file mode 100644
index 84628a2..0000000
--- a/queue_example/queue_example.test
+++ /dev/null
@@ -1,66 +0,0 @@
-<?php
-
-/**
- * @file
- * Test the queue example module.
- */
-class QueueExampleTestCase extends DrupalWebTestCase {
-
- public static function getInfo() {
- return array(
- 'name' => 'Queue Example functionality',
- 'description' => 'Test Queue Example functionality',
- 'group' => 'Examples',
- );
- }
-
- /**
- * Enable modules and create user with specific permissions.
- */
- function setUp() {
- parent::setUp('queue_example');
- }
-
- /**
- * Login user, create an example node, and test blog functionality through the admin and user interfaces.
- */
- function testQueueExampleBasic() {
-
- // Load the queue with 5 items.
- for ($i = 1; $i <= 5; $i++) {
- $edit = array('queue_name' => 'queue_example_first_queue', 'string_to_add' => "boogie$i");
- $this->drupalPost('queue_example/insert_remove', $edit, t('Insert into queue'));
- $this->assertText(t('There are now @number items in the queue', array('@number' => $i)));
- }
- // Claim each of the 5 items with a claim time of 0 seconds.
- for ($i = 1; $i <= 5; $i++) {
- $edit = array('queue_name' => 'queue_example_first_queue', 'claim_time' => 0);
- $this->drupalPost(NULL, $edit, t('Claim the next item from the queue'));
- $this->assertPattern(t('%Claimed item id=.*string=@string for 0 seconds.%', array('@string' => "boogie$i")));
- }
- $edit = array('queue_name' => 'queue_example_first_queue', 'claim_time' => 0);
- $this->drupalPost(NULL, $edit, t('Claim the next item from the queue'));
- $this->assertText(t('There were no items in the queue available to claim'));
-
- // Sleep a second so we can make sure that the timeouts actually time out.
- // Local systems work fine with this but apparently the PIFR server is so
- /// fast that it needs a sleep before the cron run.
- sleep(1);
-
- // Run cron to release expired items.
- $this->drupalPost(NULL, array(), t('Run cron manually (to expire claimed items)'));
-
- $queue_items = queue_example_retrieve_queue('queue_example_first_queue');
-
- // Claim and delete each of the 5 items which should now be available.
- for ($i = 1; $i <= 5; $i++) {
- $edit = array('queue_name' => 'queue_example_first_queue', 'claim_time' => 0);
- $this->drupalPost(NULL, $edit, t('Claim the next item and delete it'));
- $this->assertPattern(t('%Claimed and deleted item id=.*string=@string for 0 seconds.%', array('@string' => "boogie$i")));
- }
- // Verify that nothing is left to claim.
- $edit = array('queue_name' => 'queue_example_first_queue', 'claim_time' => 0);
- $this->drupalPost(NULL, $edit, t('Claim the next item from the queue'));
- $this->assertText(t('There were no items in the queue available to claim'));
- }
-}
diff --git a/render_example/render_example.css b/render_example/render_example.css
deleted file mode 100644
index de562c0..0000000
--- a/render_example/render_example.css
+++ /dev/null
@@ -1,21 +0,0 @@
-
-.render-array {
- border: 2px solid black;
- margin-top: 10px;
- padding-left: 5px;
- padding-top: 5px;
-}
-
-.render-header {
- font-size: large;
- font-style: italic;
-}
-
-.unrendered-label {
- font-style: italic;
- margin-top: 10px;
-}
-
-.rendered {
- background-color: lightblue;
-} \ No newline at end of file
diff --git a/render_example/render_example.info b/render_example/render_example.info
deleted file mode 100644
index 6e6c572..0000000
--- a/render_example/render_example.info
+++ /dev/null
@@ -1,7 +0,0 @@
-name = Render example
-description = Demonstrates drupal_render's capabilities and altering render arrays
-package = Example modules
-core = 7.x
-stylesheets[all][] = render_example.css
-files[] = render_example.test
-dependencies[] = devel
diff --git a/render_example/render_example.install b/render_example/render_example.install
deleted file mode 100644
index 225e5b8..0000000
--- a/render_example/render_example.install
+++ /dev/null
@@ -1,16 +0,0 @@
-<?php
-/**
- * @file render_example.install
- * Install/uninstall routines for render example.
- */
-
-/**
- * Implementation of hook_uninstall().
- */
-function render_example_uninstall() {
- variable_del('render_example_show_page');
- variable_del('render_example_show_block');
- variable_del('render_example_reverse_sidebar');
- variable_del('render_example_note_about_render_arrays');
- variable_del('render_example_move_navigation_menu');
-}
diff --git a/render_example/render_example.module b/render_example/render_example.module
deleted file mode 100644
index 9b471d3..0000000
--- a/render_example/render_example.module
+++ /dev/null
@@ -1,498 +0,0 @@
-<?php
-/**
- * @file render_example.module
- * Demonstrate how render arrays are arranged and how they can be altered.
- * This alters blocks and the page to show the actual render array
- * that is being used to create each item.
- *
- * @see drupal_render()
- */
-
-// This allows drupal_var_export() to work.
-require_once('includes/utility.inc');
-
-/**
- * Implements hook_menu().
- */
-function render_example_menu() {
- $items['examples/render_example'] = array(
- 'title' => 'Render Example',
- 'page callback' => 'render_example_info',
- 'access callback' => TRUE,
- );
- $items['examples/render_example/altering'] = array(
- 'title' => 'Alter pages and blocks',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array('render_example_demo_form'),
- 'access arguments' => array('access devel information'),
- );
- $items['examples/render_example/arrays'] = array(
- 'title' => 'Render array examples',
- 'page callback' => 'render_example_arrays',
- 'access callback' => TRUE,
- );
-
- return $items;
-}
-
-
-/**
- * Simple basic information about the module; an entry point.
- */
-function render_example_info() {
- return t('The render example provides a <ul><li><a href="!arrays">demonstration of of render array usage</a></li><li><a href="!alter">using hook_page_alter()</a> to make various changes on a page.</li></ul>', array('!arrays' => url('examples/render_example/arrays'), '!alter' => url('examples/render_example/altering')));
-}
-
-
-/**
- * Provides a number of render arrays and show what they do.
- * Each array is keyed by a description; it's returned for rendering at page
- * render time. It's easy to add new examples to this.
- *
- * The array items in $demos are intended to be raw, normal render arrays
- * that can be experimented with to end up with different outcomes.
- */
-function render_example_arrays() {
-
- $interval = 60; // Interval in seconds for cache update with #cache.
-
- $demos = array(
- // Demonstrate the simplest markup, a #markup element.
- t('Super simple #markup') => array(
- '#markup' => t('Some basic text in a #markup (shows basic markup and how it is rendered)'),
- ),
-
- // Shows how #prefix and #suffix can add markup into an array.
- t('Using #prefix and #suffix') => array(
- '#markup' => t('This one adds a prefix and suffix, which put a div around the item'),
- '#prefix' => '<div><br/>(prefix)<br/>',
- '#suffix' => '<br/>(suffix)</div>',
- ),
-
- // When #theme is provided, it is the #theme function's job to figure out
- // the meaning of the render array. The #theme function receives the entire
- // element in $variables and must return it, where it will be the content
- // of '#children'. When a #theme or other function is provided, custom
- // properties can be invented and used as needed, as the #separator
- // property provided here.
- //
- // If #theme is not provided, either explicitly or by the underlying
- // element, then the children are rendered using their own properties and
- // the results go into #children.
- t('theme for an element') => array(
- 'child' => array(
- t('This is some text that should be put together'),
- t('This is some more text that we need'),
- ),
- '#separator' => ' | ', // Made up for this theme function.
- '#theme' => 'render_example_aggregate',
- ),
-
- // #theme_wrappers provides an array of theme functions which theme the
- // envelope or "wrapper" of a set of child elements. The theme function
- // finds its element children (the sub-arrays) already rendered in
- // '#children'.
- t('theme_wrappers demonstration') => array(
- 'child1' => array('#markup' => t('Markup for child1')),
- 'child2' => array('#markup' => t('Markup for child2')),
- '#theme_wrappers' => array('render_example_add_div', 'render_example_add_notes'),
- ),
-
- // Add '#pre_render' and '#post_render' handlers.
- // - '#pre_render' functions get access to the array before it is rendered
- // and can change it. This is similar to a theme function, but it is a
- // specific fixed function and changes the array in place rather than
- // rendering it..
- // - '#post_render' functions get access to the rendered content, but also
- // have the original array available.
- t('pre_render and post_render') => array(
- '#markup' => '<div style="color:green">' . t('markup for pre_render and post_render example') . '</div>',
- '#pre_render' => array('render_example_add_suffix'),
- '#post_render' => array('render_example_add_prefix'),
- ),
-
- // Cache an element for $interval seconds using #cache.
- // The assumption here is that this is an expensive item to render, perhaps
- // large or otherwise expensive. Of course here it's just a piece of markup,
- // so we don't get the value.
- //
- // #cache allows us to set
- // - 'keys', an array of strings that will create the string cache key.
- // - 'bin', the cache bin
- // - 'expire', the expire timestamp. Note that this is actually limited
- // to the granularity of a cron run.
- // - 'granularity', a bitmask determining at what level the caching is done
- // (user, role, page).
- t('cache demonstration') => array(
- '#markup' => t('The current time was %time when this was cached. Updated every %interval seconds', array('%time' => date('r'), '%interval' => $interval)),
- '#cache' => array(
- 'keys' => array('render_example', 'cache', 'demonstration'),
- 'bin' => 'cache',
- 'expire' => time() + $interval,
- 'granularity' => DRUPAL_CACHE_PER_PAGE | DRUPAL_CACHE_PER_ROLE,
- ),
- ),
- );
-
-
- // The rest of this function just places the above arrays in a context where
- // they can be rendered (hopefully attractively and usefully) on the page.
- $page_array = array();
- foreach($demos as $key => $item) {
- $page_array[$key]['#theme_wrappers'] = array('render_array');
- $page_array[$key]['#description'] = $key;
-
- $page_array[$key]['unrendered'] = array(
- '#prefix' => '<div class="unrendered-label">' . t('Unrendered array (as plain text and with a krumo version)') . ':</div>',
- '#type' => 'markup',
- '#markup' => htmlentities(drupal_var_export($item)),
- );
- $page_array[$key]['kpr'] = array(
- // The kpr() function is from devel module and is here only allow us
- // to output the array in a way that's easy to explore.
- '#markup' => kpr($item, TRUE),
- );
- $page_array[$key]['hr'] = array('#markup' => '<hr/>');
- $page_array[$key]['rendered'] = array($item);
- $page_array[$key]['rendered']['#prefix'] = '<p><em>Rendered version (light blue)</em>:</p>' . '<div class="rendered">';
- $page_array[$key]['rendered']['#suffix'] = '</div>';
- }
-
- return $page_array;
-}
-
-
-/**
- * A '#pre_render' function.
- *
- * @param $element
- * The element which will be rendered.
- *
- * @return
- * The altered element. In this case we add a #prefix to it.
- */
-function render_example_add_suffix($element) {
- $element['#suffix'] = '<div style="color:red">' . t('This #suffix was added by a #pre_render') . '</div>';
-
- // The following line is due to the bug described in
- // http://drupal.org/node/914792. A #markup element's #pre_render must set
- // #children because it replaces the default #markup pre_render, which is
- // drupal_pre_render_markup().
- $element['#children'] = $element['#markup'];
- return $element;
-}
-
-/**
- * A '#post_render' function to add a little markup onto the end markup.
- *
- * @param $markup
- * The rendered element.
- * @param $element
- * The element which was rendered (for reference)
- * @return
- * Markup altered as necessary. In this case we add a little postscript to it.
- */
-function render_example_add_prefix($markup, $element) {
- $markup = '<div style="color:blue">This markup was added after rendering by a #post_render</div>' . $markup;
- return $markup;
-}
-
-/**
- * A #theme function has the responsibility of consolidating/rendering the
- * children's markup and returning it, where it will be placed in the
- * element's #children property.
- */
-function theme_render_example_aggregate($variables) {
- $output = '';
- foreach (element_children($variables['element']['child']) as $item) {
- $output .= $variables['element']['child'][$item] . $variables['element']['#separator'];
- }
- return $output;
-}
-
-/*************** Altering Section **************************
- * The following section of the example builds and arranges the altering
- * example.
- */
-/**
- * Builds the form that offers options of what items to show.
- */
-function render_example_demo_form($form, &$form_state) {
- $form['description'] = array(
- '#type' => 'markup',
- '#markup' => t('This example shows what render arrays look like in the building of a page. It will not work unless the user running it has the "access devel information" privilege. It shows both the actual arrays used to build a page or block and also the capabilities of altering the page late in its lifecycle.'),
- );
-
- $form['show_arrays'] = array(
- '#type' => 'fieldset',
- '#title' => t('Show render arrays'),
- );
-
- foreach (array('block', 'page') as $type) {
- $form['show_arrays']['render_example_show_' . $type] = array(
- '#type' => 'checkbox',
- '#title' => t('Show @type render arrays', array('@type' => $type)),
- '#default_value' => variable_get('render_example_show_' . $type, FALSE),
- );
- }
-
- $form['page_fiddling'] = array(
- '#type' => 'fieldset',
- '#title' => t('Make changes on page via hook_page_alter()'),
- );
- $form['page_fiddling']['render_example_note_about_render_arrays'] = array(
- '#title' => t('Add a note about render arrays to top of sidebar_first (if it exists)'),
- '#description' => t('Creates a simple render array that displays the use of #pre_render, #post_render, #theme, and #theme_wrappers.'),
- '#type' => 'checkbox',
- '#default_value' => variable_get('render_example_note_about_render_arrays', FALSE),
- );
- $form['page_fiddling']['render_example_move_navigation_menu'] = array(
- '#title' => t('Move the navigation menu to the top of the content area'),
- '#description' => t('Uses hook_page_alter() to move the navigation menu into another region.'),
- '#type' => 'checkbox',
- '#default_value' => variable_get('render_example_move_navigation_menu', FALSE),
- );
- $form['page_fiddling']['render_example_reverse_sidebar'] = array(
- '#title' => t('Reverse ordering of sidebar_first elements (if it exists) - will affect the above'),
- '#description' => t('Uses hook_page_alter() to reverse the ordering of items in sidebar_first'),
- '#type' => 'checkbox',
- '#default_value' => variable_get('render_example_reverse_sidebar', FALSE),
- );
- $form['page_fiddling']['render_example_prefix'] = array(
- '#title' => t('Use #prefix and #suffix to wrap a div around every block '),
- '#description' => t('Uses hook_page_alter to wrap all blocks with a div using #prefix and #suffix'),
- '#type' => 'checkbox',
- '#default_value' => variable_get('render_example_prefix'),
- );
-
- return system_settings_form($form);
-}
-
-/**
- * Implements hook_page_alter().
- *
- * Alters the page in several different ways based on how the form has been
- * configured.
- */
-function render_example_page_alter(&$page) {
-
- $original_page = $page;
-
- // Re-sort the sidebar in reverse order.
- if (variable_get('render_example_reverse_sidebar', FALSE) && !empty($page['sidebar_first'])) {
- $page['sidebar_first'] = array_reverse($page['sidebar_first']);
- foreach(element_children($page['sidebar_first']) as $element) {
- // Reverse the weights if they exist.
- if (!empty($page['sidebar_first'][$element]['#weight'])) {
- $page['sidebar_first'][$element]['#weight'] *= -1;
- }
- }
- $page['sidebar_first']['#sorted'] = FALSE;
- }
-
- // Add a list of items to the top of sidebar_first.
- // This shows how #theme and #theme_wrappers work.
- if (variable_get('render_example_note_about_render_arrays', FALSE) && !empty($page['sidebar_first'])) {
- $items = array(
- t('Render arrays are everywhere in D7'),
- t('Leave content unrendered as much as possible'),
- t('This allows rearrangement and alteration very late in page cycle'),
- );
-
- $note = array(
- '#title' => t('Render Array Example'),
- '#items' => $items,
-
- // The functions in #pre_render get to alter the actual data before it
- // gets rendered by the various theme functions.
- '#pre_render' => array('render_example_change_to_ol'),
- // The functions in #post_render get both the element and the rendered
- // data and can add to the rendered data.
- '#post_render' => array('render_example_add_hr'),
- // The #theme theme operation gets the first chance at rendering the
- // element and its children.
- '#theme' => 'item_list',
- // Then the theme operations in #theme_wrappers can wrap more around
- // what #theme left in #chilren.
- '#theme_wrappers' => array('render_example_add_div', 'render_example_add_notes'),
- '#weight' => -9999,
- );
- $page['sidebar_first']['render_array_note'] = $note;
- $page['sidebar_first']['#sorted'] = FALSE;
- }
-
-
- // Move the navigation menu into the content area.
- if (variable_get('render_example_move_navigation_menu', FALSE) && !empty($page['sidebar_first']['system_navigation']) && !empty($page['content'])) {
- $page['content']['system_navigation'] = $page['sidebar_first']['system_navigation'];
- $page['content']['system_navigation']['#weight'] = -99999;
- unset($page['content']['#sorted']);
- unset($page['sidebar_first']['system_navigation']);
- }
-
- // Show the render array used to build the page render array display.
- if (variable_get('render_example_show_page', FALSE)) {
- $form['render_example_page_fieldset'] = array(
- '#type' => 'fieldset',
- '#title' => t('Page render array'),
- '#collapsible' => TRUE,
- '#collapsed' => TRUE,
- );
- $form['render_example_page_fieldset']['markup'] = array(
- // The kpr() function is from devel module and is here only allow us
- // to output the array in a way that's easy to explore.
- '#markup' => kpr($page, TRUE),
- );
- $page['content']['page_render_array'] = drupal_get_form('render_example_embedded_form', $form);
- $page['content']['page_render_array']['#weight'] = -999999;
- $page['content']['#sorted'] = FALSE;
- }
-
- // Add render array to the bottom of each block
- if (variable_get('render_example_show_block', FALSE)) {
- foreach (element_children($page) as $region_name) {
- foreach (element_children($page[$region_name]) as $block_name) {
-
- // Push the block down a level so we can add another block after it.
- $old_block = $page[$region_name][$block_name];
- $page[$region_name][$block_name] = array(
- $block_name => $old_block,
- );
- $form['render_example_block_fieldset'] = array(
- '#type' => 'fieldset',
- '#title' => t('Block render array'),
- '#collapsible' => TRUE,
- '#collapsed' => TRUE,
- );
-
- $form['render_example_block_fieldset']['markup'] = array(
- '#type' => 'item',
- '#title' => t('%blockname block render array', array('%blockname' => $block_name)),
- // The kpr() function is from devel module and is here only allow us
- // to output the array in a way that's easy to explore.
- '#markup' => kpr($old_block, TRUE),
- );
-
- // Add the new block that contains the render array.
- $page[$region_name][$block_name]['render_example_block_render_array'] = drupal_get_form('render_example_embedded_form', $form);
- $page[$region_name][$block_name]['render_example_block_render_array']['#weight'] = 999;
- }
- }
- }
-
- // Add #prefix and #suffix to a block to wrap a div around it.
- if (variable_get('render_example_prefix', FALSE)) {
- foreach (element_children($page) as $region_name) {
- foreach(element_children($page[$region_name]) as $block_name) {
- $block = &$page[$region_name][$block_name];
- $block['#prefix'] = '<div class="block-prefix"><p>Prefixed</p>';
- $block['#suffix'] = '<span class="block-suffix">Block suffix</span></div>';
- }
- }
- }
- $altered_page = $page;
-
-}
-
-/**
- * Utility function to build a named form given a set of form elements.
- * This is a standard form builder function that takes an additional array,
- * which is itself a form.
- *
- * @param $form
- * The standard $form
- * @param $form_state
- * The standard $form_state
- * @param $form_items
- * The form items to be included in this form.
- */
-function render_example_embedded_form($form, &$form_state, $form_items) {
- return $form_items;
-}
-
-/**
- * Implements hook_theme().
- */
-function render_example_theme() {
- $items = array(
- 'render_example_add_div' => array(
- 'render element' => 'element',
- ),
- 'render_example_add_notes' => array(
- 'render element' => 'element',
- ),
- 'render_array' => array(
- 'render element' => 'element',
- ),
- 'render_example_aggregate' => array(
- 'render element' => 'element',
- ),
- );
- return $items;
-}
-
-/**
- * Wrap a div around the already-rendered #children.
- */
-function theme_render_example_add_div($variables) {
- $element = $variables['element'];
- $output = '<div class="render-example-wrapper-div">';
- $output .= $element['#children'];
- $output .= '</div>';
- return $output;
-}
-
-/**
- * Wrap a div and add a little text after the rendered #children.
- */
-function theme_render_example_add_notes($variables) {
- $element = $variables['element'];
- $output = '<div class="render-example-notes-wrapper-div">';
- $output .= $element['#children'];
- $output .= '<em>' . t('This is a note added by a #theme_wrapper') . '</em>';
- $output .= '</div>';
-
- return $output;
-}
-
-/**
- * Theme render array (from the demonstration page).
- */
-function theme_render_array($variables) {
- $heading = '<div class="render-header">' . $variables['element']['#description'] . '</div>';
-
- $rendered = '<div class="render-array">' . $heading . $variables['element']['#children'] . '</div>';
- return $rendered;
-}
-
-/**
- * Add a #type to the element before it gets rendered.
- * In this case, changes from the default 'ul' to 'ol'.
- * @param $element
- * The element to be altered, in this case a list, ready for theme_item_list.
- *
- * @return
- * The altered list (with '#type')
- */
-function render_example_change_to_ol($element) {
- $element['#type'] = 'ol';
- return $element;
-}
-
-/**
- * This #post_render function gets to alter the rendered output after all
- * theme functions have acted on it, and it receives the original data, so
- * can make decisions based on that. In this example, no use is made of the
- * passed-in $element.
- * @param $markup
- * The already-rendered data
- * @param unknown_type $element
- * The data element that was rendered
- *
- * @return
- * The altered data.
- */
-function render_example_add_hr($markup, $element) {
- $output = $markup . '<hr />';
- return $output;
-} \ No newline at end of file
diff --git a/render_example/render_example.test b/render_example/render_example.test
deleted file mode 100644
index 938a44c..0000000
--- a/render_example/render_example.test
+++ /dev/null
@@ -1,138 +0,0 @@
-<?php
-
-/**
- * @file
- * Test for the render example module.
- */
-class RenderExampleTestCase extends DrupalWebTestCase {
- public static function getInfo() {
- return array(
- 'name' => 'Render example functionality',
- 'description' => 'Test Render Example',
- 'group' => 'Examples',
- 'dependencies' => array('devel'),
- );
- }
-
- /**
- * Enable modules and create user with specific permissions.
- */
- function setUp() {
- parent::setUp('devel', 'render_example');
- }
-
-
- /**
- * Assert that all of the xpaths in the array have results.
- *
- * @param $xpath_array
- * An array of xpaths, each of which must return something.
- */
- function assertRenderResults($xpath_array) {
- foreach($xpath_array as $xpath) {
- $result = $this->xpath($xpath);
- $this->assertTrue(!empty($result), t('Found xpath ') . $xpath);
- }
- }
-
-
- /**
- * Asserts that the string value of the result is the same as the passed text.
- *
- * @param $xpath_array
- * Array of keyed arrays of tests to be made. Each child array consists of
- * $xpath => $expected_text
- */
- function assertRenderedText($xpath_array) {
- foreach($xpath_array as $xpath => $text) {
- $result = $this->xpath($xpath);
- $this->assertTrue((string)$result[0][0] == $text, t('%ary selects text %text', array('%ary' => $xpath, '%text' => $text)));
- }
- }
-
-
- /**
- * Login user, create an example node, and test blog functionality through the admin and user interfaces.
- */
- function testRenderExampleBasic() {
-
- // Create a user that can access devel information and log in.
- $web_user = $this->drupalCreateUser(array('access devel information', 'access content'));
- $this->drupalLogin($web_user);
-
- // Turn on the block render array display and make sure it shows up.
- $edit = array(
- 'render_example_show_block' => TRUE,
- );
- $this->drupalPost('examples/render_example/altering', $edit, t('Save configuration'));
-
- $xpath_array = array(
- "//div[@id='sidebar-first']//fieldset[starts-with(@id, 'edit-render-example-block-fieldset')]",
- '//*[@id="content"]//fieldset[contains(@id,"edit-render-example-block-fieldset")]',
- );
- $this->assertRenderResults($xpath_array);
-
-
- // Turn off block render array display and turn on the page render array
- // display.
- $edit = array(
- 'render_example_show_page' => TRUE,
- 'render_example_show_block' => FALSE,
- );
- $this->drupalPost('examples/render_example/altering', $edit, t('Save configuration'));
-
- $xpath_array = array(
- '//*[@id="content"]//fieldset[starts-with(@id,"edit-render-example-page-fieldset")]',
- );
- $this->assertRenderResults($xpath_array);
-
- // Add note about render arrays to the top of sidebar_first.
- $edit = array(
- 'render_example_note_about_render_arrays' => TRUE,
- );
- $this->drupalPost('examples/render_example/altering', $edit, t('Save configuration'));
- $xpath_array = array(
- '//*[@id="sidebar-first"]//ol//li[starts-with(.,"Render arrays are everywhere")]',
- );
- $this->assertRenderResults($xpath_array);
-
- // Move the navigation menu to the top of the content area.
- $edit = array(
- 'render_example_move_navigation_menu' => TRUE,
- );
- $this->drupalPost('examples/render_example/altering', $edit, t('Save configuration'));
- $xpath_array = array(
- '//*[@id="content"]//h2[starts-with(.,"Navigation")]',
- );
- $this->assertRenderResults($xpath_array);
-
- // Skip a test for reversing order of sidebar_first as I think it would
- // be too fragile.
-
- // Test the addition of #prefix and #suffix
- $edit = array(
- 'render_example_prefix' => TRUE,
- );
- $this->drupalPost('examples/render_example/altering', $edit, t('Save configuration'));
- $xpath_array = array(
- '//*[@id="sidebar-first"]//*[contains(@class, "block-prefix")]/span[contains(@class, "block-suffix")]',
- );
- $this->assertRenderResults($xpath_array);
-
- // Test some rendering facets of the various render examples
- $this->drupalGet('examples/render_example/arrays');
- $content = $this->xpath('//*[@class="render-array"][1]');
-
- $xpath_array = array(
- '//div[@class="rendered"][starts-with(.,"Some basic text in a #markup")]' => 'Some basic text in a #markup (shows basic markup and how it is rendered)',
- '//div[@class="rendered"][starts-with(.,"This is some text that should be put to")]' => 'This is some text that should be put together | This is some more text that we need | ',
- '//div[@class="rendered"][starts-with(.,"The current time was")]' => 'The current time was when this was cached. Updated every seconds',
- '//div[@class="rendered"]/div[text()][starts-with(.,"(prefix)This one")]' => '(prefix)This one adds a prefix and suffix, which put a div around the item(suffix)',
- '//div[@class="rendered"]/div[text()][starts-with(.,"markup for pre_")]' => 'markup for pre_render and post_render example',
- '//div[@class="rendered"]/div[text()][starts-with(.,"This markup was added")]' => 'This markup was added after rendering by a #post_render',
- '//div[@class="rendered"]/div[text()][starts-with(.,"This #suffix")]' => 'This #suffix was added by a #pre_render',
- );
- $this->assertRenderedText($xpath_array);
-
- }
-}
diff --git a/simpletest_example/simpletest_example.info b/simpletest_example/simpletest_example.info
deleted file mode 100644
index 503cae5..0000000
--- a/simpletest_example/simpletest_example.info
+++ /dev/null
@@ -1,7 +0,0 @@
-
-name = Simpletest Example
-description = Provides simpletest_example page node type.
-core = 7.x
-package = Example modules
-dependencies[] = simpletest
-files[] = simpletest_example.test
diff --git a/simpletest_example/simpletest_example.install b/simpletest_example/simpletest_example.install
deleted file mode 100644
index 494fcf0..0000000
--- a/simpletest_example/simpletest_example.install
+++ /dev/null
@@ -1,29 +0,0 @@
-<?php
-
-/**
- * @file
- * Install, update and uninstall functions for the simpletest_example module.
- */
-
-/**
- * Implements hook_install().
- */
-function simpletest_example_install() {
- // Ensure the simpletest_example node type is available.
- node_types_rebuild();
- $types = node_type_get_types();
- node_add_body_field($types['simpletest_example']);
-}
-
-function simpletest_example_uninstall() {
-
-}
-
-/**
- * Add a body field to the simpletest_example node type.
- */
-function simpletest_example_update_7001() {
- node_types_rebuild();
- $types = node_type_get_types();
- node_add_body_field($types['simpletest_example']);
-} \ No newline at end of file
diff --git a/simpletest_example/simpletest_example.module b/simpletest_example/simpletest_example.module
deleted file mode 100644
index c76ddc3..0000000
--- a/simpletest_example/simpletest_example.module
+++ /dev/null
@@ -1,112 +0,0 @@
-<?php
-
-/**
- * @file
- * An example of simpletest tests to accompany the tutorial at
- * http://drupal.org/node/890654.
- *
- * This is built on a traditional node-type implementation.
- *
- */
-
-
-/**
- * Implements hook_node_info().
- */
-function simpletest_example_node_info() {
- return array(
- 'simpletest_example' => array(
- 'name' => t('Simpletest Example Node Type'),
- 'module' => 'simpletest_example',
- 'base' => 'simpletest_example',
- 'description' => t('simpletest_example page node type.'),
- )
- );
-}
-
-/**
- * Implements hook_permission().
- *
- * In this case we're adding an addition permission that does the same
- * as the one the node module offers, just to demonstrate this error.
- */
-function simpletest_example_permission() {
- $perms = array();
- $perms['extra special edit any simpletest_example'] = array('title' => t('Extra special edit any Simpletest Example'), 'description' => t('Extra special edit any Simpletest Example'));
- return $perms;
-}
-
-/**
- * Implements hook_node_access().
- *
- * Demonstrates a bug that we'll find in our test.
- *
- * If this is running on the testbot, we don't want the error to show so will
- * work around it by testing to see if we're in the 'checkout' directory.
- */
-function simpletest_example_node_access($node, $op, $account) {
- // Don't get involved if this isn't a simpletest_example node, etc.
- $type = is_string($node) ? $node : $node->type;
- if ($type != 'simpletest_example' || ($op != 'update' && $op != 'delete')) {
- return NODE_ACCESS_IGNORE;
- }
-
- // This code has a BUG that we'll find in testing.
-
- // This is the incorrect version we'll use to demonstrate test failure.
- // The correct version should have ($op == 'update' || $op == 'delete').
- // The author had mistakenly always tested with User 1 so it always
- // allowed access and the bug wasn't noticed!
- if ( ($op == 'delete') && (user_access('extra special edit any simpletest_example', $account) && ($account->uid == $node->uid))) {
- return NODE_ACCESS_ALLOW;
- }
-
- return NODE_ACCESS_DENY;
-}
-
-/**
- * Implements hook_form().
- *
- * Form for the node type.
- */
-function simpletest_example_form($node, $form_state) {
- $type = node_type_get_type($node);
- $form = array();
- if ($type->has_title) {
- $form['title'] = array(
- '#type' => 'textfield',
- '#title' => check_plain($type->title_label),
- '#required' => TRUE,
- '#default_value' => $node->title,
- '#maxlength' => 255,
- '#weight' => -5,
- );
- }
- return $form;
-}
-
-/**
- * Implements hook_menu().
- *
- * Provide an explanation.
- */
-function simpletest_example_menu() {
- $items['examples/simpletest_example'] = array(
- 'title' => 'Simpletest Example',
- 'description' => 'Explain the simpletest example and allow the error logic to be executed.',
- 'page callback' => '_simpletest_example_explanation',
- 'access callback' => TRUE,
- );
- return $items;
-}
-
-/**
- * Return an explanation of this module.
- */
-function _simpletest_example_explanation() {
-
- $explanation = t("This Simpletest Example is designed to give an introductory tutorial to writing
- a simpletest test. Please see the <a href='http://drupal.org/node/890654'>associated tutorial</a>.");
- return $explanation;
-}
-
diff --git a/simpletest_example/simpletest_example.test b/simpletest_example/simpletest_example.test
deleted file mode 100644
index 23945a7..0000000
--- a/simpletest_example/simpletest_example.test
+++ /dev/null
@@ -1,79 +0,0 @@
-<?php
-
-/**
- * @file
- * An example of simpletest tests to accompany the tutorial at
- * http://drupal.org/node/890654.
- */
-
-class SimpletestExampleTestCase extends DrupalWebTestCase {
- protected $privileged_user;
-
- public static function getInfo() {
- return array(
- 'name' => 'Simpletest Example',
- 'description' => 'Ensure that the simpletest_example content type provided functions properly.',
- 'group' => 'Examples',
- );
- }
-
- public function setUp() {
- parent::setUp('simpletest_example'); // Enable any modules required for the test
- // Create and log in our user. The user has the arbitrary privilege
- // 'extra special edit any simpletest_example' which the code uses
- // to grant access.
- $this->privileged_user = $this->drupalCreateUser(array('create simpletest_example content', 'extra special edit any simpletest_example'));
- $this->drupalLogin($this->privileged_user);
- }
-
- // Create a simpletest_example node using the node form
- public function testSimpleTestExampleCreate() {
- // Create node to edit.
- $edit = array();
- $edit['title'] = $this->randomName(8);
- $edit["body[und][0][value]"] = $this->randomName(16);
- $this->drupalPost('node/add/simpletest-example', $edit, t('Save'));
- $this->assertText(t('Simpletest Example Node Type @title has been created.', array('@title' => $edit['title'])));
- }
-
- // Create a simpletest_example node and then see if our user can edit it
- public function testSimpleTestExampleEdit() {
- $settings = array(
- 'type' => 'simpletest_example',
- 'title' => $this->randomName(32),
- 'body' => array(LANGUAGE_NONE => array(array($this->randomName(64)))),
- );
- $node = $this->drupalCreateNode($settings);
-
- // For debugging, we might output the node structure with $this->verbose()
- $this->verbose('Node created: ' . var_export($node, TRUE));
- // It would only be output if the testing settings had 'verbose' set.
-
- // We'll run this test normally, but not on the testbot, as it would
- // indicate that the examples module was failing tests.
- if (!$this->runningOnTestbot()) {
- // The debug() statement will output information into the test results.
- // It can also be used in Drupal 7 anywhere in code and will come out
- // as a drupal_set_message().
- debug('We are not running on the PIFR testing server, so will go ahead and catch the failure.');
- $this->drupalGet("node/{$node->nid}/edit");
- // Make sure we don't get a 401 unauthorized response:
- $this->assertResponse(200, t('User is allowed to edit the content.'));
-
- // Looking for title text in the page to determine whether we were
- // successful opening edit form.
- $this->assertText(t("@title", array('@title' => $settings['title'])), "Found title in edit form");
- }
- }
-
- /**
- * Detect if we're running on PIFR testbot; skip intentional failure in that
- * case.
- * @return boolean
- * TRUE if running on testbot.
- */
- public function runningOnTestbot() {
- $testbot_code_directory = "../checkout";
- return file_exists($testbot_code_directory);
- }
-}
diff --git a/token_example/token_example.info b/token_example/token_example.info
deleted file mode 100644
index c6b7e3c..0000000
--- a/token_example/token_example.info
+++ /dev/null
@@ -1,7 +0,0 @@
-
-name = Token example
-description = An example module showing how to define and use tokens.
-dependencies[] = token
-package = Example modules
-core = 7.x
-files[] = token_example.test
diff --git a/token_example/token_example.module b/token_example/token_example.module
deleted file mode 100644
index a09dc86..0000000
--- a/token_example/token_example.module
+++ /dev/null
@@ -1,195 +0,0 @@
-<?php
-
-/**
- * Implements hook_menu().
- */
-function token_example_menu() {
- $items['examples/token'] = array(
- 'title' => 'Token example',
- 'description' => 'Test replacement tokens in real time.',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array('token_example_example_form'),
- 'access callback' => TRUE,
- );
- return $items;
-}
-
-/**
- * Implements hook_entity_info_alter().
- *
- * @todo Remove this when the testbot can properly pick up dependencies
- * for contrib modules.
- */
-function token_example_entity_info_alter(&$info) {
- if (isset($info['taxonomy_term'])) {
- $info['taxonomy_term']['token type'] = 'term';
- }
- if (isset($info['taxonomy_vocabulary'])) {
- $info['taxonomy_vocabulary']['token type'] = 'vocabulary';
- }
-}
-
-/**
- * Form builder; display lists of supported token entities and text to tokenize.
- */
-function token_example_example_form($form, &$form_state) {
- $entities = entity_get_info();
- $token_types = array();
-
- // Scan through the list of entities for supported token entities.
- foreach ($entities as $entity => $info) {
- $object_callback = "_token_example_get_{$entity}";
- if (function_exists($object_callback) && $objects = $object_callback()) {
- $form[$entity] = array(
- '#type' => 'select',
- '#title' => $info['label'],
- '#options' => array(0 => t('Not selected')) + $objects,
- '#default_value' => isset($form_state['storage'][$entity]) ? $form_state['storage'][$entity] : 0,
- '#access' => !empty($objects),
- );
-
- // Build a list of supported token types based on the available entites.
- if ($form[$entity]['#access']) {
- $token_types[$entity] = !empty($info['token type']) ? $info['token type'] : $entity;
- }
- }
- }
-
- $form['text'] = array(
- '#type' => 'textarea',
- '#title' => t('Enter your text here'),
- '#default_value' => 'Hello [current-user:name]!'
- );
-
- // Display the results of tokenized text.
- if (!empty($form_state['storage']['text'])) {
- $form['text']['#default_value'] = $form_state['storage']['text'];
-
- $data = array();
- foreach ($entities as $entity => $info) {
- if (!empty($form_state['storage'][$entity])) {
- $objects = entity_load($entity, array($form_state['storage'][$entity]));
- if ($objects) {
- $data[$token_types[$entity]] = reset($objects);
- }
- }
- }
-
- // Display the tokenized text.
- $form['text_tokenized'] = array(
- '#type' => 'item',
- '#title' => t('Result'),
- '#markup' => token_replace($form_state['storage']['text'], $data),
- );
- }
-
- $form['submit'] = array(
- '#type' => 'submit',
- '#value' => t('Submit'),
- );
-
- if (module_exists('token')) {
- $form['token_tree'] = array(
- '#theme' => 'token_tree',
- '#token_types' => $token_types,
- );
- }
- else {
- $form['token_tree'] = array(
- '#markup' => '<p>' . t('Enable the <a href="@drupal-token">Token module</a> to view the available token browser.', array('@drupal-token' => 'http://drupal.org/project/token')) . '</p>',
- );
- }
-
- return $form;
-}
-
-/**
- * Submit callback; store the submitted values into storage.
- */
-function token_example_example_form_submit($form, &$form_state) {
- $form_state['storage'] = $form_state['values'];
- $form_state['rebuild'] = TRUE;
-}
-
-/**
- * Build a list of available content.
- */
-function _token_example_get_node() {
- if (!user_access('access content') && !user_access('bypass node access')) {
- return array();
- }
-
- $node_query = db_select('node', 'n');
- $node_query->fields('n', array('nid', 'title'));
- $node_query->condition('n.status', NODE_PUBLISHED);
- $node_query->orderBy('n.created', 'DESC');
- $node_query->range(0, 10);
- $node_query->addTag('node_access');
- $nodes = $node_query->execute()->fetchAllKeyed();
- $nodes = array_map('check_plain', $nodes);
- return $nodes;
-}
-
-/**
- * Build a list of available comments.
- */
-function _token_example_get_comment() {
- if (!module_exists('comment') || (!user_access('access comments') && !user_access('administer comments'))) {
- return array();
- }
-
- $comment_query = db_select('comment', 'c');
- $comment_query->innerJoin('node', 'n', 'n.nid = c.nid');
- $comment_query->fields('c', array('cid', 'subject'));
- $comment_query->condition('n.status', NODE_PUBLISHED);
- $comment_query->condition('c.status', COMMENT_PUBLISHED);
- $comment_query->orderBy('c.created', 'DESC');
- $comment_query->range(0, 10);
- $comment_query->addTag('node_access');
- $comments = $comment_query->execute()->fetchAllKeyed();
- $comments = array_map('check_plain', $comments);
- return $comments;
-}
-
-/**
- * Build a list of available user accounts.
- */
-function _token_example_get_user() {
- if (!user_access('access user profiles') && !user_access('administer users')) {
- return array();
- }
-
- $account_query = db_select('users', 'u');
- $account_query->fields('u', array('uid', 'name'));
- $account_query->condition('u.uid', 0, '>');
- $account_query->condition('u.status', 1);
- $account_query->range(0, 10);
- $accounts = $account_query->execute()->fetchAllKeyed();
- $accounts = array_map('check_plain', $accounts);
- return $accounts;
-}
-
-/**
- * Build a list of available taxonomy terms.
- */
-function _token_example_get_taxonomy_term() {
- $term_query = db_select('taxonomy_term_data', 'ttd');
- $term_query->fields('ttd', array('tid', 'name'));
- $term_query->range(0, 10);
- $term_query->addTag('term_access');
- $terms = $term_query->execute()->fetchAllKeyed();
- $terms = array_map('check_plain', $terms);
- return $terms;
-}
-
-/**
- * Build a list of available files.
- */
-function _token_example_get_file() {
- $file_query = db_select('file_managed', 'f');
- $file_query->fields('f', array('fid', 'filename'));
- $file_query->range(0, 10);
- $files = $file_query->execute()->fetchAllKeyed();
- $files = array_map('check_plain', $files);
- return $files;
-}
diff --git a/token_example/token_example.test b/token_example/token_example.test
deleted file mode 100644
index 256ec46..0000000
--- a/token_example/token_example.test
+++ /dev/null
@@ -1,63 +0,0 @@
-<?php
-
-/**
- * @file
- * Test cases for Testing the token example module.
- */
-
-class TokenExampleTestCase extends DrupalWebTestCase {
- protected $web_user;
-
- public static function getInfo() {
- return array(
- 'name' => 'Token example functionality',
- 'description' => 'Verify the token example interface.',
- 'group' => 'Examples',
- 'dependencies' => array('token'),
- );
- }
-
- function setUp() {
- parent::setUp('token_example');
- $this->web_user = $this->drupalCreateUser();
- $this->drupalLogin($this->web_user);
- }
-
- function testInterface() {
- $filtered_id = db_query("SELECT format FROM {filter_format} WHERE name = 'Filtered HTML'")->fetchField();
- $plain_id = db_query("SELECT format FROM {filter_format} WHERE name = 'Plain text'")->fetchField();
-
- $this->drupalGet('examples/token');
- $this->assertNoFieldByName('node');
- $this->assertNoFieldByName('user');
-
- $edit = array(
- 'text' => 'User [current-user:name] is trying the token example!',
- );
- $this->drupalPost(NULL, $edit, t('Submit'));
- $this->assertText('User ' . $this->web_user->name . ' is trying the token example!');
-
- // Create a node and then make the 'Plain text' text format the default.
- $node = $this->drupalCreateNode(array('title' => 'Example node', 'status' => NODE_PUBLISHED));
- db_update('filter_format')
- ->fields(array('weight' => -10))
- ->condition('name', 'Plain text')
- ->execute();
-
- $this->drupalGet('examples/token');
- $this->assertFieldByName('node');
-
- $edit = array(
- 'text' => 'Would you like to view the [node:type-name] [node:title] with text format [node:body-format] (ID [node:body-format:id])?',
- 'node' => $node->nid,
- );
- $this->drupalPost(NULL, $edit, t('Submit'));
- $this->assertText('Would you like to view the Basic page Example node with text format Filtered HTML (ID ' . $filtered_id . ')?');
-
- $edit = array(
- 'text' => 'Your default text format is [default-format:name] (ID [default-format:id]).',
- );
- $this->drupalPost(NULL, $edit, t('Submit'));
- $this->assertText('Your default text format is Plain text (ID ' . $plain_id . ')');
- }
-}
diff --git a/token_example/token_example.tokens.inc b/token_example/token_example.tokens.inc
deleted file mode 100644
index 462e0c9..0000000
--- a/token_example/token_example.tokens.inc
+++ /dev/null
@@ -1,129 +0,0 @@
-<?php
-
-/**
- * @file
- * Token callbacks for the token_example module.
- */
-
-/**
- * Implements hook_token_info().
- */
-function token_example_token_info() {
- // Add two different token types. The first is the generic text format. The
- // second is the user's default text format, which is itself a 'format' token
- // type so it can be used directly.
- $info['types']['format'] = array(
- 'name' => t('Text formats'),
- 'description' => t('Tokens related to text formats.'),
- 'needs-data' => 'format',
- );
- $info['types']['default-format'] = array(
- 'name' => t('Default text format'),
- 'description' => t("Tokens related to the currently logged in user's default text format."),
- 'type' => 'format',
- );
-
- // Tokens for the text format token type.
- $info['tokens']['format']['id'] = array(
- 'name' => t('ID'),
- 'description' => t("The unique ID of the text format."),
- );
- $info['tokens']['format']['name'] = array(
- 'name' => t('Name'),
- 'description' => t("The name of the text format."),
- );
-
- // Node tokens.
- $info['tokens']['node']['body-format'] = array(
- 'name' => t('Body text format'),
- 'description' => t("The name of the text format used on the node's body field."),
- 'type' => 'format',
- );
-
- // Comment tokens.
- if (module_exists('comment')) {
- $info['tokens']['comment']['body-format'] = array(
- 'name' => t('Body text format'),
- 'description' => t("The name of the text format used on the comment's body field."),
- 'type' => 'format',
- );
- }
-
- return $info;
-}
-
-/**
- * Implements hook_tokens().
- */
-function token_example_tokens($type, $tokens, array $data = array(), array $options = array()) {
- $replacements = array();
- $sanitize = !empty($options['sanitize']);
-
- // Text format tokens.
- if ($type == 'format' && !empty($data['format'])) {
- $format = $data['format'];
-
- foreach ($tokens as $name => $original) {
- switch ($name) {
- case 'id':
- // Since {filter_format}.format is an integer and not user-entered
- // text, it does not need to ever be sanitized.
- $replacements[$original] = $format->format;
- break;
- case 'name':
- // Since the format name is user-entered text, santize when requested.
- $replacements[$original] = $sanitize ? filter_xss($format->name) : $format->name;
- break;
- }
- }
- }
-
- // Default format tokens.
- if ($type == 'default-format') {
- $default_id = filter_default_format();
- $default_format = filter_format_load($default_id);
- $replacements += token_generate('format', $tokens, array('format' => $default_format), $options);
- }
-
- // Node tokens.
- if ($type == 'node' && !empty($data['node'])) {
- $node = $data['node'];
-
- foreach ($tokens as $name => $original) {
- switch ($name) {
- case 'body-format':
- $format = filter_format_load($node->body[LANGUAGE_NONE][0]['format']);
- $replacements[$original] = $sanitize ? filter_xss($format->name) : $format->name;
- break;
- }
- }
-
- // Chained token relationships.
- if ($format_tokens = token_find_with_prefix($tokens, 'body-format')) {
- $body_format = filter_format_load($node->body[LANGUAGE_NONE][0]['format']);
- $replacements += token_generate('format', $format_tokens, array('format' => $body_format), $options);
- }
- }
-
- // Comment tokens.
- if ($type == 'comment' && !empty($data['comment'])) {
- $comment = $data['comment'];
-
- foreach ($tokens as $name => $original) {
- switch ($name) {
- case 'body-format':
- $format = filter_format_load($comment->comment_body[LANGUAGE_NONE][0]['format']);
- $replacements[$original] = $sanitize ? filter_xss($format->name) : $format->name;
- break;
- }
- }
-
- // Chained token relationships.
- if ($format_tokens = token_find_with_prefix($tokens, 'body-format')) {
- $body_format = filter_format_load($comment->comment_body[LANGUAGE_NONE][0]['format']);
- $replacements += token_generate('format', $format_tokens, array('format' => $body_format), $options);
- }
- }
-
- return $replacements;
-}
diff --git a/trigger_example/CHANGELOG.txt b/trigger_example/CHANGELOG.txt
deleted file mode 100644
index f01577f..0000000
--- a/trigger_example/CHANGELOG.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-
-#618578 by ilo, rfay: D7 trigger example module
diff --git a/trigger_example/trigger_example.info b/trigger_example/trigger_example.info
deleted file mode 100644
index b7ee8c3..0000000
--- a/trigger_example/trigger_example.info
+++ /dev/null
@@ -1,7 +0,0 @@
-
-name = Trigger example
-description = An example showing how a module can provide triggers that can have actions associated with them.
-package = Example modules
-core = 7.x
-dependencies[] = trigger
-files[] = trigger_example.test
diff --git a/trigger_example/trigger_example.module b/trigger_example/trigger_example.module
deleted file mode 100644
index cac508c..0000000
--- a/trigger_example/trigger_example.module
+++ /dev/null
@@ -1,312 +0,0 @@
-<?php
-
-/**
- * @file
- * Trigger definition example module.
- *
- * Triggers and actions are a pair of special-purpose functions allowing some
- * Drupal programming without using PHP. Using the
- * appropriate action in a specific event, a site administrator can
- * add new functionality. Examples are:
- * - Send an email after a node is published or edited.
- * - Display a message after a user has logged in.
- * - Display a message and send an email after a node has been deleted.
- *
- * A Trigger is a special function able to enqueue actions. The trigger module
- * provides the interface allowing us to associate certain actions with certain
- * triggers.
- *
- * Actions are functions intended to be run by triggers.
- *
- * A trigger should build the appropriate context for the action to be fired.
- * Actions are very often
- * grouped by functionality: examples are 'user', 'node', 'taxonomy'. When some
- * actions are grouped it is because they expect the same arguments. This way,
- * you can enqueue as many actions understanding the 'user' object as you want.
- *
- * Not all actions can be used in all triggers because they require different
- * contexts. But some actions
- * are generic enough to not require special objects in their
- * contexts, and so can be used on every available trigger. This 'group' type
- * is used by actions to be available for this trigger.
- *
- * What are good candidates to be triggers? Any function can be a trigger, as
- * long as it has the code to call the enqueued actions, but to make Drupal
- * more extensible, you will find hooks (from Drupal and contributed modules)
- * very good candidates. A trigger should build the arguments, ask for enqueued
- * actions and run them. You may define a function being a trigger, and run it
- * through a button in the front page, or you may prepare a trigger for a hook,
- * and everytime that hook is fired, your trigger will be.
- *
- * What are good candidates to be actions? any function is a possible action,
- * the only problem is finding a trigger able to run it.
- *
- * This module describes how to create triggers and actions for Drupal. In this
- * example we are providing two triggers:
- *
- * - A custom trigger, in its simplest form. We provide a page with a button.
- * This button does nothing at all, but when you click (and submit the empty
- * form), any actions you have configured will be executed.
- *
- * - A trigger which extends the capabilities of User triggers.
- * This creates a new event which fires the first time a user ever logs in.
- * In the module we will create it, and then provide a trigger for
- * the administrator to be able to enqueue actions. They will be executed
- * only the first time the user logs in the system.
- *
- * See:
- *
- * @link http://drupal.org/node/375833 Creating Triggers @endlink
- *
- * @link http://drupal.org/node/172152 Writing Actions @endlink
- *
- * @link http://drupal.org/node/199254 Triggers and Actions in Drupal 6 @endlink
- *
- * @see hook_trigger_info()
- * @see hook_trigger_info_alter()
- * Also see the @link action_example.module Action Example @endlink.
- */
-
-/**
- * Implements hook_trigger_info().
- *
- * We call hook_trigger_info when we are defining the triggers we provide.
- * Triggers are the events that make fire any number of assigned actions. In
- * this example, we are registering our three new triggers, providing the group
- * (system, user..), the callback 'hook' (only informative, does not require a
- * real hook) function and the label to be shown in the triggers interface.
- *
- * Example: In the group (a tab) 'system', for the 'mail' functionality, show:
- * An email is sent by Drupal.
- */
-function trigger_example_trigger_info() {
- return array(
- 'user' => array(
- 'user_first_time_login' => array(
- 'label' => t('After a user has logged in for the first time'),
- ),
- ),
- 'trigger_example' => array(
- 'triggersomething' => array(
- 'label' => t('After the triggersomething button is clicked'),
- ),
- ),
- );
-}
-
-/**
- * Triggers are used most of the time to do something when an event happens.
- * The most common type of event is a hook invocation,
- * but that is not the only possibility.
- *
- */
-
-/**
- * triggersomething trigger: Run actions associated with an arbitrary event.
- *
- * Here pressing a button is a trigger. We have defined a
- * custom function as a trigger (trigger_example_triggersomething).
- * It will ask for all actions attached to the 'triggersomething' event,
- * prepare a basic 'context' for them
- * and run all of them. This could have been implemented by a hook
- * implementation, but in this demonstration, it will just be called in a
- * form's submit.
- *
- * This function is executed during the submission of the example form defined
- * in this module.
- *
- * @param array $options arguments used to call the triggersomething function, if any.
- */
-function trigger_example_triggersomething($options = array()) {
- // Ask the trigger module for all actions enqueued for the 'triggersomething' trigger.
- $aids = trigger_get_assigned_actions('triggersomething');
- // prepare a basic context, indicating group and "hook", and call all the
- // actions with this context as arguments.
- $context = array(
- 'group' => 'trigger_example',
- 'hook' => 'triggersomething'
- );
- actions_do(array_keys($aids), (object) $options, $context);
-}
-
-
-/**
- * The next trigger is more complex, we are providing a trigger for a
- * new event: "user first time login". We need to create this event
- * first.
- */
-
-/**
- * Implements hook_user_login().
- *
- * User first login trigger: Run actions on user first login.
- *
- * The event "User first time login" does not exist, we should create it before
- * it can be used. We use hook_user_login to be informed when a user logs in and
- * try to find if the user has previously logged in before. If the user has not
- * accessed previously, we make a call to our trigger function.
- *
- */
-function trigger_example_user_login(&$edit, $account, $category = NULL) {
- // Verify user has never accessed the site: last access was creation date.
- if ($account->access == 0) {
- // Call the aproppriate trigger function
- _trigger_example_first_time_login('user_first_time_login', $edit, $account, $category);
- }
-}
-
-/**
- * Trigger function for "User first time login"
- *
- * This trigger is a user-type triggers, so is grouped with other user-type
- * triggers. It needs to provide all the context that user-type triggers
- * provide. For this example, we are going to copy the trigger.module
- * implementation for the 'User has logged in' event.
- *
- * This function will run all the actions assigned to the
- * 'user_first_time_login' trigger.
- *
- * For testing you can use an update query like this to reset a user to
- * "never logged in":
- * @code
- * update users set access=created where name='test1';
- * @endcode
- *
- * @param string $hook
- * the trigger identification.
- * @param array $edit
- * modifications for the account object (should be empty).
- * @param object $account
- * user object that has logged in.
- * @param string $category
- * category of the profile.
- *
- */
-function _trigger_example_first_time_login($hook, &$edit, $account, $category = NULL) {
- // Keep objects for reuse so that changes actions make to objects can persist.
- static $objects;
- // Get all assigned actions for the 'user_first_time_login' trigger.
- $aids = trigger_get_assigned_actions($hook);
- $context = array(
- 'group' => 'user',
- 'hook' => $hook,
- 'form_values' => &$edit,
- );
- // Instead of making a call to actions_do for all triggers, doing this loop
- // we provide the oportunity for actions to alter the account object, and
- // the next action should have this altered account object as argument.
- foreach ($aids as $aid => $info) {
- $type = $info['type'];
- if ($type != 'user') {
- if (!isset($objects[$type])) {
- $objects[$type] = _trigger_normalize_user_context($type, $account);
- }
- $context['user'] = $account;
- actions_do($aid, $objects[$type], $context);
- }
- else {
- actions_do($aid, $account, $context, $category);
- }
- }
-}
-
-/**
- * Helper functions for the module interface to test the triggersomething trigger.
- */
-
-/**
- * Implements hook_help().
- */
-function trigger_example_help($path, $arg) {
- switch ($path) {
- case 'examples/trigger_example':
- $explanation = t(
- 'Click the button on this page to call trigger_example_triggersomething()
- and fire the triggersomething event. First, you need to create an action
- and assign it to the "After the triggersomething button is clicked" trigger,
- or nothing will happen. Use the <a href="@actions-url">Actions settings page</a>
- and assign these actions to the triggersomething event on the
- <a href="@triggers-url">Triggers settings page</a>. <br/><br/>
- The other example is the "user never logged in before" example. For that one,
- assign an action to the "After a user has logged in for the first time" trigger
- and then log a user in.', array('@actions-url' => url('admin/config/system/actions'), '@triggers-url' => url('admin/structure/trigger/trigger_example')));
- return "<p>$explanation</p>";
- case 'admin/structure/trigger/system':
- return t('you can assign actions to run everytime an email is sent by Drupal');
- case 'admin/structure/trigger/trigger_example':
- $explanation = t(
- "A trigger is a system event. For the trigger example, it's just a button-press.
- To demonstrate the trigger example, choose to associate the 'display a message to the user'
- action with the 'after the triggersomething button is pressed' trigger.");
- return "<p>$explanation</p>";
- }
-}
-
-/**
- * Implements hook_menu().
- *
- * Provide a form that can be used to fire the module's triggers.
- */
-function trigger_example_menu() {
- $items['examples/trigger_example'] = array(
- 'title' => 'Trigger Example',
- 'description' => 'Provides a form to demonstrate the trigger example.',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array('trigger_example_form'),
- 'access callback' => TRUE,
- );
- return $items;
-}
-
-/**
- * Trigger example test form
- *
- * Provide a button to run the triggersomething event.
- */
-function trigger_example_form($form_state) {
- $form['triggersomething'] = array(
- '#type' => 'submit',
- '#value' => t('Run triggersomething event'),
- );
- return $form;
-}
-
-/**
- * Submit handler for the trigger_example_form.
- */
-function trigger_example_form_submit($form, $form_state) {
- // If the user clicked the button, then run the triggersomething trigger.
- if ($form_state['values']['op'] == t('Run triggersomething event')) {
- trigger_example_triggersomething();
- }
-}
-
-
-/**
- * Optional usage of hook_trigger_info_aler()
- *
- * This function is not required to write your own triggers, but it may be
- * useful when you want to alter existing triggers.
- *
- */
-
-/**
- * Implements hook_trigger_info_alter().
- *
- * We call hook_trigger_info_alter when we want to change an existing trigger.
- * As mentioned earlier, this hook is not required to create your own triggers,
- * and should only be used when you need to alter current existing triggers. In
- * this example implementation a little change is done to the existing trigger
- * provided by core: 'cron'
- *
- * @param array $triggers
- * Array of trigger information returned by hook_trigger_info()
- * implementations.
- *
- * @see hook_trigger_info()
- */
-function trigger_example_trigger_info_alter(&$triggers) {
- // Make a simple change to an existing core trigger, altering the label
- // "When cron runs" to our custom label "On cron execution"
- $triggers['system']['cron']['label'] = t('On cron execution');
-}
diff --git a/trigger_example/trigger_example.test b/trigger_example/trigger_example.test
deleted file mode 100644
index adac43b..0000000
--- a/trigger_example/trigger_example.test
+++ /dev/null
@@ -1,78 +0,0 @@
-<?php
-
-/**
- * @file
- * test file for trigger_example module.
- */
-
-/**
- * Default test case for the trigger_example module.
- */
-class TriggerExampleTestCase extends DrupalWebTestCase {
-
- public static function getInfo() {
- return array(
- 'name' => 'Trigger example',
- 'description' => 'Perform various tests on trigger_example module.' ,
- 'group' => 'Examples',
- );
- }
-
- function setUp() {
- parent::setUp('trigger', 'trigger_example');
- }
-
- /**
- * Test assigning a configurable action to the triggersomething event.
- */
- function testTriggersomethingEvent() {
- // Create an administrative user.
- $test_user = $this->drupalCreateUser(array('administer actions'));
- $this->drupalLogin($test_user);
-
- // Create a configurable action for display a message to the user
- $hash = drupal_hash_base64('system_message_action');
- $action_label = $this->randomName();
- $edit = array(
- 'actions_label' => $action_label,
- 'message' => $action_label,
- );
- $this->drupalPost('admin/config/system/actions/configure/' . $hash, $edit, t('Save'));
- $aid = db_query('SELECT aid FROM {actions} WHERE callback = :callback', array(':callback' => 'system_message_action'))->fetchField();
- // $aid is likely 3 but if we add more uses for the sequences table in
- // core it might break, so it is easier to get the value from the database.
- $edit = array('aid' => drupal_hash_base64($aid));
-
- // Note that this only works because there's just one item on the page.
- $this->drupalPost('admin/structure/trigger/trigger_example', $edit, t('Assign'));
-
- // Request triggersomething form and submit.
- $this->drupalPost('examples/trigger_example', array(), t('Run triggersomething event'));
- // Verify the message is shown to the user.
- $this->assertText($action_label, t('The triggersomething event executed the action.'));
- }
-
- function testUserLogin() {
- // Create an administrative user.
- $admin_user = $this->drupalCreateUser(array('administer actions'));
- $this->drupalLogin($admin_user);
-
- // Create a configurable action for display a message to the user
- $hash = drupal_hash_base64('system_message_action');
- $action_label = $this->randomName();
- $edit = array(
- 'actions_label' => $action_label,
- 'message' => $action_label,
- );
- $this->drupalPost('admin/config/system/actions/configure/' . $hash, $edit, t('Save'));
- $aid = db_query('SELECT aid FROM {actions} WHERE callback = :callback', array(':callback' => 'system_message_action'))->fetchField();
- $edit = array('aid' => drupal_hash_base64($aid));
-
- // Find the correct trigger
- $this->drupalPost('admin/structure/trigger/user', $edit, t('Assign'), array(), array(), 'trigger-user-first-time-login-assign-form');
-
- $test_user = $this->drupalCreateUser();
- $this->drupalLogin($test_user);
- $this->assertText($action_label);
- }
-}
diff --git a/vertical_tabs_example/vertical_tabs_example.info b/vertical_tabs_example/vertical_tabs_example.info
deleted file mode 100644
index a61ba45..0000000
--- a/vertical_tabs_example/vertical_tabs_example.info
+++ /dev/null
@@ -1,4 +0,0 @@
-name = Vertical tabs example
-description = Show how to use vertical tabs for enhancing user experience.
-core = 7.x
-package = Example modules
diff --git a/vertical_tabs_example/vertical_tabs_example.js b/vertical_tabs_example/vertical_tabs_example.js
deleted file mode 100644
index 9aea6e8..0000000
--- a/vertical_tabs_example/vertical_tabs_example.js
+++ /dev/null
@@ -1,24 +0,0 @@
-
-(function ($) {
-
-/**
- * Custom summary for the module vertical tab.
- */
-Drupal.behaviors.vertical_tabs_exampleFieldsetSummaries = {
- attach: function (context) {
- // Use the fieldset class to identify the vertical tab element
- $('fieldset#edit-vertical-tabs-example', context).drupalSetSummary(function (context) {
- // Depending on the checkbox status, the settings will be customized, so
- // update the summary with the custom setting textfield string or a use a
- // default string.
- if ($('#edit-vertical-tabs-example-enabled', context).attr('checked')) {
- return Drupal.checkPlain($('#edit-vertical-tabs-example-custom-setting', context).val());
- }
- else {
- return Drupal.t('Using default');
- }
- });
- }
-};
-
-})(jQuery);
diff --git a/vertical_tabs_example/vertical_tabs_example.module b/vertical_tabs_example/vertical_tabs_example.module
deleted file mode 100644
index fc12536..0000000
--- a/vertical_tabs_example/vertical_tabs_example.module
+++ /dev/null
@@ -1,89 +0,0 @@
-<?php
-
-/**
- * @file
- * Shows how to use the vertical tabs functionality provided by Drupal 7. This
- * example does not cover how to save / load custom setting, and only deals with
- * elements visibility.
- */
-
-/**
- * Implements hook_menu for a simple explanation page.
- */
-function vertical_tabs_example_menu() {
- $items['examples/vertical_tabs'] = array(
- 'title' => 'Vertical tabs example',
- 'description' => 'Shows how vertical tabs can best be supported by a custom module',
- 'page callback' => '_vertical_tabs_example_explanation',
- 'access callback' => TRUE,
- );
- return $items;
-}
-
-/**
- * Implement hook_form_alter().
- *
- * Adds custom fieldset to the node form, and attach ajax behaviour for vertical
- * panels to update the settings description.
- */
-function vertical_tabs_example_form_alter(&$form, $form_state, $form_id) {
- // Only include on node add/edit forms.
- if (!empty($form['#node_edit_form'])) {
-
- $form['vertical_tabs_example'] = array(
- '#type' => 'fieldset',
- '#title' => t('Example vertical tab'),
- '#collapsible' => TRUE,
- '#collapsed' => FALSE,
- // The #group value must match the name of the vertical tabs element.
- // In most cases, this is 'additional_settings'.
- '#group' => 'additional_settings',
- // Attach the javascript for vertical tabs.
- '#attached' => array(
- 'js' => array(
- 'vertical-tabs' => drupal_get_path('module', 'vertical_tabs_example') . '/vertical_tabs_example.js',
- ),
- ),
- '#tree' => TRUE,
- '#weight' => -2,
- );
-
- // This checkbox is used to show or hide the custom settings form using
- // javascript (altering states of a container defined later).
- $form['vertical_tabs_example']['enabled'] = array(
- '#type' => 'checkbox',
- '#title' => t('Use custom configuration'),
- '#default_value' => FALSE,
- );
-
- // This container will be used to store the whole form for our custom
- // settings. This way, showing/hidding the form using javascript is easier,
- // as only one element should be set visible.
- $form['vertical_tabs_example']['vertical_tabs_examplecontainer'] = array(
- '#type' => 'container',
- '#parents' => array('vertical_tabs_example'),
- '#states' => array(
- 'invisible' => array(
- // If the checkbox is not enabled, show the container.
- 'input[name="vertical_tabs_example[enabled]"]' => array('checked' => FALSE),
- ),
- ),
- );
-
- // The string of this textfield will be shown as summary in the vertical
- // tab.
- $form['vertical_tabs_example']['vertical_tabs_examplecontainer']['custom_setting'] = array(
- '#type' => 'textfield',
- '#title' => t('Use this custom setting'),
- '#default_value' => '',
- '#description' => t('This field is a demonstration about how to use Vertical Tabs in your forms. This setting will not be saved.'),
- );
- }
-}
-
-/**
- * Simple explanation page.
- */
-function _vertical_tabs_example_explanation() {
- return t("The Vertical Tabs Example shows how a custom module can best support vertical tabs. To see the effects of this module, look at the <a href='!node_add'>node/add</a> form", array('!node_add' => url('node/add')));
-}
diff --git a/xmlrpc_example/xmlrpc_example.info b/xmlrpc_example/xmlrpc_example.info
deleted file mode 100644
index 8e28812..0000000
--- a/xmlrpc_example/xmlrpc_example.info
+++ /dev/null
@@ -1,6 +0,0 @@
-
-name = XMLRPC example
-description = This is an example of how to implement client and server communications using XML-RPC.
-package = Example modules
-core = 7.x
-files[] = xmlrpc_example.test
diff --git a/xmlrpc_example/xmlrpc_example.module b/xmlrpc_example/xmlrpc_example.module
deleted file mode 100644
index 225624c..0000000
--- a/xmlrpc_example/xmlrpc_example.module
+++ /dev/null
@@ -1,647 +0,0 @@
-<?php
-
-/**
- * @file
- * This is an example of how to implement and XML-RPC server by registering
- * callbacks to specific methods and how to make xmlrpc calls using the built-in
- * xmlrpc() factory provided by Drupal.
- *
- * For experimentation you may be interested in the
- * @link http://drupal.org/project/xmlrpctester XML-RPC Tester module @endlink.
- *
- * Note that the @link http://drupal.org/project/services Services module @endlink
- * is another common way to do XML-RPC at this time.
- *
- * @see hook_xmlrpc()
- * @see xmlrpc()
- * @see xmlrpc_errno()
- * @see xmlrpc_error_msg()
- */
-
-// This is the common part of the module, implementing all the code required
-// for the client and the server part (most of this code is UI related). The
-// menu definition is the only part shared in this implementation.
-
-/**
- * Implements hook_menu().
- * Register all the demonstration forms.
- */
-function xmlrpc_example_menu() {
- $items['examples/xmlrpc'] = array(
- 'title' => 'XML-RPC Example',
- 'description' => 'Information about the XML-RPC example',
- 'page callback' => 'xmlrpc_example_info',
- 'access callback' => TRUE,
- );
- // This is the server configuration form menu entry. This form can be used to
- // configure the settings of the exposed services. An XML-RPC server does not
- // require a configuration form, and has been included here as an example.
- $items['examples/xmlrpc/server'] = array(
- 'title' => 'XML-RPC Server configuration',
- 'description' => 'Server configuration form',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array('xmlrpc_example_server_form'),
- 'access callback' => TRUE,
- 'weight' => 0,
- );
- // This is the client form menu entry. This form is used to allow user
- // interaction with the services, but again, user interface is not required
- // to create an XML-RPC client with Drupal.
- $items['examples/xmlrpc/client'] = array(
- 'title' => 'XML-RPC Client form',
- 'description' => 'Demonstrates client side XML-RPC calls with Drupal',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array('xmlrpc_example_client_form'),
- 'access callback' => TRUE,
- 'weight' => 1,
- );
- // This part is completely optional. It will allow the modification of services
- // defined by this or other modules. This configuration form is used to
- // enable the hook_xmlrpc_alter API and alter current existing services
- $items['examples/xmlrpc/alter'] = array(
- 'title' => 'XML-RPC Alterations',
- 'description' => 'Demonstrates how to alter defined XML-RPC services',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array('xmlrpc_example_alter_form'),
- 'access callback' => TRUE,
- 'weight' => 2,
- );
- return $items;
-}
-
-/**
- * A simple landing-page information function.
- */
-function xmlrpc_example_info() {
- $server = url($GLOBALS['base_url'] . '/xmlrpc.php', array('external' => TRUE));
-
- $options = array(
- 'system.listMethods' => array(),
- );
- // Make the xmlrpc request and process the results.
- $supported_methods = xmlrpc($server, $options);
- if ($supported_methods === FALSE) {
- drupal_set_message(t('Error return from xmlrpc(): Error: @errno, Message: @message', array('@errno' => xmlrpc_errno(), '@message' => xmlrpc_error_msg())));
- }
-
- return array(
- 'basic' => array('#markup' => t('This XML-RPC example presents code that shows <ul><li><a href="!server">XML-RPC server code</a></li><li><a href="!client">XML-RPC client code</a></li><li>and <a href="!alter">an example hook_xmlrpc_alter() call</a></li></ul>', array('!server' => url('examples/xmlrpc/server'), '!client' => url('examples/xmlrpc/client'), '!alter' => url('examples/xmlrpc/alter')))),
- 'method_array' => array('#markup' => theme('item_list', array('title' => t('These methods are supported by !server', array('!server' => $server)), 'items' => $supported_methods))),
- );
-}
-
-// This is the server part of the module, implementing a simple and little
-// server with just two simple services. The server is divided in two
-// different parts: the XML-RPC implementation (required) and a webform
-// interface (optional) to configure some settings in the server side.
-//
-// The XMLRPC server will define two different services:
-//
-// - subtract: perform the subtraction of two numbers. The minimum and maximum
-// values returned by the server can be configured in the server configuration
-// form.
-// - add: perform the addition of two numbers. The minimum and maximum values
-// returned by the server can be configured in the server configuration form.
-//
-// If the result value for the operation is over the maximum limit, a custom
-// error number 10001 is returned. This is an arbitrary number and could be any
-// number.
-//
-// If the result value for the operation is below the minimum limit, a custom
-// error number 10002 is returned. Again, this value is arbitrary and could be
-// any other number. Client applications must know the meaning of the error
-// numbers returned by the server.
-
-// The following code is the XML-RPC implementation of the server part. The first
-// step is to define the methods. This methods should be associated to callbacks
-// that will be defined later.
-
-/**
- * Implements hook_xmlrpc().
- *
- * Provides Drupal with an array to map XML-RPC callbacks to existing functions.
- * These functions may be defined in other modules. The example implementation
- * defines specific functions for the example services.
- *
- * Note: Drupal's built-in XML-RPC server already includes several methods by
- * default:
- *
- * Service dicovery methods:
- * - system.listMethods: return a list of the methods the server has, by name.
- * - system.methodSignature: return a description of the argument format a
- * - system.methodHelp: returns a text description of a particular method.
- * particular method expects.
- *
- * Other:
- * - system.multicall: perform several method calls in a single xmlrpc request.
- * - system.getCapabilities: determine if a given capability is supported.
- *
- * The methods defined by hook_xmlrpc() will be added to those provided by
- * default by Drupal's XML-RPC server.
- *
- * @see hook_xmlrpc()
- */
-function xmlrpc_example_xmlrpc() {
- $methods[] = array(
- // First argument is the method name.
- 'xmlrpc_example.add',
- // Callback to execute when this method is requested.
- '_xmlrpc_example_server_add',
- // An array defines the types of output and input values for this method.
- array(
- // The first value is the return type, an integer in this case.
- 'int',
- // First operand is an integer.
- 'int',
- // Second operatnd is an integer.
- 'int',
- ),
- // Include a little description that is shown when XML-RPC server is
- // requested for the implemented methods list.
- t('Returns the sum of the two arguments.') // Method description
- );
- // The subtract method is similar to the addition, only the method name,
- // callback and description are different.
- $methods[] = array(
- 'xmlrpc_example.subtract',
- '_xmlrpc_example_server_subtract',
- array('int', 'int', 'int'),
- t('Return difference of the two arguments.')
- );
-
- return $methods;
-}
-
-// The following code for the server is optional if the callbacks already exist.
-// A server may implement methods associated to callbacks like node_load(),
-// variable_get() or any other existing function (php functions as well).
-//
-// If the callbacks associated to the methods don't exist they must be
-// created. This implementation requires two specific callbacks:
-// - _xmlrpc_example_server_add()
-// - _xmlrpc_example_server_subtract()
-//
-
-/**
- * This is the callback for the xmlrpc_example.add method.
- *
- * Sum the two arguments and return value or an error if the result is out of the
- * configured limits.
- *
- * @param $num1
- * The first number to be summed.
- * @param $num2
- * The second number to be summed.
- * @return
- * The sum of the arguments, or error if it is not in server defined bounds.
- *
- * @see xmlrpc_error()
- */
-function _xmlrpc_example_server_add($num1, $num2) {
- $sum = $num1 + $num2;
- // If result is not within maximum and minimum limits, return corresponding error
- $max = variable_get('xmlrpc_example_server_max', 10);
- $min = variable_get('xmlrpc_example_server_min', 0);
- if ($sum > $max) {
- return xmlrpc_error(10001, t('Result is over the upper limit (@max) defined by the server.', array('@max' => $max)));
- }
- if ($sum < $min) {
- return xmlrpc_error(10002, t('Result is below the lower limit defined by the server (@min).', array('@min' => $min)));
- }
- // Otherwise return the result.
- return $sum;
-}
-
-/**
- * This is the callback for the xmlrpc_example.subtract xmlrpc method.
- *
- * Return the difference of the two arguments, or an error if the result is out of the
- * configured limits..
- *
- *
- * @param numeric $num1
- * @param numeric $num2
- * @return
- * The difference of the two arguments, or error if it is not in server defined bounds.
- *
- * @see xmlrpc_error()
- */
-function _xmlrpc_example_server_subtract($num1, $num2) {
- $diference = $num1 - $num2;
- $max = variable_get('xmlrpc_example_server_max', 10);
- $min = variable_get('xmlrpc_example_server_min', 0);
-
- // If result is not within maximum and minimum limits, return corresponding error
- if ($diference > $max) {
- return xmlrpc_error(10001, t('Result is above the upper limit (@max) defined by the server.', array('@max' => $max)));
- }
- if ($diference < $min) {
- return xmlrpc_error(10002, t('Result is below the lower limit (@min) defined by the server.', array('@min' => $min)));
- }
- // Otherwise return the result.
- return $diference;
-}
-
-// User interface for the XML-RPC Server part.
-// A server does not require an interface at all. In this implementation we
-// use a server configuration form to set the limits available for the addition
-// and subtraction operations.
-
-/**
- * Present a form to configure the service options. In this case the maximum
- * and minimum values for any of the operations (add or subtraction).
- */
-function xmlrpc_example_server_form() {
- $form = array();
- $form['explanation'] = array(
- '#markup' => '<div>' . t('This is the XML-RPC server configuration page.<br />Here you may define the maximum and minimum values for the addition or subtraction exposed services.<br />') . '</div>',
- );
- $form['xmlrpc_example_server_min'] = array(
- '#type' => 'textfield',
- '#title' => t('Enter the minimum value returned by the subtraction or addition methods'),
- '#description' => t('If the result of the operation is lower than this value, a custom XML-RPC error will be returned: 10002.'),
- '#default_value' => variable_get('xmlrpc_example_server_min', 0),
- '#size' => 5,
- '#required' => TRUE,
- );
- $form['xmlrpc_example_server_max'] = array(
- '#type' => 'textfield',
- '#title' => t('Enter the maximum value returned by sub or add methods'),
- '#description' => t('if the result of the operation is bigger than this value, a custom XML-RPC error will be returned: 10001.'),
- '#default_value' => variable_get('xmlrpc_example_server_max', 10),
- '#size' => 5,
- '#required' => TRUE,
- );
- $form['info'] = array(
- '#type' => 'markup',
- '#markup' => '<div>' . t('Use the <a href="!link">XML-RPC Client example form</a> to experiment', array('!link' => url('examples/xmlrpc/client'))),
- );
- if (variable_get('xmlrpc_example_alter_enabled', FALSE)) {
- $form['overridden'] = array(
- '#type' => 'markup',
- '#markup' => '<div><strong>' . t('Just a note of warning: The <a href="!link">alter form</a> has been used to disable the limits, so you may want to turn that off if you do not want it.', array('!link' => url('examples/xmlrpc/alter'))) . '</strong></div>',
- );
- }
- return system_settings_form($form);
-}
-
-
-// The server part of the module ends here.
-
-// This is the client part of the module. If defines a form with two input
-// fields to call xmlrpc_example.add or xmlrpc_example.subtract methods on this
-// host. Please note that having a user interface to query an XML-RPC service is
-// not required. A method can be requested to a server using the xmlrpc()
-// function directly. We have included an user interface to make the testing
-// easier.
-
-// The client user interface part of the module starts here.
-
-/**
- * Present a form to get two arguments, and make a call to an XML-RPC server
- * using these arguments as input, showing the result in a message.
- */
-function xmlrpc_example_client_form() {
- $form = array();
- $form['explanation'] = array(
- '#markup' => '<div>' . t('This example demonstrates how to make XML-RPC calls with Drupal. <br />The "Request methods" button makes a request to the server and asks for the available list of methods, as a service discovery request. <br/>The "Add integers" and "Subtract integers" use the xmlrpc() function to act as a client, calling the XML-RPC server defined in this same example for some defined methods.<br />An XML-RPC error will result if the result in the addition or subtraction requested is out of bounds defined by the server. These error numbers are defined by the server. <br />The "Add and Subtract" button performs a multicall operation on the XML-RPC server: several requests in a single XML-RPC call.<br />') . '</div>',
- );
- // We are going to call add and subtract methods, and they work with integer values.
- $form['num1'] = array(
- '#type' => 'textfield',
- '#title' => t('Enter an integer'),
- '#default_value' => 2,
- '#size' => 5,
- '#required' => TRUE,
- );
- $form['num2'] = array(
- '#type' => 'textfield',
- '#title' => t('Enter a second integer'),
- '#default_value' => 2,
- '#size' => 5,
- '#required' => TRUE,
- );
- // Include several buttons, each of them calling a different method.
- // This button submits a XML-RPC call to the system.listMethods method.
- $form['information'] = array(
- '#type' => 'submit',
- '#value' => t('Request methods'),
- '#submit' => array('xmlrpc_example_client_request_methods_submit'),
- );
- // This button submits a XML-RPC call to the xmlrpc_example.add method.
- $form['add'] = array(
- '#type' => 'submit',
- '#value' => t('Add the integers'),
- '#submit' => array('xmlrpc_example_client_add_submit'),
- );
- // This button submits a XML-RPC call to the xmlrpc_example.subtract method.
- $form['subtract'] = array(
- '#type' => 'submit',
- '#value' => t('Subtract the integers'),
- '#submit' => array('xmlrpc_example_client_subtract_submit'),
- );
- // This button submits a XML-RPC call to the system.multicall method.
- $form['add_subtract'] = array(
- '#type' => 'submit',
- '#value' => t('Add and Subtract'),
- '#submit' => array('xmlrpc_example_client_multicall_submit'),
- );
- if (variable_get('xmlrpc_example_alter_enabled', FALSE)) {
- $form['overridden'] = array(
- '#type' => 'markup',
- '#markup' => '<div><strong>' . t('Just a note of warning: The <a href="!link">alter form</a> has been used to disable the limits, so you may want to turn that off if you do not want it.', array('!link' => url('examples/xmlrpc/alter'))) . '</strong></div>',
- );
- }
- return $form;
-}
-
-/**
- * Submit: query the XML-RPC endpoint for the method system.listMethods
- * and report the result as a Drupal message. The result is a list of the
- * available methods in this XML-RPC server.
- *
- * Important note: Not all XML-RPC servers implement this method. Drupal's
- * built-in XML-RPC server implements this method by default.
- *
- * @param $form
- * @param $form_state
- *
- * @see xmlrpc()
- * @see xmlrpc_errno()
- * @see xmlrpc_error_msg()
- */
-function xmlrpc_example_client_request_methods_submit($form, &$form_state) {
- // First define the endpoint of the XML-RPC service, in this case this is our
- // own server.
- $server = url($GLOBALS['base_url'] . '/xmlrpc.php', array('external' => TRUE));
- // Then we should define the method to call. xmlrpc() requires that all the
- // information related to the called method be passed as an array in the form
- // of 'method_name' => arguments_array
- $options = array(
- 'system.listMethods' => array(),
- );
- // Make the xmlrpc request and process the results.
- $result = xmlrpc($server, $options);
- if ($result === FALSE) {
- drupal_set_message(
- t('Error return from xmlrpc(): Error: @errno, Message: @message',
- array('@errno' => xmlrpc_errno(), '@message' => xmlrpc_error_msg())),
- 'error'
- );
- }
- else {
- drupal_set_message(
- t('The XML-RPC server returned this response: <pre>@response</pre>',
- array('@response' => print_r($result, TRUE)))
- );
- }
-}
-
-/**
- * Submit: query the XML-RPC endpoint for the method xmlrpc_example.add
- * and report the result as a Drupal message.
- *
- * @param $form
- * @param $form_state
- *
- * @see xmlrpc()
- * @see xmlrpc_errno()
- * @see xmlrpc_error_msg()
- */
-function xmlrpc_example_client_add_submit($form, &$form_state) {
- // First define the endpoint of the XML-RPC service, in this case is our
- // own server.
- $server = url($GLOBALS['base_url'] . '/xmlrpc.php', array('external' => TRUE));
- // Then we should define the method to call. xmlrpc() requires that all the
- // information related to the called method is passed as an array in the form
- // of 'method_name' => arguments_array
- $options = array(
- 'xmlrpc_example.add' => array(
- (int) $form_state['values']['num1'],
- (int) $form_state['values']['num2'],
- ),
- );
- // Make the xmlrpc request and process the results.
- $result = xmlrpc($server, $options);
- if ($result === FALSE) {
- drupal_set_message(
- t('Error return from xmlrpc(): Error: @errno, Message: @message',
- array('@errno' => xmlrpc_errno(), '@message' => xmlrpc_error_msg())),
- 'error'
- );
- }
- else {
- drupal_set_message(
- t('The XML-RPC server returned this response: @response',
- array('@response' => print_r($result, TRUE)))
- );
- }
-}
-
-/**
- * Submit: query the XML-RPC endpoint for the method xmlrpc_example.subtract
- * and report the result as a Drupal message.
- *
- * @param $form
- * @param $form_state
- *
- * @see xmlrpc()
- * @see xmlrpc_errno()
- * @see xmlrpc_error_msg()
- * @see xmlrpc_example_client_add_submit()
- */
-function xmlrpc_example_client_subtract_submit($form, &$form_state) {
- $server = url($GLOBALS['base_url'] . '/xmlrpc.php', array('external' => TRUE));
- $options = array(
- 'xmlrpc_example.subtract' => array(
- (int) $form_state['values']['num1'],
- (int) $form_state['values']['num2'],
- ),
- );
- // Make the xmlrpc request and process the results.
- $result = xmlrpc($server, $options);
- if ($result === FALSE) {
- drupal_set_message(
- t('Error return from xmlrpc(): Error: @errno, Message: @message',
- array('@errno' => xmlrpc_errno(), '@message' => xmlrpc_error_msg())),
- 'error'
- );
- }
- else {
- drupal_set_message(
- t('The XML-RPC server returned this response: @response',
- array('@response' => print_r($result, TRUE)))
- );
- }
-}
-
-/**
- * Submit a multicall request: query the XML-RPC endpoint for the methods
- * xmlrpc_example.add and xmlrpc_example.subtract and report the result as a
- * Drupal message. Drupal's XML-RPC client builds the system.multicall request
- * automatically when there is more than one method to call.
- *
- * @param $form
- * @param $form_state
- *
- * @see xmlrpc()
- * @see xmlrpc_errno()
- * @see xmlrpc_error_msg()
- * @see xmlrpc_example_client_multicall_submit()
- */
-function xmlrpc_example_client_multicall_submit($form, &$form_state) {
- $server = url($GLOBALS['base_url'] . '/xmlrpc.php', array('external' => TRUE));
-
- /*
- * Drupal's built-in xmlrpc server supports the system.multicall method.
- *
- * To make a multicall request, the main invoked method should be the
- * function 'system.multicall', and the arguments to make this call must be
- * defined as an array of single method calls, being the array keys the
- * service methods to be called, and the array elements the method arguments.
- *
- * See the code below this comment as example.
- */
-
- // Build an array of several calls, Drupal's xmlrpc built-in support will
- // construct the correct system.multicall request for the server.
- $options = array(
- 'xmlrpc_example.add' => array(
- (int) $form_state['values']['num1'],
- (int) $form_state['values']['num2'],
- ),
- 'xmlrpc_example.subtract' => array(
- (int) $form_state['values']['num1'],
- (int) $form_state['values']['num2'],
- ),
- );
- // Make the xmlrpc request and process the results.
- $result = xmlrpc($server, $options);
-
- if ($result === FALSE) {
- drupal_set_message(
- t('Error return from xmlrpc(): Error: @errno, Message: @message',
- array('@errno' => xmlrpc_errno(), '@message' => xmlrpc_error_msg()))
- );
- }
- else {
- drupal_set_message(
- t('The XML-RPC server returned this response: <pre>@response</pre>',
- array('@response' => print_r($result, TRUE)))
- );
- }
-}
-
-// The client part of the module ends here.
-
-// The alteration part of the module starts here. hook_xmlrpc_alter() is
-// useful when you want to extend, limit or alter methods defined by other
-// modules. This part is not required to have an XML-RPC server or client
-// working, but is useful to understand what can we do using current xmlrpc
-// API provided by drupal.
-//
-// This code can be defined in other module to alter the methods exposed by
-// this xmlrpc demonstration server, or can be used to alter methods defined
-// by other modules implementing hook_xmlrpc()
-//
-// As with the rest of the example module, an user interface is not required to
-// make use of this hook. A configuration form is included to enable/disable
-// this functionality, but this part is optional if you want to implement
-// hook_xmlrpc_alter()
-
-
-// This is the XML-RPC code for the alteration part. It will check if an option
-// to enable the functionality is enabled and then alter it. We alter the
-// 'xmlrpc_example.add' and 'xmlrpc_example.subtract' methods, changing the
-// associated callback with custom functions. The modified methods (with
-// new callbacks associated) will perform the addition or subtraction of the
-// integer inputs, but will never check for limits nor return errors.
-
-/**
- * Implements hook_xmlrpc_alter().
- *
- * Check to see if xmlrpc_example.add and xmlrpc_example.subtract methods are
- * defined and replace their callbacks with custom code.
- *
- * @see hook_xmlrpc_alter()
- */
-function xmlrpc_example_xmlrpc_alter(&$methods) {
-
- // Only perform alterations if instructed to do so.
- if (!variable_get('xmlrpc_example_alter_enabled', 0)) {
- return;
- }
- // Loop all defined methods (other modules may have include additional methods)
- foreach ($methods as $index => $method) {
- // First element in the method array is the method name.
- if ($method[0] == 'xmlrpc_example.add') {
- // Replace current callback with custom callback (second argument of the array)
- $methods[$index][1] = '_xmlrpc_example_alter_add';
- }
- // Do the same for the substraction method.
- if ($method[0] == 'xmlrpc_example.subtract') {
- $methods[$index][1] = '_xmlrpc_example_alter_subtract';
- }
- }
-}
-
-// Now we define the custom callbacks replacing the original defined by the
-// altered methods: xmlrpc_example.add and _xmlrpc_example.subtract . These
-// new callbacks will not check if the result of the operation is within the
-// limits defined by the server and will always return the value of the operation.
-
-/**
- * Sum the two arguments without limit checking.
- *
- * This is the replacement callback for the xmlrpc_example.add xmlrpc method.
- *
- * @param $num1
- * @param $num2
- * @return
- * The sum of the arguments
- */
-function _xmlrpc_example_alter_add($num1, $num2) {
- return $num1 + $num2;
-}
-
-/**
- * Return the difference of the two arguments without limit checking.
- *
- * This is the replacement callback for the xmlrpc_example.subtract xmlrpc method.
- *
- * @param numeric $num1
- * @param numeric $num2
- * @return
- * The difference of the two arguments
- */
-function _xmlrpc_example_alter_subtract($num1, $num2) {
- return $num1 - $num2;
-}
-
-
-// Our implementation of hook_xmlrpc_alter will work only if a system variable
-// is set to true, and we need a configuration form to enable/disable this
-// 'feature'. This is the user interface to enable or disable the hook_xmlrpc_alter
-// operations.
-
-/**
- * Present a form to enable or disable the code implemented in hook_xmlrpc_alter.
- */
-function xmlrpc_example_alter_form() {
- $form = array();
- $form['explanation'] = array(
- '#markup' => '<div>' . t('This is a configuration form to enable the alteration of XML-RPC methods using hook_xmlrpc_alter.<br />hook_xmlrpc_alter() can be used to alter the current defined methods by other modules. In this case as demonstration, we will overide current add and subtraction methods with others not being limited. Remember that this hook is optional and is not required to create XMLRPC services.<br />') . '</div>',
- );
- $form['xmlrpc_example_alter_enabled'] = array(
- '#type' => 'checkbox',
- '#title' => t('Overide current xmlrpc_example.add and xmlrpc_example.subtraction methods'),
- '#description' => t('If this checkbox is enabled, the default methods will be replaced with custom methods that ignore the XML-RPC server maximum and minimum restrictions.'),
- '#default_value' => variable_get('xmlrpc_example_alter_enabled', 0),
- );
- $form['info'] = array(
- '#markup' => '<div>' . t('Use the <a href="!link">client submission form</a> to see the results of checking this checkbox', array('!link' => url('examples/xmlrpc/client'))) . '</div>',
- );
- return system_settings_form($form);
-}
-
-// The alteration part of the module ends here.
diff --git a/xmlrpc_example/xmlrpc_example.test b/xmlrpc_example/xmlrpc_example.test
deleted file mode 100644
index 6f278a0..0000000
--- a/xmlrpc_example/xmlrpc_example.test
+++ /dev/null
@@ -1,128 +0,0 @@
-<?php
-
-/**
- * @file
- * Test case for the XML-RPC example module.
- */
-class XmlrpcExampleTestCase extends DrupalWebTestCase {
- protected $xmlrpc_url;
-
- public static function getInfo() {
- return array(
- 'name' => 'XMLRPC example functionality',
- 'description' => 'Test xmlrpc service implementation.',
- 'group' => 'Examples',
- );
- }
-
- /**
- * Enable module.
- */
- function setUp() {
- parent::setUp('xmlrpc_example');
-
- // Init common variables.
- global $base_url;
- $this->xmlrpc_url = url($GLOBALS['base_url'] . '/xmlrpc.php', array('external' => TRUE));
- }
-
- /**
- * Perform several calls to the XML-RPC interface to test the services.
- */
- function testXmlrpcExampleBasic() {
- // Unit test functionality.
- $result = xmlrpc($this->xmlrpc_url, array('xmlrpc_example.add' => array(3, 4)));
- $this->assertEqual($result, 7, t('Successfully added 3+4 = 7'));
-
- $result = xmlrpc($this->xmlrpc_url, array('xmlrpc_example.subtract' => array(4, 3)));
- $this->assertEqual($result, 1, t('Successfully subtracted 4-3 = 1'));
-
- // Make a multicall request
- $options = array(
- 'xmlrpc_example.add' => array(5, 2),
- 'xmlrpc_example.subtract' => array(5, 2),
- );
- $expected = array(7, 3);
- $result = xmlrpc($this->xmlrpc_url, $options);
- $this->assertEqual($result, $expected, t('Successfully called multicall request'));
-
- // Verify default limits
- $result = xmlrpc($this->xmlrpc_url, array('xmlrpc_example.subtract' => array(3, 4)));
- $this->assertEqual(xmlrpc_errno(), 10002, t('Results below minimum return custom error: 10002'));
-
- $result = xmlrpc($this->xmlrpc_url, array('xmlrpc_example.add' => array(7, 4)));
- $this->assertEqual(xmlrpc_errno(), 10001, t('Results beyond maximum return custom error: 10001'));
- }
-
- /**
- * Perform several calls using XML-RPC web client.
- */
- function testXmlrpcExampleClient() {
- // Now test the UI.
- // Add the integers.
- $edit = array('num1' => 3, 'num2' => 5);
- $this->drupalPost('examples/xmlrpc/client', $edit, t('Add the integers'));
- $this->assertText(t('The XML-RPC server returned this response: @num', array('@num' => 8)));
- // Subtract the integers.
- $edit = array('num1' => 8, 'num2' => 3);
- $result = $this->drupalPost('examples/xmlrpc/client', $edit, t('Subtract the integers'));
- $this->assertText(t('The XML-RPC server returned this response: @num', array('@num' => 5)));
- // Request available methods.
- $this->drupalPost('examples/xmlrpc/client', $edit, t('Request methods'));
- $this->assertText('xmlrpc_example.add', t('The XML-RPC Add method was found.'));
- $this->assertText('xmlrpc_example.subtract', t('The XML-RPC Subtract method was found.'));
- // Before testing multicall, verify that method exists
- $this->assertText('system.multicall', t('The XML-RPC Multicall method was found.'));
- // Verify multicall request
- $edit = array('num1' => 5, 'num2' => 2);
- $this->drupalPost('examples/xmlrpc/client', $edit, t('Add and Subtract'));
- $this->assertText('[0] =&gt; 7', t('The XML-RPC server returned the addition result.'));
- $this->assertText('[1] =&gt; 3', t('The XML-RPC server returned the subtraction result.'));
- }
-
- /**
- * Perform several XML-RPC requests with different server settings.
- */
- function testXmlrpcExampleServer() {
- // Set different minimum and maxmimum valuesI.
- $options = array('xmlrpc_example_server_min' => 3, 'xmlrpc_example_server_max' => 7);
- $this->drupalPost('examples/xmlrpc/server', $options, t('Save configuration'));
- $this->assertText(t('The configuration options have been saved'), t('Results limited to >= 3 and <= 7'));
-
- $edit = array('num1' => 8, 'num2' => 3);
- $this->drupalPost('examples/xmlrpc/client', $edit, t('Subtract the integers'));
- $this->assertText(t('The XML-RPC server returned this response: @num', array('@num' => 5)));
-
- $result = xmlrpc($this->xmlrpc_url, array('xmlrpc_example.add' => array(3, 4)));
- $this->assertEqual($result, 7, t('Successfully added 3+4 = 7'));
-
- $result = xmlrpc($this->xmlrpc_url, array('xmlrpc_example.subtract' => array(4, 3)));
- $this->assertEqual(xmlrpc_errno(), 10002, t('subtracting 4-3 = 1 returns custom error: 10002'));
-
- $result = xmlrpc($this->xmlrpc_url, array('xmlrpc_example.add' => array(7, 4)));
- $this->assertEqual(xmlrpc_errno(), 10001, t('Adding 7 + 4 = 11 returns custom error: 10001'));
- }
-
- /**
- * Perform several XML-RPC requests altering the server behaviour with
- * hook_xmlrpc_alter API
- */
- function testXmlrpcExampleAlter() {
- // Enable XML-RPC service altering functionality.
- $options = array('xmlrpc_example_alter_enabled' => 1);
- $this->drupalPost('examples/xmlrpc/alter', $options, t('Save configuration'));
- $this->assertText(t('The configuration options have been saved'), t('Results are not limited due to methods alteration'));
-
- // After altering the functionality, the add and subtract methods have no
- // limits and should not return any error.
- $edit = array('num1' => 80, 'num2' => 3);
- $this->drupalPost('examples/xmlrpc/client', $edit, t('Subtract the integers'));
- $this->assertText(t('The XML-RPC server returned this response: @num', array('@num' => 77)));
-
- $result = xmlrpc($this->xmlrpc_url, array('xmlrpc_example.add' => array(30, 4)));
- $this->assertEqual($result, 34, t('Successfully added 30+4 = 34'));
-
- $result = xmlrpc($this->xmlrpc_url, array('xmlrpc_example.subtract' => array(4, 30)));
- $this->assertEqual($result, -26, t('Successfully substracted 4-30 = -26'));
- }
-}