Platon Technologies
neprihlásený Prihlásiť Registrácia
SlovakEnglish
open source software development oslavujeme 10 rokov vývoja otvoreného softvéru! Sobota, 12. október 2024

Súbor: [Platon] / wolboard / wolboard.php (stiahnutie)

Revízia 1.14, Thu Sep 26 09:08:10 2002 UTC (22 years ago) by wolcano


Zmeny od 1.13: +1 -1 [lines]

Fixed bug in ereg_replace (occured when replacing variables which were postfixes of others)

<?
/*
    Module:    WolBoard.php3

    Author:    Martin Karas a.k.a. Wolcano
    Date:    24.04.2002
    Mail:    wolcano@pobox.sk
    Version:    v5.2
    License:    not chosen yet - this file is strictly private,
        you may not copy/change/distribute it without authors
        explicit premission.
    Description:    Simple message-board. Can store data in files or
        PEAR-compliant DB (not fully implemented yet)
    Copyright: Platon SDG     http://www.platon.sk

    TODO: (see TODO file)

    External files specification:
    $message_file :== (<message_line><eoln>)*
        <message_line> :== <unix_time>:<username>:<message> ||
            <unix_time>:<username>:<deleted_message>
        <deleted_message> :== *<message>

    $user_file :== (<user_line><eoln>)*
        <user_line> :== <username>:<email>:<md5sum_of_password>

    Database specification:
        See "sql/" files.
    
    Input parameters:
        $pagesize    - # of messages  per page
        $page        - #th page
        $autorefresh    - refresh time (secs)
//        $admin        - user/message mantainance
        $style        - message view style (0 = board, 1 = chat)
        $time        - message time index
        $nick        - user nickname
        $pass        - password
        $message    - text of the posted message
        $header        - shows only header
        $body        - show only body
        $bodyframe    - target body frame
        $headerframe    - targer header frame
        $disablepart    - Wont show some parts of the whole document
            (0 - none, 1 - body, 2 - head, 3 - both)
        $setframes    - 1 - create <framesset>
            0 - disable frames (?? :))
        $frameset    - are the frames set? :)
        $setframes    - do we want to create framewires?

        $createuser    - (internal)
        $deleteok    - (internal)
        $newnick    - (internal)
        $archive    - archive file prefix
        $archive_no    - index of archived file
        $submit_type    - submit button type
        $reply_to    - index of message you want to reply (inserts quoted message)
        $rootlogin    - wether should display the root login dialog

        CHANGE LOG:
        * 5.4    - "fixed" adduser bug (now ignoring result of flock() :()
                 - added root login for viewing deleted messages
        * 5.3    - external CSS file
        * 5.2    - added "reply" link
        * 5.1   - updated SQL queries
                   - sprtinf()-ed and quote()-ed all SQL queries
                - some bug fixes
        * 5.0   - DB implementation finished (hopefully)
                - now allowing some html tags (specified by (array) $allowed_tags)
                - no more dependent on external <framesets>! :) we do the dirty work
                  ourself (try setting the setframes=1 GET parameter)
        * 4.4.2 - 3/4 implementation DB done
        * 4.4   - DB/PEAR drafts
                - sources moved to CVS
        * 4.3   - starting MySQL DB implementation
        * 4.2   - started documentation
                - removed autosubmit on nick change
                - changed default autorefresh to 5 mins
                *FIX* now rawurldecoding username (previously rawurlencoded)
        * 4.1   - undocumented :)
*/


    // IMPORTANT CONSTANTS (change if needed)
    $WB_version = "5.2";
    $WB_name = "Wol's Message Board";
    $strip_slashes = 1;
    $DEFAULT_HEAD_FRAME = "";
    $DEFAULT_BODY_FRAME = "";
    $css_file = "style.css";
    $use_virtual_delete = 1;    //use delete flagging instead of real delete
    $root_name = "root";
    $root_md5_password = "896ae34257056a6edb7643e3db85bb21";

    // Filesystem defaults
    $message_file = "messages.dat";
    $user_file = "users.dat";
    $move_old_mesages = 1;
    $old_messages_folder = "history/";
    $hist_file_prefix = "board_hist_file_"; // used in REGEXPs! alphabeticals only
    $max_msgs_in_one_file = 200;
    $min_msgs_in_board = 50;

    // Database defaults
    $use_db = 0;
    $db_message_table = "wolboard_messages";
    $db_user_table = "wolboard_users";
    //$db_host = "db.host.sk";
    $db_host = "localhost";
    $db_database = "syndrome";
    $db_user = "";
    $db_pass = "";

    $allowed_tags = array(
        "<b>", "</b>",
        "<i>", "</i>",
        "<u>", "</u>",
        "<del>", "</del>",
        "&copy;"
        );


    // FUNCTIONS

    function good($a) {
        return (isset($a)
         && (
            (is_string($a) && ($a != "")) ||
            (!is_string($a) && ($a != 0))
            )
        );
    } // good($a)

    function link_replace($link, $paramname, $paramvalue) {
        $link = eregi_replace("&$", "", $link);
        $link = eregi_replace("(&|^)$paramname=[^&]*", "", $link);
        if ($paramvalue)
            $link .= "&$paramname=$paramvalue";
        return $link;
    } // link_replace($link, $paramname, $paramvalue)

    function show_array($a) {
        echo "<table border=1>\n";
        $keys = array_keys($a);

        for($i = 0; $i < sizeof($a); $i++) {
            echo "<tr>\n";
            echo "<td>";
            echo $keys[$i] . "</td>\n<td>";

            if ((is_array($a[$keys[$i]])) && ($keys[$i] !== "GLOBALS")) {
                show_array($a[$keys[$i]]);
            }
            else {
                echo $a[$keys[$i]];
            };
            echo "</td>\n</tr>\n";
        }
        echo "</table>";
    } // show_array($a)

    function array_copy($a, $i, $n = "x") {
        if (($n == "x") || ($n > (sizeof($a) - $i)))
            $n = sizeof($a) - $i;

        for($j = 0; $j < $n; $j++) {
            $ret[$j] = $a[$j + $i];
        }

        return $ret;
    } // array_copy($a, $i, $n = "x")

    function array_chunk($a, $n) {
        if (!is_array($a))
            return $a;
        $splits = sizeof($a) / $n;
        for($i = 0; $i < $splits; $i++) {
            $ret[$i] = array_copy($a, $i*$n, $n);
        }
        return $ret;
    } // array_chunk($a, $n)

    function w_chk($n, $v) {
        return ($v ? "$n=$v&" : "");
    } // w_chk($n, $v)

    function create_link() {
         global $pagesize, $page, $autorefresh, $admin, $style,
             $time, $nick, $pass, $message, $createuser, $deleteok,
            $autorefresh, $disablepart, $frameset, $headframe,
            $bodyframe, $archive, $archive_no;
        return eregi_replace("&$", "",
            w_chk("nick", $nick) .
            w_chk("pagesize", $pagesize) .
            w_chk("page", $page) .
//            w_chk("time", $time) .
//            w_chk("pass", $pass) .
//            w_chk("message", $message) .
//            w_chk("deleteok", $deleteok) .
//            w_chk("createuser", $createuser) .
//            w_chk("newnick", $newnick) .
            w_chk("autorefresh", $autorefresh) .
            w_chk("style", $style) .
            w_chk("admin", $admin) .
            w_chk("disablepart", $disablepart) .
            w_chk("frameset", $frameset) .
            w_chk("headframe", $headframe) .
            w_chk("bodyframe", $bodyframe) .
            w_chk("archive", $archive) .
            w_chk("archive_no", $archive_no)
        );
    } // create_link()

    function split_url_vars($s) {
        $a = explode('&', $s);
        $i = 0;
        $s = array();
        while ($i < sizeof($a)) {
            $b = explode('=', $a[$i]);
            $s[htmlspecialchars(urldecode($b[0]))] = 
                htmlspecialchars(urldecode($b[1]));
            $i++;
        }
        return $s;
    } // split_url_vars($s)

    function create_hidden_inputs($a, $val = 0) {
        if (is_array($a)) {
            $k = array_keys($a);
            $ret = '';
            for($i = 0; $i < sizeof($a); $i++) {
                $ret .= "<input type=hidden name=\"$k[$i]\" ".
                    "value=\"" . $a[$k[$i]] . "\">\n";
            }
            return $ret;
        }
        else {
            return "<input type=hidden name=\"$a\" value=\"$val\">\n";
        }
    } // create_hidden_inputs($a);

    function create_reply($msg_arr) {
        /*
         $msg_arr keys: time, name, message, email 
        */
        $quote_string = "&gt; ";
        $ret = $msg_arr["name"] .
            " (" .
            format_time($msg_arr["time"]) . 
            ")<br>\n$quote_string" .
            eregi_replace("\n", "\n$quote_string", $msg_arr["message"]) .
            "<br>";
        return $ret;
    } // create_reply($msg_arr)
    
    function wait_read_lock($f, $max_wait = 9999) {
        $start = time();
        while ((!flock($f, 1)) && ($start + $max_wait < time()))
            sleep(1);
        return ($start + $max_wait < time());
    } // wait_read_lock($f, $max_wait = 9999)

    function wait_write_lock($f, $max_wait = 9999) {
        $start = time();
        while ((!flock($f, 2)) && ($start + $max_wait < time()))
            sleep(1);
        return ($start + $max_wait < time());
    } // wait_write_lock($f, $max_wait = 9999)

    function release_lock($f) {
        flock($f, 3);
        return 1;
    } // release_lock($f)

    function show_options($optnames, $optvalues, $selected) {
        if (!is_array($optvalues))
            return 0;

        $found = 0;
        $ret = "";
        for($i = 0; $i < sizeof($optvalues); $i++) {
            $ret .= "<option";
            if (good($optvalues[$i])) {
                $ret .= " value=" . $optvalues[$i];
                if ($optvalues[$i] == $selected) {
                    $found++;
                    $ret .= " selected";
                }
            }
            $ret .= ">";
            if (good($optnames[$i]))
                $ret .= $optnames[$i];
            $ret .= "</option>\n";
        }
        if ((!$found) && ($selected != ""))
            $ret .= "<option value=$selected selected>Custom</option>\n";
        echo $ret;
    } // show_options($optnames, $optvalues, $selected)

    function get_user($str, $i = 0) {
        $tmp = strtok(trim($str), ":");
        if ($i)
            // (1) from $MESSAGE_FILE
            return strtok(":");
        else
            // (0) from $USER_FILE
            return $tmp;
    } // get_user($str, $i = 0)

    function get_users($usr_file, $use_db = 0, $db_conn = 0) {
        if (!$use_db) {
            // Working with files
            $fp = fopen($usr_file, "r");
            wait_read_lock($fp);
            $ret = file($usr_file);
            for($i = 0; $i < sizeof($ret); $i++) {
                $ret[$i] = trim($ret[$i]);
                $ret[$i] = get_user($ret[$i], 0);
            }
            release_lock($fp);
            return $ret;
        }
        else {
            // Working with DB
            // $usr_file stores Table name
            if (!$db_conn)
                return false;

            $sql = "SELECT nick FROM $usr_file";
            $res = $db_conn->query($sql);

            if (DB::isError($res))
                return false;

            $i = 0;
            while ($tmp = $res->fetchRow()) {
                $ret[$i++] = $tmp["nick"];
            }

            $res->free();
            return $ret;
        }
    } // get_users($usr_file, $use_db = 0, $db_conn = 0)

    function format_time($time, $style = 0) {
        switch($style) {
            case 1:
                return date("H:i:s", $time);
            default:
                return date("H:i:s - d. M Y", $time);
        }
    } // format_time($time, $style = 0)

    function get_time($str) {
        return strtok(trim($str), ":");
    } // get_time($str)

    function get_pass($str) {
        return rawurldecode(trim(strtr(strrchr($str, ":"), ":", " ")));
    } // get_pass($str)

    function get_email($str) {
        if (ereg("[^:]*:([^:]*):", $str, $regs))
            return $regs[1];
        else
            return "";
    } // get_email($str)

    function write_mail($usr_file, $user, $mail = '', $pass = '', $root_name = '', $use_db = 0, $db_conn) {
        $pass = md5(rawurlencode($pass));
        if ($user == $root_name)
            return false;
        if (!$use_db) {
            // Working with files
            $fp = fopen($usr_file, "a");
            wait_write_lock($fp);
            /*
            // this should work, but doesn't :(((
            // won't use this shitty file locking mechanism
            if (!wait_write_lock($fp))
                return false;
            */
            fwrite($fp, strtr($user, ":", ";") . ":" . strtr($mail, ":", ";") .
                ":" . $pass . "\n");
            release_lock($fp);
            fclose($fp);
            return true;
        }
        else {
            // Working with DB
            if (!$db_conn)
                return false;

            $sql = sprintf("INSERT INTO %s (nick, email, pass) VALUES (%s, %s, %s)",
                $usr_file, $db_conn->quote($user),
                $db_conn->quote($mail), $db_conn->quote($pass));

            $res = $db_conn->query($sql);

            return !(DB::isError($res));
        }
    } // write_mail($usr_file, $user, $mail = "", $pass = "", $use_db = 0, $db_conn)

    function change_mail($usr_file, $user, $newmail = "", $pass = "",
        $use_db = 0, $db_conn = 0) {
        function set_mail($usr_line, $newmail) {
            $ret = strtok($usr_line, ":");
            strtok(":");
            $ret .= $newmail . ":" . strtok(":");
            return $ret;
        }

        if (!$use_db) {
            //check if valid data is sent
            //we dont want to run for now
            if (true)//!!!!!!!!
                return 0;

            // Using files
            $fp = fopen($usr_file, "w+");
            wait_write_lock($fp);
            $tmp = files($usr_file);
            $i = 0;
            $found = false;
            while (($i < length($tmp)) && (!$found)) {
                $u = get_user($tmp[$i]);
                if ($u == $user) {
                    $tmp[$i] = set_mail($tmp[$i], $newmail);
                    $found = true;
                }
                $i++;
            }

            if ($found) {
                fwrite($fp, $u);
                release_lock($fp);
                fclose($fp);
                return 1;
            }
            else
                return 0;
        }
        else {
            // Using DB
            if (!$db_conn)
                return false;

            $sql = sprintf("UPDATE %s SET mail = %s WHERE name = %s AND pass = %s",
                $usr_file, $db_conn->quote($newmail),
                $db_conn->quote($user), $db_conn->quote($pass));
            $res = $db_conn->query($sql);

            return !(DB::isError($res));
        }
    }

    function delete_mail($usr_file, $user = "", $mail = "", $pass = "",
        $use_db = 0, $db_conn = 0) {
        if (!$use_db) {
            //!!!! TODO
            // Use files
            return false;
        }
        else {
            // Use DB
            if (!$db_conn)
                return false;

            $sql = sprintf("UPDATE %s SET mail = '' WHERE ".
                "name = %s AND pass = %s AND mail = %s",
                $usr_file, $db_conn->quote($user),
                $db_conn->quote($pass), $db_conn->quote($mail));
            $res = $db_conn->query($sql);

            return !(DB::isError($res));
        }
    }

    function get_emails($usr_file, $use_db = 0, $db_conn = 0) {
        if (!$use_db) {
            // Use files
            $fp = fopen($usr_file, "r");
            wait_read_lock($fp);
            $f = file($usr_file);
            for($i = 0; $i < sizeof($f); $i++)
                $ret[get_user($f[$i], 0)] = get_email($f[$i]);

            release_lock($fp);
            return $ret;
        }
        else {
            // Use DB
            if (!$db_conn)
                return false;

            $sql = sprintf("SELECT nick, email FROM %s", $usr_file);
            $res = $db_conn->query($sql);
            if (DB::isError($res))
                return false;

            while ($row = $res->fetchRow()) {
                $rows[$row["nick"]] = $row["email"];
            }

            $res->free();

            return $rows;
        }
    } // get_emails($usr_file, $use_db = 0, $db_conn = 0)

    function read_messages($msg_file, $usr_file, $full = 0, $use_db = 0,
        $db_conn = 0) {
        if (!$use_db) {
            $mails = get_emails($usr_file, 0);
            $mfp = fopen($msg_file, "r");
            wait_read_lock($mfp);
            $f = file($msg_file);
            $n = 0;
            for ($i = 0; $i < sizeof($f); $i++) {
                if ($f[$i] != "") {
                    if ((!$full) && ereg("[^:]*:[^:]*:\*", $f[$i], $regs))
                        continue;
                    $ret[$n]["time"] = strtok($f[$i], ":");
                    $ret[$n]["name"] = rawurldecode(strtok(":"));
                    $ret[$n]["message"] = trim(rawurldecode(strtok(":")));
                    $ret[$n]["email"] = $mails[$ret[$n]["name"]];
                    $n++;
                }
            }
            release_lock($mfp);
            return $ret;
        }
        else {
            // Use DB
            if (!$db_conn)
                return false;

            $sql = sprintf("SELECT author_id, created AS time, " .
                "text AS message FROM %s", $msg_file);
            if (!$full)
                $sql .= " WHERE flags = 0";

            $res = $db_conn->query($sql);
            if (DB::isError($res))
                return false;

            $j = 0;
            while ($row = $res->fetchRow()) {
                $authors[$row["author_id"]][] = $j;
                $t = $row["time"];

                $row["time"] = mktime(
                    $row["time"][8] . $row["time"][9],
                    $row["time"][10] . $row["time"][11],
                    $row["time"][12] . $row["time"][13],
                    $row["time"][4] . $row["time"][5],
                    $row["time"][6] . $row["time"][7],
                    $row["time"][0] . $row["time"][1] .
                    $row["time"][2] . $row["time"][3]
                );

                $row["message"] = rawurldecode($row["message"]);
                $messages[$j++] = $row;
            }
            $res->free;

            $sql = sprintf("SELECT id, nick AS name, email FROM %s", $usr_file);
            if (is_array($authors)) {
                $sql .= " WHERE";
                $ids = array_keys($authors);
                for ($i = 0;;) {
                    $sql .= " id = '" . $db_conn->quote($ids[$i]) . "'";

                    if ($i < sizeof($ids))
                        break;

                    if ((++$i) < sizeof($ids))
                        $sql .= " OR";
                }
            }

            $res = $db_conn->query($sql);

            if (DB::isError($res))
                return false;

            while ($row = $res->fetchRow())
                for ($i = 0; $i < sizeof($authors[$row["id"]]); $i++) {
                    $messages[$authors[$row["id"]][$i]]["name"] = rawurldecode($row["name"]);
                    $messages[$authors[$row["id"]][$i]]["email"] = $row["email"];
                }

            $res->free();

            return $messages;
        }
    }

    function need_to_split($a, $max, $min) {
        if ((sizeof($a) - $max) <= $min)
            return false;
        else
            return true;
    } // need_to_split($a, $max, $min)

    function split_messages_to_more_files($msgs, $max_len, $min_len,
    $hist_dir, $hist_file_prefix = "board_hist_file_", $index_style = 0) {
        if (!need_to_split($msgs, $max_len, $min_len))
            return $msgs;
        $full = array_chunk($msgs, $max_len);

        $d = opendir($hist_dir);
        $i = -1;
        $max_num = -1;
        // looking for previous save of maximum index (and count of saves)
        while (($file = readdir($d)) !== false) {
            if (ereg("^$hist_file_prefix([0-9]*)", $file, $regs)) {
                $i++;
                if ($max_num < $regs[1])
                    $max_num = $regs[1];
            }
        }
        closedir($d);

        switch($index_style) {
            case "0":
                $new_index = $max_num + 1;
                break;
            case "1":
                $new_index = ++$i;
                break;
        }

        for($i = 0; $i < (sizeof($full) - 1); $i++) {
            $new_file = $hist_dir . $hist_file_prefix . ($new_index + $i);
            $fp = fopen($new_file, "a");
            wait_write_lock($fp);
            fwrite($fp, implode($full[$i], ""));
            release_lock($fp);
        }
        $msgs = $full[sizeof($full) - 1];

        return $msgs;
    }

    function validate_message($message, $allowed_tags) {
        $message = trim($message);
        //some fun :)
        $message = ereg_replace("ignor[^a-zA-Z]*", "igno-what? &copy; Wol ", $message);
        $message = rawurlencode(nl2br(htmlspecialchars($message)));

        for ($i = 0; $i < sizeof($allowed_tags); $i++) {
            $message = str_replace(
                rawurlencode(htmlspecialchars($allowed_tags[$i])),
                $allowed_tags[$i],
                $message
            );
        }

        return $message;
    } // validate_message($message, $allowed_tags)

    function write_message($msg_file, $usr_file, $user = "Anonym", $text = "<no message>",
        $time = 0, $old_messages_folder, $max_msgs_in_one_file, $min_msgs_in_board,
        $hist_file_prefix, $allowed_tags, $use_db = 0, $db_conn = 0) {

        if (($time == 0) || !ereg("^[0-9]*$", $time))
            $time = time();
        $text = validate_message($text, $allowed_tags);

        if (!$use_db) {
            // Use files
            $user = rawurlencode($user);
            if ($text[0] == '*')    // this is used as the deleted flag prefix
                $text = " " . $text;
            $new_msg =
                "$time:$user:$text\n";
            $msgs = file($msg_file);
            $msgs[] = $new_msg;

            if (need_to_split($msgs, $max_msgs_in_one_file,
                                        $min_msgs_in_board)) {
                $fp = fopen($msg_file, "w");
                wait_write_lock($fp);
                sort($msgs);
                $msgs = split_messages_to_more_files(
                    $msgs,
                    $max_msgs_in_one_file,
                    $min_msgs_in_board,
                    $old_messages_folder,
                    $hist_file_prefix,
                    0
                );
                $msgs = implode($msgs, "");
                if (trim($msgs) == "")
                    $msgs = "";
                fwrite($fp, $msgs);
            }
            else {
                unset($msgs);
                $fp = fopen($msg_file, "a");
                wait_write_lock($fp);
                fwrite($fp, $new_msg);
            }

            release_lock($fp);
            fclose($fp);
            return 1;
        }
        else {
            // Use DB
            // $msg_file stores Message Table name
            if (!$db_conn)
                return false;

            // get the authors id
            $sql = sprintf("SELECT id FROM %s WHERE nick=%s",
                $usr_file, $db_conn->quote($user));
            $author_id = $db_conn->getOne($sql);

            if (DB::isError($author_id))
                return false;

            /*
            $row = $res->fetchRow();
            $res->free();
            $author_id = $row["id"];
            */

            $sql = sprintf("INSERT INTO %s (author_id, created, text) VALUES " .
                "(%s, sysdate(), %s)",
                $msg_file, $db_conn->quote($author_id), $db_conn->quote($text));
            $res = $db_conn->query($sql);

            return !(DB::isError($res));
        }
    }


    function delete_message($msg_file, $usr_file, $user, $time, $pass,
        $use_virtual_delete, $use_db = 0, $db_conn = 0) {
        if (!$use_db) {
            // Use files
            $found = false;
            $i = 0;
            $fp = fopen($usr_file, "r");
            wait_read_lock($fp);
            $p = file($usr_file);
            release_lock($fp);
            if ($user != "") {
                while ((!$found) && ($i < sizeof($p))) {
                    if ($user == get_user($p[$i], 0))
                        $found = true;
                    $i++;
                };
            }
            else
                $found = true;

            if (!$found)
                return 1;

            if (!(($user == "") && ($pass == "")))
                if (get_pass($p[--$i]) != md5($pass))
                    return 2;

            $fp = fopen($msg_file, "r");
            wait_read_lock($fp);
            $f = file($msg_file);
            $found = false;
            $i = 0;
            while (!$found && ($i < sizeof($f))) {
                if (get_user($f[$i], 1) == $user && get_time($f[$i]) == $time)
                    $found = true;
                $i++;
            }
            if (!$found)
                return 3;
            $i--;

            if ($use_virtual_delete) {
                // if already marked as deleted then delete it really
                if (ereg("[^:]*:[^:]*:\*.*", $f[$i], $regs))
                    $f[$i] = $f[sizeof($f) - 1];
                // if not marked, mark it :)
                else
                    $f[$i] = ereg_replace("([^:]*:[^:]*:)(.*)", "\\1*\\2", $f[$i]);
            }
            else {
                if (sizeof($f) > 0) {
                    $f[$i] = $f[sizeof($f) - 1];
                }
                else
                    $f = array();
            }

            // we supppose the array to be sorted (sorting while insert)
            //sort($f);

            release_lock($fp);

            $fp = fopen($msg_file, "w");
            wait_write_lock($fp);
            if (is_array($f))
                fwrite($fp, trim(implode($f, "")) . "\n");
            else
                if (trim($f) != "")
                    fwrite($fp, trim($f) . "\n");
            release_lock($fp);
            fclose($fp);

            return 0;
        }
        else {
            // Use DB
            if (!$db_conn)
                return false;

            $pass = md5($pass);
            $time = date("YmdHis", $time);

            $sql = sprintf("SELECT id FROM %s WHERE nick=%s AND pass=%s",
                $usr_file, $db_conn->quote($user), $db_conn->quote($pass));
            $author_id = $db_conn->getOne($sql);

            if (DB::isError($author_id))
                return 2; // wrong password (or no such user)

            switch($use_virtual_delete) {
                case true:
                    $sql = sprintf("SELECT id FROM %s WHERE flags=1 AND author_id=%s " .
                        "AND created=%s",
                        $msg_file, $db_conn->quote($author_id), $db_conn->quote($time));
                    $res = $db_conn->query($sql);

                    if (DB::isError($res))
                        return false;

                    if ($res->numRows() == 0) {
                        $res->free();
                        $sql = sprintf("UPDATE %s SET created=%s, deleted=sysdate(), " .
                            "flags=1 WHERE author_id = %s AND created=%s",
                            $msg_file, $db_conn->quote($time),
                            $db_conn->quote($author_id), $db_conn->quote($time));
                        break;
                    }
                    // else continue to hard delete
                case false:
                    $sql = sprintf("DELETE FROM %s WHERE author_id=%s AND created=%s",
                        $msg_file, $db_conn->quote($author_id), $db_conn->quote($time));
            }
            //echo "!@#$sql#@!";
            $res = $db_conn->query($sql);

            if (DB::isError($res))
                return 4; // unknown error (or No such message)
            else
                return 0;
        }
    }

    function show_root_login_form($rootnick, $user_nick = '') {
        global $self;
        echo "\n<center><h3><b>Admin login</b></h3><br><br>";
        echo "\n<center>\n<form name=rootlogin method=get action=$self>\n";
        echo create_hidden_inputs(split_url_vars(link_replace(link_replace(create_link(), 'nick', $rootnick), 'newnick', $user_nick)));
        echo "<table align=center>\n";
        echo "\t\n<tr>\n\t\t<td>Password:</td><td><input type=password name=pass></td></tr>\n";
        echo "\t\n<tr>\n\t\t<td colspan=2 align=center><input type=submit name=submit_type value=Login>\n</td></tr>\n";
        echo "\t<tr><td align=center colspan=2><a href=$self?" .
            create_link() .
            ">cancel</a></td></tr>\n";
        echo "</table>\n";
        echo "</form>\n</center>\n";
    } // show_root_login_form($rootnick, $user_nick)
    
    function show_data_form($user_file, $self, $nick, $message,
        $style, $WB_name, $autorefresh, $pagesize, $use_db = 0, $db_conn = 0) {
        // TODO !!!!!!
        global $headframe;
        global $bodyframe;
        global $show_body;
        global $frameset;
?>
<center>
<h3><?echo $WB_name?></h3>
Current time is <?echo format_time(time())?>.
<br>
<table border=0>
<form name=data method=GET action="<?echo "$self"?>" target="<?echo $bodyframe?>">
<?
        $tmp = link_replace(create_link(), 'page', '');
        if (good($frameset))
            $tmp = link_replace($tmp, 'disablepart', '2');
        echo create_hidden_inputs(split_url_vars($tmp));
?>
<tr>
    <td align=center valign=middle rowspan=3>
        <textarea name="message" cols=40 rows=<?
    echo (sizeof(explode("\n",$message)) + 5)?>><?echo $message?></textarea></td>
    <td align=center valign=middle>Nick</td>
    <td align=left valign=middle>
        <select name="nick">
            <option value="Anonym">&lt;choose&gt;</option>
<?
        $nicknames = get_users($user_file, $use_db, $db_conn);

        if (good($nicknames)) {
            sort($nicknames);
            show_options(
                $nicknames,
                $nicknames,
                $nick);
        }

        unset($nicknames);
?>
        </select>
    </td>
</tr>
<tr>
    <td valign=middle align=center colspan=1 rowspan=1><input type=submit name=submit_type value="Send"<?
        // TODO redo the JS inline function (it doesn't clear the memo now)
        if (!$show_body)
            echo " onClick=\"javascript:submit();message.value=''\"";

?>></td>
    <td align=center>
        <a href="<?echo $self . "?" . link_replace(create_link(), "createuser", "1")?>">New nick</a>
    </td>
</tr>
<tr></tr>
<tr>
    <td align=right><?
        if (!$style)
            echo "Board /</td><td><a href=$self?" .
                link_replace(create_link(), "style", "1") . ">Chat</a></td>";
        else
            echo "<a href=$self?" . link_replace(create_link(), "style", "0") .
                ">Board</a> /</td><td>Chat</td>";
?>
</tr>
<tr>
    <td align=center colspan=1>Autorefresh time:
        <select name=autorefresh onChange="javascript:form.submit()">
<?
        show_options(
            array("10 secs", "30 secs", "1 min", "5 min", "10 min", "30 min", "infinite"),
            array("10", "30", "60", "300", "600", "1800", "999999999"),
            $autorefresh);
?>
        </select>
    </td><td align=center colspan=1>Page size:
        <select name=pagesize onChange="javascript:form.submit()">
<?
        show_options(
            array("10", "25", "50", "100", "all"),
            array("10", "25", "50", "100", "999999"),
            $pagesize);
?>
        </select>
    </td>
    <td align=center>
        <a href="<?
        echo "$self?" . link_replace(link_replace(create_link(), "setframes", 1), "disablepart", 3);
?>" target=_top>Switch to frames</a> <font size=-3><a href="<?
        echo $self . '?' . link_replace(create_link(), 'rootlogin', '1');
?>">&pi;</a></font>
    </td>
</tr>
</form>
</table>
</center>
<?
        return 1;
    }

    function show_page_walk($currentpage, $pagesize, $nummsgs, $firstmsg, $lastmsg) {
        global $self;
        $lastpage = ceil($nummsgs / $pagesize);

        echo "<center>Messages " . ($firstmsg + 1) . "-" .
            ($lastmsg + 1) . " of $nummsgs<br>";

        // REWIND to begin
        if ($firstmsg == 0)
            echo "&lt;&lt;";
        else
            echo "<a href=$self?" . link_replace(create_link(), "page", "1") . ">&lt;&lt;</a>";
        echo " ";

        // PREVIOUS PAGE
        if ($firstmsg == 0)
            echo "&lt;";
        else
            echo "<a href=$self?" . link_replace(create_link(), "page", ($currentpage-1)) .
                ">&lt;</a>";

        echo " ";

        // OTHER PAGES
        for ($i = 1; $i <= $lastpage; $i++) {
            echo ($i == $currentpage) ? "$i " : "<a href=$self?" .
                link_replace(create_link(), "page", $i) . ">" . $i . "</a> ";
        }

        // NEXT PAGE
        if ($lastmsg >= ($nummsgs - 1))
            echo "&gt;";
        else
            echo "<a href=$self?" .
                link_replace(create_link(), "page", ($currentpage+1)) .
                ">&gt;</a>";

        echo " ";

        // REWIND PAGE to end
        if ($lastmsg >= ($nummsgs - 1))
            echo "&gt;&gt;";
        else
            echo "<a href=$self?" .
                link_replace(create_link(), "page", $lastpage) .
                ">&gt;&gt;</a>";

        echo "</center>\n";
    } // show_page_walk($currentpage, $pagesize, $nummsgs, $firstmsg, $lastmsg)

    function show_nonrefresh_head() {
        global $WB_name, $WB_version;
?>
<html>
<head>
<title><?echo "$WB_name v$WB_version"?></title>
<link rel="stylesheet" href="<?echo $css_file?>" type="text/css">
</head>
<body>
<?
    } // show_nonrefresh_head()

    function show_delete_dialog($nick, $time) {
        global $self;
        echo "\n<center><h3><b>Delete message</b></h3><br><br>";
        echo "\n<center>\n<form name=deletemessage method=get action=$self>\n";
        echo create_hidden_inputs(split_url_vars(link_replace(link_replace(create_link(), "deleteok", 1), "time", $time)));
        echo "<table align=center>\n";
        echo "\t\n<tr>\n\t\t<td>Your Nick:</td><td><input type=text value=\"$nick\" readonly></td></tr>\n";
        echo "\t\n<tr>\n\t\t<td>Message No.:</td><td><input type=text value=\"$time\" readonly></td></tr>\n";
        echo "\t\n<tr>\n\t\t<td>Password:</td><td><input type=password name=pass></td></tr>\n";
        echo "\t\n<tr>\n\t\t<td colspan=2 align=center><input type=submit name=submit_type value=Delete>\n</td></tr>\n";
        echo "\t<tr><td align=center colspan=2><a href=$self?" .
            create_link() .
            ">cancel</a></td></tr>\n";
        echo "</table>\n";
        echo "</form>\n</center>\n";
    } // show_delete_dialog($nick, $time)

    function show_createuser_dialog($newnick, $email) {
        global $self;
        echo "\n<center><h3><b>Create new user</b></h3><br><br>";
        echo "<table size=90% align=center>\n";

        echo "\n<form name=createuser method=get action=$self>";
        echo create_hidden_inputs(split_url_vars(
            link_replace(link_replace(
                create_link(), "createok", 1), "createuser", 1
            )));
        echo "\t<tr>\n\t\t<td>New Nick:</td><td><input type=text name=newnick maxsize=16 value=$newnick></td>\n";
        echo "\t<tr><td>E-mail:</td><td><input type=text name=mail value=$email></td>\n\t</tr>\n";
        echo "\t<tr><td>Password:</td><td><input type=password name=pass></td>\n\t</tr>\n";
        echo "\t<tr><td align=center colspan=2><input type=submit name=submit_type value=Create></td>\n\t</tr>\n";
        echo "\t<tr><td align=center colspan=2><a href=$self?" .
            link_replace(create_link(), "createuser", "") .
            ">cancel</a></td></tr>\n";
        echo "</form>\n</table>\n</center>\n";
    } // show_createuser_dialog($newnick, $email)

    function show_message($message, $style = 0) {
        global $self;
        global $headframe;
        switch($style) {
            case 1:
            // Chat message line
                echo "<tr><td valign=top class=time>";
                echo "<a href=$self?" .
                    link_replace(
                        link_replace(
                            create_link(), "time", $message["time"]
                            ),
                        "nick",
                        $message["name"]) .
                    " class=time>" . format_time($message["time"], 1) . "</a></td>";
                if ($message["email"] != "")
                    echo "<td valign=top class=email><a href=\"mailto:" . $message["email"] .
                        "\">" . $message["name"] . "</a>";
                else
                    echo "<td valign=top class=nick>" . $message["name"];
                echo ":</td><td class=msg width=99%>" . $message["message"];
                echo "</td></tr>\n";
                break;
            default:
            // Board message style
                // remark this /* to a //* and the modes will switch
                /*
                echo "<tr><td valign=top class=email>";
                if ($message["email"] != "")
                    echo "<a href=\"mailto:" . $message["email"] . "\">\n";
                echo $message["name"] . "</a></td>\n";
                echo "\t<td class=time>" . format_time($message["time"]) . "</td>";
                echo "<td><a href=$self?" .
                    link_replace(
                        link_replace(
                            create_link(), "time", $message["time"]
                            ),
                        "nick",
                        $message["name"]) .
                    ">delete</a>\n";
                echo "</td></tr><tr><td colspan=3>";
                echo "\t" . $message["message"] . "\n";
                echo "</td></tr>\n";
                /*/
                echo "<tr><td valign=top>";
                if ($message["email"] != "")
                    echo "<a href=\"mailto:" . $message["email"] . "\">\n";
                echo $message["name"] . "</a>\n";
                echo "" . format_time($message["time"]) . "";
                echo " <a href=$self?" .
                    link_replace(
                        link_replace(
                            create_link(), "time", $message["time"]
                            ),
                        "nick",
                        $message["name"]) .
                    ">delete</a>\n";
                echo "<a href=$self?" .
                    link_replace(
                        create_link(),
                        "reply_to",
                        rawurlencode($message["name"]."#".$message["time"])
                    ) .
                    " target=$headframe>reply</a>\n";
                echo "</td></tr><tr><td>";
                echo "\t" . $message["message"] . "\n";
                echo "</td></tr>\n";
                
                //*/
                break;
        }
    } // show_message($message, $style = 0)

    function show_messages($message_file, $user_file, $page, $pagesize,
        $msg_style = 0, $show_all = 0, $use_db = 0, $db_conn = 0) {

        $messages = read_messages($message_file, $user_file, $show_all,
            $use_db, $db_conn);

        if (!good($messages))
            $messages = array();
        $n = sizeof($messages);
        global $self;

        if ($n <= 0) {
            echo "<center><font color=red><b>No messages YeT !</b></font></center>";
        }
        else {
            if ($page < 1)
                $page = 1;
            if ($page >= ($n / $pagesize))
                $page = ceil($n / $pagesize);

            $first = $pagesize * ($page - 1);
            $last = ($pagesize * $page) - 1;

            if ($first < 0)
                $first = 0;
            if ($first > $n)
                $first = $n - 1;

            if ($last > ($n - 1))
                $last = $n - 1;
            if ($last < $first)
                $last = $first;

            show_page_walk($page, $pagesize, $n, $first, $last);

            echo "<table border=0>";
            for ($i = $first; $i <= $last; $i++) {
                show_message($messages[sizeof($messages) - 1 - $i], $msg_style);
            }
            echo "</table>";

            show_page_walk($page, $pagesize, $n, $first, $last);
        }
    }


