<commit_before><?php

/**
 * This file controls all databsae access
 *
 * @author     <NAME> <<EMAIL>>
 * @copyright  1997-Present WC Blog Dev Team
 *
 */

require_once dirname(__FILE__)."/config.php";
require_once dirname(__FILE__)."/WCDB.php";

// Check that this file is not loaded directly.
if ( basename( __FILE__ ) == basename( $_SERVER["PHP_SELF"] ) ) exit();

// if init has not loaded, quit the file
if(!defined("WC")) exit("common.php not loaded");

/**
 * Generate the table names using the prefix
 */
$WC["settings_table"] = $WC["db_prefix"]."_settings";
$WC["pages_table"] = $WC["db_prefix"]."_pages";
$WC["posts_table"] = $WC["db_prefix"]."_posts";
$WC["users_table"] = $WC["db_prefix"]."_users";
$WC["comments_table"] = $WC["db_prefix"]."_comments";
$WC["tags_table"] = $WC["db_prefix"]."_tags";

/**
 * Create a new database object for these functions to use
 */
$WCDB = new WCDB($WC["db_server"], $WC["db_name"], $WC["db_user"], $WC["db_password"]);


/**
 * Gets the application settings.
 *
 * @return  array
 *
 */
function wc_db_get_settings(){

    global $WC, $WCDB;

    $sql = "select * from {$WC["settings_table"]}";

    $WCDB->query($sql);

    $settings = array();

    while($rec = $WCDB->fetch()){
        if($rec["S"]){
            $settings[$rec["name"]] = json_decode($rec["data"]);
        } else {
            $settings[$rec["name"]] = $rec["data"];
        }
    }

    return $settings;
}


/**
 * Save the application settings.
 *
 * @param   $settings Array of settings to save.
 * @return  void
 *
 */
function wc_db_save_settings($settings){

    global $WC, $WCDB;

    if(empty($settings)) return false;

    $success = false;

    $clean_arr = array();

    foreach($settings as $name=>$data){

        switch($name){
            case "session_days":
                $clean_arr[] = array("name"=>$name, "type"=>"V", "data"=>(int)$data);
                break;

            case "base_url":
            case "session_secret":
            case "session_path":
            case "session_domain":
            case "date_format_long":
            case "date_format_short":
            case "template":
            case "default_title":
            case "default_description":
            case "akismet_key":
            case "email_comment":
                $clean_arr[] = array("name"=>$name, "type"=>"V", "data"=>$WCDB->escape($data));
                break;

            case "use_rewrite":
            case "use_captcha":
            case "use_akismet":
            case "moderate_all":
            case "allow_comments":
            case "send_linkbacks":
                $clean_arr[] = array("name"=>$name, "type"=>"V", "data"=>(bool)$data);
                break;

            default:
                trigger_error("Invalid field $name sent to ".__FUNCTION__.".", E_USER_WARNING);
                continue;
        }

    }

    $success = true;

    foreach($clean_arr as $setting){

        $sql = "replace into {$WC["settings_table"]} set
                    name = '$setting[name]',
                    type = '$setting[type]',
                    data = '$setting[data]'";

        if(!$WCDB->query($sql)){
            $success = false;
        }

    }

    return $success;
}


/**
 * Checks the given cookie against the database for a user
 *
 * @param   $cookie     The cookie value to check
 * @return  mixed
 *
 */
function wc_db_check_cookie($cookie){

    global $WCDB, $WC;

    $user = array();

    if(strpos($cookie, ":")!==false){
        list($user_id, $session_id) = explode(":", $cookie);

        $user_id = $WCDB->escape($user_id);
        $session_id = $WCDB->escape($session_id);

        $sql = "select * from {$WC['users_table']} where session_id='$session_id' and user_id='$user_id'";

        $user = $WCDB->query_fetch($sql, WC_DB_FETCH_ASSOC);
    }

    return $user;

}


