function rebuild_forum_view($forum_id, $page = 0)
{
    if (!db_locked()) {
        $ll = 1;
        db_lock('phpgw_fud_thread_view WRITE, phpgw_fud_thread WRITE, phpgw_fud_msg WRITE, phpgw_fud_forum WRITE');
    }
    $tm = __request_timestamp__;
    /* Remove expired moved thread pointers */
    q('DELETE FROM phpgw_fud_thread WHERE forum_id=' . $forum_id . ' AND last_post_date<' . ($tm - 86400 * $GLOBALS['MOVED_THR_PTR_EXPIRY']) . ' AND moved_to!=0');
    if ($aff_rows = db_affected()) {
        q('UPDATE phpgw_fud_forum SET thread_count=thread_count-' . $aff_rows . ' WHERE id=' . $forum_id);
        $page = 0;
    }
    /* De-announce expired announcments and sticky messages */
    $r = q("SELECT phpgw_fud_thread.id FROM phpgw_fud_thread INNER JOIN phpgw_fud_msg ON phpgw_fud_thread.root_msg_id=phpgw_fud_msg.id WHERE phpgw_fud_thread.forum_id=" . $forum_id . " AND thread_opt>=2 AND (phpgw_fud_msg.post_stamp+phpgw_fud_thread.orderexpiry)<=" . $tm);
    while ($tid = db_rowarr($r)) {
        q("UPDATE phpgw_fud_thread SET orderexpiry=0, thread_opt=thread_opt & ~ (2|4) WHERE id=" . $tid[0]);
    }
    unset($r);
    if (__dbtype__ == 'pgsql') {
        $tmp_tbl_name = "phpgw_fud_ftvt_" . get_random_value();
        q("CREATE TEMP TABLE " . $tmp_tbl_name . " ( forum_id INT NOT NULL, page INT NOT NULL, thread_id INT NOT NULL, pos SERIAL, tmp INT )");
        if ($page) {
            q("DELETE FROM phpgw_fud_thread_view WHERE forum_id=" . $forum_id . " AND page<" . ($page + 1));
            q("INSERT INTO " . $tmp_tbl_name . " (thread_id,forum_id,page,tmp) SELECT phpgw_fud_thread.id, phpgw_fud_thread.forum_id, 2147483647, CASE WHEN thread_opt>=2 AND (phpgw_fud_msg.post_stamp+phpgw_fud_thread.orderexpiry>" . $tm . " OR phpgw_fud_thread.orderexpiry=0) THEN 2147483647 ELSE phpgw_fud_thread.last_post_date END AS sort_order_fld  FROM phpgw_fud_thread INNER JOIN phpgw_fud_msg ON phpgw_fud_thread.root_msg_id=phpgw_fud_msg.id WHERE forum_id=" . $forum_id . " AND phpgw_fud_msg.apr=1 ORDER BY sort_order_fld DESC, phpgw_fud_thread.last_post_id DESC LIMIT " . $GLOBALS['THREADS_PER_PAGE'] * $page);
        } else {
            q("DELETE FROM phpgw_fud_thread_view WHERE forum_id=" . $forum_id);
            q("INSERT INTO " . $tmp_tbl_name . " (thread_id,forum_id,page,tmp) SELECT phpgw_fud_thread.id, phpgw_fud_thread.forum_id, 2147483647, CASE WHEN thread_opt>=2 AND (phpgw_fud_msg.post_stamp+phpgw_fud_thread.orderexpiry>" . $tm . " OR phpgw_fud_thread.orderexpiry=0) THEN 2147483647 ELSE phpgw_fud_thread.last_post_date END AS sort_order_fld  FROM phpgw_fud_thread INNER JOIN phpgw_fud_msg ON phpgw_fud_thread.root_msg_id=phpgw_fud_msg.id WHERE forum_id=" . $forum_id . " AND phpgw_fud_msg.apr=1 ORDER BY sort_order_fld DESC, phpgw_fud_thread.last_post_id DESC");
        }
        q("INSERT INTO phpgw_fud_thread_view (thread_id,forum_id,page,pos) SELECT thread_id,forum_id,CEIL(pos/" . $GLOBALS['THREADS_PER_PAGE'] . ".0),(pos-(CEIL(pos/" . $GLOBALS['THREADS_PER_PAGE'] . ".0)-1)*" . $GLOBALS['THREADS_PER_PAGE'] . ") FROM " . $tmp_tbl_name);
        q("DROP TABLE " . $tmp_tbl_name);
        return;
    } else {
        if (__dbtype__ == 'mysql') {
            if ($page) {
                q('DELETE FROM phpgw_fud_thread_view WHERE forum_id=' . $forum_id . ' AND page<' . ($page + 1));
                q("INSERT INTO phpgw_fud_thread_view (thread_id,forum_id,page,tmp) SELECT phpgw_fud_thread.id, phpgw_fud_thread.forum_id, 2147483645, CASE WHEN thread_opt>=2 AND (phpgw_fud_msg.post_stamp+phpgw_fud_thread.orderexpiry>" . $tm . " OR phpgw_fud_thread.orderexpiry=0) THEN 4294967294 ELSE phpgw_fud_thread.last_post_date END AS sort_order_fld  FROM phpgw_fud_thread INNER JOIN phpgw_fud_msg ON phpgw_fud_thread.root_msg_id=phpgw_fud_msg.id WHERE forum_id=" . $forum_id . " AND phpgw_fud_msg.apr=1 ORDER BY sort_order_fld DESC, phpgw_fud_thread.last_post_id DESC LIMIT 0, " . $GLOBALS['THREADS_PER_PAGE'] * $page);
                q('UPDATE phpgw_fud_thread_view SET page=CEILING(pos/' . $GLOBALS['THREADS_PER_PAGE'] . '), pos=pos-(CEILING(pos/' . $GLOBALS['THREADS_PER_PAGE'] . ')-1)*' . $GLOBALS['THREADS_PER_PAGE'] . ' WHERE forum_id=' . $forum_id . ' AND page=2147483645');
            } else {
                q('DELETE FROM phpgw_fud_thread_view WHERE forum_id=' . $forum_id);
                q("INSERT INTO phpgw_fud_thread_view (thread_id,forum_id,page,tmp) SELECT phpgw_fud_thread.id, phpgw_fud_thread.forum_id, 2147483645, CASE WHEN thread_opt>=2 AND (phpgw_fud_msg.post_stamp+phpgw_fud_thread.orderexpiry>" . $tm . " OR phpgw_fud_thread.orderexpiry=0) THEN 4294967294 ELSE phpgw_fud_thread.last_post_date END AS sort_order_fld  FROM phpgw_fud_thread INNER JOIN phpgw_fud_msg ON phpgw_fud_thread.root_msg_id=phpgw_fud_msg.id WHERE forum_id=" . $forum_id . " AND phpgw_fud_msg.apr=1 ORDER BY sort_order_fld DESC, phpgw_fud_thread.last_post_id DESC");
                q('UPDATE phpgw_fud_thread_view SET page=CEILING(pos/' . $GLOBALS['THREADS_PER_PAGE'] . '), pos=pos-(CEILING(pos/' . $GLOBALS['THREADS_PER_PAGE'] . ')-1)*' . $GLOBALS['THREADS_PER_PAGE'] . ' WHERE forum_id=' . $forum_id);
            }
        }
    }
    if (isset($ll)) {
        db_unlock();
    }
}
function fud_sql_error_handler($query, $error_string, $error_number, $server_version)
{
    if (db_locked()) {
        if (__dbtype__ == 'mysql' && $query != 'UNLOCK TABLES' || __dbtype__ == 'pgsql' && $query != 'COMMIT WORK') {
            db_unlock();
        }
    }
    if (function_exists("debug_backtrace")) {
        $tmp = debug_backtrace();
        $_SERVER['PATH_TRANSLATED'] = '';
        foreach ($tmp as $v) {
            $_SERVER['PATH_TRANSLATED'] .= "{$v['file']}:{$v['line']}<br />\n";
        }
    } else {
        if (!isset($_SERVER['PATH_TRANSLATED'])) {
            $_SERVER['PATH_TRANSLATED'] = realpath(__FILE__);
        }
    }
    $error_msg = "(" . $_SERVER['PATH_TRANSLATED'] . ") " . $error_number . ": " . $error_string . "<br />\n";
    $error_msg .= "Query: " . htmlspecialchars($query) . "<br />\n";
    $error_msg .= "Server Version: " . $server_version . "<br />\n";
    if (isset($_SERVER['HTTP_REFERER'])) {
        $error_msg .= "[Referring Page] " . $_SERVER['HTTP_REFERER'] . "<br />\n";
    }
    if (!error_log('[' . gmdate("D M j G:i:s T Y", __request_timestamp__) . '] ' . base64_encode($error_msg) . "\n", 3, $GLOBALS['ERROR_PATH'] . 'sql_errors')) {
        echo "<b>UNABLE TO WRITE TO SQL LOG FILE</b><br>\n";
        echo $error_msg;
    } else {
        if (defined('forum_debug') || isset($GLOBALS['usr']->users_opt) && $GLOBALS['usr']->users_opt & 1048576) {
            echo $error_msg;
        } else {
            trigger_error('SQL Error has occurred, please contact the <a href="mailto:' . $GLOBALS['ADMIN_EMAIL'] . '?subject=SQL%20Error">administrator</a> of the forum and have them review the forum&#39;s SQL query log', E_USER_ERROR);
            if (ini_get('display_errors') !== 1) {
                exit('SQL Error has occurred, please contact the <a href="mailto:' . $GLOBALS['ADMIN_EMAIL'] . '?subject=SQL%20Error">administrator</a> of the forum and have them review the forum&#39;s SQL query log');
            }
        }
    }
    exit;
}
function write_pmsg_body($text)
{
    if (!db_locked()) {
        $ll = 1;
        db_lock('phpgw_fud_pmsg WRITE');
    }
    $fp = fopen($GLOBALS['MSG_STORE_DIR'] . 'private', 'ab');
    fseek($fp, 0, SEEK_END);
    if (!($s = ftell($fp))) {
        $s = __ffilesize($fp);
    }
    if (($len = fwrite($fp, $text)) !== strlen($text)) {
        exit("FATAL ERROR: system has ran out of disk space<br>\n");
    }
    fclose($fp);
    if (isset($ll)) {
        db_unlock();
    }
    if (!$s) {
        chmod($GLOBALS['MSG_STORE_DIR'] . 'private', $GLOBALS['FUD_OPT_2'] & 8388608 ? 0600 : 0666);
    }
    return array($s, $len);
}
    function approve($id, $unlock_safe = false)
    {
        /* fetch info about the message, poll (if one exists), thread & forum */
        $mtf = db_sab('SELECT
					m.id, m.poster_id, m.apr, m.subject, m.foff, m.length, m.file_id, m.thread_id, m.poll_id, m.attach_cnt,
					m.post_stamp, m.reply_to, m.mlist_msg_id,
					t.forum_id, t.last_post_id, t.root_msg_id, t.last_post_date,
					m2.post_stamp AS frm_last_post_date,
					f.name AS frm_name,
					u.alias, u.email, u.sig,
					n.id AS nntp_id, ml.id AS mlist_id
				FROM phpgw_fud_msg m
				INNER JOIN phpgw_fud_thread t ON m.thread_id=t.id
				INNER JOIN phpgw_fud_forum f ON t.forum_id=f.id
				LEFT JOIN phpgw_fud_msg m2 ON f.last_post_id=m2.id
				LEFT JOIN phpgw_fud_users u ON m.poster_id=u.id
				LEFT JOIN phpgw_fud_mlist ml ON ml.forum_id=f.id
				LEFT JOIN phpgw_fud_nntp n ON n.forum_id=f.id
				WHERE m.id=' . $id . ' AND m.apr=0');
        /* nothing to do or bad message id */
        if (!$mtf) {
            return;
        }
        if ($mtf->alias) {
            reverse_fmt($mtf->alias);
        } else {
            $mtf->alias = $GLOBALS['ANON_NICK'];
        }
        if (!db_locked()) {
            db_lock('phpgw_fud_thread_view WRITE, phpgw_fud_level WRITE, phpgw_fud_users WRITE, phpgw_fud_forum WRITE, phpgw_fud_thread WRITE, phpgw_fud_msg WRITE');
            $ll = 1;
        }
        q("UPDATE phpgw_fud_msg SET apr=1 WHERE id=" . $mtf->id);
        if ($mtf->poster_id) {
            user_set_post_count($mtf->poster_id);
        }
        $last_post_id = $mtf->post_stamp > $mtf->frm_last_post_date ? $mtf->id : 0;
        if ($mtf->root_msg_id == $mtf->id) {
            /* new thread */
            rebuild_forum_view($mtf->forum_id);
            $threads = 1;
        } else {
            /* reply to thread */
            if ($mtf->post_stamp > $mtf->last_post_date) {
                th_inc_post_count($mtf->thread_id, 1, $mtf->id, $mtf->post_stamp);
            } else {
                th_inc_post_count($mtf->thread_id, 1);
            }
            rebuild_forum_view($mtf->forum_id, q_singleval('SELECT page FROM phpgw_fud_thread_view WHERE forum_id=' . $mtf->forum_id . ' AND thread_id=' . $mtf->thread_id));
            $threads = 0;
        }
        /* update forum thread & post count as well as last_post_id field */
        frm_updt_counts($mtf->forum_id, 1, $threads, $last_post_id);
        if ($unlock_safe || isset($ll)) {
            db_unlock();
        }
        if ($mtf->poll_id) {
            poll_activate($mtf->poll_id, $mtf->forum_id);
        }
        $mtf->body = read_msg_body($mtf->foff, $mtf->length, $mtf->file_id);
        if ($GLOBALS['FUD_OPT_1'] & 16777216) {
            index_text(preg_match('!Re: !i', $mtf->subject) ? '' : $mtf->subject, $mtf->body, $mtf->id);
        }
        /* handle notifications */
        if ($mtf->root_msg_id == $mtf->id) {
            if (empty($mtf->frm_last_post_date)) {
                $mtf->frm_last_post_date = 0;
            }
            /* send new thread notifications to forum subscribers */
            $c = uq('SELECT u.email, u.icq, u.users_opt
					FROM phpgw_fud_forum_notify fn
					INNER JOIN phpgw_fud_users u ON fn.user_id=u.id
					LEFT JOIN phpgw_fud_forum_read r ON r.forum_id=fn.forum_id AND r.user_id=fn.user_id
					INNER JOIN phpgw_fud_group_cache g1 ON g1.user_id=2147483647 AND g1.resource_id=' . $mtf->forum_id . '
					LEFT JOIN phpgw_fud_group_cache g2 ON g2.user_id=fn.user_id AND g2.resource_id=' . $mtf->forum_id . '
				WHERE
					fn.forum_id=' . $mtf->forum_id . ' AND fn.user_id!=' . (int) $mtf->poster_id . '
					AND (CASE WHEN (r.last_view IS NULL AND (u.last_read=0 OR u.last_read >= ' . $mtf->frm_last_post_date . ')) OR r.last_view > ' . $mtf->frm_last_post_date . ' THEN 1 ELSE 0 END)=1
					AND ((CASE WHEN g2.id IS NOT NULL THEN g2.group_cache_opt ELSE g1.group_cache_opt END) & 2) > 0');
            $notify_type = 'frm';
        } else {
            /* send new reply notifications to thread subscribers */
            $c = uq('SELECT u.email, u.icq, u.users_opt, r.msg_id, u.id
					FROM phpgw_fud_thread_notify tn
					INNER JOIN phpgw_fud_users u ON tn.user_id=u.id
					LEFT JOIN phpgw_fud_read r ON r.thread_id=tn.thread_id AND r.user_id=tn.user_id
					INNER JOIN phpgw_fud_group_cache g1 ON g1.user_id=2147483647 AND g1.resource_id=' . $mtf->forum_id . '
					LEFT JOIN phpgw_fud_group_cache g2 ON g2.user_id=tn.user_id AND g2.resource_id=' . $mtf->forum_id . '
				WHERE
					tn.thread_id=' . $mtf->thread_id . ' AND tn.user_id!=' . (int) $mtf->poster_id . '
					AND (r.msg_id=' . $mtf->last_post_id . ' OR (r.msg_id IS NULL AND ' . $mtf->post_stamp . ' > u.last_read))
					AND ((CASE WHEN g2.id IS NOT NULL THEN g2.group_cache_opt ELSE g1.group_cache_opt END) & 2) > 0');
            $notify_type = 'thr';
        }
        while ($r = db_rowarr($c)) {
            if ($r[2] & 16) {
                $to['EMAIL'] = $r[0];
            } else {
                $to['ICQ'] = $r[1] . '@pager.icq.com';
            }
            if (isset($r[4]) && is_null($r[3])) {
                $tl[] = $r[4];
            }
        }
        unset($c);
        if (isset($tl)) {
            /* this allows us to mark the message we are sending notification about as read, so that we do not re-notify the user
             * until this message is read.
             */
            q('INSERT INTO phpgw_fud_read (thread_id, msg_id, last_view, user_id) SELECT ' . $mtf->thread_id . ', 0, 0, id FROM phpgw_fud_users WHERE id IN(' . implode(',', $tl) . ')');
        }
        if (isset($to)) {
            send_notifications($to, $mtf->id, $mtf->subject, $mtf->alias, $notify_type, $notify_type == 'thr' ? $mtf->thread_id : $mtf->forum_id, $mtf->frm_name, $mtf->forum_id);
        }
        // Handle Mailing List and/or Newsgroup syncronization.
        if (($mtf->nntp_id || $mtf->mlist_id) && !$mtf->mlist_msg_id) {
            fud_use('email_msg_format.inc', true);
            reverse_fmt($mtf->alias);
            $from = $mtf->poster_id ? $mtf->alias . ' <' . $mtf->email . '>' : $GLOBALS['ANON_NICK'] . ' <' . $GLOBALS['NOTIFY_FROM'] . '>';
            $body = $mtf->body . ($mtf->msg_opt & 1 && $mtf->sig ? "\n--\n" . $mtf->sig : '');
            plain_text($body);
            plain_text($subject);
            if ($mtf->reply_to) {
                $replyto_id = q_singleval('SELECT mlist_msg_id FROM phpgw_fud_msg WHERE id=' . $mtf->reply_to);
            } else {
                $replyto_id = 0;
            }
            if ($mtf->attach_cnt) {
                $r = uq("SELECT a.id, a.original_name,\n\t\t\t\t\t\tCASE WHEN m.mime_hdr IS NULL THEN 'application/octet-stream' ELSE m.mime_hdr END\n\t\t\t\t\t\tFROM phpgw_fud_attach a\n\t\t\t\t\t\tLEFT JOIN phpgw_fud_mime m ON a.mime_type=m.id\n\t\t\t\t\t\tWHERE a.message_id=" . $mtf->id . " AND a.attach_opt=0");
                while ($ent = db_rowarr($r)) {
                    $attach[$ent[1]] = file_get_contents($GLOBALS['FILE_STORE'] . $ent[0] . '.atch');
                    if ($mtf->mlist_id) {
                        $attach_mime[$ent[1]] = $ent[2];
                    }
                }
            } else {
                $attach_mime = $attach = null;
            }
            if ($mtf->nntp_id) {
                fud_use('nntp.inc', true);
                $nntp_adm = db_sab('SELECT * FROM phpgw_fud_nntp WHERE id=' . $mtf->nntp_id);
                $nntp = new fud_nntp();
                $nntp->server = $nntp_adm->server;
                $nntp->newsgroup = $nntp_adm->newsgroup;
                $nntp->port = $nntp_adm->port;
                $nntp->timeout = $nntp_adm->timeout;
                $nntp->nntp_opt = $nntp_adm->nntp_opt;
                $nntp->login = $nntp_adm->login;
                $nntp->pass = $nntp_adm->pass;
                define('sql_p', 'phpgw_fud_');
                $lock = $nntp->get_lock();
                $nntp->post_message($mtf->subject, $body, $from, $mtf->id, $replyto_id, $attach);
                $nntp->close_connection();
                $nntp->release_lock($lock);
            } else {
                fud_use('mlist_post.inc', true);
                $GLOBALS['CHARSET'] = 'ISO-8859-15';
                $r = db_saq('SELECT name, additional_headers FROM phpgw_fud_mlist WHERE id=' . $mtf->mlist_id);
                mail_list_post($r[0], $from, $mtf->subject, $body, $mtf->id, $replyto_id, $attach, $attach_mime, $r[1]);
            }
        }
    }
function grp_rebuild_cache($user_id = null)
{
    $list = array();
    if ($user_id !== null) {
        $lmt = ' user_id IN(' . implode(',', $user_id) . ') ';
    } else {
        $lmt = '';
    }
    /* generate an array of permissions, in the end we end up with 1ist of permissions */
    $r = uq("SELECT gm.user_id AS uid, gm.group_members_opt AS gco, gr.resource_id AS rid FROM phpgw_fud_group_members gm INNER JOIN phpgw_fud_group_resources gr ON gr.group_id=gm.group_id WHERE gm.group_members_opt>=65536 AND (gm.group_members_opt & 65536) > 0" . ($lmt ? ' AND ' . $lmt : ''));
    while ($o = db_rowobj($r)) {
        foreach ($o as $k => $v) {
            $o->{$k} = (int) $v;
        }
        if (isset($list[$o->rid][$o->uid])) {
            if ($o->gco & 131072) {
                $list[$o->rid][$o->uid] |= $o->gco;
            } else {
                $list[$o->rid][$o->uid] &= $o->gco;
            }
        } else {
            $list[$o->rid][$o->uid] = $o->gco;
        }
    }
    $tmp_t = "phpgw_fud_gc_" . __request_timestamp__;
    q("CREATE TEMPORARY TABLE " . $tmp_t . " (a INT, b INT, c INT)");
    $tmp = array();
    foreach ($list as $k => $v) {
        foreach ($v as $u => $p) {
            $tmp[] = $k . ", " . $p . ", " . $u;
        }
    }
    if ($tmp) {
        if (__dbtype__ == 'mysql') {
            ins_m($tmp_t, "a,b,c", $tmp, 1);
        } else {
            ins_m($tmp_t, "a,b,c", $tmp, "integer, integer, integer");
        }
    }
    if (!db_locked()) {
        $ll = 1;
        db_lock("phpgw_fud_group_cache WRITE");
    }
    q("DELETE FROM phpgw_fud_group_cache" . ($lmt ? ' WHERE ' . $lmt : ''));
    q("INSERT INTO phpgw_fud_group_cache (resource_id, group_cache_opt, user_id) SELECT a,b,c FROM " . $tmp_t);
    if (isset($ll)) {
        db_unlock();
    }
    q("DROP TABLE " . $tmp_t);
}