Перегляд переліку публікацій на сайті

Для підключення API новин з власного сайту потрібно: 

В корінь сайту розмістити файл php з наступним змістом (попередньо вказати доступи до БД)

 "localhost",
    "db"   => "",
    "user" => "",
    "pass" => ""
]);

$data = [];

if (isset($_REQUEST['id'])) {

    $request_id = json_decode($_REQUEST['id'], true);

    if (!is_array($request_id)) {
        $request_id = json_decode(
            urldecode($_REQUEST['id']),
            true
        );
    }

    $id = array_values(
        array_filter(
            (array) $request_id,
            static function ($value) {
                return filter_var(
                    $value,
                    FILTER_VALIDATE_INT
                ) !== false;
            }
        )
    );

    if (count($id) > 0) {
        $data = $db->getAll(
            "
            SELECT
                p.id,
                p.post_date AS date,
                p.post_title AS title,
                p.post_author AS autor,
                p.post_name AS alt_name,
                p.comment_count AS comm_num,
                p.post_status AS approve
            FROM
                wp_posts AS p
            WHERE
                p.id IN (?a)
            ORDER BY
                p.post_date DESC
            ",
            $id
        );
    }

} else {

    $start = 0;

    if (isset($_REQUEST['start'])) {
        $start = max(0, (int) $_REQUEST['start']);
    }

    $limit = 10;

    if (isset($_REQUEST['limit'])) {
        $limit = (int) $_REQUEST['limit'];
    }

    $limit = max(1, min($limit, 100));

    $search = '';

    if (isset($_REQUEST['search'])) {
        $search = trim((string) $_REQUEST['search']);
    }

    if ($search !== '') {

        $searchLike = '%' . $search . '%';

        $data = $db->getAll(
            "
            SELECT
                p.id,
                p.post_date AS date,
                p.post_title AS title,
                p.post_author AS autor,
                p.post_name AS alt_name,
                p.comment_count AS comm_num,
                p.post_status AS approve
            FROM
                wp_posts AS p
            WHERE
                p.post_type = 'post'
                AND p.post_status IN ('pending', 'publish')
                AND (
                    p.post_title LIKE ?s
                    OR p.post_content LIKE ?s
                    OR p.post_excerpt LIKE ?s
                    OR p.post_name LIKE ?s
                )
            ORDER BY
                p.post_date DESC
            LIMIT {$start}, {$limit}
            ",
            $searchLike,
            $searchLike,
            $searchLike,
            $searchLike
        );

    } else {

        $data = $db->getAll(
            "
            SELECT
                p.id,
                p.post_date AS date,
                p.post_title AS title,
                p.post_author AS autor,
                p.post_name AS alt_name,
                p.comment_count AS comm_num,
                p.post_status AS approve
            FROM
                wp_posts AS p
            WHERE
                p.post_type = 'post'
                AND p.post_status IN ('pending', 'publish')
            ORDER BY
                p.post_date DESC
            LIMIT {$start}, {$limit}
            "
        );
    }
}

header('Content-Type: application/json; charset=utf-8');

die(
    json_encode(
        $data,
        JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
    )
);


class MySQL
{
    public $conn;

    private $stats = [];
    private $emode;
    private $exname;

    public $query_num = 0;

    private $defaults = [
        'host'      => 'localhost',
        'user'      => 'root',
        'pass'      => '',
        'db'        => 'test',
        'port'      => null,
        'socket'    => null,
        'pconnect'  => false,
        'charset'   => 'utf8mb4',
        'errmode'   => 'error',
        'exception' => 'Exception'
    ];

    const RESULT_ASSOC = MYSQLI_ASSOC;
    const RESULT_NUM   = MYSQLI_NUM;

    public function __construct($opt = [])
    {
        $opt = array_merge($this->defaults, $opt);

        $this->emode = $opt['errmode'];
        $this->exname = $opt['exception'];

        if ($opt['pconnect']) {
            $opt['host'] = 'p:' . $opt['host'];
        }

        $this->conn = @mysqli_connect(
            $opt['host'],
            $opt['user'],
            $opt['pass'],
            $opt['db'],
            $opt['port'],
            $opt['socket']
        );

        if (!$this->conn) {
            $this->error(
                mysqli_connect_errno() . ' ' . mysqli_connect_error()
            );
        }

        if (!mysqli_set_charset($this->conn, $opt['charset'])) {
            $this->error(mysqli_error($this->conn));
        }

        unset($opt);
    }

