<?php
// Disallow direct access to this file for security reasons
if(!defined("IN_MYBB")) {
    die("Direct initialization of this file is not allowed.<br /><br />Please make sure IN_MYBB is defined.");
}
// Hooks
$plugins->add_hook('global_start', 'links_toplink_lang');
$plugins->add_hook("admin_load", "links_admin");
$plugins->add_hook("admin_config_menu", "links_admin_nav");
$plugins->add_hook("admin_config_action_handler", "links_action_handler");
global $templates;
/* INSTALL/DEINSTALL Functions */
/* --------------------------- */
function links_info() {
    global $lang;
    
    $lang->load("forum_links", false, true);
    
    return array(
        "name"          => "Links",
        "description"   => $lang->links_desc,
        "website"       => "http://www.site.ch",
        "author"        => "Name",
        "authorsite"    => "http://www.site.ch",
        "version"       => "0.9",
        "guid"          => "",
        "compatibility" => "16*",
    );
}
function links_install() {
    global $db, $mybb, $lang;
    
    // Check if tables exists
    if($db->table_exists('link') && $db->table_exists('linkcat')) {
        $db->drop_table('link');
        $db->drop_table('linkcat');
    }
 
    // Create both tables
    $db->write_query("
                CREATE TABLE `".TABLE_PREFIX."link` (
                    `ip` varchar(100) collate utf8_unicode_ci NOT NULL,
                    `time` int(11) NOT NULL,
                    `lid` int(11) NOT NULL auto_increment,
                    `cid` tinyint(4) NOT NULL,
                    `name` varchar(100) collate utf8_unicode_ci default NULL,
                    `link` char(255) collate utf8_unicode_ci default NULL,
                    `ldesc` char(255) collate utf8_unicode_ci default NULL,
                    `vgood` int(11) NOT NULL,
                    `vbad` int(11) NOT NULL,
                    `count` int(11) NOT NULL,
                    `created` int(11) NOT NULL,
                    PRIMARY KEY  (`lid`)
                ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
        ");
        
    $db->write_query("
                CREATE TABLE `".TABLE_PREFIX."linkcat` (
                    `cid` int(11) NOT NULL auto_increment,
                    `name` varchar(100) collate utf8_unicode_ci NOT NULL,
                    `name_pl` varchar(100) collate utf8_unicode_ci NOT NULL,
                    `description` varchar(255) collate utf8_unicode_ci NOT NULL,
                    PRIMARY KEY  (`cid`)
                ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
        ");
        
    // Vorinstallierte Links und Kategorien
    $db->write_query("INSERT INTO ".TABLE_PREFIX."linkcat (name, name_pl, description) VALUES (\"Informationsseite\", \"Informationsseiten\", \"Wikis, Dokumente, Texte, ...\");");
    $db->write_query("INSERT INTO ".TABLE_PREFIX."linkcat (name, name_pl, description) VALUES (\"Websuche\", \"Websuchen\", \"Google und Co.\");");
    $db->write_query("INSERT INTO ".TABLE_PREFIX."linkcat (name, name_pl, description) VALUES (\"Community\", \"Communitys\", \"Foren, Communitys und Sozial Networks, die Treffpunkte im Internet.\");");
    $db->write_query("INSERT INTO ".TABLE_PREFIX."linkcat (name, name_pl, description) VALUES (\"Fotoseite\",\"Fotoseiten\", \"Seiten mit Fotos.\");");
    $db->write_query("INSERT INTO ".TABLE_PREFIX."linkcat (name, name_pl, description) VALUES (\"Programm\", \"Programme\", \"Ofizielle Seiten von Computerprogrammen.\");");
    $db->write_query("INSERT INTO ".TABLE_PREFIX."linkcat (name, name_pl, description) VALUES (\"Blog\", \"Blogs\", \"Lesenswerte Internettagebül;cher\");");
    $db->write_query("INSERT INTO ".TABLE_PREFIX."linkcat (name, name_pl, description) VALUES (\"Browsergame\", \"Browsergames\", \"spannende Spiele im Netz (keine Onlinegames)\");");
    $db->write_query("INSERT INTO ".TABLE_PREFIX."linkcat (name, name_pl, description) VALUES (\"Konsolengame\", \"Konsolengames\", \"Spiele für PC, XBox, PS und Co.\");");
    $db->write_query("INSERT INTO ".TABLE_PREFIX."linkcat (name, name_pl, description) VALUES (\"Newsportal\", \"Newsportale\", \"Neuigkeiten usw.\");");
    $db->write_query("INSERT INTO ".TABLE_PREFIX."linkcat (name, name_pl, description) VALUES (\"Sonstige\", \"Sonstige\", \"Seiten, die zu keiner vorhandenen Kategorie passen.\");");
    
    //$db->write_query("INSERT INTO ".TABLE_PREFIX."link (ip, time, lid, cid, name, link, ldesc, count, created) VALUES (\"92.106.160.145\", \"\", \"1\", \"1\", \"Google\", \"http://www.google.ch\", \"Die Suchmaschine\", \"0\", \"3\");");
}
function links_is_installed() {
    global $db;
    
    if($db->table_exists('link') && $db->table_exists('linkcat'))
    {
        return true;
    }
    
    return false;
}
function links_activate() {
    global $db;
    include MYBB_ROOT.'/inc/adminfunctions_templates.php';
    
    $temp = array(
        "sid"        => "NULL",
        "title"        => "links_form",
        "template"    => $db->escape_string('<form action="#" method="post" enctype="multipart/form-data"><b>{$lang->link_eintragen}</b>
        <input name="name" class="textbox" type="text" size="20" value="{$form_name}" onfocus="if (this.value == \'{$lang->name}\') this.value = \'\';" onblur="if (this.value == \'\') this.value = \'{$lang->name}\';">
        <input name="ldesc" class="textbox" type="text" size="30" value="{$form_ldesc}" onfocus="if (this.value == \'{$lang->description}\') this.value = \'\';">
        <input name="linkadresse" class="textbox" type="text" value="{$form_linkadress}" onblur="if (this.value == \'\') this.value = \'http://\';" size="20">
        <select name="cat">{$option}</select>
        <input type="submit" name="action" value="{$lang->send_button}">
        <input type="reset" value="{$lang->reset_button}" title="{$lang->reset_button_title}">
     </form>'),
        "sid"        => "-1",
        "version"    => "1.0",
        "status"    => "0",
        "dateline"  => time(),
    );
    $db->insert_query("templates", $temp);
    
    $temp = array(
        "sid"        => "NULL",
        "title"        => "links_page",
        "template"    => $db->escape_string('<html>
        <head>
          <title>{$mybb->settings[\'bbname\']} - Links</title>
          
          <link rel="stylesheet" href="http://clubfreeware.bplaced.net/css/links.css" type="text/css" />
          {$headerinclude}
        </head>
        <body>
          {$header}
          <div align="center"><h1>{$lang->links_ueberschrift}</h1></div>
          CF Links befindet sich im Beta Status, eingetragene Links werden mit folgenden Updates gelöscht.
          <div class="tborder" style="padding:3px;display:block;width:auto;">{$addform}</div>
          {$form_message}
          <br>
          {$inhalt}
          {$footer}
        </body>
      </html>'),
        "sid"        => "-1",
        "version"    => "1.0",
        "status"    => "0",
        "dateline"  => time(),
    );
    $db->insert_query("templates", $temp);
  
    $temp = array(
        "sid"        => "NULL",
        "title"        => "links_linkcontent",
        "template"    => $db->escape_string('<table border="0" cellspacing="{$theme[\'borderwidth\']}" cellpadding="{$theme[\'tablespace\']}" class="tborder" style="margin-bottom:5px;">
        <thead>
          <tr>
            <td class="thead"colspan="3"> 
               <div class="expcolimage"><img src="images/collapse.gif" id="{$cat_name}_img" class="expander" alt="[-]" /></div>
               <div><strong>{$cat_name}</strong>{$cat_description}</div>
            </td>
          </tr>
        </thead>
        <tbody  id="{$cat_name}_e">
         {$content}
        </tbody>
      </table>'),
        "sid"        => "-1",
        "version"    => "1.0",
        "status"    => "0",
        "dateline"  => time(),
    );
    $db->insert_query("templates", $temp);
    
    $temp = array(
        "sid"        => "NULL",
        "title"        => "linkcontent_all",
        "template"    => $db->escape_string('<table border="0" cellspacing="{$theme[\'borderwidth\']}" cellpadding="{$theme[\'tablespace\']}" class="tborder" style="margin-bottom:5px;">
        <thead>
          <tr>
            <td class="thead" colspan="4"> 
               <div><strong>{$cat_name}</strong>{$cat_description}</div>
            </td>
          </tr>
        </thead>
        <tbody  id="{$cat_name}_e">
         {$content}
        </tbody>
      </table>'),
        "sid"        => "-1",
        "version"    => "1.0",
        "status"    => "0",
        "dateline"  => time(),
    );
    $db->insert_query("templates", $temp);
    
    $temp = array(
        "sid"        => "NULL",
        "title"        => "linkserror",
        "template"    => $db->escape_string('<html>
         <head>
           {$headerinclude}
           <title>{$mybb->settings[\'bbname\']} - Links Fehler</title>
         </head>
         <body>
          {$header}
          <div align="center"><h1>{$lang->links_ueberschrift}</h1></div>
          {$error}
          {$footer}
        </body>
      </html>'),
        "sid"        => "-1",
        "version"    => "1.0",
        "status"    => "0",
        "dateline"  => time(),
    );
    $db->insert_query("templates", $temp);
    
    $temp = array(
        "sid"        => "NULL",
        "title"        => "linkshomeinhalt",
        "template"    => $db->escape_string('
    <div style="display:inline-block;width:200px;margin-right:20px;">
        <table class="tborder" border="0" cellpadding="3" cellspacing="1">
            <thead>
                <tr>
                    <td class="thead"> 
                        <div><strong>Zufällige Links</strong></div>
                    </td>
                </tr>
            </thead>
            <tbody id="home_1">
                <tr>
                    <td style="padding:0px;margin:0px;">{$toprandom}</td>
                </tr>
                <tr>
                    <td class="tfoot" align="center"><a href="links.php?all">Alle Links</a></td>
                </tr>
            </tbody>
        </table>
    </div>
    <div style="display:inline-block;width:200px;">
        <table class="tborder" border="0" cellpadding="3" cellspacing="1">
            <thead>
                <tr>
                    <td class="thead"> 
                        <div><strong>Meistbesuchte Links</strong></div>
                    </td>
                </tr>
            </thead>
            <tbody id="home_2">
                <tr>
                    <td style="padding:0px;margin:0px;">{$topmostvisited}</td>
                </tr>
                <tr>
                    <td class="tfoot" align="center"><a href="links.php?all=mostvisited">Alle meistbesuchten Links</a></td>
                </tr>
            </tbody>
        </table>
    </div>
    
    <div style="display:inline-block;width:200px;margin-left:20px;">
        <table class="tborder" border="0" cellpadding="3" cellspacing="1">
            <thead>
                <tr>
                    <td class="thead">                            
                        <div><strong>Neuste Links</strong></div>
                    </td>
                </tr>
            </thead>
            <tbody  id="home_3">
                <tr>
                    <td style="padding:0px;margin:0px;">{$topnewest}</td>
                </tr>
                <tr>
                    <td class="tfoot" align="center"><a href="links.php?all=newest">Alle neusten Links</a></td>
                </tr>
            </tbody>
        </table>
    </div>
    
    <div style="display:inline-block;width:200px;margin-left:20px;">
        <table class="tborder" border="0" cellpadding="3" cellspacing="1">
            <thead>
                <tr>
                    <td class="thead">                            
                        <div><strong>Deine Links</strong></div>
                    </td>
                </tr>
            </thead>
            <tbody  id="home_3">
                <tr>
                    <td style="padding:0px;margin:0px;">{$mylinks}</td>
                </tr>
                <tr>
                    <td class="tfoot" align="center"><a href="links.php?all=newest">Alle Links von dir</a></td>
                </tr>
            </tbody>
        </table>
    </div>
    <br>Eingetragene Links: {$link_count_all}
    <br>Deine Links: {$link_count_my}'),
        "sid"        => "-1",
        "version"    => "1.0",
        "status"    => "0",
        "dateline"  => time(),
    );
    
    $db->insert_query("templates", $temp);
    
        $temp = array(
        "sid"        => "NULL",
        "title"        => "links_favicon",
        "template"    => $db->escape_string('<img src="{$linkadresse}/favicon.ico" onerror="this.src=\'./images/toplinks/linklist.png\'" style=\"height:16px;width:16px;margin:1px;\" />'),
        "sid"        => "-1",
        "version"    => "1.0",
        "status"    => "0",
        "dateline"  => time(),
    );
    
    $db->insert_query("templates", $temp);
    
        $temp = array(
        "sid"        => "NULL",
        "title"        => "userlinks",
        "template"    => $db->escape_string('<table class="tcat">
        <tr>
            <td>
                Links des Users
            </td>
        </tr>
    </table>'),
        "sid"        => "-1",
        "version"    => "1.0",
        "status"    => "0",
        "dateline"  => time(),
    );
    $db->insert_query("templates", $temp);
    
}
function links_deactivate() {
    global $db;
    include MYBB_ROOT.'/inc/adminfunctions_templates.php';
    
    find_replace_templatesets("header", '#\n<li><a href="{$mybb->settings[\'bburl\']}/links.php"><img src="{$theme[\'imgdir\']}/toplinks/linklist.png" border="0" alt="{$lang->toplinks_links}" />{$lang->toplinks_links}</a></li>#', '', 0);
    $delete_templates = array('links_page','links_linkcontent','linkserror', 'links_form', 'linkcontent_all', 'links_inhalt_startseite', 'linkshomeinhalt', 'links_favicon');
    
    foreach($delete_templates as $title)
    {
        $db->write_query("DELETE FROM `".TABLE_PREFIX."templates` WHERE title='$title' AND sid='-1'");
    }
}
function links_uninstall() {
    global $db;
    
    $db->drop_table('link');
    $db->drop_table('linkcat');
}
if(preg_match("=^[0-9]+$=i",$_GET['uid'])) {
    global $db;
    $cat = $db->simple_select('linkcat', '*', "");
    
    $link = $db->query("
        SELECT *
        FROM ".TABLE_PREFIX."link
        WHERE created='".$_GET['uid']."'
        ORDER BY name
    ");
    
    while($link_data = $db->fetch_array($link)) {
        $url = parse_url($link_data['link']);
        $img_fav = "<img src=\"http://".$url['host']."/favicon.ico\" onerror=\"this.src='./images/toplinks/linklist.png'\" height=\"16px\" width=\"16px\">";
        
        $dots = '';
        if(strlen($link_data['ldesc']) > 100) {
            $dots = '...';
        }
        
        $ldesc = substr($link_data['ldesc'],0,100).$dots;
        $eingetragen_um = my_date($mybb->settings['dateformat'], $link_data['time']);
        
        $proposer = get_user($link_data['created']);
        $bgcolor = alt_trow();
        //Kategorie
        $linkcid = $link_data['cid'];
        $catquery = $db->simple_select('linkcat', '*', 'cid = '.$linkcid.'');
        $catitem = $db->fetch_array($catquery);
        
        $cat_name = $lang->alle_links_des_users.$proposer['username'];
        $cat_description = "";
        
        $profile_link = get_profile_link($link_data['created']) ;
        
        $content .= "<tr class=\"".$bgcolor."\">
                <td><a href=\"links.php?id=".$link_data['lid']."\" target=\"_blank\" style=\"text-decoration:none;\">".$img_fav."<div style=\"line-height:16px;display:inline;vertical-align:top;\"> ".$link_data['name']."</div></a><div style=\"line-height:16px;display:inline;vertical-align:top;\"> ".$ldesc."</div></td>
                <td align=\"right\"><nobr>".$eingetragen_um."</nobr></td>
            </tr>";
    }
    
    global $userslinks;
    
    $userslinks = "<table border=\"0\" cellspacing=\"".$theme['borderwidth']."\" cellpadding=\"".$theme['tablespace']."\" class=\"tborder\" style=\"margin-bottom:5px;\">
        <thead>
          <tr>
            <td class=\"thead\" colspan=\"4\"> 
               <div><strong>".$cat_name."</strong>".$cat_description."</div>
            </td>
          </tr>
        </thead>
        <tbody  id=".$cat_name."_e\">
         ".$content."
        </tbody>
      </table>";
}
global $somelinks,$db,$mybb;
$query_r = $db->simple_select("link", "*", "",array('order_by' => 'RAND()', 'order_dir' => 'DESC', 'limit' => '5'));
while($random = $db->fetch_array($query_r))
{
    $bgcolor = alt_trow();
    $url = parse_url($random['link']);
    $linkadresse = $url['scheme']."://".$url['host'];
    eval("\$favicon = \"".$templates->get('links_favicon')."\";");
    $somelinks .= "<a href=\"links.php?id=".$random['lid']."\" target=\"_blank\" title=\"".$random['ldesc']."\" style=\"text-decoration:none;display:block;padding:3px;\" class=\"".$bgcolor."\">".$favicon."<div style=\"line-height:16px;display:inline;vertical-align:top;\"> ".$random['name']."</div></a>";
};
global $somebrowsergames,$db,$mybb;
$query_r = $db->query("
        SELECT *
        FROM ".TABLE_PREFIX."link
        WHERE cid='7'
        ORDER BY RAND()
        LIMIT 5
    ");
// $query_r = $db->simple_select("link", "*", "",array('order_by' => 'RAND()', 'order_dir' => 'DESC', 'limit' => '5', 'WHERE' => 'gid=7'));
while($random = $db->fetch_array($query_r))
{
    $bgcolor = alt_trow();
    $url = parse_url($random['link']);
    $linkadresse = $url['scheme']."://".$url['host'];
    eval("\$favicon = \"".$templates->get('links_favicon')."\";");
    $somebrowsergames .= "<a href=\"links.php?id=".$random['lid']."\" target=\"_blank\" title=\"".$random['ldesc']."\" style=\"text-decoration:none;display:block;padding:3px;\" class=\"".$bgcolor."\">".$favicon."<div style=\"line-height:16px;display:inline;vertical-align:top;\"> ".$random['name']."</div></a>";
}; 
/* LANGUAGE Function */
/* ----------------- */
function links_toplink_lang() {
    global $mybb, $lang;
    
    if(!isset($mybb->settings['bblanguage']))
    {
        $mybb->settings['bblanguage'] = 'english';
    }
    
    $lang->set_language($mybb->settings['bblanguage']);
    $lang->load('links');
}
/* ADMIN Functions */
/* --------------- */
function links_action_handler(&$action)
{
    $action['links'] = array('active' => 'links', 'file' => '');
}
function links_admin_nav(&$sub_menu)
{
    global $mybb, $lang;
    
    $lang->load("config_links", false, true);
        
    end($sub_menu);
    $key = (key($sub_menu))+10;
    
    if(!$key)
    {
        $key = '60';
    }
    
    $sub_menu[$key] = array('id' => 'links', 'title' => $lang->links_nav, 'link' => "index.php?module=config/links");
}
function links_admin()
{
    global $mybb, $db, $page, $lang;
    if($page->active_action != "links")
    {
        return;
    }
    
    $page->add_breadcrumb_item($lang->links_breadcrumb, "index.php?module=config/links");
    if($mybb->input['action'] == "manage_cat")
    {
        $page->add_breadcrumb_item($lang->manage_cat);
        $page->output_header($lang->links_title." - ".$lang->manage_cat);
        
        $sub_tabs['links'] = array(
            'title' => $lang->links_links,
            'link' => "index.php?module=config/links",
            'description' => $lang->links_links_desc
        );
        $sub_tabs['add_cat'] = array(
            'title' => $lang->links_Add_Cat,
            'link' => "index.php?module=config/links&action=add_cat",
            'description' => $lang->links_cat_desc
        );
        $sub_tabs['manage_cat'] = array(
        'title' => $lang->manage_cat,
        'link' => "index.php?module=config/links&action=manage_cad",
        'description' => $lang->manage_cat_desc
        );
        $page->output_nav_tabs($sub_tabs, "manage_cat");
        $table = new Table;
        $table->construct_header($lang->cat_name);
            $table->construct_header($lang->cat_adress);
            $table->construct_header($lang->controls, array("class" => "align_center", "width" => 150, "colspan" => 2));
        
        $query_cat = $db->simple_select("linkcat", "*", "");
        while($cats = $db->fetch_array($query_cat))
        {
            
                $table->construct_cell($cats['name']);
                $table->construct_cell($cats['description']);
                $table->construct_cell("<a href=\"index.php?module=config/links&action=edit_cat&cid={$cats['cid']}\">{$lang->edit}</a>", array("class" => "align_center", "width" => 75));
                $table->construct_cell("<a href=\"index.php?module=config/links&action=delete_cat&cid={$cats['cid']}\" onclick=\"return AdminCP.deleteConfirmation(this, '{$lang->confirm_link_deletion}');\">{$lang->delete}</a>", array("class" => "align_center", "width" => 75));
                $table->construct_row();
            }
            $table->output($lang->manage_cat);
        
        
        
        
        $page->output_footer();
    }
    
    if($mybb->input['action'] == "edit_cat")
    {
        $page->add_breadcrumb_item($lang->edit_cat);
        $page->output_header($lang->links_title." - ".$lang->edit_cat);
        
        $sub_tabs['links'] = array(
            'title' => $lang->links_links,
            'link' => "index.php?module=config/links",
            'description' => $lang->links_links_desc
        );
        $sub_tabs['add_cat'] = array(
            'title' => $lang->links_Add_Cat,
            'link' => "index.php?module=config/links&action=add_cat",
            'description' => $lang->links_cat_desc
        );
        $sub_tabs['manage_cat'] = array(
        'title' => $lang->manage_cat,
        'link' => "index.php?module=config/links&action=manage_cad",
        'description' => $lang->manage_cat_desc
        );
        $page->output_nav_tabs($sub_tabs, "manage_cat");
        
        if($mybb->request_method == "post")
        {
            
            $updated_cat = array(
                "name" => $db->escape_string($mybb->input['cat_name']),
                "description" => $db->escape_string($mybb->input['cat_description']),
                );
            $db->update_query("linkcat", $updated_cat, "cid=".intval($mybb->input['cid'])."");
            
            flash_message($lang->success_cat_updated, 'success');
            admin_redirect("index.php?module=config/links&action=manage_cat");
        }
        
        $query = $db->simple_select("linkcat", "*", "cid='".intval($mybb->input['cid'])."'");
        while($cat = $db->fetch_array($query))
        {
            $form = new Form("index.php?module=config/links&action=edit_cat&cid={$cat['cid']}", "post");
    
            $form_container = new FormContainer($lang->edit_cat);
            $form_container->output_row($lang->cat_name, $lang->cat_desc, $form->generate_text_box('cat_name', $cat['name']));
            $form_container->output_row($lang->cat_desc, $lang->cat_desc_desc, $form->generate_text_box('cat_description', $cat['description']));
        }
        
        $form_container->end();
    
        
        $buttons[] = $form->generate_submit_button($lang->save_cat);
        $form->output_submit_wrapper($buttons);
        $form->end();
        
        $page->output_footer();
    }
    
    if($mybb->input['action'] == "add_cat")
    {
        $page->add_breadcrumb_item($lang->add_cat);
        $page->output_header($lang->links_title." - ".$lang->add_cat);
        
        $sub_tabs['links'] = array(
            'title' => $lang->links_links,
            'link' => "index.php?module=config/links",
            'description' => $lang->links_links_desc
        );
        $sub_tabs['add_cat'] = array(
            'title' => $lang->links_Add_Cat,
            'link' => "index.php?module=config/links&action=add_cat",
            'description' => $lang->links_cat_desc
        );
        $sub_tabs['manage_cat'] = array(
        'title' => $lang->manage_cat,
        'link' => "index.php?module=config/links&action=manage_cat",
        'description' => $lang->manage_cat_desc
        );
        $page->output_nav_tabs($sub_tabs, "add_cat");
        
        if($mybb->request_method == "post")
        {
            
            $new_cat = array(
                "name" => $db->escape_string($mybb->input['cat_name']),
                "description" => $db->escape_string($mybb->input['cat_description']),
                );
            $db->insert_query("linkcat", $new_cat, "");
            
            flash_message($lang->success_cat_created, 'success');
            admin_redirect("index.php?module=config/links");
        }
        
        $form = new Form("index.php?module=config/links&action=add_cat", "post");
        $form_container = new FormContainer($lang->add_cat);
        $form_container->output_row($lang->cat_name, $lang->cat_desc, $form->generate_text_box('cat_name'));
        $form_container->output_row($lang->cat_name_desc, $lang->cat_desc_desc, $form->generate_text_box('cat_description'));
        $form_container->end();
        $buttons[] = $form->generate_submit_button($lang->add_cat);
        $form->output_submit_wrapper($buttons);
        $form->end();
        
        $page->output_footer();
    }
    
    if($mybb->input['action'] == "delete_link")
    {
        $db->delete_query("link", "lid=".intval($mybb->input['lid'])."");
        
        flash_message($lang->success_link_deleted, 'success');
        admin_redirect("index.php?module=config/links");
    }
    if($mybb->input['action'] == "delete_cat")
    {
        $db->delete_query("linkcat", "cid=".intval($mybb->input['cid'])."");
        
        flash_message($lang->success_cat_deleted, 'success');
        admin_redirect("index.php?module=config/links");
    }
    
    if($mybb->input['action'] == "edit_link")
    {
        $page->add_breadcrumb_item($lang->edit_link);
        $page->output_header($lang->links_title." - ".$lang->edit_link);
        
        $sub_tabs['links'] = array(
            'title' => $lang->links_links,
            'link' => "index.php?module=config/links",
            'description' => $lang->links_links_desc
        );
        $sub_tabs['add_cat'] = array(
            'title' => $lang->links_Add_Cat,
            'link' => "index.php?module=config/links&action=add_cat",
            'description' => $lang->links_cat_desc
        );
        $sub_tabs['manage_cat'] = array(
        'title' => $lang->manage_cat,
        'link' => "index.php?module=config/links&action=manage_cad",
        'description' => $lang->manage_cat_desc
        );
        $page->output_nav_tabs($sub_tabs, "edit_link");
        
        if($mybb->request_method == "post")
        {
            
            $updated_link = array(
                "name" => $db->escape_string($mybb->input['link_name']),
                "link" => $db->escape_string($mybb->input['link_adress']),
                "created" => $db->escape_string($mybb->input['link_created'])
                );
            $db->update_query("link", $updated_link, "lid=".intval($mybb->input['lid'])."");
            
            flash_message($lang->success_link_updated, 'success');
            admin_redirect("index.php?module=config/links");
        }
        
        $query = $db->simple_select("link", "*", "lid='".intval($mybb->input['lid'])."'");
        while($link = $db->fetch_array($query))
        {
            $form = new Form("index.php?module=config/links&action=edit&lid={$link['lid']}", "post");
    
            $form_container = new FormContainer($lang->edit_link);
            $form_container->output_row($lang->link_name, $lang->name_desc, $form->generate_text_box('link_name', $link['name']));
            $form_container->output_row($lang->link_adress, $lang->name_desc, $form->generate_text_box('link_adress', $link['link']));
            $form_container->output_row($lang->link_created, $lang->name_desc, $form->generate_text_box('link_created', $link['created'], array('id' => 'link_created')));
        }
        
        $form_container->end();
        
        // Autocompletion for usernames
        echo '
        <script type="text/javascript" src="../jscripts/autocomplete.js?ver=140"></script>
        <script type="text/javascript">
        <!--
            new autoComplete("link_created", "../xmlhttp.php?action=get_users", {valueSpan: "username"});
            
        // -->
        </script>';
        
        $buttons[] = $form->generate_submit_button($lang->save_link);
        $form->output_submit_wrapper($buttons);
        $form->end();
        
        $page->output_footer();
    }
    
    if(!$mybb->input['action'])
    {    
        $page->output_header($lang->links_title);
        
        if(!empty($errors))
        {
            $page->output_inline_error($errors);
        }
        
        $sub_tabs['links'] = array(
            'title' => $lang->links_links,
            'link' => "index.php?module=config/links",
            'description' => $lang->links_links_desc
        );
        $sub_tabs['add_cat'] = array(
            'title' => $lang->links_Add_Cat,
            'link' => "index.php?module=config/links&action=add_cat",
            'description' => $lang->links_cat_desc
        );
        
        $sub_tabs['edit_cat'] = array(
            'title' => $lang->links_edit_Cat,
            'link' => "index.php?module=config/links&action=manage_cat",
            'description' => $lang->links_manage_cat_desc
        );
        
        $page->output_nav_tabs($sub_tabs, "links");    
        
        $table = new Table;
        $query_cat = $db->simple_select("linkcat", "*", "");
        while($cats = $db->fetch_array($query_cat))
        {
            $cat_name = $cats['name'];
            $cat_description = $cats['description'];
        
            $table->construct_header($lang->link_name);
            $table->construct_header($lang->link_adress);
            $table->construct_header($lang->link_created);
            $table->construct_header($lang->controls, array("class" => "align_center", "width" => 150, "colspan" => 2));
        
            $query_links = $db->simple_select("link", "*", "cid = ".$cats['cid']."");
            while($links = $db->fetch_array($query_links))
            {
                $table->construct_cell($links['name']);
                $table->construct_cell($links['link']);
                $table->construct_cell($links['created']);
                $table->construct_cell("<a href=\"index.php?module=config/links&action=edit_link&lid={$links['lid']}\">{$lang->edit}</a>", array("class" => "align_center", "width" => 75));
                $table->construct_cell("<a href=\"index.php?module=config/links&action=delete_link&lid={$links['lid']}\" onclick=\"return AdminCP.deleteConfirmation(this, '{$lang->confirm_link_deletion}');\">{$lang->delete}</a>", array("class" => "align_center", "width" => 75));
                $table->construct_row();
            }
            $table->output($cats['name'] ." [".$cats['description']."]");
        
        }
        
        
        $page->output_footer();
    }    
    exit;
}
?>