Location: PHPKode > projects > Geeklog Plugins, Static Pages and Blocks > multifaq/functions-advanced.inc
<?php
//
// +---------------------------------------------------------------------------+
// | Multilingual FAQ Plugin           |
// +---------------------------------------------------------------------------+
// | functions-advanced.inc                                                    |
// +---------------------------------------------------------------------------+
// | Copyright (C) 2009 by the following authors:                              |
// |                                                                           |
// | Author:  http://lior.weissbrod.com                                               |
//
// | Copyright (C) 2006 by the following authors:                              |
// |                                                                           |
// | Author:  Oliver Spiesshofer                                               |
// | Constructed with the Universal Plugin                                     |
// | Copyright (C) 2002 by the following authors:                              |
// | Tom Willett                 -    hide@address.com           |
// | Blaine Lang                 -    hide@address.com                    |
// | The Universal Plugin is based on prior work by:                           |
// | Tony Bibbs                  -    hide@address.com                       |
// +---------------------------------------------------------------------------+
// |                                                                           |
// | 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 2            |
// | 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, write to the Free Software Foundation,   |
// | Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.           |
// |                                                                           |
// +---------------------------------------------------------------------------+
//

function plg_mfaq_checkright($what, $where) {
    global $LANG_MULTIFAQ, $_USER, $_PLG_MULTIFAQ;

    if (!is_array($what))
        $what = array($what);

    for ($i = 0; $i < count($what); $i++)
        if (SEC_hasRights($_PLG_MULTIFAQ["pi_name"].".{$what[$i]}")) {
             $approved = true;
             break;
        }

    if (!isset($approved)) {
            // Someone is trying to illegally access this page
        COM_errorLog("Someone has tried to illegally $where in {$_PLG_MULTIFAQ["pi_name"]}."
                    . " User id: {$_USER['uid']}, Username: {$_USER['username']},"
                    . "IP: {$_SERVER['REMOTE_ADDR']}",1);
        $display = COM_siteHeader()
                 . COM_startBlock($LANG_MULTIFAQ['access_denied'])
                 . $LANG_MULTIFAQ['access_denied_msg']
                 . COM_endBlock()
                 . COM_siteFooter(true);
        plg_mfaq_finalecho($display);
        exit;
    }
}

function plg_mfaq_sel() { // intermediary function to select what to edit within one group
    plg_mfaq_checkright(array("admin", "edit"), "enter the admin menu selection");
    global $_TABLES, $LANG_MULTIFAQ, $_PLG_MULTIFAQ;

    $out = '';
    if (empty($_REQUEST['what'])) {
        $what = 'topic';
    } else {
        $what = $_REQUEST['what'];  # get what to edit from plg_mfaq_menu
    }

    if ($what == "language") { #  $table,   $orderby, $idfield, $textname, $textfield
// custom code - start
        if (isset($_POST['default_language'])) {
                $default_language = $_POST['default_language'];
                DB_query ("UPDATE {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_lang']} SET is_default = 0 WHERE is_default = 1");
                DB_query ("UPDATE {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_lang']} SET is_default = 1,is_open=1 WHERE language = '$default_language'");
                $out .= COM_showMessage(60);
        }
        $out .= plg_mfaq_selform($_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_lang'], "l_id", "l_id", $LANG_MULTIFAQ['language'],
                                 "language", "plg_mfaq_edit_language");
// custom code - end
    } elseif ($what == "question") {
        $out.=plg_mfaq_selform($_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_questions'], "q_id", "q_id",
                               $LANG_MULTIFAQ['question'], "question", "plg_mfaq_edit_question");
    } elseif ($what == "topic") {
        $out.=plg_mfaq_selform($_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_topics'], "level", "topic_id", $LANG_MULTIFAQ['topic'],
                               "topic", "plg_mfaq_edit_topic");
    }
    return $out;
}

