Location: PHPKode > projects > Geeklog Plugins, Static Pages and Blocks > multifaq/functions.inc
<?php
//
// +---------------------------------------------------------------------------+
// | Multilingual FAQ Plugin           |
// +---------------------------------------------------------------------------+
// | functions.inc - all core functionality                                    |
// +---------------------------------------------------------------------------+
// | 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.           |
// |                                                                           |
// +---------------------------------------------------------------------------+
//

// custom code - start
// Needs to be declared so user functions could use it in global
$PLG_MFAQ_HEADER = '';
$langtag = '';
// custom code - end

// You can edit the following line
$_PLG_MULTIFAQ["multifaq_pic"] = $_CONF['site_url'] . "/multifaq/images/faq.gif";

// There should be no need to edit information below this point.
$_PLG_MULTIFAQ['plugin_shortcut'] = plugin_shortcut_multifaq(); // Inject another shortcut

function plugin_shortcut_multifaq($default = 'mfaq') {
    return $default;
}

$_PLG_MULTIFAQ["pi_name"]    = 'multifaq';
$_PLG_MULTIFAQ["pi_version"] = '3.1.8';
$_PLG_MULTIFAQ["gl_version"] = '1.4.1';
$_PLG_MULTIFAQ["pi_url"]     = 'http://gl-plg-multifaq.sourceforge.net';

$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_lang']      = $_DB_table_prefix . $_PLG_MULTIFAQ['plugin_shortcut'] . '_lang';
$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_questions'] = $_DB_table_prefix . $_PLG_MULTIFAQ['plugin_shortcut'] . '_questions';
$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_topics']    = $_DB_table_prefix . $_PLG_MULTIFAQ['plugin_shortcut'] . '_topics';
$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_trans']     = $_DB_table_prefix . $_PLG_MULTIFAQ['plugin_shortcut'] .  '_trans';
$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_link']      = $_DB_table_prefix . $_PLG_MULTIFAQ['plugin_shortcut'] .'_link';

$_PLG_MULTIFAQ['base_path'] = $_CONF['path'] . 'plugins/' . $_PLG_MULTIFAQ['pi_name'] . '/';

require_once($_PLG_MULTIFAQ['base_path'] . 'functions-advanced.inc');

/**
* Language file Include
*/
$langfile = $_PLG_MULTIFAQ['base_path'] . "language/{$_CONF['language']}.php";

if (file_exists ($langfile)) {
    include_once ($langfile);
} else {
// custom code - start
    include_once ($_PLG_MULTIFAQ['base_path'] . 'language/english.php');
// custom code - end
}

// Load the plugin's config
if (isset($config)) {
    $my_config = config::get_instance();
    if ($my_config->group_exists($_PLG_MULTIFAQ['pi_name']))
       $_PLG_MULTIFAQ = $_PLG_MULTIFAQ + $my_config->get_config($_PLG_MULTIFAQ['pi_name']);
} else {
    require_once($_PLG_MULTIFAQ['base_path'] . 'config.php');
}