    public function query()
    {
        return $this->rawQuery(
            $this->prepareQuery(func_get_args())
        );
    }

    public function fetch(
        $result,
        $mode = self::RESULT_ASSOC
    ) {
        return mysqli_fetch_array($result, $mode);
    }

    public function affectedRows()
    {
        return mysqli_affected_rows($this->conn);
    }

    public function insertId()
    {
        return mysqli_insert_id($this->conn);
    }

    public function numRows($result)
    {
        return mysqli_num_rows($result);
    }

    public function free($result)
    {
        if ($result instanceof mysqli_result) {
            mysqli_free_result($result);
        }
    }

    public function getOne()
    {
        $query = $this->prepareQuery(func_get_args());

        if ($res = $this->rawQuery($query)) {
            $row = $this->fetch($res);

            if (is_array($row)) {
                $value = reset($row);
                $this->free($res);

                return $value;
            }

            $this->free($res);
        }

        return false;
    }

    public function getRow()
    {
        $query = $this->prepareQuery(func_get_args());

        if ($res = $this->rawQuery($query)) {
            $ret = $this->fetch($res);
            $this->free($res);

            return $ret;
        }

        return false;
    }

    public function getCol()
    {
        $ret = [];
        $query = $this->prepareQuery(func_get_args());

        if ($res = $this->rawQuery($query)) {
            while ($row = $this->fetch($res)) {
                $ret[] = reset($row);
            }

            $this->free($res);
        }

        return $ret;
    }

    public function getAll()
    {
        $ret = [];
        $query = $this->prepareQuery(func_get_args());

        if ($res = $this->rawQuery($query)) {
            while ($row = $this->fetch($res)) {
                $ret[] = $row;
            }

            $this->free($res);
        }

        return $ret;
    }

    public function getInd()
    {
        $args = func_get_args();
        $index = array_shift($args);
        $query = $this->prepareQuery($args);

        $ret = [];

        if ($res = $this->rawQuery($query)) {
            while ($row = $this->fetch($res)) {
                $ret[$row[$index]] = $row;
            }

            $this->free($res);
        }

        return $ret;
    }

    public function getIndCol()
    {
        $args = func_get_args();
        $index = array_shift($args);
        $query = $this->prepareQuery($args);

        $ret = [];

        if ($res = $this->rawQuery($query)) {
            while ($row = $this->fetch($res)) {
                $key = $row[$index];

                unset($row[$index]);

                $ret[$key] = reset($row);
            }

            $this->free($res);
        }

        return $ret;
    }

    public function parse()
    {
        return $this->prepareQuery(func_get_args());
    }

    public function whiteList(
        $input,
        $allowed,
        $default = false
    ) {
        $found = array_search($input, $allowed, true);

        return $found === false
            ? $default
            : $allowed[$found];
    }

    public function filterArray(
        $input,
        $allowed
    ) {
        foreach (array_keys($input) as $key) {
            if (!in_array($key, $allowed, true)) {
                unset($input[$key]);
            }
        }

        return $input;
    }

    public function lastQuery()
    {
        if (empty($this->stats)) {
            return null;
        }

        $last = end($this->stats);

        return $last['query'] ?? null;
    }

    public function getStats()
    {
        return $this->stats;
    }

    public function rawQuery($query)
    {
        $start = microtime(true);

        $res = mysqli_query($this->conn, $query);

        $timer = microtime(true) - $start;

        $this->query_num++;

        $this->stats[] = [
            'query' => $query,
            'start' => $start,
            'timer' => $timer
        ];

        if (!$res) {
            $error = mysqli_error($this->conn);

            end($this->stats);
            $key = key($this->stats);

            if ($key !== null) {
                $this->stats[$key]['error'] = $error;
            }

            $this->cutStats();

            $this->error(
                $error . '. Full query: [' . $query . ']'
            );
        }

        $this->cutStats();

        return $res;
    }