/**
 * Checks a user name and password
 *
 * @param   $user_name  The user name to check
 * @param   $password   The password to check
 * @return  bool
 *
 */
function wc_db_check_login($user_name, $password) {

    global $WCDB, $WC;

    $user_name = $WCDB->escape($user_name);
    $password = <PASSWORD>($password).<PASSWORD>($password);

    $sql = "select user_id from {$WC['users_table']} where user_name='$user_name' and password='$password'";

    return (int)$WCDB->query_fetch($sql, WC_DB_FETCH_VALUE, "user_id");

}


/**
 * Saves a post to the database.
 * To save an existing post, put the post_id in the array.
 *
 * @param   $post    Array of post elements to save
 * @return  bool
 *
 */
function wc_db_save_post(&$post){

    global $WCDB, $WC;

    $clean_arr = array();
    $result = false;

    if(isset($post["post_id"]) && empty($post["post_id"])) unset($post["post_id"]);

    foreach($post as $field=>$value){

        switch($field){
            case "post_id":
            case "user_id":
            case "allow_comments":
                $clean_arr[$field] = (int)$value;
                break;

            case "tags":
                break;

            case "subject":
            case "body":
            case "post_date":
            case "uri":
                $clean_arr[$field] = $WCDB->escape($value);
                break;

            default:
                trigger_error("Invalid field $field sent to ".__FUNCTION__.".", E_USER_WARNING);
                continue;
        }

    }

    if(!empty($post["post_id"])){

        // build an update
        $sql = "update {$WC['posts_table']} set ";
        foreach($clean_arr as $field=>$value){
            if($field!="post_id"){
                $sql.= "$field = '$value',";
            }
        }
        $sql = substr($sql, 0, -1); // trim the last comma
        $sql.= " where post_id=".$post["post_id"];

        $result = $WCDB->query($sql);

        if($result && isset($post["tags"])){

            $sql = "delete from {$WC['tags_table']} where post_id=".$post["post_id"];
            $WCDB->query($sql);

            $tag_arr = explode(",", $post["tags"]);
            foreach($tag_arr as $tag){
                $tag = trim($tag);
                if(empty($tag)) continue;
                $sql = "insert into {$WC['tags_table']} values (".$post["post_id"].", '".$WCDB->escape($tag)."')";
                $WCDB->query($sql);
            }
        }

    } else {

        // build an insert

        if(isset($post["post_id"])) unset($post["post_id"]);

        if(!isset($post["body"])) $post["body"] = "";

        foreach($clean_arr as $field=>$value){
            $fields.="$field,";
            $values.="'$value',";
        }
        $fields = substr($fields, 0, -1); // trim the last comma
        $values = substr($values, 0, -1); // trim the last comma
        $sql = "insert into {$WC['posts_table']} ($fields) values ($values)";

        $post_id = $WCDB->query_fetch($sql, WC_DB_FETCH_INSERT_ID);
        $post["post_id"] = $post_id;

        if($post_id && isset($post["tags"])){

            $result = $post_id;

            $tag_arr = explode(",", $post["tags"]);
            foreach($tag_arr as $tag){
                $tag = trim($tag);
                if(empty($tag)) continue;
                $sql = "insert into {$WC['tags_table']} values (".$post_id.", '".$WCDB->escape($tag)."')";
                $WCDB->query($sql);
            }
        }

    }

    return (bool)$result;
}


/**
 * Fetch a single post from the database
 *
 * @param   $post_id    The id or uri of the post to fetch
 * @return  array
 *
 */
