[For 1.8] [ Tutorial ] Plugin MyBB Base & Plugin MySql
#1
Bug 
[ Tutorial ] Plugin MyBB Base & Plugin MySql

( Examples for creating Plugins in MyBB Board Software Forum)


Introduction

I want to do a tutorial of what has been learned through Support MyBB Forums. 
Personally, I think  are the  Best Software Forums Today, at this present time.  
years ago, started the study of forums with with [PhpBB2, PhpBB3, Smf... etc] for about 7 years, but in the end, what me discouragement of PhpBB forums, for example, are so many bugs and holes in security. why not turned to study the PhpBB Forum, were many years updating and studying the board software that ultimately, seeing so many security bugs , opt to leave it to the side..

MyBB has returned to give that passion by learning about the development, how useful that is a  software MyBB of an Simple software, Robust Interpreted Applications and with good Security processes, personally declare myself a fan of the software  MyBB 1.8.x

Currently being developed the  MyBB2.0 Base, such as features, is a completely new software, developed with Laravel 5.1, to be at the forefront of the smarthpones, wireless devices and tables, more information about the new features and implementation of development: Version MyBB2.0 Feat.
Evolution promises much, and is commanding by Euan T, for more information: Links soporte MyBB2.0 .

My personal opinion about this change in all the code is that it must be good, many people use mobile devices, Tablets, Smarthpones... Etc;
Personally, my economy is very limited, not use Tablets, or mobile phones to navigate, not Smarthpones, not Facebook.
Only use the computer to Study, Manage my projects and forums. and I like study the version mybb 1.8.x

When Relace MyBB2.0 I start it to study also in the areas of InstallationUpdate, Merge System, & the new Theme, To learning the basic of that version! 


[ 1 ] Plugin Base


A plugin has certain features, so the software MyBB interpret and work properly are simple commands and easy to create.

The Plugins allow a better development of applications for the Forums Software, better security & administration  MyBB, allowing in a modular way: activate, install, disable, uninstall; 
To develop the Plugin must have a knowledge in Php & MySql, and logically know the basis of MyBB.

For this example, we will use the Basic, developing a Plugin to activate it and use it in MyBB 1.8.x.

It is required to create a file with the following information:

Name: Name of the Plugin
Description: Description of what makes the Plugin
Website: Webside of Plugin (Optional)
Author: Name of the author of the Plugin
Authorsite: The URL of the author of the Plugin website (Optional)
Version: Number of the Version of the plugin
Guid:  ID Por the MyBB
Codename: Unique codename for the plugin in the Mods section.

Thise Base must be created in a file .PHP and upload it to the folder of MyBBinc/plugins/NombreDelPlugin.Php 

[Image: mybb-plugin-1.jpg]

<?php
// Disallow direct access to this file for security reasons
if(!defined("IN_MYBB"))
{
    die("Direct initialization of this file is not allowed.");
}

function myplugin_info()
{
    return array(
        "name"          => "",
        "description"   => "",
        "website"       => "",
        "author"        => "",
        "authorsite"    => "",
        "version"       => "1.0",
        "guid"          => "",
        "codename"      => "",
        "compatibility" => "*"
    );
}

function myplugin_install()
{

}

function myplugin_is_installed()
{

}

function myplugin_uninstall()
{

}

function myplugin_activate()
{

}

function myplugin_deactivate()
{

}



[ 1.1 ] Plugin Hooks


In MyBB 1.8.x a Hook is the functionality provided by the software so that the created Plugins can reuse the code, called Hook, allowing a better functionality of the Software to be able to use code Hook, codigo Hook, here a list of the Hooks..

For more information about how to use the Hooks in the plugins, in thise  URL with more support


[ 1.2 ] Plugin Creating New Page, example


Let's create a Simple Plugin in MyBB 1.8.x will work with separate files, to study them in a better way: 
  • A File .Php with  Content the  Plugin Base and the information of its development. 
  • A File .Php will be at the Root of MyBB, where we will schedule functions of the plugin. 
  • A File Template to customize our Plugin MyBB.

Recently create this Plugin, XML Database League, bring it as an example:


[ Plugin Base ]
This file goes in the Plugins Folder of MyBB



MyBB: inc/plugins/xmleague.php .

<?php

//Disallow direct Initialization for extra security.

if(!defined("IN_MYBB"))
{
    die("You Cannot Access This File Directly. Please Make Sure IN_MYBB Is Defined.");
}

// Hooks
$plugins->add_hook('global_start', 'xmleague_global_start');

// Information
function xmleague_info()
{
return array(
        "name"  => "XML Database League",
        "description"=> "Database Leagues Standing Development in XML ",
        "website"        => "http://mybb.pinostudio1.com/",
        "author"        => "DiegoPino",
        "authorsite"    => "http://diegopino.blogspot.com",
        "version"        => "1.2",
        "guid"             => "",
        "compatibility" => "18*"
    );
}

 
?>



[ Archivo .Php ]
This file name, xml-database-league.php  goes in the Root de MyBB, this file is that contains the programmed functions of the Plugin with your development.


MyBB: Root/xmleague.php .

<?php
define("IN_MYBB", 1);
define('THIS_SCRIPT', 'xml-database-league.php');

require_once "./global.php";

// Only required because we're using misc_help for our page wrapper
$lang->load("misc");

// Add a breadcrumb
add_breadcrumb('XML Database League | ', "xml-database-league.php");

eval("\$page = \"".$templates->get("xmleague_template")."\";");
output_page($page);

?>



[ Template ]
This code, Template name, can create with the Software  MyBB, The Templates serves us to give you a better detailed presentation to the plugin with its functions and development, depending on like this created the plug-in.


Add Template » xmleague_template



[ Note ] As you can see, the creation of a Plugin consists of very simple basic steps, so that the Software can accept plug-in.
If you want the code complete, in this example, you can download it from the official MyBB website: Mods & Plugins
Example OnLine: Plugin XML Database




[ 1.3 ] Plugin Statistics Query from MyBB, Example

This example will show how to make Queries of the Board Software MyBB 1.8.x, we already know how to build the Plugin Base, Now I want to enter in the Querys from DataBase MyBB, Recently Create this Plugin Signature GD, I will update it soon, programmed with GD Library to create images and at the same time to study the Statistics & Queries

As already have studied the way of the Plugin Base, we will concentrate on the code of the Plugin to Generate Queries Basic Board Software MyBB and learn a little bit more , for example

  • Forum Name ( Name of the Forum )
  • Username ( Registered user )
  • Members ( Number Total of registered users)
  • Post ( Number Total of Post in the Board Software )
  • Threads ( Number Total of Threads on Board Software )
  • Avatar ( Custom user image )
<?php
// Codigo para leer Stats de MyBB

"Forum: ". $mybb->settings['homename']);
"Username: ". $mybb->users['username']);
"Members: ". my_number_format($stats['numusers']));
"Posts: ". my_number_format($stats['numposts']));
"Threads: ". my_number_format($stats['numthreads']));
"Avatar: ". $mybb->users['avatar']);

?>


Desire to show the result of the Plugin with the queries, to explain the code more simple..

[Image: mybb-plugin-2.jpg]

In this case as we wish to Querys from Board Software MyBB, we must read the Stats, at the same time Querys Users, with the following code,

 example$stats = $cache->read ("stats");
<?php
//hacemos el codigo MyBB

define("IN_MYBB", 1);
define("KILL_GLOBALS", 1);
define("NO_ONLINE", 1);
require "../inc/init.php";
$stats = $cache->read("stats");  
$query = mysqli_query("SELECT * FROM mybb_users");

?>


The Queris its easy interpretation, must now develop the code to generate our Imagen With libreria GD, this Query steps are simple, because the code it will generate an image that Query the DataBase from Statistics of MyBB 1.8.x , for this example, see the code reference:


 $mybb->settings['homename']);

<?php
//hacemos el codigo MyBB
//Inicio de la Creacion de Imagen
Header ("Content-type: image/png");

//Definimos el Template a Usar, el Default
$imagen = imagecreatefrompng('template_01.png');

// Dimensiones de la imagen: 450px x 150px
$w_im = imagesx($imagen);
$h_im = imagesy($imagen);

