<?php
//
// +---------------------------------------------------------------------------+
// | nmoxmenu Geeklog Plugin 2.0                                       |
// +---------------------------------------------------------------------------+
// | function.inc                                                              |
// +---------------------------------------------------------------------------+
// | Copyright (C) 2007 by nmox                                                |
// |                                                                           |
// +---------------------------------------------------------------------------+
// |                                                                           |
// | 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.                              |
// |                                                                           |
// +---------------------------------------------------------------------------+
/**
* Language file Include
*/
$langfile = $_CONF['path'] . 'plugins/nmoxmenu/language/' . $_CONF['language'] . '.php';
if (file_exists ($langfile))
{
	include_once ($langfile);
}
else
{
	include_once ($_CONF['path'] . 'plugins/nmoxmenu/language/english.php');
}

require_once ($_CONF['path'] . 'plugins/nmoxmenu/config.php');

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

function plugin_chkVersion_nmoxmenu() {
	global $_NMOXMENU;

	return $_NMOXMENU['version'];
}

/**
* 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_nmoxmenu()
{
}

/**
* 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_nmoxmenu()
{
	return false;
}

/**
* 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_nmoxmenu($showsitestats)
{
	$retval = '';
	return $retval;
}

function plugin_upgrade_nmoxmenu ()
{
    global $_TABLES, $_NMOXMENU;

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

    if ($v != $_NMOXMENU['version']) {
        // update version numbers
        DB_query ("UPDATE {$_TABLES['plugins']} SET pi_version = '{$_NMOXMENU['version']}', pi_gl_version = '1.4.1' WHERE pi_name = 'nmoxmenu'");

        // check if version number was updated successfully
        $v = DB_getItem ($_TABLES['plugins'], 'pi_version', "pi_name = 'spamx'");
    }

    if ($v == $_NMOXMENU['version']) {
        return true;
    }

    return true;
}

function plugin_getheadercode_nmoxmenu()
{
    global $_CONF;

    // Changed by Phize <----
    //$str = "<link rel='stylesheet' type='text/css' href='" . $_CONF['site_url'] . "/nmoxmenu/style.css'>\n";
    $str= "<script src='" . $_CONF['site_url'] . "/nmoxmenu/functions.js' type='text/javascript'>\n</script>\n";
    // Changed by Phize ---->

    return $str;
}

function plugin_enablestatechange_nmoxmenu ($enable)
{
	global $_TABLES;

	$is_enabled = $enable ? 1 : 0;

	// toggle nmoxmenu block
	DB_query ("UPDATE {$_TABLES['blocks']} SET is_enabled = $is_enabled WHERE (type = 'phpblock') AND (phpblockfn = 'phpblock_nmoxmenu01')");
	DB_query ("UPDATE {$_TABLES['blocks']} SET is_enabled = $is_enabled WHERE (type = 'phpblock') AND (phpblockfn = 'phpblock_nmoxmenu02')");
}

/**
* Removes the datastructures for this plugin from the Geeklog database.
* This routine will get called from the Plugin install program if user select De-Install or if Delete is used in the Plugin Editor.
* The Plugin Installer will also call this routine upon and install error to remove anything it has created.
* The Plugin installer will pass the optional parameter which will then double check that plugin has first been disabled. 
* 
* For this plugin, this routine will also remove the Block definition.
* 
* Returns True if all Plugin related data is removed without error
*
* @param    string   $installCheck     Defult is blank but if set, check if plugin is disabled first
* 
* @return   boolean True if successful false otherwise
*
*/  
function plugin_uninstall_nmoxmenu($installCheck = '')
{
	global $_TABLES, $LANG_NMOXMENU,$_CONF;

	$pi_name  = 'nmoxmenu';


	$grp_id = DB_getItem($_TABLES['vars'], 'value', "name = '{$pi_name}_admin'");
	DB_delete($_TABLES['plugins'],'pi_name','nmoxmenu');
	DB_query("DELETE FROM {$_TABLES['group_assignments']} WHERE ug_main_grp_id = $grp_id",1);
	$FEATURES = array ('nmoxmenu.edit','nmoxmenu.user');
	foreach ($FEATURES as $feature) {
		$feat_id = DB_getItem($_TABLES['features'], 'ft_id', "ft_name = '$feature'");
		DB_query("DELETE FROM {$_TABLES['access']} WHERE acc_ft_id = $feat_id",1);
		DB_query("DELETE FROM {$_TABLES['features']} WHERE ft_id = $feat_id",1);
	}
	DB_query("DELETE FROM {$_TABLES['vars']} WHERE name = '{$pi_name}_admin'");
	DB_query("DELETE FROM {$_TABLES['groups']} WHERE grp_id = $grp_id",1);
    DB_query("DELETE FROM {$_TABLES['blocks']} WHERE name='nmoxmenu1'",1);
    DB_query("DELETE FROM {$_TABLES['blocks']} WHERE name='nmoxmenu2'",1);

	return true;
}

