foreach ($chans as $chan) {
    $vals = explode(';', $chan);
    $channel = escapechannel($vals[0]);
    $lastid = (int) $vals[1];
    $closed = false;
    if ($msgon == $channel && !is_null($channel)) {
        $time = time();
        if (substr($msg, 0, 1) == '/') {
            $words = explode(' ', $msg);
            switch ($words[0]) {
                case '/part':
                case '/close':
                    echo "minichat_removechannel('" . $channel . "');\n";
                    $closed = true;
                    if (!isset($_SESSION['minichat_channels'])) {
                        initchannelssession($chans);
                    }
                    $k = array_search($words[1], $_SESSION['minichat_channels']);
                    if ($k !== false) {
                        unset($_SESSION['minichat_channels'][$k]);
                    }
                    break;
            }
        } else {
            $tikilib->query("INSERT INTO tiki_minichat (nick,user,ts,channel,msg) VALUES (?,?,?,?,?)", array(smarty_modifier_username($user), $user, $tikilib->now, $channel, $msg));
            $lastid = 0;
        }
        $lasttimeout = $timeout_min;
    }
    if ($closed) {
        continue;
}
foreach ($chans as $chan) {
	$vals = explode(';', $chan);
	$channel = escapechannel($vals[0]);
	$lastid = (int)$vals[1];
	$closed = false;
	if (($msgon == $channel) && (!is_null($channel))) {
		$time = time();
		if (substr($msg, 0, 1) == '/') {
			$words = explode(' ', $msg);
			switch ($words[0]) {
				case '/part':
				case '/close':
					echo "minichat_removechannel('" . $channel . "');\n";
					$closed = true;
					if (!isset($_SESSION['minichat_channels'])) initchannelssession($chans);
					$k = array_search($words[1], $_SESSION['minichat_channels']);
					if ($k !== false) unset($_SESSION['minichat_channels'][$k]);
    				break;
			}
		} else {
				$tikilib->query("INSERT INTO tiki_minichat (nick,user,ts,channel,msg) VALUES (?,?,?,?,?)", array(smarty_modifier_username($user), $user, $tikilib->now, $channel, $msg));
				$lastid = 0;
		}
			$lasttimeout = $timeout_min;
	}
	if ($closed) continue;
	if (empty($channel)) continue;
	if ($lastid > 0) {
		$result = $tikilib->query("SELECT MAX(id) AS maxid FROM tiki_minichat WHERE channel=?", array($channel));
		$res = $result->fetchRow();