<?php
// ----------------------------------------------------------------------------
//
// ----------------------------------------------------------------------------

function getPostsByCategory($catId, $orderBy='', $limit = 0)
{
    global $nsodb;

    $sql = "SELECT * FROM posts, rel_post_cat
    		WHERE posts.id = rel_post_cat.post_id
    		AND posts.status <> 'deleted'
    		AND rel_post_cat.cat_id = $catId";

    if ($orderBy) {
        $sql .= ' ORDER BY ' . $orderBy;
    } else {
        $sql .= ' ORDER BY posts.date DESC';
    }

    if ($limit) {
        $sql .= ' LIMIT 0, ' . $limit;
    }

    $rs = $nsodb->get_results($sql, ARRAY_A);

    return $rs;
}

function getFilesByPost($postId, $fileType = '', $size = 0) {
	global $nsodb;
	$sql = 'SELECT file_id as id, path, title, flag FROM files, rel_post_file
			WHERE files.id = file_id
			AND post_id = ' . $postId;
	if (!empty($fileType)) $sql .= " AND `flag` = '{$fileType}'";
	if (!empty($size)) $sql .= ' LIMIT ' . $size;
	
	$rs = $nsodb->get_results($sql, ARRAY_A);

	return $rs;
}

function getFileByPost($postId, $fileType = '') {
	$rs = getFilesByPost($postId, $fileType, 1);
	return $rs[0];
}

function getFileWithFullPathByPost($postId, $fileType='') {
    $file = getFileByPost($postId, $fileType);
    return NSO_UPLOAD_DIR_NAME . '/'. $file['path'];
}

function getImagePathBySize($path, $size = '120') {
	return str_replace('_source', '_'.$size, $path);
}

function getPage($pageFlag) {
	global $nsodb;

	$sql = "SELECT * FROM posts, post_meta
			WHERE `meta_key` = 'page_flag'
			AND posts.id = post_meta.post_id
			AND posts.status <> 'deleted'
			AND `meta_value` = '{$pageFlag}'";
	$row = $nsodb->get_row($sql, ARRAY_A);

	return $row;
}

function getPost($postId) {
    global $nsodb;
    $sql = "SELECT * FROM posts WHERE id = {$postId}";
    $row = $nsodb->get_row($sql, ARRAY_A);
	return $row;
}

function getCategoryName($catId) {
    global $nsodb;

    $sql = 'SELECT * FROM categories WHERE id = ' . $catId;
    $row = $nsodb->get_row($sql);
    if ($row) {
        $categoryName = $row->name;
    }

    return $categoryName;
}

/**
 * 获取父类下所有子类
 */
function getCategoriesByParent ($parent = 0)
{
    global $nsodb;
    $sql = "SELECT * FROM categories 
			WHERE parent = {$parent} 
			ORDER BY `od`";
    $rs = $nsodb->get_results($sql, ARRAY_A);
    return $rs;
}

function showClassCurrent($filename) {
    if ( NutFunction::getCurrentPageFileName() == $filename ) {
        echo ' current';
    }
}