function plg_mfaq_selform($table, $orderby, $idfield, $textname, $textfield, $function) {
    # generic display of tabe contents
    global $LANG_MULTIFAQ, $LANG_ADMIN, $_CONF, $_PLG_MULTIFAQ,                  $LANG04, $LANG_DIRECTION, $_TABLES;

    plg_mfaq_checkright(array("admin", "edit"), "enter the admin selform");
    require_once( $_CONF['path_system'] . '/lib-admin.php' );

    $display = '';

    $topic_id = 0;
    if (isset($_REQUEST['topic_id']) && $_REQUEST['topic_id'] > 0)
         $topic_id = $_REQUEST['topic_id'];

    if (isset($_GET['mode'])) {
         if ($_GET['mode'] == 'install')
              $display .= COM_showMessage(44);
    } elseif (floatval (VERSION) >= 1.5 && isset($_POST['reset'])) {
         plg_mfaq_checkright('admin', 'restore the default general settings');
         plugin_load_configuration();
         $display .= COM_showMessage(60);
    } elseif (isset($_POST['sort_order'])) {
         plg_mfaq_checkright('admin', "change the questions' sort order");
         foreach ($_POST['sort_order'] as $key=>$value) {
            $upd = "UPDATE {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_questions']} SET q_order=$value "
                 . "WHERE q_id='$key';";
            DB_query($upd,1);
         }
         plg_mfaq_reorder('questions', 'q_order', 'q_id', 't_id', $topic_id);
         $display .= COM_showMessage(6);
    }

    $header_arr = array();
// custom code - start
    $form_arr = '';
    if ($textname == $LANG_MULTIFAQ['language'])
        $header_arr[] = array('text' => $LANG_MULTIFAQ['default_choice'], 'field' => 'is_default', 'sort' => false);
// custom code - end
    $header_arr[] = array('text' => $LANG_ADMIN['edit'], 'field' => 'edit', 'sort' => false);
    if ($textname == $LANG_MULTIFAQ['topic']) {
        $sorter = true;
        $rst = DB_query("SELECT COUNT(*) as count FROM $table");
        $A = DB_fetchArray($rst);
        $itemcount = $A['count'];
    } else {
        $sorter = true;
    }
    $header_arr[] = array('text' => $LANG_MULTIFAQ['id'], 'field' => $idfield, 'sort' => $sorter);
    $header_arr[] = array('text' => $textname, 'field' => $textfield, 'sort' => false);
    if ($LANG_DIRECTION <> 'ltr')
        $form_arr_align = 'left';
    else
        $form_arr_align = 'right';
    $form_arr_structure = '<div align="' . $form_arr_align . '">replacethis</div>';
    if ($textname == $LANG_MULTIFAQ['question']) {
          if (SEC_hasRights($_PLG_MULTIFAQ["pi_name"] . '.admin'))
              $form_arr = array('bottom' => str_replace('replacethis', '<input type=hidden name="topic_id" value="' . $topic_id . '">
<input type=button name="sorting" value="' . $LANG04[9] . '" onclick="this.form.submit()">', $form_arr_structure));
        $header_arr[] = array('text' => $LANG04[58], 'field' => 'sort_order', 'sort' => true);
    } elseif ($textname == $LANG_MULTIFAQ['topic'] && SEC_hasRights($_PLG_MULTIFAQ["pi_name"] . '.admin')) {
        // $header_arr[] = array('text' => $LANG_MULTIFAQ['level'], 'field' => 'level', 'sort' => true);
        if (!isset($_REQUEST['order']))
            $header_arr[] = array('text' => $LANG_MULTIFAQ['move'], 'field' => 'move', 'sort' => false);
        else
            $form_arr = array('bottom' => str_replace('replacethis', '<input type="button" value="'  . $LANG_MULTIFAQ['move'] . '" onclick="this.form.submit()">', $form_arr_structure));
    }

    $defsort_arr = array('field' => $orderby, 'direction' => 'asc');

// custom code - start
  if (SEC_hasRights($_PLG_MULTIFAQ["pi_name"] . '.admin')) {
    $intopic = '';
    if ($textfield == "question" && isset($_POST['topic_id']) && $_POST['topic_id'] > 0)
       $intopic = "&amp;topic_id=" . $_POST['topic_id'];
    $menu_arr[] = array('url' => $_CONF['site_admin_url'] . "/plugins/multifaq/index.php?plg_mfaq_action=plg_mfaq_edit_$textfield&amp;$idfield=0$intopic",
                          'text' => $LANG_ADMIN['create_new']);
  }
// custom code - end

    $menuvalues = array("topic", "language", "question");
    $menuitems = array(
$LANG_MULTIFAQ["menu_edit"] . " " . $LANG_MULTIFAQ["menu_topic"],
$LANG_MULTIFAQ["menu_edit"] . " " . $LANG_MULTIFAQ["menu_language"],
$LANG_MULTIFAQ["menu_edit"] . " " . $LANG_MULTIFAQ["menu_question"]
);

  if (!SEC_hasRights($_PLG_MULTIFAQ["pi_name"] . '.admin'))
    for ($i = 0; $i < count($menuitems); $i++)
       if ($menuvalues[$i] == 'language') {
           unset($menuvalues[$i]);
           unset($menuitems[$i]);
           $menuvalues = array_values($menuvalues);
           $menuitems = array_values($menuitems);
           break;
       }

    for ($i = 0; $i < count($menuitems); $i++) {  #iterate array
        $out = $_CONF['site_url']
             . "/admin/plugins/multifaq/index.php?plg_mfaq_action=plg_mfaq_sel"
             . "&amp;what=$menuvalues[$i]";
        if ($menuvalues[$i] != $textfield) {
            $menu_arr[] = array('url' => $out, 'text' => $menuitems[$i]);
        }
    }

    // check if faqman-plugin is installed and show import-button.
    global $_TABLES, $_DB_table_prefix;
    if ($_TABLES['faq_topics'] == $_DB_table_prefix . 'faq_topics') {
        $menu_arr[] = array(
            'url' => $_CONF['site_admin_url'] . "/plugins/multifaq/index.php?plg_mfaq_action=plg_mfaq_import",
            'text' => $LANG_MULTIFAQ['import']
        );
    }
// custom code - start
/*
    // add version check
    $out = "{$_PLG_MULTIFAQ["pi_url"]}versionchecker.php?program="
         . $_PLG_MULTIFAQ["pi_name"]."&amp;version=" . $_PLG_MULTIFAQ["pi_version"];

    $menu_arr[] = array('url' => $out, 'text' => $LANG_MULTIFAQ["menu_version"]);
    $menu_arr[] = array('url' => $_CONF['site_admin_url'], 'text' => $LANG_ADMIN['admin_home']);
*/
// custom code - end

    $text_arr = array('has_menu' =>  true,
                      'has_extras'   => true,
                      'title' => $LANG_MULTIFAQ['admin']. ": " . $textname,
                      'instructions' => '',
                      'icon' => "{$_CONF['site_url']}/multifaq/images/multifaq.gif",
                      'form_url' => $_CONF['site_admin_url']
                                 . "/plugins/multifaq/index.php?plg_mfaq_action=plg_mfaq_sel&amp;what=$textfield");

// custom code - start
    if ($topic_id)
       $text_arr['form_url'] .= '&amp;topic_id=' . $topic_id;

    $filter = '';
    $table2 = " SELECT *";
    if ($textfield == "question")
        $table2 .= ", {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_questions']}.t_id as topic_id";
    $table2 .= " FROM $table ";
    if ($textfield == "language") {
       $table2 .= COM_getPermSQL("WHERE", 0, 3);
       $query_fields = array('l_id');
    } elseif (!$_PLG_MULTIFAQ['editabletopics']) {
        $table2 = "SELECT * FROM $table WHERE NULL";
        $query_fields = array();
    } else {
       $defsort_arr = '';
       $table2 .= "LEFT JOIN {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_trans']} ON $idfield=e_id WHERE type='{$idfield{0}}'";
       if ($textfield == "question" && $topic_id)
           $table2 .= " AND {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_questions']}.t_id = '$topic_id'";
       $table2 .= COM_getPermSQL("AND", 0, 3) . " GROUP BY $idfield";
       $query_fields = array('e_id', 'field1', 'field2');
       if ($textfield == "question") {
             if ($topic_id) {
                 if (!isset($_REQUEST['order']))
                      $table2 .= " ORDER BY q_order";
             } elseif (!isset($_REQUEST['order']))
                 $table2 .= " ORDER BY {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_questions']}.t_id, q_order";
          $filter = $LANG_ADMIN['topic']
        . ': ' . plg_mfaq_list_topics($topic_id, true);
          $get_to_post = array('order', 'prevorder', 'direction');
          foreach ($get_to_post as $value)
              if (isset($_REQUEST[$value]))
                 $filter .= LB . "<input name=\"$value\" type=\"hidden\" value=\"{$_REQUEST[$value]}\">";
       } elseif (!isset($_REQUEST['order']))
           $table2 .=  " ORDER BY level";
       if (isset($_REQUEST['order']) && isset($_REQUEST['direction'])) {
          $order = $header_arr[$_REQUEST['order']]['field'];
          switch($order) {
/*
            case 'question':
            case 'topic':
               $order = 'field1';
            break;
*/
            case 'sort_order':
               $order = "{$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_questions']}.t_id, q_order";
            break;
          }
          $table2 .= " ORDER BY $order {$_REQUEST['direction']}";
          unset($_GET['order'], $_POST['order']);
       }
    }

    $query_arr = array('table' => 'links',
/*
                       'sql' => "SELECT * FROM $table WHERE 1=1",
                       'query_fields' => array('title', 'category', 'url', 'description'));
*/
                       'sql' => $table2,
                       'query_fields' => $query_fields);

    if (floatval (VERSION) >= 1.5) {
    $display .= ADMIN_createMenu($menu_arr, "");
    $display .= ADMIN_list ("multifaq", "plugin_getListField_multifaq", $header_arr, $text_arr,
                        $query_arr, $defsort_arr, $filter,
                        array('table' => $table,
                               'orderby' => $orderby,
                               'idfield' => $idfield,
                               'textname' => $textname,
                               'textfield' => $textfield,
                               'function' => $function),
                        '', $form_arr);
}
// custom code - end
else

    $display .= ADMIN_list ("multifaq", "plugin_getListField_multifaq", $header_arr, $text_arr,
                        $query_arr, $menu_arr, $defsort_arr, $filter,
                        array('table' => $table,
                               'orderby' => $orderby,
                               'idfield' => $idfield,
                               'textname' => $textname,
                               'textfield' => $textfield,
                               'function' => $function),
                        '', $form_arr);

        if (floatval (VERSION) >= 1.5 && SEC_hasRights($_PLG_MULTIFAQ["pi_name"] . '.admin')) {
             $display .= LB . '<center>';
             if (SEC_inGroup('Root')) {
                 $display .= plg_mfaq_sitegui($_PLG_MULTIFAQ['pi_name'], $LANG_MULTIFAQ['general_config']);
                 if (DB_getItem($_TABLES['plugins'], 'pi_enabled', "pi_name = 'xmlsitemap'"))
                     $display .= plg_mfaq_sitegui('xmlsitemap', $LANG_MULTIFAQ['xmlsitemap']);
             }
                $display .= '
<form method="post" action="' . $_CONF['site_admin_url'] . '/plugins/multifaq/index.php">
<input type=hidden name="plg_mfaq_action" value="plg_mfaq_sel">
<input type=submit name=reset value="' . $LANG_MULTIFAQ['reset_defaults'] . '">
</form>
</center>';
        }

    return $display;
}

function plugin_getListField_multifaq($fieldname, $fieldvalue, $A, $icon_arr, $extra)
{
    global $_CONF, $LANG_ADMIN, $LANG_ACCESS, $_TABLES, $LANG_DIRECTION, $_PLG_MULTIFAQ, $LANG_MULTIFAQ;

    $function = $extra['function'];
    $textfield = $extra['textfield'];
    $idfield = $extra['idfield'];
    $id = $A[$idfield];
    if ($textfield == 'topic' || $textfield == 'question') {
        if ($textfield == 'topic')
             $topic_id = $id;
        else
             $topic_id = $A['topic_id'];

        if (is_array($_PLG_MULTIFAQ['editabletopics']) && !in_array($topic_id, $_PLG_MULTIFAQ['editabletopics']))
              return '';
    }
    $rtl_space = '';
    if (!empty($LANG_DIRECTION) && $LANG_DIRECTION == 'rtl')
        for ($i=1; $i<=5; $i++)
            $rtl_space .= '&nbsp;';

    $retval = '';

    switch($fieldname) {
        case 'edit':
            $retval .= COM_createLink($icon_arr['edit'], "./index.php?plg_mfaq_action=$function&amp;$idfield=$id");
            break;
        case 'topic':
            $gap = "";
            $width = "";
            $width = (plg_mfaq_get_depth($A['level']) * 10) - 10;
            $gap .= "<img src=\"./images/empty.gif\" alt=\"\" width=\"$width\" height=\"1\">";
        case 'language':
                if ($fieldname == 'language') // so 'topic' wouldn't also do this due to no break
                    plg_mfaq_checkright('admin', 'enter the language settings');
        case 'question':
// custom code - start
            if ($fieldname == "topic" || $fieldname == "question") {
                list($A[$textfield],) = plg_mfaq_gettrans($id, $fieldname{0});
                if (!empty($A[$textfield])) {
                    list($url) = PLG_getCommentUrlId($_PLG_MULTIFAQ["pi_name"]);
                    $url .="?id=$id";
                    if ($fieldname == "question")
                       $url .= plg_mfaq_getLanguageTag();
                    $url = COM_buildUrl($url . "&amp;what=$fieldname");
                }
            } elseif ($_CONF['allow_user_language'] == 1 && $A[$textfield] <> $_CONF['language'] && isset($_CONF['language_files']) && in_array($A[$textfield], $_CONF['language_files'])) {
                $newLangId = array_flip($_CONF['language_files']);
                $newLangId = $newLangId[$A[$textfield]];
                $url = COM_buildUrl( $_CONF['site_url'] . '/switchlang.php?lang='
                                   . $newLangId );
            } else {
                $retval .= $gap . $A[$textfield] . $rtl_space;
                break;
            }
            if (!empty($A[$textfield]))
               $url = COM_createLink($A[$textfield], $url, plg_mfaq_needed_direction(true));
            else
               $url = $LANG_MULTIFAQ['empty_field'] . "  " . plg_mfaq_getLanguage();
            $retval .= "$gap" . $url . $rtl_space;
            break;
        case 'is_default':
            if (isset($A['is_default'])) {
                $checked = "";
                if ($A['is_default']) $checked = 'checked="checked"';
                else $checked = 'onclick="submit()"';
                $retval .= '<input type="radio" name="default_language"  value="' .
                $A[$textfield] . '" ' . $checked . '>';
            }
            break;
        case 'sort_order':
            $t_id = DB_getItem($_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_questions'], "t_id", "q_id='$id'");
            $sort_sql = "SELECT q_id FROM {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_questions']} "
                      . "WHERE t_id LIKE '$t_id';";
            $sort_result = DB_query($sort_sql,1);
            $num_rows = DB_numRows($sort_result);
            if ($num_rows > 1)
               $retval .= '<input type="text" size=1 name="sort_order[' . $id . ']"  value="' .
            $A['q_order'] . '">';
            break;
// custom code - end
        case 'move':
            $up_icon = "<img src=\"./images/up.gif\" alt=\"{$LANG_MULTIFAQ['up']}\">";
            $dwn_icon = "<img src=\"./images/down.gif\" alt=\"{$LANG_MULTIFAQ['down']}\">";
            $gap = "";
            $width = "";
            $width = (plg_mfaq_get_depth($A['level']) * 10) - 10;
            $gap .= "<img src=\"./images/empty.gif\" alt=\"\" width=\"$width\" height=\"1\">";
            $s_len = strlen($A['level']);
            $sublevel = substr($A['level'], 0, strlen($A['level'])-3);
            $lastlevel = substr($A['level'], -3);
            $sort_sql = "SELECT topic_id FROM {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_topics']} "
                      . "WHERE level LIKE '$sublevel%' AND LENGTH(level)=$s_len;";
            $sort_result = DB_query($sort_sql,1);
            $num_rows = DB_numRows($sort_result);
            $hasup = false;
            $hasdown = false;
            if ($num_rows > 0) {
                $lastlevel = intval($lastlevel);
                If ($lastlevel != "1") {
                    $hasup = true;
                }
                If ($lastlevel != $num_rows) {
                    $hasdown = true;
                }
            }

            if ($hasup) {
                $retval .= "$gap" . COM_createLink($up_icon, "./index.php?"
                    . "plg_mfaq_action=plg_mfaq_move&amp;field=$idfield&amp;id=$id"
                    . "&amp;where=up") . "&nbsp;" . $rtl_space;
            }
            if ($hasdown) {
                $retval .= "$gap" . COM_createLink($dwn_icon, "./index.php?"
                    . "plg_mfaq_action=plg_mfaq_move&amp;field=$idfield&amp;id=$id"
                    . "&amp;where=down") . $rtl_space;
            }
            break;
        default:
            $retval .= $fieldvalue;
            break;
        }
    return $retval;
}

// after a delete, correct the levels of topics so that no gaps appear in the
//level numbers
function plg_mfaq_normalize() {
    global $_TABLES, $_PLG_MULTIFAQ;
    $sql = "SELECT * FROM {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_topics']} ORDER BY level";
    $result = DB_query($sql,1);
    $lastlevel = "000";
    for ($i=0; $i<DB_numRows($result); $i++) {
        $A = DB_fetchArray($result);
        $level = $A['level'];
        $id = $A['topic_id'];
        # wenn der nächste länger ist, muss der letzte 001 sein, der rest gleich
        if (strlen($level) > strlen($lastlevel)) {
            $newlevel = $lastlevel."001";
        # andernfalls muss der letzte +1 grösser sein als der gleiche level im vorigen
        } else {
            $rootsegment = substr($lastlevel,0,(strlen($level)-3));
            $varsegment = substr($lastlevel,strlen($rootsegment),3);
            $newsegment = intval($varsegment)+1;
            while (strlen($newsegment) < 3) {
                $newsegment = "0$newsegment";
            }
            $newlevel = $rootsegment . $newsegment;
        }
        if ($level <> $newlevel) {
            $upd = "UPDATE {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_topics']} SET level='$newlevel' "
                 . "WHERE topic_id=$id;";
            DB_query($upd,1);
        }
        $lastlevel = $newlevel;
    }
}

 # move entries up and down between siblings in the topic tree
function plg_mfaq_move() {
    global $_TABLES, $_PLG_MULTIFAQ;

// custom code - start
    plg_mfaq_checkright('admin', "change the topics' sort order");
// custom code - end

    $where = $_GET['where'];
    $field = $_GET['field'];
    $id = $_GET['id'];
    if ($field == "topic_id")
        $table=$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_topics'];
    $level = DB_getItem($table, "level", "$field=$id");
    $sublevel = intval(substr($level,-3));
    $rootlevel = substr($level,0,strlen($level)-3);
    if ($where=="up") {
        $other=$sublevel-1;
    } else {
        $other=$sublevel+1;
    }
    while (strlen($other) < 3) {
        $other = "0$other";
    }
    $otherlevel = $rootlevel.$other;
    $sql = "SELECT $field, level FROM $table WHERE level LIKE '$otherlevel%'";
    $result1 = DB_query($sql,1);
    for ($i=0; $i<DB_numRows($result1); $i++) {
        $A = DB_fetchArray($result1);
        $level1 = $A['level'];
        $id1 = $A[$field];
        $templevel = "t" . $level . substr($level1, strlen($otherlevel));
        $upd = "UPDATE $table SET level='$templevel' WHERE $field=$id1;";
        DB_query($upd,1);
    }
    $sql = "SELECT $field, level FROM $table WHERE level LIKE '$level%'";
    $result2 = DB_query($sql,1);
    for ($i=0; $i<DB_numRows($result2); $i++) {
        $A = DB_fetchArray($result2);
        $level1 = $A['level'];
        $id1 = $A[$field];
        $newlevel = $otherlevel . substr($level1, strlen($otherlevel));
        $upd = "UPDATE $table SET level='$newlevel' WHERE $field=$id1;";
        DB_query($upd,1);
    }
    $sql="SELECT $field, level FROM $table WHERE level LIKE 't%'";
    $result1=DB_query($sql,1);
    for ($i=0; $i<DB_numRows($result1); $i++) {
        $A=DB_fetchArray($result1);
        $level1=$A['level'];
        $id1=$A[$field];
        $newlevel=$level . substr($level1, strlen($otherlevel)+1);
        $upd="UPDATE $table SET level='$newlevel' WHERE $field=$id1;";
        DB_query($upd,1);
    }
    if ($field=="topic_id") {
// custom code - start
        global $LANG_MULTIFAQ;
        $action=plg_mfaq_selform($table, "level", "topic_id", $LANG_MULTIFAQ['topic'], "topic", "plg_mfaq_edit_topic");}
// custom code - end
    plg_mfaq_normalize();
    return $action;
}

# generic translation retrieval
function plg_mfaq_gettrans($item_id, $type, $language=false, $plaintext=false, $puretext=false) {
    global $_CONF, $_TABLES, $_PLG_MULTIFAQ, $langtag;
    $item_arr = array();

    if (!$language) {
        if (!empty($langtag) && substr($item_id, -strlen('_xy')) == $langtag) {
           $language = $_CONF['language_files'][substr($langtag, strlen('_'))];
           $item_id = substr($item_id, 0, strrpos($item_id, '_'));
        } else
            $language = plg_mfaq_getLanguage();
    }

    if (!is_numeric($language))
       $l_id = DB_getItem($_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_lang'], 'l_id', "language='$language'");
    else
       $l_id = $language;
    $l_sql = "SELECT * FROM {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_trans']} WHERE type='$type' AND e_id='$item_id' AND l_id='$l_id';";
    $t_result = DB_query($l_sql,1);
    if (DB_numRows($t_result) == 0)
       return '';

    $t = DB_fetchArray($t_result);
    $field1 = $t['field1'];
    $field2 = $t['field2'];
    if ($puretext) {
       $field1 = addslashes($field1);
       $field2 = addslashes($field2);
       $field1 = str_replace("\r", "\r\n", $field1);
       $field2 = str_replace("\r", "\r\n", $field2);
    } else {
       $field1 = stripslashes($field1);
       $field2 = stripslashes($field2);
       if ($plaintext) {
                $field1 = htmlspecialchars($field1);
                $field2 = htmlspecialchars($field2);
       } else {
                $field1 = nl2br(PLG_replaceTags($field1));
                $field2 = nl2br(PLG_replaceTags($field2));
       }
    }
    $item_arr = array($field1,$field2, $t['commentcode']);

    return $item_arr;
}

function plg_mfaq_edit_language() { # display a form to edit languages
    plg_mfaq_checkright("admin", "edit a language");
// custom code - start
    global $_TABLES, $_CONF, $LANG_MULTIFAQ, $LANG_ADMIN, $LANG_DIRECTION, $_PLG_MULTIFAQ, $LANG_ACCESS;
// custom code - end
    $l_id = $_GET['l_id'];
    $lang_sql = "SELECT * FROM ".$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_lang']." WHERE l_id=$l_id;";
    $result = DB_query($lang_sql,1);
    $A = DB_fetchArray($result);
// custom code - start
    if (empty($A)) {
        $A = plg_mfaq_setDefaultPermissions();
        if( empty( $LANG_DIRECTION ))
	$A['direction'] = "ltr";
        else
	$A['direction'] = $LANG_DIRECTION;
    }
    $language = '';
    if (isset($A['language']))
        $language = $A['language'];
    $l_id = 0;
    if (isset($A['l_id']))
        $l_id = $A['l_id'];
// custom code - end
    if ($l_id > 0) {
        $txt .= $LANG_MULTIFAQ['edit_language'] . " \"$language\":";
    } else {
        $txt .= $LANG_ADMIN['create_new'];
    }
    if ($A['direction'] == 'ltr') {
        $selltr = ' selected="selected"';
    } else {
        $selrtl = ' selected="selected"';
    }
    $out = COM_startBlock($txt) . LB;
    $thetemplate = new Template ($_PLG_MULTIFAQ['base_path'] . 'templates/admin/');
    $thetemplate->set_file (array ('editor' => 'langeditor.thtml'));
    $thetemplate->set_var ( 'xhtml', XHTML );
    $thetemplate->set_var('l_id', $l_id);
    $thetemplate->set_var('current_language_name', $language);
    $thetemplate->set_var('new_language_name', $LANG_MULTIFAQ['language_code']);
    $thetemplate->set_var('direction_title', $LANG_MULTIFAQ['direction']);
    $thetemplate->set_var('selltr', $selltr);
    $thetemplate->set_var('ltr', $LANG_MULTIFAQ['ltr']);
    $thetemplate->set_var('selrtl', $selrtl);
    $thetemplate->set_var('rtl', $LANG_MULTIFAQ['rtl']);
    $thetemplate->set_var('lang_is_open', $LANG_MULTIFAQ['is_open']);
    if ($A['is_open']) {
        $thetemplate->set_var('checked', ' checked');
        if ($A['is_default']) {
            $thetemplate->set_var('is_open_disabled', ' disabled');
            $thetemplate->set_var('is_open_disabled_text', ' (' . $LANG_MULTIFAQ['is_open_disabled'] . ')');
        }
    }
    $thetemplate->set_var('default_commentcode', $LANG_MULTIFAQ['default_commentcode']);
    $thetemplate->set_var('commentcode', plg_mfaq_choosecommentcode($A['commentcode']));
    $access = SEC_hasAccess ($A['owner_id'], $A['group_id'], $A['perm_owner'],
            $A['perm_group'], $A['perm_members'], $A['perm_anon']);
    $thetemplate->set_var('lang_accessrights', $LANG_MULTIFAQ['defaults_lang']);
    $thetemplate->set_var('lang_owner', $LANG_ACCESS['owner']);
    $thetemplate->set_var('owner_name', COM_getDisplayName ($A['owner_id']));
    $thetemplate->set_var('owner_id', $A['owner_id']);
    $thetemplate->set_var('lang_group', $LANG_ACCESS['group']);
    $thetemplate->set_var('group_dropdown',
                             SEC_getGroupDropdown ($A['group_id'], $access));
    $thetemplate->set_var('lang_permissions', $LANG_ACCESS['permissions']);
    $thetemplate->set_var('lang_permissionskey', $LANG_ACCESS['permissionskey']);
    $thetemplate->set_var('permissions_editor', SEC_getPermissionsHTML($A['perm_owner'],$A['perm_group'],$A['perm_members'],$A['perm_anon']));
    $thetemplate->set_var('lang_permissions_msg', $LANG_ACCESS['permmsg']);
    $thetemplate->set_var('save', $LANG_ADMIN['save']);
    if ($l_id > 0)
         $thetemplate->set_var('delete', "<input type=\"submit\" name=\"submit\" value=\"{$LANG_ADMIN['delete']}\"" . XHTML . ">");

    $thetemplate->parse('output', 'editor');
    $out .= $thetemplate->finish($thetemplate->get_var('output'));
    $out .= LB . COM_endBlock();
    return $out;
}

function plg_mfaq_choose_direction($language = false) {
    global $_TABLES, $_PLG_MULTIFAQ;

// custom code - start
    if (!$language)
        $language = plg_mfaq_getLanguage(true);
// custom code - end
    $direction = DB_getItem($_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_lang'], 'direction', "language='$language'");
    if ($direction == 'rtl') {
        $auto_align = 'right';
    } else {
        $auto_align = 'left';
    }
    return array($direction, $auto_align);
}


function plg_mfaq_edit_question() { # display a form to edit questions
    plg_mfaq_checkright(array("admin", "edit"), "edit a question");
    global $_TABLES, $_CONF, $LANG_MULTIFAQ, $LANG_ADMIN, $_PLG_MULTIFAQ, $LANG_ACCESS;

    if (!$_PLG_MULTIFAQ['editabletopics'])
         plg_mfaq_checkright("null", "edit a question without having access to any topics");

// custom code - start
    if (empty($_GET)) { // If there was a failure to save
      $_GET['q_id'] = $_POST['q_id'];
      if (isset($_POST['topic_id']))
         $t_id = $_GET['topic_id'];
    }

    $q_id = $_GET['q_id'];
    if ($q_id == '0') {
        plg_mfaq_checkright("admin", "edit a question");
        $old_id = 0;
        $txt .= $LANG_ADMIN['create_new'];
        $q_id = COM_makesid();
    } else {
        $old_id = $q_id;
        $txt .= $LANG_MULTIFAQ['edit_question'] . ":";
    }

    $out = COM_startBlock($txt) . LB;
    $thetemplate = new Template ($_PLG_MULTIFAQ['base_path'] . 'templates/admin/');
    $thetemplate->set_file (array ('editor' => 'qaeditor.thtml', 
'qalist' => 'qalist_editor.thtml'));
    $thetemplate->set_var ( 'xhtml', XHTML );
    $thetemplate->set_var('old_id', $old_id);
    $thetemplate->set_var('lang_question_id', $LANG_MULTIFAQ['question_id']);
    $thetemplate->set_var('q_id', $q_id);

// custom code - start
    $t_id = 0;
    if ($old_id)
      $t_id = DB_getItem($_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_questions'], "t_id", "q_id='$q_id'");
    elseif (isset($_GET['topic_id']))
      $t_id = $_GET['topic_id'];
    $drop_topic = plg_mfaq_list_topics($t_id);
// custom code - end

    $thetemplate->set_var('lang_topic', $LANG_MULTIFAQ['topic']);
    $thetemplate->set_var('topics', $drop_topic);
    if (!SEC_hasRights($_PLG_MULTIFAQ["pi_name"] . '.admin')) {
        $thetemplate->set_var('disabled', ' disabled');
        $thetemplate->set_var('moving', " ({$LANG_MULTIFAQ['move_topic_admins']})");
    }
    $thetemplate->set_var('lang_translations', $LANG_MULTIFAQ['translations']);

    $lang_sql = "SELECT * FROM {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_lang']} ORDER BY is_default desc, language";
    $lang_result = DB_query($lang_sql,1);
    for ($i=0; $i<DB_numRows($lang_result); $i++) {
        $B = DB_fetchArray($lang_result, false);
        $language = $B['language'];
// custom code - start
        list($direction, ) = plg_mfaq_choose_direction($language);
// custom code - end
        $l_id = $B['l_id'];
        if (!is_numeric($old_id) || $old_id > 0) {
             if ((is_array($_PLG_MULTIFAQ['editabletopics']) && !in_array($t_id, $_PLG_MULTIFAQ['editabletopics'])) || !plg_mfaq_checkaccess($q_id, 'q', 'edit', false, $l_id))
                 continue;
             list($question, $answer, $commentcode[$l_id]) = plg_mfaq_gettrans($q_id, "q", $language, true);
             if (!empty($question)) // Translation found
                $B = array_merge($B, plg_mfaq_setDefaultPermissions('', $q_id, $l_id, 'q'));
        }
        if (!$t_id || empty($question)) { // New item or no translation found
             if (!isset($question))
                $question = '';
             $answer = '';
             $commentcode[$l_id] = DB_getItem($_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_lang'], "commentcode", "l_id='$l_id'");
        }

// custom code - start
       if (!DB_getItem($_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_lang'], 'is_open', "l_id='$l_id'"))
          $thetemplate->set_var('language_code', "<font color=gray>{$B['language']}</font> <font color=gray class=\"item-description\">({$LANG_MULTIFAQ['disabled_language']})</font>");
       else
           $thetemplate->set_var('language_code', $language);
        $thetemplate->set_var('deletetran', $LANG_ADMIN['delete']);
        $thetemplate->set_var('lang_question', $LANG_MULTIFAQ['question']);
        $thetemplate->set_var('l_id', $l_id);
        $thetemplate->set_var('question', $question);
        $thetemplate->set_var('direction', $direction);
        $thetemplate->set_var('lang_answer', $LANG_MULTIFAQ['answer']);
        $thetemplate->set_var('answer', $answer);
        $thetemplate->set_var('lang_comments', $LANG_MULTIFAQ['comments']);
        $thetemplate->set_var('commentcode', plg_mfaq_choosecommentcode($commentcode[$l_id], $l_id));
       $access = SEC_hasAccess ($B['owner_id'], $B['group_id'], $B['perm_owner'],
                     $B['perm_group'], $B['perm_members'], $B['perm_anon']);
       $thetemplate->set_var('lang_accessrights', '');
       $thetemplate->set_var('lang_owner', $LANG_ACCESS['owner']);
       $thetemplate->set_var('owner_name', COM_getDisplayName ($B['owner_id']));
       $thetemplate->set_var('owner_id', $B['owner_id']);
       $thetemplate->set_var('lang_group', $LANG_ACCESS['group']);
       $thetemplate->set_var('group_dropdown', str_replace('group_id', "group_id[$l_id]", 
                                                  SEC_getGroupDropdown ($B['group_id'], $access)));
       $thetemplate->set_var('lang_permissions', $LANG_ACCESS['permissions']);
       $thetemplate->set_var('lang_permissionskey', $LANG_ACCESS['permissionskey']);
       $thetemplate->set_var('permissions_editor', str_replace('[]', "[$l_id][]",
SEC_getPermissionsHTML($B['perm_owner'],$B['perm_group'],$B['perm_members'],$B['perm_anon'])));
       $thetemplate->set_var('lang_permissions_msg', $LANG_ACCESS['permmsg']);
       $thetemplate->parse ('qa_list', 'qalist', true);
    }
    $thetemplate->set_var('COM_allowedHTML', COM_allowedHTML($_PLG_MULTIFAQ['pi_name'] . '.admin'));
    $thetemplate->set_var('save', $LANG_ADMIN['save']);

    if ((!is_numeric($q_id) || $q_id>0) && SEC_hasRights($_PLG_MULTIFAQ["pi_name"] . '.admin'))
        $thetemplate->set_var('delete', "<input type=\"submit\" name=\"submit\" value=\"{$LANG_MULTIFAQ['general_delete']}\"" . XHTML . ">");

    $thetemplate->parse('output', 'editor');
    $out .= $thetemplate->finish($thetemplate->get_var('output'));
    $out.= LB . COM_endBlock();

    return $out;
}

function plg_mfaq_edit_topic() {
    plg_mfaq_checkright(array("admin", "edit"), "edit a topic");
    global $_TABLES, $_CONF, $LANG_MULTIFAQ, $LANG_ADMIN, $_PLG_MULTIFAQ, $LANG_ACCESS;

    $t_id = $_GET['topic_id'];

    if (!$t_id)
        plg_mfaq_checkright("admin", "edit an invalid topic");

    if ($t_id>0) {
        $txt .= $LANG_MULTIFAQ['edit_topic'] . ":";

        $t_level = DB_getItem($_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_topics'], "level", "topic_id=$t_id");
        $filter = " WHERE level NOT LIKE '$t_level%'";
    } else {
        $txt.= $LANG_ADMIN['create_new'];
    }
    $out = COM_startBlock($txt) . LB;
    $thetemplate = new Template ($_PLG_MULTIFAQ['base_path'] . 'templates/admin/');
    $thetemplate->set_file (array ('editor' => 'topiceditor.thtml', 
'topiclist' => 'topiclist_editor.thtml'));
    $thetemplate->set_var ( 'xhtml', XHTML );
    $thetemplate->set_var('t_id', $t_id);

    # move topic around
    $topics_sql = "SELECT * FROM {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_topics']}$filter ORDER BY LEVEL;";
    $move_rst = DB_query($topics_sql,1);
    $out2 .= "<select";
    if (!SEC_hasRights($_PLG_MULTIFAQ["pi_name"] . '.admin'))
       $out2 .= " disabled";
    $out2 .= " name=\"t_m_id\">\n"
          . "<option value=\"0\">{$LANG_MULTIFAQ['root']}</option>\n";
    for ($i=0; $i<DB_numRows($move_rst); $i++) {
        $gap = "";
        $M = DB_fetchArray($move_rst);
        $t_m_id = $M['topic_id'];
        $t_m_level = $M['level'];
        list($topic,) = plg_mfaq_gettrans($t_m_id, "t", "", true);
        $sel="";
        if ($t_m_level == substr($t_level,0,-3))
            $sel=" selected";
        elseif (!SEC_hasRights($_PLG_MULTIFAQ["pi_name"] . '.admin'))
            continue;
        for ($j=0; $j<strlen($t_m_level); $j++) {
            $gap.="&nbsp;";
        }
        $out2 .= "<option value=\"$t_m_id\"$sel>$gap{$topic}</option>\n";
    }
    $out2 .= "</select>";

    $lang_parenttopic = '<input type="checkbox" name="move" value="1"';
    $thetemplate->set_var('parenttopic', $out2);
    if (!SEC_hasRights($_PLG_MULTIFAQ["pi_name"] . '.admin')) {
        $lang_parenttopic .= ' disabled';
        $thetemplate->set_var('disabled', ' disabled');
        $thetemplate->set_var('moving', " ({$LANG_MULTIFAQ['move_topic_admins']})");
    }
    $lang_parenttopic .= XHTML . '>';
    if (!$t_id)
      $thetemplate->set_var('lang_parenttopic', $LANG_MULTIFAQ['put_topic_in']);
    else
      $thetemplate->set_var('lang_parenttopic', $lang_parenttopic . $LANG_MULTIFAQ['move_topic_to']);
    $thetemplate->set_var('lang_translations', $LANG_MULTIFAQ['translations']);

    $lang_sql = "SELECT * FROM {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_lang']} ORDER BY is_default desc, language";
    $lang_result = DB_query($lang_sql,1);
    for ($i=0; $i<DB_numRows($lang_result); $i++) {
        $B = DB_fetchArray($lang_result, false);
        $l_id = $B['l_id'];
        if ($t_id > 0) {
             if (!plg_mfaq_checkaccess($t_id, 't', 'edit', true, $l_id))
                 continue;
              list($topicx, $descriptionx) = plg_mfaq_gettrans($t_id, "t", $B['language'], true);
              if (!empty($topicx)) // Translation found
                $B = array_merge($B, plg_mfaq_setDefaultPermissions('', $t_id, $l_id, 't'));
        } elseif (!$t_id) {
            $topicx = '';
            $descriptionx = '';
        }
// custom code - start
       list($direction, ) = plg_mfaq_choose_direction($B['language']);
       if (!DB_getItem($_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_lang'], 'is_open', "l_id='$l_id'"))
          $thetemplate->set_var('language_code', "<font color=gray>{$B['language']}</font> <font color=gray class=\"item-description\">({$LANG_MULTIFAQ['disabled_language']})</font>");              else
          $thetemplate->set_var('language_code', $B['language']);
       $thetemplate->set_var('deletetran', $LANG_ADMIN['delete']);
       $thetemplate->set_var('lang_topic_name', $LANG_MULTIFAQ['topic_name']);
       $thetemplate->set_var('l_id', $l_id);
       $thetemplate->set_var('topic_name', $topicx);
       $thetemplate->set_var('direction', $direction);
       $thetemplate->set_var('lang_description', $LANG_MULTIFAQ['description']);
       $thetemplate->set_var('description', $descriptionx);
       $access = SEC_hasAccess ($B['owner_id'], $B['group_id'], $B['perm_owner'],
                     $B['perm_group'], $B['perm_members'], $B['perm_anon']);
       $thetemplate->set_var('lang_accessrights', '');
       $thetemplate->set_var('lang_owner', $LANG_ACCESS['owner']);
       $thetemplate->set_var('owner_name', COM_getDisplayName ($B['owner_id']));
       $thetemplate->set_var('owner_id', $B['owner_id']);
       $thetemplate->set_var('lang_group', $LANG_ACCESS['group']);
       $thetemplate->set_var('group_dropdown', str_replace('group_id', "group_id[$l_id]", 
                                                  SEC_getGroupDropdown ($B['group_id'], $access)));
       $thetemplate->set_var('lang_permissions', $LANG_ACCESS['permissions']);
       $thetemplate->set_var('lang_permissionskey', $LANG_ACCESS['permissionskey']);
       $thetemplate->set_var('permissions_editor', str_replace('[]', "[$l_id][]",
SEC_getPermissionsHTML($B['perm_owner'],$B['perm_group'],$B['perm_members'],$B['perm_anon'])));
       $thetemplate->set_var('lang_permissions_msg', $LANG_ACCESS['permmsg']);
       $thetemplate->parse ('topic_list', 'topiclist', true);
// custom code - end
    }

    $thetemplate->set_var('allowedHTML', COM_allowedHTML($_PLG_MULTIFAQ['pi_name'] . '.admin'));
    $thetemplate->set_var('save', $LANG_ADMIN['save']);

    if ($t_id>0 && SEC_hasRights($_PLG_MULTIFAQ["pi_name"] . '.admin')) {
        $delete_prompt = $LANG_MULTIFAQ['global_delete'] . ', ';
        if ($_PLG_MULTIFAQ['global_delete'])
             $delete_prompt .= $LANG_MULTIFAQ['global_delete_true'];
        else
             $delete_prompt .= $LANG_MULTIFAQ['global_delete_false'];
        $thetemplate->set_var('delete', "<input onclick=\"return confirm('$delete_prompt');\" type=\"submit\" name=\"submit\" value=\"{$LANG_MULTIFAQ['general_delete']}\"" . XHTML . ">");
    }

    $thetemplate->parse('output', 'editor');
    $out .= $thetemplate->finish($thetemplate->get_var('output'));
    $out.= LB . COM_endBlock();
    return $out;
    }

function plg_mfaq_write_language() {
    plg_mfaq_checkright("admin", "modify a language");
    global $_TABLES, $_CONF, $LANG_ADMIN, $LANG_MULTIFAQ, $_PLG_MULTIFAQ;

     $tablelayout = array('language', 'direction', 'is_open', 'commentcode', 'owner_id', 'group_id', 'perm_owner', 'perm_group', 'perm_members', 'perm_anon');

    $l_id = $_POST['l_id'];
    $x_action = $_POST['submit'];
    if ($x_action == $LANG_ADMIN['save']) {
        if ($l_id == 0) {
            plg_mfaq_minimizeid($_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_lang']);
            $sql = "INSERT INTO {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_lang']} " . plg_mfaq_replace_tablefields($tablelayout, 'insert');
            # features add
            # $feature="multifaq.trans_$language";
            # $desc="Contact for translation requests ($language)";
        } else {
            // If someone tried to cheat and disable a default language
            if (!isset($_POST['is_open']) && $_POST['l_id'] == plg_mfaq_getLanguageid(true))
                $_POST['is_open'] = 1;
            $sql = "UPDATE {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_lang']} " . plg_mfaq_replace_tablefields($tablelayout, 'update') . " WHERE `l_id` = '$l_id' LIMIT 1";
            $action = 'updated';
        }
    } elseif ($x_action == $LANG_ADMIN['delete']) {
        $sql = "DELETE FROM {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_trans']} WHERE `l_id` = '$l_id';";
        $result=DB_query($sql,1);
        $sql = "DELETE FROM {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_lang']} WHERE `l_id` = '$l_id' LIMIT 1";
        $action = 'deleted';
    }
// If deleting a language that was enabled or updating the enable/disable setting
    if (isset($action)) {
      if (($action == 'deleted' && DB_getItem($_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_lang'], "is_open", "l_id=$l_id")) || ($action == "update" && $_POST['is_open'] <> DB_getItem($_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_lang'], "is_open", "l_id=$l_id")))
         $PLG_needed = true;
       if ($action == 'updated' && $_POST['language'] <> DB_getItem($_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_lang'], "language", "l_id=$l_id"))
          $renamed_language = true;
      if ($action == 'deleted' || (isset($renamed_language) && $renamed_language))
           $langtag = plg_mfaq_getLanguageTag($l_id);
    }

    $result = DB_query($sql,1);

    if (isset($PLG_needed) && $PLG_needed)
       PLG_itemSaved('*', $_PLG_MULTIFAQ["pi_name"]);

    if (isset($action) && ($action == 'deleted' || (isset($renamed_language) && $renamed_language))) {
        $delete_comments = array('type' => $_PLG_MULTIFAQ["pi_name"]);
        if (!empty($langtag))
             DB_query("DELETE FROM {$_TABLES['comments']} WHERE `type` = '{$_PLG_MULTIFAQ["pi_name"]}' AND `sid` LIKE '%_$langtag'");
        else
             DB_delete($_TABLES['comments'], array_keys($delete_comments),
                                                                array_values($delete_comments));
        }

    return COM_showMessage(60) . plg_mfaq_selform($_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_lang'], "language", "l_id", $LANG_MULTIFAQ['language'], "language", "plg_mfaq_edit_language");
}

function plg_mfaq_write_topic() {
    plg_mfaq_checkright(array("admin", "edit"), "modify a topic");
    global $_TABLES, $_CONF, $LANG_ADMIN, $LANG_MULTIFAQ, $_PLG_MULTIFAQ;

     $tablelayout = array('field1', 'field2', 'owner_id', 'group_id', 'perm_owner', 'perm_group', 'perm_members', 'perm_anon');

    if (!$_PLG_MULTIFAQ['editabletopics'])
         plg_mfaq_checkright("null", "modify a topic without having access to any topics");

    $x_action = $_POST['submit'];
    if ($x_action == $LANG_MULTIFAQ['general_delete'])
            plg_mfaq_checkright("admin", "delete a topic");

    $t_id = $_POST['t_id'];

    if (!SEC_hasRights($_PLG_MULTIFAQ["pi_name"] . '.admin')) {
        if (isset($_POST['t_m_id'])) // It's supposed to be disabled for none admins
            plg_mfaq_checkright("admin", "submit a new topic");
        $t_m_id = -1;
    } else
        $t_m_id = $_POST['t_m_id'];

    if (is_array($_PLG_MULTIFAQ['editabletopics']) && (($t_id > 0 && !in_array($t_id, $_PLG_MULTIFAQ['editabletopics'])) || ($t_m_id > 0 && !in_array($t_m_id, $_PLG_MULTIFAQ['editabletopics']))))
         plg_mfaq_checkright("null", "modify a forbidden topic");

    if (!empty($_POST['field1']))
        foreach ($_POST['field1'] as $key=>$value)
           if (!plg_mfaq_checkaccess($t_id, 't', 'edit', true, $key))
                 plg_mfaq_checkright("admin", "translate a topic without edit permission");
    if (!empty($_POST['deletetran']))
        foreach ($_POST['deletetran'] as $key=>$value)
           if (!plg_mfaq_checkaccess($t_id, 't', 'edit', true, $key))
                 plg_mfaq_checkright("admin", "delete a topic's translation without edit permission");

    if ($x_action == $LANG_ADMIN['save']) {
      // If admins create a new topic or change the level of an existing topic
      if ($t_m_id > -1 && (!$t_id || isset($_POST['move']))) {
        if (!empty($t_m_id)) {#find out level where this goes in
            $level = DB_getItem($_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_topics'],"level","topic_id=$t_m_id");
        } else
            $level = '';
        $length = strlen($level)+3;
        $level_sql = "SELECT * FROM {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_topics']} "
                   . "WHERE level LIKE '$level%' AND LENGTH(level)=$length "
                   . "ORDER BY LEVEL DESC LIMIT 1";
        $level_rst = DB_query($level_sql,1);
        if (DB_numRows($level_rst) == 0) {
            $lastnum = "001";
        } else {
            $L = DB_fetchArray($level_rst);
            $xlevel = $L['level'];
            $lastnum = substr($xlevel,-3);
            settype($lastnum, "integer");
            $lastnum++;
            settype($lastnum, "string");
            while (strlen($lastnum)<3) {
                $lastnum="0$lastnum";
            }
        }
        $level .= $lastnum;
      } else
        $level = 0;

        if ($t_id == 0) { // New topic
            plg_mfaq_minimizeid($_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_topics']);
            $sql = "INSERT INTO {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_topics']} (`level`) "
                 . "VALUES ('$level');";
        $result = DB_query($sql,1);
        $t_id=DB_insertId();
        } elseif ($level) { // New level
           $original_level = DB_getItem($_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_topics'],"level","topic_id=$t_id");
           $depth_original_level = plg_mfaq_get_depth($original_level);
           $depth_level = plg_mfaq_get_depth($level);
            $sql = "SELECT * FROM {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_topics']} WHERE `level` LIKE '$original_level%'";
            $result = DB_query($sql,1);
             for ($i=0; $i<DB_numRows($result); $i++) {
                   $A = DB_fetchArray($result);
                   $id = $A['topic_id'];
                   $newlevel = $A['level'];
                   $newlevel = preg_replace('/^' . $original_level . '/', $level, $newlevel);
                   $upd = "UPDATE {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_topics']} SET level='$newlevel' WHERE topic_id=$id;";
                  DB_query($upd,1);
             }
             $PLG_needed = true;
             plg_mfaq_normalize();
        }

        $lang_sql = "SELECT * FROM {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_lang']} ORDER BY is_default DESC, language";
        $lang_result = DB_query($lang_sql,1);
        for ($i=0; $i<DB_numRows($lang_result); $i++) {
            $B = DB_fetchArray($lang_result);
            $l_id = $B['l_id'];

            if (!empty($_POST['field1'][$l_id]) || !empty($_POST['deletetran'][$l_id])) {
                $extra_fields = array('e_id' =>$t_id, 'l_id' => $l_id, 'type' => 't');
                $field_exists = false;
                if ($t_id > 0) {
                    $field_check = '';
                    foreach ($extra_fields as $key=>$value)
                         $field_check .= "$key='$value' AND ";
                    $field_check = substr($field_check, 0, -strlen(" AND "));
                    $field_exists = DB_getItem($_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_trans'], 't_id', $field_check);
                }
                if ($field_exists) {
                  if (!empty($_POST['deletetran'][$l_id])) // Deleting a translation
                    $trans_sql = "DELETE FROM {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_trans']} WHERE `t_id` = $field_exists LIMIT 1";
                  else { // Updating a translation
                    $trans_sql = "UPDATE {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_trans']} " . plg_mfaq_replace_tablefields($tablelayout, 'update', $l_id, $extra_fields) . " WHERE `t_id` = $field_exists LIMIT 1";
                    $PLG_needed = true;
                    if (!isset($at_least_one_translation))
                       $at_least_one_translation = true;
                   }
                } else { // New translation
                  plg_mfaq_minimizeid($_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_trans']);
                  if (empty($_POST['deletetran'][$l_id])) {
                    $trans_sql = "INSERT INTO {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_trans']} " . plg_mfaq_replace_tablefields($tablelayout, 'insert', $l_id, $extra_fields);
                    if (!isset($at_least_one_translation))
                       $at_least_one_translation = true;
                  }
                }
                $trans_result = DB_query($trans_sql, 1);
            }
        }

        // Making a dummy translation so there's at least one translation
        if (!isset($at_least_one_translation)) {
            $sql = "SELECT * FROM {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_trans']} WHERE e_id='$t_id' AND type='t' LIMIT 1";
            $result = DB_query($sql);
            $nrows = DB_numRows($result);
            if (!$nrows) {
                $extra_fields['l_id'] = plg_mfaq_getLanguageid(true);
                $extra_fields['field1'] = "";
                $sql = "INSERT INTO {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_trans']} (`" . implode("`, `", array_keys($extra_fields)) . "`) VALUES('" . implode("', '", array_values($extra_fields)) . "')";
                 $result = DB_query($sql);
            }
        }

    } elseif ($x_action == $LANG_MULTIFAQ['general_delete']) {
        $level = DB_getItem($_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_topics'],"level","topic_id=$t_id");
// custom code - start
        if ($level <> '001')
           $upperlevel = substr($level,0,strlen($level)-3);
        else {
           $upperlevel = "SELECT * FROM {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_topics']} WHERE level != '$level' ORDER BY level LIMIT 1";
           $upperlevel = DB_query($upperlevel,1);
           $upperlevel = DB_fetchArray($upperlevel);
           $upperlevel = $upperlevel['level'];
        }
        $upperid = DB_getItem($_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_topics'],"topic_id","level='$upperlevel'");
        if ($_PLG_MULTIFAQ['global_delete']) {
           $sql = "DELETE {$_TABLES['comments']} FROM {$_TABLES['comments']} LEFT JOIN {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_trans']} ON (sid=e_id OR sid LIKE CONCAT( e_id, '\___' )) LEFT JOIN {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_questions']} ON {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_questions']}.q_id=e_id WHERE {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_questions']}.t_id='$t_id'";
           $result = DB_query($sql,1);
           $sql = "DELETE {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_questions']}, {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_trans']} FROM {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_questions']} LEFT JOIN {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_trans']} ON e_id=q_id WHERE {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_questions']}.t_id='$t_id'";
        } else
           $sql = "UPDATE {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_questions']} SET t_id=$upperid WHERE t_id='$t_id';";
        $result = DB_query($sql,1);
        $sql = "DELETE FROM {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_topics']} WHERE `topic_id` = '$t_id' LIMIT 1";
        $result = DB_query($sql,1);
        $sql = "DELETE FROM {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_trans']} WHERE `e_id` = '$t_id' and type='t'";
        $result = DB_query($sql,1);
        $PLG_needed = true;
        plg_mfaq_normalize();
        }

        if (isset($PLG_needed) && $PLG_needed)
             PLG_itemSaved('*', $_PLG_MULTIFAQ["pi_name"]);

    return COM_showMessage(60) . plg_mfaq_selform($_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_topics'], "level", "topic_id", $LANG_MULTIFAQ['topic'], "topic", "plg_mfaq_edit_topic");
}

function plg_mfaq_write_question() {
    plg_mfaq_checkright(array("admin", "edit"), "modify a question");
    global $_TABLES, $_CONF, $LANG_ADMIN, $LANG_MULTIFAQ, $_PLG_MULTIFAQ;

    if (!$_PLG_MULTIFAQ['editabletopics'])
         plg_mfaq_checkright("null", "modify a question without having access to any topics");

     $tablelayout = array('field1', 'field2', 'commentcode', 'owner_id', 'group_id', 'perm_owner', 'perm_group', 'perm_members', 'perm_anon');

    $x_action = $_POST['submit'];
    if ($x_action == $LANG_MULTIFAQ['general_delete'])
            plg_mfaq_checkright("admin", "delete a question");

    $old_id = $_POST['old_id'];
    if (!SEC_hasRights($_PLG_MULTIFAQ["pi_name"] . '.admin')) {
        if (isset($_POST['q_id'])) // It's supposed to be disabled for none admins
            plg_mfaq_checkright("admin", "submit a new question");
        $t_id = DB_getItem($_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_questions'], "t_id", "q_id=$old_id");
        $q_id = $old_id;
    } else {
        $t_id = $_POST['topic_id'];
        $q_id = $_POST['q_id'];
        if (!$q_id) {
          $_POST['q_id'] = $old_id;
          return plg_mfaq_edit_question();
        }
    }

    if (!is_numeric($old_id) || $old_id > 0) // If editing an existing question
         $old_t_id = DB_getItem($_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_questions'], "t_id", "q_id='$old_id'");

    if (is_array($_PLG_MULTIFAQ['editabletopics']) && ((isset($old_t_id) && !in_array($old_t_id, $_PLG_MULTIFAQ['editabletopics'])) || !in_array($t_id, $_PLG_MULTIFAQ['editabletopics'])))
         plg_mfaq_checkright("null", "modify a question with a forbidden topic");

    if (!empty($_POST['field1']))
        foreach ($_POST['field1'] as $key=>$value)
           if (!plg_mfaq_checkaccess($t_id, 't', 'edit', true, $key) || !plg_mfaq_checkaccess($q_id, 'q', 'edit', false, $key))
        plg_mfaq_checkright("admin", "translate a question without edit permission");
    if (!empty($_POST['deletetran']))
        foreach ($_POST['deletetran'] as $key=>$value)
           if (!plg_mfaq_checkaccess($t_id, 't', 'edit', true, $key) || !plg_mfaq_checkaccess($q_id, 'q', 'edit', false, $key))
        plg_mfaq_checkright("admin", "delete a question's translation without edit permission");

    if ($x_action == $LANG_ADMIN['save']) {
        if (is_numeric($old_id) && $old_id == 0) { // If creating a new question
/*
            $sql = "INSERT INTO {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_questions']} "
                 . "(`q_id`,`t_id`,`changedate`) "
                 . "VALUES ('$q_id','$t_id',NOW());";
*/ 
            $neworder = plg_mfaq_neworder($t_id);
            $sql = "INSERT INTO {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_questions']} (`q_id`,`t_id`, `q_order`) VALUES ('$q_id','$t_id', $neworder);";
       } else { // If updating an existing question
/*
            $sql = "UPDATE {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_questions']} SET `q_id`='$q_id',`t_id`='$t_id' WHERE `q_id` = '$old_id' LIMIT 1";
*/
            $newvalues = "`q_id`='$q_id',`t_id`='$t_id'";
            if ($old_t_id <> $t_id) {
              $neworder = plg_mfaq_neworder($t_id);
              $newvalues .= ",`q_order`=$neworder";
            }
            $sql = "UPDATE {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_questions']} SET $newvalues WHERE `q_id` = '$old_id' LIMIT 1";
            // update link table
            list($mysql_checkfortable, $mssql_checkfortable) = plg_mfaq_querycheckfortable($_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_link']);
            $upd_link_sql = $mssql_checkfortable;
            $upd_link_sql .= "UPDATE" . $mysql_checkfortable . "{$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_link']} "
                 . "SET `new_id`='$q_id' WHERE `new_id` = '$old_id' LIMIT 1";
            $link_result = DB_query($upd_link_sql,1);
        }
        $result = DB_query($sql,1);
        if (($x_action == $LANG_ADMIN['save'] && is_numeric($old_id) && $old_id == 0) || (isset($newvalues) && strpos($newvalues, "q_order") !== false)) {
            plg_mfaq_reorder('questions', 'q_order', 'q_id', 't_id', $t_id);
            if (isset($newvalues) && strpos($newvalues, "q_order") !== false)
                 plg_mfaq_reorder('questions', 'q_order', 'q_id', 't_id', $old_t_id);
        }

        $lang_sql = "SELECT * FROM {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_lang']} ORDER BY is_default DESC, language";
        $lang_result = DB_query($lang_sql,1);
        for ($i=0; $i<DB_numRows($lang_result); $i++) {
            $B = DB_fetchArray($lang_result);
            $l_id = $B['l_id'];
            $langtag = plg_mfaq_getLanguageTag($B['language']);
            $thePLG_item = array($q_id . $langtag, $_PLG_MULTIFAQ["pi_name"]);

            if (!empty($_POST['field1'][$l_id]) || !empty($_POST['deletetran'][$l_id])) {
                if (!is_numeric($old_id) || $old_id > 0) // If editing existing item
                   $e_id = $old_id;
                else
                   $e_id = $q_id; // If creating new item
                $extra_fields = array('e_id' =>$e_id, 'l_id' => $l_id, 'type' => 'q');
                $field_exists = false;
                if ($t_id > 0) {
                     $field_check = '';
                    foreach ($extra_fields as $key=>$value)
                         $field_check .= "$key='$value' AND ";
                    $field_check = substr($field_check, 0, -strlen(" AND "));
                    $field_exists = DB_getItem($_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_trans'], 't_id', $field_check);
                }
                if ($field_exists) { // Editing an existing item
                  if (!empty($_POST['deletetran'][$l_id])) { // Deleting a certain language
                    $trans_sql = "DELETE FROM {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_trans']} WHERE `t_id` = $field_exists LIMIT 1";
                    $thePLG_type = 'Deleted';
                  } else { // Updating a translation
                    $extra_fields['e_id'] = $q_id;
                    $trans_sql = "UPDATE {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_trans']} " . plg_mfaq_replace_tablefields($tablelayout, 'update', $l_id, $extra_fields) . " WHERE `t_id` = $field_exists LIMIT 1";
                    $thePLG_type = 'Saved';
                    $thePLG_item[] = $old_id . $langtag;
                    if (!isset($at_least_one_translation))
                       $at_least_one_translation = true;
                  }
                } else { // Adding a new ID
                  plg_mfaq_minimizeid($_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_trans']);
                  if (empty($_POST['deletetran'][$l_id])) {
                     $trans_sql = "INSERT INTO {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_trans']} " . plg_mfaq_replace_tablefields($tablelayout, 'insert', $l_id, $extra_fields);
                      $thePLG_type = 'Saved';
                      if (!isset($at_least_one_translation))
                          $at_least_one_translation = true;
                  }
                }
                $trans_result = DB_query($trans_sql, 1);
                if (isset($thePLG_type))
                  call_user_func_array('PLG_item' . $thePLG_type, $thePLG_item);

                if (!empty($langtag)) {
                    $delete_comments = array('sid' => addslashes($old_id . $langtag), 'type' => $_PLG_MULTIFAQ["pi_name"]);
                    if (count($thePLG_item)>2 && $q_id <> $old_id) // If changing an ID
                       DB_change($_TABLES['comments'], 'sid', addslashes($q_id . $langtag), array_keys($delete_comments), array_values($delete_comments));
                    elseif ($thePLG_type == 'Deleted') // If deleting a certain translation
                       DB_delete($_TABLES['comments'], array_keys($delete_comments), array_values($delete_comments));
                }

            }
        }

        // Making a dummy translation so there's at least one translation
        if (!isset($at_least_one_translation)) {
            $sql = "SELECT * FROM {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_trans']} WHERE e_id='$e_id' AND type='q' LIMIT 1";
            $result = DB_query($sql);
            $nrows = DB_numRows($result);
            if (!$nrows) {
                $extra_fields['l_id'] = plg_mfaq_getLanguageid(true);
                $extra_fields['field1'] = "";
                $sql = "INSERT INTO {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_trans']} (`" . implode("`, `", array_keys($extra_fields)) . "`) VALUES('" . implode("', '", array_values($extra_fields)) . "')";
                 $result = DB_query($sql);
            }
        }

    } elseif ($x_action == $LANG_MULTIFAQ['general_delete']) {
        $sql = "DELETE FROM {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_questions']} WHERE `q_id` = '$q_id' LIMIT 1";
        $result = DB_query($sql,1);
        $sql = "DELETE FROM {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_trans']} WHERE `e_id` = '$q_id' and type='q'";
        $result = DB_query($sql,1);

        if (is_array($_CONF['language_files'])) {
            foreach ($_CONF['language_files'] as $key=>$value) {
               $langtag = plg_mfaq_getLanguageTag($key);
               if (!empty($langtag)) {
                $delete_comments = array('sid' => addslashes($old_id . $langtag), 'type' => $_PLG_MULTIFAQ["pi_name"]);
                DB_delete($_TABLES['comments'], array_keys($delete_comments), array_values($delete_comments));
                  PLG_itemDeleted($q_id . $langtag, $_PLG_MULTIFAQ["pi_name"]);
               }
            }
        } else {
            $delete_comments = array('sid' => addslashes($old_id), 'type' => $_PLG_MULTIFAQ["pi_name"]);
            DB_delete($_TABLES['comments'], array_keys($delete_comments), array_values($delete_comments));
            PLG_itemDeleted($q_id, $_PLG_MULTIFAQ["pi_name"]);
        }

        plg_mfaq_reorder('questions', 'q_order', 'q_id', 't_id', $t_id);
    }
    return COM_showMessage(60) . plg_mfaq_selform($_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_questions'], "q_id", "q_id", $LANG_MULTIFAQ['question'], "question", "plg_mfaq_edit_question");
}

function plg_mfaq_top_x_questions() {
    global $_CONF, $_TABLES, $_PLG_MULTIFAQ, $LANG_MULTIFAQ, $langtag;

    $display = '';

    $l_id = plg_mfaq_getLanguageid();
// custom code - start
    $question_sql = "SELECT e_id, hits, {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_questions']}.t_id FROM {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_questions']} LEFT JOIN {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_trans']} ON q_id=e_id WHERE {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_questions']}.t_id IS NOT NULL AND l_id=$l_id AND hits>0" . COM_getPermSQL("AND") . " ORDER BY hits DESC LIMIT {$_PLG_MULTIFAQ["top_x_count"]};";
// custom code - end
    $result_q = DB_query($question_sql,1);

    if (DB_numRows($result_q) == 0)
        return $display;

     if ($_PLG_MULTIFAQ["javascript"])
        $display .= "\n<span class=\"clickable_faq\" onclick=\"toggle('topic_top', false); return false\">";
    $display .= COM_startBlock($LANG_MULTIFAQ['top_faq']);
     if ($_PLG_MULTIFAQ["javascript"])
        $display .= "</span><div id=\"topic_top\">";
    for ($j=0; $j<DB_numRows($result_q); $j++) {
        $B = DB_fetchArray($result_q);
        $hits = $B['hits'];
        $topic_id = $B['t_id'];
        $q_id = $B['e_id'];

         if (is_array($_PLG_MULTIFAQ['allowedtopics']) && !in_array($topic_id, $_PLG_MULTIFAQ['allowedtopics']))
           continue;
        if (!isset($atleastonequestion))
           $atleastonequestion = true;

        list($question, $answer) = plg_mfaq_gettrans($q_id, 'q'); # get translations
        $url = COM_buildUrl ($_CONF['site_url']
             . "/multifaq/index.php?id=".$q_id . $langtag); //what=qa&amp;
        $display .=  LB . "- <span" . plg_mfaq_needed_direction() . ">";
        if ($_PLG_MULTIFAQ["javascript"])
           $display .= "<u><font color=blue class=\"clickable_faq\" onclick=\"toggle('question_top{$q_id}', true); return false\">" . $question . "</font></u>";
        else
           $display .= COM_createLink($question, $url);
        $display .= " ($hits)</span>";

        $display .= plg_mfaq_editlink("question", $q_id);

        if ($_PLG_MULTIFAQ["javascript"])
           $display .= "\n<div class=\"toggleA\" id=\"question_top$q_id\"><p>$answer</p></div>";
        $display .= "<br>\n";
    }
    $display .= "</div>";

    $display .= COM_endBlock();

    if (!isset($atleastonequestion))
       $display = '';

    return $display;
}

function plg_mfaq_recent_additions() {
    global $_CONF, $_TABLES, $_PLG_MULTIFAQ, $LANG_MULTIFAQ, $langtag;

    $display = '';

     if ($_PLG_MULTIFAQ["javascript"])
        $display .= "\n<span class=\"clickable_faq\" onclick=\"toggle('topic_recent', false); return false\">";
    $display .= COM_startBlock($LANG_MULTIFAQ['recent_aditions']);
     if ($_PLG_MULTIFAQ["javascript"])
        $display .= "</span><div id=\"topic_recent\">";

    $l_id = plg_mfaq_getLanguageid();
// custom code - start
    $question_sql = "SELECT changedate, e_id, {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_questions']}.t_id from {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_questions']} LEFT JOIN {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_trans']} ON q_id=e_id WHERE {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_questions']}.t_id IS NOT NULL AND l_id=$l_id" . COM_getPermSQL("AND") . "  ORDER BY changedate DESC LIMIT {$_PLG_MULTIFAQ["recent_count"]};";
    $result_q = DB_query($question_sql,1);

    if (DB_numRows($result_q) == 0)
        return '';

// custom code - end
    for ($j=0; $j<DB_numRows($result_q); $j++) {
        $B = DB_fetchArray($result_q);
        $q_id = $B['e_id'];
        $topic_id = $B['t_id'];

         if (is_array($_PLG_MULTIFAQ['allowedtopics']) && !in_array($topic_id, $_PLG_MULTIFAQ['allowedtopics']))
            continue;
        if (!isset($atleastonequestion))
           $atleastonequestion = true;

        list($question, $answer) = plg_mfaq_gettrans($q_id, 'q');     # get translations
        $date = $B['changedate'];
        $url = COM_buildUrl ($_CONF['site_url']
                . "/multifaq/index.php?id=$q_id" . $langtag);
        $display .=  LB . "- <span" . plg_mfaq_needed_direction() . ">";
        if ($_PLG_MULTIFAQ["javascript"])
           $display .= "<u><font color=blue class=\"clickable_faq\" onclick=\"toggle('question_recent$q_id', true); return false\">" . $question . "</font></u>";
        else
           $display .= COM_createLink($question, $url);
        $display .= " ($date)</span>";

        $display .= plg_mfaq_editlink("question", $q_id);

        if ($_PLG_MULTIFAQ["javascript"])
           $display .= "\n<div class=\"toggleA\" id=\"question_recent$q_id\"><p>$answer</p></div>";
        $display .= "<br>\n";
    }
    $display .= "</div>";

    $display.=COM_endBlock();

    if (!isset($atleastonequestion))
       $display = '';

    return $display;
}

function plg_mfaq_get_q_and_a($getquestion, $searchterms, $getstype) {
    global  $_TABLES, $_PLG_MULTIFAQ, $LANG_ADMIN, $_CONF, $LANG05, $LANG_DIRECTION, $PLG_MFAQ_HEADER, $LANG_MULTIFAQ, $langtag;

    $display = '';

    list($searchterms, $getstype) = plg_mfaq_search_perm($searchterms, $getstype);

    $l_id = plg_mfaq_getLanguageid();
    $topic_id = DB_getItem($_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_questions'], "t_id", "q_id='$getquestion'");

    if (empty($topic_id) || !$_PLG_MULTIFAQ['allowedtopics'] || (is_array($_PLG_MULTIFAQ['allowedtopics']) && !in_array($topic_id, $_PLG_MULTIFAQ['allowedtopics'])) || !plg_mfaq_checkaccess($getquestion, 'q', 'read')) {
        $display .= COM_startBlock($LANG_MULTIFAQ['access_denied'])
                 . $LANG_MULTIFAQ['access_denied_msg']
                 . COM_endBlock();
        return $display;
    }

    $getlevel = DB_getItem($_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_topics'],"level","topic_id='$topic_id'");

// custom code - start
     $direction = plg_mfaq_needed_direction();
     $align = "";
     if (!empty($direction)) {
       list(, $align) = plg_mfaq_choose_direction("");
       $align = " align=\"$align\"";
    }

    list($question, $answer) = plg_mfaq_gettrans($getquestion, 'q');     # get translations
    if (empty($question)) // Question found but not its translation
        $question = $LANG_MULTIFAQ['empty_field'] . "  " . plg_mfaq_getLanguage();
    if (empty($answer)) // Answer found but not its translation
        $answer = $LANG_MULTIFAQ['empty_field'] . "  " . plg_mfaq_getLanguage();
// custom code - end

    $rawquestion = $question;
// custom code - start

     if (isset($question_alt) && !empty($question_alt)) {
        $old_l_id = $l_id;
        $l_id = plg_mfaq_getLanguageid(true);
    }
    $date = DB_getItem($_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_trans'], 
"changedate", "e_id='$getquestion' AND type='q' AND l_id=$l_id");
     if (isset($question_alt) && !empty($question_alt))
        $l_id = $old_l_id;

    // Highlight the searchterms in questions and/or answers
    if (!empty($searchterms))
        list($question, $answer) = plg_mfaq_highlight($question, $answer, $searchterms, $getstype);

    $question = plg_mfaq_editlink("question", $getquestion, true) . $question;
    $display .= COM_startBlock("<div" . $angle . $direction . ">$question</div>");
    $display .= "<div" . $align . $direction . ">$answer</div><br><br>\n" . plg_mfaq_language_selection(). "<hr>";
// custom code - end

// If the user is neither an admin nor an editor unless they are countable
    if ((!SEC_hasRights($_PLG_MULTIFAQ['pi_name'] . '.admin') && !SEC_hasRights($_PLG_MULTIFAQ['pi_name'] . '.edit')) || (SEC_hasRights($_PLG_MULTIFAQ['pi_name'] . '.admin') && $_PLG_MULTIFAQ['count_admin']) || (SEC_hasRights($_PLG_MULTIFAQ['pi_name'] . '.edit') && $_PLG_MULTIFAQ['count_editor'])) {
/*
    if ($_PLG_MULTIFAQ['count_admin'] == true || !SEC_hasRights($_PLG_MULTIFAQ['pi_name'] . '.admin')) {
*/
        # update hitcount
        $hit_sql = "UPDATE {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_trans']} SET hits=hits+1 WHERE e_id='$getquestion' AND type='q' AND l_id=$l_id;";
        $h_result = DB_query($hit_sql,1);
    }

    if ($_PLG_MULTIFAQ["show_datetime"]) {
        $display.="<div align=\"center\">{$LANG_MULTIFAQ['last_update']}: $date</div>";
    }
    # display hierarchy path
    $path .= "<img src=\"{$_PLG_MULTIFAQ["multifaq_pic"]}\" alt=\"\">"
          . "&nbsp;";
    $path_url = $_CONF['site_url'] . "/";
    if (!$_PLG_MULTIFAQ['replace_homepage'])
        $path_url .= "multifaq/index.php";
    $path .= COM_createLink($LANG_MULTIFAQ['menu_label'], $path_url);
// custom code - start
    $stringpath = $LANG_MULTIFAQ['plugin'];
// custom code - end
    $depth = plg_mfaq_get_depth($getlevel);
    for ($i=1; $i<=$depth; $i++) {
        $steplevel = substr($getlevel, 0, $i*3);
        $topic_sql = "SELECT * FROM {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_topics']} WHERE level='$steplevel';";
        $result = DB_query($topic_sql,1);
        $A = DB_fetchArray($result);
        list($topic,) = plg_mfaq_gettrans($A['topic_id'], 't');     # get translations
        $url = COM_buildUrl ($_CONF['site_url']
            . "/multifaq/index.php?id={$A['topic_id']}&amp;what=topic");
// custom code - start
        $path .= "&nbsp;&gt;&nbsp;" . COM_createLink($topic, $url, plg_mfaq_needed_direction(true));
        if (!empty($topic)) {
           $bracket = "&gt;";
           $stringpath .= " " . $bracket ." ". $topic;
        }
    }
    $display .= $path . plg_mfaq_editlink("topic", $A['topic_id']);

    $q_order = DB_getItem($_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_questions'], "q_order", "q_id='$getquestion'");
    $prev_question = DB_getItem($_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_questions'], "q_id", "t_id='$topic_id' AND q_order=" . ($q_order-10));
    $next_question = DB_getItem($_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_questions'], "q_id", "t_id='$topic_id' AND q_order=" . ($q_order+10));
    if (isset($prev_question) || isset($next_question)) {
        $display .= "<br><br>\n<table width=\"99%\"><tr>\n";
        list(, $align) = plg_mfaq_choose_direction(plg_mfaq_getLanguage());
        if ($align == "left")
           $align_rev = "right";
        else
           $align_rev = "left";
        if (isset($prev_question)) {
                if (plg_mfaq_checkaccess($prev_question, 'q', 'read')) {
                    list($prev_question_title) = plg_mfaq_gettrans($prev_question, 'q');
                    $prev_question_cut = mb_substr($prev_question_title, 0, 60);
                    if ($prev_question_cut <> $prev_question_title)
                        $prev_question_cut .= '...';
                    $prev_question = COM_createLink($prev_question_cut, COM_buildUrl ($_CONF['site_url'] . "/multifaq/index.php?id=$prev_question" . $langtag), array("title" => $prev_question_title));
                } else
                    unset($prev_question);
        }
        if (isset($next_question)) {
                if (plg_mfaq_checkaccess($next_question, 'q', 'read')) {
                    list($next_question_title) = plg_mfaq_gettrans($next_question, 'q');
                    $next_question_cut = mb_substr($next_question_title, 0, 60);
                    if ($next_question_cut <> $next_question_title)
                        $next_question_cut .= '...';
                    $next_question = COM_createLink($next_question_cut, COM_buildUrl ($_CONF['site_url'] . "/multifaq/index.php?id=$next_question" . $langtag), array("title" => $next_question_title));
                } else
                    unset($next_question);
        }
        if ($align == "left") {
                if (isset($prev_question))
                   $display .= "<td align=\"$align\">$prev_question &lt;=&nbsp;<b>{$LANG05[6]}</b></td>";
                if (isset($next_question))
                   $display .= "<td align=\"$align_rev\"><b>{$LANG05[5]}</b>&nbsp;=&gt; $next_question</td>";
        } else {
                if (isset($prev_question))
                     $display .= "<td align=\"$align\">$prev_question &lt;=&nbsp;<b>{$LANG05[6]}</b></td>";
                if (isset($next_question))
                    $display .= "<td align=\"$align_rev\"><b>{$LANG05[5]}</b>&nbsp;=&gt; $next_question</td>";
        }
        $display .= "\n</tr></table>\n";
    }
// custom code - end

    $PLG_MFAQ_HEADER = $rawquestion." (".$stringpath.")";

    $cid=NULL; $order=NULL; $format=NULL; $page=NULL; $view=NULL;
    $display .= PLG_displayComment($_PLG_MULTIFAQ['pi_name'], 
$getquestion . $langtag, $cid, $rawquestion, $order, $format, $page, $view);

    $display .= COM_endBlock();

    return $display;
}

function plg_mfaq_import() {
// custom code - start
    global $_TABLES, $_PLG_MULTIFAQ, $_CONF, $LANG_MULTIFAQ;
// custom code - end
    plg_mfaq_checkright("admin", "prepare an import");
    $display = "";
// custom code - start
    $sql = "SELECT l_id, language FROM {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_lang']}";
    $result = DB_query($sql);
    for ($i=0; $i<DB_numRows($result); $i++) {
          $A = DB_fetchArray($result);
          $language[] = "<option value=\"{$A['l_id']}\">{$A['language']}</option>";
    }
    $language = implode(LB, $language);
    $current_translation = plg_mfaq_getLanguage();
    $language = str_replace(">$current_translation<", " selected=\"selected\">$current_translation<", $language);
// custom code - end
    $display .= COM_startBlock($LANG_MULTIFAQ['import'])
             . $LANG_MULTIFAQ['import_description']
             . "<form action=\"{$_CONF['site_admin_url']}/plugins/multifaq/index.php\" method=\"post\">"
             . "<input type=\"hidden\" name=\"plg_mfaq_action\" value=\"plg_mfaq_doimport\">"
// custom code - start
             . "\n{$LANG_MULTIFAQ['language_faq']}:\n<select name=\"translation_id\">\n$language\n</select>\n<br>"
// custom code - end
             . "<input type=\"submit\" value=\"{$LANG_MULTIFAQ['import']}\">"
             . "&nbsp;<input type=\"checkbox\" name=\"linkdata\" value=\"true\">" . $LANG_MULTIFAQ['preserve_links']
             . "</form>";
    $display .= COM_endBlock();
    return $display;
}

function plg_mfaq_doimport() {
    global $_PLG_MULTIFAQ, $_TABLES, $_CONF, $LANG_MULTIFAQ;
    plg_mfaq_checkright("admin", "import");
    $display = "";

// custom code - start
    if (isset($_POST['translation_id']))
        $l_id = COM_applyFilter($_POST['translation_id']);
    if (!isset($l_id) || DB_count($_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_lang'], "l_id", $l_id) == 0)
        $l_id = plg_mfaq_getLanguageid();
    $language = DB_getItem($_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_lang'], "language", "l_id = '$l_id'");
// custom code - end
    if (isset($_POST['linkdata'])) {
        $link = COM_applyFilter($_POST['linkdata']);
    }
    // create link table
    if ($link) {
        plg_mfaq_createlink_table();
    }
    $display .= COM_startBlock($LANG_MULTIFAQ['import']);
    $imp_cat_sql = "SELECT catID, name, description FROM {$_TABLES['faq_categories']};";
    $cat_result = DB_query($imp_cat_sql);
    plg_mfaq_minimizeid($_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_topics']);
    plg_mfaq_minimizeid($_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_trans']);
    for ($i=0; $i<DB_numRows($cat_result); $i++) {
        $A = DB_fetchArray($cat_result);
        $name = addslashes($A['name']);
        $desc = addslashes($A['description']);
        // insert data
// custom code - start
        $ins_cat_sql1 = "INSERT INTO {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_topics']} (`level`) "
                 . "VALUES ('001');";
        $ins_cat_result1 = DB_query($ins_cat_sql1);
        $topic_id = DB_insertId();
        list($direction, ) = plg_mfaq_choose_direction($language);
        $ins_cat_sql2 = "INSERT INTO {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_trans']} (`e_id`,`l_id`,`type`,`field1`,`field2`, `changedate`) "
                 . "VALUES ('$topic_id','$l_id', 't', '$name','$desc', NOW());";
/*
        $ins_cat_sql = "INSERT INTO {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_topics']} (`topic`,`description`,`level`) "
                 . "VALUES ('$name','$desc','001');";
*/

        $ins_cat_result2 = DB_query($ins_cat_sql2);
        if (DB_affectedRows($ins_cat_result1) == 1 && DB_affectedRows($ins_cat_result2) == 1)
 {
/*
            $ins_cat_id = DB_insertId();
*/
            $ins_cat_id = $topic_id;
            $language_note = "<li>" . $LANG_MULTIFAQ['import_to_language'] . ":<br><b>" . $language . "</b>, " . $LANG_MULTIFAQ['import_to_direction'] . " <b>" . $LANG_MULTIFAQ[$direction] . "</b></li>";
            $language_note .= "<li>" . $LANG_MULTIFAQ['import_to_note'] . "</li><br><br>";
            $display .= $language_note;
            $display .= $LANG_MULTIFAQ['import_t_ok']. ": <b><span dir=\"$direction\">{$A['name']}</span></b><br>";
// custom code - end
            if ($link) {
                $display .= plg_mfaq_createlink_entry(
                    $A['catID'],
                    $ins_cat_id,
                    't',
                    'faqman'
                );
            }
            plg_mfaq_normalize();
        } else {
            $display .= $LANG_MULTIFAQ['import_t_fail']. ": {$A['name']}<br>";
        }

        $imp_qa_sql = "SELECT topicID, catID, question, answer FROM {$_TABLES['faq_topics']} "
                    . "WHERE catID ='{$A['catID']}';";
        $imp_qa_result = DB_query($imp_qa_sql);
        for ($j=0; $j<DB_numRows($imp_qa_result); $j++) {
            $B = DB_fetchArray($imp_qa_result);
            $ques = addslashes($B['question']);
            $ans = addslashes($B['answer']);
            $q_id = COM_makesid() . $B['topicID'];
// custom code - start
/*
            $ins_qa_sql1 = "INSERT INTO {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_questions']} "
                 . "(`q_id`,`t_id`,`changedate`) "
                 . "VALUES ('$q_id','$ins_cat_id',NOW());";
*/
            $ins_qa_sql1 = "INSERT INTO {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_questions']} (`q_id`,`t_id`) VALUES ('$q_id','$ins_cat_id');";
            $ins_qa_sql2 = "INSERT INTO {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_trans']} (`e_id`,`l_id`,`type`,`field1`,`field2`, `changedate`) "
                 . "VALUES ('$q_id','$l_id', 'q', '$ques','$ans', NOW());";
/*
            $ins_qa_sql = "INSERT INTO {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_questions']} "
                 . "(`q_id`,`t_id`,`question`,`answer`,`changedate`) "
                 . "VALUES ('$q_id','$ins_cat_id','$ques','$ans', NOW());";
*/
            $ins_qa_result1 = DB_query($ins_qa_sql1);
            $ins_qa_result2 = DB_query($ins_qa_sql2);
            PLG_itemSaved($q_id . plg_mfaq_getLanguageTag($language), $_PLG_MULTIFAQ["pi_name"]);
            if (DB_affectedRows($ins_qa_result1) == 1 && DB_affectedRows($ins_qa_result2) == 1) {
                if (!isset($language_note))
                    $display .= $language_note;
// custom code - end
                $display .= $LANG_MULTIFAQ['import_qa_ok']. ": <b><span dir=\"$direction\">{$B['question']}</span></b><br>";
                if ($link) {
                    $display .= plg_mfaq_createlink_entry(
                        $B['topicID'],
                        $q_id,
                        'q',
                        'faqman'
                    );
                }
            } else {
                $display .= $LANG_MULTIFAQ['import_qa_fail']. ": {$B['question']}<br>";
            }
        }
    }
    $display .= COM_endBlock();
    return $display;
}
// this function creates a link entry in the link table to identify
// the former ids of FAQMAN and the new ids of MultiFAQ
function plg_mfaq_createlink_entry($old_id, $new_id, $type, $source) {
    // insert link into table
    global $_TABLES, $LANG_MULTIFAQ, $_PLG_MULTIFAQ;
    plg_mfaq_checkright("admin", "submit an import to the database");
    $check_sql = "SELECT * FROM {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_link']} "
               . "WHERE old_id = '$old_id' AND `type`='$type' AND source='$source'";
    $check_result = DB_query($check_sql);
    if (DB_numRows($check_result) > 0) {
        $display .= $LANG_MULTIFAQ['link_fail_double']. "<br>";
    } else {
        $link_sql = "INSERT INTO {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_link']}"
                  . "(`old_id`, `new_id`, `type`, `source`)"
                  . "VALUES ('$old_id', '$new_id', '$type', '$source');";
        $link_result = DB_query($link_sql);
        if (DB_affectedRows($link_result) == 1) {
            $display .= $LANG_MULTIFAQ['link_ok']. "<br>";
        } else {
            $display .= $LANG_MULTIFAQ['link_fail']. "<br>";
        }
    }
    return $display;
}

// create the table that holds the links.
function plg_mfaq_createlink_table() {
    plg_mfaq_checkright("admin", "create a table for imports");
    global $_TABLES, $_PLG_MULTIFAQ;

    list($mysql_checkfortable, $mssql_checkfortable) = plg_mfaq_querycheckfortable($_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_link'], true);
    $sql = $mssql_checkfortable;
    $sql .= "CREATE TABLE" . $mysql_checkfortable . "`{$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_link']}` "
         . "(`old_id` INT NOT NULL , `new_id` VARCHAR(40) NOT NULL ,`type` ENUM( 't', 'q' ) NOT NULL, "
         . "`source` VARCHAR( 10 ) NOT NULL);";
    $result = DB_query($sql);
}

function plg_mfaq_get_depth($level) {
    $d =  strlen($level)/3;
    return $d;
}

// display the tree to the user
function plg_mfaq_get_tree($gettopic = NULL, $gettype, $searchterms, $getstype) {
    global  $_TABLES, $_PLG_MULTIFAQ, $_CONF, $LANG_ADMIN, $PLG_MFAQ_HEADER, $LANG_MULTIFAQ, $LANG09, $LANG_DIRECTION;

    $display = '';

    list($searchterms, $getstype) = plg_mfaq_search_perm($searchterms, $getstype);

    $base_url = $_CONF['site_url'] . "/multifaq/index.php?id=";
    $topic_url = $base_url . "{topic_id}&amp;what=topic";
    $question_url = $base_url . "{question_id}" . plg_mfaq_getLanguageTag();
    $question_url_post = "&amp;what=question";
    $url_post = '';

    if (!empty($searchterms)) {
//         $searchurl = "&amp;query=" . urlencode($searchterms) . "&amp;type=$getstype";
         $searchurl = "&amp;type=$getstype";
         if ($_CONF['url_rewrite'])
           $searchurl_terms = "?";
         else
           $searchurl_terms = "&amp";
         $searchurl_terms .= "query=" . urlencode($searchterms);
         $search_fields = array('field1', 'field2');
         $search_sql = '';
         for ($i = 0; $i < count($search_fields); $i++) {
            $search_sql .= "`{$search_fields[$i]}` REGEXP '[[:<:]]{searchterms}[[:>:]]'";
            if ($i < count($search_fields) -1 )
               $search_sql .= " OR ";
         }
         if (strpos($searchterms, " ") !== false) {
             $searchterms_sql = '';
             $searchterms = explode(" ", $searchterms);
             $searchterms = array_unique($searchterms);
             if ($getstype == 'all' || $getstype == 'any') {
                 if ($getstype == 'all')
                    $search_break = "AND";
                 elseif ($getstype == 'any')
                    $search_break = "OR";
                 for ($i = 0; $i < count($searchterms); $i++) {
                     if ($i > 0)
                         $searchterms_sql .= " $search_break ";
                     if ($getstype == 'all')
                         $searchterms_sql .= '(';
                     $searchterms_sql .= str_replace('{searchterms}', $searchterms[$i], $search_sql);
                     if ($getstype == 'all')
                         $searchterms_sql .= ')';
                 }
             }
             $searchterms = implode(" ", $searchterms);
         }
         if (strpos($searchterms, " ") === false || $getstype == 'phrase') {
           $searchterms_regexp = $searchterms;
           if (strpos($searchterms, " ") !== false)
             $searchterms_regexp = str_replace(" ", '([[:blank:]]|[[:blank:]][[:punct:]]|[[:punct:]][[:blank:]])' , $searchterms_regexp);
           $searchterms_sql = str_replace('{searchterms}', $searchterms_regexp, $search_sql);
         }
    }
    $l_id = plg_mfaq_getLanguageid();

    if ($gettopic == NULL) {
        $gettopic = 1;
    } else
        $_PLG_MULTIFAQ["expand_all"] = false;

    $getlevel = DB_getItem($_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_topics'], "level", "topic_id=$gettopic");

    $thetitle .= $LANG_MULTIFAQ['faq_topics'];
    if ((!$_PLG_MULTIFAQ["expand_all"] && $gettopic > 1) || !empty($searchterms)) {
      if ($_PLG_MULTIFAQ['replace_homepage'])
          $thetitle_url .= $_CONF['site_url']  . '/';
     else
          $thetitle_url .= '.';
      $thetitle = COM_createLink($thetitle, $thetitle_url);
    }   
    $display .= COM_startBlock($thetitle);

    $display .= "\n<div" . plg_mfaq_needed_direction() . " class=\"mfaq-tree\">";
    if ($_PLG_MULTIFAQ["javascript"]) {

        function toggleall($spanid, $block, $description) {
            if ($spanid)
                  $spanid = "true";
             else
                  $spanid = "false";
             if ($block)
                  $block = "true";
             else
                  $block = "false";

             return "<u><font color=blue class=\"clickable_faq_navigation\"
onclick=\"toggleAll($spanid, $block); return false\">[$description]</font></u>";
        }
    }

        $display .= LB . '
<center>
';

    if (!COM_isAnonUser() || $_CONF['searchloginrequired'] < 2) {
           $selected = array('phrase', 'all', 'any');
            foreach ($selected as $key => $value) {
                unset($selected[$key]);
                if (!empty($getstype) && $value == $getstype)
                   $selected[$value] = ' selected="selected"';
                else
                    $selected[$value] = '';
             }
        $display .= '
<form action="'. $_CONF['site_url'] . '/multifaq/" method="get">
';
        if (!$_PLG_MULTIFAQ["expand_all"])
            $display .= '<input type="hidden" name="id" value="' . $gettopic . '">';
        $display .= '
<input type="hidden" name="what" value="' . $gettype . '">
<input type="text" name="query" maxlength=20 value=\'' . $searchterms . '\'>
';
        if (!COM_isAnonUser() || $_CONF['searchloginrequired'] == 0)
           $display .= '<br><select name="stype" class="internalsearch">
<option value="phrase"' . $selected['phrase'] . '>' . $LANG09['43'] . '</option>
<option value="all"' . $selected['all'] . '>' . $LANG09['44'] . '</option>
<option value="any"' . $selected['any'] . '>' . $LANG09['45'] . '</option>
</select>
';
        $display .= '<br><input type="submit" value="' . $LANG_MULTIFAQ['faq_search'];
        if (!$_PLG_MULTIFAQ["expand_all"])
           $display .= " {$LANG_MULTIFAQ['this_topic']}: {this topic}";
        $display .= '">';
        if (!$_PLG_MULTIFAQ["expand_all"] && (!COM_isAnonUser() || $_CONF['searchloginrequired'] == 0 ))
           $display .= '
<br><input type="button" name="searchall" value="' . $LANG_MULTIFAQ['faq_search_global'] . '" onclick="' . "window.location.href('{$_CONF['site_url']}/search.php?query=' + encodeURIComponent(query.value).replace(/%20/g, '+') + '&amp;keyType=' + stype.value + '&amp;type={$_PLG_MULTIFAQ["pi_name"]}&amp;mode=search')" . '">';
        $display .= '
</form>
';
    }

    if ($_PLG_MULTIFAQ["javascript"])
        $display .= '
<b>' . $LANG_MULTIFAQ['dynamic_navigation'] . '</b>' . LB . '<br>' .
toggleall(true, false, $LANG_MULTIFAQ['expand_all']) . LB . '<br>' .
toggleall(false, false, $LANG_MULTIFAQ['collapse_all']) . LB . '<br>' .
toggleall(true, true, $LANG_MULTIFAQ['expand_topics']) . LB . '<br>' .
toggleall(false, true, $LANG_MULTIFAQ['collapse_topics']) . LB;

    $display .= "\n</center>\n{found_searchterms}";

    $class = 'mfaq-tree-';
    $subclass = $class . 'question';
    $class .= 'topic-';
    $class_closed = $class . 'closed';

        if (!empty($searchterms)) {
            $sql = "SELECT {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_questions']}.t_id as topic_id FROM {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_questions']} LEFT JOIN {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_trans']} ON q_id=e_id WHERE type='q' AND l_id=$l_id";
            if (!$_PLG_MULTIFAQ["expand_all"])
                $sql .= " AND {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_questions']}.t_id='$gettopic'";
            $sql .= " AND ($searchterms_sql)" . COM_getPermSQL("AND") . " GROUP BY topic_id";
            $result_search = DB_query($sql);
            $nrows_search = DB_numRows($result_search);
            if ($nrows_search > 0) {
                $levels = array_flip($_PLG_MULTIFAQ['allowedtopics']);
                for ($i=0; $i<$nrows_search; $i++) {
                    $A = DB_fetchArray($result_search);
                    $searchable_level = $levels[$A['topic_id']];
                    if (in_array($searchable_level, $levels))
                        foreach ($levels as $topic_id => $level)
                             if (strpos($searchable_level, $level) !== false) {
                                 $allowedtopics[$level] = $topic_id;
                                 unset($levels[$topic_id]);
                             }
                }
                if (!isset($allowedtopics))
                  $nrows_search = 0;
            }
        } else
            $allowedtopics = $_PLG_MULTIFAQ['allowedtopics'];

    $searchmatches = 0;
   if (!isset($nrows_search) || $nrows_search > 0)
    foreach ($allowedtopics as $level => $topic_id) {

       // Show topic if showing all topics, or it's a root topic or a direct (1 level down) sub-topic
       if (!($_PLG_MULTIFAQ["expand_all"] || strlen($level) / 3 == 1 || strpos($getlevel, $level) !== false || (strpos($level, $getlevel) !== false && strlen($level) / 3 <= (strlen($getlevel) / 3) + 1)))
            continue;

        list($topic, $description) = plg_mfaq_gettrans($topic_id, 't');     # get translations
        if (empty($topic))
          $topic = $LANG_MULTIFAQ['empty_field'] . "  " . plg_mfaq_getLanguage();
        $topic = "&nbsp;$topic";

       $openclose = 'closed';
       if ($_PLG_MULTIFAQ["expand_all"] || $level == $getlevel)
         $openclose = 'open';
       $count = strlen($level) / 3;
       for ($x = 0; $x < $count; $x++) {
          if (!$x)
             $display .= "\n\n";
          $display .= "<ul class=\"$class_closed\">";
          if ($x == $count-1)
              $display .= "<li class=\"$class$openclose\">";
       }

        if (!empty($description)) {
            $description=" <span class=\"topic-description\">$description</span>";
            $topic .= ' - ' . $description;
        }

        $editlink = '';
        $checkaccess = plg_mfaq_checkaccess($t_id, 't', 'edit', true, $l_id);
        if ((is_array($checkaccess) && in_array($t_id, $checkaccess)) || $checkaccess)
            $editlink = plg_mfaq_editlink("topic", $topic_id);
        if ($_PLG_MULTIFAQ["javascript"] && ($_PLG_MULTIFAQ["expand_all"] || $topic_id == $gettopic))
                  $link = "<h2 class=\"clickable_faq\" onclick=\"toggle('topic$topic_id', false); return false\">$topic</h2>$editlink";
        elseif ($_PLG_MULTIFAQ["expand_all"] || $topic_id==$gettopic)
                  $link="<h2>$topic$editlink</h2>";
        else { // Links for sub-topics
                  $url = str_replace('{topic_id}', $topic_id, $topic_url);
                  if (!empty($searchterms)) {
                    $url .= $searchurl;
                    $url_post = $searchurl_terms;
                  }
                  $url = COM_buildUrl ($url) . $url_post;
                  $link = "<h2>" . COM_createLink($topic, $url) . $editlink . "</h2>";
        }

       $display .= $link;

       $question_output = '';

        # display available questions for this topic
        if (($topic_id == $gettopic) or ($_PLG_MULTIFAQ["expand_all"])) {
            $question_sql = "SELECT * FROM {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_questions']} LEFT JOIN {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_trans']} ON q_id=e_id WHERE {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_questions']}.t_id='$topic_id' AND type='q' AND l_id=$l_id AND field1 != ''" . COM_getPermSQL("AND") . " ORDER BY q_order asc;";
            $result_q = DB_query($question_sql,1);
            $noquestions = 0;
            for ($j=0; $j<DB_numRows($result_q); $j++) {
                $B = DB_fetchArray($result_q);
                list($question, $answer) = plg_mfaq_gettrans($B['q_id'], 'q');     # get translations
                if (!$_PLG_MULTIFAQ["javascript"])
                    $url = str_replace('{question_id}', $B['q_id'], $question_url);

                if (!empty($searchterms)) {
                    $show_question = false;
                    $show_answer = false;
                    list($temp_question, $temp_answer) = plg_mfaq_highlight($question, $answer, $searchterms, $getstype);
                    // If the question matches the search terms
                    if ($question <> $temp_question) {
                        $question = $temp_question;
                        $show_question = true;
                    }
                    if ($answer <> $temp_answer) {
                        $answer = $temp_answer;
                        $show_answer = true;
                    }
                   // Skip the question if neither it nor its answer contain the search terms
                   if (!$show_question && !$show_answer) {
                       $noquestions += 1;
                       continue;
                   } else {
                      $searchmatches += 1;
                      if (!$_PLG_MULTIFAQ["javascript"]) {
                          $url .= $question_url_post . $searchurl;
                          $url_post = $searchurl_terms;
                      }
                   }
                }

                $question_output .= "\n<li class=\"$subclass\">";

                if ($_PLG_MULTIFAQ["javascript"])
                    $question_output .= "<u><font color=blue class=\"clickable_faq\" onclick=\"toggle('question{$B['q_id']}', true); return false\">" . $question . "</font></u>";
                else
                    $question_output .= COM_createLink($question, COM_buildUrl($url) . $url_post);

                if (plg_mfaq_checkaccess($B['q_id'], 'q', 'edit', false, $l_id))
                    $question_output .= plg_mfaq_editlink("question", $B['q_id']);
                $question_output .= '</li>';

                if ($_PLG_MULTIFAQ["javascript"])
                    $question_output .= "\n<div class=\"toggleA\" id=\"question{$B['q_id']}\"><p>$answer</p></div>";
            }
        }

        if (!empty($question_output) && $noquestions < $j) {
            $display .= "\n";
            if ($_PLG_MULTIFAQ["javascript"])
                $display .= "<div id=\"topic$topic_id\">\n";
            $display .= "<ul class=\"$subclass\">\n$question_output\n\n</ul>";
            if ($_PLG_MULTIFAQ["javascript"])
                $display .= "\n</div>\n";
        }

       for ($x = 0; $x < $count; $x++) {
         if (!$x)
            $display .= "</li>";
         $display .= "</ul>";
       } 
    }

    list($topic, ) = plg_mfaq_gettrans($gettopic, 't');

    if (!$_PLG_MULTIFAQ["expand_all"])
        $display = str_replace('{this topic}', $topic, $display);

    if (!empty($searchterms)) {
        $searchresults = '<br>' . sprintf($LANG_MULTIFAQ['search_results'], $searchmatches) . ' ' . $LANG_MULTIFAQ['faq_contain'] . " <b>$searchterms</b>";
        if (!$_PLG_MULTIFAQ["expand_all"]) {
            $url = str_replace('{topic_id}', $gettopic, $topic_url);
            $url = COM_buildUrl($url);
            $link = COM_createLink($topic, $url);
            $searchresults .= " {$LANG_MULTIFAQ['this_topic']}: $link";
        }
        $searchresults .= '.';
        $display = str_replace('{found_searchterms}', $searchresults, $display);
    } else
        $display = str_replace('{found_searchterms}', '', $display);

    if ($_PLG_MULTIFAQ["javascript"] && !empty($searchterms) && $searchmatches > 0 && $searchmatches <= $_PLG_MULTIFAQ['javascript_search_open_count'])
        $display .= "\n\n<script>
toggleAll(true, false)
</script>";

    $display .= "\n\n</div>" . plg_mfaq_language_selection();
    $display .= LB . LB . COM_endBlock();

// custom code - start
    $PLG_MFAQ_HEADER = $LANG_MULTIFAQ['plugin'];
    if (!empty($topic) && !$_PLG_MULTIFAQ["expand_all"]) {
        $bracket = "&gt;";
// custom code - end
        $stringpath .= " " . $bracket ." ". $topic;
       $PLG_MFAQ_HEADER .= " " . $bracket . " " . $topic;
    }

    return $display;
}

function plg_mfaq_getLanguageid($get_default = false) {
    global $_TABLES, $_CONF, $_PLG_MULTIFAQ;

    if ($get_default || DB_count($_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_lang'], "language", $_CONF['language']) == 0 || !DB_getItem($_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_lang'], "is_open", "language='{$_CONF['language']}'"))
        $relevant_translation = DB_getItem($_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_lang'], "l_id", "is_default=1");
    else
        $relevant_translation = DB_getItem($_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_lang'], "l_id", "language='{$_CONF['language']}'");
    return $relevant_translation;
}

function plg_mfaq_getLanguage($get_default = false)
{
// custom code - start
    global $_TABLES, $_CONF, $_PLG_MULTIFAQ;

    if ($get_default && is_numeric($get_default))
        $relevant_translation = DB_getItem($_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_lang'], "language", "l_id=$get_default");
    elseif ($get_default || DB_count($_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_lang'], "language", $_CONF['language']) == 0 || !DB_getItem($_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_lang'], "is_open", "language='{$_CONF['language']}'"))
        $relevant_translation = DB_getItem($_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_lang'], "language", "is_default=1");
    else
        $relevant_translation = $_CONF['language'];

    return $relevant_translation;

// custom code - end
}

function plg_mfaq_getLanguageTag($langtag = '')
{
global $_CONF, $_TABLES, $_PLG_MULTIFAQ;

    if (!is_array($_CONF['language_files']))
        return '';

    if (!empty($langtag)) {
        // If specifying just a language shortcut and not a whole language name
        if (is_numeric($langtag)) // If specifying a language ID
             $langtag = DB_getItem($_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_lang'], 'language', "l_id=$langtag");
        elseif (strlen($langtag) == strlen('xy') && !isset($_CONF['language_files'][$langtag]))
                $langtag = '';
        if (!empty($langtag) && strlen($langtag) > strlen('xy')) {
            if (!in_array($langtag, $_CONF['language_files']))
                $langtag = '';
            else {
                $language_files = array_flip($_CONF['language_files']);
                $langtag = $language_files[$langtag];
                }
        }
    } else {
        $langtag = plg_mfaq_getLanguage();
        if (in_array($langtag, $_CONF['language_files'])) {
            $language_files = array_flip($_CONF['language_files']);
            $langtag = $language_files[$langtag];
        } else
             $langtag = '';
    }

     if (!empty($langtag))
         $langtag = '_' . $langtag;

    return $langtag;
}

function plg_mfaq_needed_direction($href = false) {
    global $_TABLES, $_CONF, $LANG_DIRECTION;
    if (!$href)
        $needed_direction = '';
    else
        $needed_direction = array();
    if (plg_mfaq_getLanguage() <> $_CONF['language']) {
        list($direction, ) = plg_mfaq_choose_direction("");
        if ((empty($LANG_DIRECTION) && $direction == "rtl") || (!empty($LANG_DIRECTION) && $LANG_DIRECTION <> $direction)) {
              if (!$href)
                  $needed_direction = " dir=\"$direction\"";
              else
                  $needed_direction = array("dir" => $direction);
        }
    }
    return $needed_direction;
}

function plg_mfaq_needed_align() {
    global $_TABLES;
    $needed_align = '';
    list($direction, $align) = plg_mfaq_choose_direction();
    if ($direction == "rtl")
             	$needed_align = " align=\"$align\"";
    return $needed_align;
}

function plg_mfaq_language_selection() {
    global $LANG_MULTIFAQ, $_CONF, $_TABLES, $LANG_DIRECTION, $_PLG_MULTIFAQ;

    $retval = "";

// If the site disallows changing languages or if it's not even needed
    if ($_CONF['allow_user_language'] == 0 || plg_mfaq_getLanguage() == $_CONF['language'])
          return $retval;

    $sql = "SELECT language FROM {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_lang']}";
    $result = DB_query($sql);
    for ($i=0; $i<DB_numRows($result); $i++) {
          $A = DB_fetchArray($result);
          $language[] = $A['language'];
    }

// If the site generally supports multilinguality
    if (is_array($_CONF['language_files'])) {
          $array_intersect = array_intersect($_CONF['language_files'], $language);
          if (!empty($array_intersect))
                        $quick_switch = phpblock_switch_language();
    }

// If the site supports multilinguality with languages that MultiFAQ has translations for
    if (isset($quick_switch) && !empty($quick_switch)) {
          $reverse_languages = array_flip($_CONF['languages']);
          $retval .= $LANG_MULTIFAQ['no_quick_translations'];
          if (strpos($quick_switch, "form") === false) {
                        if (in_array($_CONF['language_files'][$reverse_languages[strip_tags($quick_switch)]], $language))
		    $retval .= " (" . $quick_switch . ").";
          } elseif (count($array_intersect) == 1) {
                        $backup_language_files = $_CONF['language_files'];
                        $backup_languages = $_CONF['languages'];
                        $_CONF['language_files'] = $array_intersect;
                        $_CONF['language_files'][] = "";
                        $array_intersect_key = array_keys($array_intersect);
                        $array_intersect_key = $array_intersect_key[0];
                        $_CONF['languages'] = array($array_intersect_key => $_CONF['languages'][$array_intersect_key], "");
                        $retval .= " (" . phpblock_switch_language() . ").";
                        $_CONF['language_files'] = $backup_language_files;
                        $_CONF['languages'] = $backup_languages;
          } else {
                        $retval .= ".\n<br>" . $LANG_MULTIFAQ['all_quick_translations'] . ":". LB;
                        $quick_switch = str_replace(' selected="selected"', '', $quick_switch);
                        foreach ($_CONF['languages'] as $key => $value) {
		    if (!in_array($_CONF['language_files'][$key], $language))
                                                $quick_switch = str_replace("<option value=\"$key\">$value</option>\n", '', $quick_switch);
		    if ($_CONF['language_files'][$key] == plg_mfaq_getLanguage(true)) {
                                                if (!empty($LANG_DIRECTION) && $LANG_DIRECTION == "rtl")
      		         		$newvalue = "$value *";
                                                else
               			$newvalue = "* $value";
                                                $quick_switch = str_replace("\"$key\"", "\"$key\" selected=\"selected\"", $quick_switch);
                                                $quick_switch = str_replace($value, $newvalue, $quick_switch);
		    }
                        }
                        $retval .= $quick_switch;
                        $retval .= "* " . $LANG_MULTIFAQ['the_default_translation'] . LB;
          }

    }

// Show languages that the user can change to manually and see their MultiFAQ translations
    if (!isset($_CONF['language_files']) || (isset($array_intersect) && 
count($language) > count($array_intersect))) {
        if (isset($quick_switch))
            $manual_languages .= "<br>";
        $manual_languages .= "{$LANG_MULTIFAQ['manual_translations']}:<select";
        if ($LANG_DIRECTION <> 'ltr')
            $manual_languages .= ' dir="ltr"';
        $manual_languages .= '>';
        $all_languages = MBYTE_languageList(COM_getCharset());
        if (isset($_CONF['language_files']) && !empty($_CONF['language_files']))
            $temp_language_files = $_CONF['language_files'];
        else
            $temp_language_files = array();
        foreach( $language as $key => $value )
            if (in_array($value, array_flip($all_languages)) && !in_array($value, $temp_language_files)) {
            	$manual_languages .= "<option>$all_languages[$value]</option>" . LB;
             	unset($all_languages[$value]);
        }
        $manual_languages .= "</select>" . LB;
    }

    if (isset($manual_languages) && strpos($manual_languages, "</option>") !== false)
        $retval .= $manual_languages;

    $retval = '
<hr>
' . $retval;

    return $retval ;
}

function plg_mfaq_highlight($question, $answer, $searchterms, $searchtype) {
    global $_PLG_MULTIFAQ;
// Dummy replacements
    $start = "\v\v";
    $end = "\f\f";
// Real replacements
    $start_real = '<font color=red><b>';
    $end_real = '</b></font>';

    $before = "/(?!(?:[^<]+>|[^>]+<\/a>))\b";
    $after = "\b/i";
    if ($searchterms <> utf8_encode($searchterms)) {
         if (@preg_match('/^\pL$/u', urldecode('%C3%B1'))) { // Unicode property support
              $before = "/(?<!\p{L})";
              $after = "(?!\p{L})/u";
         } else {
              $before = "/";
              $after = "/u";
         }
    }

    if ($searchtype == 'phrase') {
        $specialspace = '[\"\'\\\?\=\+\&\`\~\!\@\#\$\%\^\*\(\)\;\,\.\/\_\-\:]';
        $searchterms = preg_replace('/\s+/', "(\s|\s$specialspace|$specialspace\s)", preg_quote($searchterms));
        $question = preg_replace($before . $searchterms . $after, $start . "\\0" . $end, $question);
        $answer = preg_replace($before . $searchterms . $after, $start . "\\0" . $end, $answer);
    } else {
        $match_all = true;
        $searchterms = explode(' ', $searchterms);
        $question_temp = $question;
        $answer_temp = $answer;
        foreach ($searchterms as $value) {
                list($question_temp2, $answer_temp2) = plg_mfaq_highlight($question_temp, $answer_temp, $value, 'phrase');
                // If neither the question nor the answer match all search terms
                if ($searchtype == 'all' && $question_temp == $question_temp2 && $answer_temp == $answer_temp2) {
                     $match_all = false;
                     break;
                } else {
                     $question_temp = $question_temp2;
                     $answer_temp = $answer_temp2;
               }
        }
        if ($match_all) {
                     $question = $question_temp;
                     $answer = $answer_temp;
        }
    }

    $question = preg_replace("/" . $start . "/", $start_real, $question);
    $answer = preg_replace("/" . $start . "/", $start_real, $answer);
    $question = preg_replace("/" . $end . "/", $end_real, $question);
    $answer = preg_replace("/" . $end . "/", $end_real, $answer);

    return array($question, $answer, $end_real);
}

function plg_mfaq_preparetext($content) {

    $content = addslashes (COM_checkHTML (COM_checkWords ($content)));
     
    return $content;
}

function plg_mfaq_querycheckfortable($table, $negative=false) {
global $_DB_dbms;

    $not = '';
    if ($negative)
         $not = ' not';
    $query_line = 'if' . $not . ' exists';
    $result_mysql = ' ';
    $result_mssql = '';

    if ($_DB_dbms == 'mysql') {
        if ($negative)
             $result_mysql = $result_mysql . strtoupper($query_line) . $result_mysql;
        else
             $result_mysql = $result_mysql;
    } else
        $result_mssql = $query_line . " (select * from sysobjects where name = '$table')\n";

    return array($result_mysql, $result_mssql);
}

function plg_mfaq_choosecommentcode($commentcode, $number_in_array = '') {
global $LANG_MULTIFAQ;
   $retval = '';

    if (!empty($number_in_array) && is_numeric($number_in_array))
       $number_in_array = '[' . $number_in_array . ']';

    $selected = array(0, -1, 1);
    foreach ($selected as $key => $value) {
        unset($selected[$key]);
        if ($value == $commentcode)
               $selected[$value] = ' selected="selected"';
        else
               $selected[$value] = '';
    }

   $retval .= "<select name=\"commentcode$number_in_array\">
<option value=\"0\"{$selected[0]}>{$LANG_MULTIFAQ['comments_enabled']}</option>
<option value=\"-1\"{$selected[-1]}>{$LANG_MULTIFAQ['comments_disabled']}</option>
<option value=\"1\"{$selected[1]}>{$LANG_MULTIFAQ['comments_closed']}</option>
</select>
";

   return $retval;
}

function plg_mfaq_setDefaultPermissions($group_id = '', $e_id=0, $l_id=0, $type=false) {
global $_USER, $_GROUPS, $_TABLES, $_PLG_MULTIFAQ;

    if (!is_numeric($e_id) || $e_id > 0) {
        $lang_sql = "SELECT * FROM {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_trans']} WHERE e_id='$e_id' AND l_id=$l_id AND type='$type'";
        $lang_result = DB_query($lang_sql,1);
        $T = DB_fetchArray($lang_result, false);
        foreach ($T as $key=>$value) {
              if ($key == 'commentcode')
                    break;
              unset($T[$key]);
        }
    } else {
        $T['is_open'] = '1';
        $T['commentcode'] = $_PLG_MULTIFAQ['default_commentcode'];
        $T['owner_id'] = $_USER['uid'];
        if ($group_id)
            $T['group_id'] = $group_id;
        else {
            if (isset ($_GROUPS[$_PLG_MULTIFAQ['pi_name'] . ' editor'])) {
                  $T['group_id'] = $_GROUPS[$_PLG_MULTIFAQ['pi_name'] . ' editor'];
            } else {
                $T['group_id'] = SEC_getFeatureGroup ($_PLG_MULTIFAQ['pi_name'] . '.edit');
            }
        }
        SEC_setDefaultPermissions ($T, $_PLG_MULTIFAQ['default_permissions']);
    }

  return $T;
}

function plg_mfaq_replace_tablefields($tablelayout, $method, $postarray = 0, $extra_fields = '') {

    $date_value = "NOW()";
    if (is_array($extra_fields) && $extra_fields['type'] == 'q') {
       list($question, $answer) = plg_mfaq_gettrans($_POST['old_id'], $extra_fields['type'], $extra_fields['l_id'], true, true);
       if ($question <> $_POST['field1'][$extra_fields['l_id']] || $answer <> $_POST['field2'][$extra_fields['l_id']])
           $extra_fields['changedate'] = $date_value;
    }

    for ($i = 0; $i < count($tablelayout); $i++) {
       if ($postarray == 0 && isset($_POST[$tablelayout[$i]]))
           $$tablelayout[$i] = $_POST[$tablelayout[$i]];
       elseif ($postarray > 0 && isset($_POST[$tablelayout[$i]][$postarray])) {
           $$tablelayout[$i] = $_POST[$tablelayout[$i]][$postarray];
           if ($i < 2)
                $$tablelayout[$i] = plg_mfaq_preparetext($$tablelayout[$i]);
       } else
          $$tablelayout[$i] = 0;
    }

    list($perm_owner,$perm_group,$perm_members,$perm_anon) = SEC_getPermissionValues($perm_owner,$perm_group,$perm_members,$perm_anon);

    if ($method == 'insert') {
         $tablelayout1 = '(';
         $tablelayout2 = ' VALUES(';
         if (is_array($extra_fields))
              foreach ($extra_fields as $key=>$value) {
                   $tablelayout1 .= "`" . $key . "`, ";
                   if (!is_numeric($value) && $value<>$date_value)
                      $tablelayout2 .= "'";
                   $tablelayout2 .= $value;
                   if (!is_numeric($value) && $value<>$date_value)
                      $tablelayout2 .= "'";
                   $tablelayout2 .= ", ";
             }
    } elseif ($method == 'update') {
         $tablelayout1 = 'SET ';
         $tablelayout2 = '';
         if (is_array($extra_fields))
              foreach ($extra_fields as $key=>$value) {
                   $tablelayout1 .= "`" . $key . "`=";
                   if (!is_numeric($value) && $value<>$date_value)
                      $tablelayout1 .= "'";
                   $tablelayout1 .= $value;
                   if (!is_numeric($value) && $value<>$date_value)
                      $tablelayout1 .= "'";
                   $tablelayout1 .= ", ";
             }
    }

    for ($i = 0; $i < count($tablelayout); $i++) {
        if ($method == 'insert') {
           $tablelayout1 .= "`" . $tablelayout[$i] . "`";
           if (!is_numeric($$tablelayout[$i]))
                $tablelayout2 .= "'";
           $tablelayout2 .= $$tablelayout[$i];
           if (!is_numeric($$tablelayout[$i]))
                $tablelayout2 .= "'";
        } elseif ($method == 'update') {
           $tablelayout1 .= "`" . $tablelayout[$i] . "`=";
           if (!is_numeric($$tablelayout[$i]))
               $tablelayout1 .= "'";
           $tablelayout1 .= $$tablelayout[$i];
          if (!is_numeric($$tablelayout[$i]))
               $tablelayout1 .= "'";
        }
        if ($i < (count($tablelayout)-1)) {
             $tablelayout1 .= ', ';
             if ($method == 'insert')
                 $tablelayout2 .= ', ';
       } elseif ($method == 'insert') {
                $tablelayout1 .= ')';
                $tablelayout2 .= ')';
       }
   }

    $tablelayout = $tablelayout1 . $tablelayout2;

    return $tablelayout;
}

function plg_mfaq_checkaccess($item_id, $type, $requirement, $checkparents=false, $l_id='', $uid = 0, $perlanguage = false) {
global $_TABLES, $_PLG_MULTIFAQ;

    $retval = false;

    if ($requirement == 'read')
        $requirement = 2;
    elseif ($requirement == 'edit')
        $requirement = 3;

// Immediate approval for roots, unless a tree structure is needed
    if (!(!$item_id && $type == 't' && $requirement == 2 && $checkparents && $l_id <> 'any') && SEC_inGroup('Root'))
       return true;

    if (empty($l_id))
       $l_id = plg_mfaq_getLanguageid();

   $levels = '';
  
  if ($checkparents && $item_id) {
        $level = DB_getItem($_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_topics'], "level", "topic_id='$item_id'");
        $levelcount = plg_mfaq_get_depth($level);
        for ($i = 1; $i < $levelcount; $i++) {
           $level = substr($level, 0, -3);
           $levels .= " OR level='$level'";
        }
    }
    
$secquery = COM_getPermSQL("AND", $uid, $requirement);
    $groupby = " GROUP BY e_id";
      $sql = "SELECT * FROM {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut']  . '_trans']} ";
      if ($type == 't')
         $sql .= "LEFT JOIN {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_topics']} ON e_id=topic_id ";
      $sql .= "WHERE type='$type' AND ";
      if ($checkparents && !$item_id)
          $sql .= "LENGTH(LEVEL)=3";
      elseif ($l_id <> 'any')
          $sql .= "l_id=$l_id AND ";
      if ($perlanguage)
          $sql .= " AND l_id=$l_id";
      if ($type == 't' && !empty($levels))
           $sql .= "(";
      if (!($checkparents && !$item_id))
           $sql .= "e_id='$item_id'";
      if ($type == 't' && !empty($levels))
           $sql .= $levels . ')';
      $sql_sec = $sql . $secquery .$groupby;
      if ($checkparents && !$item_id)
          $sql_sec .= " ORDER BY level";
      $sql .= $groupby;
      if ($type == 'q' || ($checkparents && !$item_id))
          $result = DB_query($sql_sec);
      else
          $result = DB_query($sql);

      if (DB_numRows($result) > 0) {
          if ($type == 'q')
             $retval = true;
          elseif (!($checkparents && !$item_id)) {
             $result_sec = DB_query($sql_sec);
             if (DB_numRows($result) == DB_numRows($result_sec))
                $retval = true;
          } else {
             for ($i=0; $i<DB_numRows($result); $i++) {
                $level = DB_fetchArray($result);
                $alltopicids[$level['level']] = $level['topic_id'];
                $levels[] = $level['level'];
             }
             foreach ($levels as $value) {
                $sql_temp = "SELECT topic_id, level FROM {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut']  . '_topics']} WHERE level != $value AND level LIKE '$value%' ORDER BY level";
                $result = DB_query($sql_temp);
                for ($i=0; $i<DB_numRows($result); $i++) {
                     $A = DB_fetchArray($result);
                     if (plg_mfaq_checkaccess($A['topic_id'], 't', $requirement, false, $l_id))
                         $alltopicids[$A['level']] = $A['topic_id'];
                     else
                         break;
                }
             }
                $retval = $alltopicids;
          }
      }

    return $retval;
}

function plg_mfaq_list_topics($t_id, $all = false) { # display a list of topics
global $LANG09, $_TABLES, $_PLG_MULTIFAQ, $LANG_MULTIFAQ;

    # topic dropdown
    $topic_sql = "SELECT * FROM {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_topics']} ORDER BY level;";
    $topic_result = DB_query($topic_sql, 1);
    $drop_topic .= "<select";
    if ($all) $drop_topic .= ' onchange="this.form.submit()"';
    if (!SEC_hasRights($_PLG_MULTIFAQ["pi_name"] . '.admin'))
       $drop_topic .= " disabled";
    $drop_topic .= " " . plg_mfaq_needed_direction() . " name=\"topic_id\">\n";
// custom code - start
    if ($all) {
           $tl_id = 0;
           $topic = $LANG09[9];
           if ($tl_id == $t_id)
               $sel=" selected";
           $drop_topic .= "<option value=\"$tl_id\"$sel>$gap$topic</option>\n";
        }
// custom code - end
    for ($i=0; $i<DB_numRows($topic_result); $i++) {
        $gap = "";
        $sel = "";
        $B = DB_fetchArray($topic_result);
        $tl_id = $B['topic_id'];
// custom code - start
        if (is_array($_PLG_MULTIFAQ['editabletopics']) && !in_array($tl_id, $_PLG_MULTIFAQ['editabletopics']))
            continue;
        list($topic, ) = plg_mfaq_gettrans($tl_id, 't', false, true);
        if (empty($topic))
           $topic = $LANG_MULTIFAQ['empty_field'] . "  " . plg_mfaq_getLanguage();
// custom code - end
        $level = $B['level'];
        if ($tl_id == $t_id)
            $sel=" selected";
        elseif (!SEC_hasRights($_PLG_MULTIFAQ["pi_name"] . '.admin'))
            continue;
        for ($j=3; $j<strlen($level); $j++) {
            $gap.="&nbsp;";
        }
        $drop_topic .= "<option value=\"$tl_id\"$sel>$gap$topic</option>\n";
    }
    $drop_topic .= "</select>";

    return $drop_topic;
}

function plg_mfaq_reorder($what_table, $theorder, $what_field, $what_extrafield = false, $topic_id = false) {
    global $_TABLES, $_PLG_MULTIFAQ;

    $where = '';
    $sqlclause = '';

    $sqlclause .= "$theorder asc";
    if ($what_extrafield) {
        $sqlclause = $what_extrafield . " asc, " . $sqlclause;
    }
    $sqlclause = "ORDER BY $sqlclause";
    if ($topic_id && $what_extrafield) {
       $sqlclause = "WHERE $what_extrafield='$topic_id' $sqlclause";
       $what_extrafield = '';
    }

    $sql = "SELECT * FROM {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . "_" . $what_table]} $sqlclause;";
    $result = DB_query($sql);
    $nrows = DB_numRows($result);

    $lastside = 0;
    $blockOrd = 10;
    $stepNumber = 10;

    for ($i = 0; $i < $nrows; $i++) {
        $A = DB_fetchArray($result);

        if ($what_extrafield && $lastside > 0 && $lastside != $A[$what_extrafield]) {
            $blockOrd = 10;              // so start with 10 again
        }
        if ($A[$theorder] != $blockOrd) {  // only update incorrect ones
            $q = "UPDATE {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . "_" . $what_table]} SET $theorder = '" .
                  $blockOrd . "' WHERE $what_field = '" . $A[$what_field] ."'";
          DB_query($q);
        }
        $blockOrd += $stepNumber;
        if ($what_extrafield)
           $lastside = $A[$what_extrafield];       // save variable for next round
    }
}

function plg_mfaq_minimizeid($table) {
global $_DB_dbms;

    if ($_DB_dbms == 'mysql')
       $sql = "alter table `$table` auto_increment=1";
/*
    else
       $sql = "alter table $table add mycolumn bigint identity(1, 1)";
*/

     if (isset($sql))
        DB_query($sql,1);
}

function plg_mfaq_siteFooter() {
    global $LANG_MULTIFAQ, $_PLG_MULTIFAQ;

    $retval = "\n<br /><center>" . COM_createLink("{$LANG_MULTIFAQ['menu_label']} &copy; {$_PLG_MULTIFAQ["pi_url"]}", $_PLG_MULTIFAQ["pi_url"]) . "</center><br />\n";;

    return $retval;
}

function plg_mfaq_neworder($t_id) {
global $_TABLES, $_PLG_MULTIFAQ;

    if ($_PLG_MULTIFAQ['new_at_end']) {
          $sql = "SELECT max(q_order) as q_order from {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_questions']} where `t_id`='$t_id'";
          $result = DB_query($sql);
          $result = DB_fetchArray($result);
          $neworder = ($result['q_order'] + 1);
    } else
      $neworder = 1;

    return $neworder;
}

function plg_mfaq_editlink($item_name, $item_id, $image = false) {
global $_CONF, $_IMAGE_TYPE, $LANG01, $_PLG_MULTIFAQ;

    $display = '';

    if ((!$text_pre && !$_PLG_MULTIFAQ["tree_edit_links"]) || !SEC_hasRights($_PLG_MULTIFAQ['pi_name'] . '.admin'))
       return '';

    if (!$image) {
        $text_pre = ' <small><span class="item-description">';
        $text_post = '</span>';
        $editihtml = $LANG01[4];
    } else {
        $text_pre = '<sup>';
        $text_post = str_replace("<", "</", $text_pre);
        $editicon = $_CONF['layout_url'] . '/images/edit.' . $_IMAGE_TYPE;
        $editihtml = '<img src="' . $editicon . '" alt="' . $LANG01[4] . '" title="' . $LANG01[4] . '"' . XHTML . '>';
    }

    if (!$image) {
        $text_pre .= '[';
        $text_post .= ']</small>';
    }

    if ($item_name == 'question')
        $item_idname = 'q';
    else
        $item_idname = $item_name;

    $display .= $text_pre . COM_createLink($editihtml, "{$_CONF['site_admin_url']}/plugins/multifaq/index.php?plg_mfaq_action=plg_mfaq_edit_$item_name&amp;{$item_idname}_id=$item_id") . $text_post . LB;

    return $display;
}

function plg_mfaq_continuetree($count) {

    $retval = '';

    for ($x = 0; $x < $count; $x++) {
         if (!$x)
            $retval .= "</li>";
         $retval .= "</ul>";
    } 

    return $retval;
}

function plg_mfaq_search_perm($searchterms, $getstype) {
global $_CONF;

// If an anonyous user got here through an internal site search
    if (!empty($searchterms) && COM_isAnonUser()) {
       if ($_CONF['searchloginrequired'] == 2)
           $searchterms = '';
       elseif ($_CONF['searchloginrequired'] == 1)
           $nochoice = true;
    }

// If no search was done or anonymous users must use search defaults
    if (empty($getstype) || (isset($nochoice) && $nochoice)) {
       if (floatval (VERSION) < 1.6)
           $getstype = 'phrase';
       else
           $getstype = $_CONF['search_def_keytype'];
    }

    return array($searchterms, $getstype);
}

function plg_mfaq_sitemap($upgrade = false) {
global $_PLG_MULTIFAQ, $_XMLSMAP_CONF;

    $type = $_PLG_MULTIFAQ["pi_name"];
    if (function_exists('plugin_pluginstatechange_xmlsitemap'))
       if (!$upgrade || !in_array($type, $_XMLSMAP_CONF['types']))
          plugin_pluginstatechange_xmlsitemap($type, 'installed');
}

function plg_mfaq_sitegui($plugin_name, $message) {
global $_CONF;

    $display = '';

    $display .= '
<form method="post" action="' . $_CONF['site_admin_url'] . '/configuration.php">
<input type=hidden name="conf_group" value="' . $plugin_name . '">
<input type=submit value="' . $message . '">
</form>';

    return $display;
}

function plg_mfaq_finalecho($display) {
   if (function_exists(COM_output))
      COM_output($display);
   else
      echo $display;
}
?>
Return current item: Geeklog Plugins, Static Pages and Blocks