// ///////////////////////////////////////////////
// /////////// THIS IS MAIN FUNCTION /////////////
// ///////////////////////////////////////////////

    // DEFAULTS

    if (!good($self))
        $self = $PHP_SELF;
    
    $abs_self = "http://" . $GLOBALS["HTTP_HOST"] . $self;

    header ("Cache-Control: no-cache, must-revalidate");
    header ("Pragma: no-cache");

    if ($strip_slashes) {
        $message = stripslashes($message);
        $nick = stripslashes($nick);
        $pass = stripslashes($pass);
        $header = stripslashes($header);
        $body = stripslashes($body);
        $bodyframe = stripslashes($bodyframe);
        $headerframe = stripslashes($headerframe);
        $disablepart = stripslashes($disablepart);
        $newnick = stripslashes($newnick);
    }


    settype($pagesize, integer);
    if ($pagesize < 10)
        $pagesize = 50;

    settype($autorefresh, integer);
    if ($autorefresh < 10)
        $autorefresh = 300;

    if (!good($disablepart) || ($disablepart > 3) || ($disablepart < 0))
        $disablepart = 0;

    if (!good($headframe))
        $headframe = $DEFAULT_HEAD_FRAME;

    if (!good($bodyframe))
        $bodyframe = $DEFAULT_BODY_FRAME;

    switch ($disablepart) {
        case 0:
            $show_body = true;
            $show_head = true;
            break;
        case 1:
            $show_head = true;
            $show_body = false;
            break;
        case 2:
            $show_head = false;
            $show_body = true;
            break;
        case 3:
            $show_body = false;
            $show_head = false;
            break;
    }

    if (!good($page))
        $page = 0;

    // check for superuser view
    if ($nick == $root_name) {
        if (md5($pass) == $root_md5_password)
            $superuser = 1;
        else {
            unset($nick);
            $superuser = 0;
        }
    }
    
    // SHOW ROOT LOGIN FORM
    if ($rootlogin) {
        show_nonrefresh_head();
        show_root_login_form($root_name, $nick);
        $show_body = false;
        $show_head = false;
    }

    if (!isset($nick) && good($newnick))
        $nick = $newnick;

    if (!good($mail))
        $mail = get_email($nick);

    if (good($archive))
        $hist_file_prefix = $archive;

    if (good($archive_no) && !$use_db)
        $message_file = $old_messages_folder . $hist_file_prefix . $archive_no;

    if ($use_db) {
        require_once "DB.php";

        $db_handle = DB::connect("mysql://$db_user:$db_pass"
                                . "@$db_host/$db_database");
        if (DB::isError($db_handle)) {
            echo $db_handle->getMessage();
            $db_handle = 0;
            $use_db = 0;
            //exit;
        }
        if ($use_db) {
            $db_handle->setFetchMode(DB_FETCHMODE_ASSOC);
            $user_file = $db_user_table;
            $message_file = $db_message_table;
        }
    }

    // Insert quoted REPLY TO message
    if (good($reply_to)) {
        $pivot = strrpos($reply_to, "#");
        if (!($pivot === false)) {
            $tmp_name = substr($reply_to, 0, $pivot);
            $tmp_time = substr($reply_to, $pivot + 1);
            $messages = read_messages($message_file, $user_file, $superuser,
                $use_db, $db_conn);
            for ($i = 0; $i < sizeof($messages); $i++) {
                if (($messages[$i]["time"] == $tmp_time) &&
                    ($messages[$i]["name"] == $tmp_name)){
                    $found = true;
                    break;
                }
            }
            if ($found) {
                $tmp_msg = create_reply($messages[$i]);
                if (good($message)) {
                    $tmp_msg .= $message;
                }
                $message = $tmp_msg;
            $message = strip_tags($message);
            }
        }
    }
    
    // CREATE NEW USER
    if ($createuser) {
        $mails = get_emails($user_file, $use_db, $db_handle);
        if ((!($mails === false)) &&
            good($newnick) &&
            ($mails[$newnick] == "") &&
            good($createok) &&
            ($createok == 1)) {
            if (!write_mail($user_file, $newnick, $mail, $pass, $root_name, $use_db, $db_handle)) {
                //echo "drblo to"; // something failed, ignoring for now
                die();
            }

            header("HTTP/1.0 302 Found");
            header("Location: $abs_self?" . create_link());
            die();
        }
        else {
            show_nonrefresh_head();
            show_createuser_dialog($newnick, $email);
            $show_head = false;
            $show_body = false;
        }
    }

    // WRITE MESSAGE TO DB
    if (good($message) && good($submit_type)) {
        if (write_message($message_file, $user_file, $nick, $message, 0,
            $old_messages_folder, $max_msgs_in_one_file, $min_msgs_in_board,
            $hist_file_prefix, $allowed_tags, $use_db, $db_handle))
            ; // something failed, ignoring for now

        $message = '';
        header('HTTP/1.0 302 Found');
        header("Location: $abs_self?" . create_link());
        die();
    }

    // DELETE MESSAGE FROM DB
    if (good($time)) {
        if (good($deleteok) && ($deleteok == 1)){
            header('HTTP/1.0 302 Found');
            header("Location: $abs_self?" . create_link());
            switch(delete_message($message_file, $user_file, $nick,
                $time, $pass, $use_virtual_delete, $use_db, $db_handle)) {
                case 0: // All OK
                    echo "<center>Message deleted succesfully<br></center>\n";
                    break;
                case 1: // No such user
                    echo "<center>Error while deleting: There is no such user!<br></center>\n";
                    break;
                case 2: // Wrong password
                    echo "<center>Error while deleting: Wrong password!<br></center>\n";
                    break;
                case 3: // No such message
                    echo "<center>Error while deleting: No such message!<br></center>\n";
                    break;
                default:// Unknown error
                    echo "<center>Fatal Error while deleting: unknown error code!</center><br>\n";
                    break;
            }
            die();
        } else {
            show_nonrefresh_head();
            show_delete_dialog($nick, $time);
            $show_body = false;
            $show_head = false;
        }
    }


    // We don't want to show body, when other form is shown