   private function prepareQuery($args)
{
    $query = '';
    $raw = array_shift($args);

    $array = preg_split(
        '~(\?[nsiuap])~u',
        $raw,
        null,
        PREG_SPLIT_DELIM_CAPTURE
    );

    $anum = count($args);
    $pnum = (int) floor(count($array) / 2);

    if ($pnum !== $anum) {
        $this->error(
            "Number of args ({$anum}) doesn't match " .
            "number of placeholders ({$pnum}) in [{$raw}]"
        );
    }

    foreach ($array as $i => $part) {
        if (($i % 2) === 0) {
            $query .= $part;
            continue;
        }

        $value = array_shift($args);

        switch ($part) {
            case '?n':
                $part = $this->escapeIdent($value);
                break;

            case '?s':
                $part = $this->escapeString($value);
                break;

            case '?i':
                $part = $this->escapeInt($value);
                break;

            case '?a':
                $part = $this->createIN($value);
                break;

            case '?u':
                $part = $this->createSET($value);
                break;

            case '?p':
                $part = $value;
                break;
        }

        $query .= $part;
    }

    return $query;
}
    private function escapeInt($value)
    {
        if ($value === null) {
            return 'NULL';
        }

        if (!is_numeric($value)) {
            $this->error(
                'Integer (?i) placeholder expects numeric value, ' .
                gettype($value) .
                ' given'
            );

            return false;
        }

        if (is_float($value)) {
            $value = number_format(
                $value,
                0,
                '.',
                ''
            );
        }

        return (string) $value;
    }

    private function escapeString($value)
    {
        if ($value === null) {
            return 'NULL';
        }

        return "'" .
            mysqli_real_escape_string(
                $this->conn,
                (string) $value
            ) .
            "'";
    }

    private function escapeIdent($value)
    {
        if ($value !== null && $value !== '') {
            return '`' .
                str_replace(
                    '`',
                    '``',
                    (string) $value
                ) .
                '`';
        }

        $this->error(
            'Empty value for identifier (?n) placeholder'
        );

        return '';
    }

    private function createIN($data)
    {
        if (!is_array($data)) {
            $this->error(
                'Value for IN (?a) placeholder should be array'
            );

            return 'NULL';
        }

        if (!$data) {
            return 'NULL';
        }

        $query = '';
        $comma = '';

        foreach ($data as $value) {
            $query .= $comma . $this->escapeString($value);
            $comma = ',';
        }

        return $query;
    }

    private function createSET($data)
    {
        if (!is_array($data)) {
            $this->error(
                'SET (?u) placeholder expects array, ' .
                gettype($data) .
                ' given'
            );

            return '';
        }

        if (!$data) {
            $this->error(
                'Empty array for SET (?u) placeholder'
            );

            return '';
        }

        $query = '';
        $comma = '';

        foreach ($data as $key => $value) {
            $query .=
                $comma .
                $this->escapeIdent($key) .
                '=' .
                $this->escapeString($value);

            $comma = ',';
        }

        return $query;
    }

    private function error($err)
    {
        $err = __CLASS__ . ': ' . $err;

        if ($this->emode === 'error') {
            $err .=
                '. Error initiated in ' .
                $this->caller() .
                ', thrown';

            trigger_error(
                $err,
                E_USER_ERROR
            );

            return;
        }

        $exceptionClass = $this->exname;

        throw new $exceptionClass($err);
    }

    private function caller()
    {
        $trace = debug_backtrace();
        $caller = '';

        foreach ($trace as $item) {
            if (
                isset($item['class']) &&
                $item['class'] === __CLASS__
            ) {
                $file = $item['file'] ?? 'unknown file';
                $line = $item['line'] ?? 'unknown line';

                $caller = $file . ' on line ' . $line;
            } else {
                break;
            }
        }

        return $caller;
    }

    private function cutStats()
    {
        if (count($this->stats) > 100) {
            reset($this->stats);

            $first = key($this->stats);

            if ($first !== null) {
                unset($this->stats[$first]);
            }
        }
    }
}

В налаштуваннях хмари (Адміністрування→Налаштування) вказати: 

  • Покликання на файл API CMS новин (наприклад: https://yousitenews.com/api_lcloud.php)
  • домен CMS новин (наприклад: yousitenews.com)
Доступ за замовчуванням Груп доступу: 2
  • Викладачі Базові права (надаються автоматично)
  • Перегляд новин DLE
Загальнонаціональна хвилина мовчання за загиблими внаслідок збройної агресії рф проти України
60