Skip to content

Commit

Permalink
1.99.0
Browse files Browse the repository at this point in the history
- PHP 7.4 & 8.0 compatible version
  • Loading branch information
Karel Wintersky committed Aug 27, 2024
1 parent db03bfc commit 817c242
Show file tree
Hide file tree
Showing 5 changed files with 76 additions and 58 deletions.
8 changes: 6 additions & 2 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,12 @@
"platform-check": false
},
"require": {
"php": "^7.4 | 8.*",
"ext-pdo": "*",
"ext-json": "*",
"ext-curl": "*",
"psr/log": "^1.1",
"curl/curl": "^2.3.0"
"psr/log": "*",
"curl/curl": "^2"
},
"autoload": {
"psr-4": {
Expand All @@ -37,5 +38,8 @@
"target": "admin/longreads.tpl"
}
]
},
"require-dev": {
"rector/rector": "^1.2"
}
}
64 changes: 36 additions & 28 deletions extra/longreads.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,30 +2,38 @@
* jQuery required
*/
$(function () {
window.longreads = window.longreads || [];

let URLS = {
IMPORT: '/longreads/import/',
DELETE: '/longreads/delete/',
TOGGLE: '/longreads/page_toggle/',
ADD: '/longreads/page_add/',
GET_PAGES_LIST: '/longreads/get_tilda_pages_list/',
};
// Шаблон строки для новой страницы
let template_pagerow = '\
<tr id="row-%id%" data-status="0" data-id="%id%" class="new">\
<td align="center">%projectid%</td>\
<td align="center" class="date">%date%<span class="change"></span></td>\
<td>\
<p class="pagetitle">%title%</p>\
<p class="description">%descr%</p>\
</td>\
<td class="buttons">\
<button data-id="%id%" class="pull-right update" style="display: none;">Обновить</button>\
<button data-id="%id%" class="pull-right delete" style="display: none;">Удалить</button>\
<button data-id="%id%" class="pull-right toshow" style="display: none;">Вернуть</button>\
<button data-id="%id%" class="pull-right import" style="display: block;">Импорт</button>\
<button data-id="%id%" class="pull-right tohide" style="display: block;">Скрыть</button>\
<div class="import-block" style="display: none;">\
<button data-id="%id%" class="cancel">Отмена</button>\
<button data-id="%id%" class="start">Начать импорт</button>\
<input class="folder" type="text" value="" placeholder="URL по которому будет доступен лонгрид">\
</div>\
</td>\
</tr>';

/* =========== ФУНКЦИИ ============ */
let template_pagerow = `
<tr id="row-%id%" data-status="0" data-id="%id%" class="new">
<td align="center">%projectid%</td>
<td align="center" class="date">%date%<span class="change"></span></td>
<td>
<p class="pagetitle">%title%</p>
<p class="description">%descr%</p>
</td>
<td class="buttons">
<button data-id="%id%" class="pull-right update" style="display: none;">Обновить</button>
<button data-id="%id%" class="pull-right delete" style="display: none;">Удалить</button>
<button data-id="%id%" class="pull-right toshow" style="display: none;">Вернуть</button>
<button data-id="%id%" class="pull-right import" style="display: block;">Импорт</button>
<button data-id="%id%" class="pull-right tohide" style="display: block;">Скрыть</button>
<div class="import-block" style="display: none;">
<button data-id="%id%" class="cancel">Отмена</button>
<button data-id="%id%" class="start">Начать импорт</button>
<input class="folder" type="text" value="" placeholder="URL по которому будет доступен лонгрид">
</div>
</td>
</tr>
`;

/**
* Удалить страницу
Expand All @@ -34,7 +42,7 @@ $(function () {
*/
function page_delete(id) {
disable_buttons();
$.post('/longreads/delete/', {
$.post(URLS.DELETE, {
id: id
}, function (response) {
if (response === 'ok') {
Expand All @@ -55,7 +63,7 @@ $(function () {
*/
function page_toggle(id, toggle) {
disable_buttons();
$.post('/longreads/page_toggle/', {
$.post(URLS.TOGGLE, {
id: id,
toggle: toggle
}, function (response) {
Expand Down Expand Up @@ -110,7 +118,7 @@ $(function () {
function page_import(id, folder, update = false) {
message('Идет импорт страницы...');
disable_buttons();
$.post('/longreads/import/', {
$.post(URLS.IMPORT, {
id: id,
folder: folder, update: update
}).complete(function (response) {
Expand Down Expand Up @@ -215,7 +223,7 @@ $(function () {
message('Идет получение страниц по Tilda API...');
disable_buttons();

$.post('/longreads/get_tilda_pages_list/', { }, function (data) {
$.post(URLS.GET_PAGES_LIST, { }, function (data) {

// Если ответ от Tilda не получен
if (data.status !== 'FOUND' || !data.result) {
Expand Down Expand Up @@ -253,7 +261,7 @@ $(function () {

// добавляем запись о лонгриде в базу
complete = false;
$.post('/longreads/page_add/', {
$.post(URLS.ADD, {
page: page
}, function (response) {
if (response === 'ok') {
Expand Down
4 changes: 2 additions & 2 deletions extra/longreads.tpl
Original file line number Diff line number Diff line change
Expand Up @@ -71,11 +71,11 @@
{$longread.id}: '{$longread.date}',
{/foreach}
};
let showhidden = false;
window.showhidden = false;
let tildapages;
</script>
<script type="text/javascript" src="/frontend/js/admin/longreads.js"></script>
<style type="text/css">
<style>
.longreads_action {
display: block;
padding: 1px 8px;
Expand Down
3 changes: 2 additions & 1 deletion sources/LongreadError.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@ class LongreadError
public int $error_code;

/**
* @var string
* @param int $error_code
* @param string $url
*/
public string $url;

Expand Down
55 changes: 30 additions & 25 deletions sources/Longreads.php
Original file line number Diff line number Diff line change
@@ -1,25 +1,20 @@
<?php

/**
* Longreads UNIT for Steamboat Engine
* Longreads UNIT for FSNews Engine
*/

namespace AJUR\FSNews;

use Curl\Curl;
use PDO;
use PDOException;
use Psr\Log\NullLogger;
use RuntimeException;
use PDO;
use Psr\Log\LoggerInterface;
use RuntimeException;

class Longreads implements LongreadsInterface
{
/**
* @var PDO
*/
private $pdo;

/**
* Логгер
*
Expand Down Expand Up @@ -71,7 +66,7 @@ class Longreads implements LongreadsInterface
private $sql_table;

/**
* Опция "отрезать ли футер чтобы вставить на его место счетчики из шаблона?" (true)
* Опция "отрезать ли футер, чтобы вставить на его место счетчики из шаблона?" (true)
*
* @var bool|mixed
*/
Expand Down Expand Up @@ -101,8 +96,15 @@ class Longreads implements LongreadsInterface
*/
private bool $throw_on_error;

/**
* @var mixed|PDO
*/
private $pdo;

public function __construct($pdo, array $options = [], LoggerInterface $logger = null)
{
$this->pdo = $pdo;

$this->api_request_types = [
'getprojectslist' => '', // Список проектов
'getproject' => 'projectid', // Информация о проекте
Expand All @@ -113,8 +115,6 @@ public function __construct($pdo, array $options = [], LoggerInterface $logger =
'getpageexport' => 'pageid', // Информация о странице для экспорта (+ body html-code)
'getpagefullexport' => 'pageid', // Информация о странице для экспорта (+ fullpage html-code)
];

$this->pdo = $pdo;
$this->logger = is_null($logger) ? new NullLogger() : $logger;

$this->api_options['version'] = $options['api.version'] ?? 'v1';
Expand All @@ -138,13 +138,15 @@ public function __construct($pdo, array $options = [], LoggerInterface $logger =
if (is_array($options['projects'])) {
$this->tilda_projects_list = $options['projects'];
} elseif (is_string($options['projects'])) {
$this->tilda_projects_list = array_map(static function ($i) { return (int)$i; }, explode(' ', $options['projects']));
$this->tilda_projects_list = array_map(function ($i) { return (int)$i; }, explode(' ', $options['projects']));
}
}

public function __get($name)
{
if ($this->{$name}) return $this->{$name};
if ($this->{$name}) {
return $this->{$name};
}

return null;
}
Expand Down Expand Up @@ -188,7 +190,7 @@ public function getStoredByID($id = null):array
return [];
}

$sql = "SELECT * FROM {$this->sql_table} WHERE id = :id ";
$sql = vsprintf("SELECT * FROM %s WHERE id = :id", [ $this->sql_table ]);

$this->logger->debug("Запрошен сохраненный лонгрид по ID: ", [ $id ]);

Expand Down Expand Up @@ -313,7 +315,7 @@ public function import($id, string $folder = '', string $import_mode = 'update')

if ('' !== $this->path_to_footer_template) {
$html = str_replace([ '</body>', '</html>' ], '', $html);

if (!is_readable($this->path_to_footer_template)) {
throw new RuntimeException("Файл шаблона-футера нечитаем или отсутствует");
}
Expand Down Expand Up @@ -354,7 +356,7 @@ public function import($id, string $folder = '', string $import_mode = 'update')
} // foreach

// теперь проверяем, существует ли в базе импортированных лонгридов такая запись
$sql = "SELECT COUNT(*) AS cnt FROM `{$this->sql_table}` WHERE `id` = :id";
$sql = vsprintf("SELECT COUNT(*) AS cnt FROM %s WHERE id = :id", [ $this->sql_table ]);
$sth = $this->pdo->prepare($sql);
$sth->execute(['id' => $id]);

Expand Down Expand Up @@ -452,7 +454,8 @@ public function add($page = null)
}

// проверим существование
$sth = $this->pdo->prepare("SELECT COUNT(*) FROM {$this->sql_table} WHERE id = :id ");
$sql = vsprintf("SELECT COUNT(*) FROM %s WHERE id = :id", [ $this->sql_table ]);
$sth = $this->pdo->prepare($sql);
$sth->execute(['id' => $dataset['id']]);
$count = $sth->fetchColumn();

Expand Down Expand Up @@ -500,7 +503,8 @@ public function deleteStored($id)

$this->logger->debug("Начинаем удаление лонгрида с ID: ", [ $id ]);

$sth = $this->pdo->prepare("SELECT * FROM {$this->sql_table} WHERE id = :id");
$sql = vsprintf("SELECT * FROM %s WHERE id = :id", [ $this->sql_table ]);
$sth = $this->pdo->prepare($sql);
$sth->execute([
'id' => $id
]);
Expand All @@ -510,7 +514,7 @@ public function deleteStored($id)
throw new RuntimeException("Лонгрид с указанным идентификатором не найден в базе данных");
}

$lr_folder = rtrim($this->path_storage, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . trim($longread['folder'], DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
$lr_folder = rtrim($this->path_storage, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . trim((string) $longread['folder'], DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;

if (!is_dir($lr_folder)) {
throw new RuntimeException('Директории с лонгридом не существует. Обратитесь к администратору!');
Expand All @@ -536,7 +540,7 @@ public function deleteStored($id)
}

// удаляем запись из базы
$sth = $this->pdo->prepare("DELETE FROM {$this->sql_table} WHERE id = :id");
$sth = $this->pdo->prepare(vsprintf("DELETE FROM %s WHERE id = :id", [ $this->sql_table ]));

if (false === $sth->execute([ 'id' => $id])) {
throw new RuntimeException("Не удалось удалить лонгрид из базы данных, код лонгрида: {$id}");
Expand Down Expand Up @@ -565,7 +569,8 @@ public function itemToggleVisibility($id, string $new_state = 'hide')
$new_state = in_array($new_state, [ 'hide', 'show' ]) ? $new_state : 'hide';
$new_state = ($new_state === 'hide') ? -1 : 0;

$sth = $this->pdo->prepare("UPDATE `longreads` SET `status` = :status WHERE `id` = :id ");
$sql = vsprintf("UPDATE %s SET status = :status WHERE id = :id", [ $this->sql_table ]);
$sth = $this->pdo->prepare($sql);
$sth->execute([
'status' => $new_state,
'id' => $id
Expand Down Expand Up @@ -796,7 +801,7 @@ private static function makeReplaceQuery(string $table, array &$dataset, string
$query = "REPLACE `{$table}` SET ";

foreach ($dataset as $index => $value) {
if (\strtoupper(\trim($value)) === 'NOW()') {
if (\strtoupper(\trim((string) $value)) === 'NOW()') {
$fields[] = "`{$index}` = NOW()";
unset($dataset[ $index ]);
continue;
Expand Down Expand Up @@ -827,10 +832,10 @@ private static function makeInsertQuery(string $table, &$dataset):string

$set = [];

$query = "INSERT INTO `{$table}` SET ";
$query = "INSERT INTO {$table} SET ";

foreach ($dataset as $index => $value) {
if (\strtoupper(\trim($value)) === 'NOW()') {
if (\strtoupper(\trim((string) $value)) === 'NOW()') {
$set[] = "`{$index}` = NOW()";
unset($dataset[ $index ]);
continue;
Expand Down Expand Up @@ -863,7 +868,7 @@ private static function makeUpdateQuery(string $table, &$dataset, $where_conditi
$query = "UPDATE `{$table}` SET";

foreach ($dataset as $index => $value) {
if (\strtoupper(\trim($value)) === 'NOW()') {
if (\strtoupper(\trim((string) $value)) === 'NOW()') {
$set[] = "`{$index}` = NOW()";
unset($dataset[ $index ]);
continue;
Expand Down

0 comments on commit 817c242

Please sign in to comment.