?>
<html>
<head>
<title><?echo "$WB_name v$WB_version"?></title>
<link rel="stylesheet" href="<?echo $css_file?>" type="text/css">
</head>
<body>
<?
    /*
        If set, do nothing, just create frames and recursively call self
    */
    if (good($setframes)) {
        $frmlnk =
            link_replace(
                link_replace(
                    link_replace(create_link(), "frameset", 1),
                    "bodyframe",
                    "bodyframe"),
                "headframe",
                "headframe"
            );
        echo "<frameset rows=\"230,*\" framespacing=0 cols=*>\n";
        echo "<frame name=headframe src=\"$self?" .
            link_replace($frmlnk, "disablepart", 1) .
            "\">\n";
        echo "<frame name=bodyframe src=\"$self?" .
            link_replace($frmlnk, "disablepart", 2) .
            "\" scrolling=AUTO>\n";
        echo "</frameset>\n";
        echo "</html>";
        $show_body = false;
        $show_head = false;
    }

    if ($show_head) {
        show_data_form($user_file, $self, $nick, $message, $style,
            $WB_name, $autorefresh, $pagesize, $use_db, $db_handle);
    }

    if ($show_body) {
        echo "<meta HTTP-EQUIV=\"Refresh\" CONTENT=\"$autorefresh URL=$self?" .
            create_link() . "\">\n";
        show_messages($message_file, $user_file, $page, $pagesize,
            $style, $superuser, $use_db, $db_handle);
    }

    if ($use_db && $db_handle) {
        $db_handle->disconnect();
    }
?>
</body>
</html>

Platon Group <platon@platon.sk> http://platon.sk/
Copyright © 2002-2006 Platon Group
Stránka používa redakčný systém Metafox
Na začiatok