Browse Source

Add a semirandom theme

This theme displays random threads intermixed with recently bumped ones.
The number of each is configurable.
pull/40/head
Matěj Grabovský 9 years ago
parent
commit
7c6eef81c5
  1. 70
      templates/themes/semirand/info.php
  2. 158
      templates/themes/semirand/semirand.js
  3. 254
      templates/themes/semirand/theme.php
  4. BIN
      templates/themes/semirand/thumb.png

70
templates/themes/semirand/info.php

@ -0,0 +1,70 @@
<?php
// Basic theme properties
$theme = array(
'name' => 'Mixed All/Random Overboard',
// Description (you can use Tinyboard markup here)
'description' => 'Board with threads from all boards with most recently bumped and random ones intermixed',
'version' => 'v0.1',
// Unique function name for building and installing whatever's necessary
'build_function' => 'semirand_build',
'install_callback' => 'semirand_install',
);
// Theme configuration
$theme['config'] = array(
array(
'title' => 'Board name',
'name' => 'title',
'type' => 'text',
'default' => 'Semirandom',
),
array(
'title' => 'Board URI',
'name' => 'uri',
'type' => 'text',
'default' => '.',
'comment' => '("mixed", for example)',
),
array(
'title' => 'Subtitle',
'name' => 'subtitle',
'type' => 'text',
'comment' => '(%s = thread limit, for example "%s coolest threads")',
),
array(
'title' => 'Excluded boards',
'name' => 'exclude',
'type' => 'text',
'comment' => '(space seperated)',
),
array(
'title' => 'Number of threads',
'name' => 'thread_limit',
'type' => 'text',
'default' => '15',
),
array(
'title' => 'Random threads',
'name' => 'random_count',
'comment' => '(number of consecutive random threads)',
'type' => 'text',
'default' => '1',
),
array(
'title' => 'Bumped threads',
'name' => 'bumped_count',
'comment' => '(number of consecutive recent threads)',
'type' => 'text',
'default' => '1',
),
);
if (!function_exists('semirand_install')) {
function semirand_install($settings) {
if (!file_exists($settings['uri'])) {
@mkdir($settings['uri'], 0777) or error("Couldn't create {$settings['uri']}. Check permissions.", true);
}
}
}

158
templates/themes/semirand/semirand.js

@ -0,0 +1,158 @@
$(document).ready(function() {
var cachedPages = [],
loading = false,
timer = null;
// Load data from HTML5 localStorage
var hiddenBoards = JSON.parse(localStorage.getItem('hiddenboards'));
var storeHiddenBoards = function() {
localStorage.setItem('hiddenboards', JSON.stringify(hiddenBoards));
};
// No board are hidden by default
if (!hiddenBoards) {
hiddenBoards = {};
storeHiddenBoards();
}
// Hide threads from the same board and remember for next time
var onHideClick = function(e) {
e.preventDefault();
var board = $(this).parent().next().data('board'),
threads = $('[data-board="'+board+'"]:not([data-cached="yes"])'),
btns = threads.prev().find('.threads-toggle'),
hrs = btns.next();
if (hiddenBoards[board]) {
threads.show();
btns.find('.threads-toggle').html(_('(hide threads from this board)'));
hrs.hide();
} else {
threads.hide();
btns.html(_('(show threads from this board)'));
hrs.show();
}
hiddenBoards[board] = !hiddenBoards[board];
storeHiddenBoards();
};
// Add a hiding link and horizontal separator to each thread
var addHideButton = function() {
var board = $(this).next().data('board'),
// Create the link and separator
button = $('<a href="#" class="unimportant threads-toggle"></a>')
.click(onHideClick),
myHr = $('<hr />');
// Insert them after the board name
$(this).append(' ').append(button).append(myHr);
if (hiddenBoards[board]) {
button.html(_('(show threads from this board)'));
$(this).next().hide();
} else {
button.html(_('(hide threads from this board)'));
myHr.hide();
}
};
$('h2').each(addHideButton);
var appendThread = function(elem, data) {
var boardLink = $('<h2><a href="' + modRoot + data.board + '/">/' +
data.board + '/</a></h2>');
// Push the thread after the currently last one
$('div[id*="thread_"]').last()
.after(elem.data('board', data.board)
.data('cached', 'no')
.show());
// Add the obligatory board link
boardLink.insertBefore(elem);
// Set up the hiding link
addHideButton.call(boardLink);
// Trigger an event to let the world know that we have a new thread aboard
$(document).trigger('new_post', elem);
};
var attemptLoadNext = function() {
if (!ukko_overflow.length) {
$('.pages').show().html(_('No more threads to display'));
return;
}
var viewHeight = $(window).scrollTop() + $(window).height(),
pageHeight = $(document).height();
// Keep loading deferred threads as long as we're close to the bottom of the
// page and there are threads remaining
while(viewHeight + 1000 > pageHeight && !loading && ukko_overflow.length > 0) {
// Take the first unloaded post
var post = ukko_overflow.shift(),
page = modRoot + post.board + '/' + post.page;
var thread = $('div#thread_' + post.id + '[data-board="' + post.board + '"]');
// Check that the thread hasn't been inserted yet
if (thread.length && thread.data('cached') !== 'yes') {
continue;
}
// Check if we've already downloaded the index page on which this thread
// is located
if ($.inArray(page, cachedPages) !== -1) {
if (thread.length) {
appendThread(thread, post);
}
// Otherwise just load the page and cache its threads
} else {
// Make sure that no other thread does the job that we're about to do
loading = true;
$('.pages').show().html(_('Loading…'));
// Retrieve the page from the server
$.get(page, function(data) {
cachedPages.push(page);
// Cache each retrieved thread
$(data).find('div[id*="thread_"]').each(function() {
var thread_id = $(this).attr('id').replace('thread_', '');
// Check that this thread hasn't already been loaded somehow
if ($('div#thread_' + thread_id + '[data-board="' +
post.board + '"]').length)
{
return;
}
// Hide the freshly loaded threads somewhere at the top
// of the page for now
$('form[name="postcontrols"]')
.prepend($(this).hide()
.data('cached', 'yes')
.data('data-board', post.board));
});
// Find the current thread in the newly retrieved ones
thread = $('div#thread_' + post.id + '[data-board="' +
post.board + '"][data-cached="yes"]');
if (thread.length) {
appendThread(thread, post);
}
// Release the lock
loading = false;
$('.pages').hide().html('');
});
break;
}
}
clearTimeout(timer);
// Check again in one second
timer = setTimeout(attemptLoadNext, 1000);
};
attemptLoadNext();
});