function NMOXMENU_get_tab($tab,$n,$toggle){
	for($i=1;$i<=10;$i++){
		$tab_bit[$i]=substr($tab,($i-1),1);
	}
	$tab_bit[$n]=$toggle;
	return implode("",$tab_bit);
}

function NMOXMENU_get_tid($topic){
	global $_TABLES;
	$sql="select tid from ".$_TABLES["topics"]." where topic='".$topic."'";
	$rs=DB_query($sql);
	$rc=DB_fetchArray($rs);
	return $rc["tid"];
}

function NMOXMENU_num_stories($tid){
	global $_TABLES;
	$show_num_stories=0;
	$sql="select * from ".$_TABLES["stories"]." where draft_flag=0 and date<'".date("Y-m-d H:i:s")."' and tid='".$tid."'";
	$rs=DB_query($sql);
	while($rc=DB_fetchArray($rs)){
		//閲覧可能な記事数をカウント
		$permission=SEC_hasAccess($rc["owner_id"],$rc["group_id"],$rc["perm_owner"],$rc["perm_group"],$rc["perm_members"],$rc["perm_anon"]);
		if($permission>1){
			$show_num_stories++;
		}
	}
	return $show_num_stories;
}

function NMOXMENU_separate($indexname){
	$retval=null;
	$separate_ch=array("_","-");
	foreach($separate_ch as $separate){
		$retval=explode($separate,$indexname);
		if(isset($retval[1])){
			break;
		}
	}
	return $retval;
}

