bb_register_plugin_activation_hook函数——bbPress的BUG

标签: , , ,

最近开发 bbPress 插件,要在插件启用时初始化一些设置(比如新建数据表)。在 WordPress 中实现该功能的函数是 register_activation_hook ,bbPress 中对应的函数是 bb_register_plugin_activation_hook

但是 bbPress 连官方文档都没有,只好参考 WordPress 的文档,WordPress 上面的示例代码是这样的:

register_activation_hook( __FILE__, 'myplugin_activate' );

This will call the myplugin_activate() function on activation of the plugin. This is a more reliable method than using the activate_pluginname action.

于是依样画葫芦,在 bbPress 插件中加上:

bb_register_plugin_activation_hook( __FILE__, 'myplugin_activate');
function myplugin_activate() {
    file_put_contents( 'myplugin_activate.txt', 'Hello world' );
}

然而却没有得到想要的结果,myplugin_activate 函数根本没有被调用。像 bbPress 这样非主流的论坛系统,使用的人寥寥无几,更不用说对它有一定研究的了。碰到问题连个求助的人都没有,真是郁闷。曾经对 bbPress 情有独钟的 yexingzhe 也表示无能为力。

bbPress 官网上有一个叫 bbPress Attachments 的插件也用了这个 hook 来初始化数据表。我测试了一下,依然无效,数据库根本就没有任何变化。

仔细看了一下代码,发现它是这样调用的:

bb_register_plugin_activation_hook(str_replace('-init.php','.php',__FILE__),'bb_attachments_install');

而在这行代码的前面有一行注释:

// $file=str_replace(array(str_replace('/','\\',BB_PLUGIN_DIR),str_replace('/','\\',BB_CORE_PLUGIN_DIR),'-init.php'),array('user#','core#','.php'),__FILE__);

我灵机一动,把注释去掉,再修改一下函数调用,变成:

$file=str_replace(array(str_replace('/','\\',BB_PLUGIN_DIR),str_replace('/','\\',BB_CORE_PLUGIN_DIR),'-init.php'),array('user#','core#','.php'),__FILE__);
bb_register_plugin_activation_hook($file,'bb_attachments_install');

重新启用插件,数据库中多了个 bb_attachments 表!函数居然被正确调用了!

看来有必要跟踪一下 bb_register_plugin_activation_hook 函数,原函数是这样的:

function bb_register_plugin_activation_hook( $file, $function )
{
    $file = bb_plugin_basename( $file );
    add_action( 'bb_activate_plugin_' . $file, $function );
}

修改一下以便于跟踪:

function bb_register_plugin_activation_hook( $file, $function )
{
    $org = $file;
    $file = bb_plugin_basename( $file );
    file_put_contents( 'bb_register_plugin_activation_hook.txt', "$org\n$file");
    add_action( 'bb_activate_plugin_' . $file, $function );
}

分别启用修改前后的 bbPress Attachments 插件,分别输出:

C:\inetpub\wwwroot\bbs\my-plugins\bb-attachments\bb-attachments.php
user#bb-attachments/bb-attachments.php
user#bb-attachments\bb-attachments.php
user#bb-attachments\bb-attachments.php

可以看出,当 $file 变量为 user#bb-attachments/bb-attachments.php 的时候函数无法被正确调用,而为 user#bb-attachments\bb-attachments.php 的时候却可以被正确调用,BUG。

我没有在 Linux 下测试,也许只是 Windows 下才有这个问题吧,但是就算只在 Windows 出问题,也仍然是BUG。

bbPress 太不成熟了!浪费了我大半天的时间!

赞赏

微信赞赏支付宝赞赏

随机文章:

  1. 用VBS播放音乐
  2. ass2srt.vbs(ass/ssa批量转换srt)
  3. 爱因斯坦带来的悖论
  4. 利用 WindowsInstaller.Installer 对象计算文件 MD5 hash 值
  5. Chrome用 –proxy-server 设置代理服务器

留下回复