254
templates/themes/semirand/theme.php

@ -0,0 +1,254 @@
<?php
require 'info.php';
/**
* Generate the board's HTML and move it and its JavaScript in place, whence
* it's served
*/
function semirand_build($action, $settings) {
global $config;
if ($action !== 'all' && $action !== 'post' && $action !== 'post-thread' &&
$action !== 'post-delete')
{
return;
}
if ($config['smart_build']) {
file_unlink($settings['uri'] . '/index.html');
} else {
$semirand = new semirand($settings);
// Copy the generated board HTML to its place
file_write($settings['uri'] . '/index.html', $semirand->build());
file_write($settings['uri'] . '/semirand.js',
Element('themes/semirand/semirand.js', array()));
}
}
/**
* Encapsulation of the theme's internals
*/
class semirand {
private $settings;
function __construct($settings) {
$this->settings = $this->parseSettings($settings);
}
/**
* Parse and validate configuration parameters passed from the UI
*/
private function parseSettings($settings) {
if (!is_numeric($settings['thread_limit']) ||
!is_numeric($settings['random_count']) ||
!is_numeric($settings['recent_count']))
{
error('Invalid configuration parameters.', true);
}
$settings['exclude'] = explode(' ', $settings['exclude']);
$settings['thread_limit'] = intval($settings['thread_limit']);
$settings['random_count'] = intval($settings['random_count']);
$settings['recent_count'] = intval($settings['recent_count']);
if ($settings['thread_limit'] < 1 ||
$settings['random_count'] < 1 ||
$settings['recent_count'] < 1)
{
error('Invalid configuration parameters.', true);
}
return $settings;
}
/**
* Obtain list of all threads from all non-excluded boards
*/
private function fetchThreads() {
$query = '';
$boards = listBoards(true);
foreach ($boards as $b) {
if (in_array($b, $this->settings['exclude']))
continue;
// Threads are those posts that have no parent thread
$query .= "SELECT *, '$b' AS `board` FROM ``posts_$b`` " .
"WHERE `thread` IS NULL UNION ALL ";
}
$query = preg_replace('/UNION ALL $/', 'ORDER BY `bump` DESC', $query);
$result = query($query) or error(db_error());
return $result->fetchAll(PDO::FETCH_ASSOC);
}
/**
* Retrieve all replies to a given thread
*/
private function fetchReplies($board, $thread_id) {
$query = prepare("SELECT * FROM ``posts_$board`` WHERE `thread` = :id");
$query->bindValue(':id', $thread_id, PDO::PARAM_INT);
$query->execute() or error(db_error($query));
return $query->fetchAll(PDO::FETCH_ASSOC);
}
/**
* Intersperse random threads between those in bump order
*/
private function shuffleThreads($threads) {
$random_count = $this->settings['random_count'];
$recent_count = $this->settings['recent_count'];
$total = count($threads);
// Storage for threads that will be randomly interspersed
$shuffled = array();
// Ratio of bumped / all threads
$topRatio = $recent_count / ($recent_count + $random_count);
// Shuffle the bottom half of all threads
$random = array_splice($threads, floor($total * $topRatio));
shuffle($random);
// Merge the random and sorted threads into one sequence. The pattern
// starts at random threads
while (!empty($threads)) {
$shuffled = array_merge($shuffled,
array_splice($random, 0, $random_count),
array_splice($threads, 0, $recent_count));
}
return $shuffled;
}
/**
* Build the HTML of a single thread in the catalog
*/
private function buildOne($post, $mod = false) {
global $config;
openBoard($post['board']);
$thread = new Thread($post, $mod ? '?/' : $config['root'], $mod);
$replies = $this->fetchReplies($post['board'], $post['id']);
// Number of replies to a thread that are displayed beneath it
$preview_count = $post['sticky'] ? $config['threads_preview_sticky'] :
$config['threads_preview'];
// Chomp the last few replies
$disp_replies = array_splice($replies, 0, $preview_count);
$disp_img_count = 0;
foreach ($disp_replies as $reply) {
if ($reply['files'] !== '')
++$disp_img_count;
// Append the reply to the thread as it's being built
$thread->add(new Post($reply, $mod ? '?/' : $config['root'], $mod));
}
// Count the number of omitted image replies
$omitted_img_count = count(array_filter($replies, function($p) {
return $p['files'] !== '';
}));
// Set the corresponding omitted numbers on the thread
if (!empty($replies)) {
$thread->omitted = count($replies);
$thread->omitted_images = $omitted_img_count;
}
// Board name and link
$html = '<h2><a href="' . $config['root'] . $post['board'] . '/">/' .
$post['board'] . '/</a></h2>';
// The thread itself
$html .= $thread->build(true);
return $html;
}
/**
* Query the required information and generate the HTML
*/
public function build($mod = false) {
if (!isset($this->settings)) {
error('Theme is not configured properly.');
}
global $config;
$html = '';
$overflow = array();
// Fetch threads from all boards and chomp the first 'n' posts, depending
// on the setting
$threads = $this->shuffleThreads($this->fetchThreads());
$total_count = count($threads);
// Top threads displayed on load
$top_threads = array_splice($threads, 0, $this->settings['thread_limit']);
// Number of processed threads by board
$counts = array();
// Output threads up to the specified limit
foreach ($top_threads as $post) {
if (array_key_exists($post['board'], $counts)) {
++$counts[$post['board']];
} else {
$counts[$post['board']] = 1;
}
$html .= $this->buildOne($post, $mod);
}
foreach ($threads as $post) {
if (array_key_exists($post['board'], $counts)) {
++$counts[$post['board']];
} else {
$counts[$post['board']] = 1;
}
$page = 'index';
$board_page = floor($counts[$post['board']] / $config['threads_per_page']);
if ($board_page > 0) {
$page = $board_page + 1;
}
$overflow[] = array(
'id' => $post['id'],
'board' => $post['board'],
'page' => $page . '.html'
);
}
$html .= '<script>var ukko_overflow = ' . json_encode($overflow) . '</script>';
$html .= '<script type="text/javascript" src="/'.$this->settings['uri'].'/semirand.js"></script>';
return Element('index.html', array(
'config' => $config,
'board' => array(
'url' => $this->settings['uri'],
'title' => $this->settings['title'],
'subtitle' => str_replace('%s', $this->settings['thread_limit'],
strval(min($this->settings['subtitle'], $total_count))),
),
'no_post_form' => true,
'body' => $html,
'mod' => $mod,
'boardlist' => createBoardlist($mod),
));
}
};
if (!function_exists('array_column')) {
/**
* Pick out values from subarrays by given key
*/
function array_column($array, $key) {
$result = [];
foreach ($array as $val) {
$result[] = $val[$key];
}
return $result;
}
}

BIN
templates/themes/semirand/thumb.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Loading…
Cancel
Save