// Codigo para leer Stats de MyBB

imagefttext($imagen, 14, 0, 10, 50, $clr_amarillo, $ttf_black , "Forum: ". $mybb->settings['homename']);
imagefttext($imagen, 14, 0, 10, 70, $clr_azul, $ttf_black , "Username: ". $mybb->users['username']);
imagefttext($imagen, 14, 0, 10, 90, $clr_rojo, $ttf_black, "Members: ". my_number_format($stats['numusers']));
imagefttext($imagen, 14, 0, 10, 110, $clr_blanco, $ttf_black, "Posts: ". my_number_format($stats['numposts']));
imagefttext($imagen, 14, 0, 10, 130, $clr_blanco, $ttf_black, "Threads: ". my_number_format($stats['numthreads']));
imagefttext($imagen, 14, 0, 310, 90, $clr_azul, $ttf_black , "Avatar: ". $mybb->users['avatar']);
//Relleno de amarillo para el avatar	
imagefilledrectangle($imagen, 310, 90, 4000, 4000, imagecolorallocatealpha($imagen, 1, 10, 255, 75));

// Grosor para la imagen
$grosor = 7;

?>


[ Note ] In this example, note that queries the database, are easy to interpret, note that, as we are generating an image, , The template MyBB  are calling from the Root, signaturegd.php The templates are not complicated you can create as we saw in the video above , From the Panel Admin, you can also create the template from the Plugin Base, or as in this example, from a separate file, hosted at the MyBB Root. 
Here the code, see$template



<?php
// Inicio de MyBB Plugin
define("IN_MYBB", 1);
define('THIS_SCRIPT', 'signaturegd.php');

// Only required because we're using misc_help for our page wrapper
require_once "./global.php";

$lang->load("misc");

// Add a breadcrumb
add_breadcrumb('Signature GD', "signaturegd.php");

$template = '
<html>
<head>
<title>Signature GD</title>
{$headerinclude}
</head>
<body>
{$header}

<p>Click on the <b>Image Template</b> GD Signature, Template Select Example:</p>

 <form action="signaturegd.php" method="GET">
     <input type="image" src="gdsignature/template_01.png" alt="Submit" width="400" height="133"><br>
 </form>

<p><b>Signature GD</b> Library: Dynamic Creation of Images Graphics Draw with Stats Forum software MyBB </p>

<object data="gdsignature/gd.php" type="image/png" height="134" width="400" form="gd_signature" name="Signature GD"></object>

<p><i>for the next version</i> 
    <ul>
          <li>Add <b>Template Select</b> files</li>
          <li>Add <b>Avatar</b> User</li>
        <li>Performance Resize Images Signature GD to: <b>400 x 133 | 350 x 117 | 300 x 100</b>  </li>
        <li>Performance with more user queries Stats MyBB</li>
        <li>Performance for <b>Users Select</b> Type of <b>Queris Display</b> in Signature GD</li>
        <li>Save image file Signatures of users, File in Folder Root GdSignature</li>
        <li>URL Performance for Signature Users, can use  friendly URL .Png  </li>
             <li>More Suggest are welcome...</li>
        <li>Enjoy!</li>
    </ul>
</p>
<p><b> Signature GD </b> con Template, Example Code</p>
<p>{$gd_signature}</p>
<p><b> Resize Image: </b> for the Next Version,  </p>
<iframe src="gdsignature/gd.php">
{$footer}
</body>
</html>

';

$template = str_replace("\'", "'", addslashes($template));
eval("\$signaturegd=\"".$template."\";");
output_page($signaturegd);

?>


If you want the code complete, in this example, you can download it from the official MyBB website: Mods & Plugins

Example OnLine: Plugin Signature GD



[ 1.4 ] Plugin With MySql, Example


In this example, I want to create a table in MySql, to manage it from the Panel of administration of the Board Software MyBB 1.8.x, the steps for creating the plugin , depend of how you want to develop it, you can create, for example:  

The template From the Panel of  Administration, From a File, Use a  Hook, varies so much depending on the type of plugin development. 

