放牧代码和思想
专注自然语言处理、机器学习算法
    博主不用扣扣,公事请博客留言,私事请微博私信。开源项目一律GitHub见,发错地方恕不回复,谢谢。

Chapter 06: Working with Users用户操作代码

这一章感觉挺好懂的,越来越具体了。

先是legalagree模块,给我的账户和注册页面添加一个是否同意的选项:

legalagree.info

name = Legal Agreement
description = Displays a dubious legal agreement during user registration.
package = Pro Drupal Development
core = 7.x
files[] = legalagree.module

legalagree.module

<?php
 
/**
* @file
* Support for dubious legal agreement during user registration.
*/
/**
 * Implements hook_form_alter().
 */
function legalagree_form_alter (&$form, &$form_state, $form_id)
{
    // check to see if the form is the user registration or user profile form
    // if not then return and don’t do anything
    // 检查表单是否是用户注册或者用户信息,如果不是的话直接返回
    if (! ($form_id == 'user_register_form' || $form_id == 'user_profile_form'))
    {
        return;
    }
    // add a new validate function to the user form to handle the legal
    // agreement
    // 添加一个新的激活选项
    $form['#validate'][] = 'legalagree_user_form_validate';
    // add a field set to wrap the legal agreement
    // 限制同意协议
    $form['account']['legal_agreement'] = array(
            '#type' => 'fieldset',
            '#title' => t('Legal agreement')
    );
    // add the legal agreement radio buttons
    // 添加单选框
    $form['account']['legal_agreement']['decision'] = array(
            '#type' => 'radios',
            '#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')
                    )),
            '#default_value' => 0,
            '#options' => array(
                    t('I disagree'),
                    t('I agree')
            )
    );
}
 
/**
 * Form validation handler for the current password on the user_account_form().
 * 表单有效性检查
 * @see user_account_form()
 *
 */
function legalagree_user_form_validate ($form, &$form_state)
{
    global $user;
    // Did user agree?
    // 用户是否同意
    if ($form_state['input']['decision'] != 1)
    {
        form_set_error('decision', 
                t(
                        'You must agree to the Legal Agreement before registration
can be completed.'));
    }
    else
    {
        watchdog('user', 
                t('User %user agreed to legal terms', 
                        array(
                                '%user' => $user->name
                        )));
    }
}

最后的效果:

然后是记录用户登录次数的loginhistory模块:

loginhistory.info

name = Login History
description = Keeps track of user logins.
package = Pro Drupal Development
core = 7.x
files[] = loginhistory.install
files[] = loginhistory.module

loginhistory.install

<?php
 
/**
* Implements hook_schema().
* 往数据库里加表
*/
function loginhistory_schema ()
{
    $schema['login_history'] = array(
            'description' => 'Stores information about user logins.',
            'fields' => array(
                    'uid' => array(
                            'type' => 'int',
                            'unsigned' => TRUE,
                            'not null' => TRUE,
                            'description' => 'The {user}.uid of the user logging in.'
                    ),
                    'login' => array(
                            'type' => 'int',
                            'unsigned' => TRUE,
                            'not null' => TRUE,
                            'description' => 'Unix timestamp denoting time of login.'
                    )
            ),
            'indexes' => array( // login_history表的索引,凭此排序 
                    'uid' => array(
                            'uid'
                    )
            )
    );
    return $schema;
}


loginhistory.module

<?php
 
/**
* @file
* Keeps track of user logins.
* 记录用户登录次数
*/
/**
 * Implements hook_user_login
 */
function loginhistory_user_login (&$edit, $account)
{
    // insert a new record each time the user logs in
    // 每次登录往表单里添加一个记录,其实这个非常没有效率,应该直接记录次数而不是Unix时间戳
    $nid = db_insert('login_history')->fields(
            array(
                    'uid' => $account->uid,
                    'login' => $account->login
            ))->execute();
}
 
/**
 * Implements hook_user_view_alter
 * 我的账户——查看的时候被调用
 */
function loginhistory_user_view_alter (&$build)
{
    global $user;
    // count the number of logins for the user
    // 计算登录次数,为啥没效率了的原因,不过时间戳可以换算成北京时间倒也有用
    $login_count = db_query(
            "SELECT count(*) FROM {login_history} where uid = :uid", 
            array(
                    ':uid' => $user->uid
            ))->fetchField();                           // fetchField从数据库获得一个单个的值,
                                                        // 其实就是依靠索引统计行数
                                                        // update the user page 把数字显示在我的账户——查看上
                                                        // by adding the number
                                                        // of logins to the page
    $build['summary']['login_history'] = array(
            '#type' => 'user_profile_item',
            '#title' => t('Number of logins'),
            '#markup' => $login_count,
            '#weight' => 10
    );
}

最后是自定义的外部登录验证

authdave.info

name = Authenticate Daves
description = External authentication for all Daves.
package = Pro Drupal Development
core = 7.x
files[] = authdave.module

authdave.module

<?php
 
/**
* Implements hook_form_alter().
* We replace the local login validation handler with our own.
* 替代原来的登录校验函数
*/
function authdave_form_alter (&$form, &$form_state, $form_id)
{
    // In this simple example we authenticate on username to see whether starts
    // with dave
    // 在这个简单的例子里直接用用户名是否含有dave来判断用户是否能够登录
    if ($form_id == 'user_login' || $form_id == 'user_login_block')
    {
        $form['#validate'][] = 'authdave_user_form_validate';
    }
}
 
/**
 * Custom form validation function
 * 用户接管的登录函数
 */
function authdave_user_form_validate ($form, &$form_state)
{
    if (! authdave_authenticate($form_state))
    {
        form_set_error('name', t('Unrecognized username.'));
    }
}
 
/**
 * Custom user authentication function
 * 对用户名的检验
 */
function authdave_authenticate ($form_state)
{                                             // get the first four characters取出开头四个字母
                                              // of the users name
    $username = $form_state['input']['name'];
    $testname = drupal_substr(drupal_strtolower($username), 0, 4);
    // check to see if the person is a dave
    // 检查是不是dave
    if ($testname == "dave")
    {
        // if it’s a dave then use the external_login_register function
        // to either log the person in or create a new account if that
        // person doesn’t exist as a Drupal user
        // 如果是的话就让它登录或者给它注册一个authdave的用户
        user_external_login_register($username, 'authdave');
        return TRUE;
    }
    else
    {
        return FALSE;
    }
}
 
/**
 * Implements hook_user_insert().
 * 钩子,实现给新加入的用户在user表里增加邮箱地址,当然mycompany_email_lookup还没有实现,所以
 * 暂时注释掉
 */
// function authdave_user_insert (&$edit, &$account, $category = NULL)
// {
//     global $authdave_authenticated;
//     if ($authdave_authenticated)
//     {
//         $email = mycompany_email_lookup($account->name);
//         // Set e-mail address in the users table for this user.
//         db_update('users')->fields(array(
//                 'mail' => $email
//         ))
//             ->condition('uid', $account->uid)
//             ->execute();
//     }
// }

在数据库中的样子:

知识共享许可协议 知识共享署名-非商业性使用-相同方式共享码农场 » Chapter 06: Working with Users用户操作代码

分享到:更多 ()

评论 欢迎留言

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

我的开源项目

HanLP自然语言处理包基于DoubleArrayTrie的Aho Corasick自动机