function wc_db_get_post($identifier) {

    global $WCDB, $WC;

    if(is_numeric($identifier)){
        $where = "post_id = $identifier";
    } else {
        $where = "uri = '".$WCDB->escape($identifier)."'";
    }

    $sql = "select {$WC['posts_table']}.*, {$WC['users_table']}.user_name from {$WC['posts_table']} inner join {$WC['users_table']} using (user_id) where $where";

    $post = $WCDB->query_fetch($sql, WC_DB_FETCH_ASSOC);

    if(!empty($post)){

        if(empty($post_id)) $post_id = $post["post_id"];

        $sql = "select tag from {$WC['tags_table']} where post_id=".$post_id;

        $WCDB->query($sql);

        $post["tags"] = array();

        while($row = $WCDB->fetch()){
            $post["tags"][] = $row["tag"];
        }

        $post["tags_text"] = implode(", ", $post["tags"]);

        // get comment count
        $sql = "select count(*) as count from {$WC['comments_table']} where post_id=$post_id and status='APPROVED'";

        $post["comment_count"] = (int)$WCDB->query_fetch($sql, WC_DB_FETCH_VALUE, "count");

    }

    return $post;

}

/**
 * Function description
 * The funtion returns an array where the first element
 * is the posts and the second is the total.
 *
 * @param   $var    desctription
 * @return  mixed
 *
 */