function phpblock_nmoxmenu01(){
	//type1 normal
	global $_CONF,$_TABLES,$LANG_NMOXMENU,$_USER;
	
	//多言語対応用に言語IDを取得
	if (strcmp(VERSION, '1.4.1') < 0) {
		$lang="ja";
	}
	if( !isset( $_CONF['languages'] ) || !isset( $_CONF['language_files'] ) ||
		( count( $_CONF['languages'] ) != count( $_CONF['language_files'] ))) {
		$langId="";
	} else {
		$lang=COM_getLanguage();
		$langId = COM_getLanguageId($lang );
    }
	
	//状態保存用にユーザーIDを取得、ゲストはすべて1とする
	if($_USER["uid"]>0){
		$user=$_USER["uid"];
	}else{
		$user=1;
	}
	//状態を再現
	$rc=DB_fetchArray(DB_query("select * from ".$_TABLES["nmoxmenu"]." where uid=".$user));
	if(isset($_GET["tab"])){
		$tab=$_GET["tab"];
	}elseif(!empty($rc["tab"])){
		$tab=$rc["tab"];
	}else{
		$tab="";
		for($j=1;$j<=10;$j++){
			$tab.="0";
		}
	}
	//状態を保存
	if(empty($rc)){
		DB_query("insert into ".$_TABLES["nmoxmenu"]."(uid,tab)values(".$user.",'".$tab."')");
	}else{
		DB_query("update ".$_TABLES["nmoxmenu"]." set tab='".$tab."' where uid=".$user);
	}
	
	//階層リストを配列変数に作成
	$num_full=0;
	$num_first=0;
	$sql="SELECT tid,topic FROM ".$_TABLES['topics']." ORDER BY sortnum ASC";
	$rs=DB_query($sql);
	while($rc=DB_fetchArray($rs)){
		$topics_fullname[$num_full]=$rc["topic"];
		$topic_separatename=NMOXMENU_separate($topics_fullname[$num_full]);
		if($topic_separatename[0]!=$last_topicword){
			//直前の第一階層文字と変わっていれば、第一階層文字を取得
			$topics_first[$num_first]=$topic_separatename[0];
			$last_topicword=$topic_separatename[0];
			$num_first++;
		}
		$num_full++;
	}
	
	//階層メニューを生成
	$n=1;
	$html="<ul class='nmoxmenu'>\n";

/* Geeklog Japanese Ivy 2007.6.8 */
if($topics_first){
	foreach($topics_first as $topic_first){
		$tid=NMOXMENU_get_tid($topic_first);
		//他の言語用だった場合はスルー
		$langcheck=explode("_",$tid);
		if( !empty( $langId )){
			if(isset($langcheck[1])){
				if($langcheck[1]!=$langId){
					 continue;
				}
			}
		}
		//見せるべき記事があるかどうか
		$indexname="";
		$sql="select * from ".$_TABLES["topics"]." where topic like '".$topic_first."%'";
		$rst=DB_query($sql);
		while($rct=DB_fetchArray($rst)){
			$sql="select * from ".$_TABLES["stories"]." where tid='".$rct["tid"]."'";
			$rss=DB_query($sql);
			while($rcs=DB_fetchArray($rss)){
				//話題が閲覧可能で、記事も閲覧可能なら、表示フラグを立てる
				if(SEC_hasTopicAccess($rct["tid"])>0
				 && SEC_hasAccess($rcs["owner_id"],$rcs["group_id"],$rcs["perm_owner"],$rcs["perm_group"],$rcs["perm_members"],$rcs["perm_anon"])>1){
					$indexname=$rct["topic"];
				}
			}
		}
		if(!empty($indexname)){
			$exist_subindex=0;
			//見せるべき話題である
			$exist_subindex=NMOXMENU_separate($indexname);
			if(isset($exist_subindex[1])){
				//第二階層がある話題
				if(substr($tab,$n-1,1)=="1"){
					//開いている話題
					$html.="<li class='open'><a href='".$_CONF['site_url']."/index.php?topic=".$rct["tid"]."&amp;tab=".NMOXMENU_get_tab($tab,$n,0)."'>".$topic_first."</a>\n";
					$html.="<ul>\n";
					$sql = "select * from ".$_TABLES["topics"]." where topic like '".$topic_first."_%'";
					$rst = DB_query($sql);
					while($rct=DB_fetchArray($rst)){
						$show_num_stories=NMOXMENU_num_stories($rct["tid"]);
						if(SEC_hasTopicAccess($rct["tid"])>0 && $show_num_stories>0){
							//記事があれば見せるべき話題である
							$topic=NMOXMENU_separate($rct["topic"]);
							$html.="<li>└<a href='".$_CONF['site_url']."/index.php?topic=".$rct["tid"]."&amp;tab=".$tab."'>".$topic[1]."</a>".($_CONF["showstorycount"]>0?"(".$show_num_stories.")":"")."</li>\n";
						}
					}
					$html.="</ul>\n</li>\n";
				}else{
					//閉じている話題
					$topic=explode("_",$rct["topic"]);
					$html.="<li class='close'><a href='".$_CONF['site_url']."/index.php?topic=".$tid."&amp;tab=".NMOXMENU_get_tab($tab,$n,1)."'>".$topic_first."</a></li>\n";
				}
			}else{	
				//第二階層が無い話題
				$show_num_stories=NMOXMENU_num_stories($tid);
				if($show_num_stories>0){
					$html.="<li class='only'><a href='".$_CONF['site_url']."/index.php?topic=".$tid."&amp;tab=".$tab."'>".$topic_first."</a>".($_CONF["showstorycount"]>0?"(".$show_num_stories.")":"")."</li>\n";
				}
			}
		}
		$n++;
	}
}
	$html.="</ul>\n";
	
	//$retval="<link rel='stylesheet' type='text/css' href='".$_CONF['site_url']."/nmoxmenu/style.css'>\n";

    // Changed by Phize <----
	$retval.="<div class='block-box'>".$html."</div>\n";
    // Changed by Phize ---->

	return $retval;
}