if (DB_getItem($_TABLES['plugins'], 'pi_enabled', "pi_name = '{$_PLG_MULTIFAQ["pi_name"]}'")) {
// If what's new is enabled, or viewing the plugin's regular pages, or viewing site stats
if (!$_PLG_MULTIFAQ["hide_whatsnew"] || (substr_count($_SERVER["PHP_SELF"], $_PLG_MULTIFAQ["pi_name"]) > 0 && substr_count($_SERVER["PHP_SELF"], 'admin/plugins') == 0) || substr_count($_SERVER["PHP_SELF"], 'stats') > 0) {
     $topic_id = '';
     // If refreshing comment view
     if (empty($getitem) && empty($gettype) && isset($_POST['id_comment'])) {
         $refreshed_comments=true;
         $_GET['id'] = $_POST['id_comment'];
         $_GET['what'] = 'question';
     }
     if (!$_PLG_MULTIFAQ["show_recent"] && !$_PLG_MULTIFAQ["show_top_x"]) {
         if (!isset($refreshed_comments))
             COM_setArgNames (array ('id', 'what', 'stype', 'searchall'));
         $gettype = COM_applyFilter (COM_getArgument ('what'));
         $getitem = COM_applyFilter (COM_getArgument ('id'));
         if (is_array($_CONF['language_files']))
              $getitem = substr($getitem, 0, -strlen('_xy'));
         if (!empty($getitem) and (empty($gettype) or ($gettype=='question'))) # one certain question has been called
             $topic_id = DB_getItem($_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_questions'], "t_id", "q_id='$getitem'");
     }
     $_PLG_MULTIFAQ['allowedtopics'] = plg_mfaq_checkaccess($topic_id, 't', 'read', true, plg_mfaq_getLanguageid());
     if (is_array($_PLG_MULTIFAQ['allowedtopics']))
         ksort($_PLG_MULTIFAQ['allowedtopics'], SORT_STRING);
}

if (substr_count($_SERVER["PHP_SELF"], $_PLG_MULTIFAQ["pi_name"]) > 0 && substr_count($_SERVER["PHP_SELF"], 'admin/plugins') > 0) {
     $topic_id = '';
     if (isset($_REQUEST['topic_id']) && !isset($_REQUEST['q_id']) && $_REQUEST['topic_id'] > 0)
         $topic_id = $_REQUEST['topic_id'];
     $_PLG_MULTIFAQ['editabletopics'] = plg_mfaq_checkaccess($topic_id, 't', 'edit', true, 'any');
     if (is_array($_PLG_MULTIFAQ['editabletopics']))
         ksort($_PLG_MULTIFAQ['editabletopics'], SORT_STRING);
     if ($topic_id > 0 && (!$_PLG_MULTIFAQ['editabletopics'] || is_array($_PLG_MULTIFAQ['editabletopics']) && !in_array($topic_id, $_PLG_MULTIFAQ['editabletopics'])))
         plg_mfaq_checkright('null', "administer without having access to topics");
}
}

// +---------------------------------------------------------------------------+
// | Geeklog Plugin API Implementations                                        |
// +---------------------------------------------------------------------------+

/**
* Returns the items for this plugin that should appear on the main menu
*
* NOTE: this MUST return the url/value pairs in the following format
* $<arrayname>[<label>] = <url>
*
* Universal Plugin:  Uncomment and fill in variables;
*
* @return    array   Associative array of menu items to be added to menu
*
*/
function plugin_getmenuitems_multifaq() {
    global $_CONF, $LANG_MULTIFAQ, $_PLG_MULTIFAQ;

    $menulabel = $LANG_MULTIFAQ['menu_label'];                // Put your menu label here
    $menurul = $_CONF['site_url'] . "/multifaq/index.php";     // Menu url here

    $menuitems = array();
    # if (SEC_hasRights($_PLG_MULTIFAQ["pi_name"] . '.view')) {
        $menuitems["$menulabel"] = $menurul;
    # }
    return $menuitems;
}

/**
* Called by the plugin Editor to display the current plugin code version
* This may be different than the version installed and registered currently.
* If newer then you may want to run the update
*
* @return   string  version number
*
*/
function plugin_chkVersion_multifaq ()
{
    global $_PLG_MULTIFAQ;
    return $_PLG_MULTIFAQ["pi_version"];
}

/**
 * Saving a comment
 *
 * @param   string  $title  comment title
 * @param   string  $comment comment text
 * @param   string  $id     Item id to which $cid belongs
 * @param   int     $pid    comment parent
 * @param   string  $postmode 'html' or 'text'
 * @return  mixed   false for failure, HTML string (redirect?) for success
 */
function plugin_savecomment_multifaq($title, $comment, $id, $pid, $postmode) {
global $_PLG_MULTIFAQ, $_CONF, $_TABLES, $LANG03, $_USER;

    $retval = '';

    if (is_array($_CONF['language_files']))
        $l_id = DB_getItem ($_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_lang'], 'l_id', "language='{$_CONF['language_files'][substr($id, -strlen('_xy')+strlen('_'))]}'");

    $commentcode = DB_getItem ($_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_trans'], 'commentcode', "e_id='$id' AND l_id='$l_id'");
    if ($commentcode != 0) {
        return COM_refresh ($_CONF['site_url'] . '/index.php');
    }

    $ret = CMT_saveComment ($title, $comment, $id, $pid, $_PLG_MULTIFAQ['pi_name'], $postmode);

    list($url) = PLG_getCommentUrlId($_PLG_MULTIFAQ["pi_name"]);
    $retval .= COM_refresh(COM_buildUrl("$url?id=$id"));

    return $retval;
}

/**
 * delete a comment
 *
 * @param   int     $cid    Comment to be deleted
 * @param   string  $id     Item id to which $cid belongs
 * @return  mixed   false for failure, HTML string (redirect?) for success
 */
function plugin_deletecomment_multifaq($cid, $id) {
global $_PLG_MULTIFAQ, $_CONF, $_TABLES, $_USER;
    $retval = '';

    $has_editPermissions = SEC_hasRights ($_PLG_MULTIFAQ["pi_name"] . '.admin');
    $real_id = explode('_', $id);
    $langtag = plg_mfaq_getLanguageTag(array_pop($real_id));
    $real_id = implode('_', $real_id);

/*
    $result = DB_query ("SELECT owner_id,group_id,perm_owner,perm_group,perm_members,perm_anon FROM {$_TABLES['polltopics']} WHERE pid = '{$real_id}'");
    $A = DB_fetchArray ($result);
*/

    if ($has_editPermissions) {
/*
 && SEC_hasAccess ($A['owner_id'],
            $A['group_id'], $A['perm_owner'], $A['perm_group'],
            $A['perm_members'], $A['perm_anon']) == 3) {
*/
        CMT_deleteComment($cid, $id, $_PLG_MULTIFAQ['pi_name']);
        $retval .= COM_refresh(COM_buildUrl($_CONF['site_url']
                                 . "/{$_PLG_MULTIFAQ['pi_name']}/index.php?id=$real_id" . $langtag));
    } else {
        COM_errorLog ("User {$_USER['username']} (IP: {$_SERVER['REMOTE_ADDR']}) "
                    . "tried to illegally delete comment $cid from {$_PLG_MULTIFAQ['pi_name']} $id");
          list($url) = PLG_getCommentUrlId($_PLG_MULTIFAQ["pi_name"]);
          $retval .= COM_refresh(COM_buildUrl("$url?id=$id"));
    }

    return $retval;
}

/**
* Plugin should display [a] comment[s]
*
* @param   string  $id     Unique idenifier for item comment belongs to
* @param   int     $cid    Comment id to display (possibly including sub-comments)
* @param   string  $title  Page/comment title
* @param   string  $order  'ASC' or 'DESC' or blank
* @param   string  $format 'threaded', 'nested', or 'flat'
* @param   int     $page   Page number of comments to display
* @param   boolean $view   True to view comment (by cid), false to display (by $pid)
* @return  mixed   results of calling the plugin_displaycomment_ function
*/
function plugin_displaycomment_multifaq($id, $cid, $title, $order, $format, $page, $view) {
global $_CONF, $_PLG_MULTIFAQ;

     $display = '';
    $dynamic_values = array('order' => 'order', 'mode' => 'format');
    foreach ($dynamic_values as $key=>$value)
        if (is_null($$value)) {
           if (isset($_POST[$key]))
              $$value = $_POST[$key];
           else
              $$value = '';
        }

    if (is_null($cid)) $cid=0;
    if (is_null($page)) $page=1;
    if (is_null($view)) $view=false;

//    $real_id = substr($id, 0, strrpos($id, '_'));
    list(, , $commentcode) = plg_mfaq_gettrans($id, 'q', '', true);
    if (SEC_hasRights($_PLG_MULTIFAQ['pi_name'] . '.admin'))
          $delete_option = true;
     else
          $delete_option = false;

    if ($commentcode > -1) {
          if (floatval (VERSION) < 1.4)
              $display .= COM_userComments($id, $title, $_PLG_MULTIFAQ['pi_name'], $order, $format, $cid ,$page ,$view, $delete_option);
          else {
              require_once $_CONF['path_system'] . 'lib-comment.php';
              $display .= CMT_userComments($id, $title, $_PLG_MULTIFAQ['pi_name'], $order, $format, $cid, $page, $view, $delete_option, $commentcode);
          }
     }

     return $display;
}

/*
    global $_TABLES, $LANG_ACCESS;

    list(, , $commentcode) = plg_mfaq_gettrans($id, 'q', '', true);
    $retval .= plg_mfaq_commenthelper($commentcode, $id, $title, $order, $format, $cid, $page, $view);
*/
/*
    $sql = "SELECT COUNT(*) AS count, commentcode, owner_id, group_id, perm_owner, "
        . "perm_group, perm_members, perm_anon "
        . "FROM {$_TABLES['polltopics']} "
        . "WHERE (pid = '$id')" . COM_getPermSQL('AND')
        . ' GROUP BY pid';
    $result = DB_query ($sql);
    $A = DB_fetchArray ($result);
    $allowed = $A['count'];

    if ($allowed == 1) {
        $delete_option = (SEC_hasRights ('polls.edit') &&
                (SEC_hasAccess ($A['owner_id'], $A['group_id'],
                    $A['perm_owner'], $A['perm_group'], $A['perm_members'],
                    $A['perm_anon']) == 3));
        $retval .= CMT_userComments ($id, $title, 'polls', $order, $format,
                                     $cid, $page, $view, $delete_option,
                                     $A['commentcode']);
    } else {
        $retval .= COM_startBlock ($LANG_ACCESS['accessdenied'], '',
                        COM_getBlockTemplate ('_msg_block', 'header'))
                . $LANG_ACCESS['storydenialmsg']
                . COM_endBlock (COM_getBlockTemplate ('_msg_block', 'footer'));
    }

    return $retval;
}
*/

/**
* Check to see if this Plugin uses comments
*
* Geeklog is checking to see if this plugin supports comments, tell it no!
* NOTE: to support comments you must use the same date/time based ID for your
* widget.  In other words, to make primary keys for your plugin you should call
* makesid().  Comments are keyed off of that...it is a limitation on how geeklog
* does comments.
*
* @return   boolean true or false
*
*/
function plugin_commentsupport_multifaq() {
    return false;
}

/**
* User has reuqested to create a comment for the plugin
* Redirects user to comment form if initial comment for plugin record or returns
* formated HTML including the Site footer and the comments
*
* @param        int      $comment_id      GL Comment table primary key.
* @param        string   $commentmode     Has user selected a new comment preview mode (Flat, Nested, Threaded, None)
* @param        string   $order           Has the user selected a different comment first (Newest or Oldest comment first)
* @param        string   $reply           Has the user used the reply button on the Comment Bar
* @return        string     Formated HTML containing site footer and the comments with the comment command bar
*                        or redirect user to create top level comment
*/
/**
function plugin_commentform_multifaq($comment_id,$commentmode='',$order='',$reply='') {
    global $_CONF,$_TABLES,$_FM_TABLES;

    // Pass the comment type - use the plugin name
    $type="multifaq";
    // Recommended Comment ID is to use the plugin_name and a ID that links back to your plugin record.
    // In this case, I need to parse out the Plugin Record ID
    $file_id = substr($comment_id,9, strlen($comment_id-9));
    // Determine if there are existing comments for this plugin record
    $commentCount = DB_count($_TABLES['comments'],'sid',$comment_id);
    $title = DB_getItem($_FM_TABLES['multifaq'],'title',"lid=$file_id");
    // Was the comment mode passed - if not default it.
    if ($commentmode == "") {
        $commentmode = $_CONF['comment_mode'];
    }
      // Has the user selected a new comment order using the Comment Bar
    if ($order == "") {
        $order="ASC";
    }
    // If this is the first comment or someone used the reply button on the comment header bar
    if ($commentCount == 0 || $reply != "") {
        $story=$comment_id;
        $pid=0;
        $type="multifaq";
        echo COM_refresh($_CONF['site_url'] . "/comment.php?sid=$comment_id&amp;pid=$pid&amp;type=$type");
    } else {
        $display = COM_siteHeader();
        // Optionally call a plugin function to return a formated view of the Plugin record so it's displayed above the comments
        # $display .= plugin_commentparent_multifaq($file_id);
        // Return the formated comment records with the Comment Header and active reply links
        $display .=    COM_userComments($comment_id,$title,$type,$order,$commentmode);
        $display .= COM_siteFooter();
    }
    return $display;
}

**/
/**
* Shows the statistics for the plugin on stats.php.  If
* $showsitestats is 1 then we are to only print the overall stats in the 'site
* statistics' box otherwise we show the detailed stats for the plugin
*
* Universal Plugin:  Modify/uncomment use it
*
* @param    int showsitestate   Flag to let us know which stats to get
* @return   string  returns formatted HTML to insert in stats page
*
*/
function plugin_showstats_multifaq($showsitestats) {
    global $_CONF, $_TABLES, $_USER, $LANG_MULTIFAQ, $_PLG_MULTIFAQ;
    $retval = '';

// custom code - start
    if (!$_PLG_MULTIFAQ['allowedtopics'] || !$_PLG_MULTIFAQ["show_top_x"])
        return '';
// custom code - end

    require_once ($_CONF['path_system'] . 'lib-admin.php');

    $l_id = plg_mfaq_getLanguageid();
// custom code - start
    $sql = "SELECT e_id, hits, {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_questions']}.t_id from {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_trans']} LEFT JOIN {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_questions']} ON e_id=q_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 = DB_query ($sql);
    $nrows  = DB_numRows ($result);
    if ($nrows > 0) {
        $header_arr = array(
            array('text'         => $LANG_MULTIFAQ['stats_questions'],
                  'field'        => 'question',
                  'header_class' => 'stats-header-title'
            ),
            array('text'         => $LANG_MULTIFAQ['stats_hits'],
                  'field'        => 'hits',
                  'header_class' => 'stats-header-count',
                  'field_class'  => 'stats-list-count'
            )
        );
        $data_arr = array();
        $text_arr = array('has_menu' => false,
                          'title'    => $LANG_MULTIFAQ['stats_title'],
        );
        for ($i = 0; $i < $nrows; $i++) {
            $A = DB_fetchArray ($result);
            $t_id = $A['t_id'];
            $q_id = $A['e_id'];
// custom code - start
             if (is_array($_PLG_MULTIFAQ['allowedtopics']) && !in_array($t_id, $_PLG_MULTIFAQ['allowedtopics']))
               continue;
            list($question,) = plg_mfaq_gettrans($q_id, 'q');
            $langtag = plg_mfaq_getLanguageTag();
            $url = COM_buildUrl ($_CONF['site_url']
                     . "/multifaq/index.php?id=" . $q_id. $langtag);
            $q_id = COM_createLink($question, $url, array_merge(array("title" => $question), plg_mfaq_needed_direction(true)));
// custom code - end
            $hits = COM_numberFormat ($A['hits']);
            $data_arr[] = array('title' => $question,
                                'question' => $q_id,
                                'hits' => $hits
                          );
        }
        $retval .= ADMIN_simpleList ('', $header_arr, $text_arr, $data_arr);
    } else {
        $retval .= COM_startBlock ($LANG_MULTIFAQ['stats_title']);
        $retval .= $LANG_MULTIFAQ['stats_no_hits'];
        $retval .= COM_endBlock ();
    }

    return $retval;
}
/**
* New stats plugin API function for proper integration with the site stats
*
* @return   array(item text, item count);
*
*/
function plugin_statssummary_multifaq () {
    global $LANG_MULTIFAQ, $_TABLES, $_PLG_MULTIFAQ;

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

    $total_questions = 0;
    $total_clicks = 0;
    foreach ($l_id as $key=>$value) {
       $total_lang_questions = 0;
       $total_lang_clicks = 0;
// custom code - start
       $sql = "SELECT e_id, hits, {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_questions']}.t_id from {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_trans']} LEFT JOIN {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_questions']} ON e_id=q_id WHERE {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_questions']}.t_id IS NOT NULL AND l_id=$key" . COM_getPermSQL("AND");

       if ($key <> plg_mfaq_getLanguageid())
           $allowedtopics = $_PLG_MULTIFAQ['allowedtopics'];
       else
           $allowedtopics = plg_mfaq_checkaccess('', 't', 'read', true, $key);
        if (!$allowedtopics)
          continue '';

// custom code - end
       $result = DB_query($sql);
       for ($i=0; $i<DB_numRows($result); $i++) {
          $A = DB_fetchArray($result);
          $t_id = $A['t_id'];
          $q_id = $A['e_id'];

           if (is_array($allowedtopics) && !in_array($t_id, $allowedtopics))
             continue;

          $total_lang_questions++;
          $total_questions++;
          if (!empty($A['hits']) && $A['hits'] > 0) {
               $total_lang_clicks += $A['hits'];
               $total_clicks += $A['hits'];
          }
       }
       $item_count[$key] = COM_NumberFormat ($total_lang_questions)
                . ' (' . COM_NumberFormat ($total_lang_clicks) . ')';
    }

    $statsarray[] = array(sprintf($LANG_MULTIFAQ['faq_questions'], ''), COM_NumberFormat ($total_questions)
                . ' (' . COM_NumberFormat ($total_clicks) . ')');

    foreach ($item_count as $key=>$value) {
           $all_languages = MBYTE_languageList(COM_getCharset());
           $statsarray[] = array(sprintf($LANG_MULTIFAQ['faq_questions'],  $all_languages[plg_mfaq_getLanguage($key)] . ' '), $value);
    }

return $statsarray;
}


/**
* This will put an option for the plugin in the command and control block on moderation.php
*
* Add the plugin name, icon and link to the command and control block in moderation.php
*
* @return   array   Array containing (plugin name, admin url, url of plugin icon)
*
*/
function plugin_cclabel_multifaq() {
    global $_CONF, $LANG_MULTIFAQ;
    return array($LANG_MULTIFAQ['admin_label'],$_CONF['site_admin_url'] . '/plugins/multifaq/index.php',$_CONF['site_url'] . '/multifaq/images/multifaq.gif');
}

/**
* Returns the administrative option for this plugin
*
* Adds the plugin to the Admin menu
*
* Universal Plugin:  Modify/Uncomment use it
*
* @return   array   Array containing (plugin name, plugin admin url, # of items in plugin or '')
*
*/
function plugin_getadminoption_multifaq() {
    global $_CONF, $_TABLES, $LANG_MULTIFAQ, $_PLG_MULTIFAQ;

    $count = DB_count($_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_questions']);
    if (SEC_hasRights($_PLG_MULTIFAQ["pi_name"] . '.edit')) {
        return array($LANG_MULTIFAQ['admin_label'], $_CONF['site_admin_url'] . '/plugins/multifaq/index.php', $count);
    }
}

/**
* Returns the user option for this plugin
*
* Adds the plugin to the user menu
*
* Universal Plugin:  modify/uncomment use it
*
* @return   array   Array containing (plugin name, plugin user url, 0)
*
*/
function plugin_getuseroption_multifaq() {
//    global $_CONF;

//    if (SEC_hasRights('multifaq.edit,multifaq.view','OR')) {
//        return array('multifaq', $_CONF['site_url'] . '/multifaq/index.php', 0);
//    }
}


/**
* Geeklog is asking us to provide any new items that show up in the type drop-down
* on search.php.  Let's let users search!
*
*/
function plugin_searchtypes_multifaq() {
    global $LANG_MULTIFAQ, $_PLG_MULTIFAQ;
    $tmp[$_PLG_MULTIFAQ["pi_name"]] = $LANG_MULTIFAQ['search_type'];
    return $tmp;
}

/**
* this searches for pages matching the user query and returns an array of
* for the header and table rows back to search.php where it will be formated and
* printed
*
* @query            string          Keywords user is looking for
* @datestart        date/time       Start date to get results for
* @dateend          date/time       End date to get results for
* @topic            string          The topic they were searching in
* @type             string          Type of items they are searching
* @author           string          Get all results by this author
*
*/
function plugin_dopluginsearch_multifaq($query, $datestart, $dateend, $topic, $type, $author, $keyType) {
    global $_TABLES, $_CONF, $LANG_MULTIFAQ, $_PLG_MULTIFAQ;

    if (!$_PLG_MULTIFAQ['allowedtopics'])
        return '';

    if (empty($type)) {
        $type = 'all';
    }

    // Bail if we aren't supppose to do our search
// custom code - start
    $langtag = plg_mfaq_getLanguageTag();

    if (floatval (VERSION) >= 1.6)
       $query = trim(addslashes($query));
    if ($type <> 'all' AND $type <> $_PLG_MULTIFAQ["pi_name"]) {
     if (floatval (VERSION) < 1.6) {
// custom code - end
        $plugin_results = new Plugin();
        $plugin_results->plugin_name = $_PLG_MULTIFAQ["pi_name"];
        $plugin_results->searchlabel = $LANG_MULTIFAQ['search_type'] . $LANG_MULTIFAQ['results'];
// custom code - start 
     } else $plugin_results = '';
// custom code - end
        return $plugin_results;
    }

    // For Geeklog < 1.6
    if (!empty($query) && empty($keyType))
          $keyType = 'phrase';

    // Build search SQL
    $l_id = plg_mfaq_getLanguageid();
// custom code - start
  if (floatval (VERSION) < 1.6) {
// custom code - end
    $sql = "SELECT UNIX_TIMESTAMP(changedate) as unixdate, e_id, hits, {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_questions']}.t_id from {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_trans']} LEFT JOIN {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_questions']} ON e_id=q_id WHERE {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_questions']}.t_id IS NOT NULL AND l_id=$l_id" . COM_getPermSQL("AND");
    $result = DB_query($sql);
// custom code - start
  } else {
    $needed_direction_pre = plg_mfaq_needed_direction();
    $needed_direction_post = '';
    if (!empty($needed_direction_pre)) {
        $needed_direction_pre = '<span' . $needed_direction_pre . '>';
        $needed_direction_post = '</span>';
    }
    $sql = "SELECT e_id AS id, field1 AS title, field2 AS description, UNIX_TIMESTAMP(changedate) as date, owner_id AS uid, hits, CONCAT('/multifaq/index.php?id=', e_id, '$langtag&what=question&stype=$keyType') AS url FROM {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_trans']} WHERE type='q' AND l_id=$l_id" . COM_getPermSQL("AND") . " ";
  }

// custom code - start
  if (!empty ($author)) {
      $sql .= "AND (owner_id = '$author') ";
  }
// custom code - start

  if (!empty($datestart) && !empty($dateend)) {
        $delim = substr($datestart, 4, 1);
        if (!empty($delim)) {
            $DS = explode($delim, $datestart);
            $DE = explode($delim, $dateend);
            $startdate = mktime(0,0,0,$DS[1],$DS[2],$DS[0]);
            $enddate = mktime(23,59,59,$DE[1],$DE[2],$DE[0]);
            $sql .= " AND (UNIX_TIMESTAMP(changedate) BETWEEN '$startdate' AND '$enddate') ";
        }
  }
// custom code - end

    // OK, now create new plugin object and insert table header labels
// custom code - start
  if (floatval (VERSION) < 1.6) {
// custom code - end
    $plugin_results = new Plugin();
    $plugin_results->plugin_name = $_PLG_MULTIFAQ["pi_name"];
    $plugin_results->searchlabel = $LANG_MULTIFAQ['search_type'] . "-" .$LANG_MULTIFAQ['results'];
// custom code - start
    $plugin_results->addSearchHeading($LANG_MULTIFAQ['topic']);
// custom code - end
    $plugin_results->addSearchHeading($LANG_MULTIFAQ['question']);
// custom code - start
    $plugin_results->addSearchHeading($LANG_MULTIFAQ['answer']);
// custom code - end
    $plugin_results->addSearchHeading($LANG_MULTIFAQ['changedate']);
    $plugin_results->addSearchHeading($LANG_MULTIFAQ['hitsmsg']);
// custom code - start
  } else {
    $search = new SearchCriteria($_PLG_MULTIFAQ["pi_name"], $LANG_MULTIFAQ['plugin']);
    $columns = array('title' => 'field1', 'description' => 'field2');
    list($sql,$ftsql) = $search->buildSearchSQL($keyType, $query, $columns, $sql);
    $search->setSQL($sql);
    $search->setFTSQL($ftsql);
    $search->setRank(4);
    $search->setURLRewrite(true);
    return $search;
  }
// custom code - end

  if (floatval (VERSION) < 1.6) {
    $mycount = DB_numRows($result);

// custom code - start
    if ($mycount > 0) {
        $direction = plg_mfaq_needed_direction();
        $align = plg_mfaq_needed_align();
    }
// custom code - end

    // NOTE if any of your data items need to be links then add them here!
    // make sure data elements are in an array and in the same order as your
    // headings above!
    for ($i = 1; $i <= $mycount; $i++) {
        // Get text to search
        # get ev. translations
        global $_USER, $_CONF;
        $A =DB_fetchArray($result);
        $t_id = $A['t_id'];
        $q_id = $A['e_id'];
// custom code - start
             if (is_array($_PLG_MULTIFAQ['allowedtopics']) && !in_array($t_id, $_PLG_MULTIFAQ['allowedtopics']))
               continue;
        list($topic_name,) = plg_mfaq_gettrans($t_id, 't');
        $topic_name = "<div" . $align . $direction . ">" . $topic_name . "</div>";
// custom code - end
        $hits = $A['hits'];
        $changedate = COM_getUserDateTimeFormat($A['unixdate']);
        $changedate = $changedate[0];
// custom code - start
        list($question, $answer) = plg_mfaq_gettrans($q_id, 'q');
        # translation end
        // Search it
        $searchterms = '';
        if (!empty($query))
               $searchterms = "&amp;what=question&amp;type=$keyType";
        $url = COM_buildUrl ($_CONF['site_url']
                 . "/multifaq/index.php?id=$q_id" . $langtag . $searchterms);
        if (!empty($searchterms)) {
           if (strpos($answer, '?') !== false)
              $url .= '&amp';
           else
              $url .= '?';
           $url .= 'query=' . urlencode($query);
        }
         if (!empty($query)) {
               $show_question = true;
               $show_answer = true;
               list($temp_question, $temp_answer, $pointofreplacement) = plg_mfaq_highlight($question, $answer, $query, $keyType);
              if ($question == $temp_question)
                    $show_question = false;
              else
                    $question = $temp_question;
              if ($answer == $temp_answer)
                    $show_answer = false;
              else
                    $answer = $temp_answer;
             if (!$show_question && !$show_answer)
                    continue;
                if (strpos($answer, $pointofreplacement) === false) {
	                $breakPosition = strpos($answer,"\r\n\r\n");
	                if (($breakPosition > 0) AND ($breakPosition < strlen($answer)) AND 1)
	                $answer = mb_substr($answer, 0,$breakPosition);
                }
        } else
                $answer = strip_tags(mb_substr($answer, 0, 60)) . '...';
        $rcnt++;
        $answer = "<div" . $align . $direction . ">" . $answer . "</div>";
        $question = "<div" . $align . $direction . ">" . COM_createLink($question, $url) . "</div>";
        $row = array($topic_name, $question, $answer, $changedate, $hits);
        $plugin_results->addSearchResult($row);
    }
    $plugin_results->num_searchresults = $rcnt;
    $plugin_results->num_itemssearched = DB_count($_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_questions']);
    return $plugin_results;
  }

}

function plugin_whatsnewsupported_multifaq() {
    global $_PLG_MULTIFAQ, $LANG_MULTIFAQ, $LANG_WHATSNEW;

    if ( $_PLG_MULTIFAQ["hide_whatsnew"] == 0 ) {
        $retval = array(
            $LANG_MULTIFAQ['new_faqs'],
            COM_formatTimeString( $LANG_WHATSNEW['new_last'],
            $_PLG_MULTIFAQ["new_faq_interval"] )
        );
    } else {
        $retval = false;
    }

    return $retval;
}

function plugin_getwhatsnew_multifaq() {
    global $_CONF, $_TABLES, $_USER, $_PLG_MULTIFAQ, $LANG_MULTIFAQ;

    if (!$_PLG_MULTIFAQ['allowedtopics'])
        return $LANG_MULTIFAQ['no_new_faq'];

    $l_id = plg_mfaq_getLanguageid();
// custom code - start
    $sql = "SELECT changedate, e_id, {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_questions']}.t_id from {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_trans']} LEFT JOIN {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_questions']} ON e_id=q_id WHERE {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_questions']}.t_id IS NOT NULL AND l_id=$l_id AND ";
// custom code - end
    $now = time();
    $desired = $now - $_PLG_MULTIFAQ['new_faq_interval'];
// custom code - start
    $sql .= "UNIX_TIMESTAMP(changedate) > {$desired}" . COM_getPermSQL("AND") . " ORDER by changedate DESC LIMIT 15";
// custom code - end
    $result = DB_query ($sql);
    $nrows = DB_numRows ($result);

    if ($nrows == 0) {
        $newqa = $LANG_MULTIFAQ['no_new_faq'];
    } else {
        $newqa = array();
        for ($i = 0; $i < $nrows; $i++) {
            $A = DB_fetchArray($result);
            $t_id = $A['t_id'];
            $q_id = $A['e_id'];
             if (is_array($_PLG_MULTIFAQ['allowedtopics']) && !in_array($t_id, $_PLG_MULTIFAQ['allowedtopics']))
               continue;
            list($question,) = plg_mfaq_gettrans($q_id, 'q');     # get translations
            $langtag = plg_mfaq_getLanguageTag();
            $url = COM_buildUrl ($_CONF['site_url']
                . "/multifaq/index.php?id=$q_id" . $langtag);
// custom code - start
            if (strlen ($question) > 30)
                $question_trim = mb_substr($question, 0, 30) . '...';
            $newqa[] = COM_createLink($question_trim, $url, array_merge(array("title" => $question), plg_mfaq_needed_direction(true)));
// custom code - end
        }
    }
    return $newqa;
}

function plugin_getheadercode_multifaq() {
    global $_PLG_MULTIFAQ, $_CONF;
    $str = '';

    // use the CSS if "not dynamic" or if we are on the plugin's pages
    if ($_PLG_MULTIFAQ['replace_homepage'] || !$_PLG_MULTIFAQ['dynamic_css'] || substr_count($_SERVER["PHP_SELF"], $_PLG_MULTIFAQ["pi_name"]) >0) {
        $str .= LB . "<link rel=\"stylesheet\" type=\"text/css\" "
             . "href=\"{$_CONF['site_url']}/multifaq/multifaq.css\">";
    }

    if ($_PLG_MULTIFAQ['javascript'] && (substr_count($_SERVER["PHP_SELF"], $_PLG_MULTIFAQ["pi_name"]) >0 || $_PLG_MULTIFAQ['replace_homepage']))
        $str .= LB . '<script type="text/javascript" src="' . $_CONF['site_url'] . '/multifaq/dynamic_navigation.js"></script>';

    return $str;
}

function plugin_autouninstall_multifaq() {
    global $_PLG_MULTIFAQ, $_TABLES, $_DB_dbms;

    $pi_name = $_PLG_MULTIFAQ['pi_name'];

    foreach($_TABLES as $key => $value)
          if (substr($key, 0, strlen($_PLG_MULTIFAQ['plugin_shortcut'] . '_')) == $_PLG_MULTIFAQ['plugin_shortcut'] . '_') {
                 if ($key == $_PLG_MULTIFAQ['plugin_shortcut'] . '_link') {
                       COM_errorLog ("Dropping table {$_TABLES[$key]}", 1);
                       DB_query ("DROP TABLE {$_TABLES[$key]}", 1);
                       COM_errorLog ('...success', 1);
                 } else
                        $thetables[] = $key;
          }

    $out = array (
        /* give the name of the tables, without $_TABLES[] */
        'tables' => $thetables,
        /* give the full name of the group, as in the db */
        'groups' => array(ucfirst($pi_name) . ' Admin', ucfirst($pi_name) . ' Editor'),
        /* give the full name of the feature, as in the db */
        'features' => array($pi_name . '.admin', $pi_name . '.edit'),
        /* give the full name of the block, including 'phpblock_', etc */
//        'php_blocks' => array('phpblock_' . $pi_name),
        /* give all vars with their name */
//        'vars'=> array($pi_name . '_gid')
    );
    return $out;
}

/**
* Loads the configuration records for the GL Online Config Manager
* 
* @return   boolean     true = proceed with install, false = an error occured
* 
*/
function plugin_load_configuration() {
    global $_CONF, $_PLG_MULTIFAQ;

    require_once $_CONF['path_system'] . 'classes/config.class.php';
    require_once $_PLG_MULTIFAQ['base_path'] . 'install_defaults.php'; 

    return plugin_initconfig_multifaq($_MULTIFAQ_DEFAULT);
}

function plugin_upgrade_multifaq() {
    global $_PLG_MULTIFAQ, $_TABLES;

$pi_name = $_PLG_MULTIFAQ["pi_name"];
$pi_version = $_PLG_MULTIFAQ["pi_version"];
$gl_version = $_PLG_MULTIFAQ["gl_version"];
$pi_url = $_PLG_MULTIFAQ["pi_url"];

$pi_name_editor = ucfirst($pi_name) . ' Editor';

    // Load the online configuration records
    if (function_exists('plugin_load_configuration')) {
        if (!plugin_load_configuration()) {
            PLG_uninstall($pi_name);

            return false;
        } else {
            $my_config = config::get_instance();
            if ($my_config->group_exists($_PLG_MULTIFAQ['pi_name']))
               $_PLG_MULTIFAQ = $_PLG_MULTIFAQ + $my_config->get_config($_PLG_MULTIFAQ['pi_name']);
        }
    }

$perm = plg_mfaq_setDefaultPermissions();

// Versions that can be upgraded from
$UP_1_0["insert_level_field"]="ALTER TABLE " . $_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_topics'] . " ADD `level` TEXT NOT NULL AFTER `topic`;";
$UP_1_0["update_level_values"]="UPDATE " . $_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_topics'] . " SET `level`='001';";

$UP_2_1["update_chanedate_fieldtype"]="ALTER TABLE " . $_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_questions'] . " CHANGE `changedate` `changedate` VARCHAR( 14 ) DEFAULT NULL";

$UP_2_2b["insert_translator_field"]="ALTER TABLE " . $_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_lang'] . " ADD `uid` int(11) NOT NULL default '0' AFTER `language`;";

$UP_2_2RC2["add_direction_field"] = "ALTER TABLE {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_lang']} ADD `direction` ENUM('ltr', 'rtl') NOT NULL DEFAULT 'ltr' AFTER `language`;";

$UP_3_0RC1["add_group"]="INSERT INTO {$_TABLES['groups']} (grp_name, grp_descr) VALUES ('$pi_name_editor', 'Users in this group can edit $pi_name items');";
$UP_3_0RC1["add_group_assignment"]="INSERT INTO {$_TABLES['group_assignments']} VALUES (" . DB_getItem($_TABLES['groups'], 'grp_id', "grp_name='$pi_name_editor'") . ", NULL, 1);";
$UP_3_0RC1["del_var"]="DELETE FROM {$_TABLES['vars']} WHERE name='{$pi_name}_gid';";
$UP_3_0RC1["fix_access"]="UPDATE {$_TABLES['access']} SET `acc_grp_id`=" . DB_getItem($_TABLES['groups'], 'grp_id', "grp_name='$pi_name_editor'") . " WHERE `acc_ft_id`=" . DB_getItem($_TABLES['features'], 'ft_id', "ft_name='$pi_name.view'") . ";";
$UP_3_0RC1["fix_feature"]="UPDATE {$_TABLES['features']} SET `ft_name`='$pi_name.edit', `ft_descr`='$pi_name_editor' WHERE `ft_id`=" . DB_getItem($_TABLES['features'], 'ft_id', "ft_name='$pi_name.view'") . ";";
$UP_3_0RC1["less_ids"] = "ALTER TABLE {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_lang']} CHANGE `l_id` `l_id` TINYINT(3) NOT NULL AUTO_INCREMENT";
$UP_3_0RC1["add_default_translation"] = "ALTER TABLE {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_lang']} ADD `is_default` tinyint(1) NOT NULL default '0';";
$UP_3_0RC1["set_default_translation"]="UPDATE " . $_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_lang'] . " SET `is_default`='1' WHERE `l_id`=1;";
$UP_3_0RC1["delete_title_qa_fields"] = "ALTER TABLE {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_questions']} DROP COLUMN `question`,  DROP COLUMN `answer`, DROP COLUMN `hits`, DROP COLUMN `changedate`;";
$UP_3_0RC1["add_qa_order_field"] = "ALTER TABLE {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_questions']} ADD `q_order` int(1) NOT NULL default '10'";
$UP_3_0RC1["delete_title_topic_fields"] = "ALTER TABLE {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_topics']} DROP COLUMN `topic`, DROP COLUMN `description`;";
$UP_3_0RC1["delete_lang_uid"] = "ALTER TABLE {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_lang']} DROP COLUMN uid`;";
$UP_3_0RC1["delete_questions_fields"] = "ALTER TABLE {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_lang']} DROP COLUMN uid`;";
$UP_3_0RC1["add_trans_permissions"] = "ALTER TABLE {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_trans']} ADD `hits` int(11) NOT NULL default '0', ADD `changedate` TIMESTAMP ON UPDATE CURRENT_TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, ADD `commentcode` tinyint(1) NOT NULL default '0',
ADD `owner_id` mediumint(8) unsigned NOT NULL default '1',
ADD `group_id` mediumint(8) unsigned NOT NULL default '1',
ADD `perm_owner` tinyint(1) unsigned NOT NULL default '3',
ADD `perm_group` tinyint(1) unsigned NOT NULL default '2',
ADD `perm_members` tinyint(1) unsigned NOT NULL default '2',
ADD `perm_anon` tinyint(1) unsigned NOT NULL default '2'";
$UP_3_0RC1["add_lang_permissions"] = str_replace('_trans', "_lang ADD `is_open` tinyint(1) NOT NULL default '1',", $UP_3_0RC1["add_lang_permissions"]);
$UP_3_0RC1["add_trans_permissions"] = str_replace("commentcode tinyint(1) NOT NULL default '0'", "commentcode tinyint(1) NULL", $UP_3_0RC1["add_trans_permissions"]);
$UP_3_0RC1["update_lang_permissions"]="UPDATE " . $_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_lang'] . " SET `commentcode`='{$perm['commentcode']}', `owner_id`='{$perm['owner_id']}', `group_id`='{$perm['group_id']}', `perm_owner`='{$perm['perm_owner']}', `perm_group`='{$perm['perm_group']}', `perm_members`='{$perm['perm_members']}', `perm_anon`='{$perm['perm_anon']}';";

$UP_3_0RC1["update_trans_commentcode"] = str_replace('_lang', '_trans', $UP_3_0RC1["update_lang_permissions"]);

$UP_3_1["fix_date"] = "ALTER TABLE {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_trans']} CHANGE `changedate` `changedate` DATETIME default NULL";

$UP_VERSION["update_homepage"]="UPDATE " . $_TABLES['plugins'] . " SET `pi_homepage`='$pi_url' WHERE `pi_name`='$pi_name';";
$UP_VERSION["update_gl_plugin_version"]="UPDATE " . $_TABLES['plugins'] . " SET `pi_gl_version`='$gl_version' WHERE `pi_name`='$pi_name';";
$UP_VERSION["update_plugin_version"]="UPDATE " . $_TABLES['plugins'] . " SET `pi_version`='$pi_version' WHERE `pi_name`='$pi_name';";

$UPGRADES["1.0"] = $UP_1_0;      # FROM beta to V1
$UPGRADES["2.0"] = $UP_2_1;      # FROM v2 to V2.1
$UPGRADES["2.1"] = $UP_2_2b;     # FROM v2.1 to V2.2b
$UPGRADES["2.2RC1"] = $UP_2_2RC2;    # FROM v2.2RC1 to v2.2RC2
$UPGRADES["2.2RC2"] = $UP_3_0RC1;    # FROM v2.2RC2 to v3.0RC1
$UPGRADES["3.0RC1"] = $UP_3_1;    # FROM v3.0RC1 to v3.1

$UPGRADES[$pi_version] = $UP_VERSION;

    $currentversion = DB_getItem($_TABLES['plugins'],'pi_version',"pi_name='$pi_name'");

    $currentversion_calc = $currentversion;
    if (strpos($currentversion, "RC") !== false || strpos($currentversion, "b") !== false)
      $currentversion_calc = $currentversion_calc-0.001;

    COM_errorLog("Attempting to upgrade the $pi_name plugin",1);
    COM_errorLog("Upgrading from version ".$currentversion."!",1);
    $upgrade_fromhere=false;
    $i=0;

    foreach ($UPGRADES as $upgrade => $action_arr) # check through ALL upgrades
        {
        $i++;
        if ($currentversion_calc<=$upgrade) # this is newer than the current version, start upgrading from here!
            {
            $upgrade_from_here=true;
            if ($upgrade < $pi_version)
              COM_errorLog("Found entrypoint into upgrade list from ver. ".$upgrade."!",1);
            }
        if ($upgrade_from_here)
            {
            foreach ($action_arr as $step => $sql)
                {
                if ($currentversion_calc<=$upgrade)
                   COM_errorLog("Upgrading Step to Ver. ".$upgrade.", Step $step",1);
                DB_query($sql,1);
                $upd_id = DB_insertId();
                $err = DB_error();
                if ($err)
                    {
                    COM_errorLog("Error upgrading, step $step",1);
                    var_dump($err);
                    COM_errorLog("SQL in question: $sql",1);
                    PLG_uninstall($pi_name);
                    return 3002;
                    exit;
                    }
                }
            }
        }
        if ($upgrade_from_here) {
            plg_mfaq_sitemap(true);
            COM_errorLog("Successfully upgraded the $pi_name plugin from version $currentversion to $pi_version!",1);
            return 3001;
        }
}

function plugin_centerblock_multifaq($where=0, $page=1, $topic='') {
    global $_CONF, $LANG_LOGIN, $_PLG_MULTIFAQ, $LANG_MULTIFAQ, $PLG_MFAQ_HEADER, $langtag;

    $display = '';

    if (is_numeric($where) && ($where > 0 || !$_PLG_MULTIFAQ['replace_homepage']))
        return $display;

    if ($_PLG_MULTIFAQ['require_login'] && COM_isAnonUser()) {
// || !SEC_hasRights('multifaq.view')) {
    $display .= COM_siteHeader ('menu', $LANG_LOGIN[1]);
    $display .= COM_startBlock ($LANG_LOGIN[1], '',
                                COM_getBlockTemplate ('_msg_block', 'header'));
    $login = new Template($_CONF['path_layout'] . 'submit');
    $login->set_file (array ('login'=>'submitloginrequired.thtml'));
    $login->set_var ( 'xhtml', XHTML );
    $login->set_var ('site_url', $_CONF['site_url']);
    $login->set_var ('site_admin_url', $_CONF['site_admin_url']);
    $login->set_var ('layout_url', $_CONF['layout_url']);
    $login->set_var ('login_message', $LANG_LOGIN[2]);
    $login->set_var ('lang_login', $LANG_LOGIN[3]);
    $login->set_var ('lang_newuser', $LANG_LOGIN[4]);
    $login->parse ('output', 'login');
    $display .= $login->finish ($login->get_var('output'));
    $display .= COM_endBlock (COM_getBlockTemplate ('_msg_block', 'footer'));
    $display .= COM_siteFooter();
    return $display;
}

if (!$_PLG_MULTIFAQ['allowedtopics'])
     return COM_siteHeader() . COM_startBlock($LANG_MULTIFAQ['no_faq'])
                 . $LANG_MULTIFAQ['no_faq_detailed'] . '.'
                 . COM_endBlock() . plg_mfaq_siteFooter() . COM_siteFooter();

/*
* Main Function
*/

             COM_setArgNames (array ('id', 'what', 'stype', 'searchall'));
$gettype = COM_applyFilter (COM_getArgument ('what'));
$getitem = COM_applyFilter (COM_getArgument ('id'));
if (substr($getitem, -strlen('_xy'), 1) == '_' || is_array($_CONF['language_files'])) {
   if (substr($getitem, -strlen('_xy'), 1) == '_')
      $langtag = substr($getitem, -strlen('_xy')+strlen('_'));
   $langtag = plg_mfaq_getLanguageTag($langtag);
   if (substr($getitem, -strlen('_xy'), 1) == '_')
      $getitem = substr($getitem, 0, -strlen('_xy'));
   if (!empty($langtag) && $langtag <> plg_mfaq_getLanguageTag()) {
      $language_bak = $_CONF['language'];
      $_CONF['language'] = $_CONF['language_files'][$langtag];
   }
}
$searchterms = trim(preg_replace('/(\s){2,}/', '$1', COM_applyFilter (COM_getArgument ('query'))));
$getstype = COM_applyFilter (COM_getArgument ('stype'));

if (!empty($getitem) and (empty($gettype) or ($gettype=='question'))) {# one certain question has been called
    $display .= plg_mfaq_get_q_and_a($getitem, $searchterms, $getstype);
} else {# get level hierarchy
    $display .= plg_mfaq_get_tree($getitem, 'topic', $searchterms, $getstype);
}

if ($_PLG_MULTIFAQ["show_recent"]) {
    $display .= plg_mfaq_recent_additions();
}

if ($_PLG_MULTIFAQ["show_top_x"]) {
    $display .= plg_mfaq_top_x_questions();
}

$display .= plg_mfaq_siteFooter() . COM_siteFooter();

$url = $_CONF['site_url'] . "/multifaq/index.php";
if (!empty($getitem))
    $url .= "?id=" . $getitem . $langtag;
if (!empty($gettype) && $gettype <> 'question')
    $url .= "&what=" . $gettype;
$url = COM_buildUrl ($url);
$headercode = '<link rel="canonical" href="' . $url . '"' . XHTML . '>' . LB;
$PLG_MFAQ_HEADER = COM_siteHeader('menu', $PLG_MFAQ_HEADER, $headercode);

$display = $PLG_MFAQ_HEADER . $display;

if (isset($language_bak))
      $_CONF['language'] = $language_bak;

return $display;
}

/**
* Return information for an event
*
* @param    string  $eid        event ID or '*'
* @param    string  $what       comma-separated list of properties
* @param    int     $uid        user ID or 0 = current user
* @param    array   $options    (reserved for future extensions)
* @return   mixed               string or array of strings with the information
*
*/
function plugin_getiteminfo_multifaq($eid, $what, $uid = 0, $options = array())
{
    global $_CONF, $_TABLES, $_PLG_MULTIFAQ;

    if (is_null($_PLG_MULTIFAQ))
       $_PLG_MULTIFAQ['plugin_shortcut'] = plugin_shortcut_multifaq();

    $eid_name = 'e_id';
    $id_name = 'id';
    $fields = array('l_id', "{$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_questions']}.t_id");
    $leftjoin = " LEFT JOIN {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_questions']} ON $eid_name=q_" . $id_name;
    $requirements = "type='q' AND ";

       if (is_array($_CONF['language_files'])) {
          $language_files = array_flip($_CONF['language_files']);
          if (strpos($eid, '_') !== false) {
             $langtag = substr($eid, -strlen('_xy')+strlen('_'));
             $l_id[] = DB_getItem($_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_lang'], 'is_open', "language='{$_CONF['language_files'][$langtag]}'");
             if (!$l_id)
                 return array();
             $eid = substr($eid, 0, -strlen('_xy'));
          }
       }

    if ($eid != '*')
       $requirements .= "$fields[0]=" . plg_mfaq_getLanguageid();
    else
       $requirements .= "($fields[0]=";

       if (!isset($l_id)) {
          $sql = "SELECT $fields[0], language FROM {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_lang']} WHERE is_open=1 ORDER BY is_default desc, language";
          $result = DB_query($sql,1);
          for ($i=0; $i<DB_numRows($result); $i++) {
             $A = DB_fetchArray ($result);
             if (isset($language_files))
                      $l_id[$language_files[$A['language']]] = $A[$fields[0]];
             else            
                      $l_id[] = $A[$fields[0]];
          }
          $language = array_flip($l_id);
       }

       foreach ($l_id as $value)
          $allowedtopics[$value] = plg_mfaq_checkaccess('', 't', 'read', true, $value, $uid, true);

    if ($eid == '*')
       $requirements .= implode(" OR $fields[0]=", $l_id) . ')';

    // parse $what to see what we need to pull from the database
    $properties = explode(',', $what);

    foreach ($properties as $p) {
        switch ($p) {
        // no date! we don't keep track of the _item's_ create/modify dates!
        case 'description':
        case 'excerpt':
            $fields[] = 'field2 AS description';
            break;
        case 'id':
            $fields[] = 'e_id AS eid';
            break;
        case 'title':
            $fields[] = 'field1 AS title';
            break;
        case 'url':
            // needed for $eid == '*', but also in case we're only requesting
            // the URL (so that $fields isn't emtpy)
            $fields[] = 'e_id AS eid';
            break;
        case 'date-modified':
            $fields[] = "UNIX_TIMESTAMP(changedate) AS 'date-modified'";
            break;
        default:
            // nothing to do
            break;
        }
    }

    $fields = array_unique($fields);

    if (count($fields) == 0) {
        $retval = array();

        return $retval;
    }

    // prepare SQL request
    if ($eid == '*') {
        $where = '';
        $permOp = 'WHERE';
    } else {
        $where = " WHERE $eid_name = '" . addslashes($eid) . "'";
        $permOp = 'AND';
    }

    if ($uid > 0) {
        $permSql = COM_getPermSql($permOp, $uid);
    } else {
        $permSql = COM_getPermSql($permOp);
    }

    if (isset($requirements)) {
       if (empty($where) && empty($permSql))
         $requirements = ' WHERE ' . $requirements;
       else
         $requirements = ' AND ' . $requirements;
    }

    $sql = "SELECT " . implode(',', $fields)
            . " FROM {$_TABLES[$_PLG_MULTIFAQ['plugin_shortcut'] . '_trans']}" . $leftjoin . $where . $permSql . $requirements;

    if ($eid != '*') {
        $sql .= ' LIMIT 1';
    }

    $result = DB_query($sql);
    $numRows = DB_numRows($result);

    $retval = array();
    for ($i = 0; $i < $numRows; $i++) {
        $A = DB_fetchArray($result);

        $props = array();
        foreach ($properties as $p) {
            $langtag = $A[$fields[0]];
            if (strpos($fields[1], '.') !== false)
               $fields[1] = substr($fields[1], strpos($fields[1], '.') +strlen('.'));
            if (!is_array($allowedtopics[$langtag]) || !in_array($A[$fields[1]], $allowedtopics[$langtag]))
                continue;

            if ($eid == '*') {
                 $langtag = $language[$langtag];
            } else
                 $langtag = '';
            $langtag = plg_mfaq_getLanguageTag($langtag);

            switch ($p) {
            case 'description':
            case 'excerpt':
                $props[$p] = $A['description'];
                break;
            case 'id':
                $props['id'] = $A['eid'] . $langtag;
                break;
            case 'title':
                $props['title'] = stripslashes($A['title']);
                break;
            case 'url':
                if (empty($A['eid']))
                    $theid = $eid;
                else
                    $theid = $A['eid'];
                $props['url'] = COM_buildUrl($_CONF['site_url'] . '/multifaq/index.php?'
                                  . "$id_name=" . $theid . $langtag);
                break;
            case 'date-modified':
                $props['date-modified'] = $A['date-modified'];
                break;
            default:
                // return empty string for unknown properties
                $props[$p] = '';
                break;
            }
        }

        $mapped = array();
        foreach ($props as $key => $value) {
            if ($eid == '*') {
                if ($value != '') {
                    $mapped[$key] = $value;
                }
            } else {
                $mapped[] = $value;
            }
        }

        if ($eid == '*') {
            $retval[] = $mapped;
        } else {
            $retval = $mapped;
            break;
        }
    }

    if (($eid != '*') && (count($retval) == 1)) {
        $retval = $retval[0];
    }

    return $retval;
}

function plugin_getcommenturlid_multifaq() {
    return array('', 'id_comment');
}

/**
* Implements autotags.
*
* @param    string  $op         operation to perform
* @param    string  $content    item (e.g. story text), including the autotag
* @param    array   $autotag    parameters used in the autotag
* @param    mixed               tag names (for $op='tagname') or formatted content
*
*/
function plugin_autotags_multifaq ($op, $content = '', $autotag = '') {
global $_CONF;

    $available_tags = array('mfaq', 'mfaq_topic');
    $available_ids = array('question', 'topic');
    if ($op == 'tagname' ) {
        return $available_tags;
    } else if ($op == 'parse') {
        $available_id = array_flip($available_tags);
        $available_id = $available_id[$autotag['tag']];
        $available_id = $available_ids[$available_id];
        $id = COM_applyFilter($autotag['parm1']);
        if (empty($autotag['parm2']))
            list($title,) = plg_mfaq_gettrans($id, $available_id{0});
       else
            $title = $autotag['parm2'];
        if ($available_id == $available_ids[0])
            $langtag = plg_mfaq_getLanguageTag();
        else
            $langtag = '';
        $url = COM_buildUrl ($_CONF['site_url']
                     . "/multifaq/index.php?id=" . $id. $langtag . '/' . $available_id);
        $link = COM_createLink($title, $url, array_merge(array("title" => $title), plg_mfaq_needed_direction(true)));
    $content = str_replace($autotag['tagstr'], $link, $content);
    return $content;
    }
}
?>
Return current item: Geeklog Plugins, Static Pages and Blocks