<?php
/**
* Tops plugin
*
* @package Monstra
* @subpackage Plugins
* @author El'Drako
* @copyright 2012 El'Drako
* @version 1.0.0
*
*/
// Register plugin
Plugin::register( __FILE__,
__('Tops'),
__('Tops page'),
'1.0.0',
'El\'Drako',
'http://monstra.org/',
'tops');
/**
* Shorcode: {tops list="last_added_authors" count="10"}
*/
Shortcode::add('tops', 'Tops::_shorcode');
if(Session::exists('user_role') && in_array(Session::get('user_role'), array('admin', 'editor'))) {
// Include Admin
Plugin::Admin('tops');
}
class TopsPager extends Pager
{
/**
* Implementation of abstract method getData of Pager class
*
* Gets records from array with given offset and limit
* and total number of records
*
* @param $data mixed - array of all the records
* @return mixed - array of records
*/
public function getData($data)
{
$this->total = count($data);
$data = array_slice($data, $this->getOffset(), $this->limit);
return $data;
}
}
class Tops extends Frontend {
public static $users = null;
public static $out = '';
public static $titles = '';
public static function _shorcode($attributes) {
extract($attributes);
$count = (isset($count)) ? (int)$count : 5;
Action::run('dblink');
$db = goDB::getDB("SIDB");
if (isset($list)) {
switch ($list) {
case 'last_added_authors':
return Tops::getLastAddedAuthors($db, $count);
case 'last_updates':
return Tops::getLastUpdates($db, $count);
case 'top_rating_authors':
return Tops::getTopRatingAuthors($db, $count);
case 'top_readed_authors':
return Tops::getTopReadedAuthors($db, $count);
case 'top_users_lists':
return Tops::getLastRegisteredUsers($count);
case 'check_si_servers':
return Tops::getSiStatus();
}
}
}
/**
* Get Top Readed Authors
*/
public static function getTopReadedAuthors($db, $count) {
$cache = Mcache::getInstance();
$cache_id = 'getTopReadedAuthors';
$sortedby=' ORDER BY `watchers` DESC LIMIT ?i';
$query = "SELECT COUNT(`aname`) `watchers`, l.id `id`, l.aname `aname`, l.url `url`, l.text `textlist`, l.rating `rating` FROM `links` l LEFT JOIN `users2links` u2l on (l.id = u2l.linkid) WHERE l.type = 2 GROUP BY `aname` ".$sortedby;
$data = array($count);
if ($cache->exists($cache_id)) {
$authorlist = $cache->get($cache_id);
} else {
$authorlist = $db->query($query, $data, 'assoc');
$cache->set($cache_id, $authorlist, 60 * 60 * 1);
}
View::factory('tops/views/frontend/getTopReadedAuthors')
->assign('authorlist', $authorlist)
->display();
}
/**
* Get Top Rating Authors
*/
public static function getTopRatingAuthors($db, $count) {
$cache = Mcache::getInstance();
$cache_id = 'getTopRatingAuthors';
$sortedby=' ORDER BY `rating` DESC LIMIT ?i';
$query = "SELECT COUNT(*) `watchers`, l.id `id`, l.aname `aname`, l.url `url`, l.text `textlist`, l.rating `rating` FROM `links` l RIGHT JOIN `users2links` u2l on (l.id = u2l.linkid) WHERE l.type = 2 GROUP BY l.aname ".$sortedby;
$data = array($count);
if ($cache->exists($cache_id)) {
$authorlist = $cache->get($cache_id);
} else {
$authorlist = $db->query($query, $data, 'assoc');
$cache->set($cache_id, $authorlist, 60 * 60 * 1);
}
View::factory('tops/views/frontend/getTopRatingAuthors')
->assign('authorlist', $authorlist)
->display();
}
/**
* Get Last Updates
*/
public static function getLastUpdates($db, $count) {
$cache = Mcache::getInstance();
$cache_id = 'getLastUpdates';
$sortedby='ORDER BY `updated` DESC LIMIT ?i';
$query = "SELECT * FROM `links` l WHERE l.type = 1 ".$sortedby;
$data = array($count);
if ($cache->exists($cache_id)) {
$authorlist = $cache->get($cache_id);
} else {
$authorlist = $db->query($query, $data, 'assoc');
$cache->set($cache_id, $authorlist, 60 * 60 * 1);
}
View::factory('tops/views/frontend/getLastUpdates')
->assign('authorlist', $authorlist)
->display();
}
/**
* Get Last Added Authors
*/
public static function getLastAddedAuthors($db, $count) {
$cache = Mcache::getInstance();
$cache_id = 'getLastAddedAuthors';
$sortedby=' ORDER BY `id` DESC LIMIT ?i';
$query = "SELECT l.id `id`, l.aname `aname`, l.url `url`, l.rating `rating`, l.updated `updated` FROM `links` l WHERE l.type = 2 GROUP BY l.aname ".$sortedby;
$data = array($count);
if ($cache->exists($cache_id)) {
$authorlist = $cache->get($cache_id);
} else {
$authorlist = $db->query($query, $data, 'assoc');
$cache->set($cache_id, $authorlist, 60 * 60 * 1);
}
View::factory('tops/views/frontend/getLastAddedAuthors')
->assign('authorlist', $authorlist)
->display();
}
/**
* Функция возвращает окончание для множественного числа слова на основании числа и массива окончаний
* @param $number Integer Число на основе которого нужно сформировать окончание
* @param $endingsArray Array Массив слов или окончаний для чисел (1, 4, 5),
* например array('яблоко', 'яблока', 'яблок')
* @return String
*/
public static function getNumEnding($number, $endingArray) {
$number = $number % 100;
if ($number>=11 && $number<=19) {
$ending=$endingArray[2];
} else {
$i = $number % 10;
switch ($i) {
case (1): $ending = $endingArray[0]; break;
case (2):
case (3):
case (4): $ending = $endingArray[1]; break;
default: $ending=$endingArray[2];
}
}
return $ending;
}
/**
* Get Tops list
*/
public static function getList() {
$authorlist = '';
Action::run('dblink');
$db = goDB::getDB("SIDB");
$errors = array();
$users = new Table('siwusers');
$cache = Mcache::getInstance();
$pageNum = (isset($_GET['p']) && $_GET['p'] != '') ? (int)$_GET['p'] : 1;
$sortedby = ' ORDER BY l.aname ASC';
$s_query = "SELECT COUNT(u2l.id) `watchers`, l.id `id`, l.aname `aname`, l.url `url`, l.text `textlist`, l.rating `rating` FROM `links` l RIGHT JOIN `users2links` u2l on (l.id = u2l.linkid) WHERE l.type = 2 GROUP BY l.aname ".$sortedby;
//$author_list = $db->query($s_query, null, 'assoc');
//Debug::dump($author_list);exit;
if (Uri::segment(1)=='sorted-by' && Uri::segment(2)=='rating') {
$sortedby=' ORDER BY `rating` DESC';
$s_query = "SELECT COUNT(*) `watchers`, l.id `id`, l.aname `aname`, l.url `url`, l.text `textlist`, l.rating `rating` FROM `links` l RIGHT JOIN `users2links` u2l on (l.id = u2l.linkid) WHERE l.type = 2 GROUP BY l.aname ".$sortedby;
if ($cache->exists("tops_list_r")) {
$author_list = $cache->get("tops_list_r");
} else {
$author_list = $db->query($s_query, null, 'assoc');
$cache->set("tops_list_r", $author_list, 60 * 60 * 1);
}
} else if (Uri::segment(1)=='sorted-by' && Uri::segment(2)=='watchers') {
$sortedby=' ORDER BY `watchers` DESC';
$s_query = "SELECT COUNT(`aname`) `watchers`, l.id `id`, l.aname `aname`, l.url `url`, l.text `textlist`, l.rating `rating` FROM `links` l LEFT JOIN `users2links` u2l on (l.id = u2l.linkid) WHERE l.type = 2 GROUP BY `aname` ".$sortedby;
if ($cache->exists("tops_list_w")) {
$author_list = $cache->get("tops_list_w");
} else {
$author_list = $db->query($s_query, null, 'assoc');
$cache->set("tops_list_w", $author_list, 60 * 60 * 1);
}
} else if (Uri::segment(1)=='sorted-by' && Uri::segment(2)=='adddate') {
$sortedby=' ORDER BY `id` DESC';
$s_query = "SELECT COUNT(*) `watchers`, l.id `id`, l.aname `aname`, l.url `url`, l.text `textlist`, l.rating `rating` FROM `links` l RIGHT JOIN `users2links` u2l on (l.id = u2l.linkid) WHERE l.type = 2 GROUP BY l.aname ".$sortedby;
if ($cache->exists("tops_list_d")) {
$author_list = $cache->get("tops_list_d");
} else {
$author_list = $db->query($s_query, null, 'assoc');
$cache->set("tops_list_d", $author_list, 60 * 60 * 1);
}
} else {
if ($cache->exists("tops_list")) {
$author_list = $cache->get("tops_list");
} else {
$author_list = $db->query($s_query, null, 'assoc');
$cache->set("tops_list", $author_list, 60 * 60 * 1);
}
}
$s_query = "SELECT * FROM `users2links` u2l WHERE u2l.type = 2;";
//$author_userlists = $db->query($s_query, null, 'assoc');
if ($cache->exists("tops_userlists")) {
$author_userlists = $cache->get("tops_userlists");
} else {
$author_userlists = $db->query($s_query, null, 'assoc');
$cache->set("tops_userlists", $author_userlists, 60 * 60 * 1);
}
if (Session::exists('siwuser_id') && (Session::get('siwuser_login') != '')) {
//под юзером
$user = $users->select('[login="'.Session::get('siwuser_login').'"]', null);
$tmp_query = "SELECT u2l.linkid FROM `users2links` u2l WHERE u2l.type = 2 AND u2l.userid = (select u.id from `users` u where u.jid='".$user['jabber']."');";
//$author_userlist = $db->query($tmp_query, null, 'col');
if ($cache->exists("tops_userlist_".$user['jabber'])) {
$author_userlist = $cache->get("tops_userlist_".$user['jabber']);
} else {
$author_userlist = $db->query($tmp_query, null, 'col');
$cache->set("tops_userlist_".$user['jabber'], $author_userlist, 60 * 60 * 0.15);
}
} else {
// для гостей
$author_userlist = array();
}
$pager = new PagerArray($pageNum, Option::get('tops_perpage'));
$authorlist = $pager->getData($author_list);
$pagerNav = $pager->render();
$statsString = '<div class="range">(Авторы с %d по %d из %d)</div>';
View::factory('tops/views/frontend/index')
->assign('author_list', $authorlist)
->assign('author_userlist', $author_userlist)
->assign('author_userlists', $author_userlists)
->assign('pagerNav', $pagerNav)
->assign('pagerTotal', $pager->renderStats($statsString))
->display();
}
/**
* Get all links to Author's texts
*/
public static function getAuthorLinks($db, $id) {
$links = array();
$s_query = "SELECT l.text FROM `links` l WHERE l.type = 2 AND l.id = ".$id." LIMIT 1;";
$links = explode(" ", $db->query($s_query, null, 'el'));
return $links;
}
/**
* Get count of all Author's texts
*/
public static function getAuthorTextCount($db, $nick) {
$links = array();
$s_query = "SELECT COUNT(*) FROM `links` l WHERE l.type = 1 AND l.url LIKE ? ;";
$data = array($nick[0].'/'.$nick.'/%');
return $db->query($s_query, $data, 'el');
}
/**
* Get Author name
*/
public static function getAuthorNameById($db, $id) {
$s_query = "SELECT l.aname FROM `links` l WHERE l.type = 2 AND l.id = ".$id." LIMIT 1;";
return $db->query($s_query, null, 'el');
}
/**
* Get Author name by nick
*/
public static function getAuthorNameByNick($db, $nick) {
$s_query = "SELECT l.aname FROM `links` l WHERE l.type = '2' AND l.url = ? ;";
$data = array($nick[0].'/'.$nick);
$out = $db->query($s_query, $data, 'el');
return $out;
}
/**
* Get Author texts by nick
*/
public static function getAuthorTextsByNick($db, $nick) {
$s_query = "SELECT * FROM `links` l WHERE l.type = '1' AND l.url LIKE ? ORDER BY l.updated DESC;";
$data = array($nick[0].'/'.$nick.'/%');
$out = $db->query($s_query, $data, 'assoc');
return $out;
}
/**
* Get all id's to Author's texts
*/
public static function getAuthorTextIDs($db, $id) {
$links = Tops::getAuthorLinks($db, $id);
$id = array();
foreach ($links as $link) {
$s_query = "SELECT l.id FROM `links` l WHERE l.type = 1 AND l.url = '".$link."' LIMIT 1;";
$res = $db->query($s_query, null, 'el');
if ($res) $id[] = $res;
}
return $id;
}
/**
* Get Author page
*/
public static function getAuthorPage($nick) {
Action::run('dblink');
$db = goDB::getDB("SIDB");
$users = new Table('siwusers');
$cache = Mcache::getInstance();
$author = Tops::getAuthorNameByNick($db, $nick);
if ($author =='') Request::redirect("/tops");
$texts = Tops::getAuthorTextsByNick($db, $nick);
$textcount = Tops::getAuthorTextCount($db, $nick);
//число читателей у текста
$s_query = "SELECT COUNT(u2l.id) `watchers`, u2l.linkid FROM `links` l RIGHT JOIN `users2links` u2l on (l.id = u2l.linkid) WHERE l.type = 1 AND l.url LIKE ? GROUP BY l.url ";
$data = array($nick[0].'/'.$nick.'/%');
$readers_count = $db->query($s_query, $data, 'assoc');
if (Session::exists('siwuser_id') && (Session::get('siwuser_login') != '')) {
//под юзером
$user = $users->select('[login="'.Session::get('siwuser_login').'"]', null);
//готовим список идов текстов автора для выборки подписанных
$ids = array();
foreach ($texts as $t) $ids []= $t['id'];
if (count($ids) == 0) $ids[] = 0;
$tmp_query = "SELECT u2l.linkid FROM `users2links` u2l WHERE u2l.type IN (1,4) AND u2l.userid = (select u.id from `users` u where u.jid=?) AND u2l.linkid IN (?list);";
//$author_userlist = $db->query($tmp_query, null, 'col');
$data = array($user['jabber'], $ids);
if ($cache->exists($nick."_userlist_".$user['jabber'])) {
$author_userlist = $cache->get($nick."_userlist_".$user['jabber']);
} else {
$author_userlist = $db->query($tmp_query, $data, 'col');
$cache->set($nick."_userlist_".$user['jabber'], $author_userlist, 60 * 60 * 0.15);
}
} else {
// для гостей
$author_userlist = array();
}
View::factory('tops/views/frontend/authorpage')
->assign('author', $author)
->assign('nick', $nick)
->assign('textcount', $textcount)
->assign('texts', $texts)
->assign('author_userlist', $author_userlist)
->assign('readers_count', $readers_count)
->display();
}
/**
* Get Author rss-page
*/
public static function getRSSAuthor($nick) {
Action::run('dblink');
$db = goDB::getDB("SIDB");
$users = new Table('siwusers');
$cache = Mcache::getInstance();
include_once PLUGINS . '/tops/rss_generator.inc.php';
$author = Tops::getAuthorNameByNick($db, $nick);
if ($author =='') Request::redirect("/tops");
$texts = Tops::getAuthorTextsByNick($db, $nick);
$rss_channel = new rssGenerator_channel();
$rss_channel->atomLinkHref = Option::get('siteurl');
$rss_channel->title = 'SIwatcher - Список произведений автора '.$author;
$rss_channel->link = Option::get('siteurl').'tops/rss/'.$nick;
$rss_channel->description = 'Всего у автора отслеживается ' . count($texts) . Tops::getNumEnding(count($texts), array(' текст',' текста',' текстов'));
$rss_channel->language = 'ru';
$rss_channel->generator = 'SIwatcher RSS Feed Generator';
$rss_channel->managingEditor = 'admin@siwatcher.ru (El\'Drako)';
$rss_channel->webMaster = 'admin@siwatcher.ru (El\'Drako)';
//debug::dump($texts);
$rss_feed = new rssGenerator_rss();
foreach ($texts as $t) {
$item = new rssGenerator_item();
$a = explode('||', $t['text']);
//debug::dump($t['text']);exit;
$item->title = $a[1];
$s = '<strong>Последнее сканирование:</strong> '.date("G:i:s j.m.Yг. (T)", $t['date']).'<br/>';
$s .= strlen($a[0]) > 3 ? '<strong>Автор:</strong> '.$a[0].'<br/>' : '';
$s .= strlen($a[3]) > 3 ? '<strong>Жанр:</strong> '.$a[3].'<br/>' : '';
$s .= strlen($a[4]) > 3 ? '<strong>Аннотация:</strong> '.$a[4].'<br/><br/><strong>Размер:</strong> '.$a[2].' КБ' : '<br/><strong>Размер:</strong> '.$a[2].' КБ';
$s .= '<br/><br/><a href="http://budclub.ru/'.$t['url'].'">Ссылка на budclub.ru</a>';
$item->description = $rss_feed->cData($s);
$item->link = 'http://samlib.ru/'.$t['url'];
$item->guid = $t['id'];
$item->pubDate = date("r", $t['updated']);
$rss_channel->items[] = $item;
}
//$rss_feed = new rssGenerator_rss();
$rss_feed->encoding = 'UTF-8';
$rss_feed->version = '2.0';
header('Content-Type: text/xml');
echo $rss_feed->createFeed($rss_channel);
exit;
}
public static function main() {
}
public static function content() {
}
/**
* Set Tops template
*/
public static function template() {
return Option::get('tops_template');
}
}