function phpblock_nmoxmenu02(){
	//type2 with javascript

	global $_CONF,$_TABLES,$LANG_NMOXMENU,$_USER;
	
	//多言語対応用に言語IDを取得
	if (strcmp(VERSION, '1.4.1') < 0) {
		$lang="ja";
	}
	if( !isset( $_CONF['languages'] ) || !isset( $_CONF['language_files'] ) ||
		( count( $_CONF['languages'] ) != count( $_CONF['language_files'] ))) {
		$langId="";
	} else {
		$lang=COM_getLanguage();
		$langId = COM_getLanguageId($lang );
    }
	
	//階層リストを配列変数に作成
	$num_full=0;
	$num_first=0;
	$sql="SELECT tid,topic FROM ".$_TABLES['topics']." ORDER BY sortnum ASC";
	$rs=DB_query($sql);
	while($rc=DB_fetchArray($rs)){
		$topics_fullname[$num_full]=$rc["topic"];
		$topic_separatename=NMOXMENU_separate($topics_fullname[$num_full]);
		if($topic_separatename[0]!=$last_topicword){
			//直前の第一階層文字と変わっていれば、第一階層文字を取得
			$topics_first[$num_first]=$topic_separatename[0];
			$last_topicword=$topic_separatename[0];
			$num_first++;
		}
		$num_full++;
	}
	
	//階層メニューを生成
	$n=1;
	$html="<ul class='nmoxmenu'>\n
	";

/* Geeklog Japanese Ivy 2007.6.8 */
if($topics_first){
	foreach($topics_first as $topic_first){
		$tid=NMOXMENU_get_tid($topic_first);
		//他の言語用だった場合はスルー
		$langcheck=explode("_",$tid);
		if( !empty( $langId )){
			if(isset($langcheck[1])){
				if($langcheck[1]!=$langId){
					 continue;
				}
			}
		}
		//見せるべき記事があるかどうか
		$indexname="";
		$sql="select * from ".$_TABLES["topics"]." where topic like '".$topic_first."%'";
		$rst=DB_query($sql);
		while($rct=DB_fetchArray($rst)){
			$sql="select * from ".$_TABLES["stories"]." where tid='".$rct["tid"]."'";
			$rss=DB_query($sql);
			while($rcs=DB_fetchArray($rss)){
				//話題が閲覧可能で、記事も閲覧可能なら、表示フラグを立てる
				if(SEC_hasTopicAccess($rct["tid"])>0
				 && SEC_hasAccess($rcs["owner_id"],$rcs["group_id"],$rcs["perm_owner"],$rcs["perm_group"],$rcs["perm_members"],$rcs["perm_anon"])>1){
					$indexname=$rct["topic"];
				}
			}
		}
		if(!empty($indexname)){
			$exist_subindex=0;
			//見せるべき話題である
			$exist_subindex=NMOXMENU_separate($indexname);
			if(isset($exist_subindex[1])){
				//第二階層がある話題
				$html.="<li class='close' id='t".$n."'><a href=\"javaScript:exMenu('menu".$n."','t".$n."')\">".$topic_first."</a>\n";
				$html.="<ul id='menu".$n."' style='display:none'>\n";
				$sql = "select * from ".$_TABLES["topics"]." where topic like '".$topic_first."_%'";
				$rst = DB_query($sql);
				while($rct=DB_fetchArray($rst)){
					$show_num_stories=NMOXMENU_num_stories($rct["tid"]);
					if(SEC_hasTopicAccess($rct["tid"])>0 && $show_num_stories>0){
						//記事があれば見せるべき話題である
						$topic=NMOXMENU_separate($rct["topic"]);
						$html.="<li>└<a href='".$_CONF['site_url']."/index.php?topic=".$rct["tid"]."'>".$topic[1]."</a>".($_CONF["showstorycount"]>0?"(".$show_num_stories.")":"")."</li>\n";
					}
				}
				$html.="</ul>\n</li>\n";
			}else{	
				//第二階層が無い話題
				$show_num_stories=NMOXMENU_num_stories($tid);
				if($show_num_stories>0){
					$html.="<li class='only'><a href='".$_CONF['site_url']."/index.php?topic=".$tid."'>".$topic_first."</a>".($_CONF["showstorycount"]>0?"(".$show_num_stories.")":"")."</li>\n";
				}
			}
		}
		$n++;
	}
}
	$html.="</ul>\n";
	
	//$retval="<link rel='stylesheet' type='text/css' href='".$_CONF['site_url']."/nmoxmenu/style.css'>\n";

    // Changed by Phize <----
	$retval.="<div class='block-box'>".$html."</div>\n";
    // Changed by Phize ---->

	return $retval;
}
?>