function wc_db_get_post_list($start=false, $limit=false, $bodies=false, $filter="", $tag="", $post_ids=false) {

    global $WCDB, $WC;

    $bodies = (bool)$bodies;

    if(!$bodies){
        $fields = "post_id, subject, post_date, user_id";
    } else {
        $fields = "*";
    }


    $sql = "select SQL_CALC_FOUND_ROWS $fields from {$WC['posts_table']} ";

    $where = array();

    if($tag){
        $tag = $WCDB->escape((string)$tag);

        $sql.= "inner join {$WC['tags_table']} on
                    {$WC['posts_table']}.post_id={$WC['tags_table']}.post_id and
                    {$WC['tags_table']}.tag='$tag' ";

    }

    if($filter) {

        $words = preg_split('!\s+!', $filter);

        $match = $WCDB->escape("+".implode(" +", $words));

        $where[] = "match (subject, body) against ('$match' in boolean mode)";
    }

    if($post_ids!=false && is_array($post_ids)){
        $WCDB->escape($post_ids, "int");
        if(count($post_ids)){
            $where[] = "post_id in (".implode(",", $post_ids).")";
        }
    }

    if(count($where)){
        $sql.= " where ".implode(" and ", $where);
    }

    $sql.= "order by post_date desc";

    if(is_numeric($start) && is_numeric($limit)){
        $sql.= " limit $start, $limit";
    }

    $WCDB->query($sql);

    while($row = $WCDB->fetch()){

        // seed comment count and tags
        $row["comment_count"] = 0;
        $row["tags"] = array();

        $posts[$row["post_id"]] = $row;

        $user_ids[$row["post_id"]] = $row["user_id"];
    }

    $sql = "select found_rows() as total";
    $total = $WCDB->query_fetch($sql, WC_DB_FETCH_VALUE, "total");

    if(!empty($posts)){

        // get users
        $sql = "select user_id, user_name from {$WC['users_table']} where user_id in (".implode(",", $user_ids).")";
        $WCDB->query($sql);

        while($row = $WCDB->fetch()){
            $usernames[$row["user_id"]] = $row["user_name"];
        }

        foreach($user_ids as $post_id=>$user_id){
            $posts[$post_id]["user_name"] = $usernames[$user_id];
        }

        // get tags
        $sql = "select post_id, tag from {$WC['tags_table']} where post_id in (".implode(",", array_keys($posts)).")";

        $WCDB->query($sql);


        while($row = $WCDB->fetch()){
            $posts[$row["post_id"]]["tags"][] = $row["tag"];
        }


        // get comment count
        $sql = "select post_id, count(*) as count from {$WC['comments_table']} where post_id in (".implode(",", array_keys($posts)).") and status='APPROVED'";

        $WCDB->query($sql);
<commit_msg>fixed database error as found by atrandafir<commit_after><?php

/**
 * This file controls all databsae access
 *
 * @author     <NAME> <<EMAIL>>
 * @copyright  1997-Present WC Blog Dev Team
 *
 */

require_once dirname(__FILE__)."/config.php";
require_once dirname(__FILE__)."/WCDB.php";

// Check that this file is not loaded directly.
if ( basename( __FILE__ ) == basename( $_SERVER["PHP_SELF"] ) ) exit();

// if init has not loaded, quit the file
if(!defined("WC")) exit("common.php not loaded");

/**
 * Generate the table names using the prefix
 */
$WC["settings_table"] = $WC["db_prefix"]."_settings";
$WC["pages_table"] = $WC["db_prefix"]."_pages";
$WC["posts_table"] = $WC["db_prefix"]."_posts";
$WC["users_table"] = $WC["db_prefix"]."_users";
$WC["comments_table"] = $WC["db_prefix"]."_comments";
$WC["tags_table"] = $WC["db_prefix"]."_tags";

/**
 * Create a new database object for these functions to use
 */
$WCDB = new WCDB($WC["db_server"], $WC["db_name"], $WC["db_user"], $WC["db_password"]);


/**
 * Gets the application settings.
 *
 * @return  array
 *
 */
function wc_db_get_settings(){

    global $WC, $WCDB;

    $sql = "select * from {$WC["settings_table"]}";

    $WCDB->query($sql);

    $settings = array();

    while($rec = $WCDB->fetch()){
        if($rec["S"]){
            $settings[$rec["name"]] = json_decode($rec["data"]);
        } else {
            $settings[$rec["name"]] = $rec["data"];
        }
    }

    return $settings;
}


/**
 * Save the application settings.
 *
 * @param   $settings Array of settings to save.
 * @return  void
 *
 */
function wc_db_save_settings($settings){

    global $WC, $WCDB;

    if(empty($settings)) return false;

    $success = false;

    $clean_arr = array();

    foreach($settings as $name=>$data){

        switch($name){
            case "session_days":
                $clean_arr[] = array("name"=>$name, "type"=>"V", "data"=>(int)$data);
                break;

            case "base_url":
            case "session_secret":
            case "session_path":
            case "session_domain":
            case "date_format_long":
            case "date_format_short":
            case "template":
            case "default_title":
            case "default_description":
            case "akismet_key":
            case "email_comment":
                $clean_arr[] = array("name"=>$name, "type"=>"V", "data"=>$WCDB->escape($data));
                break;

            case "use_rewrite":
            case "use_captcha":
            case "use_akismet":
            case "moderate_all":
            case "allow_comments":
            case "send_linkbacks":
                $clean_arr[] = array("name"=>$name, "type"=>"V", "data"=>(bool)$data);
                break;

            default:
                trigger_error("Invalid field $name sent to ".__FUNCTION__.".", E_USER_WARNING);
                continue;
        }

    }

    $success = true;

    foreach($clean_arr as $setting){

        $sql = "replace into {$WC["settings_table"]} set
                    name = '$setting[name]',
                    type = '$setting[type]',
                    data = '$setting[data]'";

        if(!$WCDB->query($sql)){
            $success = false;
        }

    }

    return $success;
}


/**
 * Checks the given cookie against the database for a user
 *
 * @param   $cookie     The cookie value to check
 * @return  mixed
 *
 */
function wc_db_check_cookie($cookie){

    global $WCDB, $WC;

    $user = array();

    if(strpos($cookie, ":")!==false){
        list($user_id, $session_id) = explode(":", $cookie);

        $user_id = $WCDB->escape($user_id);
        $session_id = $WCDB->escape($session_id);

        $sql = "select * from {$WC['users_table']} where session_id='$session_id' and user_id='$user_id'";

        $user = $WCDB->query_fetch($sql, WC_DB_FETCH_ASSOC);
    }

    return $user;

}


/**
 * Checks a user name and password
 *
 * @param   $user_name  The user name to check
 * @param   $password   The password to check
 * @return  bool
 *
 */
function wc_db_check_login($user_name, $password) {

    global $WCDB, $WC;

    $user_name = $WCDB->escape($user_name);
    $password = <PASSWORD>($password).<PASSWORD>($password);

    $sql = "select user_id from {$WC['users_table']} where user_name='$user_name' and password='$password'";

    return (int)$WCDB->query_fetch($sql, WC_DB_FETCH_VALUE, "user_id");

}


/**
 * Saves a post to the database.
 * To save an existing post, put the post_id in the array.
 *
 * @param   $post    Array of post elements to save
 * @return  bool
 *
 */
function wc_db_save_post(&$post){

    global $WCDB, $WC;

    $clean_arr = array();
    $result = false;

    if(isset($post["post_id"]) && empty($post["post_id"])) unset($post["post_id"]);

    foreach($post as $field=>$value){

        switch($field){
            case "post_id":
            case "user_id":
            case "allow_comments":
                $clean_arr[$field] = (int)$value;
                break;

            case "tags":
                break;

            case "subject":
            case "body":
            case "post_date":
            case "uri":
                $clean_arr[$field] = $WCDB->escape($value);
                break;

            default:
                trigger_error("Invalid field $field sent to ".__FUNCTION__.".", E_USER_WARNING);
                continue;
        }

    }

    if(!empty($post["post_id"])){

        // build an update
        $sql = "update {$WC['posts_table']} set ";
        foreach($clean_arr as $field=>$value){
            if($field!="post_id"){
                $sql.= "$field = '$value',";
            }
        }
        $sql = substr($sql, 0, -1); // trim the last comma
        $sql.= " where post_id=".$post["post_id"];

        $result = $WCDB->query($sql);

        if($result && isset($post["tags"])){

            $sql = "delete from {$WC['tags_table']} where post_id=".$post["post_id"];
            $WCDB->query($sql);

            $tag_arr = explode(",", $post["tags"]);
            foreach($tag_arr as $tag){
                $tag = trim($tag);
                if(empty($tag)) continue;
                $sql = "insert into {$WC['tags_table']} values (".$post["post_id"].", '".$WCDB->escape($tag)."')";
                $WCDB->query($sql);
            }
        }

    } else {

        // build an insert

        if(isset($post["post_id"])) unset($post["post_id"]);

        if(!isset($post["body"])) $post["body"] = "";

        foreach($clean_arr as $field=>$value){
            $fields.="$field,";
            $values.="'$value',";
        }
        $fields = substr($fields, 0, -1); // trim the last comma
        $values = substr($values, 0, -1); // trim the last comma
        $sql = "insert into {$WC['posts_table']} ($fields) values ($values)";

        $post_id = $WCDB->query_fetch($sql, WC_DB_FETCH_INSERT_ID);
        $post["post_id"] = $post_id;

        if($post_id && isset($post["tags"])){

            $result = $post_id;

            $tag_arr = explode(",", $post["tags"]);
            foreach($tag_arr as $tag){
                $tag = trim($tag);
                if(empty($tag)) continue;
                $sql = "insert into {$WC['tags_table']} values (".$post_id.", '".$WCDB->escape($tag)."')";
                $WCDB->query($sql);
            }
        }

    }

    return (bool)$result;
}


/**
 * Fetch a single post from the database
 *
 * @param   $post_id    The id or uri of the post to fetch
 * @return  array
 *
 */
function wc_db_get_post($identifier) {

    global $WCDB, $WC;

    if(is_numeric($identifier)){
        $where = "post_id = $identifier";
    } else {
        $where = "uri = '".$WCDB->escape($identifier)."'";
    }

    $sql = "select {$WC['posts_table']}.*, {$WC['users_table']}.user_name from {$WC['posts_table']} inner join {$WC['users_table']} using (user_id) where $where";

    $post = $WCDB->query_fetch($sql, WC_DB_FETCH_ASSOC);

    if(!empty($post)){

        if(empty($post_id)) $post_id = $post["post_id"];

        $sql = "select tag from {$WC['tags_table']} where post_id=".$post_id;

        $WCDB->query($sql);

        $post["tags"] = array();

        while($row = $WCDB->fetch()){
            $post["tags"][] = $row["tag"];
        }

        $post["tags_text"] = implode(", ", $post["tags"]);

        // get comment count
        $sql = "select count(*) as count from {$WC['comments_table']} where post_id=$post_id and status='APPROVED'";

        $post["comment_count"] = (int)$WCDB->query_fetch($sql, WC_DB_FETCH_VALUE, "count");

    }

    return $post;

}

/**
 * Function description
 * The funtion returns an array where the first element
 * is the posts and the second is the total.
 *
 * @param   $var    desctription
 * @return  mixed
 *
 */
function wc_db_get_post_list($start=false, $limit=false, $bodies=false, $filter="", $tag="", $post_ids=false) {

    global $WCDB, $WC;

    $bodies = (bool)$bodies;

    if(!$bodies){
        $fields = "post_id, subject, post_date, user_id";
    } else {
        $fields = "*";
    }


    $sql = "select SQL_CALC_FOUND_ROWS $fields from {$WC['posts_table']} ";

    $where = array();

    if($tag){
        $tag = $WCDB->escape((string)$tag);

        $sql.= "inner join {$WC['tags_table']} on
                    {$WC['posts_table']}.post_id={$WC['tags_table']}.post_id and
                    {$WC['tags_table']}.tag='$tag' ";

    }

    if($filter) {

        $words = preg_split('!\s+!', $filter);

        $match = $WCDB->escape("+".implode(" +", $words));

        $where[] = "match (subject, body) against ('$match' in boolean mode)";
    }

    if($post_ids!=false && is_array($post_ids)){
        $WCDB->escape($post_ids, "int");
        if(count($post_ids)){
            $where[] = "post_id in (".implode(",", $post_ids).")";
        }
    }

    if(count($where)){
        $sql.= " where ".implode(" and ", $where);
    }

    $sql.= "order by post_date desc";

    if(is_numeric($start) && is_numeric($limit)){
        $sql.= " limit $start, $limit";
    }

    $WCDB->query($sql);

    while($row = $WCDB->fetch()){

        // seed comment count and tags
        $row["comment_count"] = 0;
        $row["tags"] = array();

        $posts[$row["post_id"]] = $row;

        $user_ids[$row["post_id"]] = $row["user_id"];
    }

    $sql = "select found_rows() as total";
    $total = $WCDB->query_fetch($sql, WC_DB_FETCH_VALUE, "total");

    if(!empty($posts)){

        // get users
        $sql = "select user_id, user_name from {$WC['users_table']} where user_id in (".implode(",", $user_ids).")";
        $WCDB->query($sql);

        while($row = $WCDB->fetch()){
            $usernames[$row["user_id"]] = $row["user_name"];
        }

        foreach($user_ids as $post_id=>$user_id){
            $posts[$post_id]["user_name"] = $usernames[$user_id];
        }

        // get tags
        $sql = "select post_id, tag from {$WC['tags_table']} where post_id in (".implode(",", array_keys($posts)).")";

        $WCDB->query($sql);


        while($row = $WCDB->fetch()){
            $posts[$row["post_id"]]["tags"][] = $row["tag"];
        }


        // get comment count
        $sql = "select post_id, count(*) as count from {$WC['comments_table']} where post_id in (".implode(",", array_keys($posts)).") and status='APPROVED' group by post_id";

        $WCDB->query($sql);

{'fraction_non_alphanumeric': 0.1883159699327443, 'fraction_numerical': 0.0009670754758450921, 'mean_word_length': 2.3446045280799765, 'pattern_counts': {'":': 56, '<': 15, '<?xml version=': 0, '>': 107, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4471172', 'n_tokens_mistral': 7657, 'n_tokens_neox': 7414, 'n_words': 1589}