posts - 431,  comments - 344,  trackbacks - 0
          1.Introduction to hook_user()

          Implementing hook_user() gives your modules a chance to react to the different operations performed on a user account, and to modify the $user object. Let’s examine the function signature:

          function hook_user($op, &$edit, &$user, $category = NULL)

          The $op parameter is used to describe the current operation being performed on the user account and can have many different values:

          • after_update: Called after the $user object has been saved to the database.

          • categories: Returns an array of categories that appear as Drupal menu local tasks when the user edits the user account. See profile_user() in profile.module for an implementation.

          • delete: A user has just been deleted from the database. This is an opportunity for the module to remove information related to the user from the database.

          • form: Inject an additional form field element into the user edit form being displayed.

          • insert: The new user account is about to be created and inserted into the database.

          • login: The user has successfully logged in.

          • logout: The user just logged out and his or her session has been destroyed.

          • load: The user account was successfully loaded. The module may add additional information into the $user object.

          • register: The user account registration form is about to be displayed. The module may add additional form elements to the form.

          • submit: The user edit form has been submitted. Modify the account information before it is sent to user_save().

          • update: The existing user account is about to be saved to the database.

          • validate: The user account has been modified. The module should validate its custom

          data and raise any necessary errors.

          • view: The user’s account information is being displayed. The module should return

          its custom additions to the display as an array. The view operation ultimately calls

          theme_user_profile to format the user profile page. More details on this shortly.

          The $edit parameter is an array of the form values submitted when a user account is being created or updated. Notice that it’s passed by reference, so any changes you make will actually change the form values.

          The $user object is also passed by reference, so any changes you make will actually change the $user information.

          The $category parameter is the active user account category being edited.

          Caution Don’t confuse the $user parameter within hook_user() with the global $user object. The $user parameter is the user object for the account currently being manipulated. The global $user object is the user currently logged in.

          2.The User Registration Process

          Add a legalagree.module

          <?php

          function legalagree_user($op, &$edit, &$user, $category = NULL) {

                 switch ($op) {

                        // User is registering

                        case 'register':

                               //Add a fieldset containing radio buttons to the user registration form

                               $fields['legal_agreement'] = array(

                                      '#type' => 'fieldset',

                                      '#title' => t('Legal Agreement')

                               );

                               $fields['legal_agreement']['decision'] = array(

                                      '#type' => 'radios',

                                      '#options' => array(t('I disagree'), t('I agree')),

                                      '#default_value' => 0,

                                      '#description' => t('By registering at %site-name, you agree that

                                      at any time, we (or our surly, brutish henchmen) may enter your place of

                                      residence and smash your belongings with a ball-peen hammer.',

                                      array('%site-name' => variable_get('site_name', 'drupal')))

                               );

                               return $fields;

                        case 'validate':

                               // Make sure the user selected radio button 1 ('I agree').

                               // the validate op is reused when a user updates information on

                               // The 'my account' page, so we use isset() to test whether we are

                               // on the registration page where the decision field is present.

                               if (isset($edit['decision']) && $edit['decision'] != '1') {

                                      form_set_error('decision', t('You must agree to the legal agreement before

                                      registration can be completed.'));

                               }

                               return;

                        case 'insert':

                               // Record information for future lawsuit.

                               watchdog('user', t('User %user agreed to legal terms', array('%user' => $user->name)));

                               return;

                 }

          }

          3.Adding Data to the $user Object

          Loginhistory.module

          <?php

          function loginhistory_user($op, &$edit, &$account, $category = NULL) {

                 switch($op) {

                        case 'login':

                               // Record timestamp in database

                               db_query("INSERT INTO {login_history} (uid, timestamp) values (%d, %d)", $account->uid, $account->login);

                               break;

                        case 'load':

                               // Add the number of times user has logged in.

                               $account->loginhistory_count = db_result(db_query("SELECT COUNT(timestamp) as count FROM {login_history} WHERE uid = %d", $account->uid));

                               break;

                        case 'view':

                               // Add a field displaying number of logins.

                               $items['login_history'] = array(

                                      'title' => t('Number of logins'),

                                      'value' => $account->loginhistory_count,

                                      'class' => 'member'

                               );

                               return array(t('History')=>$items);

                 }

          }

          Loginhistory.install

          <?php

          function loginhistory_install() {

                 switch ($GLOBALS['db_type']) {

                        case 'mysql':

                        case 'mysqli':

                               db_query("CREATE TABLE {login_history} (

                                      uid int NOT NULL default '0',

                                      timestamp int NOT NULL default '0',

                                      KEY (uid)

                               )/*!40100 DEFAULT CHARACTER SET UTF8 */");

                               break;

                        case 'pgsql':

                               db_query("CREATE TABLE {login_history} (

                                      uid int_unsigned default '0',

                                      timestamp int_unsigned NOT NULL default '0',

                                      KEY (uid)

                               )");

                               break;

                 }

          }

          function loginhistory_uninstall() {

                 db_query("DROP TABLE {login_history}");

          }

          4.Simple External Authentication

          Let’s implement a very simple external authentication module that might be used inside a company where simple usernames are used. Suppose your company only hires people named Dave, and usernames are assigned based on first and last names. This module authenticates anyone whose username begins with the string dave, so the users davebrown, davesmith, and davejones will all successfully log in.

          <?php

          /**

          * Implementation of hook_auth()

          */

          function authdave_auth($username, $pass, $server) {

                 // Does username begin with 'dave'?

                 if (substr(drupal_strtolower($username), 0, 4 ) == 'dave') {

                        // Make a global variable to note that we did the authentication.

                        global $authdave_authenticated;

                        $authdave_authenticated = TRUE;

                        return TRUE;

                 }

                 else {

                        return FALSE;

                 }

          }

          If a row in the users table does not exist for this user, one will be created. However, no e-mail address has been provided at login like it was for Drupal’s default local user registration, so a module this simple is not a real solution if your site relies on sending e-mail to users. You’ll want to set the mail column of the users table so you will have an e-mail address associated with the user. To do this, you can have your module respond to the insert operation of the user hook, which is fired whenever a new user is inserted:

          /**

          * Implementation of hook_user()

          */

          function authdave_user($op, &$edit, &$account, $category = NULL) {

                 switch($op) {

                        case 'insert':

                               // New user was just added; if we did authentication,

                               // look up email address of user in a legacy database.

                               global $authdave_authenticated;

                               if ($authdave_authenticated) {

                                      $email = mycompany_email_lookup($account->name);

                                      // Set email address in the user table for this user.

                                      db_query("UPDATE {users} SET mail = '%s' WHERE uid = %d", $email,

                                      $account->uid);

                               }

                               break;

                 }

          }

          posted on 2007-12-03 14:32 周銳 閱讀(266) 評論(0)  編輯  收藏 所屬分類: PHP
          主站蜘蛛池模板: 台山市| 平安县| 莱西市| 祁阳县| 宣化县| 金沙县| 建德市| 五河县| 宝坻区| 永康市| 成都市| 吕梁市| 罗平县| 和硕县| 锦州市| 绥江县| 墨竹工卡县| 许昌市| 罗平县| 衡山县| 汉源县| 巴塘县| 郸城县| 巫山县| 湖南省| 柘城县| 通榆县| 山丹县| 姚安县| 临安市| 昌黎县| 金川县| 上思县| 浮山县| 蒙山县| 涿鹿县| 嘉禾县| 巴马| 磐安县| 汕头市| 湾仔区|