In this case, we are going to create something simple, to explain. 
As always, the tutorials, the development with Soccer Game, for this example, want to create a Plugin which can control from the Panel of Administration MyBB 1.8.x,:
  • Adminin Teams. 
  • Team Name
  • Logo Team (Image).
  • City. 
  • Fans Club.
MySql 

CREATE TABLE ClubTeams (
 Id (20),
 Nombre varchar (40),
 Imagen ),

 Description );

+--------------+
| ClubTeams |
+--------------+
| Id              |
| Name         |
| Image        |
| Description |
+-------------+

CREATE TABLE ClubFans (
 Id (),
 User Id (),
 Team 
);

+--------------+
| ClubFans    |
+--------------+
| Id              |
| User Id       |
| Team         |
+-------------+

Are going to focus on the creation of the table, for this example, you must create from the Plugin Base, where you can enter the code to MySql, in the Plugin Base also must write code to uninstall the MySql table.

This would be the code: example:
$db->write_query("CREATE TABLE IF NOT EXISTS "[/color][color=#336633].TABLE_PREFIX.[/color][color=#444444]"[/color][color=#cc3333]clubteams[/color][color=#444444]

PHP Code:
<?php
// Instalacion ClubsTeams
function clubsteams_install()
{
    global $db;

// Creamos Base de Datos MySql
    
    $db->write_query("CREATE TABLE IF NOT EXISTS `".TABLE_PREFIX."clubteams` (
      `id` int(10) unsigned NOT NULL auto_increment,
      `name` varchar(240) NOT NULL,
      `image` text,
      `des` text,
      PRIMARY KEY  (`id`)
    ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=2 ;
                     ");

    $db->write_query("CREATE TABLE IF NOT EXISTS `".TABLE_PREFIX."clubfans` (
      `id` int(10) unsigned NOT NULL auto_increment,
      `uid` int(10) default NULL,
      `team` int(10) default NULL,
      PRIMARY KEY  (`id`)
    ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=2 ;
                     "); ?>

As you can see, all this code goes in the Plugin Base, you must implement the programming for the uninstallation of the tables. example:
PHP Code:
<?php 
function clubsteams_uninstall()
{
    global $db;
    
    $db->write_query("DROP TABLE ".TABLE_PREFIX."clubteams");
    $db->write_query("DROP TABLE ".TABLE_PREFIX."clubfans"); ?>


With this file .Php, the Plugin Base, also can create the Templates for the plugin.
the previous examples, we have seen how you can create from the MyBB's Administration Panel or from a File, in this case, we are going to implement from the Plugin Base. 
this would be the code, example:

PHP Code:
<?php
// Templante que Muestra la info para MyBB     
    $temp = array(
        "sid"        => "NULL",
        "title"        => "club_team",
        "template"    => $db->escape_string('
            <TABLE BORDER=0 CELLPADDING=10>
                <TR>
                        <TH ROWSPAN=10 ALIGN=LEFT ><img src="{$team_image}" WIDTH=160 HEIGHT=160 alt="Imagen del Team"><br>{$team_name} <br> {$team_des} <br>Fans Total:<br> $members_num</TH>
                        <TD BGCOLOR="#99CCFF">Clubs Fans</TD> 
                    </TR>
                <TR>
                        <TD>{$members_bit}</TD> 
                    </TR>
    
                </TABLE>                    
        <br />'),
        "sid"        => "-1",
        "version"    => "1.0",
        "status"    => "0",
        "dateline"    => time(),
    );
    
    $db->insert_query("templates", $temp);

// Template MyBB  para Club_User
    
    $temp = array(
        "sid"        => "NULL",
        "title"        => "club_user",
        "template"    => $db->escape_string('<tr><td class="trow1"><a href="member.php?action=profile&uid={$members_uid}">{$user_name}</a></td><td class="trow1">{$members_pos}</td></tr>'),
        "sid"        => "-1",
        "version"    => "1.0",
        "status"    => "0",
        "dateline"    => time(),
    );
    
    $db->insert_query("templates", $temp); [/code]


[color=#444444][size=medium][font=Verdana]in the file, also you must include code to uninstall the [b]Templates and the MySql tables[/b], Code example: [/font][/size][/color]

[color=#333333][b]PHP Code:[/b][/color]
[code]<?php
function clubsteams_uninstall()
{
    global $db;
    
    $db->write_query("DROP TABLE ".TABLE_PREFIX."clubteams");
    $db->write_query("DROP TABLE ".TABLE_PREFIX."clubfans");

// Borramos query de forum software al desinstalar
    
    $db->delete_query("templates","title ='club_index'");
    $db->delete_query("templates","title ='club_team'");
    $db->delete_query("templates","title ='club_team_none'");
    $db->delete_query("templates","title ='club_user'");
    $db->delete_query("templates","title ='club_user_none'");
    
    rebuild_settings();    
}
?>


MyBB's Administration Panel, this example would be well!
[Image: mybb-acp.jpg]

Now, the  File that has been programmed The functions of the Plugin and its development should go in the Root or folder Admin:

MyBB: Admin/Modules/Clubs . 

Code Example:

PHP Code:
<?php

if(!defined("IN_MYBB"))
{
    die("Direct initialization of this file is not allowed.<br /><br />Please make sure IN_MYBB is defined.");
}

//MyBB Panel Admin, Add Team
$page->add_breadcrumb_item("Create Team", "index.php?module=clubs/addteam");

if($mybb->input['save']=="save")
{
    if(empty($mybb->input['name']) || empty($mybb->input['des']))
    {
        flash_message("One of the required fields was not correctly filled in", 'error');
        
        $title = $mybb->input['name'];
        $image = $mybb->input['image'];
        $des = $mybb->input['des'];
    }
    else
    {
        flash_message("Your team has been created", 'success');
        
        $insert_array = array(
                    "name"            => addslashes($mybb->input['name']),
                    "image"            => addslashes($mybb->input['image']),
                    "des"                => $db->escape_string($mybb->input['des']),
                    
                );
                
        $db->insert_query("clubteams", $insert_array);
    }
}

//MyBB Panel Admin, Add Team start the page
$page->output_header("Create Team");

$form = new Form("index.php?module=clubs/addteam", "post", "", 1);

$form_container = new FormContainer("Create Team");
echo $form->generate_hidden_field("save", "save", array('id' => "save"))."\n";

$form_container->output_row("Name", "The teams name", $form->generate_text_box('name', $name, array('id' => 'name')), 'name');
$form_container->output_row("Image", "The image URL that will appear on the clubs page", $form->generate_text_box('image', $image, array('id' => 'image')), 'image');
$form_container->output_row("Description City", "City of the team", $form->generate_text_box('des', $des, array('id' => 'des')), 'des');

// close the form container
$form_container->end();

// create the save button
$buttons[] = $form->generate_submit_button("Save");

// wrap up the form
$form->output_submit_wrapper($buttons);
$form->end();

// end the page
$page->output_footer();

?>



If you want the code complete, in this example, you can download it from the Post: Plugin Development

Example OnLine: ClubsTeams.php


This Tutorial will be updated, with more examples for creating Plugins, in coming days! 

comments and feedbacks are welcome




Referencias:
Reply
#2
This has to be one helpful thread.
Thanks so much for helping everyone. Toungue
Reply
#3
Very good read. Read this through my iPhone - seems like I can reference this thread in future.
Plugin Count: I lost count.
Public Plugins are available here.
Official GitHub.
Please do not PM me for support unless asked to.
Reply
#4
yup, really cool tutorial for starters Smile.
Owner of ForumAnime.PT
Reply
#5
I wonder why so less members appreciated for such an nice article , this should be a stickie Smile

thanks for such nice short basic TUT & thanks .m. for linking this to me
Reply
#6
Thanks in Advance for:  Your FeedBack and Comments are Welcome!  
It is good to know, the basic guide can help for community!

we will continue to step [ 1.5 ] Simple Example, Panel Admin

**************************************

[ 1.5 ]  Admin Table from the Admin Panel. Example 2


In this example, I want to create a table MySql, To Manage from the Administration Panel from Board Software MyBB 1.8.x, Steps to create the plugin, depends on how you want to develop the plugin, for example: 
The template  from the Administration Panel, from a file, or used a Hook, so their development varies greatly depending on the type of plugin. 

For this example, let's create something simple to explain. 
Display a table in which you can control from Administration Panel, content and format: MyBooks
  • Admin Books. 
  • BookName.
  • BookFormat
  • Illustracion.
  • Review. 
  • Link or web.
The construction of the plugin requires reading of the above steps: 
[ 1 ] Plugin Base,  Now we will concentrate on the manipulation of information from Administration Panel, in which we can edit and update information to display on page plugin. 

This would be the table to manage from the admin panel

MySql 

CREATE TABLE MyBooks (
 Bid (20),
 Name (40),

 Author(40), 
 BookFormat (40) 
 Imagen (40),
 LinkDescarga (80 );

+--------------+
| MyBooks     |
+--------------+
| Bid             |
| Name
| Author        |
| BookFormat |
| Image        |
| LinkDescarga |
+-------------+


see part of the code:


/admin/config/MyBooks.phph
<?php

// Book editing view control panel admin.

elseif($mybb->input['action'] == "edit_book") {
 
 $mybooks->check_id($mybb->input['bid'], "books");
 $book = $db->fetch_array($db->simple_select("mybooks_books", "*", "`bid` = {$mybb->input['bid']}"));
 $country_url = $mybooks->country_url($mybb->input['bid'], "acp");
 
 $form = new Form("index.php?module=config-mybooks&amp;action=update_book&amp;bid={$mybb->input['bid']}", "post", "edit", 1);
 $form_container = new FormContainer($lang->mybooks_edit_book);
 $form_container->output_row($lang->mybooks_name." <em>*</em>", "", $form->generate_text_box("name", $book['name'], array('id' => "name")), "name");
 $form_container->output_row($lang->mybooks_bookformat, $lang->mybooks_bookformat_description, $form->generate_text_box("bookformat", $book['bookformat'], array('id' => "bookformat")), "bookformat");
 $form_container->output_row($lang->mybooks_author, "", $form->generate_text_box("author", $book['author'], array('id' => "author")), "author");
 $form_container->output_row($lang->mybooks_new_country, $lang->mybooks_new_country_description, $form->generate_file_upload_box("country", array('id' => "country")), "country");
 

 if($country_url) {
 $country = "<img src=\"{$country_url}\" alt=\"country\" style=\"max-width: 100px; max-height: 100px; margin: 0px;\" />";
 $form_container->output_row($lang->mybooks_current_country, "", $country."<br />".$form->generate_check_box("delete_country", "yes", $lang->delete, array('id' => "delete_country")), "delete_country");
 }
 

 
 $form_container->output_row($lang->mybooks_review, "", $form->generate_text_box("review", $book['review'], array('id' => "review")), "review");
 $form_container->output_row($lang->mybooks_website, "", $form->generate_text_box("website", $book['website'], array('id' => "website")), "website");
 
 $form_container->end();
 $buttons[] = $form->generate_submit_button($lang->mybooks_save);
 $form->output_submit_wrapper($buttons);
 $form->end();
 
}



We seek information table MySql:

$mybooks->check_id($mybb->input['bid'], "books");
$book = $db->fetch_array($db->simple_select("mybooks_books", "*", "[/color][color=#cc3333]bid[/color][color=#444444] = {$mybb->input['bid']}"));


Now Check, We started using language that will help us build the table, to show and to manage tables; textbox .

$form_container = new FormContainer
$form_container -> output_row
$form -> generate_text_box
$lang -> mybooks_name  
$form -> generate_file_upload_box

Please, Check the image and the different $form_container 

[Image: mybooks-manager-panel.png]



As can be seen, the language is easy to interpret, plus easy handling to manage from the admin panel, it is important to say, in that step,  it must study the above guidelines to interpret the steps in this part.
  
It is a basic guide!


In the next Update of the tutorial, hope can explain the development to display the information online Page, with templates.  
[Image: mybook-manager1.png]


hope to continue studying and contributing to the community!
Thanks in advance for your FeedBack! 


PD: Next Update: step [ 1.6 ]
Reply
#7
Very awesome tutorial. I will be reflecting on this a lot here soon. Smile
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)