MyBB Community Forums

Full Version: My First Plugin
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Well as the subject says, im creating my first mybb plugin.

Its a very simple plugin that im needing in my forum but i haven't found anything like this in all mybb directory.

The script gets a random menssage from the DB to be shown in the forum index.

But Im having some problems when i activate the plugin, and i have no idea why let me show you some images:

This happens in the ACP:
http://img222.imageshack.us/img222/5913/capturayuf.jpg

If im logged in, the plugin have no warnings in the index forum and works perfectly:
http://img651.imageshack.us/img651/2291/captura2u.jpg

But if i try to log out:
http://img222.imageshack.us/img222/253/captura3b.jpg

And this when im a guess:
http://img12.imageshack.us/img12/8135/captura4n.jpg

I dont know how to fix this problem, this is my source:
<?php
/**
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by 
 * the Free Software Foundation, either version 3 of the License, 
 * or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, 
 * but WITHOUT ANY WARRANTY; without even the implied warranty of 
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
 * See the GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License 
 * along with this program.  
 * If not, see <http://www.gnu.org/licenses/>.
 *
 * MADE BY NILORD - LAST UPDATE 03/04/11
 */
 
if(!defined("IN_MYBB"))
{
    die("Direct initialization of this file is not allowed.<br /><br />Please make sure IN_MYBB is defined.");
}

$plugins->add_hook('global_start', 'sabias_que_mostrar_mensaje');

/*Información sobre el plugin - Plugin Information*/
function sabias_que_info()
{
    return array(
                "name" => "¿Sabías qué?",
                "description" => "Muestra un mensaje aleatorio a los usuarios registrados.",
                "website" => "",
                "author" => "NiLord",
                "authorsite" => "http://www.sheikav.com",
                "version" => "1.0",
                "guid" => "",
                "compatibility" => "16*"
            );
}

/*Función de activación del plugin - Activation Function*/
function sabias_que_activate()
{
    global $db;
	
	// Crear el grupo de opciones - Crete the option group
    $query = $db->simple_select("settinggroups", "COUNT(*) as rows");
    $rows = $db->fetch_field($query, "rows");

    $new_groupconfig = array(
        'name' => 'sabias_que', 
        'title' => '¿Sabías qué?',
        'description' => 'Opciones para la configuración del sabías qué.',
        'disporder' => $rows+1,
        'isdefault' => 0
    );
    
    $group['gid'] = $db->insert_query("settinggroups", $new_groupconfig);
	
	// Crear las opciones - Create options
    $new_config = array();
        
    $new_config[] = array(
        'name' => 'sabias_que_active',
        'title' => 'Activar plugin',
        'description' => 'Selecciona si deseas activar el plugin.',
        'optionscode' => 'yesno',
        'value' => '1',
        'disporder' => 10,
        'gid' => $group['gid']
    );
	
	foreach($new_config as $array => $content)
    {
        $db->insert_query("settings", $content);
    }
      
    //Creo la tabla en la base de datos - Create the data base
    $db->write_query("CREATE TABLE `".TABLE_PREFIX."mensajes` (
    `ID` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
    `mensaje` LONGTEXT NOT NULL
     ) ENGINE = MYISAM");
	 
	//Necesitamos al menos 1 mensaje para que el plugin funcione, por ello lo añadimos 
        //We need at least 1 menssage in the db for show the plugin
	 $db->write_query("INSERT INTO `".TABLE_PREFIX."mensajes` (`ID` ,`mensaje`)
VALUES (NULL , 'Necesitamos al menos 1 mensaje para que el plugin sea mostrado, aquí está')");
        
	// Editar el template index - Edit the index template
    require MYBB_ROOT."/inc/adminfunctions_templates.php";
    find_replace_templatesets('index', '#{\$header}#', '{$header}<!-- Sabíasque -->{$mostrar}<!-- /Sabíasque -->');
    
	// rebuild settings...
	rebuild_settings();
	
    return TRUE;

}

/*Funcion que desactiva el plugin - Desactivate Function*/
 function sabias_que_deactivate()
{
    global $db;
    
    // Borrar el grupo de opciones - Delete the Option Group
    $query = $db->simple_select("settinggroups", "gid", "name = \"sabias_que\"");
    $rows = $db->fetch_field($query, "gid");

    $db->delete_query("settinggroups", "gid = {$rows}");
    
    // Borrar las opciones - Delete the Options
    $db->delete_query("settings", "gid = {$rows}");
	
	//borro la tabla en la base de datos - Drop the table in the DB 
	$db->write_query("DROP TABLE ".TABLE_PREFIX."mensajes");

	// Borrar la Edición del template / index - Delete the template/index edition
    require MYBB_ROOT."/inc/adminfunctions_templates.php";
    find_replace_templatesets('index', '#' . preg_quote('<!-- Sabíasque -->{$mostrar}<!-- /Sabíasque -->') . '#', '');
	
   // rebuild settings...
   rebuild_settings();
    
    return TRUE;
}

/*Muestra el mensaje - show mensage*/
function sabias_que_mostrar_mensaje()
{
    global $mybb, $mostrar, $db;
    
    // Si el plugin se encuentra desactivado o es un invitado, no hacemos nada 
    //If the plugin is desactivated or the user is a guess, it doesnt do anything
    if($mybb->settings['sabias_que_active'] == '0' || $mybb->user['uid'] == 0)
    {
        return FALSE;
    }
    
    // Comprobamos si el usuario esta logueado - We check if the user is not a guess
    else if($mybb->user['uid'] != 0)
    {
        // Si el uid del usuario es indistinto a cero, el usuario se encuentra identificado 
        //If the uid is not 0, the user is loged
		$query = $db->simple_select("mensajes ORDER BY RAND() LIMIT 0,1");
        while($q = $db->fetch_array($query))
	    {
		$trow = alt_trow();		
        $mostrar=$q['mensaje'];
		break;
        }
    }
}

?>

Hope you can help me =( i really want to finish this one.
- Check if there isn't any whitespace before "<?php".
- Change your text editor if you are using windows notepad (Notepad++, for example).
Couple of things;

- You are using global_start hook but are using index template to show {$mostrar}
- Your template find and replace is not finding/replacing the code correctly, it should be like this;
find_replace_templatesets("index", "#".preg_quote('{$header}')."#i", '{\$header}{\$mostrar}');
- Your setting group is not inserting to the db.
Hi, thanks for your help I'm using the tutorial you did, im another spanish speaker.

By the way, I'm using Notepad++ (windows) to create the plugin and i have no whitespaces in my code but I realized what my error is, and i'll share the solution.

To use "´" and "ñ" and other spanish special characters i changed the codification to UFT-8. I changed back to ANSI and i have no error.

But now i have another problem and I would like to ask another question. Whats the best way to create a form inside ACP to add or delete information from my DB. With a module in ACP? Because i think the setting groups cant change DB ​​values, can they? Do I need to use a module?

@yaldaram Im inserting my setting group using this code
    foreach($new_config as $array => $content)
    {
        $db->insert_query("settings", $content);
    }
You could just use the settings to store the information (they are stored in the db). For your application it might be easiest to just separate each string by a new line in a textarea setting, then explode the values and pick one at random.
Well guys I've finished my plugin by my own. I used a module because i dont know if I'll add more features in the future.

Here it is: http://www.mediafire.com/?7m9p7ys7b16ba70

This is the plugin in the index: http://img573.imageshack.us/img573/3633/capturagl.jpg

You can change the table tittle, in that way you can post as tittle "curiosities, ads, announcements" etc : http://img98.imageshack.us/img98/4051/captura2x.jpg

Here you can edit / deleate all message that are being shown: http://img146.imageshack.us/img146/4955/captura3v.jpg

And here is the form to add new menssage to the DB, you can use HTML but no more that 250 characters: http://img194.imageshack.us/img194/492/captura4r.jpg

Next update it'll be avaiable in english. What do i need to do to add my plugin to the mybb directory? I hope you guys help me with this last thing.

EDIT: Never mind i did it!